Debian Codegraph @

app/dirlist.go

raw
1 package app
2
3 import (
4 "bytes"
5 "cmp"
6 "context"
7 "math"
8 "path/filepath"
9 "regexp"
10 "slices"
11 "time"
12
13 "git.sr.ht/~rjarry/aerc/config"
14 "git.sr.ht/~rjarry/aerc/lib"
15 "git.sr.ht/~rjarry/aerc/lib/log"
16 "git.sr.ht/~rjarry/aerc/lib/state"
17 "git.sr.ht/~rjarry/aerc/lib/templates"
18 "git.sr.ht/~rjarry/aerc/lib/ui"
19 "git.sr.ht/~rjarry/aerc/models"
20 "git.sr.ht/~rjarry/aerc/worker/types"
21 "go.rockorager.dev/vaxis"
22 )
23
24 type DirectoryLister interface {
25 ui.Drawable
26
27 Selected() string
28 Previous() string
29
30 Select(string)
31 Open(string, string, time.Duration, func(types.WorkerMessage), bool)
32
33 Update(types.WorkerMessage)
34 List() []string
35 ClearList()
36
37 OnVirtualNode(func())
38
39 NextPrev(int, bool)
40
41 CollapseFolder(string)
42 ExpandFolder(string)
43 ToggleFolder(string)
44
45 SelectedMsgStore() (*lib.MessageStore, bool)
46 MsgStore(string) (*lib.MessageStore, bool)
47 SelectedDirectory() *models.Directory
48 Directory(string) *models.Directory
49 SetMsgStore(*models.Directory, *lib.MessageStore)
50
51 FilterDirs([]string, []string, bool) []string
52 GetRUECount(string) (int, int, int)
53
54 UiConfig(string) *config.UIConfig
55 }
56
57 type DirectoryList struct {
58 Scrollable
59 acctConf *config.AccountConfig
60 store *lib.DirStore
61 dirs []string
62 selecting string
63 selected string
64 previous string
65 spinner *Spinner
66 worker *types.Worker
67 ctx context.Context
68 cancel context.CancelFunc
69 }
70
71 func NewDirectoryList(acctConf *config.AccountConfig,
72 worker *types.Worker,
73 ) DirectoryLister {
74 dirlist := &DirectoryList{
75 acctConf: acctConf,
76 store: lib.NewDirStore(),
77 worker: worker,
78 }
79 dirlist.NewContext()
80 uiConf := dirlist.UiConfig("")
81 dirlist.spinner = NewSpinner(uiConf)
82 dirlist.spinner.Start()
83
84 if uiConf.DirListTree {
85 return NewDirectoryTree(dirlist)
86 }
87
88 return dirlist
89 }
90
91 func (dirlist *DirectoryList) NewContext() {
92 if dirlist.cancel != nil {
93 dirlist.cancel()
94 }
95 dirlist.ctx, dirlist.cancel = context.WithCancel(context.Background())
96 }
97
98 func (dirlist *DirectoryList) UiConfig(dir string) *config.UIConfig {
99 if dir == "" {
100 dir = dirlist.Selected()
101 }
102 return config.Ui().ForAccount(dirlist.acctConf.Name).ForFolder(dir)
103 }
104
105 func (dirlist *DirectoryList) List() []string {
106 return dirlist.dirs
107 }
108
109 func (dirlist *DirectoryList) ClearList() {
110 dirlist.store = lib.NewDirStore()
111 dirlist.dirs = []string{}
112 }
113
114 func (dirlist *DirectoryList) OnVirtualNode(_ func()) {
115 }
116
117 func (dirlist *DirectoryList) Update(msg types.WorkerMessage) {
118 switch msg := msg.(type) {
119 case *types.Done:
120 switch msg := msg.InResponseTo().(type) {
121 case *types.OpenDirectory:
122 dirlist.previous = dirlist.selected
123 dirlist.selected = msg.Directory
124 dirlist.filterDirsByFoldersConfig()
125 hasSelected := slices.Contains(dirlist.dirs, dirlist.selected)
126 if !hasSelected && dirlist.selected != "" {
127 dirlist.dirs = append(dirlist.dirs, dirlist.selected)
128 }
129 if dirlist.acctConf.EnableFoldersSort {
130 slices.Sort(dirlist.dirs)
131 }
132 dirlist.sortDirsByFoldersSortConfig()
133 store, ok := dirlist.SelectedMsgStore()
134 if !ok {
135 return
136 }
137 store.SetContext(msg.Context())
138 case *types.ListDirectories:
139 dirlist.filterDirsByFoldersConfig()
140 dirlist.sortDirsByFoldersSortConfig()
141 dirlist.spinner.Stop()
142 dirlist.Invalidate()
143 case *types.RemoveDirectory:
144 dirlist.store.Remove(msg.Directory)
145 dirlist.filterDirsByFoldersConfig()
146 dirlist.sortDirsByFoldersSortConfig()
147 case *types.CreateDirectory:
148 dirlist.filterDirsByFoldersConfig()
149 dirlist.sortDirsByFoldersSortConfig()
150 dirlist.Invalidate()
151 }
152 case *types.DirectoryInfo:
153 dir := dirlist.Directory(msg.Info.Name)
154 if dir == nil {
155 return
156 }
157 dir.Exists = msg.Info.Exists
158 dir.Recent = msg.Info.Recent
159 dir.Unseen = msg.Info.Unseen
160 if msg.Refetch {
161 store, ok := dirlist.SelectedMsgStore()
162 if ok {
163 store.Sort(store.GetCurrentSortCriteria(), nil)
164 }
165 }
166 default:
167 return
168 }
169 }
170
171 func (dirlist *DirectoryList) CollapseFolder(string) {
172 // no effect for the DirectoryList
173 }
174
175 func (dirlist *DirectoryList) ExpandFolder(string) {
176 // no effect for the DirectoryList
177 }
178
179 func (dirlist *DirectoryList) ToggleFolder(string) {
180 // no effect for the DirectoryList
181 }
182
183 func (dirlist *DirectoryList) Select(name string) {
184 dirlist.Open(name, "", dirlist.UiConfig(name).DirListDelay, nil, false)
185 }
186
187 func (dirlist *DirectoryList) Open(name string, query string, delay time.Duration,
188 cb func(types.WorkerMessage), force bool,
189 ) {
190 dirlist.selecting = name
191
192 dirlist.NewContext()
193
194 go func(ctx context.Context) {
195 defer log.PanicHandler()
196
197 select {
198 case <-time.After(delay):
199 dirlist.worker.PostAction(ctx, &types.OpenDirectory{
200 Directory: name,
201 Query: query,
202 Force: force,
203 },
204 func(msg types.WorkerMessage) {
205 switch msg := msg.(type) {
206 case *types.Error:
207 dirlist.selecting = ""
208 log.Errorf("(%s) couldn't open directory %s: %v",
209 dirlist.acctConf.Name,
210 name,
211 msg.Error)
212 case *types.Cancelled:
213 log.Debugf("OpenDirectory cancelled")
214 }
215 if cb != nil {
216 cb(msg)
217 }
218 })
219 case <-ctx.Done():
220 log.Tracef("dirlist: skip %s", name)
221 return
222 }
223 }(dirlist.ctx)
224 }
225
226 func (dirlist *DirectoryList) Selected() string {
227 return dirlist.selected
228 }
229
230 func (dirlist *DirectoryList) Previous() string {
231 return dirlist.previous
232 }
233
234 func (dirlist *DirectoryList) Invalidate() {
235 ui.Invalidate()
236 }
237
238 // Returns the Recent, Unread, and Exist counts for the named directory
239 func (dirlist *DirectoryList) GetRUECount(name string) (int, int, int) {
240 dir := dirlist.Directory(name)
241 if dir == nil {
242 return 0, 0, 0
243 }
244 return dir.Recent, dir.Unseen, dir.Exists
245 }
246
247 func (dirlist *DirectoryList) Draw(ctx *ui.Context) {
248 uiConfig := dirlist.UiConfig("")
249 ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ',
250 uiConfig.GetStyle(config.STYLE_DIRLIST_DEFAULT))
251
252 if dirlist.spinner.IsRunning() {
253 dirlist.spinner.Draw(ctx)
254 return
255 }
256
257 if len(dirlist.dirs) == 0 {
258 style := uiConfig.GetStyle(config.STYLE_DIRLIST_DEFAULT)
259 ctx.Printf(0, 0, style, "%s", uiConfig.EmptyDirlist)
260 return
261 }
262
263 dirlist.UpdateScroller(ctx.Height(), len(dirlist.dirs))
264 dirlist.EnsureScroll(findString(dirlist.dirs, dirlist.selecting))
265
266 textWidth := ctx.Width()
267 if dirlist.NeedScrollbar() {
268 textWidth -= 1
269 }
270 if textWidth < 0 {
271 return
272 }
273
274 listCtx := ctx.Subcontext(0, 0, textWidth, ctx.Height())
275
276 data := state.NewDataSetter()
277 data.SetAccount(dirlist.acctConf)
278
279 for i, name := range dirlist.dirs {
280 if i < dirlist.Scroll() {
281 continue
282 }
283 row := i - dirlist.Scroll()
284 if row >= ctx.Height() {
285 break
286 }
287
288 data.SetFolder(dirlist.Directory(name))
289 data.SetRUE([]string{name}, dirlist.GetRUECount)
290 left, right, style := dirlist.renderDir(
291 name, uiConfig, data.Data(),
292 name == dirlist.selecting, listCtx.Width(),
293 )
294 listCtx.Printf(0, row, style, "%s %s", left, right)
295 }
296
297 if dirlist.NeedScrollbar() {
298 scrollBarCtx := ctx.Subcontext(ctx.Width()-1, 0, 1, ctx.Height())
299 dirlist.drawScrollbar(scrollBarCtx)
300 }
301 }
302
303 func (dirlist *DirectoryList) renderDir(
304 path string, conf *config.UIConfig, data models.TemplateData,
305 selected bool, width int,
306 ) (string, string, vaxis.Style) {
307 var left, right string
308 var buf bytes.Buffer
309
310 var styles []config.StyleObject
311 var style vaxis.Style
312
313 r, u, _ := dirlist.GetRUECount(path)
314 if u > 0 {
315 styles = append(styles, config.STYLE_DIRLIST_UNREAD)
316 }
317 if r > 0 {
318 styles = append(styles, config.STYLE_DIRLIST_RECENT)
319 }
320 conf = conf.ForFolder(path)
321 if selected {
322 style = conf.GetComposedStyleSelected(
323 config.STYLE_DIRLIST_DEFAULT, styles)
324 } else {
325 style = conf.GetComposedStyle(
326 config.STYLE_DIRLIST_DEFAULT, styles)
327 }
328
329 err := templates.Render(conf.DirListLeft, &buf, data)
330 if err != nil {
331 log.Errorf("dirlist-left: %s", err)
332 left = err.Error()
333 style = conf.GetStyle(config.STYLE_ERROR)
334 } else {
335 left = buf.String()
336 }
337 buf.Reset()
338 err = templates.Render(conf.DirListRight, &buf, data)
339 if err != nil {
340 log.Errorf("dirlist-right: %s", err)
341 right = err.Error()
342 style = conf.GetStyle(config.STYLE_ERROR)
343 } else {
344 right = buf.String()
345 }
346 buf.Reset()
347
348 lbuf := ui.StyledString(left)
349 ui.ApplyAttrs(lbuf, style)
350 lwidth := lbuf.Len()
351 rbuf := ui.StyledString(right)
352 ui.ApplyAttrs(rbuf, style)
353 rwidth := rbuf.Len()
354
355 if lwidth+rwidth+1 > width {
356 if rwidth > 3*width/4 {
357 rwidth = 3 * width / 4
358 }
359 lwidth = width - rwidth - 1
360 ui.TruncateHead(rbuf, rwidth)
361 right = rbuf.Encode()
362 ui.Truncate(lbuf, lwidth)
363 left = lbuf.Encode()
364 } else {
365 for i := 0; i < (width - lwidth - rwidth - 1); i += 1 {
366 lbuf.Cells = append(lbuf.Cells, vaxis.Cell{
367 Character: vaxis.Character{
368 Grapheme: " ",
369 Width: 1,
370 },
371 })
372 }
373 left = lbuf.Encode()
374 right = rbuf.Encode()
375 }
376
377 return left, right, style
378 }
379
380 func (dirlist *DirectoryList) drawScrollbar(ctx *ui.Context) {
381 gutterStyle := vaxis.Style{}
382 pillStyle := vaxis.Style{Attribute: vaxis.AttrReverse}
383
384 // gutter
385 ctx.Fill(0, 0, 1, ctx.Height(), ' ', gutterStyle)
386
387 // pill
388 pillSize := int(math.Ceil(float64(ctx.Height()) * dirlist.PercentVisible()))
389 pillOffset := int(math.Floor(float64(ctx.Height()) * dirlist.PercentScrolled()))
390 ctx.Fill(0, pillOffset, 1, pillSize, ' ', pillStyle)
391 }
392
393 func (dirlist *DirectoryList) MouseEvent(localX int, localY int, event vaxis.Event) {
394 if event, ok := event.(vaxis.Mouse); ok {
395 switch event.Button {
396 case vaxis.MouseLeftButton:
397 clickedDir, ok := dirlist.Clicked(localX, localY)
398 if ok {
399 dirlist.Select(clickedDir)
400 }
401 case vaxis.MouseWheelDown:
402 dirlist.Next()
403 case vaxis.MouseWheelUp:
404 dirlist.Prev()
405 }
406 }
407 }
408
409 func (dirlist *DirectoryList) Clicked(x int, y int) (string, bool) {
410 if len(dirlist.dirs) == 0 {
411 return "", false
412 }
413 for i, name := range dirlist.dirs {
414 if i == y {
415 return name, true
416 }
417 }
418 return "", false
419 }
420
421 func (dirlist *DirectoryList) NextPrevDelta(delta int) {
422 if delta == 0 {
423 return
424 }
425 curIdx := findString(dirlist.dirs, dirlist.selecting)
426 if curIdx == len(dirlist.dirs) {
427 return
428 }
429 newIdx := curIdx + delta
430 ndirs := len(dirlist.dirs)
431
432 if ndirs == 0 {
433 return
434 }
435
436 if newIdx < 0 {
437 newIdx = ndirs - 1
438 } else if newIdx >= ndirs {
439 newIdx = 0
440 }
441
442 dirlist.Select(dirlist.dirs[newIdx])
443 }
444
445 func (dirlist *DirectoryList) NextPrev(delta int, unseen bool) {
446 if unseen {
447 ndirs := len(dirlist.dirs)
448 for range ndirs {
449 dirlist.NextPrevDelta(delta)
450 if findString(dirlist.dirs, dirlist.selecting) >= 0 {
451 if dirlist.Directory(dirlist.selecting).Unseen > 0 {
452 return
453 }
454 }
455 }
456 } else {
457 dirlist.NextPrevDelta(delta)
458 }
459 }
460
461 func (dirlist *DirectoryList) Next() {
462 dirlist.NextPrevDelta(1)
463 }
464
465 func (dirlist *DirectoryList) Prev() {
466 dirlist.NextPrevDelta(-1)
467 }
468
469 func folderMatches(folder string, pattern string) bool {
470 if len(pattern) == 0 {
471 return false
472 }
473 if pattern[0] == '~' {
474 r, err := regexp.Compile(pattern[1:])
475 if err != nil {
476 return false
477 }
478 return r.Match([]byte(folder))
479 }
480 return pattern == folder
481 }
482
483 // sortDirsByFoldersSortConfig sets dirlist.dirs to be sorted based on the
484 // AccountConfig.FoldersSort option. Folders not included in the option
485 // will be appended at the end in alphabetical order
486 func (dirlist *DirectoryList) sortDirsByFoldersSortConfig() {
487 if !dirlist.acctConf.EnableFoldersSort {
488 return
489 }
490
491 foldersSort := dirlist.acctConf.FoldersSort
492 slices.SortFunc(dirlist.dirs, func(a, b string) int {
493 idxA := findFirstMatchingString(foldersSort, a)
494 idxB := findFirstMatchingString(foldersSort, b)
495 if idxA != idxB {
496 if idxA >= 0 && idxB >= 0 {
497 return cmp.Compare(idxA, idxB)
498 }
499 if idxA >= 0 {
500 return -1
501 }
502 if idxB >= 0 {
503 return 1
504 }
505 }
506 return cmp.Compare(a, b)
507 })
508 }
509
510 // filterDirsByFoldersConfig sets dirlist.dirs to the filtered subset of the
511 // dirstore, based on AccountConfig.Folders (inclusion) and
512 // AccountConfig.FoldersExclude (exclusion), in that order.
513 func (dirlist *DirectoryList) filterDirsByFoldersConfig() {
514 dirlist.dirs = dirlist.store.List()
515
516 // 'folders' (if available) is used to make the initial list and
517 // 'folders-exclude' removes from that list.
518 configFolders := dirlist.acctConf.Folders
519 dirlist.dirs = dirlist.FilterDirs(dirlist.dirs, configFolders, false)
520
521 configFoldersExclude := dirlist.acctConf.FoldersExclude
522 dirlist.dirs = dirlist.FilterDirs(dirlist.dirs, configFoldersExclude, true)
523 }
524
525 // FilterDirs filters directories by the supplied filter. If exclude is false,
526 // the filter will only include directories from orig which exist in filters.
527 // If exclude is true, the directories in filters are removed from orig
528 func (dirlist *DirectoryList) FilterDirs(orig, filters []string, exclude bool) []string {
529 if len(filters) == 0 {
530 return orig
531 }
532 var dest []string
533 for _, folder := range orig {
534 // When excluding, include things by default, and vice-versa
535 include := exclude
536 for _, f := range filters {
537 if folderMatches(folder, f) {
538 // If matched an exclusion, don't include
539 // If matched an inclusion, do include
540 include = !exclude
541 break
542 }
543 }
544 if include {
545 dest = append(dest, folder)
546 }
547 }
548 return dest
549 }
550
551 func (dirlist *DirectoryList) SelectedMsgStore() (*lib.MessageStore, bool) {
552 return dirlist.store.MessageStore(dirlist.selected)
553 }
554
555 func (dirlist *DirectoryList) MsgStore(name string) (*lib.MessageStore, bool) {
556 return dirlist.store.MessageStore(name)
557 }
558
559 func (dirlist *DirectoryList) SelectedDirectory() *models.Directory {
560 return dirlist.store.Directory(dirlist.selected)
561 }
562
563 func (dirlist *DirectoryList) Directory(name string) *models.Directory {
564 return dirlist.store.Directory(name)
565 }
566
567 func (dirlist *DirectoryList) SetMsgStore(dir *models.Directory, msgStore *lib.MessageStore) {
568 dirlist.store.SetMessageStore(dir, msgStore)
569 msgStore.OnUpdateDirs(func() {
570 dirlist.Invalidate()
571 })
572 }
573
574 func findString(slice []string, str string) int {
575 for i, s := range slice {
576 if str == s {
577 return i
578 }
579 }
580 return -1
581 }
582
583 func findFirstMatchingString(slice []string, str string) int {
584 for i, s := range slice {
585 matches, err := filepath.Match(s, str)
586 if err == nil && matches {
587 return i
588 }
589 }
590 return -1
591 }