@@ -0,0 +1,2638 @@
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)
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+instance HasSpiderTimeline x => Align (Event x) where
1135+ nil = eventNever
1136+ align ea eb = mapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1137+
1138+data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1139+ | BuildDyn !(EventM x (PatchTarget p), Event x p)
1140+ | HoldDyn !(Hold x p)
1141+
1142+newtype Dyn x p = Dyn { unDyn :: IORef (DynType x p) }
1143+
1144+newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1145+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1146+
1147+--TODO: Avoid the duplication between this and R.zipDynWith
1148+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1149+zipDynWith f da db =
1150+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1151+ ec = flip push eab $ \o -> do
1152+ (a, b) <- case o of
1153+ This (Identity a) -> do
1154+ b <- readBehaviorUntracked $ dynamicCurrent db
1155+ return (a, b)
1156+ That (Identity b) -> do
1157+ a <- readBehaviorUntracked $ dynamicCurrent da
1158+ return (a, b)
1159+ These (Identity a) (Identity b) -> return (a, b)
1160+ return $ Just $ Identity $ f a b
1161+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1162+
1163+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1164+buildDynamic readV0 v' = do
1165+ result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1166+ let !d = Dyn result
1167+ defer $ SomeDynInit d
1168+ return d
1169+
1170+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1171+unsafeBuildDynamic readV0 v' = Dyn $ unsafeNewIORef x $ UnsafeDyn x
1172+ where x = (readV0, v')
1173+
1174+-- ResultM can read behaviors and events
1175+type ResultM = EventM
1176+
1177+{-# NOINLINE unsafeNewIORef #-}
1178+unsafeNewIORef :: a -> b -> IORef b
1179+unsafeNewIORef a b = unsafePerformIO $ do
1180+ touch a
1181+ newIORef b
1182+
1183+instance HasSpiderTimeline x => Functor (Event x) where
1184+ fmap f = push $ return . Just . f
1185+
1186+instance Functor (Behavior x) where
1187+ fmap f = pull . fmap f . readBehaviorTracked
1188+
1189+{-# INLINE push #-}
1190+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1191+push f e = cacheEvent (pushCheap f e)
1192+
1193+{-# INLINABLE pull #-}
1194+pull :: BehaviorM x a -> Behavior x a
1195+pull a = behaviorPull $ Pull
1196+ { pullCompute = a
1197+ , pullValue = unsafeNewIORef a Nothing
1198+#ifdef DEBUG_NODEIDS
1199+ , pullNodeId = unsafeNodeId a
1200+#endif
1201+ }
1202+
1203+{-# INLINABLE switch #-}
1204+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1205+switch a = eventSwitch $ Switch
1206+ { switchParent = a
1207+ , switchSubscribed = unsafeNewIORef a Nothing
1208+ }
1209+
1210+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1211+coincidence a = eventCoincidence $ Coincidence
1212+ { coincidenceParent = a
1213+ , coincidenceSubscribed = unsafeNewIORef a Nothing
1214+ }
1215+
1216+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1217+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1218+run roots after = do
1219+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1220+ let t = spiderTimeline :: SpiderTimelineEnv x
1221+ result <- SpiderHost $ withMVar (_spiderTimeline_lock t) $ \_ -> unSpiderHost $ runFrame $ do
1222+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1223+ occBefore <- liftIO $ do
1224+ occBefore <- readIORef occRef
1225+ writeIORef occRef $! DMap.insert k a occBefore
1226+ return occBefore
1227+ if DMap.null occBefore
1228+ then do scheduleRootClear occRef
1229+ return $ Just r
1230+ else return Nothing
1231+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1232+ propagate a subscribersRef
1233+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1234+ let go = do
1235+ delayed <- liftIO $ readIORef delayedRef
1236+ case IntMap.minViewWithKey delayed of
1237+ Nothing -> return ()
1238+ Just ((currentHeight, cur), future) -> do
1239+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1240+ putCurrentHeight $ Height currentHeight
1241+ liftIO $ writeIORef delayedRef $! future
1242+ sequence_ cur
1243+ go
1244+ go
1245+ putCurrentHeight maxBound
1246+ after
1247+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1248+ return result
1249+
1250+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1251+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1252+ height <- liftIO $ readIORef heightRef
1253+ currentHeight <- getCurrentHeight
1254+ case height `compare` currentHeight of
1255+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1256+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1257+ EQ -> a
1258+
1259+data SomeClear = forall a. SomeClear {-# UNPACK #-} !(IORef (Maybe a))
1260+
1261+data SomeIntClear = forall a. SomeIntClear {-# UNPACK #-} !(IORef (IntMap a))
1262+
1263+data SomeRootClear = forall k. SomeRootClear {-# UNPACK #-} !(IORef (DMap k Identity))
1264+
1265+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1266+
1267+debugFinalize :: Bool
1268+debugFinalize = False
1269+
1270+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1271+mkWeakPtrWithDebug x debugNote = do
1272+ x' <- evaluate x
1273+ mkWeakPtr x' $
1274+ if debugFinalize
1275+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1276+ else Nothing
1277+
1278+type WeakList a = [Weak a]
1279+
1280+{-# INLINE withIncreasedDepth #-}
1281+#ifdef DEBUG
1282+withIncreasedDepth :: CanTrace x m => m a -> m a
1283+withIncreasedDepth a = do
1284+ spiderTimeline <- askSpiderTimelineEnv
1285+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1286+ result <- a
1287+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1288+ return result
1289+#else
1290+withIncreasedDepth :: m a -> m a
1291+withIncreasedDepth = id
1292+#endif
1293+
1294+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1295+
1296+{-# INLINE tracePropagate #-}
1297+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1298+tracePropagate p = traceWhen p debugPropagate
1299+
1300+{-# INLINE traceInvalidate #-}
1301+traceInvalidate :: String -> IO ()
1302+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1303+
1304+{-# INLINE traceWhen #-}
1305+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1306+traceWhen p b message = traceMWhen p b $ return message
1307+
1308+{-# INLINE traceMWhen #-}
1309+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1310+traceMWhen _ b getMessage = when b $ do
1311+ message <- getMessage
1312+#ifdef DEBUG
1313+ spiderTimeline <- askSpiderTimelineEnv
1314+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1315+#else
1316+ let d = 0
1317+#endif
1318+ liftIO $ putStrLn $ replicate d ' ' <> message
1319+
1320+whoCreatedIORef :: IORef a -> IO [String]
1321+whoCreatedIORef (IORef a) = whoCreated $! a
1322+
1323+#ifdef DEBUG_CYCLES
1324+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1325+groupByHead = \case
1326+ [] -> []
1327+ (x :| xs) : t -> case groupByHead t of
1328+ [] -> [(x, xs :| [])]
1329+ l@((y, yss) : t')
1330+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1331+ | otherwise -> (x, xs :| []) : l
1332+
1333+listsToForest :: Eq a => [[a]] -> Forest a
1334+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1335+#endif
1336+
1337+{-# INLINE propagateSubscriberHold #-}
1338+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1339+propagateSubscriberHold h a = do
1340+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1341+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1342+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1343+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1344+ case {-# SCC "apply" #-} apply a v of
1345+ Nothing -> return ()
1346+ Just v' -> do
1347+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1348+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1349+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1350+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1351+
1352+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1353+
1354+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1355+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1356+
1357+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1358+askInvalidator = do
1359+ (!m, _) <- BehaviorM ask
1360+ case m of
1361+ Nothing -> return Nothing
1362+ Just (!wi, _) -> return $ Just wi
1363+
1364+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1365+askParentsRef = do
1366+ (!m, _) <- BehaviorM ask
1367+ case m of
1368+ Nothing -> return Nothing
1369+ Just (_, !p) -> return $ Just p
1370+
1371+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1372+askBehaviorHoldInits = do
1373+ (_, !his) <- BehaviorM ask
1374+ return his
1375+
1376+{-# INLINE getDynHold #-}
1377+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1378+getDynHold d = do
1379+ mh <- liftIO $ readIORef $ unDyn d
1380+ case mh of
1381+ HoldDyn h -> return h
1382+ UnsafeDyn (readV0, v') -> do
1383+ holdInits <- getDeferralQueue
1384+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1385+ hold' v0 v'
1386+ BuildDyn (readV0, v') -> do
1387+ v0 <- liftIO $ runEventM readV0
1388+ hold' v0 v'
1389+ where
1390+ hold' v0 v' = do
1391+ h <- hold v0 v'
1392+ liftIO $ writeIORef (unDyn d) $ HoldDyn h
1393+ return h
1394+
1395+
1396+-- Always refers to 0
1397+{-# NOINLINE zeroRef #-}
1398+zeroRef :: IORef Height
1399+zeroRef = unsafePerformIO $ newIORef zeroHeight
1400+
1401+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1402+getRootSubscribed k r sub = do
1403+ mSubscribed <- readIORef $ rootSubscribed r
1404+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1405+ case DMap.lookup k mSubscribed of
1406+ Just subscribed -> {-# SCC "hitRoot" #-} do
1407+ sln <- subscribeRootSubscribed subscribed sub
1408+ occ <- getOcc
1409+ return (sln, subscribed, occ)
1410+ Nothing -> {-# SCC "missRoot" #-} do
1411+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1412+ let !cached = rootSubscribed r
1413+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1414+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1415+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1416+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1417+ writeIORef uninitRef $! uninit
1418+ let !subscribed = RootSubscribed
1419+ { rootSubscribedKey = k
1420+ , rootSubscribedCachedSubscribed = cached
1421+ , rootSubscribedOccurrence = getOcc
1422+ , rootSubscribedSubscribers = subs
1423+ , rootSubscribedUninit = uninit
1424+ , rootSubscribedWeakSelf = weakSelf
1425+#ifdef DEBUG_NODEIDS
1426+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1427+#endif
1428+ }
1429+ -- If we die at the same moment that all our children die, they will
1430+ -- try to clean us up but will fail because their Weak reference to us
1431+ -- will also be dead. So, if we are dying, check if there are any
1432+ -- children; since children don't bother cleaning themselves up if
1433+ -- their parents are already dead, I don't think there's a race
1434+ -- condition here. However, if there are any children, then we can
1435+ -- infer that we need to clean ourselves up, so we do.
1436+ finalCleanup = do
1437+ cs <- readIORef $ _weakBag_children subs
1438+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1439+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1440+ 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
1441+ occ <- getOcc
1442+ return (sln, subscribed, occ)
1443+
1444+#ifdef USE_TEMPLATE_HASKELL
1445+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1446+#endif
1447+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1448+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1449+ rootSubscribedUninit self
1450+ modifyIORef' cached $ DMap.delete k
1451+
1452+{-# INLINE subscribeRootSubscribed #-}
1453+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1454+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1455+
1456+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1457+
1458+data FanInt x a = FanInt
1459+ { _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
1460+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1461+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1462+ }
1463+
1464+newFanInt :: IO (FanInt x a)
1465+newFanInt = do
1466+ 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
1467+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1468+ occRef <- newIORef $ error "fanInt: no occurrence"
1469+ return $ FanInt
1470+ { _fanInt_subscribers = subscribers
1471+ , _fanInt_subscriptionRef = subscriptionRef
1472+ , _fanInt_occRef = occRef
1473+ }
1474+
1475+{-# NOINLINE unsafeNewFanInt #-}
1476+unsafeNewFanInt :: b -> FanInt x a
1477+unsafeNewFanInt b = unsafePerformIO $ do
1478+ touch b
1479+ newFanInt
1480+
1481+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1482+fanInt p =
1483+ let self = unsafeNewFanInt p
1484+ in EventSelectorInt $ \k -> Event $ \sub -> do
1485+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1486+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1487+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1488+ { subscriberPropagate = \m -> do
1489+ liftIO $ writeIORef (_fanInt_occRef self) m
1490+ scheduleIntClear $ _fanInt_occRef self
1491+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1492+ FastWeakBag.traverse b $ \s -> do
1493+ subscriberPropagate s v
1494+ , subscriberInvalidateHeight = \old -> do
1495+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1496+ FastWeakBag.traverse b $ \s -> do
1497+ subscriberInvalidateHeight s old
1498+ , subscriberRecalculateHeight = \new -> do
1499+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1500+ FastWeakBag.traverse b $ \s -> do
1501+ subscriberRecalculateHeight s new
1502+ }
1503+ liftIO $ do
1504+ writeIORef (_fanInt_subscriptionRef self) subscription
1505+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1506+ scheduleIntClear $ _fanInt_occRef self
1507+ liftIO $ do
1508+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1509+ Nothing -> do
1510+ b <- FastWeakBag.empty
1511+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1512+ return b
1513+ Just b -> return b
1514+ t <- liftIO $ FastWeakBag.insert sub b
1515+ currentOcc <- readIORef (_fanInt_occRef self)
1516+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1517+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1518+
1519+{-# INLINABLE getFanSubscribed #-}
1520+getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket, FanSubscribed x k, Maybe a)
1521+getFanSubscribed k f sub = do
1522+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1523+ case mSubscribed of
1524+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1525+ sln <- subscribeFanSubscribed k subscribed sub
1526+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1527+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1528+ Nothing -> {-# SCC "missFan" #-} do
1529+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1530+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1531+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1532+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1533+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1534+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1535+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1536+ occRef <- liftIO $ newIORef parentOcc
1537+ when (isJust parentOcc) $ scheduleClear occRef
1538+ let subscribed = FanSubscribed
1539+ { fanSubscribedCachedSubscribed = fanSubscribed f
1540+ , fanSubscribedOccurrence = occRef
1541+ , fanSubscribedParent = subscription
1542+ , fanSubscribedSubscribers = subscribersRef
1543+#ifdef DEBUG_NODEIDS
1544+ , fanSubscribedNodeId = unsafeNodeId f
1545+#endif
1546+ }
1547+ let !self = (k, subscribed)
1548+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1549+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1550+ liftIO $ writeIORef subscribedRef $! subscribed
1551+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1552+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1553+
1554+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1555+cleanupFanSubscribed (k, subscribed) = do
1556+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1557+ let reducedSubscribers = DMap.delete k subscribers
1558+ if DMap.null reducedSubscribers
1559+ then do
1560+ unsubscribe $ fanSubscribedParent subscribed
1561+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1562+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1563+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1564+
1565+{-# INLINE subscribeFanSubscribed #-}
1566+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1567+subscribeFanSubscribed k subscribed sub = do
1568+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1569+ case DMap.lookup k subscribers of
1570+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1571+ let !self = (k, subscribed)
1572+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1573+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1574+ 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
1575+ return sln
1576+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1577+
1578+{-# INLINABLE getSwitchSubscribed #-}
1579+getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1580+getSwitchSubscribed s sub = do
1581+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1582+ case mSubscribed of
1583+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1584+ sln <- subscribeSwitchSubscribed subscribed sub
1585+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1586+ return (sln, subscribed, occ)
1587+ Nothing -> {-# SCC "missSwitch" #-} do
1588+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1589+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1590+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1591+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1592+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1593+ wiRef <- liftIO $ newIORef wi
1594+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1595+ holdInits <- getDeferralQueue
1596+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1597+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1598+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1599+ subscriptionRef <- liftIO $ newIORef subscription
1600+ occRef <- liftIO $ newIORef parentOcc
1601+ when (isJust parentOcc) $ scheduleClear occRef
1602+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1603+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1604+ let !subscribed = SwitchSubscribed
1605+ { switchSubscribedCachedSubscribed = switchSubscribed s
1606+ , switchSubscribedOccurrence = occRef
1607+ , switchSubscribedHeight = heightRef
1608+ , switchSubscribedSubscribers = subs
1609+ , switchSubscribedOwnInvalidator = i
1610+ , switchSubscribedOwnWeakInvalidator = wiRef
1611+ , switchSubscribedBehaviorParents = parentsRef
1612+ , switchSubscribedParent = switchParent s
1613+ , switchSubscribedCurrentParent = subscriptionRef
1614+ , switchSubscribedWeakSelf = weakSelf
1615+#ifdef DEBUG_NODEIDS
1616+ , switchSubscribedNodeId = unsafeNodeId s
1617+#endif
1618+ }
1619+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1620+ liftIO $ writeIORef subscribedRef $! subscribed
1621+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1622+ return (slnForSub, subscribed, parentOcc)
1623+
1624+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1625+cleanupSwitchSubscribed subscribed = do
1626+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1627+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1628+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1629+
1630+{-# INLINE subscribeSwitchSubscribed #-}
1631+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1632+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1633+
1634+{-# INLINABLE getCoincidenceSubscribed #-}
1635+getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1636+getCoincidenceSubscribed c sub = do
1637+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1638+ case mSubscribed of
1639+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1640+ sln <- subscribeCoincidenceSubscribed subscribed sub
1641+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1642+ return (sln, subscribed, occ)
1643+ Nothing -> {-# SCC "missCoincidence" #-} do
1644+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1645+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1646+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1647+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1648+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1649+ (occ, height, mInnerSubd) <- case outerOcc of
1650+ Nothing -> return (Nothing, outerHeight, Nothing)
1651+ Just o -> do
1652+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1653+ return (occ, height, Just innerSubd)
1654+ occRef <- liftIO $ newIORef occ
1655+ when (isJust occ) $ scheduleClear occRef
1656+ heightRef <- liftIO $ newIORef height
1657+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1658+ scheduleClear innerSubdRef
1659+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1660+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1661+ let subscribed = CoincidenceSubscribed
1662+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1663+ , coincidenceSubscribedOccurrence = occRef
1664+ , coincidenceSubscribedHeight = heightRef
1665+ , coincidenceSubscribedSubscribers = subs
1666+ , coincidenceSubscribedOuter = subOuter
1667+ , coincidenceSubscribedOuterParent = outerSubscription
1668+ , coincidenceSubscribedInnerParent = innerSubdRef
1669+ , coincidenceSubscribedWeakSelf = weakSelf
1670+#ifdef DEBUG_NODEIDS
1671+ , coincidenceSubscribedNodeId = unsafeNodeId c
1672+#endif
1673+ }
1674+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1675+ liftIO $ writeIORef subscribedRef $! subscribed
1676+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1677+ return (slnForSub, subscribed, occ)
1678+
1679+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1680+cleanupCoincidenceSubscribed subscribed = do
1681+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1682+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1683+
1684+{-# INLINE subscribeCoincidenceSubscribed #-}
1685+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1686+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1687+
1688+{-# INLINE merge #-}
1689+merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1690+merge d = cacheEvent (mergeCheap d)
1691+
1692+{-# INLINE mergeWithMove #-}
1693+mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1694+mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1695+
1696+{-# INLINE [1] mergeCheap #-}
1697+mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1698+mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
1699+ where
1700+ updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1701+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1702+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1703+ (mOldSubd, newPs) <- case me of
1704+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1705+ Just e -> do
1706+ let s = subscriber $ return k
1707+ subscription@(EventSubscription _ subd) <- subscribe e s
1708+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1709+ let newParent = MergeSubscribedParent subscription
1710+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1711+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1712+ forM_ mOldSubd $ \oldSubd -> do
1713+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1714+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1715+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1716+ foldM f ([], oldParents) $ DMap.toList p
1717+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1718+ getInitialSubscribers initialParents subscriber = do
1719+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1720+ let s = subscriber $ return k
1721+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1722+ height <- liftIO $ getEventSubscribedHeight parentSubd
1723+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1724+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1725+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1726+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1727+ )
1728+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1729+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1730+
1731+{-# INLINE [1] mergeCheapWithMove #-}
1732+mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1733+mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
1734+ where
1735+ updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1736+ updateMe subscriber heightBagRef oldParents p = do
1737+ -- Prepare new parents for insertion
1738+ let subscribeParent :: forall a. k a -> Event x a -> EventM x (MergeSubscribedParentWithMove x k a)
1739+ subscribeParent k e = do
1740+ keyRef <- liftIO $ newIORef k
1741+ let s = subscriber $ liftIO $ readIORef keyRef
1742+ subscription@(EventSubscription _ subd) <- subscribe e s
1743+ liftIO $ do
1744+ newParentHeight <- getEventSubscribedHeight subd
1745+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1746+ return $ MergeSubscribedParentWithMove subscription keyRef
1747+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1748+ -- Collect old parents for deletion and update the keys of moved parents
1749+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Event x) a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1750+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1751+ Nothing -> do
1752+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1753+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1754+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1755+ Just toKey -> do
1756+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1757+ return Nothing
1758+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1759+ return (toDelete, applyAlways p' oldParents)
1760+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1761+ getInitialSubscribers initialParents subscriber = do
1762+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1763+ keyRef <- liftIO $ newIORef k
1764+ let s = subscriber $ liftIO $ readIORef keyRef
1765+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1766+ height <- liftIO $ getEventSubscribedHeight parentSubd
1767+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1768+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1769+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1770+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1771+ )
1772+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1773+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1774+
1775+type MergeUpdateFunc k x p s
1776+ = (forall a. EventM x (k a) -> Subscriber x a)
1777+ -> IORef HeightBag
1778+ -> DMap k s
1779+ -> p
1780+ -> EventM x ([EventSubscription x], DMap k s)
1781+
1782+type MergeInitFunc k x s
1783+ = DMap k (Event x)
1784+ -> (forall a. EventM x (k a) -> Subscriber x a)
1785+ -> EventM x (DMap k Identity, [Height], DMap k s)
1786+
1787+type MergeDestroyFunc k s
1788+ = DMap k s
1789+ -> IO ()
1790+
1791+data Merge x k s = Merge
1792+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1793+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1794+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1795+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k Identity))
1796+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k Identity))
1797+ }
1798+
1799+invalidateMergeHeight :: Merge x k s -> IO ()
1800+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1801+
1802+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1803+invalidateMergeHeight' heightRef sub = do
1804+ oldHeight <- readIORef heightRef
1805+ 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
1806+ writeIORef heightRef $! invalidHeight
1807+ subscriberInvalidateHeight sub oldHeight
1808+
1809+
1810+revalidateMergeHeight :: Merge x k s -> IO ()
1811+revalidateMergeHeight m = do
1812+ currentHeight <- readIORef $ _merge_heightRef m
1813+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1814+ heights <- readIORef $ _merge_heightBagRef m
1815+ parents <- readIORef $ _merge_parentsRef m
1816+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1817+ case heightBagSize heights `compare` DMap.size parents of
1818+ LT -> return ()
1819+ EQ -> do
1820+ let height = succHeight $ heightBagMax heights
1821+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1822+ writeIORef (_merge_heightRef m) $! height
1823+ subscriberRecalculateHeight (_merge_sub m) height
1824+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1825+
1826+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k s -> Height -> EventM x ()
1827+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1828+ vals <- liftIO $ readIORef $ _merge_accumRef m
1829+ 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
1830+ --TODO: Assert that m is not empty
1831+ subscriberPropagate (_merge_sub m) vals
1832+
1833+mergeSubscriber :: forall x k s a. (HasSpiderTimeline x, GCompare k) => Merge x k s -> EventM x (k a) -> Subscriber x a
1834+mergeSubscriber m getKey = Subscriber
1835+ { subscriberPropagate = \a -> do
1836+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1837+ k <- getKey
1838+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1839+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1840+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1841+ when (DMap.null oldM) $ do -- Only schedule the firing once
1842+ height <- liftIO $ readIORef $ _merge_heightRef m
1843+ --TODO: assertions about height
1844+ currentHeight <- getCurrentHeight
1845+ when (height <= currentHeight) $ do
1846+ if height /= invalidHeight
1847+ then do
1848+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1849+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1850+ else liftIO $ do
1851+#ifdef DEBUG_CYCLES
1852+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1853+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1854+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1855+#else
1856+ let cycleInfo = ""
1857+#endif
1858+ error $ "Causality loop found" <> cycleInfo
1859+ scheduleMergeSelf m height
1860+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1861+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1862+ invalidateMergeHeight m
1863+ , subscriberRecalculateHeight = \new -> do
1864+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1865+ revalidateMergeHeight m
1866+ }
1867+
1868+--TODO: Be able to run as much of this as possible promptly
1869+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k s -> MergeUpdateFunc k x p s -> p -> SomeMergeUpdate x
1870+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1871+ where updateMe = do
1872+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1873+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1874+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1875+ return subscriptionsToKill
1876+
1877+{-# INLINE mergeCheap' #-}
1878+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)
1879+mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1880+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1881+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1882+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1883+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1884+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1885+ let m = Merge
1886+ { _merge_parentsRef = parentsRef
1887+ , _merge_heightBagRef = heightBagRef
1888+ , _merge_heightRef = heightRef
1889+ , _merge_sub = sub
1890+ , _merge_accumRef = accumRef
1891+ }
1892+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1893+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1894+ myHeight = if invalidHeight `elem` heights
1895+ then invalidHeight
1896+ else succHeight $ heightBagMax myHeightBag
1897+ currentHeight <- getCurrentHeight
1898+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1899+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1900+ else (Nothing, dm)
1901+ unless (DMap.null accum) $ do
1902+ scheduleMergeSelf m myHeight
1903+ liftIO $ writeIORef accumRef $! accum
1904+ liftIO $ writeIORef heightRef $! myHeight
1905+ liftIO $ writeIORef heightBagRef $! myHeightBag
1906+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1907+ liftIO $ writeIORef parentsRef $! initialParentState
1908+ defer $ SomeMergeInit $ do
1909+ let s = Subscriber
1910+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1911+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1912+ defer $ updateMerge m updateFunc a
1913+ , subscriberInvalidateHeight = \_ -> return ()
1914+ , subscriberRecalculateHeight = \_ -> return ()
1915+ }
1916+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1917+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1918+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1919+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1920+ -- its subscription.
1921+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1922+ let unsubscribeAll = destroy =<< readIORef parentsRef
1923+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1924+ , occ
1925+ )
1926+
1927+mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1928+mergeInt = cacheEvent . mergeIntCheap
1929+
1930+{-# INLINABLE mergeIntCheap #-}
1931+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1932+mergeIntCheap d = Event $ \sub -> do
1933+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1934+ accum <- liftIO $ FastMutableIntMap.newEmpty
1935+ heightRef <- liftIO $ newIORef zeroHeight
1936+ heightBagRef <- liftIO $ newIORef heightBagEmpty
1937+ parents <- liftIO $ FastMutableIntMap.newEmpty
1938+ let scheduleSelf = do
1939+ height <- liftIO $ readIORef $ heightRef
1940+ scheduleMerge' height heightRef $ do
1941+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1942+ subscriberPropagate sub vals
1943+ invalidateMyHeight = do
1944+ invalidateMergeHeight' heightRef sub
1945+ recalculateMyHeight = do
1946+ currentHeight <- readIORef heightRef
1947+ 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?
1948+ heights <- readIORef heightBagRef
1949+ numParents <- FastMutableIntMap.size parents
1950+ case heightBagSize heights `compare` numParents of
1951+ LT -> return ()
1952+ EQ -> do
1953+ let height = succHeight $ heightBagMax heights
1954+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1955+ writeIORef heightRef $! height
1956+ subscriberRecalculateHeight sub height
1957+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
1958+ mySubscriber k = Subscriber
1959+ { subscriberPropagate = \a -> do
1960+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1961+ liftIO $ FastMutableIntMap.insert accum k a
1962+ when wasEmpty scheduleSelf
1963+ , subscriberInvalidateHeight = \old -> do
1964+ modifyIORef' heightBagRef $ heightBagRemove old
1965+ invalidateMyHeight
1966+ , subscriberRecalculateHeight = \new -> do
1967+ modifyIORef' heightBagRef $ heightBagAdd new
1968+ recalculateMyHeight
1969+ }
1970+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
1971+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
1972+ liftIO $ do
1973+ forM_ parentOcc $ FastMutableIntMap.insert accum k
1974+ FastMutableIntMap.insert parents k subscription
1975+ height <- getEventSubscribedHeight parentSubd
1976+ if height == invalidHeight
1977+ then writeIORef heightRef invalidHeight
1978+ else do
1979+ modifyIORef' heightBagRef $ heightBagAdd height
1980+ modifyIORef' heightRef $ \oldHeight ->
1981+ if oldHeight == invalidHeight
1982+ then invalidHeight
1983+ else max (succHeight height) oldHeight
1984+ myHeight <- liftIO $ readIORef heightRef
1985+ currentHeight <- getCurrentHeight
1986+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1987+ occ <- if currentHeight >= myHeight -- If we should have fired by now
1988+ then if isEmpty
1989+ then return Nothing
1990+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
1991+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
1992+ return Nothing
1993+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1994+ defer $ SomeMergeInit $ do
1995+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
1996+ where
1997+ u = do
1998+ let f k newParent = do
1999+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2000+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2001+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2002+ return subscription
2003+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2004+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2005+ liftIO $ for_ oldParents $ \oldParent -> do
2006+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2007+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2008+ return $ IntMap.elems oldParents
2009+ let s = Subscriber
2010+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2011+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2012+ defer $ updateMe a
2013+ , subscriberInvalidateHeight = \_ -> return ()
2014+ , subscriberRecalculateHeight = \_ -> return ()
2015+ }
2016+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2017+ forM_ change $ \c -> defer $ updateMe c
2018+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2019+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2020+ -- its subscription.
2021+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2022+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2023+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2024+ , occ
2025+ )
2026+
2027+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2028+
2029+fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
2030+fan e =
2031+ let f = Fan
2032+ { fanParent = e
2033+ , fanSubscribed = unsafeNewIORef e Nothing
2034+ }
2035+ in EventSelector $ \k -> eventFan k f
2036+
2037+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2038+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2039+ holdInits <- liftIO $ readIORef holdInitRef
2040+ dynInits <- liftIO $ readIORef dynInitRef
2041+ mergeInits <- liftIO $ readIORef mergeInitRef
2042+ unless (null holdInits && null dynInits && null mergeInits) $ do
2043+ liftIO $ writeIORef holdInitRef []
2044+ liftIO $ writeIORef dynInitRef []
2045+ liftIO $ writeIORef mergeInitRef []
2046+ mapM_ initHold holdInits
2047+ mapM_ initDyn dynInits
2048+ mapM_ unSomeMergeInit mergeInits
2049+ runHoldInits holdInitRef dynInitRef mergeInitRef
2050+
2051+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2052+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2053+
2054+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2055+initDyn (SomeDynInit d) = void $ getDynHold d
2056+
2057+newEventEnv :: IO (EventEnv x)
2058+newEventEnv = do
2059+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2060+ holdInitRef <- newIORef []
2061+ dynInitRef <- newIORef []
2062+ mergeUpdateRef <- newIORef []
2063+ mergeInitRef <- newIORef []
2064+ heightRef <- newIORef zeroHeight
2065+ toClearRef <- newIORef []
2066+ toClearIntRef <- newIORef []
2067+ toClearRootRef <- newIORef []
2068+ coincidenceInfosRef <- newIORef []
2069+ delayedRef <- newIORef IntMap.empty
2070+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2071+
2072+clearEventEnv :: EventEnv x -> IO ()
2073+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2074+ writeIORef toAssignRef []
2075+ writeIORef holdInitRef []
2076+ writeIORef dynInitRef []
2077+ writeIORef mergeUpdateRef []
2078+ writeIORef mergeInitRef []
2079+ writeIORef heightRef zeroHeight
2080+ writeIORef toClearRef []
2081+ writeIORef toClearIntRef []
2082+ writeIORef toClearRootRef []
2083+ writeIORef coincidenceInfosRef []
2084+ writeIORef delayedRef IntMap.empty
2085+
2086+-- | Run an event action outside of a frame
2087+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2088+runFrame a = SpiderHost $ do
2089+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2090+ let go = do
2091+ result <- a
2092+ 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
2093+ return result
2094+ result <- runEventM go
2095+ toClear <- readIORef $ eventEnvClears env
2096+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
2097+ toClearInt <- readIORef $ eventEnvIntClears env
2098+ forM_ toClearInt $ \(SomeIntClear ref) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2099+ toClearRoot <- readIORef $ eventEnvRootClears env
2100+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2101+ toAssign <- readIORef $ eventEnvAssignments env
2102+ toReconnectRef <- newIORef []
2103+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2104+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2105+ writeIORef vRef v
2106+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2107+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2108+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2109+ writeIORef (eventEnvMergeUpdates env) []
2110+ when debugPropagate $ putStrLn "Updating merges"
2111+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2112+ when debugPropagate $ putStrLn "Updating merges done"
2113+ toReconnect <- readIORef toReconnectRef
2114+ clearEventEnv env
2115+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2116+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2117+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2118+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2119+ finalize wi
2120+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2121+ wi' <- mkWeakPtrWithDebug i "wi'"
2122+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2123+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2124+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2125+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2126+ 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
2127+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2128+ sub <- newSubscriberSwitch subscribed
2129+ 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
2130+ {-
2131+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2132+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2133+ EventRoot _ -> "EventRoot"
2134+ EventNever -> "EventNever"
2135+ _ -> "something else"
2136+ -}
2137+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2138+ return oldSubscription
2139+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2140+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2141+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2142+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2143+ parentHeight <- getEventSubscribedHeight subd'
2144+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2145+ when (parentHeight /= myHeight) $ do
2146+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2147+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2148+ 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
2149+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2150+ unsubscribe subscription
2151+ mapM_ invalidateCoincidenceHeight mcs
2152+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2153+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2154+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2155+ height <- calculateSwitchHeight subscribed
2156+ updateSwitchHeight height subscribed
2157+ return result
2158+
2159+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2160+
2161+{-# INLINE zeroHeight #-}
2162+zeroHeight :: Height
2163+zeroHeight = Height 0
2164+
2165+{-# INLINE invalidHeight #-}
2166+invalidHeight :: Height
2167+invalidHeight = Height (-1000)
2168+
2169+#ifdef DEBUG_CYCLES
2170+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2171+{-# INLINE invalidHeightBeingTraversed #-}
2172+invalidHeightBeingTraversed :: Height
2173+invalidHeightBeingTraversed = Height (-1001)
2174+#endif
2175+
2176+{-# INLINE succHeight #-}
2177+succHeight :: Height -> Height
2178+succHeight h@(Height a) =
2179+ if h == invalidHeight
2180+ then invalidHeight
2181+ else Height $ succ a
2182+
2183+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2184+invalidateCoincidenceHeight subscribed = do
2185+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2186+ when (oldHeight /= invalidHeight) $ do
2187+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2188+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2189+
2190+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2191+updateSwitchHeight new subscribed = do
2192+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2193+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2194+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2195+ writeIORef (switchSubscribedHeight subscribed) $! new
2196+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2197+
2198+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2199+recalculateCoincidenceHeight subscribed = do
2200+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2201+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2202+ height <- calculateCoincidenceHeight subscribed
2203+ when (height /= invalidHeight) $ do
2204+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2205+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2206+
2207+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2208+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2209+
2210+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2211+calculateCoincidenceHeight subscribed = do
2212+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2213+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2214+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2215+
2216+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2217+
2218+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2219+invalidate toReconnectRef wis = do
2220+ forM_ wis $ \wi -> do
2221+ mi <- deRefWeak wi
2222+ case mi of
2223+ Nothing -> do
2224+ traceInvalidate "invalidate Dead"
2225+ return () --TODO: Should we clean this up here?
2226+ Just i -> do
2227+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2228+ case i of
2229+ InvalidatorPull p -> do
2230+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2231+ mVal <- readIORef $ pullValue p
2232+ forM_ mVal $ \val -> do
2233+ writeIORef (pullValue p) Nothing
2234+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2235+ InvalidatorSwitch subscribed -> do
2236+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2237+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2238+ 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
2239+
2240+--------------------------------------------------------------------------------
2241+-- Reflex integration
2242+--------------------------------------------------------------------------------
2243+
2244+-- | Designates the default, global Spider timeline
2245+data SpiderTimeline x
2246+type role SpiderTimeline nominal
2247+
2248+-- | The default, global Spider environment
2249+type Spider = SpiderTimeline Global
2250+
2251+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2252+ {-# INLINABLE sample #-}
2253+ sample (SpiderBehavior b) = readBehaviorUntracked b
2254+
2255+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2256+ {-# INLINABLE hold #-}
2257+ hold = holdSpiderEventM
2258+ {-# INLINABLE holdDyn #-}
2259+ holdDyn = holdDynSpiderEventM
2260+ {-# INLINABLE holdIncremental #-}
2261+ holdIncremental = holdIncrementalSpiderEventM
2262+ {-# INLINABLE buildDynamic #-}
2263+ buildDynamic = buildDynamicSpiderEventM
2264+ {-# INLINABLE headE #-}
2265+ headE = R.slowHeadE
2266+-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2267+
2268+instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2269+ {-# INLINABLE sample #-}
2270+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2271+
2272+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2273+ {-# INLINABLE sample #-}
2274+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2275+
2276+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2277+ {-# INLINABLE hold #-}
2278+ hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2279+ {-# INLINABLE holdDyn #-}
2280+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2281+ {-# INLINABLE holdIncremental #-}
2282+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2283+ {-# INLINABLE buildDynamic #-}
2284+ buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2285+ {-# INLINABLE headE #-}
2286+ headE = R.slowHeadE
2287+-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2288+
2289+instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2290+ {-# INLINE return #-}
2291+ return = pure
2292+ {-# INLINE (>>=) #-}
2293+ x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2294+ {-# INLINE (>>) #-}
2295+ (>>) = (*>)
2296+ {-# INLINE fail #-}
2297+ fail _ = error "Dynamic does not support 'fail'"
2298+
2299+{-# INLINABLE newJoinDyn #-}
2300+newJoinDyn :: HasSpiderTimeline x => Reflex.Spider.Internal.Dynamic x (Identity (Reflex.Spider.Internal.Dynamic x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2301+newJoinDyn d =
2302+ let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2303+ eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2304+ eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2305+ eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2306+ v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2307+ in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2308+
2309+instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2310+ fmap = mapDynamicSpider
2311+ x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2312+
2313+mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2314+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2315+{-# INLINE [1] mapDynamicSpider #-}
2316+
2317+instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2318+ pure = SpiderDynamic . dynamicConst
2319+#if MIN_VERSION_base(4,10,0)
2320+ liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2321+#endif
2322+ SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2323+ a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2324+ (<*) = flip (*>) -- There are no effects, so order doesn't matter
2325+
2326+holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2327+holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2328+
2329+holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2330+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2331+
2332+holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2333+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2334+
2335+buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2336+buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2337+
2338+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2339+ {-# INLINABLE hold #-}
2340+ hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2341+ {-# INLINABLE holdDyn #-}
2342+ holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2343+ {-# INLINABLE holdIncremental #-}
2344+ holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2345+ {-# INLINABLE buildDynamic #-}
2346+ buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2347+ {-# INLINABLE headE #-}
2348+ headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2349+
2350+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2351+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2352+
2353+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2354+ {-# INLINABLE hold #-}
2355+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2356+ {-# INLINABLE holdDyn #-}
2357+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2358+ {-# INLINABLE holdIncremental #-}
2359+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2360+ {-# INLINABLE buildDynamic #-}
2361+ buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2362+ {-# INLINABLE headE #-}
2363+ headE = R.slowHeadE
2364+-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2365+
2366+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2367+ {-# INLINABLE sample #-}
2368+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2369+
2370+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2371+ {-# INLINABLE sample #-}
2372+ sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2373+
2374+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2375+ {-# INLINABLE hold #-}
2376+ hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2377+ {-# INLINABLE holdDyn #-}
2378+ holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2379+ {-# INLINABLE holdIncremental #-}
2380+ holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2381+ {-# INLINABLE buildDynamic #-}
2382+ buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2383+ {-# INLINABLE headE #-}
2384+ headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2385+
2386+--------------------------------------------------------------------------------
2387+-- Deprecated items
2388+--------------------------------------------------------------------------------
2389+
2390+-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2391+{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2392+type SpiderEnv = SpiderTimeline
2393+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2394+ {-# INLINABLE subscribeEvent #-}
2395+ subscribeEvent e = SpiderHostFrame $ do
2396+ --TODO: Unsubscribe eventually (manually and/or with weak ref)
2397+ val <- liftIO $ newIORef Nothing
2398+ subscription <- subscribe (unSpiderEvent e) $ Subscriber
2399+ { subscriberPropagate = \a -> do
2400+ liftIO $ writeIORef val $ Just a
2401+ scheduleClear val
2402+ , subscriberInvalidateHeight = \_ -> return ()
2403+ , subscriberRecalculateHeight = \_ -> return ()
2404+ }
2405+ return $ SpiderEventHandle
2406+ { spiderEventHandleSubscription = subscription
2407+ , spiderEventHandleValue = val
2408+ }
2409+
2410+instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2411+ type EventTrigger (SpiderTimeline x) = RootTrigger x
2412+ type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2413+ type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2414+
2415+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2416+ {-# NOINLINE readEvent #-}
2417+ readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2418+ result <- readIORef $ spiderEventHandleValue h
2419+ touch h
2420+ return result
2421+
2422+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2423+ newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2424+ newFanEventWithTrigger f = SpiderHost $ do
2425+ es <- newFanEventWithTriggerIO f
2426+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2427+
2428+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2429+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2430+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2431+ es <- newFanEventWithTriggerIO f
2432+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2433+
2434+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2435+ {-# INLINABLE subscribeEvent #-}
2436+ subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2437+
2438+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2439+ type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2440+ fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2441+ runHostFrame = runFrame . runSpiderHostFrame
2442+
2443+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2444+unsafeNewSpiderTimelineEnv = do
2445+ lock <- newMVar ()
2446+ env <- newEventEnv
2447+#ifdef DEBUG
2448+ depthRef <- newIORef 0
2449+#endif
2450+ return $ SpiderTimelineEnv
2451+ { _spiderTimeline_lock = lock
2452+ , _spiderTimeline_eventEnv = env
2453+#ifdef DEBUG
2454+ , _spiderTimeline_depth = depthRef
2455+#endif
2456+ }
2457+
2458+-- | Create a new SpiderTimelineEnv
2459+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2460+newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2461+
2462+data LocalSpiderTimeline x s
2463+
2464+instance Reifies s (SpiderTimelineEnv x) =>
2465+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2466+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2467+
2468+localSpiderTimeline
2469+ :: Proxy s
2470+ -> SpiderTimelineEnv x
2471+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2472+localSpiderTimeline _ = unsafeCoerce
2473+
2474+-- | Pass a new timeline to the given function.
2475+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2476+withSpiderTimeline k = do
2477+ env <- unsafeNewSpiderTimelineEnv
2478+ reify env $ \s -> k $ localSpiderTimeline s env
2479+
2480+newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2481+
2482+type ComputeM = EventM
2483+
2484+newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2485+
2486+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2487+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2488+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2489+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2490+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2491+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2492+ type PullM (SpiderTimeline x) = SpiderPullM x
2493+ type PushM (SpiderTimeline x) = SpiderPushM x
2494+ {-# INLINABLE never #-}
2495+ never = SpiderEvent eventNever
2496+ {-# INLINABLE constant #-}
2497+ constant = SpiderBehavior . behaviorConst
2498+ {-# INLINE push #-}
2499+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2500+ {-# INLINE pushCheap #-}
2501+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2502+ {-# INLINABLE pull #-}
2503+ pull = SpiderBehavior . pull . coerce
2504+ {-# INLINABLE merge #-}
2505+ merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2506+ {-# INLINABLE fan #-}
2507+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2508+ {-# INLINABLE switch #-}
2509+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2510+ {-# INLINABLE coincidence #-}
2511+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2512+ {-# INLINABLE current #-}
2513+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2514+ {-# INLINABLE updated #-}
2515+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2516+ {-# INLINABLE unsafeBuildDynamic #-}
2517+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2518+ {-# INLINABLE unsafeBuildIncremental #-}
2519+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2520+ {-# INLINABLE mergeIncremental #-}
2521+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2522+ {-# INLINABLE mergeIncrementalWithMove #-}
2523+ mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2524+ {-# INLINABLE currentIncremental #-}
2525+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2526+ {-# INLINABLE updatedIncremental #-}
2527+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2528+ {-# INLINABLE incrementalToDynamic #-}
2529+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2530+ c <- readBehaviorUntracked $ dynamicCurrent i
2531+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2532+ eventCoercion Coercion = Coercion
2533+ behaviorCoercion Coercion = Coercion
2534+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2535+ {-# INLINABLE mergeIntIncremental #-}
2536+ mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2537+ {-# INLINABLE fanInt #-}
2538+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2539+
2540+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2541+
2542+data SpiderEventHandle x a = SpiderEventHandle
2543+ { spiderEventHandleSubscription :: EventSubscription x
2544+ , spiderEventHandleValue :: IORef (Maybe a)
2545+ }
2546+
2547+instance MonadRef (EventM x) where
2548+ type Ref (EventM x) = Ref IO
2549+ {-# INLINABLE newRef #-}
2550+ {-# INLINABLE readRef #-}
2551+ {-# INLINABLE writeRef #-}
2552+ newRef = liftIO . newRef
2553+ readRef = liftIO . readRef
2554+ writeRef r a = liftIO $ writeRef r a
2555+
2556+instance MonadAtomicRef (EventM x) where
2557+ {-# INLINABLE atomicModifyRef #-}
2558+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2559+
2560+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2561+newtype SpiderHost x a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2562+
2563+instance Monad (SpiderHost x) where
2564+ {-# INLINABLE (>>=) #-}
2565+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2566+ {-# INLINABLE (>>) #-}
2567+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2568+ {-# INLINABLE return #-}
2569+ return x = SpiderHost $ return x
2570+ {-# INLINABLE fail #-}
2571+ fail s = SpiderHost $ fail s
2572+
2573+-- | Run an action affecting the global Spider timeline; this will be guarded by
2574+-- a mutex for that timeline
2575+runSpiderHost :: SpiderHost Global a -> IO a
2576+runSpiderHost (SpiderHost a) = a
2577+
2578+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2579+-- mutex for that timeline
2580+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2581+runSpiderHostForTimeline (SpiderHost a) _ = a
2582+
2583+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2584+ deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2585+
2586+instance Monad (SpiderHostFrame x) where
2587+ {-# INLINABLE (>>=) #-}
2588+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2589+ {-# INLINABLE (>>) #-}
2590+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2591+ {-# INLINABLE return #-}
2592+ return x = SpiderHostFrame $ return x
2593+ {-# INLINABLE fail #-}
2594+ fail s = SpiderHostFrame $ fail s
2595+
2596+instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2597+ notReadyUntil _ = pure ()
2598+ notReady = pure ()
2599+
2600+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2601+newEventWithTriggerIO f = do
2602+ es <- newFanEventWithTriggerIO $ \Refl -> f
2603+ return $ select es Refl
2604+
2605+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2606+newFanEventWithTriggerIO f = do
2607+ occRef <- newIORef DMap.empty
2608+ subscribedRef <- newIORef DMap.empty
2609+ let !r = Root
2610+ { rootOccurrence = occRef
2611+ , rootSubscribed = subscribedRef
2612+ , rootInit = f
2613+ }
2614+ return $ EventSelector $ \k -> eventRoot k r
2615+
2616+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2617+
2618+instance MonadRef (SpiderHost x) where
2619+ type Ref (SpiderHost x) = Ref IO
2620+ newRef = SpiderHost . newRef
2621+ readRef = SpiderHost . readRef
2622+ writeRef r = SpiderHost . writeRef r
2623+
2624+instance MonadAtomicRef (SpiderHost x) where
2625+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2626+
2627+instance MonadRef (SpiderHostFrame x) where
2628+ type Ref (SpiderHostFrame x) = Ref IO
2629+ newRef = SpiderHostFrame . newRef
2630+ readRef = SpiderHostFrame . readRef
2631+ writeRef r = SpiderHostFrame . writeRef r
2632+
2633+instance MonadAtomicRef (SpiderHostFrame x) where
2634+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2635+
2636+instance PrimMonad (SpiderHostFrame x) where
2637+ type PrimState (SpiderHostFrame x) = PrimState IO
2638+ primitive = SpiderHostFrame . EventM . primitive