Debian Codegraph @

app/account.go

raw
1 package app
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "math"
9 "strings"
10 "sync"
11 "time"
12
13 "git.sr.ht/~rjarry/aerc/config"
14 "git.sr.ht/~rjarry/aerc/lib"
15 "git.sr.ht/~rjarry/aerc/lib/hooks"
16 "git.sr.ht/~rjarry/aerc/lib/log"
17 "git.sr.ht/~rjarry/aerc/lib/marker"
18 "git.sr.ht/~rjarry/aerc/lib/pama"
19 "git.sr.ht/~rjarry/aerc/lib/sort"
20 "git.sr.ht/~rjarry/aerc/lib/state"
21 "git.sr.ht/~rjarry/aerc/lib/templates"
22 "git.sr.ht/~rjarry/aerc/lib/ui"
23 "git.sr.ht/~rjarry/aerc/models"
24 "git.sr.ht/~rjarry/aerc/worker"
25 "git.sr.ht/~rjarry/aerc/worker/types"
26 "go.rockorager.dev/vaxis"
27 )
28
29 var _ ProvidesMessages = (*AccountView)(nil)
30
31 var WorkerMessages = make(chan types.WorkerMessage, 2048)
32
33 type AccountView struct {
34 sync.Mutex
35 acct *config.AccountConfig
36 dirlist DirectoryLister
37 labels []string
38 grid *ui.Grid
39 tab *ui.Tab
40 msglist *MessageList
41 worker *types.Worker
42 state state.AccountState
43 newConn bool // True if this is a first run after a new connection/reconnection
44
45 split *MessageViewer
46 splitSize int
47 splitDebounce *time.Timer
48 splitDir config.SplitDirection
49 splitLoaded bool
50
51 sidebarHidden bool
52
53 // Check-mail ticker
54 ticker *time.Ticker
55 checkingMail bool
56 // Indicates whether the account has a new mail: this is a mail that has
57 // arrived since the account tab was last focused (if it's currently
58 // focused, the flag is not set).
59 hasNew bool
60
61 // Reconnection with exponential backoff
62 reconnectRetries int
63 }
64
65 func (acct *AccountView) UiConfig() *config.UIConfig {
66 if dirlist := acct.Directories(); dirlist != nil {
67 return dirlist.UiConfig("")
68 }
69 return config.Ui().ForAccount(acct.acct.Name)
70 }
71
72 func NewAccountView(
73 acct *config.AccountConfig, deferLoop chan struct{},
74 ) (*AccountView, error) {
75 view := &AccountView{
76 acct: acct,
77 }
78
79 worker, err := worker.NewWorker(acct.Source, acct.Name, WorkerMessages)
80 if err != nil {
81 SetError(fmt.Sprintf("%s: %s", acct.Name, err))
82 log.Errorf("%s: %v", acct.Name, err)
83 return view, err
84 }
85 view.worker = worker
86
87 view.dirlist = NewDirectoryList(acct, worker)
88
89 view.msglist = NewMessageList(view)
90
91 view.Configure()
92
93 go func() {
94 defer log.PanicHandler()
95
96 if deferLoop != nil {
97 <-deferLoop
98 }
99
100 worker.Backend.Run()
101 }()
102
103 worker.PostAction(context.TODO(), &types.Configure{Config: acct}, nil)
104 worker.PostAction(context.TODO(), &types.Connect{}, nil)
105 view.SetStatus(state.ConnectionActivity("Connecting..."))
106 if acct.CheckMail.Minutes() > 0 {
107 view.CheckMailTimer(acct.CheckMail)
108 }
109
110 return view, nil
111 }
112
113 func (acct *AccountView) Configure() {
114 acct.dirlist.OnVirtualNode(func() {
115 acct.msglist.SetStore(nil)
116 acct.Invalidate()
117 })
118 acct.buildGrid()
119 acct.setTitle()
120
121 // handle splits
122 if acct.split != nil {
123 acct.split.Close()
124 }
125 splitDirection := acct.splitDir
126 acct.splitDir = config.SPLIT_NONE
127 switch splitDirection {
128 case config.SPLIT_HORIZONTAL:
129 acct.Split(acct.SplitSize())
130 case config.SPLIT_VERTICAL:
131 acct.Vsplit(acct.SplitSize())
132 }
133 }
134
135 func (acct *AccountView) SetStatus(setters ...state.SetStateFunc) {
136 for _, fn := range setters {
137 fn(&acct.state, acct.SelectedDirectory())
138 }
139 acct.UpdateStatus()
140 }
141
142 func (acct *AccountView) UpdateStatus() {
143 if acct.isSelected() {
144 UpdateStatus()
145 }
146 }
147
148 func (acct *AccountView) Select() {
149 for i, widget := range aerc.tabs.TabContent.Children() {
150 if widget == acct {
151 aerc.SelectTabIndex(i)
152 }
153 }
154 }
155
156 func (acct *AccountView) PushStatus(status string, expiry time.Duration) {
157 PushStatus(fmt.Sprintf("%s: %s", acct.acct.Name, status), expiry)
158 }
159
160 func (acct *AccountView) PushError(err error) {
161 PushError(fmt.Sprintf("%s: %v", acct.acct.Name, err))
162 }
163
164 func (acct *AccountView) PushWarning(warning string) {
165 PushWarning(fmt.Sprintf("%s: %s", acct.acct.Name, warning))
166 }
167
168 func (acct *AccountView) AccountConfig() *config.AccountConfig {
169 return acct.acct
170 }
171
172 func (acct *AccountView) Worker() *types.Worker {
173 return acct.worker
174 }
175
176 func (acct *AccountView) Name() string {
177 return acct.acct.Name
178 }
179
180 func (acct *AccountView) Invalidate() {
181 ui.Invalidate()
182 }
183
184 func (acct *AccountView) Draw(ctx *ui.Context) {
185 acct.grid.Draw(ctx)
186 }
187
188 func (acct *AccountView) MouseEvent(localX int, localY int, event vaxis.Event) {
189 acct.grid.MouseEvent(localX, localY, event)
190 }
191
192 func (acct *AccountView) Focus(focus bool) {
193 // TODO: Unfocus children I guess
194 acct.hasNew = false
195 acct.setTitle()
196 }
197
198 func (acct *AccountView) Directories() DirectoryLister {
199 return acct.dirlist
200 }
201
202 func (acct *AccountView) SetDirectories(d DirectoryLister) {
203 if acct.grid != nil {
204 acct.grid.ReplaceChild(acct.dirlist, d)
205 }
206 acct.dirlist = d
207 }
208
209 func (acct *AccountView) Labels() []string {
210 return acct.labels
211 }
212
213 func (acct *AccountView) Messages() *MessageList {
214 return acct.msglist
215 }
216
217 func (acct *AccountView) Store() *lib.MessageStore {
218 if acct.msglist == nil {
219 return nil
220 }
221 return acct.msglist.Store()
222 }
223
224 func (acct *AccountView) SelectedAccount() *AccountView {
225 return acct
226 }
227
228 func (acct *AccountView) SelectedDirectory() string {
229 return acct.dirlist.Selected()
230 }
231
232 func (acct *AccountView) SelectedMessage() (*models.MessageInfo, error) {
233 if acct.msglist == nil || acct.msglist.Store() == nil {
234 return nil, errors.New("init in progress")
235 }
236 if len(acct.msglist.Store().Uids()) == 0 {
237 return nil, errors.New("no message selected")
238 }
239 msg := acct.msglist.Selected()
240 if msg == nil {
241 return nil, errors.New("message not loaded")
242 }
243 return msg, nil
244 }
245
246 func (acct *AccountView) MarkedMessages() ([]models.UID, error) {
247 if store := acct.Store(); store != nil {
248 return store.Marker().Marked(), nil
249 }
250 return nil, errors.New("no store available")
251 }
252
253 func (acct *AccountView) SelectedMessagePart() *PartInfo {
254 return nil
255 }
256
257 func (acct *AccountView) Terminal() *Terminal {
258 if acct.split == nil {
259 return nil
260 }
261
262 return acct.split.Terminal()
263 }
264
265 func (acct *AccountView) isSelected() bool {
266 return acct == SelectedAccount()
267 }
268
269 func (acct *AccountView) newStore(name string) *lib.MessageStore {
270 uiConf := acct.dirlist.UiConfig(name)
271 dir := acct.dirlist.Directory(name)
272 role := ""
273 if dir != nil {
274 role = string(dir.Role)
275 }
276 backend := acct.AccountConfig().Backend
277 store := lib.NewMessageStore(acct.worker, name,
278 func() *config.UIConfig {
279 return config.Ui().
280 ForAccount(acct.Name()).
281 ForFolder(name)
282 },
283 func(msg *models.MessageInfo) {
284 acct.worker.Debugf("Invoking mail-received hook")
285 err := hooks.RunHook(&hooks.MailReceived{
286 Account: acct.Name(),
287 Backend: backend,
288 Folder: name,
289 Role: role,
290 MsgInfo: msg,
291 })
292 if err != nil {
293 msg := fmt.Sprintf("mail-received hook: %s", err)
294 PushError(msg)
295 }
296 }, func() {
297 acct.worker.Debugf("Invoking directory-change hook")
298 if uiConf.NewMessageBell {
299 aerc.Beep()
300 }
301 // Set a new message indicator.
302 if aerc.SelectedTab() != acct.tab {
303 acct.hasNew = true
304 }
305 }, func() {
306 acct.worker.Debugf("Invoking mail-deleted hook")
307 err := hooks.RunHook(&hooks.MailDeleted{
308 Account: acct.Name(),
309 Backend: backend,
310 Folder: name,
311 Role: role,
312 })
313 if err != nil {
314 msg := fmt.Sprintf("mail-deleted hook: %s", err)
315 PushError(msg)
316 }
317 }, func(dest string) {
318 acct.worker.Debugf("Invoking mail-added hook")
319 err := hooks.RunHook(&hooks.MailAdded{
320 Account: acct.Name(),
321 Backend: backend,
322 Folder: dest,
323 Role: role,
324 })
325 if err != nil {
326 msg := fmt.Sprintf("mail-added hook: %s", err)
327 PushError(msg)
328 }
329 }, func(add []string, remove []string, toggle []string) {
330 acct.worker.Debugf("Invoking tag-modified hook")
331 err := hooks.RunHook(&hooks.TagModified{
332 Account: acct.Name(),
333 Backend: backend,
334 Add: add,
335 Remove: remove,
336 Toggle: toggle,
337 })
338 if err != nil {
339 msg := fmt.Sprintf("tag-modified hook: %s", err)
340 PushError(msg)
341 }
342 }, func(flagname string) {
343 acct.worker.Debugf("Invoking flag-changed hook")
344 err := hooks.RunHook(&hooks.FlagChanged{
345 Account: acct.Name(),
346 Backend: backend,
347 Folder: acct.SelectedDirectory(),
348 Role: role,
349 FlagName: flagname,
350 })
351 if err != nil {
352 msg := fmt.Sprintf("flag-changed hook: %s", err)
353 PushError(msg)
354 }
355 },
356 func(msg *models.MessageInfo) {
357 acct.updateSplitView(msg)
358
359 auto := false
360 if c := acct.AccountConfig(); c != nil {
361 r, ok := c.Params["pama-auto-switch"]
362 if ok {
363 if strings.ToLower(r) == "true" {
364 auto = true
365 }
366 }
367 }
368 if !auto {
369 return
370 }
371 var name string
372 if msg != nil && msg.Envelope != nil {
373 name = pama.FromSubject(msg.Envelope.Subject)
374 }
375 pama.DebouncedSwitchProject(name)
376 },
377 )
378 store.Configure(acct.SortCriteria(uiConf))
379 store.SetMarker(marker.New(store))
380 return store
381 }
382
383 func (acct *AccountView) onMessage(msg types.WorkerMessage) {
384 msg = acct.worker.ProcessMessage(msg)
385 switch msg := msg.(type) {
386 case *types.Done:
387 switch resp := msg.InResponseTo().(type) {
388 case *types.Connect, *types.Reconnect:
389 acct.reconnectRetries = 0
390 acct.SetStatus(state.ConnectionActivity("Listing mailboxes..."))
391 log.Infof("[%s] connected.", acct.acct.Name)
392 acct.SetStatus(state.SetConnected(true))
393 log.Tracef("[%s] Listing mailboxes...", acct.acct.Name)
394 acct.worker.PostAction(context.TODO(), &types.ListDirectories{}, nil)
395 case *types.Disconnect:
396 acct.dirlist.ClearList()
397 acct.msglist.SetStore(nil)
398 log.Infof("[%s] disconnected.", acct.acct.Name)
399 acct.SetStatus(state.SetConnected(false))
400 case *types.OpenDirectory:
401 acct.dirlist.Update(msg)
402 if store, ok := acct.dirlist.SelectedMsgStore(); ok {
403 // If we've opened this dir before, we can re-render it from
404 // memory while we wait for the update and the UI feels
405 // snappier. If not, we'll unset the store and show the spinner
406 // while we download the UID list.
407 acct.msglist.SetStore(store)
408 acct.Store().Update(msg.InResponseTo())
409 } else {
410 acct.msglist.SetStore(nil)
411 }
412 case *types.CreateDirectory:
413 store := acct.newStore(resp.Directory)
414 acct.dirlist.SetMsgStore(&models.Directory{
415 Name: resp.Directory,
416 }, store)
417 acct.dirlist.Update(msg)
418 case *types.RemoveDirectory:
419 acct.dirlist.Update(msg)
420 case *types.FetchMessageHeaders:
421 if acct.newConn {
422 acct.checkMailOnStartup()
423 }
424 case *types.ListDirectories:
425 acct.dirlist.Update(msg)
426 if dir := acct.dirlist.Selected(); dir != "" {
427 acct.dirlist.Select(dir)
428 return
429 }
430 // Nothing selected, select based on config
431 dirs := acct.dirlist.List()
432 var dir string
433 for _, _dir := range dirs {
434 if _dir == acct.acct.Default {
435 dir = _dir
436 break
437 }
438 }
439 if dir == "" && len(dirs) > 0 {
440 dir = dirs[0]
441 }
442 if dir != "" {
443 acct.dirlist.Select(dir)
444 }
445 acct.msglist.SetInitDone()
446 acct.newConn = true
447 }
448 case *types.Directory:
449 store, ok := acct.dirlist.MsgStore(msg.Dir.Name)
450 if !ok {
451 store = acct.newStore(msg.Dir.Name)
452 }
453 acct.dirlist.SetMsgStore(msg.Dir, store)
454 case *types.DirectoryInfo:
455 acct.dirlist.Update(msg)
456 case *types.DirectoryContents:
457 if store, ok := acct.dirlist.MsgStore(msg.Directory); ok {
458 store.Update(msg)
459 if store == acct.Store() {
460 if acct.msglist.Store() == nil {
461 acct.msglist.SetStore(store)
462 }
463 acct.SetStatus(state.Threading(store.ThreadedView()))
464 }
465 }
466 if acct.newConn && len(msg.Uids) == 0 {
467 acct.checkMailOnStartup()
468 }
469 case *types.DirectoryThreaded:
470 if store, ok := acct.dirlist.MsgStore(msg.Directory); ok {
471 store.Update(msg)
472 if store == acct.Store() {
473 if acct.msglist.Store() == nil {
474 acct.msglist.SetStore(store)
475 }
476 acct.SetStatus(state.Threading(store.ThreadedView()))
477 }
478 }
479 if acct.newConn && len(msg.Threads) == 0 {
480 acct.checkMailOnStartup()
481 }
482 case *types.FullMessage:
483 if store, ok := acct.dirlist.SelectedMsgStore(); ok {
484 store.Update(msg)
485 }
486 case *types.MessageInfo:
487 if store, ok := acct.dirlist.MsgStore(msg.Info.Directory); ok {
488 if msg.InResponseTo() == nil || msg.ReplaceFlags {
489 // This is a server generated message update, e.g. a
490 // notification that a message has changed (this will happen
491 // mostly for flags according to section 2.3.1.1 alinea 4 in
492 // the IMAP4rev1 RFC), or a forced flag update.
493 // In case the store and the notification disagree on the Seen
494 // flag, trust the notification.
495 seen_in_sync := true
496 if msg_in_store, ok := store.Messages[msg.Info.Uid]; ok && msg_in_store != nil {
497 seen_in_sync = msg_in_store.Flags.Has(models.SeenFlag) ==
498 msg.Info.Flags.Has(models.SeenFlag)
499 }
500 if !seen_in_sync {
501 if dir := acct.dirlist.Directory(msg.Info.Directory); dir != nil {
502 // Our view of Unseen is out-of-sync with the server's;
503 // update it now.
504 if msg.Info.Flags.Has(models.SeenFlag) {
505 dir.Unseen -= 1
506 } else {
507 dir.Unseen += 1
508 }
509 dir.Unseen = acct.ensurePositive(dir.Unseen, "Unseen")
510 }
511 }
512 }
513 store.Update(msg)
514 }
515 case *types.MessagesDeleted:
516 if dir := acct.dirlist.Directory(msg.Directory); dir != nil {
517 acct.updateDirCounts(dir.Name, msg.Uids, true)
518 }
519 if store, ok := acct.dirlist.MsgStore(msg.Directory); ok {
520 store.Update(msg)
521 }
522 case *types.MessagesCopied:
523 acct.updateDirCounts(msg.Destination, msg.Uids, false)
524 case *types.MessagesMoved:
525 acct.updateDirCounts(msg.Destination, msg.Uids, false)
526 case *types.LabelList:
527 acct.labels = msg.Labels
528 case *types.ConnError:
529 log.Errorf("[%s] connection error: %v", acct.acct.Name, msg.Error)
530 acct.SetStatus(state.SetConnected(false))
531 acct.PushError(msg.Error)
532 acct.msglist.SetStore(nil)
533 // Exponential backoff: 1.8^retries seconds, capped at ReconnectMaxWait
534 var wait time.Duration
535 if acct.reconnectRetries > 0 {
536 backoff := math.Pow(1.8, float64(acct.reconnectRetries))
537 wait = time.Duration(backoff) * time.Second
538 maxWait := acct.acct.ReconnectMaxWait
539 if wait > maxWait {
540 wait = maxWait
541 }
542 }
543 acct.reconnectRetries++
544 time.AfterFunc(wait, func() {
545 acct.worker.PostAction(context.TODO(), &types.Reconnect{}, nil)
546 })
547 case *types.Error:
548 log.Errorf("[%s] unexpected error: %v", acct.acct.Name, msg.Error)
549 acct.PushError(msg.Error)
550 }
551 acct.UpdateStatus()
552 acct.setTitle()
553 }
554
555 func (acct *AccountView) ensurePositive(val int, name string) int {
556 if val < 0 {
557 acct.worker.Errorf("Unexpected negative value (%d) for %s", val, name)
558 return 0
559 }
560 return val
561 }
562
563 func (acct *AccountView) updateDirCounts(destination string, uids []models.UID, deleted bool) {
564 // Only update the destination destDir if it is initialized
565 if destDir := acct.dirlist.Directory(destination); destDir != nil {
566 var recent, unseen int
567 var accurate bool = true
568 store := acct.Store()
569 if store == nil {
570 // This could happen for example if a disconnection happened,
571 // and we can't do anything but bail out.
572 accurate = false
573 } else {
574 for _, uid := range uids {
575 // Get the message from the originating store
576 msg, ok := store.Messages[uid]
577 if !ok {
578 continue
579 }
580 // If message that was not yet loaded is copied
581 if msg == nil {
582 accurate = false
583 break
584 }
585 if msg.Flags.Has(models.RecentFlag) {
586 recent++
587 }
588 seen := msg.Flags.Has(models.SeenFlag)
589 if !seen {
590 // If the message is unseen, the directory's current unseen
591 // count is off by one and (1) too low if the message is new,
592 // or (2) too high if the message has been deleted.
593 if !deleted {
594 unseen++
595 } else {
596 unseen--
597 }
598 }
599 }
600 }
601 if accurate {
602 destDir.Recent += recent
603 destDir.Unseen += unseen
604 }
605 if !deleted {
606 destDir.Exists += len(uids)
607 } else {
608 destDir.Exists -= len(uids)
609 }
610 destDir.Unseen = acct.ensurePositive(destDir.Unseen, "Unseen")
611 destDir.Recent = acct.ensurePositive(destDir.Recent, "Recent")
612 destDir.Exists = acct.ensurePositive(destDir.Exists, "Exists")
613 } else {
614 acct.worker.Errorf("Skipping unknown directory %s", destination)
615 }
616 }
617
618 func (acct *AccountView) SortCriteria(uiConf *config.UIConfig) []*types.SortCriterion {
619 if uiConf == nil {
620 return nil
621 }
622 if len(uiConf.Sort) == 0 {
623 return nil
624 }
625 criteria, err := sort.GetSortCriteria(uiConf.Sort)
626 if err != nil {
627 acct.PushError(fmt.Errorf("ui sort: %w", err))
628 return nil
629 }
630 return criteria
631 }
632
633 func (acct *AccountView) GetSortCriteria() []*types.SortCriterion {
634 return acct.SortCriteria(acct.UiConfig())
635 }
636
637 func (acct *AccountView) CheckMail() {
638 acct.Lock()
639 defer acct.Unlock()
640 if acct.checkingMail {
641 return
642 }
643 // Exclude selected mailbox, per IMAP specification
644 exclude := append(acct.AccountConfig().CheckMailExclude, acct.dirlist.Selected()) //nolint:gocritic // intentional append to different slice
645 dirs := acct.dirlist.List()
646 dirs = acct.dirlist.FilterDirs(dirs, acct.AccountConfig().CheckMailInclude, false)
647 dirs = acct.dirlist.FilterDirs(dirs, exclude, true)
648 log.Debugf("Checking for new mail on account %s", acct.Name())
649 acct.SetStatus(state.ConnectionActivity("Checking for new mail..."))
650 msg := &types.CheckMail{
651 Directories: dirs,
652 Command: acct.acct.CheckMailCmd,
653 Timeout: acct.acct.CheckMailTimeout,
654 }
655 acct.checkingMail = true
656
657 var cb func(types.WorkerMessage)
658 cb = func(response types.WorkerMessage) {
659 dirsMsg, ok := response.(*types.CheckMailDirectories)
660 if ok {
661 checkMailMsg := &types.CheckMail{
662 Directories: dirsMsg.Directories,
663 Command: acct.acct.CheckMailCmd,
664 Timeout: acct.acct.CheckMailTimeout,
665 }
666 acct.worker.PostAction(context.TODO(), checkMailMsg, cb)
667 } else { // Done
668 acct.SetStatus(state.ConnectionActivity(""))
669 acct.Lock()
670 acct.checkingMail = false
671 acct.Unlock()
672 }
673 }
674 acct.worker.PostAction(context.TODO(), msg, cb)
675 }
676
677 // CheckMailReset resets the check-mail timer
678 func (acct *AccountView) CheckMailReset() {
679 if acct.ticker != nil {
680 d := acct.AccountConfig().CheckMail
681 acct.ticker = time.NewTicker(d)
682 }
683 }
684
685 func (acct *AccountView) checkMailOnStartup() {
686 if acct.AccountConfig().CheckMail.Minutes() > 0 {
687 acct.newConn = false
688 acct.CheckMail()
689 }
690 }
691
692 func (acct *AccountView) CheckMailTimer(d time.Duration) {
693 acct.ticker = time.NewTicker(d)
694 go func() {
695 defer log.PanicHandler()
696 for range acct.ticker.C {
697 if !acct.state.Connected {
698 continue
699 }
700 acct.CheckMail()
701 }
702 }()
703 }
704
705 func (acct *AccountView) closeSplit() {
706 if acct.split != nil {
707 acct.split.Close()
708 }
709 acct.splitSize = 0
710 acct.splitDir = config.SPLIT_NONE
711 acct.split = nil
712 acct.buildGrid()
713 ui.Invalidate()
714 }
715
716 func (acct *AccountView) updateSplitView(msg *models.MessageInfo) {
717 uiConf := acct.UiConfig()
718 if !acct.splitLoaded {
719 switch uiConf.MessageListSplit.Direction {
720 case config.SPLIT_HORIZONTAL:
721 acct.Split(uiConf.MessageListSplit.Size)
722 case config.SPLIT_VERTICAL:
723 acct.Vsplit(uiConf.MessageListSplit.Size)
724 }
725 acct.splitLoaded = true
726 }
727 if acct.splitSize == 0 || !acct.splitLoaded {
728 return
729 }
730 if acct.splitDebounce != nil {
731 acct.splitDebounce.Stop()
732 }
733 fn := func() {
734 if acct.split != nil {
735 acct.grid.RemoveChild(acct.split)
736 acct.split.Close()
737 }
738 lib.NewMessageStoreView(msg, false, acct.Store(), CryptoProvider(), DecryptKeys,
739 func(view lib.MessageView, err error) {
740 if err != nil {
741 PushError(err.Error())
742 return
743 }
744 viewer, err := NewMessageViewer(acct, view)
745 if err != nil {
746 PushError(err.Error())
747 return
748 }
749 acct.split = viewer
750 switch acct.splitDir {
751 case config.SPLIT_HORIZONTAL:
752 if acct.hasSidebar() {
753 acct.grid.AddChild(acct.split).At(1, 1)
754 } else {
755 acct.grid.AddChild(acct.split).At(1, 0)
756 }
757 case config.SPLIT_VERTICAL:
758 if acct.hasSidebar() {
759 acct.grid.AddChild(acct.split).At(0, 2)
760 } else {
761 acct.grid.AddChild(acct.split).At(0, 1)
762 }
763 }
764 // If the user wants to, start a timer to mark the message read
765 // if it stays in the message viewer longer than the requested
766 // delay.
767 if !uiConf.AutoMarkReadInSplit {
768 return
769 }
770 acct.splitDebounce = time.AfterFunc(uiConf.AutoMarkReadInSplitDelay, func() {
771 if view == nil || view.MessageInfo() == nil || view.Store() == nil {
772 return
773 }
774 view.Store().Flag([]models.UID{view.MessageInfo().Uid}, models.SeenFlag, true, nil)
775 })
776 })
777 }
778 acct.splitDebounce = time.AfterFunc(100*time.Millisecond, func() {
779 ui.QueueFunc(fn)
780 })
781 }
782
783 func (acct *AccountView) SplitSize() int {
784 return acct.splitSize
785 }
786
787 func (acct *AccountView) SetSplitSize(n int) {
788 if n == 0 {
789 acct.closeSplit()
790 }
791 acct.splitSize = n
792 }
793
794 func (acct *AccountView) ToggleHeaders() {
795 config.Viewer().ShowHeaders = !config.Viewer().ShowHeaders
796 if acct.splitSize == 0 {
797 return
798 }
799 msg, err := acct.SelectedMessage()
800 if err != nil {
801 log.Debugf("split: load message error: %v", err)
802 }
803 acct.updateSplitView(msg)
804 }
805
806 // ToggleSidebar toggles the visibility of the sidebar
807 func (acct *AccountView) ToggleSidebar() {
808 acct.sidebarHidden = !acct.sidebarHidden
809 switch acct.splitDir {
810 case config.SPLIT_HORIZONTAL:
811 acct.splitDir = config.SPLIT_NONE
812 acct.Split(acct.splitSize)
813 case config.SPLIT_VERTICAL:
814 acct.splitDir = config.SPLIT_NONE
815 acct.Vsplit(acct.splitSize)
816 default:
817 acct.buildGrid()
818 }
819 ui.Invalidate()
820 }
821
822 func (acct *AccountView) hasSidebar() bool {
823 return !acct.sidebarHidden && acct.UiConfig().SidebarWidth > 0
824 }
825
826 // buildGrid creates the basic grid layout without splits
827 func (acct *AccountView) buildGrid() {
828 sidebar := acct.UiConfig().SidebarWidth
829 if !acct.hasSidebar() {
830 acct.grid = ui.NewGrid().Rows([]ui.GridSpec{
831 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
832 }).Columns([]ui.GridSpec{
833 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
834 })
835 acct.grid.AddChild(acct.msglist).At(0, 0)
836 } else {
837 acct.grid = ui.NewGrid().Rows([]ui.GridSpec{
838 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
839 }).Columns([]ui.GridSpec{
840 {Strategy: ui.SIZE_EXACT, Size: func() int {
841 return sidebar
842 }},
843 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
844 })
845 acct.grid.AddChild(ui.NewBordered(acct.dirlist, ui.BORDER_RIGHT, acct.UiConfig()))
846 acct.grid.AddChild(acct.msglist).At(0, 1)
847 }
848 }
849
850 // Split splits the message list view horizontally. The message list will be n
851 // rows high. If n is 0, any existing split is removed
852 func (acct *AccountView) Split(n int) {
853 acct.SetSplitSize(n)
854 if acct.splitDir == config.SPLIT_HORIZONTAL || n == 0 {
855 return
856 }
857 acct.splitDir = config.SPLIT_HORIZONTAL
858
859 rowSpecs := []ui.GridSpec{
860 // Add 1 so that the splitSize is the number of visible messages
861 {Strategy: ui.SIZE_EXACT, Size: func() int { return acct.SplitSize() + 1 }},
862 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
863 }
864
865 msglistCol := 1
866 if !acct.hasSidebar() {
867 acct.grid = ui.NewGrid().Rows(rowSpecs).Columns([]ui.GridSpec{
868 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
869 })
870 msglistCol = 0
871 } else {
872 acct.grid = ui.NewGrid().Rows(rowSpecs).Columns([]ui.GridSpec{
873 {Strategy: ui.SIZE_EXACT, Size: func() int {
874 return acct.UiConfig().SidebarWidth
875 }},
876 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
877 })
878 acct.grid.AddChild(ui.NewBordered(acct.dirlist, ui.BORDER_RIGHT, acct.UiConfig())).Span(2, 1)
879 }
880
881 acct.grid.AddChild(ui.NewBordered(acct.msglist, ui.BORDER_BOTTOM, acct.UiConfig())).At(0, msglistCol)
882 acct.split, _ = NewMessageViewer(acct, nil)
883 acct.grid.AddChild(acct.split).At(1, msglistCol)
884 msg, err := acct.SelectedMessage()
885 if err != nil {
886 log.Debugf("split: load message error: %v", err)
887 }
888 acct.updateSplitView(msg)
889 }
890
891 // Vsplit splits the message list view vertically. The message list will be n
892 // rows wide. If n is 0, any existing split is removed
893 func (acct *AccountView) Vsplit(n int) {
894 acct.SetSplitSize(n)
895 if acct.splitDir == config.SPLIT_VERTICAL || n == 0 {
896 return
897 }
898 acct.splitDir = config.SPLIT_VERTICAL
899
900 rowSpecs := []ui.GridSpec{
901 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
902 }
903
904 msglistCol := 1
905 splitCol := 2
906 if !acct.hasSidebar() {
907 acct.grid = ui.NewGrid().Rows(rowSpecs).Columns([]ui.GridSpec{
908 {Strategy: ui.SIZE_EXACT, Size: acct.SplitSize},
909 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
910 })
911 msglistCol = 0
912 splitCol = 1
913 } else {
914 acct.grid = ui.NewGrid().Rows(rowSpecs).Columns([]ui.GridSpec{
915 {Strategy: ui.SIZE_EXACT, Size: func() int {
916 return acct.UiConfig().SidebarWidth
917 }},
918 {Strategy: ui.SIZE_EXACT, Size: acct.SplitSize},
919 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
920 })
921 acct.grid.AddChild(ui.NewBordered(acct.dirlist, ui.BORDER_RIGHT, acct.UiConfig())).At(0, 0)
922 }
923
924 acct.grid.AddChild(ui.NewBordered(acct.msglist, ui.BORDER_RIGHT, acct.UiConfig())).At(0, msglistCol)
925 acct.split, _ = NewMessageViewer(acct, nil)
926 acct.grid.AddChild(acct.split).At(0, splitCol)
927 msg, err := acct.SelectedMessage()
928 if err != nil {
929 log.Debugf("split: load message error: %v", err)
930 }
931 acct.updateSplitView(msg)
932 }
933
934 // setTitle executes the title template and sets the tab title
935 func (acct *AccountView) setTitle() {
936 if acct.tab == nil {
937 return
938 }
939
940 data := state.NewDataSetter()
941 data.SetAccount(acct.acct)
942 data.SetFolder(acct.Directories().SelectedDirectory())
943 data.SetRUE(acct.dirlist.List(), acct.dirlist.GetRUECount)
944 data.SetState(&acct.state)
945 data.SetHasNew(acct.hasNew)
946
947 var buf bytes.Buffer
948 err := templates.Render(acct.UiConfig().TabTitleAccount, &buf, data.Data())
949 if err != nil {
950 acct.PushError(err)
951 return
952 }
953 acct.tab.SetTitle(buf.String())
954 }