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