Skip to content
This repository
tree: 3df055cc3a
Fetching contributors…

Cannot retrieve contributors at this time

file 469 lines (415 sloc) 16.589 kb
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
{-# LANGUAGE OverloadedStrings #-}
module Main where

import Blaze.ByteString.Builder
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Control.Monad.Trans
import Data.Aeson
import Data.Aeson.Encode
import Data.IORef
import Data.Monoid
import Data.Time
import Graphics.Gloss
import Graphics.Gloss.Interface.Game
import Snap.Http.Server
import Snap.Types
import Snap.Util.FileServe
import Text.Templating.Heist
import Text.XmlHtml

import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as LB

import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T

import App
import EventStream
import CacheMap
import Source
import Serialize
import GlossAdapters


main :: IO ()
main = do
    Right heist <- loadTemplates "web" (emptyTemplateState "web")
    app <- newApp heist
    quickHttpServe $
        route [ ("draw", draw app),
                ("anim", anim app),
                ("sim", sim app),
                ("game", game app),
                ("displayInBrowser", displayInBrowser app),
                ("animateInBrowser", animateInBrowser app),
                ("animateStream", animateStream app),
                ("simulateInBrowser", simulateInBrowser app),
                ("simulateStream", simulateStream app),
                ("gameInBrowser", gameInBrowser app),
                ("gameStream", gameStream app),
                ("gameEvent", gameEvent app) ]
        <|> serveDirectory "web"


draw :: App -> Snap ()
draw app = do
    Just (b,t) <- renderTemplate
        (addSplices (appHeist app))
        "editor"
    modifyResponse (setContentType t)
    writeBuilder b
  where
    addSplices = bindSplices [
        ("intro", introSplice),
        ("action", actionSplice),
        ("defaults", defaultsSplice)
        ]
    introSplice = return [
        TextNode "Define a variable called ",
        Element "code" [] [TextNode "picture"],
        TextNode " describing your picture."
        ]
    actionSplice = return [ TextNode "displayInBrowser" ]
    defaultsSplice = return [ Element "script" [("type", "text/javascript")] [
        TextNode "var sourceCookie = 'displaySource';",
        TextNode "var initialSource = 'import Graphics.Gloss\\n\\n",
        TextNode "picture = circle 80';"
        ]]


anim :: App -> Snap ()
anim app = do
    Just (b,t) <- renderTemplate
        (addSplices (appHeist app))
        "editor"
    modifyResponse (setContentType t)
    writeBuilder b
  where
    addSplices = bindSplices [
        ("intro", introSplice),
        ("action", actionSplice),
        ("defaults", defaultsSplice)
        ]
    introSplice = return [
        TextNode "Define a variable called ",
        Element "code" [] [TextNode "animation"],
        TextNode " describing your animation."
        ]
    actionSplice = return [ TextNode "animateInBrowser" ]
    defaultsSplice = return [ Element "script" [("type", "text/javascript")] [
        TextNode "var sourceCookie = 'animateSource';",
        TextNode "var initialSource = 'import Graphics.Gloss\\n\\n",
        TextNode "animation t = rotate (60*t) (rectangleSolid 80 200)';"
        ]]


sim :: App -> Snap ()
sim app = do
    Just (b,t) <- renderTemplate
        (addSplices (appHeist app))
        "editor"
    modifyResponse (setContentType t)
    writeBuilder b
  where
    addSplices = bindSplices [
        ("intro", introSplice),
        ("action", actionSplice),
        ("defaults", defaultsSplice)
        ]
    introSplice = return [
        TextNode "Define variables called ",
        Element "code" [] [TextNode "initial"],
        TextNode ", ",
        Element "code" [] [TextNode "step"],
        TextNode ", and ",
        Element "code" [] [TextNode "draw"],
        TextNode " describing your simulation's initial state, step function, and appearance."
        ]
    actionSplice = return [ TextNode "simulateInBrowser" ]
    defaultsSplice = return [ Element "script" [("type", "text/javascript")] [
        TextNode "var sourceCookie = 'simulateSource';",
        TextNode "var initialSource = 'import Graphics.Gloss\\n\\n",
        TextNode "data BallState = BallAt Float Float\\n",
        TextNode "initial = BallAt 100 0\\n",
        TextNode "step _ t (BallAt x v) = BallAt (x+v*t) (0.99*v-x*t)\\n",
        TextNode "draw (BallAt x v) = translate x x (circle 20)';"
        ]]


game :: App -> Snap ()
game app = do
    Just (b,t) <- renderTemplate
        (addSplices (appHeist app))
        "editor"
    modifyResponse (setContentType t)
    writeBuilder b
  where
    addSplices = bindSplices [
        ("intro", introSplice),
        ("action", actionSplice),
        ("defaults", defaultsSplice)
        ]
    introSplice = return [
        TextNode "Define variables called ",
        Element "code" [] [TextNode "initial"],
        TextNode ", ",
        Element "code" [] [TextNode "event"],
        TextNode ", ",
        Element "code" [] [TextNode "step"],
        TextNode ", and ",
        Element "code" [] [TextNode "draw"],
        TextNode " describing your game's initial state, event handler, step function, and appearance."
        ]
    actionSplice = return [ TextNode "gameInBrowser" ]
    defaultsSplice = return [ Element "script" [("type", "text/javascript")] [
        TextNode "var sourceCookie = 'gameSource';",
        TextNode "var initialSource = 'import Graphics.Gloss\\n",
        TextNode "import Graphics.Gloss.Interface.Game\\n\\n",
        TextNode "initial :: Point\\n",
        TextNode "initial = (0.0,0.0)\\n\\n",
        TextNode "event (EventMotion (x,y)) world = (x,y)\\n",
        TextNode "event _ world = world\\n\\n",
        TextNode "step time world = world\\n\\n",
        TextNode "draw (x,y) = translate x y (circle 50)';"
        ]]


displayInBrowser :: App -> Snap ()
displayInBrowser app = do
    src <- maybe pass return =<< getParam "source"
    res <- liftIO $ getPicture app src
    case res of
        Left errs -> errors app errs
        Right pic -> display app pic


display :: App -> Picture -> Snap ()
display app pic = do
    Just (b, t) <- renderTemplate
        (bindSplice "displayScript" (scrSplice pic) (appHeist app))
        "display"
    modifyResponse (setContentType t)
    writeBuilder b
  where
    scrSplice pic = return [ Element "script" [("type", "text/javascript")] [
        TextNode "picture = '",
        TextNode $ T.decodeUtf8 $ toByteString $ base64 $ fromPicture pic,
        TextNode "';"
        ]]


animateInBrowser :: App -> Snap ()
animateInBrowser app = do
    src <- maybe pass return =<< getParam "source"
    res <- liftIO $ getAnimation app src
    case res of
        Left errs -> errors app errs
        Right pic -> animate app res pic


animate :: App -> Err (Float -> Picture) -> (Float -> Picture) -> Snap ()
animate app e f = do
    t <- liftIO getCurrentTime
    let anim = (e, t, f)
    k <- liftIO $ cacheNew (appAnimations app) anim
    liftIO $ keepAlive (appAnimations app) k 30
    Just (b, t) <- renderTemplate
        (bindSplice "displayScript" (scrSplice k) (appHeist app))
        "display"
    modifyResponse (setContentType t)
    writeBuilder b
  where
    scrSplice k = return [ Element "script" [("type", "text/javascript")] [
        TextNode "streamURI = \'animateStream?key=",
        TextNode $ T.pack $ show k,
        TextNode "\';"
        ]]


animateStream :: App -> Snap ()
animateStream app = do
    k <- fmap (read . BC.unpack) $ maybe pass return =<< getParam "key"
    (_, t0, f) <- maybe pass return =<< liftIO (getCached (appAnimations app) k)
    tv <- liftIO (newIORef =<< getCurrentTime)
    source <- cullDuplicates $ do
        keepAlive (appAnimations app) k 30
        t1 <- getCurrentTime
        t' <- readIORef tv
        let interval = t1 `diffUTCTime` t'
        when (interval < targetInterval) $
            threadDelay $ round $ 1000000 * (targetInterval - interval)
        t1 <- getCurrentTime
        writeIORef tv t1
        let t = realToFrac (t1 `diffUTCTime` t0)
        return (f t)
    eventStreamPull (fmap pictureEvent source)
  where
    targetInterval = 0.1


simulateInBrowser :: App -> Snap ()
simulateInBrowser app = do
    src <- maybe pass return =<< getParam "source"
    res <- liftIO $ getSimulation app src
    case res of
        Left errs -> errors app errs
        Right pic -> simulate app res pic


simulate :: App -> Err Simulation -> Simulation -> Snap ()
simulate app e sim = do
    t <- liftIO getCurrentTime
    simul <- liftIO $ newMVar (t, sim)
    k <- liftIO $ cacheNew (appSimulations app) (e, simul)
    liftIO $ keepAlive (appSimulations app) k 30
    Just (b, t) <- renderTemplate
        (bindSplice "displayScript" (scrSplice k) (appHeist app))
        "display"
    modifyResponse (setContentType t)
    writeBuilder b
  where
    scrSplice k = return [ Element "script" [("type", "text/javascript")] [
        TextNode "streamURI = \'simulateStream?key=",
        TextNode $ T.pack $ show k,
        TextNode "\';"
        ]]


simulateStream :: App -> Snap ()
simulateStream app = do
    k <- fmap (read . BC.unpack) $ maybe pass return =<< getParam "key"
    (_, var) <- maybe pass return =<< liftIO (getCached (appSimulations app) k)
    source <- cullDuplicates $ modifyMVar var $ \(t0, sim) -> do
        keepAlive (appSimulations app) k 30
        t1 <- getCurrentTime
        let interval = t1 `diffUTCTime` t0
        when (interval < targetInterval) $
            threadDelay $ round $ 1000000 * (targetInterval - interval)
        t1 <- getCurrentTime
        let t = realToFrac (t1 `diffUTCTime` t0)
        let sim' = advanceSimulation t sim
        let pic = simulationToPicture sim'
        return ((t1, sim'), pic)
    eventStreamPull (fmap pictureEvent source)
  where
    targetInterval = 0.1


gameInBrowser :: App -> Snap ()
gameInBrowser app = do
    src <- maybe pass return =<< getParam "source"
    res <- liftIO $ getGame app src
    case res of
        Left errs -> errors app errs
        Right pic -> runGame app res pic


runGame :: App -> Err Game -> Game -> Snap ()
runGame app e game = do
    t <- liftIO getCurrentTime
    gvar <- liftIO $ newMVar (t, 0, game)
    k <- liftIO $ cacheNew (appGames app) (e, gvar)
    liftIO $ keepAlive (appGames app) k 30
    Just (b, t) <- renderTemplate
        (bindSplice "displayScript" (scrSplice k) (appHeist app))
        "display"
    modifyResponse (setContentType t)
    writeBuilder b
  where
    scrSplice k = return [ Element "script" [("type", "text/javascript")] [
        TextNode "streamURI = \'gameStream?key=",
        TextNode $ T.pack $ show k,
        TextNode "\';",
        TextNode "eventURI = \'gameEvent?key=",
        TextNode $ T.pack $ show k,
        TextNode "\';"
        ]]


gameStream :: App -> Snap ()
gameStream app = do
    k <- fmap (read . BC.unpack) $ maybe pass return =<< getParam "key"
    (_, var) <- maybe pass return =<< liftIO (getCached (appGames app) k)
    source <- cullDuplicates $ modifyMVar var $ \(t0, prev, game) -> do
        keepAlive (appGames app) k 30
        t1 <- getCurrentTime
        let interval = t1 `diffUTCTime` t0
        when (interval < targetInterval) $
            threadDelay $ round $ 1000000 * (targetInterval - interval)
        t1 <- getCurrentTime
        let t = realToFrac (t1 `diffUTCTime` t0)
        let game' = advanceGame t game
        let pic = gameToPicture game'
        return ((t1, prev, game'), pic)
    eventStreamPull (fmap pictureEvent source)
  where
    targetInterval = 0.1


gameEvent :: App -> Snap ()
gameEvent app = do
    nstr <- maybe pass return =<< getParam "n"
    case reads (BC.unpack nstr) of
        ((n,"") : _) -> mapM_ handle [0 .. n-1]
        _ -> pass

  where
    handle i = do
        typ <- maybe pass return =<< getParam (pname "type" i)
        case typ of
            "k" -> key i
            "m" -> move i
            _ -> pass

    key i = do
        k <- toKey =<< maybe pass return =<< getParam (pname "btn" i)
        d <- toKeyState =<< maybe pass return =<< getParam (pname "state" i)
        shift <- toKeyState =<< maybe pass return =<< getParam (pname "shift" i)
        alt <- toKeyState =<< maybe pass return =<< getParam (pname "alt" i)
        ctrl <- toKeyState =<< maybe pass return =<< getParam (pname "ctrl" i)
        x <- bsToNum =<< maybe pass return =<< getParam (pname "x" i)
        y <- bsToNum =<< maybe pass return =<< getParam (pname "y" i)
        dispatch True $ EventKey k d (Modifiers shift ctrl alt) (x,y)

    move i = do
        x <- bsToNum =<< maybe pass return =<< getParam (pname "x" i)
        y <- bsToNum =<< maybe pass return =<< getParam (pname "y" i)
        dispatch False $ EventMotion (x,y)

    dispatch force event = do
        k <- fmap (read . BC.unpack) $ maybe pass return =<< getParam "key"
        ts <- fmap (read . BC.unpack) $ maybe pass return =<< getParam "ts"
        (_, var) <- maybe pass return =<< liftIO (getCached (appGames app) k)
        liftIO $ modifyMVar var $ \ (t0, prev, game) -> do
            if force || ts >= prev
                then return ((t0, ts , signalGame event game), ())
                else return ((t0, prev, game ), ())

    pname s i = B.append s (BC.pack (show i))

bsToNum :: ByteString -> Snap Float
bsToNum bs = case reads (BC.unpack bs) of
    [(f,"")] -> return f
    _ -> pass


toKeyState :: ByteString -> Snap KeyState
toKeyState "1" = return Down
toKeyState "0" = return Up
toKeyState _ = pass


toKey :: ByteString -> Snap Key
toKey bs = case bs of
    -- Special keys and mouse events; always > 1 character
    "F1" -> return (SpecialKey KeyF1)
    "F2" -> return (SpecialKey KeyF2)
    "F3" -> return (SpecialKey KeyF3)
    "F4" -> return (SpecialKey KeyF4)
    "F5" -> return (SpecialKey KeyF5)
    "F6" -> return (SpecialKey KeyF6)
    "F7" -> return (SpecialKey KeyF7)
    "F8" -> return (SpecialKey KeyF8)
    "F9" -> return (SpecialKey KeyF9)
    "F10" -> return (SpecialKey KeyF10)
    "F11" -> return (SpecialKey KeyF11)
    "F12" -> return (SpecialKey KeyF12)
    "Left" -> return (SpecialKey KeyLeft)
    "Up" -> return (SpecialKey KeyUp)
    "Right" -> return (SpecialKey KeyRight)
    "Down" -> return (SpecialKey KeyDown)
    "PageUp" -> return (SpecialKey KeyPageUp)
    "PageDown" -> return (SpecialKey KeyPageDown)
    "Home" -> return (SpecialKey KeyHome)
    "End" -> return (SpecialKey KeyEnd)
    "Insert" -> return (SpecialKey KeyInsert)
    "Del" -> return (SpecialKey KeyDelete)
    "NumLock" -> return (SpecialKey KeyNumLock)
    "lbtn" -> return (MouseButton LeftButton)
    "rbtn" -> return (MouseButton RightButton)
    "mbtn" -> return (MouseButton MiddleButton)
    "mwup" -> return (MouseButton WheelUp)
    "mwdn" -> return (MouseButton WheelDown)
    _ | B.length bs == 1 -> return (Char (BC.head bs))
      | otherwise -> pass


cullDuplicates :: (Eq a, MonadIO m) => IO a -> m (IO (Maybe a))
cullDuplicates source = do
    oldVar <- liftIO (newMVar Nothing)
    return $ do
        new <- source
        old <- swapMVar oldVar (Just new)
        return $ case old of
            Nothing -> Just new
            Just o | o == new -> Nothing
                   | otherwise -> Just new


pictureEvent :: Maybe Picture -> ServerEvent
pictureEvent Nothing = CommentEvent mempty
pictureEvent (Just p) = ServerEvent Nothing Nothing [ base64 $ fromPicture p ]


errors :: App -> [String] -> Snap ()
errors app errs = do
    Just (b, t) <- renderTemplate
        (bindSplice "showErrors" (errSplice errs) (appHeist app))
        "errors"
    modifyResponse (setContentType t)
    writeBuilder b
  where
    errSplice errs = return [Element "ul" []
        (map (\s -> Element "li" [] [
                Element "pre" [] [TextNode (T.pack s) ]]) errs)]
Something went wrong with that request. Please try again.