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