4

I am trying to write a small program that detects button inputs on a video game controller, using the Haskell SDL bindings. My program is rather simple:

import Control.Monad (forever, when)
import System.Exit (exitSuccess)
import Data.Time.Clock.POSIX (getPOSIXTime)

import qualified Graphics.UI.SDL.General  as SG
import qualified Graphics.UI.SDL.Events   as SE
import qualified Graphics.UI.SDL.Joystick as SJ
import qualified Graphics.UI.SDL.Video    as SV
import qualified Graphics.UI.SDL.Types    as ST


main :: IO ()
main =
  SG.withInit [SG.InitVideo, SG.InitJoystick] $ do
    -- Open joystick.  We assume it's always present.
    numJoysticks <- SJ.countAvailable
    putStrLn $ show numJoysticks ++ " joystick(s) available"
    js <- SJ.open 0

    -- Create window
    SV.setVideoMode 320 240 24 [ST.SWSurface, ST.Resizable]

    -- Handle events
    forever $ do
      evt <- SE.waitEvent
      case evt of
        SE.JoyButtonDown dev btn -> do
                 t <- getPOSIXTime
                 print (show t ++ " - Button pressed: " ++ show dev ++ " " ++ show btn)
        SE.Quit -> exitSuccess
        _ -> return ()

On my system (Debian stable, GHC 7.4, libghc-sdl-dev 0.6.3), the button events are captured during the first second (more or less) of execution of the program, then nothing. Is there something wrong with my code?

gnuvince
  • 2,357
  • 20
  • 27
  • unrelated note: You don't have to give all the sdl modules different names. You can `import qualified TheModule as SDL` for all of them and then access all of their functions as `SDL.f` - you won't get any namespace clashes within SDL itself. – Cubic Mar 15 '14 at 14:55

1 Answers1

1

Add SJ.close js after your forever block. I believe the Joystick gets auto-closed when Haskell thinks it's no longer required.

Gerold Meisinger
  • 4,500
  • 5
  • 26
  • 33