Debian Codegraph @

app/compose.go

raw
1 package app
2
3 import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "io"
8 "net/textproto"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strconv"
13 "strings"
14 "sync"
15 "sync/atomic"
16 "time"
17
18 "github.com/emersion/go-message/mail"
19 "github.com/mattn/go-runewidth"
20 "github.com/pkg/errors"
21
22 "git.sr.ht/~rjarry/aerc/commands/mode"
23 "git.sr.ht/~rjarry/aerc/completer"
24 "git.sr.ht/~rjarry/aerc/config"
25 "git.sr.ht/~rjarry/aerc/lib"
26 "git.sr.ht/~rjarry/aerc/lib/format"
27 "git.sr.ht/~rjarry/aerc/lib/log"
28 "git.sr.ht/~rjarry/aerc/lib/send"
29 "git.sr.ht/~rjarry/aerc/lib/state"
30 "git.sr.ht/~rjarry/aerc/lib/templates"
31 "git.sr.ht/~rjarry/aerc/lib/ui"
32 "git.sr.ht/~rjarry/aerc/lib/xdg"
33 "git.sr.ht/~rjarry/aerc/models"
34 "git.sr.ht/~rjarry/aerc/worker/types"
35 "go.rockorager.dev/vaxis"
36 )
37
38 type withCenteredGrid struct {
39 width int
40 centeredLayoutWidth int
41 }
42
43 type Composer struct {
44 withCenteredGrid
45 sync.Mutex
46 editors map[string]*headerEditor // indexes in lower case (from / cc / bcc)
47 header *mail.Header
48 parent *models.OriginalMail // parent of current message, only set if reply
49
50 acctConfig *config.AccountConfig
51 acct *AccountView
52 seldir string
53
54 attachments []lib.Attachment
55 editor *Terminal
56 email *os.File
57 grid atomic.Value
58 heditors atomic.Value // from, to, cc display a user can jump to
59 review *reviewMessage
60 worker *types.Worker
61 completer *completer.Completer
62 crypto *cryptoStatus
63 sign bool
64 encrypt bool
65 attachKey bool
66 editHeaders bool
67
68 layout HeaderLayout
69 focusable []ui.MouseableDrawableInteractive
70 focused int
71 sent bool
72 archive string
73
74 recalledFrom string
75 postponed bool
76
77 onClose []func(ti *Composer)
78
79 textParts []*lib.Part
80 Tab *ui.Tab
81 }
82
83 func (o *withCenteredGrid) centerWidth() int {
84 if o.centeredLayoutWidth > 0 && o.width >= o.centeredLayoutWidth {
85 return o.centeredLayoutWidth
86 }
87 return o.width
88 }
89
90 func (o *withCenteredGrid) makeCenteredGrid(rowspecs []ui.GridSpec) *ui.Grid {
91 return ui.NewGrid().Rows(rowspecs).Columns([]ui.GridSpec{
92 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
93 {Strategy: ui.SIZE_EXACT, Size: o.centerWidth},
94 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
95 })
96 }
97
98 func NewComposer(
99 acct *AccountView, acctConfig *config.AccountConfig,
100 worker *types.Worker, editHeaders bool, template string,
101 h *mail.Header, orig *models.OriginalMail, body io.Reader,
102 ) (*Composer, error) {
103 if h == nil {
104 h = new(mail.Header)
105 }
106
107 composePath := xdg.StatePath("aerc", "compose")
108 _ = os.MkdirAll(composePath, 0o700)
109
110 email, err := os.CreateTemp(composePath, "aerc-compose-*.eml")
111 if err != nil {
112 // TODO: handle this better
113 return nil, err
114 }
115
116 c := &Composer{
117 acct: acct,
118 acctConfig: acctConfig,
119 seldir: acct.Directories().Selected(),
120 header: h,
121 parent: orig,
122 email: email,
123 worker: worker,
124 // You have to backtab to get to "From", since you usually don't edit it
125 focused: 1,
126 completer: nil,
127
128 editHeaders: editHeaders,
129
130 withCenteredGrid: withCenteredGrid{0, acct.UiConfig().CenteredLayoutWidth},
131 }
132
133 data := state.NewDataSetter()
134 data.SetAccount(acct.acct)
135 data.SetFolder(acct.Directories().SelectedDirectory())
136 data.SetHeaders(h, orig)
137 data.SetComposer(c)
138 if body != nil {
139 buf := new(strings.Builder)
140 _, err := io.Copy(buf, body)
141 if err != nil {
142 return nil, err
143 }
144 data.SetBody(buf.String())
145 }
146 if err := c.setUpFields(template, data.Data()); err != nil {
147 return nil, err
148 }
149 if err := c.setupFor(acct); err != nil {
150 return nil, err
151 }
152
153 if err := c.ShowTerminal(editHeaders); err != nil {
154 return nil, err
155 }
156
157 mode.NoQuit()
158
159 return c, nil
160 }
161
162 func (c *Composer) SelectedDirectory() string {
163 return c.seldir
164 }
165
166 func (c *Composer) Parent() *models.OriginalMail {
167 return c.parent
168 }
169
170 func (c *Composer) SwitchAccount(newAcct *AccountView) error {
171 // sync the header with the editors
172 for _, editor := range c.editors {
173 editor.storeValue()
174 }
175 // ensure that from header is updated, so remove it
176 c.header.Del("from")
177 c.header.Del("message-id")
178 // update entire composer with new the account
179 if err := c.setupFor(newAcct); err != nil {
180 return err
181 }
182 // sync the header with the editors
183 for _, editor := range c.editors {
184 editor.loadValue()
185 }
186 c.resetReview()
187 c.Invalidate()
188 log.Debugf("account successfully switched")
189 return nil
190 }
191
192 func (c *Composer) setupFor(view *AccountView) error {
193 c.Lock()
194 defer c.Unlock()
195 // set new account
196 c.acct = view
197 c.worker = view.Worker()
198 c.acctConfig = c.acct.AccountConfig()
199 // Set from header if not already in header
200 if fl, err := c.header.AddressList("from"); err != nil || fl == nil {
201 c.header.SetAddressList("from", []*mail.Address{view.acct.From})
202 }
203 if !c.header.Has("to") {
204 c.header.SetAddressList("to", make([]*mail.Address, 0))
205 }
206 if !c.header.Has("subject") {
207 c.header.SetSubject("")
208 }
209
210 // update completer
211 cmd := view.acct.AddressBookCmd
212 if cmd == "" {
213 cmd = config.Compose().AddressBookCmd
214 }
215 cmpl := completer.New(cmd, func(err error) {
216 PushError(
217 fmt.Sprintf("could not complete header: %v", err))
218 log.Errorf("could not complete header: %v", err)
219 })
220 c.completer = cmpl
221
222 // if editor already exists, we have to get it from the focusable slice
223 // because this will be rebuild during buildComposeHeader()
224 var focusEditor ui.MouseableDrawableInteractive
225 if c.editor != nil && len(c.focusable) > 0 {
226 focusEditor = c.focusable[len(c.focusable)-1]
227 }
228
229 // rebuild editors and focusable slice
230 c.buildComposeHeader(cmpl)
231
232 // restore the editor in the focusable list
233 if focusEditor != nil {
234 c.focusable = append(c.focusable, focusEditor)
235 }
236 if c.focused >= len(c.focusable) {
237 c.focused = len(c.focusable) - 1
238 }
239
240 // update the crypto parts
241 c.crypto = nil
242 c.sign = false
243 if c.acct.acct.PgpAutoSign {
244 err := c.SetSign(true)
245 log.Warnf("failed to enable message signing: %v", err)
246 }
247 c.encrypt = false
248 if c.acct.acct.PgpOpportunisticEncrypt {
249 c.SetEncrypt(true)
250 }
251 err := c.updateCrypto()
252 if err != nil {
253 log.Warnf("failed to update crypto: %v", err)
254 }
255
256 // redraw the grid
257 c.grid.Store(c.buildGrid())
258
259 return nil
260 }
261
262 func (c *Composer) buildComposeHeader(cmpl *completer.Completer) {
263 c.layout = config.Compose().HeaderLayout
264 c.editors = make(map[string]*headerEditor)
265 c.focusable = make([]ui.MouseableDrawableInteractive, 0)
266 uiConfig := c.acct.UiConfig()
267
268 for i, row := range c.layout {
269 for j, h := range row {
270 h = strings.ToLower(h)
271 c.layout[i][j] = h // normalize to lowercase
272 e := newHeaderEditor(h, c.header, uiConfig)
273 if uiConfig.CompletionPopovers {
274 e.input.TabComplete(
275 cmpl.ForHeader(h),
276 uiConfig.CompletionDelay,
277 uiConfig.CompletionMinChars,
278 &config.Binds().Compose.CompleteKey,
279 )
280 }
281 c.editors[h] = e
282 switch h {
283 case "from":
284 // Prepend From to support backtab
285 c.focusable = append([]ui.MouseableDrawableInteractive{e}, c.focusable...)
286 default:
287 c.focusable = append(c.focusable, e)
288 }
289 e.OnChange(func() {
290 c.setTitle()
291 ui.Invalidate()
292 })
293 e.OnFocusLost(func() {
294 c.PrepareHeader() //nolint:errcheck // tab title only, fine if it's not valid yet
295 c.setTitle()
296 ui.Invalidate()
297 })
298 }
299 }
300
301 // Add Cc/Bcc editors to layout if present in header and not already visible
302 for _, h := range []string{"cc", "bcc"} {
303 if c.header.Has(h) {
304 if _, ok := c.editors[h]; !ok {
305 e := newHeaderEditor(h, c.header, uiConfig)
306 if uiConfig.CompletionPopovers {
307 e.input.TabComplete(
308 cmpl.ForHeader(h),
309 uiConfig.CompletionDelay,
310 uiConfig.CompletionMinChars,
311 &config.Binds().Compose.CompleteKey,
312 )
313 }
314 c.editors[h] = e
315 c.focusable = append(c.focusable, e)
316 c.layout = append(c.layout, []string{h})
317 }
318 }
319 }
320
321 // load current header values into all editors
322 for _, e := range c.editors {
323 e.loadValue()
324 }
325 }
326
327 func (c *Composer) headerOrder() []string {
328 var order []string
329 for _, row := range c.layout {
330 order = append(order, row...)
331 }
332 return order
333 }
334
335 func (c *Composer) SetSent(archive string) {
336 c.sent = true
337 c.archive = archive
338 }
339
340 func (c *Composer) Sent() bool {
341 return c.sent
342 }
343
344 func (c *Composer) SetPostponed() {
345 c.postponed = true
346 }
347
348 func (c *Composer) Postponed() bool {
349 return c.postponed
350 }
351
352 func (c *Composer) SetRecalledFrom(folder string) {
353 c.recalledFrom = folder
354 }
355
356 func (c *Composer) RecalledFrom() string {
357 return c.recalledFrom
358 }
359
360 func (c *Composer) Archive() string {
361 return c.archive
362 }
363
364 func (c *Composer) SetAttachKey(attach bool) error {
365 if c.crypto == nil {
366 if err := c.updateCrypto(); err != nil {
367 return err
368 }
369 }
370 if !attach {
371 name := c.crypto.signKey + ".asc"
372 found := false
373 for _, a := range c.attachments {
374 if a.Name() == name {
375 found = true
376 }
377 }
378 if found {
379 err := c.DeleteAttachment(name)
380 if err != nil {
381 return fmt.Errorf("failed to delete attachment '%s: %w", name, err)
382 }
383 }
384 }
385 if attach {
386 var s string
387 var err error
388 if c.crypto.signKey == "" {
389 if c.acctConfig.PgpKeyId != "" {
390 s = c.acctConfig.PgpKeyId
391 } else {
392 s = c.acctConfig.From.Address
393 }
394 c.crypto.signKey, err = CryptoProvider().GetSignerKeyId(s)
395 if err != nil {
396 return err
397 }
398 }
399
400 r, err := CryptoProvider().ExportKey(c.crypto.signKey)
401 if err != nil {
402 return err
403 }
404
405 newPart, err := lib.NewPart(
406 "application/pgp-keys",
407 map[string]string{"charset": "UTF-8"},
408 r,
409 )
410 if err != nil {
411 return err
412 }
413 c.attachments = append(c.attachments,
414 lib.NewPartAttachment(
415 newPart,
416 c.crypto.signKey+".asc",
417 ),
418 )
419
420 }
421
422 c.attachKey = attach
423
424 c.resetReview()
425 return nil
426 }
427
428 func (c *Composer) AttachKey() bool {
429 return c.attachKey
430 }
431
432 func (c *Composer) SetSign(sign bool) error {
433 c.sign = sign
434 err := c.updateCrypto()
435 if err != nil {
436 c.sign = !sign
437 return fmt.Errorf("Cannot sign message: %w", err)
438 }
439 if c.acct.acct.PgpAttachKey {
440 if err := c.SetAttachKey(sign); err != nil {
441 return err
442 }
443 }
444 return nil
445 }
446
447 func (c *Composer) Sign() bool {
448 return c.sign
449 }
450
451 func (c *Composer) SetEncrypt(encrypt bool) *Composer {
452 if !encrypt {
453 c.encrypt = encrypt
454 err := c.updateCrypto()
455 if err != nil {
456 log.Warnf("failed to update crypto: %v", err)
457 }
458 return c
459 }
460 // Check on any attempt to encrypt, and any lost focus of "to", "cc", or
461 // "bcc" field. Use OnFocusLost instead of OnChange to limit keyring checks
462 c.encrypt = c.checkEncryptionKeys("")
463 if c.crypto.setEncOneShot {
464 // Prevent registering a lot of callbacks
465 c.OnFocusLost("to", c.checkEncryptionKeys)
466 c.OnFocusLost("cc", c.checkEncryptionKeys)
467 c.OnFocusLost("bcc", c.checkEncryptionKeys)
468 c.crypto.setEncOneShot = false
469 }
470 return c
471 }
472
473 func (c *Composer) Encrypt() bool {
474 return c.encrypt
475 }
476
477 func (c *Composer) updateCrypto() error {
478 if c.crypto == nil {
479 uiConfig := c.acct.UiConfig()
480 c.crypto = newCryptoStatus(uiConfig)
481 }
482 if c.sign {
483 cp := CryptoProvider()
484 s, err := c.Signer()
485 if err != nil {
486 return errors.Wrap(err, "Signer")
487 }
488 c.crypto.signKey, err = cp.GetSignerKeyId(s)
489 if err != nil {
490 return err
491 }
492 }
493
494 st := ""
495 switch {
496 case c.sign && c.encrypt:
497 st = fmt.Sprintf("Sign (%s) & Encrypt", c.crypto.signKey)
498 case c.sign:
499 st = fmt.Sprintf("Sign (%s)", c.crypto.signKey)
500 case c.encrypt:
501 st = "Encrypt"
502 }
503 c.crypto.status.Text(st)
504
505 c.grid.Store(c.buildGrid())
506
507 return nil
508 }
509
510 func (c *Composer) writeEml(reader io.Reader) error {
511 // .eml files must always use '\r\n' line endings, but some editors
512 // don't support these, so if they are using one of those, the
513 // line-endings are transformed
514 lineEnding := "\r\n"
515 if config.Compose().LFEditor {
516 lineEnding = "\n"
517 }
518
519 scanner := bufio.NewScanner(reader)
520 for scanner.Scan() {
521 _, err := c.email.WriteString(scanner.Text() + lineEnding)
522 if err != nil {
523 return err
524 }
525 }
526 if scanner.Err() != nil {
527 return scanner.Err()
528 }
529 return c.email.Sync()
530 }
531
532 // Note: this does not reload the editor. You must call this before the first
533 // Draw() call.
534 func (c *Composer) setContents(reader io.Reader) error {
535 _, err := c.email.Seek(0, io.SeekStart)
536 if err != nil {
537 return err
538 }
539 err = c.email.Truncate(0)
540 if err != nil {
541 return err
542 }
543 lineEnding := "\r\n"
544 if config.Compose().LFEditor {
545 lineEnding = "\n"
546 }
547
548 if c.editHeaders {
549 for _, h := range c.headerOrder() {
550 var value string
551 switch h {
552 case "to", "from", "cc", "bcc":
553 addresses, err := c.header.AddressList(h)
554 if err != nil {
555 log.Warnf("header.AddressList: %s", err)
556 value, err = c.header.Text(h)
557 if err != nil {
558 log.Warnf("header.Text: %s", err)
559 value = c.header.Get(h)
560 }
561 } else {
562 addr := make([]string, 0, len(addresses))
563 for _, a := range addresses {
564 addr = append(addr, format.AddressForHumans(a))
565 }
566 value = strings.Join(addr, ","+lineEnding+"\t")
567 }
568 default:
569 value, err = c.header.Text(h)
570 if err != nil {
571 log.Warnf("header.Text: %s", err)
572 value = c.header.Get(h)
573 }
574 }
575 key := textproto.CanonicalMIMEHeaderKey(h)
576
577 var sep string
578 if value == "" && config.Compose().FormatFlowed {
579 sep = ":"
580 } else {
581 sep = ": "
582 }
583 _, err = fmt.Fprintf(c.email, "%s%s%s%s", key, sep, value, lineEnding)
584 if err != nil {
585 return err
586 }
587 }
588 _, err = c.email.WriteString(lineEnding)
589 if err != nil {
590 return err
591 }
592 }
593 return c.writeEml(reader)
594 }
595
596 func (c *Composer) AppendPart(mimetype string, params map[string]string, body io.Reader) error {
597 if !strings.HasPrefix(mimetype, "text") {
598 return fmt.Errorf("can only append text mimetypes")
599 }
600 for _, part := range c.textParts {
601 if part.MimeType == mimetype {
602 return fmt.Errorf("%s part already exists", mimetype)
603 }
604 }
605 newPart, err := lib.NewPart(mimetype, params, body)
606 if err != nil {
607 return err
608 }
609 c.textParts = append(c.textParts, newPart)
610 c.resetReview()
611 return nil
612 }
613
614 func (c *Composer) RemovePart(mimetype string) error {
615 if mimetype == "text/plain" {
616 return fmt.Errorf("cannot remove text/plain parts")
617 }
618 for i, part := range c.textParts {
619 if part.MimeType != mimetype {
620 continue
621 }
622 c.textParts = append(c.textParts[:i], c.textParts[i+1:]...)
623 c.resetReview()
624 return nil
625 }
626 return fmt.Errorf("%s part not found", mimetype)
627 }
628
629 func (c *Composer) setUpFields(
630 template string, data models.TemplateData,
631 ) error {
632 if template == "" {
633 // No template, but there might be a body from recall
634 return c.setContents(strings.NewReader(data.Body()))
635 }
636
637 templateText, err := templates.ParseTemplateFromFile(
638 template, config.Templates().TemplateDirs, data)
639 if err != nil {
640 return err
641 }
642
643 buf, err := io.ReadAll(templateText)
644 if err != nil {
645 return err
646 }
647
648 mr, err := mail.CreateReader(bytes.NewReader(buf))
649 if err != nil {
650 log.Warnf("failed to parse rendered template '%s' as email: %v",
651 template, err)
652 // For backward compatibility with old aerc which supported
653 // templates that don't parse as an email.
654
655 return c.setContents(bytes.NewReader(buf))
656 }
657
658 // copy the headers contained in the template to the compose headers
659 hf := mr.Header.Fields()
660 for hf.Next() {
661 c.header.Set(hf.Key(), hf.Value())
662 }
663
664 part, err := mr.NextPart()
665 if err != nil {
666 return fmt.Errorf("NextPart: %w", err)
667 }
668
669 return c.setContents(part.Body)
670 }
671
672 func (c *Composer) GetBody() (*bytes.Buffer, error) {
673 _, err := c.email.Seek(0, io.SeekStart)
674 if err != nil {
675 return nil, err
676 }
677 scanner := bufio.NewScanner(c.email)
678 if c.editHeaders {
679 // skip headers
680 for scanner.Scan() {
681 if scanner.Text() == "" {
682 break // stop on first empty line
683 }
684 }
685 }
686 // .eml files must always use '\r\n' line endings
687 buf := new(bytes.Buffer)
688 for scanner.Scan() {
689 buf.WriteString(scanner.Text() + "\r\n")
690 }
691 err = scanner.Err()
692 if err != nil {
693 return nil, err
694 }
695 return buf, nil
696 }
697
698 func (c *Composer) FocusTerminal() *Composer {
699 c.Lock()
700 defer c.Unlock()
701 return c.focusTerminalPriv()
702 }
703
704 func (c *Composer) focusTerminalPriv() *Composer {
705 if c.editor == nil {
706 return c
707 }
708 c.focusActiveWidget(false)
709 c.focused = len(c.focusable) - 1
710 c.focusActiveWidget(true)
711 return c
712 }
713
714 // OnHeaderChange registers an OnChange callback for the specified header.
715 func (c *Composer) OnHeaderChange(header string, fn func(subject string)) {
716 if editor, ok := c.editors[strings.ToLower(header)]; ok {
717 editor.OnChange(func() {
718 fn(editor.input.String())
719 })
720 }
721 }
722
723 // OnFocusLost registers an OnFocusLost callback for the specified header.
724 func (c *Composer) OnFocusLost(header string, fn func(input string) bool) {
725 if editor, ok := c.editors[strings.ToLower(header)]; ok {
726 editor.OnFocusLost(func() {
727 fn(editor.input.String())
728 })
729 }
730 }
731
732 func (c *Composer) OnClose(fn func(composer *Composer)) {
733 c.onClose = append(c.onClose, fn)
734 }
735
736 func (c *Composer) Terminal() *Terminal {
737 return c.editor
738 }
739
740 func (c *Composer) Draw(ctx *ui.Context) {
741 c.setTitle()
742 c.width = ctx.Width()
743 c.grid.Load().(*ui.Grid).Draw(ctx)
744 }
745
746 func (c *Composer) Invalidate() {
747 ui.Invalidate()
748 }
749
750 func (c *Composer) Close() {
751 for _, onClose := range c.onClose {
752 onClose(c)
753 }
754 if c.email != nil {
755 path := c.email.Name()
756 c.email.Close()
757 os.Remove(path)
758 c.email = nil
759 }
760 if c.editor != nil {
761 c.editor.Destroy()
762 c.editor = nil
763 }
764 mode.NoQuitDone()
765 }
766
767 func (c *Composer) Bindings() string {
768 c.Lock()
769 defer c.Unlock()
770 switch c.editor {
771 case nil:
772 return "compose::review"
773 case c.focusedWidget():
774 return "compose::editor"
775 default:
776 return "compose"
777 }
778 }
779
780 func (c *Composer) focusedWidget() ui.MouseableDrawableInteractive {
781 if c.focused < 0 || c.focused >= len(c.focusable) {
782 return nil
783 }
784 return c.focusable[c.focused]
785 }
786
787 func (c *Composer) focusActiveWidget(focus bool) {
788 if w := c.focusedWidget(); w != nil {
789 w.Focus(focus)
790 }
791 }
792
793 func (c *Composer) Event(event vaxis.Event) bool {
794 c.Lock()
795 defer c.Unlock()
796 var processed bool
797 // Color theme changes always need to be propagated to the editor so
798 // that it can repaint itself.
799 if _, ok := event.(vaxis.ColorThemeUpdate); ok && c.editor != nil {
800 processed = c.editor.Event(event)
801 }
802 if w := c.focusedWidget(); c.editor != nil && w != nil {
803 processed = w.Event(event) || processed
804 }
805 return processed
806 }
807
808 func (c *Composer) MouseEvent(localX int, localY int, event vaxis.Event) {
809 c.Lock()
810 for _, e := range c.focusable {
811 he, ok := e.(*headerEditor)
812 if ok && he.focused {
813 he.focused = false
814 }
815 }
816 c.Unlock()
817 c.grid.Load().(*ui.Grid).MouseEvent(localX, localY, event)
818 c.Lock()
819 defer c.Unlock()
820 for i, e := range c.focusable {
821 he, ok := e.(*headerEditor)
822 if ok && he.focused {
823 if c.editor == nil {
824 he.focused = false
825 } else {
826 c.focusActiveWidget(false)
827 c.focused = i
828 c.focusActiveWidget(true)
829 }
830 return
831 }
832 }
833 }
834
835 func (c *Composer) Focus(focus bool) {
836 c.Lock()
837 if c.editor != nil {
838 c.focusActiveWidget(focus)
839 }
840 c.Unlock()
841 }
842
843 func (c *Composer) Show(visible bool) {
844 c.Lock()
845 if w := c.focusedWidget(); w != nil && c.editor != nil {
846 if vis, ok := w.(ui.Visible); ok {
847 vis.Show(visible)
848 }
849 }
850 c.Unlock()
851 }
852
853 func (c *Composer) Config() *config.AccountConfig {
854 return c.acctConfig
855 }
856
857 func (c *Composer) Account() *AccountView {
858 return c.acct
859 }
860
861 func (c *Composer) Worker() *types.Worker {
862 return c.worker
863 }
864
865 // PrepareHeader finalizes the header, adding the value from the editors
866 func (c *Composer) PrepareHeader() (*mail.Header, error) {
867 for _, editor := range c.editors {
868 editor.storeValue()
869 }
870
871 // control headers not normally set by the user
872 // repeated calls to PrepareHeader should be a noop
873 if !c.header.Has("Message-Id") {
874 froms, err := c.header.AddressList("from")
875 if err != nil {
876 return nil, err
877 }
878 if len(froms) == 0 {
879 return nil, fmt.Errorf("no valid From address found")
880 }
881 hostname, err := send.GetMessageIdHostname(
882 c.acctConfig.SendWithHostname, froms[0])
883 if err != nil {
884 return nil, err
885 }
886 if err := c.header.GenerateMessageIDWithHostname(hostname); err != nil {
887 return nil, err
888 }
889 }
890
891 // update the "Date" header every time PrepareHeader is called
892 if c.acctConfig.SendAsUTC {
893 c.header.SetDate(time.Now().UTC())
894 } else {
895 c.header.SetDate(time.Now())
896 }
897
898 return c.header, nil
899 }
900
901 func (c *Composer) parseEmbeddedHeader() (*mail.Header, error) {
902 _, err := c.email.Seek(0, io.SeekStart)
903 if err != nil {
904 return nil, errors.Wrap(err, "Seek")
905 }
906
907 buf := bytes.NewBuffer([]byte{})
908 _, err = io.Copy(buf, c.email)
909 if err != nil {
910 return nil, fmt.Errorf("mail.ReadMessageCopy: %w", err)
911 }
912 if config.Compose().LFEditor {
913 bytes.ReplaceAll(buf.Bytes(), []byte{'\n'}, []byte{'\r', '\n'})
914 }
915
916 msg, err := mail.CreateReader(buf)
917 if errors.Is(err, io.EOF) { // completely empty
918 h := mail.HeaderFromMap(make(map[string][]string))
919 return &h, nil
920 } else if err != nil {
921 return nil, fmt.Errorf("mail.ReadMessage: %w", err)
922 }
923
924 // merge repeated to, cc, and bcc headers into a single one of each
925 for _, key := range []string{"To", "Cc", "Bcc"} {
926 fields := msg.Header.FieldsByKey(key)
927 if fields.Len() <= 1 {
928 continue
929 }
930 var addrs []*mail.Address
931 for fields.Next() {
932 if strings.TrimSpace(fields.Value()) == "" {
933 continue
934 }
935 al, err := mail.ParseAddressList(fields.Value())
936 if err != nil {
937 return nil, fmt.Errorf(
938 "%s: cannot parse address list: %w", key, err)
939 }
940 addrs = append(addrs, al...)
941 }
942 msg.Header.SetAddressList(key, addrs)
943 PushWarning(fmt.Sprintf(
944 "Multiple %s headers found; merged in a single one.", key))
945 }
946
947 return &msg.Header, nil
948 }
949
950 func getRecipientsEmail(c *Composer) ([]string, error) {
951 h, err := c.PrepareHeader()
952 if err != nil {
953 return nil, errors.Wrap(err, "PrepareHeader")
954 }
955
956 // collect all 'recipients' from header (to:, cc:, bcc:)
957 rcpts := make(map[string]bool)
958 for _, key := range []string{"to", "cc", "bcc"} {
959 list, err := h.AddressList(key)
960 if err != nil {
961 continue
962 }
963 for _, entry := range list {
964 if entry != nil {
965 rcpts[entry.Address] = true
966 }
967 }
968 }
969
970 // return email addresses as string slice
971 results := []string{}
972 for email := range rcpts {
973 results = append(results, email)
974 }
975 return results, nil
976 }
977
978 func (c *Composer) Signer() (string, error) {
979 signer := ""
980
981 if c.acctConfig.PgpKeyId != "" {
982 // get key from explicitly set keyid
983 signer = c.acctConfig.PgpKeyId
984 } else {
985 // get signer from `from` header
986 from, err := c.header.AddressList("from")
987 if err != nil {
988 return "", err
989 }
990
991 if len(from) > 0 {
992 signer = from[0].Address
993 } else {
994 // fall back to address from config
995 signer = c.acctConfig.From.Address
996 }
997 }
998
999 return signer, nil
1000 }
1001
1002 func (c *Composer) WriteMessage(header *mail.Header, writer io.Writer) error {
1003 if c.sign || c.encrypt {
1004
1005 var signedHeader mail.Header
1006 signedHeader.SetContentType("text/plain", nil)
1007
1008 var buf bytes.Buffer
1009 var cleartext io.WriteCloser
1010 var err error
1011
1012 signer := ""
1013 if c.sign {
1014 signer, err = c.Signer()
1015 if err != nil {
1016 return errors.Wrap(err, "Signer")
1017 }
1018 }
1019
1020 if c.encrypt {
1021 rcpts, err := getRecipientsEmail(c)
1022 if err != nil {
1023 return err
1024 }
1025
1026 if c.acct.acct.PgpSelfEncrypt {
1027 signer, err := c.Signer()
1028 if err != nil {
1029 return err
1030 }
1031 rcpts = append(rcpts, signer)
1032 }
1033
1034 cleartext, err = CryptoProvider().Encrypt(&buf, rcpts, signer, DecryptKeys, header)
1035 if err != nil {
1036 return err
1037 }
1038 } else {
1039 cleartext, err = CryptoProvider().Sign(&buf, signer, DecryptKeys, header)
1040 if err != nil {
1041 return err
1042 }
1043 }
1044
1045 err = writeMsgImpl(c, &signedHeader, cleartext)
1046 if err != nil {
1047 return err
1048 }
1049 err = cleartext.Close()
1050 if err != nil {
1051 return err
1052 }
1053 _, err = io.Copy(writer, &buf)
1054 if err != nil {
1055 return fmt.Errorf("failed to write message: %w", err)
1056 }
1057 return nil
1058
1059 } else {
1060 return writeMsgImpl(c, header, writer)
1061 }
1062 }
1063
1064 func (c *Composer) ShouldWarnAttachment() bool {
1065 regex := config.Compose().NoAttachmentWarning
1066
1067 if regex == nil || len(c.attachments) > 0 {
1068 return false
1069 }
1070
1071 body, err := c.GetBody()
1072 if err != nil {
1073 log.Warnf("failed to check for a forgotten attachment: %v", err)
1074 return true
1075 }
1076
1077 return regex.Match(body.Bytes())
1078 }
1079
1080 func (c *Composer) ShouldWarnSubject() bool {
1081 if !config.Compose().EmptySubjectWarning {
1082 return false
1083 }
1084
1085 // ignore errors because the raw header field is sufficient here
1086 subject, _ := c.header.Subject()
1087 return len(subject) == 0
1088 }
1089
1090 func (c *Composer) CheckForMultipartErrors() error {
1091 problems := []string{}
1092 for _, p := range c.textParts {
1093 if p.ConversionError != nil {
1094 text := fmt.Sprintf("%s: %s", p.MimeType, p.ConversionError.Error())
1095 problems = append(problems, text)
1096 }
1097 }
1098
1099 if len(problems) == 0 {
1100 return nil
1101 }
1102
1103 return fmt.Errorf("multipart conversion error: %s", strings.Join(problems, "; "))
1104 }
1105
1106 func writeMsgImpl(c *Composer, header *mail.Header, writer io.Writer) error {
1107 mimeParams := map[string]string{"Charset": "UTF-8"}
1108 if config.Compose().FormatFlowed {
1109 mimeParams["Format"] = "Flowed"
1110 }
1111 body, err := c.GetBody()
1112 if err != nil {
1113 return err
1114 }
1115 if len(c.attachments) == 0 && len(c.textParts) == 0 {
1116 // no attachments
1117 return writeInlineBody(header, body, writer, mimeParams)
1118 } else {
1119 // with attachments
1120 w, err := mail.CreateWriter(writer, *header)
1121 if err != nil {
1122 return errors.Wrap(err, "CreateWriter")
1123 }
1124 newPart, err := lib.NewPart("text/plain", mimeParams, body)
1125 if err != nil {
1126 return err
1127 }
1128 parts := []*lib.Part{newPart}
1129 if err := writeMultipartBody(append(parts, c.textParts...), w); err != nil {
1130 return errors.Wrap(err, "writeMultipartBody")
1131 }
1132 for _, a := range c.attachments {
1133 if err := a.WriteTo(w); err != nil {
1134 return errors.Wrap(err, "writeAttachment")
1135 }
1136 }
1137 w.Close()
1138 }
1139 return nil
1140 }
1141
1142 func writeInlineBody(
1143 header *mail.Header,
1144 body io.Reader,
1145 writer io.Writer,
1146 mimeParams map[string]string,
1147 ) error {
1148 header.SetContentType("text/plain", mimeParams)
1149 w, err := mail.CreateSingleInlineWriter(writer, *header)
1150 if err != nil {
1151 return errors.Wrap(err, "CreateSingleInlineWriter")
1152 }
1153 defer w.Close()
1154 if _, err := io.Copy(w, body); err != nil {
1155 return errors.Wrap(err, "io.Copy")
1156 }
1157 return nil
1158 }
1159
1160 // write the message body to the multipart message
1161 func writeMultipartBody(parts []*lib.Part, w *mail.Writer) error {
1162 bi, err := w.CreateInline()
1163 if err != nil {
1164 return errors.Wrap(err, "CreateInline")
1165 }
1166 defer bi.Close()
1167
1168 for _, part := range parts {
1169 bh := mail.InlineHeader{}
1170 bh.SetContentType(part.MimeType, part.Params)
1171 bw, err := bi.CreatePart(bh)
1172 if err != nil {
1173 return errors.Wrap(err, "CreatePart")
1174 }
1175 defer bw.Close()
1176 if _, err := io.Copy(bw, part.NewReader()); err != nil {
1177 return errors.Wrap(err, "io.Copy")
1178 }
1179 }
1180
1181 return nil
1182 }
1183
1184 func (c *Composer) GetAttachments() []string {
1185 var names []string
1186 for _, a := range c.attachments {
1187 names = append(names, a.Name())
1188 }
1189 return names
1190 }
1191
1192 func (c *Composer) AddAttachment(path string) {
1193 path, _ = filepath.Abs(path)
1194 path = xdg.TildeHome(path)
1195 c.attachments = append(c.attachments, lib.NewFileAttachment(path))
1196 c.resetReview()
1197 }
1198
1199 func (c *Composer) AddPartAttachment(name string, mimetype string,
1200 params map[string]string, body io.Reader,
1201 ) error {
1202 p, err := lib.NewPart(mimetype, params, body)
1203 if err != nil {
1204 return err
1205 }
1206 c.attachments = append(c.attachments, lib.NewPartAttachment(
1207 p, name,
1208 ))
1209 c.resetReview()
1210 return nil
1211 }
1212
1213 func (c *Composer) DeleteAttachment(name string) error {
1214 for i, a := range c.attachments {
1215 if a.Name() == name {
1216 c.attachments = append(c.attachments[:i], c.attachments[i+1:]...)
1217 c.resetReview()
1218 return nil
1219 }
1220 }
1221
1222 return errors.New("attachment does not exist")
1223 }
1224
1225 func (c *Composer) resetReview() {
1226 if c.review != nil {
1227 c.grid.Load().(*ui.Grid).RemoveChild(c.review)
1228 c.review = newReviewMessage(c, nil)
1229 c.grid.Load().(*ui.Grid).AddChild(c.review).At(3, 1)
1230 }
1231 }
1232
1233 func (c *Composer) termEvent(event vaxis.Event) bool {
1234 if event, ok := event.(vaxis.Mouse); ok {
1235 if event.Button == vaxis.MouseLeftButton {
1236 c.FocusTerminal()
1237 return true
1238 }
1239 }
1240 return false
1241 }
1242
1243 func (c *Composer) reopenEmailFile() error {
1244 name := c.email.Name()
1245 f, err := os.OpenFile(name, os.O_RDWR, 0o600)
1246 if err != nil {
1247 return err
1248 }
1249 err = c.email.Close()
1250 c.email = f
1251 return err
1252 }
1253
1254 func (c *Composer) termClosed(err error) {
1255 c.Lock()
1256 // RemoveTab() on error must be called *AFTER* c.Unlock() but the defer
1257 // statement does the exact opposite (last defer statement is executed
1258 // first). Use an explicit list that begins with unlocking first.
1259 deferred := []func(){c.Unlock}
1260 defer func() {
1261 for _, d := range deferred {
1262 d()
1263 }
1264 }()
1265 if c.editor == nil {
1266 return
1267 }
1268 if e := c.reopenEmailFile(); e != nil {
1269 PushError("Failed to reopen email file: " + e.Error())
1270 }
1271 editor := c.editor
1272 deferred = append(deferred, editor.Destroy)
1273 c.editor = nil
1274 c.focusable = c.focusable[:len(c.focusable)-1]
1275 if c.focused >= len(c.focusable) {
1276 c.focused = len(c.focusable) - 1
1277 }
1278
1279 if editor.cmd.ProcessState.ExitCode() > 0 {
1280 deferred = append(deferred, func() {
1281 RemoveTab(c, true)
1282 PushError("Editor exited with error. Compose aborted!")
1283 })
1284 return
1285 }
1286
1287 if c.editHeaders {
1288 // parse embedded header when editor is closed
1289 embedHeader, err := c.parseEmbeddedHeader()
1290 if err != nil {
1291 PushError(err.Error())
1292 err := c.showTerminal()
1293 if err != nil {
1294 deferred = append(deferred, func() {
1295 RemoveTab(c, true)
1296 PushError(err.Error())
1297 })
1298 }
1299 return
1300 }
1301 // delete previous headers first
1302 for _, h := range c.headerOrder() {
1303 c.delEditor(h)
1304 }
1305 hf := embedHeader.Fields()
1306 for hf.Next() {
1307 if hf.Value() != "" {
1308 // add new header values in order
1309 c.addEditor(hf.Key(), hf.Value(), false)
1310 }
1311 }
1312 }
1313
1314 // prepare review window
1315 c.review = newReviewMessage(c, err)
1316 c.grid.Store(c.buildGrid())
1317 }
1318
1319 func (c *Composer) ShowTerminal(editHeaders bool) error {
1320 c.Lock()
1321 defer c.Unlock()
1322 if c.editor != nil {
1323 return nil
1324 }
1325 body, err := c.GetBody()
1326 if err != nil {
1327 return err
1328 }
1329 c.editHeaders = editHeaders
1330 err = c.setContents(body)
1331 if err != nil {
1332 return err
1333 }
1334 return c.showTerminal()
1335 }
1336
1337 func (c *Composer) showTerminal() error {
1338 if c.editor != nil {
1339 c.editor.Destroy()
1340 }
1341 editorName, err := CmdFallbackSearch(config.EditorCmds(), false)
1342 if err != nil {
1343 c.acct.PushError(fmt.Errorf("could not start editor: %w", err))
1344 }
1345 editor := exec.Command("/bin/sh", "-c", editorName+" "+c.email.Name())
1346 env := os.Environ()
1347 env = append(env, fmt.Sprintf("AERC_ACCOUNT=%s", c.Account().Name()))
1348 env = append(env, fmt.Sprintf("AERC_ADDRESS_BOOK_CMD=%s", c.Account().AccountConfig().AddressBookCmd))
1349 editor.Env = env
1350
1351 c.editor, err = NewTerminal(editor)
1352 if err != nil {
1353 return err
1354 }
1355 c.editor.OnEvent = c.termEvent
1356 c.editor.OnClose = c.termClosed
1357 c.focusable = append(c.focusable, c.editor)
1358 c.review = nil
1359 c.grid.Store(c.buildGrid())
1360 if c.editHeaders || config.Compose().FocusBody {
1361 c.focusTerminalPriv()
1362 }
1363 return nil
1364 }
1365
1366 func (c *Composer) PrevField() bool {
1367 c.Lock()
1368 defer c.Unlock()
1369 if c.editHeaders || c.editor == nil {
1370 return false
1371 }
1372 c.focusActiveWidget(false)
1373 c.focused--
1374 if c.focused == -1 {
1375 c.focused = len(c.focusable) - 1
1376 }
1377 c.focusActiveWidget(true)
1378 return true
1379 }
1380
1381 func (c *Composer) NextField() bool {
1382 c.Lock()
1383 defer c.Unlock()
1384 if c.editHeaders || c.editor == nil {
1385 return false
1386 }
1387 c.focusActiveWidget(false)
1388 c.focused = (c.focused + 1) % len(c.focusable)
1389 c.focusActiveWidget(true)
1390 return true
1391 }
1392
1393 func (c *Composer) FocusEditor(editor string) bool {
1394 c.Lock()
1395 defer c.Unlock()
1396 if c.editHeaders || c.editor == nil {
1397 return false
1398 }
1399 return c.focusEditor(editor)
1400 }
1401
1402 func (c *Composer) focusEditor(editor string) bool {
1403 editor = strings.ToLower(editor)
1404 c.focusActiveWidget(false)
1405 defer c.focusActiveWidget(true)
1406 for i, f := range c.focusable {
1407 e := f.(*headerEditor)
1408 if strings.ToLower(e.name) == editor {
1409 c.focused = i
1410 return true
1411 }
1412 }
1413 return false
1414 }
1415
1416 // AddEditor appends a new header editor to the compose window.
1417 func (c *Composer) AddEditor(header string, value string, appendHeader bool) error {
1418 c.Lock()
1419 defer c.Unlock()
1420 if c.editHeaders && c.editor != nil {
1421 return errors.New("header should be added directly in the text editor")
1422 }
1423 value = c.addEditor(header, value, appendHeader)
1424 if value == "" {
1425 c.focusEditor(header)
1426 }
1427 c.grid.Store(c.buildGrid())
1428 return nil
1429 }
1430
1431 func (c *Composer) addEditor(header string, value string, appendHeader bool) string {
1432 var editor *headerEditor
1433 header = strings.ToLower(header)
1434 if e, ok := c.editors[header]; ok {
1435 e.storeValue() // flush modifications from the user to the header
1436 editor = e
1437 } else {
1438 uiConfig := c.acct.UiConfig()
1439 e := newHeaderEditor(header, c.header, uiConfig)
1440 if uiConfig.CompletionPopovers {
1441 e.input.TabComplete(
1442 c.completer.ForHeader(header),
1443 uiConfig.CompletionDelay,
1444 uiConfig.CompletionMinChars,
1445 &config.Binds().Compose.CompleteKey,
1446 )
1447 }
1448 c.editors[header] = e
1449 c.layout = append(c.layout, []string{header})
1450 if len(c.focusable) == 0 || c.editor == nil {
1451 // no terminal editor, insert at the end
1452 c.focusable = append(c.focusable, e)
1453 } else {
1454 // Insert focus of new editor before terminal editor
1455 c.focusable = append(
1456 c.focusable[:len(c.focusable)-1],
1457 e,
1458 c.focusable[len(c.focusable)-1],
1459 )
1460 }
1461 editor = e
1462 }
1463
1464 if appendHeader {
1465 currVal := editor.input.String()
1466 if currVal != "" {
1467 value = strings.TrimSpace(currVal) + ", " + value
1468 }
1469 }
1470 if value != "" || appendHeader {
1471 c.editors[header].input.Set(value)
1472 editor.storeValue()
1473 }
1474 return value
1475 }
1476
1477 // DelEditor removes a header editor from the compose window.
1478 func (c *Composer) DelEditor(header string) error {
1479 c.Lock()
1480 defer c.Unlock()
1481 if c.editHeaders && c.editor != nil {
1482 return errors.New("header should be removed directly in the text editor")
1483 }
1484 c.delEditor(header)
1485 c.grid.Store(c.buildGrid())
1486 return nil
1487 }
1488
1489 func (c *Composer) delEditor(header string) {
1490 header = strings.ToLower(header)
1491 c.header.Del(header)
1492 editor, ok := c.editors[header]
1493 if !ok {
1494 return
1495 }
1496
1497 var layout HeaderLayout = make([][]string, 0, len(c.layout))
1498 for _, row := range c.layout {
1499 r := make([]string, 0, len(row))
1500 for _, h := range row {
1501 if h != header {
1502 r = append(r, h)
1503 }
1504 }
1505 if len(r) > 0 {
1506 layout = append(layout, r)
1507 }
1508 }
1509 c.layout = layout
1510
1511 focusable := make([]ui.MouseableDrawableInteractive, 0, len(c.focusable)-1)
1512 for i, f := range c.focusable {
1513 if f == editor {
1514 if c.focused > 0 && c.focused >= i {
1515 c.focused--
1516 }
1517 } else {
1518 focusable = append(focusable, f)
1519 }
1520 }
1521 c.focusable = focusable
1522 c.focusActiveWidget(true)
1523
1524 delete(c.editors, header)
1525 }
1526
1527 // buildGrid should be called when the underlying header layout is changed.
1528 func (c *Composer) buildGrid() *ui.Grid {
1529 grid := c.makeCenteredGrid(nil)
1530
1531 if c.editHeaders && c.review == nil {
1532 grid.Rows([]ui.GridSpec{
1533 // 0: editor
1534 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
1535 })
1536 if c.editor != nil {
1537 grid.AddChild(c.editor).At(0, 1)
1538 }
1539 return grid
1540 }
1541
1542 heditors, height := c.layout.grid(
1543 func(h string) ui.Drawable {
1544 return c.editors[h]
1545 },
1546 )
1547
1548 crHeight := 0
1549 if c.sign || c.encrypt {
1550 crHeight = 1
1551 }
1552 grid.Rows([]ui.GridSpec{
1553 // 0: headers
1554 {Strategy: ui.SIZE_EXACT, Size: ui.Const(height)},
1555 // 1: crypto status
1556 {Strategy: ui.SIZE_EXACT, Size: ui.Const(crHeight)},
1557 // 2: filler line
1558 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)},
1559 // 3: editor or review
1560 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
1561 })
1562
1563 borderStyle := c.acct.UiConfig().GetStyle(config.STYLE_BORDER)
1564 borderChar := c.acct.UiConfig().BorderCharHorizontal
1565 grid.AddChild(heditors).At(0, 1)
1566 grid.AddChild(c.crypto).At(1, 1)
1567 grid.AddChild(ui.NewFill(borderChar, borderStyle)).At(2, 0)
1568 grid.AddChild(ui.NewFill(borderChar, borderStyle)).At(2, 1)
1569 grid.AddChild(ui.NewFill(borderChar, borderStyle)).At(2, 2)
1570 if c.review != nil {
1571 grid.AddChild(c.review).At(3, 1)
1572 } else if c.editor != nil {
1573 grid.AddChild(c.editor).At(3, 1)
1574 }
1575 c.heditors.Store(heditors)
1576 return grid
1577 }
1578
1579 type headerEditor struct {
1580 name string
1581 header *mail.Header
1582 focused bool
1583 input *ui.TextInput
1584 uiConfig *config.UIConfig
1585 }
1586
1587 func newHeaderEditor(name string, h *mail.Header,
1588 uiConfig *config.UIConfig,
1589 ) *headerEditor {
1590 he := &headerEditor{
1591 input: ui.NewTextInput("", uiConfig),
1592 name: name,
1593 header: h,
1594 uiConfig: uiConfig,
1595 }
1596 he.loadValue()
1597 return he
1598 }
1599
1600 // extractHumanHeaderValue extracts the human readable string for key from the
1601 // header. If a parsing error occurs the raw value is returned
1602 func extractHumanHeaderValue(key string, h *mail.Header) string {
1603 var val string
1604 var err error
1605 switch strings.ToLower(key) {
1606 case "to", "from", "cc", "bcc":
1607 var list []*mail.Address
1608 list, err = h.AddressList(key)
1609 val = format.FormatAddresses(list)
1610 default:
1611 val, err = h.Text(key)
1612 }
1613 if err != nil {
1614 // if we can't parse it, show it raw
1615 val = h.Get(key)
1616 }
1617 return val
1618 }
1619
1620 // loadValue loads the value of he.name form the underlying header
1621 // the value is decoded and meant for human consumption.
1622 // decoding issues are ignored and return their raw values
1623 func (he *headerEditor) loadValue() {
1624 he.input.Set(extractHumanHeaderValue(he.name, he.header))
1625 ui.Invalidate()
1626 }
1627
1628 // storeValue writes the current state back to the underlying header.
1629 // errors are ignored
1630 func (he *headerEditor) storeValue() {
1631 val := he.input.String()
1632 switch strings.ToLower(he.name) {
1633 case "to", "from", "cc", "bcc":
1634 if strings.TrimSpace(val) == "" {
1635 // if header is empty, delete it
1636 he.header.Del(he.name)
1637 return
1638 }
1639 list, err := mail.ParseAddressList(val)
1640 if err == nil {
1641 he.header.SetAddressList(he.name, list)
1642 } else {
1643 // garbage, but it'll blow up upon sending and the user can
1644 // fix the issue
1645 he.header.SetText(he.name, val)
1646 }
1647 default:
1648 he.header.SetText(he.name, val)
1649 }
1650 if strings.ToLower(he.name) == "from" {
1651 he.header.Del("message-id")
1652 }
1653 }
1654
1655 func (he *headerEditor) Draw(ctx *ui.Context) {
1656 name := textproto.CanonicalMIMEHeaderKey(he.name)
1657 // Extra character to put a blank cell between the header and the input
1658 size := runewidth.StringWidth(name+":") + 1
1659 defaultStyle := he.uiConfig.GetStyle(config.STYLE_DEFAULT)
1660 headerStyle := he.uiConfig.GetStyle(config.STYLE_HEADER)
1661 ctx.Fill(0, 0, size, ctx.Height(), ' ', defaultStyle)
1662 ctx.Printf(0, 0, headerStyle, "%s:", name)
1663 he.input.Draw(ctx.Subcontext(size, 0, ctx.Width()-size, 1))
1664 }
1665
1666 func (he *headerEditor) MouseEvent(localX int, localY int, event vaxis.Event) {
1667 if event, ok := event.(vaxis.Mouse); ok {
1668 if event.Button == vaxis.MouseLeftButton {
1669 he.focused = true
1670 }
1671
1672 width := runewidth.StringWidth(he.name + " ")
1673 if localX >= width {
1674 he.input.MouseEvent(localX-width, localY, event)
1675 }
1676 }
1677 }
1678
1679 func (he *headerEditor) Invalidate() {
1680 ui.Invalidate()
1681 }
1682
1683 func (he *headerEditor) Focus(focused bool) {
1684 he.focused = focused
1685 he.input.Focus(focused)
1686 }
1687
1688 func (he *headerEditor) Event(event vaxis.Event) bool {
1689 return he.input.Event(event)
1690 }
1691
1692 func (he *headerEditor) OnChange(fn func()) {
1693 he.input.OnChange(func(_ *ui.TextInput) {
1694 fn()
1695 })
1696 }
1697
1698 func (he *headerEditor) OnFocusLost(fn func()) {
1699 he.input.OnFocusLost(func(_ *ui.TextInput) {
1700 fn()
1701 })
1702 }
1703
1704 type reviewMessage struct {
1705 composer *Composer
1706 grid *ui.Grid
1707 }
1708
1709 var defaultAnnotations = map[string]string{
1710 ":send<enter>": "Send",
1711 ":edit<enter>": "Edit (body and headers)",
1712 ":attach<space>": "Add attachment",
1713 ":detach<space>": "Remove attachment",
1714 ":postpone<enter>": "Postpone",
1715 ":preview<enter>": "Preview message",
1716 ":abort<enter>": "Abort (discard message, no confirmation)",
1717 ":choose -o d discard abort -o p postpone postpone<enter>": "Abort or postpone",
1718 }
1719
1720 func newReviewMessage(composer *Composer, err error) *reviewMessage {
1721 bindings := config.Binds().ComposeReview.ForAccount(
1722 composer.acctConfig.Name,
1723 )
1724 bindings = bindings.ForFolder(composer.SelectedDirectory())
1725
1726 type reviewCmd struct {
1727 input string
1728 output string
1729 annotation string
1730 }
1731
1732 var reviewCmds []reviewCmd
1733
1734 for _, binding := range bindings.Bindings {
1735 if binding.Annotation == "-" {
1736 // explicitly hidden by user
1737 continue
1738 }
1739
1740 inputs := config.FormatKeyStrokes(binding.Input)
1741 outputs := config.FormatKeyStrokes(binding.Output)
1742 annotation := binding.Annotation
1743 if annotation == "" {
1744 for i := range reviewCmds {
1745 r := &reviewCmds[i]
1746 if r.output == outputs {
1747 // aliased action with a different binding
1748 r.input += ", " + inputs
1749 goto next
1750 }
1751 }
1752 annotation = defaultAnnotations[outputs]
1753 }
1754 reviewCmds = append(reviewCmds, reviewCmd{
1755 input: inputs,
1756 output: outputs,
1757 annotation: annotation,
1758 })
1759 next:
1760 }
1761
1762 longest := 0
1763 for _, rcmd := range reviewCmds {
1764 if len(rcmd.input) > longest {
1765 longest = len(rcmd.input)
1766 }
1767 }
1768
1769 const maxInputWidth = 6
1770 width := max(longest, maxInputWidth)
1771 widthstr := strconv.Itoa(width)
1772
1773 var actions []string
1774 for _, rcmd := range reviewCmds {
1775 actions = append(actions, fmt.Sprintf(" %-"+widthstr+"s %-40s %s",
1776 rcmd.input, rcmd.annotation, rcmd.output))
1777 }
1778
1779 spec := []ui.GridSpec{
1780 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)},
1781 }
1782 for i := 0; i < len(actions)-1; i++ {
1783 spec = append(spec, ui.GridSpec{Strategy: ui.SIZE_EXACT, Size: ui.Const(1)})
1784 }
1785 spec = append(spec, ui.GridSpec{Strategy: ui.SIZE_EXACT, Size: ui.Const(2)})
1786 spec = append(spec, ui.GridSpec{Strategy: ui.SIZE_EXACT, Size: ui.Const(1)})
1787 for i := 0; i < len(composer.attachments)-1; i++ {
1788 spec = append(spec, ui.GridSpec{Strategy: ui.SIZE_EXACT, Size: ui.Const(1)})
1789 }
1790 if len(composer.textParts) > 0 {
1791 spec = append(spec, ui.GridSpec{Strategy: ui.SIZE_EXACT, Size: ui.Const(1)})
1792 spec = append(spec, ui.GridSpec{Strategy: ui.SIZE_EXACT, Size: ui.Const(1)})
1793 for i := 0; i < len(composer.textParts); i++ {
1794 spec = append(spec, ui.GridSpec{Strategy: ui.SIZE_EXACT, Size: ui.Const(1)})
1795 }
1796 }
1797 // make the last element fill remaining space
1798 spec = append(spec, ui.GridSpec{Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)})
1799
1800 grid := ui.NewGrid()
1801 grid.Rows(spec)
1802 grid.Columns([]ui.GridSpec{
1803 {Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)},
1804 })
1805
1806 uiConfig := composer.acct.UiConfig()
1807
1808 if err != nil {
1809 grid.AddChild(ui.NewText(err.Error(), uiConfig.GetStyle(config.STYLE_ERROR)))
1810 grid.AddChild(ui.NewText("Press [q] to close this tab.",
1811 uiConfig.GetStyle(config.STYLE_DEFAULT))).At(1, 0)
1812 } else {
1813 grid.AddChild(ui.NewText("Send this email?",
1814 uiConfig.GetStyle(config.STYLE_TITLE))).At(0, 0)
1815 i := 1
1816 for _, action := range actions {
1817 grid.AddChild(ui.NewText(action,
1818 uiConfig.GetStyle(config.STYLE_DEFAULT))).At(i, 0)
1819 i += 1
1820 }
1821 grid.AddChild(ui.NewText("Attachments:",
1822 uiConfig.GetStyle(config.STYLE_TITLE))).At(i, 0)
1823 i += 1
1824 if len(composer.attachments) == 0 {
1825 grid.AddChild(ui.NewText("(none)",
1826 uiConfig.GetStyle(config.STYLE_DEFAULT))).At(i, 0)
1827 i += 1
1828 } else {
1829 for _, a := range composer.attachments {
1830 grid.AddChild(ui.NewText(a.Name(), uiConfig.GetStyle(config.STYLE_DEFAULT))).
1831 At(i, 0)
1832 i += 1
1833 }
1834 }
1835 if len(composer.textParts) > 0 {
1836 grid.AddChild(ui.NewText("Parts:",
1837 uiConfig.GetStyle(config.STYLE_TITLE))).At(i, 0)
1838 i += 1
1839 grid.AddChild(ui.NewText("text/plain", uiConfig.GetStyle(config.STYLE_DEFAULT))).At(i, 0)
1840 i += 1
1841 for _, p := range composer.textParts {
1842 err := composer.updateMultipart(p)
1843 if err != nil {
1844 msg := fmt.Sprintf("%s error: %s", p.MimeType, err)
1845 grid.AddChild(ui.NewText(msg,
1846 uiConfig.GetStyle(config.STYLE_ERROR))).At(i, 0)
1847 } else {
1848 grid.AddChild(ui.NewText(p.MimeType,
1849 uiConfig.GetStyle(config.STYLE_DEFAULT))).At(i, 0)
1850 }
1851 i += 1
1852 }
1853
1854 }
1855 }
1856
1857 return &reviewMessage{
1858 composer: composer,
1859 grid: grid,
1860 }
1861 }
1862
1863 func (c *Composer) updateMultipart(p *lib.Part) error {
1864 // conversion errors handling
1865 p.ConversionError = nil
1866 setError := func(e error) error {
1867 p.ConversionError = e
1868 return e
1869 }
1870 if !p.Converted {
1871 // text/* multipart created without a command (e.g. by :accept)
1872 return nil
1873 }
1874 command, found := config.Converters()[p.MimeType]
1875 if !found {
1876 // unreachable
1877 return setError(fmt.Errorf("no command defined for mime/type"))
1878 }
1879 // reset part body to avoid it leaving outdated if the command fails
1880 p.Data = nil
1881 body, err := c.GetBody()
1882 if err != nil {
1883 return setError(errors.Wrap(err, "GetBody"))
1884 }
1885 cmd := exec.Command("sh", "-c", command)
1886 cmd.Stdin = body
1887 out, err := cmd.Output()
1888 if err != nil {
1889 var stderr string
1890 var ee *exec.ExitError
1891 if errors.As(err, &ee) {
1892 // append the first 30 chars of stderr if any
1893 stderr = strings.Trim(string(ee.Stderr), " \t\n\r")
1894 stderr = strings.ReplaceAll(stderr, "\n", "; ")
1895 if stderr != "" {
1896 stderr = fmt.Sprintf(": %.30s", stderr)
1897 }
1898 }
1899 return setError(fmt.Errorf("%s: %w%s", command, err, stderr))
1900 }
1901 p.Data = out
1902 return nil
1903 }
1904
1905 func (rm *reviewMessage) Invalidate() {
1906 ui.Invalidate()
1907 }
1908
1909 func (rm *reviewMessage) Draw(ctx *ui.Context) {
1910 rm.grid.Draw(ctx)
1911 }
1912
1913 type cryptoStatus struct {
1914 title string
1915 status *ui.Text
1916 uiConfig *config.UIConfig
1917 signKey string
1918 setEncOneShot bool
1919 }
1920
1921 func newCryptoStatus(uiConfig *config.UIConfig) *cryptoStatus {
1922 defaultStyle := uiConfig.GetStyle(config.STYLE_DEFAULT)
1923 return &cryptoStatus{
1924 title: "Security",
1925 status: ui.NewText("", defaultStyle),
1926 uiConfig: uiConfig,
1927 signKey: "",
1928 setEncOneShot: true,
1929 }
1930 }
1931
1932 func (cs *cryptoStatus) Draw(ctx *ui.Context) {
1933 // Extra character to put a blank cell between the header and the input
1934 size := runewidth.StringWidth(cs.title+":") + 1
1935 defaultStyle := cs.uiConfig.GetStyle(config.STYLE_DEFAULT)
1936 titleStyle := cs.uiConfig.GetStyle(config.STYLE_HEADER)
1937 ctx.Fill(0, 0, size, ctx.Height(), ' ', defaultStyle)
1938 ctx.Printf(0, 0, titleStyle, "%s:", cs.title)
1939 cs.status.Draw(ctx.Subcontext(size, 0, ctx.Width()-size, 1))
1940 }
1941
1942 func (cs *cryptoStatus) Invalidate() {
1943 ui.Invalidate()
1944 }
1945
1946 func (c *Composer) checkEncryptionKeys(_ string) bool {
1947 rcpts, err := getRecipientsEmail(c)
1948 if err != nil {
1949 // checkEncryptionKeys gets registered as a callback and must
1950 // explicitly call c.SetEncrypt(false) when encryption is not possible
1951 c.SetEncrypt(false)
1952 st := fmt.Sprintf("Cannot encrypt: %v", err)
1953 aerc.statusline.PushError(st)
1954 return false
1955 }
1956 var mk []string
1957 for _, rcpt := range rcpts {
1958 key, err := CryptoProvider().GetKeyId(rcpt)
1959 if err != nil || key == "" {
1960 mk = append(mk, rcpt)
1961 }
1962 }
1963
1964 encrypt := true
1965 switch {
1966 case len(mk) > 0:
1967 c.SetEncrypt(false)
1968 st := fmt.Sprintf("Cannot encrypt, missing keys: %s", strings.Join(mk, ", "))
1969 if c.Config().PgpOpportunisticEncrypt {
1970 switch c.Config().PgpErrorLevel {
1971 case config.PgpErrorLevelWarn:
1972 aerc.statusline.PushWarning(st)
1973 return false
1974 case config.PgpErrorLevelNone:
1975 return false
1976 case config.PgpErrorLevelError:
1977 // Continue to the default
1978 }
1979 }
1980 PushError(st)
1981 encrypt = false
1982 case len(rcpts) == 0:
1983 encrypt = false
1984 }
1985
1986 // If callbacks were registered, encrypt will be set when user removes
1987 // recipients with missing keys
1988 c.encrypt = encrypt
1989 err = c.updateCrypto()
1990 if err != nil {
1991 log.Warnf("failed update crypto: %v", err)
1992 }
1993 return true
1994 }
1995
1996 // setTitle executes the title template and sets the tab title
1997 func (c *Composer) setTitle() {
1998 if c.Tab == nil {
1999 return
2000 }
2001
2002 header := c.header.Copy()
2003 // Get subject direct from the textinput
2004 subject, ok := c.editors["subject"]
2005 if ok {
2006 header.SetSubject(subject.input.String())
2007 }
2008 if header.Get("subject") == "" {
2009 header.SetSubject("New Email")
2010 }
2011
2012 data := state.NewDataSetter()
2013 data.SetAccount(c.acctConfig)
2014 data.SetFolder(c.acct.Directories().SelectedDirectory())
2015 data.SetHeaders(&header, c.parent)
2016
2017 var buf bytes.Buffer
2018 uiConf := c.acct.UiConfig()
2019 err := templates.Render(uiConf.TabTitleComposer, &buf,
2020 data.Data())
2021 if err != nil {
2022 c.acct.PushError(err)
2023 return
2024 }
2025 c.Tab.SetTitle(buf.String())
2026 }