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