@@ -0,0 +1,2150 @@
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+asksEventEnv :: (EventEnv x -> a) -> EventM x a
677+asksEventEnv = EventM . asks
678+
679+class MonadIO m => Defer a m where
680+ getDeferralQueue :: m (IORef [a])
681+
682+{-# INLINE defer #-}
683+defer :: Defer a m => a -> m ()
684+defer a = do
685+ q <- getDeferralQueue
686+ liftIO $ modifyIORef' q (a:)
687+
688+instance Defer (SomeAssignment x) (EventM x) where
689+ {-# INLINE getDeferralQueue #-}
690+ getDeferralQueue = asksEventEnv eventEnvAssignments
691+
692+instance Defer (SomeHoldInit x) (EventM x) where
693+ {-# INLINE getDeferralQueue #-}
694+ getDeferralQueue = asksEventEnv eventEnvHoldInits
695+
696+instance Defer (SomeHoldInit x) (BehaviorM x) where
697+ {-# INLINE getDeferralQueue #-}
698+ getDeferralQueue = BehaviorM $ asks snd
699+
700+instance Defer (SomeMergeUpdate x) (EventM x) where
701+ {-# INLINE getDeferralQueue #-}
702+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
703+
704+instance Defer (SomeMergeInit x) (EventM x) where
705+ {-# INLINE getDeferralQueue #-}
706+ getDeferralQueue = asksEventEnv eventEnvMergeInits
707+
708+class HasCurrentHeight x m | m -> x where
709+ getCurrentHeight :: m Height
710+ scheduleMerge :: Height -> EventM x () -> m ()
711+
712+instance HasCurrentHeight x (EventM x) where
713+ {-# INLINE getCurrentHeight #-}
714+ getCurrentHeight = EventM $ do
715+ heightRef <- asks eventEnvCurrentHeight
716+ liftIO $ readIORef heightRef
717+ {-# INLINE scheduleMerge #-}
718+ scheduleMerge height subscribed = EventM $ do
719+ delayedRef <- asks eventEnvDelayedMerges
720+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
721+
722+class HasSpiderTimeline x m | m -> x where
723+ -- | Retrieve the current SpiderTimeline
724+ askSpiderTimeline :: m (SpiderTimeline x)
725+
726+instance HasSpiderTimeline x (EventM x) where
727+ {-# INLINE askSpiderTimeline #-}
728+ askSpiderTimeline = asksEventEnv eventEnvSpiderTimeline
729+
730+instance HasSpiderTimeline x (SpiderHost x) where
731+ {-# INLINE askSpiderTimeline #-}
732+ askSpiderTimeline = SpiderHost ask
733+
734+putCurrentHeight :: Height -> EventM x ()
735+putCurrentHeight h = EventM $ do
736+ heightRef <- asks eventEnvCurrentHeight
737+ liftIO $ writeIORef heightRef $! h
738+
739+instance Defer SomeClear (EventM x) where
740+ {-# INLINE getDeferralQueue #-}
741+ getDeferralQueue = asksEventEnv eventEnvClears
742+
743+{-# INLINE scheduleClear #-}
744+scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
745+scheduleClear r = defer $ SomeClear r
746+
747+instance Defer SomeRootClear (EventM x) where
748+ {-# INLINE getDeferralQueue #-}
749+ getDeferralQueue = asksEventEnv eventEnvRootClears
750+
751+{-# INLINE scheduleRootClear #-}
752+scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
753+scheduleRootClear r = defer $ SomeRootClear r
754+
755+instance Defer (SomeResetCoincidence x) (EventM x) where
756+ {-# INLINE getDeferralQueue #-}
757+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
758+
759+-- Note: hold cannot examine its event until after the phase is over
760+{-# SPECIALIZE hold :: R.Patch p => R.PatchTarget p -> Event x p -> EventM x (Hold x p) #-}
761+{-# SPECIALIZE hold :: R.Patch p => R.PatchTarget p -> Event x p -> ComputeM x (Hold x p) #-}
762+hold :: (R.Patch p, Defer (SomeHoldInit x) m) => R.PatchTarget p -> Event x p -> m (Hold x p)
763+hold v0 e = do
764+ valRef <- liftIO $ newIORef v0
765+ invsRef <- liftIO $ newIORef []
766+ parentRef <- liftIO $ newIORef Nothing
767+#ifdef DEBUG_NODEIDS
768+ nodeId <- liftIO newNodeId
769+#endif
770+ let h = Hold
771+ { holdValue = valRef
772+ , holdInvalidators = invsRef
773+ , holdEvent = e
774+ , holdParent = parentRef
775+#ifdef DEBUG_NODEIDS
776+ , holdNodeId = nodeId
777+#endif
778+ }
779+ defer $ SomeHoldInit h
780+ return h
781+
782+{-# INLINE getHoldEventSubscription #-}
783+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)
784+getHoldEventSubscription h = do
785+ ep <- liftIO $ readIORef $ holdParent h
786+ case ep of
787+ Just subd -> return subd
788+ Nothing -> do
789+ let e = holdEvent h
790+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
791+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
792+ liftIO $ writeIORef subscriptionRef $! subscription
793+ case occ of
794+ Nothing -> return ()
795+ Just o -> do
796+ old <- liftIO $ readIORef $ holdValue h
797+ case R.apply o old of
798+ Nothing -> return ()
799+ Just new -> do
800+ -- Need to evaluate these so that we don't retain the Hold itself
801+ v <- liftIO $ evaluate $ holdValue h
802+ i <- liftIO $ evaluate $ holdInvalidators h
803+ defer $ SomeAssignment v i new
804+ liftIO $ writeIORef (holdParent h) $ Just subscription
805+ return subscription
806+
807+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
808+
809+--type role BehaviorM representational
810+-- BehaviorM can sample behaviors
811+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
812+
813+instance Monad (BehaviorM x) where
814+ {-# INLINE (>>=) #-}
815+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
816+ {-# INLINE (>>) #-}
817+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
818+ {-# INLINE return #-}
819+ return x = BehaviorM $ return x
820+ {-# INLINE fail #-}
821+ fail s = BehaviorM $ fail s
822+
823+data BehaviorSubscribed x a
824+ = forall p. BehaviorSubscribedHold (Hold x p)
825+ | BehaviorSubscribedPull (PullSubscribed x a)
826+
827+data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
828+
829+--type role PullSubscribed representational
830+data PullSubscribed x a
831+ = PullSubscribed { pullSubscribedValue :: !a
832+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
833+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
834+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
835+ }
836+
837+--type role Pull representational
838+data Pull x a
839+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
840+ , pullCompute :: !(BehaviorM x a)
841+#ifdef DEBUG_NODEIDS
842+ , pullNodeId :: Int
843+#endif
844+ }
845+
846+data Invalidator x
847+ = forall a. InvalidatorPull (Pull x a)
848+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
849+
850+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
851+ { rootSubscribedKey :: !(k a)
852+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
853+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
854+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
855+ , rootSubscribedUninit :: IO ()
856+ , 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?
857+#ifdef DEBUG_NODEIDS
858+ , rootSubscribedNodeId :: Int
859+#endif
860+ }
861+
862+data Root x (k :: * -> *)
863+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
864+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
865+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
866+ }
867+
868+data SomeHoldInit x = forall p. R.Patch p => SomeHoldInit !(Hold x p)
869+
870+data SomeMergeUpdate x = SomeMergeUpdate
871+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
872+ , _someMergeUpdate_invalidateHeight :: !(IO ())
873+ , _someMergeUpdate_recalculateHeight :: !(IO ())
874+ }
875+
876+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
877+
878+-- EventM can do everything BehaviorM can, plus create holds
879+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
880+
881+newtype ComputeM x a = ComputeM (ReaderT (IORef [SomeHoldInit x]) IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
882+
883+instance Defer (SomeHoldInit x) (ComputeM x) where
884+ getDeferralQueue = ComputeM ask
885+
886+{-# SPECIALIZE runComputeM :: ComputeM x a -> EventM x a #-}
887+runComputeM :: Defer (SomeHoldInit x) m => ComputeM x a -> m a
888+runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
889+
890+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
891+
892+data HeightBag = HeightBag
893+ { _heightBag_size :: {-# UNPACK #-} !Int
894+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
895+ }
896+ deriving (Show, Read, Eq, Ord)
897+
898+heightBagEmpty :: HeightBag
899+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
900+
901+heightBagSize :: HeightBag -> Int
902+heightBagSize = _heightBag_size
903+
904+heightBagFromList :: [Height] -> HeightBag
905+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
906+
907+heightBagAdd :: Height -> HeightBag -> HeightBag
908+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
909+
910+heightBagRemove :: Height -> HeightBag -> HeightBag
911+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
912+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
913+ Just old -> HeightBag (pred s) $ case old of
914+ 0 -> IntMap.delete h c
915+ _ -> IntMap.insert h (pred old) c
916+
917+heightBagMax :: HeightBag -> Height
918+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
919+ Just ((h, _), _) -> Height h
920+ Nothing -> zeroHeight
921+
922+heightBagVerify :: HeightBag -> HeightBag
923+#ifdef DEBUG
924+heightBagVerify b@(HeightBag s c) = if
925+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
926+ -> error $ "heightBagVerify: size doesn't match: " <> show b
927+ | unHeight invalidHeight `IntMap.member` c
928+ -> error $ "heightBagVerify: contains invalid height: " <> show b
929+ | otherwise -> b
930+#else
931+heightBagVerify = id
932+#endif
933+
934+data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
935+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
936+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
937+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
938+ }
939+
940+data FanSubscribed (x :: *) k
941+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
942+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
943+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
944+ , fanSubscribedParent :: !(EventSubscription x)
945+#ifdef DEBUG_NODEIDS
946+ , fanSubscribedNodeId :: Int
947+#endif
948+ }
949+
950+data Fan x k
951+ = Fan { fanParent :: !(Event x (DMap k Identity))
952+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
953+ }
954+
955+data SwitchSubscribed x a
956+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
957+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
958+ , switchSubscribedHeight :: !(IORef Height)
959+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
960+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
961+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
962+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
963+ , switchSubscribedParent :: !(Behavior x (Event x a))
964+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
965+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
966+#ifdef DEBUG_NODEIDS
967+ , switchSubscribedNodeId :: Int
968+#endif
969+ }
970+
971+data Switch x a
972+ = Switch { switchParent :: !(Behavior x (Event x a))
973+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
974+ }
975+
976+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
977+data CoincidenceSubscribed x a
978+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
979+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
980+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
981+ , coincidenceSubscribedHeight :: !(IORef Height)
982+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
983+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
984+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
985+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
986+#ifdef DEBUG_NODEIDS
987+ , coincidenceSubscribedNodeId :: Int
988+#endif
989+ }
990+
991+data Coincidence x a
992+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
993+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
994+ }
995+
996+{-# NOINLINE newInvalidatorSwitch #-}
997+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
998+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
999+
1000+{-# NOINLINE newInvalidatorPull #-}
1001+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1002+newInvalidatorPull p = return $! InvalidatorPull p
1003+
1004+instance R.FunctorMaybe (Event x) where
1005+ fmapMaybe f = push $ return . f
1006+
1007+instance Align (Event x) where
1008+ nil = eventNever
1009+ align ea eb = R.fmapMaybe R.dmapToThese $ merge $ dynamicConst $ DMap.fromList [R.LeftTag :=> ea, R.RightTag :=> eb]
1010+
1011+newtype Dyn x p = Dyn { unDyn :: IORef (Either (BehaviorM x (R.PatchTarget p), Event x p) (Hold x p)) }
1012+
1013+newMapDyn :: (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1014+newMapDyn f d = dynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1015+
1016+--TODO: Avoid the duplication between this and R.zipDynWith
1017+zipDynWith :: (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1018+zipDynWith f da db =
1019+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1020+ ec = flip push eab $ \o -> do
1021+ (a, b) <- case o of
1022+ This (Identity a) -> do
1023+ b <- readBehaviorUntracked $ dynamicCurrent db
1024+ return (a, b)
1025+ That (Identity b) -> do
1026+ a <- readBehaviorUntracked $ dynamicCurrent da
1027+ return (a, b)
1028+ These (Identity a) (Identity b) -> return (a, b)
1029+ return $ Just $ Identity $ f a b
1030+ in dynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1031+
1032+unsafeDyn :: BehaviorM x (R.PatchTarget p) -> Event x p -> Dyn x p
1033+unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1034+ where x = (readV0, v')
1035+
1036+newJoinDyn :: Dynamic x (Identity (Dynamic x (Identity a))) -> Dyn x (Identity a)
1037+newJoinDyn d =
1038+ let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
1039+ eOuter = push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
1040+ eInner = switch $ dynamicUpdated <$> dynamicCurrent d
1041+ eBoth = coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
1042+ v' = unSpiderEvent $ R.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
1043+ in unsafeDyn readV0 v'
1044+
1045+-- ResultM can read behaviors and events
1046+type ResultM = EventM
1047+
1048+{-# NOINLINE unsafeNewIORef #-}
1049+unsafeNewIORef :: a -> b -> IORef b
1050+unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1051+
1052+instance Functor (Event x) where
1053+ fmap f = push $ return . Just . f
1054+
1055+instance Functor (Behavior x) where
1056+ fmap f = pull . fmap f . readBehaviorTracked
1057+
1058+{-# INLINABLE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly
1059+push :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1060+push f e = cacheEvent (pushCheap f e)
1061+{-
1062+push f e = eventPush $ Push
1063+ { pushCompute = f
1064+ , pushParent = e
1065+ , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead?
1066+ }
1067+-- DISABLED: {- RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-}
1068+-}
1069+
1070+{-# INLINABLE pull #-}
1071+pull :: BehaviorM x a -> Behavior x a
1072+pull a = behaviorPull $ Pull
1073+ { pullCompute = a
1074+ , pullValue = unsafeNewIORef a Nothing
1075+#ifdef DEBUG_NODEIDS
1076+ , pullNodeId = unsafeNodeId a
1077+#endif
1078+ }
1079+
1080+{-# INLINABLE switch #-}
1081+switch :: Behavior x (Event x a) -> Event x a
1082+switch a = eventSwitch $ Switch
1083+ { switchParent = a
1084+ , switchSubscribed = unsafeNewIORef a Nothing
1085+ }
1086+
1087+coincidence :: Event x (Event x a) -> Event x a
1088+coincidence a = eventCoincidence $ Coincidence
1089+ { coincidenceParent = a
1090+ , coincidenceSubscribed = unsafeNewIORef a Nothing
1091+ }
1092+
1093+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1094+run :: [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1095+run roots after = do
1096+ tracePropagate $ "Running an event frame with " <> show (length roots) <> " events"
1097+ spiderTimeline <- SpiderHost ask
1098+ result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock spiderTimeline) $ \_ -> flip runReaderT spiderTimeline $ unSpiderHost $ runFrame $ do
1099+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1100+ occBefore <- liftIO $ do
1101+ occBefore <- readIORef occRef
1102+ writeIORef occRef $! DMap.insert k a occBefore
1103+ return occBefore
1104+ if DMap.null occBefore
1105+ then do scheduleRootClear occRef
1106+ return $ Just r
1107+ else return Nothing
1108+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1109+ propagate a subscribersRef
1110+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1111+ let go = do
1112+ delayed <- liftIO $ readIORef delayedRef
1113+ case IntMap.minViewWithKey delayed of
1114+ Nothing -> return ()
1115+ Just ((currentHeight, cur), future) -> do
1116+ tracePropagate $ "Running height " ++ show currentHeight
1117+ putCurrentHeight $ Height currentHeight
1118+ liftIO $ writeIORef delayedRef $! future
1119+ sequence_ cur
1120+ go
1121+ go
1122+ putCurrentHeight maxBound
1123+ after
1124+ tracePropagate "Done running an event frame"
1125+ return result
1126+
1127+scheduleMerge' :: Height -> IORef Height -> EventM x () -> EventM x ()
1128+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1129+ height <- liftIO $ readIORef heightRef
1130+ currentHeight <- getCurrentHeight
1131+ case height `compare` currentHeight of
1132+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1133+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1134+ EQ -> a
1135+
1136+data SomeClear = forall a. SomeClear (IORef (Maybe a))
1137+
1138+data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
1139+
1140+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1141+
1142+debugFinalize :: Bool
1143+debugFinalize = False
1144+
1145+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1146+mkWeakPtrWithDebug x debugNote = do
1147+ x' <- evaluate x
1148+ mkWeakPtr x' $
1149+ if debugFinalize
1150+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1151+ else Nothing
1152+
1153+type WeakList a = [Weak a]
1154+
1155+{-# INLINE withIncreasedDepth #-}
1156+#ifdef DEBUG
1157+withIncreasedDepth :: CanTrace x m => m a -> m a
1158+withIncreasedDepth a = do
1159+ spiderTimeline <- askSpiderTimeline
1160+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1161+ result <- a
1162+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1163+ return result
1164+#else
1165+withIncreasedDepth :: m a -> m a
1166+withIncreasedDepth = id
1167+#endif
1168+
1169+type CanTrace x m = (HasSpiderTimeline x m, MonadIO m)
1170+
1171+{-# INLINE tracePropagate #-}
1172+tracePropagate :: (CanTrace x m) => String -> m ()
1173+tracePropagate = traceWhen debugPropagate
1174+
1175+{-# INLINE traceInvalidate #-}
1176+traceInvalidate :: String -> IO ()
1177+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1178+
1179+{-# INLINE traceWhen #-}
1180+traceWhen :: (CanTrace x m) => Bool -> String -> m ()
1181+traceWhen b message = traceMWhen b $ return message
1182+
1183+{-# INLINE traceMWhen #-}
1184+traceMWhen :: (CanTrace x m) => Bool -> m String -> m ()
1185+traceMWhen b getMessage = when b $ do
1186+ message <- getMessage
1187+#ifdef DEBUG
1188+ spiderTimeline <- askSpiderTimeline
1189+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1190+#else
1191+ let d = 0
1192+#endif
1193+ liftIO $ putStrLn $ replicate d ' ' <> message
1194+
1195+whoCreatedIORef :: IORef a -> IO [String]
1196+whoCreatedIORef (IORef a) = whoCreated $! a
1197+
1198+#ifdef DEBUG_CYCLES
1199+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1200+groupByHead = \case
1201+ [] -> []
1202+ (x :| xs) : t -> case groupByHead t of
1203+ [] -> [(x, xs :| [])]
1204+ l@((y, yss) : t')
1205+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1206+ | otherwise -> (x, xs :| []) : l
1207+
1208+listsToForest :: Eq a => [[a]] -> Forest a
1209+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1210+#endif
1211+
1212+{-# INLINE propagateSubscriberHold #-}
1213+propagateSubscriberHold :: R.Patch p => Hold x p -> p -> EventM x ()
1214+propagateSubscriberHold h a = do
1215+ {-# SCC "trace" #-} traceMWhen debugPropagate $ liftIO $ do
1216+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1217+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1218+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1219+ case {-# SCC "apply" #-} R.apply a v of
1220+ Nothing -> return ()
1221+ Just v' -> do
1222+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1223+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1224+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1225+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1226+
1227+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1228+
1229+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1230+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1231+
1232+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1233+askInvalidator = do
1234+ (!m, _) <- BehaviorM ask
1235+ case m of
1236+ Nothing -> return Nothing
1237+ Just (!wi, _) -> return $ Just wi
1238+
1239+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1240+askParentsRef = do
1241+ (!m, _) <- BehaviorM ask
1242+ case m of
1243+ Nothing -> return Nothing
1244+ Just (_, !p) -> return $ Just p
1245+
1246+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1247+askBehaviorHoldInits = do
1248+ (_, !his) <- BehaviorM ask
1249+ return his
1250+
1251+{-# INLINE getDynHold #-}
1252+getDynHold :: (Defer (SomeHoldInit x) m, R.Patch p) => Dyn x p -> m (Hold x p)
1253+getDynHold d = do
1254+ mh <- liftIO $ readIORef $ unDyn d
1255+ case mh of
1256+ Right h -> return h
1257+ Left (readV0, v') -> do
1258+ holdInits <- getDeferralQueue
1259+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1260+ h <- hold v0 v'
1261+ liftIO $ writeIORef (unDyn d) $ Right h
1262+ return h
1263+
1264+-- Always refers to 0
1265+{-# NOINLINE zeroRef #-}
1266+zeroRef :: IORef Height
1267+zeroRef = unsafePerformIO $ newIORef zeroHeight
1268+
1269+type CanSubscribe x m =
1270+ ( HasSpiderTimeline x m
1271+ , HasCurrentHeight x m
1272+ , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1273+ , Defer SomeClear m -- Wiping out event firings
1274+ , Defer (SomeAssignment x) m -- Updating state
1275+ , Defer (SomeResetCoincidence x) m
1276+ , m ~ EventM x
1277+ )
1278+
1279+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1280+getRootSubscribed k r sub = do
1281+ mSubscribed <- readIORef $ rootSubscribed r
1282+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1283+ case DMap.lookup k mSubscribed of
1284+ Just subscribed -> {-# SCC "hitRoot" #-} do
1285+ sln <- subscribeRootSubscribed subscribed sub
1286+ occ <- getOcc
1287+ return (sln, subscribed, occ)
1288+ Nothing -> {-# SCC "missRoot" #-} do
1289+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1290+ let !cached = rootSubscribed r
1291+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1292+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1293+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1294+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1295+ writeIORef uninitRef $! uninit
1296+ let subscribed = RootSubscribed
1297+ { rootSubscribedKey = k
1298+ , rootSubscribedCachedSubscribed = cached
1299+ , rootSubscribedOccurrence = getOcc
1300+ , rootSubscribedSubscribers = subs
1301+ , rootSubscribedUninit = uninit
1302+ , rootSubscribedWeakSelf = weakSelf
1303+#ifdef DEBUG_NODEIDS
1304+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1305+#endif
1306+ }
1307+ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1308+ 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
1309+ occ <- getOcc
1310+ return (sln, subscribed, occ)
1311+
1312+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1313+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1314+cleanupRootSubscribed self@(RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached }) = do
1315+ rootSubscribedUninit self
1316+ modifyIORef' cached $ DMap.delete k
1317+
1318+{-# INLINE subscribeRootSubscribed #-}
1319+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1320+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1321+
1322+{-# SPECIALIZE getFanSubscribed :: GCompare k => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket, FanSubscribed x k, Maybe a) #-}
1323+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)
1324+getFanSubscribed k f sub = do
1325+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1326+ case mSubscribed of
1327+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1328+ sln <- subscribeFanSubscribed k subscribed sub
1329+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1330+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1331+ Nothing -> {-# SCC "missFan" #-} do
1332+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1333+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1334+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1335+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1336+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1337+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1338+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1339+ occRef <- liftIO $ newIORef parentOcc
1340+ when (isJust parentOcc) $ scheduleClear occRef
1341+ let subscribed = FanSubscribed
1342+ { fanSubscribedCachedSubscribed = fanSubscribed f
1343+ , fanSubscribedOccurrence = occRef
1344+ , fanSubscribedParent = subscription
1345+ , fanSubscribedSubscribers = subscribersRef
1346+#ifdef DEBUG_NODEIDS
1347+ , fanSubscribedNodeId = unsafeNodeId f
1348+#endif
1349+ }
1350+ let !self = (k, subscribed)
1351+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1352+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1353+ liftIO $ writeIORef subscribedRef $! subscribed
1354+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1355+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1356+
1357+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1358+cleanupFanSubscribed (k, subscribed) = do
1359+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1360+ let reducedSubscribers = DMap.delete k subscribers
1361+ if DMap.null reducedSubscribers
1362+ then do
1363+ unsubscribe $ fanSubscribedParent subscribed
1364+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1365+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1366+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1367+
1368+{-# INLINE subscribeFanSubscribed #-}
1369+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1370+subscribeFanSubscribed k subscribed sub = do
1371+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1372+ case DMap.lookup k subscribers of
1373+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1374+ let !self = (k, subscribed)
1375+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1376+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1377+ 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
1378+ return sln
1379+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1380+
1381+{-# SPECIALIZE getSwitchSubscribed :: Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a) #-}
1382+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)
1383+getSwitchSubscribed s sub = do
1384+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1385+ case mSubscribed of
1386+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1387+ sln <- subscribeSwitchSubscribed subscribed sub
1388+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1389+ return (sln, subscribed, occ)
1390+ Nothing -> {-# SCC "missSwitch" #-} do
1391+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1392+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1393+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1394+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1395+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1396+ wiRef <- liftIO $ newIORef wi
1397+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1398+ holdInits <- getDeferralQueue
1399+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1400+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1401+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1402+ subscriptionRef <- liftIO $ newIORef subscription
1403+ occRef <- liftIO $ newIORef parentOcc
1404+ when (isJust parentOcc) $ scheduleClear occRef
1405+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1406+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1407+ let !subscribed = SwitchSubscribed
1408+ { switchSubscribedCachedSubscribed = switchSubscribed s
1409+ , switchSubscribedOccurrence = occRef
1410+ , switchSubscribedHeight = heightRef
1411+ , switchSubscribedSubscribers = subs
1412+ , switchSubscribedOwnInvalidator = i
1413+ , switchSubscribedOwnWeakInvalidator = wiRef
1414+ , switchSubscribedBehaviorParents = parentsRef
1415+ , switchSubscribedParent = switchParent s
1416+ , switchSubscribedCurrentParent = subscriptionRef
1417+ , switchSubscribedWeakSelf = weakSelf
1418+#ifdef DEBUG_NODEIDS
1419+ , switchSubscribedNodeId = unsafeNodeId s
1420+#endif
1421+ }
1422+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1423+ liftIO $ writeIORef subscribedRef $! subscribed
1424+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1425+ return (slnForSub, subscribed, parentOcc)
1426+
1427+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1428+cleanupSwitchSubscribed subscribed = do
1429+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1430+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1431+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1432+
1433+{-# INLINE subscribeSwitchSubscribed #-}
1434+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1435+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1436+
1437+{-# SPECIALIZE getCoincidenceSubscribed :: Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a) #-}
1438+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)
1439+getCoincidenceSubscribed c sub = do
1440+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1441+ case mSubscribed of
1442+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1443+ sln <- subscribeCoincidenceSubscribed subscribed sub
1444+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1445+ return (sln, subscribed, occ)
1446+ Nothing -> {-# SCC "missCoincidence" #-} do
1447+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1448+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1449+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1450+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1451+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1452+ (occ, height, mInnerSubd) <- case outerOcc of
1453+ Nothing -> return (Nothing, outerHeight, Nothing)
1454+ Just o -> do
1455+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1456+ return (occ, height, Just innerSubd)
1457+ occRef <- liftIO $ newIORef occ
1458+ when (isJust occ) $ scheduleClear occRef
1459+ heightRef <- liftIO $ newIORef height
1460+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1461+ scheduleClear innerSubdRef
1462+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1463+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1464+ let subscribed = CoincidenceSubscribed
1465+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1466+ , coincidenceSubscribedOccurrence = occRef
1467+ , coincidenceSubscribedHeight = heightRef
1468+ , coincidenceSubscribedSubscribers = subs
1469+ , coincidenceSubscribedOuter = subOuter
1470+ , coincidenceSubscribedOuterParent = outerSubscription
1471+ , coincidenceSubscribedInnerParent = innerSubdRef
1472+ , coincidenceSubscribedWeakSelf = weakSelf
1473+#ifdef DEBUG_NODEIDS
1474+ , coincidenceSubscribedNodeId = unsafeNodeId c
1475+#endif
1476+ }
1477+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1478+ liftIO $ writeIORef subscribedRef $! subscribed
1479+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1480+ return (slnForSub, subscribed, occ)
1481+
1482+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1483+cleanupCoincidenceSubscribed subscribed = do
1484+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1485+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1486+
1487+{-# INLINE subscribeCoincidenceSubscribed #-}
1488+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1489+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1490+
1491+{-# INLINE merge #-}
1492+merge :: forall k x. GCompare k => Dynamic x (R.PatchDMap k (Event x)) -> Event x (DMap k Identity)
1493+merge d = cacheEvent $ Event $ \sub -> do
1494+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1495+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1496+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1497+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1498+ parentsRef <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1499+ let scheduleSelf height = scheduleMerge' height heightRef $ do
1500+ m <- liftIO $ readIORef accumRef
1501+ liftIO $ writeIORef accumRef $! DMap.empty
1502+ --TODO: Assert that m is not empty
1503+ subscriberPropagate sub m
1504+ invalidateMyHeight = do
1505+ oldHeight <- readIORef heightRef
1506+ 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
1507+ writeIORef heightRef $! invalidHeight
1508+ subscriberInvalidateHeight sub oldHeight
1509+ revalidateMyHeight = do
1510+ currentHeight <- readIORef heightRef
1511+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1512+ heights <- readIORef heightBagRef
1513+ parents <- readIORef parentsRef
1514+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1515+ case heightBagSize heights `compare` DMap.size parents of
1516+ LT -> return ()
1517+ EQ -> do
1518+ let height = succHeight $ heightBagMax heights
1519+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1520+ writeIORef heightRef $! height
1521+ subscriberRecalculateHeight sub height
1522+ GT -> error $ "revalidateMergeHeight: more heights than parents for Merge"
1523+ subscriber :: forall a. k a -> Subscriber x a
1524+ subscriber k = Subscriber
1525+ { subscriberPropagate = \a -> do
1526+ oldM <- liftIO $ readIORef accumRef
1527+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1528+ tracePropagate $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1529+ liftIO $ writeIORef accumRef $! newM
1530+ when (DMap.null oldM) $ do -- Only schedule the firing once
1531+ height <- liftIO $ readIORef heightRef
1532+ --TODO: assertions about height
1533+ currentHeight <- getCurrentHeight
1534+ when (height <= currentHeight) $ do
1535+ if height /= invalidHeight
1536+ then do
1537+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1538+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1539+ else liftIO $ do
1540+#ifdef DEBUG_CYCLES
1541+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1542+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1543+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1544+#else
1545+ let cycleInfo = ""
1546+#endif
1547+ error $ "Causality loop found" <> cycleInfo
1548+ scheduleSelf height
1549+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1550+ modifyIORef' heightBagRef $ heightBagRemove old
1551+ invalidateMyHeight
1552+ , subscriberRecalculateHeight = \new -> do
1553+ modifyIORef' heightBagRef $ heightBagAdd new
1554+ revalidateMyHeight
1555+ }
1556+ subscribers :: [(Maybe (DSum k Identity), Height, DSum k (MergeSubscribedParent x))] <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1557+ let s = subscriber k
1558+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1559+ height <- liftIO $ getEventSubscribedHeight parentSubd
1560+ return $ (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1561+ let dm = DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1562+ heights = fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1563+ myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1564+ myHeight = if invalidHeight `elem` heights
1565+ then invalidHeight
1566+ else succHeight $ heightBagMax myHeightBag
1567+ currentHeight <- getCurrentHeight
1568+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1569+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1570+ else (Nothing, dm)
1571+ unless (DMap.null accum) $ do
1572+ scheduleSelf myHeight
1573+ occRef <- liftIO $ newIORef occ
1574+ when (isJust occ) $ scheduleClear occRef
1575+ liftIO $ writeIORef accumRef $! accum
1576+ liftIO $ writeIORef heightRef $! myHeight
1577+ liftIO $ writeIORef heightBagRef $! myHeightBag
1578+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1579+ liftIO $ writeIORef parentsRef $! DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1580+ let updateMe (R.PatchDMap p) = do
1581+ oldParents <- liftIO $ readIORef parentsRef
1582+ let f (subscriptionsToKill, ps) (k :=> R.ComposeMaybe me) = do
1583+ (mOldSubd, newPs) <- case me of
1584+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1585+ Just e -> do
1586+ let s = subscriber k
1587+ subscription@(EventSubscription _ subd) <- subscribe e s
1588+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1589+ let newParent = MergeSubscribedParent subscription
1590+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1591+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1592+ forM_ mOldSubd $ \oldSubd -> do
1593+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1594+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1595+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1596+ (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
1597+ liftIO $ writeIORef parentsRef $! newParents
1598+ return subscriptionsToKill
1599+ defer $ SomeMergeInit $ do
1600+ let s = Subscriber
1601+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1602+ tracePropagate $ "SubscriberMerge/Change"
1603+ defer $ SomeMergeUpdate (updateMe a) invalidateMyHeight revalidateMyHeight
1604+ , subscriberInvalidateHeight = \_ -> return ()
1605+ , subscriberRecalculateHeight = \_ -> return ()
1606+ }
1607+ (EventSubscription _ changeSubd, change) <- subscribeAndRead (dynamicUpdated d) s
1608+ forM_ change $ \c -> defer $ SomeMergeUpdate (updateMe c) invalidateMyHeight revalidateMyHeight
1609+ liftIO $ writeIORef changeSubdRef (s, changeSubd)
1610+ let unsubscribeAll = do
1611+ parents <- readIORef parentsRef
1612+ forM_ (DMap.toList parents) $ \(_ :=> MergeSubscribedParent s) -> unsubscribe s
1613+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1614+ , occ
1615+ )
1616+
1617+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1618+
1619+fan :: GCompare k => Event x (DMap k Identity) -> EventSelector x k
1620+fan e =
1621+ let f = Fan
1622+ { fanParent = e
1623+ , fanSubscribed = unsafeNewIORef e Nothing
1624+ }
1625+ in EventSelector $ \k -> eventFan k f
1626+
1627+runHoldInits :: IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1628+runHoldInits holdInitRef mergeInitRef = do
1629+ holdInits <- liftIO $ readIORef holdInitRef
1630+ mergeInits <- liftIO $ readIORef mergeInitRef
1631+ unless (null holdInits && null mergeInits) $ do
1632+ liftIO $ writeIORef holdInitRef []
1633+ liftIO $ writeIORef mergeInitRef []
1634+ mapM_ initHold holdInits
1635+ mapM_ unSomeMergeInit mergeInits
1636+ runHoldInits holdInitRef mergeInitRef
1637+
1638+initHold :: SomeHoldInit x -> EventM x ()
1639+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1640+
1641+-- | Run an event action outside of a frame
1642+runFrame :: forall x a. EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1643+runFrame a = SpiderHost $ ask >>= \spiderTimeline -> lift $ do
1644+ -- 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
1645+ pendingCleanups <- atomicModifyIORef (_spiderTimeline_cleanups spiderTimeline) $ \x -> ([], x)
1646+ {-# SCC "cleanups" #-} sequence_ pendingCleanups
1647+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1648+ holdInitRef <- newIORef []
1649+ mergeUpdateRef <- newIORef []
1650+ mergeInitRef <- newIORef []
1651+ heightRef <- newIORef zeroHeight
1652+ toClearRef <- newIORef []
1653+ toClearRootRef <- newIORef []
1654+ coincidenceInfosRef <- newIORef []
1655+ delayedRef <- liftIO $ newIORef IntMap.empty
1656+ let env = EventEnv spiderTimeline toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1657+ let go = do
1658+ result <- a
1659+ 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
1660+ return result
1661+ result <- runEventM go env
1662+ toClear <- readIORef toClearRef
1663+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1664+ toClearRoot <- readIORef toClearRootRef
1665+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1666+ toAssign <- readIORef toAssignRef
1667+ toReconnectRef <- newIORef []
1668+ coincidenceInfos <- readIORef coincidenceInfosRef
1669+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1670+ writeIORef vRef v
1671+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
1672+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1673+ mergeUpdates <- readIORef mergeUpdateRef
1674+ writeIORef mergeUpdateRef []
1675+ when debugPropagate $ putStrLn "Updating merges"
1676+ mergeSubscriptionsToKill <- flip runEventM env $ concat <$> mapM _someMergeUpdate_update mergeUpdates
1677+ when debugPropagate $ putStrLn "Updating merges done"
1678+ toReconnect <- readIORef toReconnectRef
1679+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1680+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1681+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1682+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1683+ finalize wi
1684+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1685+ wi' <- mkWeakPtrWithDebug i "wi'"
1686+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1687+ writeIORef (switchSubscribedBehaviorParents subscribed) []
1688+ writeIORef holdInitRef [] --TODO: Should we reuse this?
1689+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) holdInitRef
1690+ 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
1691+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1692+ sub <- newSubscriberSwitch subscribed
1693+ 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
1694+ {-
1695+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1696+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1697+ EventRoot _ -> "EventRoot"
1698+ EventNever -> "EventNever"
1699+ _ -> "something else"
1700+ -}
1701+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1702+ return oldSubscription
1703+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
1704+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
1705+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1706+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1707+ parentHeight <- getEventSubscribedHeight subd'
1708+ myHeight <- readIORef $ switchSubscribedHeight subscribed
1709+ when (parentHeight /= myHeight) $ do
1710+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1711+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1712+ 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
1713+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1714+ unsubscribe subscription
1715+ mapM_ invalidateCoincidenceHeight mcs
1716+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1717+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
1718+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1719+ height <- calculateSwitchHeight subscribed
1720+ updateSwitchHeight height subscribed
1721+ return result
1722+
1723+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1724+
1725+{-# INLINE zeroHeight #-}
1726+zeroHeight :: Height
1727+zeroHeight = Height 0
1728+
1729+{-# INLINE invalidHeight #-}
1730+invalidHeight :: Height
1731+invalidHeight = Height (-1000)
1732+
1733+#ifdef DEBUG_CYCLES
1734+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1735+{-# INLINE invalidHeightBeingTraversed #-}
1736+invalidHeightBeingTraversed :: Height
1737+invalidHeightBeingTraversed = Height (-1001)
1738+#endif
1739+
1740+{-# INLINE succHeight #-}
1741+succHeight :: Height -> Height
1742+succHeight h@(Height a) =
1743+ if h == invalidHeight
1744+ then invalidHeight
1745+ else Height $ succ a
1746+
1747+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1748+invalidateCoincidenceHeight subscribed = do
1749+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1750+ when (oldHeight /= invalidHeight) $ do
1751+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1752+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1753+
1754+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1755+updateSwitchHeight new subscribed = do
1756+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1757+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1758+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1759+ writeIORef (switchSubscribedHeight subscribed) $! new
1760+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1761+
1762+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1763+recalculateCoincidenceHeight subscribed = do
1764+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1765+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1766+ height <- calculateCoincidenceHeight subscribed
1767+ when (height /= invalidHeight) $ do
1768+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
1769+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1770+
1771+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1772+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1773+
1774+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1775+calculateCoincidenceHeight subscribed = do
1776+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1777+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1778+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1779+
1780+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1781+
1782+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1783+invalidate toReconnectRef wis = do
1784+ forM_ wis $ \wi -> do
1785+ mi <- deRefWeak wi
1786+ case mi of
1787+ Nothing -> do
1788+ traceInvalidate "invalidate Dead"
1789+ return () --TODO: Should we clean this up here?
1790+ Just i -> do
1791+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1792+ case i of
1793+ InvalidatorPull p -> do
1794+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
1795+ mVal <- readIORef $ pullValue p
1796+ forM_ mVal $ \val -> do
1797+ writeIORef (pullValue p) Nothing
1798+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1799+ InvalidatorSwitch subscribed -> do
1800+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1801+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1802+ 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
1803+
1804+--------------------------------------------------------------------------------
1805+-- Reflex integration
1806+--------------------------------------------------------------------------------
1807+
1808+-- | The default, global Spider environment
1809+type Spider = SpiderTimeline Global
1810+
1811+-- | Designates the default, global Spider timeline
1812+data Global
1813+
1814+{-# NOINLINE globalSpiderTimeline #-}
1815+globalSpiderTimeline :: SpiderTimeline Global
1816+globalSpiderTimeline = unsafePerformIO unsafeNewSpiderTimeline
1817+
1818+-- | Stores all global data relevant to a particular Spider timeline; only one
1819+-- value should exist for each type @x@
1820+data SpiderTimeline x = SpiderTimeline
1821+ { _spiderTimeline_toUnsubscribe :: !(IORef [EventSubscription x])
1822+ , _spiderTimeline_lock :: !(MVar ())
1823+ , _spiderTimeline_cleanups :: !(IORef [IO ()])
1824+#ifdef DEBUG
1825+ , _spiderTimeline_depth :: !(IORef Int)
1826+#endif
1827+ }
1828+type role SpiderTimeline nominal
1829+
1830+instance GEq SpiderTimeline where
1831+ a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
1832+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimeline can't have two different 'x' arguments
1833+ else Nothing
1834+
1835+unsafeNewSpiderTimeline :: forall x. IO (SpiderTimeline x)
1836+unsafeNewSpiderTimeline = do
1837+ toUnsubscribe <- newIORef []
1838+ lock <- newMVar ()
1839+ cleanups <- newIORef []
1840+#ifdef DEBUG
1841+ depthRef <- newIORef 0
1842+#endif
1843+ return $ SpiderTimeline
1844+ { _spiderTimeline_toUnsubscribe = toUnsubscribe
1845+ , _spiderTimeline_lock = lock
1846+ , _spiderTimeline_cleanups = cleanups
1847+#ifdef DEBUG
1848+ , _spiderTimeline_depth = depthRef
1849+#endif
1850+ }
1851+
1852+-- | Create a new SpiderTimeline
1853+newSpiderTimeline :: IO (Some SpiderTimeline)
1854+newSpiderTimeline = withSpiderTimeline (pure . Some.This)
1855+
1856+-- | Pass a new timeline to the given function.
1857+withSpiderTimeline :: (forall x. SpiderTimeline x -> IO r) -> IO r
1858+withSpiderTimeline k = unsafeNewSpiderTimeline >>= k
1859+
1860+newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1861+
1862+newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1863+
1864+instance Functor (R.Dynamic (SpiderTimeline x)) where
1865+ fmap f = SpiderDynamic . newMapDyn f . unSpiderDynamic
1866+
1867+instance Applicative (R.Dynamic (SpiderTimeline x)) where
1868+ pure = SpiderDynamic . dynamicConst
1869+ SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ zipDynWith ($) a b
1870+ _ *> b = b
1871+ a <* _ = a
1872+
1873+instance Monad (R.Dynamic (SpiderTimeline x)) where
1874+ {-# INLINE return #-}
1875+ return = pure
1876+ {-# INLINE (>>=) #-}
1877+ x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
1878+ {-# INLINE (>>) #-}
1879+ _ >> y = y
1880+ {-# INLINE fail #-}
1881+ fail _ = error "Dynamic does not support 'fail'"
1882+
1883+instance R.Reflex (SpiderTimeline x) where
1884+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
1885+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
1886+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
1887+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
1888+ type PullM (SpiderTimeline x) = SpiderPullM x
1889+ type PushM (SpiderTimeline x) = SpiderPushM x
1890+ {-# INLINABLE never #-}
1891+ never = SpiderEvent eventNever
1892+ {-# INLINABLE constant #-}
1893+ constant = SpiderBehavior . behaviorConst
1894+ {-# INLINABLE push #-}
1895+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
1896+ {-# INLINABLE pull #-}
1897+ pull = SpiderBehavior . pull . coerce
1898+ {-# INLINABLE merge #-}
1899+ merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
1900+ {-# INLINABLE fan #-}
1901+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
1902+ {-# INLINABLE switch #-}
1903+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
1904+ {-# INLINABLE coincidence #-}
1905+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
1906+ {-# INLINABLE current #-}
1907+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
1908+ {-# INLINABLE updated #-}
1909+ updated = SpiderEvent . fmap runIdentity . dynamicUpdated . unSpiderDynamic
1910+ {-# INLINABLE unsafeBuildDynamic #-}
1911+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (coerce readV0) $ coerce $ unSpiderEvent v'
1912+ {-# INLINABLE unsafeBuildIncremental #-}
1913+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
1914+ {-# INLINABLE mergeIncremental #-}
1915+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (R.PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (R.PatchDMap k (Event x))) . unSpiderIncremental
1916+ {-# INLINABLE currentIncremental #-}
1917+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
1918+ {-# INLINABLE updatedIncremental #-}
1919+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
1920+ {-# INLINABLE incrementalToDynamic #-}
1921+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
1922+ c <- readBehaviorUntracked $ dynamicCurrent i
1923+ return $ Identity <$> R.apply p c --TODO: Avoid the redundant 'apply'
1924+ eventCoercion Coercion = Coercion
1925+ behaviorCoercion Coercion = Coercion
1926+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
1927+
1928+instance R.MonadSample (SpiderTimeline x) (EventM x) where
1929+ {-# INLINABLE sample #-}
1930+ sample (SpiderBehavior b) = readBehaviorUntracked b
1931+
1932+instance R.MonadHold (SpiderTimeline x) (EventM x) where
1933+ {-# INLINABLE hold #-}
1934+ hold = holdSpiderEventM
1935+ {-# INLINABLE holdDyn #-}
1936+ holdDyn = holdDynSpiderEventM
1937+ {-# INLINABLE holdIncremental #-}
1938+ holdIncremental = holdIncrementalSpiderEventM
1939+
1940+holdSpiderEventM :: a -> R.Event (SpiderTimeline x) a -> EventM x (R.Behavior (SpiderTimeline x) a)
1941+holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
1942+
1943+holdDynSpiderEventM :: a -> R.Event (SpiderTimeline x) a -> EventM x (R.Dynamic (SpiderTimeline x) a)
1944+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
1945+
1946+holdIncrementalSpiderEventM :: R.Patch p => R.PatchTarget p -> R.Event (SpiderTimeline x) p -> EventM x (R.Incremental (SpiderTimeline x) p)
1947+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ hold v0 $ unSpiderEvent e
1948+
1949+instance R.MonadHold (SpiderTimeline x) (SpiderHost x) where
1950+ {-# INLINABLE hold #-}
1951+ hold v0 e = R.runHostFrame $ R.hold v0 e
1952+ {-# INLINABLE holdDyn #-}
1953+ holdDyn v0 e = R.runHostFrame $ R.holdDyn v0 e
1954+ {-# INLINABLE holdIncremental #-}
1955+ holdIncremental v0 e = R.runHostFrame $ R.holdIncremental v0 e
1956+
1957+instance R.MonadSample (SpiderTimeline x) (SpiderHost x) where
1958+ {-# INLINABLE sample #-}
1959+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
1960+
1961+instance R.MonadSample (SpiderTimeline x) (SpiderPullM x) where
1962+ {-# INLINABLE sample #-}
1963+ sample = coerce . readBehaviorTracked . unSpiderBehavior
1964+
1965+instance R.MonadSample (SpiderTimeline x) (SpiderPushM x) where
1966+ {-# INLINABLE sample #-}
1967+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
1968+
1969+instance R.MonadHold (SpiderTimeline x) (SpiderPushM x) where
1970+ {-# INLINABLE hold #-}
1971+ hold v0 e = R.current <$> R.holdDyn v0 e
1972+ {-# INLINABLE holdDyn #-}
1973+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce e
1974+ {-# INLINABLE holdIncremental #-}
1975+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> hold v0 e
1976+
1977+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
1978+
1979+data SpiderEventHandle x a = SpiderEventHandle
1980+ { spiderEventHandleSubscription :: EventSubscription x
1981+ , spiderEventHandleValue :: IORef (Maybe a)
1982+ }
1983+
1984+instance R.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
1985+ {-# INLINABLE subscribeEvent #-}
1986+ subscribeEvent e = SpiderHostFrame $ do
1987+ --TODO: Unsubscribe eventually (manually and/or with weak ref)
1988+ val <- liftIO $ newIORef Nothing
1989+ subscription <- subscribe (unSpiderEvent e) $ Subscriber
1990+ { subscriberPropagate = \a -> do
1991+ liftIO $ writeIORef val $ Just a
1992+ scheduleClear val
1993+ , subscriberInvalidateHeight = \_ -> return ()
1994+ , subscriberRecalculateHeight = \_ -> return ()
1995+ }
1996+ return $ SpiderEventHandle
1997+ { spiderEventHandleSubscription = subscription
1998+ , spiderEventHandleValue = val
1999+ }
2000+
2001+instance R.ReflexHost (SpiderTimeline x) where
2002+ type EventTrigger (SpiderTimeline x) = RootTrigger x
2003+ type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2004+ type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2005+
2006+instance R.MonadReadEvent (SpiderTimeline x) (ReadPhase x) where
2007+ {-# NOINLINE readEvent #-}
2008+ readEvent h = ReadPhase $ fmap (fmap return) $ liftIO $ do
2009+ result <- readIORef $ spiderEventHandleValue h
2010+ touch h
2011+ return result
2012+
2013+instance MonadRef (EventM x) where
2014+ type Ref (EventM x) = Ref IO
2015+ {-# INLINABLE newRef #-}
2016+ {-# INLINABLE readRef #-}
2017+ {-# INLINABLE writeRef #-}
2018+ newRef = liftIO . newRef
2019+ readRef = liftIO . readRef
2020+ writeRef r a = liftIO $ writeRef r a
2021+
2022+instance MonadAtomicRef (EventM x) where
2023+ {-# INLINABLE atomicModifyRef #-}
2024+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2025+
2026+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2027+newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimeline x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2028+
2029+instance Monad (SpiderHost x) where
2030+ {-# INLINABLE (>>=) #-}
2031+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2032+ {-# INLINABLE (>>) #-}
2033+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2034+ {-# INLINABLE return #-}
2035+ return x = SpiderHost $ return x
2036+ {-# INLINABLE fail #-}
2037+ fail s = SpiderHost $ fail s
2038+
2039+-- | Run an action affecting the global Spider timeline; this will be guarded by
2040+-- a mutex for that timeline
2041+runSpiderHost :: SpiderHost Global a -> IO a
2042+runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimeline
2043+
2044+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2045+-- mutex for that timeline
2046+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimeline x -> IO a
2047+runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2048+
2049+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2050+
2051+instance Monad (SpiderHostFrame x) where
2052+ {-# INLINABLE (>>=) #-}
2053+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2054+ {-# INLINABLE (>>) #-}
2055+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2056+ {-# INLINABLE return #-}
2057+ return x = SpiderHostFrame $ return x
2058+ {-# INLINABLE fail #-}
2059+ fail s = SpiderHostFrame $ fail s
2060+
2061+instance R.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2062+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2063+
2064+instance R.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2065+ {-# INLINABLE hold #-}
2066+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2067+ {-# INLINABLE holdDyn #-}
2068+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2069+ {-# INLINABLE holdIncremental #-}
2070+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ hold v0 $ unSpiderEvent e
2071+
2072+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2073+newEventWithTriggerIO f = do
2074+ es <- newFanEventWithTriggerIO $ \Refl -> f
2075+ return $ select es Refl
2076+
2077+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2078+newFanEventWithTriggerIO f = do
2079+ occRef <- newIORef DMap.empty
2080+ subscribedRef <- newIORef DMap.empty
2081+ let !r = Root
2082+ { rootOccurrence = occRef
2083+ , rootSubscribed = subscribedRef
2084+ , rootInit = f
2085+ }
2086+ return $ EventSelector $ \k -> eventRoot k r
2087+
2088+instance R.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2089+ newEventWithTrigger = SpiderHost . lift . fmap SpiderEvent . newEventWithTriggerIO
2090+ newFanEventWithTrigger f = SpiderHost $ lift $ do
2091+ es <- newFanEventWithTriggerIO f
2092+ return $ R.EventSelector $ SpiderEvent . select es
2093+
2094+instance R.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2095+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2096+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2097+ es <- newFanEventWithTriggerIO f
2098+ return $ R.EventSelector $ SpiderEvent . select es
2099+
2100+instance R.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2101+ {-# INLINABLE subscribeEvent #-}
2102+ subscribeEvent = runFrame . runSpiderHostFrame . R.subscribeEvent
2103+
2104+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2105+
2106+instance R.MonadSample (SpiderTimeline x) (ReadPhase x) where
2107+ {-# INLINABLE sample #-}
2108+ sample = ReadPhase . R.sample
2109+
2110+instance R.MonadHold (SpiderTimeline x) (ReadPhase x) where
2111+ {-# INLINABLE hold #-}
2112+ hold v0 e = ReadPhase $ R.hold v0 e
2113+ {-# INLINABLE holdDyn #-}
2114+ holdDyn v0 e = ReadPhase $ R.holdDyn v0 e
2115+ {-# INLINABLE holdIncremental #-}
2116+ holdIncremental v0 e = ReadPhase $ R.holdIncremental v0 e
2117+
2118+instance R.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2119+ type ReadPhase (SpiderHost x) = ReadPhase x
2120+ fireEventsAndRead es (ReadPhase a) = run es a
2121+ runHostFrame = runFrame . runSpiderHostFrame
2122+
2123+instance MonadRef (SpiderHost x) where
2124+ type Ref (SpiderHost x) = Ref IO
2125+ newRef = SpiderHost . newRef
2126+ readRef = SpiderHost . readRef
2127+ writeRef r = SpiderHost . writeRef r
2128+
2129+instance MonadAtomicRef (SpiderHost x) where
2130+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2131+
2132+instance MonadRef (SpiderHostFrame x) where
2133+ type Ref (SpiderHostFrame x) = Ref IO
2134+ newRef = SpiderHostFrame . newRef
2135+ readRef = SpiderHostFrame . readRef
2136+ writeRef r = SpiderHostFrame . writeRef r
2137+
2138+instance MonadAtomicRef (SpiderHostFrame x) where
2139+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2140+
2141+instance PrimMonad (SpiderHostFrame x) where
2142+ type PrimState (SpiderHostFrame x) = PrimState IO
2143+ primitive = SpiderHostFrame . EventM . primitive
2144+
2145+--------------------------------------------------------------------------------
2146+-- Deprecated items
2147+--------------------------------------------------------------------------------
2148+
2149+{-# DEPRECATED SpiderEnv "Use 'SpiderTimeline' instead" #-}
2150+type SpiderEnv = SpiderTimeline