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