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