Debian Codegraph @

app/aerc.go

raw
1 package app
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "net/url"
9 "os/exec"
10 "slices"
11 "strings"
12 "time"
13 "unicode"
14
15 "git.sr.ht/~rjarry/go-opt/v2"
16 "github.com/ProtonMail/go-crypto/openpgp"
17 "github.com/emersion/go-message/mail"
18 "go.rockorager.dev/vaxis"
19
20 "git.sr.ht/~rjarry/aerc/config"
21 "git.sr.ht/~rjarry/aerc/lib"
22 "git.sr.ht/~rjarry/aerc/lib/crypto"
23 "git.sr.ht/~rjarry/aerc/lib/log"
24 "git.sr.ht/~rjarry/aerc/lib/ui"
25 "git.sr.ht/~rjarry/aerc/models"
26 "git.sr.ht/~rjarry/aerc/worker/types"
27 )
28
29 type Aerc struct {
30 accounts map[string]*AccountView
31 cmd func(string, *config.AccountConfig, *models.MessageInfo) error
32 cmdHistory lib.History
33 complete func(ctx context.Context, cmd string) ([]opt.Completion, string)
34 focused ui.Interactive
35 grid *ui.Grid
36 simulating int
37 statusbar *ui.Stack
38 statusline *StatusLine
39 pasting bool
40 pendingKeys []config.KeyStroke
41 prompts *ui.Stack
42 tabs *ui.Tabs
43 beep func()
44 dialog ui.DrawableInteractive
45 keyhint *KeyHint
46 keyhintPending time.Time
47 keyhintTimer *time.Timer
48
49 Crypto crypto.Provider
50 }
51
52 func (aerc Aerc) CmdHistory() lib.History {
53 return aerc.cmdHistory
54 }
55
56 type Choice struct {
57 Key string
58 Text string
59 Command string
60 }
61
62 func (aerc *Aerc) Init(
63 crypto crypto.Provider,
64 cmd func(string, *config.AccountConfig, *models.MessageInfo) error,
65 complete func(ctx context.Context, cmd string) ([]opt.Completion, string), cmdHistory lib.History,
66 deferLoop chan struct{},
67 ) {
68 tabs := ui.NewTabs(func(d ui.Drawable) *config.UIConfig {
69 acct := aerc.account(d)
70 if acct != nil {
71 return config.Ui().ForAccount(acct.Name())
72 }
73 return config.Ui()
74 })
75
76 statusbar := ui.NewStack(config.Ui())
77 statusline := &StatusLine{}
78 statusbar.Push(statusline)
79
80 grid := ui.NewGrid().Rows([]ui.GridSpec{
81 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)},
82 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
83 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)},
84 }).Columns([]ui.GridSpec{
85 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
86 })
87 grid.AddChild(tabs.TabStrip)
88 grid.AddChild(tabs.TabContent).At(1, 0)
89 grid.AddChild(statusbar).At(2, 0)
90
91 aerc.accounts = make(map[string]*AccountView)
92 aerc.cmd = cmd
93 aerc.cmdHistory = cmdHistory
94 aerc.complete = complete
95 aerc.grid = grid
96 aerc.statusbar = statusbar
97 aerc.statusline = statusline
98 aerc.prompts = ui.NewStack(config.Ui())
99 aerc.tabs = tabs
100 aerc.Crypto = crypto
101
102 for _, acct := range config.Accounts {
103 view, err := NewAccountView(acct, deferLoop)
104 if err != nil {
105 tabs.Add(errorScreen(err.Error()), acct.Name, false)
106 } else {
107 aerc.accounts[acct.Name] = view
108 view.tab = tabs.Add(view, acct.Name, false)
109 }
110 }
111
112 if len(config.Accounts) == 0 {
113 wizard := NewAccountWizard()
114 wizard.Focus(true)
115 aerc.NewTab(wizard, "New account", false)
116 }
117
118 tabs.Select(0)
119
120 tabs.CloseTab = func(index int) {
121 tab := aerc.tabs.Get(index)
122 if tab == nil {
123 return
124 }
125 switch content := tab.Content.(type) {
126 case *AccountView:
127 return
128 case *AccountWizard:
129 return
130 default:
131 aerc.RemoveTab(content, true)
132 }
133 }
134
135 aerc.showConfigWarnings()
136 }
137
138 func (aerc *Aerc) showConfigWarnings() {
139 var dialogs []ui.DrawableInteractive
140
141 callback := func(string, error) {
142 aerc.CloseDialog()
143 if len(dialogs) > 0 {
144 d := dialogs[0]
145 dialogs = dialogs[1:]
146 aerc.AddDialog(d)
147 }
148 }
149
150 for _, w := range config.Warnings {
151 dialogs = append(dialogs, NewSelectorDialog(
152 w.Title, w.Body, []string{"OK"}, 0,
153 aerc.SelectedAccountUiConfig(),
154 callback,
155 ))
156 }
157
158 callback("", nil)
159 }
160
161 func (aerc *Aerc) OnBeep(f func()) {
162 aerc.beep = f
163 }
164
165 func (aerc *Aerc) Beep() {
166 if aerc.beep == nil {
167 log.Warnf("should beep, but no beeper")
168 return
169 }
170 aerc.beep()
171 }
172
173 func (aerc *Aerc) HandleMessage(msg types.WorkerMessage) {
174 if acct, ok := aerc.accounts[msg.Account()]; ok {
175 acct.onMessage(msg)
176 }
177 }
178
179 func (aerc *Aerc) Invalidate() {
180 ui.Invalidate()
181 }
182
183 func (aerc *Aerc) Focus(focus bool) {
184 // who cares
185 }
186
187 func (aerc *Aerc) Draw(ctx *ui.Context) {
188 if len(aerc.prompts.Children()) > 0 {
189 previous := aerc.focused
190 prompt := aerc.prompts.Pop().(*ExLine)
191 prompt.finish = func() {
192 aerc.statusbar.Pop()
193 aerc.focus(previous)
194 }
195
196 aerc.statusbar.Push(prompt)
197 aerc.focus(prompt)
198 }
199 aerc.grid.Draw(ctx)
200 if aerc.dialog != nil {
201 w, h := ctx.Width(), ctx.Height()
202 if d, ok := aerc.dialog.(Dialog); ok {
203 xstart, width := d.ContextWidth()
204 ystart, height := d.ContextHeight()
205 aerc.dialog.Draw(
206 ctx.Subcontext(xstart(w), ystart(h),
207 width(w), height(h)))
208 } else if w > 8 && h > 4 {
209 aerc.dialog.Draw(ctx.Subcontext(4, h/2-2, w-8, 4))
210 }
211 }
212 if !aerc.keyhintPending.IsZero() && aerc.dialog == nil {
213 uiConf := aerc.SelectedAccountUiConfig()
214 if time.Since(aerc.keyhintPending) >= uiConf.KeyHintDelay {
215 bindings := aerc.getBindings()
216 allBindings := bindings.Bindings
217 if bindings.Globals {
218 allBindings = append(allBindings, config.Binds().Global.Bindings...)
219 }
220 aerc.keyhint = NewKeyHint(allBindings, aerc.pendingKeys)
221 aerc.keyhintPending = time.Time{}
222 aerc.keyhintTimer = nil
223 }
224 }
225 if aerc.keyhint != nil && aerc.dialog == nil &&
226 aerc.keyhint.HasEntries() {
227 w, h := ctx.Width(), ctx.Height()
228 uiConf := aerc.SelectedAccountUiConfig()
229 khW := aerc.keyhint.RequiredWidth() + 2
230 khH := aerc.keyhint.RequiredHeight() + 2
231 if khH > h-2 {
232 khH = h - 2
233 }
234 if khW > w-2 {
235 khW = w - 2
236 }
237 if khW > 0 && khH > 0 {
238 var x int
239 switch aerc.keyHintPosition(uiConf) {
240 case "bottom-left":
241 x = 1
242 case "bottom-center":
243 x = (w - khW) / 2
244 default:
245 x = w - khW - 1
246 }
247 y := h - khH - 2
248 if y < 1 {
249 y = 1
250 }
251 prefixStr := config.FormatKeyStrokes(
252 aerc.keyhint.Prefix())
253 box := ui.NewBox(aerc.keyhint, prefixStr, "", uiConf)
254 box.Draw(ctx.Subcontext(x, y, khW, khH))
255 }
256 }
257 }
258
259 func (aerc *Aerc) HumanReadableBindings() []string {
260 var result []string
261 binds := aerc.getBindings()
262 format := func(s string) string {
263 return strings.ReplaceAll(s, "%", "%%")
264 }
265 annotate := func(b *config.Binding) string {
266 if b.Annotation == "" {
267 return ""
268 }
269 return "[" + b.Annotation + "]"
270 }
271 fmtStr := "%10s %s %s"
272 for _, bind := range binds.Bindings {
273 result = append(result, fmt.Sprintf(fmtStr,
274 format(config.FormatKeyStrokes(bind.Input)),
275 format(config.FormatKeyStrokes(bind.Output)),
276 annotate(bind),
277 ))
278 }
279 if binds.Globals && config.Binds().Global != nil {
280 for _, bind := range config.Binds().Global.Bindings {
281 result = append(result, fmt.Sprintf(fmtStr+" (Globals)",
282 format(config.FormatKeyStrokes(bind.Input)),
283 format(config.FormatKeyStrokes(bind.Output)),
284 annotate(bind),
285 ))
286 }
287 }
288 result = append(result, fmt.Sprintf(fmtStr,
289 "$ex",
290 fmt.Sprintf("'%c'", binds.ExKey.Key), "",
291 ))
292 result = append(result, fmt.Sprintf(fmtStr,
293 "Globals",
294 fmt.Sprintf("%v", binds.Globals), "",
295 ))
296 slices.Sort(result)
297 return result
298 }
299
300 func (aerc *Aerc) getBindings() *config.KeyBindings {
301 selectedAccountName := ""
302 if aerc.SelectedAccount() != nil {
303 selectedAccountName = aerc.SelectedAccount().acct.Name
304 }
305 switch view := aerc.SelectedTabContent().(type) {
306 case *AccountView:
307 binds := config.Binds().MessageList.ForAccount(selectedAccountName)
308 return binds.ForFolder(view.SelectedDirectory())
309 case *AccountWizard:
310 return config.Binds().AccountWizard
311 case *Composer:
312 var binds *config.KeyBindings
313 switch view.Bindings() {
314 case "compose::editor":
315 binds = config.Binds().ComposeEditor.ForAccount(
316 selectedAccountName)
317 case "compose::review":
318 binds = config.Binds().ComposeReview.ForAccount(
319 selectedAccountName)
320 default:
321 binds = config.Binds().Compose.ForAccount(
322 selectedAccountName)
323 }
324 return binds.ForFolder(view.SelectedDirectory())
325 case *MessageViewer:
326 var binds *config.KeyBindings
327 switch view.Bindings() {
328 case "view::passthrough":
329 binds = config.Binds().MessageViewPassthrough.ForAccount(
330 selectedAccountName)
331 default:
332 binds = config.Binds().MessageView.ForAccount(
333 selectedAccountName)
334 }
335 return binds.ForFolder(view.SelectedAccount().SelectedDirectory())
336 case *Terminal:
337 return config.Binds().Terminal
338 default:
339 return config.Binds().Global
340 }
341 }
342
343 func (aerc *Aerc) clearKeyhint() {
344 aerc.keyhint = nil
345 aerc.keyhintPending = time.Time{}
346 if aerc.keyhintTimer != nil {
347 aerc.keyhintTimer.Stop()
348 aerc.keyhintTimer = nil
349 }
350 }
351
352 func (aerc *Aerc) simulate(strokes []config.KeyStroke) {
353 aerc.pendingKeys = []config.KeyStroke{}
354 aerc.clearKeyhint()
355 bindings := aerc.getBindings()
356 complete := aerc.SelectedAccountUiConfig().CompletionMinChars != config.MANUAL_COMPLETE
357 aerc.simulating += 1
358
359 for _, stroke := range strokes {
360 simulated := vaxis.Key{
361 Keycode: stroke.Key,
362 Modifiers: stroke.Modifiers,
363 }
364 if unicode.IsUpper(stroke.Key) {
365 simulated.Keycode = unicode.ToLower(stroke.Key)
366 simulated.Modifiers |= vaxis.ModShift
367 }
368 // If none of these mods are present, set the text field to
369 // enable matching keys like ":"
370 if stroke.Modifiers&vaxis.ModCtrl == 0 &&
371 stroke.Modifiers&vaxis.ModAlt == 0 &&
372 stroke.Modifiers&vaxis.ModSuper == 0 &&
373 stroke.Modifiers&vaxis.ModHyper == 0 {
374
375 simulated.Text = string(stroke.Key)
376 }
377 aerc.Event(simulated)
378 complete = stroke == bindings.CompleteKey
379 }
380 aerc.simulating -= 1
381 if exline, ok := aerc.focused.(*ExLine); ok {
382 // we are still focused on the exline, turn on tab complete
383 exline.TabComplete(func(ctx context.Context, cmd string) ([]opt.Completion, string) {
384 return aerc.complete(ctx, cmd)
385 })
386 if complete {
387 // force completion now
388 exline.Event(vaxis.Key{Keycode: vaxis.KeyTab})
389 }
390 }
391 }
392
393 func (aerc *Aerc) Event(event vaxis.Event) bool {
394 if config.General().QuakeMode {
395 if e, ok := event.(vaxis.Key); ok && e.MatchString("F1") {
396 ToggleQuake()
397 return true
398 }
399 }
400
401 if aerc.dialog != nil {
402 return aerc.dialog.Event(event)
403 }
404
405 if aerc.focused != nil {
406 return aerc.focused.Event(event)
407 }
408
409 switch event := event.(type) {
410 // TODO: more vaxis events handling
411 case vaxis.Key:
412 // If we are in a bracketed paste, don't process the keys for
413 // bindings
414 if aerc.pasting {
415 interactive, ok := aerc.SelectedTabContent().(ui.Interactive)
416 if ok {
417 return interactive.Event(event)
418 }
419 return false
420 }
421 aerc.statusline.Expire()
422 stroke := config.KeyStroke{
423 Modifiers: event.Modifiers,
424 }
425 switch {
426 case event.ShiftedCode != 0:
427 stroke.Key = event.ShiftedCode
428 stroke.Modifiers &^= vaxis.ModShift
429 default:
430 stroke.Key = event.Keycode
431 }
432 aerc.pendingKeys = append(aerc.pendingKeys, stroke)
433 ui.Invalidate()
434 bindings := aerc.getBindings()
435 incomplete := false
436 result, strokes := bindings.GetBinding(aerc.pendingKeys)
437 switch result {
438 case config.BINDING_FOUND:
439 aerc.clearKeyhint()
440 aerc.simulate(strokes)
441 return true
442 case config.BINDING_INCOMPLETE:
443 incomplete = true
444 case config.BINDING_NOT_FOUND:
445 }
446 if bindings.Globals {
447 result, strokes = config.Binds().Global.GetBinding(aerc.pendingKeys)
448 switch result {
449 case config.BINDING_FOUND:
450 aerc.clearKeyhint()
451 aerc.simulate(strokes)
452 return true
453 case config.BINDING_INCOMPLETE:
454 incomplete = true
455 case config.BINDING_NOT_FOUND:
456 }
457 }
458 if !incomplete {
459 aerc.pendingKeys = []config.KeyStroke{}
460 aerc.clearKeyhint()
461 exKey := bindings.ExKey
462 if aerc.simulating > 0 {
463 // Keybindings still use : even if you change the ex key
464 exKey = config.Binds().Global.ExKey
465 }
466 if aerc.isExKey(event, exKey) {
467 aerc.BeginExCommand("")
468 return true
469 }
470 interactive, ok := aerc.SelectedTabContent().(ui.Interactive)
471 if ok {
472 return interactive.Event(event)
473 }
474 return false
475 }
476 if incomplete && aerc.simulating == 0 && aerc.SelectedAccountUiConfig().KeyHint {
477 if aerc.keyhint != nil {
478 bindings := aerc.getBindings()
479 allBindings := bindings.Bindings
480 if bindings.Globals {
481 allBindings = append(allBindings, config.Binds().Global.Bindings...)
482 }
483 aerc.keyhint = NewKeyHint(allBindings, aerc.pendingKeys)
484 } else if aerc.keyhintPending.IsZero() {
485 aerc.keyhintPending = time.Now()
486 delay := aerc.SelectedAccountUiConfig().KeyHintDelay
487 aerc.keyhintTimer = time.AfterFunc(delay, func() {
488 ui.Invalidate()
489 })
490 }
491 }
492 case vaxis.Mouse:
493 aerc.grid.MouseEvent(event.Col, event.Row, event)
494 return true
495 case vaxis.PasteStartEvent:
496 aerc.pasting = true
497 interactive, ok := aerc.SelectedTabContent().(ui.Interactive)
498 if ok {
499 return interactive.Event(event)
500 }
501 return false
502 case vaxis.PasteEndEvent:
503 aerc.pasting = false
504 interactive, ok := aerc.SelectedTabContent().(ui.Interactive)
505 if ok {
506 return interactive.Event(event)
507 }
508 return false
509 case vaxis.FocusIn:
510 if focusable, ok := aerc.SelectedTabContent().(ui.Focusable); ok {
511 focusable.Focus(true)
512 return true
513 }
514 return false
515 case vaxis.FocusOut:
516 if focusable, ok := aerc.SelectedTabContent().(ui.Focusable); ok {
517 focusable.Focus(false)
518 return true
519 }
520 return false
521 case vaxis.ColorThemeUpdate:
522 // Color theme changes need to be sent to all the tabs because
523 // there may be for instance multiple open virtual terminals
524 // each running a program that needs to be made aware of the
525 // change in order to repaint itself.
526 processed := false
527 i := 0
528 for tab := aerc.tabs.Get(0); tab != nil; tab = aerc.tabs.Get(i) {
529 i++
530 if interactive, ok := tab.Content.(ui.Interactive); ok {
531 processed = interactive.Event(event) || processed
532 }
533 }
534 return processed
535 }
536 return false
537 }
538
539 func (aerc *Aerc) SelectedAccount() *AccountView {
540 return aerc.account(aerc.SelectedTabContent())
541 }
542
543 func (aerc *Aerc) Account(name string) (*AccountView, error) {
544 if acct, ok := aerc.accounts[name]; ok {
545 return acct, nil
546 }
547 return nil, fmt.Errorf("account <%s> not found", name)
548 }
549
550 func (aerc *Aerc) PrevAccount() (*AccountView, error) {
551 cur := aerc.SelectedAccount()
552 if cur == nil {
553 return nil, fmt.Errorf("no account selected, cannot get prev")
554 }
555 for i, conf := range config.Accounts {
556 if conf.Name == cur.Name() {
557 i -= 1
558 if i == -1 {
559 i = len(config.Accounts) - 1
560 }
561 conf = config.Accounts[i]
562 return aerc.Account(conf.Name)
563 }
564 }
565 return nil, fmt.Errorf("no prev account")
566 }
567
568 func (aerc *Aerc) NextAccount() (*AccountView, error) {
569 cur := aerc.SelectedAccount()
570 if cur == nil {
571 return nil, fmt.Errorf("no account selected, cannot get next")
572 }
573 for i, conf := range config.Accounts {
574 if conf.Name == cur.Name() {
575 i += 1
576 if i == len(config.Accounts) {
577 i = 0
578 }
579 conf = config.Accounts[i]
580 return aerc.Account(conf.Name)
581 }
582 }
583 return nil, fmt.Errorf("no next account")
584 }
585
586 func (aerc *Aerc) AccountNames() []string {
587 results := make([]string, 0)
588 for name := range aerc.accounts {
589 results = append(results, name)
590 }
591 return results
592 }
593
594 func (aerc *Aerc) account(d ui.Drawable) *AccountView {
595 switch tab := d.(type) {
596 case *AccountView:
597 return tab
598 case *MessageViewer:
599 return tab.SelectedAccount()
600 case *Composer:
601 return tab.Account()
602 }
603 return nil
604 }
605
606 func (aerc *Aerc) SelectedAccountUiConfig() *config.UIConfig {
607 acct := aerc.SelectedAccount()
608 if acct == nil {
609 return config.Ui()
610 }
611 return acct.UiConfig()
612 }
613
614 func (aerc *Aerc) SelectedTabContent() ui.Drawable {
615 tab := aerc.tabs.Selected()
616 if tab == nil {
617 return nil
618 }
619 return tab.Content
620 }
621
622 func (aerc *Aerc) SelectedTab() *ui.Tab {
623 return aerc.tabs.Selected()
624 }
625
626 func (aerc *Aerc) NewTab(clickable ui.Drawable, name string, background bool) *ui.Tab {
627 tab := aerc.tabs.Add(clickable, name, background)
628 aerc.UpdateStatus()
629 return tab
630 }
631
632 func (aerc *Aerc) RemoveTab(tab ui.Drawable, closeContent bool) {
633 aerc.tabs.Remove(tab)
634 aerc.UpdateStatus()
635 if content, ok := tab.(ui.Closeable); ok && closeContent {
636 content.Close()
637 }
638 }
639
640 func (aerc *Aerc) ReplaceTab(tabSrc ui.Drawable, tabTarget ui.Drawable, name string, closeSrc bool) {
641 aerc.tabs.Replace(tabSrc, tabTarget, name)
642 if content, ok := tabSrc.(ui.Closeable); ok && closeSrc {
643 content.Close()
644 }
645 }
646
647 func (aerc *Aerc) MoveTab(i int, relative bool) {
648 aerc.tabs.MoveTab(i, relative)
649 }
650
651 func (aerc *Aerc) PinTab() {
652 aerc.tabs.PinTab()
653 }
654
655 func (aerc *Aerc) UnpinTab() {
656 aerc.tabs.UnpinTab()
657 }
658
659 func (aerc *Aerc) NextTab() {
660 aerc.tabs.NextTab()
661 }
662
663 func (aerc *Aerc) PrevTab() {
664 aerc.tabs.PrevTab()
665 }
666
667 func (aerc *Aerc) SelectTab(name string) bool {
668 ok := aerc.tabs.SelectName(name)
669 if ok {
670 aerc.UpdateStatus()
671 }
672 return ok
673 }
674
675 func (aerc *Aerc) SelectTabIndex(index int) bool {
676 ok := aerc.tabs.Select(index)
677 if ok {
678 aerc.UpdateStatus()
679 }
680 return ok
681 }
682
683 func (aerc *Aerc) SelectTabAtOffset(offset int) {
684 aerc.tabs.SelectOffset(offset)
685 }
686
687 func (aerc *Aerc) TabNames() []string {
688 return aerc.tabs.Names()
689 }
690
691 func (aerc *Aerc) SelectPreviousTab() bool {
692 return aerc.tabs.SelectPrevious()
693 }
694
695 func (aerc *Aerc) UpdateStatus() {
696 if acct := aerc.SelectedAccount(); acct != nil {
697 aerc.statusline.Update(acct)
698 } else {
699 aerc.statusline.Clear()
700 }
701 }
702
703 func (aerc *Aerc) SetError(err string) {
704 aerc.statusline.SetError(err)
705 }
706
707 func (aerc *Aerc) PushStatus(text string, expiry time.Duration) *StatusMessage {
708 return aerc.statusline.Push(text, expiry)
709 }
710
711 func (aerc *Aerc) PushError(text string) *StatusMessage {
712 return aerc.statusline.PushError(text)
713 }
714
715 func (aerc *Aerc) PushWarning(text string) *StatusMessage {
716 return aerc.statusline.PushWarning(text)
717 }
718
719 func (aerc *Aerc) PushSuccess(text string) *StatusMessage {
720 return aerc.statusline.PushSuccess(text)
721 }
722
723 func (aerc *Aerc) focus(item ui.Interactive) {
724 if aerc.focused == item {
725 return
726 }
727 if aerc.focused != nil {
728 aerc.focused.Focus(false)
729 }
730 aerc.focused = item
731 interactive, ok := aerc.SelectedTabContent().(ui.Interactive)
732 if item != nil {
733 item.Focus(true)
734 if ok {
735 interactive.Focus(false)
736 }
737 } else if ok {
738 interactive.Focus(true)
739 }
740 }
741
742 func (aerc *Aerc) BeginExCommand(cmd string) {
743 previous := aerc.focused
744 var tabComplete func(context.Context, string) ([]opt.Completion, string)
745 if aerc.simulating != 0 {
746 // Don't try to draw completions for simulated events
747 tabComplete = nil
748 } else {
749 tabComplete = aerc.complete
750 }
751 exline := NewExLine(cmd, func(cmd string) {
752 err := aerc.cmd(cmd, nil, nil)
753 if err != nil {
754 aerc.PushError(err.Error())
755 }
756 // only add to history if this is an unsimulated command,
757 // ie one not executed from a keybinding
758 if aerc.simulating == 0 {
759 aerc.cmdHistory.Add(cmd)
760 }
761 }, func() {
762 aerc.statusbar.Pop()
763 aerc.focus(previous)
764 }, tabComplete, aerc.cmdHistory)
765 aerc.statusbar.Push(exline)
766 aerc.focus(exline)
767 }
768
769 func (aerc *Aerc) PushPrompt(prompt *ExLine) {
770 aerc.prompts.Push(prompt)
771 }
772
773 func (aerc *Aerc) RegisterPrompt(prompt string, cmd string) {
774 p := NewPrompt(prompt, func(text string) {
775 if text != "" {
776 cmd += " " + opt.QuoteArg(text)
777 }
778 err := aerc.cmd(cmd, nil, nil)
779 if err != nil {
780 aerc.PushError(err.Error())
781 }
782 }, func(ctx context.Context, cmd string) ([]opt.Completion, string) {
783 return nil, "" // TODO: completions
784 })
785 aerc.prompts.Push(p)
786 }
787
788 func (aerc *Aerc) RegisterChoices(choices []Choice) {
789 cmds := make(map[string]string)
790 texts := []string{}
791 for _, c := range choices {
792 text := fmt.Sprintf("[%s] %s", c.Key, c.Text)
793 if strings.Contains(c.Text, c.Key) {
794 text = strings.Replace(c.Text, c.Key, "["+c.Key+"]", 1)
795 }
796 texts = append(texts, text)
797 cmds[c.Key] = c.Command
798 }
799 prompt := strings.Join(texts, ", ") + "? "
800 p := NewPrompt(prompt, func(text string) {
801 cmd, ok := cmds[text]
802 if !ok {
803 return
804 }
805 err := aerc.cmd(cmd, nil, nil)
806 if err != nil {
807 aerc.PushError(err.Error())
808 }
809 }, func(ctx context.Context, cmd string) ([]opt.Completion, string) {
810 return nil, "" // TODO: completions
811 })
812 aerc.prompts.Push(p)
813 }
814
815 func (aerc *Aerc) Command(args []string) error {
816 switch {
817 case len(args) == 0:
818 return nil // noop success, i.e. ping
819 case strings.HasPrefix(args[0], "mailto:"):
820 mailto, err := url.Parse(args[0])
821 if err != nil {
822 return err
823 }
824 return aerc.mailto(mailto)
825 case strings.HasPrefix(args[0], "mbox:"):
826 return aerc.mbox(args[0])
827 case strings.HasPrefix(args[0], ":"):
828 cmdline := args[0]
829 if len(args) > 1 {
830 cmdline = opt.QuoteArgs(args...).String()
831 }
832 defer ui.Invalidate()
833 return aerc.cmd(cmdline, nil, nil)
834 default:
835 return errors.New("command not understood")
836 }
837 }
838
839 func (aerc *Aerc) DirectCommand(cmdline string) error {
840 defer ui.Invalidate()
841 return aerc.cmd(cmdline, nil, nil)
842 }
843
844 func (aerc *Aerc) mailto(addr *url.URL) error {
845 var subject string
846 var body string
847 var acctName string
848 var attachments []string
849 h := &mail.Header{}
850 to, err := mail.ParseAddressList(addr.Opaque)
851 if err != nil && addr.Opaque != "" {
852 return fmt.Errorf("Could not parse to: %w", err)
853 }
854 h.SetAddressList("to", to)
855 template := config.Templates().NewMessage
856 for key, vals := range addr.Query() {
857 switch strings.ToLower(key) {
858 case "account":
859 acctName = strings.Join(vals, "")
860 case "bcc":
861 list, err := mail.ParseAddressList(strings.Join(vals, ","))
862 if err != nil {
863 break
864 }
865 h.SetAddressList("Bcc", list)
866 case "body":
867 body = strings.Join(vals, "\r\n")
868 case "cc":
869 list, err := mail.ParseAddressList(strings.Join(vals, ","))
870 if err != nil {
871 break
872 }
873 h.SetAddressList("Cc", list)
874 case "in-reply-to":
875 for i, msgID := range vals {
876 if len(msgID) > 1 && msgID[0] == '<' &&
877 msgID[len(msgID)-1] == '>' {
878 vals[i] = msgID[1 : len(msgID)-1]
879 }
880 }
881 h.SetMsgIDList("In-Reply-To", vals)
882 case "subject":
883 subject = strings.Join(vals, ",")
884 h.SetText("Subject", subject)
885 case "template":
886 template = strings.Join(vals, "")
887 log.Tracef("template set to %s", template)
888 case "attach":
889 for _, path := range vals {
890 // remove a potential file:// prefix.
891 attachments = append(attachments, strings.TrimPrefix(path, "file://"))
892 }
893 default:
894 // any other header gets ignored on purpose to avoid control headers
895 // being injected
896 }
897 }
898
899 acct := aerc.SelectedAccount()
900 if acctName != "" {
901 if a, ok := aerc.accounts[acctName]; ok && a != nil {
902 acct = a
903 }
904 }
905
906 if acct == nil {
907 return errors.New("No account selected")
908 }
909
910 defer ui.Invalidate()
911
912 composer, err := NewComposer(acct,
913 acct.AccountConfig(), acct.Worker(),
914 config.Compose().EditHeaders, template, h, nil,
915 strings.NewReader(body))
916 if err != nil {
917 return err
918 }
919 composer.FocusEditor("subject")
920 title := "New email"
921 if subject != "" {
922 title = subject
923 composer.FocusTerminal()
924 }
925 if to == nil {
926 composer.FocusEditor("to")
927 }
928 composer.Tab = aerc.NewTab(composer, title, false)
929
930 for _, file := range attachments {
931 composer.AddAttachment(file)
932 }
933 return nil
934 }
935
936 func (aerc *Aerc) mbox(source string) error {
937 acctConf := config.AccountConfig{}
938 if selectedAcct := aerc.SelectedAccount(); selectedAcct != nil {
939 acctConf = *selectedAcct.acct
940 info := fmt.Sprintf("Loading outgoing mbox mail settings from account [%s]", selectedAcct.Name())
941 aerc.PushStatus(info, 10*time.Second)
942 log.Debugf(info)
943 } else {
944 acctConf.From = &mail.Address{Address: "user@localhost"}
945 }
946 acctConf.Name = "mbox"
947 acctConf.Source = source
948 acctConf.Default = "INBOX"
949 acctConf.Archive = "Archive"
950 acctConf.Postpone = "Drafts"
951 acctConf.CopyTo = []string{"Sent"}
952
953 defer ui.Invalidate()
954
955 mboxView, err := NewAccountView(&acctConf, nil)
956 if err != nil {
957 aerc.NewTab(errorScreen(err.Error()), acctConf.Name, false)
958 } else {
959 aerc.accounts[acctConf.Name] = mboxView
960 aerc.NewTab(mboxView, acctConf.Name, false)
961 }
962 return nil
963 }
964
965 func (aerc *Aerc) CloseBackends() error {
966 var returnErr error
967 for _, acct := range aerc.accounts {
968 var raw any = acct.worker.Backend
969 c, ok := raw.(io.Closer)
970 if !ok {
971 continue
972 }
973 err := c.Close()
974 if err != nil {
975 returnErr = err
976 log.Errorf("Closing backend failed for %s: %v", acct.Name(), err)
977 }
978 }
979 return returnErr
980 }
981
982 func (aerc *Aerc) AddDialog(d ui.DrawableInteractive) {
983 aerc.dialog = d
984 aerc.Invalidate()
985 }
986
987 func (aerc *Aerc) CloseDialog() {
988 aerc.dialog = nil
989 aerc.Invalidate()
990 }
991
992 func (aerc *Aerc) GetPassword(title string, prompt string) (chText chan string, chErr chan error) {
993 chText = make(chan string, 1)
994 chErr = make(chan error, 1)
995 getPasswd := NewGetPasswd(title, prompt, func(pw string, err error) {
996 defer func() {
997 close(chErr)
998 close(chText)
999 aerc.CloseDialog()
1000 }()
1001 if err != nil {
1002 chErr <- err
1003 return
1004 }
1005 chErr <- nil
1006 chText <- pw
1007 })
1008 aerc.AddDialog(getPasswd)
1009
1010 return
1011 }
1012
1013 func (aerc *Aerc) DecryptKeys(keys []openpgp.Key, symmetric bool) (b []byte, err error) {
1014 for _, key := range keys {
1015 ident := key.Entity.PrimaryIdentity()
1016 chPass, chErr := aerc.GetPassword("Decrypt PGP private key",
1017 fmt.Sprintf("Enter password for %s (%8X)\nPress <ESC> to cancel",
1018 ident.Name, key.PublicKey.KeyId))
1019
1020 for err := range chErr {
1021 if err != nil {
1022 return nil, err
1023 }
1024 pass := <-chPass
1025 err = key.PrivateKey.Decrypt([]byte(pass))
1026 return nil, err
1027 }
1028 }
1029 return nil, err
1030 }
1031
1032 // errorScreen is a widget that draws an error in the middle of the context
1033 func errorScreen(s string) ui.Drawable {
1034 errstyle := config.Ui().GetStyle(config.STYLE_ERROR)
1035 text := ui.NewText(s, errstyle).Strategy(ui.TEXT_CENTER)
1036 grid := ui.NewGrid().Rows([]ui.GridSpec{
1037 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
1038 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)},
1039 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
1040 }).Columns([]ui.GridSpec{
1041 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
1042 })
1043 grid.AddChild(ui.NewFill(' ', vaxis.Style{})).At(0, 0)
1044 grid.AddChild(text).At(1, 0)
1045 grid.AddChild(ui.NewFill(' ', vaxis.Style{})).At(2, 0)
1046 return grid
1047 }
1048
1049 func (aerc *Aerc) isExKey(key vaxis.Key, exKey config.KeyStroke) bool {
1050 return key.Matches(exKey.Key, exKey.Modifiers)
1051 }
1052
1053 // CmdFallbackSearch checks cmds for the first executable available in PATH. An error is
1054 // returned if none are found
1055 func CmdFallbackSearch(cmds []string, silent bool) (string, error) {
1056 var tried []string
1057 for _, cmd := range cmds {
1058 if cmd == "" {
1059 continue
1060 }
1061 params := strings.Split(cmd, " ")
1062 _, err := exec.LookPath(params[0])
1063 if err != nil {
1064 tried = append(tried, cmd)
1065 if !silent {
1066 warn := fmt.Sprintf("cmd '%s' not found in PATH, using fallback", cmd)
1067 PushWarning(warn)
1068 }
1069 continue
1070 }
1071 return cmd, nil
1072 }
1073 return "", fmt.Errorf("no command found in PATH: %s", tried)
1074 }
1075
1076 func (aerc *Aerc) keyHintPosition(uiConf *config.UIConfig) string {
1077 if uiConf.KeyHintPosition != "" {
1078 return uiConf.KeyHintPosition
1079 }
1080 sl := config.Statusline()
1081 idx := sl.PendingKeysColIndex()
1082 n := len(sl.StatusColumns)
1083 switch {
1084 case idx < 0 || n <= 1:
1085 return "bottom-center"
1086 case idx == 0:
1087 return "bottom-left"
1088 case idx == n-1:
1089 return "bottom-right"
1090 default:
1091 return "bottom-center"
1092 }
1093 }