summaryrefslogtreecommitdiffstats
path: root/lib/Phi/Phi.hs
blob: 4a896c76d48901fada4eb36e6e2b69f5b172b8c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{-# LANGUAGE ExistentialQuantification, DeriveDataTypeable, StandaloneDeriving #-}

module Phi.Phi ( Phi
               , Message
               , DefaultMessage(..)
               , fromMessage
               , initPhi
               , dupPhi
               , sendMessage
               , sendMessages
               , receiveMessage
               , messageAvailable
               ) where

import Control.Concurrent.STM
import Control.Monad
import Control.Monad.IO.Class

import Data.Typeable

data Phi = Phi !(TChan Message)

data Message = forall a. (Typeable a, Show a) => Message a
deriving instance Show Message

data DefaultMessage = Repaint | ResetBackground | Shutdown | HoldShutdown | ReleaseShutdown deriving (Typeable, Show)

fromMessage :: (Typeable a, Show a) => Message -> Maybe a
fromMessage (Message m) = cast m

initPhi :: MonadIO m => m Phi
initPhi = liftM Phi $ liftIO $ atomically newTChan

dupPhi :: MonadIO m => Phi -> m Phi
dupPhi (Phi chan) = liftM Phi $ liftIO $ atomically $ dupTChan chan

sendMessage :: (MonadIO m, Typeable a, Show a) => Phi -> a -> m ()
sendMessage (Phi chan) = liftIO . atomically . writeTChan chan . Message

sendMessages :: (MonadIO m, Typeable a, Show a) => Phi -> [a] -> m ()
sendMessages (Phi chan) = liftIO . atomically . mapM_ (writeTChan chan . Message)

receiveMessage :: MonadIO m => Phi -> m Message
receiveMessage (Phi chan) = liftIO $ atomically $ readTChan chan

messageAvailable :: MonadIO m => Phi -> m Bool
messageAvailable (Phi chan) = liftIO $ liftM not $ atomically $ isEmptyTChan chan