summaryrefslogtreecommitdiffhomepage
path: root/src/Xmobar/Plugins/StdinReader.hs
blob: 4d5c438ec7f885d38a4c20db0fad349cc17a5d23 (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
{-# LANGUAGE ViewPatterns #-}

-----------------------------------------------------------------------------
-- |
-- Module      :  Plugins.StdinReader
-- Copyright   :  (c) Andrea Rossato
-- License     :  BSD-style (see LICENSE)
--
-- Maintainer  :  Jose A. Ortega Ruiz <jao@gnu.org>
-- Stability   :  unstable
-- Portability :  unportable
--
-- A plugin for reading from `stdin`.
--
-- Exports:
-- - `StdinReader` to safely display stdin content (striping actions).
-- - `UnsafeStdinReader` to display stdin content as-is.
--
-----------------------------------------------------------------------------

module Xmobar.Plugins.StdinReader (StdinReader(..)) where

import Prelude
import System.Posix.Process
import System.Exit
import System.IO
import System.IO.Error (isEOFError)
import Xmobar.Run.Exec
import Xmobar.X11.Actions (stripActions)
import Control.Concurrent (threadDelay)
import Control.Exception
import Control.Monad (forever)

data StdinReader = StdinReader | UnsafeStdinReader
  deriving (Read, Show)

instance Exec StdinReader where
  start stdinReader cb = forever $ (cb . escape stdinReader =<< getLine) `catch` handler
    where
      -- rethrow async exceptions like ThreadKilled, etc.
      handler (fromException -> Just e) = throwIO (e :: SomeAsyncException)
      -- XMonad.Hooks.DynamicLog.statusBar starts new xmobar on every xmonad
      -- reload and the old xmobar is only signalled to exit via the pipe
      -- being closed, so we must unconditionally terminate on EOF, otherwise
      -- there'd be a pileup of xmobars
      handler (fromException -> Just e) | isEOFError e = exitImmediately ExitSuccess
      -- any other exception, like "invalid argument (invalid byte sequence)",
      -- is logged to both stderr and the bar itself, throttled to avoid
      -- excessive CPU usage whenever someone pipes garbage into xmobar, and
      -- then discarded without terminating, so a single charset error doesn't
      -- break the entire xmobar
      handler e = do
        let errorMessage = "xmobar: Received exception " <> show e
        hPutStrLn stderr errorMessage
        cb $ stripActions errorMessage
        threadDelay 1000000

escape :: StdinReader -> String -> String
escape StdinReader = stripActions
escape UnsafeStdinReader = id