Fix alignment.
[matthijs/projects/fpprac.git] / FPPrac.hs
1 {-# LANGUAGE RecordWildCards, ExistentialQuantification #-}
2 module FPPrac (
3         Request(..),
4         Response(..),
5         TinaProgram(..),
6         Color, Rect(..), Point(..),
7         rgb, pt, point,
8         runTina
9 ) where
10
11 import qualified Graphics.UI.Gtk as Gtk
12 import Graphics.UI.Gtk (AttrOp(..)) -- For the := constructor
13 import qualified Graphics.Rendering.Cairo as Cairo
14 import qualified Graphics.UI.Gtk.Gdk.EventM as EventM
15
16 import Control.Monad.Trans -- for liftIO
17 import Data.IORef
18 import Control.Applicative
19 import Control.Monad
20 import Char
21 import System.Exit
22
23 -- | A rectangle in two dimensional space
24 data Rect = Rect 
25         { rectLeft :: !Int
26         , rectTop :: !Int
27         , rectWidth :: !Int
28         , rectHeight :: !Int
29 } deriving (Show, Eq)
30
31 data Point = Point !Int !Int deriving (Show, Eq)
32
33 type Color = Gtk.Color
34
35 -- Create a Color from Red, Green and Blue values. The inputs should be
36 -- between 0 and 255 (inclusive).
37 rgb :: Int -> Int -> Int -> Color
38 rgb r g b = Gtk.Color (conv r) (conv g) (conv b)
39         where conv = fromInteger . toInteger . (*256)
40
41 -- | Some predefined colours
42 red = rgb 0xff 0 0
43 green = rgb 0 0xff 0
44 blue = rgb 0 0 0xff
45 white = rgb 0xff 0xff 0xff
46
47 -- | Helper functions for creating a Point
48 point, pt :: Int -> Int -> Point
49 point = Point
50 pt = Point
51
52 data Request
53         = GfxLines      Color   [Point]                 -- coloured line through a list of points
54         | GfxPolygon    Color   [Point]                 -- filled polygon of given colour
55         | GfxPicture    FilePath Point                  -- shows a picture
56         | GfxText       Color    Point  String          -- coloured string on position Point
57         | GfxRectangle  Color    Rect                   -- filled rectangle of given colour
58         | GfxEllipse    Color    Rect                   -- ellipse within given rectangle
59         | GfxDisc       Color    Rect                   -- filled ellipse within given rectangle
60         | GfxClear                                      -- clears the graphical window
61         -- | GfxInstance   Bool
62         | GfxFont       String   Int                    -- changes to fontname of given size
63         | WinPrompt     String   String String          -- pops up a window with an edit field
64         -- | WinFilePrompt Bool
65         | WinMenu       [(String,[String])]             -- adds a menu list to the graphical window
66         | WinTitle      String                          -- gives a title to the graphical window
67         | FRead         String                          -- read file with a given name
68         | FWrite        String   String                 -- writes a text file with a given filename
69         | ReqQuit                                       -- quits the graphical system
70         deriving Show
71
72 data Response
73         = KeyIn            Char                         -- touched key with given character
74         | MouseDoubleClick Point                        -- mouse event on position Point
75         | MouseDragged     Point                        -- ibid
76         | MouseDown        Point                        -- ibid
77         | MouseUp          Point                        -- ibid
78         | MenuItem         String String                -- selected item from WinMenu with a given name
79         | PromptResponse   String String String         -- response to WinPrompt request
80         | FileContents     String String                -- response to FRead request
81         deriving Show
82
83 type TinaStep s = s -> Response -> (s,[Request])
84 data TinaProgram = forall s. Main
85         { initialState    :: s
86         , initialRequests :: [Request]
87         , eventHandler    :: TinaStep s
88         , windowWidth
89         , windowHeight    :: Int
90         }
91
92 testProg = Main
93         { initialState    = 1
94         , initialRequests = [GfxText red (pt 0 0) "foo", GfxText blue (pt 100 100) "bar"]
95         , eventHandler    = \s e -> (s+1,[GfxText green (pt 50 50) $ show (s,e)])
96         , windowWidth     = 200
97         , windowHeight    = 200
98         }
99
100 data IState = forall s. IS
101         { {-sFrame    :: Frame    ()
102         , sPanel    :: Panel    ()
103         , buffer    :: MemoryDC ()
104         , -}postponed :: IORef [Request]
105         , usrState  :: IORef s
106         , usrProg   :: TinaStep s
107         }
108
109 processPostponed :: IState -> IO ()
110 processPostponed s@IS {..} = do
111         ps <- readIORef postponed
112         unless (null ps) $ do
113                 writeIORef postponed (tail ps)
114                 rs  <- handle s (head ps)
115                 mapM (stepUserProgram s) rs
116                 processPostponed s
117
118 post s r = stepUserProgram s r >> processPostponed s
119
120 stepUserProgram :: IState -> Response -> IO ()
121 stepUserProgram IS {..} r = do
122         state <- readIORef usrState
123         let (state',reqs) = usrProg state r
124         writeIORef usrState state'
125         readIORef postponed >>= writeIORef postponed . (++ reqs)
126
127 handle :: IState -> Request -> IO [Response]
128 handle s@IS {..} r = do
129         resps <- maybe (fail $ "No handler for request " ++ show r) id $
130                 fmap (>> return []) (gfxHandler s r <|> winHandler s r <|> miscHandler s r)
131         return resps
132
133 runTina :: TinaProgram -> IO ()
134 runTina Main {..} = do
135         usrState  <- newIORef initialState
136         postponed <- newIORef (GfxText (rgb 0 0 0) (pt 50 50) "foo" : GfxClear :initialRequests)
137         let state = IS { usrProg = eventHandler, .. }
138         runGUI {-(sz windowWidth windowHeight) -}state
139
140 runGUI :: {-Size ->-} IState -> IO ()
141 runGUI s = do
142         -- Init GTK.
143         Gtk.initGUI
144         
145         -- Create a window, which will make the mainloop terminated when
146         -- it is closed.
147         window <- Gtk.windowNew
148         Gtk.set window [ Gtk.containerBorderWidth := 10
149                        , Gtk.windowTitle := "FP Practicum" ]
150         Gtk.onDestroy window Gtk.mainQuit
151         
152         -- Show the window and start the Gtk mainloop.
153         Gtk.widgetShowAll window
154         Gtk.mainGUI
155
156
157 {-
158 runGUI s IS {..} = do
159         sFrame <- frame
160                 [ text       := "FP Practicum"
161                 , size       := s
162                 ]
163         buffer <- memoryDCCreate
164         bitmapCreateEmpty s 24 >>= memoryDCSelectObject buffer
165         withBrushStyle (BrushStyle BrushSolid white) (dcSetBackground buffer)
166         dcClear buffer
167         buffer `set`
168                 [ fontFace   := "Courier New"
169                 , fontSize   := 10
170                 , brushColor := rgb 0 0 0
171                 , brushKind  := BrushSolid
172                 , penColor   := rgb 0 0 0
173                 , penKind    := PenSolid
174                 ]
175         sPanel <- panel sFrame [ size := s ]
176         let state = IS {..}
177         sPanel `set`
178                 [ on paint       := onPaint state
179                 , on doubleClick := post state . MouseDoubleClick
180                 , on click       := post state . MouseDown
181                 , on drag        := post state . MouseDragged
182                 , on unclick     := post state . MouseUp
183                 , on anyKey      := transKey (post state . KeyIn)
184                 ]
185         sFrame `set`
186                 [ on closing := sFrame `set` [ visible := False ] >> wxcAppExit
187                 , on anyKey  := transKey (post state . KeyIn)
188                 , layout     := widget sPanel
189                 ]
190         windowSetFocus sFrame
191         processPostponed state
192 onPaint :: IState -> DC a -> Rect -> IO ()
193 onPaint IS {..} dest va = do
194         dcBlit dest va buffer (Point 0 0) wxCOPY False >> return ()
195
196 transKey :: (Char -> IO ()) -> Key -> IO ()
197 transKey prod (KeyChar c) = prod c
198 transKey prod  KeySpace   = prod ' '
199 transKey prod  KeyEscape  = prod '\ESC'
200 transKey prod  KeyReturn  = prod '\n'
201 transKey prod  KeyTab     = prod '\t'
202 transKey _ _ = return ()
203
204 -}
205
206 {-
207 miscHandler s@IS {..} (FRead  fn     ) = Just $ readFile fn >>= post s . FileContents fn
208 miscHandler   IS {..} (FWrite fn cnts) = Just $ writeFile fn cnts
209 miscHandler   IS {..} ReqQuit = Just $ putStrLn "Quiting" >> wxcAppExit
210 -}
211 miscHandler   IS {..} _ = Nothing
212
213 {-
214 winHandler s@IS {..} (WinPrompt st1 st2 st3) = Just $ textDialog sFrame st1 st2 st3 >>= post s . PromptResponse st1 st2
215 winHandler   IS {..} (WinTitle     st) = Just $ sFrame `set` [text := st]
216 winHandler s@IS {..} (WinMenu      ms) = Just $ mkMenu >>= \ms' -> sFrame `set` [menuBar := ms']
217         where
218         mkMenu = sequence
219                 [ do
220                         p  <- menuPane [ text := name ]
221                         sequence
222                                 [ do
223                                         i <- menuItem p [ text := item ]
224                                         sFrame `set` [on (menu i) := post s (MenuItem name item)]
225                                  | item <- items ]
226                         return p
227                  | (name,items) <- ms ]
228 -}
229 winHandler _        _                = Nothing
230
231 {-
232 gfxHandler IS {..} (GfxLines     col ps)    = Just $ polyline buffer ps [penColor := col] >> dirtyPts sPanel ps
233 gfxHandler IS {..} (GfxPolygon   col ps)    = Just $ polygon  buffer ps [penColor := col, brushColor := col] >> dirtyPts sPanel ps
234 gfxHandler IS {..} (GfxText      col xy st) = Just $ drawText buffer st xy [textColor := col] >> getTextExtent buffer st >>= dirtyRect' sPanel xy
235 gfxHandler IS {..} (GfxRectangle col rt)    = Just $ drawRect buffer rt [penColor := col, brushColor := col] >> dirtyRect sPanel rt
236 gfxHandler IS {..} (GfxEllipse   col rt)    = Just $ ellipse buffer rt [penColor := col, brushKind := BrushTransparent] >> dirtyRect sPanel rt
237 gfxHandler IS {..} (GfxDisc      col rt)    = Just $ ellipse buffer rt [penColor := col, brushColor := col] >> dirtyRect sPanel rt
238 gfxHandler IS {..} (GfxFont      st  sz)    = Just $ buffer `set` [ fontSize := sz, fontFace := st ]
239 gfxHandler IS {..}  GfxClear                = Just $ dcClear buffer >> windowRefresh sPanel False
240 gfxHandler IS {..} (GfxPicture   fd  pt)    = Just $ bitmapCreateFromFile fd >>= \bm -> drawBitmap buffer bm pt False [] >> bitmapGetSize bm >>= dirtyRect' sPanel pt
241 -}
242 gfxHandler _        _                       = Nothing
243
244 {-
245 dirtyPts :: Window a -> [Point] -> IO ()
246 dirtyPts dc ps = dirtyRect' dc (pt x y) Size {..}
247         where
248         xs     = map pointX ps
249         ys     = map pointY ps
250         x      = minimum xs
251         y      = minimum ys
252         sizeW  = maximum xs - x
253         sizeH  = maximum ys - y
254
255 dirtyRect' :: Window a -> Point -> Size -> IO ()
256 dirtyRect' dc Point {..} Size {..} = dirtyRect dc $ Rect pointX pointY sizeW sizeH
257
258 dirtyRect :: Window a -> Rect -> IO ()
259 dirtyRect dc rect = windowRefreshRect dc False (grow 2 rect)
260
261 rectanglify :: Point -> Size -> Rect
262 rectanglify Point {..} Size {..} = Rect pointX pointY sizeW sizeH
263
264 grow :: Int -> Rect -> Rect
265 grow n Rect {..} = Rect
266         { rectLeft   = rectLeft   - n
267         , rectTop    = rectTop    - n
268         , rectWidth  = rectWidth  + 2 * n
269         , rectHeight = rectHeight + 2 * n }
270
271 -}