{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
-----------------------------------------------------------------------------------------
-- |
-- Module      :  FRP.Yampa.Event
-- Copyright   :  (c) Antony Courtney and Henrik Nilsson, Yale University, 2003
-- License     :  BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer  :  ivan.perez@keera.co.uk
-- Stability   :  provisional
-- Portability :  portable
--
-- Events in Yampa represent discrete time-signals, meaning those that do not
-- change continuously. Examples of event-carrying signals would be mouse
-- clicks (in between clicks it is assumed that there is no click), some
-- keyboard events, button presses on wiimotes or window-manager events.
--
-- The type 'Event' is isomorphic to 'Maybe' (@Event a = NoEvent | Event a@)
-- but, semantically, a 'Maybe'-carrying signal could change continuously,
-- whereas an 'Event'-carrying signal should not: for two events in subsequent
-- samples, there should be an small enough sampling frequency such that we sample
-- between those two samples and there are no 'Event's between them.
-- Nevertheless, no mechanism in Yampa will check this or misbehave if this
-- assumption is violated.
--
-- Events are essential for many other Yampa constructs, like switches (see
-- 'FRP.Yampa.Switches.switch' for details).
--
----------------------------------------------------------------------------
--
-- Note on naming conventions used in this module.
--
-- Names here might have to be rethought. It's really a bit messy.
-- In general, the aim has been short and convenient names (like 'tag',
-- 'attach', 'lMerge') and thus we have tried to stay away from suffixing/
-- prefixing conventions. E.g. 'Event' as a common suffix would be very
-- verbose.
--
-- However, part of the names come from a desire to stay close to similar
-- functions for the Maybe type. e.g. 'event', 'fromEvent', 'isEvent'.
-- In many cases, this use of 'Event' could be understood to refer to the
-- constructor 'Event', not to the type name 'Event'. Thus this use of
-- event should not be seen as a suffixing-with-type-name convention. But
-- that is obviously not easy to see, and, more over, interpreting 'Event'
-- as the name of the type might make equally good or better sense. E.g.
-- 'fromEvent' can also be seen as a function taking an event signal,
-- which is a partial function on time, to a normal signal. The latter is
-- then undefined when the source event function is undefined.
--
-- In other cases, it has been necessary to somehow stay out of the way of
-- names used by the prelude or other commonly imported modules/modules
-- which could be expected to be used heavily in Yampa code. In those cases
-- a suffix 'E' have been added. Examples are 'filterE' (exists in Prelude)
-- and 'joinE' (exists in Monad). Maybe the suffix isn't necessary in the
-- last case.
--
-- Some functions (actually only one currently, 'mapFilterE') have got an 'E'
-- suffix just because they're closely related (by name or semantics) to one
-- which already has an 'E' suffix. Another candidate would be 'splitE' to
-- complement 'joinE'. But events carrying pairs could obviously have other
-- sources than a 'joinE', so currently it is called 'split'.
--
-- 2003-05-19: Actually, have now changed to 'splitE' to avoid a clash
-- with the method 'split' in the class RandomGen.
--
-- 2003-05-19: What about 'gate'? Stands out compared to e.g. 'filterE'.
--
-- Currently the 'E' suffix is considered an exception. Maybe we should use
-- completely different names to avoid the 'E' suffix. If the functions
-- are not used that often, 'Event' might be approriate. Alternatively the
-- suffix 'E' should be adopted globaly (except if the name already contains
-- 'event' in some form?).
--
-- Arguably, having both a type 'Event' and a constructor 'Event' is confusing
-- since there are more than one constructor. But the name 'Event' for the
-- constructor is quite apt. It's really the type name that is wrong. But
-- no one has found a better name, and changing it would be a really major
-- undertaking. Yes, the constructor 'Event' is not exported, but we still
-- need to talk conceptually about them. On the other hand, if we consider
-- Event-signals as partial functions on time, maybe it isn't so confusing:
-- they just don't have a value between events, so 'NoEvent' does not really
-- exist conceptually.
-----------------------------------------------------------------------------------------

module FRP.Yampa.Event where

-- Event is an instance of Functor, Eq, and Ord. Some method instances:
-- fmap :: (a -> b) -> Event a -> Event b
-- (==)     :: Event a -> Event a -> Bool
-- (<=) :: Event a -> Event a -> Bool

import Control.Applicative
import Control.DeepSeq (NFData(..))
import qualified Control.Monad.Fail as Fail

import FRP.Yampa.Diagnostics


infixl 8 `tag`, `attach`, `gate`
infixl 7 `joinE`
infixl 6 `lMerge`, `rMerge`, `merge`


------------------------------------------------------------------------------
-- The Event type
------------------------------------------------------------------------------

-- The type Event represents a single possible event occurrence.
-- It is isomorphic to Maybe, but its constructors are not exposed outside
-- the AFRP implementation.
-- There could possibly be further constructors, but note that the NeverEvent-
-- idea does not work, at least not in the current AFRP implementation.
-- Also note that it unfortunately is possible to partially break the
-- abstractions through judicious use of e.g. snap and switching.

-- | A single possible event occurrence, that is, a value that may or may
-- not occur. Events are used to represent values that are not produced
-- continuously, such as mouse clicks (only produced when the mouse is clicked,
-- as opposed to mouse positions, which are always defined).
data Event a = NoEvent | Event a deriving (Int -> Event a -> ShowS
[Event a] -> ShowS
Event a -> String
(Int -> Event a -> ShowS)
-> (Event a -> String) -> ([Event a] -> ShowS) -> Show (Event a)
forall a. Show a => Int -> Event a -> ShowS
forall a. Show a => [Event a] -> ShowS
forall a. Show a => Event a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [Event a] -> ShowS
$cshowList :: forall a. Show a => [Event a] -> ShowS
show :: Event a -> String
$cshow :: forall a. Show a => Event a -> String
showsPrec :: Int -> Event a -> ShowS
$cshowsPrec :: forall a. Show a => Int -> Event a -> ShowS
Show)

-- | Make the NoEvent constructor available. Useful e.g. for initialization,
-- ((-->) & friends), and it's easily available anyway (e.g. mergeEvents []).
noEvent :: Event a
noEvent :: Event a
noEvent = Event a
forall a. Event a
NoEvent


-- | Suppress any event in the first component of a pair.
noEventFst :: (Event a, b) -> (Event c, b)
noEventFst :: (Event a, b) -> (Event c, b)
noEventFst (Event a
_, b
b) = (Event c
forall a. Event a
NoEvent, b
b)


-- | Suppress any event in the second component of a pair.
noEventSnd :: (a, Event b) -> (a, Event c)
noEventSnd :: (a, Event b) -> (a, Event c)
noEventSnd (a
a, Event b
_) = (a
a, Event c
forall a. Event a
NoEvent)


-- | Eq instance (equivalent to derived instance)
instance Eq a => Eq (Event a) where
    -- | Equal if both NoEvent or both Event carrying equal values.
    Event a
NoEvent   == :: Event a -> Event a -> Bool
== Event a
NoEvent   = Bool
True
    (Event a
x) == (Event a
y) = a
x a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
y
    Event a
_         == Event a
_         = Bool
False


-- | Ord instance (equivalent to derived instance)
instance Ord a => Ord (Event a) where
    -- | NoEvent is smaller than Event, Event x < Event y if x < y
    compare :: Event a -> Event a -> Ordering
compare Event a
NoEvent   Event a
NoEvent   = Ordering
EQ
    compare Event a
NoEvent   (Event a
_) = Ordering
LT
    compare (Event a
_) Event a
NoEvent   = Ordering
GT
    compare (Event a
x) (Event a
y) = a -> a -> Ordering
forall a. Ord a => a -> a -> Ordering
compare a
x a
y

-- | Functor instance (could be derived).
instance Functor Event where
    -- | Apply function to value carried by 'Event', if any.
    fmap :: (a -> b) -> Event a -> Event b
fmap a -> b
_ Event a
NoEvent   = Event b
forall a. Event a
NoEvent
    fmap a -> b
f (Event a
a) = b -> Event b
forall a. a -> Event a
Event (a -> b
f a
a)


-- | Applicative instance (similar to 'Maybe').
instance Applicative Event where
    -- | Wrap a pure value in an 'Event'.
    pure :: a -> Event a
pure = a -> Event a
forall a. a -> Event a
Event
    -- | If any value (function or arg) is 'NoEvent', everything is.
    Event (a -> b)
NoEvent <*> :: Event (a -> b) -> Event a -> Event b
<*> Event a
_ = Event b
forall a. Event a
NoEvent
    Event a -> b
f <*> Event a
x = a -> b
f (a -> b) -> Event a -> Event b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Event a
x

-- | Monad instance
instance Monad Event where
    -- | Combine events, return 'NoEvent' if any value in the
    -- sequence is 'NoEvent'.
    (Event a
x) >>= :: Event a -> (a -> Event b) -> Event b
>>= a -> Event b
k = a -> Event b
k a
x
    Event a
NoEvent  >>= a -> Event b
_  = Event b
forall a. Event a
NoEvent

    >> :: Event a -> Event b -> Event b
(>>) = Event a -> Event b -> Event b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
(*>)

    -- | See 'pure'.
    return :: a -> Event a
return          = a -> Event a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

#if !(MIN_VERSION_base(4,13,0))
    -- | Fail with 'NoEvent'.
    fail            = Fail.fail
#endif

instance Fail.MonadFail Event where
    -- | Fail with 'NoEvent'.
    fail :: String -> Event a
fail String
_          = Event a
forall a. Event a
NoEvent

-- | Alternative instance
instance Alternative Event where
    -- | An empty alternative carries no event, so it is ignored.
    empty :: Event a
empty = Event a
forall a. Event a
NoEvent
    -- | Merge favouring the left event ('NoEvent' only if both are
    -- 'NoEvent').
    Event a
NoEvent <|> :: Event a -> Event a -> Event a
<|> Event a
r = Event a
r
    Event a
l       <|> Event a
_ = Event a
l

-- | NFData instance
instance NFData a => NFData (Event a) where
    -- | Evaluate value carried by event.
    rnf :: Event a -> ()
rnf Event a
NoEvent   = ()
    rnf (Event a
a) = a -> ()
forall a. NFData a => a -> ()
rnf a
a () -> () -> ()
`seq` ()

------------------------------------------------------------------------------
-- Internal utilities for event construction
------------------------------------------------------------------------------

-- These utilities are to be considered strictly internal to AFRP for the
-- time being.

-- | Convert a maybe value into a event ('Event' is isomorphic to 'Maybe').
maybeToEvent :: Maybe a -> Event a
maybeToEvent :: Maybe a -> Event a
maybeToEvent Maybe a
Nothing  = Event a
forall a. Event a
NoEvent
maybeToEvent (Just a
a) = a -> Event a
forall a. a -> Event a
Event a
a


------------------------------------------------------------------------------
-- Utility functions similar to those available for Maybe
------------------------------------------------------------------------------

-- | An event-based version of the maybe function.
event :: a -> (b -> a) -> Event b -> a
event :: a -> (b -> a) -> Event b -> a
event a
a b -> a
_ Event b
NoEvent   = a
a
event a
_ b -> a
f (Event b
b) = b -> a
f b
b

-- | Extract the value from an event. Fails if there is no event.
fromEvent :: Event a -> a
fromEvent :: Event a -> a
fromEvent (Event a
a) = a
a
fromEvent Event a
NoEvent   = String -> String -> String -> a
forall a. String -> String -> String -> a
usrErr String
"AFRP" String
"fromEvent" String
"Not an event."

-- | Tests whether the input represents an actual event.
isEvent :: Event a -> Bool
isEvent :: Event a -> Bool
isEvent Event a
NoEvent   = Bool
False
isEvent (Event a
_) = Bool
True

-- | Negation of 'isEvent'.
isNoEvent :: Event a -> Bool
isNoEvent :: Event a -> Bool
isNoEvent = Bool -> Bool
not (Bool -> Bool) -> (Event a -> Bool) -> Event a -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Event a -> Bool
forall a. Event a -> Bool
isEvent


------------------------------------------------------------------------------
-- Event tagging
------------------------------------------------------------------------------

-- | Tags an (occurring) event with a value ("replacing" the old value).
--
-- Applicative-based definition:
--  tag = ($>)
tag :: Event a -> b -> Event b
Event a
e tag :: Event a -> b -> Event b
`tag` b
b = (a -> b) -> Event a -> Event b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (b -> a -> b
forall a b. a -> b -> a
const b
b) Event a
e

-- | Tags an (occurring) event with a value ("replacing" the old value). Same
-- as 'tag' with the arguments swapped.
--
-- Applicative-based definition:
-- tagWith = (<$)
tagWith :: b -> Event a -> Event b
tagWith :: b -> Event a -> Event b
tagWith = (Event a -> b -> Event b) -> b -> Event a -> Event b
forall a b c. (a -> b -> c) -> b -> a -> c
flip Event a -> b -> Event b
forall a b. Event a -> b -> Event b
tag

-- | Attaches an extra value to the value of an occurring event.
attach :: Event a -> b -> Event (a, b)
Event a
e attach :: Event a -> b -> Event (a, b)
`attach` b
b = (a -> (a, b)) -> Event a -> Event (a, b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\a
a -> (a
a, b
b)) Event a
e


------------------------------------------------------------------------------
-- Event merging (disjunction) and joining (conjunction)
------------------------------------------------------------------------------

-- !!! I think this is too complicated. rMerge can be obtained simply by
-- !!! swapping the arguments. So the only time it is possibly of any
-- !!! interest is for partial app. "merge" is inherently dangerous.
-- !!! But this is NOT obvious from its type: it's type is just like
-- !!! the others. This is the only example of such a def.
-- !!! Finally: mergeEvents is left-biased, but this is not reflected in
-- !!! its name.

-- | Left-biased event merge (always prefer left event, if present).
lMerge :: Event a -> Event a -> Event a
lMerge :: Event a -> Event a -> Event a
lMerge = Event a -> Event a -> Event a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
(<|>)


-- | Right-biased event merge (always prefer right event, if present).
rMerge :: Event a -> Event a -> Event a
rMerge :: Event a -> Event a -> Event a
rMerge = (Event a -> Event a -> Event a) -> Event a -> Event a -> Event a
forall a b c. (a -> b -> c) -> b -> a -> c
flip Event a -> Event a -> Event a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
(<|>)


-- | Unbiased event merge: simultaneous occurrence is an error.
merge :: Event a -> Event a -> Event a
merge :: Event a -> Event a -> Event a
merge = (a -> a -> a) -> Event a -> Event a -> Event a
forall a. (a -> a -> a) -> Event a -> Event a -> Event a
mergeBy (String -> String -> String -> a -> a -> a
forall a. String -> String -> String -> a
usrErr String
"AFRP" String
"merge" String
"Simultaneous event occurrence.")


-- | Event merge parameterized by a conflict resolution function.
--
-- Applicative-based definition:
-- mergeBy f le re = (f <$> le <*> re) <|> le <|> re
mergeBy :: (a -> a -> a) -> Event a -> Event a -> Event a
mergeBy :: (a -> a -> a) -> Event a -> Event a -> Event a
mergeBy a -> a -> a
_       Event a
NoEvent      Event a
NoEvent      = Event a
forall a. Event a
NoEvent
mergeBy a -> a -> a
_       le :: Event a
le@(Event a
_) Event a
NoEvent      = Event a
le
mergeBy a -> a -> a
_       Event a
NoEvent      re :: Event a
re@(Event a
_) = Event a
re
mergeBy a -> a -> a
resolve (Event a
l)    (Event a
r)    = a -> Event a
forall a. a -> Event a
Event (a -> a -> a
resolve a
l a
r)

-- | A generic event merge-map utility that maps event occurrences,
-- merging the results. The first three arguments are mapping functions,
-- the third of which will only be used when both events are present.
-- Therefore, 'mergeBy' = 'mapMerge' 'id' 'id'
--
-- Applicative-based definition:
-- mapMerge lf rf lrf le re = (f <$> le <*> re) <|> (lf <$> le) <|> (rf <$> re)
mapMerge :: (a -> c) -> (b -> c) -> (a -> b -> c)
            -> Event a -> Event b -> Event c
mapMerge :: (a -> c)
-> (b -> c) -> (a -> b -> c) -> Event a -> Event b -> Event c
mapMerge a -> c
_  b -> c
_  a -> b -> c
_   Event a
NoEvent   Event b
NoEvent   = Event c
forall a. Event a
NoEvent
mapMerge a -> c
lf b -> c
_  a -> b -> c
_   (Event a
l) Event b
NoEvent   = c -> Event c
forall a. a -> Event a
Event (a -> c
lf a
l)
mapMerge a -> c
_  b -> c
rf a -> b -> c
_   Event a
NoEvent   (Event b
r) = c -> Event c
forall a. a -> Event a
Event (b -> c
rf b
r)
mapMerge a -> c
_  b -> c
_  a -> b -> c
lrf (Event a
l) (Event b
r) = c -> Event c
forall a. a -> Event a
Event (a -> b -> c
lrf a
l b
r)

-- | Merge a list of events; foremost event has priority.
--
-- Foldable-based definition:
-- mergeEvents :: Foldable t => t (Event a) -> Event a
-- mergeEvents =  asum
mergeEvents :: [Event a] -> Event a
mergeEvents :: [Event a] -> Event a
mergeEvents = (Event a -> Event a -> Event a) -> Event a -> [Event a] -> Event a
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Event a -> Event a -> Event a
forall a. Event a -> Event a -> Event a
lMerge Event a
forall a. Event a
NoEvent

-- | Collect simultaneous event occurrences; no event if none.
--
-- Traverable-based definition:
-- catEvents :: Foldable t => t (Event a) -> Event (t a)
-- carEvents e  = if (null e) then NoEvent else (sequenceA e)
catEvents :: [Event a] -> Event [a]
catEvents :: [Event a] -> Event [a]
catEvents [Event a]
eas = case [ a
a | Event a
a <- [Event a]
eas ] of
                    [] -> Event [a]
forall a. Event a
NoEvent
                    [a]
as -> [a] -> Event [a]
forall a. a -> Event a
Event [a]
as

-- | Join (conjunction) of two events. Only produces an event
-- if both events exist.
--
-- Applicative-based definition:
-- joinE = liftA2 (,)
joinE :: Event a -> Event b -> Event (a,b)
joinE :: Event a -> Event b -> Event (a, b)
joinE Event a
NoEvent   Event b
_         = Event (a, b)
forall a. Event a
NoEvent
joinE Event a
_         Event b
NoEvent   = Event (a, b)
forall a. Event a
NoEvent
joinE (Event a
l) (Event b
r) = (a, b) -> Event (a, b)
forall a. a -> Event a
Event (a
l,b
r)


-- | Split event carrying pairs into two events.
splitE :: Event (a,b) -> (Event a, Event b)
splitE :: Event (a, b) -> (Event a, Event b)
splitE Event (a, b)
NoEvent       = (Event a
forall a. Event a
NoEvent, Event b
forall a. Event a
NoEvent)
splitE (Event (a
a,b
b)) = (a -> Event a
forall a. a -> Event a
Event a
a, b -> Event b
forall a. a -> Event a
Event b
b)


------------------------------------------------------------------------------
-- Event filtering
------------------------------------------------------------------------------

-- | Filter out events that don't satisfy some predicate.
filterE :: (a -> Bool) -> Event a -> Event a
filterE :: (a -> Bool) -> Event a -> Event a
filterE a -> Bool
p e :: Event a
e@(Event a
a) = if a -> Bool
p a
a then Event a
e else Event a
forall a. Event a
NoEvent
filterE a -> Bool
_ Event a
NoEvent     = Event a
forall a. Event a
NoEvent


-- | Combined event mapping and filtering. Note: since 'Event' is a 'Functor',
-- see 'fmap' for a simpler version of this function with no filtering.
mapFilterE :: (a -> Maybe b) -> Event a -> Event b
mapFilterE :: (a -> Maybe b) -> Event a -> Event b
mapFilterE a -> Maybe b
_ Event a
NoEvent   = Event b
forall a. Event a
NoEvent
mapFilterE a -> Maybe b
f (Event a
a) = case a -> Maybe b
f a
a of
                            Maybe b
Nothing -> Event b
forall a. Event a
NoEvent
                            Just b
b  -> b -> Event b
forall a. a -> Event a
Event b
b


-- | Enable/disable event occurences based on an external condition.
gate :: Event a -> Bool -> Event a
Event a
_ gate :: Event a -> Bool -> Event a
`gate` Bool
False = Event a
forall a. Event a
NoEvent
Event a
e `gate` Bool
True  = Event a
e