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