module Graphics.Blank.DeviceContext where
import Control.Concurrent.STM
import Data.Set (Set)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import Graphics.Blank.Events
import Graphics.Blank.JavaScript
import qualified Web.Scotty.Comet as KC
data DeviceContext = DeviceContext
{ theComet :: KC.Document
, eventQueue :: EventQueue
, ctx_width :: !Int
, ctx_height :: !Int
, ctx_devicePixelRatio :: !Double
, localFiles :: TVar (Set Text)
}
instance Image DeviceContext where
jsImage = jsImage . deviceCanvasContext
width = fromIntegral . ctx_width
height = fromIntegral . ctx_height
deviceCanvasContext :: DeviceContext -> CanvasContext
deviceCanvasContext cxt = CanvasContext 0 (ctx_width cxt) (ctx_height cxt)
devicePixelRatio :: DeviceContext -> Double
devicePixelRatio = ctx_devicePixelRatio
sendToCanvas :: DeviceContext -> ShowS -> IO ()
sendToCanvas cxt cmds = do
KC.send (theComet cxt) $ "try{" <> T.pack (cmds "}catch(e){alert('JavaScript Failure: '+e.message);}")
wait :: DeviceContext -> IO Event
wait c = atomically $ readTChan (eventQueue c)
flush :: DeviceContext -> IO [Event]
flush cxt = atomically $ loop
where loop = do
b <- isEmptyTChan (eventQueue cxt)
if b then return [] else do
e <- readTChan (eventQueue cxt)
es <- loop
return (e : es)