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