summaryrefslogtreecommitdiffhomepage
path: root/Monitors/Common.hs
blob: a7c33e64b5f87fa471effb3bcc697578fb3855a0 (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
-----------------------------------------------------------------------------
-- |
-- Module      :  Monitors.Common
-- Copyright   :  (c) Andrea Rossato
-- License     :  BSD-style (see LICENSE)
-- 
-- Maintainer  :  Andrea Rossato <andrea.rossato@unibz.it>
-- Stability   :  unstable
-- Portability :  unportable
--
-- Utilities for creating monitors for XMobar
--
-----------------------------------------------------------------------------

module Monitors.Common ( 
                       -- * Monitors
                       -- $monitor
                         Monitor
                       , MConfig (..)
                       , Opts (..)
                       , setConfigValue
                       , getConfigValue
                       , newConfig
                       , runMonitor
                       , runM
                       , io
                       -- * Parsers
                       -- $parsers
                       , runP
                       , skipRestOfLine
                       , getNumbers
                       , getNumbersAsString
                       , getAllBut
                       , getAfterString
                       , skipTillString
                       , parseTemplate
                       -- ** String Manipulation
                       -- $strings
                       , showWithColors
                       , takeDigits
                       , floatToPercent
                       , stringParser
                       -- * Threaded Actions
                       -- $thread
                       , doActionTwiceWithDelay
                       ) where


import Control.Concurrent
import Control.Monad.Reader

import qualified Data.ByteString.Lazy.Char8 as B
import Data.IORef
import qualified Data.Map as Map 

import Numeric

import Text.ParserCombinators.Parsec

import System.Console.GetOpt
import System.Environment
import System.Exit

-- $monitor

type Monitor a = ReaderT MConfig IO a

data MConfig =
    MC { normalColor :: IORef (Maybe String)
       , low :: IORef Int
       , lowColor :: IORef (Maybe String)
       , high :: IORef Int
       , highColor :: IORef (Maybe String)
       , template :: IORef String
       , packageName :: IORef String
       , usageTail :: IORef String
       , addedArgs :: IORef [OptDescr Opts]
       , export :: IORef [String]
       } 

-- | from 'http:\/\/www.haskell.org\/hawiki\/MonadState'
type Selector a = MConfig -> IORef a

sel :: Selector a -> Monitor a
sel s = 
    do hs <- ask
       liftIO $ readIORef (s hs)

mods :: Selector a -> (a -> a) -> Monitor ()
mods s m = 
    do v <- ask
       io $ modifyIORef (s v) m

setConfigValue :: a -> Selector a -> Monitor ()
setConfigValue v s =
       mods s (\_ -> v)

getConfigValue :: Selector a -> Monitor a
getConfigValue s =
    sel s

newConfig :: String
          -> String
          -> String
          -> [OptDescr Opts]
          -> [String]
          -> IO MConfig
newConfig tmpl pkg usg args exprts =
    do lc <- newIORef Nothing
       l <- newIORef 33
       nc <- newIORef Nothing
       h <- newIORef 66
       hc <- newIORef Nothing
       t <- newIORef tmpl
       p <- newIORef pkg
       u <- newIORef usg
       a <- newIORef args
       e <- newIORef exprts
       return $ MC nc l lc h hc t p u a e

data Opts = Help
          | Version
          | HighColor String
          | NormalColor String
          | LowColor String
          | Low String
          | High String
          | Template String
          | Others String

options :: Monitor [OptDescr Opts]
options =
    do t <- getConfigValue export
       ao <- getConfigValue addedArgs 
       tmpl <- getConfigValue template
       return $ [ Option ['h']  ["help"]    (NoArg Help)    "Show this help"
                , Option ['V']  ["version"] (NoArg Version) "Show version information"
                , Option ['H']  ["High"]  (ReqArg High "number") "The high threshold"
                , Option ['L']  ["Low"]  (ReqArg Low "number") "The low threshold"
                , Option []  ["high"]  (ReqArg HighColor "color number") "Color for the high threshold: es \"#FF0000\""
                , Option []  ["normal"]  (ReqArg NormalColor "color number") "Color for the normal threshold: es \"#00FF00\""
                , Option []  ["low"]  (ReqArg LowColor "color number") "Color for the low threshold: es \"#0000FF\""
                , Option ['t']  ["template"]  (ReqArg Template "output template") 
                             ("Output template.\nAvaliable variables: " ++ show t ++ "\nDefault template: " ++ show tmpl)
                ] ++ ao

usage :: Monitor ()
usage =
    do pn <- io $ getProgName
       u <- getConfigValue usageTail
       opts <- options
       io $ putStr $ usageInfo ("Usage: " ++ pn ++ " [OPTIONS...] " ++ u) opts

version :: String
version = "0.5"

versinfo :: String -> String -> IO ()
versinfo p v = putStrLn $ p ++" " ++ v

doArgs :: [String] 
       -> Monitor String 
       -> ([String] -> Monitor String)
       -> Monitor String
doArgs args actionFail action =
    do opts <- options
       case (getOpt Permute opts args) of
         (o, n, []) -> do
           doConfigOptions o
           case n of
             []   -> actionFail
             nd   -> action nd
         (_, _, errs) -> io $ error (concat errs)

doConfigOptions :: [Opts] -> Monitor ()
doConfigOptions [] = io $ return ()
doConfigOptions (o:oo) =
    do pn <- getConfigValue packageName
       let next = doConfigOptions oo
       case o of
         Help -> usage >> io (exitWith ExitSuccess)
         Version -> io $ versinfo pn version >> exitWith ExitSuccess
         High h -> setConfigValue (read h) high >> next
         Low l -> setConfigValue (read l) low >> next
         HighColor hc -> setConfigValue (Just hc) highColor >> next
         NormalColor nc -> setConfigValue (Just nc) normalColor >> next
         LowColor lc -> setConfigValue (Just lc) lowColor >> next
         Template t -> setConfigValue t template >> next
         _ -> next

runMonitor ::  IO MConfig -> Monitor String -> ([String] -> Monitor String) -> IO ()
runMonitor conf actionFail action =
    do c <- conf
       args <- getArgs
       let ac = doArgs args actionFail action
       putStrLn =<< runReaderT ac c

runM :: [String] -> IO MConfig -> Monitor String -> ([String] -> Monitor String) -> IO String
runM args conf actionFail action =
    do c <- conf
       let ac = doArgs args actionFail action
       runReaderT ac c

io :: IO a -> Monitor a
io = liftIO



-- $parsers

runP :: Parser [a] -> String -> IO [a]
runP p i = 
    do case (parse p "" i) of
         Left _ -> return []
         Right x  -> return x

getAllBut :: String -> Parser String
getAllBut s =
    manyTill (noneOf s) (char $ head s)

getNumbers :: Parser Float
getNumbers = skipMany space >> many1 digit >>= \n -> return $ read n

getNumbersAsString :: Parser String
getNumbersAsString = skipMany space >> many1 digit >>= \n -> return n

skipRestOfLine :: Parser Char
skipRestOfLine =
    do many $ noneOf "\n\r"
       newline

getAfterString :: String -> Parser String
getAfterString s =
    do { try $ manyTill skipRestOfLine $ string s
       ; v <- manyTill anyChar $ newline
       ; return v
       } <|> return ("<" ++ s ++ " not found!>")

skipTillString :: String -> Parser String
skipTillString s = 
    manyTill skipRestOfLine $ string s

-- | Parses the output template string
templateStringParser :: Parser (String,String,String)
templateStringParser =
    do{ s <- many $ noneOf "<"
      ; (_,com,_) <- templateCommandParser
      ; ss <- many $ noneOf "<"
      ; return (s, com, ss)
      } 

-- | Parses the command part of the template string
templateCommandParser :: Parser (String,String,String)
templateCommandParser =
    do { char '<'
       ; com <- many $ noneOf ">"
       ; char '>'
       ; return $ ("",com,"")
       }

-- | Combines the template parsers
templateParser :: Parser [(String,String,String)]
templateParser = many templateStringParser --"%")

-- | Takes a list of strings that represent the values of the exported
-- keys. The strings are joined with the exported keys to form a map
-- to be combined with 'combine' to the parsed template. Returns the
-- final output of the monitor.
parseTemplate :: [String] -> Monitor String
parseTemplate l =
    do t <- getConfigValue template
       s <- io $ runP templateParser t
       e <- getConfigValue export
       let m = Map.fromList . zip e $ l 
       return $ combine m s 

-- | Given a finite "Map" and a parsed templatet produces the
-- | resulting output string.
combine :: Map.Map String String -> [(String, String, String)] -> String
combine _ [] = []
combine m ((s,ts,ss):xs) = 
    s ++ str ++ ss ++ combine m xs
        where str = Map.findWithDefault err ts m
              err = "<" ++ ts ++ " not found!>"

-- $strings

type Pos = (Int, Int)

takeDigits :: Int -> Float -> Float
takeDigits d n = 
    read $ showFFloat (Just d) n ""

floatToPercent :: Float -> String
floatToPercent n = 
    showFFloat (Just 2) (n*100) "%" 

stringParser :: Pos -> B.ByteString -> String
stringParser (x,y) =
     flip (!!) x . map B.unpack . B.words . flip (!!) y . B.lines

setColor :: String -> Selector (Maybe String) -> Monitor String
setColor str s =
    do a <- getConfigValue s
       case a of
            Nothing -> return str
            Just c -> return $
                "<fc=" ++ c ++ ">" ++ str ++ "</fc>"

showWithColors :: (Float -> String) -> Float -> Monitor String
showWithColors f x =
    do h <- getConfigValue high
       l <- getConfigValue low
       let col = setColor $ f x
       head $ [col highColor | x > fromIntegral h ] ++
              [col normalColor | x > fromIntegral l ] ++
              [col lowColor | True]

-- $threads

doActionTwiceWithDelay :: Int -> IO [a] -> IO ([a], [a])
doActionTwiceWithDelay delay action = 
    do v1 <- newMVar []
       forkIO $! getData action v1 0
       v2 <- newMVar []
       forkIO $! getData action v2 delay
       threadDelay (delay `div` 3 * 4)
       a <- readMVar v1
       b <- readMVar v2
       return (a,b)

getData :: IO a -> MVar a -> Int -> IO ()
getData action var d =
    do threadDelay d
       s <- action
       modifyMVar_ var (\_ -> return $! s)