ghcjs + sodium: no events after some time - haskell

UPDATE: there is a issue in ghcjs: https://github.com/ghcjs/ghcjs/issues/296
i play with ghcjs and sodium but after 3 seconds my application doesn't emit events anymore.
a minimal example:
a button: emit events
a counter behavior: counts the button clicks
a div: displays the counter behavior
after 3 seconds, the div doesn't update anymore
if i reload the page, the counter updates again - for 3 seconds
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Applicative ((<$>))
import Control.Concurrent (forkIO, threadDelay)
import Control.Monad (forever)
import Data.Default (def)
import Data.Text (Text, pack)
import FRP.Sodium
import JavaScript.JQuery hiding (Event)
main :: IO ()
main = do
body <- select "body"
-- a button
(btn, btnE) <- mkBtnE "Click"
appendJQuery btn body
-- a behavior: counter - increment when btnE (button event) arrive
counterB <- sync $ accum 0 (const (+1) <$> btnE)
-- a div with the counter value
counterView <- mkDiv $ fmap (pack . show) counterB
appendJQuery counterView body
-- wait -> nothing changed
-- forkIO $ forever (threadDelay 1000000000)
return ()
mkBtn :: Text -> IO JQuery
mkBtn label = select "<button/>" >>= setText label
mkBtnE :: Text -> IO (JQuery, Event ())
mkBtnE label = do
(e, t) <- sync newEvent
btn <- mkBtn label
on (const $ sync $ t ()) "click" def btn
return (btn, e)
mkDiv :: Behaviour Text -> IO JQuery
mkDiv b = do
div <- select "<div/>"
sync $ listen (value b) (\t -> setText t div >> return ())
return div
The full example is under https://github.com/j-keck/ghcjs-sodium
thanks

Related

Setup custom Events with data in reactive-banana

I have a sample I picked up from the reactive-banana repo. This uses gloss.
But when I work with events I have my own events with data. These events are not necessarily UI events. So I was expecting that FRP can help me code with custom events. So, for example, a list could change and the changed data is inside an event and another part of the application uses the changed data.
My preliminary Haskell knowledge didn't help me to achieve this using reactive-banana but I did come across something similar.
How can I use my own events likemakeTickEvent and fire them ? Can it hold data ?
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Control.Monad (when)
import Data.Maybe (isJust, fromJust)
import Data.List (nub)
import System.Random
import System.IO
import Debug.Trace
import Data.IORef
import Reactive.Banana as R
import Reactive.Banana.Frameworks as R
import Graphics.Gloss
import Graphics.Gloss.Data.Extent
import Graphics.Gloss.Interface.Pure.Game
import Graphics.Gloss.Data.Picture
main :: IO()
main = do
sources <- makeSources
network <- compile $ networkDescription sources
actuate network
eventLoop sources
display windowDisplay white drawBoard
windowDisplay :: Display
windowDisplay = InWindow "Window" (200, 200) (10, 10)
makeTickEvent :: MomentIO (R.Event ())
makeTickEvent = do
(etick, tick) <- newEvent
tid <- liftIO $ do
tick ()
pure etick
drawBoard :: Picture
drawBoard =
Pictures $ [ translate x y $ rectangleWire 90 90| x<-[0,90..180], y<-[0,90..180] ]
makeSources = newAddHandler
type EventSource a = (AddHandler a, a -> IO ())
addHandler :: EventSource a -> AddHandler a
addHandler = fst
eventLoop :: (EventSource ()) -> IO ()
eventLoop (displayvalueevent) =
fire displayvalueevent ()
fire :: EventSource a -> a -> IO ()
fire = snd
networkDescription :: (EventSource ()) -> MomentIO ()
networkDescription ( displayvalueevent )= do
-- Obtain events
displayvalue <- fromAddHandler (addHandler displayvalueevent)
reactimate $ putStrLn . showValue <$> displayvalue
showValue value = "Value is " ++ show value
This is from the documentation.
plainChanges :: Behavior a -> MomentIO (Event a)
plainChanges b = do
(e, handle) <- newEvent
eb <- changes b
reactimate' $ (fmap handle) <$> eb
return e
Does this create a new Event that can be fired ?
I have managed to make this code work for now. An event is fired and a new frame is rendered in the initial Gloss Window. It seems to be possible to fire a custom event. But I am not sure about encapsulating data inside the event.
makeNewEvent :: MomentIO (Reactive.Banana.Event ())
makeNewEvent = do
(enew, new) <- newEvent
tid <- liftIO $ do
putStrLn "Fire new Event"
new ()
return enew
The following code answers some questions. If I have more details I can edit later. This is still very basic as I am learning reactive-banana and 'haskell'
------------------------------------------------------------------------------}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BlockArguments #-}
module Main where
import Data.IORef
import Data.Bool (bool)
import Data.IORef (newIORef, readIORef, writeIORef)
import Graphics.Gloss hiding (pictures)
import Reactive.Banana
import Reactive.Banana.Frameworks
import Graphics.Gloss.Interface.IO.Game( Event(..) )
import Graphics.Gloss.Interface.IO.Game( MouseButton(..) )
import Graphics.Gloss.Interface.IO.Game( KeyState( Down ) )
import Graphics.Gloss.Interface.IO.Game
import qualified Graphics.Gloss.Interface.IO.Game as Gloss (Event, playIO)
main = do
(eventHandler,event)<- makeSources
picRef ← newIORef blank
network <- compile $ networkDescriptor picRef eventHandler
actuate network
let handleEvent e#(EventKey k Down _ _) = case k of
(SpecialKey KeySpace) -> event e
_ -> return ()
handleEvent e = return ()
Gloss.playIO
(InWindow "Functional Reactive" (550, 490) (800, 200))
white
30
()
(\() -> readIORef picRef)
(\ ev () -> handleEvent ev)
(\_ () -> pure ())
reactToKeyPress :: IO ()
reactToKeyPress = putStrLn "Key Pressed"
drawBoard :: Picture
drawBoard =
Pictures $ [ color violet $ translate x y $ rectangleWire 90 90| x<-[0,90..180], y<-[0,90..180] ]
makeSources = newAddHandler
type EventSource a = (AddHandler a, a -> IO ())
addHandler :: EventSource a -> AddHandler a
addHandler = fst
fire :: EventSource a -> a -> IO ()
fire = snd
networkDescriptor :: IORef Picture -> AddHandler Gloss.Event -> MomentIO ()
networkDescriptor lastFrame displayGlossEvent = do
glossEvent <- fromAddHandler displayGlossEvent
reactimate $ putStrLn . showValue <$> glossEvent
picture <- liftMoment (handleKeys glossEvent )
changes picture >>= reactimate' . fmap (fmap (writeIORef lastFrame))
valueBLater picture >>= liftIO . writeIORef lastFrame
showValue value = "Value is " ++ show value
handleKeys :: Reactive.Banana.Event e -> Moment (Behavior Picture)
handleKeys glossEvent = do
let picture = drawBoard
return $ pure picture

How to find definition of Haskell function in VSCode?

I'm learning Haskell, and some functions like text aren't easy to google. Look at this example:
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Web.Spock
import Web.Spock.Config
import Control.Monad.Trans
import Data.IORef
import qualified Data.Text as T
data MySession = EmptySession
data MyAppState = DummyAppState (IORef Int)
main :: IO ()
main =
do ref <- newIORef 0
spockCfg <- defaultSpockCfg EmptySession PCNoDatabase (DummyAppState ref)
runSpock 8080 (spock spockCfg app)
app :: SpockM () MySession MyAppState ()
app =
do get root $ text "Hello World!"
get ("hello" <//> var) $ \name ->
do (DummyAppState ref) <- getState
visitorNumber <- liftIO $ atomicModifyIORef' ref $ \i -> (i+1, i+1)
text ("Hello " <> name <> ", you are visitor number " <> T.pack (show visitorNumber))
do get root $ text "Hello World!"
Normally, on VSCode, with any language, I would click on text with the rigth button, and "go to defintion". How do I find the definition of a function in VSCode?
I installed the haskell.haskell extension, and it didn't add this functionality.

How to get a DoubleClicked event from a reflex-dom listbox

The following code displays a reflex-dom dropdown element visually as a listbox and displays at the bottom always the last selected (clicked) line.
{-# LANGUAGE OverloadedStrings #-}
import Reflex.Dom
import qualified Data.Text as T
import qualified Data.Map as Map
import Data.Monoid((<>))
import Data.Maybe (fromJust)
main :: IO ()
main = mainWidget $ el "div" $ do
dd <- dropdown "2" (constDyn countries) $ def & attributes .~ constDyn ("size" =: "10")
el "p" $ return ()
let selItem = result <$> value dd
dynText selItem
return ()
countries :: Map.Map T.Text T.Text
countries = Map.fromList [("1", "France"), ("2", "Switzerland"), ("3", "Germany"), ("4", "Italy"), ("5", "USA")]
result :: T.Text -> T.Text
result key = "You selected: " <> fromJust (Map.lookup key countries)
I want to change this code, so it displays at the bottom always the last double clicked line!
I tried several things
use the domEvent function: This does not work, because Dropdown is not an instance of the HasDomEvent class.
filter the event in the value _dropdown_change of the Dropdown record. But I didn't find any way to filter only DoubleClick events.
use the newtype EventSelector. Again I don't see hwo I can use it.
Question: How can I get at the double click event?
You can use domEvent to get at the double click.
The following code uses elAttr to create a listbox like the one you created with dropdown. The domEvent function is used to create double click Event's for each of the listbox options which are then combined to get a Dynamic that represents the most recently double clicked option.
I left the dropbox code in place for comparison purposes.
{-# LANGUAGE OverloadedStrings #-}
import Reflex.Dom
import qualified Data.Text as T
import qualified Data.Map as Map
import Data.Monoid((<>))
import Data.Maybe (fromJust)
import Data.Traversable (forM)
-- a listbox that responds to double clicks
listbox :: MonadWidget t m => T.Text -- default
-> Map.Map T.Text T.Text -- entries
-> Map.Map T.Text T.Text -- attributes
-> m (Dynamic t T.Text)
listbox def entries attr = do
optEv <- elAttr "select" attr $
forM (Map.toList entries) $ \(i,c) -> do
let sel = if i == def
then "selected" =: "selected"
else mempty
(e, _) <- elAttr' "option" sel $ text c
return (i <$ domEvent Dblclick e)
holdDyn def $ leftmost optEv
main :: IO ()
main = mainWidget $ el "div" $ do
-- original code (responds to single clicks)
dd <- dropdown "2" (constDyn countries) $ def & attributes .~ constDyn ("size" =: "10")
el "p" $ return ()
let selItem = result <$> value dd
dynText selItem
el "p" $ return ()
-- new code (responds to double clicks)
lb <- listbox "3" countries ("size" =: "10")
el "p" $ return ()
let dblItem = result <$> lb
dynText dblItem
return ()
countries :: Map.Map T.Text T.Text
countries = Map.fromList [("1", "France"), ("2", "Switzerland"), ("3", "Germany"), ("4", "Italy"), ("5", "USA")]
result :: T.Text -> T.Text
result key = "You selected: " <> fromJust (Map.lookup key countries)

Pipes and callbacks in Haskell

I'm processing some audio using portaudio. The haskell FFI bindings call a user defined callback whenever there's audio data to be processed. This callback should be handled very quickly and ideally with no I/O. I wanted to save the audio input and return quickly since my application doesn't need to react to the audio in realtime (right now I'm just saving the audio data to a file; later I'll construct a simple speech recognition system).
I like the idea of pipes and thought I could use that library. The problem is that I don't know how to create a Producer that returns data that came in through a callback.
How do I handle my use case?
Here's what I'm working with right now, in case that helps (the datum mvar isn't working right now but I don't like storing all the data in a seq... I'd rather process it as it came instead of just at the end):
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
module Main where
import Codec.Wav
import Sound.PortAudio
import Sound.PortAudio.Base
import Sound.PortAudio.Buffer
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.C.Types
import Foreign.Storable
import qualified Data.StorableVector as SV
import qualified Data.StorableVector.Base as SVB
import Control.Exception.Base (evaluate)
import Data.Int
import Data.Sequence as Seq
import Control.Concurrent
instance Buffer SV.Vector a where
fromForeignPtr fp = return . SVB.fromForeignPtr fp
toForeignPtr = return . (\(a, b, c) -> (a, c)) . SVB.toForeignPtr
-- | Wrap a buffer callback into the generic stream callback type.
buffCBtoRawCB' :: (StreamFormat input, StreamFormat output, Buffer a input, Buffer b output) =>
BuffStreamCallback input output a b -> StreamCallback input output
buffCBtoRawCB' func = \a b c d e -> do
fpA <- newForeignPtr_ d -- We will not free, as callback system will do that for us
fpB <- newForeignPtr_ e -- We will not free, as callback system will do that for us
storeInp <- fromForeignPtr fpA (fromIntegral $ 1 * c)
storeOut <- fromForeignPtr fpB (fromIntegral $ 0 * c)
func a b c storeInp storeOut
callback :: MVar (Seq.Seq [Int32]) -> PaStreamCallbackTimeInfo -> [StreamCallbackFlag] -> CULong
-> SV.Vector Int32 -> SV.Vector Int32 -> IO StreamResult
callback seqmvar = \timeinfo flags numsamples input output -> do
putStrLn $ "timeinfo: " ++ show timeinfo ++ "; flags are " ++ show flags ++ " in callback with " ++ show numsamples ++ " samples."
print input
-- write data to output
--mapM_ (uncurry $ pokeElemOff output) $ zip (map fromIntegral [0..(numsamples-1)]) datum
--print "wrote data"
input' <- evaluate $ SV.unpack input
modifyMVar_ seqmvar (\s -> return $ s Seq.|> input')
case flags of
[] -> return $ if unPaTime (outputBufferDacTime timeinfo) > 0.2 then Complete else Continue
_ -> return Complete
done doneMVar = do
putStrLn "total done dood!"
putMVar doneMVar True
return ()
main = do
let samplerate = 16000
Nothing <- initialize
print "initialized"
m <- newEmptyMVar
datum <- newMVar Seq.empty
Right s <- openDefaultStream 1 0 samplerate Nothing (Just $ buffCBtoRawCB' (callback datum)) (Just $ done m)
startStream s
_ <- takeMVar m -- wait until our callbacks decide they are done!
Nothing <- terminate
print "let's see what we've recorded..."
stuff <- takeMVar datum
print stuff
-- write out wav file
-- let datum =
-- audio = Audio { sampleRate = samplerate
-- , channelNumber = 1
-- , sampleData = datum
-- }
-- exportFile "foo.wav" audio
print "main done"
The simplest solution is to use MVars to communicate between the callback and Producer. Here's how:
import Control.Proxy
import Control.Concurrent.MVar
fromMVar :: (Proxy p) => MVar (Maybe a) -> () -> Producer p a IO ()
fromMVar mvar () = runIdentityP loop where
loop = do
ma <- lift $ takeMVar mvar
case ma of
Nothing -> return ()
Just a -> do
respond a
loop
Your stream callback will write Just input to the MVar and your finalization callback will write Nothing to terminate the Producer.
Here's a ghci example demonstrating how it works:
>>> mvar <- newEmptyMVar :: IO (MVar (Maybe Int))
>>> forkIO $ runProxy $ fromMVar mvar >-> printD
>>> putMVar mvar (Just 1)
1
>>> putMVar mvar (Just 2)
2
>>> putMVar mvar Nothing
>>> putMVar mvar (Just 3)
>>>
Edit: The pipes-concurrency library now provides this feature, and it even has a section in the tutorial explaining specifically how to use it to get data out of callbacks.

Concurrent Haskell Actions with Timeout

how could one implement a function in concurrent haskell that either returns 'a' successfully or due to timeout 'b'?
timed :: Int → IO a → b → IO (Either a b)
timed max act def = do
Best Regards,
Cetin SertNote: the signature of timed can be completely or slightly different.
Implementing your desired timed on top of System.Timeout.timeout is easy:
import System.Timeout (timeout)
timed :: Int -> IO a -> b -> IO (Either b a)
timed us act def = liftM (maybe (Left def) Right) (timeout us act)
By the way, the common implementation of timeout is closer to this: ($! = seq to try to force evaluation of the returned value in the thread rather than only returning a thunk):
import Control.Concurrent (forkIO, threadDelay, killThread)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import System.IO (hPrint, stderr)
timeout :: Int -> IO a -> IO (Maybe a)
timeout us act = do
mvar <- newEmptyMVar
tid1 <- forkIO $ (putMVar mvar . Just $!) =<< act
tid2 <- forkIO $ threadDelay us >> putMVar mvar Nothing
res <- takeMVar mvar
killThread (maybe tid1 (const tid2) res) `catch` hPrint stderr
return res
The implementation of System.Timeout.timeout in the libraries is a little more complex, handling more exceptional cases.
import Control.Concurrent (forkIO, threadDelay, myThreadId, killThread)
import Control.Exception (Exception, handleJust, throwTo, bracket)
import Data.Typeable
import Data.Unique (Unique, newUnique)
data Timeout = Timeout Unique deriving Eq
timeoutTc :: TyCon
timeoutTc = mkTyCon "Timeout"
instance Typeable Timeout where { typeOf _ = mkTyConApp timeoutTc [] }
instance Show Timeout where
show _ = "<<timeout>>"
instance Exception Timeout
timeout n f
| n < 0 = fmap Just f
| n == 0 = return Nothing
| otherwise = do
pid <- myThreadId
ex <- fmap Timeout newUnique
handleJust (\e -> if e == ex then Just () else Nothing)
(\_ -> return Nothing)
(bracket (forkIO (threadDelay n >> throwTo pid ex))
(killThread)
(\_ -> fmap Just f))
Here's the first answer I could come up with. I needed this for a port scanner. o_O Forgot the admin password of my router and wanted to check which ports I had opened on our home server before that I could now repurpose and reuse ^ _ ^" ... This implementation should do the job for the time being.
module Control.Concurrent.Timed (timed) where
import Prelude hiding (take)
import System.IO
import Control.Monad
import System.Process
import System.Timeout
import Control.Concurrent
import System.Environment
timed :: Int → IO a → b → IO (Either b a)
timed max act def = do
w ← new
r ← new
t ← forkIO $ do
a ← act
r ≔ Right a
e ← em w
case e of
False → kill =<< take w
True → return ()
s ← forkIO $ do
(w ≔) =<< mine
wait max
e ← em r
case e of
True → do
kill t
r ≔ Left def
False → return ()
take r
timed_ :: Int → IO a → a → IO a
timed_ max act def = do
r ← timed max act def
return $ case r of
Right a → a
Left a → a
(≔) = putMVar
new = newEmptyMVar
wait = threadDelay
em = isEmptyMVar
kill = killThread
mine = myThreadId
take = takeMVar
or just use System.Timeout.timeout -__-"

Resources