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