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