{-# LANGUAGE CPP #-}

------------------------------------------------------------------------------
-- |
-- Module: Xmobar.App.Compile
-- Copyright: (c) 2018, 2026 Jose Antonio Ortega Ruiz
-- License: BSD3-style (see LICENSE)
--
-- Maintainer: jao@gnu.org
-- Stability: unstable
-- Portability: portable
-- Created: Mon Nov 26, 2018 03:36
--
--
-- Utlities to compile xmobar executables on the fly
--
------------------------------------------------------------------------------


module Xmobar.App.Compile(recompile, trace, xmessage) where

import Control.Monad.IO.Class
import Control.Exception (SomeException(..))
import qualified Control.Exception as E
import Control.Monad (filterM, when)
import Data.List ((\\))
import System.FilePath((</>), takeExtension)
import System.IO
import System.Directory
import System.Process
import System.Exit
import System.Posix.Process(executeFile, forkProcess)
import System.Posix.Types(ProcessID)

isExecutable :: FilePath -> IO Bool
isExecutable :: [Char] -> IO Bool
isExecutable [Char]
f =
  IO Bool -> (SomeException -> IO Bool) -> IO Bool
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
E.catch (Permissions -> Bool
executable (Permissions -> Bool) -> IO Permissions -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> IO Permissions
getPermissions [Char]
f) (\(SomeException e
_) -> Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False)

checkBuildScript :: Bool -> FilePath -> IO Bool
checkBuildScript :: Bool -> [Char] -> IO Bool
checkBuildScript Bool
verb [Char]
buildscript = do
  exists <- [Char] -> IO Bool
doesFileExist [Char]
buildscript
  if exists
    then do
      isExe <- isExecutable buildscript
      if isExe
        then do
          trace verb $ "Xmobar will use build script at "
                       ++ show buildscript ++ " to recompile."
          return True
        else do
          trace verb $ unlines
            [ "Xmobar will not use build script, because "
              ++ show buildscript ++ " is not executable."
            , "Suggested resolution to use it: chmod u+x "
              ++ show buildscript
            ]
          return False
    else do
      trace verb $ "Xmobar will use ghc to recompile, because "
                   ++ show buildscript ++ " does not exist."
      return False

shouldRecompile :: Bool -> FilePath -> FilePath -> FilePath -> IO Bool
shouldRecompile :: Bool -> [Char] -> [Char] -> [Char] -> IO Bool
shouldRecompile Bool
verb [Char]
src [Char]
bin [Char]
lib = do
  libTs <- ([Char] -> IO (Maybe UTCTime)) -> [[Char]] -> IO [Maybe UTCTime]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM [Char] -> IO (Maybe UTCTime)
getModTime ([[Char]] -> IO [Maybe UTCTime])
-> ([[Char]] -> [[Char]]) -> [[Char]] -> IO [Maybe UTCTime]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Char] -> Bool) -> [[Char]] -> [[Char]]
forall a. (a -> Bool) -> [a] -> [a]
filter [Char] -> Bool
isSource ([[Char]] -> IO [Maybe UTCTime])
-> IO [[Char]] -> IO [Maybe UTCTime]
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< [Char] -> IO [[Char]]
allFiles [Char]
lib
  srcT <- getModTime src
  binT <- getModTime bin
  if any (binT <) (srcT : libTs)
    then do
      trace verb "Xmobar recompiling because some files have changed."
      return True
    else do
      trace verb $ "Xmobar skipping recompile because it is not forced "
                   ++ "(e.g. via --recompile), and not any *.hs / *.lhs / *.hsc"
                   ++ " files in lib/ have been changed."
      return False
  where isSource :: [Char] -> Bool
isSource = ([Char] -> [[Char]] -> Bool) -> [[Char]] -> [Char] -> Bool
forall a b c. (a -> b -> c) -> b -> a -> c
flip [Char] -> [[Char]] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
elem [[Char]
".hs",[Char]
".lhs",[Char]
".hsc"] ([Char] -> Bool) -> ([Char] -> [Char]) -> [Char] -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
takeExtension
        allFiles :: [Char] -> IO [[Char]]
allFiles [Char]
t = do
            let prep :: [[Char]] -> [[Char]]
prep = ([Char] -> [Char]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map ([Char]
t[Char] -> [Char] -> [Char]
</>) ([[Char]] -> [[Char]])
-> ([[Char]] -> [[Char]]) -> [[Char]] -> [[Char]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Char] -> Bool) -> [[Char]] -> [[Char]]
forall a. (a -> Bool) -> [a] -> [a]
Prelude.filter ([Char] -> [[Char]] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [[Char]
".",[Char]
".."])
            cs <- [[Char]] -> [[Char]]
prep ([[Char]] -> [[Char]]) -> IO [[Char]] -> IO [[Char]]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO [[Char]] -> (SomeException -> IO [[Char]]) -> IO [[Char]]
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
E.catch ([Char] -> IO [[Char]]
getDirectoryContents [Char]
t)
                                   (\(SomeException e
_) -> [[Char]] -> IO [[Char]]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [])
            ds <- filterM doesDirectoryExist cs
            concat . ((cs \\ ds):) <$> mapM allFiles ds
        getModTime :: [Char] -> IO (Maybe UTCTime)
getModTime [Char]
f = IO (Maybe UTCTime)
-> (SomeException -> IO (Maybe UTCTime)) -> IO (Maybe UTCTime)
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
E.catch (UTCTime -> Maybe UTCTime
forall a. a -> Maybe a
Just (UTCTime -> Maybe UTCTime) -> IO UTCTime -> IO (Maybe UTCTime)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> IO UTCTime
getModificationTime [Char]
f)
                               (\(SomeException e
_) -> Maybe UTCTime -> IO (Maybe UTCTime)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe UTCTime
forall a. Maybe a
Nothing)

runProc :: FilePath -> [String] -> FilePath -> Handle -> IO ProcessHandle
runProc :: [Char] -> [[Char]] -> [Char] -> Handle -> IO ProcessHandle
runProc [Char]
bin [[Char]]
args [Char]
dir Handle
eh =
  [Char]
-> [[Char]]
-> Maybe [Char]
-> Maybe [([Char], [Char])]
-> Maybe Handle
-> Maybe Handle
-> Maybe Handle
-> IO ProcessHandle
runProcess [Char]
bin [[Char]]
args ([Char] -> Maybe [Char]
forall a. a -> Maybe a
Just [Char]
dir) Maybe [([Char], [Char])]
forall a. Maybe a
Nothing Maybe Handle
forall a. Maybe a
Nothing Maybe Handle
forall a. Maybe a
Nothing (Handle -> Maybe Handle
forall a. a -> Maybe a
Just Handle
eh)

xmessage :: String -> IO System.Posix.Types.ProcessID
xmessage :: [Char] -> IO ProcessID
xmessage [Char]
msg = IO () -> IO ProcessID
forkProcess (IO () -> IO ProcessID) -> IO () -> IO ProcessID
forall a b. (a -> b) -> a -> b
$
  [Char] -> Bool -> [[Char]] -> Maybe [([Char], [Char])] -> IO ()
forall a.
[Char] -> Bool -> [[Char]] -> Maybe [([Char], [Char])] -> IO a
executeFile [Char]
"xmessage" Bool
True [[Char]
"-default", [Char]
"okay", [Char] -> [Char]
replaceUnicode [Char]
msg] Maybe [([Char], [Char])]
forall a. Maybe a
Nothing
  where -- Replace some of the unicode symbols GHC uses in its output
        replaceUnicode :: [Char] -> [Char]
replaceUnicode = (Char -> Char) -> [Char] -> [Char]
forall a b. (a -> b) -> [a] -> [b]
map ((Char -> Char) -> [Char] -> [Char])
-> (Char -> Char) -> [Char] -> [Char]
forall a b. (a -> b) -> a -> b
$ \Char
c -> case Char
c of
         Char
'\8226' -> Char
'*'  -- •
         Char
'\8216' -> Char
'`'  -- ‘
         Char
'\8217' -> Char
'`'  -- ’
         Char
_ -> Char
c

ghcErrorMsg :: (Monad m, Show a) => String -> a -> String -> m String
ghcErrorMsg :: forall (m :: * -> *) a.
(Monad m, Show a) =>
[Char] -> a -> [Char] -> m [Char]
ghcErrorMsg [Char]
src a
status [Char]
ghcErr = [Char] -> m [Char]
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Char] -> m [Char])
-> ([[Char]] -> [Char]) -> [[Char]] -> m [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [[Char]] -> [Char]
unlines ([[Char]] -> m [Char]) -> [[Char]] -> m [Char]
forall a b. (a -> b) -> a -> b
$
  [[Char]
"Error detected while loading xmobar configuration file: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
src]
  [[Char]] -> [[Char]] -> [[Char]]
forall a. [a] -> [a] -> [a]
++ [Char] -> [[Char]]
lines (if [Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
ghcErr then a -> [Char]
forall a. Show a => a -> [Char]
show a
status else [Char]
ghcErr)
  [[Char]] -> [[Char]] -> [[Char]]
forall a. [a] -> [a] -> [a]
++ [[Char]
"",[Char]
"Please check the file for errors."]

-- | A 'trace' for the 'X' monad. Logs a string to stderr. The result may
-- be found in your .xsession-errors file
trace :: MonadIO m => Bool -> String -> m ()
trace :: forall (m :: * -> *). MonadIO m => Bool -> [Char] -> m ()
trace Bool
verb [Char]
msg = Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
verb (IO () -> m ()
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ Handle -> [Char] -> IO ()
hPutStrLn Handle
stderr [Char]
msg)

-- | 'recompile force', recompile the xmobar configuration file when
-- any of the following apply:
--
--      * force is 'True'
--
--      * the execName executable does not exist
--
--      * the xmobar executable is older than .hs or any file in
--        the @lib@ directory (under the configuration directory).
--
-- The -i flag is used to restrict recompilation to the xmobar.hs file only,
-- and any files in the aforementioned @lib@ directory.
--
-- Compilation errors (if any) are logged to the @xmobar.errors@ file
-- in the given directory.  If GHC indicates failure with a
-- non-zero exit code, an xmessage displaying that file is spawned.
--
-- 'False' is returned if there are compilation errors.
--
recompile :: MonadIO m => String -> String -> String -> Bool -> Bool -> m Bool
recompile :: forall (m :: * -> *).
MonadIO m =>
[Char] -> [Char] -> [Char] -> Bool -> Bool -> m Bool
recompile [Char]
confDir [Char]
dataDir [Char]
execName Bool
force Bool
verb = IO Bool -> m Bool
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> m Bool) -> IO Bool -> m Bool
forall a b. (a -> b) -> a -> b
$ do
    let bin :: [Char]
bin  = [Char]
confDir [Char] -> [Char] -> [Char]
</> [Char]
execName
        err :: [Char]
err  = [Char]
dataDir [Char] -> [Char] -> [Char]
</> ([Char]
execName [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
".errors")
        src :: [Char]
src  = [Char]
confDir [Char] -> [Char] -> [Char]
</> ([Char]
execName [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
".hs")
        lib :: [Char]
lib  = [Char]
confDir [Char] -> [Char] -> [Char]
</> [Char]
"lib"
        script :: [Char]
script = [Char]
confDir [Char] -> [Char] -> [Char]
</> [Char]
"build"
    useScript <- Bool -> [Char] -> IO Bool
checkBuildScript Bool
verb [Char]
script
    sc <- if useScript || force
          then return True
          else shouldRecompile verb src bin lib
    if sc
      then do
        status <- withFile err WriteMode $
                    \Handle
errHandle ->
                      ProcessHandle -> IO ExitCode
waitForProcess (ProcessHandle -> IO ExitCode) -> IO ProcessHandle -> IO ExitCode
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<<
                        if Bool
useScript
                        then [Char] -> [Char] -> [Char] -> Handle -> IO ProcessHandle
runScript [Char]
script [Char]
bin [Char]
confDir Handle
errHandle
                        else [Char] -> [Char] -> Handle -> IO ProcessHandle
runGHC [Char]
bin [Char]
confDir Handle
errHandle
        if status == ExitSuccess
            then trace verb "Xmobar recompilation process exited with success!"
            else do
                msg <- readFile err >>= ghcErrorMsg src status
                hPutStrLn stderr msg
                exitWith (ExitFailure 1)
        return (status == ExitSuccess)
      else return True
 where opts :: [Char] -> [[Char]]
opts [Char]
bin = [[Char]
"--make" , [Char]
execName [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
".hs" , [Char]
"-i" , [Char]
"-ilib"
                  , [Char]
"-fforce-recomp" , [Char]
"-main-is", [Char]
"main" , [Char]
"-v0"]
#ifdef THREADED_RUNTIME
                  ++ ["-threaded"]
#endif
#ifdef RTSOPTS
                  [[Char]] -> [[Char]] -> [[Char]]
forall a. [a] -> [a] -> [a]
++ [[Char]
"-rtsopts", [Char]
"-with-rtsopts", [Char]
"-V0"]
#endif
#ifdef SHARED_LIBRARIES
                  ++ ["-dynamic"]
#endif
                  [[Char]] -> [[Char]] -> [[Char]]
forall a. [a] -> [a] -> [a]
++ [[Char]
"-o", [Char]
bin]
       runGHC :: [Char] -> [Char] -> Handle -> IO ProcessHandle
runGHC [Char]
bin = [Char] -> [[Char]] -> [Char] -> Handle -> IO ProcessHandle
runProc [Char]
"ghc" ([Char] -> [[Char]]
opts [Char]
bin)
       runScript :: [Char] -> [Char] -> [Char] -> Handle -> IO ProcessHandle
runScript [Char]
script [Char]
bin = [Char] -> [[Char]] -> [Char] -> Handle -> IO ProcessHandle
runProc [Char]
script [[Char]
bin]