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