summaryrefslogtreecommitdiffhomepage
path: root/src/Plugins/Monitors/Cpu.hs
blob: 5abde7e9722c58448b0fbca1814f29b2ed212082 (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
-----------------------------------------------------------------------------
-- |
-- Module      :  Plugins.Monitors.Cpu
-- Copyright   :  (c) 2011 Jose Antonio Ortega Ruiz
--                (c) 2007-2010 Andrea Rossato
-- License     :  BSD-style (see LICENSE)
--
-- Maintainer  :  Jose A. Ortega Ruiz <jao@gnu.org>
-- Stability   :  unstable
-- Portability :  unportable
--
-- A cpu monitor for Xmobar
--
-----------------------------------------------------------------------------

module Plugins.Monitors.Cpu (startCpu) where

import Plugins.Monitors.Common
import qualified Data.ByteString.Lazy.Char8 as B
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import System.Console.GetOpt

data CpuOpts = CpuOpts
  { loadDynamicString :: Maybe DynamicString
  }

defaultOpts :: CpuOpts
defaultOpts = CpuOpts
  { loadDynamicString = Nothing
  }

options :: [OptDescr (CpuOpts -> CpuOpts)]
options =
  [ Option "" ["load-dynamic-string"] (ReqArg (\x o ->
     o { loadDynamicString = Just $ parseDynamicString x }) "") ""
  ]

parseOpts :: [String] -> IO CpuOpts
parseOpts argv =
  case getOpt Permute options argv of
    (o, _, []) -> return $ foldr id defaultOpts o
    (_, _, errs) -> ioError . userError $ concat errs

cpuConfig :: IO MConfig
cpuConfig = mkMConfig
       "Cpu: <total>%"
       ["bar","vbar","dstr","total","user","nice","system","idle","iowait"]

type CpuDataRef = IORef [Int]

cpuData :: IO [Int]
cpuData = cpuParser `fmap` B.readFile "/proc/stat"

cpuParser :: B.ByteString -> [Int]
cpuParser = map (read . B.unpack) . tail . B.words . head . B.lines

parseCpu :: CpuDataRef -> IO [Float]
parseCpu cref =
    do a <- readIORef cref
       b <- cpuData
       writeIORef cref b
       let dif = zipWith (-) b a
           tot = fromIntegral $ sum dif
           percent = map ((/ tot) . fromIntegral) dif
       return percent

formatCpu :: CpuOpts -> [Float] -> Monitor [String]
formatCpu _ [] = return $ replicate 8 ""
formatCpu opts xs = do
  let t = sum $ take 3 xs
  b <- showPercentBar (100 * t) t
  v <- showVerticalBar (100 * t) t
  d <- showDynamicString (loadDynamicString opts) t
  ps <- showPercentsWithColors (t:xs)
  return (b:v:d:ps)

runCpu :: CpuDataRef -> [String] -> Monitor String
runCpu cref argv =
    do c <- io (parseCpu cref)
       opts <- io $ parseOpts argv
       l <- formatCpu opts c
       parseTemplate l

startCpu :: [String] -> Int -> (String -> IO ()) -> IO ()
startCpu a r cb = do
  cref <- newIORef []
  _ <- parseCpu cref
  runM a cpuConfig (runCpu cref) r cb