Debian Codegraph @

config/ui.go

raw
1 package config
2
3 import (
4 "fmt"
5 "math"
6 "path"
7 "reflect"
8 "regexp"
9 "strconv"
10 "strings"
11 "sync/atomic"
12 "text/template"
13 "time"
14
15 "git.sr.ht/~rjarry/aerc/lib/log"
16 "github.com/emersion/go-message/mail"
17 "github.com/go-ini/ini"
18 "go.rockorager.dev/vaxis"
19 )
20
21 type UIConfig struct {
22 IndexColumns []*ColumnDef `ini:"index-columns" parse:"ParseIndexColumns" default:"flags:4,name<20%,subject,date>="`
23 ColumnSeparator string `ini:"column-separator" default:" "`
24
25 DirListLeft *template.Template `ini:"dirlist-left" default:"{{.Folder}}"`
26 DirListRight *template.Template `ini:"dirlist-right" default:"{{if .Unread}}{{humanReadable .Unread}}{{end}}"`
27
28 AutoMarkRead bool `ini:"auto-mark-read" default:"true"`
29 AutoMarkReadInSplit bool `ini:"auto-mark-read-split" default:"false"`
30 AutoMarkReadInSplitDelay time.Duration `ini:"auto-mark-read-split-delay" default:"3s"`
31 TimestampFormat string `ini:"timestamp-format" default:"2006 Jan 02"`
32 ThisDayTimeFormat string `ini:"this-day-time-format" default:"15:04"`
33 ThisWeekTimeFormat string `ini:"this-week-time-format" default:"Jan 02"`
34 ThisYearTimeFormat string `ini:"this-year-time-format" default:"Jan 02"`
35 MessageViewTimestampFormat string `ini:"message-view-timestamp-format" default:"2006 Jan 02, 15:04 GMT-0700"`
36 MessageViewThisDayTimeFormat string `ini:"message-view-this-day-time-format"`
37 MessageViewThisWeekTimeFormat string `ini:"message-view-this-week-time-format"`
38 MessageViewThisYearTimeFormat string `ini:"message-view-this-year-time-format"`
39 PinnedTabMarker string "ini:\"pinned-tab-marker\" default:\"`\""
40 SidebarWidth int `ini:"sidebar-width" default:"22"`
41 QuakeHeight int `ini:"quake-terminal-height" default:"20"`
42 MessageListSplit SplitParams `ini:"message-list-split" parse:"ParseSplit"`
43 EmptyMessage string `ini:"empty-message" default:"(no messages)"`
44 EmptyDirlist string `ini:"empty-dirlist" default:"(no folders)"`
45 EmptySubject string `ini:"empty-subject" default:"(no subject)"`
46 MouseEnabled bool `ini:"mouse-enabled"`
47 ThreadingEnabled bool `ini:"threading-enabled"`
48 ForceClientThreads bool `ini:"force-client-threads"`
49 ThreadingBySubject bool `ini:"threading-by-subject"`
50 ClientThreadsDelay time.Duration `ini:"client-threads-delay" default:"50ms"`
51 ThreadContext bool `ini:"show-thread-context"`
52 FuzzyComplete bool `ini:"fuzzy-complete"`
53 NewMessageBell bool `ini:"new-message-bell" default:"true"`
54 Spinner string `ini:"spinner" default:"[..] , [..] , [..] , [..] , [..], [..] , [..] , [..] "`
55 SpinnerDelimiter string `ini:"spinner-delimiter" default:","`
56 SpinnerInterval time.Duration `ini:"spinner-interval" default:"200ms"`
57 IconUnencrypted string `ini:"icon-unencrypted"`
58 IconEncrypted string `ini:"icon-encrypted" default:"[e]"`
59 IconSigned string `ini:"icon-signed" default:"[s]"`
60 IconSignedEncrypted string `ini:"icon-signed-encrypted"`
61 IconUnknown string `ini:"icon-unknown" default:"[s?]"`
62 IconInvalid string `ini:"icon-invalid" default:"[s!]"`
63 IconAttachment string `ini:"icon-attachment" default:"a"`
64 IconReplied string `ini:"icon-replied" default:"r"`
65 IconForwarded string `ini:"icon-forwarded" default:"f"`
66 IconNew string `ini:"icon-new" default:"N"`
67 IconOld string `ini:"icon-old" default:"O"`
68 IconDraft string `ini:"icon-draft" default:"d"`
69 IconFlagged string `ini:"icon-flagged" default:"!"`
70 IconMarked string `ini:"icon-marked" default:"*"`
71 IconDeleted string `ini:"icon-deleted" default:"X"`
72 DirListDelay time.Duration `ini:"dirlist-delay" default:"200ms"`
73 DirListTree bool `ini:"dirlist-tree"`
74 DirListCollapse int `ini:"dirlist-collapse"`
75 Sort []string `ini:"sort" delim:" "`
76 NextMessageOnDelete bool `ini:"next-message-on-delete" default:"true"`
77 CompletionDelay time.Duration `ini:"completion-delay" default:"250ms"`
78 CompletionMinChars int `ini:"completion-min-chars" default:"1" parse:"ParseCompletionMinChars"`
79 CompletionPopovers bool `ini:"completion-popovers" default:"true"`
80 MsglistScrollOffset int `ini:"msglist-scroll-offset" default:"0"`
81 DialogPosition string `ini:"dialog-position" default:"center" parse:"ParseDialogPosition"`
82 DialogWidth int `ini:"dialog-width" default:"50" parse:"ParseDialogDimensions"`
83 DialogHeight int `ini:"dialog-height" default:"50" parse:"ParseDialogDimensions"`
84 StyleSetDirs []string `ini:"stylesets-dirs" delim:":"`
85 StyleSetName string `ini:"styleset-name" default:"default"`
86 CenteredLayoutWidth int `ini:"centered-layout-width" default:"0"`
87 KeyHint bool `ini:"keyhint" default:"false"`
88 KeyHintDelay time.Duration `ini:"keyhint-delay" default:"200ms"`
89 KeyHintPosition string `ini:"keyhint-position" default:"" parse:"ParseKeyHintPosition"`
90
91 // customize border appearance
92 BorderCharVertical rune `ini:"border-char-vertical" default:"│" type:"rune"`
93 BorderCharHorizontal rune `ini:"border-char-horizontal" default:"─" type:"rune"`
94
95 SelectLast bool `ini:"select-last-message" default:"false"`
96 ReverseOrder bool `ini:"reverse-msglist-order"`
97 ReverseThreadOrder bool `ini:"reverse-thread-order"`
98 SortThreadSiblings bool `ini:"sort-thread-siblings"`
99
100 ThreadPrefixTip string `ini:"thread-prefix-tip" default:">"`
101 ThreadPrefixIndent string `ini:"thread-prefix-indent" default:" "`
102 ThreadPrefixStem string `ini:"thread-prefix-stem" default:"│"`
103 ThreadPrefixLimb string `ini:"thread-prefix-limb" default:""`
104 ThreadPrefixFolded string `ini:"thread-prefix-folded" default:"+"`
105 ThreadPrefixUnfolded string `ini:"thread-prefix-unfolded" default:""`
106 ThreadPrefixFirstChild string `ini:"thread-prefix-first-child" default:""`
107 ThreadPrefixHasSiblings string `ini:"thread-prefix-has-siblings" default:"├─"`
108 ThreadPrefixLone string `ini:"thread-prefix-lone" default:""`
109 ThreadPrefixOrphan string `ini:"thread-prefix-orphan" default:""`
110 ThreadPrefixLastSibling string `ini:"thread-prefix-last-sibling" default:"└─"`
111 ThreadPrefixDummy string `ini:"thread-prefix-dummy" default:"┬─"`
112 ThreadPrefixLastSiblingReverse string `ini:"thread-prefix-last-sibling-reverse" default:"┌─"`
113 ThreadPrefixFirstChildReverse string `ini:"thread-prefix-first-child-reverse" default:""`
114 ThreadPrefixOrphanReverse string `ini:"thread-prefix-orphan-reverse" default:""`
115 ThreadPrefixDummyReverse string `ini:"thread-prefix-dummy-reverse" default:"┴─"`
116
117 // Tab Templates
118 TabTitleAccount *template.Template `ini:"tab-title-account" default:"{{.Account}}"`
119 TabTitleComposer *template.Template `ini:"tab-title-composer" default:"{{if .To}}to:{{index (.To | shortmboxes) 0}} {{end}}{{.SubjectBase}}"`
120 TabTitleTerminal *template.Template `ini:"tab-title-terminal" default:"{{.Title}}"`
121 TabTitleViewer *template.Template `ini:"tab-title-viewer" default:"{{.Subject}}"`
122
123 // private
124 style atomic.Pointer[StyleSet]
125 contextualUis []*UiConfigContext
126 contextualCounts map[uiContextType]int
127 contextualCache map[uiContextKey]*UIConfig
128 }
129
130 type uiContextType int
131
132 const (
133 uiContextFolder uiContextType = iota
134 uiContextAccount
135 )
136
137 type UiConfigContext struct {
138 ContextType uiContextType
139 Regex *regexp.Regexp
140 UiConfig *UIConfig
141 Section ini.Section
142 }
143
144 type uiContextKey struct {
145 ctxType uiContextType
146 value string
147 }
148
149 var uiConfig atomic.Pointer[UIConfig]
150
151 func Ui() *UIConfig {
152 return uiConfig.Load()
153 }
154
155 var uiContextualSectionRe = regexp.MustCompile(`^ui:(account|folder)([~=])(.+)$`)
156
157 func parseUi(file *ini.File) (*UIConfig, error) {
158 conf := &UIConfig{
159 contextualCounts: make(map[uiContextType]int),
160 contextualCache: make(map[uiContextKey]*UIConfig),
161 }
162 if err := conf.parse(file.Section("ui")); err != nil {
163 return nil, err
164 }
165
166 for _, section := range file.Sections() {
167 var err error
168 groups := uiContextualSectionRe.FindStringSubmatch(section.Name())
169 if groups == nil {
170 continue
171 }
172 ctx, separator, value := groups[1], groups[2], groups[3]
173
174 uiSubConfig := UIConfig{}
175 if err = uiSubConfig.parse(section); err != nil {
176 return nil, err
177 }
178 contextualUi := UiConfigContext{
179 UiConfig: &uiSubConfig,
180 Section: *section,
181 }
182
183 switch ctx {
184 case "account":
185 contextualUi.ContextType = uiContextAccount
186 case "folder":
187 contextualUi.ContextType = uiContextFolder
188 }
189 if separator == "=" {
190 value = "^" + regexp.QuoteMeta(value) + "$"
191 }
192 contextualUi.Regex, err = regexp.Compile(value)
193 if err != nil {
194 return nil, err
195 }
196
197 conf.contextualUis = append(conf.contextualUis, &contextualUi)
198 conf.contextualCounts[contextualUi.ContextType]++
199 }
200
201 // append default paths to styleset-dirs
202 for _, dir := range SearchDirs {
203 conf.StyleSetDirs = append(
204 conf.StyleSetDirs, path.Join(dir, "stylesets"),
205 )
206 }
207
208 if err := conf.LoadStyle(); err != nil {
209 return nil, err
210 }
211
212 log.Debugf("aerc.conf: [ui] %#v", conf)
213
214 return conf, nil
215 }
216
217 func (config *UIConfig) parse(section *ini.Section) error {
218 if err := MapToStruct(section, config, section.Name() == "ui"); err != nil {
219 return err
220 }
221
222 if config.MessageViewTimestampFormat == "" {
223 config.MessageViewTimestampFormat = config.TimestampFormat
224 }
225
226 return nil
227 }
228
229 func (*UIConfig) ParseIndexColumns(section *ini.Section, key *ini.Key) ([]*ColumnDef, error) {
230 if !section.HasKey("column-date") {
231 _, _ = section.NewKey("column-date", `{{.DateAutoFormat .Date.Local}}`)
232 }
233 if !section.HasKey("column-name") {
234 _, _ = section.NewKey("column-name", `{{index (.From | names) 0}}`)
235 }
236 if !section.HasKey("column-flags") {
237 _, _ = section.NewKey("column-flags", `{{.Flags | join ""}}`)
238 }
239 if !section.HasKey("column-subject") {
240 _, _ = section.NewKey("column-subject", `{{.ThreadPrefix}}{{.Subject}}`)
241 }
242 return ParseColumnDefs(key, section)
243 }
244
245 type SplitDirection int
246
247 const (
248 SPLIT_NONE SplitDirection = iota
249 SPLIT_HORIZONTAL
250 SPLIT_VERTICAL
251 )
252
253 type SplitParams struct {
254 Direction SplitDirection
255 Size int
256 }
257
258 func (*UIConfig) ParseSplit(section *ini.Section, key *ini.Key) (p SplitParams, err error) {
259 re := regexp.MustCompile(`^\s*(v(?:ert(?:ical)?)?|h(?:oriz(?:ontal)?)?)?\s+(\d+)\s*$`)
260 match := re.FindStringSubmatch(key.String())
261 if len(match) != 3 {
262 err = fmt.Errorf("bad option value")
263 return
264 }
265 p.Direction = SPLIT_HORIZONTAL
266 switch match[1] {
267 case "v", "vert", "vertical":
268 p.Direction = SPLIT_VERTICAL
269 case "h", "horiz", "horizontal":
270 p.Direction = SPLIT_HORIZONTAL
271 }
272 size, e := strconv.ParseUint(match[2], 10, 32)
273 if e != nil {
274 err = e
275 return
276 }
277 p.Size = int(size)
278 return
279 }
280
281 func (*UIConfig) ParseDialogPosition(section *ini.Section, key *ini.Key) (string, error) {
282 match, _ := regexp.MatchString(`^\s*(top|center|bottom)\s*$`, key.String())
283 if !(match) {
284 return "", fmt.Errorf("bad option value")
285 }
286 return key.String(), nil
287 }
288
289 func (*UIConfig) ParseKeyHintPosition(section *ini.Section, key *ini.Key) (string, error) {
290 val := strings.TrimSpace(key.String())
291 if val == "" {
292 return "", nil
293 }
294 match, _ := regexp.MatchString(`^(bottom-left|bottom-center|bottom-right)$`, val)
295 if !match {
296 return "", fmt.Errorf("bad option value")
297 }
298 return val, nil
299 }
300
301 const (
302 DIALOG_MIN_PROPORTION = 10
303 DIALOG_MAX_PROPORTION = 100
304 )
305
306 func (*UIConfig) ParseDialogDimensions(section *ini.Section, key *ini.Key) (int, error) {
307 value, err := key.Int()
308 if value < DIALOG_MIN_PROPORTION || value > DIALOG_MAX_PROPORTION || err != nil {
309 return 0, fmt.Errorf("value out of range")
310 }
311 return value, nil
312 }
313
314 const MANUAL_COMPLETE = math.MaxInt
315
316 func (*UIConfig) ParseCompletionMinChars(section *ini.Section, key *ini.Key) (int, error) {
317 if key.String() == "manual" {
318 return MANUAL_COMPLETE, nil
319 }
320 return key.Int()
321 }
322
323 func (ui *UIConfig) ClearCache() {
324 for k := range ui.contextualCache {
325 delete(ui.contextualCache, k)
326 }
327 }
328
329 func (ui *UIConfig) LoadStyle() error {
330 if err := ui.loadStyleSet(ui.StyleSetDirs); err != nil {
331 return err
332 }
333
334 for _, contextualUi := range ui.contextualUis {
335 if contextualUi.UiConfig.StyleSetName == "" &&
336 len(contextualUi.UiConfig.StyleSetDirs) == 0 {
337 continue // no need to do anything if nothing is overridden
338 }
339 // fill in the missing part from the base
340 if contextualUi.UiConfig.StyleSetName == "" {
341 contextualUi.UiConfig.StyleSetName = ui.StyleSetName
342 } else if len(contextualUi.UiConfig.StyleSetDirs) == 0 {
343 contextualUi.UiConfig.StyleSetDirs = ui.StyleSetDirs
344 }
345 // since at least one of them has changed, load the styleset
346 if err := contextualUi.UiConfig.loadStyleSet(
347 contextualUi.UiConfig.StyleSetDirs); err != nil {
348 return err
349 }
350 }
351
352 return nil
353 }
354
355 func (ui *UIConfig) loadStyleSet(styleSetDirs []string) error {
356 style := NewStyleSet()
357 err := style.LoadStyleSet(ui.StyleSetName, styleSetDirs)
358 if err != nil {
359 if len(style.paths) == 0 {
360 style.paths = append(style.paths, ui.StyleSetName)
361 }
362 return fmt.Errorf("%v: %w", style.paths, err)
363 }
364
365 ui.style.Store(style)
366
367 return nil
368 }
369
370 func (base *UIConfig) mergeContextual(
371 contextType uiContextType, s string,
372 ) *UIConfig {
373 for _, contextualUi := range base.contextualUis {
374 if contextualUi.ContextType != contextType {
375 continue
376 }
377 if !contextualUi.Regex.Match([]byte(s)) {
378 continue
379 }
380
381 ui := new(UIConfig)
382
383 // only copy public fields
384 baseVal := reflect.ValueOf(base).Elem()
385 uiVal := reflect.ValueOf(ui).Elem()
386 for i := range baseVal.NumField() {
387 field := baseVal.Type().Field(i)
388 if field.IsExported() {
389 uiVal.Field(i).Set(baseVal.Field(i))
390 }
391 }
392
393 err := ui.parse(&contextualUi.Section)
394 if err != nil {
395 log.Warnf("merge ui failed: %v", err)
396 }
397 ui.contextualCache = make(map[uiContextKey]*UIConfig)
398 ui.contextualCounts = base.contextualCounts
399 ui.contextualUis = base.contextualUis
400 if contextualUi.UiConfig.StyleSetName != "" {
401 ui.style.Store(contextualUi.UiConfig.style.Load())
402 } else {
403 ui.style.Store(base.style.Load())
404 }
405 return ui
406 }
407 return base
408 }
409
410 func (uiConfig *UIConfig) GetUserStyle(name string) vaxis.Style {
411 return uiConfig.style.Load().UserStyle(name)
412 }
413
414 func (uiConfig *UIConfig) GetStyle(so StyleObject) vaxis.Style {
415 return uiConfig.style.Load().Get(so, nil)
416 }
417
418 func (uiConfig *UIConfig) GetStyleSelected(so StyleObject) vaxis.Style {
419 return uiConfig.style.Load().Selected(so, nil)
420 }
421
422 func (uiConfig *UIConfig) GetComposedStyle(base StyleObject,
423 styles []StyleObject,
424 ) vaxis.Style {
425 return uiConfig.style.Load().Compose(base, styles, nil)
426 }
427
428 func (uiConfig *UIConfig) GetComposedStyleSelected(
429 base StyleObject, styles []StyleObject,
430 ) vaxis.Style {
431 return uiConfig.style.Load().ComposeSelected(base, styles, nil)
432 }
433
434 func (uiConfig *UIConfig) MsgComposedStyle(
435 base StyleObject, styles []StyleObject, h *mail.Header,
436 ) vaxis.Style {
437 return uiConfig.style.Load().Compose(base, styles, h)
438 }
439
440 func (uiConfig *UIConfig) MsgComposedStyleSelected(
441 base StyleObject, styles []StyleObject, h *mail.Header,
442 ) vaxis.Style {
443 return uiConfig.style.Load().ComposeSelected(base, styles, h)
444 }
445
446 func (uiConfig *UIConfig) StyleSetPath() string {
447 return strings.Join(uiConfig.style.Load().paths, ",")
448 }
449
450 func (base *UIConfig) contextual(ctxType uiContextType, value string) *UIConfig {
451 if base.contextualCounts[ctxType] == 0 {
452 // shortcut if no contextual ui for that type
453 return base
454 }
455 key := uiContextKey{ctxType: ctxType, value: value}
456 c, found := base.contextualCache[key]
457 if !found {
458 c = base.mergeContextual(ctxType, value)
459 base.contextualCache[key] = c
460 }
461 return c
462 }
463
464 func (base *UIConfig) ForAccount(account string) *UIConfig {
465 return base.contextual(uiContextAccount, account)
466 }
467
468 func (base *UIConfig) ForFolder(folder string) *UIConfig {
469 return base.contextual(uiContextFolder, folder)
470 }