/
lettericon.go
299 lines (250 loc) · 6.01 KB
/
lettericon.go
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
package lettericon
import (
"bufio"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"io"
"log"
"math"
"net/url"
"path"
"strconv"
"strings"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
"golang.org/x/net/publicsuffix"
"github.com/golang/freetype/truetype"
"github.com/mat/besticon/colorfinder"
"github.com/mat/besticon/lettericon/fonts"
)
const dpi = 72
const fontSizeFactor = 0.6180340 // (by taste)
const yOffsetFactor = 102.0 / 1024.0 // (by trial and error) :-)
func Render(letter string, bgColor color.Color, width int, out io.Writer) error {
fg := pickForegroundColor(bgColor)
rgba := image.NewRGBA(image.Rect(0, 0, width, width))
draw.Draw(rgba, rgba.Bounds(), &image.Uniform{bgColor}, image.ZP, draw.Src)
fontSize := fontSizeFactor * float64(width)
d := &font.Drawer{
Dst: rgba,
Src: &image.Uniform{fg},
Face: truetype.NewFace(fnt, &truetype.Options{
Size: fontSize,
DPI: dpi,
Hinting: font.HintingNone,
}),
}
y := int(yOffsetFactor*float64(width)) + int(math.Ceil(fontSize*dpi/72))
d.Dot = fixed.Point26_6{
X: (fixed.I(width) - d.MeasureString(letter)) / 2,
Y: fixed.I(y),
}
d.DrawString(letter)
b := bufio.NewWriter(out)
encoder := png.Encoder{CompressionLevel: png.BestCompression}
err := encoder.Encode(b, rgba)
if err != nil {
return err
}
err = b.Flush()
if err != nil {
return err
}
return nil
}
func pickForegroundColor(bgColor color.Color) color.Color {
cWhite := contrastRatio(pickLighterColor(color.White, bgColor))
// We prefer white text, this ratio was deemed good enough
if cWhite > 1.5 {
return color.White
}
return lightDark
}
func pickLighterColor(c1, c2 color.Color) (color.Color, color.Color) {
_, _, v1 := RGBToHSV(c1)
_, _, v2 := RGBToHSV(c2)
if v1 >= v2 {
return c1, c2
}
return c2, c1
}
// https://code.google.com/p/gorilla/source/browse/color/hsv.go?r=ef489f63418265a7249b1d53bdc358b09a4a2ea0
func RGBToHSV(c color.Color) (h, s, v float64) {
r, g, b, _ := c.RGBA()
fR := float64(r) / 255
fG := float64(g) / 255
fB := float64(b) / 255
max := math.Max(math.Max(fR, fG), fB)
min := math.Min(math.Min(fR, fG), fB)
d := max - min
s, v = 0, max
if max > 0 {
s = d / max
}
if max == min {
// Achromatic.
h = 0
} else {
// Chromatic.
switch max {
case fR:
h = (fG - fB) / d
if fG < fB {
h += 6
}
case fG:
h = (fB-fR)/d + 2
case fB:
h = (fR-fG)/d + 4
}
h /= 6
}
return
}
func contrastRatio(c1 color.Color, c2 color.Color) float64 {
// http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
l1 := relativeLuminance(c1)
l2 := relativeLuminance(c2)
return (l1 + 0.05) / (l2 + 0.05)
}
func relativeLuminance(c color.Color) float64 {
r, g, b, _ := c.RGBA()
r64 := foo(r)
g64 := foo(g)
b64 := foo(b)
return 0.2126*r64 + 0.7152*g64 + 0.0722*b64
}
const shiftRGB = uint8(8)
func foo(col uint32) float64 {
c := float64(uint8(col >> shiftRGB))
c /= 255.0
if c < 0.03928 {
return c / 12.92
}
return math.Pow(((c + 0.055) / 1.055), 2.4)
}
var (
errMalformedColorString = errors.New("Malformed hex color string")
)
func ColorFromHex(hex string) (*color.RGBA, error) {
if len(hex) != 6 && len(hex) != 7 {
return nil, errMalformedColorString
}
hex = strings.TrimPrefix(hex, "#")
r, err := strconv.ParseInt(hex[0:2], 16, 16)
if err != nil {
return nil, errMalformedColorString
}
g, err := strconv.ParseInt(hex[2:4], 16, 16)
if err != nil {
return nil, errMalformedColorString
}
b, err := strconv.ParseInt(hex[4:6], 16, 16)
if err != nil {
return nil, errMalformedColorString
}
col := color.RGBA{uint8(r), uint8(g), uint8(b), 0xff}
return &col, nil
}
func IconPath(letter string, size string, colr *color.RGBA) string {
if letter == "" {
letter = " "
} else {
letter = strings.ToUpper(letter)
}
if colr != nil {
return fmt.Sprintf("/lettericons/%s-%s-%s.png", letter, size, colorfinder.ColorToHex(*colr))
}
return fmt.Sprintf("/lettericons/%s-%s.png", letter, size)
}
const defaultIconSize = 144
// TODO: Sync with besticon.MaxIconSize ?
const maxIconSize = 256
// path is like: lettericons/M-144-EFC25D.png
func ParseIconPath(fullpath string) (string, *color.RGBA, int) {
fullpath = percentDecode(fullpath)
_, filename := path.Split(fullpath)
filename = strings.TrimSuffix(filename, ".png")
params := strings.Split(filename, "-")
if len(params) < 1 || len(params[0]) < 1 {
return "", nil, -1
}
charParam := firstRune(params[0])
sizeParam := ""
if len(params) >= 2 {
sizeParam = params[1]
}
colorParam := ""
if len(params) >= 3 {
colorParam = params[2]
}
size, err := strconv.Atoi(sizeParam)
if err != nil || size < 0 {
size = defaultIconSize
}
if size > maxIconSize {
size = maxIconSize
}
col, _ := ColorFromHex(colorParam)
if col == nil {
col = DefaultBackgroundColor
}
return charParam, col, size
}
func MainLetterFromURL(URL string) string {
URL = strings.TrimSpace(URL)
if !strings.HasPrefix(URL, "http:") && !strings.HasPrefix(URL, "https:") {
URL = "http://" + URL
}
url, err := url.Parse(URL)
if err != nil {
return ""
}
host := url.Host
hostSuffix, _ := publicsuffix.PublicSuffix(host)
if hostSuffix != "" {
host = strings.TrimSuffix(host, hostSuffix)
host = strings.TrimSuffix(host, ".")
}
hostParts := strings.Split(host, ".")
domain := hostParts[len(hostParts)-1]
if len(domain) > 0 {
return firstRune(domain)
} else if len(hostSuffix) > 0 {
return string(hostSuffix[0])
}
return ""
}
func firstRune(str string) string {
for _, runeValue := range str {
return fmt.Sprintf("%c", runeValue)
}
return ""
}
func percentDecode(p string) string {
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
u, err := url.ParseRequestURI(p)
if err != nil {
return p
}
return u.Path
}
var fnt *truetype.Font
var DefaultBackgroundColor *color.RGBA
var lightDark *color.RGBA
func init() {
var err error
fnt, err = truetype.Parse(fonts.NotoSansRegularBytes())
if err != nil {
log.Println(err)
return
}
DefaultBackgroundColor, _ = ColorFromHex("#909090")
lightDark, _ = ColorFromHex("#505050")
}