Xmonad/Mutable state in contrib modules or xmonad.hs

From HaskellWiki
< Xmonad
Revision as of 19:08, 29 December 2012 by Avo (talk | contribs) (→‎Data.IORef: re-word)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

This page describes how to keep track of mutable state in a module in xmonad-contrib or in the configuration.

General options


This module, available in xmonad-0.10 or later, allows you to store data in xmonad's internal state eliminating the need to explicitly pass around IORef values as seen in the previous sections.

For information on how to use it, refer to the module's documentation.


Layouts can keep track of their state placing the information in the data type that is an instance of LayoutClass. The various methods of this typeclass allow one to update this information by supplying a new value of this type as a return value.

Note that this sensible for per-workspace state.

{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, FlexibleContexts, MultiParamTypeClasses, UndecidableInstances #-}
import XMonad
import XMonad.Layout.LayoutModifier
import Data.Traversable (traverse)
import Control.Monad

data WSState s a = WSState s deriving (Read,Show)

withState s0 layout = ModifiedLayout (WSState s0) layout

newtype (WSF s) = WSF (s -> X (Maybe s)) deriving (Typeable)
instance Typeable s => Message (WSF s)

instance (Typeable s, Show (WSState s a), Read (WSState s a)) =>
             LayoutModifier (WSState s) a where
    handleMess (WSState s) m = case fromMessage m of
        Just (WSF f) -> do
            s' <- f s
            return $ case s' of
                Just s'' -> Just (WSState s'')
                Nothing -> Nothing
        Nothing -> return Nothing

    {- -- equivalent but harder to understand :p
    handleMess (WSState s) m = fmap join $
      (\(WSF f) -> fmap WSState `fmap` f s) `traverse` fromMessage m

Using the above 'withState' layout modifier and the message 'WSF', you can do per-layout/workspace state. For example one could keep track of whether a workspace has been previously viewed (ex. to start some applications iff you have not seen the workspace before, as done with A.TopicSpace):

-- this modifies a layout
viewed layout = withState False layout

-- this goes in logHook
viewedHook = sendMessage (WSF $ \b -> if b then return Nothing -- already viewed
    else do
      spawn "xterm"
      return (Just True))


A more general way is to store data using Data.IORef. To create an IORef, one uses newIORef; the returned value can then be passed to functions for reading from or writing to it.

Here is an example for a keybinding that keeps track of how many times it has been pressed:

import Data.IORef
updatingBinding :: IORef Integer -> X ()
updatingBinding ref = do
  val <- io $ readIORef ref
  io $ writeIORef ref (val+1)
  spawn $ "xmessage I have been pressed " ++ show val ++ " times before!"

To use this, it needs to be passed an IORef as a parameter:

import Data.IORef
import XMonad.Util.EZConfig
main = do
  ref <- newIORef 0 -- this is the initival value
  xmonad defaultConfig `additionalKeysP` [("M-S-t", updatingBinding ref)]

Note that the content of an IORef is lost when xmonad is restarted.

Implicit Parameters

This extension is useful for passing in the iorefs. You generally need these two extensions together, if you like to leave out the type signatures (which are as much work as explicitly passing the parameters):

{-# LANGUAGE ImplicitParams, NoMonomorphismRestriction #-}

main = do
  ref <- newIORef 0
  let ?ref = ref -- all references to ?ref later on will be this one
  xmonad defaultConfig `additionalKeysP` [("M-S-t", updatingBinding)]

-- updatingBinding :: (?ref :: IORef Integer) => X () -- this is the actual type
updatingBinding = do
  val <- io $ readIORef ?ref
  io $ writeIORef ?ref (val+1)
  spawn $ "xmessage I have been pressed " ++ show val ++ " times before!"


This is an even less desirable alternative, but it is one of the more acceptable uses of this unsafe function.

Basically, you create a top-level IORef which is forced to be a single copy:

{-# NOINLINE ref #-}
ref = unsafePerformIO (newIORef 0)

Previous versions of xmonad had this used in some contrib modules such as XMonad.Hooks.UrgencyHook source here.

properties stored with X-server

XMonad.Util.StringProp has been available since xmonad-0.8. Refer to haddock documentation. Another example, where the text saved is per-window is the source of XMonad.Actions.TagWindows.