module Protocol where import System.IO import Options import Network (PortID(..), Socket, listenOn) import System.Random (randomRIO) data Protocol = Exec String | Kill | GetOptions | SetOptions String deriving (Show, Read) put :: Handle -> Protocol -> IO() put handle msg = do hPutStrLn handle $ show msg hFlush handle get :: (Read a) => Handle -> IO a get handle = hGetLine handle >>= readIO {- From GUI-API -} isExecuting :: Handle -> IO (Maybe Bool) isExecuting handle = do x <- hReady handle case x of False -> return Nothing True -> do msg <- hGetLine handle readIO msg >>= return . Just kill :: Handle -> IO () kill handle = do put handle Kill getOptions :: Handle -> IO Options getOptions handle = do put handle GetOptions get handle setOptions :: Options -> Handle -> IO () setOptions options handle = do put handle $ SetOptions $ show options executeStmt :: String -> Handle -> IO () executeStmt stmt handle = do put handle $ Exec stmt {- From GHCProcess to GUI -} setIsExecuting :: Handle -> Bool -> IO() setIsExecuting handle is = do hPutStrLn handle $ show is hFlush handle listenOnRandomPort :: Int -- ^ Number of tries -> IO(Socket, Int) listenOnRandomPort 0 = error "Could not establish socket connection" listenOnRandomPort tries = tryGetSocket `catch` tryAgain where tryGetSocket = do port <- randomRIO (16384, 65535) socket <- listenOn (PortNumber $ fromIntegral port) return (socket, port) tryAgain _ = listenOnRandomPort (tries-1)