-----------------------------------------------------------------------------
-- |
-- Module      :  Plugins.Monitors.MultiCoreTemp
-- Copyright   :  (c) 2019, 2020 Felix Springer
-- License     :  BSD-style (see LICENSE)
--
-- Maintainer  :  Felix Springer <felixspringer149@gmail.com>
-- Stability   :  unstable
-- Portability :  unportable
--
-- A core temperature monitor for Xmobar
--
-----------------------------------------------------------------------------

module Xmobar.Plugins.Monitors.MultiCoreTemp (startMultiCoreTemp) where

import Xmobar.Plugins.Monitors.Common
import Control.Monad (filterM)
import Data.Char (isDigit)
import Data.List (isPrefixOf)
import System.Console.GetOpt
import System.Directory ( doesDirectoryExist
                        , doesFileExist
                        , listDirectory
                        )

-- | Declare Options.
data CTOpts = CTOpts { CTOpts -> Maybe IconPattern
maxIconPattern :: Maybe IconPattern
                     , CTOpts -> Maybe IconPattern
avgIconPattern :: Maybe IconPattern
                     , CTOpts -> Float
mintemp :: Float
                     , CTOpts -> Float
maxtemp :: Float
                     , CTOpts -> Maybe [Char]
hwMonitorPath :: Maybe String
                     }

-- | Set default Options.
defaultOpts :: CTOpts
defaultOpts :: CTOpts
defaultOpts = CTOpts { maxIconPattern :: Maybe IconPattern
maxIconPattern = Maybe IconPattern
forall a. Maybe a
Nothing
                     , avgIconPattern :: Maybe IconPattern
avgIconPattern = Maybe IconPattern
forall a. Maybe a
Nothing
                     , mintemp :: Float
mintemp = Float
0
                     , maxtemp :: Float
maxtemp = Float
100
                     , hwMonitorPath :: Maybe [Char]
hwMonitorPath = Maybe [Char]
forall a. Maybe a
Nothing
                     }

-- | Apply configured Options.
options :: [OptDescr (CTOpts -> CTOpts)]
options :: [OptDescr (CTOpts -> CTOpts)]
options = [ [Char]
-> [[Char]]
-> ArgDescr (CTOpts -> CTOpts)
-> [Char]
-> OptDescr (CTOpts -> CTOpts)
forall a. [Char] -> [[Char]] -> ArgDescr a -> [Char] -> OptDescr a
Option [] [[Char]
"max-icon-pattern"]
              (([Char] -> CTOpts -> CTOpts)
-> [Char] -> ArgDescr (CTOpts -> CTOpts)
forall a. ([Char] -> a) -> [Char] -> ArgDescr a
ReqArg
                (\ [Char]
arg CTOpts
opts -> CTOpts
opts { maxIconPattern = Just $ parseIconPattern arg })
                [Char]
"")
              [Char]
""
          , [Char]
-> [[Char]]
-> ArgDescr (CTOpts -> CTOpts)
-> [Char]
-> OptDescr (CTOpts -> CTOpts)
forall a. [Char] -> [[Char]] -> ArgDescr a -> [Char] -> OptDescr a
Option [] [[Char]
"avg-icon-pattern"]
              (([Char] -> CTOpts -> CTOpts)
-> [Char] -> ArgDescr (CTOpts -> CTOpts)
forall a. ([Char] -> a) -> [Char] -> ArgDescr a
ReqArg
                (\ [Char]
arg CTOpts
opts -> CTOpts
opts { avgIconPattern = Just $ parseIconPattern arg })
                [Char]
"")
              [Char]
""
          , [Char]
-> [[Char]]
-> ArgDescr (CTOpts -> CTOpts)
-> [Char]
-> OptDescr (CTOpts -> CTOpts)
forall a. [Char] -> [[Char]] -> ArgDescr a -> [Char] -> OptDescr a
Option [] [[Char]
"mintemp"]
              (([Char] -> CTOpts -> CTOpts)
-> [Char] -> ArgDescr (CTOpts -> CTOpts)
forall a. ([Char] -> a) -> [Char] -> ArgDescr a
ReqArg
                (\ [Char]
arg CTOpts
opts -> CTOpts
opts { mintemp = read arg })
                [Char]
"")
              [Char]
""
          , [Char]
-> [[Char]]
-> ArgDescr (CTOpts -> CTOpts)
-> [Char]
-> OptDescr (CTOpts -> CTOpts)
forall a. [Char] -> [[Char]] -> ArgDescr a -> [Char] -> OptDescr a
Option [] [[Char]
"maxtemp"]
              (([Char] -> CTOpts -> CTOpts)
-> [Char] -> ArgDescr (CTOpts -> CTOpts)
forall a. ([Char] -> a) -> [Char] -> ArgDescr a
ReqArg
                (\ [Char]
arg CTOpts
opts -> CTOpts
opts { maxtemp = read arg })
                [Char]
"")
              [Char]
""
          , [Char]
-> [[Char]]
-> ArgDescr (CTOpts -> CTOpts)
-> [Char]
-> OptDescr (CTOpts -> CTOpts)
forall a. [Char] -> [[Char]] -> ArgDescr a -> [Char] -> OptDescr a
Option [] [[Char]
"hwmon-path"]
              (([Char] -> CTOpts -> CTOpts)
-> [Char] -> ArgDescr (CTOpts -> CTOpts)
forall a. ([Char] -> a) -> [Char] -> ArgDescr a
ReqArg
                (\ [Char]
arg CTOpts
opts -> CTOpts
opts { hwMonitorPath = Just arg })
                [Char]
"")
              [Char]
""
          ]

-- | Generate Config with a default template and options.
cTConfig :: IO MConfig
cTConfig :: IO MConfig
cTConfig = [Char] -> [[Char]] -> IO MConfig
mkMConfig [Char]
cTTemplate [[Char]]
cTOptions
  where cTTemplate :: [Char]
cTTemplate = [Char]
"Temp: <max>°C - <maxpc>%"
        cTOptions :: [[Char]]
cTOptions = [ [Char]
"max" , [Char]
"maxpc" , [Char]
"maxbar" , [Char]
"maxvbar" , [Char]
"maxipat"
                    , [Char]
"avg" , [Char]
"avgpc" , [Char]
"avgbar" , [Char]
"avgvbar" , [Char]
"avgipat"
                    ] [[Char]] -> [[Char]] -> [[Char]]
forall a. [a] -> [a] -> [a]
++ IconPattern -> [Int] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map (([Char]
"core" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++) ([Char] -> [Char]) -> IconPattern -> IconPattern
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IconPattern
forall a. Show a => a -> [Char]
show) [Int
0 :: Int ..]

-- | Returns all paths in dir matching the predicate.
getMatchingPathsInDir :: FilePath -> (String -> Bool) -> IO [FilePath]
getMatchingPathsInDir :: [Char] -> ([Char] -> Bool) -> IO [[Char]]
getMatchingPathsInDir [Char]
dir [Char] -> Bool
f = do exists <- [Char] -> IO Bool
doesDirectoryExist [Char]
dir
                                 if exists
                                    then do
                                      files <- filter f <$> listDirectory dir
                                      return $ fmap (\[Char]
file -> [Char]
dir [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"/" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
file) files
                                    else return []

-- | Given a prefix, suffix, and path string, return true if the path string
-- format is prefix ++ numeric ++ suffix.
numberedPathMatcher :: String -> String -> String -> Bool
numberedPathMatcher :: [Char] -> [Char] -> [Char] -> Bool
numberedPathMatcher [Char]
prefix [Char]
suffix [Char]
path =
    [Char]
prefix [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf` [Char]
path
    Bool -> Bool -> Bool
&& Bool -> Bool
not ([Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
digits)
    Bool -> Bool -> Bool
&& [Char]
afterDigits [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
suffix
  where afterPrefix :: [Char]
afterPrefix = Int -> [Char] -> [Char]
forall a. Int -> [a] -> [a]
drop ([Char] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Char]
prefix) [Char]
path
        digits :: [Char]
digits = (Char -> Bool) -> [Char] -> [Char]
forall a. (a -> Bool) -> [a] -> [a]
takeWhile Char -> Bool
isDigit [Char]
afterPrefix
        afterDigits :: [Char]
afterDigits = (Char -> Bool) -> [Char] -> [Char]
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isDigit [Char]
afterPrefix

-- | Returns the first coretemp.N path found.
coretempPath :: IO (Maybe String)
coretempPath :: IO (Maybe [Char])
coretempPath = do ps <- [Char] -> ([Char] -> Bool) -> IO [[Char]]
getMatchingPathsInDir [Char]
"/sys/bus/platform/devices" [Char] -> Bool
coretempMatcher
                  xs <- filterM doesDirectoryExist ps
                  return (if null xs then Nothing else Just $ head xs ++ "/")
  where coretempMatcher :: [Char] -> Bool
coretempMatcher = [Char] -> [Char] -> [Char] -> Bool
numberedPathMatcher [Char]
"coretemp." [Char]
""

-- | Returns the first hwmonN in coretemp path found or the ones in sys/class.
hwmonPaths :: IO [String]
hwmonPaths :: IO [[Char]]
hwmonPaths = do p <- IO (Maybe [Char])
coretempPath
                let (sc, path) = case p of
                                   Just [Char]
s -> (Bool
False, [Char]
s)
                                   Maybe [Char]
Nothing -> (Bool
True, [Char]
"/sys/class/")
                cps <- getMatchingPathsInDir (path ++ "hwmon") hwmonMatcher
                ecps <- filterM doesDirectoryExist cps
                return $ if sc || null ecps then ecps else [head ecps]
  where hwmonMatcher :: [Char] -> Bool
hwmonMatcher = [Char] -> [Char] -> [Char] -> Bool
numberedPathMatcher [Char]
"hwmon" [Char]
""

-- | Checks Labels, if they refer to a core and returns Strings of core-
-- temperatures.
corePaths :: Maybe String -> IO [String]
corePaths :: Maybe [Char] -> IO [[Char]]
corePaths Maybe [Char]
s = do ps <- case Maybe [Char]
s of
                        Just [Char]
pth -> [[Char]] -> IO [[Char]]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [[Char]
pth]
                        Maybe [Char]
_ -> IO [[Char]]
hwmonPaths
                 cps <- concat <$> traverse (`getMatchingPathsInDir` corePathMatcher) ps
                 ls <- filterM doesFileExist cps
                 cls <- filterM isLabelFromCore ls
                 return $ map labelToCore cls
  where corePathMatcher :: [Char] -> Bool
corePathMatcher = [Char] -> [Char] -> [Char] -> Bool
numberedPathMatcher [Char]
"temp" [Char]
"_label"

-- | Checks if Label refers to a core.
isLabelFromCore :: FilePath -> IO Bool
isLabelFromCore :: [Char] -> IO Bool
isLabelFromCore [Char]
p = do a <- [Char] -> IO [Char]
readFile [Char]
p
                       return $ take 4 a `elem` ["Core", "Tdie", "Tctl"]

-- | Transform a path to Label to a path to core-temperature.
labelToCore :: FilePath -> FilePath
labelToCore :: [Char] -> [Char]
labelToCore = ([Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"input") ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
forall a. [a] -> [a]
reverse ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> [Char] -> [Char]
forall a. Int -> [a] -> [a]
drop Int
5 ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
forall a. [a] -> [a]
reverse

-- | Reads core-temperatures as data from the system.
cTData :: Maybe String -> IO [Float]
cTData :: Maybe [Char] -> IO [Float]
cTData Maybe [Char]
p = do fps <- Maybe [Char] -> IO [[Char]]
corePaths Maybe [Char]
p
              traverse readSingleFile fps
  where readSingleFile :: FilePath -> IO Float
        readSingleFile :: [Char] -> IO Float
readSingleFile [Char]
s = do a <- [Char] -> IO [Char]
readFile [Char]
s
                              return $ parseContent a
          where parseContent :: String -> Float
                parseContent :: [Char] -> Float
parseContent = [Char] -> Float
forall a. Read a => [Char] -> a
read ([Char] -> Float) -> ([Char] -> [Char]) -> [Char] -> Float
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [[Char]] -> [Char]
forall a. HasCallStack => [a] -> a
head ([[Char]] -> [Char]) -> ([Char] -> [[Char]]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [[Char]]
lines

-- | Transforms data of temperatures into temperatures of degree Celsius.
parseCT :: CTOpts -> IO [Float]
parseCT :: CTOpts -> IO [Float]
parseCT CTOpts
opts = do rawCTs <- Maybe [Char] -> IO [Float]
cTData (CTOpts -> Maybe [Char]
hwMonitorPath CTOpts
opts)
                  let normalizedCTs = (Float -> Float) -> [Float] -> [Float]
forall a b. (a -> b) -> [a] -> [b]
map (Float -> Float -> Float
forall a. Fractional a => a -> a -> a
/ Float
1000) [Float]
rawCTs :: [Float]
                  return normalizedCTs

-- | Performs calculation for maximum and average.
-- Sets up Bars and Values to be printed.
formatCT :: CTOpts -> [Float] -> Monitor [String]
formatCT :: CTOpts -> [Float] -> Monitor [[Char]]
formatCT CTOpts
opts [Float]
cTs = do let CTOpts { mintemp :: CTOpts -> Float
mintemp = Float
minT
                                  , maxtemp :: CTOpts -> Float
maxtemp = Float
maxT } = CTOpts
opts
                           domainT :: Float
domainT = Float
maxT Float -> Float -> Float
forall a. Num a => a -> a -> a
- Float
minT
                           maxCT :: Float
maxCT = [Float] -> Float
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum [Float]
cTs
                           avgCT :: Float
avgCT = [Float] -> Float
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Float]
cTs Float -> Float -> Float
forall a. Fractional a => a -> a -> a
/ Int -> Float
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Float] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Float]
cTs)
                           calcPc :: Float -> Float
calcPc Float
t = (Float
t Float -> Float -> Float
forall a. Num a => a -> a -> a
- Float
minT) Float -> Float -> Float
forall a. Fractional a => a -> a -> a
/ Float
domainT
                           maxCTPc :: Float
maxCTPc = Float -> Float
calcPc Float
maxCT
                           avgCTPc :: Float
avgCTPc = Float -> Float
calcPc Float
avgCT

                       cs <- (Float -> ReaderT MConfig IO [Char]) -> [Float] -> Monitor [[Char]]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Float -> ReaderT MConfig IO [Char]
showTempWithColors [Float]
cTs

                       m <- showTempWithColors maxCT
                       mp <- showWithColors' (show (round (100*maxCTPc) :: Int)) maxCT
                       mb <- showPercentBar maxCT maxCTPc
                       mv <- showVerticalBar maxCT maxCTPc
                       mi <- showIconPattern (maxIconPattern opts) maxCTPc

                       a <- showTempWithColors avgCT
                       ap <- showWithColors' (show (round (100*avgCTPc) :: Int)) avgCT
                       ab <- showPercentBar avgCT avgCTPc
                       av <- showVerticalBar avgCT avgCTPc
                       ai <- showIconPattern (avgIconPattern opts) avgCTPc

                       let ms = [ [Char]
m , [Char]
mp , [Char]
mb , [Char]
mv , [Char]
mi ]
                           as = [ [Char]
a , [Char]
ap , [Char]
ab , [Char]
av , [Char]
ai ]

                       return (ms ++ as ++ cs)
  where showTempWithColors :: Float -> Monitor String
        showTempWithColors :: Float -> ReaderT MConfig IO [Char]
showTempWithColors = (Float -> [Char]) -> Float -> ReaderT MConfig IO [Char]
forall a.
(Num a, Ord a) =>
(a -> [Char]) -> a -> ReaderT MConfig IO [Char]
showWithColors (IconPattern
forall a. Show a => a -> [Char]
show IconPattern -> (Float -> Int) -> Float -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Float -> Int
forall b. Integral b => Float -> b
forall a b. (RealFrac a, Integral b) => a -> b
round :: Float -> Int))


runCT :: [String] -> Monitor String
runCT :: [[Char]] -> ReaderT MConfig IO [Char]
runCT [[Char]]
argv = do opts <- IO CTOpts -> Monitor CTOpts
forall a. IO a -> Monitor a
io (IO CTOpts -> Monitor CTOpts) -> IO CTOpts -> Monitor CTOpts
forall a b. (a -> b) -> a -> b
$ [OptDescr (CTOpts -> CTOpts)] -> CTOpts -> [[Char]] -> IO CTOpts
forall opts.
[OptDescr (opts -> opts)] -> opts -> [[Char]] -> IO opts
parseOptsWith [OptDescr (CTOpts -> CTOpts)]
options CTOpts
defaultOpts [[Char]]
argv
                cTs <- io $ parseCT opts
                l <- formatCT opts cTs
                parseTemplate l

startMultiCoreTemp :: [String] -> Int -> (String -> IO ()) -> IO ()
startMultiCoreTemp :: [[Char]] -> Int -> ([Char] -> IO ()) -> IO ()
startMultiCoreTemp [[Char]]
a = [[Char]]
-> IO MConfig
-> ([[Char]] -> ReaderT MConfig IO [Char])
-> Int
-> ([Char] -> IO ())
-> IO ()
runM [[Char]]
a IO MConfig
cTConfig [[Char]] -> ReaderT MConfig IO [Char]
runCT