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