[Haskell-beginners] Event handling in GTK2hs: managing events and global state

Brandon S. Allbery KF8NH allbery at ece.cmu.edu
Wed Mar 25 01:18:45 EDT 2009

On 2009 Mar 25, at 0:24, Александър Л. Димитров  
> The gtk2hs docs suggest I 'keep around' the connectId, but herein  
> lies my
> problem. The loadFile function can be called from several spots in the
> application (and I'd like to keep it that way.) Even if I wrapped  
> loadFile in a
> State monad, those entry points to load file (command line, menu,  
> button,
> possibly more) have no way of knowing the state of connectId, lest I  
> make it
> global (*shudders*) using unsafePerformIO and a Maybe IORef.

You can make it "global" without using unsafePerformIO:  Set up a  
ReaderT MyState IO and run the program inside it, after initializing  
your MyState with appropriate IORefs.  You need to lift gtk2hs  
functions, and callbacks have to be wrapped to push them back up into  
the ReaderT:

     curState <- ask
     lift $ widget `on` buttonPressEvent $ runReaderT curState .  

The reason you want a ReaderT instead of a StateT is that any state  
not accessed via an IORef can't be propagated between the mainline  
code and callbacks, so you want something that is forced to be read- 
only after initialization except via an IORef stored within it.

Aside:  I've suggested at times that gtk2hs use class MonadIO instead  
of type IO, which would make explicit lifting (and I think "dropping")  
unnecessary.  I never made a formal enhancement suggestion though; I  
should do so.

brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university    KF8NH

-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 195 bytes
Desc: This is a digitally signed message part
Url : http://www.haskell.org/pipermail/beginners/attachments/20090325/b7421f10/PGP-0001.bin

More information about the Beginners mailing list