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