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