@@ -0,0 +1,2730 @@
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 = BehaviorM $ fail s
980+#endif
981+
982+data BehaviorSubscribed x a
983+ = forall p. BehaviorSubscribedHold (Hold x p)
984+ | BehaviorSubscribedPull (PullSubscribed x a)
985+
986+newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
987+
988+--type role PullSubscribed representational
989+data PullSubscribed x a
990+ = PullSubscribed { pullSubscribedValue :: !a
991+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
992+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
993+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
994+ }
995+
996+--type role Pull representational
997+data Pull x a
998+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
999+ , pullCompute :: !(BehaviorM x a)
1000+#ifdef DEBUG_NODEIDS
1001+ , pullNodeId :: Int
1002+#endif
1003+ }
1004+
1005+data Invalidator x
1006+ = forall a. InvalidatorPull (Pull x a)
1007+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
1008+
1009+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
1010+ { rootSubscribedKey :: !(k a)
1011+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
1012+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1013+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
1014+ , rootSubscribedUninit :: IO ()
1015+ , 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?
1016+#ifdef DEBUG_NODEIDS
1017+ , rootSubscribedNodeId :: Int
1018+#endif
1019+ }
1020+
1021+data Root x k
1022+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
1023+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
1024+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
1025+ }
1026+
1027+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1028+
1029+data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1030+
1031+data SomeMergeUpdate x = SomeMergeUpdate
1032+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1033+ , _someMergeUpdate_invalidateHeight :: !(IO ())
1034+ , _someMergeUpdate_recalculateHeight :: !(IO ())
1035+ }
1036+
1037+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1038+
1039+-- EventM can do everything BehaviorM can, plus create holds
1040+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
1041+
1042+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1043+
1044+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1045+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1046+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1047+ }
1048+
1049+data HeightBag = HeightBag
1050+ { _heightBag_size :: {-# UNPACK #-} !Int
1051+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1052+ }
1053+ deriving (Show, Read, Eq, Ord)
1054+
1055+heightBagEmpty :: HeightBag
1056+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1057+
1058+heightBagSize :: HeightBag -> Int
1059+heightBagSize = _heightBag_size
1060+
1061+heightBagFromList :: [Height] -> HeightBag
1062+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1063+
1064+heightBagAdd :: Height -> HeightBag -> HeightBag
1065+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1066+
1067+heightBagRemove :: Height -> HeightBag -> HeightBag
1068+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1069+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1070+ Just old -> HeightBag (pred s) $ case old of
1071+ 0 -> IntMap.delete h c
1072+ _ -> IntMap.insert h (pred old) c
1073+
1074+heightBagMax :: HeightBag -> Height
1075+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1076+ Just ((h, _), _) -> Height h
1077+ Nothing -> zeroHeight
1078+
1079+heightBagVerify :: HeightBag -> HeightBag
1080+#ifdef DEBUG
1081+heightBagVerify b@(HeightBag s c) = if
1082+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1083+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1084+ | unHeight invalidHeight `IntMap.member` c
1085+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1086+ | otherwise -> b
1087+#else
1088+heightBagVerify = id
1089+#endif
1090+
1091+data FanSubscribedChildren x k v a = FanSubscribedChildren
1092+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1093+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1094+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
1095+ }
1096+
1097+data FanSubscribed x k v
1098+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1099+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1100+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
1101+ , fanSubscribedParent :: !(EventSubscription x)
1102+#ifdef DEBUG_NODEIDS
1103+ , fanSubscribedNodeId :: Int
1104+#endif
1105+ }
1106+
1107+data Fan x k v
1108+ = Fan { fanParent :: !(Event x (DMap k v))
1109+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1110+ }
1111+
1112+data SwitchSubscribed x a
1113+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1114+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1115+ , switchSubscribedHeight :: !(IORef Height)
1116+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1117+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1118+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1119+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1120+ , switchSubscribedParent :: !(Behavior x (Event x a))
1121+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1122+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1123+#ifdef DEBUG_NODEIDS
1124+ , switchSubscribedNodeId :: Int
1125+#endif
1126+ }
1127+
1128+data Switch x a
1129+ = Switch { switchParent :: !(Behavior x (Event x a))
1130+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1131+ }
1132+
1133+#ifdef USE_TEMPLATE_HASKELL
1134+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1135+#endif
1136+data CoincidenceSubscribed x a
1137+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1138+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1139+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1140+ , coincidenceSubscribedHeight :: !(IORef Height)
1141+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1142+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1143+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1144+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1145+#ifdef DEBUG_NODEIDS
1146+ , coincidenceSubscribedNodeId :: Int
1147+#endif
1148+ }
1149+
1150+data Coincidence x a
1151+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1152+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1153+ }
1154+
1155+{-# NOINLINE newInvalidatorSwitch #-}
1156+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1157+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1158+
1159+{-# NOINLINE newInvalidatorPull #-}
1160+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1161+newInvalidatorPull p = return $! InvalidatorPull p
1162+
1163+instance HasSpiderTimeline x => Filterable (Event x) where
1164+ mapMaybe f = push $ return . f
1165+
1166+instance HasSpiderTimeline x => Align (Event x) where
1167+ nil = eventNever
1168+#if MIN_VERSION_these(0, 8, 0)
1169+instance HasSpiderTimeline x => Semialign (Event x) where
1170+#endif
1171+ align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1172+ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1173+
1174+#ifdef MIN_VERSION_semialign
1175+#if MIN_VERSION_semialign(1,1,0)
1176+instance HasSpiderTimeline x => Zip (Event x) where
1177+#endif
1178+ zip x y = mapMaybe justThese $ align x y
1179+#endif
1180+
1181+data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1182+ | BuildDyn !(EventM x (PatchTarget p), Event x p)
1183+ | HoldDyn !(Hold x p)
1184+
1185+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1186+
1187+newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)
1188+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1189+
1190+--TODO: Avoid the duplication between this and R.zipDynWith
1191+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)
1192+zipDynWith f da db =
1193+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1194+ ec = flip push eab $ \o -> do
1195+ (a, b) <- case o of
1196+ This (Identity a) -> do
1197+ b <- readBehaviorUntracked $ dynamicCurrent db
1198+ return (a, b)
1199+ That (Identity b) -> do
1200+ a <- readBehaviorUntracked $ dynamicCurrent da
1201+ return (a, b)
1202+ These (Identity a) (Identity b) -> return (a, b)
1203+ return $ Just $ Identity $ f a b
1204+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1205+
1206+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1207+buildDynamic readV0 v' = do
1208+ result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1209+ let !d = Dyn result
1210+ defer $ SomeDynInit d
1211+ return d
1212+
1213+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1214+unsafeBuildDynamic readV0 v' =
1215+ Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
1216+
1217+-- ResultM can read behaviors and events
1218+type ResultM = EventM
1219+
1220+instance HasSpiderTimeline x => Functor (Event x) where
1221+ fmap f = push $ return . Just . f
1222+
1223+instance Functor (Behavior x) where
1224+ fmap f = pull . fmap f . readBehaviorTracked
1225+
1226+{-# INLINE push #-}
1227+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1228+push f e = cacheEvent (pushCheap f e)
1229+
1230+{-# INLINABLE pull #-}
1231+pull :: BehaviorM x a -> Behavior x a
1232+pull a = unsafePerformIO $ do
1233+ ref <- newIORef Nothing
1234+#ifdef DEBUG_NODEIDS
1235+ nid <- newNodeId
1236+#endif
1237+ pure $ behaviorPull $ Pull
1238+ { pullCompute = a
1239+ , pullValue = ref
1240+#ifdef DEBUG_NODEIDS
1241+ , pullNodeId = nid
1242+#endif
1243+ }
1244+
1245+{-# INLINABLE switch #-}
1246+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1247+switch a = unsafePerformIO $ do
1248+ ref <- newIORef Nothing
1249+ pure $ eventSwitch $ Switch
1250+ { switchParent = a
1251+ , switchSubscribed = ref
1252+ }
1253+
1254+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1255+coincidence a = unsafePerformIO $ do
1256+ ref <- newIORef Nothing
1257+ pure $ eventCoincidence $ Coincidence
1258+ { coincidenceParent = a
1259+ , coincidenceSubscribed = ref
1260+ }
1261+
1262+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1263+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1264+run roots after = do
1265+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1266+ let t = spiderTimeline :: SpiderTimelineEnv x
1267+ result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do
1268+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1269+ occBefore <- liftIO $ do
1270+ occBefore <- readIORef occRef
1271+ writeIORef occRef $! DMap.insert k a occBefore
1272+ return occBefore
1273+ if DMap.null occBefore
1274+ then do scheduleRootClear occRef
1275+ return $ Just r
1276+ else return Nothing
1277+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1278+ propagate a subscribersRef
1279+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1280+ let go = do
1281+ delayed <- liftIO $ readIORef delayedRef
1282+ case IntMap.minViewWithKey delayed of
1283+ Nothing -> return ()
1284+ Just ((currentHeight, cur), future) -> do
1285+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1286+ putCurrentHeight $ Height currentHeight
1287+ liftIO $ writeIORef delayedRef $! future
1288+ sequence_ cur
1289+ go
1290+ go
1291+ putCurrentHeight maxBound
1292+ after
1293+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1294+ return result
1295+
1296+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1297+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1298+ height <- liftIO $ readIORef heightRef
1299+ currentHeight <- getCurrentHeight
1300+ case height `compare` currentHeight of
1301+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1302+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1303+ EQ -> a
1304+
1305+newtype Clear a = Clear (IORef (Maybe a))
1306+
1307+newtype IntClear a = IntClear (IORef (IntMap a))
1308+
1309+newtype RootClear k = RootClear (IORef (DMap k Identity))
1310+
1311+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1312+
1313+debugFinalize :: Bool
1314+debugFinalize = False
1315+
1316+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1317+mkWeakPtrWithDebug x debugNote = do
1318+ x' <- evaluate x
1319+ mkWeakPtr x' $
1320+ if debugFinalize
1321+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1322+ else Nothing
1323+
1324+type WeakList a = [Weak a]
1325+
1326+{-# INLINE withIncreasedDepth #-}
1327+#ifdef DEBUG
1328+withIncreasedDepth :: CanTrace x m => m a -> m a
1329+withIncreasedDepth a = do
1330+ spiderTimeline <- askSpiderTimelineEnv
1331+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) succ
1332+ result <- a
1333+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) pred
1334+ return result
1335+#else
1336+withIncreasedDepth :: m a -> m a
1337+withIncreasedDepth = id
1338+#endif
1339+
1340+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1341+
1342+{-# INLINE tracePropagate #-}
1343+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1344+tracePropagate p = traceWhen p debugPropagate
1345+
1346+{-# INLINE traceInvalidate #-}
1347+traceInvalidate :: String -> IO ()
1348+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1349+
1350+{-# INLINE traceWhen #-}
1351+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1352+traceWhen p b message = traceMWhen p b $ return message
1353+
1354+{-# INLINE traceMWhen #-}
1355+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1356+traceMWhen _ b getMessage = when b $ do
1357+ message <- getMessage
1358+#ifdef DEBUG
1359+ spiderTimeline <- askSpiderTimelineEnv
1360+ d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE spiderTimeline
1361+#else
1362+ let d = 0
1363+#endif
1364+ liftIO $ putStrLn $ replicate d ' ' <> message
1365+
1366+whoCreatedIORef :: IORef a -> IO [String]
1367+whoCreatedIORef (IORef a) = whoCreated $! a
1368+
1369+#ifdef DEBUG_CYCLES
1370+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1371+groupByHead = \case
1372+ [] -> []
1373+ (x :| xs) : t -> case groupByHead t of
1374+ [] -> [(x, xs :| [])]
1375+ l@((y, yss) : t')
1376+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1377+ | otherwise -> (x, xs :| []) : l
1378+
1379+listsToForest :: Eq a => [[a]] -> Forest a
1380+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1381+#endif
1382+
1383+{-# INLINE propagateSubscriberHold #-}
1384+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1385+propagateSubscriberHold h a = do
1386+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1387+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1388+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1389+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1390+ case {-# SCC "apply" #-} apply a v of
1391+ Nothing -> return ()
1392+ Just v' -> do
1393+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1394+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1395+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1396+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1397+
1398+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1399+
1400+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1401+runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)
1402+
1403+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1404+askInvalidator = do
1405+ (!m, _) <- ask
1406+ case m of
1407+ Nothing -> return Nothing
1408+ Just (!wi, _) -> return $ Just wi
1409+
1410+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1411+askParentsRef = do
1412+ (!m, _) <- ask
1413+ case m of
1414+ Nothing -> return Nothing
1415+ Just (_, !p) -> return $ Just p
1416+
1417+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1418+askBehaviorHoldInits = do
1419+ (_, !his) <- ask
1420+ return his
1421+
1422+{-# INLINE getDynHold #-}
1423+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1424+getDynHold d = do
1425+ mh <- liftIO $ readIORef $ unDyn d
1426+ case mh of
1427+ HoldDyn h -> return h
1428+ UnsafeDyn (readV0, v') -> do
1429+ holdInits <- getDeferralQueue
1430+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1431+ hold' v0 v'
1432+ BuildDyn (readV0, v') -> do
1433+ v0 <- liftIO $ runEventM readV0
1434+ hold' v0 v'
1435+ where
1436+ hold' v0 v' = do
1437+ h <- hold v0 v'
1438+ liftIO $ writeIORef (unDyn d) $ HoldDyn h
1439+ return h
1440+
1441+
1442+-- Always refers to 0
1443+{-# NOINLINE zeroRef #-}
1444+zeroRef :: IORef Height
1445+zeroRef = unsafePerformIO $ newIORef zeroHeight
1446+
1447+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1448+getRootSubscribed k r sub = do
1449+ mSubscribed <- readIORef $ rootSubscribed r
1450+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1451+ case DMap.lookup k mSubscribed of
1452+ Just subscribed -> {-# SCC "hitRoot" #-} do
1453+ sln <- subscribeRootSubscribed subscribed sub
1454+ occ <- getOcc
1455+ return (sln, subscribed, occ)
1456+ Nothing -> {-# SCC "missRoot" #-} do
1457+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1458+ let !cached = rootSubscribed r
1459+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1460+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1461+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1462+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1463+ writeIORef uninitRef $! uninit
1464+#ifdef DEBUG_NODEIDS
1465+ nid <- newNodeId
1466+#endif
1467+ let !subscribed = RootSubscribed
1468+ { rootSubscribedKey = k
1469+ , rootSubscribedCachedSubscribed = cached
1470+ , rootSubscribedOccurrence = getOcc
1471+ , rootSubscribedSubscribers = subs
1472+ , rootSubscribedUninit = uninit
1473+ , rootSubscribedWeakSelf = weakSelf
1474+#ifdef DEBUG_NODEIDS
1475+ , rootSubscribedNodeId = nid
1476+#endif
1477+ }
1478+ -- If we die at the same moment that all our children die, they will
1479+ -- try to clean us up but will fail because their Weak reference to us
1480+ -- will also be dead. So, if we are dying, check if there are any
1481+ -- children; since children don't bother cleaning themselves up if
1482+ -- their parents are already dead, I don't think there's a race
1483+ -- condition here. However, if there are any children, then we can
1484+ -- infer that we need to clean ourselves up, so we do.
1485+ finalCleanup = do
1486+ cs <- readIORef $ _weakBag_children subs
1487+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1488+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1489+ 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
1490+ occ <- getOcc
1491+ return (sln, subscribed, occ)
1492+
1493+#ifdef USE_TEMPLATE_HASKELL
1494+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1495+#endif
1496+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1497+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1498+ rootSubscribedUninit self
1499+ modifyIORef' cached $ DMap.delete k
1500+
1501+{-# INLINE subscribeRootSubscribed #-}
1502+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1503+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1504+
1505+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1506+
1507+data FanInt x a = FanInt
1508+ { _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
1509+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1510+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1511+ }
1512+
1513+newFanInt :: IO (FanInt x a)
1514+newFanInt = do
1515+ 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
1516+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1517+ occRef <- newIORef $ error "fanInt: no occurrence"
1518+ return $ FanInt
1519+ { _fanInt_subscribers = subscribers
1520+ , _fanInt_subscriptionRef = subscriptionRef
1521+ , _fanInt_occRef = occRef
1522+ }
1523+
1524+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1525+fanInt p = unsafePerformIO $ do
1526+ self <- newFanInt
1527+ pure $ EventSelectorInt $ \k -> Event $ \sub -> do
1528+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1529+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1530+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1531+ { subscriberPropagate = \m -> do
1532+ liftIO $ writeIORef (_fanInt_occRef self) m
1533+ scheduleIntClear $ _fanInt_occRef self
1534+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1535+ FastWeakBag.traverse_ b $ \s -> do
1536+ subscriberPropagate s v
1537+ , subscriberInvalidateHeight = \old -> do
1538+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1539+ FastWeakBag.traverse_ b $ \s -> do
1540+ subscriberInvalidateHeight s old
1541+ , subscriberRecalculateHeight = \new -> do
1542+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1543+ FastWeakBag.traverse_ b $ \s -> do
1544+ subscriberRecalculateHeight s new
1545+ }
1546+ liftIO $ do
1547+ writeIORef (_fanInt_subscriptionRef self) subscription
1548+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1549+ scheduleIntClear $ _fanInt_occRef self
1550+ liftIO $ do
1551+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1552+ Nothing -> do
1553+ b <- FastWeakBag.empty
1554+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1555+ return b
1556+ Just b -> return b
1557+ t <- liftIO $ FastWeakBag.insert sub b
1558+ currentOcc <- readIORef (_fanInt_occRef self)
1559+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1560+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1561+
1562+{-# INLINABLE getFanSubscribed #-}
1563+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))
1564+getFanSubscribed k f sub = do
1565+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1566+ case mSubscribed of
1567+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1568+ sln <- subscribeFanSubscribed k subscribed sub
1569+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1570+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1571+ Nothing -> {-# SCC "missFan" #-} do
1572+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1573+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1574+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1575+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1576+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1577+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1578+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1579+ occRef <- liftIO $ newIORef parentOcc
1580+ when (isJust parentOcc) $ scheduleClear occRef
1581+#ifdef DEBUG_NODEIDS
1582+ nid <- liftIO newNodeId
1583+#endif
1584+ let subscribed = FanSubscribed
1585+ { fanSubscribedCachedSubscribed = fanSubscribed f
1586+ , fanSubscribedOccurrence = occRef
1587+ , fanSubscribedParent = subscription
1588+ , fanSubscribedSubscribers = subscribersRef
1589+#ifdef DEBUG_NODEIDS
1590+ , fanSubscribedNodeId = nid
1591+#endif
1592+ }
1593+ let !self = (k, subscribed)
1594+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1595+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1596+ liftIO $ writeIORef subscribedRef $! subscribed
1597+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1598+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1599+
1600+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
1601+cleanupFanSubscribed (k, subscribed) = do
1602+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1603+ let reducedSubscribers = DMap.delete k subscribers
1604+ if DMap.null reducedSubscribers
1605+ then do
1606+ unsubscribe $ fanSubscribedParent subscribed
1607+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1608+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1609+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1610+
1611+{-# INLINE subscribeFanSubscribed #-}
1612+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
1613+subscribeFanSubscribed k subscribed sub = do
1614+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1615+ case DMap.lookup k subscribers of
1616+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1617+ let !self = (k, subscribed)
1618+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1619+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1620+ 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
1621+ return sln
1622+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1623+
1624+{-# INLINABLE getSwitchSubscribed #-}
1625+getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1626+getSwitchSubscribed s sub = do
1627+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1628+ case mSubscribed of
1629+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1630+ sln <- subscribeSwitchSubscribed subscribed sub
1631+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1632+ return (sln, subscribed, occ)
1633+ Nothing -> {-# SCC "missSwitch" #-} do
1634+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1635+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1636+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1637+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1638+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1639+ wiRef <- liftIO $ newIORef wi
1640+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1641+ holdInits <- getDeferralQueue
1642+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1643+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1644+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1645+ subscriptionRef <- liftIO $ newIORef subscription
1646+ occRef <- liftIO $ newIORef parentOcc
1647+ when (isJust parentOcc) $ scheduleClear occRef
1648+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1649+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1650+#ifdef DEBUG_NODEIDS
1651+ nid <- liftIO newNodeId
1652+#endif
1653+ let !subscribed = SwitchSubscribed
1654+ { switchSubscribedCachedSubscribed = switchSubscribed s
1655+ , switchSubscribedOccurrence = occRef
1656+ , switchSubscribedHeight = heightRef
1657+ , switchSubscribedSubscribers = subs
1658+ , switchSubscribedOwnInvalidator = i
1659+ , switchSubscribedOwnWeakInvalidator = wiRef
1660+ , switchSubscribedBehaviorParents = parentsRef
1661+ , switchSubscribedParent = switchParent s
1662+ , switchSubscribedCurrentParent = subscriptionRef
1663+ , switchSubscribedWeakSelf = weakSelf
1664+#ifdef DEBUG_NODEIDS
1665+ , switchSubscribedNodeId = nid
1666+#endif
1667+ }
1668+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1669+ liftIO $ writeIORef subscribedRef $! subscribed
1670+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1671+ return (slnForSub, subscribed, parentOcc)
1672+
1673+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1674+cleanupSwitchSubscribed subscribed = do
1675+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1676+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1677+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1678+
1679+{-# INLINE subscribeSwitchSubscribed #-}
1680+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1681+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1682+
1683+{-# INLINABLE getCoincidenceSubscribed #-}
1684+getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1685+getCoincidenceSubscribed c sub = do
1686+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1687+ case mSubscribed of
1688+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1689+ sln <- subscribeCoincidenceSubscribed subscribed sub
1690+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1691+ return (sln, subscribed, occ)
1692+ Nothing -> {-# SCC "missCoincidence" #-} do
1693+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1694+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1695+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1696+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1697+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1698+ (occ, height, mInnerSubd) <- case outerOcc of
1699+ Nothing -> return (Nothing, outerHeight, Nothing)
1700+ Just o -> do
1701+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1702+ return (occ, height, Just innerSubd)
1703+ occRef <- liftIO $ newIORef occ
1704+ when (isJust occ) $ scheduleClear occRef
1705+ heightRef <- liftIO $ newIORef height
1706+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1707+ scheduleClear innerSubdRef
1708+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1709+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1710+#ifdef DEBUG_NODEIDS
1711+ nid <- liftIO newNodeId
1712+#endif
1713+ let subscribed = CoincidenceSubscribed
1714+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1715+ , coincidenceSubscribedOccurrence = occRef
1716+ , coincidenceSubscribedHeight = heightRef
1717+ , coincidenceSubscribedSubscribers = subs
1718+ , coincidenceSubscribedOuter = subOuter
1719+ , coincidenceSubscribedOuterParent = outerSubscription
1720+ , coincidenceSubscribedInnerParent = innerSubdRef
1721+ , coincidenceSubscribedWeakSelf = weakSelf
1722+#ifdef DEBUG_NODEIDS
1723+ , coincidenceSubscribedNodeId = nid
1724+#endif
1725+ }
1726+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1727+ liftIO $ writeIORef subscribedRef $! subscribed
1728+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1729+ return (slnForSub, subscribed, occ)
1730+
1731+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1732+cleanupCoincidenceSubscribed subscribed = do
1733+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1734+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1735+
1736+{-# INLINE subscribeCoincidenceSubscribed #-}
1737+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1738+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1739+
1740+{-# INLINE mergeG #-}
1741+mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1742+ => (forall a. q a -> Event x (v a))
1743+ -> DynamicS x (PatchDMap k q) -> Event x (DMap k v)
1744+mergeG nt d = cacheEvent (mergeCheap nt d)
1745+
1746+{-# INLINE mergeWithMove #-}
1747+mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1748+ => (forall a. q a -> Event x (v a))
1749+ -> DynamicS x (PatchDMapWithMove k q) -> Event x (DMap k v)
1750+mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1751+
1752+{-# INLINE [1] mergeCheap #-}
1753+mergeCheap
1754+ :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1755+ => (forall a. q a -> Event x (v a))
1756+ -> DynamicS x (PatchDMap k q)
1757+ -> Event x (DMap k v)
1758+mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
1759+ where
1760+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1761+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1762+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1763+ (mOldSubd, newPs) <- case me of
1764+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1765+ Just e -> do
1766+ let s = subscriber $ return k
1767+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1768+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1769+ let newParent = MergeSubscribedParent subscription
1770+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1771+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1772+ forM_ mOldSubd $ \oldSubd -> do
1773+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1774+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1775+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1776+ foldM f ([], oldParents) $ DMap.toList p
1777+
1778+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1779+ getInitialSubscribers initialParents subscriber = do
1780+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1781+ let s = subscriber $ return k
1782+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1783+ height <- liftIO $ getEventSubscribedHeight parentSubd
1784+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
1785+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1786+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1787+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1788+ )
1789+
1790+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1791+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1792+
1793+{-# INLINE [1] mergeCheapWithMove #-}
1794+mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1795+ => (forall a. q a -> Event x (v a))
1796+ -> DynamicS x (PatchDMapWithMove k q)
1797+ -> Event x (DMap k v)
1798+mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
1799+ where
1800+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1801+ updateMe subscriber heightBagRef oldParents p = do
1802+ -- Prepare new parents for insertion
1803+ let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1804+ subscribeParent k e = do
1805+ keyRef <- liftIO $ newIORef k
1806+ let s = subscriber $ liftIO $ readIORef keyRef
1807+ subscription@(EventSubscription _ subd) <- subscribe e s
1808+ liftIO $ do
1809+ newParentHeight <- getEventSubscribedHeight subd
1810+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1811+ return $ MergeSubscribedParentWithMove subscription keyRef
1812+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1813+ -- Collect old parents for deletion and update the keys of moved parents
1814+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1815+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1816+ Nothing -> do
1817+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1818+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1819+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1820+ Just toKey -> do
1821+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1822+ return Nothing
1823+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1824+ return (toDelete, applyAlways p' oldParents)
1825+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1826+ getInitialSubscribers initialParents subscriber = do
1827+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1828+ keyRef <- liftIO $ newIORef k
1829+ let s = subscriber $ liftIO $ readIORef keyRef
1830+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1831+ height <- liftIO $ getEventSubscribedHeight parentSubd
1832+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1833+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1834+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1835+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1836+ )
1837+
1838+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1839+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1840+
1841+type MergeUpdateFunc k v x p s
1842+ = (forall a. EventM x (k a) -> Subscriber x (v a))
1843+ -> IORef HeightBag
1844+ -> DMap k s
1845+ -> p
1846+ -> EventM x ([EventSubscription x], DMap k s)
1847+
1848+type MergeInitFunc k v q x s
1849+ = DMap k q
1850+ -> (forall a. EventM x (k a) -> Subscriber x (v a))
1851+ -> EventM x (DMap k v, [Height], DMap k s)
1852+
1853+type MergeDestroyFunc k s
1854+ = DMap k s
1855+ -> IO ()
1856+
1857+data Merge x k v s = Merge
1858+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1859+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1860+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1861+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1862+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
1863+ }
1864+
1865+invalidateMergeHeight :: Merge x k v s -> IO ()
1866+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1867+
1868+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1869+invalidateMergeHeight' heightRef sub = do
1870+ oldHeight <- readIORef heightRef
1871+ 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
1872+ writeIORef heightRef $! invalidHeight
1873+ subscriberInvalidateHeight sub oldHeight
1874+
1875+revalidateMergeHeight :: Merge x k v s -> IO ()
1876+revalidateMergeHeight m = do
1877+ currentHeight <- readIORef $ _merge_heightRef m
1878+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1879+ heights <- readIORef $ _merge_heightBagRef m
1880+ parents <- readIORef $ _merge_parentsRef m
1881+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1882+ case heightBagSize heights `compare` DMap.size parents of
1883+ LT -> return ()
1884+ EQ -> do
1885+ let height = succHeight $ heightBagMax heights
1886+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1887+ writeIORef (_merge_heightRef m) $! height
1888+ subscriberRecalculateHeight (_merge_sub m) height
1889+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1890+
1891+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
1892+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1893+ vals <- liftIO $ readIORef $ _merge_accumRef m
1894+ 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
1895+ --TODO: Assert that m is not empty
1896+ subscriberPropagate (_merge_sub m) vals
1897+
1898+mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
1899+mergeSubscriber m getKey = Subscriber
1900+ { subscriberPropagate = \a -> do
1901+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1902+ k <- getKey
1903+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
1904+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1905+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1906+ when (DMap.null oldM) $ do -- Only schedule the firing once
1907+ height <- liftIO $ readIORef $ _merge_heightRef m
1908+ --TODO: assertions about height
1909+ currentHeight <- getCurrentHeight
1910+ when (height <= currentHeight) $ do
1911+ if height /= invalidHeight
1912+ then do
1913+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1914+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1915+ else liftIO $ do
1916+#ifdef DEBUG_CYCLES
1917+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1918+ stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
1919+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1920+#else
1921+ let cycleInfo = ""
1922+#endif
1923+ error $ "Causality loop found" <> cycleInfo
1924+ scheduleMergeSelf m height
1925+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1926+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1927+ invalidateMergeHeight m
1928+ , subscriberRecalculateHeight = \new -> do
1929+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1930+ revalidateMergeHeight m
1931+ }
1932+
1933+--TODO: Be able to run as much of this as possible promptly
1934+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
1935+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1936+ where updateMe = do
1937+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1938+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1939+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1940+ return subscriptionsToKill
1941+
1942+{-# INLINE mergeGCheap' #-}
1943+mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1944+ => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> DynamicS x p -> Event x (DMap k v)
1945+mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1946+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1947+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1948+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1949+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1950+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1951+ let m = Merge
1952+ { _merge_parentsRef = parentsRef
1953+ , _merge_heightBagRef = heightBagRef
1954+ , _merge_heightRef = heightRef
1955+ , _merge_sub = sub
1956+ , _merge_accumRef = accumRef
1957+ }
1958+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1959+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1960+ myHeight = if invalidHeight `elem` heights
1961+ then invalidHeight
1962+ else succHeight $ heightBagMax myHeightBag
1963+ currentHeight <- getCurrentHeight
1964+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1965+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1966+ else (Nothing, dm)
1967+ unless (DMap.null accum) $ do
1968+ scheduleMergeSelf m myHeight
1969+ liftIO $ writeIORef accumRef $! accum
1970+ liftIO $ writeIORef heightRef $! myHeight
1971+ liftIO $ writeIORef heightBagRef $! myHeightBag
1972+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1973+ liftIO $ writeIORef parentsRef $! initialParentState
1974+ defer $ SomeMergeInit $ do
1975+ let s = Subscriber
1976+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1977+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1978+ defer $ updateMerge m updateFunc a
1979+ , subscriberInvalidateHeight = \_ -> return ()
1980+ , subscriberRecalculateHeight = \_ -> return ()
1981+ }
1982+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1983+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1984+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1985+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1986+ -- its subscription.
1987+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1988+ let unsubscribeAll = destroy =<< readIORef parentsRef
1989+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1990+ , occ
1991+ )
1992+
1993+mergeInt :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1994+mergeInt = cacheEvent . mergeIntCheap
1995+
1996+{-# INLINABLE mergeIntCheap #-}
1997+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1998+mergeIntCheap d = Event $ \sub -> do
1999+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
2000+ accum <- liftIO $ FastMutableIntMap.newEmpty
2001+ heightRef <- liftIO $ newIORef zeroHeight
2002+ heightBagRef <- liftIO $ newIORef heightBagEmpty
2003+ parents <- liftIO $ FastMutableIntMap.newEmpty
2004+ let scheduleSelf = do
2005+ height <- liftIO $ readIORef $ heightRef
2006+ scheduleMerge' height heightRef $ do
2007+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
2008+ subscriberPropagate sub vals
2009+ invalidateMyHeight = do
2010+ invalidateMergeHeight' heightRef sub
2011+ recalculateMyHeight = do
2012+ currentHeight <- readIORef heightRef
2013+ 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?
2014+ heights <- readIORef heightBagRef
2015+ numParents <- FastMutableIntMap.size parents
2016+ case heightBagSize heights `compare` numParents of
2017+ LT -> return ()
2018+ EQ -> do
2019+ let height = succHeight $ heightBagMax heights
2020+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
2021+ writeIORef heightRef $! height
2022+ subscriberRecalculateHeight sub height
2023+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
2024+ mySubscriber k = Subscriber
2025+ { subscriberPropagate = \a -> do
2026+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2027+ liftIO $ FastMutableIntMap.insert accum k a
2028+ when wasEmpty scheduleSelf
2029+ , subscriberInvalidateHeight = \old -> do
2030+ modifyIORef' heightBagRef $ heightBagRemove old
2031+ invalidateMyHeight
2032+ , subscriberRecalculateHeight = \new -> do
2033+ modifyIORef' heightBagRef $ heightBagAdd new
2034+ recalculateMyHeight
2035+ }
2036+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
2037+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
2038+ liftIO $ do
2039+ forM_ parentOcc $ FastMutableIntMap.insert accum k
2040+ FastMutableIntMap.insert parents k subscription
2041+ height <- getEventSubscribedHeight parentSubd
2042+ if height == invalidHeight
2043+ then writeIORef heightRef invalidHeight
2044+ else do
2045+ modifyIORef' heightBagRef $ heightBagAdd height
2046+ modifyIORef' heightRef $ \oldHeight ->
2047+ if oldHeight == invalidHeight
2048+ then invalidHeight
2049+ else max (succHeight height) oldHeight
2050+ myHeight <- liftIO $ readIORef heightRef
2051+ currentHeight <- getCurrentHeight
2052+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2053+ occ <- if currentHeight >= myHeight -- If we should have fired by now
2054+ then if isEmpty
2055+ then return Nothing
2056+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2057+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2058+ return Nothing
2059+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2060+ defer $ SomeMergeInit $ do
2061+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2062+ where
2063+ u = do
2064+ let f k newParent = do
2065+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2066+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2067+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2068+ return subscription
2069+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2070+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2071+ liftIO $ for_ oldParents $ \oldParent -> do
2072+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2073+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2074+ return $ IntMap.elems oldParents
2075+ let s = Subscriber
2076+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2077+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2078+ defer $ updateMe a
2079+ , subscriberInvalidateHeight = \_ -> return ()
2080+ , subscriberRecalculateHeight = \_ -> return ()
2081+ }
2082+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2083+ forM_ change $ \c -> defer $ updateMe c
2084+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2085+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2086+ -- its subscription.
2087+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2088+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2089+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2090+ , occ
2091+ )
2092+
2093+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2094+newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
2095+
2096+fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2097+fanG e = unsafePerformIO $ do
2098+ ref <- newIORef Nothing
2099+ let f = Fan
2100+ { fanParent = e
2101+ , fanSubscribed = ref
2102+ }
2103+ pure $ EventSelectorG $ \k -> eventFan k f
2104+
2105+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2106+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2107+ holdInits <- liftIO $ readIORef holdInitRef
2108+ dynInits <- liftIO $ readIORef dynInitRef
2109+ mergeInits <- liftIO $ readIORef mergeInitRef
2110+ unless (null holdInits && null dynInits && null mergeInits) $ do
2111+ liftIO $ writeIORef holdInitRef []
2112+ liftIO $ writeIORef dynInitRef []
2113+ liftIO $ writeIORef mergeInitRef []
2114+ mapM_ initHold holdInits
2115+ mapM_ initDyn dynInits
2116+ mapM_ unSomeMergeInit mergeInits
2117+ runHoldInits holdInitRef dynInitRef mergeInitRef
2118+
2119+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2120+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2121+
2122+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2123+initDyn (SomeDynInit d) = void $ getDynHold d
2124+
2125+newEventEnv :: IO (EventEnv x)
2126+newEventEnv = do
2127+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2128+ holdInitRef <- newIORef []
2129+ dynInitRef <- newIORef []
2130+ mergeUpdateRef <- newIORef []
2131+ mergeInitRef <- newIORef []
2132+ heightRef <- newIORef zeroHeight
2133+ toClearRef <- newIORef []
2134+ toClearIntRef <- newIORef []
2135+ toClearRootRef <- newIORef []
2136+ coincidenceInfosRef <- newIORef []
2137+ delayedRef <- newIORef IntMap.empty
2138+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2139+
2140+clearEventEnv :: EventEnv x -> IO ()
2141+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2142+ writeIORef toAssignRef []
2143+ writeIORef holdInitRef []
2144+ writeIORef dynInitRef []
2145+ writeIORef mergeUpdateRef []
2146+ writeIORef mergeInitRef []
2147+ writeIORef heightRef zeroHeight
2148+ writeIORef toClearRef []
2149+ writeIORef toClearIntRef []
2150+ writeIORef toClearRootRef []
2151+ writeIORef coincidenceInfosRef []
2152+ writeIORef delayedRef IntMap.empty
2153+
2154+-- | Run an event action outside of a frame
2155+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2156+runFrame a = SpiderHost $ do
2157+ let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
2158+ let go = do
2159+ result <- a
2160+ 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
2161+ return result
2162+ result <- runEventM go
2163+ toClear <- readIORef $ eventEnvClears env
2164+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2165+ toClearInt <- readIORef $ eventEnvIntClears env
2166+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2167+ toClearRoot <- readIORef $ eventEnvRootClears env
2168+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2169+ toAssign <- readIORef $ eventEnvAssignments env
2170+ toReconnectRef <- newIORef []
2171+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2172+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2173+ writeIORef vRef v
2174+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2175+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2176+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2177+ writeIORef (eventEnvMergeUpdates env) []
2178+ when debugPropagate $ putStrLn "Updating merges"
2179+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2180+ when debugPropagate $ putStrLn "Updating merges done"
2181+ toReconnect <- readIORef toReconnectRef
2182+ clearEventEnv env
2183+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2184+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2185+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2186+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2187+ finalize wi
2188+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2189+ wi' <- mkWeakPtrWithDebug i "wi'"
2190+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2191+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2192+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2193+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2194+ 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
2195+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2196+ sub <- newSubscriberSwitch subscribed
2197+ 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
2198+ {-
2199+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2200+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2201+ EventRoot _ -> "EventRoot"
2202+ EventNever -> "EventNever"
2203+ _ -> "something else"
2204+ -}
2205+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2206+ return oldSubscription
2207+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2208+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2209+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2210+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2211+ parentHeight <- getEventSubscribedHeight subd'
2212+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2213+ when (parentHeight /= myHeight) $ do
2214+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2215+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2216+ 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
2217+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2218+ unsubscribe subscription
2219+ mapM_ invalidateCoincidenceHeight mcs
2220+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2221+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2222+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2223+ height <- calculateSwitchHeight subscribed
2224+ updateSwitchHeight height subscribed
2225+ return result
2226+
2227+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2228+
2229+{-# INLINE zeroHeight #-}
2230+zeroHeight :: Height
2231+zeroHeight = Height 0
2232+
2233+{-# INLINE invalidHeight #-}
2234+invalidHeight :: Height
2235+invalidHeight = Height (-1000)
2236+
2237+#ifdef DEBUG_CYCLES
2238+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2239+{-# INLINE invalidHeightBeingTraversed #-}
2240+invalidHeightBeingTraversed :: Height
2241+invalidHeightBeingTraversed = Height (-1001)
2242+#endif
2243+
2244+{-# INLINE succHeight #-}
2245+succHeight :: Height -> Height
2246+succHeight h@(Height a) =
2247+ if h == invalidHeight
2248+ then invalidHeight
2249+ else Height $ succ a
2250+
2251+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2252+invalidateCoincidenceHeight subscribed = do
2253+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2254+ when (oldHeight /= invalidHeight) $ do
2255+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2256+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2257+
2258+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2259+updateSwitchHeight new subscribed = do
2260+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2261+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2262+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2263+ writeIORef (switchSubscribedHeight subscribed) $! new
2264+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2265+
2266+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2267+recalculateCoincidenceHeight subscribed = do
2268+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2269+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2270+ height <- calculateCoincidenceHeight subscribed
2271+ when (height /= invalidHeight) $ do
2272+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2273+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2274+
2275+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2276+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2277+
2278+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2279+calculateCoincidenceHeight subscribed = do
2280+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2281+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2282+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2283+
2284+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2285+
2286+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2287+invalidate toReconnectRef wis = do
2288+ forM_ wis $ \wi -> do
2289+ mi <- deRefWeak wi
2290+ case mi of
2291+ Nothing -> do
2292+ traceInvalidate "invalidate Dead"
2293+ return () --TODO: Should we clean this up here?
2294+ Just i -> do
2295+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2296+ case i of
2297+ InvalidatorPull p -> do
2298+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2299+ mVal <- readIORef $ pullValue p
2300+ forM_ mVal $ \val -> do
2301+ writeIORef (pullValue p) Nothing
2302+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2303+ InvalidatorSwitch subscribed -> do
2304+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2305+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2306+ 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
2307+
2308+--------------------------------------------------------------------------------
2309+-- Reflex integration
2310+--------------------------------------------------------------------------------
2311+
2312+-- | Designates the default, global Spider timeline
2313+data SpiderTimeline x
2314+type role SpiderTimeline nominal
2315+
2316+-- | The default, global Spider environment
2317+type Spider = SpiderTimeline Global
2318+
2319+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2320+ {-# INLINABLE sample #-}
2321+ sample (SpiderBehavior b) = readBehaviorUntracked b
2322+
2323+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2324+ {-# INLINABLE hold #-}
2325+ hold = holdSpiderEventM
2326+ {-# INLINABLE holdDyn #-}
2327+ holdDyn = holdDynSpiderEventM
2328+ {-# INLINABLE holdIncremental #-}
2329+ holdIncremental = holdIncrementalSpiderEventM
2330+ {-# INLINABLE buildDynamic #-}
2331+ buildDynamic = buildDynamicSpiderEventM
2332+ {-# INLINABLE headE #-}
2333+ headE = R.slowHeadE
2334+-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2335+
2336+instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2337+ {-# INLINABLE sample #-}
2338+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2339+
2340+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2341+ {-# INLINABLE sample #-}
2342+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2343+
2344+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2345+ {-# INLINABLE hold #-}
2346+ hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2347+ {-# INLINABLE holdDyn #-}
2348+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2349+ {-# INLINABLE holdIncremental #-}
2350+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2351+ {-# INLINABLE buildDynamic #-}
2352+ buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2353+ {-# INLINABLE headE #-}
2354+ headE = R.slowHeadE
2355+-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2356+
2357+instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2358+ {-# INLINE return #-}
2359+ return = pure
2360+ {-# INLINE (>>=) #-}
2361+ x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2362+ {-# INLINE (>>) #-}
2363+ (>>) = (*>)
2364+#if !MIN_VERSION_base(4,13,0)
2365+ {-# INLINE fail #-}
2366+ fail _ = error "Dynamic does not support 'fail'"
2367+#endif
2368+
2369+{-# INLINABLE newJoinDyn #-}
2370+newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2371+newJoinDyn d =
2372+ let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2373+ eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2374+ eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2375+ eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2376+ v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2377+ in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2378+
2379+instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2380+ fmap = mapDynamicSpider
2381+ x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2382+
2383+mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2384+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2385+{-# INLINE [1] mapDynamicSpider #-}
2386+
2387+instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2388+ pure = SpiderDynamic . dynamicConst
2389+#if MIN_VERSION_base(4,10,0)
2390+ liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2391+#endif
2392+ SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2393+ a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2394+ (<*) = flip (*>) -- There are no effects, so order doesn't matter
2395+
2396+holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2397+holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2398+
2399+holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2400+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2401+
2402+holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2403+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2404+
2405+buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2406+buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2407+
2408+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2409+ {-# INLINABLE hold #-}
2410+ hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2411+ {-# INLINABLE holdDyn #-}
2412+ holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2413+ {-# INLINABLE holdIncremental #-}
2414+ holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2415+ {-# INLINABLE buildDynamic #-}
2416+ buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2417+ {-# INLINABLE headE #-}
2418+ headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2419+
2420+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2421+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2422+
2423+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2424+ {-# INLINABLE hold #-}
2425+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2426+ {-# INLINABLE holdDyn #-}
2427+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2428+ {-# INLINABLE holdIncremental #-}
2429+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2430+ {-# INLINABLE buildDynamic #-}
2431+ buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2432+ {-# INLINABLE headE #-}
2433+ headE = R.slowHeadE
2434+-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2435+
2436+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2437+ {-# INLINABLE sample #-}
2438+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2439+
2440+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2441+ {-# INLINABLE sample #-}
2442+ sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2443+
2444+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2445+ {-# INLINABLE hold #-}
2446+ hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2447+ {-# INLINABLE holdDyn #-}
2448+ holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2449+ {-# INLINABLE holdIncremental #-}
2450+ holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2451+ {-# INLINABLE buildDynamic #-}
2452+ buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2453+ {-# INLINABLE headE #-}
2454+ headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2455+
2456+--------------------------------------------------------------------------------
2457+-- Deprecated items
2458+--------------------------------------------------------------------------------
2459+
2460+-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2461+{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2462+type SpiderEnv = SpiderTimeline
2463+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2464+ {-# INLINABLE subscribeEvent #-}
2465+ subscribeEvent e = SpiderHostFrame $ do
2466+ --TODO: Unsubscribe eventually (manually and/or with weak ref)
2467+ val <- liftIO $ newIORef Nothing
2468+ subscription <- subscribe (unSpiderEvent e) $ Subscriber
2469+ { subscriberPropagate = \a -> do
2470+ liftIO $ writeIORef val $ Just a
2471+ scheduleClear val
2472+ , subscriberInvalidateHeight = \_ -> return ()
2473+ , subscriberRecalculateHeight = \_ -> return ()
2474+ }
2475+ return $ SpiderEventHandle
2476+ { spiderEventHandleSubscription = subscription
2477+ , spiderEventHandleValue = val
2478+ }
2479+
2480+instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2481+ type EventTrigger (SpiderTimeline x) = RootTrigger x
2482+ type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2483+ type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2484+
2485+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2486+ {-# NOINLINE readEvent #-}
2487+ readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2488+ result <- readIORef $ spiderEventHandleValue h
2489+ touch h
2490+ return result
2491+
2492+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2493+ newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2494+ newFanEventWithTrigger f = SpiderHost $ do
2495+ es <- newFanEventWithTriggerIO f
2496+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2497+
2498+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2499+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2500+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2501+ es <- newFanEventWithTriggerIO f
2502+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2503+
2504+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2505+ {-# INLINABLE subscribeEvent #-}
2506+ subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2507+
2508+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2509+ type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2510+ fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2511+ runHostFrame = runFrame . runSpiderHostFrame
2512+
2513+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2514+unsafeNewSpiderTimelineEnv = do
2515+ lock <- newMVar ()
2516+ env <- newEventEnv
2517+#ifdef DEBUG
2518+ depthRef <- newIORef 0
2519+#endif
2520+ return $ STE $ SpiderTimelineEnv
2521+ { _spiderTimeline_lock = lock
2522+ , _spiderTimeline_eventEnv = env
2523+#ifdef DEBUG
2524+ , _spiderTimeline_depth = depthRef
2525+#endif
2526+ }
2527+
2528+-- | Create a new SpiderTimelineEnv
2529+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2530+newSpiderTimeline = withSpiderTimeline (pure . Some)
2531+
2532+data LocalSpiderTimeline (x :: Type) s
2533+
2534+instance Reifies s (SpiderTimelineEnv x) =>
2535+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2536+ spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)
2537+
2538+localSpiderTimeline
2539+ :: proxy s
2540+ -> SpiderTimelineEnv x
2541+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2542+localSpiderTimeline _ = coerce
2543+
2544+-- | Pass a new timeline to the given function.
2545+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2546+withSpiderTimeline k = do
2547+ env <- unsafeNewSpiderTimelineEnv
2548+ reify env $ \s -> k $ localSpiderTimeline s env
2549+
2550+newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2551+
2552+type ComputeM = EventM
2553+
2554+newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2555+
2556+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2557+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2558+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2559+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2560+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: DynamicS x (Identity a) } -- deriving (Functor, Applicative, Monad)
2561+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: DynamicS x p }
2562+ type PullM (SpiderTimeline x) = SpiderPullM x
2563+ type PushM (SpiderTimeline x) = SpiderPushM x
2564+ {-# INLINABLE never #-}
2565+ never = SpiderEvent eventNever
2566+ {-# INLINABLE constant #-}
2567+ constant = SpiderBehavior . behaviorConst
2568+ {-# INLINE push #-}
2569+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2570+ {-# INLINE pushCheap #-}
2571+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2572+ {-# INLINABLE pull #-}
2573+ pull = SpiderBehavior . pull . coerce
2574+ {-# INLINABLE fanG #-}
2575+ fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2576+ {-# INLINABLE mergeG #-}
2577+ mergeG
2578+ :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2579+ => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2580+ -> DMap k q
2581+ -> R.Event (SpiderTimeline x) (DMap k v)
2582+ mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2583+ {-# INLINABLE switch #-}
2584+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2585+ {-# INLINABLE coincidence #-}
2586+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2587+ {-# INLINABLE current #-}
2588+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2589+ {-# INLINABLE updated #-}
2590+ updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic
2591+ {-# INLINABLE unsafeBuildDynamic #-}
2592+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2593+ {-# INLINABLE unsafeBuildIncremental #-}
2594+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2595+ {-# INLINABLE mergeIncrementalG #-}
2596+ mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2597+ {-# INLINABLE mergeIncrementalWithMoveG #-}
2598+ mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2599+ {-# INLINABLE currentIncremental #-}
2600+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2601+ {-# INLINABLE updatedIncremental #-}
2602+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2603+ {-# INLINABLE incrementalToDynamic #-}
2604+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2605+ c <- readBehaviorUntracked $ dynamicCurrent i
2606+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2607+ eventCoercion Coercion = Coercion
2608+ behaviorCoercion Coercion = Coercion
2609+ dynamicCoercion Coercion = Coercion
2610+ incrementalCoercion Coercion Coercion = Coercion
2611+ {-# INLINABLE mergeIntIncremental #-}
2612+ mergeIntIncremental = SpiderEvent . mergeInt . coerce
2613+ {-# INLINABLE fanInt #-}
2614+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2615+
2616+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2617+
2618+data SpiderEventHandle x a = SpiderEventHandle
2619+ { spiderEventHandleSubscription :: EventSubscription x
2620+ , spiderEventHandleValue :: IORef (Maybe a)
2621+ }
2622+
2623+instance MonadRef (EventM x) where
2624+ type Ref (EventM x) = Ref IO
2625+ {-# INLINABLE newRef #-}
2626+ {-# INLINABLE readRef #-}
2627+ {-# INLINABLE writeRef #-}
2628+ newRef = liftIO . newRef
2629+ readRef = liftIO . readRef
2630+ writeRef r a = liftIO $ writeRef r a
2631+
2632+instance MonadAtomicRef (EventM x) where
2633+ {-# INLINABLE atomicModifyRef #-}
2634+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2635+
2636+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2637+newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2638+
2639+instance Monad (SpiderHost x) where
2640+ {-# INLINABLE (>>=) #-}
2641+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2642+ {-# INLINABLE (>>) #-}
2643+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2644+ {-# INLINABLE return #-}
2645+ return x = SpiderHost $ return x
2646+#if !MIN_VERSION_base(4,13,0)
2647+ {-# INLINABLE fail #-}
2648+ fail = MonadFail.fail
2649+#endif
2650+
2651+instance MonadFail (SpiderHost x) where
2652+ {-# INLINABLE fail #-}
2653+ fail s = SpiderHost $ MonadFail.fail s
2654+
2655+-- | Run an action affecting the global Spider timeline; this will be guarded by
2656+-- a mutex for that timeline
2657+runSpiderHost :: SpiderHost Global a -> IO a
2658+runSpiderHost (SpiderHost a) = a
2659+
2660+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2661+-- mutex for that timeline
2662+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2663+runSpiderHostForTimeline (SpiderHost a) _ = a
2664+
2665+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2666+ deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2667+
2668+instance Monad (SpiderHostFrame x) where
2669+ {-# INLINABLE (>>=) #-}
2670+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2671+ {-# INLINABLE (>>) #-}
2672+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2673+ {-# INLINABLE return #-}
2674+ return x = SpiderHostFrame $ return x
2675+#if !MIN_VERSION_base(4,13,0)
2676+ {-# INLINABLE fail #-}
2677+ fail s = SpiderHostFrame $ fail s
2678+#endif
2679+
2680+instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2681+ notReadyUntil _ = pure ()
2682+ notReady = pure ()
2683+
2684+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2685+newEventWithTriggerIO f = do
2686+ es <- newFanEventWithTriggerIO $ \Refl -> f
2687+ return $ select es Refl
2688+
2689+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2690+newFanEventWithTriggerIO f = do
2691+ occRef <- newIORef DMap.empty
2692+ subscribedRef <- newIORef DMap.empty
2693+ let !r = Root
2694+ { rootOccurrence = occRef
2695+ , rootSubscribed = subscribedRef
2696+ , rootInit = f
2697+ }
2698+ return $ EventSelector $ \k -> eventRoot k r
2699+
2700+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2701+
2702+instance MonadRef (SpiderHost x) where
2703+ type Ref (SpiderHost x) = Ref IO
2704+ newRef = SpiderHost . newRef
2705+ readRef = SpiderHost . readRef
2706+ writeRef r = SpiderHost . writeRef r
2707+
2708+instance MonadAtomicRef (SpiderHost x) where
2709+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2710+
2711+instance MonadRef (SpiderHostFrame x) where
2712+ type Ref (SpiderHostFrame x) = Ref IO
2713+ newRef = SpiderHostFrame . newRef
2714+ readRef = SpiderHostFrame . readRef
2715+ writeRef r = SpiderHostFrame . writeRef r
2716+
2717+instance MonadAtomicRef (SpiderHostFrame x) where
2718+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2719+
2720+instance PrimMonad (SpiderHostFrame x) where
2721+ type PrimState (SpiderHostFrame x) = PrimState IO
2722+ primitive = SpiderHostFrame . EventM . primitive
2723+
2724+instance NotReady (SpiderTimeline x) (SpiderHost x) where
2725+ notReadyUntil _ = return ()
2726+ notReady = return ()
2727+
2728+instance HasSpiderTimeline x => NotReady (SpiderTimeline x) (PerformEventT (SpiderTimeline x) (SpiderHost x)) where
2729+ notReadyUntil _ = return ()
2730+ notReady = return ()