about summary refs log blame commit diff stats
path: root/widgets/msgviewer.go
blob: 93d3d89eb07791c286728339aea5153352c19159 (plain) (tree)
fa04a1epre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
# compare immutable-error.mu

def main [
  local-scope
  x:&:num <- new number:type
  foo x
]

def foo x:&:num -> x:&:num [
  local-scope
  load-ingredients
  *x <- copy 34
]
w DeVault <sir@cmpwn.com> 2020-01-05 16:02:39 -0500 msgviewer: do not anchor ansi escape to start of line' href='/akspecs/aerc/commit/widgets/msgviewer.go?h=0.5.2&id=7a1770f12924fca85869f0568d169ead2c5648f8'>7a1770f ^
0647ea6 ^
3e535f4 ^

fa04a1e ^
511fea3 ^
753adb9 ^
3376f92 ^

3376f92 ^
cce7cb4 ^
511fea3 ^





fb12413 ^



f6216bb ^


fa04a1e ^

753adb9 ^
cce7cb4 ^
67fb093 ^
b360cca ^









67fb093 ^



b2fa5a1 ^
67fb093 ^


fa04a1e ^
fa04a1e ^
dfc048f ^
fa04a1e ^




511fea3 ^
4bdef7d ^
b83e7c9 ^
dfc048f ^




3376f92 ^
3376f92 ^
dfc048f ^
7f43485 ^
3376f92 ^
f6216bb ^
753adb9 ^
b83e7c9 ^
511fea3 ^



3376f92 ^
f6216bb ^


dfc048f ^
3376f92 ^
ef4c2f6 ^
dfc048f ^









ef4c2f6 ^
dfc048f ^

b360cca ^

dfc048f ^

3376f92 ^


4bdef7d ^
c610c3c ^
4a5aa7d ^
511fea3 ^








4bdef7d ^
511fea3 ^





4bdef7d ^
511fea3 ^







4bdef7d ^
4a5aa7d ^
97bee66 ^
b83e7c9 ^
97bee66 ^
4a5aa7d ^
fb12413 ^
b83e7c9 ^
b83e7c9 ^
1d1fe7c ^
4bdef7d ^
b83e7c9 ^







4bdef7d ^
4a5aa7d ^
b83e7c9 ^


dd17826 ^
97bee66 ^
b83e7c9 ^



dd17826 ^
b83e7c9 ^

97bee66 ^
302bc1c ^









dd17826 ^
b83e7c9 ^





3376f92 ^








f6216bb ^






3376f92 ^









753adb9 ^







217e85a ^




753adb9 ^

3e535f4 ^




b83e7c9 ^

4a5aa7d ^
0647ea6 ^
4bdef7d ^
b83e7c9 ^
0647ea6 ^

b83e7c9 ^



363aab5 ^
28fc9fa ^










0897413 ^



























be4ea0d ^



511fea3 ^










4bdef7d ^
3376f92 ^

511fea3 ^

fb12413 ^
511fea3 ^

3376f92 ^
511fea3 ^
f6216bb ^
511fea3 ^



d224487 ^
511fea3 ^

d224487 ^

4f28926 ^


d224487 ^

511fea3 ^




f6216bb ^






809083f ^
f6216bb ^















































be4ea0d ^





511fea3 ^





3376f92 ^


511fea3 ^
b83e7c9 ^



cce7cb4 ^
b83e7c9 ^

c610c3c ^
b83e7c9 ^




4bdef7d ^

3376f92 ^

4bdef7d ^
cce7cb4 ^
4a5aa7d ^
b83e7c9 ^
3376f92 ^
bbdf9df ^




f9262e4 ^
bbdf9df ^


3376f92 ^
bbdf9df ^
3376f92 ^
bbdf9df ^


3376f92 ^

bbdf9df ^


36419d8 ^
bbdf9df ^
8e5ed2a ^





c610c3c ^
8e5ed2a ^
c610c3c ^
8e5ed2a ^
c610c3c ^
8e5ed2a ^

36419d8 ^
8e5ed2a ^



bbdf9df ^


3376f92 ^





511fea3 ^
3376f92 ^


bbdf9df ^
4bdef7d ^



















3376f92 ^
b83e7c9 ^





4a5aa7d ^
b83e7c9 ^


4bdef7d ^

27b2517 ^

511fea3 ^






0abafa6 ^

3376f92 ^

f9262e4 ^
3376f92 ^


fa04a1e ^

3376f92 ^
ad68a9e ^
3376f92 ^

3cf6c82 ^
3376f92 ^
3cf6c82 ^
bbdf9df ^
3376f92 ^
bbdf9df ^
3376f92 ^

bbdf9df ^
f9262e4 ^
3cf6c82 ^













310bec2 ^
3cf6c82 ^
bbdf9df ^

0abafa6 ^
b83e7c9 ^
cb16868 ^


b83e7c9 ^

126119c ^





0647ea6 ^
126119c ^
cb16868 ^
b83e7c9 ^
b360cca ^


cb16868 ^
b360cca ^
cb16868 ^
b83e7c9 ^

0647ea6 ^
9096049 ^
0647ea6 ^





9096049 ^
0647ea6 ^
3376f92 ^
0abafa6 ^



3376f92 ^
511fea3 ^
fa04a1e ^

3376f92 ^
511fea3 ^


33f2d4f ^
ef029aa ^


4bdef7d ^



511fea3 ^


9096049 ^
511fea3 ^

3376f92 ^



f9262e4 ^
3376f92 ^
fa04a1e ^

be4ea0d ^






4bdef7d ^






fa04a1e ^
5685a17 ^
fa04a1e ^




27b2517 ^



4bdc0f3 ^




337dd18 ^
4bdc0f3 ^

337dd18 ^
4bdc0f3 ^

337dd18 ^
4bdc0f3 ^
27b2517 ^

fa04a1e ^


5685a17 ^
fa04a1e ^
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693


               
               
                
             

                 
                
                 
 
                                         
                                  
                                 

                                       


                                         
                                         

 
                                                         
 

                                              
                           
                        
                             

                                   
                         
                                    





                                  



                                    


                             

 
                                                                 
                                                                          
 









                                                                         



                                                 
                                                                                               


                         
 
                                                
                                              




                                    
                                   
                                                               
                       




                                      
         
 
                                      
                                        
 
                             
                               
                               



                                   
         


                        
 
 
                                                                               









                                                                
                                                                

                                           

                                                     

                                                    


         
                                                                                        
                                                            
                                             








                                                         
                                                                       





                                                          
                                                                                







                                         
                                                                                       
                                                                 
 
                     
                              
                                                      
                                                            
 
                                              
                                     
                                                                                             







                                                     
                                                                       
                                                        


                                  
                                      
                                                                                        



                                                             
                                                              

                                                                                       
                         









                                                                               
                                 





                         








                                                                                  






                                                                                









                                                               







                                                         




                                                                         

 




                                                                          

                                          
                                                                
                              
                                                             
                       

                                                                          



                             
                                                          










                                                 



























                                                                                   



                                  










                                                       
                                                 

 

                                               
                                              

                                               
         
                                                                          
                                



                                                                     
                                            

                                                               

                                                                                


                                                                                          

                                                                     




                                                        






                                                                               
                                                                            















































                                                                                            





                                             





                                                        


                        
                        



                             
                                       

                                  
                                         




                                     

                             

 
                                                              
                                                         
                                   
                                           
 




                                      
                                 


                                                  
                               
         
 


                                                

                                                               


                                                             
                                                                            
                         





                                                             
                                                                                  
                                  
                                                                                
                                  
                                                                                

                                                          
                                                                            



                                  


                          





                                                               
                                                               


                                       
 



















                                                                                
                          





                                     
                                                     


                                   

                                      

         






                                                       

         

                      
 


                                                   

 
                                     
                                                                           

                                                           
                                                           
                                         
                                                    
                                   
                                                                     
                                               

                                                       
                                 
                                              













                                                                     
                                                
                                                  

                           
                           
                                                                          


                                                                                            

                                                                       





                                                                                                   
                                                             
                                                                                
                                                                       
                                 


                                                                                 
                                                                                                     
                                 
                                                              

                         
                                                       
                                                                      





                                                                              
                                                           
                         
                                       



                   
                                    
                           

 
                                             


                                                                                  
                                                                               


                                                                           



                                                                                             


                        
                                                                                                

                                 



                                                                                  
         
                         

 






                                                       






                                                     
                        
                        




                                             



                                                             




                                                    
                             

                                                                        
                

                                                      
         
                                                              

                                          


                                    
                           
 
package widgets

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os/exec"
	"regexp"
	"strings"

	"github.com/danwakefield/fnmatch"
	"github.com/gdamore/tcell"
	"github.com/google/shlex"
	"github.com/mattn/go-runewidth"

	"git.sr.ht/~sircmpwn/aerc/config"
	"git.sr.ht/~sircmpwn/aerc/lib"
	"git.sr.ht/~sircmpwn/aerc/lib/ui"
	"git.sr.ht/~sircmpwn/aerc/models"
)

var ansi = regexp.MustCompile("\x1B\\[[0-?]*[ -/]*[@-~]")

var _ ProvidesMessages = (*MessageViewer)(nil)

type MessageViewer struct {
	ui.Invalidatable
	acct     *AccountView
	conf     *config.AercConfig
	err      error
	grid     *ui.Grid
	msg      *models.MessageInfo
	switcher *PartSwitcher
	store    *lib.MessageStore
}

type PartSwitcher struct {
	ui.Invalidatable
	parts          []*PartViewer
	selected       int
	showHeaders    bool
	alwaysShowMime bool

	height int
	mv     *MessageViewer
}

func NewMessageViewer(acct *AccountView, conf *config.AercConfig,
	store *lib.MessageStore, msg *models.MessageInfo) *MessageViewer {

	hf := HeaderLayoutFilter{
		layout: HeaderLayout(conf.Viewer.HeaderLayout),
		keep: func(msg *models.MessageInfo, header string) bool {
			if fmtHeader(msg, header, "2") != "" {
				return true
			}
			return false
		},
	}
	layout := hf.forMessage(msg)
	header, headerHeight := layout.grid(
		func(header string) ui.Drawable {
			return &HeaderView{
				Name:  header,
				Value: fmtHeader(msg, header, acct.UiConfig().TimestampFormat),
			}
		},
	)

	grid := ui.NewGrid().Rows([]ui.GridSpec{
		{ui.SIZE_EXACT, headerHeight},
		{ui.SIZE_WEIGHT, 1},
	}).Columns([]ui.GridSpec{
		{ui.SIZE_WEIGHT, 1},
	})

	switcher := &PartSwitcher{}
	err := createSwitcher(acct, switcher, conf, store, msg)
	if err != nil {
		return &MessageViewer{
			err:  err,
			grid: grid,
			msg:  msg,
		}
	}

	grid.AddChild(header).At(0, 0)
	grid.AddChild(switcher).At(1, 0)

	mv := &MessageViewer{
		acct:     acct,
		conf:     conf,
		grid:     grid,
		msg:      msg,
		store:    store,
		switcher: switcher,
	}
	switcher.mv = mv

	return mv
}

func fmtHeader(msg *models.MessageInfo, header string, timefmt string) string {
	switch header {
	case "From":
		return models.FormatAddresses(msg.Envelope.From)
	case "To":
		return models.FormatAddresses(msg.Envelope.To)
	case "Cc":
		return models.FormatAddresses(msg.Envelope.Cc)
	case "Bcc":
		return models.FormatAddresses(msg.Envelope.Bcc)
	case "Date":
		return msg.Envelope.Date.Local().Format(timefmt)
	case "Subject":
		return msg.Envelope.Subject
	case "Labels":
		return strings.Join(msg.Labels, ", ")
	default:
		return msg.RFC822Headers.Get(header)
	}
}

func enumerateParts(acct *AccountView, conf *config.AercConfig, store *lib.MessageStore,
	msg *models.MessageInfo, body *models.BodyStructure,
	index []int) ([]*PartViewer, error) {

	var parts []*PartViewer
	for i, part := range body.Parts {
		curindex := append(index, i+1)
		if part.MIMEType == "multipart" {
			// Multipart meta-parts are faked
			pv := &PartViewer{part: part}
			parts = append(parts, pv)
			subParts, err := enumerateParts(
				acct, conf, store, msg, part, curindex)
			if err != nil {
				return nil, err
			}
			parts = append(parts, subParts...)
			continue
		}
		pv, err := NewPartViewer(acct, conf, store, msg, part, curindex)
		if err != nil {
			return nil, err
		}
		parts = append(parts, pv)
	}
	return parts, nil
}

func createSwitcher(acct *AccountView, switcher *PartSwitcher, conf *config.AercConfig,
	store *lib.MessageStore, msg *models.MessageInfo) error {

	var err error
	switcher.selected = -1
	switcher.showHeaders = conf.Viewer.ShowHeaders
	switcher.alwaysShowMime = conf.Viewer.AlwaysShowMime

	if len(msg.BodyStructure.Parts) == 0 {
		switcher.selected = 0
		pv, err := NewPartViewer(acct, conf, store, msg, msg.BodyStructure, []int{1})
		if err != nil {
			return err
		}
		switcher.parts = []*PartViewer{pv}
		pv.OnInvalidate(func(_ ui.Drawable) {
			switcher.Invalidate()
		})
	} else {
		switcher.parts, err = enumerateParts(acct, conf, store,
			msg, msg.BodyStructure, []int{})
		if err != nil {
			return err
		}
		selectedPriority := -1
		fmt.Printf("Selecting best message from %v\n", conf.Viewer.Alternatives)
		for i, pv := range switcher.parts {
			pv.OnInvalidate(func(_ ui.Drawable) {
				switcher.Invalidate()
			})
			// Switch to user's preferred mimetype
			if switcher.selected == -1 && pv.part.MIMEType != "multipart" {
				switcher.selected = i
			}
			mime := strings.ToLower(pv.part.MIMEType) +
				"/" + strings.ToLower(pv.part.MIMESubType)
			for idx, m := range conf.Viewer.Alternatives {
				if m != mime {
					continue
				}
				priority := len(conf.Viewer.Alternatives) - idx
				if priority > selectedPriority {
					selectedPriority = priority
					switcher.selected = i
				}
			}
		}
	}
	return nil
}

func (mv *MessageViewer) Draw(ctx *ui.Context) {
	if mv.err != nil {
		ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', tcell.StyleDefault)
		ctx.Printf(0, 0, tcell.StyleDefault, "%s", mv.err.Error())
		return
	}
	mv.grid.Draw(ctx)
}

func (mv *MessageViewer) MouseEvent(localX int, localY int, event tcell.Event) {
	if mv.err != nil {
		return
	}
	mv.grid.MouseEvent(localX, localY, event)
}

func (mv *MessageViewer) Invalidate() {
	mv.grid.Invalidate()
}

func (mv *MessageViewer) OnInvalidate(fn func(d ui.Drawable)) {
	mv.grid.OnInvalidate(func(_ ui.Drawable) {
		fn(mv)
	})
}

func (mv *MessageViewer) Store() *lib.MessageStore {
	return mv.store
}

func (mv *MessageViewer) SelectedAccount() *AccountView {
	return mv.acct
}

func (mv *MessageViewer) SelectedMessage() (*models.MessageInfo, error) {
	if mv.msg == nil {
		return nil, errors.New("no message selected")
	}
	return mv.msg, nil
}

func (mv *MessageViewer) MarkedMessages() ([]*models.MessageInfo, error) {
	store := mv.Store()
	return msgInfoFromUids(store, store.Marked())
}

func (mv *MessageViewer) ToggleHeaders() {
	switcher := mv.switcher
	mv.conf.Viewer.ShowHeaders = !mv.conf.Viewer.ShowHeaders
	err := createSwitcher(
		mv.acct, switcher, mv.conf, mv.store, mv.msg)
	if err != nil {
		mv.acct.Logger().Printf(
			"warning: error during create switcher - %v", err)
	}
	switcher.Invalidate()
}

func (mv *MessageViewer) SelectedMessagePart() *PartInfo {
	switcher := mv.switcher
	part := switcher.parts[switcher.selected]

	return &PartInfo{
		Index: part.index,
		Msg:   part.msg,
		Part:  part.part,
		Store: part.store,
	}
}

func (mv *MessageViewer) PreviousPart() {
	switcher := mv.switcher
	for {
		switcher.selected--
		if switcher.selected < 0 {
			switcher.selected = len(switcher.parts) - 1
		}
		if switcher.parts[switcher.selected].part.MIMEType != "multipart" {
			break
		}
	}
	mv.Invalidate()
}

func (mv *MessageViewer) NextPart() {
	switcher := mv.switcher
	for {
		switcher.selected++
		if switcher.selected >= len(switcher.parts) {
			switcher.selected = 0
		}
		if switcher.parts[switcher.selected].part.MIMEType != "multipart" {
			break
		}
	}
	mv.Invalidate()
}

func (mv *MessageViewer) Close() {
	mv.switcher.Cleanup()
}

func (ps *PartSwitcher) Invalidate() {
	ps.DoInvalidate(ps)
}

func (ps *PartSwitcher) Focus(focus bool) {
	if ps.parts[ps.selected].term != nil {
		ps.parts[ps.selected].term.Focus(focus)
	}
}

func (ps *PartSwitcher) Event(event tcell.Event) bool {
	return ps.parts[ps.selected].Event(event)
}

func (ps *PartSwitcher) Draw(ctx *ui.Context) {
	height := len(ps.parts)
	if height == 1 && !ps.alwaysShowMime {
		ps.parts[ps.selected].Draw(ctx)
		return
	}
	// TODO: cap height and add scrolling for messages with many parts
	ps.height = ctx.Height()
	y := ctx.Height() - height
	for i, part := range ps.parts {
		style := tcell.StyleDefault.Reverse(ps.selected == i)
		ctx.Fill(0, y+i, ctx.Width(), 1, ' ', style)
		name := fmt.Sprintf("%s/%s",
			strings.ToLower(part.part.MIMEType),
			strings.ToLower(part.part.MIMESubType))
		if filename, ok := part.part.DispositionParams["filename"]; ok {
			name += fmt.Sprintf(" (%s)", filename)
		} else if filename, ok := part.part.Params["name"]; ok {
			// workaround golang not supporting RFC2231 besides ASCII and UTF8
			name += fmt.Sprintf(" (%s)", filename)
		}
		ctx.Printf(len(part.index)*2, y+i, style, "%s", name)
	}
	ps.parts[ps.selected].Draw(ctx.Subcontext(
		0, 0, ctx.Width(), ctx.Height()-height))
}

func (ps *PartSwitcher) MouseEvent(localX int, localY int, event tcell.Event) {
	switch event := event.(type) {
	case *tcell.EventMouse:
		switch event.Buttons() {
		case tcell.Button1:
			height := len(ps.parts)
			y := ps.height - height
			if localY < y && ps.parts[ps.selected].term != nil {
				ps.parts[ps.selected].term.MouseEvent(localX, localY, event)
			}
			for i, _ := range ps.parts {
				if localY != y+i {
					continue
				}
				if ps.parts[i].part.MIMEType == "multipart" {
					continue
				}
				if ps.parts[ps.selected].term != nil {
					ps.parts[ps.selected].term.Focus(false)
				}
				ps.selected = i
				ps.Invalidate()
				if ps.parts[ps.selected].term != nil {
					ps.parts[ps.selected].term.Focus(true)
				}
			}
		case tcell.WheelDown:
			height := len(ps.parts)
			y := ps.height - height
			if localY < y {
				ps.parts[ps.selected].term.MouseEvent(localX, localY, event)
			}
			if ps.parts[ps.selected].term != nil {
				ps.parts[ps.selected].term.Focus(false)
			}
			ps.mv.NextPart()
			if ps.parts[ps.selected].term != nil {
				ps.parts[ps.selected].term.Focus(true)
			}
		case tcell.WheelUp:
			height := len(ps.parts)
			y := ps.height - height
			if localY < y {
				ps.parts[ps.selected].term.MouseEvent(localX, localY, event)
			}
			if ps.parts[ps.selected].term != nil {
				ps.parts[ps.selected].term.Focus(false)
			}
			ps.mv.PreviousPart()
			if ps.parts[ps.selected].term != nil {
				ps.parts[ps.selected].term.Focus(true)
			}
		}
	}
}

func (ps *PartSwitcher) Cleanup() {
	for _, partViewer := range ps.parts {
		partViewer.Cleanup()
	}
}

func (mv *MessageViewer) Event(event tcell.Event) bool {
	return mv.switcher.Event(event)
}

func (mv *MessageViewer) Focus(focus bool) {
	mv.switcher.Focus(focus)
}

type PartViewer struct {
	ui.Invalidatable
	err         error
	fetched     bool
	filter      *exec.Cmd
	index       []int
	msg         *models.MessageInfo
	pager       *exec.Cmd
	pagerin     io.WriteCloser
	part        *models.BodyStructure
	showHeaders bool
	sink        io.WriteCloser
	source      io.Reader
	store       *lib.MessageStore
	term        *Terminal
	selecter    *Selecter
	grid        *ui.Grid
}

func NewPartViewer(acct *AccountView, conf *config.AercConfig,
	store *lib.MessageStore, msg *models.MessageInfo,
	part *models.BodyStructure,
	index []int) (*PartViewer, error) {

	var (
		filter  *exec.Cmd
		pager   *exec.Cmd
		pipe    io.WriteCloser
		pagerin io.WriteCloser
		term    *Terminal
	)
	cmd, err := shlex.Split(conf.Viewer.Pager)
	if err != nil {
		return nil, err
	}

	pager = exec.Command(cmd[0], cmd[1:]...)

	for _, f := range conf.Filters {
		mime := strings.ToLower(part.MIMEType) +
			"/" + strings.ToLower(part.MIMESubType)
		switch f.FilterType {
		case config.FILTER_MIMETYPE:
			if fnmatch.Match(f.Filter, mime, 0) {
				filter = exec.Command("sh", "-c", f.Command)
			}
		case config.FILTER_HEADER:
			var header string
			switch f.Header {
			case "subject":
				header = msg.Envelope.Subject
			case "from":
				header = models.FormatAddresses(msg.Envelope.From)
			case "to":
				header = models.FormatAddresses(msg.Envelope.To)
			case "cc":
				header = models.FormatAddresses(msg.Envelope.Cc)
			}
			if f.Regex.Match([]byte(header)) {
				filter = exec.Command("sh", "-c", f.Command)
			}
		}
		if filter != nil {
			break
		}
	}
	if filter != nil {
		if pipe, err = filter.StdinPipe(); err != nil {
			return nil, err
		}
		if pagerin, _ = pager.StdinPipe(); err != nil {
			return nil, err
		}
		if term, err = NewTerminal(pager); err != nil {
			return nil, err
		}
	}

	grid := ui.NewGrid().Rows([]ui.GridSpec{
		{ui.SIZE_EXACT, 3}, // Message
		{ui.SIZE_EXACT, 1}, // Selector
		{ui.SIZE_WEIGHT, 1},
	}).Columns([]ui.GridSpec{
		{ui.SIZE_WEIGHT, 1},
	})

	selecter := NewSelecter([]string{"Save message", "Pipe to command"}, 0).
		OnChoose(func(option string) {
			switch option {
			case "Save message":
				acct.aerc.BeginExCommand("save ")
			case "Pipe to command":
				acct.aerc.BeginExCommand("pipe ")
			}
		})

	grid.AddChild(selecter).At(2, 0)

	pv := &PartViewer{
		filter:      filter,
		index:       index,
		msg:         msg,
		pager:       pager,
		pagerin:     pagerin,
		part:        part,
		showHeaders: conf.Viewer.ShowHeaders,
		sink:        pipe,
		store:       store,
		term:        term,
		selecter:    selecter,
		grid:        grid,
	}

	if term != nil {
		term.OnStart = func() {
			pv.attemptCopy()
		}
		term.OnInvalidate(func(_ ui.Drawable) {
			pv.Invalidate()
		})
	}

	return pv, nil
}

func (pv *PartViewer) SetSource(reader io.Reader) {
	pv.source = reader
	pv.attemptCopy()
}

func (pv *PartViewer) attemptCopy() {
	if pv.source != nil && pv.pager != nil && pv.pager.Process != nil {
		if pv.filter != nil {
			stdout, _ := pv.filter.StdoutPipe()
			stderr, _ := pv.filter.StderrPipe()
			pv.filter.Start()
			ch := make(chan interface{})
			go func() {
				_, err := io.Copy(pv.pagerin, stdout)
				if err != nil {
					pv.err = err
					pv.Invalidate()
				}
				stdout.Close()
				ch <- nil
			}()
			go func() {
				_, err := io.Copy(pv.pagerin, stderr)
				if err != nil {
					pv.err = err
					pv.Invalidate()
				}
				stderr.Close()
				ch <- nil
			}()
			go func() {
				<-ch
				<-ch
				pv.filter.Wait()
				pv.pagerin.Close()
			}()
		}
		go func() {
			if pv.showHeaders && pv.msg.RFC822Headers != nil {
				// header need to bypass the filter, else we run into issues
				// with the filter messing with newlines etc.
				// hence all writes in this block go directly to the pager
				fields := pv.msg.RFC822Headers.Fields()
				for fields.Next() {
					var value string
					var err error
					if value, err = fields.Text(); err != nil {
						// better than nothing, use the non decoded version
						value = fields.Value()
					}
					field := fmt.Sprintf(
						"%s: %s\n", fields.Key(), value)
					pv.pagerin.Write([]byte(field))
				}
				// virtual header
				if len(pv.msg.Labels) != 0 {
					labels := fmtHeader(pv.msg, "Labels", "")
					pv.pagerin.Write([]byte(fmt.Sprintf("Labels: %s\n", labels)))
				}
				pv.pagerin.Write([]byte{'\n'})
			}

			if pv.part.MIMEType == "text" {
				scanner := bufio.NewScanner(pv.source)
				for scanner.Scan() {
					text := scanner.Text()
					text = ansi.ReplaceAllString(text, "")
					io.WriteString(pv.sink, text+"\n")
				}
			} else {
				io.Copy(pv.sink, pv.source)
			}
			pv.sink.Close()
		}()
	}
}

func (pv *PartViewer) Invalidate() {
	pv.DoInvalidate(pv)
}

func (pv *PartViewer) Draw(ctx *ui.Context) {
	if pv.filter == nil {
		// TODO: Let them download it directly or something
		ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', tcell.StyleDefault)
		ctx.Printf(0, 0, tcell.StyleDefault.Foreground(tcell.ColorRed),
			"No filter configured for this mimetype ('%s/%s')",
			pv.part.MIMEType, pv.part.MIMESubType,
		)
		ctx.Printf(0, 2, tcell.StyleDefault,
			"You can still :save the message or :pipe it to an external command")
		pv.selecter.Focus(true)
		pv.grid.Draw(ctx)
		return
	}
	if !pv.fetched {
		pv.store.FetchBodyPart(pv.msg.Uid, pv.msg.BodyStructure, pv.index, pv.SetSource)
		pv.fetched = true
	}
	if pv.err != nil {
		ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', tcell.StyleDefault)
		ctx.Printf(0, 0, tcell.StyleDefault, "%s", pv.err.Error())
		return
	}
	pv.term.Draw(ctx)
}

func (pv *PartViewer) Cleanup() {
	if pv.pager != nil && pv.pager.Process != nil {
		pv.pager.Process.Kill()
		pv.pager = nil
	}
}

func (pv *PartViewer) Event(event tcell.Event) bool {
	if pv.term != nil {
		return pv.term.Event(event)
	}
	return pv.selecter.Event(event)
}

type HeaderView struct {
	ui.Invalidatable
	Name  string
	Value string
}

func (hv *HeaderView) Draw(ctx *ui.Context) {
	name := hv.Name
	size := runewidth.StringWidth(name)
	lim := ctx.Width() - size - 1
	value := runewidth.Truncate(" "+hv.Value, lim, "…")
	var (
		hstyle tcell.Style
		vstyle tcell.Style
	)
	// TODO: Make this more robust and less dumb
	if hv.Name == "PGP" {
		vstyle = tcell.StyleDefault.Foreground(tcell.ColorGreen)
		hstyle = tcell.StyleDefault.Bold(true)
	} else {
		vstyle = tcell.StyleDefault
		hstyle = tcell.StyleDefault.Bold(true)
	}
	ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', vstyle)
	ctx.Printf(0, 0, hstyle, name)
	ctx.Printf(size, 0, vstyle, value)
}

func (hv *HeaderView) Invalidate() {
	hv.DoInvalidate(hv)
}