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