{-|
hledger-ui - a hledger add-on providing an efficient TUI.

SPDX-License-Identifier: GPL-3.0-or-later
Copyright (c) 2007-2025 (each year in this range) Simon Michael <simon@joyful.com> and contributors.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <https://www.gnu.org/licenses/>.

-}

{-# LANGUAGE CPP                   #-}
{-# LANGUAGE LambdaCase            #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}

module Hledger.UI.Main where

import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (withAsync)
#if MIN_VERSION_base(4,20,0)
import Control.Exception.Backtrace (setBacktraceMechanismState, BacktraceMechanism(..))
#endif
import Control.Monad (forM_, void, when)
import Control.Monad.IO.Class (liftIO)
import Data.Bifunctor (first)
import Data.Function ((&))
import Data.List (find)
import Data.List.Extra (nubSort)
import Data.Maybe (fromMaybe)
import Data.Text qualified as T
import Data.Time.Clock (getCurrentTime)
import Graphics.Vty (Event (EvKey), Key (KChar), Modifier (MCtrl), Mode (Focus, Mouse), Vty (outputIface), Output (setMode))
import Graphics.Vty.CrossPlatform (mkVty)
#ifndef mingw32_HOST_OS
import Control.Exception (throwIO)
import Graphics.Vty.Platform.Unix (mkVtyWithSettings)
import Graphics.Vty.Platform.Unix.Settings (UnixSettings(..), VtyUnixConfigurationError(..))
import System.Environment (lookupEnv)
import System.IO.Error (catchIOError)
import System.Posix.IO (OpenMode(ReadOnly), OpenFileFlags(..), defaultFileFlags, openFd, stdOutput)
import System.Posix.Terminal (getTerminalName, queryTerminal)
import System.Posix.Types (Fd)
#endif
import Lens.Micro ((^.))
import System.Directory (canonicalizePath)
import System.Environment (withProgName)
import System.FilePath (takeDirectory)
import System.FSNotify (Event(Added, Modified), watchDir, withManager, EventIsDirectory (IsFile))
import Brick
import Brick.BChan qualified as BC

import Hledger
import Hledger.Cli hiding (progname,prognameandversion)
import Hledger.Cli.Commands.Quickref (showQuickref)
import Hledger.UI.Theme
import Hledger.UI.UIOptions
import Hledger.UI.UITypes
import Hledger.UI.UIState (uiState, uiDisplayJournal)
import Hledger.UI.UIUtils (clickFocusStep, dbguiEv, journalIsFromStdin, showScreenStack, showScreenSelection, uiInstallWarningCollector, uiTakeWarnings)
import Hledger.UI.MenuScreen
import Hledger.UI.AccountsScreen
import Hledger.UI.RegisterScreen
import Hledger.UI.TransactionScreen
import Hledger.UI.ErrorScreen
import Hledger.UI.UIScreens


----------------------------------------------------------------------

newChan :: IO (BC.BChan a)
newChan :: forall a. IO (BChan a)
newChan = Int -> IO (BChan a)
forall a. Int -> IO (BChan a)
BC.newBChan Int
10

writeChan :: BC.BChan a -> a -> IO ()
writeChan :: forall a. BChan a -> a -> IO ()
writeChan = BChan a -> a -> IO ()
forall a. BChan a -> a -> IO ()
BC.writeBChan


hledgerUiMain :: IO ()
hledgerUiMain :: IO ()
hledgerUiMain = IO () -> IO ()
handleExit (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ IO () -> IO ()
forall {a}. a -> a
withGhcDebug' (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> IO () -> IO ()
forall a. [Char] -> IO a -> IO a
withProgName [Char]
"hledger-ui.log" (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do  -- force Hledger.Utils.Debug.* to log to hledger-ui.log
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (GhcDebugMode
ghcDebugMode GhcDebugMode -> GhcDebugMode -> Bool
forall a. Eq a => a -> a -> Bool
== GhcDebugMode
GDPauseAtStart) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ IO ()
ghcDebugPause'

#if MIN_VERSION_base(4,20,0)
  -- Control ghc 9.10+'s stack traces.
  -- CostCentreBacktrace   - collect cost-centre stack backtraces (only available when built with profiling)
  -- HasCallStackBacktrace - collect HasCallStack backtraces
  -- ExecutionBacktrace    - collect backtraces from native execution stack unwinding
  -- IPEBacktrace          - collect backtraces from Info Table Provenance Entries
#ifdef DEBUG
  setBacktraceMechanismState HasCallStackBacktrace True
#else
  BacktraceMechanism -> Bool -> IO ()
setBacktraceMechanismState BacktraceMechanism
HasCallStackBacktrace Bool
False
#endif
#endif

  [Char] -> IO ()
forall (m :: * -> *). MonadIO m => [Char] -> m ()
dbg1MsgIO [Char]
"\n\n\n\n==== hledger-ui start"
  [Char] -> [[Char]] -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => [Char] -> a -> m ()
dbg1IO [Char]
"args" [[Char]]
progArgs
  [Char] -> Int -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => [Char] -> a -> m ()
dbg1IO [Char]
"debugLevel" Int
debugLevel

  opts1@UIOpts{uoCliOpts=copts@CliOpts{rawopts_=rawopts}} <- IO UIOpts
getHledgerUIOpts
  -- when (debug_ $ cliopts_ opts) $ printf "%s\n" prognameandversion >> printf "opts: %s\n" (show opts)

  usecolor <- useColorOnStdout
  -- And when it's not, disable colour in the TUI ?
  -- Theme.hs's themes currently hard code various colours and styles provided by vty,
  -- which probably are disabled automatically when terminal doesn't support them.
  -- But we'll at least force hledger-ui's theme to a monochrome one.
  let opts = if Bool
usecolor then UIOpts
opts1 else UIOpts
opts1{uoTheme=Just "terminal"}

  -- always generate forecasted periodic transactions; their visibility will be toggled by the UI.
  let copts' = UIOpts -> CliOpts -> CliOpts
uiAdjustOpts UIOpts
opts CliOpts
copts

  -- always load the journal with full lot detail retained and amounts as recorded; the UI
  -- collapses lots and converts to cost for display (toggled by the L and B keys), so the
  -- loaded journal stays available without re-reading files.
  let loadcopts = CliOpts -> CliOpts
uiLoadOpts CliOpts
copts'

  case True of
    Bool
_ | [Char] -> RawOpts -> Bool
boolopt [Char]
"quickref" RawOpts
rawopts -> IO ()
showQuickref
    Bool
_ | [Char] -> RawOpts -> Bool
boolopt [Char]
"help"    RawOpts
rawopts -> [Char] -> IO ()
runPager ([Char] -> IO ()) -> [Char] -> IO ()
forall a b. (a -> b) -> a -> b
$ Mode RawOpts -> [Char]
forall a. Mode a -> [Char]
showModeUsage Mode RawOpts
uimode [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"\n"
    Bool
_ | [Char] -> RawOpts -> Bool
boolopt [Char]
"examples" RawOpts
rawopts -> [Char] -> IO ()
runTldrForPage [Char]
"hledger-ui"
    Bool
_ | [Char] -> RawOpts -> Bool
boolopt [Char]
"info"    RawOpts
rawopts -> [Char] -> Maybe [Char] -> IO ()
runInfoForTopic [Char]
"hledger-ui" Maybe [Char]
forall a. Maybe a
Nothing
    Bool
_ | [Char] -> RawOpts -> Bool
boolopt [Char]
"man"     RawOpts
rawopts -> [Char] -> Maybe [Char] -> IO ()
runManForTopic  [Char]
"hledger-ui" Maybe [Char]
forall a. Maybe a
Nothing
    Bool
_ | [Char] -> RawOpts -> Bool
boolopt [Char]
"webman"  RawOpts
rawopts -> IO ExitCode -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ExitCode -> IO ()) -> IO ExitCode -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> IO ExitCode
openBrowserOn ([Char] -> IO ExitCode) -> [Char] -> IO ExitCode
forall a b. (a -> b) -> a -> b
$ [Char] -> Maybe [Char] -> [Char]
webManualUrl [Char]
"hledger-ui" Maybe [Char]
forall a. Maybe a
Nothing
    Bool
_ | [Char] -> RawOpts -> Bool
boolopt [Char]
"version" RawOpts
rawopts -> [Char] -> IO ()
putStrLn [Char]
prognameandversion
    -- _ | boolopt "binary-filename" rawopts -> putStrLn (binaryfilename progname)
    Bool
_                                         -> do
        -- From here on, warnings (from loading or later reloading the journal) should be
        -- collected for display in the UI, not printed to stderr where they would be
        -- hidden or would disrupt the terminal display.
        IO ()
uiInstallWarningCollector
        CliOpts -> (Journal -> IO ()) -> IO ()
forall a. CliOpts -> (Journal -> IO a) -> IO a
withJournal CliOpts
loadcopts (UIOpts -> Journal -> IO ()
runBrickUi UIOpts
opts)

  when (ghcDebugMode == GDPauseAtEnd) $ ghcDebugPause'

-- | Make an action like @mkVty mempty@, but reading keyboard input from the
-- controlling terminal's device rather than from stdin. Used when the journal data
-- was read from stdin, which leaves that handle consumed and closed.
-- The terminal is opened once, here; the returned action can be run repeatedly
-- (eg when resuming after a suspend). Unix only; on Windows this is just mkVty.
ttyVtyMaker :: IO (IO Vty)
#ifdef mingw32_HOST_OS
ttyVtyMaker = return $ mkVty mempty
#else
ttyVtyMaker :: IO (IO Vty)
ttyVtyMaker = do
  term  <- [Char] -> IO (Maybe [Char])
lookupEnv [Char]
"TERM" IO (Maybe [Char]) -> (Maybe [Char] -> IO [Char]) -> IO [Char]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO [Char] -> ([Char] -> IO [Char]) -> Maybe [Char] -> IO [Char]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (VtyUnixConfigurationError -> IO [Char]
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO VtyUnixConfigurationError
MissingTermEnvVar) [Char] -> IO [Char]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return
  ttyfd <- openTerminal
  return $ mkVtyWithSettings mempty UnixSettings
    { settingVmin      = 1
    , settingVtime     = 100
    , settingInputFd   = ttyfd
    , settingOutputFd  = stdOutput
    , settingTermName  = term
    }

-- | Open the controlling terminal for reading, without making it our controlling
-- terminal if we have none, and not inherited by child processes.
-- Prefer the terminal's real device path (eg /dev/ttys003) over /dev/tty:
-- macOS's kqueue can't wait on the latter, so vty's input thread would block
-- in read() and shutdown would hang until the next key press.
-- Fall back to /dev/tty if the device can't be opened (eg after su).
openTerminal :: IO Fd
openTerminal :: IO Fd
openTerminal = do
  isterm <- Fd -> IO Bool
queryTerminal Fd
stdOutput
  mdev   <- if isterm then Just <$> getTerminalName stdOutput else return Nothing
  let open [Char]
p = [Char] -> OpenMode -> OpenFileFlags -> IO Fd
openFd [Char]
p OpenMode
ReadOnly OpenFileFlags
defaultFileFlags{noctty = True, cloexec = True}
  case mdev of
    Maybe [Char]
Nothing  -> [Char] -> IO Fd
open [Char]
"/dev/tty"
    Just [Char]
dev -> [Char] -> IO Fd
open [Char]
dev IO Fd -> (IOError -> IO Fd) -> IO Fd
forall a. IO a -> (IOError -> IO a) -> IO a
`catchIOError` \IOError
_ -> [Char] -> IO Fd
open [Char]
"/dev/tty"
#endif

-- | Build hledger-ui's startup state: normalise the options, choose the initial
-- screen, and set up the stack of previous screens as if the user had navigated
-- down to it from the menu. Uses the startup report date (@copts^.rsDay@), so it is
-- deterministic and reusable outside the brick app (eg from tests). Keep synced with msNew.
uiInitialState :: UIOpts -> Journal -> UIState
uiInitialState :: UIOpts -> Journal -> UIState
uiInitialState uopts0 :: UIOpts
uopts0@UIOpts{uoCliOpts :: UIOpts -> CliOpts
uoCliOpts=copts :: CliOpts
copts@CliOpts{reportspec_ :: CliOpts -> ReportSpec
reportspec_=rspec :: ReportSpec
rspec@ReportSpec{_rsReportOpts :: ReportSpec -> ReportOpts
_rsReportOpts=ReportOpts
ropts}}} Journal
j =
  UIOpts -> Journal -> [Screen] -> Screen -> UIState
uiState UIOpts
uopts Journal
j [Screen]
prevscrs Screen
currscr
  where
    today :: Day
today = CliOpts
coptsCliOpts -> Getting Day CliOpts Day -> Day
forall s a. s -> Getting a s a -> a
^.Getting Day CliOpts Day
forall c. HasReportSpec c => Lens' c Day
Lens' CliOpts Day
rsDay

    -- hledger-ui's query handling is currently in flux, mixing old and new approaches.
    -- Related: #1340, #1383, #1387. Some notes and terminology:

    -- The *startup query* is the Query generated at program startup, from
    -- command line options, arguments, and the current date. hledger CLI
    -- uses this.

    -- hledger-ui/hledger-web allow the query to be changed at will, creating
    -- a new *runtime query* each time.

    -- The startup query or part of it can be used as a *constraint query*,
    -- limiting all runtime queries. hledger-web does this with the startup
    -- report period, never showing transactions outside those dates.
    -- hledger-ui does not do this.

    -- A query is a combination of multiple subqueries/terms, which are
    -- generated from command line options and arguments, ui/web app runtime
    -- state, and/or the current date.

    -- Some subqueries are generated by parsing freeform user input, which
    -- can fail. We don't want hledger users to see such failures except:

    -- 1. at program startup, in which case the program exits
    -- 2. after entering a new freeform query in hledger-ui/web, in which case
    --    the change is rejected and the program keeps running

    -- So we should parse those kinds of subquery only at those times. Any
    -- subqueries which do not require parsing can be kept separate. And
    -- these can be combined to make the full query when needed, eg when
    -- hledger-ui screens are generating their data. (TODO)

    -- Some parts of the query are also kept separate for UI reasons.
    -- hledger-ui provides special UI for controlling depth (number keys), 
    -- the report period (shift arrow keys), realness/status filters (RUPC keys) etc.
    -- There is also a freeform text area for extra query terms (/ key).
    -- It's cleaner and less conflicting to keep the former out of the latter.

    uopts :: UIOpts
uopts = UIOpts
uopts0{
      uoCliOpts=copts{
         reportspec_=rspec{
            _rsQuery=filteredQuery $ _rsQuery rspec,  -- query with depth/date parts removed
            _rsReportOpts=ropts{
               depth_    = queryDepth $ _rsQuery rspec,  -- query's depth part
               period_   = periodfromoptsandargs,       -- query's date part
               no_elide_ = accountlistmode_ ropts == ALTree,   -- avoid squashing boring account names, for a more regular tree (unlike hledger)
               empty_    = not $ empty_ ropts,  -- show zero items by default, hide them with -E (unlike hledger)
               declared_ = True  -- always show declared accounts even if unused
               }
            }
         }
      }
      where
        datespanfromargs :: DateSpan
datespanfromargs = Bool -> Query -> DateSpan
queryDateSpan (ReportOpts -> Bool
date2_ ReportOpts
ropts) (Query -> DateSpan) -> Query -> DateSpan
forall a b. (a -> b) -> a -> b
$ ReportSpec -> Query
_rsQuery ReportSpec
rspec
        periodfromoptsandargs :: Period
periodfromoptsandargs =
          DateSpan -> Period
dateSpanAsPeriod (DateSpan -> Period) -> DateSpan -> Period
forall a b. (a -> b) -> a -> b
$ [DateSpan] -> DateSpan
spansIntersect [Period -> DateSpan
periodAsDateSpan (Period -> DateSpan) -> Period -> DateSpan
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Period
period_ ReportOpts
ropts, DateSpan
datespanfromargs]
        filteredQuery :: Query -> Query
filteredQuery Query
q = Query -> Query
simplifyQuery (Query -> Query) -> Query -> Query
forall a b. (a -> b) -> a -> b
$ [Query] -> Query
And [ReportOpts -> Query
queryFromFlags ReportOpts
ropts, Query -> Query
filtered Query
q]
          where filtered :: Query -> Query
filtered = (Query -> Bool) -> Query -> Query
filterQuery (\Query
x -> Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Query -> Bool
queryIsDepth Query
x Bool -> Bool -> Bool
|| Query -> Bool
queryIsDate Query
x)

    -- The journal collapsed for display per the current lots toggle; the initial screens
    -- are built from it, while uiState keeps the uncollapsed journal for the L toggle.
    jdisplay :: Journal
jdisplay = UIOpts -> Journal -> Journal
uiDisplayJournal UIOpts
uopts Journal
j

    -- Choose the initial screen to display.
    -- We also set up a stack of previous screens, as if you had navigated down to it from the top.
    -- Note the previous screens list is ordered nearest-first, with the top-most (menu) screen last.
    -- Keep all of this synced with msNew.
    rawopts :: RawOpts
rawopts = CliOpts -> RawOpts
rawopts_ (CliOpts -> RawOpts) -> CliOpts -> RawOpts
forall a b. (a -> b) -> a -> b
$ UIOpts -> CliOpts
uoCliOpts (UIOpts -> CliOpts) -> UIOpts -> CliOpts
forall a b. (a -> b) -> a -> b
$ UIOpts
uopts
    -- The screen-selecting flag given last wins, so eg a config file's choice
    -- can be overridden on the command line.
    mscreenflag :: Maybe [Char]
mscreenflag = ([Char] -> Maybe [Char]) -> RawOpts -> Maybe [Char]
forall a. ([Char] -> Maybe a) -> RawOpts -> Maybe a
choiceopt (\[Char]
n -> if [Char]
n [Char] -> [[Char]] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [[Char]
"cash",[Char]
"bs",[Char]
"is",[Char]
"all",[Char]
"register"] then [Char] -> Maybe [Char]
forall a. a -> Maybe a
Just [Char]
n else Maybe [Char]
forall a. Maybe a
Nothing) RawOpts
rawopts
    ([Screen]
prevscrs, Screen
currscr) =
      (([Screen], Screen) -> [Char])
-> ([Screen], Screen) -> ([Screen], Screen)
forall a. (a -> [Char]) -> a -> a
dbg1With ([Char] -> (Screen -> [Char]) -> UIState -> [Char]
showScreenStack [Char]
"initial" Screen -> [Char]
showScreenSelection (UIState -> [Char])
-> (([Screen], Screen) -> UIState) -> ([Screen], Screen) -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Screen] -> Screen -> UIState) -> ([Screen], Screen) -> UIState
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry2 (UIOpts -> Journal -> [Screen] -> Screen -> UIState
uiState UIOpts
defuiopts Journal
nulljournal)) (([Screen], Screen) -> ([Screen], Screen))
-> ([Screen], Screen) -> ([Screen], Screen)
forall a b. (a -> b) -> a -> b
$
      case Maybe [Char]
mscreenflag of
        -- An accounts screen is specified. Its previous screen will be the menu screen with it selected.
        Just [Char]
"cash" -> ([Int -> Screen -> Screen
msSetSelectedScreen Int
csItemIndex Screen
menuscr], Screen
csacctsscr)
        Just [Char]
"bs"   -> ([Int -> Screen -> Screen
msSetSelectedScreen Int
bsItemIndex Screen
menuscr], Screen
bsacctsscr)
        Just [Char]
"is"   -> ([Int -> Screen -> Screen
msSetSelectedScreen Int
isItemIndex Screen
menuscr], Screen
isacctsscr)
        Just [Char]
"all"  -> ([Int -> Screen -> Screen
msSetSelectedScreen Int
asItemIndex Screen
menuscr], Screen
allacctsscr)

        -- A register screen is specified with --register=ACCT. The initial screen stack will be:
        --
        --   menu screen, with ACCTSSCR selected
        --    ACCTSSCR (the accounts screen containing ACCT), with ACCT selected
        --     register screen for ACCT
        --
        Just [Char]
"register" | Just [Char]
apat <- UIOpts -> Maybe [Char]
uoRegister UIOpts
uopts ->
          let
            -- the account being requested
            acct :: Text
acct = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe ([Char] -> Text
forall a. [Char] -> a
error' ([Char] -> Text) -> [Char] -> Text
forall a b. (a -> b) -> a -> b
$ [Char]
"--register "[Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++[Char]
apat[Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++[Char]
" did not match any account")  -- PARTIAL:
              (Maybe Text -> Text) -> ([Text] -> Maybe Text) -> [Text] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Text] -> Maybe Text
firstMatch ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ Journal -> [Text]
journalAccountNamesDeclaredOrImplied Journal
jdisplay
              where
                firstMatch :: [Text] -> Maybe Text
firstMatch = case Text -> Either [Char] Regexp
toRegexCI (Text -> Either [Char] Regexp) -> Text -> Either [Char] Regexp
forall a b. (a -> b) -> a -> b
$ [Char] -> Text
T.pack [Char]
apat of
                    Right Regexp
re -> (Text -> Bool) -> [Text] -> Maybe Text
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (Regexp -> Text -> Bool
regexMatchText Regexp
re)
                    Left  [Char]
_  -> Maybe Text -> [Text] -> Maybe Text
forall a b. a -> b -> a
const Maybe Text
forall a. Maybe a
Nothing

            -- the register screen for acct
            regscr :: Screen
regscr = 
              Text -> Bool -> Screen -> Screen
rsSetAccount Text
acct Bool
False (Screen -> Screen) -> Screen -> Screen
forall a b. (a -> b) -> a -> b
$
              UIOpts -> Day -> Journal -> Text -> Bool -> Screen
rsNew UIOpts
uopts Day
today Journal
jdisplay Text
acct Bool
forceinclusive
                where
                  -- Take the depth from uopts, not `getDepth ui`: ui depends on regscr
                  -- (this binding), so referencing ui here ties a knot that StrictData's
                  -- strict UIState fields turn into a <<loop>> at startup (#1825).
                  forceinclusive :: Bool
forceinclusive = case DepthSpec -> Maybe Int
dsFlatDepth (ReportOpts -> DepthSpec
depth_ ReportOpts
regropts) of
                                    Just Int
de -> Text -> Int
accountNameLevel Text
acct Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
de
                                    Maybe Int
Nothing -> Bool
False
                    where regropts :: ReportOpts
regropts = ReportSpec -> ReportOpts
_rsReportOpts (ReportSpec -> ReportOpts) -> ReportSpec -> ReportOpts
forall a b. (a -> b) -> a -> b
$ CliOpts -> ReportSpec
reportspec_ (CliOpts -> ReportSpec) -> CliOpts -> ReportSpec
forall a b. (a -> b) -> a -> b
$ UIOpts -> CliOpts
uoCliOpts UIOpts
uopts

            -- The accounts screen containing acct.
            -- Keep these selidx values synced with the menu items in msNew.
            (Screen
acctsscr, Int
selidx) =
              case Journal -> Text -> Maybe AccountType
journalAccountType Journal
jdisplay Text
acct of
                Just AccountType
t | AccountType -> Bool
isBalanceSheetAccountType AccountType
t    -> (Screen
bsacctsscr, Int
1)
                Just AccountType
t | AccountType -> Bool
isIncomeStatementAccountType AccountType
t -> (Screen
isacctsscr, Int
2)
                Maybe AccountType
_                                       -> (Screen
allacctsscr,Int
0)
              (Screen, Int) -> ((Screen, Int) -> (Screen, Int)) -> (Screen, Int)
forall a b. a -> (a -> b) -> b
& (Screen -> Screen) -> (Screen, Int) -> (Screen, Int)
forall a b c. (a -> b) -> (a, c) -> (b, c)
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (Text -> Screen -> Screen
asSetSelectedAccount Text
acct)

            -- the menu screen
            menuscr' :: Screen
menuscr' = Int -> Screen -> Screen
msSetSelectedScreen Int
selidx Screen
menuscr
          in ([Screen
acctsscr, Screen
menuscr'], Screen
regscr)

        -- Otherwise, start on the menu screen.
        Maybe [Char]
_ -> ([], Screen
menuscr)

        where
          menuscr :: Screen
menuscr     = Screen
msNew
          allacctsscr :: Screen
allacctsscr = AccountsScreenKind
-> UIOpts -> Day -> Journal -> Maybe Text -> Screen
asNew AccountsScreenKind
AllAccounts             UIOpts
uopts Day
today Journal
jdisplay Maybe Text
forall a. Maybe a
Nothing
          csacctsscr :: Screen
csacctsscr  = AccountsScreenKind
-> UIOpts -> Day -> Journal -> Maybe Text -> Screen
asNew AccountsScreenKind
CashAccounts            UIOpts
uopts Day
today Journal
jdisplay Maybe Text
forall a. Maybe a
Nothing
          bsacctsscr :: Screen
bsacctsscr  = AccountsScreenKind
-> UIOpts -> Day -> Journal -> Maybe Text -> Screen
asNew AccountsScreenKind
BalancesheetAccounts    UIOpts
uopts Day
today Journal
jdisplay Maybe Text
forall a. Maybe a
Nothing
          isacctsscr :: Screen
isacctsscr  = AccountsScreenKind
-> UIOpts -> Day -> Journal -> Maybe Text -> Screen
asNew AccountsScreenKind
IncomestatementAccounts UIOpts
uopts Day
today Journal
jdisplay Maybe Text
forall a. Maybe a
Nothing


runBrickUi :: UIOpts -> Journal -> IO ()
runBrickUi :: UIOpts -> Journal -> IO ()
runBrickUi UIOpts
uopts0 Journal
j =
  do
  -- show any warnings collected while loading the journal (until the first keypress)
  startupwarnings <- IO [[Char]]
uiTakeWarnings

  let
    ui  = (UIOpts -> Journal -> UIState
uiInitialState UIOpts
uopts0 Journal
j){aWarnings=startupwarnings}
    app = Maybe [Char] -> App UIState AppEvent Name
brickApp (UIOpts -> Maybe [Char]
uoTheme UIOpts
uopts0)

  -- print (length (show ui)) >> exitSuccess  -- show any debug output to this point & quit

  let
  -- how to make a Vty terminal controller: the usual way, or when the journal
  -- came from stdin, reading keys from the terminal device instead
  mkvty <- if journalIsFromStdin j then ttyVtyMaker else return (mkVty mempty)

  let
    -- helper: make a Vty terminal controller with mouse support and focus reporting enabled
    makevty = do
      v <- IO Vty
mkvty
      setMode (outputIface v) Mouse True
      setMode (outputIface v) Focus True
      return v

  if not (uoWatch uopts0)
  then do
#if MIN_VERSION_brick(3,1,0)
    void $ customMain (Just makevty) Nothing app ui
#else
    vty <- makevty
    void $ customMain vty makevty Nothing app ui
#endif

  else do
    -- a channel for sending misc. events to the app
    eventChan <- newChan

    -- start a background thread reporting changes in the current date
    -- use async for proper child termination in GHCI
    let
      watchDate Day
old = do
        Int -> IO ()
threadDelay Int
1000000 -- 1 s
        new <- IO Day
getCurrentDay
        when (new /= old) $ do
          let dc = Day -> Day -> AppEvent
DateChange Day
old Day
new
          -- dbg1IO "datechange" dc -- XXX don't uncomment until dbg*IO fixed to use traceIO, GHC may block/end thread
          -- traceIO $ show dc
          writeChan eventChan dc
        watchDate new

    withAsync
      -- run this small task asynchronously:
      (getCurrentDay >>= watchDate)
      -- until this main task terminates:
      $ \Async (ZonkAny 0)
_async ->
      -- start one or more background threads reporting changes in the directories of our files
      -- XXX many quick successive saves causes the problems listed in BUGS
      -- with Debounce increased to 1s it easily gets stuck on an error or blank screen
      -- until you press g, but it becomes responsive again quickly.
      -- withManagerConf defaultConfig{confDebounce=Debounce 1} $ \mgr -> do
      -- with Debounce at the default 1ms it clears transient errors itself
      -- but gets tied up for ages
      (WatchManager -> IO ()) -> IO ()
forall a. (WatchManager -> IO a) -> IO a
withManager ((WatchManager -> IO ()) -> IO ())
-> (WatchManager -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \WatchManager
mgr -> do
        fs <- ([Char] -> IO [Char]) -> [[Char]] -> IO [[Char]]
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 [Char]
canonicalizePath ([[Char]] -> IO [[Char]]) -> [[Char]] -> IO [[Char]]
forall a b. (a -> b) -> a -> b
$ ([Char] -> Bool) -> [[Char]] -> [[Char]]
forall a. (a -> Bool) -> [a] -> [a]
filter ([Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
/= [Char]
"-") ([[Char]] -> [[Char]]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> a -> b
$ Journal -> [[Char]]
journalAllFilePaths Journal
j
        let directories = [[Char]] -> [[Char]]
forall a. Ord a => [a] -> [a]
nubSort ([[Char]] -> [[Char]]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> a -> b
$ ([Char] -> [Char]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map [Char] -> [Char]
takeDirectory [[Char]]
fs
        dbg1IO "files" fs
        dbg1IO "directories to watch" directories

        forM_ directories $ \[Char]
d -> WatchManager -> [Char] -> ActionPredicate -> Action -> IO (IO ())
watchDir
          WatchManager
mgr
          [Char]
d
          -- predicate: ignore changes not involving our files
          (\case
            Added [Char]
f UTCTime
_ EventIsDirectory
IsFile -> [Char]
f [Char] -> [[Char]] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [[Char]]
fs -- for editors which write the whole file from scratch on saves
            Modified [Char]
f UTCTime
_ EventIsDirectory
IsFile -> [Char]
f [Char] -> [[Char]] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [[Char]]
fs -- for editors which modify existing files in place
            -- we don't handle adding/removing journal files right now
            -- and there might be some of those events from tmp files
            -- clogging things up so let's ignore them
            Event
_ -> Bool
False
            )
          -- action: send event to app
          (\Event
fev -> do
            -- return $ dbglog "fsnotify" $ showFSNEvent fev -- not working
            [Char] -> [Char] -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => [Char] -> a -> m ()
dbg1IO [Char]
"fsnotify" ([Char] -> IO ()) -> [Char] -> IO ()
forall a b. (a -> b) -> a -> b
$ Event -> [Char]
forall a. Show a => a -> [Char]
show Event
fev
            BChan AppEvent -> AppEvent -> IO ()
forall a. BChan a -> a -> IO ()
writeChan BChan AppEvent
eventChan AppEvent
FileChange
            )

        -- and start the app. Must be inside the withManager block. (XXX makevty too ?)
#if MIN_VERSION_brick(3,1,0)
        void $ customMain (Just makevty) (Just eventChan) app ui
#else
        vty <- makevty
        void $ customMain vty makevty (Just eventChan) app ui
#endif

brickApp :: Maybe String -> App UIState AppEvent Name
brickApp :: Maybe [Char] -> App UIState AppEvent Name
brickApp Maybe [Char]
mtheme = App {
    appStartEvent :: EventM Name UIState ()
appStartEvent   = () -> EventM Name UIState ()
forall a. a -> EventM Name UIState a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  , appAttrMap :: UIState -> AttrMap
appAttrMap      = AttrMap -> UIState -> AttrMap
forall a b. a -> b -> a
const (AttrMap -> UIState -> AttrMap) -> AttrMap -> UIState -> AttrMap
forall a b. (a -> b) -> a -> b
$ AttrMap -> Maybe AttrMap -> AttrMap
forall a. a -> Maybe a -> a
fromMaybe AttrMap
defaultTheme (Maybe AttrMap -> AttrMap) -> Maybe AttrMap -> AttrMap
forall a b. (a -> b) -> a -> b
$ [Char] -> Maybe AttrMap
getTheme ([Char] -> Maybe AttrMap) -> Maybe [Char] -> Maybe AttrMap
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe [Char]
mtheme
  , appChooseCursor :: UIState -> [CursorLocation Name] -> Maybe (CursorLocation Name)
appChooseCursor = UIState -> [CursorLocation Name] -> Maybe (CursorLocation Name)
forall s n. s -> [CursorLocation n] -> Maybe (CursorLocation n)
showFirstCursor
  , appHandleEvent :: BrickEvent Name AppEvent -> EventM Name UIState ()
appHandleEvent  = BrickEvent Name AppEvent -> EventM Name UIState ()
uiHandle
  , appDraw :: UIState -> [Widget Name]
appDraw         = UIState -> [Widget Name]
uiDraw
  }

uiHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
uiHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
uiHandle BrickEvent Name AppEvent
ev = do
  [Char] -> EventM Name UIState ()
forall s. [Char] -> EventM Name s ()
dbguiEv ([Char] -> EventM Name UIState ())
-> [Char] -> EventM Name UIState ()
forall a b. (a -> b) -> a -> b
$ [Char]
"\n==== " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ BrickEvent Name AppEvent -> [Char]
forall a. Show a => a -> [Char]
show BrickEvent Name AppEvent
ev
  -- dismiss any displayed warnings on the next key press (which is otherwise handled as usual)
  case BrickEvent Name AppEvent
ev of
    VtyEvent (EvKey Key
_ [Modifier]
_) -> (UIState -> UIState) -> EventM Name UIState ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify ((UIState -> UIState) -> EventM Name UIState ())
-> (UIState -> UIState) -> EventM Name UIState ()
forall a b. (a -> b) -> a -> b
$ \UIState
u -> if [[Char]] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (UIState -> [[Char]]
aWarnings UIState
u) then UIState
u else UIState
u{aWarnings=[]}
    BrickEvent Name AppEvent
_ -> () -> EventM Name UIState ()
forall a. a -> EventM Name UIState a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  -- track focus, to recognise and ignore a click that just brings the window forward
  now <- IO UTCTime -> EventM Name UIState UTCTime
forall a. IO a -> EventM Name UIState a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO IO UTCTime
getCurrentTime
  ui0 <- get
  let (clickfocus, ignore) = clickFocusStep now ev (aClickFocus ui0)
      ui = UIState
ui0{aClickFocus=clickfocus}
  put ui
  case (ev, aScreen ui) of
    -- no redraw, to keep the time between a focus event and its click short
    (BrickEvent Name AppEvent, Screen)
_ | Bool
ignore -> EventM Name UIState ()
forall n s. EventM n s ()
continueWithoutRedraw
    -- C-c: quit, from any screen or mode (vty's raw mode delivers it as a key, not SIGINT)
    (VtyEvent (EvKey (KChar Char
'c') [Modifier
MCtrl]), Screen
_) -> EventM Name UIState ()
forall n s. EventM n s ()
halt
    (BrickEvent Name AppEvent
_, MS MenuScreenState
sst) -> MenuScreenState
-> BrickEvent Name AppEvent -> EventM Name UIState ()
msHandle MenuScreenState
sst BrickEvent Name AppEvent
ev
    (BrickEvent Name AppEvent
_, AS AccountsScreenState
sst) -> AccountsScreenState
-> BrickEvent Name AppEvent -> EventM Name UIState ()
asHandle AccountsScreenState
sst BrickEvent Name AppEvent
ev
    (BrickEvent Name AppEvent
_, RS RegisterScreenState
sst) -> RegisterScreenState
-> BrickEvent Name AppEvent -> EventM Name UIState ()
rsHandle RegisterScreenState
sst BrickEvent Name AppEvent
ev
    (BrickEvent Name AppEvent
_, TS TransactionScreenState
sst) -> TransactionScreenState
-> BrickEvent Name AppEvent -> EventM Name UIState ()
tsHandle TransactionScreenState
sst BrickEvent Name AppEvent
ev
    (BrickEvent Name AppEvent
_, ES ErrorScreenState
sst) -> ErrorScreenState
-> BrickEvent Name AppEvent -> EventM Name UIState ()
esHandle ErrorScreenState
sst BrickEvent Name AppEvent
ev

uiDraw :: UIState -> [Widget Name]
uiDraw :: UIState -> [Widget Name]
uiDraw UIState
ui = case [[Char]] -> [[Char]]
forall a. [a] -> [a]
reverse ([[Char]] -> [[Char]]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> a -> b
$ UIState -> [[Char]]
aWarnings UIState
ui of
    []           -> [Widget Name]
screenlayers
    [Char]
latest:[[Char]]
older -> [Char] -> Int -> Widget Name
warningOverlay [Char]
latest ([[Char]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[Char]]
older) Widget Name -> [Widget Name] -> [Widget Name]
forall a. a -> [a] -> [a]
: [Widget Name]
screenlayers
  where
    screenlayers :: [Widget Name]
screenlayers =
      case UIState -> Screen
aScreen UIState
ui of
        MS MenuScreenState
sst -> MenuScreenState -> UIState -> [Widget Name]
msDraw MenuScreenState
sst UIState
ui
        AS AccountsScreenState
sst -> AccountsScreenState -> UIState -> [Widget Name]
asDraw AccountsScreenState
sst UIState
ui
        RS RegisterScreenState
sst -> RegisterScreenState -> UIState -> [Widget Name]
rsDraw RegisterScreenState
sst UIState
ui
        TS TransactionScreenState
sst -> TransactionScreenState -> UIState -> [Widget Name]
tsDraw TransactionScreenState
sst UIState
ui
        ES ErrorScreenState
sst -> ErrorScreenState -> UIState -> [Widget Name]
esDraw ErrorScreenState
sst UIState
ui

-- | An overlay layer showing the given (most recent) warning message,
-- and how many more there are, on the screen's bottom line until the next keypress.
warningOverlay :: String -> Int -> Widget Name
warningOverlay :: [Char] -> Int -> Widget Name
warningOverlay [Char]
msg Int
nolder =
  Size -> Size -> RenderM Name (Result Name) -> Widget Name
forall n. Size -> Size -> RenderM n (Result n) -> Widget n
Widget Size
Greedy Size
Greedy (RenderM Name (Result Name) -> Widget Name)
-> RenderM Name (Result Name) -> Widget Name
forall a b. (a -> b) -> a -> b
$ do
    c <- RenderM Name (Context Name)
forall n. RenderM n (Context n)
getContext
    render $
      translateLayer (Location (0, c^.availHeightL - 1)) $
      withAttr (attrName "warning") $ str $
      " Warning: " ++ takeWhile (/='\n') msg ++ morestr ++ " "
  where
    morestr :: [Char]
morestr = if Int
nolder Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 then [Char]
" (and " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ Int -> [Char]
forall a. Show a => a -> [Char]
show Int
nolder [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" more)" else [Char]
""

#if !MIN_VERSION_brick(3,0,0)
-- | brick 3.0 renamed translateBy to translateLayer.
translateLayer :: Location -> Widget n -> Widget n
translateLayer = translateBy
#endif