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