| 1 |
{-| |
| 2 |
hledger-ui - a hledger add-on providing an efficient TUI. |
| 3 |
|
| 4 |
SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
Copyright (c) 2007-2025 (each year in this range) Simon Michael <[email protected]> and contributors. |
| 6 |
|
| 7 |
This program is free software: you can redistribute it and/or modify |
| 8 |
it under the terms of the GNU General Public License as published by |
| 9 |
the Free Software Foundation, either version 3 of the License, or |
| 10 |
(at your option) any later version. |
| 11 |
|
| 12 |
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; |
| 13 |
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 14 |
See the GNU General Public License for more details. |
| 15 |
You should have received a copy of the GNU General Public License along with this program. |
| 16 |
If not, see <https://www.gnu.org/licenses/>. |
| 17 |
|
| 18 |
-} |
| 19 |
|
| 20 |
{-# LANGUAGE CPP #-} |
| 21 |
{-# LANGUAGE LambdaCase #-} |
| 22 |
{-# LANGUAGE MultiParamTypeClasses #-} |
| 23 |
{-# LANGUAGE OverloadedStrings #-} |
| 24 |
{-# LANGUAGE MultiWayIf #-} |
| 25 |
|
| 26 |
module Hledger.UI.Main where |
| 27 |
|
| 28 |
import Control.Applicative ((<|>)) |
| 29 |
import Control.Concurrent (threadDelay) |
| 30 |
import Control.Concurrent.Async (withAsync) |
| 31 |
#if MIN_VERSION_base(4,20,0) |
| 32 |
import Control.Exception.Backtrace (setBacktraceMechanismState, BacktraceMechanism(..)) |
| 33 |
#endif |
| 34 |
import Control.Monad (forM_, void, when) |
| 35 |
import Data.Bifunctor (first) |
| 36 |
import Data.Function ((&)) |
| 37 |
import Data.List (find) |
| 38 |
import Data.List.Extra (nubSort) |
| 39 |
import Data.Maybe (fromMaybe) |
| 40 |
import Data.Text qualified as T |
| 41 |
import Graphics.Vty (Mode (Mouse), Vty (outputIface), Output (setMode)) |
| 42 |
import Graphics.Vty.CrossPlatform (mkVty) |
| 43 |
import Lens.Micro ((^.)) |
| 44 |
import System.Directory (canonicalizePath) |
| 45 |
import System.Environment (withProgName) |
| 46 |
import System.FilePath (takeDirectory) |
| 47 |
import System.FSNotify (Event(Added, Modified), watchDir, withManager, EventIsDirectory (IsFile)) |
| 48 |
import Brick hiding (bsDraw) |
| 49 |
import Brick.BChan qualified as BC |
| 50 |
|
| 51 |
import Hledger |
| 52 |
import Hledger.Cli hiding (progname,prognameandversion) |
| 53 |
import Hledger.UI.Theme |
| 54 |
import Hledger.UI.UIOptions |
| 55 |
import Hledger.UI.UITypes |
| 56 |
import Hledger.UI.UIState (uiState, getDepth) |
| 57 |
import Hledger.UI.UIUtils (dbguiEv, showScreenStack, showScreenSelection) |
| 58 |
import Hledger.UI.MenuScreen |
| 59 |
import Hledger.UI.AccountsScreen |
| 60 |
import Hledger.UI.CashScreen |
| 61 |
import Hledger.UI.BalancesheetScreen |
| 62 |
import Hledger.UI.IncomestatementScreen |
| 63 |
import Hledger.UI.RegisterScreen |
| 64 |
import Hledger.UI.TransactionScreen |
| 65 |
import Hledger.UI.ErrorScreen |
| 66 |
import Hledger.UI.UIScreens |
| 67 |
|
| 68 |
|
| 69 |
---------------------------------------------------------------------- |
| 70 |
|
| 71 |
newChan :: IO (BC.BChan a) |
| 72 |
newChan = BC.newBChan 10 |
| 73 |
|
| 74 |
writeChan :: BC.BChan a -> a -> IO () |
| 75 |
writeChan = BC.writeBChan |
| 76 |
|
| 77 |
|
| 78 |
hledgerUiMain :: IO () |
| 79 |
hledgerUiMain = handleExit $ withGhcDebug' $ withProgName "hledger-ui.log" $ do -- force Hledger.Utils.Debug.* to log to hledger-ui.log |
| 80 |
when (ghcDebugMode == GDPauseAtStart) $ ghcDebugPause' |
| 81 |
|
| 82 |
#if MIN_VERSION_base(4,20,0) |
| 83 |
-- Control ghc 9.10+'s stack traces. |
| 84 |
-- CostCentreBacktrace - collect cost-centre stack backtraces (only available when built with profiling) |
| 85 |
-- HasCallStackBacktrace - collect HasCallStack backtraces |
| 86 |
-- ExecutionBacktrace - collect backtraces from native execution stack unwinding |
| 87 |
-- IPEBacktrace - collect backtraces from Info Table Provenance Entries |
| 88 |
#ifdef DEBUG |
| 89 |
setBacktraceMechanismState HasCallStackBacktrace True |
| 90 |
#else |
| 91 |
setBacktraceMechanismState HasCallStackBacktrace False |
| 92 |
#endif |
| 93 |
#endif |
| 94 |
|
| 95 |
dbg1MsgIO "\n\n\n\n==== hledger-ui start" |
| 96 |
dbg1IO "args" progArgs |
| 97 |
dbg1IO "debugLevel" debugLevel |
| 98 |
|
| 99 |
opts1@UIOpts{uoCliOpts=copts@CliOpts{inputopts_=iopts,rawopts_=rawopts}} <- getHledgerUIOpts |
| 100 |
-- when (debug_ $ cliopts_ opts) $ printf "%s\n" prognameandversion >> printf "opts: %s\n" (show opts) |
| 101 |
|
| 102 |
usecolor <- useColorOnStdout |
| 103 |
-- And when it's not, disable colour in the TUI ? |
| 104 |
-- Theme.hs's themes currently hard code various colours and styles provided by vty, |
| 105 |
-- which probably are disabled automatically when terminal doesn't support them. |
| 106 |
-- But we'll at least force hledger-ui's theme to a monochrome one. |
| 107 |
let opts = if usecolor then opts1 else opts1{uoTheme=Just "terminal"} |
| 108 |
|
| 109 |
-- always generate forecasted periodic transactions; their visibility will be toggled by the UI. |
| 110 |
let copts' = copts{inputopts_=iopts{forecast_=forecast_ iopts <|> Just nulldatespan}} |
| 111 |
|
| 112 |
case True of |
| 113 |
_ | boolopt "help" rawopts -> runPager $ showModeUsage uimode ++ "\n" |
| 114 |
_ | boolopt "tldr" rawopts -> runTldrForPage "hledger-ui" |
| 115 |
_ | boolopt "info" rawopts -> runInfoForTopic "hledger-ui" Nothing |
| 116 |
_ | boolopt "man" rawopts -> runManForTopic "hledger-ui" Nothing |
| 117 |
_ | boolopt "version" rawopts -> putStrLn prognameandversion |
| 118 |
-- _ | boolopt "binary-filename" rawopts -> putStrLn (binaryfilename progname) |
| 119 |
_ -> withJournal copts' (runBrickUi opts) |
| 120 |
|
| 121 |
when (ghcDebugMode == GDPauseAtEnd) $ ghcDebugPause' |
| 122 |
|
| 123 |
runBrickUi :: UIOpts -> Journal -> IO () |
| 124 |
runBrickUi uopts0@UIOpts{uoCliOpts=copts@CliOpts{inputopts_=_iopts,reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}}} j = |
| 125 |
do |
| 126 |
let |
| 127 |
today = copts^.rsDay |
| 128 |
|
| 129 |
-- hledger-ui's query handling is currently in flux, mixing old and new approaches. |
| 130 |
-- Related: #1340, #1383, #1387. Some notes and terminology: |
| 131 |
|
| 132 |
-- The *startup query* is the Query generated at program startup, from |
| 133 |
-- command line options, arguments, and the current date. hledger CLI |
| 134 |
-- uses this. |
| 135 |
|
| 136 |
-- hledger-ui/hledger-web allow the query to be changed at will, creating |
| 137 |
-- a new *runtime query* each time. |
| 138 |
|
| 139 |
-- The startup query or part of it can be used as a *constraint query*, |
| 140 |
-- limiting all runtime queries. hledger-web does this with the startup |
| 141 |
-- report period, never showing transactions outside those dates. |
| 142 |
-- hledger-ui does not do this. |
| 143 |
|
| 144 |
-- A query is a combination of multiple subqueries/terms, which are |
| 145 |
-- generated from command line options and arguments, ui/web app runtime |
| 146 |
-- state, and/or the current date. |
| 147 |
|
| 148 |
-- Some subqueries are generated by parsing freeform user input, which |
| 149 |
-- can fail. We don't want hledger users to see such failures except: |
| 150 |
|
| 151 |
-- 1. at program startup, in which case the program exits |
| 152 |
-- 2. after entering a new freeform query in hledger-ui/web, in which case |
| 153 |
-- the change is rejected and the program keeps running |
| 154 |
|
| 155 |
-- So we should parse those kinds of subquery only at those times. Any |
| 156 |
-- subqueries which do not require parsing can be kept separate. And |
| 157 |
-- these can be combined to make the full query when needed, eg when |
| 158 |
-- hledger-ui screens are generating their data. (TODO) |
| 159 |
|
| 160 |
-- Some parts of the query are also kept separate for UI reasons. |
| 161 |
-- hledger-ui provides special UI for controlling depth (number keys), |
| 162 |
-- the report period (shift arrow keys), realness/status filters (RUPC keys) etc. |
| 163 |
-- There is also a freeform text area for extra query terms (/ key). |
| 164 |
-- It's cleaner and less conflicting to keep the former out of the latter. |
| 165 |
|
| 166 |
uopts = uopts0{ |
| 167 |
uoCliOpts=copts{ |
| 168 |
reportspec_=rspec{ |
| 169 |
_rsQuery=filteredQuery $ _rsQuery rspec, -- query with depth/date parts removed |
| 170 |
_rsReportOpts=ropts{ |
| 171 |
depth_ = queryDepth $ _rsQuery rspec, -- query's depth part |
| 172 |
period_ = periodfromoptsandargs, -- query's date part |
| 173 |
no_elide_ = True, -- avoid squashing boring account names, for a more regular tree (unlike hledger) |
| 174 |
empty_ = not $ empty_ ropts, -- show zero items by default, hide them with -E (unlike hledger) |
| 175 |
declared_ = True -- always show declared accounts even if unused |
| 176 |
} |
| 177 |
} |
| 178 |
} |
| 179 |
} |
| 180 |
where |
| 181 |
datespanfromargs = queryDateSpan (date2_ ropts) $ _rsQuery rspec |
| 182 |
periodfromoptsandargs = |
| 183 |
dateSpanAsPeriod $ spansIntersect [periodAsDateSpan $ period_ ropts, datespanfromargs] |
| 184 |
filteredQuery q = simplifyQuery $ And [queryFromFlags ropts, filtered q] |
| 185 |
where filtered = filterQuery (\x -> not $ queryIsDepth x || queryIsDate x) |
| 186 |
|
| 187 |
-- Choose the initial screen to display. |
| 188 |
-- We also set up a stack of previous screens, as if you had navigated down to it from the top. |
| 189 |
-- Note the previous screens list is ordered nearest-first, with the top-most (menu) screen last. |
| 190 |
-- Keep all of this synced with msNew. |
| 191 |
rawopts = rawopts_ $ uoCliOpts $ uopts |
| 192 |
(prevscrs, currscr) = |
| 193 |
dbg1With (showScreenStack "initial" showScreenSelection . uncurry2 (uiState defuiopts nulljournal)) $ |
| 194 |
if |
| 195 |
-- An accounts screen is specified. Its previous screen will be the menu screen with it selected. |
| 196 |
| boolopt "cash" rawopts -> ([msSetSelectedScreen csItemIndex menuscr], csacctsscr) |
| 197 |
| boolopt "bs" rawopts -> ([msSetSelectedScreen bsItemIndex menuscr], bsacctsscr) |
| 198 |
| boolopt "is" rawopts -> ([msSetSelectedScreen isItemIndex menuscr], isacctsscr) |
| 199 |
| boolopt "all" rawopts -> ([msSetSelectedScreen asItemIndex menuscr], allacctsscr) |
| 200 |
|
| 201 |
-- A register screen is specified with --register=ACCT. The initial screen stack will be: |
| 202 |
-- |
| 203 |
-- menu screen, with ACCTSSCR selected |
| 204 |
-- ACCTSSCR (the accounts screen containing ACCT), with ACCT selected |
| 205 |
-- register screen for ACCT |
| 206 |
-- |
| 207 |
| Just apat <- uoRegister uopts -> |
| 208 |
let |
| 209 |
-- the account being requested |
| 210 |
acct = fromMaybe (error' $ "--register "++apat++" did not match any account") -- PARTIAL: |
| 211 |
. firstMatch $ journalAccountNamesDeclaredOrImplied j |
| 212 |
where |
| 213 |
firstMatch = case toRegexCI $ T.pack apat of |
| 214 |
Right re -> find (regexMatchText re) |
| 215 |
Left _ -> const Nothing |
| 216 |
|
| 217 |
-- the register screen for acct |
| 218 |
regscr = |
| 219 |
rsSetAccount acct False $ |
| 220 |
rsNew uopts today j acct forceinclusive |
| 221 |
where |
| 222 |
forceinclusive = case getDepth ui of |
| 223 |
Just de -> accountNameLevel acct >= de |
| 224 |
Nothing -> False |
| 225 |
|
| 226 |
-- The accounts screen containing acct. |
| 227 |
-- Keep these selidx values synced with the menu items in msNew. |
| 228 |
(acctsscr, selidx) = |
| 229 |
case journalAccountType j acct of |
| 230 |
Just t | isBalanceSheetAccountType t -> (bsacctsscr, 1) |
| 231 |
Just t | isIncomeStatementAccountType t -> (isacctsscr, 2) |
| 232 |
_ -> (allacctsscr,0) |
| 233 |
& first (asSetSelectedAccount acct) |
| 234 |
|
| 235 |
-- the menu screen |
| 236 |
menuscr' = msSetSelectedScreen selidx menuscr |
| 237 |
in ([acctsscr, menuscr'], regscr) |
| 238 |
|
| 239 |
-- Otherwise, start on the menu screen. |
| 240 |
| otherwise -> ([], menuscr) |
| 241 |
|
| 242 |
where |
| 243 |
menuscr = msNew |
| 244 |
allacctsscr = asNew uopts today j Nothing |
| 245 |
csacctsscr = csNew uopts today j Nothing |
| 246 |
bsacctsscr = bsNew uopts today j Nothing |
| 247 |
isacctsscr = isNew uopts today j Nothing |
| 248 |
|
| 249 |
ui = uiState uopts j prevscrs currscr |
| 250 |
app = brickApp (uoTheme uopts) |
| 251 |
|
| 252 |
-- print (length (show ui)) >> exitSuccess -- show any debug output to this point & quit |
| 253 |
|
| 254 |
let |
| 255 |
-- helper: make a Vty terminal controller with mouse support enabled |
| 256 |
makevty = do |
| 257 |
v <- mkVty mempty |
| 258 |
setMode (outputIface v) Mouse True |
| 259 |
return v |
| 260 |
|
| 261 |
if not (uoWatch uopts) |
| 262 |
then do |
| 263 |
vty <- makevty |
| 264 |
void $ customMain vty makevty Nothing app ui |
| 265 |
|
| 266 |
else do |
| 267 |
-- a channel for sending misc. events to the app |
| 268 |
eventChan <- newChan |
| 269 |
|
| 270 |
-- start a background thread reporting changes in the current date |
| 271 |
-- use async for proper child termination in GHCI |
| 272 |
let |
| 273 |
watchDate old = do |
| 274 |
threadDelay 1000000 -- 1 s |
| 275 |
new <- getCurrentDay |
| 276 |
when (new /= old) $ do |
| 277 |
let dc = DateChange old new |
| 278 |
-- dbg1IO "datechange" dc -- XXX don't uncomment until dbg*IO fixed to use traceIO, GHC may block/end thread |
| 279 |
-- traceIO $ show dc |
| 280 |
writeChan eventChan dc |
| 281 |
watchDate new |
| 282 |
|
| 283 |
withAsync |
| 284 |
-- run this small task asynchronously: |
| 285 |
(getCurrentDay >>= watchDate) |
| 286 |
-- until this main task terminates: |
| 287 |
$ \_async -> |
| 288 |
-- start one or more background threads reporting changes in the directories of our files |
| 289 |
-- XXX many quick successive saves causes the problems listed in BUGS |
| 290 |
-- with Debounce increased to 1s it easily gets stuck on an error or blank screen |
| 291 |
-- until you press g, but it becomes responsive again quickly. |
| 292 |
-- withManagerConf defaultConfig{confDebounce=Debounce 1} $ \mgr -> do |
| 293 |
-- with Debounce at the default 1ms it clears transient errors itself |
| 294 |
-- but gets tied up for ages |
| 295 |
withManager $ \mgr -> do |
| 296 |
files <- mapM (canonicalizePath . fst) $ jfiles j |
| 297 |
let directories = nubSort $ map takeDirectory files |
| 298 |
dbg1IO "files" files |
| 299 |
dbg1IO "directories to watch" directories |
| 300 |
|
| 301 |
forM_ directories $ \d -> watchDir |
| 302 |
mgr |
| 303 |
d |
| 304 |
-- predicate: ignore changes not involving our files |
| 305 |
(\case |
| 306 |
Added f _ IsFile -> f `elem` files -- for editors which write the whole file from scratch on saves |
| 307 |
Modified f _ IsFile -> f `elem` files -- for editors which modify existing files in place |
| 308 |
-- we don't handle adding/removing journal files right now |
| 309 |
-- and there might be some of those events from tmp files |
| 310 |
-- clogging things up so let's ignore them |
| 311 |
_ -> False |
| 312 |
) |
| 313 |
-- action: send event to app |
| 314 |
(\fev -> do |
| 315 |
-- return $ dbglog "fsnotify" $ showFSNEvent fev -- not working |
| 316 |
dbg1IO "fsnotify" $ show fev |
| 317 |
writeChan eventChan FileChange |
| 318 |
) |
| 319 |
|
| 320 |
-- and start the app. Must be inside the withManager block. (XXX makevty too ?) |
| 321 |
vty <- makevty |
| 322 |
void $ customMain vty makevty (Just eventChan) app ui |
| 323 |
|
| 324 |
brickApp :: Maybe String -> App UIState AppEvent Name |
| 325 |
brickApp mtheme = App { |
| 326 |
appStartEvent = return () |
| 327 |
, appAttrMap = const $ fromMaybe defaultTheme $ getTheme =<< mtheme |
| 328 |
, appChooseCursor = showFirstCursor |
| 329 |
, appHandleEvent = uiHandle |
| 330 |
, appDraw = uiDraw |
| 331 |
} |
| 332 |
|
| 333 |
uiHandle :: BrickEvent Name AppEvent -> EventM Name UIState () |
| 334 |
uiHandle ev = do |
| 335 |
dbguiEv $ "\n==== " ++ show ev |
| 336 |
ui <- get |
| 337 |
case aScreen ui of |
| 338 |
MS _ -> msHandle ev |
| 339 |
AS _ -> asHandle ev |
| 340 |
CS _ -> csHandle ev |
| 341 |
BS _ -> bsHandle ev |
| 342 |
IS _ -> isHandle ev |
| 343 |
RS _ -> rsHandle ev |
| 344 |
TS _ -> tsHandle ev |
| 345 |
ES _ -> esHandle ev |
| 346 |
|
| 347 |
uiDraw :: UIState -> [Widget Name] |
| 348 |
uiDraw ui = |
| 349 |
case aScreen ui of |
| 350 |
MS _ -> msDraw ui |
| 351 |
AS _ -> asDraw ui |
| 352 |
CS _ -> csDraw ui |
| 353 |
BS _ -> bsDraw ui |
| 354 |
IS _ -> isDraw ui |
| 355 |
RS _ -> rsDraw ui |
| 356 |
TS _ -> tsDraw ui |
| 357 |
ES _ -> esDraw ui |