@@ -0,0 +1,2692 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE EmptyDataDecls #-}
5+{-# LANGUAGE ExistentialQuantification #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE FunctionalDependencies #-}
9+{-# LANGUAGE GADTs #-}
10+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11+{-# LANGUAGE LambdaCase #-}
12+{-# LANGUAGE MultiParamTypeClasses #-}
13+{-# LANGUAGE MultiWayIf #-}
14+{-# LANGUAGE RankNTypes #-}
15+{-# LANGUAGE RoleAnnotations #-}
16+{-# LANGUAGE ScopedTypeVariables #-}
17+{-# LANGUAGE TypeFamilies #-}
18+{-# LANGUAGE TypeOperators #-}
19+{-# LANGUAGE UndecidableInstances #-}
20+{-# LANGUAGE PolyKinds #-}
21+{-# LANGUAGE DeriveFunctor #-}
22+{-# LANGUAGE StandaloneDeriving #-}
23+{-# LANGUAGE InstanceSigs #-}
24+
25+#ifdef USE_REFLEX_OPTIMIZER
26+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
27+#endif
28+{-# OPTIONS_GHC -Wunused-binds #-}
29+-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
30+-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
31+module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
32+
33+#if MIN_VERSION_base(4,10,0)
34+import Control.Applicative (liftA2)
35+#endif
36+import Control.Concurrent
37+import Control.Exception
38+import Control.Monad hiding (forM, forM_, mapM, mapM_)
39+import Control.Monad.Exception
40+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
41+import Control.Monad.Primitive
42+--import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_)
43+import Control.Monad.Reader.Class
44+import Control.Monad.IO.Class
45+import Control.Monad.ReaderIO
46+import Control.Monad.Ref
47+import Data.Align
48+import Data.Coerce
49+import Data.Dependent.Map (DMap, DSum (..))
50+import qualified Data.Dependent.Map as DMap
51+import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
52+import qualified Data.FastMutableIntMap as FastMutableIntMap
53+import Data.Foldable hiding (concat, elem, sequence_)
54+import Data.Functor.Constant
55+import Data.Functor.Misc
56+import Data.Functor.Product
57+import Data.GADT.Compare
58+import Data.IntMap.Strict (IntMap)
59+import qualified Data.IntMap.Strict as IntMap
60+import Data.IORef
61+import Data.Kind (Type)
62+import Data.Maybe hiding (mapMaybe)
63+import Data.Monoid ((<>))
64+import Data.Proxy
65+import Data.These
66+import Data.Traversable
67+import Data.Witherable (Filterable, mapMaybe)
68+import GHC.Exts
69+import GHC.IORef (IORef (..))
70+import GHC.Stack
71+import Reflex.FastWeak
72+import System.IO.Unsafe
73+import System.Mem.Weak
74+import Unsafe.Coerce
75+
76+#ifdef DEBUG_CYCLES
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)
82+#endif
83+
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
96+import Reflex.Patch
97+import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
98+
99+#ifdef DEBUG_TRACE_EVENTS
100+import qualified Data.ByteString.Char8 as BS8
101+import System.IO (stderr)
102+#endif
103+
104+#ifdef DEBUG_TRACE_EVENTS
105+
106+withStackOneLine :: (BS8.ByteString -> a) -> a
107+withStackOneLine expr = unsafePerformIO $ do
108+ stack <- currentCallStack
109+ return (expr (BS8.pack (unwords (reverse stack))))
110+
111+#endif
112+
113+debugPropagate :: Bool
114+
115+debugInvalidateHeight :: Bool
116+
117+debugInvalidate :: Bool
118+
119+#ifdef DEBUG
120+
121+#define DEBUG_NODEIDS
122+
123+debugPropagate = True
124+
125+debugInvalidateHeight = False
126+
127+debugInvalidate = True
128+
129+class HasNodeId a where
130+ getNodeId :: a -> Int
131+
132+instance HasNodeId (Hold x p a) where
133+ getNodeId = holdNodeId
134+
135+instance HasNodeId (PushSubscribed x a b) where
136+ getNodeId = pushSubscribedNodeId
137+
138+instance HasNodeId (SwitchSubscribed x a) where
139+ getNodeId = switchSubscribedNodeId
140+
141+instance HasNodeId (FanSubscribed x a) where
142+ getNodeId = fanSubscribedNodeId
143+
144+instance HasNodeId (CoincidenceSubscribed x a) where
145+ getNodeId = coincidenceSubscribedNodeId
146+
147+instance HasNodeId (RootSubscribed x a) where
148+ getNodeId = rootSubscribedNodeId
149+
150+instance HasNodeId (Pull x a) where
151+ getNodeId = pullNodeId
152+
153+{-# INLINE showNodeId #-}
154+showNodeId :: HasNodeId a => a -> String
155+showNodeId = ("#"<>) . show . getNodeId
156+
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"
169+
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"
183+
184+#else
185+
186+debugPropagate = False
187+
188+debugInvalidateHeight = False
189+
190+debugInvalidate = False
191+
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
195+showNodeId _ = ""
196+
197+#endif
198+
199+#ifdef DEBUG_NODEIDS
200+{-# NOINLINE nextNodeIdRef #-}
201+nextNodeIdRef :: IORef Int
202+nextNodeIdRef = unsafePerformIO $ newIORef 1
203+
204+newNodeId :: IO Int
205+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
206+#endif
207+
208+--------------------------------------------------------------------------------
209+-- EventSubscription
210+--------------------------------------------------------------------------------
211+
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)
217+ }
218+
219+unsubscribe :: EventSubscription x -> IO ()
220+unsubscribe (EventSubscription u _) = u
221+
222+--------------------------------------------------------------------------------
223+-- Event
224+--------------------------------------------------------------------------------
225+
226+newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
227+
228+{-# INLINE subscribeAndRead #-}
229+subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
230+subscribeAndRead = unEvent
231+
232+{-# RULES
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
236+ #-}
237+
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
246+ mb <- f a
247+ mapM_ (subscriberPropagate sub) mb
248+ }
249+ occ' <- join <$> mapM f occ
250+ return (subscription, occ')
251+
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 ()
259+ }
260+
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
270+ }
271+ liftIO $ case occ of
272+ Nothing -> writeIORef subscriptionRef $! subscription
273+ Just _ -> unsubscribe subscription
274+ return (subscription, occ)
275+
276+--TODO: Make this lazy in its input event
277+headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
278+headE originalE = do
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
288+
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))
293+ }
294+
295+-- | Construct an 'Event' whose value is guaranteed not to be recomputed
296+-- repeatedly
297+--
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
300+--subscriber joins
301+{-# NOINLINE [0] cacheEvent #-}
302+cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
303+cacheEvent e =
304+#ifdef DEBUG_TRACE_EVENTS
305+ withStackOneLine $ \callSite -> Event $
306+#else
307+ Event $
308+#endif
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
315+#endif
316+ subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
317+ Just subscribedTicket -> return subscribedTicket
318+ Nothing -> do
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
330+ }
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
338+ }
339+ subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
340+ liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
341+ return subscribedTicket
342+ liftIO $ do
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
350+ when isEmpty $ do
351+ writeIORef mSubscribedRef emptyFastWeak
352+ unsubscribe $ _cacheSubscribed_parent subscribed
353+ touch ticket
354+ touch subscribedTicket
355+ , _eventSubscription_subscribed = EventSubscribed
356+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
357+ , eventSubscribedRetained = toAny subscribedTicket
358+ }
359+ }
360+ return (es, occ)
361+
362+subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
363+subscribe e s = fst <$> subscribeAndRead e s
364+
365+{-# INLINE wrap #-}
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
369+ let es = tag subd
370+ return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
371+
372+eventRoot :: GCompare k => k a -> Root x k -> Event x a
373+eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
374+
375+eventNever :: Event x a
376+eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
377+
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
380+
381+eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
382+eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
383+
384+eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
385+eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
386+
387+eventHold :: Hold x p -> Event x p
388+eventHold !h = Event $ subscribeHoldEvent h
389+
390+eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
391+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
392+
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)
402+
403+--------------------------------------------------------------------------------
404+-- Subscriber
405+--------------------------------------------------------------------------------
406+
407+data Subscriber x a = Subscriber
408+ { subscriberPropagate :: !(a -> EventM x ())
409+ , subscriberInvalidateHeight :: !(Height -> IO ())
410+ , subscriberRecalculateHeight :: !(Height -> IO ())
411+ }
412+
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.
419+--
420+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
421+-- the weak pointer to it in some cases.
422+
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 ()
428+ }
429+
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_
441+ return ()
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"
452+ }
453+
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"
472+ }
473+
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
485+ case occ of
486+ Nothing -> do
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"
503+ }
504+
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
510+ case occ of
511+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
512+ Nothing -> do
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"
524+ }
525+
526+invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
527+invalidateSubscriberHeight = flip subscriberInvalidateHeight
528+
529+recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
530+recalculateSubscriberHeight = flip subscriberRecalculateHeight
531+
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
538+
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
545+
546+--------------------------------------------------------------------------------
547+-- EventSubscribed
548+--------------------------------------------------------------------------------
549+
550+toAny :: a -> Any
551+toAny = unsafeCoerce
552+
553+-- Why do we use Any here, instead of just giving eventSubscribedRetained an
554+-- existential type? Sadly, GHC does not currently know how to unbox types
555+-- with existentially quantified fields. So instead we just coerce values
556+-- to type Any on the way in. Since we never coerce them back, this is
557+-- perfectly safe.
558+data EventSubscribed x = EventSubscribed
559+ { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
560+ , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
561+#ifdef DEBUG_CYCLES
562+ , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
563+ , eventSubscribedHasOwnHeightRef :: !Bool
564+ , eventSubscribedWhoCreated :: !(IO [String])
565+#endif
566+ }
567+
568+eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
569+eventSubscribedRoot !r = EventSubscribed
570+ { eventSubscribedHeightRef = zeroRef
571+ , eventSubscribedRetained = toAny r
572+#ifdef DEBUG_CYCLES
573+ , eventSubscribedGetParents = return []
574+ , eventSubscribedHasOwnHeightRef = False
575+ , eventSubscribedWhoCreated = return ["root"]
576+#endif
577+ }
578+
579+eventSubscribedNever :: EventSubscribed x
580+eventSubscribedNever = EventSubscribed
581+ { eventSubscribedHeightRef = zeroRef
582+ , eventSubscribedRetained = toAny ()
583+#ifdef DEBUG_CYCLES
584+ , eventSubscribedGetParents = return []
585+ , eventSubscribedHasOwnHeightRef = False
586+ , eventSubscribedWhoCreated = return ["never"]
587+#endif
588+ }
589+
590+eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
591+eventSubscribedFan !subscribed = EventSubscribed
592+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
593+ , eventSubscribedRetained = toAny subscribed
594+#ifdef DEBUG_CYCLES
595+ , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
596+ , eventSubscribedHasOwnHeightRef = False
597+ , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
598+#endif
599+ }
600+
601+eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
602+eventSubscribedSwitch !subscribed = EventSubscribed
603+ { eventSubscribedHeightRef = switchSubscribedHeight subscribed
604+ , eventSubscribedRetained = toAny subscribed
605+#ifdef DEBUG_CYCLES
606+ , eventSubscribedGetParents = do
607+ s <- readIORef $ switchSubscribedCurrentParent subscribed
608+ return [Some $ _eventSubscription_subscribed s]
609+ , eventSubscribedHasOwnHeightRef = True
610+ , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
611+#endif
612+ }
613+
614+eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
615+eventSubscribedCoincidence !subscribed = EventSubscribed
616+ { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
617+ , eventSubscribedRetained = toAny subscribed
618+#ifdef DEBUG_CYCLES
619+ , eventSubscribedGetParents = do
620+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
621+ let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
622+ innerParents = maybeToList $ fmap Some innerSubscription
623+ return $ outerParent : innerParents
624+ , eventSubscribedHasOwnHeightRef = True
625+ , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
626+#endif
627+ }
628+
629+getEventSubscribedHeight :: EventSubscribed x -> IO Height
630+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
631+
632+#ifdef DEBUG_CYCLES
633+whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
634+whoCreatedEventSubscribed = eventSubscribedWhoCreated
635+
636+walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
637+walkInvalidHeightParents s0 = do
638+ subscribers <- flip execStateT mempty $ ($ Some s0) $ fix $ \loop (Some s) -> do
639+ h <- liftIO $ readIORef $ eventSubscribedHeightRef s
640+ when (h == invalidHeight) $ do
641+ when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
642+ modify (Some s :)
643+ mapM_ loop =<< liftIO (eventSubscribedGetParents s)
644+ forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
645+ return subscribers
646+#endif
647+
648+{-# INLINE subscribeHoldEvent #-}
649+subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
650+subscribeHoldEvent = subscribeAndRead . holdEvent
651+
652+--------------------------------------------------------------------------------
653+-- Behavior
654+--------------------------------------------------------------------------------
655+
656+newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
657+
658+behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
659+behaviorHold !h = Behavior $ readHoldTracked h
660+
661+behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
662+behaviorHoldIdentity = behaviorHold
663+
664+behaviorConst :: a -> Behavior x a
665+behaviorConst !a = Behavior $ return a
666+
667+behaviorPull :: Pull x a -> Behavior x a
668+behaviorPull !p = Behavior $ do
669+ val <- liftIO $ readIORef $ pullValue p
670+ case val of
671+ Just subscribed -> do
672+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
673+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
674+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
675+ return $ pullSubscribedValue subscribed
676+ Nothing -> do
677+ i <- liftIO $ newInvalidatorPull p
678+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
679+ parentsRef <- liftIO $ newIORef []
680+ holdInits <- askBehaviorHoldInits
681+ a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
682+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
683+ parents <- liftIO $ readIORef parentsRef
684+ let subscribed = PullSubscribed
685+ { pullSubscribedValue = a
686+ , pullSubscribedInvalidators = invsRef
687+ , pullSubscribedOwnInvalidator = i
688+ , pullSubscribedParents = parents
689+ }
690+ liftIO $ writeIORef (pullValue p) $ Just subscribed
691+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
692+ return a
693+
694+behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
695+behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
696+
697+{-# INLINE readHoldTracked #-}
698+readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
699+readHoldTracked h = do
700+ result <- liftIO $ readIORef $ holdValue h
701+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
702+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
703+ liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
704+ return result
705+
706+{-# INLINABLE readBehaviorUntracked #-}
707+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
708+readBehaviorUntracked b = do
709+ holdInits <- getDeferralQueue
710+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
711+
712+--------------------------------------------------------------------------------
713+-- Dynamic
714+--------------------------------------------------------------------------------
715+
716+type DynamicS x p = Dynamic x (PatchTarget p) p
717+
718+data Dynamic x target p = Dynamic
719+ { dynamicCurrent :: !(Behavior x target)
720+ , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
721+ }
722+
723+deriving instance (HasSpiderTimeline x) => Functor (Dynamic x target)
724+
725+
726+
727+
728+dynamicHold :: Hold x p -> DynamicS x p
729+dynamicHold !h = Dynamic
730+ { dynamicCurrent = behaviorHold h
731+ , dynamicUpdated = eventHold h
732+ }
733+
734+dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)
735+dynamicHoldIdentity = dynamicHold
736+
737+dynamicConst :: PatchTarget p -> DynamicS x p
738+dynamicConst !a = Dynamic
739+ { dynamicCurrent = behaviorConst a
740+ , dynamicUpdated = eventNever
741+ }
742+
743+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p
744+dynamicDyn !d = Dynamic
745+ { dynamicCurrent = behaviorDyn d
746+ , dynamicUpdated = eventDyn d
747+ }
748+
749+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
750+dynamicDynIdentity = dynamicDyn
751+
752+--------------------------------------------------------------------------------
753+-- Combinators
754+--------------------------------------------------------------------------------
755+
756+--type role Hold representational
757+data Hold x p
758+ = Hold { holdValue :: !(IORef (PatchTarget p))
759+ , holdInvalidators :: !(IORef [Weak (Invalidator x)])
760+ , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
761+ , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
762+#ifdef DEBUG_NODEIDS
763+ , holdNodeId :: Int
764+#endif
765+ }
766+
767+-- | A statically allocated 'SpiderTimeline'
768+data Global
769+
770+{-# NOINLINE globalSpiderTimelineEnv #-}
771+globalSpiderTimelineEnv :: SpiderTimelineEnv Global
772+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
773+
774+-- | Stores all global data relevant to a particular Spider timeline; only one
775+-- value should exist for each type @x@
776+newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}
777+-- We implement SpiderTimelineEnv with a newtype wrapper so
778+-- we can get the coercions we want safely.
779+type role SpiderTimelineEnv nominal
780+
781+data SpiderTimelineEnv' x = SpiderTimelineEnv
782+ { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
783+ , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
784+#ifdef DEBUG
785+ , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
786+#endif
787+ }
788+type role SpiderTimelineEnv' phantom
789+
790+instance Eq (SpiderTimelineEnv x) where
791+ _ == _ = True -- Since only one exists of each type
792+
793+instance GEq SpiderTimelineEnv where
794+ a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)
795+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
796+ else Nothing
797+
798+data EventEnv x
799+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
800+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
801+ , eventEnvDynInits :: !(IORef [SomeDynInit x])
802+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
803+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
804+ , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
805+ , eventEnvIntClears :: !(IORef [Some IntClear])
806+ , eventEnvRootClears :: !(IORef [Some RootClear])
807+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
808+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
809+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
810+ }
811+
812+{-# INLINE runEventM #-}
813+runEventM :: EventM x a -> IO a
814+runEventM = unEventM
815+
816+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
817+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))
818+
819+class MonadIO m => Defer a m where
820+ getDeferralQueue :: m (IORef [a])
821+
822+{-# INLINE defer #-}
823+defer :: Defer a m => a -> m ()
824+defer a = do
825+ q <- getDeferralQueue
826+ liftIO $ modifyIORef' q (a:)
827+
828+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
829+ {-# INLINE getDeferralQueue #-}
830+ getDeferralQueue = asksEventEnv eventEnvAssignments
831+
832+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
833+ {-# INLINE getDeferralQueue #-}
834+ getDeferralQueue = asksEventEnv eventEnvHoldInits
835+
836+instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
837+ {-# INLINE getDeferralQueue #-}
838+ getDeferralQueue = asksEventEnv eventEnvDynInits
839+
840+instance Defer (SomeHoldInit x) (BehaviorM x) where
841+ {-# INLINE getDeferralQueue #-}
842+ getDeferralQueue = BehaviorM $ asks snd
843+
844+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
845+ {-# INLINE getDeferralQueue #-}
846+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
847+
848+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
849+ {-# INLINE getDeferralQueue #-}
850+ getDeferralQueue = asksEventEnv eventEnvMergeInits
851+
852+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
853+ getCurrentHeight :: m Height
854+ scheduleMerge :: Height -> EventM x () -> m ()
855+
856+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
857+ {-# INLINE getCurrentHeight #-}
858+ getCurrentHeight = do
859+ heightRef <- asksEventEnv eventEnvCurrentHeight
860+ liftIO $ readIORef heightRef
861+ {-# INLINE scheduleMerge #-}
862+ scheduleMerge height subscribed = do
863+ delayedRef <- asksEventEnv eventEnvDelayedMerges
864+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
865+
866+class HasSpiderTimeline x where
867+ -- | Retrieve the current SpiderTimelineEnv
868+ spiderTimeline :: SpiderTimelineEnv x
869+
870+instance HasSpiderTimeline Global where
871+ spiderTimeline = globalSpiderTimelineEnv
872+
873+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
874+putCurrentHeight h = do
875+ heightRef <- asksEventEnv eventEnvCurrentHeight
876+ liftIO $ writeIORef heightRef $! h
877+
878+instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
879+ {-# INLINE getDeferralQueue #-}
880+ getDeferralQueue = asksEventEnv eventEnvClears
881+
882+{-# INLINE scheduleClear #-}
883+scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
884+scheduleClear r = defer $ Some $ Clear r
885+
886+instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
887+ {-# INLINE getDeferralQueue #-}
888+ getDeferralQueue = asksEventEnv eventEnvIntClears
889+
890+{-# INLINE scheduleIntClear #-}
891+scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
892+scheduleIntClear r = defer $ Some $ IntClear r
893+
894+instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
895+ {-# INLINE getDeferralQueue #-}
896+ getDeferralQueue = asksEventEnv eventEnvRootClears
897+
898+{-# INLINE scheduleRootClear #-}
899+scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
900+scheduleRootClear r = defer $ Some $ RootClear r
901+
902+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
903+ {-# INLINE getDeferralQueue #-}
904+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
905+
906+-- Note: hold cannot examine its event until after the phase is over
907+{-# INLINE [1] hold #-}
908+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
909+hold v0 e = do
910+ valRef <- liftIO $ newIORef v0
911+ invsRef <- liftIO $ newIORef []
912+ parentRef <- liftIO $ newIORef Nothing
913+#ifdef DEBUG_NODEIDS
914+ nodeId <- liftIO newNodeId
915+#endif
916+ let h = Hold
917+ { holdValue = valRef
918+ , holdInvalidators = invsRef
919+ , holdEvent = e
920+ , holdParent = parentRef
921+#ifdef DEBUG_NODEIDS
922+ , holdNodeId = nodeId
923+#endif
924+ }
925+ defer $ SomeHoldInit h
926+ return h
927+
928+{-# INLINE getHoldEventSubscription #-}
929+getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
930+getHoldEventSubscription h = do
931+ ep <- liftIO $ readIORef $ holdParent h
932+ case ep of
933+ Just subd -> return subd
934+ Nothing -> do
935+ let e = holdEvent h
936+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
937+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
938+ liftIO $ writeIORef subscriptionRef $! subscription
939+ case occ of
940+ Nothing -> return ()
941+ Just o -> do
942+ old <- liftIO $ readIORef $ holdValue h
943+ case apply o old of
944+ Nothing -> return ()
945+ Just new -> do
946+ -- Need to evaluate these so that we don't retain the Hold itself
947+ v <- liftIO $ evaluate $ holdValue h
948+ i <- liftIO $ evaluate $ holdInvalidators h
949+ defer $ SomeAssignment v i new
950+ liftIO $ writeIORef (holdParent h) $ Just subscription
951+ return subscription
952+
953+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
954+
955+-- BehaviorM can sample behaviors
956+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderIO (BehaviorEnv x) a }
957+ deriving (Functor, Applicative, MonadIO, MonadFix, MonadReader (BehaviorEnv x))
958+
959+instance Monad (BehaviorM x) where
960+ {-# INLINE (>>=) #-}
961+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
962+ {-# INLINE (>>) #-}
963+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
964+ {-# INLINE return #-}
965+ return x = BehaviorM $ return x
966+ {-# INLINE fail #-}
967+ fail s = BehaviorM $ fail s
968+
969+data BehaviorSubscribed x a
970+ = forall p. BehaviorSubscribedHold (Hold x p)
971+ | BehaviorSubscribedPull (PullSubscribed x a)
972+
973+newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
974+
975+--type role PullSubscribed representational
976+data PullSubscribed x a
977+ = PullSubscribed { pullSubscribedValue :: !a
978+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
979+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
980+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
981+ }
982+
983+--type role Pull representational
984+data Pull x a
985+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
986+ , pullCompute :: !(BehaviorM x a)
987+#ifdef DEBUG_NODEIDS
988+ , pullNodeId :: Int
989+#endif
990+ }
991+
992+data Invalidator x
993+ = forall a. InvalidatorPull (Pull x a)
994+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
995+
996+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
997+ { rootSubscribedKey :: !(k a)
998+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
999+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1000+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
1001+ , rootSubscribedUninit :: IO ()
1002+ , 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?
1003+#ifdef DEBUG_NODEIDS
1004+ , rootSubscribedNodeId :: Int
1005+#endif
1006+ }
1007+
1008+data Root x k
1009+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
1010+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
1011+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
1012+ }
1013+
1014+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1015+
1016+data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1017+
1018+data SomeMergeUpdate x = SomeMergeUpdate
1019+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1020+ , _someMergeUpdate_invalidateHeight :: !(IO ())
1021+ , _someMergeUpdate_recalculateHeight :: !(IO ())
1022+ }
1023+
1024+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1025+
1026+-- EventM can do everything BehaviorM can, plus create holds
1027+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
1028+
1029+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1030+
1031+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1032+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1033+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1034+ }
1035+
1036+data HeightBag = HeightBag
1037+ { _heightBag_size :: {-# UNPACK #-} !Int
1038+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1039+ }
1040+ deriving (Show, Read, Eq, Ord)
1041+
1042+heightBagEmpty :: HeightBag
1043+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1044+
1045+heightBagSize :: HeightBag -> Int
1046+heightBagSize = _heightBag_size
1047+
1048+heightBagFromList :: [Height] -> HeightBag
1049+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1050+
1051+heightBagAdd :: Height -> HeightBag -> HeightBag
1052+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1053+
1054+heightBagRemove :: Height -> HeightBag -> HeightBag
1055+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1056+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1057+ Just old -> HeightBag (pred s) $ case old of
1058+ 0 -> IntMap.delete h c
1059+ _ -> IntMap.insert h (pred old) c
1060+
1061+heightBagMax :: HeightBag -> Height
1062+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1063+ Just ((h, _), _) -> Height h
1064+ Nothing -> zeroHeight
1065+
1066+heightBagVerify :: HeightBag -> HeightBag
1067+#ifdef DEBUG
1068+heightBagVerify b@(HeightBag s c) = if
1069+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1070+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1071+ | unHeight invalidHeight `IntMap.member` c
1072+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1073+ | otherwise -> b
1074+#else
1075+heightBagVerify = id
1076+#endif
1077+
1078+data FanSubscribedChildren x k v a = FanSubscribedChildren
1079+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1080+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1081+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
1082+ }
1083+
1084+data FanSubscribed x k v
1085+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1086+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1087+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
1088+ , fanSubscribedParent :: !(EventSubscription x)
1089+#ifdef DEBUG_NODEIDS
1090+ , fanSubscribedNodeId :: Int
1091+#endif
1092+ }
1093+
1094+data Fan x k v
1095+ = Fan { fanParent :: !(Event x (DMap k v))
1096+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1097+ }
1098+
1099+data SwitchSubscribed x a
1100+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1101+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1102+ , switchSubscribedHeight :: !(IORef Height)
1103+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1104+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1105+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1106+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1107+ , switchSubscribedParent :: !(Behavior x (Event x a))
1108+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1109+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1110+#ifdef DEBUG_NODEIDS
1111+ , switchSubscribedNodeId :: Int
1112+#endif
1113+ }
1114+
1115+data Switch x a
1116+ = Switch { switchParent :: !(Behavior x (Event x a))
1117+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1118+ }
1119+
1120+#ifdef USE_TEMPLATE_HASKELL
1121+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1122+#endif
1123+data CoincidenceSubscribed x a
1124+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1125+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1126+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1127+ , coincidenceSubscribedHeight :: !(IORef Height)
1128+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1129+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1130+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1131+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1132+#ifdef DEBUG_NODEIDS
1133+ , coincidenceSubscribedNodeId :: Int
1134+#endif
1135+ }
1136+
1137+data Coincidence x a
1138+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1139+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1140+ }
1141+
1142+{-# NOINLINE newInvalidatorSwitch #-}
1143+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1144+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1145+
1146+{-# NOINLINE newInvalidatorPull #-}
1147+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1148+newInvalidatorPull p = return $! InvalidatorPull p
1149+
1150+instance HasSpiderTimeline x => Filterable (Event x) where
1151+ mapMaybe f = push $ return . f
1152+
1153+instance HasSpiderTimeline x => Align (Event x) where
1154+ nil = eventNever
1155+#if MIN_VERSION_these(0, 8, 0)
1156+instance HasSpiderTimeline x => Semialign (Event x) where
1157+#endif
1158+ align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1159+ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1160+
1161+data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1162+ | BuildDyn !(EventM x (PatchTarget p), Event x p)
1163+ | HoldDyn !(Hold x p)
1164+
1165+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1166+
1167+newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)
1168+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1169+
1170+--TODO: Avoid the duplication between this and R.zipDynWith
1171+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)
1172+zipDynWith f da db =
1173+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1174+ ec = flip push eab $ \o -> do
1175+ (a, b) <- case o of
1176+ This (Identity a) -> do
1177+ b <- readBehaviorUntracked $ dynamicCurrent db
1178+ return (a, b)
1179+ That (Identity b) -> do
1180+ a <- readBehaviorUntracked $ dynamicCurrent da
1181+ return (a, b)
1182+ These (Identity a) (Identity b) -> return (a, b)
1183+ return $ Just $ Identity $ f a b
1184+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1185+
1186+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1187+buildDynamic readV0 v' = do
1188+ result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1189+ let !d = Dyn result
1190+ defer $ SomeDynInit d
1191+ return d
1192+
1193+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1194+unsafeBuildDynamic readV0 v' =
1195+ Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
1196+
1197+-- ResultM can read behaviors and events
1198+type ResultM = EventM
1199+
1200+instance HasSpiderTimeline x => Functor (Event x) where
1201+ fmap f = push $ return . Just . f
1202+
1203+instance Functor (Behavior x) where
1204+ fmap f = pull . fmap f . readBehaviorTracked
1205+
1206+{-# INLINE push #-}
1207+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1208+push f e = cacheEvent (pushCheap f e)
1209+
1210+{-# INLINABLE pull #-}
1211+pull :: BehaviorM x a -> Behavior x a
1212+pull a = unsafePerformIO $ do
1213+ ref <- newIORef Nothing
1214+#ifdef DEBUG_NODEIDS
1215+ nid <- newNodeId
1216+#endif
1217+ pure $ behaviorPull $ Pull
1218+ { pullCompute = a
1219+ , pullValue = ref
1220+#ifdef DEBUG_NODEIDS
1221+ , pullNodeId = nid
1222+#endif
1223+ }
1224+
1225+{-# INLINABLE switch #-}
1226+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1227+switch a = unsafePerformIO $ do
1228+ ref <- newIORef Nothing
1229+ pure $ eventSwitch $ Switch
1230+ { switchParent = a
1231+ , switchSubscribed = ref
1232+ }
1233+
1234+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1235+coincidence a = unsafePerformIO $ do
1236+ ref <- newIORef Nothing
1237+ pure $ eventCoincidence $ Coincidence
1238+ { coincidenceParent = a
1239+ , coincidenceSubscribed = ref
1240+ }
1241+
1242+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1243+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1244+run roots after = do
1245+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1246+ let t = spiderTimeline :: SpiderTimelineEnv x
1247+ result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do
1248+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1249+ occBefore <- liftIO $ do
1250+ occBefore <- readIORef occRef
1251+ writeIORef occRef $! DMap.insert k a occBefore
1252+ return occBefore
1253+ if DMap.null occBefore
1254+ then do scheduleRootClear occRef
1255+ return $ Just r
1256+ else return Nothing
1257+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1258+ propagate a subscribersRef
1259+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1260+ let go = do
1261+ delayed <- liftIO $ readIORef delayedRef
1262+ case IntMap.minViewWithKey delayed of
1263+ Nothing -> return ()
1264+ Just ((currentHeight, cur), future) -> do
1265+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1266+ putCurrentHeight $ Height currentHeight
1267+ liftIO $ writeIORef delayedRef $! future
1268+ sequence_ cur
1269+ go
1270+ go
1271+ putCurrentHeight maxBound
1272+ after
1273+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1274+ return result
1275+
1276+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1277+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1278+ height <- liftIO $ readIORef heightRef
1279+ currentHeight <- getCurrentHeight
1280+ case height `compare` currentHeight of
1281+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1282+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1283+ EQ -> a
1284+
1285+newtype Clear a = Clear (IORef (Maybe a))
1286+
1287+newtype IntClear a = IntClear (IORef (IntMap a))
1288+
1289+newtype RootClear k = RootClear (IORef (DMap k Identity))
1290+
1291+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1292+
1293+debugFinalize :: Bool
1294+debugFinalize = False
1295+
1296+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1297+mkWeakPtrWithDebug x debugNote = do
1298+ x' <- evaluate x
1299+ mkWeakPtr x' $
1300+ if debugFinalize
1301+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1302+ else Nothing
1303+
1304+type WeakList a = [Weak a]
1305+
1306+{-# INLINE withIncreasedDepth #-}
1307+#ifdef DEBUG
1308+withIncreasedDepth :: CanTrace x m => m a -> m a
1309+withIncreasedDepth a = do
1310+ spiderTimeline <- askSpiderTimelineEnv
1311+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) succ
1312+ result <- a
1313+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) pred
1314+ return result
1315+#else
1316+withIncreasedDepth :: m a -> m a
1317+withIncreasedDepth = id
1318+#endif
1319+
1320+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1321+
1322+{-# INLINE tracePropagate #-}
1323+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1324+tracePropagate p = traceWhen p debugPropagate
1325+
1326+{-# INLINE traceInvalidate #-}
1327+traceInvalidate :: String -> IO ()
1328+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1329+
1330+{-# INLINE traceWhen #-}
1331+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1332+traceWhen p b message = traceMWhen p b $ return message
1333+
1334+{-# INLINE traceMWhen #-}
1335+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1336+traceMWhen _ b getMessage = when b $ do
1337+ message <- getMessage
1338+#ifdef DEBUG
1339+ spiderTimeline <- askSpiderTimelineEnv
1340+ d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE spiderTimeline
1341+#else
1342+ let d = 0
1343+#endif
1344+ liftIO $ putStrLn $ replicate d ' ' <> message
1345+
1346+whoCreatedIORef :: IORef a -> IO [String]
1347+whoCreatedIORef (IORef a) = whoCreated $! a
1348+
1349+#ifdef DEBUG_CYCLES
1350+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1351+groupByHead = \case
1352+ [] -> []
1353+ (x :| xs) : t -> case groupByHead t of
1354+ [] -> [(x, xs :| [])]
1355+ l@((y, yss) : t')
1356+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1357+ | otherwise -> (x, xs :| []) : l
1358+
1359+listsToForest :: Eq a => [[a]] -> Forest a
1360+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1361+#endif
1362+
1363+{-# INLINE propagateSubscriberHold #-}
1364+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1365+propagateSubscriberHold h a = do
1366+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1367+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1368+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1369+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1370+ case {-# SCC "apply" #-} apply a v of
1371+ Nothing -> return ()
1372+ Just v' -> do
1373+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1374+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1375+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1376+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1377+
1378+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1379+
1380+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1381+runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)
1382+
1383+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1384+askInvalidator = do
1385+ (!m, _) <- ask
1386+ case m of
1387+ Nothing -> return Nothing
1388+ Just (!wi, _) -> return $ Just wi
1389+
1390+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1391+askParentsRef = do
1392+ (!m, _) <- ask
1393+ case m of
1394+ Nothing -> return Nothing
1395+ Just (_, !p) -> return $ Just p
1396+
1397+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1398+askBehaviorHoldInits = do
1399+ (_, !his) <- ask
1400+ return his
1401+
1402+{-# INLINE getDynHold #-}
1403+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1404+getDynHold d = do
1405+ mh <- liftIO $ readIORef $ unDyn d
1406+ case mh of
1407+ HoldDyn h -> return h
1408+ UnsafeDyn (readV0, v') -> do
1409+ holdInits <- getDeferralQueue
1410+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1411+ hold' v0 v'
1412+ BuildDyn (readV0, v') -> do
1413+ v0 <- liftIO $ runEventM readV0
1414+ hold' v0 v'
1415+ where
1416+ hold' v0 v' = do
1417+ h <- hold v0 v'
1418+ liftIO $ writeIORef (unDyn d) $ HoldDyn h
1419+ return h
1420+
1421+
1422+-- Always refers to 0
1423+{-# NOINLINE zeroRef #-}
1424+zeroRef :: IORef Height
1425+zeroRef = unsafePerformIO $ newIORef zeroHeight
1426+
1427+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1428+getRootSubscribed k r sub = do
1429+ mSubscribed <- readIORef $ rootSubscribed r
1430+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1431+ case DMap.lookup k mSubscribed of
1432+ Just subscribed -> {-# SCC "hitRoot" #-} do
1433+ sln <- subscribeRootSubscribed subscribed sub
1434+ occ <- getOcc
1435+ return (sln, subscribed, occ)
1436+ Nothing -> {-# SCC "missRoot" #-} do
1437+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1438+ let !cached = rootSubscribed r
1439+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1440+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1441+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1442+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1443+ writeIORef uninitRef $! uninit
1444+#ifdef DEBUG_NODEIDS
1445+ nid <- newNodeId
1446+#endif
1447+ let !subscribed = RootSubscribed
1448+ { rootSubscribedKey = k
1449+ , rootSubscribedCachedSubscribed = cached
1450+ , rootSubscribedOccurrence = getOcc
1451+ , rootSubscribedSubscribers = subs
1452+ , rootSubscribedUninit = uninit
1453+ , rootSubscribedWeakSelf = weakSelf
1454+#ifdef DEBUG_NODEIDS
1455+ , rootSubscribedNodeId = nid
1456+#endif
1457+ }
1458+ -- If we die at the same moment that all our children die, they will
1459+ -- try to clean us up but will fail because their Weak reference to us
1460+ -- will also be dead. So, if we are dying, check if there are any
1461+ -- children; since children don't bother cleaning themselves up if
1462+ -- their parents are already dead, I don't think there's a race
1463+ -- condition here. However, if there are any children, then we can
1464+ -- infer that we need to clean ourselves up, so we do.
1465+ finalCleanup = do
1466+ cs <- readIORef $ _weakBag_children subs
1467+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1468+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1469+ 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
1470+ occ <- getOcc
1471+ return (sln, subscribed, occ)
1472+
1473+#ifdef USE_TEMPLATE_HASKELL
1474+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1475+#endif
1476+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1477+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1478+ rootSubscribedUninit self
1479+ modifyIORef' cached $ DMap.delete k
1480+
1481+{-# INLINE subscribeRootSubscribed #-}
1482+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1483+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1484+
1485+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1486+
1487+data FanInt x a = FanInt
1488+ { _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
1489+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1490+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1491+ }
1492+
1493+newFanInt :: IO (FanInt x a)
1494+newFanInt = do
1495+ 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
1496+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1497+ occRef <- newIORef $ error "fanInt: no occurrence"
1498+ return $ FanInt
1499+ { _fanInt_subscribers = subscribers
1500+ , _fanInt_subscriptionRef = subscriptionRef
1501+ , _fanInt_occRef = occRef
1502+ }
1503+
1504+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1505+fanInt p = unsafePerformIO $ do
1506+ self <- newFanInt
1507+ pure $ EventSelectorInt $ \k -> Event $ \sub -> do
1508+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1509+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1510+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1511+ { subscriberPropagate = \m -> do
1512+ liftIO $ writeIORef (_fanInt_occRef self) m
1513+ scheduleIntClear $ _fanInt_occRef self
1514+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1515+ FastWeakBag.traverse b $ \s -> do
1516+ subscriberPropagate s v
1517+ , subscriberInvalidateHeight = \old -> do
1518+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1519+ FastWeakBag.traverse b $ \s -> do
1520+ subscriberInvalidateHeight s old
1521+ , subscriberRecalculateHeight = \new -> do
1522+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1523+ FastWeakBag.traverse b $ \s -> do
1524+ subscriberRecalculateHeight s new
1525+ }
1526+ liftIO $ do
1527+ writeIORef (_fanInt_subscriptionRef self) subscription
1528+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1529+ scheduleIntClear $ _fanInt_occRef self
1530+ liftIO $ do
1531+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1532+ Nothing -> do
1533+ b <- FastWeakBag.empty
1534+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1535+ return b
1536+ Just b -> return b
1537+ t <- liftIO $ FastWeakBag.insert sub b
1538+ currentOcc <- readIORef (_fanInt_occRef self)
1539+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1540+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1541+
1542+{-# INLINABLE getFanSubscribed #-}
1543+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))
1544+getFanSubscribed k f sub = do
1545+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1546+ case mSubscribed of
1547+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1548+ sln <- subscribeFanSubscribed k subscribed sub
1549+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1550+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1551+ Nothing -> {-# SCC "missFan" #-} do
1552+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1553+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1554+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1555+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1556+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1557+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1558+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1559+ occRef <- liftIO $ newIORef parentOcc
1560+ when (isJust parentOcc) $ scheduleClear occRef
1561+#ifdef DEBUG_NODEIDS
1562+ nid <- liftIO newNodeId
1563+#endif
1564+ let subscribed = FanSubscribed
1565+ { fanSubscribedCachedSubscribed = fanSubscribed f
1566+ , fanSubscribedOccurrence = occRef
1567+ , fanSubscribedParent = subscription
1568+ , fanSubscribedSubscribers = subscribersRef
1569+#ifdef DEBUG_NODEIDS
1570+ , fanSubscribedNodeId = nid
1571+#endif
1572+ }
1573+ let !self = (k, subscribed)
1574+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1575+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1576+ liftIO $ writeIORef subscribedRef $! subscribed
1577+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1578+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1579+
1580+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
1581+cleanupFanSubscribed (k, subscribed) = do
1582+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1583+ let reducedSubscribers = DMap.delete k subscribers
1584+ if DMap.null reducedSubscribers
1585+ then do
1586+ unsubscribe $ fanSubscribedParent subscribed
1587+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1588+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1589+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1590+
1591+{-# INLINE subscribeFanSubscribed #-}
1592+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
1593+subscribeFanSubscribed k subscribed sub = do
1594+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1595+ case DMap.lookup k subscribers of
1596+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1597+ let !self = (k, subscribed)
1598+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1599+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1600+ 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
1601+ return sln
1602+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1603+
1604+{-# INLINABLE getSwitchSubscribed #-}
1605+getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1606+getSwitchSubscribed s sub = do
1607+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1608+ case mSubscribed of
1609+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1610+ sln <- subscribeSwitchSubscribed subscribed sub
1611+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1612+ return (sln, subscribed, occ)
1613+ Nothing -> {-# SCC "missSwitch" #-} do
1614+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1615+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1616+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1617+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1618+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1619+ wiRef <- liftIO $ newIORef wi
1620+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1621+ holdInits <- getDeferralQueue
1622+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1623+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1624+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1625+ subscriptionRef <- liftIO $ newIORef subscription
1626+ occRef <- liftIO $ newIORef parentOcc
1627+ when (isJust parentOcc) $ scheduleClear occRef
1628+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1629+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1630+#ifdef DEBUG_NODEIDS
1631+ nid <- liftIO newNodeId
1632+#endif
1633+ let !subscribed = SwitchSubscribed
1634+ { switchSubscribedCachedSubscribed = switchSubscribed s
1635+ , switchSubscribedOccurrence = occRef
1636+ , switchSubscribedHeight = heightRef
1637+ , switchSubscribedSubscribers = subs
1638+ , switchSubscribedOwnInvalidator = i
1639+ , switchSubscribedOwnWeakInvalidator = wiRef
1640+ , switchSubscribedBehaviorParents = parentsRef
1641+ , switchSubscribedParent = switchParent s
1642+ , switchSubscribedCurrentParent = subscriptionRef
1643+ , switchSubscribedWeakSelf = weakSelf
1644+#ifdef DEBUG_NODEIDS
1645+ , switchSubscribedNodeId = nid
1646+#endif
1647+ }
1648+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1649+ liftIO $ writeIORef subscribedRef $! subscribed
1650+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1651+ return (slnForSub, subscribed, parentOcc)
1652+
1653+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1654+cleanupSwitchSubscribed subscribed = do
1655+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1656+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1657+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1658+
1659+{-# INLINE subscribeSwitchSubscribed #-}
1660+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1661+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1662+
1663+{-# INLINABLE getCoincidenceSubscribed #-}
1664+getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1665+getCoincidenceSubscribed c sub = do
1666+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1667+ case mSubscribed of
1668+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1669+ sln <- subscribeCoincidenceSubscribed subscribed sub
1670+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1671+ return (sln, subscribed, occ)
1672+ Nothing -> {-# SCC "missCoincidence" #-} do
1673+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1674+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1675+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1676+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1677+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1678+ (occ, height, mInnerSubd) <- case outerOcc of
1679+ Nothing -> return (Nothing, outerHeight, Nothing)
1680+ Just o -> do
1681+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1682+ return (occ, height, Just innerSubd)
1683+ occRef <- liftIO $ newIORef occ
1684+ when (isJust occ) $ scheduleClear occRef
1685+ heightRef <- liftIO $ newIORef height
1686+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1687+ scheduleClear innerSubdRef
1688+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1689+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1690+#ifdef DEBUG_NODEIDS
1691+ nid <- liftIO newNodeId
1692+#endif
1693+ let subscribed = CoincidenceSubscribed
1694+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1695+ , coincidenceSubscribedOccurrence = occRef
1696+ , coincidenceSubscribedHeight = heightRef
1697+ , coincidenceSubscribedSubscribers = subs
1698+ , coincidenceSubscribedOuter = subOuter
1699+ , coincidenceSubscribedOuterParent = outerSubscription
1700+ , coincidenceSubscribedInnerParent = innerSubdRef
1701+ , coincidenceSubscribedWeakSelf = weakSelf
1702+#ifdef DEBUG_NODEIDS
1703+ , coincidenceSubscribedNodeId = nid
1704+#endif
1705+ }
1706+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1707+ liftIO $ writeIORef subscribedRef $! subscribed
1708+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1709+ return (slnForSub, subscribed, occ)
1710+
1711+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1712+cleanupCoincidenceSubscribed subscribed = do
1713+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1714+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1715+
1716+{-# INLINE subscribeCoincidenceSubscribed #-}
1717+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1718+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1719+
1720+{-# INLINE mergeG #-}
1721+mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1722+ => (forall a. q a -> Event x (v a))
1723+ -> DynamicS x (PatchDMap k q) -> Event x (DMap k v)
1724+mergeG nt d = cacheEvent (mergeCheap nt d)
1725+
1726+{-# INLINE mergeWithMove #-}
1727+mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1728+ => (forall a. q a -> Event x (v a))
1729+ -> DynamicS x (PatchDMapWithMove k q) -> Event x (DMap k v)
1730+mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1731+
1732+{-# INLINE [1] mergeCheap #-}
1733+mergeCheap
1734+ :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1735+ => (forall a. q a -> Event x (v a))
1736+ -> DynamicS x (PatchDMap k q)
1737+ -> Event x (DMap k v)
1738+mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
1739+ where
1740+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1741+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1742+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1743+ (mOldSubd, newPs) <- case me of
1744+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1745+ Just e -> do
1746+ let s = subscriber $ return k
1747+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1748+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1749+ let newParent = MergeSubscribedParent subscription
1750+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1751+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1752+ forM_ mOldSubd $ \oldSubd -> do
1753+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1754+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1755+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1756+ foldM f ([], oldParents) $ DMap.toList p
1757+
1758+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1759+ getInitialSubscribers initialParents subscriber = do
1760+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1761+ let s = subscriber $ return k
1762+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1763+ height <- liftIO $ getEventSubscribedHeight parentSubd
1764+ return (fmap (\x -> k :=> x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1765+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1766+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1767+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1768+ )
1769+
1770+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1771+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1772+
1773+{-# INLINE [1] mergeCheapWithMove #-}
1774+mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1775+ => (forall a. q a -> Event x (v a))
1776+ -> DynamicS x (PatchDMapWithMove k q)
1777+ -> Event x (DMap k v)
1778+mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
1779+ where
1780+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1781+ updateMe subscriber heightBagRef oldParents p = do
1782+ -- Prepare new parents for insertion
1783+ let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1784+ subscribeParent k e = do
1785+ keyRef <- liftIO $ newIORef k
1786+ let s = subscriber $ liftIO $ readIORef keyRef
1787+ subscription@(EventSubscription _ subd) <- subscribe e s
1788+ liftIO $ do
1789+ newParentHeight <- getEventSubscribedHeight subd
1790+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1791+ return $ MergeSubscribedParentWithMove subscription keyRef
1792+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1793+ -- Collect old parents for deletion and update the keys of moved parents
1794+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1795+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1796+ Nothing -> do
1797+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1798+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1799+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1800+ Just toKey -> do
1801+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1802+ return Nothing
1803+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1804+ return (toDelete, applyAlways p' oldParents)
1805+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1806+ getInitialSubscribers initialParents subscriber = do
1807+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1808+ keyRef <- liftIO $ newIORef k
1809+ let s = subscriber $ liftIO $ readIORef keyRef
1810+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1811+ height <- liftIO $ getEventSubscribedHeight parentSubd
1812+ return (fmap (\x -> k :=> x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1813+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1814+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1815+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1816+ )
1817+
1818+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1819+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1820+
1821+type MergeUpdateFunc k v x p s
1822+ = (forall a. EventM x (k a) -> Subscriber x (v a))
1823+ -> IORef HeightBag
1824+ -> DMap k s
1825+ -> p
1826+ -> EventM x ([EventSubscription x], DMap k s)
1827+
1828+type MergeInitFunc k v q x s
1829+ = DMap k q
1830+ -> (forall a. EventM x (k a) -> Subscriber x (v a))
1831+ -> EventM x (DMap k v, [Height], DMap k s)
1832+
1833+type MergeDestroyFunc k s
1834+ = DMap k s
1835+ -> IO ()
1836+
1837+data Merge x k v s = Merge
1838+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1839+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1840+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1841+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1842+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
1843+ }
1844+
1845+invalidateMergeHeight :: Merge x k v s -> IO ()
1846+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1847+
1848+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1849+invalidateMergeHeight' heightRef sub = do
1850+ oldHeight <- readIORef heightRef
1851+ 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
1852+ writeIORef heightRef $! invalidHeight
1853+ subscriberInvalidateHeight sub oldHeight
1854+
1855+revalidateMergeHeight :: Merge x k v s -> IO ()
1856+revalidateMergeHeight m = do
1857+ currentHeight <- readIORef $ _merge_heightRef m
1858+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1859+ heights <- readIORef $ _merge_heightBagRef m
1860+ parents <- readIORef $ _merge_parentsRef m
1861+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1862+ case heightBagSize heights `compare` DMap.size parents of
1863+ LT -> return ()
1864+ EQ -> do
1865+ let height = succHeight $ heightBagMax heights
1866+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1867+ writeIORef (_merge_heightRef m) $! height
1868+ subscriberRecalculateHeight (_merge_sub m) height
1869+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1870+
1871+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
1872+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1873+ vals <- liftIO $ readIORef $ _merge_accumRef m
1874+ 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
1875+ --TODO: Assert that m is not empty
1876+ subscriberPropagate (_merge_sub m) vals
1877+
1878+mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
1879+mergeSubscriber m getKey = Subscriber
1880+ { subscriberPropagate = \a -> do
1881+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1882+ k <- getKey
1883+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
1884+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1885+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1886+ when (DMap.null oldM) $ do -- Only schedule the firing once
1887+ height <- liftIO $ readIORef $ _merge_heightRef m
1888+ --TODO: assertions about height
1889+ currentHeight <- getCurrentHeight
1890+ when (height <= currentHeight) $ do
1891+ if height /= invalidHeight
1892+ then do
1893+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1894+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1895+ else liftIO $ do
1896+#ifdef DEBUG_CYCLES
1897+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1898+ stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
1899+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1900+#else
1901+ let cycleInfo = ""
1902+#endif
1903+ error $ "Causality loop found" <> cycleInfo
1904+ scheduleMergeSelf m height
1905+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1906+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1907+ invalidateMergeHeight m
1908+ , subscriberRecalculateHeight = \new -> do
1909+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1910+ revalidateMergeHeight m
1911+ }
1912+
1913+--TODO: Be able to run as much of this as possible promptly
1914+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
1915+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1916+ where updateMe = do
1917+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1918+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1919+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1920+ return subscriptionsToKill
1921+
1922+{-# INLINE mergeGCheap' #-}
1923+mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1924+ => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> DynamicS x p -> Event x (DMap k v)
1925+mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1926+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1927+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1928+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1929+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1930+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1931+ let m = Merge
1932+ { _merge_parentsRef = parentsRef
1933+ , _merge_heightBagRef = heightBagRef
1934+ , _merge_heightRef = heightRef
1935+ , _merge_sub = sub
1936+ , _merge_accumRef = accumRef
1937+ }
1938+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1939+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1940+ myHeight = if invalidHeight `elem` heights
1941+ then invalidHeight
1942+ else succHeight $ heightBagMax myHeightBag
1943+ currentHeight <- getCurrentHeight
1944+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1945+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1946+ else (Nothing, dm)
1947+ unless (DMap.null accum) $ do
1948+ scheduleMergeSelf m myHeight
1949+ liftIO $ writeIORef accumRef $! accum
1950+ liftIO $ writeIORef heightRef $! myHeight
1951+ liftIO $ writeIORef heightBagRef $! myHeightBag
1952+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1953+ liftIO $ writeIORef parentsRef $! initialParentState
1954+ defer $ SomeMergeInit $ do
1955+ let s = Subscriber
1956+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1957+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1958+ defer $ updateMerge m updateFunc a
1959+ , subscriberInvalidateHeight = \_ -> return ()
1960+ , subscriberRecalculateHeight = \_ -> return ()
1961+ }
1962+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1963+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1964+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1965+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1966+ -- its subscription.
1967+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1968+ let unsubscribeAll = destroy =<< readIORef parentsRef
1969+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1970+ , occ
1971+ )
1972+
1973+mergeInt :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1974+mergeInt = cacheEvent . mergeIntCheap
1975+
1976+{-# INLINABLE mergeIntCheap #-}
1977+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1978+mergeIntCheap d = Event $ \sub -> do
1979+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1980+ accum <- liftIO $ FastMutableIntMap.newEmpty
1981+ heightRef <- liftIO $ newIORef zeroHeight
1982+ heightBagRef <- liftIO $ newIORef heightBagEmpty
1983+ parents <- liftIO $ FastMutableIntMap.newEmpty
1984+ let scheduleSelf = do
1985+ height <- liftIO $ readIORef $ heightRef
1986+ scheduleMerge' height heightRef $ do
1987+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1988+ subscriberPropagate sub vals
1989+ invalidateMyHeight = do
1990+ invalidateMergeHeight' heightRef sub
1991+ recalculateMyHeight = do
1992+ currentHeight <- readIORef heightRef
1993+ 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?
1994+ heights <- readIORef heightBagRef
1995+ numParents <- FastMutableIntMap.size parents
1996+ case heightBagSize heights `compare` numParents of
1997+ LT -> return ()
1998+ EQ -> do
1999+ let height = succHeight $ heightBagMax heights
2000+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
2001+ writeIORef heightRef $! height
2002+ subscriberRecalculateHeight sub height
2003+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
2004+ mySubscriber k = Subscriber
2005+ { subscriberPropagate = \a -> do
2006+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2007+ liftIO $ FastMutableIntMap.insert accum k a
2008+ when wasEmpty scheduleSelf
2009+ , subscriberInvalidateHeight = \old -> do
2010+ modifyIORef' heightBagRef $ heightBagRemove old
2011+ invalidateMyHeight
2012+ , subscriberRecalculateHeight = \new -> do
2013+ modifyIORef' heightBagRef $ heightBagAdd new
2014+ recalculateMyHeight
2015+ }
2016+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
2017+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
2018+ liftIO $ do
2019+ forM_ parentOcc $ FastMutableIntMap.insert accum k
2020+ FastMutableIntMap.insert parents k subscription
2021+ height <- getEventSubscribedHeight parentSubd
2022+ if height == invalidHeight
2023+ then writeIORef heightRef invalidHeight
2024+ else do
2025+ modifyIORef' heightBagRef $ heightBagAdd height
2026+ modifyIORef' heightRef $ \oldHeight ->
2027+ if oldHeight == invalidHeight
2028+ then invalidHeight
2029+ else max (succHeight height) oldHeight
2030+ myHeight <- liftIO $ readIORef heightRef
2031+ currentHeight <- getCurrentHeight
2032+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2033+ occ <- if currentHeight >= myHeight -- If we should have fired by now
2034+ then if isEmpty
2035+ then return Nothing
2036+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2037+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2038+ return Nothing
2039+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2040+ defer $ SomeMergeInit $ do
2041+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2042+ where
2043+ u = do
2044+ let f k newParent = do
2045+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2046+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2047+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2048+ return subscription
2049+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2050+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2051+ liftIO $ for_ oldParents $ \oldParent -> do
2052+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2053+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2054+ return $ IntMap.elems oldParents
2055+ let s = Subscriber
2056+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2057+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2058+ defer $ updateMe a
2059+ , subscriberInvalidateHeight = \_ -> return ()
2060+ , subscriberRecalculateHeight = \_ -> return ()
2061+ }
2062+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2063+ forM_ change $ \c -> defer $ updateMe c
2064+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2065+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2066+ -- its subscription.
2067+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2068+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2069+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2070+ , occ
2071+ )
2072+
2073+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2074+newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
2075+
2076+fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2077+fanG e = unsafePerformIO $ do
2078+ ref <- newIORef Nothing
2079+ let f = Fan
2080+ { fanParent = e
2081+ , fanSubscribed = ref
2082+ }
2083+ pure $ EventSelectorG $ \k -> eventFan k f
2084+
2085+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2086+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2087+ holdInits <- liftIO $ readIORef holdInitRef
2088+ dynInits <- liftIO $ readIORef dynInitRef
2089+ mergeInits <- liftIO $ readIORef mergeInitRef
2090+ unless (null holdInits && null dynInits && null mergeInits) $ do
2091+ liftIO $ writeIORef holdInitRef []
2092+ liftIO $ writeIORef dynInitRef []
2093+ liftIO $ writeIORef mergeInitRef []
2094+ mapM_ initHold holdInits
2095+ mapM_ initDyn dynInits
2096+ mapM_ unSomeMergeInit mergeInits
2097+ runHoldInits holdInitRef dynInitRef mergeInitRef
2098+
2099+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2100+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2101+
2102+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2103+initDyn (SomeDynInit d) = void $ getDynHold d
2104+
2105+newEventEnv :: IO (EventEnv x)
2106+newEventEnv = do
2107+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2108+ holdInitRef <- newIORef []
2109+ dynInitRef <- newIORef []
2110+ mergeUpdateRef <- newIORef []
2111+ mergeInitRef <- newIORef []
2112+ heightRef <- newIORef zeroHeight
2113+ toClearRef <- newIORef []
2114+ toClearIntRef <- newIORef []
2115+ toClearRootRef <- newIORef []
2116+ coincidenceInfosRef <- newIORef []
2117+ delayedRef <- newIORef IntMap.empty
2118+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2119+
2120+clearEventEnv :: EventEnv x -> IO ()
2121+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2122+ writeIORef toAssignRef []
2123+ writeIORef holdInitRef []
2124+ writeIORef dynInitRef []
2125+ writeIORef mergeUpdateRef []
2126+ writeIORef mergeInitRef []
2127+ writeIORef heightRef zeroHeight
2128+ writeIORef toClearRef []
2129+ writeIORef toClearIntRef []
2130+ writeIORef toClearRootRef []
2131+ writeIORef coincidenceInfosRef []
2132+ writeIORef delayedRef IntMap.empty
2133+
2134+-- | Run an event action outside of a frame
2135+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2136+runFrame a = SpiderHost $ do
2137+ let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
2138+ let go = do
2139+ result <- a
2140+ 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
2141+ return result
2142+ result <- runEventM go
2143+ toClear <- readIORef $ eventEnvClears env
2144+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2145+ toClearInt <- readIORef $ eventEnvIntClears env
2146+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2147+ toClearRoot <- readIORef $ eventEnvRootClears env
2148+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2149+ toAssign <- readIORef $ eventEnvAssignments env
2150+ toReconnectRef <- newIORef []
2151+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2152+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2153+ writeIORef vRef v
2154+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2155+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2156+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2157+ writeIORef (eventEnvMergeUpdates env) []
2158+ when debugPropagate $ putStrLn "Updating merges"
2159+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2160+ when debugPropagate $ putStrLn "Updating merges done"
2161+ toReconnect <- readIORef toReconnectRef
2162+ clearEventEnv env
2163+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2164+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2165+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2166+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2167+ finalize wi
2168+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2169+ wi' <- mkWeakPtrWithDebug i "wi'"
2170+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2171+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2172+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2173+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2174+ 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
2175+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2176+ sub <- newSubscriberSwitch subscribed
2177+ 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
2178+ {-
2179+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2180+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2181+ EventRoot _ -> "EventRoot"
2182+ EventNever -> "EventNever"
2183+ _ -> "something else"
2184+ -}
2185+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2186+ return oldSubscription
2187+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2188+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2189+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2190+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2191+ parentHeight <- getEventSubscribedHeight subd'
2192+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2193+ when (parentHeight /= myHeight) $ do
2194+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2195+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2196+ 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
2197+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2198+ unsubscribe subscription
2199+ mapM_ invalidateCoincidenceHeight mcs
2200+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2201+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2202+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2203+ height <- calculateSwitchHeight subscribed
2204+ updateSwitchHeight height subscribed
2205+ return result
2206+
2207+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2208+
2209+{-# INLINE zeroHeight #-}
2210+zeroHeight :: Height
2211+zeroHeight = Height 0
2212+
2213+{-# INLINE invalidHeight #-}
2214+invalidHeight :: Height
2215+invalidHeight = Height (-1000)
2216+
2217+#ifdef DEBUG_CYCLES
2218+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2219+{-# INLINE invalidHeightBeingTraversed #-}
2220+invalidHeightBeingTraversed :: Height
2221+invalidHeightBeingTraversed = Height (-1001)
2222+#endif
2223+
2224+{-# INLINE succHeight #-}
2225+succHeight :: Height -> Height
2226+succHeight h@(Height a) =
2227+ if h == invalidHeight
2228+ then invalidHeight
2229+ else Height $ succ a
2230+
2231+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2232+invalidateCoincidenceHeight subscribed = do
2233+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2234+ when (oldHeight /= invalidHeight) $ do
2235+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2236+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2237+
2238+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2239+updateSwitchHeight new subscribed = do
2240+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2241+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2242+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2243+ writeIORef (switchSubscribedHeight subscribed) $! new
2244+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2245+
2246+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2247+recalculateCoincidenceHeight subscribed = do
2248+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2249+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2250+ height <- calculateCoincidenceHeight subscribed
2251+ when (height /= invalidHeight) $ do
2252+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2253+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2254+
2255+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2256+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2257+
2258+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2259+calculateCoincidenceHeight subscribed = do
2260+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2261+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2262+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2263+
2264+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2265+
2266+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2267+invalidate toReconnectRef wis = do
2268+ forM_ wis $ \wi -> do
2269+ mi <- deRefWeak wi
2270+ case mi of
2271+ Nothing -> do
2272+ traceInvalidate "invalidate Dead"
2273+ return () --TODO: Should we clean this up here?
2274+ Just i -> do
2275+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2276+ case i of
2277+ InvalidatorPull p -> do
2278+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2279+ mVal <- readIORef $ pullValue p
2280+ forM_ mVal $ \val -> do
2281+ writeIORef (pullValue p) Nothing
2282+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2283+ InvalidatorSwitch subscribed -> do
2284+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2285+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2286+ 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
2287+
2288+--------------------------------------------------------------------------------
2289+-- Reflex integration
2290+--------------------------------------------------------------------------------
2291+
2292+-- | Designates the default, global Spider timeline
2293+data SpiderTimeline x
2294+type role SpiderTimeline nominal
2295+
2296+-- | The default, global Spider environment
2297+type Spider = SpiderTimeline Global
2298+
2299+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2300+ {-# INLINABLE sample #-}
2301+ sample (SpiderBehavior b) = readBehaviorUntracked b
2302+
2303+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2304+ {-# INLINABLE hold #-}
2305+ hold = holdSpiderEventM
2306+ {-# INLINABLE holdDyn #-}
2307+ holdDyn = holdDynSpiderEventM
2308+ {-# INLINABLE holdIncremental #-}
2309+ holdIncremental = holdIncrementalSpiderEventM
2310+ {-# INLINABLE buildDynamic #-}
2311+ buildDynamic = buildDynamicSpiderEventM
2312+ {-# INLINABLE headE #-}
2313+ headE = R.slowHeadE
2314+-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2315+
2316+instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2317+ {-# INLINABLE sample #-}
2318+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2319+
2320+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2321+ {-# INLINABLE sample #-}
2322+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2323+
2324+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2325+ {-# INLINABLE hold #-}
2326+ hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2327+ {-# INLINABLE holdDyn #-}
2328+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2329+ {-# INLINABLE holdIncremental #-}
2330+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2331+ {-# INLINABLE buildDynamic #-}
2332+ buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2333+ {-# INLINABLE headE #-}
2334+ headE = R.slowHeadE
2335+-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2336+
2337+instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2338+ {-# INLINE return #-}
2339+ return = pure
2340+ {-# INLINE (>>=) #-}
2341+ x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2342+ {-# INLINE (>>) #-}
2343+ (>>) = (*>)
2344+ {-# INLINE fail #-}
2345+ fail _ = error "Dynamic does not support 'fail'"
2346+
2347+{-# INLINABLE newJoinDyn #-}
2348+newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2349+newJoinDyn d =
2350+ let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2351+ eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2352+ eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2353+ eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2354+ v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2355+ in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2356+
2357+instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2358+ fmap = mapDynamicSpider
2359+ x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2360+
2361+mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2362+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2363+{-# INLINE [1] mapDynamicSpider #-}
2364+
2365+instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2366+ pure = SpiderDynamic . dynamicConst
2367+#if MIN_VERSION_base(4,10,0)
2368+ liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2369+#endif
2370+ SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2371+ a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2372+ (<*) = flip (*>) -- There are no effects, so order doesn't matter
2373+
2374+holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2375+holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2376+
2377+holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2378+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2379+
2380+holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2381+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2382+
2383+buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2384+buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2385+
2386+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2387+ {-# INLINABLE hold #-}
2388+ hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2389+ {-# INLINABLE holdDyn #-}
2390+ holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2391+ {-# INLINABLE holdIncremental #-}
2392+ holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2393+ {-# INLINABLE buildDynamic #-}
2394+ buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2395+ {-# INLINABLE headE #-}
2396+ headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2397+
2398+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2399+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2400+
2401+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2402+ {-# INLINABLE hold #-}
2403+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2404+ {-# INLINABLE holdDyn #-}
2405+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2406+ {-# INLINABLE holdIncremental #-}
2407+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2408+ {-# INLINABLE buildDynamic #-}
2409+ buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2410+ {-# INLINABLE headE #-}
2411+ headE = R.slowHeadE
2412+-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2413+
2414+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2415+ {-# INLINABLE sample #-}
2416+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2417+
2418+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2419+ {-# INLINABLE sample #-}
2420+ sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2421+
2422+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2423+ {-# INLINABLE hold #-}
2424+ hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2425+ {-# INLINABLE holdDyn #-}
2426+ holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2427+ {-# INLINABLE holdIncremental #-}
2428+ holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2429+ {-# INLINABLE buildDynamic #-}
2430+ buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2431+ {-# INLINABLE headE #-}
2432+ headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2433+
2434+--------------------------------------------------------------------------------
2435+-- Deprecated items
2436+--------------------------------------------------------------------------------
2437+
2438+-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2439+{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2440+type SpiderEnv = SpiderTimeline
2441+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2442+ {-# INLINABLE subscribeEvent #-}
2443+ subscribeEvent e = SpiderHostFrame $ do
2444+ --TODO: Unsubscribe eventually (manually and/or with weak ref)
2445+ val <- liftIO $ newIORef Nothing
2446+ subscription <- subscribe (unSpiderEvent e) $ Subscriber
2447+ { subscriberPropagate = \a -> do
2448+ liftIO $ writeIORef val $ Just a
2449+ scheduleClear val
2450+ , subscriberInvalidateHeight = \_ -> return ()
2451+ , subscriberRecalculateHeight = \_ -> return ()
2452+ }
2453+ return $ SpiderEventHandle
2454+ { spiderEventHandleSubscription = subscription
2455+ , spiderEventHandleValue = val
2456+ }
2457+
2458+instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2459+ type EventTrigger (SpiderTimeline x) = RootTrigger x
2460+ type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2461+ type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2462+
2463+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2464+ {-# NOINLINE readEvent #-}
2465+ readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2466+ result <- readIORef $ spiderEventHandleValue h
2467+ touch h
2468+ return result
2469+
2470+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2471+ newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2472+ newFanEventWithTrigger f = SpiderHost $ do
2473+ es <- newFanEventWithTriggerIO f
2474+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2475+
2476+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2477+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2478+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2479+ es <- newFanEventWithTriggerIO f
2480+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2481+
2482+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2483+ {-# INLINABLE subscribeEvent #-}
2484+ subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2485+
2486+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2487+ type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2488+ fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2489+ runHostFrame = runFrame . runSpiderHostFrame
2490+
2491+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2492+unsafeNewSpiderTimelineEnv = do
2493+ lock <- newMVar ()
2494+ env <- newEventEnv
2495+#ifdef DEBUG
2496+ depthRef <- newIORef 0
2497+#endif
2498+ return $ STE $ SpiderTimelineEnv
2499+ { _spiderTimeline_lock = lock
2500+ , _spiderTimeline_eventEnv = env
2501+#ifdef DEBUG
2502+ , _spiderTimeline_depth = depthRef
2503+#endif
2504+ }
2505+
2506+-- | Create a new SpiderTimelineEnv
2507+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2508+newSpiderTimeline = withSpiderTimeline (pure . Some)
2509+
2510+data LocalSpiderTimeline (x :: Type) s
2511+
2512+instance Reifies s (SpiderTimelineEnv x) =>
2513+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2514+ spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)
2515+
2516+localSpiderTimeline
2517+ :: proxy s
2518+ -> SpiderTimelineEnv x
2519+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2520+localSpiderTimeline _ = coerce
2521+
2522+-- | Pass a new timeline to the given function.
2523+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2524+withSpiderTimeline k = do
2525+ env <- unsafeNewSpiderTimelineEnv
2526+ reify env $ \s -> k $ localSpiderTimeline s env
2527+
2528+newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2529+
2530+type ComputeM = EventM
2531+
2532+newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2533+
2534+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2535+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2536+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2537+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2538+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: DynamicS x (Identity a) } -- deriving (Functor, Applicative, Monad)
2539+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: DynamicS x p }
2540+ type PullM (SpiderTimeline x) = SpiderPullM x
2541+ type PushM (SpiderTimeline x) = SpiderPushM x
2542+ {-# INLINABLE never #-}
2543+ never = SpiderEvent eventNever
2544+ {-# INLINABLE constant #-}
2545+ constant = SpiderBehavior . behaviorConst
2546+ {-# INLINE push #-}
2547+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2548+ {-# INLINE pushCheap #-}
2549+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2550+ {-# INLINABLE pull #-}
2551+ pull = SpiderBehavior . pull . coerce
2552+ {-# INLINABLE fanG #-}
2553+ fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2554+ {-# INLINABLE mergeG #-}
2555+ mergeG
2556+ :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2557+ => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2558+ -> DMap k q
2559+ -> R.Event (SpiderTimeline x) (DMap k v)
2560+ mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2561+ {-# INLINABLE switch #-}
2562+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2563+ {-# INLINABLE coincidence #-}
2564+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2565+ {-# INLINABLE current #-}
2566+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2567+ {-# INLINABLE updated #-}
2568+ updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic
2569+ {-# INLINABLE unsafeBuildDynamic #-}
2570+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2571+ {-# INLINABLE unsafeBuildIncremental #-}
2572+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2573+ {-# INLINABLE mergeIncrementalG #-}
2574+ mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2575+ {-# INLINABLE mergeIncrementalWithMoveG #-}
2576+ mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2577+ {-# INLINABLE currentIncremental #-}
2578+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2579+ {-# INLINABLE updatedIncremental #-}
2580+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2581+ {-# INLINABLE incrementalToDynamic #-}
2582+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2583+ c <- readBehaviorUntracked $ dynamicCurrent i
2584+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2585+ eventCoercion Coercion = Coercion
2586+ behaviorCoercion Coercion = Coercion
2587+ dynamicCoercion Coercion = Coercion
2588+ incrementalCoercion Coercion Coercion = Coercion
2589+ {-# INLINABLE mergeIntIncremental #-}
2590+ mergeIntIncremental = SpiderEvent . mergeInt . coerce
2591+ {-# INLINABLE fanInt #-}
2592+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2593+
2594+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2595+
2596+data SpiderEventHandle x a = SpiderEventHandle
2597+ { spiderEventHandleSubscription :: EventSubscription x
2598+ , spiderEventHandleValue :: IORef (Maybe a)
2599+ }
2600+
2601+instance MonadRef (EventM x) where
2602+ type Ref (EventM x) = Ref IO
2603+ {-# INLINABLE newRef #-}
2604+ {-# INLINABLE readRef #-}
2605+ {-# INLINABLE writeRef #-}
2606+ newRef = liftIO . newRef
2607+ readRef = liftIO . readRef
2608+ writeRef r a = liftIO $ writeRef r a
2609+
2610+instance MonadAtomicRef (EventM x) where
2611+ {-# INLINABLE atomicModifyRef #-}
2612+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2613+
2614+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2615+newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2616+
2617+instance Monad (SpiderHost x) where
2618+ {-# INLINABLE (>>=) #-}
2619+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2620+ {-# INLINABLE (>>) #-}
2621+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2622+ {-# INLINABLE return #-}
2623+ return x = SpiderHost $ return x
2624+ {-# INLINABLE fail #-}
2625+ fail s = SpiderHost $ fail s
2626+
2627+-- | Run an action affecting the global Spider timeline; this will be guarded by
2628+-- a mutex for that timeline
2629+runSpiderHost :: SpiderHost Global a -> IO a
2630+runSpiderHost (SpiderHost a) = a
2631+
2632+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2633+-- mutex for that timeline
2634+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2635+runSpiderHostForTimeline (SpiderHost a) _ = a
2636+
2637+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2638+ deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2639+
2640+instance Monad (SpiderHostFrame x) where
2641+ {-# INLINABLE (>>=) #-}
2642+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2643+ {-# INLINABLE (>>) #-}
2644+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2645+ {-# INLINABLE return #-}
2646+ return x = SpiderHostFrame $ return x
2647+ {-# INLINABLE fail #-}
2648+ fail s = SpiderHostFrame $ fail s
2649+
2650+instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2651+ notReadyUntil _ = pure ()
2652+ notReady = pure ()
2653+
2654+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2655+newEventWithTriggerIO f = do
2656+ es <- newFanEventWithTriggerIO $ \Refl -> f
2657+ return $ select es Refl
2658+
2659+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2660+newFanEventWithTriggerIO f = do
2661+ occRef <- newIORef DMap.empty
2662+ subscribedRef <- newIORef DMap.empty
2663+ let !r = Root
2664+ { rootOccurrence = occRef
2665+ , rootSubscribed = subscribedRef
2666+ , rootInit = f
2667+ }
2668+ return $ EventSelector $ \k -> eventRoot k r
2669+
2670+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2671+
2672+instance MonadRef (SpiderHost x) where
2673+ type Ref (SpiderHost x) = Ref IO
2674+ newRef = SpiderHost . newRef
2675+ readRef = SpiderHost . readRef
2676+ writeRef r = SpiderHost . writeRef r
2677+
2678+instance MonadAtomicRef (SpiderHost x) where
2679+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2680+
2681+instance MonadRef (SpiderHostFrame x) where
2682+ type Ref (SpiderHostFrame x) = Ref IO
2683+ newRef = SpiderHostFrame . newRef
2684+ readRef = SpiderHostFrame . readRef
2685+ writeRef r = SpiderHostFrame . writeRef r
2686+
2687+instance MonadAtomicRef (SpiderHostFrame x) where
2688+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2689+
2690+instance PrimMonad (SpiderHostFrame x) where
2691+ type PrimState (SpiderHostFrame x) = PrimState IO
2692+ primitive = SpiderHostFrame . EventM . primitive