@@ -0,0 +1,2681 @@
1+{-# LANGUAGE BangPatterns #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE EmptyDataDecls #-}
5+{-# LANGUAGE ExistentialQuantification #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE FunctionalDependencies #-}
10+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11+{-# LANGUAGE LambdaCase #-}
12+{-# LANGUAGE MultiWayIf #-}
13+{-# LANGUAGE RankNTypes #-}
14+{-# LANGUAGE RoleAnnotations #-}
15+{-# LANGUAGE ScopedTypeVariables #-}
16+{-# LANGUAGE TypeFamilies #-}
17+{-# LANGUAGE TypeOperators #-}
18+{-# LANGUAGE UndecidableInstances #-}
19+{-# LANGUAGE PolyKinds #-}
20+{-# LANGUAGE InstanceSigs #-}
22+#ifdef USE_REFLEX_OPTIMIZER
23+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
25+{-# OPTIONS_GHC -Wunused-binds #-}
26+-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
27+-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
28+module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
30+#if MIN_VERSION_base(4,10,0)
31+import Control.Applicative (liftA2)
33+import Control.Concurrent
34+import Control.Exception
35+import Control.Monad hiding (forM, forM_, mapM, mapM_)
36+import Control.Monad.Exception
37+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
38+import Control.Monad.Primitive
39+import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_)
40+import Control.Monad.Ref
43+import Data.Dependent.Map (DMap, DSum (..))
44+import qualified Data.Dependent.Map as DMap
45+import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
46+import qualified Data.FastMutableIntMap as FastMutableIntMap
47+import Data.Foldable hiding (concat, elem, sequence_)
48+import Data.Functor.Constant
49+import Data.Functor.Misc
50+import Data.Functor.Product
51+import Data.GADT.Compare
52+import Data.IntMap.Strict (IntMap)
53+import qualified Data.IntMap.Strict as IntMap
55+import Data.Kind (Type)
56+import Data.Maybe hiding (mapMaybe)
57+import Data.Monoid ((<>))
60+import Data.Traversable
61+import Data.Witherable (Filterable, mapMaybe)
63+import GHC.IORef (IORef (..))
65+import Reflex.FastWeak
66+import System.IO.Unsafe
67+import System.Mem.Weak
70+#if defined(MIN_VERSION_semialign)
71+#if MIN_VERSION_these(0,8,0)
72+import Data.These.Combinators (justThese)
77+import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
78+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
79+import qualified Data.List.NonEmpty as NonEmpty
80+import Data.Monoid (mempty)
81+import Data.Tree (Forest, Tree (..), drawForest)
84+import Data.FastWeakBag (FastWeakBag)
85+import qualified Data.FastWeakBag as FastWeakBag
86+import Data.Reflection
87+import Data.Some (Some(Some))
88+import Data.Type.Coercion
89+import Data.Profunctor.Unsafe ((#.), (.#))
90+import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
91+import qualified Data.WeakBag as WeakBag
92+import qualified Reflex.Class
93+import qualified Reflex.Class as R
94+import qualified Reflex.Host.Class
95+import Reflex.NotReady.Class
97+import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
99+#ifdef DEBUG_TRACE_EVENTS
100+import qualified Data.ByteString.Char8 as BS8
101+import System.IO (stderr)
104+#ifdef DEBUG_TRACE_EVENTS
106+withStackOneLine :: (BS8.ByteString -> a) -> a
107+withStackOneLine expr = unsafePerformIO $ do
108+ stack <- currentCallStack
109+ return (expr (BS8.pack (unwords (reverse stack))))
113+debugPropagate :: Bool
115+debugInvalidateHeight :: Bool
117+debugInvalidate :: Bool
121+#define DEBUG_NODEIDS
123+debugPropagate = True
125+debugInvalidateHeight = False
127+debugInvalidate = True
129+class HasNodeId a where
130+ getNodeId :: a -> Int
132+instance HasNodeId (Hold x p a) where
133+ getNodeId = holdNodeId
135+instance HasNodeId (PushSubscribed x a b) where
136+ getNodeId = pushSubscribedNodeId
138+instance HasNodeId (SwitchSubscribed x a) where
139+ getNodeId = switchSubscribedNodeId
141+instance HasNodeId (FanSubscribed x a) where
142+ getNodeId = fanSubscribedNodeId
144+instance HasNodeId (CoincidenceSubscribed x a) where
145+ getNodeId = coincidenceSubscribedNodeId
147+instance HasNodeId (RootSubscribed x a) where
148+ getNodeId = rootSubscribedNodeId
150+instance HasNodeId (Pull x a) where
151+ getNodeId = pullNodeId
153+{-# INLINE showNodeId #-}
154+showNodeId :: HasNodeId a => a -> String
155+showNodeId = ("#"<>) . show . getNodeId
157+showSubscriberType :: Subscriber x a -> String
158+showSubscriberType = \case
159+ SubscriberPush _ _ -> "SubscriberPush"
160+ SubscriberMerge _ _ -> "SubscriberMerge"
161+ SubscriberFan _ -> "SubscriberFan"
162+ SubscriberMergeChange _ -> "SubscriberMergeChange"
163+ SubscriberHold _ -> "SubscriberHold"
164+ SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
165+ SubscriberSwitch _ -> "SubscriberSwitch"
166+ SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
167+ SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
168+ SubscriberHandle -> "SubscriberHandle"
170+showEventType :: Event x a -> String
171+showEventType = \case
172+ EventRoot _ _ -> "EventRoot"
173+ EventNever -> "EventNever"
174+ EventPush _ -> "EventPush"
175+ EventMerge _ -> "EventMerge"
176+ EventFan _ _ -> "EventFan"
177+ EventSwitch _ -> "EventSwitch"
178+ EventCoincidence _ -> "EventCoincidence"
179+ EventHold _ -> "EventHold"
180+ EventDyn _ -> "EventDyn"
181+ EventHoldIdentity _ -> "EventHoldIdentity"
182+ EventDynIdentity _ -> "EventDynIdentity"
186+debugPropagate = False
188+debugInvalidateHeight = False
190+debugInvalidate = False
192+-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
193+{-# INLINE showNodeId #-}
194+showNodeId :: a -> String
200+{-# NOINLINE nextNodeIdRef #-}
201+nextNodeIdRef :: IORef Int
202+nextNodeIdRef = unsafePerformIO $ newIORef 1
205+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
208+--------------------------------------------------------------------------------
210+--------------------------------------------------------------------------------
212+--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
213+-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
214+data EventSubscription x = EventSubscription
215+ { _eventSubscription_unsubscribe :: !(IO ())
216+ , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
219+unsubscribe :: EventSubscription x -> IO ()
220+unsubscribe (EventSubscription u _) = u
222+--------------------------------------------------------------------------------
224+--------------------------------------------------------------------------------
226+newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
228+{-# INLINE subscribeAndRead #-}
229+subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
230+subscribeAndRead = unEvent
233+"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
234+"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
235+"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
238+-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
239+-- caching; if the computation function is very cheap, this is (much) more
240+-- efficient than 'push'
241+{-# INLINE [1] pushCheap #-}
242+pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
243+pushCheap !f e = Event $ \sub -> do
244+ (subscription, occ) <- subscribeAndRead e $ sub
245+ { subscriberPropagate = \a -> do
247+ mapM_ (subscriberPropagate sub) mb
249+ occ' <- join <$> mapM f occ
250+ return (subscription, occ')
252+-- | A subscriber that never triggers other 'Event's
253+{-# INLINE terminalSubscriber #-}
254+terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
255+terminalSubscriber p = Subscriber
256+ { subscriberPropagate = p
257+ , subscriberInvalidateHeight = \_ -> return ()
258+ , subscriberRecalculateHeight = \_ -> return ()
261+-- | Subscribe to an Event only for the duration of one occurrence
262+{-# INLINE subscribeAndReadHead #-}
263+subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
264+subscribeAndReadHead e sub = do
265+ subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
266+ (subscription, occ) <- subscribeAndRead e $ sub
267+ { subscriberPropagate = \a -> do
268+ liftIO $ unsubscribe =<< readIORef subscriptionRef
269+ subscriberPropagate sub a
271+ liftIO $ case occ of
272+ Nothing -> writeIORef subscriptionRef $! subscription
273+ Just _ -> unsubscribe subscription
274+ return (subscription, occ)
276+--TODO: Make this lazy in its input event
277+headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
279+ parent <- liftIO $ newIORef $ Just originalE
280+ defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
281+ let clearParent = liftIO $ writeIORef parent Nothing
282+ (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ \_ -> clearParent
283+ when (isJust occ) clearParent
284+ return $ Event $ \sub -> do
285+ liftIO (readIORef parent) >>= \case
286+ Nothing -> return (EventSubscription (return ()) $ EventSubscribed zeroRef $ toAny (), Nothing)
287+ Just e -> subscribeAndReadHead e sub
289+data CacheSubscribed x a
290+ = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
291+ , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
292+ , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
295+-- | Construct an 'Event' whose value is guaranteed not to be recomputed
298+--TODO: Try a caching strategy where we subscribe directly to the parent when
299+--there's only one subscriber, and then build our own FastWeakBag only when a second
301+{-# NOINLINE [0] cacheEvent #-}
302+cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
304+#ifdef DEBUG_TRACE_EVENTS
305+ withStackOneLine $ \callSite -> Event $
309+ unsafePerformIO $ do
310+ mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
311+ <- newIORef emptyFastWeak
312+ pure $ \sub -> {-# SCC "cacheEvent" #-} do
313+#ifdef DEBUG_TRACE_EVENTS
314+ unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
316+ subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
317+ Just subscribedTicket -> return subscribedTicket
319+ subscribers <- liftIO FastWeakBag.empty
320+ occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
321+ (parentSub, occ) <- subscribeAndRead e $ Subscriber
322+ { subscriberPropagate = \a -> do
323+ liftIO $ writeIORef occRef $ Just a
324+ scheduleClear occRef
325+ propagateFast a subscribers
326+ , subscriberInvalidateHeight = \old -> do
327+ FastWeakBag.traverse subscribers $ invalidateSubscriberHeight old
328+ , subscriberRecalculateHeight = \new -> do
329+ FastWeakBag.traverse subscribers $ recalculateSubscriberHeight new
331+ when (isJust occ) $ do
332+ liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
333+ scheduleClear occRef
334+ let !subscribed = CacheSubscribed
335+ { _cacheSubscribed_subscribers = subscribers
336+ , _cacheSubscribed_parent = parentSub
337+ , _cacheSubscribed_occurrence = occRef
339+ subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
340+ liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
341+ return subscribedTicket
343+ subscribed <- getFastWeakTicketValue subscribedTicket
344+ ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
345+ occ <- readIORef $ _cacheSubscribed_occurrence subscribed
346+ let es = EventSubscription
347+ { _eventSubscription_unsubscribe = do
348+ FastWeakBag.remove ticket
349+ isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
351+ writeIORef mSubscribedRef emptyFastWeak
352+ unsubscribe $ _cacheSubscribed_parent subscribed
354+ touch subscribedTicket
355+ , _eventSubscription_subscribed = EventSubscribed
356+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
357+ , eventSubscribedRetained = toAny subscribedTicket
362+subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
363+subscribe e s = fst <$> subscribeAndRead e s
366+wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
367+wrap tag getSpecificSubscribed sub = do
368+ (sln, subd, occ) <- getSpecificSubscribed sub
370+ return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
372+eventRoot :: GCompare k => k a -> Root x k -> Event x a
373+eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
375+eventNever :: Event x a
376+eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
378+eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)
379+eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
381+eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
382+eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
384+eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
385+eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
387+eventHold :: Hold x p -> Event x p
388+eventHold !h = Event $ subscribeHoldEvent h
390+eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
391+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
393+{-# INLINE subscribeCoincidenceInner #-}
394+subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
395+subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
396+ subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
397+ (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
398+ innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
399+ let height = max innerHeight outerHeight
400+ defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
401+ return (innerOcc, height, innerSubd)
403+--------------------------------------------------------------------------------
405+--------------------------------------------------------------------------------
407+data Subscriber x a = Subscriber
408+ { subscriberPropagate :: !(a -> EventM x ())
409+ , subscriberInvalidateHeight :: !(Height -> IO ())
410+ , subscriberRecalculateHeight :: !(Height -> IO ())
413+--TODO: Move this comment to WeakBag
414+-- These function are constructor functions that are marked NOINLINE so they are
415+-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
416+-- so any weak references that are attached to the constructors will have their
417+-- finalizer run. Using the opaque constructor, does not see the
418+-- constructor application, so it behaves like an IORef and cannot be fused away.
420+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
421+-- the weak pointer to it in some cases.
423+newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
424+newSubscriberHold h = return $ Subscriber
425+ { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
426+ , subscriberInvalidateHeight = \_ -> return ()
427+ , subscriberRecalculateHeight = \_ -> return ()
430+newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
431+newSubscriberFan subscribed = return $ Subscriber
432+ { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
433+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
434+ tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
435+ liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
436+ scheduleClear $ fanSubscribedOccurrence subscribed
437+ let f _ (Pair v subsubs) = do
438+ propagate v $ _fanSubscribedChildren_list subsubs
439+ return $ Constant ()
440+ _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
442+ , subscriberInvalidateHeight = \old -> do
443+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
444+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
445+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
446+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
447+ , subscriberRecalculateHeight = \new -> do
448+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
449+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
450+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
451+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
454+newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
455+newSubscriberSwitch subscribed = return $ Subscriber
456+ { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
457+ tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
458+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
459+ scheduleClear $ switchSubscribedOccurrence subscribed
460+ propagate a $ switchSubscribedSubscribers subscribed
461+ , subscriberInvalidateHeight = \_ -> do
462+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
463+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
464+ when (oldHeight /= invalidHeight) $ do
465+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
466+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
467+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
468+ , subscriberRecalculateHeight = \new -> do
469+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
470+ updateSwitchHeight new subscribed
471+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
474+newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
475+newSubscriberCoincidenceOuter subscribed = return $ Subscriber
476+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
477+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
478+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
479+ tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
480+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
481+ tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
482+ tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
483+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
484+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
487+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
488+ writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
489+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
490+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
491+ Just o -> do -- Since it's already firing, no need to adjust height
492+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
493+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
494+ propagate o $ coincidenceSubscribedSubscribers subscribed
495+ , subscriberInvalidateHeight = \_ -> do
496+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
497+ invalidateCoincidenceHeight subscribed
498+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
499+ , subscriberRecalculateHeight = \_ -> do
500+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
501+ recalculateCoincidenceHeight subscribed
502+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
505+newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
506+newSubscriberCoincidenceInner subscribed = return $ Subscriber
507+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
508+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
509+ occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
511+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
513+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
514+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
515+ propagate a $ coincidenceSubscribedSubscribers subscribed
516+ , subscriberInvalidateHeight = \_ -> do
517+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
518+ invalidateCoincidenceHeight subscribed
519+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
520+ , subscriberRecalculateHeight = \_ -> do
521+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
522+ recalculateCoincidenceHeight subscribed
523+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
526+invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
527+invalidateSubscriberHeight = flip subscriberInvalidateHeight
529+recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
530+recalculateSubscriberHeight = flip subscriberRecalculateHeight
532+-- | Propagate everything at the current height
533+propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
534+propagate a subscribers = withIncreasedDepth $ do
535+ -- 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
536+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
537+ WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
539+-- | Propagate everything at the current height
540+propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
541+propagateFast a subscribers = withIncreasedDepth $ do
542+ -- 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
543+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
544+ FastWeakBag.traverse subscribers $ \s -> subscriberPropagate s a
546+--------------------------------------------------------------------------------
548+--------------------------------------------------------------------------------
553+data EventSubscribed x = EventSubscribed
554+ { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
555+ , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
557+ , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
558+ , eventSubscribedHasOwnHeightRef :: !Bool
559+ , eventSubscribedWhoCreated :: !(IO [String])
563+eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
564+eventSubscribedRoot !r = EventSubscribed
565+ { eventSubscribedHeightRef = zeroRef
566+ , eventSubscribedRetained = toAny r
568+ , eventSubscribedGetParents = return []
569+ , eventSubscribedHasOwnHeightRef = False
570+ , eventSubscribedWhoCreated = return ["root"]
574+eventSubscribedNever :: EventSubscribed x
575+eventSubscribedNever = EventSubscribed
576+ { eventSubscribedHeightRef = zeroRef
577+ , eventSubscribedRetained = toAny ()
579+ , eventSubscribedGetParents = return []
580+ , eventSubscribedHasOwnHeightRef = False
581+ , eventSubscribedWhoCreated = return ["never"]
585+eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
586+eventSubscribedFan !subscribed = EventSubscribed
587+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
588+ , eventSubscribedRetained = toAny subscribed
590+ , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
591+ , eventSubscribedHasOwnHeightRef = False
592+ , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
596+eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
597+eventSubscribedSwitch !subscribed = EventSubscribed
598+ { eventSubscribedHeightRef = switchSubscribedHeight subscribed
599+ , eventSubscribedRetained = toAny subscribed
601+ , eventSubscribedGetParents = do
602+ s <- readIORef $ switchSubscribedCurrentParent subscribed
603+ return [Some $ _eventSubscription_subscribed s]
604+ , eventSubscribedHasOwnHeightRef = True
605+ , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
609+eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
610+eventSubscribedCoincidence !subscribed = EventSubscribed
611+ { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
612+ , eventSubscribedRetained = toAny subscribed
614+ , eventSubscribedGetParents = do
615+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
616+ let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
617+ innerParents = maybeToList $ fmap Some innerSubscription
618+ return $ outerParent : innerParents
619+ , eventSubscribedHasOwnHeightRef = True
620+ , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
624+getEventSubscribedHeight :: EventSubscribed x -> IO Height
625+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
628+whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
629+whoCreatedEventSubscribed = eventSubscribedWhoCreated
631+walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
632+walkInvalidHeightParents s0 = do
633+ subscribers <- flip execStateT mempty $ ($ Some s0) $ fix $ \loop (Some s) -> do
634+ h <- liftIO $ readIORef $ eventSubscribedHeightRef s
635+ when (h == invalidHeight) $ do
636+ when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
638+ mapM_ loop =<< liftIO (eventSubscribedGetParents s)
639+ forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
643+{-# INLINE subscribeHoldEvent #-}
644+subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
645+subscribeHoldEvent = subscribeAndRead . holdEvent
647+--------------------------------------------------------------------------------
649+--------------------------------------------------------------------------------
651+newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
653+behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
654+behaviorHold !h = Behavior $ readHoldTracked h
656+behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
657+behaviorHoldIdentity = behaviorHold
659+behaviorConst :: a -> Behavior x a
660+behaviorConst !a = Behavior $ return a
662+behaviorPull :: Pull x a -> Behavior x a
663+behaviorPull !p = Behavior $ do
664+ val <- liftIO $ readIORef $ pullValue p
666+ Just subscribed -> do
667+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
668+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
669+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
670+ return $ pullSubscribedValue subscribed
672+ i <- liftIO $ newInvalidatorPull p
673+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
674+ parentsRef <- liftIO $ newIORef []
675+ holdInits <- askBehaviorHoldInits
676+ a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
677+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
678+ parents <- liftIO $ readIORef parentsRef
679+ let subscribed = PullSubscribed
680+ { pullSubscribedValue = a
681+ , pullSubscribedInvalidators = invsRef
682+ , pullSubscribedOwnInvalidator = i
683+ , pullSubscribedParents = parents
685+ liftIO $ writeIORef (pullValue p) $ Just subscribed
686+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
689+behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
690+behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
692+{-# INLINE readHoldTracked #-}
693+readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
694+readHoldTracked h = do
695+ result <- liftIO $ readIORef $ holdValue h
696+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
697+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
698+ liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
701+{-# INLINABLE readBehaviorUntracked #-}
702+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
703+readBehaviorUntracked b = do
704+ holdInits <- getDeferralQueue
705+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
707+--------------------------------------------------------------------------------
709+--------------------------------------------------------------------------------
711+data Dynamic x p = Dynamic
712+ { dynamicCurrent :: !(Behavior x (PatchTarget p))
713+ , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
716+dynamicHold :: Hold x p -> Dynamic x p
717+dynamicHold !h = Dynamic
718+ { dynamicCurrent = behaviorHold h
719+ , dynamicUpdated = eventHold h
722+dynamicHoldIdentity :: Hold x (Identity a) -> Dynamic x (Identity a)
723+dynamicHoldIdentity = dynamicHold
725+dynamicConst :: PatchTarget p -> Dynamic x p
726+dynamicConst !a = Dynamic
727+ { dynamicCurrent = behaviorConst a
728+ , dynamicUpdated = eventNever
731+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
732+dynamicDyn !d = Dynamic
733+ { dynamicCurrent = behaviorDyn d
734+ , dynamicUpdated = eventDyn d
737+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
738+dynamicDynIdentity = dynamicDyn
740+--------------------------------------------------------------------------------
742+--------------------------------------------------------------------------------
744+--TODO: Figure out why certain things are not 'representational', then make them
745+--representational so we can use coerce
747+--type role Hold representational
749+ = Hold { holdValue :: !(IORef (PatchTarget p))
750+ , holdInvalidators :: !(IORef [Weak (Invalidator x)])
751+ , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
752+ , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
758+-- | A statically allocated 'SpiderTimeline'
761+{-# NOINLINE globalSpiderTimelineEnv #-}
762+globalSpiderTimelineEnv :: SpiderTimelineEnv Global
763+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
765+-- | Stores all global data relevant to a particular Spider timeline; only one
766+-- value should exist for each type @x@
767+data SpiderTimelineEnv x = SpiderTimelineEnv
768+ { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
769+ , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
771+ , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
774+type role SpiderTimelineEnv nominal
776+instance Eq (SpiderTimelineEnv x) where
777+ _ == _ = True -- Since only one exists of each type
779+instance GEq SpiderTimelineEnv where
780+ a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
781+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
785+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
786+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
787+ , eventEnvDynInits :: !(IORef [SomeDynInit x])
788+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
789+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
790+ , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
791+ , eventEnvIntClears :: !(IORef [Some IntClear])
792+ , eventEnvRootClears :: !(IORef [Some RootClear])
793+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
794+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
795+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
798+{-# INLINE runEventM #-}
799+runEventM :: EventM x a -> IO a
802+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
803+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
805+class MonadIO m => Defer a m where
806+ getDeferralQueue :: m (IORef [a])
809+defer :: Defer a m => a -> m ()
811+ q <- getDeferralQueue
812+ liftIO $ modifyIORef' q (a:)
814+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
815+ {-# INLINE getDeferralQueue #-}
816+ getDeferralQueue = asksEventEnv eventEnvAssignments
818+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
819+ {-# INLINE getDeferralQueue #-}
820+ getDeferralQueue = asksEventEnv eventEnvHoldInits
822+instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
823+ {-# INLINE getDeferralQueue #-}
824+ getDeferralQueue = asksEventEnv eventEnvDynInits
826+instance Defer (SomeHoldInit x) (BehaviorM x) where
827+ {-# INLINE getDeferralQueue #-}
828+ getDeferralQueue = BehaviorM $ asks snd
830+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
831+ {-# INLINE getDeferralQueue #-}
832+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
834+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
835+ {-# INLINE getDeferralQueue #-}
836+ getDeferralQueue = asksEventEnv eventEnvMergeInits
838+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
839+ getCurrentHeight :: m Height
840+ scheduleMerge :: Height -> EventM x () -> m ()
842+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
843+ {-# INLINE getCurrentHeight #-}
844+ getCurrentHeight = do
845+ heightRef <- asksEventEnv eventEnvCurrentHeight
846+ liftIO $ readIORef heightRef
847+ {-# INLINE scheduleMerge #-}
848+ scheduleMerge height subscribed = do
849+ delayedRef <- asksEventEnv eventEnvDelayedMerges
850+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
852+class HasSpiderTimeline x where
853+ -- | Retrieve the current SpiderTimelineEnv
854+ spiderTimeline :: SpiderTimelineEnv x
856+instance HasSpiderTimeline Global where
857+ spiderTimeline = globalSpiderTimelineEnv
859+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
860+putCurrentHeight h = do
861+ heightRef <- asksEventEnv eventEnvCurrentHeight
862+ liftIO $ writeIORef heightRef $! h
864+instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
865+ {-# INLINE getDeferralQueue #-}
866+ getDeferralQueue = asksEventEnv eventEnvClears
868+{-# INLINE scheduleClear #-}
869+scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
870+scheduleClear r = defer $ Some $ Clear r
872+instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
873+ {-# INLINE getDeferralQueue #-}
874+ getDeferralQueue = asksEventEnv eventEnvIntClears
876+{-# INLINE scheduleIntClear #-}
877+scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
878+scheduleIntClear r = defer $ Some $ IntClear r
880+instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
881+ {-# INLINE getDeferralQueue #-}
882+ getDeferralQueue = asksEventEnv eventEnvRootClears
884+{-# INLINE scheduleRootClear #-}
885+scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
886+scheduleRootClear r = defer $ Some $ RootClear r
888+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
889+ {-# INLINE getDeferralQueue #-}
890+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
892+-- Note: hold cannot examine its event until after the phase is over
893+{-# INLINE [1] hold #-}
894+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
896+ valRef <- liftIO $ newIORef v0
897+ invsRef <- liftIO $ newIORef []
898+ parentRef <- liftIO $ newIORef Nothing
900+ nodeId <- liftIO newNodeId
903+ { holdValue = valRef
904+ , holdInvalidators = invsRef
906+ , holdParent = parentRef
908+ , holdNodeId = nodeId
911+ defer $ SomeHoldInit h
914+{-# INLINE getHoldEventSubscription #-}
915+getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
916+getHoldEventSubscription h = do
917+ ep <- liftIO $ readIORef $ holdParent h
919+ Just subd -> return subd
922+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
923+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
924+ liftIO $ writeIORef subscriptionRef $! subscription
926+ Nothing -> return ()
928+ old <- liftIO $ readIORef $ holdValue h
930+ Nothing -> return ()
932+ -- Need to evaluate these so that we don't retain the Hold itself
933+ v <- liftIO $ evaluate $ holdValue h
934+ i <- liftIO $ evaluate $ holdInvalidators h
935+ defer $ SomeAssignment v i new
936+ liftIO $ writeIORef (holdParent h) $ Just subscription
939+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
941+--type role BehaviorM representational
942+-- BehaviorM can sample behaviors
943+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
945+instance Monad (BehaviorM x) where
946+ {-# INLINE (>>=) #-}
947+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
949+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
950+ {-# INLINE return #-}
951+ return x = BehaviorM $ return x
953+ fail s = BehaviorM $ fail s
955+data BehaviorSubscribed x a
956+ = forall p. BehaviorSubscribedHold (Hold x p)
957+ | BehaviorSubscribedPull (PullSubscribed x a)
959+newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
961+--type role PullSubscribed representational
962+data PullSubscribed x a
963+ = PullSubscribed { pullSubscribedValue :: !a
964+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
965+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
966+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
969+--type role Pull representational
971+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
972+ , pullCompute :: !(BehaviorM x a)
979+ = forall a. InvalidatorPull (Pull x a)
980+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
982+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
983+ { rootSubscribedKey :: !(k a)
984+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
985+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
986+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
987+ , rootSubscribedUninit :: IO ()
988+ , 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?
990+ , rootSubscribedNodeId :: Int
995+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
996+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
997+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
1000+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1002+data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1004+data SomeMergeUpdate x = SomeMergeUpdate
1005+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1006+ , _someMergeUpdate_invalidateHeight :: !(IO ())
1007+ , _someMergeUpdate_recalculateHeight :: !(IO ())
1010+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1012+-- EventM can do everything BehaviorM can, plus create holds
1013+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
1015+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1017+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1018+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1019+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1022+data HeightBag = HeightBag
1023+ { _heightBag_size :: {-# UNPACK #-} !Int
1024+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1026+ deriving (Show, Read, Eq, Ord)
1028+heightBagEmpty :: HeightBag
1029+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1031+heightBagSize :: HeightBag -> Int
1032+heightBagSize = _heightBag_size
1034+heightBagFromList :: [Height] -> HeightBag
1035+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1037+heightBagAdd :: Height -> HeightBag -> HeightBag
1038+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1040+heightBagRemove :: Height -> HeightBag -> HeightBag
1041+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1042+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1043+ Just old -> HeightBag (pred s) $ case old of
1044+ 0 -> IntMap.delete h c
1045+ _ -> IntMap.insert h (pred old) c
1047+heightBagMax :: HeightBag -> Height
1048+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1049+ Just ((h, _), _) -> Height h
1050+ Nothing -> zeroHeight
1052+heightBagVerify :: HeightBag -> HeightBag
1054+heightBagVerify b@(HeightBag s c) = if
1055+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1056+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1057+ | unHeight invalidHeight `IntMap.member` c
1058+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1061+heightBagVerify = id
1064+data FanSubscribedChildren x k v a = FanSubscribedChildren
1065+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1066+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1067+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
1070+data FanSubscribed x k v
1071+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1072+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1073+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
1074+ , fanSubscribedParent :: !(EventSubscription x)
1075+#ifdef DEBUG_NODEIDS
1076+ , fanSubscribedNodeId :: Int
1081+ = Fan { fanParent :: !(Event x (DMap k v))
1082+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1085+data SwitchSubscribed x a
1086+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1087+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1088+ , switchSubscribedHeight :: !(IORef Height)
1089+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1090+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1091+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1092+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1093+ , switchSubscribedParent :: !(Behavior x (Event x a))
1094+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1095+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1096+#ifdef DEBUG_NODEIDS
1097+ , switchSubscribedNodeId :: Int
1102+ = Switch { switchParent :: !(Behavior x (Event x a))
1103+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1106+#ifdef USE_TEMPLATE_HASKELL
1107+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1109+data CoincidenceSubscribed x a
1110+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1111+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1112+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1113+ , coincidenceSubscribedHeight :: !(IORef Height)
1114+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1115+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1116+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1117+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1118+#ifdef DEBUG_NODEIDS
1119+ , coincidenceSubscribedNodeId :: Int
1123+data Coincidence x a
1124+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1125+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1128+{-# NOINLINE newInvalidatorSwitch #-}
1129+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1130+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1132+{-# NOINLINE newInvalidatorPull #-}
1133+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1134+newInvalidatorPull p = return $! InvalidatorPull p
1136+instance HasSpiderTimeline x => Filterable (Event x) where
1137+ mapMaybe f = push $ return . f
1139+instance HasSpiderTimeline x => Align (Event x) where
1141+#if MIN_VERSION_these(0, 8, 0)
1142+instance HasSpiderTimeline x => Semialign (Event x) where
1144+ align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1145+ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1147+#if defined(MIN_VERSION_semialign)
1148+ zip x y = mapMaybe justThese $ align x y
1151+data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1152+ | BuildDyn !(EventM x (PatchTarget p), Event x p)
1153+ | HoldDyn !(Hold x p)
1155+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1157+newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1158+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1160+--TODO: Avoid the duplication between this and R.zipDynWith
1161+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1162+zipDynWith f da db =
1163+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1164+ ec = flip push eab $ \o -> do
1165+ (a, b) <- case o of
1166+ This (Identity a) -> do
1167+ b <- readBehaviorUntracked $ dynamicCurrent db
1169+ That (Identity b) -> do
1170+ a <- readBehaviorUntracked $ dynamicCurrent da
1172+ These (Identity a) (Identity b) -> return (a, b)
1173+ return $ Just $ Identity $ f a b
1174+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1176+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1177+buildDynamic readV0 v' = do
1178+ result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1179+ let !d = Dyn result
1180+ defer $ SomeDynInit d
1183+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1184+unsafeBuildDynamic readV0 v' =
1185+ Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
1187+-- ResultM can read behaviors and events
1188+type ResultM = EventM
1190+instance HasSpiderTimeline x => Functor (Event x) where
1191+ fmap f = push $ return . Just . f
1193+instance Functor (Behavior x) where
1194+ fmap f = pull . fmap f . readBehaviorTracked
1197+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1198+push f e = cacheEvent (pushCheap f e)
1200+{-# INLINABLE pull #-}
1201+pull :: BehaviorM x a -> Behavior x a
1202+pull a = unsafePerformIO $ do
1203+ ref <- newIORef Nothing
1204+#ifdef DEBUG_NODEIDS
1207+ pure $ behaviorPull $ Pull
1210+#ifdef DEBUG_NODEIDS
1215+{-# INLINABLE switch #-}
1216+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1217+switch a = unsafePerformIO $ do
1218+ ref <- newIORef Nothing
1219+ pure $ eventSwitch $ Switch
1221+ , switchSubscribed = ref
1224+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1225+coincidence a = unsafePerformIO $ do
1226+ ref <- newIORef Nothing
1227+ pure $ eventCoincidence $ Coincidence
1228+ { coincidenceParent = a
1229+ , coincidenceSubscribed = ref
1232+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1233+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1234+run roots after = do
1235+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1236+ let t = spiderTimeline :: SpiderTimelineEnv x
1237+ result <- SpiderHost $ withMVar (_spiderTimeline_lock t) $ \_ -> unSpiderHost $ runFrame $ do
1238+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1239+ occBefore <- liftIO $ do
1240+ occBefore <- readIORef occRef
1241+ writeIORef occRef $! DMap.insert k a occBefore
1243+ if DMap.null occBefore
1244+ then do scheduleRootClear occRef
1246+ else return Nothing
1247+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1248+ propagate a subscribersRef
1249+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1251+ delayed <- liftIO $ readIORef delayedRef
1252+ case IntMap.minViewWithKey delayed of
1253+ Nothing -> return ()
1254+ Just ((currentHeight, cur), future) -> do
1255+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1256+ putCurrentHeight $ Height currentHeight
1257+ liftIO $ writeIORef delayedRef $! future
1261+ putCurrentHeight maxBound
1263+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1266+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1267+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1268+ height <- liftIO $ readIORef heightRef
1269+ currentHeight <- getCurrentHeight
1270+ case height `compare` currentHeight of
1271+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1272+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1275+newtype Clear a = Clear (IORef (Maybe a))
1277+newtype IntClear a = IntClear (IORef (IntMap a))
1279+newtype RootClear k = RootClear (IORef (DMap k Identity))
1281+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1283+debugFinalize :: Bool
1284+debugFinalize = False
1286+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1287+mkWeakPtrWithDebug x debugNote = do
1291+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1294+type WeakList a = [Weak a]
1296+{-# INLINE withIncreasedDepth #-}
1298+withIncreasedDepth :: CanTrace x m => m a -> m a
1299+withIncreasedDepth a = do
1300+ spiderTimeline <- askSpiderTimelineEnv
1301+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1303+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1306+withIncreasedDepth :: m a -> m a
1307+withIncreasedDepth = id
1310+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1312+{-# INLINE tracePropagate #-}
1313+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1314+tracePropagate p = traceWhen p debugPropagate
1316+{-# INLINE traceInvalidate #-}
1317+traceInvalidate :: String -> IO ()
1318+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1320+{-# INLINE traceWhen #-}
1321+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1322+traceWhen p b message = traceMWhen p b $ return message
1324+{-# INLINE traceMWhen #-}
1325+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1326+traceMWhen _ b getMessage = when b $ do
1327+ message <- getMessage
1329+ spiderTimeline <- askSpiderTimelineEnv
1330+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1334+ liftIO $ putStrLn $ replicate d ' ' <> message
1336+whoCreatedIORef :: IORef a -> IO [String]
1337+whoCreatedIORef (IORef a) = whoCreated $! a
1340+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1343+ (x :| xs) : t -> case groupByHead t of
1344+ [] -> [(x, xs :| [])]
1346+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1347+ | otherwise -> (x, xs :| []) : l
1349+listsToForest :: Eq a => [[a]] -> Forest a
1350+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1353+{-# INLINE propagateSubscriberHold #-}
1354+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1355+propagateSubscriberHold h a = do
1356+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1357+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1358+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1359+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1360+ case {-# SCC "apply" #-} apply a v of
1361+ Nothing -> return ()
1363+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1364+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1365+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1366+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1368+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1370+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1371+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1373+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1375+ (!m, _) <- BehaviorM ask
1377+ Nothing -> return Nothing
1378+ Just (!wi, _) -> return $ Just wi
1380+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1382+ (!m, _) <- BehaviorM ask
1384+ Nothing -> return Nothing
1385+ Just (_, !p) -> return $ Just p
1387+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1388+askBehaviorHoldInits = do
1389+ (_, !his) <- BehaviorM ask
1392+{-# INLINE getDynHold #-}
1393+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1395+ mh <- liftIO $ readIORef $ unDyn d
1397+ HoldDyn h -> return h
1398+ UnsafeDyn (readV0, v') -> do
1399+ holdInits <- getDeferralQueue
1400+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1402+ BuildDyn (readV0, v') -> do
1403+ v0 <- liftIO $ runEventM readV0
1408+ liftIO $ writeIORef (unDyn d) $ HoldDyn h
1412+-- Always refers to 0
1413+{-# NOINLINE zeroRef #-}
1414+zeroRef :: IORef Height
1415+zeroRef = unsafePerformIO $ newIORef zeroHeight
1417+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1418+getRootSubscribed k r sub = do
1419+ mSubscribed <- readIORef $ rootSubscribed r
1420+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1421+ case DMap.lookup k mSubscribed of
1422+ Just subscribed -> {-# SCC "hitRoot" #-} do
1423+ sln <- subscribeRootSubscribed subscribed sub
1425+ return (sln, subscribed, occ)
1426+ Nothing -> {-# SCC "missRoot" #-} do
1427+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1428+ let !cached = rootSubscribed r
1429+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1430+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1431+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1432+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1433+ writeIORef uninitRef $! uninit
1434+#ifdef DEBUG_NODEIDS
1437+ let !subscribed = RootSubscribed
1438+ { rootSubscribedKey = k
1439+ , rootSubscribedCachedSubscribed = cached
1440+ , rootSubscribedOccurrence = getOcc
1441+ , rootSubscribedSubscribers = subs
1442+ , rootSubscribedUninit = uninit
1443+ , rootSubscribedWeakSelf = weakSelf
1444+#ifdef DEBUG_NODEIDS
1445+ , rootSubscribedNodeId = nid
1448+ -- If we die at the same moment that all our children die, they will
1449+ -- try to clean us up but will fail because their Weak reference to us
1450+ -- will also be dead. So, if we are dying, check if there are any
1451+ -- children; since children don't bother cleaning themselves up if
1452+ -- their parents are already dead, I don't think there's a race
1453+ -- condition here. However, if there are any children, then we can
1454+ -- infer that we need to clean ourselves up, so we do.
1456+ cs <- readIORef $ _weakBag_children subs
1457+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1458+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1459+ 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
1461+ return (sln, subscribed, occ)
1463+#ifdef USE_TEMPLATE_HASKELL
1464+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1466+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1467+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1468+ rootSubscribedUninit self
1469+ modifyIORef' cached $ DMap.delete k
1471+{-# INLINE subscribeRootSubscribed #-}
1472+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1473+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1475+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1477+data FanInt x a = FanInt
1478+ { _fanInt_subscribers :: {-# UNPACK #-} !(FastMutableIntMap (FastWeakBag (Subscriber x a))) --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1479+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1480+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1483+newFanInt :: IO (FanInt x a)
1485+ subscribers <- FastMutableIntMap.newEmpty --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1486+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1487+ occRef <- newIORef $ error "fanInt: no occurrence"
1489+ { _fanInt_subscribers = subscribers
1490+ , _fanInt_subscriptionRef = subscriptionRef
1491+ , _fanInt_occRef = occRef
1494+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1495+fanInt p = unsafePerformIO $ do
1497+ pure $ EventSelectorInt $ \k -> Event $ \sub -> do
1498+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1499+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1500+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1501+ { subscriberPropagate = \m -> do
1502+ liftIO $ writeIORef (_fanInt_occRef self) m
1503+ scheduleIntClear $ _fanInt_occRef self
1504+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1505+ FastWeakBag.traverse b $ \s -> do
1506+ subscriberPropagate s v
1507+ , subscriberInvalidateHeight = \old -> do
1508+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1509+ FastWeakBag.traverse b $ \s -> do
1510+ subscriberInvalidateHeight s old
1511+ , subscriberRecalculateHeight = \new -> do
1512+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1513+ FastWeakBag.traverse b $ \s -> do
1514+ subscriberRecalculateHeight s new
1517+ writeIORef (_fanInt_subscriptionRef self) subscription
1518+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1519+ scheduleIntClear $ _fanInt_occRef self
1521+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1523+ b <- FastWeakBag.empty
1524+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1527+ t <- liftIO $ FastWeakBag.insert sub b
1528+ currentOcc <- readIORef (_fanInt_occRef self)
1529+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1530+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1532+{-# INLINABLE getFanSubscribed #-}
1533+getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k v -> Subscriber x (v a) -> EventM x (WeakBagTicket, FanSubscribed x k v, Maybe (v a))
1534+getFanSubscribed k f sub = do
1535+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1536+ case mSubscribed of
1537+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1538+ sln <- subscribeFanSubscribed k subscribed sub
1539+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1540+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1541+ Nothing -> {-# SCC "missFan" #-} do
1542+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1543+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1544+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1545+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1546+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1547+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1548+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1549+ occRef <- liftIO $ newIORef parentOcc
1550+ when (isJust parentOcc) $ scheduleClear occRef
1551+#ifdef DEBUG_NODEIDS
1552+ nid <- liftIO newNodeId
1554+ let subscribed = FanSubscribed
1555+ { fanSubscribedCachedSubscribed = fanSubscribed f
1556+ , fanSubscribedOccurrence = occRef
1557+ , fanSubscribedParent = subscription
1558+ , fanSubscribedSubscribers = subscribersRef
1559+#ifdef DEBUG_NODEIDS
1560+ , fanSubscribedNodeId = nid
1563+ let !self = (k, subscribed)
1564+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1565+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1566+ liftIO $ writeIORef subscribedRef $! subscribed
1567+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1568+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1570+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
1571+cleanupFanSubscribed (k, subscribed) = do
1572+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1573+ let reducedSubscribers = DMap.delete k subscribers
1574+ if DMap.null reducedSubscribers
1576+ unsubscribe $ fanSubscribedParent subscribed
1577+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1578+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1579+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1581+{-# INLINE subscribeFanSubscribed #-}
1582+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
1583+subscribeFanSubscribed k subscribed sub = do
1584+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1585+ case DMap.lookup k subscribers of
1586+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1587+ let !self = (k, subscribed)
1588+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1589+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1590+ 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
1592+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1594+{-# INLINABLE getSwitchSubscribed #-}
1595+getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1596+getSwitchSubscribed s sub = do
1597+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1598+ case mSubscribed of
1599+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1600+ sln <- subscribeSwitchSubscribed subscribed sub
1601+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1602+ return (sln, subscribed, occ)
1603+ Nothing -> {-# SCC "missSwitch" #-} do
1604+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1605+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1606+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1607+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1608+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1609+ wiRef <- liftIO $ newIORef wi
1610+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1611+ holdInits <- getDeferralQueue
1612+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1613+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1614+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1615+ subscriptionRef <- liftIO $ newIORef subscription
1616+ occRef <- liftIO $ newIORef parentOcc
1617+ when (isJust parentOcc) $ scheduleClear occRef
1618+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1619+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1620+#ifdef DEBUG_NODEIDS
1621+ nid <- liftIO newNodeId
1623+ let !subscribed = SwitchSubscribed
1624+ { switchSubscribedCachedSubscribed = switchSubscribed s
1625+ , switchSubscribedOccurrence = occRef
1626+ , switchSubscribedHeight = heightRef
1627+ , switchSubscribedSubscribers = subs
1628+ , switchSubscribedOwnInvalidator = i
1629+ , switchSubscribedOwnWeakInvalidator = wiRef
1630+ , switchSubscribedBehaviorParents = parentsRef
1631+ , switchSubscribedParent = switchParent s
1632+ , switchSubscribedCurrentParent = subscriptionRef
1633+ , switchSubscribedWeakSelf = weakSelf
1634+#ifdef DEBUG_NODEIDS
1635+ , switchSubscribedNodeId = nid
1638+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1639+ liftIO $ writeIORef subscribedRef $! subscribed
1640+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1641+ return (slnForSub, subscribed, parentOcc)
1643+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1644+cleanupSwitchSubscribed subscribed = do
1645+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1646+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1647+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1649+{-# INLINE subscribeSwitchSubscribed #-}
1650+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1651+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1653+{-# INLINABLE getCoincidenceSubscribed #-}
1654+getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1655+getCoincidenceSubscribed c sub = do
1656+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1657+ case mSubscribed of
1658+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1659+ sln <- subscribeCoincidenceSubscribed subscribed sub
1660+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1661+ return (sln, subscribed, occ)
1662+ Nothing -> {-# SCC "missCoincidence" #-} do
1663+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1664+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1665+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1666+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1667+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1668+ (occ, height, mInnerSubd) <- case outerOcc of
1669+ Nothing -> return (Nothing, outerHeight, Nothing)
1671+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1672+ return (occ, height, Just innerSubd)
1673+ occRef <- liftIO $ newIORef occ
1674+ when (isJust occ) $ scheduleClear occRef
1675+ heightRef <- liftIO $ newIORef height
1676+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1677+ scheduleClear innerSubdRef
1678+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1679+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1680+#ifdef DEBUG_NODEIDS
1681+ nid <- liftIO newNodeId
1683+ let subscribed = CoincidenceSubscribed
1684+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1685+ , coincidenceSubscribedOccurrence = occRef
1686+ , coincidenceSubscribedHeight = heightRef
1687+ , coincidenceSubscribedSubscribers = subs
1688+ , coincidenceSubscribedOuter = subOuter
1689+ , coincidenceSubscribedOuterParent = outerSubscription
1690+ , coincidenceSubscribedInnerParent = innerSubdRef
1691+ , coincidenceSubscribedWeakSelf = weakSelf
1692+#ifdef DEBUG_NODEIDS
1693+ , coincidenceSubscribedNodeId = nid
1696+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1697+ liftIO $ writeIORef subscribedRef $! subscribed
1698+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1699+ return (slnForSub, subscribed, occ)
1701+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1702+cleanupCoincidenceSubscribed subscribed = do
1703+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1704+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1706+{-# INLINE subscribeCoincidenceSubscribed #-}
1707+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1708+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1710+{-# INLINE mergeG #-}
1711+mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1712+ => (forall a. q a -> Event x (v a))
1713+ -> Dynamic x (PatchDMap k q) -> Event x (DMap k v)
1714+mergeG nt d = cacheEvent (mergeCheap nt d)
1716+{-# INLINE mergeWithMove #-}
1717+mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1718+ => (forall a. q a -> Event x (v a))
1719+ -> Dynamic x (PatchDMapWithMove k q) -> Event x (DMap k v)
1720+mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1722+{-# INLINE [1] mergeCheap #-}
1724+ :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1725+ => (forall a. q a -> Event x (v a))
1726+ -> Dynamic x (PatchDMap k q)
1727+ -> Event x (DMap k v)
1728+mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
1730+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1731+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1732+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1733+ (mOldSubd, newPs) <- case me of
1734+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1736+ let s = subscriber $ return k
1737+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1738+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1739+ let newParent = MergeSubscribedParent subscription
1740+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1741+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1742+ forM_ mOldSubd $ \oldSubd -> do
1743+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1744+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1745+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1746+ foldM f ([], oldParents) $ DMap.toList p
1748+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1749+ getInitialSubscribers initialParents subscriber = do
1750+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1751+ let s = subscriber $ return k
1752+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1753+ height <- liftIO $ getEventSubscribedHeight parentSubd
1754+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
1755+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1756+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1757+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1760+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1761+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1763+{-# INLINE [1] mergeCheapWithMove #-}
1764+mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1765+ => (forall a. q a -> Event x (v a))
1766+ -> Dynamic x (PatchDMapWithMove k q)
1767+ -> Event x (DMap k v)
1768+mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
1770+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1771+ updateMe subscriber heightBagRef oldParents p = do
1772+ -- Prepare new parents for insertion
1773+ let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1774+ subscribeParent k e = do
1775+ keyRef <- liftIO $ newIORef k
1776+ let s = subscriber $ liftIO $ readIORef keyRef
1777+ subscription@(EventSubscription _ subd) <- subscribe e s
1779+ newParentHeight <- getEventSubscribedHeight subd
1780+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1781+ return $ MergeSubscribedParentWithMove subscription keyRef
1782+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1783+ -- Collect old parents for deletion and update the keys of moved parents
1784+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1785+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1787+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1788+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1789+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1791+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1793+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1794+ return (toDelete, applyAlways p' oldParents)
1795+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1796+ getInitialSubscribers initialParents subscriber = do
1797+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1798+ keyRef <- liftIO $ newIORef k
1799+ let s = subscriber $ liftIO $ readIORef keyRef
1800+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1801+ height <- liftIO $ getEventSubscribedHeight parentSubd
1802+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1803+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1804+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1805+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1808+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1809+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1811+type MergeUpdateFunc k v x p s
1812+ = (forall a. EventM x (k a) -> Subscriber x (v a))
1816+ -> EventM x ([EventSubscription x], DMap k s)
1818+type MergeInitFunc k v q x s
1820+ -> (forall a. EventM x (k a) -> Subscriber x (v a))
1821+ -> EventM x (DMap k v, [Height], DMap k s)
1823+type MergeDestroyFunc k s
1827+data Merge x k v s = Merge
1828+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1829+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1830+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1831+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1832+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
1835+invalidateMergeHeight :: Merge x k v s -> IO ()
1836+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1838+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1839+invalidateMergeHeight' heightRef sub = do
1840+ oldHeight <- readIORef heightRef
1841+ 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
1842+ writeIORef heightRef $! invalidHeight
1843+ subscriberInvalidateHeight sub oldHeight
1845+revalidateMergeHeight :: Merge x k v s -> IO ()
1846+revalidateMergeHeight m = do
1847+ currentHeight <- readIORef $ _merge_heightRef m
1848+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1849+ heights <- readIORef $ _merge_heightBagRef m
1850+ parents <- readIORef $ _merge_parentsRef m
1851+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1852+ case heightBagSize heights `compare` DMap.size parents of
1855+ let height = succHeight $ heightBagMax heights
1856+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1857+ writeIORef (_merge_heightRef m) $! height
1858+ subscriberRecalculateHeight (_merge_sub m) height
1859+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1861+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
1862+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1863+ vals <- liftIO $ readIORef $ _merge_accumRef m
1864+ liftIO $ writeIORef (_merge_accumRef m) $! DMap.empty -- Once we're done with this, we can clear it immediately, because if there's a cacheEvent in front of us, it'll handle subsequent subscribers, and if not, we won't get subsequent subscribers
1865+ --TODO: Assert that m is not empty
1866+ subscriberPropagate (_merge_sub m) vals
1868+mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
1869+mergeSubscriber m getKey = Subscriber
1870+ { subscriberPropagate = \a -> do
1871+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1873+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
1874+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1875+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1876+ when (DMap.null oldM) $ do -- Only schedule the firing once
1877+ height <- liftIO $ readIORef $ _merge_heightRef m
1878+ --TODO: assertions about height
1879+ currentHeight <- getCurrentHeight
1880+ when (height <= currentHeight) $ do
1881+ if height /= invalidHeight
1883+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1884+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1887+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1888+ stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
1889+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1893+ error $ "Causality loop found" <> cycleInfo
1894+ scheduleMergeSelf m height
1895+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1896+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1897+ invalidateMergeHeight m
1898+ , subscriberRecalculateHeight = \new -> do
1899+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1900+ revalidateMergeHeight m
1903+--TODO: Be able to run as much of this as possible promptly
1904+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
1905+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1906+ where updateMe = do
1907+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1908+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1909+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1910+ return subscriptionsToKill
1912+{-# INLINE mergeGCheap' #-}
1913+mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1914+ => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> Dynamic x p -> Event x (DMap k v)
1915+mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1916+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1917+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1918+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1919+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1920+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1922+ { _merge_parentsRef = parentsRef
1923+ , _merge_heightBagRef = heightBagRef
1924+ , _merge_heightRef = heightRef
1926+ , _merge_accumRef = accumRef
1928+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1929+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1930+ myHeight = if invalidHeight `elem` heights
1932+ else succHeight $ heightBagMax myHeightBag
1933+ currentHeight <- getCurrentHeight
1934+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1935+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1937+ unless (DMap.null accum) $ do
1938+ scheduleMergeSelf m myHeight
1939+ liftIO $ writeIORef accumRef $! accum
1940+ liftIO $ writeIORef heightRef $! myHeight
1941+ liftIO $ writeIORef heightBagRef $! myHeightBag
1942+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1943+ liftIO $ writeIORef parentsRef $! initialParentState
1944+ defer $ SomeMergeInit $ do
1946+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1947+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1948+ defer $ updateMerge m updateFunc a
1949+ , subscriberInvalidateHeight = \_ -> return ()
1950+ , subscriberRecalculateHeight = \_ -> return ()
1952+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1953+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1954+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1955+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1956+ -- its subscription.
1957+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1958+ let unsubscribeAll = destroy =<< readIORef parentsRef
1959+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1963+mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1964+mergeInt = cacheEvent . mergeIntCheap
1966+{-# INLINABLE mergeIntCheap #-}
1967+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1968+mergeIntCheap d = Event $ \sub -> do
1969+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1970+ accum <- liftIO $ FastMutableIntMap.newEmpty
1971+ heightRef <- liftIO $ newIORef zeroHeight
1972+ heightBagRef <- liftIO $ newIORef heightBagEmpty
1973+ parents <- liftIO $ FastMutableIntMap.newEmpty
1974+ let scheduleSelf = do
1975+ height <- liftIO $ readIORef $ heightRef
1976+ scheduleMerge' height heightRef $ do
1977+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1978+ subscriberPropagate sub vals
1979+ invalidateMyHeight = do
1980+ invalidateMergeHeight' heightRef sub
1981+ recalculateMyHeight = do
1982+ currentHeight <- readIORef heightRef
1983+ when (currentHeight == invalidHeight) $ do --TODO: This will almost always be true; can we get rid of this check and just proceed to the next one always?
1984+ heights <- readIORef heightBagRef
1985+ numParents <- FastMutableIntMap.size parents
1986+ case heightBagSize heights `compare` numParents of
1989+ let height = succHeight $ heightBagMax heights
1990+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1991+ writeIORef heightRef $! height
1992+ subscriberRecalculateHeight sub height
1993+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
1994+ mySubscriber k = Subscriber
1995+ { subscriberPropagate = \a -> do
1996+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1997+ liftIO $ FastMutableIntMap.insert accum k a
1998+ when wasEmpty scheduleSelf
1999+ , subscriberInvalidateHeight = \old -> do
2000+ modifyIORef' heightBagRef $ heightBagRemove old
2002+ , subscriberRecalculateHeight = \new -> do
2003+ modifyIORef' heightBagRef $ heightBagAdd new
2004+ recalculateMyHeight
2006+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
2007+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
2009+ forM_ parentOcc $ FastMutableIntMap.insert accum k
2010+ FastMutableIntMap.insert parents k subscription
2011+ height <- getEventSubscribedHeight parentSubd
2012+ if height == invalidHeight
2013+ then writeIORef heightRef invalidHeight
2015+ modifyIORef' heightBagRef $ heightBagAdd height
2016+ modifyIORef' heightRef $ \oldHeight ->
2017+ if oldHeight == invalidHeight
2019+ else max (succHeight height) oldHeight
2020+ myHeight <- liftIO $ readIORef heightRef
2021+ currentHeight <- getCurrentHeight
2022+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2023+ occ <- if currentHeight >= myHeight -- If we should have fired by now
2025+ then return Nothing
2026+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2027+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2029+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2030+ defer $ SomeMergeInit $ do
2031+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2034+ let f k newParent = do
2035+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2036+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2037+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2038+ return subscription
2039+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2040+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2041+ liftIO $ for_ oldParents $ \oldParent -> do
2042+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2043+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2044+ return $ IntMap.elems oldParents
2046+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2047+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2049+ , subscriberInvalidateHeight = \_ -> return ()
2050+ , subscriberRecalculateHeight = \_ -> return ()
2052+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2053+ forM_ change $ \c -> defer $ updateMe c
2054+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2055+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2056+ -- its subscription.
2057+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2058+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2059+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2063+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2064+newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
2066+fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2067+fanG e = unsafePerformIO $ do
2068+ ref <- newIORef Nothing
2071+ , fanSubscribed = ref
2073+ pure $ EventSelectorG $ \k -> eventFan k f
2075+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2076+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2077+ holdInits <- liftIO $ readIORef holdInitRef
2078+ dynInits <- liftIO $ readIORef dynInitRef
2079+ mergeInits <- liftIO $ readIORef mergeInitRef
2080+ unless (null holdInits && null dynInits && null mergeInits) $ do
2081+ liftIO $ writeIORef holdInitRef []
2082+ liftIO $ writeIORef dynInitRef []
2083+ liftIO $ writeIORef mergeInitRef []
2084+ mapM_ initHold holdInits
2085+ mapM_ initDyn dynInits
2086+ mapM_ unSomeMergeInit mergeInits
2087+ runHoldInits holdInitRef dynInitRef mergeInitRef
2089+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2090+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2092+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2093+initDyn (SomeDynInit d) = void $ getDynHold d
2095+newEventEnv :: IO (EventEnv x)
2097+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2098+ holdInitRef <- newIORef []
2099+ dynInitRef <- newIORef []
2100+ mergeUpdateRef <- newIORef []
2101+ mergeInitRef <- newIORef []
2102+ heightRef <- newIORef zeroHeight
2103+ toClearRef <- newIORef []
2104+ toClearIntRef <- newIORef []
2105+ toClearRootRef <- newIORef []
2106+ coincidenceInfosRef <- newIORef []
2107+ delayedRef <- newIORef IntMap.empty
2108+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2110+clearEventEnv :: EventEnv x -> IO ()
2111+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2112+ writeIORef toAssignRef []
2113+ writeIORef holdInitRef []
2114+ writeIORef dynInitRef []
2115+ writeIORef mergeUpdateRef []
2116+ writeIORef mergeInitRef []
2117+ writeIORef heightRef zeroHeight
2118+ writeIORef toClearRef []
2119+ writeIORef toClearIntRef []
2120+ writeIORef toClearRootRef []
2121+ writeIORef coincidenceInfosRef []
2122+ writeIORef delayedRef IntMap.empty
2124+-- | Run an event action outside of a frame
2125+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2126+runFrame a = SpiderHost $ do
2127+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2130+ runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env) -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
2132+ result <- runEventM go
2133+ toClear <- readIORef $ eventEnvClears env
2134+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2135+ toClearInt <- readIORef $ eventEnvIntClears env
2136+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2137+ toClearRoot <- readIORef $ eventEnvRootClears env
2138+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2139+ toAssign <- readIORef $ eventEnvAssignments env
2140+ toReconnectRef <- newIORef []
2141+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2142+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2144+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2145+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2146+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2147+ writeIORef (eventEnvMergeUpdates env) []
2148+ when debugPropagate $ putStrLn "Updating merges"
2149+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2150+ when debugPropagate $ putStrLn "Updating merges done"
2151+ toReconnect <- readIORef toReconnectRef
2153+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2154+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2155+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2156+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2158+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2159+ wi' <- mkWeakPtrWithDebug i "wi'"
2160+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2161+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2162+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2163+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2164+ runEventM $ runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env) --TODO: Is this actually OK? It seems like it should be, since we know that no events are firing at this point, but it still seems inelegant
2165+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2166+ sub <- newSubscriberSwitch subscribed
2167+ subscription <- unSpiderHost $ runFrame $ {-# SCC "subscribeSwitch" #-} subscribe e sub --TODO: Assert that the event isn't firing --TODO: This should not loop because none of the events should be firing, but still, it is inefficient
2169+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2170+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2171+ EventRoot _ -> "EventRoot"
2172+ EventNever -> "EventNever"
2173+ _ -> "something else"
2175+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2176+ return oldSubscription
2177+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2178+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2179+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2180+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2181+ parentHeight <- getEventSubscribedHeight subd'
2182+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2183+ when (parentHeight /= myHeight) $ do
2184+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2185+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2186+ 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
2187+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2188+ unsubscribe subscription
2189+ mapM_ invalidateCoincidenceHeight mcs
2190+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2191+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2192+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2193+ height <- calculateSwitchHeight subscribed
2194+ updateSwitchHeight height subscribed
2197+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2199+{-# INLINE zeroHeight #-}
2200+zeroHeight :: Height
2201+zeroHeight = Height 0
2203+{-# INLINE invalidHeight #-}
2204+invalidHeight :: Height
2205+invalidHeight = Height (-1000)
2208+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2209+{-# INLINE invalidHeightBeingTraversed #-}
2210+invalidHeightBeingTraversed :: Height
2211+invalidHeightBeingTraversed = Height (-1001)
2214+{-# INLINE succHeight #-}
2215+succHeight :: Height -> Height
2216+succHeight h@(Height a) =
2217+ if h == invalidHeight
2219+ else Height $ succ a
2221+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2222+invalidateCoincidenceHeight subscribed = do
2223+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2224+ when (oldHeight /= invalidHeight) $ do
2225+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2226+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2228+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2229+updateSwitchHeight new subscribed = do
2230+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2231+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2232+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2233+ writeIORef (switchSubscribedHeight subscribed) $! new
2234+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2236+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2237+recalculateCoincidenceHeight subscribed = do
2238+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2239+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2240+ height <- calculateCoincidenceHeight subscribed
2241+ when (height /= invalidHeight) $ do
2242+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2243+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2245+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2246+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2248+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2249+calculateCoincidenceHeight subscribed = do
2250+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2251+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2252+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2254+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2256+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2257+invalidate toReconnectRef wis = do
2258+ forM_ wis $ \wi -> do
2262+ traceInvalidate "invalidate Dead"
2263+ return () --TODO: Should we clean this up here?
2265+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2267+ InvalidatorPull p -> do
2268+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2269+ mVal <- readIORef $ pullValue p
2270+ forM_ mVal $ \val -> do
2271+ writeIORef (pullValue p) Nothing
2272+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2273+ InvalidatorSwitch subscribed -> do
2274+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2275+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2276+ 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
2278+--------------------------------------------------------------------------------
2279+-- Reflex integration
2280+--------------------------------------------------------------------------------
2282+-- | Designates the default, global Spider timeline
2283+data SpiderTimeline x
2284+type role SpiderTimeline nominal
2286+-- | The default, global Spider environment
2287+type Spider = SpiderTimeline Global
2289+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2290+ {-# INLINABLE sample #-}
2291+ sample (SpiderBehavior b) = readBehaviorUntracked b
2293+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2294+ {-# INLINABLE hold #-}
2295+ hold = holdSpiderEventM
2296+ {-# INLINABLE holdDyn #-}
2297+ holdDyn = holdDynSpiderEventM
2298+ {-# INLINABLE holdIncremental #-}
2299+ holdIncremental = holdIncrementalSpiderEventM
2300+ {-# INLINABLE buildDynamic #-}
2301+ buildDynamic = buildDynamicSpiderEventM
2302+ {-# INLINABLE headE #-}
2303+ headE = R.slowHeadE
2304+-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2306+instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2307+ {-# INLINABLE sample #-}
2308+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2310+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2311+ {-# INLINABLE sample #-}
2312+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2314+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2315+ {-# INLINABLE hold #-}
2316+ hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2317+ {-# INLINABLE holdDyn #-}
2318+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2319+ {-# INLINABLE holdIncremental #-}
2320+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2321+ {-# INLINABLE buildDynamic #-}
2322+ buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2323+ {-# INLINABLE headE #-}
2324+ headE = R.slowHeadE
2325+-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2327+instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2328+ {-# INLINE return #-}
2330+ {-# INLINE (>>=) #-}
2331+ x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2332+ {-# INLINE (>>) #-}
2334+ {-# INLINE fail #-}
2335+ fail _ = error "Dynamic does not support 'fail'"
2337+{-# INLINABLE newJoinDyn #-}
2338+newJoinDyn :: HasSpiderTimeline x => Reflex.Spider.Internal.Dynamic x (Identity (Reflex.Spider.Internal.Dynamic x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2340+ let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2341+ eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2342+ eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2343+ eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2344+ v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2345+ in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2347+instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2348+ fmap = mapDynamicSpider
2349+ x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2351+mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2352+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2353+{-# INLINE [1] mapDynamicSpider #-}
2355+instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2356+ pure = SpiderDynamic . dynamicConst
2357+#if MIN_VERSION_base(4,10,0)
2358+ liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2360+ SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2361+ a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2362+ (<*) = flip (*>) -- There are no effects, so order doesn't matter
2364+holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2365+holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2367+holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2368+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2370+holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2371+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2373+buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2374+buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2376+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2377+ {-# INLINABLE hold #-}
2378+ hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2379+ {-# INLINABLE holdDyn #-}
2380+ holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2381+ {-# INLINABLE holdIncremental #-}
2382+ holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2383+ {-# INLINABLE buildDynamic #-}
2384+ buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2385+ {-# INLINABLE headE #-}
2386+ headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2388+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2389+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2391+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2392+ {-# INLINABLE hold #-}
2393+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2394+ {-# INLINABLE holdDyn #-}
2395+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2396+ {-# INLINABLE holdIncremental #-}
2397+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2398+ {-# INLINABLE buildDynamic #-}
2399+ buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2400+ {-# INLINABLE headE #-}
2401+ headE = R.slowHeadE
2402+-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2404+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2405+ {-# INLINABLE sample #-}
2406+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2408+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2409+ {-# INLINABLE sample #-}
2410+ sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2412+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2413+ {-# INLINABLE hold #-}
2414+ hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2415+ {-# INLINABLE holdDyn #-}
2416+ holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2417+ {-# INLINABLE holdIncremental #-}
2418+ holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2419+ {-# INLINABLE buildDynamic #-}
2420+ buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2421+ {-# INLINABLE headE #-}
2422+ headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2424+--------------------------------------------------------------------------------
2426+--------------------------------------------------------------------------------
2428+-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2429+{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2430+type SpiderEnv = SpiderTimeline
2431+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2432+ {-# INLINABLE subscribeEvent #-}
2433+ subscribeEvent e = SpiderHostFrame $ do
2434+ --TODO: Unsubscribe eventually (manually and/or with weak ref)
2435+ val <- liftIO $ newIORef Nothing
2436+ subscription <- subscribe (unSpiderEvent e) $ Subscriber
2437+ { subscriberPropagate = \a -> do
2438+ liftIO $ writeIORef val $ Just a
2440+ , subscriberInvalidateHeight = \_ -> return ()
2441+ , subscriberRecalculateHeight = \_ -> return ()
2443+ return $ SpiderEventHandle
2444+ { spiderEventHandleSubscription = subscription
2445+ , spiderEventHandleValue = val
2448+instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2449+ type EventTrigger (SpiderTimeline x) = RootTrigger x
2450+ type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2451+ type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2453+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2454+ {-# NOINLINE readEvent #-}
2455+ readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2456+ result <- readIORef $ spiderEventHandleValue h
2460+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2461+ newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2462+ newFanEventWithTrigger f = SpiderHost $ do
2463+ es <- newFanEventWithTriggerIO f
2464+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2466+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2467+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2468+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2469+ es <- newFanEventWithTriggerIO f
2470+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2472+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2473+ {-# INLINABLE subscribeEvent #-}
2474+ subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2476+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2477+ type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2478+ fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2479+ runHostFrame = runFrame . runSpiderHostFrame
2481+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2482+unsafeNewSpiderTimelineEnv = do
2486+ depthRef <- newIORef 0
2488+ return $ SpiderTimelineEnv
2489+ { _spiderTimeline_lock = lock
2490+ , _spiderTimeline_eventEnv = env
2492+ , _spiderTimeline_depth = depthRef
2496+-- | Create a new SpiderTimelineEnv
2497+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2498+newSpiderTimeline = withSpiderTimeline (pure . Some)
2500+data LocalSpiderTimeline (x :: Type) s
2502+instance Reifies s (SpiderTimelineEnv x) =>
2503+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2504+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2508+ -> SpiderTimelineEnv x
2509+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2510+localSpiderTimeline _ = unsafeCoerce
2512+-- | Pass a new timeline to the given function.
2513+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2514+withSpiderTimeline k = do
2515+ env <- unsafeNewSpiderTimelineEnv
2516+ reify env $ \s -> k $ localSpiderTimeline s env
2518+newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2520+type ComputeM = EventM
2522+newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2524+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2525+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2526+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2527+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2528+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2529+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2530+ type PullM (SpiderTimeline x) = SpiderPullM x
2531+ type PushM (SpiderTimeline x) = SpiderPushM x
2532+ {-# INLINABLE never #-}
2533+ never = SpiderEvent eventNever
2534+ {-# INLINABLE constant #-}
2535+ constant = SpiderBehavior . behaviorConst
2536+ {-# INLINE push #-}
2537+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2538+ {-# INLINE pushCheap #-}
2539+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2540+ {-# INLINABLE pull #-}
2541+ pull = SpiderBehavior . pull . coerce
2542+ {-# INLINABLE fanG #-}
2543+ fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2544+ {-# INLINABLE mergeG #-}
2546+ :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2547+ => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2549+ -> R.Event (SpiderTimeline x) (DMap k v)
2550+ mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2551+ {-# INLINABLE switch #-}
2552+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2553+ {-# INLINABLE coincidence #-}
2554+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2555+ {-# INLINABLE current #-}
2556+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2557+ {-# INLINABLE updated #-}
2558+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2559+ {-# INLINABLE unsafeBuildDynamic #-}
2560+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2561+ {-# INLINABLE unsafeBuildIncremental #-}
2562+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2563+ {-# INLINABLE mergeIncrementalG #-}
2564+ mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2565+ {-# INLINABLE mergeIncrementalWithMoveG #-}
2566+ mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2567+ {-# INLINABLE currentIncremental #-}
2568+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2569+ {-# INLINABLE updatedIncremental #-}
2570+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2571+ {-# INLINABLE incrementalToDynamic #-}
2572+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2573+ c <- readBehaviorUntracked $ dynamicCurrent i
2574+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2575+ eventCoercion Coercion = Coercion
2576+ behaviorCoercion Coercion = Coercion
2577+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2578+ {-# INLINABLE mergeIntIncremental #-}
2579+ mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2580+ {-# INLINABLE fanInt #-}
2581+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2583+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2585+data SpiderEventHandle x a = SpiderEventHandle
2586+ { spiderEventHandleSubscription :: EventSubscription x
2587+ , spiderEventHandleValue :: IORef (Maybe a)
2590+instance MonadRef (EventM x) where
2591+ type Ref (EventM x) = Ref IO
2592+ {-# INLINABLE newRef #-}
2593+ {-# INLINABLE readRef #-}
2594+ {-# INLINABLE writeRef #-}
2595+ newRef = liftIO . newRef
2596+ readRef = liftIO . readRef
2597+ writeRef r a = liftIO $ writeRef r a
2599+instance MonadAtomicRef (EventM x) where
2600+ {-# INLINABLE atomicModifyRef #-}
2601+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2603+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2604+newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2606+instance Monad (SpiderHost x) where
2607+ {-# INLINABLE (>>=) #-}
2608+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2609+ {-# INLINABLE (>>) #-}
2610+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2611+ {-# INLINABLE return #-}
2612+ return x = SpiderHost $ return x
2613+ {-# INLINABLE fail #-}
2614+ fail s = SpiderHost $ fail s
2616+-- | Run an action affecting the global Spider timeline; this will be guarded by
2617+-- a mutex for that timeline
2618+runSpiderHost :: SpiderHost Global a -> IO a
2619+runSpiderHost (SpiderHost a) = a
2621+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2622+-- mutex for that timeline
2623+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2624+runSpiderHostForTimeline (SpiderHost a) _ = a
2626+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2627+ deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2629+instance Monad (SpiderHostFrame x) where
2630+ {-# INLINABLE (>>=) #-}
2631+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2632+ {-# INLINABLE (>>) #-}
2633+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2634+ {-# INLINABLE return #-}
2635+ return x = SpiderHostFrame $ return x
2636+ {-# INLINABLE fail #-}
2637+ fail s = SpiderHostFrame $ fail s
2639+instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2640+ notReadyUntil _ = pure ()
2643+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2644+newEventWithTriggerIO f = do
2645+ es <- newFanEventWithTriggerIO $ \Refl -> f
2646+ return $ select es Refl
2648+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2649+newFanEventWithTriggerIO f = do
2650+ occRef <- newIORef DMap.empty
2651+ subscribedRef <- newIORef DMap.empty
2653+ { rootOccurrence = occRef
2654+ , rootSubscribed = subscribedRef
2657+ return $ EventSelector $ \k -> eventRoot k r
2659+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2661+instance MonadRef (SpiderHost x) where
2662+ type Ref (SpiderHost x) = Ref IO
2663+ newRef = SpiderHost . newRef
2664+ readRef = SpiderHost . readRef
2665+ writeRef r = SpiderHost . writeRef r
2667+instance MonadAtomicRef (SpiderHost x) where
2668+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2670+instance MonadRef (SpiderHostFrame x) where
2671+ type Ref (SpiderHostFrame x) = Ref IO
2672+ newRef = SpiderHostFrame . newRef
2673+ readRef = SpiderHostFrame . readRef
2674+ writeRef r = SpiderHostFrame . writeRef r
2676+instance MonadAtomicRef (SpiderHostFrame x) where
2677+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2679+instance PrimMonad (SpiderHostFrame x) where
2680+ type PrimState (SpiderHostFrame x) = PrimState IO
2681+ primitive = SpiderHostFrame . EventM . primitive