{-# LANGUAGE ScopedTypeVariables, DoAndIfThenElse #-}
----------------------------------------------------------------------------
-- |
-- Module      :  XMonad.Hooks.RootKeyEvent
--
-- Maintainer  :  Marshall Lochbaum <mlochbaum@gmail.com>
-- Stability   :  unstable
-- Portability :  unportable
--
-- Allows special handling of keypresses in the root window.
--
-----------------------------------------------------------------------------

module XMonad.Hooks.RootKey (
    -- * Usage
    -- $usage
    rootKeyEvent
    ) where

import XMonad
import Data.Monoid
import qualified Data.Map as M

-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Hooks.RootKey
-- >
-- > main = xmonad $ defaultConfig {
-- >    ...
-- >    rootMask   = ... .|. keyPressMask
-- >    handleEventHook = rootKeyEvent
-- >    ...
-- >  }
--

-- | If we are in the root window, replace a simple keypress with the
-- corresponding C-M action.
rootKeyEvent :: Event -> X All
rootKeyEvent (KeyEvent {ev_event_type = t, ev_state = m, ev_keycode = code
                       ,ev_window = w })
    | t==keyPress = do
        root <- isRoot w
        mClean <- cleanMask m
        if root && (mClean==0) then do
            ks <- asks keyActions
            mm <- asks (modMask . config)
            s  <- withDisplay $ \dpy -> io $ keycodeToKeysym dpy code 0
            case (M.lookup (mm.|.controlMask, s) ks) of
                Just x  -> userCodeDef () x >> return (All False)
                Nothing -> return (All True)
        else return (All True)
rootKeyEvent _ = return (All True)
