@@ -0,0 +1,239 @@
1+{-# LANGUAGE DeriveDataTypeable #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE MultiParamTypeClasses #-}
4+{-# LANGUAGE RecursiveDo #-}
5+{-# LANGUAGE ScopedTypeVariables #-}
6+#ifdef USER_TEMPLATE_HASKELL
7+{-# LANGUAGE TemplateHaskell #-}
9+{-# LANGUAGE TypeFamilies #-}
10+module Reflex.Time where
14+import Reflex.PerformEvent.Class
15+import Reflex.PostBuild.Class
16+import Reflex.TriggerEvent.Class
18+import Control.Concurrent
19+import qualified Control.Concurrent.Thread.Delay as Concurrent
22+import Control.Monad.Fix
23+import Control.Monad.IO.Class
26+import Data.Sequence (Seq, (|>))
27+import qualified Data.Sequence as Seq
29+import Data.Time.Clock
34+ = TickInfo { _tickInfo_lastUTC :: UTCTime
35+ -- ^ UTC time immediately after the last tick.
36+ , _tickInfo_n :: Integer
37+ -- ^ Number of time periods since t0
38+ , _tickInfo_alreadyElapsed :: NominalDiffTime
39+ -- ^ Amount of time already elapsed in the current tick period.
41+ deriving (Eq, Ord, Show, Typeable)
43+-- | Special case of tickLossyFrom that uses the post-build event to start the
45+tickLossy :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> UTCTime -> m (Event t TickInfo)
46+tickLossy dt t0 = tickLossyFrom dt t0 =<< getPostBuild
48+-- | Send events over time with the given basis time and interval
49+-- If the system starts running behind, occurrences will be dropped rather than buffered
50+-- Each occurrence of the resulting event will contain the index of the current interval, with 0 representing the basis time
52+ :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
56+ -- ^ Event that starts a tick generation thread. Usually you want this to
57+ -- be something like the result of getPostBuild that only fires once. But
58+ -- there could be uses for starting multiple timer threads.
59+ -> m (Event t TickInfo)
60+tickLossyFrom dt t0 e = tickLossyFrom' $ (dt, t0) <$ e
62+-- | Generalization of tickLossyFrom that takes dt and t0 in the event.
64+ :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
65+ => Event t (NominalDiffTime, UTCTime)
66+ -- ^ Event that starts a tick generation thread. Usually you want this to
67+ -- be something like the result of getPostBuild that only fires once. But
68+ -- there could be uses for starting multiple timer threads.
69+ -> m (Event t TickInfo)
71+ rec result <- performEventAsync $ callAtNextInterval <$> leftmost [e, snd <$> result]
72+ return $ fst <$> result
73+ where callAtNextInterval pair cb = void $ liftIO $ forkIO $ do
74+ tick <- uncurry getCurrentTick pair
75+ Concurrent.delay $ ceiling $ (fst pair - _tickInfo_alreadyElapsed tick) * 1000000
78+clockLossy :: (MonadIO m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), PostBuild t m, MonadHold t m, MonadFix m) => NominalDiffTime -> UTCTime -> m (Dynamic t TickInfo)
80+ initial <- liftIO $ getCurrentTick dt t0
84+getCurrentTick :: NominalDiffTime -> UTCTime -> IO TickInfo
85+getCurrentTick dt t0 = do
87+ let offset = t `diffUTCTime` t0
88+ (n, alreadyElapsed) = offset `divMod'` dt
89+ return $ TickInfo t n alreadyElapsed
91+-- | Delay an Event's occurrences by a given amount in seconds.
92+delay :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
93+delay dt e = performEventAsync $ ffor e $ \a cb -> liftIO $ void $ forkIO $ do
94+ Concurrent.delay $ ceiling $ dt * 1000000
97+-- | Send events with Poisson timing with the given basis and rate
98+-- Each occurence of the resulting event will contain the index of
99+-- the current interval, with 0 representing the basis time
101+ :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
104+ -- ^ Poisson event rate (Hz)
106+ -- ^ Baseline time for events
108+ -- ^ Event that starts a tick generation thread. Usually you want this to
109+ -- be something like the result of getPostBuild that only fires once. But
110+ -- there could be uses for starting multiple timer threads.
111+ -- Start sending events in response to the event parameter.
112+ -> m (Event t TickInfo)
113+poissonLossyFrom rnd rate = inhomogeneousPoissonFrom rnd (constant rate) rate
116+-- | Send events with Poisson timing with the given basis and rate
117+-- Each occurence of the resulting event will contain the index of
118+-- the current interval, with 0 representing the basis time.
119+-- Automatically begin sending events when the DOM is built
121+ :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
124+ -- ^ Poisson event rate (Hz)
126+ -- ^ Baseline time for events
127+ -> m (Event t TickInfo)
128+poissonLossy rnd rate t0 = poissonLossyFrom rnd rate t0 =<< getPostBuild
130+-- | Send events with inhomogeneous Poisson timing with the given basis
131+-- and variable rate. Provide a maxRate that you expect to support.
132+inhomogeneousPoissonFrom
133+ :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
135+ -> Behavior t Double
139+ -> m (Event t TickInfo)
140+inhomogeneousPoissonFrom rnd rate maxRate t0 e = do
142+ -- Create a thread for producing homogeneous poisson events
143+ -- along with random Doubles (usage of Double's explained below)
144+ ticksWithRateRand <- performEventAsync $
145+ fmap callAtNextInterval e
147+ -- Filter homogeneous events according to associated
148+ -- random values and the current rate parameter
149+ return $ attachWithMaybe filterFun rate ticksWithRateRand
153+ -- Inhomogeneous poisson processes are built from faster
154+ -- homogeneous ones by randomly dropping events from the
155+ -- fast process. For each fast homogeneous event, choose
156+ -- a uniform random sample from (0, rMax). If the
157+ -- inhomogeneous rate at this moment is greater than the
158+ -- random sample, then keep this event, otherwise drop it
159+ filterFun :: Double -> (TickInfo, Double) -> Maybe TickInfo
160+ filterFun r (tInfo, p)
161+ | r >= p = Just tInfo
162+ | otherwise = Nothing
164+ callAtNextInterval _ cb = void $ liftIO $ forkIO $ go t0 rnd cb 0
166+ go tTargetLast lastGen cb lastN = do
169+ -- Generate random numbers for this poisson interval (u)
170+ -- and sample-retention likelihood (p)
171+ let (u, nextGen) = randomR (0,1) lastGen
172+ (p :: Double, nextGen') = randomR (0,maxRate) nextGen
174+ -- Inter-event interval is drawn from exponential
175+ -- distribution accourding to u
176+ let dt = realToFrac $ (-1) * log u / maxRate :: NominalDiffTime
178+ alreadyElapsed = diffUTCTime t tTargetLast
179+ tTarget = addUTCTime dt tTargetLast
180+ thisDelay = realToFrac $ diffUTCTime tTarget t :: Double
181+ Concurrent.delay $ ceiling $ thisDelay * 1000000
182+ _ <- cb (TickInfo t nEvents alreadyElapsed, p)
183+ go tTarget nextGen' cb nEvents
185+-- | Send events with inhomogeneous Poisson timing with the given basis
186+-- and variable rate. Provide a maxRate that you expect to support
188+ :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
190+ -> Behavior t Double
193+ -> m (Event t TickInfo)
194+inhomogeneousPoisson rnd rate maxRate t0 =
195+ inhomogeneousPoissonFrom rnd rate maxRate t0 =<< getPostBuild
197+-- | Block occurrences of an Event until the given number of seconds elapses without
198+-- the Event firing, at which point the last occurrence of the Event will fire.
199+debounce :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
201+ n :: Dynamic t Integer <- count e
202+ let tagged = attachPromptlyDynWith (,) n e
203+ delayed <- delay dt tagged
204+ return $ attachWithMaybe (\n' (t, v) -> if n' == t then Just v else Nothing) (current n) delayed
206+-- | When the given 'Event' occurs, wait the given amount of time and collect
207+-- all occurrences during that time. Then, fire the output 'Event' with the
209+batchOccurrences :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t (Seq a))
210+batchOccurrences t newValues = do
211+ let f s x = (Just newState, out)
212+ where newState = case x of
215+ These a _ -> Seq.singleton a
217+ This _ -> if Seq.null s then Just () else Nothing
219+ These _ _ -> Just ()
220+ rec (buffer, toDelay) <- mapAccumMaybe f mempty $ align newValues delayed
221+ delayed <- delay t toDelay
222+ return $ tag buffer delayed
224+#ifdef USE_TEMPLATE_HASKELL
225+makeLensesWith (lensRules & simpleLenses .~ True) ''TickInfo
227+tickInfo_lastUTC :: Lens' TickInfo UTCTime
228+tickInfo_lastUTC f (TickInfo x1 x2 x3) = (\y -> TickInfo y x2 x3) <$> f x1
229+{-# INLINE tickInfo_lastUTC #-}
231+tickInfo_n :: Lens' TickInfo Integer
232+tickInfo_n f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 y x3) <$> f x1
233+{-# INLINE tickInfo_n #-}
235+tickInfo_alreadyElapsed :: Lens' TickInfo NominalDiffTime
236+tickInfo_alreadyElapsed f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 x2 y) <$> f x1
237+{-# INLINE tickInfo_alreadyElapsed #-}