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