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