@@ -0,0 +1,2188 @@
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+#ifdef EXPERIMENTAL_DEPENDENT_SUM_INSTANCES
734+ geqToEq _ = id
735+ geqUnify (a :: SpiderTimelineEnv a) (b :: SpiderTimelineEnv b) different same = if _spiderTimeline_lock a == _spiderTimeline_lock b
736+ then case unsafeCoerce Refl :: a :~: b of
737+ Refl -> same -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
738+ else different
739+#else
740+ a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
741+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
742+ else Nothing
743+#endif
744+
745+data EventEnv x
746+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
747+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
748+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
749+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
750+ , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
751+ , eventEnvRootClears :: !(IORef [SomeRootClear])
752+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
753+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
754+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
755+ }
756+
757+{-# INLINE runEventM #-}
758+runEventM :: EventM x a -> IO a
759+runEventM = unEventM
760+
761+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
762+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
763+
764+class MonadIO m => Defer a m where
765+ getDeferralQueue :: m (IORef [a])
766+
767+{-# INLINE defer #-}
768+defer :: Defer a m => a -> m ()
769+defer a = do
770+ q <- getDeferralQueue
771+ liftIO $ modifyIORef' q (a:)
772+
773+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
774+ {-# INLINE getDeferralQueue #-}
775+ getDeferralQueue = asksEventEnv eventEnvAssignments
776+
777+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
778+ {-# INLINE getDeferralQueue #-}
779+ getDeferralQueue = asksEventEnv eventEnvHoldInits
780+
781+instance Defer (SomeHoldInit x) (BehaviorM x) where
782+ {-# INLINE getDeferralQueue #-}
783+ getDeferralQueue = BehaviorM $ asks snd
784+
785+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
786+ {-# INLINE getDeferralQueue #-}
787+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
788+
789+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
790+ {-# INLINE getDeferralQueue #-}
791+ getDeferralQueue = asksEventEnv eventEnvMergeInits
792+
793+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
794+ getCurrentHeight :: m Height
795+ scheduleMerge :: Height -> EventM x () -> m ()
796+
797+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
798+ {-# INLINE getCurrentHeight #-}
799+ getCurrentHeight = do
800+ heightRef <- asksEventEnv eventEnvCurrentHeight
801+ liftIO $ readIORef heightRef
802+ {-# INLINE scheduleMerge #-}
803+ scheduleMerge height subscribed = do
804+ delayedRef <- asksEventEnv eventEnvDelayedMerges
805+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
806+
807+#ifdef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
808+class x ~ Global => HasSpiderTimeline x where
809+#else
810+class HasSpiderTimeline x where
811+#endif
812+ -- | Retrieve the current SpiderTimelineEnv
813+ spiderTimeline :: SpiderTimelineEnv x
814+
815+instance HasSpiderTimeline Global where
816+ spiderTimeline = globalSpiderTimelineEnv
817+
818+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
819+putCurrentHeight h = do
820+ heightRef <- asksEventEnv eventEnvCurrentHeight
821+ liftIO $ writeIORef heightRef $! h
822+
823+instance HasSpiderTimeline x => Defer SomeClear (EventM x) where
824+ {-# INLINE getDeferralQueue #-}
825+ getDeferralQueue = asksEventEnv eventEnvClears
826+
827+{-# INLINE scheduleClear #-}
828+scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
829+scheduleClear r = defer $ SomeClear r
830+
831+instance HasSpiderTimeline x => Defer SomeRootClear (EventM x) where
832+ {-# INLINE getDeferralQueue #-}
833+ getDeferralQueue = asksEventEnv eventEnvRootClears
834+
835+{-# INLINE scheduleRootClear #-}
836+scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
837+scheduleRootClear r = defer $ SomeRootClear r
838+
839+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
840+ {-# INLINE getDeferralQueue #-}
841+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
842+
843+-- Note: hold cannot examine its event until after the phase is over
844+{-# INLINE [1] hold #-}
845+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
846+hold v0 e = do
847+ valRef <- liftIO $ newIORef v0
848+ invsRef <- liftIO $ newIORef []
849+ parentRef <- liftIO $ newIORef Nothing
850+#ifdef DEBUG_NODEIDS
851+ nodeId <- liftIO newNodeId
852+#endif
853+ let h = Hold
854+ { holdValue = valRef
855+ , holdInvalidators = invsRef
856+ , holdEvent = e
857+ , holdParent = parentRef
858+#ifdef DEBUG_NODEIDS
859+ , holdNodeId = nodeId
860+#endif
861+ }
862+ defer $ SomeHoldInit h
863+ return h
864+
865+{-# INLINE getHoldEventSubscription #-}
866+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)
867+getHoldEventSubscription h = do
868+ ep <- liftIO $ readIORef $ holdParent h
869+ case ep of
870+ Just subd -> return subd
871+ Nothing -> do
872+ let e = holdEvent h
873+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
874+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
875+ liftIO $ writeIORef subscriptionRef $! subscription
876+ case occ of
877+ Nothing -> return ()
878+ Just o -> do
879+ old <- liftIO $ readIORef $ holdValue h
880+ case apply o old of
881+ Nothing -> return ()
882+ Just new -> do
883+ -- Need to evaluate these so that we don't retain the Hold itself
884+ v <- liftIO $ evaluate $ holdValue h
885+ i <- liftIO $ evaluate $ holdInvalidators h
886+ defer $ SomeAssignment v i new
887+ liftIO $ writeIORef (holdParent h) $ Just subscription
888+ return subscription
889+
890+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
891+
892+--type role BehaviorM representational
893+-- BehaviorM can sample behaviors
894+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
895+
896+instance Monad (BehaviorM x) where
897+ {-# INLINE (>>=) #-}
898+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
899+ {-# INLINE (>>) #-}
900+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
901+ {-# INLINE return #-}
902+ return x = BehaviorM $ return x
903+ {-# INLINE fail #-}
904+ fail s = BehaviorM $ fail s
905+
906+data BehaviorSubscribed x a
907+ = forall p. BehaviorSubscribedHold (Hold x p)
908+ | BehaviorSubscribedPull (PullSubscribed x a)
909+
910+data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
911+
912+--type role PullSubscribed representational
913+data PullSubscribed x a
914+ = PullSubscribed { pullSubscribedValue :: !a
915+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
916+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
917+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
918+ }
919+
920+--type role Pull representational
921+data Pull x a
922+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
923+ , pullCompute :: !(BehaviorM x a)
924+#ifdef DEBUG_NODEIDS
925+ , pullNodeId :: Int
926+#endif
927+ }
928+
929+data Invalidator x
930+ = forall a. InvalidatorPull (Pull x a)
931+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
932+
933+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
934+ { rootSubscribedKey :: !(k a)
935+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
936+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
937+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
938+ , rootSubscribedUninit :: IO ()
939+ , 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?
940+#ifdef DEBUG_NODEIDS
941+ , rootSubscribedNodeId :: Int
942+#endif
943+ }
944+
945+data Root x (k :: * -> *)
946+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
947+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
948+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
949+ }
950+
951+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
952+
953+data SomeMergeUpdate x = SomeMergeUpdate
954+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
955+ , _someMergeUpdate_invalidateHeight :: !(IO ())
956+ , _someMergeUpdate_recalculateHeight :: !(IO ())
957+ }
958+
959+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
960+
961+-- EventM can do everything BehaviorM can, plus create holds
962+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
963+
964+newtype ComputeM x a = ComputeM (ReaderT (IORef [SomeHoldInit x]) IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
965+
966+instance Defer (SomeHoldInit x) (ComputeM x) where
967+ getDeferralQueue = ComputeM ask
968+
969+{-# INLINABLE runComputeM #-}
970+runComputeM :: Defer (SomeHoldInit x) m => ComputeM x a -> m a
971+runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
972+
973+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
974+
975+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
976+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
977+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
978+ }
979+
980+data HeightBag = HeightBag
981+ { _heightBag_size :: {-# UNPACK #-} !Int
982+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
983+ }
984+ deriving (Show, Read, Eq, Ord)
985+
986+heightBagEmpty :: HeightBag
987+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
988+
989+heightBagSize :: HeightBag -> Int
990+heightBagSize = _heightBag_size
991+
992+heightBagFromList :: [Height] -> HeightBag
993+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
994+
995+heightBagAdd :: Height -> HeightBag -> HeightBag
996+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
997+
998+heightBagRemove :: Height -> HeightBag -> HeightBag
999+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1000+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1001+ Just old -> HeightBag (pred s) $ case old of
1002+ 0 -> IntMap.delete h c
1003+ _ -> IntMap.insert h (pred old) c
1004+
1005+heightBagMax :: HeightBag -> Height
1006+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1007+ Just ((h, _), _) -> Height h
1008+ Nothing -> zeroHeight
1009+
1010+heightBagVerify :: HeightBag -> HeightBag
1011+#ifdef DEBUG
1012+heightBagVerify b@(HeightBag s c) = if
1013+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1014+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1015+ | unHeight invalidHeight `IntMap.member` c
1016+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1017+ | otherwise -> b
1018+#else
1019+heightBagVerify = id
1020+#endif
1021+
1022+data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1023+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1024+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1025+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1026+ }
1027+
1028+data FanSubscribed (x :: *) k
1029+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1030+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1031+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1032+ , fanSubscribedParent :: !(EventSubscription x)
1033+#ifdef DEBUG_NODEIDS
1034+ , fanSubscribedNodeId :: Int
1035+#endif
1036+ }
1037+
1038+data Fan x k
1039+ = Fan { fanParent :: !(Event x (DMap k Identity))
1040+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1041+ }
1042+
1043+data SwitchSubscribed x a
1044+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1045+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1046+ , switchSubscribedHeight :: !(IORef Height)
1047+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1048+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1049+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1050+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1051+ , switchSubscribedParent :: !(Behavior x (Event x a))
1052+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1053+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1054+#ifdef DEBUG_NODEIDS
1055+ , switchSubscribedNodeId :: Int
1056+#endif
1057+ }
1058+
1059+data Switch x a
1060+ = Switch { switchParent :: !(Behavior x (Event x a))
1061+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1062+ }
1063+
1064+#ifdef USE_TEMPLATE_HASKELL
1065+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1066+#endif
1067+data CoincidenceSubscribed x a
1068+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1069+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1070+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1071+ , coincidenceSubscribedHeight :: !(IORef Height)
1072+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1073+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1074+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1075+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1076+#ifdef DEBUG_NODEIDS
1077+ , coincidenceSubscribedNodeId :: Int
1078+#endif
1079+ }
1080+
1081+data Coincidence x a
1082+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1083+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1084+ }
1085+
1086+{-# NOINLINE newInvalidatorSwitch #-}
1087+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1088+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1089+
1090+{-# NOINLINE newInvalidatorPull #-}
1091+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1092+newInvalidatorPull p = return $! InvalidatorPull p
1093+
1094+instance HasSpiderTimeline x => FunctorMaybe (Event x) where
1095+ fmapMaybe f = push $ return . f
1096+
1097+instance HasSpiderTimeline x => Align (Event x) where
1098+ nil = eventNever
1099+ align ea eb = fmapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1100+
1101+newtype Dyn x p = Dyn { unDyn :: IORef (Either (BehaviorM x (PatchTarget p), Event x p) (Hold x p)) }
1102+
1103+newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1104+newMapDyn f d = dynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1105+
1106+--TODO: Avoid the duplication between this and R.zipDynWith
1107+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1108+zipDynWith f da db =
1109+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1110+ ec = flip push eab $ \o -> do
1111+ (a, b) <- case o of
1112+ This (Identity a) -> do
1113+ b <- readBehaviorUntracked $ dynamicCurrent db
1114+ return (a, b)
1115+ That (Identity b) -> do
1116+ a <- readBehaviorUntracked $ dynamicCurrent da
1117+ return (a, b)
1118+ These (Identity a) (Identity b) -> return (a, b)
1119+ return $ Just $ Identity $ f a b
1120+ in dynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1121+
1122+unsafeDyn :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1123+unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1124+ where x = (readV0, v')
1125+
1126+-- ResultM can read behaviors and events
1127+type ResultM = EventM
1128+
1129+{-# NOINLINE unsafeNewIORef #-}
1130+unsafeNewIORef :: a -> b -> IORef b
1131+unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1132+
1133+instance HasSpiderTimeline x => Functor (Event x) where
1134+ fmap f = push $ return . Just . f
1135+
1136+instance Functor (Behavior x) where
1137+ fmap f = pull . fmap f . readBehaviorTracked
1138+
1139+{-# INLINE push #-}
1140+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1141+push f e = cacheEvent (pushCheap f e)
1142+
1143+{-# INLINABLE pull #-}
1144+pull :: BehaviorM x a -> Behavior x a
1145+pull a = behaviorPull $ Pull
1146+ { pullCompute = a
1147+ , pullValue = unsafeNewIORef a Nothing
1148+#ifdef DEBUG_NODEIDS
1149+ , pullNodeId = unsafeNodeId a
1150+#endif
1151+ }
1152+
1153+{-# INLINABLE switch #-}
1154+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1155+switch a = eventSwitch $ Switch
1156+ { switchParent = a
1157+ , switchSubscribed = unsafeNewIORef a Nothing
1158+ }
1159+
1160+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1161+coincidence a = eventCoincidence $ Coincidence
1162+ { coincidenceParent = a
1163+ , coincidenceSubscribed = unsafeNewIORef a Nothing
1164+ }
1165+
1166+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1167+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1168+run roots after = do
1169+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1170+ t <- SpiderHost ask
1171+ result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock t) $ \_ -> flip runReaderT t $ unSpiderHost $ runFrame $ do
1172+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1173+ occBefore <- liftIO $ do
1174+ occBefore <- readIORef occRef
1175+ writeIORef occRef $! DMap.insert k a occBefore
1176+ return occBefore
1177+ if DMap.null occBefore
1178+ then do scheduleRootClear occRef
1179+ return $ Just r
1180+ else return Nothing
1181+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1182+ propagate a subscribersRef
1183+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1184+ let go = do
1185+ delayed <- liftIO $ readIORef delayedRef
1186+ case IntMap.minViewWithKey delayed of
1187+ Nothing -> return ()
1188+ Just ((currentHeight, cur), future) -> do
1189+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1190+ putCurrentHeight $ Height currentHeight
1191+ liftIO $ writeIORef delayedRef $! future
1192+ sequence_ cur
1193+ go
1194+ go
1195+ putCurrentHeight maxBound
1196+ after
1197+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1198+ return result
1199+
1200+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1201+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1202+ height <- liftIO $ readIORef heightRef
1203+ currentHeight <- getCurrentHeight
1204+ case height `compare` currentHeight of
1205+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1206+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1207+ EQ -> a
1208+
1209+data SomeClear = forall a. SomeClear (IORef (Maybe a))
1210+
1211+data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
1212+
1213+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1214+
1215+debugFinalize :: Bool
1216+debugFinalize = False
1217+
1218+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1219+mkWeakPtrWithDebug x debugNote = do
1220+ x' <- evaluate x
1221+ mkWeakPtr x' $
1222+ if debugFinalize
1223+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1224+ else Nothing
1225+
1226+type WeakList a = [Weak a]
1227+
1228+{-# INLINE withIncreasedDepth #-}
1229+#ifdef DEBUG
1230+withIncreasedDepth :: CanTrace x m => m a -> m a
1231+withIncreasedDepth a = do
1232+ spiderTimeline <- askSpiderTimelineEnv
1233+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1234+ result <- a
1235+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1236+ return result
1237+#else
1238+withIncreasedDepth :: m a -> m a
1239+withIncreasedDepth = id
1240+#endif
1241+
1242+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1243+
1244+{-# INLINE tracePropagate #-}
1245+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1246+tracePropagate p = traceWhen p debugPropagate
1247+
1248+{-# INLINE traceInvalidate #-}
1249+traceInvalidate :: String -> IO ()
1250+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1251+
1252+{-# INLINE traceWhen #-}
1253+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1254+traceWhen p b message = traceMWhen p b $ return message
1255+
1256+{-# INLINE traceMWhen #-}
1257+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1258+traceMWhen _ b getMessage = when b $ do
1259+ message <- getMessage
1260+#ifdef DEBUG
1261+ spiderTimeline <- askSpiderTimelineEnv
1262+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1263+#else
1264+ let d = 0
1265+#endif
1266+ liftIO $ putStrLn $ replicate d ' ' <> message
1267+
1268+whoCreatedIORef :: IORef a -> IO [String]
1269+whoCreatedIORef (IORef a) = whoCreated $! a
1270+
1271+#ifdef DEBUG_CYCLES
1272+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1273+groupByHead = \case
1274+ [] -> []
1275+ (x :| xs) : t -> case groupByHead t of
1276+ [] -> [(x, xs :| [])]
1277+ l@((y, yss) : t')
1278+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1279+ | otherwise -> (x, xs :| []) : l
1280+
1281+listsToForest :: Eq a => [[a]] -> Forest a
1282+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1283+#endif
1284+
1285+{-# INLINE propagateSubscriberHold #-}
1286+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1287+propagateSubscriberHold h a = do
1288+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1289+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1290+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1291+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1292+ case {-# SCC "apply" #-} apply a v of
1293+ Nothing -> return ()
1294+ Just v' -> do
1295+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1296+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1297+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1298+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1299+
1300+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1301+
1302+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1303+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1304+
1305+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1306+askInvalidator = do
1307+ (!m, _) <- BehaviorM ask
1308+ case m of
1309+ Nothing -> return Nothing
1310+ Just (!wi, _) -> return $ Just wi
1311+
1312+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1313+askParentsRef = do
1314+ (!m, _) <- BehaviorM ask
1315+ case m of
1316+ Nothing -> return Nothing
1317+ Just (_, !p) -> return $ Just p
1318+
1319+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1320+askBehaviorHoldInits = do
1321+ (_, !his) <- BehaviorM ask
1322+ return his
1323+
1324+{-# INLINE getDynHold #-}
1325+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1326+getDynHold d = do
1327+ mh <- liftIO $ readIORef $ unDyn d
1328+ case mh of
1329+ Right h -> return h
1330+ Left (readV0, v') -> do
1331+ holdInits <- getDeferralQueue
1332+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1333+ h <- hold v0 v'
1334+ liftIO $ writeIORef (unDyn d) $ Right h
1335+ return h
1336+
1337+-- Always refers to 0
1338+{-# NOINLINE zeroRef #-}
1339+zeroRef :: IORef Height
1340+zeroRef = unsafePerformIO $ newIORef zeroHeight
1341+
1342+type CanSubscribe x m =
1343+ ( HasSpiderTimeline x
1344+ , HasCurrentHeight x m
1345+ , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1346+ , Defer SomeClear m -- Wiping out event firings
1347+ , Defer (SomeAssignment x) m -- Updating state
1348+ , Defer (SomeResetCoincidence x) m
1349+ , m ~ EventM x
1350+ )
1351+
1352+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1353+getRootSubscribed k r sub = do
1354+ mSubscribed <- readIORef $ rootSubscribed r
1355+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1356+ case DMap.lookup k mSubscribed of
1357+ Just subscribed -> {-# SCC "hitRoot" #-} do
1358+ sln <- subscribeRootSubscribed subscribed sub
1359+ occ <- getOcc
1360+ return (sln, subscribed, occ)
1361+ Nothing -> {-# SCC "missRoot" #-} do
1362+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1363+ let !cached = rootSubscribed r
1364+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1365+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1366+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1367+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1368+ writeIORef uninitRef $! uninit
1369+ let !subscribed = RootSubscribed
1370+ { rootSubscribedKey = k
1371+ , rootSubscribedCachedSubscribed = cached
1372+ , rootSubscribedOccurrence = getOcc
1373+ , rootSubscribedSubscribers = subs
1374+ , rootSubscribedUninit = uninit
1375+ , rootSubscribedWeakSelf = weakSelf
1376+#ifdef DEBUG_NODEIDS
1377+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1378+#endif
1379+ }
1380+ -- If we die at the same moment that all our children die, they will
1381+ -- try to clean us up but will fail because their Weak reference to us
1382+ -- will also be dead. So, if we are dying, check if there are any
1383+ -- children; since children don't bother cleaning themselves up if
1384+ -- their parents are already dead, I don't think there's a race
1385+ -- condition here. However, if there are any children, then we can
1386+ -- infer that we need to clean ourselves up, so we do.
1387+ finalCleanup = do
1388+ cs <- readIORef $ _weakBag_children subs
1389+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1390+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1391+ 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
1392+ occ <- getOcc
1393+ return (sln, subscribed, occ)
1394+
1395+#ifdef USE_TEMPLATE_HASKELL
1396+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1397+#endif
1398+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1399+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1400+ rootSubscribedUninit self
1401+ modifyIORef' cached $ DMap.delete k
1402+
1403+{-# INLINE subscribeRootSubscribed #-}
1404+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1405+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1406+
1407+{-# INLINABLE getFanSubscribed #-}
1408+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)
1409+getFanSubscribed k f sub = do
1410+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1411+ case mSubscribed of
1412+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1413+ sln <- subscribeFanSubscribed k subscribed sub
1414+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1415+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1416+ Nothing -> {-# SCC "missFan" #-} do
1417+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1418+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1419+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1420+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1421+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1422+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1423+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1424+ occRef <- liftIO $ newIORef parentOcc
1425+ when (isJust parentOcc) $ scheduleClear occRef
1426+ let subscribed = FanSubscribed
1427+ { fanSubscribedCachedSubscribed = fanSubscribed f
1428+ , fanSubscribedOccurrence = occRef
1429+ , fanSubscribedParent = subscription
1430+ , fanSubscribedSubscribers = subscribersRef
1431+#ifdef DEBUG_NODEIDS
1432+ , fanSubscribedNodeId = unsafeNodeId f
1433+#endif
1434+ }
1435+ let !self = (k, subscribed)
1436+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1437+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1438+ liftIO $ writeIORef subscribedRef $! subscribed
1439+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1440+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1441+
1442+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1443+cleanupFanSubscribed (k, subscribed) = do
1444+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1445+ let reducedSubscribers = DMap.delete k subscribers
1446+ if DMap.null reducedSubscribers
1447+ then do
1448+ unsubscribe $ fanSubscribedParent subscribed
1449+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1450+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1451+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1452+
1453+{-# INLINE subscribeFanSubscribed #-}
1454+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1455+subscribeFanSubscribed k subscribed sub = do
1456+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1457+ case DMap.lookup k subscribers of
1458+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1459+ let !self = (k, subscribed)
1460+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1461+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1462+ 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
1463+ return sln
1464+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1465+
1466+{-# INLINABLE getSwitchSubscribed #-}
1467+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)
1468+getSwitchSubscribed s sub = do
1469+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1470+ case mSubscribed of
1471+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1472+ sln <- subscribeSwitchSubscribed subscribed sub
1473+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1474+ return (sln, subscribed, occ)
1475+ Nothing -> {-# SCC "missSwitch" #-} do
1476+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1477+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1478+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1479+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1480+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1481+ wiRef <- liftIO $ newIORef wi
1482+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1483+ holdInits <- getDeferralQueue
1484+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1485+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1486+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1487+ subscriptionRef <- liftIO $ newIORef subscription
1488+ occRef <- liftIO $ newIORef parentOcc
1489+ when (isJust parentOcc) $ scheduleClear occRef
1490+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1491+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1492+ let !subscribed = SwitchSubscribed
1493+ { switchSubscribedCachedSubscribed = switchSubscribed s
1494+ , switchSubscribedOccurrence = occRef
1495+ , switchSubscribedHeight = heightRef
1496+ , switchSubscribedSubscribers = subs
1497+ , switchSubscribedOwnInvalidator = i
1498+ , switchSubscribedOwnWeakInvalidator = wiRef
1499+ , switchSubscribedBehaviorParents = parentsRef
1500+ , switchSubscribedParent = switchParent s
1501+ , switchSubscribedCurrentParent = subscriptionRef
1502+ , switchSubscribedWeakSelf = weakSelf
1503+#ifdef DEBUG_NODEIDS
1504+ , switchSubscribedNodeId = unsafeNodeId s
1505+#endif
1506+ }
1507+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1508+ liftIO $ writeIORef subscribedRef $! subscribed
1509+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1510+ return (slnForSub, subscribed, parentOcc)
1511+
1512+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1513+cleanupSwitchSubscribed subscribed = do
1514+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1515+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1516+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1517+
1518+{-# INLINE subscribeSwitchSubscribed #-}
1519+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1520+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1521+
1522+{-# INLINABLE getCoincidenceSubscribed #-}
1523+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)
1524+getCoincidenceSubscribed c sub = do
1525+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1526+ case mSubscribed of
1527+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1528+ sln <- subscribeCoincidenceSubscribed subscribed sub
1529+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1530+ return (sln, subscribed, occ)
1531+ Nothing -> {-# SCC "missCoincidence" #-} do
1532+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1533+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1534+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1535+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1536+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1537+ (occ, height, mInnerSubd) <- case outerOcc of
1538+ Nothing -> return (Nothing, outerHeight, Nothing)
1539+ Just o -> do
1540+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1541+ return (occ, height, Just innerSubd)
1542+ occRef <- liftIO $ newIORef occ
1543+ when (isJust occ) $ scheduleClear occRef
1544+ heightRef <- liftIO $ newIORef height
1545+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1546+ scheduleClear innerSubdRef
1547+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1548+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1549+ let subscribed = CoincidenceSubscribed
1550+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1551+ , coincidenceSubscribedOccurrence = occRef
1552+ , coincidenceSubscribedHeight = heightRef
1553+ , coincidenceSubscribedSubscribers = subs
1554+ , coincidenceSubscribedOuter = subOuter
1555+ , coincidenceSubscribedOuterParent = outerSubscription
1556+ , coincidenceSubscribedInnerParent = innerSubdRef
1557+ , coincidenceSubscribedWeakSelf = weakSelf
1558+#ifdef DEBUG_NODEIDS
1559+ , coincidenceSubscribedNodeId = unsafeNodeId c
1560+#endif
1561+ }
1562+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1563+ liftIO $ writeIORef subscribedRef $! subscribed
1564+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1565+ return (slnForSub, subscribed, occ)
1566+
1567+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1568+cleanupCoincidenceSubscribed subscribed = do
1569+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1570+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1571+
1572+{-# INLINE subscribeCoincidenceSubscribed #-}
1573+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1574+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1575+
1576+{-# INLINE merge #-}
1577+merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1578+merge d = cacheEvent (mergeCheap d)
1579+
1580+{-# INLINE mergeWithMove #-}
1581+mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1582+mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1583+
1584+{-# INLINE [1] mergeCheap #-}
1585+mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1586+mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy DMap.size
1587+ where
1588+ updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1589+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1590+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1591+ (mOldSubd, newPs) <- case me of
1592+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1593+ Just e -> do
1594+ let s = subscriber $ return k
1595+ subscription@(EventSubscription _ subd) <- subscribe e s
1596+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1597+ let newParent = MergeSubscribedParent subscription
1598+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1599+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1600+ forM_ mOldSubd $ \oldSubd -> do
1601+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1602+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1603+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1604+ foldM f ([], oldParents) $ DMap.toList p
1605+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1606+ getInitialSubscribers initialParents subscriber = do
1607+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1608+ let s = subscriber $ return k
1609+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1610+ height <- liftIO $ getEventSubscribedHeight parentSubd
1611+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1612+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1613+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1614+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1615+ )
1616+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1617+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1618+
1619+{-# INLINE [1] mergeCheapWithMove #-}
1620+mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1621+mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy DMap.size
1622+ where
1623+ updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1624+ updateMe subscriber heightBagRef oldParents p = do
1625+ -- Prepare new parents for insertion
1626+ let subscribeParent :: forall a. k a -> Event x a -> EventM x (MergeSubscribedParentWithMove x k a)
1627+ subscribeParent k e = do
1628+ keyRef <- liftIO $ newIORef k
1629+ let s = subscriber $ liftIO $ readIORef keyRef
1630+ subscription@(EventSubscription _ subd) <- subscribe e s
1631+ liftIO $ do
1632+ newParentHeight <- getEventSubscribedHeight subd
1633+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1634+ return $ MergeSubscribedParentWithMove subscription keyRef
1635+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1636+ -- Collect old parents for deletion and update the keys of moved parents
1637+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Event x) a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1638+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1639+ Nothing -> do
1640+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1641+ Just toKey -> do
1642+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1643+ return Nothing
1644+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1645+ return (toDelete, applyAlways p' oldParents)
1646+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1647+ getInitialSubscribers initialParents subscriber = do
1648+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1649+ keyRef <- liftIO $ newIORef k
1650+ let s = subscriber $ liftIO $ readIORef keyRef
1651+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1652+ height <- liftIO $ getEventSubscribedHeight parentSubd
1653+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1654+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1655+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1656+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1657+ )
1658+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1659+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1660+
1661+type MergeUpdateFunc k x p s
1662+ = (forall a. EventM x (k a) -> Subscriber x a)
1663+ -> IORef HeightBag
1664+ -> DMap k s
1665+ -> p
1666+ -> EventM x ([EventSubscription x], DMap k s)
1667+
1668+type MergeInitFunc k x s
1669+ = DMap k (Event x)
1670+ -> (forall a. EventM x (k a) -> Subscriber x a)
1671+ -> EventM x (DMap k Identity, [Height], DMap k s)
1672+
1673+type MergeDestroyFunc k s
1674+ = DMap k s
1675+ -> IO ()
1676+
1677+{-# INLINE mergeCheap' #-}
1678+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)
1679+mergeCheap' getInitialSubscribers updateFunc destroy numParents d = Event $ \sub -> do
1680+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1681+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1682+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1683+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1684+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1685+ let scheduleSelf height = scheduleMerge' height heightRef $ do
1686+ m <- liftIO $ readIORef accumRef
1687+ liftIO $ writeIORef accumRef $! DMap.empty
1688+ --TODO: Assert that m is not empty
1689+ subscriberPropagate sub m
1690+ invalidateMyHeight = do
1691+ oldHeight <- readIORef heightRef
1692+ 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
1693+ writeIORef heightRef $! invalidHeight
1694+ subscriberInvalidateHeight sub oldHeight
1695+ revalidateMyHeight = do
1696+ currentHeight <- readIORef heightRef
1697+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1698+ heights <- readIORef heightBagRef
1699+ parents <- readIORef parentsRef
1700+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1701+ case heightBagSize heights `compare` numParents parents of
1702+ LT -> return ()
1703+ EQ -> do
1704+ let height = succHeight $ heightBagMax heights
1705+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1706+ writeIORef heightRef $! height
1707+ subscriberRecalculateHeight sub height
1708+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (numParents parents) <> ") for Merge"
1709+ subscriber :: forall a. EventM x (k a) -> Subscriber x a
1710+ subscriber getKey = Subscriber
1711+ { subscriberPropagate = \a -> do
1712+ oldM <- liftIO $ readIORef accumRef
1713+ k <- getKey
1714+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1715+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1716+ liftIO $ writeIORef accumRef $! newM
1717+ when (DMap.null oldM) $ do -- Only schedule the firing once
1718+ height <- liftIO $ readIORef heightRef
1719+ --TODO: assertions about height
1720+ currentHeight <- getCurrentHeight
1721+ when (height <= currentHeight) $ do
1722+ if height /= invalidHeight
1723+ then do
1724+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1725+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1726+ else liftIO $ do
1727+#ifdef DEBUG_CYCLES
1728+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1729+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1730+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1731+#else
1732+ let cycleInfo = ""
1733+#endif
1734+ error $ "Causality loop found" <> cycleInfo
1735+ scheduleSelf height
1736+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1737+ modifyIORef' heightBagRef $ heightBagRemove old
1738+ invalidateMyHeight
1739+ , subscriberRecalculateHeight = \new -> do
1740+ modifyIORef' heightBagRef $ heightBagAdd new
1741+ revalidateMyHeight
1742+ }
1743+ let updateMe x = do
1744+ oldParents <- liftIO $ readIORef parentsRef
1745+ (subscriptionsToKill, newParents) <- updateFunc subscriber heightBagRef oldParents x
1746+ liftIO $ writeIORef parentsRef $! newParents
1747+ return subscriptionsToKill
1748+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents subscriber
1749+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1750+ myHeight = if invalidHeight `elem` heights
1751+ then invalidHeight
1752+ else succHeight $ heightBagMax myHeightBag
1753+ currentHeight <- getCurrentHeight
1754+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1755+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1756+ else (Nothing, dm)
1757+ unless (DMap.null accum) $ do
1758+ scheduleSelf myHeight
1759+ occRef <- liftIO $ newIORef occ
1760+ when (isJust occ) $ scheduleClear occRef
1761+ liftIO $ writeIORef accumRef $! accum
1762+ liftIO $ writeIORef heightRef $! myHeight
1763+ liftIO $ writeIORef heightBagRef $! myHeightBag
1764+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1765+ liftIO $ writeIORef parentsRef $! initialParentState
1766+ defer $ SomeMergeInit $ do
1767+ let s = Subscriber
1768+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1769+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1770+ defer $ SomeMergeUpdate (updateMe a) invalidateMyHeight revalidateMyHeight
1771+ , subscriberInvalidateHeight = \_ -> return ()
1772+ , subscriberRecalculateHeight = \_ -> return ()
1773+ }
1774+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1775+ forM_ change $ \c -> defer $ SomeMergeUpdate (updateMe c) invalidateMyHeight revalidateMyHeight
1776+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1777+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1778+ -- its subscription.
1779+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1780+ let unsubscribeAll = destroy =<< readIORef parentsRef
1781+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1782+ , occ
1783+ )
1784+
1785+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1786+
1787+fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
1788+fan e =
1789+ let f = Fan
1790+ { fanParent = e
1791+ , fanSubscribed = unsafeNewIORef e Nothing
1792+ }
1793+ in EventSelector $ \k -> eventFan k f
1794+
1795+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1796+runHoldInits holdInitRef mergeInitRef = do
1797+ holdInits <- liftIO $ readIORef holdInitRef
1798+ mergeInits <- liftIO $ readIORef mergeInitRef
1799+ unless (null holdInits && null mergeInits) $ do
1800+ liftIO $ writeIORef holdInitRef []
1801+ liftIO $ writeIORef mergeInitRef []
1802+ mapM_ initHold holdInits
1803+ mapM_ unSomeMergeInit mergeInits
1804+ runHoldInits holdInitRef mergeInitRef
1805+
1806+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
1807+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1808+
1809+newEventEnv :: IO (EventEnv x)
1810+newEventEnv = do
1811+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1812+ holdInitRef <- newIORef []
1813+ mergeUpdateRef <- newIORef []
1814+ mergeInitRef <- newIORef []
1815+ heightRef <- newIORef zeroHeight
1816+ toClearRef <- newIORef []
1817+ toClearRootRef <- newIORef []
1818+ coincidenceInfosRef <- newIORef []
1819+ delayedRef <- newIORef IntMap.empty
1820+ return $ EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1821+
1822+clearEventEnv :: EventEnv x -> IO ()
1823+clearEventEnv (EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
1824+ writeIORef toAssignRef []
1825+ writeIORef holdInitRef []
1826+ writeIORef mergeUpdateRef []
1827+ writeIORef mergeInitRef []
1828+ writeIORef heightRef zeroHeight
1829+ writeIORef toClearRef []
1830+ writeIORef toClearRootRef []
1831+ writeIORef coincidenceInfosRef []
1832+ writeIORef delayedRef IntMap.empty
1833+
1834+-- | Run an event action outside of a frame
1835+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1836+runFrame a = SpiderHost $ ask >>= \_ -> lift $ do
1837+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
1838+ let go = do
1839+ result <- a
1840+ 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
1841+ return result
1842+ result <- runEventM go
1843+ toClear <- readIORef $ eventEnvClears env
1844+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1845+ toClearRoot <- readIORef $ eventEnvRootClears env
1846+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1847+ toAssign <- readIORef $ eventEnvAssignments env
1848+ toReconnectRef <- newIORef []
1849+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
1850+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1851+ writeIORef vRef v
1852+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
1853+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1854+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
1855+ writeIORef (eventEnvMergeUpdates env) []
1856+ when debugPropagate $ putStrLn "Updating merges"
1857+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
1858+ when debugPropagate $ putStrLn "Updating merges done"
1859+ toReconnect <- readIORef toReconnectRef
1860+ clearEventEnv env
1861+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1862+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1863+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1864+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1865+ finalize wi
1866+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1867+ wi' <- mkWeakPtrWithDebug i "wi'"
1868+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1869+ writeIORef (switchSubscribedBehaviorParents subscribed) []
1870+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
1871+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
1872+ 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
1873+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1874+ sub <- newSubscriberSwitch subscribed
1875+ 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
1876+ {-
1877+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1878+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1879+ EventRoot _ -> "EventRoot"
1880+ EventNever -> "EventNever"
1881+ _ -> "something else"
1882+ -}
1883+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1884+ return oldSubscription
1885+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
1886+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
1887+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1888+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1889+ parentHeight <- getEventSubscribedHeight subd'
1890+ myHeight <- readIORef $ switchSubscribedHeight subscribed
1891+ when (parentHeight /= myHeight) $ do
1892+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1893+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1894+ 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
1895+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1896+ unsubscribe subscription
1897+ mapM_ invalidateCoincidenceHeight mcs
1898+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1899+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
1900+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1901+ height <- calculateSwitchHeight subscribed
1902+ updateSwitchHeight height subscribed
1903+ return result
1904+
1905+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1906+
1907+{-# INLINE zeroHeight #-}
1908+zeroHeight :: Height
1909+zeroHeight = Height 0
1910+
1911+{-# INLINE invalidHeight #-}
1912+invalidHeight :: Height
1913+invalidHeight = Height (-1000)
1914+
1915+#ifdef DEBUG_CYCLES
1916+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1917+{-# INLINE invalidHeightBeingTraversed #-}
1918+invalidHeightBeingTraversed :: Height
1919+invalidHeightBeingTraversed = Height (-1001)
1920+#endif
1921+
1922+{-# INLINE succHeight #-}
1923+succHeight :: Height -> Height
1924+succHeight h@(Height a) =
1925+ if h == invalidHeight
1926+ then invalidHeight
1927+ else Height $ succ a
1928+
1929+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1930+invalidateCoincidenceHeight subscribed = do
1931+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1932+ when (oldHeight /= invalidHeight) $ do
1933+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1934+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1935+
1936+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1937+updateSwitchHeight new subscribed = do
1938+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1939+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1940+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1941+ writeIORef (switchSubscribedHeight subscribed) $! new
1942+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1943+
1944+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1945+recalculateCoincidenceHeight subscribed = do
1946+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1947+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1948+ height <- calculateCoincidenceHeight subscribed
1949+ when (height /= invalidHeight) $ do
1950+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
1951+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1952+
1953+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1954+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1955+
1956+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1957+calculateCoincidenceHeight subscribed = do
1958+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1959+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1960+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1961+
1962+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1963+
1964+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1965+invalidate toReconnectRef wis = do
1966+ forM_ wis $ \wi -> do
1967+ mi <- deRefWeak wi
1968+ case mi of
1969+ Nothing -> do
1970+ traceInvalidate "invalidate Dead"
1971+ return () --TODO: Should we clean this up here?
1972+ Just i -> do
1973+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1974+ case i of
1975+ InvalidatorPull p -> do
1976+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
1977+ mVal <- readIORef $ pullValue p
1978+ forM_ mVal $ \val -> do
1979+ writeIORef (pullValue p) Nothing
1980+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1981+ InvalidatorSwitch subscribed -> do
1982+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1983+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1984+ 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
1985+
1986+--------------------------------------------------------------------------------
1987+-- Reflex integration
1988+--------------------------------------------------------------------------------
1989+
1990+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1991+-- When we're specializing, we include this from Reflex.Class instead, because
1992+-- it needs access to these types; when we're not, we want them here, so our
1993+-- instance isn't an orphan instance.
1994+#include "SpiderTimeline.include.hs"
1995+#include "SpiderTimelineHost.include.hs"
1996+#endif
1997+
1998+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
1999+unsafeNewSpiderTimelineEnv = do
2000+ lock <- newMVar ()
2001+ env <- newEventEnv
2002+#ifdef DEBUG
2003+ depthRef <- newIORef 0
2004+#endif
2005+ return $ SpiderTimelineEnv
2006+ { _spiderTimeline_lock = lock
2007+ , _spiderTimeline_eventEnv = env
2008+#ifdef DEBUG
2009+ , _spiderTimeline_depth = depthRef
2010+#endif
2011+ }
2012+
2013+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2014+-- | Create a new SpiderTimelineEnv
2015+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2016+newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2017+
2018+data LocalSpiderTimeline x s
2019+
2020+instance Reifies s (SpiderTimelineEnv x) =>
2021+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2022+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2023+
2024+localSpiderTimeline
2025+ :: Proxy s
2026+ -> SpiderTimelineEnv x
2027+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2028+localSpiderTimeline _ = unsafeCoerce
2029+
2030+-- | Pass a new timeline to the given function.
2031+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2032+withSpiderTimeline k = do
2033+ env <- unsafeNewSpiderTimelineEnv
2034+ reify env $ \s -> k $ localSpiderTimeline s env
2035+#endif
2036+
2037+newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2038+
2039+newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2040+
2041+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2042+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2043+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2044+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2045+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2046+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2047+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2048+ type PullM (SpiderTimeline x) = SpiderPullM x
2049+ type PushM (SpiderTimeline x) = SpiderPushM x
2050+ {-# INLINABLE never #-}
2051+ never = SpiderEvent eventNever
2052+ {-# INLINABLE constant #-}
2053+ constant = SpiderBehavior . behaviorConst
2054+ {-# INLINE push #-}
2055+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2056+ {-# INLINE pushCheap #-}
2057+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2058+ {-# INLINABLE pull #-}
2059+ pull = SpiderBehavior . pull . coerce
2060+ {-# INLINABLE merge #-}
2061+ merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2062+ {-# INLINABLE fan #-}
2063+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2064+ {-# INLINABLE switch #-}
2065+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2066+ {-# INLINABLE coincidence #-}
2067+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2068+ {-# INLINABLE current #-}
2069+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2070+ {-# INLINABLE updated #-}
2071+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2072+ {-# INLINABLE unsafeBuildDynamic #-}
2073+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (coerce readV0) $ coerce $ unSpiderEvent v'
2074+ {-# INLINABLE unsafeBuildIncremental #-}
2075+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
2076+ {-# INLINABLE mergeIncremental #-}
2077+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2078+ {-# INLINABLE mergeIncrementalWithMove #-}
2079+ mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2080+ {-# INLINABLE currentIncremental #-}
2081+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2082+ {-# INLINABLE updatedIncremental #-}
2083+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2084+ {-# INLINABLE incrementalToDynamic #-}
2085+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2086+ c <- readBehaviorUntracked $ dynamicCurrent i
2087+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2088+ eventCoercion Coercion = Coercion
2089+ behaviorCoercion Coercion = Coercion
2090+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2091+#endif
2092+
2093+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2094+
2095+data SpiderEventHandle x a = SpiderEventHandle
2096+ { spiderEventHandleSubscription :: EventSubscription x
2097+ , spiderEventHandleValue :: IORef (Maybe a)
2098+ }
2099+
2100+instance MonadRef (EventM x) where
2101+ type Ref (EventM x) = Ref IO
2102+ {-# INLINABLE newRef #-}
2103+ {-# INLINABLE readRef #-}
2104+ {-# INLINABLE writeRef #-}
2105+ newRef = liftIO . newRef
2106+ readRef = liftIO . readRef
2107+ writeRef r a = liftIO $ writeRef r a
2108+
2109+instance MonadAtomicRef (EventM x) where
2110+ {-# INLINABLE atomicModifyRef #-}
2111+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2112+
2113+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2114+newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimelineEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2115+
2116+instance Monad (SpiderHost x) where
2117+ {-# INLINABLE (>>=) #-}
2118+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2119+ {-# INLINABLE (>>) #-}
2120+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2121+ {-# INLINABLE return #-}
2122+ return x = SpiderHost $ return x
2123+ {-# INLINABLE fail #-}
2124+ fail s = SpiderHost $ fail s
2125+
2126+-- | Run an action affecting the global Spider timeline; this will be guarded by
2127+-- a mutex for that timeline
2128+runSpiderHost :: SpiderHost Global a -> IO a
2129+runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimelineEnv
2130+
2131+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2132+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2133+-- mutex for that timeline
2134+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2135+runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2136+#endif
2137+
2138+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2139+
2140+instance Monad (SpiderHostFrame x) where
2141+ {-# INLINABLE (>>=) #-}
2142+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2143+ {-# INLINABLE (>>) #-}
2144+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2145+ {-# INLINABLE return #-}
2146+ return x = SpiderHostFrame $ return x
2147+ {-# INLINABLE fail #-}
2148+ fail s = SpiderHostFrame $ fail s
2149+
2150+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2151+newEventWithTriggerIO f = do
2152+ es <- newFanEventWithTriggerIO $ \Refl -> f
2153+ return $ select es Refl
2154+
2155+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2156+newFanEventWithTriggerIO f = do
2157+ occRef <- newIORef DMap.empty
2158+ subscribedRef <- newIORef DMap.empty
2159+ let !r = Root
2160+ { rootOccurrence = occRef
2161+ , rootSubscribed = subscribedRef
2162+ , rootInit = f
2163+ }
2164+ return $ EventSelector $ \k -> eventRoot k r
2165+
2166+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2167+
2168+instance MonadRef (SpiderHost x) where
2169+ type Ref (SpiderHost x) = Ref IO
2170+ newRef = SpiderHost . newRef
2171+ readRef = SpiderHost . readRef
2172+ writeRef r = SpiderHost . writeRef r
2173+
2174+instance MonadAtomicRef (SpiderHost x) where
2175+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2176+
2177+instance MonadRef (SpiderHostFrame x) where
2178+ type Ref (SpiderHostFrame x) = Ref IO
2179+ newRef = SpiderHostFrame . newRef
2180+ readRef = SpiderHostFrame . readRef
2181+ writeRef r = SpiderHostFrame . writeRef r
2182+
2183+instance MonadAtomicRef (SpiderHostFrame x) where
2184+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2185+
2186+instance PrimMonad (SpiderHostFrame x) where
2187+ type PrimState (SpiderHostFrame x) = PrimState IO
2188+ primitive = SpiderHostFrame . EventM . primitive