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