summaryrefslogtreecommitdiff
path: root/.xmonad/xmonad.hs
blob: 8a55674846ea77d7acac4160bc33e1086d20abb1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import XMonad
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageDocks
import XMonad.Util.Run
import XMonad.Util.Loggers
import XMonad.Util.EZConfig(additionalKeys)
import System.IO
import System.Environment
import Data.Map (Map)
import qualified Data.Map as Map
import qualified XMonad.StackSet as W
import System.Exit
import Control.Monad.State (get)
import XMonad.Layout.Spiral
import Data.Ratio
import Data.List
import Data.Maybe (fromMaybe, listToMaybe, catMaybes)
import XMonad.Layout.Tabbed
import XMonad.Prompt
import XMonad.Util.Scratchpad
import Control.Monad (sequence, liftM, liftM2, join)
import XMonad.Util.WorkspaceCompare
import XMonad.Layout.NoBorders
import XMonad.Layout.PerWorkspace
import XMonad.Layout.SimplestFloat
import XMonad.Layout.Renamed
import XMonad.Layout.Reflect
import XMonad.Layout.OnHost
import XMonad.Layout.Combo
import XMonad.Layout.TwoPane
import XMonad.Layout.LayoutBuilder
import XMonad.Layout.WindowNavigation
import System.Process
import System.Directory (removeFile)
import System.Posix.Files
import System.FilePath ((</>))
import Control.Concurrent
import System.Posix.Process (getProcessID)
import System.IO.Error
import System.IO
import XMonad.Hooks.ManageHelpers hiding (CW)
import XMonad.StackSet (RationalRect (..))
import Control.Monad (when, filterM)
import Graphics.X11.ExtraTypes.XF86
import XMonad.Util.Cursor
import XMonad.Actions.Warp
import XMonad.Util.SpawnOnce
import System.Directory
import System.FilePath

import XMonad.Layout.IM

import XMonad.Prompt.MyShell
import XMonad.Prompt.MySsh

import Network.HostName

import Control.Applicative ((<$>))

type KeyMap = Map (ButtonMask, KeySym) (X ())

data Host = Host
            { hName :: HostName
            , hManageHook :: ManageHook
            , hWsp :: Integer -> WorkspaceId
            , hCoWsp :: String -> Maybe WorkspaceId
            , hKeysMod :: XConfig Layout -> (KeyMap -> KeyMap)
            , hScreens :: [ScreenId]
            , hKbLayouts :: [(String, Maybe String)]
            }

defaultHost = Host { hName = "unkown"
                   , hManageHook = composeOne [manageScratchTerm]
                   , hWsp = show
                   , hCoWsp = const Nothing
                   , hKeysMod = const id
                   , hScreens = [0,1..]
                   , hKbLayouts = [ ("us", Nothing)
                                  , ("us", Just "dvp")
                                  , ("de", Nothing)
                                  ]
                   }

hostFromName :: HostName -> Host
hostFromName h@("vali") = defaultHost { hName = h
                                      , hManageHook = composeOne $ catMaybes [ Just manageScratchTerm
                                                                             , assign "web"  $ className =? ".dwb-wrapped"
                                                                             , assign "web"  $ className =? "Chromium"
                                                                             , assign "work" $ className =? "Emacs"
                                                                             , assign "media" $ className =? "mpv"
                                                                             ]
                                      , hWsp = hWsp
                                      , hCoWsp = hCoWsp
                                      , hKeysMod = \conf -> Map.union $ Map.fromList $ join $ map (spawnBindings conf) [ (xK_d, ["chromium", "chromium $(xclip -o)"])
                                                                                                                       , (xK_e, ["emacsclient -c"])
                                                                                                                       ]
                                      , hScreens = [1, 0] ++ [2,3..]
                                      }
  where
    workspaceNames = Map.fromList [ (2, "web")
                                  , (3, "work")
                                  , (10, "media")
                                  ]
    hWsp = wspFromMap workspaceNames
    hCoWsp = coWspFromMap workspaceNames
    assign wsp test = (\wsp -> test -?> doShift wsp) <$> hCoWsp wsp
hostFromName _ = defaultHost

wspFromMap workspaceNames = \i -> case Map.lookup i workspaceNames of
  Just str -> show i ++ " " ++ str
  Nothing -> show i

coWspFromMap workspaceNames = \str -> case filter ((== str) . snd) $ Map.toList workspaceNames of
  [] -> Nothing
  [(i, _)] -> Just $ wspFromMap workspaceNames i
  _ -> Nothing

spawnModifiers = [0, controlMask, shiftMask .|. controlMask]
spawnBindings conf (k, cmds) = zipWith (\m cmd -> ((modm .|. mod1Mask .|. m, k), spawn cmd)) spawnModifiers cmds
  where
    modm = XMonad.modMask conf

manageScratchTerm = (resource =? "scratchpad" <||> resource =? "keysetup") -?> doRectFloat $ RationalRect (1 % 16) (1 % 16) (7 % 8) (7 % 8)

tabbedLayout t = renamed [Replace "Tabbed"] $ reflectHoriz $ t CustomShrink $ tabbedTheme
tabbedTheme = defaultTheme { activeColor = "black"
                           , inactiveColor = "black"
                           , urgentColor = "black"
                           , activeBorderColor = "white"
                           , inactiveBorderColor = "#202020"
                           , urgentBorderColor = "#bb0000"
                           , activeTextColor = "white"
                           , inactiveTextColor = "white"
                           , urgentTextColor = "white"
                           , decoHeight = 16
                           }

main = do
  xmobarProc <- spawnPipe "xmobar"
  hostname <- getHostName
  let
    host = hostFromName hostname
  setEnv "HOST" hostname
  let myConfig = defaultConfig {
        manageHook = manageDocks <+> hManageHook host
        , terminal = "urxvtc"
        , layoutHook = smartBorders $ avoidStruts $ windowNavigation layout'
        , logHook = dynamicLogWithPP xmobarPP'
        , modMask = mod4Mask
        , keys = \conf -> hKeysMod host conf $ myKeys' conf host
        , workspaces = take (length numKeys) $ map wsp [1..]
        , startupHook = assimilateKeychain >> (sequence autostart) >> (setDefaultCursor xC_left_ptr) >> banishScreen LowerRight >> return ()
        , normalBorderColor = "#202020"
        , focusedBorderColor = "white"
        }
      wsp = hWsp host
      -- We can´t define per-host layout modifiers because we lack dependent types
      layout' = onHost "skadhi" ( onWorkspace (wsp 1) (noBorders Full ||| withIM (1%5) (Title "Buddy List") tabbedLayout') $
                                  onWorkspace (wsp 10) (noBorders Full) $
                                  onWorkspace (wsp 2) (noBorders Full ||| tabbedLayout') $ 
                                  onWorkspace (wsp 5) tabbedLayout' $
                                  onWorkspace (wsp 8) (withIM (1%5) (Title "Friends") tabbedLayout') $
                                  defaultLayouts
                                ) $
                onHost "vali"   ( onWorkspace (wsp 2) (noBorders Full ||| tabbedLayout' ||| combineTwo (TwoPane 0.01 0.57) Full tabbedLayout') $
                                  onWorkspace (wsp 3) workLayouts $ 
                                  defaultLayouts
                                ) $
                defaultLayouts
      tabbedLayout' = tabbedLayout tabbedBottomAlways
      defaultLayouts = spiralWithDir East CW (1 % 2) ||| tabbedLayout' ||| noBorders Full
      workLayouts = spiralWithDir East CW (1 % 2)
                    ||| combineTwo (TwoPane 0.1 0.65) Full (
        tabbedLayout'
        ||| (layoutN 1 (SubBox (Abs 0) (Abs 0) (Rel 1) (Rel $ 2 % 3)) Nothing Full $ layoutAll (SubBox (Rel 0) (Rel $ 2 % 3) (Rel 1) (Rel 1)) tabbedLayout')
        )
      sqrtTwo = approxRational (sqrt 2) (1 / 2560)
      xmobarPP' = xmobarPP { ppOutput = hPutStrLn xmobarProc
                           , ppTitle = shorten 50
                           , ppSort = (liftM2 (.)) getSortByIndex $ return scratchpadFilterOutWorkspace
                           , ppUrgent = wrap "(" ")" . xmobarColor "red" ""
                           , ppHiddenNoWindows = xmobarColor "#202020" "" . wrap "(" ")"
                           , ppVisible = wrap "(" ")" . xmobarColor "yellow" ""
                           , ppCurrent = wrap "(" ")" . xmobarColor "green" ""
                           , ppHidden = wrap "(" ")"
                           , ppWsSep = " "
                           , ppSep = " | "
                           }
  xmonad $ myConfig
  
autostart = [ spawnOnce "urxvtd -o"
            , spawnKeychain
            , liftIO $ setEnv "_JAVA_AWT_WM_NONREPARENTING" "1"
            ]

spawnKeychain = do
  home <- liftIO getHomeDirectory
  let keys = map ((home </>) . (".ssh/id_" ++)) ["ed25519", "ecdsa", "rsa"]
  liftIO (maybe (return ()) (setEnv "SSH_ASKPASS") =<< findAskpass)
  safeSpawn "keychain" =<< liftIO (filterM doesFileExist keys)
  where
    findAskpass = filter `liftM` readFile "/etc/zshrc"
    filter = listToMaybe . catMaybes . map (stripPrefix "export SSH_ASKPASS=") . lines

assimilateKeychain :: X ()
assimilateKeychain = liftIO $ assimilateKeychain' >> return ()
assimilateKeychain' = tryIOError $ do
  -- pid <- getProcessID
  -- tmpDir <- lookupEnv "TMPDIR"
  -- let tmpDir' = fromMaybe "/tmp" tmpDir
  --     tmpFile = tmpDir' </> "xmonad-keychain" ++ (show pid) ++ ".env"
  env <- runProcessWithInput "sh" ["-c", "eval $(keychain --eval --noask); env"] "" -- > " ++ tmpFile] ""
  -- env <- readFile tmpFile
  let envVars = Map.fromList $ map (\(k, v) -> (k, tail' v)) $ map (span (/= '=')) $ envLines
      envVars' = Map.filterWithKey (\k _ -> k `elem` transfer) envVars
      transfer = ["SSH_AUTH_SOCK", "SSH_AGENT_PID", "GPG_AGENT_INFO"]
      envLines = filter (elem '=') $ lines env :: [String]
  sequence $ map (\(k, c) -> setEnv k c) $ Map.toList envVars'
  -- removeFile tmpFile
  where
    tail' [] = []
    tail' (x:xs) = xs


numKeys = [xK_parenleft, xK_parenright, xK_braceright, xK_plus, xK_braceleft, xK_bracketright, xK_bracketleft, xK_exclam, xK_equal, xK_asterisk]

instance Shrinker CustomShrink where
  shrinkIt _ "" = [""]
  shrinkIt s cs = cs : shrinkIt s ((reverse . drop 4 . reverse $ cs) ++ "...")

xPConfig = defaultXPConfig { bgColor = "black"
                           , fgColor = "white"
                           , fgHLight = "green"
                           , bgHLight = "black"
                           , borderColor = "white"
                           }

sshOverrides = map (\h -> mkOverride { oHost = h, oCommand = moshCmd . inTmux } )
               [
                 "odin", "odin.asgard.yggdrasil"
               , "surtr", "yggdrasil.li", "surtr.yggdrasil.li", "praseodym.org", "surtr.praseodym.org", "surtr.141.li", "141.li"
               , "vindler", "vindler.alfheim.yggdrasil"
               , "ullr"
               ]
               ++
               map (\h -> mkOverride { oHost = h, oCommand = moshCmd' "/run/current-system/sw/bin/mosh-server" . withEnv [("TERM", "xterm")] . inTmux} )
               [ "bragi", "bragi.asgard.yggdrasil"
               ]
               ++
               map (\h -> mkOverride { oHost = h, oCommand = sshCmd . withEnv [("TERM", "xterm")] . inTmux } )
               [ "galois", "galois.praseodym.org"
               ]

cycleKbLayout :: [(String, Maybe String)] -> X ()
cycleKbLayout [] = return ()
cycleKbLayout layouts = liftIO $ do
  next <- (getNext . extract) `liftM` runProcessWithInput "setxkbmap" ["-query"] ""
  let
    args = case next of
      (l, Just v) -> [l, v]
      (l, Nothing) -> [l]
  safeSpawn "setxkbmap" args
  where
    extract :: String -> Maybe (String, Maybe String)
    extract str = listToMaybe $ do
      ["layout:", l] <- str'
      [(l, Just v) | ["variant:", v] <- str'] ++ pure (l, Nothing)
      where
        str' = map words $ lines str
    getNext :: Maybe (String, Maybe String) -> (String, Maybe String)
    getNext = maybe (head layouts) getNext'
    getNext' x = case elemIndex x layouts of
      Nothing -> getNext Nothing
      Just i -> layouts !! ((i + 1) `mod` length layouts)

myKeys' conf host = Map.fromList $
    -- launch a terminal
    [ ((modm,               xK_Return), spawn $ (XMonad.terminal conf) ++ " -e tmux")
    , ((modm .|. controlMask, xK_Return), scratchpadSpawnActionCustom $ (XMonad.terminal conf) ++ " -name scratchpad -title scratchpad -e tmux")
 
    -- launch dmenu
    --, ((modm,               xK_d     ), spawn "exe=`dmenu_path | dmenu` && eval \"exec $exe\"")
    , ((modm,               xK_d     ), shellPrompt "Run: " xPConfig)
    , ((modm .|. shiftMask, xK_d     ), prompt "Run in Terminal: " ("urxvtc" ++ " -e") xPConfig)
    , ((modm,               xK_at    ), sshPrompt sshOverrides xPConfig)

    -- close focused window
    , ((modm .|. shiftMask, xK_q     ), kill)
 
     -- Rotate through the available layout algorithms
    , ((modm,               xK_space ), sendMessage NextLayout)
 
    --  Reset the layouts on the current workspace to default
    , ((modm ,              xK_r     ), (setLayout $ XMonad.layoutHook conf) >> refresh)
 
    -- Resize viewed windows to the correct size
    -- , ((modm,               xK_r     ), refresh)

    -- Move focus to the next window
    , ((modm,               xK_t     ), windows W.focusDown)
 
    -- Move focus to the previous window
    , ((modm,               xK_n     ), windows W.focusUp  )
 
    -- Move focus to the master window
    , ((modm,               xK_m     ), windows W.focusMaster  )
 
    -- Swap the focused window and the master window
    , ((modm .|. shiftMask, xK_m     ), windows W.swapMaster)
 
    -- Swap the focused window with the next window
    , ((modm .|. shiftMask, xK_t     ), windows W.swapDown  )
 
    -- Swap the focused window with the previous window
    , ((modm .|. shiftMask, xK_n     ), windows W.swapUp    )

    , ((modm,                 xK_Right), sendMessage $ Go R)
    , ((modm,                 xK_Left ), sendMessage $ Go L)
    , ((modm,                 xK_Up   ), sendMessage $ Go U)
    , ((modm,                 xK_Down ), sendMessage $ Go D)
    , ((modm .|. shiftMask  , xK_Right), sendMessage $ Move R)
    , ((modm .|. shiftMask  , xK_Left ), sendMessage $ Move L)
    , ((modm .|. shiftMask  , xK_Up   ), sendMessage $ Move U)
    , ((modm .|. shiftMask  , xK_Down ), sendMessage $ Move D)
     -- Shrink the master area
    , ((modm,               xK_h     ), sendMessage Shrink)
 
    -- Expand the master area
    , ((modm,               xK_s     ), sendMessage Expand)
 
    -- Push window back into tiling
    , ((modm .|. shiftMask, xK_space ), withFocused $ windows . W.sink)
 
    -- Increment the number of windows in the master area
    , ((modm              , xK_comma ), sendMessage (IncMasterN 1))
 
    -- Deincrement the number of windows in the master area
    , ((modm              , xK_period), sendMessage (IncMasterN (-1)))

    , ((0, xF86XK_AudioRaiseVolume), safeSpawn "amixer" ["sset", "Master", "Playback", "5+"])
    , ((0, xF86XK_AudioLowerVolume), safeSpawn "amixer" ["sset", "Master", "Playback", "5-"])

    , ((modm              , xK_Escape), cycleKbLayout (hKbLayouts host))
 
    -- Toggle the status bar gap
    -- Use this binding with avoidStruts from Hooks.ManageDocks.
    -- See also the statusBar function from Hooks.DynamicLog.
    --
    , ((modm              , xK_b     ), sendMessage ToggleStruts)
 
    -- Quit xmonad
    , ((modm .|. shiftMask, xK_e     ), io (exitWith ExitSuccess))
 
    -- Restart xmonad
    , ((modm .|. shiftMask, xK_r     ), whenX (recompile True) $ safeSpawn "xmonad" ["--restart"])
    , ((modm .|. shiftMask, xK_l     ), safeSpawn "slock" [])
    ]
    ++
 
    --
    -- mod-[1..9], Switch to workspace N
    --
    -- mod-[1..9], Switch to workspace N
    -- mod-shift-[1..9], Move client to workspace N
    --
    [((m .|. modm, k), windows $ f i)
    | (i, k) <- zip (XMonad.workspaces conf) $ numKeys
    , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]
    ]
    ++
    [((m .|. modm .|. controlMask, k), screenWorkspace i >>= (flip whenJust) (windows . f))
    | (i, k) <- zip (hScreens host) [xK_g, xK_c, xK_r, xK_l]
    , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]
    ]
  where
    modm = XMonad.modMask conf