{-# LANGUAGE ScopedTypeVariables, DoAndIfThenElse #-}
----------------------------------------------------------------------------
-- |
-- Module      :  XMonad.Hooks.ShowDesktopKey
--
-- Maintainer  :  Marshall Lochbaum <mlochbaum@gmail.com>
-- Stability   :  unstable
-- Portability :  unportable
--
-- Binds a keysym to a "show desktop" key, which hides all windows when
-- pressed and restores them when released.
--
-----------------------------------------------------------------------------

module XMonad.Hooks.ShowDesktopKey (
    -- * Usage
    -- $usage
    showDesktopKey
    ) where

import XMonad
import XMonad.StackSet
import Data.Monoid

-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Hooks.ShowDesktopKey
-- >
-- > main = xmonad $ defaultConfig {
-- >    ...
-- >    clientMask = ... .|. keyPressMask .|. keyReleaseMask
-- >    rootMask   = ... .|. keyPressMask .|. keyReleaseMask
-- >    handleEventHook = showDesktopKey xK_F14
-- >    ...
-- >  }
--
-- xK_F14 can be replaced with any keysym. Note that this key should not
-- repeat; this can be set using the command @xset -r@ on the keycode at
-- initialization.

-- | If we are in the root window, replace a simple keypress with the
-- corresponding C-M action.
showDesktopKey :: KeySym -> Event -> X All
showDesktopKey r (KeyEvent {ev_event_type = t, ev_keycode = code}) = do
  s <- withDisplay $ \dpy -> io $ keycodeToKeysym dpy code 0
  if s==r && (t `elem` [keyPress,keyRelease]) then do
    if t==keyPress then hideCurrentWorkspace else revealCurrentWorkspace
    return (All False)
  else return (All True)
showDesktopKey _ _ = return (All True)

onCurrentWorkspace :: (Window -> X ()) -> X ()
onCurrentWorkspace f = withWindowSet $ \ws ->
  whenJust (stack . workspace . current $ ws) $ \s -> do
    f $ XMonad.StackSet.focus s
    mapM_ f $ up s
    mapM_ f $ down s
hideCurrentWorkspace :: X ()
hideCurrentWorkspace = onCurrentWorkspace hide
revealCurrentWorkspace :: X ()
revealCurrentWorkspace = onCurrentWorkspace reveal >> setTopFocus
