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