definition_generate_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package main
  2. import (
  3. "encoding/json"
  4. "os"
  5. "path/filepath"
  6. "strconv"
  7. "strings"
  8. "testing"
  9. intrgb "netdome.biz/paul/qmk-rgb/internal/rgb"
  10. intvia "netdome.biz/paul/qmk-rgb/internal/via"
  11. )
  12. // generateStub is a keyboard that answers an effect range, so the generated
  13. // scaffold can be checked without hardware. The Vial fields are what a keyboard
  14. // running Vial firmware would answer; zero versions read as a keyboard that is
  15. // not Vial.
  16. type generateStub struct {
  17. tops map[intvia.Channel]int
  18. vial bool
  19. vialIDs []uint16
  20. vialErr error
  21. }
  22. func (g generateStub) VialVersion() (uint32, bool, error) {
  23. if !g.vial {
  24. return 0, false, nil
  25. }
  26. return 6, true, nil
  27. }
  28. func (g generateStub) VialEffectIDs() ([]uint16, error) {
  29. if g.vialErr != nil {
  30. return nil, g.vialErr
  31. }
  32. return g.vialIDs, nil
  33. }
  34. func (g generateStub) EffectTop(ch intvia.Channel) (int, error) {
  35. return g.tops[ch], nil
  36. }
  37. func (g generateStub) GetValue(intvia.Channel, uint8) ([]byte, error) { return []byte{0}, nil }
  38. func (g generateStub) SetValue(intvia.Channel, uint8, uint8) error { return nil }
  39. func (g generateStub) SetColor(intvia.Channel, uint8, uint8) error { return nil }
  40. func (g generateStub) DetectChannels() ([]intvia.Channel, error) { return nil, nil }
  41. func (g generateStub) Close() error { return nil }
  42. // stubGenerateTarget makes the connected keyboard a fixed one. The identifiers
  43. // are a parameter because a board the binary carries a definition for is the
  44. // case `generate` has to refuse, and a stub for the wrong board would test
  45. // nothing.
  46. func stubGenerateTarget(t *testing.T, vendorID, productID uint16, channels []intvia.Channel, tops map[intvia.Channel]int) {
  47. t.Helper()
  48. original := openTarget
  49. t.Cleanup(func() { openTarget = original })
  50. openTarget = func(string) (rgbProtocol, targetDeviceData, []intvia.Channel, error) {
  51. return generateStub{tops: tops}, stubTargetData(vendorID, productID), channels, nil
  52. }
  53. }
  54. func forceGenerateRestore(t *testing.T) func() {
  55. t.Helper()
  56. original := generateForce
  57. return func() { generateForce = original }
  58. }
  59. // The whole point of the command: a generated file names no effect, so a board
  60. // with a generated definition reports the same "no names" it reported before one
  61. // existed. A scaffold that claimed names would be a guess the tool could not
  62. // read back off the keyboard.
  63. func TestGeneratedDefinitionNamesNoEffectUntilTheUserFillsItIn(t *testing.T) {
  64. dir := t.TempDir()
  65. t.Cleanup(definitionFlagRestore(t))
  66. t.Cleanup(forceDefinitionsDir(t, dir))
  67. t.Cleanup(forceGenerateRestore(t))
  68. stubGenerateTarget(t, 0x1234, 0x5678, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
  69. cmd := NewKeyboardDefinitionsGenerateCmd()
  70. var out, errOut strings.Builder
  71. cmd.SetOut(&out)
  72. cmd.SetErr(&errOut)
  73. if err := cmd.Execute(); err != nil {
  74. t.Fatalf("definitions generate error = %v (stderr %q)", err, errOut.String())
  75. }
  76. path := onlyDefinition(t, dir)
  77. def, err := intrgb.ParseDefinition(path, []byte(mustRead(t, path)))
  78. if err != nil {
  79. t.Fatalf("ParseDefinition(%s) error = %v; the generated file has to load", path, err)
  80. }
  81. if got := len(def.Catalog.Effects(intvia.ChannelRgbMatrix)); got != 0 {
  82. t.Errorf("effects on rgb_matrix = %d, want 0 until the names are written in", got)
  83. }
  84. // The slots are still there, which is the other half: the file states which
  85. // IDs exist and leaves the naming to the user.
  86. var file struct {
  87. Menus []struct {
  88. Content []struct {
  89. Label string `json:"label"`
  90. Type string `json:"type"`
  91. Content []any `json:"content"`
  92. Options []any `json:"options"`
  93. } `json:"content"`
  94. } `json:"menus"`
  95. }
  96. if err := json.Unmarshal([]byte(mustRead(t, path)), &file); err != nil {
  97. t.Fatalf("unmarshal generated file: %v", err)
  98. }
  99. var options []any
  100. for _, menu := range file.Menus {
  101. for _, entry := range menu.Content {
  102. if entry.Type == "dropdown" {
  103. options = entry.Options
  104. }
  105. }
  106. }
  107. if len(options) != 46 {
  108. t.Fatalf("effect options = %d, want 46, one per ID from 0 to 45", len(options))
  109. }
  110. for i, option := range options {
  111. pair, ok := option.([]any)
  112. if !ok || len(pair) != 2 {
  113. t.Fatalf("option %d = %v, want a name and a number", i, option)
  114. }
  115. if name, _ := pair[0].(string); name != "" {
  116. t.Errorf("option %d is named %q, want a slot with no name", i, name)
  117. }
  118. if number, _ := pair[1].(float64); int(number) != i {
  119. t.Errorf("option %d carries ID %v, want the slot numbered %d", i, pair[1], i)
  120. }
  121. }
  122. // Every control has to be addressed by a value key the parser recognises. A
  123. // key built by trimming a suffix and appending without the underscore is
  124. // `id_qmk_rgb_matrixbrightness`, which names nothing, and nothing in the
  125. // output above would say so.
  126. wantKeys := map[string]bool{
  127. "id_qmk_rgb_matrix_brightness": false,
  128. "id_qmk_rgb_matrix_effect": false,
  129. "id_qmk_rgb_matrix_effect_speed": false,
  130. }
  131. for _, menu := range file.Menus {
  132. for _, entry := range menu.Content {
  133. key, _ := entry.Content[0].(string)
  134. if _, ok := wantKeys[key]; !ok {
  135. t.Errorf("control %q is addressed by %q, which is not a VIA value key", entry.Label, key)
  136. continue
  137. }
  138. wantKeys[key] = true
  139. }
  140. }
  141. for key, found := range wantKeys {
  142. if !found {
  143. t.Errorf("no control addresses %q", key)
  144. }
  145. }
  146. }
  147. // A definition a user has written is the one command they would have run to write
  148. // it, so it must survive a second run of the command.
  149. func TestGenerateDoesNotReplaceAStoredDefinition(t *testing.T) {
  150. dir := t.TempDir()
  151. t.Cleanup(definitionFlagRestore(t))
  152. t.Cleanup(forceDefinitionsDir(t, dir))
  153. t.Cleanup(forceGenerateRestore(t))
  154. stubGenerateTarget(t, 0x1234, 0x5678, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
  155. written := `{"name":"Test Board","vendorId":"0x1234","productId":"0x5678","menus":[],"note":"hand written"}`
  156. if err := os.WriteFile(filepath.Join(dir, "test_board.json"), []byte(written), 0o644); err != nil {
  157. t.Fatal(err)
  158. }
  159. cmd := NewKeyboardDefinitionsGenerateCmd()
  160. var out, errOut strings.Builder
  161. cmd.SetOut(&out)
  162. cmd.SetErr(&errOut)
  163. err := cmd.Execute()
  164. if err == nil {
  165. t.Fatal("definitions generate = nil error, want a refusal to replace a stored definition")
  166. }
  167. if !strings.Contains(err.Error(), "--force") {
  168. t.Errorf("error = %q, want it to offer --force", err)
  169. }
  170. if got := mustRead(t, filepath.Join(dir, "test_board.json")); got != written {
  171. t.Errorf("stored file = %q, want it untouched (%q)", got, written)
  172. }
  173. }
  174. // The note beside the file is what carries the names, because a JSON file cannot
  175. // hold them: the tool would have to read comments and VIA's parser would reject
  176. // them. It has to say who wrote what, or a name is a guess wearing a count.
  177. func TestGeneratedNoteCarriesTheSpellingsAndWhoWroteThem(t *testing.T) {
  178. dir := t.TempDir()
  179. t.Cleanup(definitionFlagRestore(t))
  180. t.Cleanup(forceDefinitionsDir(t, dir))
  181. t.Cleanup(forceGenerateRestore(t))
  182. stubGenerateTarget(t, 0x1234, 0x5678, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
  183. cmd := NewKeyboardDefinitionsGenerateCmd()
  184. var out, errOut strings.Builder
  185. cmd.SetOut(&out)
  186. cmd.SetErr(&errOut)
  187. if err := cmd.Execute(); err != nil {
  188. t.Fatalf("definitions generate error = %v", err)
  189. }
  190. note := mustRead(t, strings.TrimSuffix(onlyDefinition(t, dir), ".json")+spottedNoteSuffix)
  191. if !strings.Contains(note, "rgb_matrix (channel 3), 46 slots, IDs 0 to 45") {
  192. t.Errorf("note = %q, want it to name the channel, the count and the ID range", note)
  193. }
  194. if !strings.Contains(note, string(slotsMeasured)) {
  195. t.Errorf("note = %q, want it to say where the slots came from", note)
  196. }
  197. // The measurement behind the names: a spelling, how many boards wrote it, and
  198. // which manufacturer most of them were.
  199. if !strings.Contains(note, "rainbow_moving_chevron") {
  200. t.Errorf("note = %q, want the spellings other definitions use", note)
  201. }
  202. if !strings.Contains(note, "boards:") {
  203. t.Errorf("note = %q, want a count of boards next to every name", note)
  204. }
  205. if !strings.Contains(note, "keychron") {
  206. t.Errorf("note = %q, want the manufacturer behind most of a name's spellings", note)
  207. }
  208. // Effect 23 is where the collection disagrees about what the number even is,
  209. // so the note has to show the runner-up rather than pick a winner.
  210. if !strings.Contains(note, "ID 23 ") {
  211. t.Errorf("note = %q, want a line for ID 23", note)
  212. }
  213. }
  214. func onlyDefinition(t *testing.T, dir string) string {
  215. t.Helper()
  216. matches, err := filepath.Glob(filepath.Join(dir, "*.json"))
  217. if err != nil {
  218. t.Fatal(err)
  219. }
  220. if len(matches) != 1 {
  221. t.Fatalf("definitions dir = %v, want one JSON file", matches)
  222. }
  223. return matches[0]
  224. }
  225. func mustRead(t *testing.T, path string) string {
  226. t.Helper()
  227. data, err := os.ReadFile(path)
  228. if err != nil {
  229. t.Fatal(err)
  230. }
  231. return string(data)
  232. }
  233. // A generated scaffold names no effect, so writing one for a board the binary
  234. // carries a definition for takes that board from 46 named effects to none — and
  235. // the file in the user directory is the one that is read. This is the whole
  236. // reason the built-in set is checked and not only the directory.
  237. func TestGenerateDoesNotShadowABuiltInDefinition(t *testing.T) {
  238. dir := t.TempDir()
  239. t.Cleanup(definitionFlagRestore(t))
  240. t.Cleanup(forceDefinitionsDir(t, dir))
  241. t.Cleanup(forceGenerateRestore(t))
  242. // The Impact 80, whose definition is built into the binary.
  243. stubGenerateTarget(t, 0x36B0, 0x309F, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
  244. builtIn := 0
  245. for _, def := range builtInDefinitions() {
  246. if def.Matches(0x36B0, 0x309F) {
  247. builtIn = namedEffectCount(def)
  248. }
  249. }
  250. if builtIn == 0 {
  251. t.Fatal("the binary carries no definition for 0x36B0/0x309F, so there is nothing to shadow")
  252. }
  253. cmd := NewKeyboardDefinitionsGenerateCmd()
  254. var out, errOut strings.Builder
  255. cmd.SetOut(&out)
  256. cmd.SetErr(&errOut)
  257. err := cmd.Execute()
  258. if err == nil {
  259. t.Fatal("definitions generate = nil error, want a refusal to shadow a built-in definition")
  260. }
  261. if !strings.Contains(err.Error(), "carries a definition") {
  262. t.Errorf("error = %q, want it to say the definition is one the binary carries", err)
  263. }
  264. if !strings.Contains(err.Error(), strconv.Itoa(builtIn)) {
  265. t.Errorf("error = %q, want it to name how many effects would be lost (%d)", err, builtIn)
  266. }
  267. if entries, _ := filepath.Glob(filepath.Join(dir, "*.json")); len(entries) != 0 {
  268. t.Errorf("definitions dir = %v, want nothing written", entries)
  269. }
  270. }
  271. // A Vial keyboard lists its own rgb_matrix effect IDs, and the tool must use
  272. // those rather than writing above the top: the list is the firmware answering
  273. // without being touched.
  274. func TestGenerateUsesVialsOwnListWhenTheFirmwareIsVial(t *testing.T) {
  275. dir := t.TempDir()
  276. t.Cleanup(definitionFlagRestore(t))
  277. t.Cleanup(forceDefinitionsDir(t, dir))
  278. t.Cleanup(forceGenerateRestore(t))
  279. original := openTarget
  280. t.Cleanup(func() { openTarget = original })
  281. openTarget = func(string) (rgbProtocol, targetDeviceData, []intvia.Channel, error) {
  282. stub := generateStub{
  283. tops: map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45, intvia.ChannelRgblight: 6},
  284. vial: true,
  285. vialIDs: []uint16{0, 1, 2, 40, 45},
  286. }
  287. return stub, stubTargetData(0x1234, 0x5678), []intvia.Channel{intvia.ChannelRgbMatrix, intvia.ChannelRgblight}, nil
  288. }
  289. cmd := NewKeyboardDefinitionsGenerateCmd()
  290. var out, errOut strings.Builder
  291. cmd.SetOut(&out)
  292. cmd.SetErr(&errOut)
  293. if err := cmd.Execute(); err != nil {
  294. t.Fatalf("definitions generate error = %v (stderr %q)", err, errOut.String())
  295. }
  296. if !strings.Contains(out.String(), "Vial firmware") {
  297. t.Errorf("stdout = %q, want it to say the keyboard is Vial", out.String())
  298. }
  299. if !strings.Contains(out.String(), experimentalVial) {
  300. t.Errorf("stdout = %q, want the Vial path marked %s", out.String(), experimentalVial)
  301. }
  302. // rgb_matrix comes from Vial and keeps the firmware's own numbering, gaps and
  303. // all; rgblight has no Vial list and falls back to the clamp.
  304. if !strings.Contains(out.String(), "0, 1, 2, 40, 45") {
  305. t.Errorf("stdout = %q, want the rgb_matrix slots in the firmware's numbering", out.String())
  306. }
  307. if !strings.Contains(out.String(), string(slotsReported)) || !strings.Contains(out.String(), string(slotsMeasured)) {
  308. t.Errorf("stdout = %q, want both sources named per channel", out.String())
  309. }
  310. // The note must not put QMK's spellings next to numbers that are not QMK's.
  311. note := mustRead(t, strings.TrimSuffix(onlyDefinition(t, dir), ".json")+spottedNoteSuffix)
  312. if strings.Contains(note, "rainbow_moving_chevron") {
  313. t.Errorf("note = %q, want no QMK spellings beside a Vial numbering", note)
  314. }
  315. if !strings.Contains(note, "VIALRGB_EFFECT_*") {
  316. t.Errorf("note = %q, want it to say the numbering is the firmware's own", note)
  317. }
  318. }
  319. // A Vial keyboard built without VIALRGB_ENABLE answers nothing, and a board that
  320. // cannot list its effects can still be asked by writing above the top.
  321. func TestGenerateFallsBackToTheClampWhenVialListsNothing(t *testing.T) {
  322. dir := t.TempDir()
  323. t.Cleanup(definitionFlagRestore(t))
  324. t.Cleanup(forceDefinitionsDir(t, dir))
  325. t.Cleanup(forceGenerateRestore(t))
  326. original := openTarget
  327. t.Cleanup(func() { openTarget = original })
  328. openTarget = func(string) (rgbProtocol, targetDeviceData, []intvia.Channel, error) {
  329. stub := generateStub{
  330. tops: map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45},
  331. vial: true,
  332. vialIDs: nil,
  333. }
  334. return stub, stubTargetData(0x1234, 0x5678), []intvia.Channel{intvia.ChannelRgbMatrix}, nil
  335. }
  336. cmd := NewKeyboardDefinitionsGenerateCmd()
  337. var out, errOut strings.Builder
  338. cmd.SetOut(&out)
  339. cmd.SetErr(&errOut)
  340. if err := cmd.Execute(); err != nil {
  341. t.Fatalf("definitions generate error = %v", err)
  342. }
  343. if !strings.Contains(out.String(), string(slotsMeasured)) {
  344. t.Errorf("stdout = %q, want the clamp used when Vial lists nothing", out.String())
  345. }
  346. note := mustRead(t, strings.TrimSuffix(onlyDefinition(t, dir), ".json")+spottedNoteSuffix)
  347. if !strings.Contains(note, "rainbow_moving_chevron") {
  348. t.Errorf("note = %q, want the QMK spellings again, which is what the clamp gives", note)
  349. }
  350. }