@@ -1,1346 +0,0 @@
1−{-# LANGUAGE CPP, ExistentialQuantification, GADTs, ScopedTypeVariables, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, RankNTypes, BangPatterns, UndecidableInstances, EmptyDataDecls, RecursiveDo, RoleAnnotations, LambdaCase #-}
2−module Reflex.Spider.Internal where
3−
4−import Prelude hiding (mapM, mapM_, any, sequence, concat)
5−
6−import qualified Reflex.Class as R
7−import qualified Reflex.Host.Class as R
8−
9−import Data.IORef
10−import System.Mem.Weak
11−import Data.Foldable
12−import Data.Traversable
13−import Control.Monad hiding (mapM, mapM_, forM_, forM, sequence)
14−import Control.Monad.Reader hiding (mapM, mapM_, forM_, forM, sequence)
15−import GHC.Exts
16−#if !MIN_VERSION_base(4,8,0)
17−import Control.Applicative
18−#endif
19−import Data.Dependent.Map (DMap, DSum (..))
20−import qualified Data.Dependent.Map as DMap
21−import Data.GADT.Compare
22−import Data.Functor.Misc
23−import Data.Maybe
24−import Data.IntMap (IntMap)
25−import qualified Data.IntMap as IntMap
26−import Control.Monad.Ref
27−import Data.Monoid ((<>))
28−
29−import System.IO.Unsafe
30−import Unsafe.Coerce
31−import Control.Monad.Primitive
32−
33−debugPropagate :: Bool
34−
35−debugInvalidateHeight :: Bool
36−
37−#ifdef DEBUG
38−
39−#define DEBUG_NODEIDS
40−
41−debugPropagate = True
42−
43−debugInvalidateHeight = True
44−
45−class HasNodeId a where
46− getNodeId :: a -> Int
47−
48−instance HasNodeId (Hold a) where
49− getNodeId = holdNodeId
50−
51−instance HasNodeId (PushSubscribed a b) where
52− getNodeId = pushSubscribedNodeId
53−
54−instance HasNodeId (SwitchSubscribed a) where
55− getNodeId = switchSubscribedNodeId
56−
57−instance HasNodeId (MergeSubscribed a) where
58− getNodeId = mergeSubscribedNodeId
59−
60−instance HasNodeId (FanSubscribed a) where
61− getNodeId = fanSubscribedNodeId
62−
63−instance HasNodeId (CoincidenceSubscribed a) where
64− getNodeId = coincidenceSubscribedNodeId
65−
66−instance HasNodeId (RootSubscribed a) where
67− getNodeId = rootSubscribedNodeId
68−
69−showNodeId :: HasNodeId a => a -> String
70−showNodeId = ("#"<>) . show . getNodeId
71−
72−#else
73−
74−debugPropagate = False
75−
76−debugInvalidateHeight = False
77−
78−showNodeId :: a -> String
79−showNodeId = const ""
80−
81−#endif
82−
83−#ifdef DEBUG_NODEIDS
84−{-# NOINLINE nextNodeIdRef #-}
85−nextNodeIdRef :: IORef Int
86−nextNodeIdRef = unsafePerformIO $ newIORef 1
87−
88−{-# NOINLINE unsafeNodeId #-}
89−unsafeNodeId :: a -> Int
90−unsafeNodeId a = unsafePerformIO $ do
91− touch a
92− atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
93−#endif
94−
95−--TODO: Figure out why certain things are not 'representational', then make them representational so we can use coerce
96−--type role Hold representational
97−data Hold a
98− = Hold { holdValue :: !(IORef a)
99− , holdInvalidators :: !(IORef [Weak Invalidator])
100− -- We need to use 'Any' for the next two things, because otherwise Hold inherits a nominal role for its 'a' parameter, and we want to be able to use 'coerce'
101− , holdSubscriber :: !(IORef Any) -- Keeps its subscription alive; for some reason, a regular (or strict) reference to the Subscriber itself wasn't working, so had to use an IORef
102− , holdParent :: !(IORef Any) -- Keeps its parent alive (will be undefined until the hold is initialized --TODO: Probably shouldn't be an IORef
103−#ifdef DEBUG_NODEIDS
104− , holdNodeId :: Int
105−#endif
106− }
107−
108−data EventEnv
109− = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment])
110− , eventEnvHoldInits :: !(IORef [SomeHoldInit])
111− , eventEnvClears :: !(IORef [SomeMaybeIORef])
112− , eventEnvCurrentHeight :: !(IORef Int)
113− , eventEnvCoincidenceInfos :: !(IORef [SomeCoincidenceInfo])
114− , eventEnvDelayedMerges :: !(IORef (IntMap [DelayedMerge]))
115− }
116−
117−runEventM :: EventM a -> EventEnv -> IO a
118−runEventM = runReaderT . unEventM
119−
120−askToAssignRef :: EventM (IORef [SomeAssignment])
121−askToAssignRef = EventM $ asks eventEnvAssignments
122−
123−askHoldInitRef :: EventM (IORef [SomeHoldInit])
124−askHoldInitRef = EventM $ asks eventEnvHoldInits
125−
126−getCurrentHeight :: EventM Int
127−getCurrentHeight = EventM $ do
128− heightRef <- asks eventEnvCurrentHeight
129− liftIO $ readIORef heightRef
130−
131−putCurrentHeight :: Int -> EventM ()
132−putCurrentHeight h = EventM $ do
133− heightRef <- asks eventEnvCurrentHeight
134− liftIO $ writeIORef heightRef h
135−
136−scheduleClear :: IORef (Maybe a) -> EventM ()
137−scheduleClear r = EventM $ do
138− clears <- asks eventEnvClears
139− liftIO $ modifyIORef' clears (SomeMaybeIORef r :)
140−
141−scheduleMerge :: Int -> MergeSubscribed a -> EventM ()
142−scheduleMerge height subscribed = EventM $ do
143− delayedRef <- asks eventEnvDelayedMerges
144− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) height [DelayedMerge subscribed]
145−
146−emitCoincidenceInfo :: SomeCoincidenceInfo -> EventM ()
147−emitCoincidenceInfo sci = EventM $ do
148− ciRef <- asks eventEnvCoincidenceInfos
149− liftIO $ modifyIORef' ciRef (sci:)
150−
151−-- Note: hold cannot examine its event until after the phase is over
152−hold :: a -> Event a -> EventM (Behavior a)
153−hold v0 e = do
154− holdInitRef <- askHoldInitRef
155− liftIO $ do
156− valRef <- newIORef v0
157− invsRef <- newIORef []
158− parentRef <- newIORef $ error "hold not yet initialized (parent)"
159− subscriberRef <- newIORef $ error "hold not yet initialized (subscriber)"
160− let h = Hold
161− { holdValue = valRef
162− , holdInvalidators = invsRef
163− , holdSubscriber = subscriberRef
164− , holdParent = parentRef
165−#ifdef DEBUG_NODEIDS
166− , holdNodeId = unsafeNodeId (v0, e)
167−#endif
168− }
169− !s = SubscriberHold h
170− writeIORef subscriberRef $ unsafeCoerce s
171− modifyIORef' holdInitRef (SomeHoldInit e h :)
172− return $ BehaviorHold h
173−
174−subscribeHold :: Event a -> Hold a -> EventM ()
175−subscribeHold e h = do
176− toAssignRef <- askToAssignRef
177− !s <- liftIO $ liftM unsafeCoerce $ readIORef $ holdSubscriber h -- This must be performed strictly so that the weak pointer points at the actual item
178− ws <- liftIO $ mkWeakPtrWithDebug s "holdSubscriber"
179− subd <- subscribe e $ WeakSubscriberSimple ws
180− liftIO $ writeIORef (holdParent h) $ unsafeCoerce subd
181− occ <- liftIO $ getEventSubscribedOcc subd
182− case occ of
183− Nothing -> return ()
184− Just o -> liftIO $ modifyIORef' toAssignRef (SomeAssignment h o :)
185−
186−--type role BehaviorM representational
187−-- BehaviorM can sample behaviors
188−newtype BehaviorM a = BehaviorM { unBehaviorM :: ReaderT (Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed])) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
189−
190−data BehaviorSubscribed a
191− = BehaviorSubscribedHold (Hold a)
192− | BehaviorSubscribedPull (PullSubscribed a)
193−
194−data SomeBehaviorSubscribed = forall a. SomeBehaviorSubscribed (BehaviorSubscribed a)
195−
196−--type role PullSubscribed representational
197−data PullSubscribed a
198− = PullSubscribed { pullSubscribedValue :: !a
199− , pullSubscribedInvalidators :: !(IORef [Weak Invalidator])
200− , pullSubscribedOwnInvalidator :: !Invalidator
201− , pullSubscribedParents :: ![SomeBehaviorSubscribed] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
202− }
203−
204−--type role Pull representational
205−data Pull a
206− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed a)))
207− , pullCompute :: !(BehaviorM a)
208− }
209−
210−data Invalidator
211− = forall a. InvalidatorPull (Pull a)
212− | forall a. InvalidatorSwitch (SwitchSubscribed a)
213−
214−data RootSubscribed a
215− = RootSubscribed { rootSubscribedSubscribers :: !(IORef [WeakSubscriber a])
216− , rootSubscribedOccurrence :: !(IORef (Maybe a)) -- Alias to rootOccurrence
217− }
218−
219−data Root a
220− = Root { rootOccurrence :: !(IORef (Maybe a)) -- The currently-firing occurrence of this event
221− , rootSubscribed :: !(IORef (Maybe (RootSubscribed a)))
222− , rootInit :: !(RootTrigger a -> IO (IO ()))
223− }
224−
225−data SomeHoldInit = forall a. SomeHoldInit (Event a) (Hold a)
226−
227−-- EventM can do everything BehaviorM can, plus create holds
228−newtype EventM a = EventM { unEventM :: ReaderT EventEnv IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO) -- 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
229−
230−data PushSubscribed a b
231− = PushSubscribed { pushSubscribedOccurrence :: !(IORef (Maybe b)) -- If the current height is less than our height, this should always be Nothing; during our height, this will get filled in at some point, always before our children are notified; after our height, this will be filled in with the correct value (Nothing if we are not firing, Just if we are)
232− , pushSubscribedHeight :: !(IORef Int)
233− , pushSubscribedSubscribers :: !(IORef [WeakSubscriber b])
234− , pushSubscribedSelf :: !(Subscriber a) -- Hold this in memory to ensure our WeakReferences don't die
235− , pushSubscribedParent :: !(EventSubscribed a)
236−#ifdef DEBUG_NODEIDS
237− , pushSubscribedNodeId :: Int
238−#endif
239− }
240−
241−data Push a b
242− = Push { pushCompute :: !(a -> EventM (Maybe b)) -- Compute the current firing value; assumes that its parent has been computed
243− , pushParent :: !(Event a)
244− , pushSubscribed :: !(IORef (Maybe (PushSubscribed a b))) --TODO: Can we replace this with an unsafePerformIO thunk?
245− }
246−
247−data MergeSubscribed k
248− = MergeSubscribed { mergeSubscribedOccurrence :: !(IORef (Maybe (DMap k)))
249− , mergeSubscribedAccum :: !(IORef (DMap k)) -- This will accumulate occurrences until our height is reached, at which point it will be transferred to mergeSubscribedOccurrence
250− , mergeSubscribedHeight :: !(IORef Int)
251− , mergeSubscribedSubscribers :: !(IORef [WeakSubscriber (DMap k)])
252− , mergeSubscribedSelf :: !Any -- Hold all our Subscribers in memory
253− , mergeSubscribedParents :: !(DMap (WrapArg EventSubscribed k))
254−#ifdef DEBUG_NODEIDS
255− , mergeSubscribedNodeId :: Int
256−#endif
257− }
258−
259−--TODO: DMap sucks; we should really write something better (with a functor for the value as well as the key)
260−data Merge k
261− = Merge { mergeParents :: !(DMap (WrapArg Event k))
262− , mergeSubscribed :: !(IORef (Maybe (MergeSubscribed k))) --TODO: Can we replace this with an unsafePerformIO thunk?
263− }
264−
265−data FanSubscriberKey k a where
266− FanSubscriberKey :: k a -> FanSubscriberKey k [WeakSubscriber a]
267−
268−instance GEq k => GEq (FanSubscriberKey k) where
269− geq (FanSubscriberKey a) (FanSubscriberKey b) = case geq a b of
270− Nothing -> Nothing
271− Just Refl -> Just Refl
272−
273−instance GCompare k => GCompare (FanSubscriberKey k) where
274− gcompare (FanSubscriberKey a) (FanSubscriberKey b) = case gcompare a b of
275− GLT -> GLT
276− GEQ -> GEQ
277− GGT -> GGT
278−
279−data FanSubscribed k
280− = FanSubscribed { fanSubscribedSubscribers :: !(IORef (DMap (FanSubscriberKey k)))
281− , fanSubscribedParent :: !(EventSubscribed (DMap k))
282− , fanSubscribedSelf :: !(Subscriber (DMap k))
283−#ifdef DEBUG_NODEIDS
284− , fanSubscribedNodeId :: Int
285−#endif
286− }
287−
288−data Fan k
289− = Fan { fanParent :: !(Event (DMap k))
290− , fanSubscribed :: !(IORef (Maybe (FanSubscribed k)))
291− }
292−
293−data SwitchSubscribed a
294− = SwitchSubscribed { switchSubscribedOccurrence :: !(IORef (Maybe a))
295− , switchSubscribedHeight :: !(IORef Int)
296− , switchSubscribedSubscribers :: !(IORef [WeakSubscriber a])
297− , switchSubscribedSelf :: !(Subscriber a)
298− , switchSubscribedSelfWeak :: !(IORef (Weak (Subscriber a)))
299− , switchSubscribedOwnInvalidator :: !Invalidator
300− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak Invalidator))
301− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed])
302− , switchSubscribedParent :: !(Behavior (Event a))
303− , switchSubscribedCurrentParent :: !(IORef (EventSubscribed a))
304−#ifdef DEBUG_NODEIDS
305− , switchSubscribedNodeId :: Int
306−#endif
307− }
308−
309−data Switch a
310− = Switch { switchParent :: !(Behavior (Event a))
311− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed a)))
312− }
313−
314−data CoincidenceSubscribed a
315− = CoincidenceSubscribed { coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
316− , coincidenceSubscribedSubscribers :: !(IORef [WeakSubscriber a])
317− , coincidenceSubscribedHeight :: !(IORef Int)
318− , coincidenceSubscribedOuter :: !(Subscriber (Event a))
319− , coincidenceSubscribedOuterParent :: !(EventSubscribed (Event a))
320− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed a)))
321−#ifdef DEBUG_NODEIDS
322− , coincidenceSubscribedNodeId :: Int
323−#endif
324− }
325−
326−data Coincidence a
327− = Coincidence { coincidenceParent :: !(Event (Event a))
328− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed a)))
329− }
330−
331−data Box a = Box { unBox :: a }
332−
333−--type WeakSubscriber a = Weak (Subscriber a)
334−data WeakSubscriber a
335− = forall k. GCompare k => WeakSubscriberMerge !(k a) !(Weak (Box (MergeSubscribed k))) --TODO: Can we inline the GCompare?
336− | WeakSubscriberSimple !(Weak (Subscriber a))
337−
338−showWeakSubscriberType :: WeakSubscriber a -> String
339−showWeakSubscriberType = \case
340− WeakSubscriberMerge _ _ -> "WeakSubscriberMerge"
341− WeakSubscriberSimple _ -> "WeakSubscriberSimple"
342−
343−deRefWeakSubscriber :: WeakSubscriber a -> IO (Maybe (Subscriber a))
344−deRefWeakSubscriber ws = case ws of
345− WeakSubscriberSimple w -> deRefWeak w
346− WeakSubscriberMerge k w -> liftM (fmap $ SubscriberMerge k . unBox) $ deRefWeak w
347−
348−data Subscriber a
349− = forall b. SubscriberPush !(a -> EventM (Maybe b)) (PushSubscribed a b)
350− | forall k. GCompare k => SubscriberMerge !(k a) (MergeSubscribed k) --TODO: Can we inline the GCompare?
351− | forall k. (GCompare k, a ~ DMap k) => SubscriberFan (FanSubscribed k)
352− | SubscriberHold !(Hold a)
353− | SubscriberSwitch (SwitchSubscribed a)
354− | forall b. a ~ Event b => SubscriberCoincidenceOuter (CoincidenceSubscribed b)
355− | SubscriberCoincidenceInner (CoincidenceSubscribed a)
356−
357−showSubscriberType :: Subscriber a -> String
358−showSubscriberType = \case
359− SubscriberPush _ _ -> "SubscriberPush"
360− SubscriberMerge _ _ -> "SubscriberMerge"
361− SubscriberFan _ -> "SubscriberFan"
362− SubscriberHold _ -> "SubscriberHold"
363− SubscriberSwitch _ -> "SubscriberSwitch"
364− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
365− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
366−
367−data Event a
368− = EventRoot !(Root a)
369− | EventNever
370− | forall b. EventPush !(Push b a)
371− | forall k. (GCompare k, a ~ DMap k) => EventMerge !(Merge k)
372− | forall k. GCompare k => EventFan !(k a) !(Fan k)
373− | EventSwitch !(Switch a)
374− | EventCoincidence !(Coincidence a)
375−
376−showEventType :: Event a -> String
377−showEventType = \case
378− EventRoot _ -> "EventRoot"
379− EventNever -> "EventNever"
380− EventPush _ -> "EventPush"
381− EventMerge _ -> "EventMerge"
382− EventFan _ _ -> "EventFan"
383− EventSwitch _ -> "EventSwitch"
384− EventCoincidence _ -> "EventCoincidence"
385−
386−data EventSubscribed a
387− = EventSubscribedRoot {-# NOUNPACK #-} (RootSubscribed a)
388− | EventSubscribedNever
389− | forall b. EventSubscribedPush !(PushSubscribed b a)
390− | forall k. (GCompare k, a ~ DMap k) => EventSubscribedMerge !(MergeSubscribed k)
391− | forall k. GCompare k => EventSubscribedFan !(k a) !(FanSubscribed k)
392− | EventSubscribedSwitch !(SwitchSubscribed a)
393− | EventSubscribedCoincidence !(CoincidenceSubscribed a)
394−
395−--type role Behavior representational
396−data Behavior a
397− = BehaviorHold !(Hold a)
398− | BehaviorConst !a
399− | BehaviorPull !(Pull a)
400−
401−-- ResultM can read behaviors and events
402−type ResultM = EventM
403−
404−{-# NOINLINE unsafeNewIORef #-}
405−unsafeNewIORef :: a -> b -> IORef b
406−unsafeNewIORef _ b = unsafePerformIO $ newIORef b
407−
408−instance Functor Event where
409− fmap f = push $ return . Just . f
410−
411−instance Functor Behavior where
412− fmap f = pull . liftM f . readBehaviorTracked
413−
414−{-# NOINLINE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly
415−push :: (a -> EventM (Maybe b)) -> Event a -> Event b
416−push f e = EventPush $ Push
417− { pushCompute = f
418− , pushParent = e
419− , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead?
420− }
421−{-# RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-}
422−
423−{-# NOINLINE pull #-}
424−pull :: BehaviorM a -> Behavior a
425−pull a = BehaviorPull $ Pull
426− { pullCompute = a
427− , pullValue = unsafeNewIORef a Nothing
428− }
429−{-# RULES "pull/pull" forall a. pull (readBehaviorTracked (pull a)) = pull a #-}
430−
431−{-# NOINLINE switch #-}
432−switch :: Behavior (Event a) -> Event a
433−switch a = EventSwitch $ Switch
434− { switchParent = a
435− , switchSubscribed = unsafeNewIORef a Nothing
436− }
437−{-# RULES "switch/constB" forall e. switch (BehaviorConst e) = e #-}
438−
439−coincidence :: Event (Event a) -> Event a
440−coincidence a = EventCoincidence $ Coincidence
441− { coincidenceParent = a
442− , coincidenceSubscribed = unsafeNewIORef a Nothing
443− }
444−
445−newRoot :: IO (Root a)
446−newRoot = do
447− occRef <- newIORef Nothing
448− subscribedRef <- newIORef Nothing
449− return $ Root
450− { rootOccurrence = occRef
451− , rootSubscribed = subscribedRef
452− , rootInit = const $ return $ return ()
453− }
454−
455−propagateAndUpdateSubscribersRef :: IORef [WeakSubscriber a] -> a -> EventM ()
456−propagateAndUpdateSubscribersRef subscribersRef a = do
457− subscribers <- liftIO $ readIORef subscribersRef
458− liftIO $ writeIORef subscribersRef []
459− stillAlive <- propagate a subscribers
460− liftIO $ modifyIORef' subscribersRef (++stillAlive)
461−
462−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
463−run :: [DSum RootTrigger] -> ResultM b -> IO b
464−run roots after = do
465− when debugPropagate $ putStrLn "Running an event frame"
466− result <- runFrame $ do
467− forM_ roots $ \(RootTrigger (_, occRef) :=> a) -> do
468− liftIO $ writeIORef occRef $ Just a
469− scheduleClear occRef
470− forM_ roots $ \(RootTrigger (subscribersRef, _) :=> a) -> do
471− propagateAndUpdateSubscribersRef subscribersRef a
472− delayedRef <- EventM $ asks eventEnvDelayedMerges
473− let go = do
474− delayed <- liftIO $ readIORef delayedRef
475− case IntMap.minViewWithKey delayed of
476− Nothing -> return ()
477− Just ((currentHeight, current), future) -> do
478− when debugPropagate $ liftIO $ putStrLn $ "Running height " ++ show currentHeight
479− putCurrentHeight currentHeight
480− liftIO $ writeIORef delayedRef future
481− forM_ current $ \d -> case d of
482− DelayedMerge subscribed -> do
483− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
484− case height `compare` currentHeight of
485− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
486− GT -> scheduleMerge height subscribed -- The height has been increased (by a coincidence event; TODO: is this the only way?)
487− EQ -> do
488− m <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
489− liftIO $ writeIORef (mergeSubscribedAccum subscribed) DMap.empty
490− --TODO: Assert that m is not empty
491− liftIO $ writeIORef (mergeSubscribedOccurrence subscribed) $ Just m
492− scheduleClear $ mergeSubscribedOccurrence subscribed
493− propagateAndUpdateSubscribersRef (mergeSubscribedSubscribers subscribed) m
494− go
495− go
496− putCurrentHeight maxBound
497− after
498− when debugPropagate $ putStrLn "Done running an event frame"
499− return result
500−
501−data SomeMaybeIORef = forall a. SomeMaybeIORef (IORef (Maybe a))
502−
503−data SomeAssignment = forall a. SomeAssignment (Hold a) a
504−
505−data DelayedMerge = forall k. DelayedMerge (MergeSubscribed k)
506−
507−debugFinalize :: Bool
508−debugFinalize = False
509−
510−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
511−mkWeakPtrWithDebug x debugNote = mkWeakPtr x $
512− if debugFinalize
513− then Just $ putStrLn $ "finalizing: " ++ debugNote
514− else Nothing
515−
516−type WeakList a = [Weak a]
517−
518−--TODO: Is it faster to clean up every time, or to occasionally go through and clean up as needed?
519−traverseAndCleanWeakList_ :: Monad m => (wa -> m (Maybe a)) -> [wa] -> (a -> m ()) -> m [wa]
520−traverseAndCleanWeakList_ deRef ws f = go ws
521− where go [] = return []
522− go (h:t) = do
523− ma <- deRef h
524− case ma of
525− Just a -> do
526− f a
527− t' <- go t
528− return $ h : t'
529− Nothing -> go t
530−
531−-- | Propagate everything at the current height
532−propagate :: a -> [WeakSubscriber a] -> EventM [WeakSubscriber a]
533−propagate a subscribers = do
534− traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subscribers $ \s -> case s of
535− SubscriberPush compute subscribed -> do
536− when debugPropagate $ liftIO $ putStrLn $ "SubscriberPush" <> showNodeId subscribed
537− occ <- compute a
538− case occ of
539− Nothing -> return () -- No need to write a Nothing back into the Ref
540− Just o -> do
541− liftIO $ writeIORef (pushSubscribedOccurrence subscribed) occ
542− scheduleClear $ pushSubscribedOccurrence subscribed
543− liftIO . writeIORef (pushSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (pushSubscribedSubscribers subscribed))
544− SubscriberMerge k subscribed -> do
545− when debugPropagate $ liftIO $ putStrLn $ "SubscriberMerge" <> showNodeId subscribed
546− oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
547− liftIO $ writeIORef (mergeSubscribedAccum subscribed) $ DMap.insertWith (error "Same key fired multiple times for") k a oldM
548− when (DMap.null oldM) $ do -- Only schedule the firing once
549− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
550− --TODO: assertions about height
551− currentHeight <- getCurrentHeight
552− when (height <= currentHeight) $ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")"
553− scheduleMerge height subscribed
554− SubscriberFan subscribed -> do
555− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
556− when debugPropagate $ liftIO $ putStrLn $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
557− --TODO: We need a better DMap intersection; here, we are assuming that the number of firing keys is small and the number of subscribers is large
558− forM_ (DMap.toList a) $ \(k :=> v) -> case DMap.lookup (FanSubscriberKey k) subs of
559− Nothing -> do
560− when debugPropagate $ liftIO $ putStrLn "No subscriber for key"
561− return ()
562− Just subsubs -> do
563− _ <- propagate v subsubs --TODO: use the value of this
564− return ()
565− --TODO: The following is way too slow to do all the time
566− subs' <- liftIO $ forM (DMap.toList subs) $ ((\(FanSubscriberKey k :=> subsubs) -> do
567− subsubs' <- traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subsubs (const $ return ())
568− return $ if null subsubs' then Nothing else Just $ FanSubscriberKey k :=> subsubs') :: DSum (FanSubscriberKey k) -> IO (Maybe (DSum (FanSubscriberKey k))))
569− liftIO $ writeIORef (fanSubscribedSubscribers subscribed) $ DMap.fromDistinctAscList $ catMaybes subs'
570− SubscriberHold h -> do
571− invalidators <- liftIO $ readIORef $ holdInvalidators h
572− when debugPropagate $ liftIO $ putStrLn $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
573− toAssignRef <- askToAssignRef
574− liftIO $ modifyIORef' toAssignRef (SomeAssignment h a :)
575− SubscriberSwitch subscribed -> do
576− when debugPropagate $ liftIO $ putStrLn $ "SubscriberSwitch" <> showNodeId subscribed
577− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
578− scheduleClear $ switchSubscribedOccurrence subscribed
579− subs <- liftIO $ readIORef $ switchSubscribedSubscribers subscribed
580− liftIO . writeIORef (switchSubscribedSubscribers subscribed) =<< propagate a subs
581− SubscriberCoincidenceOuter subscribed -> do
582− when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
583− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
584− when debugPropagate $ liftIO $ putStrLn $ " outerHeight = " <> show outerHeight
585− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
586− when debugPropagate $ liftIO $ putStrLn $ " isJust occ = " <> show (isJust occ)
587− when debugPropagate $ liftIO $ putStrLn $ " innerHeight = " <> show innerHeight
588− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
589− scheduleClear $ coincidenceSubscribedInnerParent subscribed
590− case occ of
591− Nothing -> do
592− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
593− writeIORef (coincidenceSubscribedHeight subscribed) innerHeight
594− mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed)
595− mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed)
596− Just o -> do -- Since it's already firing, no need to adjust height
597− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
598− scheduleClear $ coincidenceSubscribedOccurrence subscribed
599− liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed))
600− SubscriberCoincidenceInner subscribed -> do
601− when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceInner" <> showNodeId subscribed
602− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
603− scheduleClear $ coincidenceSubscribedOccurrence subscribed
604− liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate a =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed))
605−
606−data SomeCoincidenceInfo = forall a. SomeCoincidenceInfo (Weak (Subscriber a)) (Subscriber a) (Maybe (CoincidenceSubscribed a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
607−
608−subscribeCoincidenceInner :: Event a -> Int -> CoincidenceSubscribed a -> EventM (Maybe a, Int, EventSubscribed a)
609−subscribeCoincidenceInner o outerHeight subscribedUnsafe = do
610− let !subInner = SubscriberCoincidenceInner subscribedUnsafe
611− wsubInner <- liftIO $ mkWeakPtrWithDebug subInner "SubscriberCoincidenceInner"
612− innerSubd <- {-# SCC "innerSubd" #-} (subscribe o $ WeakSubscriberSimple wsubInner)
613− innerOcc <- liftIO $ getEventSubscribedOcc innerSubd
614− innerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef innerSubd
615− let height = max innerHeight outerHeight
616− emitCoincidenceInfo $ SomeCoincidenceInfo wsubInner subInner $ if height > outerHeight then Just subscribedUnsafe else Nothing
617− return (innerOcc, height, innerSubd)
618−
619−readBehavior :: Behavior a -> IO a
620−readBehavior b = runBehaviorM (readBehaviorTracked b) Nothing --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
621−
622−runBehaviorM :: BehaviorM a -> Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed]) -> IO a
623−runBehaviorM a mwi = runReaderT (unBehaviorM a) mwi
624−
625−askInvalidator :: BehaviorM (Maybe (Weak Invalidator))
626−askInvalidator = liftM (fmap fst) $ BehaviorM ask
627−
628−askParentsRef :: BehaviorM (Maybe (IORef [SomeBehaviorSubscribed]))
629−askParentsRef = liftM (fmap snd) $ BehaviorM ask
630−
631−readBehaviorTracked :: Behavior a -> BehaviorM a
632−readBehaviorTracked b = case b of
633− BehaviorHold h -> do
634− result <- liftIO $ readIORef $ holdValue h
635− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
636− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
637− liftIO $ touch $ holdSubscriber h
638− return result
639− BehaviorConst a -> return a
640− BehaviorPull p -> do
641− val <- liftIO $ readIORef $ pullValue p
642− case val of
643− Just subscribed -> do
644− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
645− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
646− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
647− return $ pullSubscribedValue subscribed
648− Nothing -> do
649− let !i = InvalidatorPull p
650− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
651− parentsRef <- liftIO $ newIORef []
652− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) $ Just (wi, parentsRef)
653− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
654− parents <- liftIO $ readIORef parentsRef
655− let subscribed = PullSubscribed
656− { pullSubscribedValue = a
657− , pullSubscribedInvalidators = invsRef
658− , pullSubscribedOwnInvalidator = i
659− , pullSubscribedParents = parents
660− }
661− liftIO $ writeIORef (pullValue p) $ Just subscribed
662− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
663− return a
664−
665−readEvent :: Event a -> ResultM (Maybe a)
666−readEvent e = case e of
667− EventRoot r -> liftIO $ readIORef $ rootOccurrence r
668− EventNever -> return Nothing
669− EventPush p -> do
670− subscribed <- getPushSubscribed p
671− liftIO $ do
672− result <- readIORef $ pushSubscribedOccurrence subscribed -- Since ResultM is always called after the final height is reached, this will always be valid
673− touch $ pushSubscribedSelf subscribed
674− return result
675− EventMerge m -> do
676− subscribed <- getMergeSubscribed m
677− liftIO $ do
678− result <- readIORef $ mergeSubscribedOccurrence subscribed
679− touch $ mergeSubscribedSelf subscribed
680− return result
681− EventFan k f -> do
682− parentOcc <- readEvent $ fanParent f
683− return $ DMap.lookup k =<< parentOcc
684− EventSwitch s -> do
685− subscribed <- getSwitchSubscribed s
686− liftIO $ do
687− result <- readIORef $ switchSubscribedOccurrence subscribed
688− touch $ switchSubscribedSelf subscribed
689− touch $ switchSubscribedOwnInvalidator subscribed
690− return result
691− EventCoincidence c -> do
692− subscribed <- getCoincidenceSubscribed c
693− liftIO $ do
694− result <- readIORef $ coincidenceSubscribedOccurrence subscribed
695− touch $ coincidenceSubscribedOuter subscribed
696− --TODO: do we need to touch the inner subscriber?
697− return result
698−
699−-- Always refers to 0
700−{-# NOINLINE zeroRef #-}
701−zeroRef :: IORef Int
702−zeroRef = unsafePerformIO $ newIORef 0
703−
704−getEventSubscribed :: Event a -> EventM (EventSubscribed a)
705−getEventSubscribed e = case e of
706− EventRoot r -> liftM EventSubscribedRoot $ getRootSubscribed r
707− EventNever -> return EventSubscribedNever
708− EventPush p -> liftM EventSubscribedPush $ getPushSubscribed p
709− EventFan k f -> liftM (EventSubscribedFan k) $ getFanSubscribed f
710− EventMerge m -> liftM EventSubscribedMerge $ getMergeSubscribed m
711− EventSwitch s -> liftM EventSubscribedSwitch $ getSwitchSubscribed s
712− EventCoincidence c -> liftM EventSubscribedCoincidence $ getCoincidenceSubscribed c
713−
714−debugSubscribe :: Bool
715−debugSubscribe = False
716−
717−subscribeEventSubscribed :: EventSubscribed a -> WeakSubscriber a -> IO ()
718−subscribeEventSubscribed es ws = case es of
719− EventSubscribedRoot r -> do
720− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Root"
721− modifyIORef' (rootSubscribedSubscribers r) (ws:)
722− EventSubscribedNever -> do
723− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Never"
724− return ()
725− EventSubscribedPush subscribed -> do
726− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Push"
727− modifyIORef' (pushSubscribedSubscribers subscribed) (ws:)
728− EventSubscribedFan k subscribed -> do
729− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Fan"
730− modifyIORef' (fanSubscribedSubscribers subscribed) $ DMap.insertWith (++) (FanSubscriberKey k) [ws]
731− EventSubscribedMerge subscribed -> do
732− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Merge"
733− modifyIORef' (mergeSubscribedSubscribers subscribed) (ws:)
734− EventSubscribedSwitch subscribed -> do
735− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Switch"
736− modifyIORef' (switchSubscribedSubscribers subscribed) (ws:)
737− EventSubscribedCoincidence subscribed -> do
738− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Coincidence"
739− modifyIORef' (coincidenceSubscribedSubscribers subscribed) (ws:)
740−
741−getEventSubscribedOcc :: EventSubscribed a -> IO (Maybe a)
742−getEventSubscribedOcc es = case es of
743− EventSubscribedRoot r -> readIORef $ rootSubscribedOccurrence r
744− EventSubscribedNever -> return Nothing
745− EventSubscribedPush subscribed -> readIORef $ pushSubscribedOccurrence subscribed
746− EventSubscribedFan k subscribed -> do
747− parentOcc <- getEventSubscribedOcc $ fanSubscribedParent subscribed
748− let occ = DMap.lookup k =<< parentOcc
749− return occ
750− EventSubscribedMerge subscribed -> readIORef $ mergeSubscribedOccurrence subscribed
751− EventSubscribedSwitch subscribed -> readIORef $ switchSubscribedOccurrence subscribed
752− EventSubscribedCoincidence subscribed -> readIORef $ coincidenceSubscribedOccurrence subscribed
753−
754−eventSubscribedHeightRef :: EventSubscribed a -> IORef Int
755−eventSubscribedHeightRef es = case es of
756− EventSubscribedRoot _ -> zeroRef
757− EventSubscribedNever -> zeroRef
758− EventSubscribedPush subscribed -> pushSubscribedHeight subscribed
759− EventSubscribedFan _ subscribed -> eventSubscribedHeightRef $ fanSubscribedParent subscribed
760− EventSubscribedMerge subscribed -> mergeSubscribedHeight subscribed
761− EventSubscribedSwitch subscribed -> switchSubscribedHeight subscribed
762− EventSubscribedCoincidence subscribed -> coincidenceSubscribedHeight subscribed
763−
764−subscribe :: Event a -> WeakSubscriber a -> EventM (EventSubscribed a)
765−subscribe e ws = do
766− subd <- getEventSubscribed e
767− liftIO $ subscribeEventSubscribed subd ws
768− return subd
769−
770−noinlineFalse :: Bool
771−noinlineFalse = False
772−{-# NOINLINE noinlineFalse #-}
773−
774−getRootSubscribed :: Root a -> EventM (RootSubscribed a)
775−getRootSubscribed r = do
776− mSubscribed <- liftIO $ readIORef $ rootSubscribed r
777− case mSubscribed of
778− Just subscribed -> return subscribed
779− Nothing -> liftIO $ do
780− subscribersRef <- newIORef []
781− let !subscribed = RootSubscribed
782− { rootSubscribedOccurrence = rootOccurrence r
783− , rootSubscribedSubscribers = subscribersRef
784− }
785− -- Strangely, init needs the same stuff as a RootSubscribed has, but it must not be the same as the one that everyone's subscribing to, or it'll leak memory
786− uninit <- rootInit r $ RootTrigger (subscribersRef, rootOccurrence r)
787− addFinalizer subscribed $ do
788− when noinlineFalse $ putStr "" -- For some reason, without this line, the finalizer will run earlier than it should
789−-- putStrLn "Uninit root"
790− uninit
791− liftIO $ writeIORef (rootSubscribed r) $ Just subscribed
792− return subscribed
793−
794−-- When getPushSubscribed returns, the PushSubscribed returned will have a fully filled-in
795−getPushSubscribed :: Push a b -> EventM (PushSubscribed a b)
796−getPushSubscribed p = do
797− mSubscribed <- liftIO $ readIORef $ pushSubscribed p
798− case mSubscribed of
799− Just subscribed -> return subscribed
800− Nothing -> do -- Not yet subscribed
801− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ pushSubscribed p
802− let !s = SubscriberPush (pushCompute p) subscribedUnsafe
803− ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberPush"
804− subd <- subscribe (pushParent p) $ WeakSubscriberSimple ws
805− parentOcc <- liftIO $ getEventSubscribedOcc subd
806− occ <- liftM join $ mapM (pushCompute p) parentOcc
807− occRef <- liftIO $ newIORef occ
808− when (isJust occ) $ scheduleClear occRef
809− subscribersRef <- liftIO $ newIORef []
810− let subscribed = PushSubscribed
811− { pushSubscribedOccurrence = occRef
812− , pushSubscribedHeight = eventSubscribedHeightRef subd -- Since pushes have the same height as their parents, share the ref
813− , pushSubscribedSubscribers = subscribersRef
814− , pushSubscribedSelf = unsafeCoerce s
815− , pushSubscribedParent = subd
816−#ifdef DEBUG_NODEIDS
817− , pushSubscribedNodeId = unsafeNodeId p
818−#endif
819− }
820− liftIO $ writeIORef (pushSubscribed p) $ Just subscribed
821− return subscribed
822−
823−getMergeSubscribed :: forall k. GCompare k => Merge k -> EventM (MergeSubscribed k)
824−getMergeSubscribed m = {-# SCC "getMergeSubscribed.entire" #-} do
825− mSubscribed <- liftIO $ readIORef $ mergeSubscribed m
826− case mSubscribed of
827− Just subscribed -> return subscribed
828− Nothing -> if DMap.null $ mergeParents m then emptyMergeSubscribed else do
829− subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized"
830− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
831− let !s = Box subscribedUnsafe
832− ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberMerge"
833− subscribers :: [(Any, Maybe (DSum k), Int, DSum (WrapArg EventSubscribed k))] <- forM (DMap.toList $ mergeParents m) $ {-# SCC "getMergeSubscribed.a" #-} \(WrapArg k :=> e) -> {-# SCC "getMergeSubscribed.a1" #-} do
834− parentSubd <- {-# SCC "getMergeSubscribed.a.parentSubd" #-} subscribe e $ WeakSubscriberMerge k ws
835− parentOcc <- {-# SCC "getMergeSubscribed.a.parentOcc" #-} liftIO $ getEventSubscribedOcc parentSubd
836− height <- {-# SCC "getMergeSubscribed.a.height" #-} liftIO $ readIORef $ eventSubscribedHeightRef parentSubd
837− return $ {-# SCC "getMergeSubscribed.a.returnVal" #-} (unsafeCoerce s :: Any, fmap (k :=>) parentOcc, height, WrapArg k :=> parentSubd)
838− let dm = DMap.fromDistinctAscList $ catMaybes $ map (\(_, x, _, _) -> x) subscribers
839− subscriberHeights = map (\(_, _, x, _) -> x) subscribers
840− myHeight =
841− if any (==invalidHeight) subscriberHeights --TODO: Replace 'any' with invalidHeight-preserving 'maximum'
842− then invalidHeight
843− else succ $ Prelude.maximum subscriberHeights -- This is safe because the DMap will never be empty here
844− currentHeight <- getCurrentHeight
845− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
846− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
847− else (Nothing, dm)
848− when (not $ DMap.null accum) $ do
849− scheduleMerge myHeight subscribedUnsafe
850− occRef <- liftIO $ newIORef occ
851− when (isJust occ) $ scheduleClear occRef
852− accumRef <- liftIO $ newIORef accum
853− heightRef <- liftIO $ newIORef myHeight
854− subsRef <- liftIO $ newIORef []
855− let subscribed = MergeSubscribed
856− { mergeSubscribedOccurrence = occRef
857− , mergeSubscribedAccum = accumRef
858− , mergeSubscribedHeight = heightRef
859− , mergeSubscribedSubscribers = subsRef
860− , mergeSubscribedSelf = unsafeCoerce $ map (\(x, _, _, _) -> x) subscribers --TODO: Does lack of strictness make this leak?
861− , mergeSubscribedParents = DMap.fromDistinctAscList $ map (\(_, _, _, x) -> x) subscribers
862−#ifdef DEBUG_NODEIDS
863− , mergeSubscribedNodeId = unsafeNodeId m
864−#endif
865− }
866− liftIO $ writeIORef subscribedRef subscribed
867− return subscribed
868− where emptyMergeSubscribed = do --TODO: This should never happen
869− occRef <- liftIO $ newIORef Nothing
870− accumRef <- liftIO $ newIORef DMap.empty
871− subsRef <- liftIO $ newIORef []
872− return $ MergeSubscribed
873− { mergeSubscribedOccurrence = occRef
874− , mergeSubscribedAccum = accumRef
875− , mergeSubscribedHeight = zeroRef
876− , mergeSubscribedSubscribers = subsRef --TODO: This will definitely leak
877− , mergeSubscribedSelf = unsafeCoerce ()
878− , mergeSubscribedParents = DMap.empty
879−#ifdef DEBUG_NODEIDS
880− , mergeSubscribedNodeId = -1
881−#endif
882− }
883−
884−getFanSubscribed :: GCompare k => Fan k -> EventM (FanSubscribed k)
885−getFanSubscribed f = do
886− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
887− case mSubscribed of
888− Just subscribed -> return subscribed
889− Nothing -> do
890− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ fanSubscribed f
891− let !sub = SubscriberFan subscribedUnsafe
892− wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberFan"
893− subd <- subscribe (fanParent f) $ WeakSubscriberSimple wsub
894− subscribersRef <- liftIO $ newIORef DMap.empty
895− let subscribed = FanSubscribed
896− { fanSubscribedParent = subd
897− , fanSubscribedSubscribers = subscribersRef
898− , fanSubscribedSelf = sub
899−#ifdef DEBUG_NODEIDS
900− , fanSubscribedNodeId = unsafeNodeId f
901−#endif
902− }
903− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
904− return subscribed
905−
906−getSwitchSubscribed :: Switch a -> EventM (SwitchSubscribed a)
907−getSwitchSubscribed s = do
908− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
909− case mSubscribed of
910− Just subscribed -> return subscribed
911− Nothing -> do
912− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
913− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
914− let !i = InvalidatorSwitch subscribedUnsafe
915− !sub = SubscriberSwitch subscribedUnsafe
916− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
917− wiRef <- liftIO $ newIORef wi
918− wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberSwitch"
919− selfWeakRef <- liftIO $ newIORef wsub
920− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
921− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) $ Just (wi, parentsRef)
922− subd <- subscribe e $ WeakSubscriberSimple wsub
923− subdRef <- liftIO $ newIORef subd
924− parentOcc <- liftIO $ getEventSubscribedOcc subd
925− occRef <- liftIO $ newIORef parentOcc
926− when (isJust parentOcc) $ scheduleClear occRef
927− heightRef <- liftIO $ newIORef =<< readIORef (eventSubscribedHeightRef subd)
928− subscribersRef <- liftIO $ newIORef []
929− let subscribed = SwitchSubscribed
930− { switchSubscribedOccurrence = occRef
931− , switchSubscribedHeight = heightRef
932− , switchSubscribedSubscribers = subscribersRef
933− , switchSubscribedSelf = sub
934− , switchSubscribedSelfWeak = selfWeakRef
935− , switchSubscribedOwnInvalidator = i
936− , switchSubscribedOwnWeakInvalidator = wiRef
937− , switchSubscribedBehaviorParents = parentsRef
938− , switchSubscribedParent = switchParent s
939− , switchSubscribedCurrentParent = subdRef
940−#ifdef DEBUG_NODEIDS
941− , switchSubscribedNodeId = unsafeNodeId s
942−#endif
943− }
944− liftIO $ writeIORef subscribedRef subscribed
945− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
946− return subscribed
947−
948−getCoincidenceSubscribed :: forall a. Coincidence a -> EventM (CoincidenceSubscribed a)
949−getCoincidenceSubscribed c = do
950− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
951− case mSubscribed of
952− Just subscribed -> return subscribed
953− Nothing -> do
954− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
955− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
956− let !subOuter = SubscriberCoincidenceOuter subscribedUnsafe
957− wsubOuter <- liftIO $ mkWeakPtrWithDebug subOuter "subOuter"
958− outerSubd <- subscribe (coincidenceParent c) $ WeakSubscriberSimple wsubOuter
959− outerOcc <- liftIO $ getEventSubscribedOcc outerSubd
960− outerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef outerSubd
961− (occ, height, mInnerSubd) <- case outerOcc of
962− Nothing -> return (Nothing, outerHeight, Nothing)
963− Just o -> do
964− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
965− return (occ, height, Just innerSubd)
966− occRef <- liftIO $ newIORef occ
967− when (isJust occ) $ scheduleClear occRef
968− heightRef <- liftIO $ newIORef height
969− innerSubdRef <- liftIO $ newIORef mInnerSubd
970− scheduleClear innerSubdRef
971− subscribersRef <- liftIO $ newIORef []
972− let subscribed = CoincidenceSubscribed
973− { coincidenceSubscribedOccurrence = occRef
974− , coincidenceSubscribedHeight = heightRef
975− , coincidenceSubscribedSubscribers = subscribersRef
976− , coincidenceSubscribedOuter = subOuter
977− , coincidenceSubscribedOuterParent = outerSubd
978− , coincidenceSubscribedInnerParent = innerSubdRef
979−#ifdef DEBUG_NODEIDS
980− , coincidenceSubscribedNodeId = unsafeNodeId c
981−#endif
982− }
983− liftIO $ writeIORef subscribedRef subscribed
984− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
985− return subscribed
986−
987−merge :: GCompare k => DMap (WrapArg Event k) -> Event (DMap k)
988−merge m = EventMerge $ Merge
989− { mergeParents = m
990− , mergeSubscribed = unsafeNewIORef m Nothing
991− }
992−
993−newtype EventSelector k = EventSelector { select :: forall a. k a -> Event a }
994−
995−fan :: GCompare k => Event (DMap k) -> EventSelector k
996−fan e =
997− let f = Fan
998− { fanParent = e
999− , fanSubscribed = unsafeNewIORef e Nothing
1000− }
1001− in EventSelector $ \k -> EventFan k f
1002−
1003−-- | Run an event action outside of a frame
1004−runFrame :: EventM a -> IO a
1005−runFrame a = do
1006− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1007− holdInitRef <- newIORef []
1008− heightRef <- newIORef 0
1009− toClearRef <- newIORef []
1010− coincidenceInfosRef <- newIORef []
1011− delayedRef <- liftIO $ newIORef IntMap.empty
1012− result <- flip runEventM (EventEnv toAssignRef holdInitRef toClearRef heightRef coincidenceInfosRef delayedRef) $ do
1013− result <- a
1014− let runHoldInits = do
1015− holdInits <- liftIO $ readIORef holdInitRef
1016− if null holdInits then return () else do
1017− liftIO $ writeIORef holdInitRef []
1018− forM_ holdInits $ \(SomeHoldInit e h) -> subscribeHold e h
1019− runHoldInits
1020− runHoldInits -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
1021− return result
1022− toClear <- readIORef toClearRef
1023− forM_ toClear $ \(SomeMaybeIORef ref) -> writeIORef ref Nothing
1024− toAssign <- readIORef toAssignRef
1025− toReconnectRef <- newIORef []
1026− forM_ toAssign $ \(SomeAssignment h v) -> do
1027− writeIORef (holdValue h) v
1028− writeIORef (holdInvalidators h) =<< invalidate toReconnectRef =<< readIORef (holdInvalidators h)
1029− coincidenceInfos <- readIORef coincidenceInfosRef
1030− forM_ coincidenceInfos $ \(SomeCoincidenceInfo wsubInner subInner mcs) -> do
1031− touch subInner
1032− finalize wsubInner
1033− mapM_ invalidateCoincidenceHeight mcs
1034− toReconnect <- readIORef toReconnectRef
1035− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1036− wsub <- readIORef $ switchSubscribedSelfWeak subscribed
1037− finalize wsub
1038− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1039− finalize wi
1040− let !i = switchSubscribedOwnInvalidator subscribed
1041− wi' <- mkWeakPtrWithDebug i "wi'"
1042− writeIORef (switchSubscribedBehaviorParents subscribed) []
1043− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed))
1044− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1045− let !sub = switchSubscribedSelf subscribed -- Must be done strictly, or the weak pointer will refer to a useless thunk
1046− wsub' <- mkWeakPtrWithDebug sub "wsub'"
1047− writeIORef (switchSubscribedSelfWeak subscribed) wsub'
1048− subd' <- runFrame $ subscribe e $ WeakSubscriberSimple wsub' --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
1049− {-
1050− stackTrace <- liftIO $ liftM renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1051− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1052− EventRoot _ -> "EventRoot"
1053− EventNever -> "EventNever"
1054− _ -> "something else"
1055− -}
1056− writeIORef (switchSubscribedCurrentParent subscribed) subd'
1057− parentHeight <- readIORef $ eventSubscribedHeightRef subd'
1058− myHeight <- readIORef $ switchSubscribedHeight subscribed
1059− if parentHeight == myHeight then return () else do
1060− writeIORef (switchSubscribedHeight subscribed) parentHeight
1061− mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1062− forM_ coincidenceInfos $ \(SomeCoincidenceInfo _ _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1063− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1064− mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1065− return result
1066−
1067−invalidHeight :: Int
1068−invalidHeight = -1000
1069−
1070−invalidateSubscriberHeight :: WeakSubscriber a -> IO ()
1071−invalidateSubscriberHeight ws = do
1072− ms <- deRefWeakSubscriber ws
1073− case ms of
1074− Nothing -> return () --TODO: cleanup?
1075− Just s -> case s of
1076− SubscriberPush _ subscribed -> do
1077− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
1078− mapM_ invalidateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed)
1079− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
1080− SubscriberMerge _ subscribed -> do
1081− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
1082− oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1083− when (oldHeight /= invalidHeight) $ do
1084− writeIORef (mergeSubscribedHeight subscribed) $ invalidHeight
1085− mapM_ invalidateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed)
1086− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
1087− SubscriberFan subscribed -> do
1088− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
1089− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1090− forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ invalidateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ())
1091− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
1092− SubscriberHold _ -> return ()
1093− SubscriberSwitch subscribed -> do
1094− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
1095− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1096− when (oldHeight /= invalidHeight) $ do
1097− writeIORef (switchSubscribedHeight subscribed) $ invalidHeight
1098− mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1099− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
1100− SubscriberCoincidenceOuter subscribed -> do
1101− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
1102− invalidateCoincidenceHeight subscribed
1103− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
1104− SubscriberCoincidenceInner subscribed -> do
1105− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
1106− invalidateCoincidenceHeight subscribed
1107− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
1108−
1109−invalidateCoincidenceHeight :: CoincidenceSubscribed a -> IO ()
1110−invalidateCoincidenceHeight subscribed = do
1111− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1112− when (oldHeight /= invalidHeight) $ do
1113− writeIORef (coincidenceSubscribedHeight subscribed) $ invalidHeight
1114− mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed)
1115−
1116−--TODO: The recalculation algorithm seems a bit funky; make sure it doesn't miss stuff or hit stuff twice; also, it should probably be lazy
1117−
1118−recalculateSubscriberHeight :: WeakSubscriber a -> IO ()
1119−recalculateSubscriberHeight ws = do
1120− ms <- deRefWeakSubscriber ws
1121− case ms of
1122− Nothing -> return () --TODO: cleanup?
1123− Just s -> case s of
1124− SubscriberPush _ subscribed -> do
1125− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
1126− mapM_ recalculateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed)
1127− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
1128− SubscriberMerge _ subscribed -> do
1129− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
1130− oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1131− when (oldHeight == invalidHeight) $ do
1132− height <- calculateMergeHeight subscribed
1133− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1134− when (height /= invalidHeight) $ do -- If height == invalidHeight, that means some of the prereqs have not yet been recomputed; when they do recompute, they'll catch this node again --TODO: this is O(n*m), where n is the number of children of this noe and m is the number that have been invalidated
1135− writeIORef (mergeSubscribedHeight subscribed) height
1136− mapM_ recalculateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed)
1137− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
1138− SubscriberFan subscribed -> do
1139− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
1140− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1141− forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ recalculateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ())
1142− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
1143− SubscriberHold _ -> return ()
1144− SubscriberSwitch subscribed -> do
1145− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
1146− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1147− when (oldHeight == invalidHeight) $ do
1148− height <- calculateSwitchHeight subscribed
1149− when (height /= invalidHeight) $ do
1150− writeIORef (switchSubscribedHeight subscribed) height
1151− mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1152− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
1153− SubscriberCoincidenceOuter subscribed -> do
1154− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
1155− void $ recalculateCoincidenceHeight subscribed
1156− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
1157− SubscriberCoincidenceInner subscribed -> do
1158− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
1159− void $ recalculateCoincidenceHeight subscribed
1160− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
1161−
1162−recalculateCoincidenceHeight :: CoincidenceSubscribed a -> IO ()
1163−recalculateCoincidenceHeight subscribed = do
1164− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1165− when (oldHeight == invalidHeight) $ do
1166− height <- calculateCoincidenceHeight subscribed
1167− when (height /= invalidHeight) $ do
1168− writeIORef (coincidenceSubscribedHeight subscribed) height
1169− mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) --TODO: This should probably be mandatory, just like with the merge and switch ones
1170−
1171−calculateMergeHeight :: MergeSubscribed k -> IO Int
1172−calculateMergeHeight subscribed = if DMap.null (mergeSubscribedParents subscribed) then return 0 else do
1173− heights <- forM (DMap.toList $ mergeSubscribedParents subscribed) $ \(WrapArg _ :=> es) -> do
1174− readIORef $ eventSubscribedHeightRef es
1175− return $ if any (== invalidHeight) heights then invalidHeight else succ $ Prelude.maximum heights --TODO: Replace 'any' with invalidHeight-preserving 'maximum'
1176−
1177−calculateSwitchHeight :: SwitchSubscribed a -> IO Int
1178−calculateSwitchHeight subscribed = readIORef . eventSubscribedHeightRef =<< readIORef (switchSubscribedCurrentParent subscribed)
1179−
1180−calculateCoincidenceHeight :: CoincidenceSubscribed a -> IO Int
1181−calculateCoincidenceHeight subscribed = do
1182− outerHeight <- readIORef $ eventSubscribedHeightRef $ coincidenceSubscribedOuterParent subscribed
1183− innerHeight <- maybe (return 0) (readIORef . eventSubscribedHeightRef) =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1184− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1185−
1186−{-
1187−recalculateEventSubscribedHeight :: EventSubscribed a -> IO Int
1188−recalculateEventSubscribedHeight es = case es of
1189− EventSubscribedRoot _ -> return 0
1190− EventSubscribedNever -> return 0
1191− EventSubscribedPush subscribed -> recalculateEventSubscribedHeight $ pushSubscribedParent subscribed
1192− EventSubscribedMerge subscribed -> do
1193− oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1194− if oldHeight /= invalidHeight then return oldHeight else do
1195− height <- calculateMergeHeight subscribed
1196− writeIORef (mergeSubscribedHeight subscribed) height
1197− return height
1198− EventSubscribedFan _ subscribed -> recalculateEventSubscribedHeight $ fanSubscribedParent subscribed
1199− EventSubscribedSwitch subscribed -> do
1200− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1201− if oldHeight /= invalidHeight then return oldHeight else do
1202− height <- calculateSwitchHeight subscribed
1203− writeIORef (switchSubscribedHeight subscribed) height
1204− return height
1205− EventSubscribedCoincidence subscribed -> recalculateCoincidenceHeight subscribed
1206−-}
1207−
1208−data SomeSwitchSubscribed = forall a. SomeSwitchSubscribed (SwitchSubscribed a)
1209−
1210−debugInvalidate :: Bool
1211−debugInvalidate = False
1212−
1213−invalidate :: IORef [SomeSwitchSubscribed] -> WeakList Invalidator -> IO (WeakList Invalidator)
1214−invalidate toReconnectRef wis = do
1215− forM_ wis $ \wi -> do
1216− mi <- deRefWeak wi
1217− case mi of
1218− Nothing -> do
1219− when debugInvalidate $ liftIO $ putStrLn "invalidate Dead"
1220− return () --TODO: Should we clean this up here?
1221− Just i -> do
1222− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1223− case i of
1224− InvalidatorPull p -> do
1225− when debugInvalidate $ liftIO $ putStrLn "invalidate Pull"
1226− mVal <- readIORef $ pullValue p
1227− forM_ mVal $ \val -> do
1228− writeIORef (pullValue p) Nothing
1229− writeIORef (pullSubscribedInvalidators val) =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1230− InvalidatorSwitch subscribed -> do
1231− when debugInvalidate $ liftIO $ putStrLn "invalidate Switch"
1232− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1233− 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
1234−
1235−--------------------------------------------------------------------------------
1236−-- Reflex integration
1237−--------------------------------------------------------------------------------
1238−
1239−data Spider
1240−
1241−instance R.Reflex Spider where
1242− newtype Behavior Spider a = SpiderBehavior { unSpiderBehavior :: Behavior a }
1243− newtype Event Spider a = SpiderEvent { unSpiderEvent :: Event a }
1244− type PullM Spider = BehaviorM
1245− type PushM Spider = EventM
1246− {-# INLINE never #-}
1247− {-# INLINE constant #-}
1248− never = SpiderEvent EventNever
1249− constant = SpiderBehavior . BehaviorConst
1250− push f = SpiderEvent. push f . unSpiderEvent
1251− pull = SpiderBehavior . pull
1252− merge = SpiderEvent . merge . (unsafeCoerce :: DMap (WrapArg (R.Event Spider) k) -> DMap (WrapArg Event k))
1253− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
1254− switch = SpiderEvent . switch . (unsafeCoerce :: Behavior (R.Event Spider a) -> Behavior (Event a)) . unSpiderBehavior
1255− coincidence = SpiderEvent . coincidence . (unsafeCoerce :: Event (R.Event Spider a) -> Event (Event a)) . unSpiderEvent
1256−
1257−instance R.MonadSample Spider SpiderHost where
1258− {-# INLINE sample #-}
1259− sample = SpiderHost . readBehavior . unSpiderBehavior
1260−
1261−instance R.MonadHold Spider SpiderHost where
1262− hold v0 = SpiderHost . liftM SpiderBehavior . runFrame . hold v0 . unSpiderEvent
1263−
1264−instance R.MonadSample Spider BehaviorM where
1265− {-# INLINE sample #-}
1266− sample = readBehaviorTracked . unSpiderBehavior
1267−
1268−instance R.MonadSample Spider EventM where
1269− {-# INLINE sample #-}
1270− sample = liftIO . readBehavior . unSpiderBehavior
1271−
1272−instance R.MonadHold Spider EventM where
1273− {-# INLINE hold #-}
1274− hold v0 e = SpiderBehavior <$> hold v0 (unSpiderEvent e)
1275−
1276−newtype RootTrigger a = RootTrigger (IORef [WeakSubscriber a], IORef (Maybe a))
1277−
1278−instance R.ReflexHost Spider where
1279− type EventTrigger Spider = RootTrigger
1280− type EventHandle Spider = R.Event Spider
1281− type HostFrame Spider = SpiderHostFrame
1282−
1283−instance R.MonadReadEvent Spider ResultM where
1284− {-# INLINE readEvent #-}
1285− readEvent = liftM (fmap return) . readEvent . unSpiderEvent
1286−
1287−instance MonadRef EventM where
1288− type Ref EventM = Ref IO
1289− {-# INLINE newRef #-}
1290− {-# INLINE readRef #-}
1291− {-# INLINE writeRef #-}
1292− {-# INLINE atomicModifyRef #-}
1293− newRef = liftIO . newRef
1294− readRef = liftIO . readRef
1295− writeRef r a = liftIO $ writeRef r a
1296− atomicModifyRef r f = liftIO $ atomicModifyRef r f
1297−
1298−newtype SpiderHost a = SpiderHost { runSpiderHost :: IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO)
1299−
1300−newtype SpiderHostFrame a = SpiderHostFrame { runSpiderHostFrame :: EventM a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO)
1301−
1302−instance R.MonadSample Spider SpiderHostFrame where
1303− sample = SpiderHostFrame . R.sample --TODO: This can cause problems with laziness, so we should get rid of it if we can
1304−
1305−instance R.MonadHold Spider SpiderHostFrame where
1306− {-# INLINE hold #-}
1307− hold v0 e = SpiderHostFrame $ R.hold v0 e
1308−
1309−newEventWithTriggerIO :: (RootTrigger a -> IO (IO ())) -> IO (R.Event Spider a)
1310−newEventWithTriggerIO f = do
1311− occRef <- newIORef Nothing
1312− subscribedRef <- newIORef Nothing
1313− let !r = Root
1314− { rootOccurrence = occRef
1315− , rootSubscribed = subscribedRef
1316− , rootInit = f
1317− }
1318− return $ SpiderEvent $ EventRoot r
1319−
1320−instance R.MonadReflexCreateTrigger Spider SpiderHost where
1321− newEventWithTrigger = SpiderHost . newEventWithTriggerIO
1322−
1323−instance R.MonadReflexCreateTrigger Spider SpiderHostFrame where
1324− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . newEventWithTriggerIO
1325−
1326−instance R.MonadReflexHost Spider SpiderHost where
1327− fireEventsAndRead es a = SpiderHost $ run es a
1328− subscribeEvent e = SpiderHost $ do
1329− _ <- runFrame $ getEventSubscribed $ unSpiderEvent e --TODO: The result of this should actually be used
1330− return e
1331− runFrame = SpiderHost . runFrame
1332− runHostFrame = SpiderHost . runFrame . runSpiderHostFrame
1333−
1334−instance MonadRef SpiderHost where
1335− type Ref SpiderHost = Ref IO
1336− newRef = SpiderHost . newRef
1337− readRef = SpiderHost . readRef
1338− writeRef r = SpiderHost . writeRef r
1339− atomicModifyRef r = SpiderHost . atomicModifyRef r
1340−
1341−instance MonadRef SpiderHostFrame where
1342− type Ref SpiderHostFrame = Ref IO
1343− newRef = SpiderHostFrame . newRef
1344− readRef = SpiderHostFrame . readRef
1345− writeRef r = SpiderHostFrame . writeRef r
1346− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r