From 962362d46183af1878596c6116ddf515a7b749bc Mon Sep 17 00:00:00 2001 From: Graham Clark Date: Mon, 7 Sep 2020 00:49:29 -0400 Subject: [PATCH] A function to construct a color by looking it up in the config file MakeColorSafe() is a gowid function to construct a color based on a string. Gowid walks through various interpretations of the string to try to construct the most likely color. This function adds an interpretation at the beginning, which is as a key in the termshark toml file. This lets you add something like [theme] flashy = "theme.red" red = "#ff0000" Now you can programmatically use "theme.flashy" as an argument and construct a color from it. This function takes an an extra argument, meaning foreground or background. This allows for pairs of colors to be used: [theme] ocean = ["#ffffff", "#0000ff"] // white on blue If you call MakeColorSafe() with "theme.ocean" and theme.Background, you'll get the blue color. Values can refer to other keys in the toml file; this can be done up to 10 times before the function gives up (in case there's a loop). --- theme/utils.go | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 theme/utils.go diff --git a/theme/utils.go b/theme/utils.go new file mode 100644 index 0000000..53dd9d2 --- /dev/null +++ b/theme/utils.go @@ -0,0 +1,62 @@ +// Copyright 2019-2020 Graham Clark. All rights reserved. Use of this source +// code is governed by the MIT license that can be found in the LICENSE +// file. + +// package theme provides utilities for customizing the styling of termshark. +package theme + +import ( + "github.com/gcla/gowid" + "github.com/gcla/termshark/v2" + log "github.com/sirupsen/logrus" +) + +//====================================================================== + +type Layer int + +const ( + Foreground Layer = 0 + Background Layer = iota +) + +// MakeColorSafe extends gowid's MakeColorSafe function, prefering to interpret +// its string argument as a toml file config key lookup first; if this fails, then +// fall back to gowid.MakeColorSafe, which will then read colors as urwid color names, +// #-prefixed hex digits, grayscales, etc. +func MakeColorSafe(s string, l Layer) (gowid.Color, error) { + loops := 10 + cur := s + for { + next := termshark.ConfString(cur, "") + if next != "" { + cur = next + } else { + next := termshark.ConfStringSlice(cur, []string{}) + if len(next) != 2 { + break + } else { + cur = next[l] + } + } + loops -= 1 + if loops == 0 { + break + } + } + col, err := gowid.MakeColorSafe(cur) + if err == nil { + return gowid.Color{IColor: col, Id: s}, nil + } + col, err = gowid.MakeColorSafe(s) + if err != nil { + log.Infof("Could not understand configured theme color '%s'", s) + } + return col, err +} + +//====================================================================== +// Local Variables: +// mode: Go +// fill-column: 110 +// End: