@@ -1,2681 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ConstraintKinds #-}
4−{-# LANGUAGE EmptyDataDecls #-}
5−{-# LANGUAGE ExistentialQuantification #-}
6−{-# LANGUAGE FlexibleContexts #-}
7−{-# LANGUAGE FlexibleInstances #-}
8−{-# LANGUAGE FunctionalDependencies #-}
9−{-# LANGUAGE GADTs #-}
10−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11−{-# LANGUAGE LambdaCase #-}
12−{-# LANGUAGE MultiWayIf #-}
13−{-# LANGUAGE RankNTypes #-}
14−{-# LANGUAGE RoleAnnotations #-}
15−{-# LANGUAGE ScopedTypeVariables #-}
16−{-# LANGUAGE TypeFamilies #-}
17−{-# LANGUAGE TypeOperators #-}
18−{-# LANGUAGE UndecidableInstances #-}
19−{-# LANGUAGE PolyKinds #-}
20−{-# LANGUAGE InstanceSigs #-}
21−
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−#if defined(MIN_VERSION_semialign)
71−#if MIN_VERSION_these(0,8,0)
72−import Data.These.Combinators (justThese)
73−#endif
74−#endif
75−
76−#ifdef DEBUG_CYCLES
77−import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
78−import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
79−import qualified Data.List.NonEmpty as NonEmpty
80−import Data.Monoid (mempty)
81−import Data.Tree (Forest, Tree (..), drawForest)
82−#endif
83−
84−import Data.FastWeakBag (FastWeakBag)
85−import qualified Data.FastWeakBag as FastWeakBag
86−import Data.Reflection
87−import Data.Some (Some(Some))
88−import Data.Type.Coercion
89−import Data.Profunctor.Unsafe ((#.), (.#))
90−import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
91−import qualified Data.WeakBag as WeakBag
92−import qualified Reflex.Class
93−import qualified Reflex.Class as R
94−import qualified Reflex.Host.Class
95−import Reflex.NotReady.Class
96−import Reflex.Patch
97−import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
98−
99−#ifdef DEBUG_TRACE_EVENTS
100−import qualified Data.ByteString.Char8 as BS8
101−import System.IO (stderr)
102−#endif
103−
104−#ifdef DEBUG_TRACE_EVENTS
105−
106−withStackOneLine :: (BS8.ByteString -> a) -> a
107−withStackOneLine expr = unsafePerformIO $ do
108− stack <- currentCallStack
109− return (expr (BS8.pack (unwords (reverse stack))))
110−
111−#endif
112−
113−debugPropagate :: Bool
114−
115−debugInvalidateHeight :: Bool
116−
117−debugInvalidate :: Bool
118−
119−#ifdef DEBUG
120−
121−#define DEBUG_NODEIDS
122−
123−debugPropagate = True
124−
125−debugInvalidateHeight = False
126−
127−debugInvalidate = True
128−
129−class HasNodeId a where
130− getNodeId :: a -> Int
131−
132−instance HasNodeId (Hold x p a) where
133− getNodeId = holdNodeId
134−
135−instance HasNodeId (PushSubscribed x a b) where
136− getNodeId = pushSubscribedNodeId
137−
138−instance HasNodeId (SwitchSubscribed x a) where
139− getNodeId = switchSubscribedNodeId
140−
141−instance HasNodeId (FanSubscribed x a) where
142− getNodeId = fanSubscribedNodeId
143−
144−instance HasNodeId (CoincidenceSubscribed x a) where
145− getNodeId = coincidenceSubscribedNodeId
146−
147−instance HasNodeId (RootSubscribed x a) where
148− getNodeId = rootSubscribedNodeId
149−
150−instance HasNodeId (Pull x a) where
151− getNodeId = pullNodeId
152−
153−{-# INLINE showNodeId #-}
154−showNodeId :: HasNodeId a => a -> String
155−showNodeId = ("#"<>) . show . getNodeId
156−
157−showSubscriberType :: Subscriber x a -> String
158−showSubscriberType = \case
159− SubscriberPush _ _ -> "SubscriberPush"
160− SubscriberMerge _ _ -> "SubscriberMerge"
161− SubscriberFan _ -> "SubscriberFan"
162− SubscriberMergeChange _ -> "SubscriberMergeChange"
163− SubscriberHold _ -> "SubscriberHold"
164− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
165− SubscriberSwitch _ -> "SubscriberSwitch"
166− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
167− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
168− SubscriberHandle -> "SubscriberHandle"
169−
170−showEventType :: Event x a -> String
171−showEventType = \case
172− EventRoot _ _ -> "EventRoot"
173− EventNever -> "EventNever"
174− EventPush _ -> "EventPush"
175− EventMerge _ -> "EventMerge"
176− EventFan _ _ -> "EventFan"
177− EventSwitch _ -> "EventSwitch"
178− EventCoincidence _ -> "EventCoincidence"
179− EventHold _ -> "EventHold"
180− EventDyn _ -> "EventDyn"
181− EventHoldIdentity _ -> "EventHoldIdentity"
182− EventDynIdentity _ -> "EventDynIdentity"
183−
184−#else
185−
186−debugPropagate = False
187−
188−debugInvalidateHeight = False
189−
190−debugInvalidate = False
191−
192−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
193−{-# INLINE showNodeId #-}
194−showNodeId :: a -> String
195−showNodeId _ = ""
196−
197−#endif
198−
199−#ifdef DEBUG_NODEIDS
200−{-# NOINLINE nextNodeIdRef #-}
201−nextNodeIdRef :: IORef Int
202−nextNodeIdRef = unsafePerformIO $ newIORef 1
203−
204−newNodeId :: IO Int
205−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
206−#endif
207−
208−--------------------------------------------------------------------------------
209−-- EventSubscription
210−--------------------------------------------------------------------------------
211−
212−--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
213−-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
214−data EventSubscription x = EventSubscription
215− { _eventSubscription_unsubscribe :: !(IO ())
216− , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
217− }
218−
219−unsubscribe :: EventSubscription x -> IO ()
220−unsubscribe (EventSubscription u _) = u
221−
222−--------------------------------------------------------------------------------
223−-- Event
224−--------------------------------------------------------------------------------
225−
226−newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
227−
228−{-# INLINE subscribeAndRead #-}
229−subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
230−subscribeAndRead = unEvent
231−
232−{-# RULES
233−"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
234−"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
235−"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
236− #-}
237−
238−-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
239−-- caching; if the computation function is very cheap, this is (much) more
240−-- efficient than 'push'
241−{-# INLINE [1] pushCheap #-}
242−pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
243−pushCheap !f e = Event $ \sub -> do
244− (subscription, occ) <- subscribeAndRead e $ sub
245− { subscriberPropagate = \a -> do
246− mb <- f a
247− mapM_ (subscriberPropagate sub) mb
248− }
249− occ' <- join <$> mapM f occ
250− return (subscription, occ')
251−
252−-- | A subscriber that never triggers other 'Event's
253−{-# INLINE terminalSubscriber #-}
254−terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
255−terminalSubscriber p = Subscriber
256− { subscriberPropagate = p
257− , subscriberInvalidateHeight = \_ -> return ()
258− , subscriberRecalculateHeight = \_ -> return ()
259− }
260−
261−-- | Subscribe to an Event only for the duration of one occurrence
262−{-# INLINE subscribeAndReadHead #-}
263−subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
264−subscribeAndReadHead e sub = do
265− subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
266− (subscription, occ) <- subscribeAndRead e $ sub
267− { subscriberPropagate = \a -> do
268− liftIO $ unsubscribe =<< readIORef subscriptionRef
269− subscriberPropagate sub a
270− }
271− liftIO $ case occ of
272− Nothing -> writeIORef subscriptionRef $! subscription
273− Just _ -> unsubscribe subscription
274− return (subscription, occ)
275−
276−--TODO: Make this lazy in its input event
277−headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
278−headE originalE = do
279− parent <- liftIO $ newIORef $ Just originalE
280− defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
281− let clearParent = liftIO $ writeIORef parent Nothing
282− (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ \_ -> clearParent
283− when (isJust occ) clearParent
284− return $ Event $ \sub -> do
285− liftIO (readIORef parent) >>= \case
286− Nothing -> return (EventSubscription (return ()) $ EventSubscribed zeroRef $ toAny (), Nothing)
287− Just e -> subscribeAndReadHead e sub
288−
289−data CacheSubscribed x a
290− = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
291− , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
292− , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
293− }
294−
295−-- | Construct an 'Event' whose value is guaranteed not to be recomputed
296−-- repeatedly
297−--
298−--TODO: Try a caching strategy where we subscribe directly to the parent when
299−--there's only one subscriber, and then build our own FastWeakBag only when a second
300−--subscriber joins
301−{-# NOINLINE [0] cacheEvent #-}
302−cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
303−cacheEvent e =
304−#ifdef DEBUG_TRACE_EVENTS
305− withStackOneLine $ \callSite -> Event $
306−#else
307− Event $
308−#endif
309− unsafePerformIO $ do
310− mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
311− <- newIORef emptyFastWeak
312− pure $ \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 v -> Event x (v 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 v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
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 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 v -> 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 $ _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 $ _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 $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
617− innerParents = maybeToList $ fmap Some 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 s0) $ fix $ \loop (Some 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 s :)
638− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
639− forM_ subscribers $ \(Some 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 (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 (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 (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 $ 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 $ 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 $ 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 v a = FanSubscribedChildren
1065− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1066− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1067− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
1068− }
1069−
1070−data FanSubscribed x k v
1071− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1072− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1073− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- 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 v
1081− = Fan { fanParent :: !(Event x (DMap k v))
1082− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
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−#if defined(MIN_VERSION_semialign)
1148− zip x y = mapMaybe justThese $ align x y
1149−#endif
1150−
1151−data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1152− | BuildDyn !(EventM x (PatchTarget p), Event x p)
1153− | HoldDyn !(Hold x p)
1154−
1155−newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1156−
1157−newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1158−newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1159−
1160−--TODO: Avoid the duplication between this and R.zipDynWith
1161−zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1162−zipDynWith f da db =
1163− let eab = align (dynamicUpdated da) (dynamicUpdated db)
1164− ec = flip push eab $ \o -> do
1165− (a, b) <- case o of
1166− This (Identity a) -> do
1167− b <- readBehaviorUntracked $ dynamicCurrent db
1168− return (a, b)
1169− That (Identity b) -> do
1170− a <- readBehaviorUntracked $ dynamicCurrent da
1171− return (a, b)
1172− These (Identity a) (Identity b) -> return (a, b)
1173− return $ Just $ Identity $ f a b
1174− in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1175−
1176−buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1177−buildDynamic readV0 v' = do
1178− result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1179− let !d = Dyn result
1180− defer $ SomeDynInit d
1181− return d
1182−
1183−unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1184−unsafeBuildDynamic readV0 v' =
1185− Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
1186−
1187−-- ResultM can read behaviors and events
1188−type ResultM = EventM
1189−
1190−instance HasSpiderTimeline x => Functor (Event x) where
1191− fmap f = push $ return . Just . f
1192−
1193−instance Functor (Behavior x) where
1194− fmap f = pull . fmap f . readBehaviorTracked
1195−
1196−{-# INLINE push #-}
1197−push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1198−push f e = cacheEvent (pushCheap f e)
1199−
1200−{-# INLINABLE pull #-}
1201−pull :: BehaviorM x a -> Behavior x a
1202−pull a = unsafePerformIO $ do
1203− ref <- newIORef Nothing
1204−#ifdef DEBUG_NODEIDS
1205− nid <- newNodeId
1206−#endif
1207− pure $ behaviorPull $ Pull
1208− { pullCompute = a
1209− , pullValue = ref
1210−#ifdef DEBUG_NODEIDS
1211− , pullNodeId = nid
1212−#endif
1213− }
1214−
1215−{-# INLINABLE switch #-}
1216−switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1217−switch a = unsafePerformIO $ do
1218− ref <- newIORef Nothing
1219− pure $ eventSwitch $ Switch
1220− { switchParent = a
1221− , switchSubscribed = ref
1222− }
1223−
1224−coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1225−coincidence a = unsafePerformIO $ do
1226− ref <- newIORef Nothing
1227− pure $ eventCoincidence $ Coincidence
1228− { coincidenceParent = a
1229− , coincidenceSubscribed = ref
1230− }
1231−
1232−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1233−run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1234−run roots after = do
1235− tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1236− let t = spiderTimeline :: SpiderTimelineEnv x
1237− result <- SpiderHost $ withMVar (_spiderTimeline_lock t) $ \_ -> unSpiderHost $ runFrame $ do
1238− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1239− occBefore <- liftIO $ do
1240− occBefore <- readIORef occRef
1241− writeIORef occRef $! DMap.insert k a occBefore
1242− return occBefore
1243− if DMap.null occBefore
1244− then do scheduleRootClear occRef
1245− return $ Just r
1246− else return Nothing
1247− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1248− propagate a subscribersRef
1249− delayedRef <- asksEventEnv eventEnvDelayedMerges
1250− let go = do
1251− delayed <- liftIO $ readIORef delayedRef
1252− case IntMap.minViewWithKey delayed of
1253− Nothing -> return ()
1254− Just ((currentHeight, cur), future) -> do
1255− tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1256− putCurrentHeight $ Height currentHeight
1257− liftIO $ writeIORef delayedRef $! future
1258− sequence_ cur
1259− go
1260− go
1261− putCurrentHeight maxBound
1262− after
1263− tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1264− return result
1265−
1266−scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1267−scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1268− height <- liftIO $ readIORef heightRef
1269− currentHeight <- getCurrentHeight
1270− case height `compare` currentHeight of
1271− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1272− GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1273− EQ -> a
1274−
1275−newtype Clear a = Clear (IORef (Maybe a))
1276−
1277−newtype IntClear a = IntClear (IORef (IntMap a))
1278−
1279−newtype RootClear k = RootClear (IORef (DMap k Identity))
1280−
1281−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1282−
1283−debugFinalize :: Bool
1284−debugFinalize = False
1285−
1286−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1287−mkWeakPtrWithDebug x debugNote = do
1288− x' <- evaluate x
1289− mkWeakPtr x' $
1290− if debugFinalize
1291− then Just $ putStrLn $ "finalizing: " ++ debugNote
1292− else Nothing
1293−
1294−type WeakList a = [Weak a]
1295−
1296−{-# INLINE withIncreasedDepth #-}
1297−#ifdef DEBUG
1298−withIncreasedDepth :: CanTrace x m => m a -> m a
1299−withIncreasedDepth a = do
1300− spiderTimeline <- askSpiderTimelineEnv
1301− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1302− result <- a
1303− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1304− return result
1305−#else
1306−withIncreasedDepth :: m a -> m a
1307−withIncreasedDepth = id
1308−#endif
1309−
1310−type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1311−
1312−{-# INLINE tracePropagate #-}
1313−tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1314−tracePropagate p = traceWhen p debugPropagate
1315−
1316−{-# INLINE traceInvalidate #-}
1317−traceInvalidate :: String -> IO ()
1318−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1319−
1320−{-# INLINE traceWhen #-}
1321−traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1322−traceWhen p b message = traceMWhen p b $ return message
1323−
1324−{-# INLINE traceMWhen #-}
1325−traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1326−traceMWhen _ b getMessage = when b $ do
1327− message <- getMessage
1328−#ifdef DEBUG
1329− spiderTimeline <- askSpiderTimelineEnv
1330− d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1331−#else
1332− let d = 0
1333−#endif
1334− liftIO $ putStrLn $ replicate d ' ' <> message
1335−
1336−whoCreatedIORef :: IORef a -> IO [String]
1337−whoCreatedIORef (IORef a) = whoCreated $! a
1338−
1339−#ifdef DEBUG_CYCLES
1340−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1341−groupByHead = \case
1342− [] -> []
1343− (x :| xs) : t -> case groupByHead t of
1344− [] -> [(x, xs :| [])]
1345− l@((y, yss) : t')
1346− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1347− | otherwise -> (x, xs :| []) : l
1348−
1349−listsToForest :: Eq a => [[a]] -> Forest a
1350−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1351−#endif
1352−
1353−{-# INLINE propagateSubscriberHold #-}
1354−propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1355−propagateSubscriberHold h a = do
1356− {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1357− invalidators <- liftIO $ readIORef $ holdInvalidators h
1358− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1359− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1360− case {-# SCC "apply" #-} apply a v of
1361− Nothing -> return ()
1362− Just v' -> do
1363− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1364− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1365− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1366− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1367−
1368−data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1369−
1370−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1371−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1372−
1373−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1374−askInvalidator = do
1375− (!m, _) <- BehaviorM ask
1376− case m of
1377− Nothing -> return Nothing
1378− Just (!wi, _) -> return $ Just wi
1379−
1380−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1381−askParentsRef = do
1382− (!m, _) <- BehaviorM ask
1383− case m of
1384− Nothing -> return Nothing
1385− Just (_, !p) -> return $ Just p
1386−
1387−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1388−askBehaviorHoldInits = do
1389− (_, !his) <- BehaviorM ask
1390− return his
1391−
1392−{-# INLINE getDynHold #-}
1393−getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1394−getDynHold d = do
1395− mh <- liftIO $ readIORef $ unDyn d
1396− case mh of
1397− HoldDyn h -> return h
1398− UnsafeDyn (readV0, v') -> do
1399− holdInits <- getDeferralQueue
1400− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1401− hold' v0 v'
1402− BuildDyn (readV0, v') -> do
1403− v0 <- liftIO $ runEventM readV0
1404− hold' v0 v'
1405− where
1406− hold' v0 v' = do
1407− h <- hold v0 v'
1408− liftIO $ writeIORef (unDyn d) $ HoldDyn h
1409− return h
1410−
1411−
1412−-- Always refers to 0
1413−{-# NOINLINE zeroRef #-}
1414−zeroRef :: IORef Height
1415−zeroRef = unsafePerformIO $ newIORef zeroHeight
1416−
1417−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1418−getRootSubscribed k r sub = do
1419− mSubscribed <- readIORef $ rootSubscribed r
1420− let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1421− case DMap.lookup k mSubscribed of
1422− Just subscribed -> {-# SCC "hitRoot" #-} do
1423− sln <- subscribeRootSubscribed subscribed sub
1424− occ <- getOcc
1425− return (sln, subscribed, occ)
1426− Nothing -> {-# SCC "missRoot" #-} do
1427− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1428− let !cached = rootSubscribed r
1429− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1430− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1431− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1432− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1433− writeIORef uninitRef $! uninit
1434−#ifdef DEBUG_NODEIDS
1435− nid <- newNodeId
1436−#endif
1437− let !subscribed = RootSubscribed
1438− { rootSubscribedKey = k
1439− , rootSubscribedCachedSubscribed = cached
1440− , rootSubscribedOccurrence = getOcc
1441− , rootSubscribedSubscribers = subs
1442− , rootSubscribedUninit = uninit
1443− , rootSubscribedWeakSelf = weakSelf
1444−#ifdef DEBUG_NODEIDS
1445− , rootSubscribedNodeId = nid
1446−#endif
1447− }
1448− -- If we die at the same moment that all our children die, they will
1449− -- try to clean us up but will fail because their Weak reference to us
1450− -- will also be dead. So, if we are dying, check if there are any
1451− -- children; since children don't bother cleaning themselves up if
1452− -- their parents are already dead, I don't think there's a race
1453− -- condition here. However, if there are any children, then we can
1454− -- infer that we need to clean ourselves up, so we do.
1455− finalCleanup = do
1456− cs <- readIORef $ _weakBag_children subs
1457− when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1458− writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1459− 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
1460− occ <- getOcc
1461− return (sln, subscribed, occ)
1462−
1463−#ifdef USE_TEMPLATE_HASKELL
1464−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1465−#endif
1466−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1467−cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1468− rootSubscribedUninit self
1469− modifyIORef' cached $ DMap.delete k
1470−
1471−{-# INLINE subscribeRootSubscribed #-}
1472−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1473−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1474−
1475−newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1476−
1477−data FanInt x a = FanInt
1478− { _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
1479− , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1480− , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1481− }
1482−
1483−newFanInt :: IO (FanInt x a)
1484−newFanInt = do
1485− 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
1486− subscriptionRef <- newIORef $ error "fanInt: no subscription"
1487− occRef <- newIORef $ error "fanInt: no occurrence"
1488− return $ FanInt
1489− { _fanInt_subscribers = subscribers
1490− , _fanInt_subscriptionRef = subscriptionRef
1491− , _fanInt_occRef = occRef
1492− }
1493−
1494−fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1495−fanInt p = unsafePerformIO $ do
1496− self <- newFanInt
1497− pure $ EventSelectorInt $ \k -> Event $ \sub -> do
1498− isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1499− when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1500− (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1501− { subscriberPropagate = \m -> do
1502− liftIO $ writeIORef (_fanInt_occRef self) m
1503− scheduleIntClear $ _fanInt_occRef self
1504− FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1505− FastWeakBag.traverse b $ \s -> do
1506− subscriberPropagate s v
1507− , subscriberInvalidateHeight = \old -> do
1508− FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1509− FastWeakBag.traverse b $ \s -> do
1510− subscriberInvalidateHeight s old
1511− , subscriberRecalculateHeight = \new -> do
1512− FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1513− FastWeakBag.traverse b $ \s -> do
1514− subscriberRecalculateHeight s new
1515− }
1516− liftIO $ do
1517− writeIORef (_fanInt_subscriptionRef self) subscription
1518− writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1519− scheduleIntClear $ _fanInt_occRef self
1520− liftIO $ do
1521− b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1522− Nothing -> do
1523− b <- FastWeakBag.empty
1524− FastMutableIntMap.insert (_fanInt_subscribers self) k b
1525− return b
1526− Just b -> return b
1527− t <- liftIO $ FastWeakBag.insert sub b
1528− currentOcc <- readIORef (_fanInt_occRef self)
1529− (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1530− return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1531−
1532−{-# INLINABLE getFanSubscribed #-}
1533−getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k v -> Subscriber x (v a) -> EventM x (WeakBagTicket, FanSubscribed x k v, Maybe (v a))
1534−getFanSubscribed k f sub = do
1535− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1536− case mSubscribed of
1537− Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1538− sln <- subscribeFanSubscribed k subscribed sub
1539− occ <- readIORef $ fanSubscribedOccurrence subscribed
1540− return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1541− Nothing -> {-# SCC "missFan" #-} do
1542− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1543− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1544− s <- liftIO $ newSubscriberFan subscribedUnsafe
1545− (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1546− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1547− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1548− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1549− occRef <- liftIO $ newIORef parentOcc
1550− when (isJust parentOcc) $ scheduleClear occRef
1551−#ifdef DEBUG_NODEIDS
1552− nid <- liftIO newNodeId
1553−#endif
1554− let subscribed = FanSubscribed
1555− { fanSubscribedCachedSubscribed = fanSubscribed f
1556− , fanSubscribedOccurrence = occRef
1557− , fanSubscribedParent = subscription
1558− , fanSubscribedSubscribers = subscribersRef
1559−#ifdef DEBUG_NODEIDS
1560− , fanSubscribedNodeId = nid
1561−#endif
1562− }
1563− let !self = (k, subscribed)
1564− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1565− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1566− liftIO $ writeIORef subscribedRef $! subscribed
1567− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1568− return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1569−
1570−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
1571−cleanupFanSubscribed (k, subscribed) = do
1572− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1573− let reducedSubscribers = DMap.delete k subscribers
1574− if DMap.null reducedSubscribers
1575− then do
1576− unsubscribe $ fanSubscribedParent subscribed
1577− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1578− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1579− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1580−
1581−{-# INLINE subscribeFanSubscribed #-}
1582−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
1583−subscribeFanSubscribed k subscribed sub = do
1584− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1585− case DMap.lookup k subscribers of
1586− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1587− let !self = (k, subscribed)
1588− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1589− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1590− 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
1591− return sln
1592− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1593−
1594−{-# INLINABLE getSwitchSubscribed #-}
1595−getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1596−getSwitchSubscribed s sub = do
1597− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1598− case mSubscribed of
1599− Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1600− sln <- subscribeSwitchSubscribed subscribed sub
1601− occ <- readIORef $ switchSubscribedOccurrence subscribed
1602− return (sln, subscribed, occ)
1603− Nothing -> {-# SCC "missSwitch" #-} do
1604− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1605− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1606− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1607− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1608− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1609− wiRef <- liftIO $ newIORef wi
1610− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1611− holdInits <- getDeferralQueue
1612− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1613− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1614− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1615− subscriptionRef <- liftIO $ newIORef subscription
1616− occRef <- liftIO $ newIORef parentOcc
1617− when (isJust parentOcc) $ scheduleClear occRef
1618− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1619− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1620−#ifdef DEBUG_NODEIDS
1621− nid <- liftIO newNodeId
1622−#endif
1623− let !subscribed = SwitchSubscribed
1624− { switchSubscribedCachedSubscribed = switchSubscribed s
1625− , switchSubscribedOccurrence = occRef
1626− , switchSubscribedHeight = heightRef
1627− , switchSubscribedSubscribers = subs
1628− , switchSubscribedOwnInvalidator = i
1629− , switchSubscribedOwnWeakInvalidator = wiRef
1630− , switchSubscribedBehaviorParents = parentsRef
1631− , switchSubscribedParent = switchParent s
1632− , switchSubscribedCurrentParent = subscriptionRef
1633− , switchSubscribedWeakSelf = weakSelf
1634−#ifdef DEBUG_NODEIDS
1635− , switchSubscribedNodeId = nid
1636−#endif
1637− }
1638− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1639− liftIO $ writeIORef subscribedRef $! subscribed
1640− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1641− return (slnForSub, subscribed, parentOcc)
1642−
1643−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1644−cleanupSwitchSubscribed subscribed = do
1645− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1646− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1647− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1648−
1649−{-# INLINE subscribeSwitchSubscribed #-}
1650−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1651−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1652−
1653−{-# INLINABLE getCoincidenceSubscribed #-}
1654−getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1655−getCoincidenceSubscribed c sub = do
1656− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1657− case mSubscribed of
1658− Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1659− sln <- subscribeCoincidenceSubscribed subscribed sub
1660− occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1661− return (sln, subscribed, occ)
1662− Nothing -> {-# SCC "missCoincidence" #-} do
1663− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1664− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1665− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1666− (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1667− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1668− (occ, height, mInnerSubd) <- case outerOcc of
1669− Nothing -> return (Nothing, outerHeight, Nothing)
1670− Just o -> do
1671− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1672− return (occ, height, Just innerSubd)
1673− occRef <- liftIO $ newIORef occ
1674− when (isJust occ) $ scheduleClear occRef
1675− heightRef <- liftIO $ newIORef height
1676− innerSubdRef <- liftIO $ newIORef mInnerSubd
1677− scheduleClear innerSubdRef
1678− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1679− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1680−#ifdef DEBUG_NODEIDS
1681− nid <- liftIO newNodeId
1682−#endif
1683− let subscribed = CoincidenceSubscribed
1684− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1685− , coincidenceSubscribedOccurrence = occRef
1686− , coincidenceSubscribedHeight = heightRef
1687− , coincidenceSubscribedSubscribers = subs
1688− , coincidenceSubscribedOuter = subOuter
1689− , coincidenceSubscribedOuterParent = outerSubscription
1690− , coincidenceSubscribedInnerParent = innerSubdRef
1691− , coincidenceSubscribedWeakSelf = weakSelf
1692−#ifdef DEBUG_NODEIDS
1693− , coincidenceSubscribedNodeId = nid
1694−#endif
1695− }
1696− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1697− liftIO $ writeIORef subscribedRef $! subscribed
1698− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1699− return (slnForSub, subscribed, occ)
1700−
1701−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1702−cleanupCoincidenceSubscribed subscribed = do
1703− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1704− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1705−
1706−{-# INLINE subscribeCoincidenceSubscribed #-}
1707−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1708−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1709−
1710−{-# INLINE mergeG #-}
1711−mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1712− => (forall a. q a -> Event x (v a))
1713− -> Dynamic x (PatchDMap k q) -> Event x (DMap k v)
1714−mergeG nt d = cacheEvent (mergeCheap nt d)
1715−
1716−{-# INLINE mergeWithMove #-}
1717−mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1718− => (forall a. q a -> Event x (v a))
1719− -> Dynamic x (PatchDMapWithMove k q) -> Event x (DMap k v)
1720−mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1721−
1722−{-# INLINE [1] mergeCheap #-}
1723−mergeCheap
1724− :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1725− => (forall a. q a -> Event x (v a))
1726− -> Dynamic x (PatchDMap k q)
1727− -> Event x (DMap k v)
1728−mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
1729− where
1730− updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1731− updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1732− let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1733− (mOldSubd, newPs) <- case me of
1734− Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1735− Just e -> do
1736− let s = subscriber $ return k
1737− subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1738− newParentHeight <- liftIO $ getEventSubscribedHeight subd
1739− let newParent = MergeSubscribedParent subscription
1740− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1741− return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1742− forM_ mOldSubd $ \oldSubd -> do
1743− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1744− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1745− return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1746− foldM f ([], oldParents) $ DMap.toList p
1747−
1748− getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1749− getInitialSubscribers initialParents subscriber = do
1750− subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1751− let s = subscriber $ return k
1752− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1753− height <- liftIO $ getEventSubscribedHeight parentSubd
1754− return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
1755− return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1756− , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1757− , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1758− )
1759−
1760− destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1761− destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1762−
1763−{-# INLINE [1] mergeCheapWithMove #-}
1764−mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1765− => (forall a. q a -> Event x (v a))
1766− -> Dynamic x (PatchDMapWithMove k q)
1767− -> Event x (DMap k v)
1768−mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
1769− where
1770− updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1771− updateMe subscriber heightBagRef oldParents p = do
1772− -- Prepare new parents for insertion
1773− let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1774− subscribeParent k e = do
1775− keyRef <- liftIO $ newIORef k
1776− let s = subscriber $ liftIO $ readIORef keyRef
1777− subscription@(EventSubscription _ subd) <- subscribe e s
1778− liftIO $ do
1779− newParentHeight <- getEventSubscribedHeight subd
1780− modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1781− return $ MergeSubscribedParentWithMove subscription keyRef
1782− p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1783− -- Collect old parents for deletion and update the keys of moved parents
1784− let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1785− moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1786− Nothing -> do
1787− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1788− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1789− return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1790− Just toKey -> do
1791− liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1792− return Nothing
1793− toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1794− return (toDelete, applyAlways p' oldParents)
1795− getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1796− getInitialSubscribers initialParents subscriber = do
1797− subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1798− keyRef <- liftIO $ newIORef k
1799− let s = subscriber $ liftIO $ readIORef keyRef
1800− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1801− height <- liftIO $ getEventSubscribedHeight parentSubd
1802− return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1803− return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1804− , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1805− , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1806− )
1807−
1808− destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1809− destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1810−
1811−type MergeUpdateFunc k v x p s
1812− = (forall a. EventM x (k a) -> Subscriber x (v a))
1813− -> IORef HeightBag
1814− -> DMap k s
1815− -> p
1816− -> EventM x ([EventSubscription x], DMap k s)
1817−
1818−type MergeInitFunc k v q x s
1819− = DMap k q
1820− -> (forall a. EventM x (k a) -> Subscriber x (v a))
1821− -> EventM x (DMap k v, [Height], DMap k s)
1822−
1823−type MergeDestroyFunc k s
1824− = DMap k s
1825− -> IO ()
1826−
1827−data Merge x k v s = Merge
1828− { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1829− , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1830− , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1831− , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1832− , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
1833− }
1834−
1835−invalidateMergeHeight :: Merge x k v s -> IO ()
1836−invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1837−
1838−invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1839−invalidateMergeHeight' heightRef sub = do
1840− oldHeight <- readIORef heightRef
1841− 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
1842− writeIORef heightRef $! invalidHeight
1843− subscriberInvalidateHeight sub oldHeight
1844−
1845−revalidateMergeHeight :: Merge x k v s -> IO ()
1846−revalidateMergeHeight m = do
1847− currentHeight <- readIORef $ _merge_heightRef m
1848− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1849− heights <- readIORef $ _merge_heightBagRef m
1850− parents <- readIORef $ _merge_parentsRef m
1851− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1852− case heightBagSize heights `compare` DMap.size parents of
1853− LT -> return ()
1854− EQ -> do
1855− let height = succHeight $ heightBagMax heights
1856− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1857− writeIORef (_merge_heightRef m) $! height
1858− subscriberRecalculateHeight (_merge_sub m) height
1859− GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1860−
1861−scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
1862−scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1863− vals <- liftIO $ readIORef $ _merge_accumRef m
1864− 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
1865− --TODO: Assert that m is not empty
1866− subscriberPropagate (_merge_sub m) vals
1867−
1868−mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
1869−mergeSubscriber m getKey = Subscriber
1870− { subscriberPropagate = \a -> do
1871− oldM <- liftIO $ readIORef $ _merge_accumRef m
1872− k <- getKey
1873− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
1874− tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1875− liftIO $ writeIORef (_merge_accumRef m) $! newM
1876− when (DMap.null oldM) $ do -- Only schedule the firing once
1877− height <- liftIO $ readIORef $ _merge_heightRef m
1878− --TODO: assertions about height
1879− currentHeight <- getCurrentHeight
1880− when (height <= currentHeight) $ do
1881− if height /= invalidHeight
1882− then do
1883− myStack <- liftIO $ whoCreatedIORef undefined --TODO
1884− error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1885− else liftIO $ do
1886−#ifdef DEBUG_CYCLES
1887− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1888− stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
1889− let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1890−#else
1891− let cycleInfo = ""
1892−#endif
1893− error $ "Causality loop found" <> cycleInfo
1894− scheduleMergeSelf m height
1895− , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1896− modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1897− invalidateMergeHeight m
1898− , subscriberRecalculateHeight = \new -> do
1899− modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1900− revalidateMergeHeight m
1901− }
1902−
1903−--TODO: Be able to run as much of this as possible promptly
1904−updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
1905−updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1906− where updateMe = do
1907− oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1908− (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1909− liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1910− return subscriptionsToKill
1911−
1912−{-# INLINE mergeGCheap' #-}
1913−mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1914− => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> Dynamic x p -> Event x (DMap k v)
1915−mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1916− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1917− accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1918− heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1919− heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1920− parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1921− let m = Merge
1922− { _merge_parentsRef = parentsRef
1923− , _merge_heightBagRef = heightBagRef
1924− , _merge_heightRef = heightRef
1925− , _merge_sub = sub
1926− , _merge_accumRef = accumRef
1927− }
1928− (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1929− let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1930− myHeight = if invalidHeight `elem` heights
1931− then invalidHeight
1932− else succHeight $ heightBagMax myHeightBag
1933− currentHeight <- getCurrentHeight
1934− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1935− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1936− else (Nothing, dm)
1937− unless (DMap.null accum) $ do
1938− scheduleMergeSelf m myHeight
1939− liftIO $ writeIORef accumRef $! accum
1940− liftIO $ writeIORef heightRef $! myHeight
1941− liftIO $ writeIORef heightBagRef $! myHeightBag
1942− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1943− liftIO $ writeIORef parentsRef $! initialParentState
1944− defer $ SomeMergeInit $ do
1945− let s = Subscriber
1946− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1947− tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1948− defer $ updateMerge m updateFunc a
1949− , subscriberInvalidateHeight = \_ -> return ()
1950− , subscriberRecalculateHeight = \_ -> return ()
1951− }
1952− (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1953− forM_ change $ \c -> defer $ updateMerge m updateFunc c
1954− -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1955− -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1956− -- its subscription.
1957− liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1958− let unsubscribeAll = destroy =<< readIORef parentsRef
1959− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1960− , occ
1961− )
1962−
1963−mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1964−mergeInt = cacheEvent . mergeIntCheap
1965−
1966−{-# INLINABLE mergeIntCheap #-}
1967−mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1968−mergeIntCheap d = Event $ \sub -> do
1969− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1970− accum <- liftIO $ FastMutableIntMap.newEmpty
1971− heightRef <- liftIO $ newIORef zeroHeight
1972− heightBagRef <- liftIO $ newIORef heightBagEmpty
1973− parents <- liftIO $ FastMutableIntMap.newEmpty
1974− let scheduleSelf = do
1975− height <- liftIO $ readIORef $ heightRef
1976− scheduleMerge' height heightRef $ do
1977− vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1978− subscriberPropagate sub vals
1979− invalidateMyHeight = do
1980− invalidateMergeHeight' heightRef sub
1981− recalculateMyHeight = do
1982− currentHeight <- readIORef heightRef
1983− 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?
1984− heights <- readIORef heightBagRef
1985− numParents <- FastMutableIntMap.size parents
1986− case heightBagSize heights `compare` numParents of
1987− LT -> return ()
1988− EQ -> do
1989− let height = succHeight $ heightBagMax heights
1990− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1991− writeIORef heightRef $! height
1992− subscriberRecalculateHeight sub height
1993− GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
1994− mySubscriber k = Subscriber
1995− { subscriberPropagate = \a -> do
1996− wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1997− liftIO $ FastMutableIntMap.insert accum k a
1998− when wasEmpty scheduleSelf
1999− , subscriberInvalidateHeight = \old -> do
2000− modifyIORef' heightBagRef $ heightBagRemove old
2001− invalidateMyHeight
2002− , subscriberRecalculateHeight = \new -> do
2003− modifyIORef' heightBagRef $ heightBagAdd new
2004− recalculateMyHeight
2005− }
2006− forM_ (IntMap.toList initialParents) $ \(k, p) -> do
2007− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
2008− liftIO $ do
2009− forM_ parentOcc $ FastMutableIntMap.insert accum k
2010− FastMutableIntMap.insert parents k subscription
2011− height <- getEventSubscribedHeight parentSubd
2012− if height == invalidHeight
2013− then writeIORef heightRef invalidHeight
2014− else do
2015− modifyIORef' heightBagRef $ heightBagAdd height
2016− modifyIORef' heightRef $ \oldHeight ->
2017− if oldHeight == invalidHeight
2018− then invalidHeight
2019− else max (succHeight height) oldHeight
2020− myHeight <- liftIO $ readIORef heightRef
2021− currentHeight <- getCurrentHeight
2022− isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2023− occ <- if currentHeight >= myHeight -- If we should have fired by now
2024− then if isEmpty
2025− then return Nothing
2026− else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2027− else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2028− return Nothing
2029− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2030− defer $ SomeMergeInit $ do
2031− let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2032− where
2033− u = do
2034− let f k newParent = do
2035− subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2036− newParentHeight <- liftIO $ getEventSubscribedHeight subd
2037− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2038− return subscription
2039− newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2040− oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2041− liftIO $ for_ oldParents $ \oldParent -> do
2042− oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2043− modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2044− return $ IntMap.elems oldParents
2045− let s = Subscriber
2046− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2047− tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2048− defer $ updateMe a
2049− , subscriberInvalidateHeight = \_ -> return ()
2050− , subscriberRecalculateHeight = \_ -> return ()
2051− }
2052− (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2053− forM_ change $ \c -> defer $ updateMe c
2054− -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2055− -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2056− -- its subscription.
2057− liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2058− let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2059− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2060− , occ
2061− )
2062−
2063−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2064−newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
2065−
2066−fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2067−fanG e = unsafePerformIO $ do
2068− ref <- newIORef Nothing
2069− let f = Fan
2070− { fanParent = e
2071− , fanSubscribed = ref
2072− }
2073− pure $ EventSelectorG $ \k -> eventFan k f
2074−
2075−runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2076−runHoldInits holdInitRef dynInitRef mergeInitRef = do
2077− holdInits <- liftIO $ readIORef holdInitRef
2078− dynInits <- liftIO $ readIORef dynInitRef
2079− mergeInits <- liftIO $ readIORef mergeInitRef
2080− unless (null holdInits && null dynInits && null mergeInits) $ do
2081− liftIO $ writeIORef holdInitRef []
2082− liftIO $ writeIORef dynInitRef []
2083− liftIO $ writeIORef mergeInitRef []
2084− mapM_ initHold holdInits
2085− mapM_ initDyn dynInits
2086− mapM_ unSomeMergeInit mergeInits
2087− runHoldInits holdInitRef dynInitRef mergeInitRef
2088−
2089−initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2090−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2091−
2092−initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2093−initDyn (SomeDynInit d) = void $ getDynHold d
2094−
2095−newEventEnv :: IO (EventEnv x)
2096−newEventEnv = do
2097− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2098− holdInitRef <- newIORef []
2099− dynInitRef <- newIORef []
2100− mergeUpdateRef <- newIORef []
2101− mergeInitRef <- newIORef []
2102− heightRef <- newIORef zeroHeight
2103− toClearRef <- newIORef []
2104− toClearIntRef <- newIORef []
2105− toClearRootRef <- newIORef []
2106− coincidenceInfosRef <- newIORef []
2107− delayedRef <- newIORef IntMap.empty
2108− return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2109−
2110−clearEventEnv :: EventEnv x -> IO ()
2111−clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2112− writeIORef toAssignRef []
2113− writeIORef holdInitRef []
2114− writeIORef dynInitRef []
2115− writeIORef mergeUpdateRef []
2116− writeIORef mergeInitRef []
2117− writeIORef heightRef zeroHeight
2118− writeIORef toClearRef []
2119− writeIORef toClearIntRef []
2120− writeIORef toClearRootRef []
2121− writeIORef coincidenceInfosRef []
2122− writeIORef delayedRef IntMap.empty
2123−
2124−-- | Run an event action outside of a frame
2125−runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2126−runFrame a = SpiderHost $ do
2127− let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2128− let go = do
2129− result <- a
2130− 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
2131− return result
2132− result <- runEventM go
2133− toClear <- readIORef $ eventEnvClears env
2134− forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2135− toClearInt <- readIORef $ eventEnvIntClears env
2136− forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2137− toClearRoot <- readIORef $ eventEnvRootClears env
2138− forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2139− toAssign <- readIORef $ eventEnvAssignments env
2140− toReconnectRef <- newIORef []
2141− coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2142− forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2143− writeIORef vRef v
2144− when debugInvalidate $ putStrLn $ "Invalidating Hold"
2145− writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2146− mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2147− writeIORef (eventEnvMergeUpdates env) []
2148− when debugPropagate $ putStrLn "Updating merges"
2149− mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2150− when debugPropagate $ putStrLn "Updating merges done"
2151− toReconnect <- readIORef toReconnectRef
2152− clearEventEnv env
2153− switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2154− oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2155− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2156− when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2157− finalize wi
2158− i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2159− wi' <- mkWeakPtrWithDebug i "wi'"
2160− writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2161− writeIORef (switchSubscribedBehaviorParents subscribed) []
2162− writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2163− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2164− 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
2165− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2166− sub <- newSubscriberSwitch subscribed
2167− 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
2168− {-
2169− stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2170− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2171− EventRoot _ -> "EventRoot"
2172− EventNever -> "EventNever"
2173− _ -> "something else"
2174− -}
2175− writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2176− return oldSubscription
2177− liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2178− liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2179− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2180− EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2181− parentHeight <- getEventSubscribedHeight subd'
2182− myHeight <- readIORef $ switchSubscribedHeight subscribed
2183− when (parentHeight /= myHeight) $ do
2184− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2185− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2186− 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
2187− forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2188− unsubscribe subscription
2189− mapM_ invalidateCoincidenceHeight mcs
2190− forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2191− mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2192− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2193− height <- calculateSwitchHeight subscribed
2194− updateSwitchHeight height subscribed
2195− return result
2196−
2197−newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2198−
2199−{-# INLINE zeroHeight #-}
2200−zeroHeight :: Height
2201−zeroHeight = Height 0
2202−
2203−{-# INLINE invalidHeight #-}
2204−invalidHeight :: Height
2205−invalidHeight = Height (-1000)
2206−
2207−#ifdef DEBUG_CYCLES
2208−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2209−{-# INLINE invalidHeightBeingTraversed #-}
2210−invalidHeightBeingTraversed :: Height
2211−invalidHeightBeingTraversed = Height (-1001)
2212−#endif
2213−
2214−{-# INLINE succHeight #-}
2215−succHeight :: Height -> Height
2216−succHeight h@(Height a) =
2217− if h == invalidHeight
2218− then invalidHeight
2219− else Height $ succ a
2220−
2221−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2222−invalidateCoincidenceHeight subscribed = do
2223− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2224− when (oldHeight /= invalidHeight) $ do
2225− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2226− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2227−
2228−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2229−updateSwitchHeight new subscribed = do
2230− oldHeight <- readIORef $ switchSubscribedHeight subscribed
2231− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2232− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2233− writeIORef (switchSubscribedHeight subscribed) $! new
2234− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2235−
2236−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2237−recalculateCoincidenceHeight subscribed = do
2238− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2239− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2240− height <- calculateCoincidenceHeight subscribed
2241− when (height /= invalidHeight) $ do
2242− writeIORef (coincidenceSubscribedHeight subscribed) $! height
2243− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2244−
2245−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2246−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2247−
2248−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2249−calculateCoincidenceHeight subscribed = do
2250− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2251− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2252− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2253−
2254−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2255−
2256−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2257−invalidate toReconnectRef wis = do
2258− forM_ wis $ \wi -> do
2259− mi <- deRefWeak wi
2260− case mi of
2261− Nothing -> do
2262− traceInvalidate "invalidate Dead"
2263− return () --TODO: Should we clean this up here?
2264− Just i -> do
2265− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2266− case i of
2267− InvalidatorPull p -> do
2268− traceInvalidate $ "invalidate: Pull" <> showNodeId p
2269− mVal <- readIORef $ pullValue p
2270− forM_ mVal $ \val -> do
2271− writeIORef (pullValue p) Nothing
2272− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2273− InvalidatorSwitch subscribed -> do
2274− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2275− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2276− 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
2277−
2278−--------------------------------------------------------------------------------
2279−-- Reflex integration
2280−--------------------------------------------------------------------------------
2281−
2282−-- | Designates the default, global Spider timeline
2283−data SpiderTimeline x
2284−type role SpiderTimeline nominal
2285−
2286−-- | The default, global Spider environment
2287−type Spider = SpiderTimeline Global
2288−
2289−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2290− {-# INLINABLE sample #-}
2291− sample (SpiderBehavior b) = readBehaviorUntracked b
2292−
2293−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2294− {-# INLINABLE hold #-}
2295− hold = holdSpiderEventM
2296− {-# INLINABLE holdDyn #-}
2297− holdDyn = holdDynSpiderEventM
2298− {-# INLINABLE holdIncremental #-}
2299− holdIncremental = holdIncrementalSpiderEventM
2300− {-# INLINABLE buildDynamic #-}
2301− buildDynamic = buildDynamicSpiderEventM
2302− {-# INLINABLE headE #-}
2303− headE = R.slowHeadE
2304−-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2305−
2306−instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2307− {-# INLINABLE sample #-}
2308− sample = coerce . readBehaviorTracked . unSpiderBehavior
2309−
2310−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2311− {-# INLINABLE sample #-}
2312− sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2313−
2314−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2315− {-# INLINABLE hold #-}
2316− hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2317− {-# INLINABLE holdDyn #-}
2318− holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2319− {-# INLINABLE holdIncremental #-}
2320− holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2321− {-# INLINABLE buildDynamic #-}
2322− buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2323− {-# INLINABLE headE #-}
2324− headE = R.slowHeadE
2325−-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2326−
2327−instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2328− {-# INLINE return #-}
2329− return = pure
2330− {-# INLINE (>>=) #-}
2331− x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2332− {-# INLINE (>>) #-}
2333− (>>) = (*>)
2334− {-# INLINE fail #-}
2335− fail _ = error "Dynamic does not support 'fail'"
2336−
2337−{-# INLINABLE newJoinDyn #-}
2338−newJoinDyn :: HasSpiderTimeline x => Reflex.Spider.Internal.Dynamic x (Identity (Reflex.Spider.Internal.Dynamic x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2339−newJoinDyn d =
2340− let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2341− eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2342− eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2343− eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2344− v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2345− in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2346−
2347−instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2348− fmap = mapDynamicSpider
2349− x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2350−
2351−mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2352−mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2353−{-# INLINE [1] mapDynamicSpider #-}
2354−
2355−instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2356− pure = SpiderDynamic . dynamicConst
2357−#if MIN_VERSION_base(4,10,0)
2358− liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2359−#endif
2360− SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2361− a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2362− (<*) = flip (*>) -- There are no effects, so order doesn't matter
2363−
2364−holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2365−holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2366−
2367−holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2368−holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2369−
2370−holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2371−holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2372−
2373−buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2374−buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2375−
2376−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2377− {-# INLINABLE hold #-}
2378− hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2379− {-# INLINABLE holdDyn #-}
2380− holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2381− {-# INLINABLE holdIncremental #-}
2382− holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2383− {-# INLINABLE buildDynamic #-}
2384− buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2385− {-# INLINABLE headE #-}
2386− headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2387−
2388−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2389− sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2390−
2391−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2392− {-# INLINABLE hold #-}
2393− hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2394− {-# INLINABLE holdDyn #-}
2395− holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2396− {-# INLINABLE holdIncremental #-}
2397− holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2398− {-# INLINABLE buildDynamic #-}
2399− buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2400− {-# INLINABLE headE #-}
2401− headE = R.slowHeadE
2402−-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2403−
2404−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2405− {-# INLINABLE sample #-}
2406− sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2407−
2408−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2409− {-# INLINABLE sample #-}
2410− sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2411−
2412−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2413− {-# INLINABLE hold #-}
2414− hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2415− {-# INLINABLE holdDyn #-}
2416− holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2417− {-# INLINABLE holdIncremental #-}
2418− holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2419− {-# INLINABLE buildDynamic #-}
2420− buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2421− {-# INLINABLE headE #-}
2422− headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2423−
2424−--------------------------------------------------------------------------------
2425−-- Deprecated items
2426−--------------------------------------------------------------------------------
2427−
2428−-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2429−{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2430−type SpiderEnv = SpiderTimeline
2431−instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2432− {-# INLINABLE subscribeEvent #-}
2433− subscribeEvent e = SpiderHostFrame $ do
2434− --TODO: Unsubscribe eventually (manually and/or with weak ref)
2435− val <- liftIO $ newIORef Nothing
2436− subscription <- subscribe (unSpiderEvent e) $ Subscriber
2437− { subscriberPropagate = \a -> do
2438− liftIO $ writeIORef val $ Just a
2439− scheduleClear val
2440− , subscriberInvalidateHeight = \_ -> return ()
2441− , subscriberRecalculateHeight = \_ -> return ()
2442− }
2443− return $ SpiderEventHandle
2444− { spiderEventHandleSubscription = subscription
2445− , spiderEventHandleValue = val
2446− }
2447−
2448−instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2449− type EventTrigger (SpiderTimeline x) = RootTrigger x
2450− type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2451− type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2452−
2453−instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2454− {-# NOINLINE readEvent #-}
2455− readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2456− result <- readIORef $ spiderEventHandleValue h
2457− touch h
2458− return result
2459−
2460−instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2461− newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2462− newFanEventWithTrigger f = SpiderHost $ do
2463− es <- newFanEventWithTriggerIO f
2464− return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2465−
2466−instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2467− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2468− newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2469− es <- newFanEventWithTriggerIO f
2470− return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2471−
2472−instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2473− {-# INLINABLE subscribeEvent #-}
2474− subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2475−
2476−instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2477− type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2478− fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2479− runHostFrame = runFrame . runSpiderHostFrame
2480−
2481−unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2482−unsafeNewSpiderTimelineEnv = do
2483− lock <- newMVar ()
2484− env <- newEventEnv
2485−#ifdef DEBUG
2486− depthRef <- newIORef 0
2487−#endif
2488− return $ SpiderTimelineEnv
2489− { _spiderTimeline_lock = lock
2490− , _spiderTimeline_eventEnv = env
2491−#ifdef DEBUG
2492− , _spiderTimeline_depth = depthRef
2493−#endif
2494− }
2495−
2496−-- | Create a new SpiderTimelineEnv
2497−newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2498−newSpiderTimeline = withSpiderTimeline (pure . Some)
2499−
2500−data LocalSpiderTimeline (x :: Type) s
2501−
2502−instance Reifies s (SpiderTimelineEnv x) =>
2503− HasSpiderTimeline (LocalSpiderTimeline x s) where
2504− spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2505−
2506−localSpiderTimeline
2507− :: Proxy s
2508− -> SpiderTimelineEnv x
2509− -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2510−localSpiderTimeline _ = unsafeCoerce
2511−
2512−-- | Pass a new timeline to the given function.
2513−withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2514−withSpiderTimeline k = do
2515− env <- unsafeNewSpiderTimelineEnv
2516− reify env $ \s -> k $ localSpiderTimeline s env
2517−
2518−newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2519−
2520−type ComputeM = EventM
2521−
2522−newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2523−
2524−instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2525− {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2526− newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2527− newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2528− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2529− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2530− type PullM (SpiderTimeline x) = SpiderPullM x
2531− type PushM (SpiderTimeline x) = SpiderPushM x
2532− {-# INLINABLE never #-}
2533− never = SpiderEvent eventNever
2534− {-# INLINABLE constant #-}
2535− constant = SpiderBehavior . behaviorConst
2536− {-# INLINE push #-}
2537− push f = SpiderEvent . push (coerce f) . unSpiderEvent
2538− {-# INLINE pushCheap #-}
2539− pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2540− {-# INLINABLE pull #-}
2541− pull = SpiderBehavior . pull . coerce
2542− {-# INLINABLE fanG #-}
2543− fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2544− {-# INLINABLE mergeG #-}
2545− mergeG
2546− :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2547− => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2548− -> DMap k q
2549− -> R.Event (SpiderTimeline x) (DMap k v)
2550− mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2551− {-# INLINABLE switch #-}
2552− switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2553− {-# INLINABLE coincidence #-}
2554− coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2555− {-# INLINABLE current #-}
2556− current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2557− {-# INLINABLE updated #-}
2558− updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2559− {-# INLINABLE unsafeBuildDynamic #-}
2560− unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2561− {-# INLINABLE unsafeBuildIncremental #-}
2562− unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2563− {-# INLINABLE mergeIncrementalG #-}
2564− mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2565− {-# INLINABLE mergeIncrementalWithMoveG #-}
2566− mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2567− {-# INLINABLE currentIncremental #-}
2568− currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2569− {-# INLINABLE updatedIncremental #-}
2570− updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2571− {-# INLINABLE incrementalToDynamic #-}
2572− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2573− c <- readBehaviorUntracked $ dynamicCurrent i
2574− return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2575− eventCoercion Coercion = Coercion
2576− behaviorCoercion Coercion = Coercion
2577− dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2578− {-# INLINABLE mergeIntIncremental #-}
2579− mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2580− {-# INLINABLE fanInt #-}
2581− fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2582−
2583−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2584−
2585−data SpiderEventHandle x a = SpiderEventHandle
2586− { spiderEventHandleSubscription :: EventSubscription x
2587− , spiderEventHandleValue :: IORef (Maybe a)
2588− }
2589−
2590−instance MonadRef (EventM x) where
2591− type Ref (EventM x) = Ref IO
2592− {-# INLINABLE newRef #-}
2593− {-# INLINABLE readRef #-}
2594− {-# INLINABLE writeRef #-}
2595− newRef = liftIO . newRef
2596− readRef = liftIO . readRef
2597− writeRef r a = liftIO $ writeRef r a
2598−
2599−instance MonadAtomicRef (EventM x) where
2600− {-# INLINABLE atomicModifyRef #-}
2601− atomicModifyRef r f = liftIO $ atomicModifyRef r f
2602−
2603−-- | The monad for actions that manipulate a Spider timeline identified by @x@
2604−newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2605−
2606−instance Monad (SpiderHost x) where
2607− {-# INLINABLE (>>=) #-}
2608− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2609− {-# INLINABLE (>>) #-}
2610− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2611− {-# INLINABLE return #-}
2612− return x = SpiderHost $ return x
2613− {-# INLINABLE fail #-}
2614− fail s = SpiderHost $ fail s
2615−
2616−-- | Run an action affecting the global Spider timeline; this will be guarded by
2617−-- a mutex for that timeline
2618−runSpiderHost :: SpiderHost Global a -> IO a
2619−runSpiderHost (SpiderHost a) = a
2620−
2621−-- | Run an action affecting a given Spider timeline; this will be guarded by a
2622−-- mutex for that timeline
2623−runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2624−runSpiderHostForTimeline (SpiderHost a) _ = a
2625−
2626−newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2627− deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2628−
2629−instance Monad (SpiderHostFrame x) where
2630− {-# INLINABLE (>>=) #-}
2631− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2632− {-# INLINABLE (>>) #-}
2633− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2634− {-# INLINABLE return #-}
2635− return x = SpiderHostFrame $ return x
2636− {-# INLINABLE fail #-}
2637− fail s = SpiderHostFrame $ fail s
2638−
2639−instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2640− notReadyUntil _ = pure ()
2641− notReady = pure ()
2642−
2643−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2644−newEventWithTriggerIO f = do
2645− es <- newFanEventWithTriggerIO $ \Refl -> f
2646− return $ select es Refl
2647−
2648−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2649−newFanEventWithTriggerIO f = do
2650− occRef <- newIORef DMap.empty
2651− subscribedRef <- newIORef DMap.empty
2652− let !r = Root
2653− { rootOccurrence = occRef
2654− , rootSubscribed = subscribedRef
2655− , rootInit = f
2656− }
2657− return $ EventSelector $ \k -> eventRoot k r
2658−
2659−newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2660−
2661−instance MonadRef (SpiderHost x) where
2662− type Ref (SpiderHost x) = Ref IO
2663− newRef = SpiderHost . newRef
2664− readRef = SpiderHost . readRef
2665− writeRef r = SpiderHost . writeRef r
2666−
2667−instance MonadAtomicRef (SpiderHost x) where
2668− atomicModifyRef r = SpiderHost . atomicModifyRef r
2669−
2670−instance MonadRef (SpiderHostFrame x) where
2671− type Ref (SpiderHostFrame x) = Ref IO
2672− newRef = SpiderHostFrame . newRef
2673− readRef = SpiderHostFrame . readRef
2674− writeRef r = SpiderHostFrame . writeRef r
2675−
2676−instance MonadAtomicRef (SpiderHostFrame x) where
2677− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2678−
2679−instance PrimMonad (SpiderHostFrame x) where
2680− type PrimState (SpiderHostFrame x) = PrimState IO
2681− primitive = SpiderHostFrame . EventM . primitive