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