@@ -0,0 +1,2731 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE EmptyDataDecls #-}
5+{-# LANGUAGE ExistentialQuantification #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE FunctionalDependencies #-}
9+{-# LANGUAGE GADTs #-}
10+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11+{-# LANGUAGE LambdaCase #-}
12+{-# LANGUAGE MultiWayIf #-}
13+{-# LANGUAGE RankNTypes #-}
14+{-# LANGUAGE RoleAnnotations #-}
15+{-# LANGUAGE ScopedTypeVariables #-}
16+{-# LANGUAGE TypeFamilies #-}
17+{-# LANGUAGE TypeOperators #-}
18+{-# LANGUAGE UndecidableInstances #-}
19+{-# LANGUAGE PolyKinds #-}
20+{-# LANGUAGE DeriveFunctor #-}
21+{-# LANGUAGE StandaloneDeriving #-}
22+{-# LANGUAGE InstanceSigs #-}
23+
24+#ifdef USE_REFLEX_OPTIMIZER
25+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
26+#endif
27+{-# OPTIONS_GHC -Wunused-binds #-}
28+-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
29+-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
30+module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
31+
32+#if MIN_VERSION_base(4,10,0)
33+import Control.Applicative (liftA2)
34+#endif
35+import Control.Concurrent
36+import Control.Exception
37+import Control.Monad hiding (forM, forM_, mapM, mapM_)
38+import Control.Monad.Exception
39+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
40+import Control.Monad.Primitive
41+--import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_)
42+import Control.Monad.Reader.Class
43+import Control.Monad.IO.Class
44+import Control.Monad.ReaderIO
45+import Control.Monad.Ref
46+import Control.Monad.Fail (MonadFail)
47+import qualified Control.Monad.Fail as MonadFail
48+import Data.Align
49+import Data.Coerce
50+import Data.Dependent.Map (DMap, DSum (..))
51+import qualified Data.Dependent.Map as DMap
52+import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
53+import qualified Data.FastMutableIntMap as FastMutableIntMap
54+import Data.Foldable hiding (concat, elem, sequence_)
55+import Data.Functor.Constant
56+import Data.Functor.Misc
57+import Data.Functor.Product
58+import Data.GADT.Compare
59+import Data.IntMap.Strict (IntMap)
60+import qualified Data.IntMap.Strict as IntMap
61+import Data.IORef
62+import Data.Kind (Type)
63+import Data.Maybe hiding (mapMaybe)
64+import Data.Monoid ((<>))
65+import Data.Proxy
66+import Data.These
67+import Data.Traversable
68+import Data.Type.Equality ((:~:)(Refl))
69+import Data.Witherable (Filterable, mapMaybe)
70+import GHC.Exts
71+import GHC.IORef (IORef (..))
72+import GHC.Stack
73+import Reflex.FastWeak
74+import System.IO.Unsafe
75+import System.Mem.Weak
76+import Unsafe.Coerce
77+
78+#ifdef MIN_VERSION_semialign
79+#if MIN_VERSION_these(0,8,0)
80+import Data.These.Combinators (justThese)
81+#endif
82+#if MIN_VERSION_semialign(1,1,0)
83+import Data.Zip (Zip (..))
84+#endif
85+#endif
86+
87+#ifdef DEBUG_CYCLES
88+import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
89+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
90+import qualified Data.List.NonEmpty as NonEmpty
91+import Data.Monoid (mempty)
92+import Data.Tree (Forest, Tree (..), drawForest)
93+#endif
94+
95+import Data.FastWeakBag (FastWeakBag)
96+import qualified Data.FastWeakBag as FastWeakBag
97+import Data.Reflection
98+import Data.Some (Some(Some))
99+import Data.Type.Coercion
100+import Data.Profunctor.Unsafe ((#.), (.#))
101+import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
102+import qualified Data.WeakBag as WeakBag
103+import qualified Reflex.Class
104+import qualified Reflex.Class as R
105+import qualified Reflex.Host.Class
106+import Reflex.NotReady.Class
107+import Reflex.Patch
108+import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
109+import Reflex.PerformEvent.Base (PerformEventT)
110+
111+#ifdef DEBUG_TRACE_EVENTS
112+import qualified Data.ByteString.Char8 as BS8
113+import System.IO (stderr)
114+#endif
115+
116+#ifdef DEBUG_TRACE_EVENTS
117+
118+withStackOneLine :: (BS8.ByteString -> a) -> a
119+withStackOneLine expr = unsafePerformIO $ do
120+ stack <- currentCallStack
121+ return (expr (BS8.pack (unwords (reverse stack))))
122+
123+#endif
124+
125+debugPropagate :: Bool
126+
127+debugInvalidateHeight :: Bool
128+
129+debugInvalidate :: Bool
130+
131+#ifdef DEBUG
132+
133+#define DEBUG_NODEIDS
134+
135+debugPropagate = True
136+
137+debugInvalidateHeight = False
138+
139+debugInvalidate = True
140+
141+class HasNodeId a where
142+ getNodeId :: a -> Int
143+
144+instance HasNodeId (Hold x p a) where
145+ getNodeId = holdNodeId
146+
147+instance HasNodeId (PushSubscribed x a b) where
148+ getNodeId = pushSubscribedNodeId
149+
150+instance HasNodeId (SwitchSubscribed x a) where
151+ getNodeId = switchSubscribedNodeId
152+
153+instance HasNodeId (FanSubscribed x a) where
154+ getNodeId = fanSubscribedNodeId
155+
156+instance HasNodeId (CoincidenceSubscribed x a) where
157+ getNodeId = coincidenceSubscribedNodeId
158+
159+instance HasNodeId (RootSubscribed x a) where
160+ getNodeId = rootSubscribedNodeId
161+
162+instance HasNodeId (Pull x a) where
163+ getNodeId = pullNodeId
164+
165+{-# INLINE showNodeId #-}
166+showNodeId :: HasNodeId a => a -> String
167+showNodeId = ("#"<>) . show . getNodeId
168+
169+showSubscriberType :: Subscriber x a -> String
170+showSubscriberType = \case
171+ SubscriberPush _ _ -> "SubscriberPush"
172+ SubscriberMerge _ _ -> "SubscriberMerge"
173+ SubscriberFan _ -> "SubscriberFan"
174+ SubscriberMergeChange _ -> "SubscriberMergeChange"
175+ SubscriberHold _ -> "SubscriberHold"
176+ SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
177+ SubscriberSwitch _ -> "SubscriberSwitch"
178+ SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
179+ SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
180+ SubscriberHandle -> "SubscriberHandle"
181+
182+showEventType :: Event x a -> String
183+showEventType = \case
184+ EventRoot _ _ -> "EventRoot"
185+ EventNever -> "EventNever"
186+ EventPush _ -> "EventPush"
187+ EventMerge _ -> "EventMerge"
188+ EventFan _ _ -> "EventFan"
189+ EventSwitch _ -> "EventSwitch"
190+ EventCoincidence _ -> "EventCoincidence"
191+ EventHold _ -> "EventHold"
192+ EventDyn _ -> "EventDyn"
193+ EventHoldIdentity _ -> "EventHoldIdentity"
194+ EventDynIdentity _ -> "EventDynIdentity"
195+
196+#else
197+
198+debugPropagate = False
199+
200+debugInvalidateHeight = False
201+
202+debugInvalidate = False
203+
204+-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
205+{-# INLINE showNodeId #-}
206+showNodeId :: a -> String
207+showNodeId _ = ""
208+
209+#endif
210+
211+#ifdef DEBUG_NODEIDS
212+{-# NOINLINE nextNodeIdRef #-}
213+nextNodeIdRef :: IORef Int
214+nextNodeIdRef = unsafePerformIO $ newIORef 1
215+
216+newNodeId :: IO Int
217+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
218+#endif
219+
220+--------------------------------------------------------------------------------
221+-- EventSubscription
222+--------------------------------------------------------------------------------
223+
224+--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
225+-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
226+data EventSubscription x = EventSubscription
227+ { _eventSubscription_unsubscribe :: !(IO ())
228+ , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
229+ }
230+
231+unsubscribe :: EventSubscription x -> IO ()
232+unsubscribe (EventSubscription u _) = u
233+
234+--------------------------------------------------------------------------------
235+-- Event
236+--------------------------------------------------------------------------------
237+
238+newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
239+
240+{-# INLINE subscribeAndRead #-}
241+subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
242+subscribeAndRead = unEvent
243+
244+{-# RULES
245+"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
246+"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
247+"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
248+ #-}
249+
250+-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
251+-- caching; if the computation function is very cheap, this is (much) more
252+-- efficient than 'push'
253+{-# INLINE [1] pushCheap #-}
254+pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
255+pushCheap !f e = Event $ \sub -> do
256+ (subscription, occ) <- subscribeAndRead e $ sub
257+ { subscriberPropagate = \a -> do
258+ mb <- f a
259+ mapM_ (subscriberPropagate sub) mb
260+ }
261+ occ' <- join <$> mapM f occ
262+ return (subscription, occ')
263+
264+-- | A subscriber that never triggers other 'Event's
265+{-# INLINE terminalSubscriber #-}
266+terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
267+terminalSubscriber p = Subscriber
268+ { subscriberPropagate = p
269+ , subscriberInvalidateHeight = \_ -> return ()
270+ , subscriberRecalculateHeight = \_ -> return ()
271+ }
272+
273+-- | Subscribe to an Event only for the duration of one occurrence
274+{-# INLINE subscribeAndReadHead #-}
275+subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
276+subscribeAndReadHead e sub = do
277+ subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
278+ (subscription, occ) <- subscribeAndRead e $ sub
279+ { subscriberPropagate = \a -> do
280+ liftIO $ unsubscribe =<< readIORef subscriptionRef
281+ subscriberPropagate sub a
282+ }
283+ liftIO $ case occ of
284+ Nothing -> writeIORef subscriptionRef $! subscription
285+ Just _ -> unsubscribe subscription
286+ return (subscription, occ)
287+
288+--TODO: Make this lazy in its input event
289+headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
290+headE originalE = do
291+ parent <- liftIO $ newIORef $ Just originalE
292+ defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
293+ let clearParent = liftIO $ writeIORef parent Nothing
294+ (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ \_ -> clearParent
295+ when (isJust occ) clearParent
296+ return $ Event $ \sub -> do
297+ liftIO (readIORef parent) >>= \case
298+ Nothing -> return (EventSubscription (return ()) $ EventSubscribed zeroRef $ toAny (), Nothing)
299+ Just e -> subscribeAndReadHead e sub
300+
301+data CacheSubscribed x a
302+ = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
303+ , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
304+ , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
305+ }
306+
307+-- | Construct an 'Event' whose value is guaranteed not to be recomputed
308+-- repeatedly
309+--
310+--TODO: Try a caching strategy where we subscribe directly to the parent when
311+--there's only one subscriber, and then build our own FastWeakBag only when a second
312+--subscriber joins
313+{-# NOINLINE [0] cacheEvent #-}
314+cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
315+cacheEvent e =
316+#ifdef DEBUG_TRACE_EVENTS
317+ withStackOneLine $ \callSite -> Event $
318+#else
319+ Event $
320+#endif
321+ unsafePerformIO $ do
322+ mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
323+ <- newIORef emptyFastWeak
324+ pure $ \sub -> {-# SCC "cacheEvent" #-} do
325+#ifdef DEBUG_TRACE_EVENTS
326+ unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
327+#endif
328+ subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
329+ Just subscribedTicket -> return subscribedTicket
330+ Nothing -> do
331+ subscribers <- liftIO FastWeakBag.empty
332+ occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
333+ (parentSub, occ) <- subscribeAndRead e $ Subscriber
334+ { subscriberPropagate = \a -> do
335+ liftIO $ writeIORef occRef $ Just a
336+ scheduleClear occRef
337+ propagateFast a subscribers
338+ , subscriberInvalidateHeight = \old -> do
339+ FastWeakBag.traverse_ subscribers $ invalidateSubscriberHeight old
340+ , subscriberRecalculateHeight = \new -> do
341+ FastWeakBag.traverse_ subscribers $ recalculateSubscriberHeight new
342+ }
343+ when (isJust occ) $ do
344+ liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
345+ scheduleClear occRef
346+ let !subscribed = CacheSubscribed
347+ { _cacheSubscribed_subscribers = subscribers
348+ , _cacheSubscribed_parent = parentSub
349+ , _cacheSubscribed_occurrence = occRef
350+ }
351+ subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
352+ liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
353+ return subscribedTicket
354+ liftIO $ do
355+ subscribed <- getFastWeakTicketValue subscribedTicket
356+ ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
357+ occ <- readIORef $ _cacheSubscribed_occurrence subscribed
358+ let es = EventSubscription
359+ { _eventSubscription_unsubscribe = do
360+ FastWeakBag.remove ticket
361+ isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
362+ when isEmpty $ do
363+ writeIORef mSubscribedRef emptyFastWeak
364+ unsubscribe $ _cacheSubscribed_parent subscribed
365+ touch ticket
366+ touch subscribedTicket
367+ , _eventSubscription_subscribed = EventSubscribed
368+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
369+ , eventSubscribedRetained = toAny subscribedTicket
370+ }
371+ }
372+ return (es, occ)
373+
374+subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
375+subscribe e s = fst <$> subscribeAndRead e s
376+
377+{-# INLINE wrap #-}
378+wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
379+wrap tag getSpecificSubscribed sub = do
380+ (sln, subd, occ) <- getSpecificSubscribed sub
381+ let es = tag subd
382+ return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
383+
384+eventRoot :: GCompare k => k a -> Root x k -> Event x a
385+eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
386+
387+eventNever :: Event x a
388+eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
389+
390+eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)
391+eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
392+
393+eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
394+eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
395+
396+eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
397+eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
398+
399+eventHold :: Hold x p -> Event x p
400+eventHold !h = Event $ subscribeHoldEvent h
401+
402+eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
403+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
404+
405+{-# INLINE subscribeCoincidenceInner #-}
406+subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
407+subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
408+ subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
409+ (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
410+ innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
411+ let height = max innerHeight outerHeight
412+ defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
413+ return (innerOcc, height, innerSubd)
414+
415+--------------------------------------------------------------------------------
416+-- Subscriber
417+--------------------------------------------------------------------------------
418+
419+data Subscriber x a = Subscriber
420+ { subscriberPropagate :: !(a -> EventM x ())
421+ , subscriberInvalidateHeight :: !(Height -> IO ())
422+ , subscriberRecalculateHeight :: !(Height -> IO ())
423+ }
424+
425+--TODO: Move this comment to WeakBag
426+-- These function are constructor functions that are marked NOINLINE so they are
427+-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
428+-- so any weak references that are attached to the constructors will have their
429+-- finalizer run. Using the opaque constructor, does not see the
430+-- constructor application, so it behaves like an IORef and cannot be fused away.
431+--
432+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
433+-- the weak pointer to it in some cases.
434+
435+newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
436+newSubscriberHold h = return $ Subscriber
437+ { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
438+ , subscriberInvalidateHeight = \_ -> return ()
439+ , subscriberRecalculateHeight = \_ -> return ()
440+ }
441+
442+newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
443+newSubscriberFan subscribed = return $ Subscriber
444+ { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
445+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
446+ tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
447+ liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
448+ scheduleClear $ fanSubscribedOccurrence subscribed
449+ let f _ (Pair v subsubs) = do
450+ propagate v $ _fanSubscribedChildren_list subsubs
451+ return $ Constant ()
452+ _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
453+ return ()
454+ , subscriberInvalidateHeight = \old -> do
455+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
456+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
457+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
458+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
459+ , subscriberRecalculateHeight = \new -> do
460+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
461+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
462+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
463+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
464+ }
465+
466+newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
467+newSubscriberSwitch subscribed = return $ Subscriber
468+ { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
469+ tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
470+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
471+ scheduleClear $ switchSubscribedOccurrence subscribed
472+ propagate a $ switchSubscribedSubscribers subscribed
473+ , subscriberInvalidateHeight = \_ -> do
474+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
475+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
476+ when (oldHeight /= invalidHeight) $ do
477+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
478+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
479+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
480+ , subscriberRecalculateHeight = \new -> do
481+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
482+ updateSwitchHeight new subscribed
483+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
484+ }
485+
486+newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
487+newSubscriberCoincidenceOuter subscribed = return $ Subscriber
488+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
489+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
490+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
491+ tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
492+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
493+ tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
494+ tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
495+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
496+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
497+ case occ of
498+ Nothing -> do
499+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
500+ writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
501+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
502+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
503+ Just o -> do -- Since it's already firing, no need to adjust height
504+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
505+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
506+ propagate o $ coincidenceSubscribedSubscribers subscribed
507+ , subscriberInvalidateHeight = \_ -> do
508+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
509+ invalidateCoincidenceHeight subscribed
510+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
511+ , subscriberRecalculateHeight = \_ -> do
512+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
513+ recalculateCoincidenceHeight subscribed
514+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
515+ }
516+
517+newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
518+newSubscriberCoincidenceInner subscribed = return $ Subscriber
519+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
520+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
521+ occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
522+ case occ of
523+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
524+ Nothing -> do
525+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
526+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
527+ propagate a $ coincidenceSubscribedSubscribers subscribed
528+ , subscriberInvalidateHeight = \_ -> do
529+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
530+ invalidateCoincidenceHeight subscribed
531+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
532+ , subscriberRecalculateHeight = \_ -> do
533+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
534+ recalculateCoincidenceHeight subscribed
535+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
536+ }
537+
538+invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
539+invalidateSubscriberHeight = flip subscriberInvalidateHeight
540+
541+recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
542+recalculateSubscriberHeight = flip subscriberRecalculateHeight
543+
544+-- | Propagate everything at the current height
545+propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
546+propagate a subscribers = withIncreasedDepth $ do
547+ -- Note: in the following traversal, we do not visit nodes that are added to the list during our traversal; they are new events, which will necessarily have full information already, so there is no need to traverse them
548+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
549+ WeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
550+
551+-- | Propagate everything at the current height
552+propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
553+propagateFast a subscribers = withIncreasedDepth $ do
554+ -- Note: in the following traversal, we do not visit nodes that are added to the list during our traversal; they are new events, which will necessarily have full information already, so there is no need to traverse them
555+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
556+ FastWeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
557+
558+--------------------------------------------------------------------------------
559+-- EventSubscribed
560+--------------------------------------------------------------------------------
561+
562+toAny :: a -> Any
563+toAny = unsafeCoerce
564+
565+-- Why do we use Any here, instead of just giving eventSubscribedRetained an
566+-- existential type? Sadly, GHC does not currently know how to unbox types
567+-- with existentially quantified fields. So instead we just coerce values
568+-- to type Any on the way in. Since we never coerce them back, this is
569+-- perfectly safe.
570+data EventSubscribed x = EventSubscribed
571+ { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
572+ , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
573+#ifdef DEBUG_CYCLES
574+ , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
575+ , eventSubscribedHasOwnHeightRef :: !Bool
576+ , eventSubscribedWhoCreated :: !(IO [String])
577+#endif
578+ }
579+
580+eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
581+eventSubscribedRoot !r = EventSubscribed
582+ { eventSubscribedHeightRef = zeroRef
583+ , eventSubscribedRetained = toAny r
584+#ifdef DEBUG_CYCLES
585+ , eventSubscribedGetParents = return []
586+ , eventSubscribedHasOwnHeightRef = False
587+ , eventSubscribedWhoCreated = return ["root"]
588+#endif
589+ }
590+
591+eventSubscribedNever :: EventSubscribed x
592+eventSubscribedNever = EventSubscribed
593+ { eventSubscribedHeightRef = zeroRef
594+ , eventSubscribedRetained = toAny ()
595+#ifdef DEBUG_CYCLES
596+ , eventSubscribedGetParents = return []
597+ , eventSubscribedHasOwnHeightRef = False
598+ , eventSubscribedWhoCreated = return ["never"]
599+#endif
600+ }
601+
602+eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
603+eventSubscribedFan !subscribed = EventSubscribed
604+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
605+ , eventSubscribedRetained = toAny subscribed
606+#ifdef DEBUG_CYCLES
607+ , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
608+ , eventSubscribedHasOwnHeightRef = False
609+ , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
610+#endif
611+ }
612+
613+eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
614+eventSubscribedSwitch !subscribed = EventSubscribed
615+ { eventSubscribedHeightRef = switchSubscribedHeight subscribed
616+ , eventSubscribedRetained = toAny subscribed
617+#ifdef DEBUG_CYCLES
618+ , eventSubscribedGetParents = do
619+ s <- readIORef $ switchSubscribedCurrentParent subscribed
620+ return [Some $ _eventSubscription_subscribed s]
621+ , eventSubscribedHasOwnHeightRef = True
622+ , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
623+#endif
624+ }
625+
626+eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
627+eventSubscribedCoincidence !subscribed = EventSubscribed
628+ { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
629+ , eventSubscribedRetained = toAny subscribed
630+#ifdef DEBUG_CYCLES
631+ , eventSubscribedGetParents = do
632+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
633+ let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
634+ innerParents = maybeToList $ fmap Some innerSubscription
635+ return $ outerParent : innerParents
636+ , eventSubscribedHasOwnHeightRef = True
637+ , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
638+#endif
639+ }
640+
641+getEventSubscribedHeight :: EventSubscribed x -> IO Height
642+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
643+
644+#ifdef DEBUG_CYCLES
645+whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
646+whoCreatedEventSubscribed = eventSubscribedWhoCreated
647+
648+walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
649+walkInvalidHeightParents s0 = do
650+ subscribers <- flip execStateT mempty $ ($ Some s0) $ fix $ \loop (Some s) -> do
651+ h <- liftIO $ readIORef $ eventSubscribedHeightRef s
652+ when (h == invalidHeight) $ do
653+ when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
654+ modify (Some s :)
655+ mapM_ loop =<< liftIO (eventSubscribedGetParents s)
656+ forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
657+ return subscribers
658+#endif
659+
660+{-# INLINE subscribeHoldEvent #-}
661+subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
662+subscribeHoldEvent = subscribeAndRead . holdEvent
663+
664+--------------------------------------------------------------------------------
665+-- Behavior
666+--------------------------------------------------------------------------------
667+
668+newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
669+
670+behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
671+behaviorHold !h = Behavior $ readHoldTracked h
672+
673+behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
674+behaviorHoldIdentity = behaviorHold
675+
676+behaviorConst :: a -> Behavior x a
677+behaviorConst !a = Behavior $ return a
678+
679+behaviorPull :: Pull x a -> Behavior x a
680+behaviorPull !p = Behavior $ do
681+ val <- liftIO $ readIORef $ pullValue p
682+ case val of
683+ Just subscribed -> do
684+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
685+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
686+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
687+ return $ pullSubscribedValue subscribed
688+ Nothing -> do
689+ i <- liftIO $ newInvalidatorPull p
690+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
691+ parentsRef <- liftIO $ newIORef []
692+ holdInits <- askBehaviorHoldInits
693+ a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
694+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
695+ parents <- liftIO $ readIORef parentsRef
696+ let subscribed = PullSubscribed
697+ { pullSubscribedValue = a
698+ , pullSubscribedInvalidators = invsRef
699+ , pullSubscribedOwnInvalidator = i
700+ , pullSubscribedParents = parents
701+ }
702+ liftIO $ writeIORef (pullValue p) $ Just subscribed
703+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
704+ return a
705+
706+behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
707+behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
708+
709+{-# INLINE readHoldTracked #-}
710+readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
711+readHoldTracked h = do
712+ result <- liftIO $ readIORef $ holdValue h
713+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
714+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
715+ liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
716+ return result
717+
718+{-# INLINABLE readBehaviorUntracked #-}
719+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
720+readBehaviorUntracked b = do
721+ holdInits <- getDeferralQueue
722+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
723+
724+--------------------------------------------------------------------------------
725+-- Dynamic
726+--------------------------------------------------------------------------------
727+
728+type DynamicS x p = Dynamic x (PatchTarget p) p
729+
730+data Dynamic x target p = Dynamic
731+ { dynamicCurrent :: !(Behavior x target)
732+ , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
733+ }
734+
735+deriving instance (HasSpiderTimeline x) => Functor (Dynamic x target)
736+
737+
738+
739+
740+dynamicHold :: Hold x p -> DynamicS x p
741+dynamicHold !h = Dynamic
742+ { dynamicCurrent = behaviorHold h
743+ , dynamicUpdated = eventHold h
744+ }
745+
746+dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)
747+dynamicHoldIdentity = dynamicHold
748+
749+dynamicConst :: PatchTarget p -> DynamicS x p
750+dynamicConst !a = Dynamic
751+ { dynamicCurrent = behaviorConst a
752+ , dynamicUpdated = eventNever
753+ }
754+
755+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p
756+dynamicDyn !d = Dynamic
757+ { dynamicCurrent = behaviorDyn d
758+ , dynamicUpdated = eventDyn d
759+ }
760+
761+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
762+dynamicDynIdentity = dynamicDyn
763+
764+--------------------------------------------------------------------------------
765+-- Combinators
766+--------------------------------------------------------------------------------
767+
768+--type role Hold representational
769+data Hold x p
770+ = Hold { holdValue :: !(IORef (PatchTarget p))
771+ , holdInvalidators :: !(IORef [Weak (Invalidator x)])
772+ , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
773+ , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
774+#ifdef DEBUG_NODEIDS
775+ , holdNodeId :: Int
776+#endif
777+ }
778+
779+-- | A statically allocated 'SpiderTimeline'
780+data Global
781+
782+{-# NOINLINE globalSpiderTimelineEnv #-}
783+globalSpiderTimelineEnv :: SpiderTimelineEnv Global
784+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
785+
786+-- | Stores all global data relevant to a particular Spider timeline; only one
787+-- value should exist for each type @x@
788+newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}
789+-- We implement SpiderTimelineEnv with a newtype wrapper so
790+-- we can get the coercions we want safely.
791+type role SpiderTimelineEnv nominal
792+
793+data SpiderTimelineEnv' x = SpiderTimelineEnv
794+ { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
795+ , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
796+#ifdef DEBUG
797+ , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
798+#endif
799+ }
800+type role SpiderTimelineEnv' phantom
801+
802+instance Eq (SpiderTimelineEnv x) where
803+ _ == _ = True -- Since only one exists of each type
804+
805+instance GEq SpiderTimelineEnv where
806+ a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)
807+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
808+ else Nothing
809+
810+data EventEnv x
811+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
812+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
813+ , eventEnvDynInits :: !(IORef [SomeDynInit x])
814+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
815+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
816+ , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
817+ , eventEnvIntClears :: !(IORef [Some IntClear])
818+ , eventEnvRootClears :: !(IORef [Some RootClear])
819+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
820+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
821+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
822+ }
823+
824+{-# INLINE runEventM #-}
825+runEventM :: EventM x a -> IO a
826+runEventM = unEventM
827+
828+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
829+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))
830+
831+class MonadIO m => Defer a m where
832+ getDeferralQueue :: m (IORef [a])
833+
834+{-# INLINE defer #-}
835+defer :: Defer a m => a -> m ()
836+defer a = do
837+ q <- getDeferralQueue
838+ liftIO $ modifyIORef' q (a:)
839+
840+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
841+ {-# INLINE getDeferralQueue #-}
842+ getDeferralQueue = asksEventEnv eventEnvAssignments
843+
844+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
845+ {-# INLINE getDeferralQueue #-}
846+ getDeferralQueue = asksEventEnv eventEnvHoldInits
847+
848+instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
849+ {-# INLINE getDeferralQueue #-}
850+ getDeferralQueue = asksEventEnv eventEnvDynInits
851+
852+instance Defer (SomeHoldInit x) (BehaviorM x) where
853+ {-# INLINE getDeferralQueue #-}
854+ getDeferralQueue = BehaviorM $ asks snd
855+
856+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
857+ {-# INLINE getDeferralQueue #-}
858+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
859+
860+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
861+ {-# INLINE getDeferralQueue #-}
862+ getDeferralQueue = asksEventEnv eventEnvMergeInits
863+
864+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
865+ getCurrentHeight :: m Height
866+ scheduleMerge :: Height -> EventM x () -> m ()
867+
868+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
869+ {-# INLINE getCurrentHeight #-}
870+ getCurrentHeight = do
871+ heightRef <- asksEventEnv eventEnvCurrentHeight
872+ liftIO $ readIORef heightRef
873+ {-# INLINE scheduleMerge #-}
874+ scheduleMerge height subscribed = do
875+ delayedRef <- asksEventEnv eventEnvDelayedMerges
876+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
877+
878+class HasSpiderTimeline x where
879+ -- | Retrieve the current SpiderTimelineEnv
880+ spiderTimeline :: SpiderTimelineEnv x
881+
882+instance HasSpiderTimeline Global where
883+ spiderTimeline = globalSpiderTimelineEnv
884+
885+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
886+putCurrentHeight h = do
887+ heightRef <- asksEventEnv eventEnvCurrentHeight
888+ liftIO $ writeIORef heightRef $! h
889+
890+instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
891+ {-# INLINE getDeferralQueue #-}
892+ getDeferralQueue = asksEventEnv eventEnvClears
893+
894+{-# INLINE scheduleClear #-}
895+scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
896+scheduleClear r = defer $ Some $ Clear r
897+
898+instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
899+ {-# INLINE getDeferralQueue #-}
900+ getDeferralQueue = asksEventEnv eventEnvIntClears
901+
902+{-# INLINE scheduleIntClear #-}
903+scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
904+scheduleIntClear r = defer $ Some $ IntClear r
905+
906+instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
907+ {-# INLINE getDeferralQueue #-}
908+ getDeferralQueue = asksEventEnv eventEnvRootClears
909+
910+{-# INLINE scheduleRootClear #-}
911+scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
912+scheduleRootClear r = defer $ Some $ RootClear r
913+
914+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
915+ {-# INLINE getDeferralQueue #-}
916+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
917+
918+-- Note: hold cannot examine its event until after the phase is over
919+{-# INLINE [1] hold #-}
920+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
921+hold v0 e = do
922+ valRef <- liftIO $ newIORef v0
923+ invsRef <- liftIO $ newIORef []
924+ parentRef <- liftIO $ newIORef Nothing
925+#ifdef DEBUG_NODEIDS
926+ nodeId <- liftIO newNodeId
927+#endif
928+ let h = Hold
929+ { holdValue = valRef
930+ , holdInvalidators = invsRef
931+ , holdEvent = e
932+ , holdParent = parentRef
933+#ifdef DEBUG_NODEIDS
934+ , holdNodeId = nodeId
935+#endif
936+ }
937+ defer $ SomeHoldInit h
938+ return h
939+
940+{-# INLINE getHoldEventSubscription #-}
941+getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
942+getHoldEventSubscription h = do
943+ ep <- liftIO $ readIORef $ holdParent h
944+ case ep of
945+ Just subd -> return subd
946+ Nothing -> do
947+ let e = holdEvent h
948+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
949+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
950+ liftIO $ writeIORef subscriptionRef $! subscription
951+ case occ of
952+ Nothing -> return ()
953+ Just o -> do
954+ old <- liftIO $ readIORef $ holdValue h
955+ case apply o old of
956+ Nothing -> return ()
957+ Just new -> do
958+ -- Need to evaluate these so that we don't retain the Hold itself
959+ v <- liftIO $ evaluate $ holdValue h
960+ i <- liftIO $ evaluate $ holdInvalidators h
961+ defer $ SomeAssignment v i new
962+ liftIO $ writeIORef (holdParent h) $ Just subscription
963+ return subscription
964+
965+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
966+
967+-- BehaviorM can sample behaviors
968+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderIO (BehaviorEnv x) a }
969+ deriving (Functor, Applicative, MonadIO, MonadFix, MonadReader (BehaviorEnv x))
970+
971+instance Monad (BehaviorM x) where
972+ {-# INLINE (>>=) #-}
973+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
974+ {-# INLINE (>>) #-}
975+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
976+ {-# INLINE return #-}
977+ return x = BehaviorM $ return x
978+#if !MIN_VERSION_base(4,13,0)
979+ {-# INLINE fail #-}
980+ fail s = BehaviorM $ fail s
981+#endif
982+
983+data BehaviorSubscribed x a
984+ = forall p. BehaviorSubscribedHold (Hold x p)
985+ | BehaviorSubscribedPull (PullSubscribed x a)
986+
987+newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
988+
989+--type role PullSubscribed representational
990+data PullSubscribed x a
991+ = PullSubscribed { pullSubscribedValue :: !a
992+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
993+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
994+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
995+ }
996+
997+--type role Pull representational
998+data Pull x a
999+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
1000+ , pullCompute :: !(BehaviorM x a)
1001+#ifdef DEBUG_NODEIDS
1002+ , pullNodeId :: Int
1003+#endif
1004+ }
1005+
1006+data Invalidator x
1007+ = forall a. InvalidatorPull (Pull x a)
1008+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
1009+
1010+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
1011+ { rootSubscribedKey :: !(k a)
1012+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
1013+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1014+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
1015+ , rootSubscribedUninit :: IO ()
1016+ , rootSubscribedWeakSelf :: !(IORef (Weak (RootSubscribed x a))) --TODO: Can we make this a lazy non-IORef and then force it manually to avoid an indirection each time we use it?
1017+#ifdef DEBUG_NODEIDS
1018+ , rootSubscribedNodeId :: Int
1019+#endif
1020+ }
1021+
1022+data Root x k
1023+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
1024+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
1025+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
1026+ }
1027+
1028+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1029+
1030+data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1031+
1032+data SomeMergeUpdate x = SomeMergeUpdate
1033+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1034+ , _someMergeUpdate_invalidateHeight :: !(IO ())
1035+ , _someMergeUpdate_recalculateHeight :: !(IO ())
1036+ }
1037+
1038+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1039+
1040+-- EventM can do everything BehaviorM can, plus create holds
1041+newtype EventM x a = EventM { unEventM :: IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadException, MonadAsyncException) -- The environment should be Nothing if we are not in a frame, and Just if we are - in which case it is a list of assignments to be done after the frame is over
1042+
1043+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1044+
1045+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1046+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1047+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1048+ }
1049+
1050+data HeightBag = HeightBag
1051+ { _heightBag_size :: {-# UNPACK #-} !Int
1052+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1053+ }
1054+ deriving (Show, Read, Eq, Ord)
1055+
1056+heightBagEmpty :: HeightBag
1057+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1058+
1059+heightBagSize :: HeightBag -> Int
1060+heightBagSize = _heightBag_size
1061+
1062+heightBagFromList :: [Height] -> HeightBag
1063+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1064+
1065+heightBagAdd :: Height -> HeightBag -> HeightBag
1066+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1067+
1068+heightBagRemove :: Height -> HeightBag -> HeightBag
1069+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1070+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1071+ Just old -> HeightBag (pred s) $ case old of
1072+ 0 -> IntMap.delete h c
1073+ _ -> IntMap.insert h (pred old) c
1074+
1075+heightBagMax :: HeightBag -> Height
1076+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1077+ Just ((h, _), _) -> Height h
1078+ Nothing -> zeroHeight
1079+
1080+heightBagVerify :: HeightBag -> HeightBag
1081+#ifdef DEBUG
1082+heightBagVerify b@(HeightBag s c) = if
1083+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1084+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1085+ | unHeight invalidHeight `IntMap.member` c
1086+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1087+ | otherwise -> b
1088+#else
1089+heightBagVerify = id
1090+#endif
1091+
1092+data FanSubscribedChildren x k v a = FanSubscribedChildren
1093+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1094+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1095+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
1096+ }
1097+
1098+data FanSubscribed x k v
1099+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1100+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1101+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
1102+ , fanSubscribedParent :: !(EventSubscription x)
1103+#ifdef DEBUG_NODEIDS
1104+ , fanSubscribedNodeId :: Int
1105+#endif
1106+ }
1107+
1108+data Fan x k v
1109+ = Fan { fanParent :: !(Event x (DMap k v))
1110+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1111+ }
1112+
1113+data SwitchSubscribed x a
1114+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1115+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1116+ , switchSubscribedHeight :: !(IORef Height)
1117+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1118+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1119+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1120+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1121+ , switchSubscribedParent :: !(Behavior x (Event x a))
1122+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1123+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1124+#ifdef DEBUG_NODEIDS
1125+ , switchSubscribedNodeId :: Int
1126+#endif
1127+ }
1128+
1129+data Switch x a
1130+ = Switch { switchParent :: !(Behavior x (Event x a))
1131+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1132+ }
1133+
1134+#ifdef USE_TEMPLATE_HASKELL
1135+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1136+#endif
1137+data CoincidenceSubscribed x a
1138+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1139+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1140+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1141+ , coincidenceSubscribedHeight :: !(IORef Height)
1142+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1143+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1144+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1145+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1146+#ifdef DEBUG_NODEIDS
1147+ , coincidenceSubscribedNodeId :: Int
1148+#endif
1149+ }
1150+
1151+data Coincidence x a
1152+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1153+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1154+ }
1155+
1156+{-# NOINLINE newInvalidatorSwitch #-}
1157+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1158+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1159+
1160+{-# NOINLINE newInvalidatorPull #-}
1161+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1162+newInvalidatorPull p = return $! InvalidatorPull p
1163+
1164+instance HasSpiderTimeline x => Filterable (Event x) where
1165+ mapMaybe f = push $ return . f
1166+
1167+instance HasSpiderTimeline x => Align (Event x) where
1168+ nil = eventNever
1169+#if MIN_VERSION_these(0, 8, 0)
1170+instance HasSpiderTimeline x => Semialign (Event x) where
1171+#endif
1172+ align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1173+ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1174+
1175+#ifdef MIN_VERSION_semialign
1176+#if MIN_VERSION_semialign(1,1,0)
1177+instance HasSpiderTimeline x => Zip (Event x) where
1178+#endif
1179+ zip x y = mapMaybe justThese $ align x y
1180+#endif
1181+
1182+data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1183+ | BuildDyn !(EventM x (PatchTarget p), Event x p)
1184+ | HoldDyn !(Hold x p)
1185+
1186+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1187+
1188+newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)
1189+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1190+
1191+--TODO: Avoid the duplication between this and R.zipDynWith
1192+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)
1193+zipDynWith f da db =
1194+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1195+ ec = flip push eab $ \o -> do
1196+ (a, b) <- case o of
1197+ This (Identity a) -> do
1198+ b <- readBehaviorUntracked $ dynamicCurrent db
1199+ return (a, b)
1200+ That (Identity b) -> do
1201+ a <- readBehaviorUntracked $ dynamicCurrent da
1202+ return (a, b)
1203+ These (Identity a) (Identity b) -> return (a, b)
1204+ return $ Just $ Identity $ f a b
1205+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1206+
1207+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1208+buildDynamic readV0 v' = do
1209+ result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1210+ let !d = Dyn result
1211+ defer $ SomeDynInit d
1212+ return d
1213+
1214+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1215+unsafeBuildDynamic readV0 v' =
1216+ Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
1217+
1218+-- ResultM can read behaviors and events
1219+type ResultM = EventM
1220+
1221+instance HasSpiderTimeline x => Functor (Event x) where
1222+ fmap f = push $ return . Just . f
1223+
1224+instance Functor (Behavior x) where
1225+ fmap f = pull . fmap f . readBehaviorTracked
1226+
1227+{-# INLINE push #-}
1228+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1229+push f e = cacheEvent (pushCheap f e)
1230+
1231+{-# INLINABLE pull #-}
1232+pull :: BehaviorM x a -> Behavior x a
1233+pull a = unsafePerformIO $ do
1234+ ref <- newIORef Nothing
1235+#ifdef DEBUG_NODEIDS
1236+ nid <- newNodeId
1237+#endif
1238+ pure $ behaviorPull $ Pull
1239+ { pullCompute = a
1240+ , pullValue = ref
1241+#ifdef DEBUG_NODEIDS
1242+ , pullNodeId = nid
1243+#endif
1244+ }
1245+
1246+{-# INLINABLE switch #-}
1247+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1248+switch a = unsafePerformIO $ do
1249+ ref <- newIORef Nothing
1250+ pure $ eventSwitch $ Switch
1251+ { switchParent = a
1252+ , switchSubscribed = ref
1253+ }
1254+
1255+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1256+coincidence a = unsafePerformIO $ do
1257+ ref <- newIORef Nothing
1258+ pure $ eventCoincidence $ Coincidence
1259+ { coincidenceParent = a
1260+ , coincidenceSubscribed = ref
1261+ }
1262+
1263+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1264+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1265+run roots after = do
1266+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1267+ let t = spiderTimeline :: SpiderTimelineEnv x
1268+ result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do
1269+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1270+ occBefore <- liftIO $ do
1271+ occBefore <- readIORef occRef
1272+ writeIORef occRef $! DMap.insert k a occBefore
1273+ return occBefore
1274+ if DMap.null occBefore
1275+ then do scheduleRootClear occRef
1276+ return $ Just r
1277+ else return Nothing
1278+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1279+ propagate a subscribersRef
1280+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1281+ let go = do
1282+ delayed <- liftIO $ readIORef delayedRef
1283+ case IntMap.minViewWithKey delayed of
1284+ Nothing -> return ()
1285+ Just ((currentHeight, cur), future) -> do
1286+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1287+ putCurrentHeight $ Height currentHeight
1288+ liftIO $ writeIORef delayedRef $! future
1289+ sequence_ cur
1290+ go
1291+ go
1292+ putCurrentHeight maxBound
1293+ after
1294+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1295+ return result
1296+
1297+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1298+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1299+ height <- liftIO $ readIORef heightRef
1300+ currentHeight <- getCurrentHeight
1301+ case height `compare` currentHeight of
1302+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1303+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1304+ EQ -> a
1305+
1306+newtype Clear a = Clear (IORef (Maybe a))
1307+
1308+newtype IntClear a = IntClear (IORef (IntMap a))
1309+
1310+newtype RootClear k = RootClear (IORef (DMap k Identity))
1311+
1312+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1313+
1314+debugFinalize :: Bool
1315+debugFinalize = False
1316+
1317+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1318+mkWeakPtrWithDebug x debugNote = do
1319+ x' <- evaluate x
1320+ mkWeakPtr x' $
1321+ if debugFinalize
1322+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1323+ else Nothing
1324+
1325+type WeakList a = [Weak a]
1326+
1327+{-# INLINE withIncreasedDepth #-}
1328+#ifdef DEBUG
1329+withIncreasedDepth :: CanTrace x m => m a -> m a
1330+withIncreasedDepth a = do
1331+ spiderTimeline <- askSpiderTimelineEnv
1332+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) succ
1333+ result <- a
1334+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) pred
1335+ return result
1336+#else
1337+withIncreasedDepth :: m a -> m a
1338+withIncreasedDepth = id
1339+#endif
1340+
1341+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1342+
1343+{-# INLINE tracePropagate #-}
1344+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1345+tracePropagate p = traceWhen p debugPropagate
1346+
1347+{-# INLINE traceInvalidate #-}
1348+traceInvalidate :: String -> IO ()
1349+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1350+
1351+{-# INLINE traceWhen #-}
1352+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1353+traceWhen p b message = traceMWhen p b $ return message
1354+
1355+{-# INLINE traceMWhen #-}
1356+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1357+traceMWhen _ b getMessage = when b $ do
1358+ message <- getMessage
1359+#ifdef DEBUG
1360+ spiderTimeline <- askSpiderTimelineEnv
1361+ d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE spiderTimeline
1362+#else
1363+ let d = 0
1364+#endif
1365+ liftIO $ putStrLn $ replicate d ' ' <> message
1366+
1367+whoCreatedIORef :: IORef a -> IO [String]
1368+whoCreatedIORef (IORef a) = whoCreated $! a
1369+
1370+#ifdef DEBUG_CYCLES
1371+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1372+groupByHead = \case
1373+ [] -> []
1374+ (x :| xs) : t -> case groupByHead t of
1375+ [] -> [(x, xs :| [])]
1376+ l@((y, yss) : t')
1377+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1378+ | otherwise -> (x, xs :| []) : l
1379+
1380+listsToForest :: Eq a => [[a]] -> Forest a
1381+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1382+#endif
1383+
1384+{-# INLINE propagateSubscriberHold #-}
1385+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1386+propagateSubscriberHold h a = do
1387+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1388+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1389+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1390+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1391+ case {-# SCC "apply" #-} apply a v of
1392+ Nothing -> return ()
1393+ Just v' -> do
1394+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1395+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1396+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1397+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1398+
1399+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1400+
1401+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1402+runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)
1403+
1404+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1405+askInvalidator = do
1406+ (!m, _) <- ask
1407+ case m of
1408+ Nothing -> return Nothing
1409+ Just (!wi, _) -> return $ Just wi
1410+
1411+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1412+askParentsRef = do
1413+ (!m, _) <- ask
1414+ case m of
1415+ Nothing -> return Nothing
1416+ Just (_, !p) -> return $ Just p
1417+
1418+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1419+askBehaviorHoldInits = do
1420+ (_, !his) <- ask
1421+ return his
1422+
1423+{-# INLINE getDynHold #-}
1424+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1425+getDynHold d = do
1426+ mh <- liftIO $ readIORef $ unDyn d
1427+ case mh of
1428+ HoldDyn h -> return h
1429+ UnsafeDyn (readV0, v') -> do
1430+ holdInits <- getDeferralQueue
1431+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1432+ hold' v0 v'
1433+ BuildDyn (readV0, v') -> do
1434+ v0 <- liftIO $ runEventM readV0
1435+ hold' v0 v'
1436+ where
1437+ hold' v0 v' = do
1438+ h <- hold v0 v'
1439+ liftIO $ writeIORef (unDyn d) $ HoldDyn h
1440+ return h
1441+
1442+
1443+-- Always refers to 0
1444+{-# NOINLINE zeroRef #-}
1445+zeroRef :: IORef Height
1446+zeroRef = unsafePerformIO $ newIORef zeroHeight
1447+
1448+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1449+getRootSubscribed k r sub = do
1450+ mSubscribed <- readIORef $ rootSubscribed r
1451+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1452+ case DMap.lookup k mSubscribed of
1453+ Just subscribed -> {-# SCC "hitRoot" #-} do
1454+ sln <- subscribeRootSubscribed subscribed sub
1455+ occ <- getOcc
1456+ return (sln, subscribed, occ)
1457+ Nothing -> {-# SCC "missRoot" #-} do
1458+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1459+ let !cached = rootSubscribed r
1460+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1461+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1462+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1463+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1464+ writeIORef uninitRef $! uninit
1465+#ifdef DEBUG_NODEIDS
1466+ nid <- newNodeId
1467+#endif
1468+ let !subscribed = RootSubscribed
1469+ { rootSubscribedKey = k
1470+ , rootSubscribedCachedSubscribed = cached
1471+ , rootSubscribedOccurrence = getOcc
1472+ , rootSubscribedSubscribers = subs
1473+ , rootSubscribedUninit = uninit
1474+ , rootSubscribedWeakSelf = weakSelf
1475+#ifdef DEBUG_NODEIDS
1476+ , rootSubscribedNodeId = nid
1477+#endif
1478+ }
1479+ -- If we die at the same moment that all our children die, they will
1480+ -- try to clean us up but will fail because their Weak reference to us
1481+ -- will also be dead. So, if we are dying, check if there are any
1482+ -- children; since children don't bother cleaning themselves up if
1483+ -- their parents are already dead, I don't think there's a race
1484+ -- condition here. However, if there are any children, then we can
1485+ -- infer that we need to clean ourselves up, so we do.
1486+ finalCleanup = do
1487+ cs <- readIORef $ _weakBag_children subs
1488+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1489+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1490+ modifyIORef' (rootSubscribed r) $ DMap.insertWith (error $ "getRootSubscribed: duplicate key inserted into Root") k subscribed --TODO: I think we can just write back mSubscribed rather than re-reading it
1491+ occ <- getOcc
1492+ return (sln, subscribed, occ)
1493+
1494+#ifdef USE_TEMPLATE_HASKELL
1495+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1496+#endif
1497+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1498+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1499+ rootSubscribedUninit self
1500+ modifyIORef' cached $ DMap.delete k
1501+
1502+{-# INLINE subscribeRootSubscribed #-}
1503+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1504+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1505+
1506+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1507+
1508+data FanInt x a = FanInt
1509+ { _fanInt_subscribers :: {-# UNPACK #-} !(FastMutableIntMap (FastWeakBag (Subscriber x a))) --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1510+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1511+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1512+ }
1513+
1514+newFanInt :: IO (FanInt x a)
1515+newFanInt = do
1516+ subscribers <- FastMutableIntMap.newEmpty --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1517+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1518+ occRef <- newIORef $ error "fanInt: no occurrence"
1519+ return $ FanInt
1520+ { _fanInt_subscribers = subscribers
1521+ , _fanInt_subscriptionRef = subscriptionRef
1522+ , _fanInt_occRef = occRef
1523+ }
1524+
1525+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1526+fanInt p = unsafePerformIO $ do
1527+ self <- newFanInt
1528+ pure $ EventSelectorInt $ \k -> Event $ \sub -> do
1529+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1530+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1531+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1532+ { subscriberPropagate = \m -> do
1533+ liftIO $ writeIORef (_fanInt_occRef self) m
1534+ scheduleIntClear $ _fanInt_occRef self
1535+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1536+ FastWeakBag.traverse_ b $ \s -> do
1537+ subscriberPropagate s v
1538+ , subscriberInvalidateHeight = \old -> do
1539+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1540+ FastWeakBag.traverse_ b $ \s -> do
1541+ subscriberInvalidateHeight s old
1542+ , subscriberRecalculateHeight = \new -> do
1543+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1544+ FastWeakBag.traverse_ b $ \s -> do
1545+ subscriberRecalculateHeight s new
1546+ }
1547+ liftIO $ do
1548+ writeIORef (_fanInt_subscriptionRef self) subscription
1549+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1550+ scheduleIntClear $ _fanInt_occRef self
1551+ liftIO $ do
1552+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1553+ Nothing -> do
1554+ b <- FastWeakBag.empty
1555+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1556+ return b
1557+ Just b -> return b
1558+ t <- liftIO $ FastWeakBag.insert sub b
1559+ currentOcc <- readIORef (_fanInt_occRef self)
1560+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1561+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1562+
1563+{-# INLINABLE getFanSubscribed #-}
1564+getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k v -> Subscriber x (v a) -> EventM x (WeakBagTicket, FanSubscribed x k v, Maybe (v a))
1565+getFanSubscribed k f sub = do
1566+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1567+ case mSubscribed of
1568+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1569+ sln <- subscribeFanSubscribed k subscribed sub
1570+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1571+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1572+ Nothing -> {-# SCC "missFan" #-} do
1573+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1574+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1575+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1576+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1577+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1578+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1579+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1580+ occRef <- liftIO $ newIORef parentOcc
1581+ when (isJust parentOcc) $ scheduleClear occRef
1582+#ifdef DEBUG_NODEIDS
1583+ nid <- liftIO newNodeId
1584+#endif
1585+ let subscribed = FanSubscribed
1586+ { fanSubscribedCachedSubscribed = fanSubscribed f
1587+ , fanSubscribedOccurrence = occRef
1588+ , fanSubscribedParent = subscription
1589+ , fanSubscribedSubscribers = subscribersRef
1590+#ifdef DEBUG_NODEIDS
1591+ , fanSubscribedNodeId = nid
1592+#endif
1593+ }
1594+ let !self = (k, subscribed)
1595+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1596+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1597+ liftIO $ writeIORef subscribedRef $! subscribed
1598+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1599+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1600+
1601+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
1602+cleanupFanSubscribed (k, subscribed) = do
1603+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1604+ let reducedSubscribers = DMap.delete k subscribers
1605+ if DMap.null reducedSubscribers
1606+ then do
1607+ unsubscribe $ fanSubscribedParent subscribed
1608+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1609+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1610+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1611+
1612+{-# INLINE subscribeFanSubscribed #-}
1613+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
1614+subscribeFanSubscribed k subscribed sub = do
1615+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1616+ case DMap.lookup k subscribers of
1617+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1618+ let !self = (k, subscribed)
1619+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1620+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1621+ writeIORef (fanSubscribedSubscribers subscribed) $! DMap.insertWith (error "subscribeFanSubscribed: key that we just failed to find is present - should be impossible") k (FanSubscribedChildren list self weakSelf) subscribers
1622+ return sln
1623+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1624+
1625+{-# INLINABLE getSwitchSubscribed #-}
1626+getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1627+getSwitchSubscribed s sub = do
1628+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1629+ case mSubscribed of
1630+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1631+ sln <- subscribeSwitchSubscribed subscribed sub
1632+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1633+ return (sln, subscribed, occ)
1634+ Nothing -> {-# SCC "missSwitch" #-} do
1635+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1636+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1637+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1638+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1639+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1640+ wiRef <- liftIO $ newIORef wi
1641+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1642+ holdInits <- getDeferralQueue
1643+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1644+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1645+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1646+ subscriptionRef <- liftIO $ newIORef subscription
1647+ occRef <- liftIO $ newIORef parentOcc
1648+ when (isJust parentOcc) $ scheduleClear occRef
1649+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1650+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1651+#ifdef DEBUG_NODEIDS
1652+ nid <- liftIO newNodeId
1653+#endif
1654+ let !subscribed = SwitchSubscribed
1655+ { switchSubscribedCachedSubscribed = switchSubscribed s
1656+ , switchSubscribedOccurrence = occRef
1657+ , switchSubscribedHeight = heightRef
1658+ , switchSubscribedSubscribers = subs
1659+ , switchSubscribedOwnInvalidator = i
1660+ , switchSubscribedOwnWeakInvalidator = wiRef
1661+ , switchSubscribedBehaviorParents = parentsRef
1662+ , switchSubscribedParent = switchParent s
1663+ , switchSubscribedCurrentParent = subscriptionRef
1664+ , switchSubscribedWeakSelf = weakSelf
1665+#ifdef DEBUG_NODEIDS
1666+ , switchSubscribedNodeId = nid
1667+#endif
1668+ }
1669+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1670+ liftIO $ writeIORef subscribedRef $! subscribed
1671+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1672+ return (slnForSub, subscribed, parentOcc)
1673+
1674+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1675+cleanupSwitchSubscribed subscribed = do
1676+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1677+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1678+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1679+
1680+{-# INLINE subscribeSwitchSubscribed #-}
1681+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1682+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1683+
1684+{-# INLINABLE getCoincidenceSubscribed #-}
1685+getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1686+getCoincidenceSubscribed c sub = do
1687+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1688+ case mSubscribed of
1689+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1690+ sln <- subscribeCoincidenceSubscribed subscribed sub
1691+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1692+ return (sln, subscribed, occ)
1693+ Nothing -> {-# SCC "missCoincidence" #-} do
1694+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1695+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1696+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1697+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1698+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1699+ (occ, height, mInnerSubd) <- case outerOcc of
1700+ Nothing -> return (Nothing, outerHeight, Nothing)
1701+ Just o -> do
1702+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1703+ return (occ, height, Just innerSubd)
1704+ occRef <- liftIO $ newIORef occ
1705+ when (isJust occ) $ scheduleClear occRef
1706+ heightRef <- liftIO $ newIORef height
1707+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1708+ scheduleClear innerSubdRef
1709+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1710+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1711+#ifdef DEBUG_NODEIDS
1712+ nid <- liftIO newNodeId
1713+#endif
1714+ let subscribed = CoincidenceSubscribed
1715+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1716+ , coincidenceSubscribedOccurrence = occRef
1717+ , coincidenceSubscribedHeight = heightRef
1718+ , coincidenceSubscribedSubscribers = subs
1719+ , coincidenceSubscribedOuter = subOuter
1720+ , coincidenceSubscribedOuterParent = outerSubscription
1721+ , coincidenceSubscribedInnerParent = innerSubdRef
1722+ , coincidenceSubscribedWeakSelf = weakSelf
1723+#ifdef DEBUG_NODEIDS
1724+ , coincidenceSubscribedNodeId = nid
1725+#endif
1726+ }
1727+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1728+ liftIO $ writeIORef subscribedRef $! subscribed
1729+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1730+ return (slnForSub, subscribed, occ)
1731+
1732+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1733+cleanupCoincidenceSubscribed subscribed = do
1734+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1735+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1736+
1737+{-# INLINE subscribeCoincidenceSubscribed #-}
1738+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1739+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1740+
1741+{-# INLINE mergeG #-}
1742+mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1743+ => (forall a. q a -> Event x (v a))
1744+ -> DynamicS x (PatchDMap k q) -> Event x (DMap k v)
1745+mergeG nt d = cacheEvent (mergeCheap nt d)
1746+
1747+{-# INLINE mergeWithMove #-}
1748+mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1749+ => (forall a. q a -> Event x (v a))
1750+ -> DynamicS x (PatchDMapWithMove k q) -> Event x (DMap k v)
1751+mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1752+
1753+{-# INLINE [1] mergeCheap #-}
1754+mergeCheap
1755+ :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1756+ => (forall a. q a -> Event x (v a))
1757+ -> DynamicS x (PatchDMap k q)
1758+ -> Event x (DMap k v)
1759+mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
1760+ where
1761+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1762+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1763+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1764+ (mOldSubd, newPs) <- case me of
1765+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1766+ Just e -> do
1767+ let s = subscriber $ return k
1768+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1769+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1770+ let newParent = MergeSubscribedParent subscription
1771+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1772+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1773+ forM_ mOldSubd $ \oldSubd -> do
1774+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1775+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1776+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1777+ foldM f ([], oldParents) $ DMap.toList p
1778+
1779+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1780+ getInitialSubscribers initialParents subscriber = do
1781+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1782+ let s = subscriber $ return k
1783+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1784+ height <- liftIO $ getEventSubscribedHeight parentSubd
1785+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
1786+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1787+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1788+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1789+ )
1790+
1791+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1792+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1793+
1794+{-# INLINE [1] mergeCheapWithMove #-}
1795+mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1796+ => (forall a. q a -> Event x (v a))
1797+ -> DynamicS x (PatchDMapWithMove k q)
1798+ -> Event x (DMap k v)
1799+mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
1800+ where
1801+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1802+ updateMe subscriber heightBagRef oldParents p = do
1803+ -- Prepare new parents for insertion
1804+ let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1805+ subscribeParent k e = do
1806+ keyRef <- liftIO $ newIORef k
1807+ let s = subscriber $ liftIO $ readIORef keyRef
1808+ subscription@(EventSubscription _ subd) <- subscribe e s
1809+ liftIO $ do
1810+ newParentHeight <- getEventSubscribedHeight subd
1811+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1812+ return $ MergeSubscribedParentWithMove subscription keyRef
1813+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1814+ -- Collect old parents for deletion and update the keys of moved parents
1815+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1816+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1817+ Nothing -> do
1818+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1819+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1820+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1821+ Just toKey -> do
1822+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1823+ return Nothing
1824+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1825+ return (toDelete, applyAlways p' oldParents)
1826+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1827+ getInitialSubscribers initialParents subscriber = do
1828+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1829+ keyRef <- liftIO $ newIORef k
1830+ let s = subscriber $ liftIO $ readIORef keyRef
1831+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1832+ height <- liftIO $ getEventSubscribedHeight parentSubd
1833+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1834+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1835+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1836+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1837+ )
1838+
1839+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1840+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1841+
1842+type MergeUpdateFunc k v x p s
1843+ = (forall a. EventM x (k a) -> Subscriber x (v a))
1844+ -> IORef HeightBag
1845+ -> DMap k s
1846+ -> p
1847+ -> EventM x ([EventSubscription x], DMap k s)
1848+
1849+type MergeInitFunc k v q x s
1850+ = DMap k q
1851+ -> (forall a. EventM x (k a) -> Subscriber x (v a))
1852+ -> EventM x (DMap k v, [Height], DMap k s)
1853+
1854+type MergeDestroyFunc k s
1855+ = DMap k s
1856+ -> IO ()
1857+
1858+data Merge x k v s = Merge
1859+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1860+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1861+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1862+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1863+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
1864+ }
1865+
1866+invalidateMergeHeight :: Merge x k v s -> IO ()
1867+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1868+
1869+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1870+invalidateMergeHeight' heightRef sub = do
1871+ oldHeight <- readIORef heightRef
1872+ when (oldHeight /= invalidHeight) $ do -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
1873+ writeIORef heightRef $! invalidHeight
1874+ subscriberInvalidateHeight sub oldHeight
1875+
1876+revalidateMergeHeight :: Merge x k v s -> IO ()
1877+revalidateMergeHeight m = do
1878+ currentHeight <- readIORef $ _merge_heightRef m
1879+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1880+ heights <- readIORef $ _merge_heightBagRef m
1881+ parents <- readIORef $ _merge_parentsRef m
1882+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1883+ case heightBagSize heights `compare` DMap.size parents of
1884+ LT -> return ()
1885+ EQ -> do
1886+ let height = succHeight $ heightBagMax heights
1887+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1888+ writeIORef (_merge_heightRef m) $! height
1889+ subscriberRecalculateHeight (_merge_sub m) height
1890+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1891+
1892+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
1893+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1894+ vals <- liftIO $ readIORef $ _merge_accumRef m
1895+ liftIO $ writeIORef (_merge_accumRef m) $! DMap.empty -- Once we're done with this, we can clear it immediately, because if there's a cacheEvent in front of us, it'll handle subsequent subscribers, and if not, we won't get subsequent subscribers
1896+ --TODO: Assert that m is not empty
1897+ subscriberPropagate (_merge_sub m) vals
1898+
1899+mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
1900+mergeSubscriber m getKey = Subscriber
1901+ { subscriberPropagate = \a -> do
1902+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1903+ k <- getKey
1904+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
1905+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1906+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1907+ when (DMap.null oldM) $ do -- Only schedule the firing once
1908+ height <- liftIO $ readIORef $ _merge_heightRef m
1909+ --TODO: assertions about height
1910+ currentHeight <- getCurrentHeight
1911+ when (height <= currentHeight) $ do
1912+ if height /= invalidHeight
1913+ then do
1914+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1915+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1916+ else liftIO $ do
1917+#ifdef DEBUG_CYCLES
1918+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1919+ stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
1920+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1921+#else
1922+ let cycleInfo = ""
1923+#endif
1924+ error $ "Causality loop found" <> cycleInfo
1925+ scheduleMergeSelf m height
1926+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1927+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1928+ invalidateMergeHeight m
1929+ , subscriberRecalculateHeight = \new -> do
1930+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1931+ revalidateMergeHeight m
1932+ }
1933+
1934+--TODO: Be able to run as much of this as possible promptly
1935+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
1936+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1937+ where updateMe = do
1938+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1939+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1940+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1941+ return subscriptionsToKill
1942+
1943+{-# INLINE mergeGCheap' #-}
1944+mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1945+ => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> DynamicS x p -> Event x (DMap k v)
1946+mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1947+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1948+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1949+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1950+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1951+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1952+ let m = Merge
1953+ { _merge_parentsRef = parentsRef
1954+ , _merge_heightBagRef = heightBagRef
1955+ , _merge_heightRef = heightRef
1956+ , _merge_sub = sub
1957+ , _merge_accumRef = accumRef
1958+ }
1959+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1960+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1961+ myHeight = if invalidHeight `elem` heights
1962+ then invalidHeight
1963+ else succHeight $ heightBagMax myHeightBag
1964+ currentHeight <- getCurrentHeight
1965+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1966+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1967+ else (Nothing, dm)
1968+ unless (DMap.null accum) $ do
1969+ scheduleMergeSelf m myHeight
1970+ liftIO $ writeIORef accumRef $! accum
1971+ liftIO $ writeIORef heightRef $! myHeight
1972+ liftIO $ writeIORef heightBagRef $! myHeightBag
1973+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1974+ liftIO $ writeIORef parentsRef $! initialParentState
1975+ defer $ SomeMergeInit $ do
1976+ let s = Subscriber
1977+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1978+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1979+ defer $ updateMerge m updateFunc a
1980+ , subscriberInvalidateHeight = \_ -> return ()
1981+ , subscriberRecalculateHeight = \_ -> return ()
1982+ }
1983+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1984+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1985+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1986+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1987+ -- its subscription.
1988+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1989+ let unsubscribeAll = destroy =<< readIORef parentsRef
1990+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1991+ , occ
1992+ )
1993+
1994+mergeInt :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1995+mergeInt = cacheEvent . mergeIntCheap
1996+
1997+{-# INLINABLE mergeIntCheap #-}
1998+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1999+mergeIntCheap d = Event $ \sub -> do
2000+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
2001+ accum <- liftIO $ FastMutableIntMap.newEmpty
2002+ heightRef <- liftIO $ newIORef zeroHeight
2003+ heightBagRef <- liftIO $ newIORef heightBagEmpty
2004+ parents <- liftIO $ FastMutableIntMap.newEmpty
2005+ let scheduleSelf = do
2006+ height <- liftIO $ readIORef $ heightRef
2007+ scheduleMerge' height heightRef $ do
2008+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
2009+ subscriberPropagate sub vals
2010+ invalidateMyHeight = do
2011+ invalidateMergeHeight' heightRef sub
2012+ recalculateMyHeight = do
2013+ currentHeight <- readIORef heightRef
2014+ when (currentHeight == invalidHeight) $ do --TODO: This will almost always be true; can we get rid of this check and just proceed to the next one always?
2015+ heights <- readIORef heightBagRef
2016+ numParents <- FastMutableIntMap.size parents
2017+ case heightBagSize heights `compare` numParents of
2018+ LT -> return ()
2019+ EQ -> do
2020+ let height = succHeight $ heightBagMax heights
2021+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
2022+ writeIORef heightRef $! height
2023+ subscriberRecalculateHeight sub height
2024+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
2025+ mySubscriber k = Subscriber
2026+ { subscriberPropagate = \a -> do
2027+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2028+ liftIO $ FastMutableIntMap.insert accum k a
2029+ when wasEmpty scheduleSelf
2030+ , subscriberInvalidateHeight = \old -> do
2031+ modifyIORef' heightBagRef $ heightBagRemove old
2032+ invalidateMyHeight
2033+ , subscriberRecalculateHeight = \new -> do
2034+ modifyIORef' heightBagRef $ heightBagAdd new
2035+ recalculateMyHeight
2036+ }
2037+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
2038+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
2039+ liftIO $ do
2040+ forM_ parentOcc $ FastMutableIntMap.insert accum k
2041+ FastMutableIntMap.insert parents k subscription
2042+ height <- getEventSubscribedHeight parentSubd
2043+ if height == invalidHeight
2044+ then writeIORef heightRef invalidHeight
2045+ else do
2046+ modifyIORef' heightBagRef $ heightBagAdd height
2047+ modifyIORef' heightRef $ \oldHeight ->
2048+ if oldHeight == invalidHeight
2049+ then invalidHeight
2050+ else max (succHeight height) oldHeight
2051+ myHeight <- liftIO $ readIORef heightRef
2052+ currentHeight <- getCurrentHeight
2053+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2054+ occ <- if currentHeight >= myHeight -- If we should have fired by now
2055+ then if isEmpty
2056+ then return Nothing
2057+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2058+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2059+ return Nothing
2060+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2061+ defer $ SomeMergeInit $ do
2062+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2063+ where
2064+ u = do
2065+ let f k newParent = do
2066+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2067+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2068+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2069+ return subscription
2070+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2071+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2072+ liftIO $ for_ oldParents $ \oldParent -> do
2073+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2074+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2075+ return $ IntMap.elems oldParents
2076+ let s = Subscriber
2077+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2078+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2079+ defer $ updateMe a
2080+ , subscriberInvalidateHeight = \_ -> return ()
2081+ , subscriberRecalculateHeight = \_ -> return ()
2082+ }
2083+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2084+ forM_ change $ \c -> defer $ updateMe c
2085+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2086+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2087+ -- its subscription.
2088+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2089+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2090+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2091+ , occ
2092+ )
2093+
2094+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2095+newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
2096+
2097+fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2098+fanG e = unsafePerformIO $ do
2099+ ref <- newIORef Nothing
2100+ let f = Fan
2101+ { fanParent = e
2102+ , fanSubscribed = ref
2103+ }
2104+ pure $ EventSelectorG $ \k -> eventFan k f
2105+
2106+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2107+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2108+ holdInits <- liftIO $ readIORef holdInitRef
2109+ dynInits <- liftIO $ readIORef dynInitRef
2110+ mergeInits <- liftIO $ readIORef mergeInitRef
2111+ unless (null holdInits && null dynInits && null mergeInits) $ do
2112+ liftIO $ writeIORef holdInitRef []
2113+ liftIO $ writeIORef dynInitRef []
2114+ liftIO $ writeIORef mergeInitRef []
2115+ mapM_ initHold holdInits
2116+ mapM_ initDyn dynInits
2117+ mapM_ unSomeMergeInit mergeInits
2118+ runHoldInits holdInitRef dynInitRef mergeInitRef
2119+
2120+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2121+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2122+
2123+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2124+initDyn (SomeDynInit d) = void $ getDynHold d
2125+
2126+newEventEnv :: IO (EventEnv x)
2127+newEventEnv = do
2128+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2129+ holdInitRef <- newIORef []
2130+ dynInitRef <- newIORef []
2131+ mergeUpdateRef <- newIORef []
2132+ mergeInitRef <- newIORef []
2133+ heightRef <- newIORef zeroHeight
2134+ toClearRef <- newIORef []
2135+ toClearIntRef <- newIORef []
2136+ toClearRootRef <- newIORef []
2137+ coincidenceInfosRef <- newIORef []
2138+ delayedRef <- newIORef IntMap.empty
2139+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2140+
2141+clearEventEnv :: EventEnv x -> IO ()
2142+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2143+ writeIORef toAssignRef []
2144+ writeIORef holdInitRef []
2145+ writeIORef dynInitRef []
2146+ writeIORef mergeUpdateRef []
2147+ writeIORef mergeInitRef []
2148+ writeIORef heightRef zeroHeight
2149+ writeIORef toClearRef []
2150+ writeIORef toClearIntRef []
2151+ writeIORef toClearRootRef []
2152+ writeIORef coincidenceInfosRef []
2153+ writeIORef delayedRef IntMap.empty
2154+
2155+-- | Run an event action outside of a frame
2156+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2157+runFrame a = SpiderHost $ do
2158+ let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
2159+ let go = do
2160+ result <- a
2161+ runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env) -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
2162+ return result
2163+ result <- runEventM go
2164+ toClear <- readIORef $ eventEnvClears env
2165+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2166+ toClearInt <- readIORef $ eventEnvIntClears env
2167+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2168+ toClearRoot <- readIORef $ eventEnvRootClears env
2169+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2170+ toAssign <- readIORef $ eventEnvAssignments env
2171+ toReconnectRef <- newIORef []
2172+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2173+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2174+ writeIORef vRef v
2175+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2176+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2177+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2178+ writeIORef (eventEnvMergeUpdates env) []
2179+ when debugPropagate $ putStrLn "Updating merges"
2180+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2181+ when debugPropagate $ putStrLn "Updating merges done"
2182+ toReconnect <- readIORef toReconnectRef
2183+ clearEventEnv env
2184+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2185+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2186+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2187+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2188+ finalize wi
2189+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2190+ wi' <- mkWeakPtrWithDebug i "wi'"
2191+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2192+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2193+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2194+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2195+ runEventM $ runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env) --TODO: Is this actually OK? It seems like it should be, since we know that no events are firing at this point, but it still seems inelegant
2196+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2197+ sub <- newSubscriberSwitch subscribed
2198+ subscription <- unSpiderHost $ runFrame $ {-# SCC "subscribeSwitch" #-} subscribe e sub --TODO: Assert that the event isn't firing --TODO: This should not loop because none of the events should be firing, but still, it is inefficient
2199+ {-
2200+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2201+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2202+ EventRoot _ -> "EventRoot"
2203+ EventNever -> "EventNever"
2204+ _ -> "something else"
2205+ -}
2206+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2207+ return oldSubscription
2208+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2209+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2210+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2211+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2212+ parentHeight <- getEventSubscribedHeight subd'
2213+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2214+ when (parentHeight /= myHeight) $ do
2215+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2216+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2217+ mapM_ _someMergeUpdate_invalidateHeight mergeUpdates --TODO: In addition to when the patch is completely empty, we should also not run this if it has some Nothing values, but none of them have actually had any effect; potentially, we could even check for Just values with no effect (e.g. by comparing their IORefs and ignoring them if they are unchanged); actually, we could just check if the new height is different
2218+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2219+ unsubscribe subscription
2220+ mapM_ invalidateCoincidenceHeight mcs
2221+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2222+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2223+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2224+ height <- calculateSwitchHeight subscribed
2225+ updateSwitchHeight height subscribed
2226+ return result
2227+
2228+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2229+
2230+{-# INLINE zeroHeight #-}
2231+zeroHeight :: Height
2232+zeroHeight = Height 0
2233+
2234+{-# INLINE invalidHeight #-}
2235+invalidHeight :: Height
2236+invalidHeight = Height (-1000)
2237+
2238+#ifdef DEBUG_CYCLES
2239+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2240+{-# INLINE invalidHeightBeingTraversed #-}
2241+invalidHeightBeingTraversed :: Height
2242+invalidHeightBeingTraversed = Height (-1001)
2243+#endif
2244+
2245+{-# INLINE succHeight #-}
2246+succHeight :: Height -> Height
2247+succHeight h@(Height a) =
2248+ if h == invalidHeight
2249+ then invalidHeight
2250+ else Height $ succ a
2251+
2252+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2253+invalidateCoincidenceHeight subscribed = do
2254+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2255+ when (oldHeight /= invalidHeight) $ do
2256+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2257+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2258+
2259+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2260+updateSwitchHeight new subscribed = do
2261+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2262+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2263+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2264+ writeIORef (switchSubscribedHeight subscribed) $! new
2265+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2266+
2267+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2268+recalculateCoincidenceHeight subscribed = do
2269+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2270+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2271+ height <- calculateCoincidenceHeight subscribed
2272+ when (height /= invalidHeight) $ do
2273+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2274+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2275+
2276+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2277+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2278+
2279+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2280+calculateCoincidenceHeight subscribed = do
2281+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2282+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2283+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2284+
2285+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2286+
2287+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2288+invalidate toReconnectRef wis = do
2289+ forM_ wis $ \wi -> do
2290+ mi <- deRefWeak wi
2291+ case mi of
2292+ Nothing -> do
2293+ traceInvalidate "invalidate Dead"
2294+ return () --TODO: Should we clean this up here?
2295+ Just i -> do
2296+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2297+ case i of
2298+ InvalidatorPull p -> do
2299+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2300+ mVal <- readIORef $ pullValue p
2301+ forM_ mVal $ \val -> do
2302+ writeIORef (pullValue p) Nothing
2303+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2304+ InvalidatorSwitch subscribed -> do
2305+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2306+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2307+ return [] -- Since we always finalize everything, always return an empty list --TODO: There are some things that will need to be re-subscribed every time; we should try to avoid finalizing them
2308+
2309+--------------------------------------------------------------------------------
2310+-- Reflex integration
2311+--------------------------------------------------------------------------------
2312+
2313+-- | Designates the default, global Spider timeline
2314+data SpiderTimeline x
2315+type role SpiderTimeline nominal
2316+
2317+-- | The default, global Spider environment
2318+type Spider = SpiderTimeline Global
2319+
2320+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2321+ {-# INLINABLE sample #-}
2322+ sample (SpiderBehavior b) = readBehaviorUntracked b
2323+
2324+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2325+ {-# INLINABLE hold #-}
2326+ hold = holdSpiderEventM
2327+ {-# INLINABLE holdDyn #-}
2328+ holdDyn = holdDynSpiderEventM
2329+ {-# INLINABLE holdIncremental #-}
2330+ holdIncremental = holdIncrementalSpiderEventM
2331+ {-# INLINABLE buildDynamic #-}
2332+ buildDynamic = buildDynamicSpiderEventM
2333+ {-# INLINABLE headE #-}
2334+ headE = R.slowHeadE
2335+-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2336+
2337+instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2338+ {-# INLINABLE sample #-}
2339+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2340+
2341+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2342+ {-# INLINABLE sample #-}
2343+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2344+
2345+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2346+ {-# INLINABLE hold #-}
2347+ hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2348+ {-# INLINABLE holdDyn #-}
2349+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2350+ {-# INLINABLE holdIncremental #-}
2351+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2352+ {-# INLINABLE buildDynamic #-}
2353+ buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2354+ {-# INLINABLE headE #-}
2355+ headE = R.slowHeadE
2356+-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2357+
2358+instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2359+ {-# INLINE return #-}
2360+ return = pure
2361+ {-# INLINE (>>=) #-}
2362+ x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2363+ {-# INLINE (>>) #-}
2364+ (>>) = (*>)
2365+#if !MIN_VERSION_base(4,13,0)
2366+ {-# INLINE fail #-}
2367+ fail _ = error "Dynamic does not support 'fail'"
2368+#endif
2369+
2370+{-# INLINABLE newJoinDyn #-}
2371+newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2372+newJoinDyn d =
2373+ let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2374+ eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2375+ eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2376+ eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2377+ v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2378+ in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2379+
2380+instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2381+ fmap = mapDynamicSpider
2382+ x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2383+
2384+mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2385+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2386+{-# INLINE [1] mapDynamicSpider #-}
2387+
2388+instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2389+ pure = SpiderDynamic . dynamicConst
2390+#if MIN_VERSION_base(4,10,0)
2391+ liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2392+#endif
2393+ SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2394+ a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2395+ (<*) = flip (*>) -- There are no effects, so order doesn't matter
2396+
2397+holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2398+holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2399+
2400+holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2401+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2402+
2403+holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2404+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2405+
2406+buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2407+buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2408+
2409+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2410+ {-# INLINABLE hold #-}
2411+ hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2412+ {-# INLINABLE holdDyn #-}
2413+ holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2414+ {-# INLINABLE holdIncremental #-}
2415+ holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2416+ {-# INLINABLE buildDynamic #-}
2417+ buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2418+ {-# INLINABLE headE #-}
2419+ headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2420+
2421+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2422+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2423+
2424+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2425+ {-# INLINABLE hold #-}
2426+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2427+ {-# INLINABLE holdDyn #-}
2428+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2429+ {-# INLINABLE holdIncremental #-}
2430+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2431+ {-# INLINABLE buildDynamic #-}
2432+ buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2433+ {-# INLINABLE headE #-}
2434+ headE = R.slowHeadE
2435+-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2436+
2437+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2438+ {-# INLINABLE sample #-}
2439+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2440+
2441+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2442+ {-# INLINABLE sample #-}
2443+ sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2444+
2445+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2446+ {-# INLINABLE hold #-}
2447+ hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2448+ {-# INLINABLE holdDyn #-}
2449+ holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2450+ {-# INLINABLE holdIncremental #-}
2451+ holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2452+ {-# INLINABLE buildDynamic #-}
2453+ buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2454+ {-# INLINABLE headE #-}
2455+ headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2456+
2457+--------------------------------------------------------------------------------
2458+-- Deprecated items
2459+--------------------------------------------------------------------------------
2460+
2461+-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2462+{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2463+type SpiderEnv = SpiderTimeline
2464+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2465+ {-# INLINABLE subscribeEvent #-}
2466+ subscribeEvent e = SpiderHostFrame $ do
2467+ --TODO: Unsubscribe eventually (manually and/or with weak ref)
2468+ val <- liftIO $ newIORef Nothing
2469+ subscription <- subscribe (unSpiderEvent e) $ Subscriber
2470+ { subscriberPropagate = \a -> do
2471+ liftIO $ writeIORef val $ Just a
2472+ scheduleClear val
2473+ , subscriberInvalidateHeight = \_ -> return ()
2474+ , subscriberRecalculateHeight = \_ -> return ()
2475+ }
2476+ return $ SpiderEventHandle
2477+ { spiderEventHandleSubscription = subscription
2478+ , spiderEventHandleValue = val
2479+ }
2480+
2481+instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2482+ type EventTrigger (SpiderTimeline x) = RootTrigger x
2483+ type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2484+ type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2485+
2486+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2487+ {-# NOINLINE readEvent #-}
2488+ readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2489+ result <- readIORef $ spiderEventHandleValue h
2490+ touch h
2491+ return result
2492+
2493+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2494+ newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2495+ newFanEventWithTrigger f = SpiderHost $ do
2496+ es <- newFanEventWithTriggerIO f
2497+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2498+
2499+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2500+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2501+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2502+ es <- newFanEventWithTriggerIO f
2503+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2504+
2505+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2506+ {-# INLINABLE subscribeEvent #-}
2507+ subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2508+
2509+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2510+ type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2511+ fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2512+ runHostFrame = runFrame . runSpiderHostFrame
2513+
2514+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2515+unsafeNewSpiderTimelineEnv = do
2516+ lock <- newMVar ()
2517+ env <- newEventEnv
2518+#ifdef DEBUG
2519+ depthRef <- newIORef 0
2520+#endif
2521+ return $ STE $ SpiderTimelineEnv
2522+ { _spiderTimeline_lock = lock
2523+ , _spiderTimeline_eventEnv = env
2524+#ifdef DEBUG
2525+ , _spiderTimeline_depth = depthRef
2526+#endif
2527+ }
2528+
2529+-- | Create a new SpiderTimelineEnv
2530+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2531+newSpiderTimeline = withSpiderTimeline (pure . Some)
2532+
2533+data LocalSpiderTimeline (x :: Type) s
2534+
2535+instance Reifies s (SpiderTimelineEnv x) =>
2536+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2537+ spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)
2538+
2539+localSpiderTimeline
2540+ :: proxy s
2541+ -> SpiderTimelineEnv x
2542+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2543+localSpiderTimeline _ = coerce
2544+
2545+-- | Pass a new timeline to the given function.
2546+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2547+withSpiderTimeline k = do
2548+ env <- unsafeNewSpiderTimelineEnv
2549+ reify env $ \s -> k $ localSpiderTimeline s env
2550+
2551+newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2552+
2553+type ComputeM = EventM
2554+
2555+newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2556+
2557+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2558+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2559+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2560+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2561+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: DynamicS x (Identity a) } -- deriving (Functor, Applicative, Monad)
2562+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: DynamicS x p }
2563+ type PullM (SpiderTimeline x) = SpiderPullM x
2564+ type PushM (SpiderTimeline x) = SpiderPushM x
2565+ {-# INLINABLE never #-}
2566+ never = SpiderEvent eventNever
2567+ {-# INLINABLE constant #-}
2568+ constant = SpiderBehavior . behaviorConst
2569+ {-# INLINE push #-}
2570+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2571+ {-# INLINE pushCheap #-}
2572+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2573+ {-# INLINABLE pull #-}
2574+ pull = SpiderBehavior . pull . coerce
2575+ {-# INLINABLE fanG #-}
2576+ fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2577+ {-# INLINABLE mergeG #-}
2578+ mergeG
2579+ :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2580+ => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2581+ -> DMap k q
2582+ -> R.Event (SpiderTimeline x) (DMap k v)
2583+ mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2584+ {-# INLINABLE switch #-}
2585+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2586+ {-# INLINABLE coincidence #-}
2587+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2588+ {-# INLINABLE current #-}
2589+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2590+ {-# INLINABLE updated #-}
2591+ updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic
2592+ {-# INLINABLE unsafeBuildDynamic #-}
2593+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2594+ {-# INLINABLE unsafeBuildIncremental #-}
2595+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2596+ {-# INLINABLE mergeIncrementalG #-}
2597+ mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2598+ {-# INLINABLE mergeIncrementalWithMoveG #-}
2599+ mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2600+ {-# INLINABLE currentIncremental #-}
2601+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2602+ {-# INLINABLE updatedIncremental #-}
2603+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2604+ {-# INLINABLE incrementalToDynamic #-}
2605+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2606+ c <- readBehaviorUntracked $ dynamicCurrent i
2607+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2608+ eventCoercion Coercion = Coercion
2609+ behaviorCoercion Coercion = Coercion
2610+ dynamicCoercion Coercion = Coercion
2611+ incrementalCoercion Coercion Coercion = Coercion
2612+ {-# INLINABLE mergeIntIncremental #-}
2613+ mergeIntIncremental = SpiderEvent . mergeInt . coerce
2614+ {-# INLINABLE fanInt #-}
2615+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2616+
2617+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2618+
2619+data SpiderEventHandle x a = SpiderEventHandle
2620+ { spiderEventHandleSubscription :: EventSubscription x
2621+ , spiderEventHandleValue :: IORef (Maybe a)
2622+ }
2623+
2624+instance MonadRef (EventM x) where
2625+ type Ref (EventM x) = Ref IO
2626+ {-# INLINABLE newRef #-}
2627+ {-# INLINABLE readRef #-}
2628+ {-# INLINABLE writeRef #-}
2629+ newRef = liftIO . newRef
2630+ readRef = liftIO . readRef
2631+ writeRef r a = liftIO $ writeRef r a
2632+
2633+instance MonadAtomicRef (EventM x) where
2634+ {-# INLINABLE atomicModifyRef #-}
2635+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2636+
2637+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2638+newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2639+
2640+instance Monad (SpiderHost x) where
2641+ {-# INLINABLE (>>=) #-}
2642+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2643+ {-# INLINABLE (>>) #-}
2644+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2645+ {-# INLINABLE return #-}
2646+ return x = SpiderHost $ return x
2647+#if !MIN_VERSION_base(4,13,0)
2648+ {-# INLINABLE fail #-}
2649+ fail = MonadFail.fail
2650+#endif
2651+
2652+instance MonadFail (SpiderHost x) where
2653+ {-# INLINABLE fail #-}
2654+ fail s = SpiderHost $ MonadFail.fail s
2655+
2656+-- | Run an action affecting the global Spider timeline; this will be guarded by
2657+-- a mutex for that timeline
2658+runSpiderHost :: SpiderHost Global a -> IO a
2659+runSpiderHost (SpiderHost a) = a
2660+
2661+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2662+-- mutex for that timeline
2663+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2664+runSpiderHostForTimeline (SpiderHost a) _ = a
2665+
2666+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2667+ deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2668+
2669+instance Monad (SpiderHostFrame x) where
2670+ {-# INLINABLE (>>=) #-}
2671+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2672+ {-# INLINABLE (>>) #-}
2673+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2674+ {-# INLINABLE return #-}
2675+ return x = SpiderHostFrame $ return x
2676+#if !MIN_VERSION_base(4,13,0)
2677+ {-# INLINABLE fail #-}
2678+ fail s = SpiderHostFrame $ fail s
2679+#endif
2680+
2681+instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2682+ notReadyUntil _ = pure ()
2683+ notReady = pure ()
2684+
2685+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2686+newEventWithTriggerIO f = do
2687+ es <- newFanEventWithTriggerIO $ \Refl -> f
2688+ return $ select es Refl
2689+
2690+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2691+newFanEventWithTriggerIO f = do
2692+ occRef <- newIORef DMap.empty
2693+ subscribedRef <- newIORef DMap.empty
2694+ let !r = Root
2695+ { rootOccurrence = occRef
2696+ , rootSubscribed = subscribedRef
2697+ , rootInit = f
2698+ }
2699+ return $ EventSelector $ \k -> eventRoot k r
2700+
2701+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2702+
2703+instance MonadRef (SpiderHost x) where
2704+ type Ref (SpiderHost x) = Ref IO
2705+ newRef = SpiderHost . newRef
2706+ readRef = SpiderHost . readRef
2707+ writeRef r = SpiderHost . writeRef r
2708+
2709+instance MonadAtomicRef (SpiderHost x) where
2710+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2711+
2712+instance MonadRef (SpiderHostFrame x) where
2713+ type Ref (SpiderHostFrame x) = Ref IO
2714+ newRef = SpiderHostFrame . newRef
2715+ readRef = SpiderHostFrame . readRef
2716+ writeRef r = SpiderHostFrame . writeRef r
2717+
2718+instance MonadAtomicRef (SpiderHostFrame x) where
2719+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2720+
2721+instance PrimMonad (SpiderHostFrame x) where
2722+ type PrimState (SpiderHostFrame x) = PrimState IO
2723+ primitive = SpiderHostFrame . EventM . primitive
2724+
2725+instance NotReady (SpiderTimeline x) (SpiderHost x) where
2726+ notReadyUntil _ = return ()
2727+ notReady = return ()
2728+
2729+instance HasSpiderTimeline x => NotReady (SpiderTimeline x) (PerformEventT (SpiderTimeline x) (SpiderHost x)) where
2730+ notReadyUntil _ = return ()
2731+ notReady = return ()