summary refs log tree commit diff stats
path: root/doc/uml/generation_settings
blob: 8cd2bc141a303b8916c5da77ed67b1f803fe0d95 (plain) (blame)
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
  python_default_defs 
  cpp_h_extension "h" cpp_src_extension "cpp" java_extension "java" php_extension "php" python_extension "py" idl_extension "idl"
  cpp_inline_dont_force_incl_in_h

  type_forms 15 // uml cpp java idl cpp_in cpp_out cpp_inout cpp_return
    "void" "void" "void" "void" "${type}" "${type} &" "${type}" "${type}"
    "any" "void *" "Object" "any" "const ${type}" "${type}" "${type} &" "${type}"
    "bool" "bool" "boolean" "boolean" "${type}" "${type} &" "${type} &" "${type}"
    "char" "char" "char" "char" "${type}" "${type} &" "${type} &" "${type}"
    "uchar" "unsigned char" "char" "octet" "${type}" "${type} &" "${type} &" "${type}"
    "byte" "unsigned char" "byte" "octet" "${type}" "${type} &" "${type} &" "${type}"
    "short" "short" "short" "short" "${type}" "${type} &" "${type} &" "${type}"
    "ushort" "unsigned short" "short" "unsigned short" "${type}" "${type} &" "${type} &" "${type}"
    "int" "int" "int" "long" "${type}" "${type} &" "${type} &" "${type}"
    "uint" "unsigned int" "int" "unsigned long" "${type}" "${type} &" "${type} &" "${type}"
    "long" "long" "long" "long" "${type}" "${type} &" "${type} &" "${type}"
    "ulong" "unsigned long" "long" "unsigned long" "${type}" "${type} &" "${type} &" "${type}"
    "float" "float" "float" "float" "${type}" "${type} &" "${type} &" "${type}"
    "double" "double" "double" "double" "${type}" "${type} &" "${type} &" "${type}"
    "string" "string" "String" "string" "${type}" "${type} &" "${type} &" "${type}"
  
  relations_stereotypes 5 // uml cpp java pythonidl
    "sequence" "vector" "Vector" "list" "sequence"
    "vector" "vector" "Vector" "list" "sequence"
    "list" "list" "List" "list" "sequence"
    "set" "set" "Set" "set" "sequence"
    "map" "map" "Map" "dict" "sequence"
  
  classes_stereotypes 14 // uml cpp java php python idl
    "class" "class" "class" "class" "class" "valuetype"
    "interface" "class" "interface" "interface" "class" "interface"
    "exception" "class" "class" "class" "class" "exception"
    "enum" "enum" "enum" "enum" "enum" "enum"
    "enum_pattern" "enum" "enum_pattern" "enum" "enum" "enum"
    "struct" "struct" "class" "class" "class" "struct"
    "union" "union" "class" "class" "class" "union"
    "typedef" "typedef" "ignored" "ignored" "ignored" "typedef"
    "boundary" "class" "class" "class" "class" "interface"
    "control" "class" "class" "class" "class" "valuetype"
    "entity" "class" "class" "class" "class" "valuetype"
    "actor" "ignored" "ignored" "ignored" "ignored" "ignored"
    "@interface" "ignored" "@interface" "ignored" "ignored" "ignored"
    "stereotype" "ignored" "ignored" "ignored" "ignored" "ignored"
  
  cpp_enum_default_type_forms "${type}" "${type} &" "${type} &" "${type}" // in out inout return
  other_cpp_types_default_type_forms "const ${type} &" "${type} &" "${type} &" "${type}" // in out inout return

  cpp_default_h_content "#ifndef ${NAMESPACE}_${NAME}_H
#define ${NAMESPACE}_${NAME}_H

${comment}
${includes}
${declarations}
${namespace_start}
${definition}
${namespace_end}
#endif
"
  cpp_default_src_content "${comment}
${includes}
${namespace_start}
${members}
${namespace_end}"
  cpp_default_class_decl "${comment}${template}class ${name}${inherit} {
${members}};
${inlines}
"
  cpp_default_external_class_decl "${name}
#include <${name}.h>
"
  cpp_default_struct_decl "${comment}${template}struct ${name}${inherit} {
${members}};
${inlines}
"
  cpp_default_union_decl "${comment}${template}union ${name} {
${members}};
${inlines}
"
  cpp_default_enum_decl "${comment}enum ${name} {
${items}
};
"
  cpp_default_typedef_decl "${comment}typedef ${type} ${name};
"
  cpp_default_attribute_declaration "    ${comment}${static}${mutable}${volatile}${const}${type} ${name}${value};
" // multiplicity 1
  "    ${comment}${static}${mutable}${volatile}${const}${stereotype}<${type}> ${name}${value};
" // multiplicity * a..b
  "    ${comment}${static}${mutable}${volatile}${const}${type} ${name}${multiplicity}${value};
" // multiplicity [..]
  cpp_default_enum_item_declaration "  ${name}${value},${comment}"
  cpp_association_aggregation_declaration
    "    ${comment}${static}${mutable}${volatile}${const}${type} * ${name}${value};
" // multiplicity 1
    "    ${comment}${static}${mutable}${volatile}${const}${stereotype}<${type} *> ${name}${value};
" // multiplicity * a..b
    "    ${comment}${static}${mutable}${volatile}${const}${type} * ${name}${multiplicity}${value};
" // multiplicity [..]
  cpp_aggregation_by_value_declaration
    "    ${comment}${static}${mutable}${volatile}${const}${type} ${name}${value};
" // multiplicity 1
    "    ${comment}${static}${mutable}${volatile}${const}${stereotype}<${type}> ${name}${value};
" // multiplicity * a..b
    "    ${comment}${static}${mutable}${volatile}${const}${type} ${name}${multiplicity}${value};
" // multiplicity [..]
  cpp_get "get_${name}" inline const value_const public
  cpp_set "set_${name}" public
  cpp_default_operation_declaration "    ${comment}${friend}${static}${inline}${virtual}${type} ${name}${(}${)}${const}${volatile}${throw}${abstract};
"
  cpp_default_operation_definition "${comment}${inline}${type} ${class}::${name}${(}${)}${const}${volatile}${throw}${staticnl}{
  ${body}}
"
  java_default_src_content "${comment}
${package}
${imports}
${definition}"
  java_default_class_decl "${comment}${@}${visibility}${final}${abstract}class ${name}${extends}${implements} {
${members}}
"
  java_default_external_class_decl "${name}"
  java_default_interface_decl "${comment}${@}${visibility}interface ${name}${extends} {
${members}}
"
  java5_default_enum_decl "${comment}${@}${visibility}${final}${abstract}enum ${name}${implements} {
${items};
${members}}
"
  java_default_enum_decl "${comment}${@}${visibility}final class ${name} {
${members}
  private final int value;

  public int value() {
    return value;
  }

  public static ${name} fromInt(int value) {
    switch (value) {
${cases}    default: throw new Error();
    }

  }
  private ${name}(int v) { value = v; };
}
"
  java_default_attribute_declaration "  ${comment}${@}${visibility}${static}${final}${transient}${volatile}${type} ${name}${value};
" // multiplicity 1
  "  ${comment}${@}${visibility}${static}${final}${transient}${volatile}${stereotype}<${type}> ${name}${value};
" // multiplicity * a..b
  "  ${comment}${@}${visibility}${static}${final}${transient}${volatile}${type}${multiplicity} ${name}${value};
" // multiplicity N
  java5_default_enum_item_declaration "  ${@}${name}${value},${comment}"
  java_default_enum_item_declaration "  ${comment}${@}public static final int _${name}${value};
public static final ${class} ${name} = new ${class}(_${name});
"
  java_default_enum_case "    case _${name}: return ${name};
"
  java_association_aggregation_declaration
    "  ${comment}${@}${visibility}${static}${final}${transient}${volatile}${type} ${name}${value};
" // multiplicity 1
    "  ${comment}${@}${visibility}${static}${final}${transient}${volatile}${stereotype}<${type}> ${name}${value};
" // multiplicity * a..b
    "  ${comment}${@}${visibility}${static}${final}${transient}${volatile}${type}${multiplicity} ${name}${value};
" // multiplicity N
  java_get "get${Name}" final public
  java_set "set${Name}" public
  java_default_operation_definition "  ${comment}${@}${visibility}${final}${static}${abstract}${synchronized}${type} ${name}${(}${)}${throws}${staticnl}{
  ${body}}
"
  php_default_src_content "<?php
${comment}
${definition}
?>
"
  php_default_class_decl "${comment}${final}${visibility}${abstract}class ${name}${extends}${implements} {
${members}}
"
  php_default_enum_decl "${comment}${visibility}final class ${name} {
${items}}
"
  php_default_external_class_decl "${name}"
  php_default_interface_decl "${comment}${visibility}interface ${name} {
${members}}
"
  php_default_attribute_declaration "  ${comment}${visibility}${const}${static}${var}${name}${value};
"
  php_default_enum_item_decl "  const ${name}${value};${comment}
"
  php_default_relation_declaration"  ${comment}${visibility}${const}${static}${var}${name}${value};
"
  php_get "get${Name}" final
  php_set "set${Name}"
  php_default_operation_definition "  ${comment}${final}${visibility}${abstract}${static}function ${name}${(}${)}
{
  ${body}}
"
  python_2_2
  python_indent_step "    "
  python_default_src_content "${comment}
${import}
${definition}"
  python_default_class_decl "class ${name}${inherit}:
${docstring}${members}
"
  python_default_enum_decl "class ${name}:
${docstring}${members}
"
  python_default_external_class_decl "${name}"
  python_default_attribute_declaration "${comment}${self}${name} = ${value}
" // multiplicity 1
  "${comment}${self}${name} = ${stereotype}()
" // multiplicity != 1
  python_default_enum_item_decl "${comment}${self}${name} = ${value}
"
  python_default_relation_declaration"${comment}${self}${name} = ${value}
" // multiplicity 1
  "${comment}${self}${name} = ${stereotype}()
" // multiplicity != 1
  python_default_composition_declaration"${comment}${self}${name} = ${type}()
" // multiplicity 1
  "${comment}${self}${name} = ${stereotype}()
" // multiplicity != 1
  python_default_operation_definition "${@}${static}${abstract}def ${name}${(}${)}:
${docstring}${body}
"
  python_default_initoperation_definition "${@}${static}${abstract}def ${name}${(}${p0}${v0}${)}:
${docstring}super(${class}, ${p0}).__init__()
${body}
"
  python_get "get${Name}"
  python_set "set${Name}"
  idl_default_src_content "#ifndef ${MODULE}_${NAME}_H
#define ${MODULE}_${NAME}_H

${comment}
${includes}
${module_start}
${definition}
${module_end}
#endif
"
  idl_default_interface_decl "${comment}${abstract}${local}interface ${name}${inherit} {
${members}};
"
  idl_default_valuetype_decl "${comment}${abstract}${custom}valuetype ${name}${inherit} {
${members}};
"
  idl_default_struct_decl "${comment}struct ${name} {
${members}};
"
  idl_default_typedef_decl "${comment}typedef ${type} ${name};
"
  idl_default_exception_decl "${comment}exception ${name} {
${members}};
"
  idl_default_union_decl "${comment}union ${name} switch(${switch}) {
${members}};
"
  idl_default_enum_decl "${comment}enum ${name} {
${items}};
"
  idl_default_external_class_decl "${name}
#include \"${name}.idl\"
"
  idl_default_attribute_declaration "  ${comment}${readonly}${attribute}${type} ${name};
" // multiplicity 1
  "  ${comment}${readonly}${attribute}${stereotype}<${type}> ${name};
" // multiplicity * a..b
  "  ${comment}${readonly}${attribute}${stereotype}<${type},${multiplicity}> ${name};
" // multiplicity N
  idl_default_valuetype_attribute_declaration "  ${comment}${visibility}${type} ${name};
" // multiplicity 1
  "  ${comment}${visibility}${stereotype}<${type}> ${name};
" // multiplicity * a..b
  "  ${comment}${visibility}${stereotype}<${type},${multiplicity}> ${name};
" // multiplicity N
  idl_default_const_declaration "  ${comment}const ${type} ${name}${value};
" // multiplicity 1
  "  ${comment}const ${stereotype}<${type}> ${name}${value};
" // multiplicity * a..b
  "  ${comment}const ${stereotype}<${type},${multiplicity}> ${name}${value};
" // multiplicity N
  idl_default_enum_item_declaration "  ${name},${comment}"
  idl_default_union_item_declaration "  ${comment}case ${case} : ${readonly}${type} ${name};" // multiplicity 1
  "  ${comment}case ${case} : ${readonly}${stereotype}<${type}> ${name};" // multiplicity * a..b
  "  ${comment}case ${case} : ${readonly}${stereotype}<${type},${multiplicity}> ${name};" // multiplicity N
  idl_association_aggregation_declaration
    "  ${comment}${readonly}${attribute}${type} ${name};
" // multiplicity 1
    "  ${comment}${readonly}${attribute}${stereotype}<${type}> ${name};
" // multiplicity * a..b
    "  ${comment}${readonly}${attribute}${stereotype}<${type},${multiplicity}> ${name};
" // multiplicity N
  idl_valuetype_association_aggregation_declaration
    "  ${comment}${visibility}${type} ${name};
" // multiplicity 1
    "  ${comment}${visibility}${stereotype}<${type}> ${name};
" // multiplicity * a..b
    "  ${comment}${visibility}${stereotype}<${type},${multiplicity}> ${name};
" // multiplicity N
  idl_union_association_aggregation_declaration
    "  ${comment}case ${case} : ${readonly}${type} ${name};" // multiplicity 1
    "  ${comment}case ${case} : ${readonly}${stereotype}<${type}> ${name};" // multiplicity * a..b
    "  ${comment}case ${case} : ${readonly}${stereotype}<${type},${multiplicity}> ${name};" // multiplicity N
  idl_get "get_${name}"
  idl_set "set_${name}"  twoways
  idl_default_operation_declaration "  ${comment}${oneway}${type} ${name}${(}${)}${raisesnl}${raises};
"
  uml_get_name uml uml_set_name uml
end
.4.0&id=2b3e123cb86f9b4c5853e31d9e76c2b0d083f90a'>^
67fb093 ^
475b697 ^



7a489cb ^






67fb093 ^






2c486cb ^

577248f ^













29de329 ^












f77d7c2 ^









577248f ^
8534720 ^



577248f ^


2a4dd5c ^
577248f ^

6c36e04 ^
887ff65 ^
6c36e04 ^

b0bf09b ^



2b3e123 ^
6c36e04 ^
67fb093 ^


6c36e04 ^


6c36e04 ^



6c36e04 ^


6c36e04 ^

6c36e04 ^
8d9d94f ^
67fb093 ^



6c36e04 ^
67fb093 ^




6c36e04 ^
67fb093 ^









































92dc31b ^
6c36e04 ^
67fb093 ^
ceeb30a ^






67fb093 ^
29de329 ^



67fb093 ^

59df06f ^
29de329 ^






cef784b ^
29de329 ^






7899d15 ^


bb620e0 ^
7899d15 ^




6c36e04 ^
7899d15 ^
6c36e04 ^
29de329 ^
7899d15 ^
bb620e0 ^



























7899d15 ^













bb620e0 ^
cef784b ^


6c36e04 ^

7899d15 ^














c9a909f ^
7899d15 ^






























0ee7d30 ^



7899d15 ^

0ee7d30 ^















7899d15 ^






bb46b2b ^
bb46b2b ^
887ff65 ^

bb46b2b ^
29de329 ^
887ff65 ^



















a974027 ^
887ff65 ^



bb46b2b ^

f37508a ^














f4b7741 ^
0ceea02 ^
f4b7741 ^
0ceea02 ^



f4b7741 ^




































67fb093 ^










bb46b2b ^




577248f ^
577248f ^














2a4dd5c ^














577248f ^
bb46b2b ^
2c486cb ^





bb46b2b ^




887ff65 ^
7899d15 ^
a669233 ^
7899d15 ^





bb46b2b ^

7899d15 ^
887ff65 ^






d851890 ^
887ff65 ^

7899d15 ^






887ff65 ^
bb46b2b ^



















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


               
               
            
                   

                  
                         
            
                 
                       
                 
              
 

                                             

                                       
                               
 
                                         

                                               

 
                      
                                        
 

                                    
 




                                     
                            

                                  
 
                              



                                          
                                         








                                                                                                 

                                                         
 





                                                               
                       




                                   
                                 
                                 
                                                                                        
                             
                                     
         
 
                      
                        

                

 




                                                                          














                                                                                             
         










                                                                              
         






                                                   
         
                                         

 




                                                                             
                      



                                    
                                              


                            
                                           
                                  



                                          






                                             






                                                                           

 













                                                         












                                      









                                                      
                                                  



                                                          


                                      
                                           

 
                                                   
                     

 



                                           
                                                                    
                                                     


                                               


                                  



                                                 


                                            

                         
                                                 
                                                            



                                                       
         




                                                                                    
         









































                                                                                                       
                 
         
 






                                                    
 



                                                                              

                                               
         






                                                                                   
                                                                  






                                            


                                                                      
                                                            




                                                         
                       
                                                       
         
                       
 



























                                                                                   













                                                                              
                                                    


                                                  

 














                                                                      
                                        






























                                                                            



                                              

                                                   















                                                                                         






                                                   
                                          
                                    

                                           
                          
                      



















                                                      
                                                                              



                                                               

 














                                                      
                                                               
                                                                              
                                           



                                                                        




































                                                                                 










                                                      




                           
                                                               














                                                                   














                                                            
 
 





                                                 




                           
                                                                     
                                                                     
                                                          





                                                                  

                                    
 






                                                                                  
                                                                                

                                                         






                                                                       
         



















                                                             
package widgets

import (
	"bufio"
	"io"
	"io/ioutil"
	"mime"
	"net/http"
	gomail "net/mail"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"github.com/emersion/go-message"
	"github.com/emersion/go-message/mail"
	"github.com/gdamore/tcell"
	"github.com/mattn/go-runewidth"
	"github.com/pkg/errors"

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

type Composer struct {
	editors map[string]*headerEditor

	acct   *config.AccountConfig
	config *config.AercConfig

	defaults    map[string]string
	editor      *Terminal
	email       *os.File
	attachments []string
	grid        *ui.Grid
	header      *ui.Grid
	review      *reviewMessage
	worker      *types.Worker

	layout    HeaderLayout
	focusable []ui.DrawableInteractive
	focused   int
}

func NewComposer(conf *config.AercConfig,
	acct *config.AccountConfig, worker *types.Worker, defaults map[string]string) *Composer {

	if defaults == nil {
		defaults = make(map[string]string)
	}
	if from := defaults["From"]; from == "" {
		defaults["From"] = acct.From
	}

	layout, editors, focusable := buildComposeHeader(
		conf.Compose.HeaderLayout, defaults)

	email, err := ioutil.TempFile("", "aerc-compose-*.eml")
	if err != nil {
		// TODO: handle this better
		return nil
	}

	c := &Composer{
		editors:  editors,
		acct:     acct,
		config:   conf,
		defaults: defaults,
		email:    email,
		worker:   worker,
		layout:   layout,
		// You have to backtab to get to "From", since you usually don't edit it
		focused:   1,
		focusable: focusable,
	}

	c.updateGrid()
	c.ShowTerminal()

	return c
}

func buildComposeHeader(layout HeaderLayout, defaults map[string]string) (
	newLayout HeaderLayout,
	editors map[string]*headerEditor,
	focusable []ui.DrawableInteractive,
) {
	editors = make(map[string]*headerEditor)
	focusable = make([]ui.DrawableInteractive, 0)

	for _, row := range layout {
		for _, h := range row {
			e := newHeaderEditor(h, "")
			editors[h] = e
			switch h {
			case "From":
				// Prepend From to support backtab
				focusable = append([]ui.DrawableInteractive{e}, focusable...)
			default:
				focusable = append(focusable, e)
			}
		}
	}

	// Add Cc/Bcc editors to layout if in defaults and not already visible
	for _, h := range []string{"Cc", "Bcc"} {
		if val, ok := defaults[h]; ok && val != "" {
			if _, ok := editors[h]; !ok {
				e := newHeaderEditor(h, "")
				editors[h] = e
				focusable = append(focusable, e)
				layout = append(layout, []string{h})
			}
		}
	}

	// Set default values for all editors
	for key := range editors {
		if val, ok := defaults[key]; ok {
			editors[key].input.Set(val)
			delete(defaults, key)
		}
	}
	return layout, editors, focusable
}

// Note: this does not reload the editor. You must call this before the first
// Draw() call.
func (c *Composer) SetContents(reader io.Reader) *Composer {
	c.email.Seek(0, os.SEEK_SET)
	io.Copy(c.email, reader)
	c.email.Sync()
	c.email.Seek(0, os.SEEK_SET)
	return c
}

func (c *Composer) FocusTerminal() *Composer {
	if c.editor == nil {
		return c
	}
	c.focusable[c.focused].Focus(false)
	c.focused = len(c.editors)
	c.focusable[c.focused].Focus(true)
	return c
}

func (c *Composer) FocusSubject() *Composer {
	c.focusable[c.focused].Focus(false)
	c.focused = 2
	c.focusable[c.focused].Focus(true)
	return c
}

// OnHeaderChange registers an OnChange callback for the specified header.
func (c *Composer) OnHeaderChange(header string, fn func(subject string)) {
	if editor, ok := c.editors[header]; ok {
		editor.OnChange(func() {
			fn(editor.input.String())
		})
	}
}

func (c *Composer) Draw(ctx *ui.Context) {
	c.grid.Draw(ctx)
}

func (c *Composer) Invalidate() {
	c.grid.Invalidate()
}

func (c *Composer) OnInvalidate(fn func(d ui.Drawable)) {
	c.grid.OnInvalidate(func(_ ui.Drawable) {
		fn(c)
	})
}

func (c *Composer) Close() {
	if c.email != nil {
		path := c.email.Name()
		c.email.Close()
		os.Remove(path)
		c.email = nil
	}
	if c.editor != nil {
		c.editor.Destroy()
		c.editor = nil
	}
}

func (c *Composer) Bindings() string {
	if c.editor == nil {
		return "compose::review"
	} else if c.editor == c.focusable[c.focused] {
		return "compose::editor"
	} else {
		return "compose"
	}
}

func (c *Composer) Event(event tcell.Event) bool {
	if c.editor != nil {
		return c.focusable[c.focused].Event(event)
	}
	return false
}

func (c *Composer) Focus(focus bool) {
	c.focusable[c.focused].Focus(focus)
}

func (c *Composer) Config() *config.AccountConfig {
	return c.acct
}

func (c *Composer) Worker() *types.Worker {
	return c.worker
}

func (c *Composer) PrepareHeader() (*mail.Header, []string, error) {
	// Extract headers from the email, if present
	if err := c.reloadEmail(); err != nil {
		return nil, nil, err
	}
	var (
		rcpts  []string
		header mail.Header
	)
	reader, err := mail.CreateReader(c.email)
	if err == nil {
		header = reader.Header
		defer reader.Close()
	} else {
		c.email.Seek(0, os.SEEK_SET)
	}
	// Update headers
	mhdr := (*message.Header)(&header.Header)
	mhdr.SetText("Message-Id", mail.GenerateMessageID())

	headerKeys := make([]string, 0, len(c.editors))
	for key := range c.editors {
		headerKeys = append(headerKeys, key)
	}
	// Ensure headers which require special processing are included.
	for _, key := range []string{"To", "From", "Cc", "Bcc", "Subject", "Date"} {
		if _, ok := c.editors[key]; !ok {
			headerKeys = append(headerKeys, key)
		}
	}

	for _, h := range headerKeys {
		val := ""
		editor, ok := c.editors[h]
		if ok {
			val = editor.input.String()
		} else {
			val, _ = mhdr.Text(h)
		}
		switch h {
		case "Subject":
			if subject, _ := header.Subject(); subject == "" {
				header.SetSubject(val)
			}
		case "Date":
			if date, err := header.Date(); err != nil || date == (time.Time{}) {
				header.SetDate(time.Now())
			}
		case "From", "To", "Cc", "Bcc": // Address headers
			if val != "" {
				hdrRcpts, err := gomail.ParseAddressList(val)
				if err != nil {
					return nil, nil, errors.Wrapf(err, "ParseAddressList(%s)", val)
				}
				edRcpts := make([]*mail.Address, len(hdrRcpts))
				for i, addr := range hdrRcpts {
					edRcpts[i] = (*mail.Address)(addr)
				}
				header.SetAddressList(h, edRcpts)
				if h != "From" {
					for _, addr := range edRcpts {
						rcpts = append(rcpts, addr.Address)
					}
				}
			}
		default:
			// Handle user configured header editors.
			if ok && !mhdr.Header.Has(h) {
				if val := editor.input.String(); val != "" {
					mhdr.SetText(h, val)
				}
			}
		}
	}

	// Merge in additional headers
	txthdr := mhdr.Header
	for key, value := range c.defaults {
		if !txthdr.Has(key) && value != "" {
			mhdr.SetText(key, value)
		}
	}

	return &header, rcpts, nil
}

func (c *Composer) WriteMessage(header *mail.Header, writer io.Writer) error {
	if err := c.reloadEmail(); err != nil {
		return err
	}
	var body io.Reader
	reader, err := mail.CreateReader(c.email)
	if err == nil {
		// TODO: Do we want to let users write a full blown multipart email
		// into the editor? If so this needs to change
		part, err := reader.NextPart()
		if err != nil {
			return errors.Wrap(err, "reader.NextPart")
		}
		body = part.Body
		defer reader.Close()
	} else {
		c.email.Seek(0, os.SEEK_SET)
		body = c.email
	}

	if len(c.attachments) == 0 {
		// don't create a multipart email if we only have text
		return writeInlineBody(header, body, writer)
	}

	// otherwise create a multipart email,
	// with a multipart/alternative part for the text
	w, err := mail.CreateWriter(writer, *header)
	if err != nil {
		return errors.Wrap(err, "CreateWriter")
	}
	defer w.Close()

	if err := writeMultipartBody(body, w); err != nil {
		return errors.Wrap(err, "writeMultipartBody")
	}

	for _, a := range c.attachments {
		if err := writeAttachment(a, w); err != nil {
			return errors.Wrap(err, "writeAttachment")
		}
	}

	return nil
}

func writeInlineBody(header *mail.Header, body io.Reader, writer io.Writer) error {
	header.SetContentType("text/plain", map[string]string{"charset": "UTF-8"})
	w, err := mail.CreateSingleInlineWriter(writer, *header)
	if err != nil {
		return errors.Wrap(err, "CreateSingleInlineWriter")
	}
	defer w.Close()
	if _, err := io.Copy(w, body); err != nil {
		return errors.Wrap(err, "io.Copy")
	}
	return nil
}

// write the message body to the multipart message
func writeMultipartBody(body io.Reader, w *mail.Writer) error {
	bh := mail.InlineHeader{}
	bh.SetContentType("text/plain", map[string]string{"charset": "UTF-8"})

	bi, err := w.CreateInline()
	if err != nil {
		return errors.Wrap(err, "CreateInline")
	}
	defer bi.Close()

	bw, err := bi.CreatePart(bh)
	if err != nil {
		return errors.Wrap(err, "CreatePart")
	}
	defer bw.Close()
	if _, err := io.Copy(bw, body); err != nil {
		return errors.Wrap(err, "io.Copy")
	}
	return nil
}

// write the attachment specified by path to the message
func writeAttachment(path string, writer *mail.Writer) error {
	filename := filepath.Base(path)

	f, err := os.Open(path)
	if err != nil {
		return errors.Wrap(err, "os.Open")
	}
	defer f.Close()

	reader := bufio.NewReader(f)

	// determine the MIME type
	// http.DetectContentType only cares about the first 512 bytes
	head, err := reader.Peek(512)
	if err != nil && err != io.EOF {
		return errors.Wrap(err, "Peek")
	}

	mimeString := http.DetectContentType(head)
	// mimeString can contain type and params (like text encoding),
	// so we need to break them apart before passing them to the headers
	mimeType, params, err := mime.ParseMediaType(mimeString)
	if err != nil {
		return errors.Wrap(err, "ParseMediaType")
	}
	params["name"] = filename

	// set header fields
	ah := mail.AttachmentHeader{}
	ah.SetContentType(mimeType, params)
	// setting the filename auto sets the content disposition
	ah.SetFilename(filename)

	aw, err := writer.CreateAttachment(ah)
	if err != nil {
		return errors.Wrap(err, "CreateAttachment")
	}
	defer aw.Close()

	if _, err := reader.WriteTo(aw); err != nil {
		return errors.Wrap(err, "reader.WriteTo")
	}

	return nil
}

func (c *Composer) GetAttachments() []string {
	return c.attachments
}

func (c *Composer) AddAttachment(path string) {
	c.attachments = append(c.attachments, path)
	c.resetReview()
}

func (c *Composer) DeleteAttachment(path string) error {
	for i, a := range c.attachments {
		if a == path {
			c.attachments = append(c.attachments[:i], c.attachments[i+1:]...)
			c.resetReview()
			return nil
		}
	}

	return errors.New("attachment does not exist")
}

func (c *Composer) resetReview() {
	if c.review != nil {
		c.grid.RemoveChild(c.review)
		c.review = newReviewMessage(c, nil)
		c.grid.AddChild(c.review).At(1, 0)
	}
}

func (c *Composer) termClosed(err error) {
	c.grid.RemoveChild(c.editor)
	c.review = newReviewMessage(c, err)
	c.grid.AddChild(c.review).At(1, 0)
	c.editor.Destroy()
	c.editor = nil
	c.focusable = c.focusable[:len(c.focusable)-1]
	if c.focused >= len(c.focusable) {
		c.focused = len(c.focusable) - 1
	}
}

func (c *Composer) ShowTerminal() {
	if c.editor != nil {
		return
	}
	if c.review != nil {
		c.grid.RemoveChild(c.review)
	}
	editorName := c.config.Compose.Editor
	if editorName == "" {
		editorName = os.Getenv("EDITOR")
	}
	if editorName == "" {
		editorName = "vi"
	}
	editor := exec.Command("/bin/sh", "-c", editorName+" "+c.email.Name())
	c.editor, _ = NewTerminal(editor) // TODO: handle error
	c.editor.OnClose = c.termClosed
	c.grid.AddChild(c.editor).At(1, 0)
	c.focusable = append(c.focusable, c.editor)
}

func (c *Composer) PrevField() {
	c.focusable[c.focused].Focus(false)
	c.focused--
	if c.focused == -1 {
		c.focused = len(c.focusable) - 1
	}
	c.focusable[c.focused].Focus(true)
}

func (c *Composer) NextField() {
	c.focusable[c.focused].Focus(false)
	c.focused = (c.focused + 1) % len(c.focusable)
	c.focusable[c.focused].Focus(true)
}

// AddEditor appends a new header editor to the compose window.
func (c *Composer) AddEditor(header string, value string, appendHeader bool) {
	if _, ok := c.editors[header]; ok {
		if appendHeader {
			header := c.editors[header].input.String()
			value = strings.TrimSpace(header) + ", " + value
		}
		c.editors[header].input.Set(value)
		return
	}
	e := newHeaderEditor(header, value)
	c.editors[header] = e
	c.layout = append(c.layout, []string{header})
	// Insert focus of new editor before terminal editor
	c.focusable = append(
		c.focusable[:len(c.focusable)-1],
		e,
		c.focusable[len(c.focusable)-1],
	)
	c.updateGrid()
}

// updateGrid should be called when the underlying header layout is changed.
func (c *Composer) updateGrid() {
	header, height := c.layout.grid(
		func(h string) ui.Drawable { return c.editors[h] },
	)

	if c.grid == nil {
		c.grid = ui.NewGrid().Columns([]ui.GridSpec{{ui.SIZE_WEIGHT, 1}})
	}

	c.grid.Rows([]ui.GridSpec{
		{ui.SIZE_EXACT, height},
		{ui.SIZE_WEIGHT, 1},
	})

	if c.header != nil {
		c.grid.RemoveChild(c.header)
	}
	c.header = header
	c.grid.AddChild(c.header).At(0, 0)
}

func (c *Composer) reloadEmail() error {
	name := c.email.Name()
	c.email.Close()
	file, err := os.Open(name)
	if err != nil {
		return errors.Wrap(err, "ReloadEmail")
	}
	c.email = file
	return nil
}

type headerEditor struct {
	name  string
	input *ui.TextInput
}

func newHeaderEditor(name string, value string) *headerEditor {
	return &headerEditor{
		input: ui.NewTextInput(value),
		name:  name,
	}
}

func (he *headerEditor) Draw(ctx *ui.Context) {
	name := he.name + " "
	size := runewidth.StringWidth(name)
	ctx.Fill(0, 0, size, ctx.Height(), ' ', tcell.StyleDefault)
	ctx.Printf(0, 0, tcell.StyleDefault.Bold(true), "%s", name)
	he.input.Draw(ctx.Subcontext(size, 0, ctx.Width()-size, 1))
}

func (he *headerEditor) Invalidate() {
	he.input.Invalidate()
}

func (he *headerEditor) OnInvalidate(fn func(ui.Drawable)) {
	he.input.OnInvalidate(func(_ ui.Drawable) {
		fn(he)
	})
}

func (he *headerEditor) Focus(focused bool) {
	he.input.Focus(focused)
}

func (he *headerEditor) Event(event tcell.Event) bool {
	return he.input.Event(event)
}

func (he *headerEditor) OnChange(fn func()) {
	he.input.OnChange(func(_ *ui.TextInput) {
		fn()
	})
}

type reviewMessage struct {
	composer *Composer
	grid     *ui.Grid
}

func newReviewMessage(composer *Composer, err error) *reviewMessage {
	spec := []ui.GridSpec{{ui.SIZE_EXACT, 2}, {ui.SIZE_EXACT, 1}}
	for i := 0; i < len(composer.attachments)-1; i++ {
		spec = append(spec, ui.GridSpec{ui.SIZE_EXACT, 1})
	}
	// make the last element fill remaining space
	spec = append(spec, ui.GridSpec{ui.SIZE_WEIGHT, 1})

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

	if err != nil {
		grid.AddChild(ui.NewText(err.Error()).
			Color(tcell.ColorRed, tcell.ColorDefault))
		grid.AddChild(ui.NewText("Press [q] to close this tab.")).At(1, 0)
	} else {
		// TODO: source this from actual keybindings?
		grid.AddChild(ui.NewText(
			"Send this email? [y]es/[n]o/[e]dit/[a]ttach")).At(0, 0)
		grid.AddChild(ui.NewText("Attachments:").
			Reverse(true)).At(1, 0)
		if len(composer.attachments) == 0 {
			grid.AddChild(ui.NewText("(none)")).At(2, 0)
		} else {
			for i, a := range composer.attachments {
				grid.AddChild(ui.NewText(a)).At(i+2, 0)
			}
		}
	}

	return &reviewMessage{
		composer: composer,
		grid:     grid,
	}
}

func (rm *reviewMessage) Invalidate() {
	rm.grid.Invalidate()
}

func (rm *reviewMessage) OnInvalidate(fn func(ui.Drawable)) {
	rm.grid.OnInvalidate(func(_ ui.Drawable) {
		fn(rm)
	})
}

func (rm *reviewMessage) Draw(ctx *ui.Context) {
	rm.grid.Draw(ctx)
}