gomuks/ui/widget/color.go

79 lines
2.2 KiB
Go
Raw Normal View History

2018-03-15 18:45:52 +01:00
// gomuks - A terminal Matrix client written in Go.
// Copyright (C) 2018 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
2018-03-18 20:24:03 +01:00
package widget
2018-03-15 18:45:52 +01:00
import (
2018-03-18 20:24:03 +01:00
"fmt"
"hash/fnv"
"sort"
"maunium.net/go/tcell"
2018-03-15 18:45:52 +01:00
)
2018-03-18 20:24:03 +01:00
var colorNames []string
2018-03-15 18:45:52 +01:00
2018-03-22 22:03:36 +01:00
// init initializes the colorNames array.
2018-03-18 20:24:03 +01:00
func init() {
colorNames = make([]string, len(tcell.ColorNames))
i := 0
2018-04-01 09:28:46 +02:00
for name := range tcell.ColorNames {
2018-03-18 20:24:03 +01:00
colorNames[i] = name
i++
}
2018-03-22 22:03:36 +01:00
// In order to have consistent coloring between restarts, we need to sort the array.
2018-03-18 20:24:03 +01:00
sort.Sort(sort.StringSlice(colorNames))
2018-03-15 18:45:52 +01:00
}
2018-03-22 22:03:36 +01:00
// GetHashColorName gets a color name for the given string based on its FNV-1 hash.
//
// The array of possible color names are the alphabetically ordered color
// names specified in tcell.ColorNames.
//
// The algorithm to get the color is as follows:
// colorNames[ FNV1(string) % len(colorNames) ]
//
// With the exception of the three special cases:
// --> = green
// <-- = red
// --- = yellow
2018-03-18 20:24:03 +01:00
func GetHashColorName(s string) string {
switch s {
case "-->":
return "green"
case "<--":
return "red"
case "---":
return "yellow"
default:
h := fnv.New32a()
_, _ = h.Write([]byte(s))
return colorNames[h.Sum32()%uint32(len(colorNames))]
2018-03-15 18:45:52 +01:00
}
}
2018-03-18 20:24:03 +01:00
2018-03-22 22:03:36 +01:00
// GetHashColor gets the tcell Color value for the given string.
//
// GetHashColor calls GetHashColorName() and gets the Color value from the tcell.ColorNames map.
2018-03-18 20:24:03 +01:00
func GetHashColor(s string) tcell.Color {
return tcell.ColorNames[GetHashColorName(s)]
}
2018-04-18 16:33:59 +02:00
// AddColor adds tview color tags to the given string.
func AddColor(s, color string) string {
return fmt.Sprintf("[%s]%s[white]", color, s)
2018-03-18 20:24:03 +01:00
}