Debian Codegraph @

Hledger/UI/RegisterScreen.hs

raw
1 -- The account register screen, showing transactions in an account, like hledger-web's register.
2
3 {-# LANGUAGE CPP #-}
4 {-# LANGUAGE FlexibleContexts #-}
5 {-# LANGUAGE OverloadedStrings #-}
6 {-# LANGUAGE RecordWildCards #-}
7 {-# OPTIONS_GHC -Wno-incomplete-record-updates #-}
8
9 module Hledger.UI.RegisterScreen
10 (rsNew
11 ,rsUpdate
12 ,rsDraw
13 ,rsHandle
14 ,rsSetAccount
15 ,rsCenterSelection
16 )
17 where
18
19 import Control.Monad
20 import Control.Monad.IO.Class (liftIO)
21 import Data.Bifunctor (bimap, Bifunctor (second))
22 #if MIN_VERSION_base(4,19,0)
23 import Data.List hiding ((!?))
24 #else
25 import Data.List
26 #endif
27 import Data.Maybe
28 import Data.Text qualified as T
29 import Data.Vector qualified as V
30 import Data.Vector ((!?))
31 import Graphics.Vty (Event(..),Key(..),Modifier(..), Button (BLeft, BScrollDown, BScrollUp))
32 import Brick
33 import Brick.Widgets.List hiding (reverse)
34 import Brick.Widgets.Edit
35 import Lens.Micro.Platform
36 import System.Console.ANSI
37
38 import Hledger
39 import Hledger.Cli hiding (mode, progname,prognameandversion)
40 import Hledger.UI.UIOptions
41 import Hledger.UI.UITypes
42 import Hledger.UI.UIState
43 import Hledger.UI.UIUtils
44 import Hledger.UI.UIScreens
45 import Hledger.UI.Editor
46 import Hledger.UI.ErrorScreen (uiReload, uiReloadIfFileChanged, uiToggleBalanceAssertions)
47
48 rsDraw :: UIState -> [Widget Name]
49 rsDraw UIState{aopts=_uopts@UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec}}
50 ,aScreen=RS RSS{..}
51 ,aMode=mode
52 } = dbgui "rsDraw" $
53 case mode of
54 Help -> [helpDialog, maincontent]
55 _ -> [maincontent]
56 where
57 displayitems = V.toList $ listElements $ _rssList
58 maincontent = Widget Greedy Greedy $ do
59 -- calculate column widths, based on current available width
60 c <- getContext
61 let
62 totalwidth = c^.availWidthL
63 - 2 -- XXX due to margin ? shouldn't be necessary (cf UIUtils)
64 -- the date column is fixed width
65 datewidth = 10
66 -- multi-commodity amounts rendered on one line can be
67 -- arbitrarily wide. Give the two amounts as much space as
68 -- they need, while reserving a minimum of space for other
69 -- columns and whitespace. If they don't get all they need,
70 -- allocate it to them proportionally to their maximum widths.
71 whitespacewidth = 10 -- inter-column whitespace, fixed width
72 minnonamtcolswidth = datewidth + 1 + 2 + 2 -- date column plus at least 1 for status and 2 for desc and accts
73 maxamtswidth = max 0 (totalwidth - minnonamtcolswidth - whitespacewidth)
74 maxchangewidthseen = maximum' $ map (wbWidth . rsItemChangeAmount) displayitems
75 maxbalwidthseen = maximum' $ map (wbWidth . rsItemBalanceAmount) displayitems
76 changewidthproportion = fromIntegral maxchangewidthseen `divideSafe` fromIntegral (maxchangewidthseen + maxbalwidthseen)
77 maxchangewidth = round $ changewidthproportion * fromIntegral maxamtswidth
78 maxbalwidth = maxamtswidth - maxchangewidth
79 changewidth = min maxchangewidth maxchangewidthseen
80 balwidth = min maxbalwidth maxbalwidthseen
81 -- assign the remaining space to the description and accounts columns
82 -- maxdescacctswidth = totalwidth - (whitespacewidth - 4) - changewidth - balwidth
83 maxdescacctswidth =
84 -- trace (show (totalwidth, datewidth, changewidth, balwidth, whitespacewidth)) $
85 max 0 (totalwidth - datewidth - 1 - changewidth - balwidth - whitespacewidth)
86 -- allocating proportionally.
87 -- descwidth' = maximum' $ map (strWidth . second6) displayitems
88 -- acctswidth' = maximum' $ map (strWidth . third6) displayitems
89 -- descwidthproportion = (descwidth' + acctswidth') / descwidth'
90 -- maxdescwidth = min (maxdescacctswidth - 7) (maxdescacctswidth / descwidthproportion)
91 -- maxacctswidth = maxdescacctswidth - maxdescwidth
92 -- descwidth = min maxdescwidth descwidth'
93 -- acctswidth = min maxacctswidth acctswidth'
94 -- allocating equally.
95 descwidth = maxdescacctswidth `div` 2
96 acctswidth = maxdescacctswidth - descwidth
97 colwidths = (datewidth,descwidth,acctswidth,changewidth,balwidth)
98
99 render $ defaultLayout toplabel bottomlabel $ renderList (rsDrawItem colwidths) True _rssList
100
101 where
102 ropts = _rsReportOpts rspec
103 ishistorical = balanceaccum_ ropts == Historical
104 -- inclusive = tree_ ropts || rsForceInclusive
105
106 toplabel =
107 withAttr (attrName "border" <> attrName "bold") (str $ T.unpack $ replaceHiddenAccountsNameWith "All" _rssAccount)
108 -- <+> withAttr ("border" <> "query") (str $ if inclusive then "" else " exclusive")
109 <+> togglefilters
110 <+> str " transactions"
111 -- <+> str (if ishistorical then " historical total" else " period total")
112 <+> borderQueryStr (T.unpack . T.unwords . map textQuoteIfNeeded $ querystring_ ropts)
113 -- <+> str " and subs"
114 <+> borderPeriodStr "in" (period_ ropts)
115 <+> str " ("
116 <+> cur
117 <+> str "/"
118 <+> total
119 <+> str ")"
120 <+> (if ignore_assertions_ . balancingopts_ $ inputopts_ copts then withAttr (attrName "border" <> attrName "query") (str " ignoring balance assertions") else str "")
121 where
122 togglefilters =
123 case concat [
124 uiShowStatus copts $ statuses_ ropts
125 ,if real_ ropts then ["real"] else []
126 ,if empty_ ropts then [] else ["nonzero"]
127 ] of
128 [] -> str ""
129 fs -> withAttr (attrName "border" <> attrName "query") (str $ " " ++ intercalate ", " fs)
130 cur = str $ case listSelected _rssList of
131 Nothing -> "-"
132 Just i -> show (i + 1)
133 total = str $ show $ length nonblanks
134 nonblanks = V.takeWhile (not . T.null . rsItemDate) $ listElements $ _rssList
135
136 -- query = query_ $ reportopts_ $ cliopts_ opts
137
138 bottomlabel = case mode of
139 Minibuffer label ed -> minibuffer label ed
140 _ -> quickhelp
141 where
142 quickhelp = borderKeysStr' [
143 ("LEFT", str "back")
144 -- ,("RIGHT", str "transaction")
145
146 -- tree/list mode - rsForceInclusive may override, but use tree_ to ensure a visible toggle effect
147 ,("t", renderToggle (tree_ ropts) "list(-subs)" "tree(+subs)")
148 -- ,("t", str "tree(+subs)")
149 -- ,("l", str "list(-subs)")
150
151 ,("H", renderToggle (not ishistorical) "historical" "period")
152 ,("F", renderToggle1 (isJust . forecast_ . inputopts_ $ copts) "forecast")
153 -- ,("a", "add")
154 -- ,("g", "reload")
155 ,("?", str "help")
156 -- ,("q", "quit")
157 ]
158
159 rsDraw _ = dbgui "rsDraw" $ errorWrongScreenType "rsDraw" -- PARTIAL:
160
161 rsDrawItem :: (Int,Int,Int,Int,Int) -> Bool -> RegisterScreenItem -> Widget Name
162 rsDrawItem (datewidth,descwidth,acctswidth,changewidth,balwidth) selected RegisterScreenItem{..} =
163 Widget Greedy Fixed $ do
164 render $
165 txt (fitText (Just datewidth) (Just datewidth) True True rsItemDate) <+>
166 txt " " <+>
167 txt (fitText (Just 1) (Just 1) True True (T.pack $ show rsItemStatus)) <+>
168 txt " " <+>
169 txt (fitText (Just descwidth) (Just descwidth) True True rsItemDescription) <+>
170 txt " " <+>
171 txt (fitText (Just acctswidth) (Just acctswidth) True True rsItemOtherAccounts) <+>
172 txt " " <+>
173 withAttr changeattr (txt $ fitText (Just changewidth) (Just changewidth) True False changeAmt) <+>
174 txt " " <+>
175 withAttr balattr (txt $ fitText (Just balwidth) (Just balwidth) True False balanceAmt)
176 where
177 changeAmt = wbToText rsItemChangeAmount
178 balanceAmt = wbToText rsItemBalanceAmount
179 changeattr | T.any (=='-') changeAmt = sel $ attrName "list" <> attrName "amount" <> attrName "decrease"
180 | otherwise = sel $ attrName "list" <> attrName "amount" <> attrName "increase"
181 balattr | T.any (=='-') balanceAmt = sel $ attrName "list" <> attrName "balance" <> attrName "negative"
182 | otherwise = sel $ attrName "list" <> attrName "balance" <> attrName "positive"
183 sel | selected = (<> attrName "selected")
184 | otherwise = id
185
186 -- XXX clean up like asHandle
187 rsHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
188 rsHandle ev = do
189 ui0 <- get'
190 dbguiEv "rsHandle"
191 case ui0 of
192 ui@UIState{
193 aScreen=RS sst@RSS{..}
194 ,aopts=UIOpts{uoCliOpts=copts}
195 ,ajournal=j
196 ,aMode=mode
197 } -> do
198 d <- liftIO getCurrentDay
199 let
200 journalspan = journalDateSpan False j
201 nonblanks = V.takeWhile (not . T.null . rsItemDate) $ listElements $ _rssList
202 lastnonblankidx = max 0 (length nonblanks - 1)
203 numberedtxns = zipWith (curry (second rsItemTransaction)) [(1::Integer)..] (V.toList nonblanks)
204 -- the transactions being shown and the currently selected or last transaction, if any:
205 mtxns :: Maybe ([NumberedTransaction], NumberedTransaction)
206 mtxns = case numberedtxns of
207 [] -> Nothing
208 nts@(_:_) -> Just (nts, maybe (last nts) (bimap ((+1).fromIntegral) rsItemTransaction) $
209 listSelectedElement _rssList) -- PARTIAL: last won't fail
210 case mode of
211 Minibuffer _ ed ->
212 case ev of
213 VtyEvent (EvKey KEsc []) -> modify' closeMinibuffer
214 VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens j d $
215 case setFilter s $ closeMinibuffer ui of
216 Left bad -> showMinibuffer "Cannot compile regular expression" (Just bad) ui
217 Right ui' -> ui'
218 where s = chomp . unlines . map strip $ getEditContents ed
219 -- VtyEvent (EvKey (KChar '/') []) -> put' $ regenerateScreens j d $ showMinibuffer ui
220 VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw
221 VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui
222 VtyEvent e -> do
223 ed' <- nestEventM' ed $ handleEditorEvent (VtyEvent e)
224 put' ui{aMode=Minibuffer "filter" ed'}
225 AppEvent _ -> return ()
226 MouseDown{} -> return ()
227 MouseUp{} -> return ()
228
229 Help ->
230 case ev of
231 -- VtyEvent (EvKey (KChar 'q') []) -> halt
232 VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw
233 VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui
234 _ -> helpHandle ev
235
236 Normal ->
237 case ev of
238 VtyEvent (EvKey (KChar 'q') []) -> halt
239 VtyEvent (EvKey KEsc []) -> put' $ resetScreens d ui
240 VtyEvent (EvKey (KChar c) []) | c == '?' -> put' $ setMode Help ui
241
242 -- AppEvents arrive in --watch mode, see AccountsScreen
243 AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old ->
244 put' $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui
245 where
246 p = reportPeriod ui
247
248 e | e `elem` [AppEvent FileChange, VtyEvent (EvKey (KChar 'g') [])] -> uiReload copts d ui >>= put'
249
250 VtyEvent (EvKey (KChar 'I') []) -> uiToggleBalanceAssertions d ui
251 VtyEvent (EvKey (KChar 'a') []) -> suspendAndResume $ clearScreen >> setCursorPosition 0 0 >> add (cliOptsDropArgs copts) j >> uiReloadIfFileChanged copts d j ui
252 VtyEvent (EvKey (KChar 'A') []) -> suspendAndResume $ void (runIadd (journalFilePath j)) >> uiReloadIfFileChanged copts d j ui
253 VtyEvent (EvKey (KChar 'T') []) -> put' $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui
254 VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor pos f) >> uiReloadIfFileChanged copts d j ui
255 where
256 (pos,f) = case listSelectedElement _rssList of
257 Nothing -> (endPosition, journalFilePath j)
258 Just (_, RegisterScreenItem{
259 rsItemTransaction=Transaction{tsourcepos=(SourcePos f' l c,_)}}) -> (Just (unPos l, Just $ unPos c),f')
260
261 -- display mode/query toggles
262 VtyEvent (EvKey (KChar 'B') []) -> rsCenterSelection (regenerateScreens j d $ toggleConversionOp ui) >>= put'
263 VtyEvent (EvKey (KChar 'V') []) -> rsCenterSelection (regenerateScreens j d $ toggleValue ui) >>= put'
264 VtyEvent (EvKey (KChar 'H') []) -> rsCenterSelection (regenerateScreens j d $ toggleHistorical ui) >>= put'
265 VtyEvent (EvKey (KChar 't') []) -> rsCenterSelection (regenerateScreens j d $ toggleTree ui) >>= put'
266 VtyEvent (EvKey (KChar c) []) | c `elem` ['z','Z'] -> rsCenterSelection (regenerateScreens j d $ toggleEmpty ui) >>= put'
267 VtyEvent (EvKey (KChar 'R') []) -> rsCenterSelection (regenerateScreens j d $ toggleReal ui) >>= put'
268 VtyEvent (EvKey (KChar 'U') []) -> rsCenterSelection (regenerateScreens j d $ toggleUnmarked ui) >>= put'
269 VtyEvent (EvKey (KChar 'P') []) -> rsCenterSelection (regenerateScreens j d $ togglePending ui) >>= put'
270 VtyEvent (EvKey (KChar 'C') []) -> rsCenterSelection (regenerateScreens j d $ toggleCleared ui) >>= put'
271 VtyEvent (EvKey (KChar 'F') []) -> rsCenterSelection (regenerateScreens j d $ toggleForecast d ui) >>= put'
272 VtyEvent (EvKey (KChar 'J') []) -> do
273 let l' = listMoveBy 10 _rssList
274 let l'' = if isBlankElement (listSelectedElement l')
275 then listMoveTo lastnonblankidx l'
276 else l'
277 put' ui{aScreen=RS sst{_rssList=l''}}
278
279 VtyEvent (EvKey (KChar 'K') []) -> do
280 let l' = listMoveBy (-10) _rssList
281 put' ui{aScreen=RS sst{_rssList=l'}}
282 VtyEvent (EvKey (KChar '/') []) -> put' $ regenerateScreens j d $ showMinibuffer "filter" Nothing ui
283 VtyEvent (EvKey (KDown) [MShift]) -> put' $ regenerateScreens j d $ shrinkReportPeriod d ui
284 VtyEvent (EvKey (KUp) [MShift]) -> put' $ regenerateScreens j d $ growReportPeriod d ui
285 VtyEvent (EvKey (KRight) [MShift]) -> put' $ regenerateScreens j d $ nextReportPeriod journalspan ui
286 VtyEvent (EvKey (KLeft) [MShift]) -> put' $ regenerateScreens j d $ previousReportPeriod journalspan ui
287 VtyEvent (EvKey k []) | k `elem` [KBS, KDel] -> (put' $ regenerateScreens j d $ resetFilter ui)
288 VtyEvent (EvKey (KChar 'l') [MCtrl]) -> scrollSelectionToMiddle _rssList >> redraw
289 VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui
290
291 -- exit screen on LEFT
292 VtyEvent e | e `elem` moveLeftEvents -> put' $ popScreen ui
293 -- or on a click in the app's left margin. This is a VtyEvent since not in a clickable widget.
294 VtyEvent (EvMouseUp x _y (Just BLeft)) | x==0 -> put' $ popScreen ui
295
296 -- enter transaction screen on RIGHT
297 VtyEvent e | e `elem` moveRightEvents ->
298 case mtxns of Nothing -> return (); Just (nts, nt) -> rsEnterTransactionScreen _rssAccount nts nt ui
299 -- or on transaction click
300 -- MouseDown is sometimes duplicated, https://github.com/jtdaugherty/brick/issues/347
301 -- just use it to move the selection
302 MouseDown _n BLeft _mods Location{loc=(_x,y)} | not $ (=="") clickeddate -> do
303 put' $ ui{aScreen=RS sst{_rssList=listMoveTo y _rssList}}
304 where clickeddate = maybe "" rsItemDate $ listElements _rssList !? y
305 -- and on MouseUp, enter the subscreen
306 MouseUp _n (Just BLeft) Location{loc=(_x,y)} | not $ (=="") clickeddate -> do
307 case mtxns of Nothing -> return (); Just (nts, nt) -> rsEnterTransactionScreen _rssAccount nts nt ui
308 where clickeddate = maybe "" rsItemDate $ listElements _rssList !? y
309
310 -- when selection is at the last item, DOWN scrolls instead of moving, until maximally scrolled
311 VtyEvent e | e `elem` moveDownEvents, isBlankElement mnextelement -> do
312 vScrollBy (viewportScroll $ listName $ _rssList) 1
313 where mnextelement = listSelectedElement $ listMoveDown _rssList
314
315 -- mouse scroll wheel scrolls the viewport up or down to its maximum extent,
316 -- pushing the selection when necessary.
317 MouseDown name btn _mods _loc | btn `elem` [BScrollUp, BScrollDown] -> do
318 let scrollamt = if btn==BScrollUp then -1 else 1
319 list' <- nestEventM' _rssList $ listScrollPushingSelection name (rsListSize _rssList) scrollamt
320 put' ui{aScreen=RS sst{_rssList=list'}}
321
322 -- if page down or end leads to a blank padding item, stop at last non-blank
323 VtyEvent e@(EvKey k []) | k `elem` [KPageDown, KEnd] -> do
324 l <- nestEventM' _rssList $ handleListEvent e
325 if isBlankElement $ listSelectedElement l
326 then do
327 let l' = listMoveTo lastnonblankidx l
328 scrollSelectionToMiddle l'
329 put' ui{aScreen=RS sst{_rssList=l'}}
330 else
331 put' ui{aScreen=RS sst{_rssList=l}}
332
333 -- fall through to the list's event handler (handles other [pg]up/down events)
334 VtyEvent e -> do
335 let e' = normaliseMovementKeys e
336 newitems <- nestEventM' _rssList $ handleListEvent e'
337 put' ui{aScreen=RS sst{_rssList=newitems}}
338
339 MouseDown{} -> return ()
340 MouseUp{} -> return ()
341 AppEvent _ -> return ()
342
343 _ -> errorWrongScreenType "rsHandle"
344
345 isBlankElement mel = ((rsItemDate . snd) <$> mel) == Just ""
346
347 rsListSize = V.length . V.takeWhile ((/="").rsItemDate) . listElements
348
349 rsSetAccount :: AccountName -> Bool -> Screen -> Screen
350 rsSetAccount a forceinclusive (RS st@RSS{}) =
351 RS st{_rssAccount=replaceHiddenAccountsNameWith "*" a, _rssForceInclusive=forceinclusive}
352 rsSetAccount _ _ st = st
353
354 -- | Scroll the selected item to the middle of the screen, when on the register screen.
355 -- No effect on other screens.
356 rsCenterSelection :: UIState -> EventM Name UIState UIState
357 rsCenterSelection ui@UIState{aScreen=RS sst} = do
358 scrollSelectionToMiddle $ _rssList sst
359 return ui -- ui is unchanged, but this makes the function more chainable
360 rsCenterSelection ui = return ui
361
362 rsEnterTransactionScreen :: AccountName -> [NumberedTransaction] -> NumberedTransaction -> UIState -> EventM Name UIState ()
363 rsEnterTransactionScreen acct nts nt ui = do
364 dbguiEv "rsEnterTransactionScreen"
365 put' $ pushScreen (tsNew acct nts nt) ui