Debian Codegraph @

app/msglist.go

raw
1 package app
2
3 import (
4 "bytes"
5 "math"
6 "strings"
7
8 sortthread "github.com/emersion/go-imap-sortthread"
9 "github.com/emersion/go-message/mail"
10 "github.com/mattn/go-runewidth"
11
12 "git.sr.ht/~rjarry/aerc/config"
13 "git.sr.ht/~rjarry/aerc/lib"
14 "git.sr.ht/~rjarry/aerc/lib/log"
15 "git.sr.ht/~rjarry/aerc/lib/state"
16 "git.sr.ht/~rjarry/aerc/lib/ui"
17 "git.sr.ht/~rjarry/aerc/models"
18 "git.sr.ht/~rjarry/aerc/worker/types"
19 "go.rockorager.dev/vaxis"
20 )
21
22 type MessageList struct {
23 Scrollable
24 height int
25 width int
26 spinner *Spinner
27 store *lib.MessageStore
28 isInitalizing bool
29 }
30
31 func NewMessageList(account *AccountView) *MessageList {
32 ml := &MessageList{
33 spinner: NewSpinner(account.UiConfig()),
34 isInitalizing: true,
35 }
36 // TODO: stop spinner, probably
37 ml.spinner.Start()
38 return ml
39 }
40
41 func (ml *MessageList) Invalidate() {
42 ui.Invalidate()
43 }
44
45 type messageRowParams struct {
46 uid models.UID
47 needsHeaders bool
48 err error
49 uiConfig *config.UIConfig
50 styles []config.StyleObject
51 headers *mail.Header
52 }
53
54 // AlignMessage aligns the selected message to position pos.
55 func (ml *MessageList) AlignMessage(pos AlignPosition) {
56 store := ml.Store()
57 if store == nil {
58 return
59 }
60 idx := 0
61 iter := store.UidsIterator()
62 for i := 0; iter.Next(); i++ {
63 if store.SelectedUid() == iter.Value().(models.UID) {
64 idx = i
65 break
66 }
67 }
68 ml.Align(idx, pos)
69 }
70
71 func (ml *MessageList) Draw(ctx *ui.Context) {
72 ml.height = ctx.Height()
73 ml.width = ctx.Width()
74 uiConfig := SelectedAccountUiConfig()
75 ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ',
76 uiConfig.GetStyle(config.STYLE_MSGLIST_DEFAULT))
77
78 acct := SelectedAccount()
79 store := ml.Store()
80 if store == nil || acct == nil || len(store.Uids()) == 0 {
81 if ml.isInitalizing {
82 ml.spinner.Draw(ctx)
83 } else {
84 ml.spinner.Stop()
85 ml.drawEmptyMessage(ctx)
86 }
87 return
88 }
89
90 ml.SetOffset(uiConfig.MsglistScrollOffset)
91 ml.UpdateScroller(ml.height, len(store.Uids()))
92 iter := store.UidsIterator()
93 for i := 0; iter.Next(); i++ {
94 if store.SelectedUid() == iter.Value().(models.UID) {
95 ml.EnsureScroll(i)
96 break
97 }
98 }
99
100 store.UpdateScroll(ml.Scroll(), ml.height)
101
102 textWidth := ctx.Width()
103 if ml.NeedScrollbar() {
104 textWidth -= 1
105 }
106 if textWidth <= 0 {
107 return
108 }
109
110 var needsHeaders []models.UID
111
112 data := state.NewDataSetter()
113 data.SetAccount(acct.acct)
114 data.SetFolder(acct.Directories().SelectedDirectory())
115
116 customDraw := func(t *ui.Table, r int, c *ui.Context) bool {
117 row := &t.Rows[r]
118 params, _ := row.Priv.(messageRowParams)
119 if params.err != nil {
120 var style vaxis.Style
121 if params.uid == store.SelectedUid() {
122 style = uiConfig.GetStyle(config.STYLE_ERROR)
123 } else {
124 style = uiConfig.GetStyleSelected(config.STYLE_ERROR)
125 }
126 ctx.Printf(0, r, style, "error: %s", params.err)
127 return true
128 }
129 if params.needsHeaders {
130 needsHeaders = append(needsHeaders, params.uid)
131 ml.spinner.Draw(ctx.Subcontext(0, r, c.Width(), 1))
132 return true
133 }
134 return false
135 }
136
137 getRowStyle := func(t *ui.Table, r int) vaxis.Style {
138 var style vaxis.Style
139 row := &t.Rows[r]
140 params, _ := row.Priv.(messageRowParams)
141 if params.uid == store.SelectedUid() {
142 style = params.uiConfig.MsgComposedStyleSelected(
143 config.STYLE_MSGLIST_DEFAULT, params.styles,
144 params.headers)
145 } else {
146 style = params.uiConfig.MsgComposedStyle(
147 config.STYLE_MSGLIST_DEFAULT, params.styles,
148 params.headers)
149 }
150 return style
151 }
152
153 table := ui.NewTable(
154 ml.height,
155 uiConfig.IndexColumns,
156 uiConfig.ColumnSeparator,
157 customDraw,
158 getRowStyle,
159 )
160
161 showThreads := store.ThreadedView()
162 threadView := newThreadView(store)
163 iter = store.UidsIterator()
164 for i := 0; iter.Next(); i++ {
165 if i < ml.Scroll() {
166 continue
167 }
168 uid := iter.Value().(models.UID)
169 if showThreads {
170 threadView.Update(data, uid)
171 }
172 if addMessage(store, uid, &table, data, uiConfig) {
173 break
174 }
175 }
176
177 table.Draw(ctx.Subcontext(0, 0, textWidth, ctx.Height()))
178
179 if ml.NeedScrollbar() {
180 scrollbarCtx := ctx.Subcontext(textWidth, 0, 1, ctx.Height())
181 ml.drawScrollbar(scrollbarCtx)
182 }
183
184 if len(store.Uids()) == 0 {
185 if store.Sorting {
186 ml.spinner.Start()
187 ml.spinner.Draw(ctx)
188 return
189 } else {
190 ml.drawEmptyMessage(ctx)
191 }
192 }
193
194 if len(needsHeaders) != 0 {
195 store.FetchHeaders(needsHeaders, nil)
196 ml.spinner.Start()
197 } else {
198 ml.spinner.Stop()
199 }
200 }
201
202 func addMessage(
203 store *lib.MessageStore, uid models.UID,
204 table *ui.Table, data state.DataSetter,
205 uiConfig *config.UIConfig,
206 ) bool {
207 msg, ok := store.Messages[uid]
208 if !ok {
209 return false
210 }
211
212 cells := make([]string, len(table.Columns))
213 params := messageRowParams{uid: uid, uiConfig: uiConfig}
214
215 if msg == nil || (msg.Envelope == nil && msg.Error == nil) {
216 params.needsHeaders = true
217 return table.AddRow(cells, params)
218 } else if msg.Error != nil {
219 params.err = msg.Error
220 return table.AddRow(cells, params)
221 }
222
223 if msg.Flags.Has(models.SeenFlag) {
224 params.styles = append(params.styles, config.STYLE_MSGLIST_READ)
225 } else {
226 params.styles = append(params.styles, config.STYLE_MSGLIST_UNREAD)
227 }
228 if msg.Flags.Has(models.AnsweredFlag) {
229 params.styles = append(params.styles, config.STYLE_MSGLIST_ANSWERED)
230 }
231 if msg.Flags.Has(models.ForwardedFlag) {
232 params.styles = append(params.styles, config.STYLE_MSGLIST_FORWARDED)
233 }
234 if msg.Flags.Has(models.FlaggedFlag) {
235 params.styles = append(params.styles, config.STYLE_MSGLIST_FLAGGED)
236 }
237 // deleted message
238 if _, ok := store.Deleted[msg.Uid]; ok {
239 params.styles = append(params.styles, config.STYLE_MSGLIST_DELETED)
240 }
241 // search result
242 if store.IsResult(msg.Uid) {
243 params.styles = append(params.styles, config.STYLE_MSGLIST_RESULT)
244 }
245 // folded thread
246 templateData, ok := data.(models.TemplateData)
247 if ok {
248 if templateData.ThreadFolded() {
249 params.styles = append(params.styles, config.STYLE_MSGLIST_THREAD_FOLDED)
250 }
251 if templateData.ThreadContext() {
252 params.styles = append(params.styles, config.STYLE_MSGLIST_THREAD_CONTEXT)
253 }
254 if templateData.ThreadOrphan() {
255 params.styles = append(params.styles, config.STYLE_MSGLIST_THREAD_ORPHAN)
256 }
257 }
258 // marked message
259 marked := store.Marker().IsMarked(msg.Uid)
260 if marked {
261 params.styles = append(params.styles, config.STYLE_MSGLIST_MARKED)
262 }
263
264 data.SetInfo(msg, len(table.Rows), marked)
265
266 for c, col := range table.Columns {
267 var buf bytes.Buffer
268 err := col.Def.Template.Execute(&buf, data.Data())
269 if err != nil {
270 log.Errorf("<%s> %s", msg.Envelope.MessageId, err)
271 cells[c] = err.Error()
272 } else {
273 cells[c] = buf.String()
274 }
275 }
276
277 params.headers = msg.RFC822Headers
278
279 return table.AddRow(cells, params)
280 }
281
282 func (ml *MessageList) drawScrollbar(ctx *ui.Context) {
283 uiConfig := SelectedAccountUiConfig()
284 gutterStyle := uiConfig.GetStyle(config.STYLE_MSGLIST_GUTTER)
285 pillStyle := uiConfig.GetStyle(config.STYLE_MSGLIST_PILL)
286
287 // gutter
288 ctx.Fill(0, 0, 1, ctx.Height(), ' ', gutterStyle)
289
290 // pill
291 pillSize := int(math.Ceil(float64(ctx.Height()) * ml.PercentVisible()))
292 pillOffset := int(math.Floor(float64(ctx.Height()) * ml.PercentScrolled()))
293 ctx.Fill(0, pillOffset, 1, pillSize, ' ', pillStyle)
294 }
295
296 func (ml *MessageList) MouseEvent(localX int, localY int, event vaxis.Event) {
297 if event, ok := event.(vaxis.Mouse); ok {
298 switch event.Button {
299 case vaxis.MouseLeftButton:
300 selectedMsg, ok := ml.Clicked(localX, localY)
301 if ok {
302 ml.Select(selectedMsg)
303 acct := SelectedAccount()
304 if acct == nil || acct.Messages().Empty() {
305 return
306 }
307 store := acct.Messages().Store()
308 msg := acct.Messages().Selected()
309 if msg == nil {
310 return
311 }
312 lib.NewMessageStoreView(msg, acct.UiConfig().AutoMarkRead,
313 store, CryptoProvider(), DecryptKeys,
314 func(view lib.MessageView, err error) {
315 if err != nil {
316 PushError(err.Error())
317 return
318 }
319 viewer, err := NewMessageViewer(acct, view)
320 if err != nil {
321 PushError(err.Error())
322 return
323 }
324 NewTab(viewer, msg.Envelope.Subject)
325 })
326 }
327 case vaxis.MouseWheelDown:
328 if ml.store != nil {
329 ml.store.Next()
330 }
331 ml.Invalidate()
332 case vaxis.MouseWheelUp:
333 if ml.store != nil {
334 ml.store.Prev()
335 }
336 ml.Invalidate()
337 }
338 }
339 }
340
341 func (ml *MessageList) Clicked(x, y int) (int, bool) {
342 nmsgs := 0
343 if store := ml.Store(); store != nil {
344 nmsgs = len(store.Uids())
345 }
346 if nmsgs == 0 || y >= nmsgs {
347 return 0, false
348 }
349 return y + ml.Scroll(), true
350 }
351
352 func (ml *MessageList) Height() int {
353 return ml.height
354 }
355
356 func (ml *MessageList) Width() int {
357 return ml.width
358 }
359
360 func (ml *MessageList) storeUpdate(store *lib.MessageStore) {
361 if ml.Store() != store {
362 return
363 }
364 ml.Invalidate()
365 }
366
367 func (ml *MessageList) SetStore(store *lib.MessageStore) {
368 if ml.Store() != store {
369 ml.Scrollable = Scrollable{}
370 }
371 ml.store = store
372 if store != nil {
373 ml.spinner.Stop()
374 store.OnUpdate(ml.storeUpdate)
375 } else {
376 ml.spinner.Start()
377 }
378 ml.Invalidate()
379 }
380
381 func (ml *MessageList) SetInitDone() {
382 ml.isInitalizing = false
383 }
384
385 func (ml *MessageList) Store() *lib.MessageStore {
386 return ml.store
387 }
388
389 func (ml *MessageList) Empty() bool {
390 store := ml.Store()
391 return store == nil || len(store.Uids()) == 0
392 }
393
394 func (ml *MessageList) Selected() *models.MessageInfo {
395 return ml.Store().Selected()
396 }
397
398 func (ml *MessageList) Select(index int) {
399 // Note that the msgstore.Select function expects a uid as argument
400 // whereas the msglist.Select expects the message number
401 store := ml.Store()
402 uids := store.Uids()
403 if len(uids) == 0 {
404 store.Select(lib.MagicUid)
405 return
406 }
407
408 iter := store.UidsIterator()
409
410 var uid models.UID
411 if index < 0 {
412 uid = uids[iter.EndIndex()]
413 } else {
414 uid = uids[iter.StartIndex()]
415 for i := 0; iter.Next(); i++ {
416 if i >= index {
417 uid = iter.Value().(models.UID)
418 break
419 }
420 }
421 }
422 store.Select(uid)
423
424 ml.Invalidate()
425 }
426
427 func (ml *MessageList) drawEmptyMessage(ctx *ui.Context) {
428 uiConfig := SelectedAccountUiConfig()
429 msg := uiConfig.EmptyMessage
430 ctx.Printf((ctx.Width()/2)-(len(msg)/2), 0,
431 uiConfig.GetStyle(config.STYLE_MSGLIST_DEFAULT), "%s", msg)
432 }
433
434 func countThreads(thread *types.Thread) (ctr int) {
435 if thread == nil {
436 return
437 }
438 _ = thread.Walk(func(t *types.Thread, _ int, _ error) error {
439 ctr++
440 return nil
441 })
442 return
443 }
444
445 func unreadInThread(thread *types.Thread, store *lib.MessageStore) (ctr int) {
446 if thread == nil {
447 return
448 }
449 _ = thread.Walk(func(t *types.Thread, _ int, _ error) error {
450 msg := store.Messages[t.Uid]
451 if msg != nil && !msg.Flags.Has(models.SeenFlag) {
452 ctr++
453 }
454 return nil
455 })
456 return
457 }
458
459 func threadPrefix(t *types.Thread, reverse bool, msglist bool) string {
460 uiConfig := SelectedAccountUiConfig()
461 var tip, prefix, firstChild, lastSibling, orphan, dummy string
462 if msglist {
463 tip = uiConfig.ThreadPrefixTip
464 } else {
465 threadPrefixSibling := "├─"
466 threadPrefixReverse := "┌─"
467 threadPrefixEnd := "└─"
468 threadStem := "│"
469 threadIndent := strings.Repeat(" ", runewidth.StringWidth(threadPrefixSibling)-1)
470
471 switch {
472 case t.Parent != nil && t.NextSibling != nil:
473 prefix += threadPrefixSibling
474 case t.Parent != nil && reverse:
475 prefix += threadPrefixReverse
476 case t.Parent != nil:
477 prefix += threadPrefixEnd
478 }
479
480 for n := t.Parent; n != nil && n.Parent != nil; n = n.Parent {
481 if n.NextSibling != nil {
482 prefix = threadStem + threadIndent + prefix
483 } else {
484 prefix = " " + threadIndent + prefix
485 }
486 }
487
488 return prefix
489 }
490
491 if reverse {
492 firstChild = uiConfig.ThreadPrefixFirstChildReverse
493 lastSibling = uiConfig.ThreadPrefixLastSiblingReverse
494 orphan = uiConfig.ThreadPrefixOrphanReverse
495 dummy = uiConfig.ThreadPrefixDummyReverse
496 } else {
497 firstChild = uiConfig.ThreadPrefixFirstChild
498 lastSibling = uiConfig.ThreadPrefixLastSibling
499 orphan = uiConfig.ThreadPrefixOrphan
500 dummy = uiConfig.ThreadPrefixDummy
501 }
502
503 var hiddenOffspring bool = t.FirstChild != nil && t.FirstChild.Hidden > 0
504 var parentAndSiblings bool = t.Parent != nil && t.NextSibling != nil
505 var hasSiblings string = uiConfig.ThreadPrefixHasSiblings
506 if t.Parent != nil && t.Parent.Hidden > 0 && t.Hidden == 0 {
507 hasSiblings = dummy
508 }
509
510 switch {
511 case parentAndSiblings && hiddenOffspring:
512 prefix = hasSiblings +
513 uiConfig.ThreadPrefixFolded
514 case parentAndSiblings && t.FirstChild != nil:
515 prefix = hasSiblings +
516 firstChild + tip
517 case parentAndSiblings:
518 prefix = hasSiblings +
519 uiConfig.ThreadPrefixLimb +
520 uiConfig.ThreadPrefixUnfolded + tip
521 case t.Parent != nil && hiddenOffspring:
522 prefix = lastSibling + uiConfig.ThreadPrefixFolded
523 case t.Parent != nil && t.FirstChild != nil:
524 prefix = lastSibling + firstChild + tip
525 case t.Parent != nil && t.FirstChild == nil:
526 prefix = lastSibling + uiConfig.ThreadPrefixLimb + tip
527 case t.Parent != nil:
528 prefix = lastSibling + uiConfig.ThreadPrefixUnfolded +
529 uiConfig.ThreadPrefixTip
530 case t.Parent == nil && hiddenOffspring:
531 prefix = uiConfig.ThreadPrefixFolded
532 case t.Parent == nil && t.Dummy:
533 prefix = dummy + tip
534 case t.Parent == nil && t.FirstChild != nil:
535 prefix = orphan
536 case t.Parent == nil && t.FirstChild == nil:
537 prefix = uiConfig.ThreadPrefixLone
538 }
539
540 for n := t.Parent; n != nil && n.Parent != nil; n = n.Parent {
541 if n.NextSibling != nil {
542 prefix = uiConfig.ThreadPrefixStem +
543 uiConfig.ThreadPrefixIndent + prefix
544 } else {
545 prefix = " " + uiConfig.ThreadPrefixIndent + prefix
546 }
547 }
548
549 return prefix
550 }
551
552 func sameParent(left, right *types.Thread) bool {
553 return left.Root() == right.Root()
554 }
555
556 func isParent(t *types.Thread) bool {
557 return t == t.Root()
558 }
559
560 func threadSubject(store *lib.MessageStore, thread *types.Thread) string {
561 msg, found := store.Messages[thread.Uid]
562 if !found || msg == nil || msg.Envelope == nil {
563 return ""
564 }
565 subject, _ := sortthread.GetBaseSubject(msg.Envelope.Subject)
566 return subject
567 }
568
569 type threadView struct {
570 store *lib.MessageStore
571 reverse bool
572 prev *types.Thread
573 prevSubj string
574 }
575
576 func newThreadView(store *lib.MessageStore) *threadView {
577 return &threadView{
578 store: store,
579 reverse: store.ReverseThreadOrder(),
580 }
581 }
582
583 func (t *threadView) Update(data state.DataSetter, uid models.UID) {
584 thread, err := t.store.Thread(uid)
585 info := state.ThreadInfo{}
586 if thread != nil && err == nil {
587 info.Prefix = threadPrefix(thread, t.reverse, true)
588 subject := threadSubject(t.store, thread)
589 info.SameSubject = subject == t.prevSubj && sameParent(thread, t.prev) && !isParent(thread)
590 t.prev = thread
591 t.prevSubj = subject
592 info.Count = countThreads(thread)
593 info.Unread = unreadInThread(thread, t.store)
594 info.Folded = thread.FirstChild != nil && thread.FirstChild.Hidden != 0
595 info.Context = thread.Context
596 info.Orphan = thread.Parent != nil && thread.Parent.Hidden > 0 && thread.Hidden == 0
597 }
598 data.SetThreading(info)
599 }