summaryrefslogtreecommitdiffstats
path: root/lib/Phi/Phi.hs
blob: 3f4b59ba60ecaf216aefedb24fe07b6f4daeea41 (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
{-# LANGUAGE ExistentialQuantification, DeriveDataTypeable, StandaloneDeriving #-}

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

import Control.Concurrent.Chan
import Control.Monad
import Control.Monad.IO.Class

import Data.Typeable

data Phi = Phi (Chan Message)

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

data DefaultMessage = Repaint 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 newChan

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

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

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