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