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