Line data Source code
1 : package gamelog
2 :
3 : import (
4 : "fmt"
5 : "image/color"
6 : "strings"
7 : )
8 :
9 : // tagColors はマークアップのセマンティックタグを色へ対応させる。
10 : // 翻訳文字列に <item>薬</item> のように書くと、その範囲がこの色で描かれる。
11 : // 色は文字列の中にあるので、訳語ごと語順とともに動かせる
12 : var tagColors = map[string]color.RGBA{
13 : "item": ColorCyan,
14 : "player": ColorGreen,
15 : "npc": ColorYellow,
16 : "damage": ColorRed,
17 : "success": ColorGreen,
18 : "warning": ColorYellow,
19 : "error": ColorRed,
20 : "location": ColorOrange,
21 : "action": ColorPurple,
22 : "money": ColorYellow,
23 : "system": ColorCyan,
24 : }
25 :
26 : // namedColors は <color_red> のように色名で直接指定するタグ用のパレット
27 : var namedColors = map[string]color.RGBA{
28 : "white": ColorWhite,
29 : "red": ColorRed,
30 : "green": ColorGreen,
31 : "blue": ColorBlue,
32 : "yellow": ColorYellow,
33 : "cyan": ColorCyan,
34 : "magenta": ColorMagenta,
35 : "orange": ColorOrange,
36 : "purple": ColorPurple,
37 : }
38 :
39 : // Markup は <tag>...</tag> マークアップ付き文字列を色付き断片へ解釈してログへ積む。
40 : // マークアップは開発者が書く信頼できる入力なので、未知タグや閉じ忘れは記述ミスとして panic する
41 : func (l *Logger) Markup(s string) *Logger {
42 1 : l.fragments = append(l.fragments, ParseMarkup(s)...)
43 1 : return l
44 1 : }
45 :
46 : // ParseMarkup は <tag>...</tag> を色付き断片列へ分解する。タグの外は白。
47 : // 未知タグ・閉じ括弧の無いマーク・閉じタグ抜けは記述ミスとして panic し、黙って地の文に落とさない。
48 : func ParseMarkup(s string) []LogFragment {
49 1 : var frags []LogFragment
50 1 : add := func(text string, c color.RGBA) {
51 1 : if text != "" {
52 1 : frags = append(frags, LogFragment{Color: c, Text: text})
53 1 : }
54 : }
55 1 : for len(s) > 0 {
56 1 : open := strings.IndexByte(s, '<')
57 1 : if open < 0 {
58 1 : add(s, ColorWhite)
59 1 : break
60 : }
61 1 : add(s[:open], ColorWhite)
62 1 : s = s[open:]
63 1 :
64 1 : gt := strings.IndexByte(s, '>')
65 1 : if gt < 0 {
66 1 : panic(fmt.Sprintf("gamelog: unclosed markup bracket in %q", s))
67 : }
68 1 : tag := s[1:gt]
69 1 : c, known := tagColor(tag)
70 1 : if !known {
71 1 : panic(fmt.Sprintf("gamelog: unknown markup tag <%s>", tag))
72 : }
73 1 : closeTag := "</" + tag + ">"
74 1 : ci := strings.Index(s[gt+1:], closeTag)
75 1 : if ci < 0 {
76 1 : panic(fmt.Sprintf("gamelog: missing close tag %s", closeTag))
77 : }
78 1 : add(s[gt+1:gt+1+ci], c)
79 1 : s = s[gt+1+ci+len(closeTag):]
80 : }
81 1 : return frags
82 : }
83 :
84 : // tagColor はタグ名を色へ解決する。セマンティックタグと color_XXX 形式に対応する
85 : func tagColor(tag string) (color.RGBA, bool) {
86 1 : if c, ok := tagColors[tag]; ok {
87 1 : return c, true
88 1 : }
89 1 : if named, ok := strings.CutPrefix(tag, "color_"); ok {
90 1 : if c, ok := namedColors[named]; ok {
91 1 : return c, true
92 1 : }
93 : }
94 1 : return color.RGBA{}, false
95 : }
96 :
97 : // Tag は text を tag で包んだマークアップ文字列を返す。色付きの値を書式の引数として
98 : // 渡したいときに使う。例: query.T(world, "%[1]s を得た", gamelog.Tag("item", name))
99 : func Tag(tag, text string) string {
100 1 : return fmt.Sprintf("<%s>%s</%s>", tag, text, tag)
101 1 : }
|