Debian Codegraph @

Hledger/UI/UITypes.hs

raw
1 {- |
2 Overview:
3 hledger-ui's UIState holds the currently active screen and any previously visited
4 screens (and their states).
5 The brick App delegates all event-handling and rendering
6 to the UIState's active screen.
7 Screens have their own screen state, render function, event handler, and app state
8 update function, so they have full control.
9
10 @
11 Brick.defaultMain brickapp st
12 where
13 brickapp :: App (UIState) V.Event
14 brickapp = App {
15 appLiftVtyEvent = id
16 , appStartEvent = return
17 , appAttrMap = const theme
18 , appChooseCursor = showFirstCursor
19 , appHandleEvent = \st ev -> sHandle (aScreen st) st ev
20 , appDraw = \st -> sDraw (aScreen st) st
21 }
22 st :: UIState
23 st = (sInit s) d
24 UIState{
25 aopts=uopts'
26 ,ajournal=j
27 ,aScreen=s
28 ,aPrevScreens=prevscrs
29 ,aMinibuffer=Nothing
30 }
31 @
32 -}
33
34 {-# LANGUAGE StandaloneDeriving #-}
35 {-# LANGUAGE DeriveAnyClass #-}
36 {-# LANGUAGE FlexibleInstances #-}
37 {-# LANGUAGE OverloadedStrings #-}
38 {-# LANGUAGE TemplateHaskell #-}
39 {-# LANGUAGE EmptyDataDeriving #-}
40
41 module Hledger.UI.UITypes where
42
43 -- import Control.Concurrent (threadDelay)
44 -- import GHC.IO (unsafePerformIO)
45 import Data.Text (Text)
46 import Data.Time.Calendar (Day)
47 import Brick.Widgets.List (List)
48 import Brick.Widgets.Edit (Editor)
49 import Lens.Micro.Platform (makeLenses)
50 import Text.Show.Functions ()
51 -- import the Show instance for functions. Warning, this also re-exports it
52
53 import Hledger
54 import Hledger.Cli (HasCliOpts(..))
55 import Hledger.UI.UIOptions
56
57 data AppEvent =
58 FileChange -- one of the Journal's files has been added/modified/removed
59 | DateChange Day Day -- the current date has changed since last checked (with the old and new values)
60 deriving (Eq, Show)
61
62 -- | hledger-ui's application state. This holds one or more stateful screens.
63 -- As you navigate through screens, the old ones are saved in a stack.
64 -- The app can be in one of several modes: normal screen operation,
65 -- showing a help dialog, entering data in the minibuffer etc.
66 data UIState = UIState {
67 -- unchanging:
68 astartupopts :: UIOpts -- ^ the command-line options and query arguments specified at program start
69 -- can change while program runs:
70 ,aopts :: UIOpts -- ^ the command-line options and query arguments currently in effect
71 ,ajournal :: Journal -- ^ the journal being viewed (can change with --watch)
72 ,aPrevScreens :: [Screen] -- ^ previously visited screens, most recent first (XXX silly, reverse these)
73 ,aScreen :: Screen -- ^ the currently active screen
74 ,aMode :: Mode -- ^ the currently active mode on the current screen
75 } deriving (Show)
76
77 -- | Any screen can be in one of several modes, which modifies
78 -- its rendering and event handling.
79 -- The mode resets to Normal when entering a new screen.
80 data Mode =
81 Normal
82 | Help
83 | Minibuffer Text (Editor String Name)
84 deriving (Show,Eq)
85
86 -- Ignore the editor when comparing Modes.
87 instance Eq (Editor l n) where _ == _ = True
88
89 -- Unique names required for brick widgets, viewports, cursor locations etc.
90 data Name =
91 HelpDialog
92 | MinibufferEditor
93 | MenuList
94 | AccountsViewport
95 | AccountsList
96 | RegisterViewport
97 | RegisterList
98 | TransactionEditor
99 deriving (Ord, Show, Eq)
100
101 -- Unique names for screens the user can navigate to from the menu.
102 data ScreenName =
103 Accounts
104 | CashScreen
105 | Balancesheet
106 | Incomestatement
107 deriving (Ord, Show, Eq)
108
109 ----------------------------------------------------------------------------------------------------
110 -- | hledger-ui screen types, v1, "one screen = one module"
111 -- These types aimed for maximum decoupling of modules and ease of adding more screens.
112 -- A new screen requires
113 -- 1. a new constructor in the Screen type,
114 -- 2. a new module implementing init/draw/handle functions,
115 -- 3. a call from any other screen which enters it.
116 -- Each screen type has generically named initialisation, draw, and event handling functions,
117 -- and zero or more uniquely named screen state fields, which hold the data for a particular
118 -- instance of this screen. Note the latter create partial functions, which means that some invalid
119 -- cases need to be handled, and also that their lenses are traversals, not single-value getters.
120 -- data Screen =
121 -- AccountsScreen {
122 -- sInit :: Day -> Bool -> UIState -> UIState -- ^ function to initialise or update this screen's state
123 -- ,sDraw :: UIState -> [Widget Name] -- ^ brick renderer for this screen
124 -- ,sHandle :: BrickEvent Name AppEvent -> EventM Name UIState () -- ^ brick event handler for this screen
125 -- -- state fields.These ones have lenses:
126 -- ,_asList :: List Name AccountsScreenItem -- ^ list widget showing account names & balances
127 -- ,_asSelectedAccount :: AccountName -- ^ a backup of the account name from the list widget's selected item (or "")
128 -- }
129 -- | RegisterScreen {
130 -- sInit :: Day -> Bool -> UIState -> UIState
131 -- ,sDraw :: UIState -> [Widget Name]
132 -- ,sHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
133 -- --
134 -- ,rsList :: List Name RegisterScreenItem -- ^ list widget showing transactions affecting this account
135 -- ,rsAccount :: AccountName -- ^ the account this register is for
136 -- ,rsForceInclusive :: Bool -- ^ should this register always include subaccount transactions,
137 -- -- even when in flat mode ? (ie because entered from a
138 -- -- depth-clipped accounts screen item)
139 -- }
140 -- | TransactionScreen {
141 -- sInit :: Day -> Bool -> UIState -> UIState
142 -- ,sDraw :: UIState -> [Widget Name]
143 -- ,sHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
144 -- --
145 -- ,tsTransaction :: NumberedTransaction -- ^ the transaction we are currently viewing, and its position in the list
146 -- ,tsTransactions :: [NumberedTransaction] -- ^ list of transactions we can step through
147 -- ,tsAccount :: AccountName -- ^ the account whose register we entered this screen from
148 -- }
149 -- | ErrorScreen {
150 -- sInit :: Day -> Bool -> UIState -> UIState
151 -- ,sDraw :: UIState -> [Widget Name]
152 -- ,sHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
153 -- --
154 -- ,esError :: String -- ^ error message to show
155 -- }
156 -- deriving (Show)
157
158 ----------------------------------------------------------------------------------------------------
159 -- | hledger-ui screen types, v2, "more parts, but simpler parts"
160 -- These types aim to be more restrictive, allowing fewer invalid states, and easier to inspect
161 -- and debug. The screen types store only state, not behaviour (functions), and there is no longer
162 -- a circular dependency between UIState and Screen.
163 -- A new screen requires
164 -- 1. a new constructor in the Screen type
165 -- 2. a new screen state type if needed
166 -- 3. a new case in toAccountsLikeScreen if needed
167 -- 4. new cases in the uiDraw and uiHandle functions
168 -- 5. new constructor and updater functions in UIScreens, and a new case in screenUpdate
169 -- 6. a new module implementing draw and event-handling functions
170 -- 7. a call from any other screen which enters it (eg the menu screen, a new case in msEnterScreen)
171 -- 8. if it appears on the main menu: a new menu item in msNew
172
173 -- cf https://github.com/jtdaugherty/brick/issues/379#issuecomment-1192000374
174 -- | The various screens which a user can navigate to in hledger-ui,
175 -- along with any screen-specific parameters or data influencing what they display.
176 -- (The separate state types add code noise but seem to reduce partial code/invalid data a bit.)
177 data Screen =
178 MS MenuScreenState
179 | AS AccountsScreenState
180 | CS AccountsScreenState
181 | BS AccountsScreenState
182 | IS AccountsScreenState
183 | RS RegisterScreenState
184 | TS TransactionScreenState
185 | ES ErrorScreenState
186 deriving (Show)
187
188 -- | A subset of the screens which reuse the account screen's state and logic.
189 -- Such Screens can be converted to and from this more restrictive type
190 -- for cleaner code.
191 data AccountsLikeScreen = ALS (AccountsScreenState -> Screen) AccountsScreenState
192 deriving (Show)
193
194 toAccountsLikeScreen :: Screen -> Maybe AccountsLikeScreen
195 toAccountsLikeScreen scr = case scr of
196 AS ass -> Just $ ALS AS ass
197 CS ass -> Just $ ALS CS ass
198 BS ass -> Just $ ALS BS ass
199 IS ass -> Just $ ALS IS ass
200 _ -> Nothing
201
202 fromAccountsLikeScreen :: AccountsLikeScreen -> Screen
203 fromAccountsLikeScreen (ALS scons ass) = scons ass
204
205 data MenuScreenState = MSS {
206 -- view data:
207 _mssList :: List Name MenuScreenItem -- ^ list widget showing screen names
208 ,_mssUnused :: () -- ^ dummy field to silence warning
209 } deriving (Show)
210
211 -- Used for the accounts screen and similar screens.
212 data AccountsScreenState = ASS {
213 -- screen parameters:
214 _assSelectedAccount :: AccountName -- ^ a copy of the account name from the list's selected item (or "")
215 -- view data derived from options, reporting date, journal, and screen parameters:
216 ,_assList :: List Name AccountsScreenItem -- ^ list widget showing account names & balances
217 } deriving (Show)
218
219 data RegisterScreenState = RSS {
220 -- screen parameters:
221 _rssAccount :: AccountName -- ^ the account this register is for
222 ,_rssForceInclusive :: Bool -- ^ should this register always include subaccount transactions,
223 -- even when in flat mode ? (ie because entered from a
224 -- depth-clipped accounts screen item)
225 -- view data derived from options, reporting date, journal, and screen parameters:
226 ,_rssList :: List Name RegisterScreenItem -- ^ list widget showing transactions affecting this account
227 } deriving (Show)
228
229 data TransactionScreenState = TSS {
230 -- screen parameters:
231 _tssAccount :: AccountName -- ^ the account whose register we entered this screen from
232 ,_tssTransactions :: [NumberedTransaction] -- ^ the transactions in that register, which we can step through
233 ,_tssTransaction :: NumberedTransaction -- ^ the currently displayed transaction, and its position in the list
234 } deriving (Show)
235
236 data ErrorScreenState = ESS {
237 -- screen parameters:
238 _essError :: String -- ^ error message to show
239 ,_essUnused :: () -- ^ dummy field to silence warning
240 } deriving (Show)
241
242 -- | An item in the menu screen's list of screens.
243 data MenuScreenItem = MenuScreenItem {
244 msItemScreenName :: Text -- ^ screen display name
245 ,msItemScreen :: ScreenName -- ^ an internal name we can use to find the corresponding screen
246 } deriving (Show)
247
248 -- | An item in the accounts screen's list of accounts and balances.
249 data AccountsScreenItem = AccountsScreenItem {
250 asItemIndentLevel :: Int -- ^ indent level
251 ,asItemAccountName :: AccountName -- ^ full account name
252 ,asItemDisplayAccountName :: AccountName -- ^ full or short account name to display
253 ,asItemMixedAmount :: Maybe MixedAmount -- ^ mixed amount to display
254 } deriving (Show)
255
256 -- | An item in the register screen's list of transactions in the current account.
257 data RegisterScreenItem = RegisterScreenItem {
258 rsItemDate :: Text -- ^ date
259 ,rsItemStatus :: Status -- ^ transaction status
260 ,rsItemDescription :: Text -- ^ description
261 ,rsItemOtherAccounts :: Text -- ^ other accounts
262 ,rsItemChangeAmount :: WideBuilder -- ^ the change to the current account from this transaction
263 ,rsItemBalanceAmount :: WideBuilder -- ^ the balance or running total after this transaction
264 ,rsItemTransaction :: Transaction -- ^ the full transaction
265 }
266 deriving (Show)
267
268 type NumberedTransaction = (Integer, Transaction)
269
270 -- These TH calls must come after most of the types above.
271 -- Fields named _foo produce lenses named foo.
272 -- XXX foo fields producing fooL lenses would be preferable
273 makeLenses ''MenuScreenState
274 makeLenses ''AccountsScreenState
275 makeLenses ''RegisterScreenState
276 makeLenses ''TransactionScreenState
277 makeLenses ''ErrorScreenState
278
279 ----------------------------------------------------------------------------------------------------
280
281 -- | Error message to use in case statements adapting to the different Screen shapes.
282 errorWrongScreenType :: String -> a
283 errorWrongScreenType lbl =
284 -- unsafePerformIO $ threadDelay 2000000 >> -- delay to allow console output to be seen
285 error' (unwords [lbl, "called with wrong screen type, should not happen"])
286
287 -- dummy monoid instance needed make lenses work with List fields not common across constructors
288 --instance Monoid (List n a)
289 -- where
290 -- mempty = list "" V.empty 1 -- XXX problem in 0.7, every list requires a unique Name
291 -- mappend l1 l = l1 & listElementsL .~ (l1^.listElementsL <> l^.listElementsL)
292
293 uioptslens f ui = (\x -> ui{aopts=x}) <$> f (aopts ui)
294
295 instance HasCliOpts UIState where
296 cliOpts = uioptslens.cliOpts
297
298 instance HasInputOpts UIState where
299 inputOpts = uioptslens.inputOpts
300
301 instance HasBalancingOpts UIState where
302 balancingOpts = uioptslens.balancingOpts
303
304 instance HasReportSpec UIState where
305 reportSpec = uioptslens.reportSpec
306
307 instance HasReportOptsNoUpdate UIState where
308 reportOptsNoUpdate = uioptslens.reportOptsNoUpdate
309
310 instance HasReportOpts UIState where
311 reportOpts = uioptslens.reportOpts
312