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