| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389 |
- package main
- import (
- "encoding/json"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "testing"
- intrgb "netdome.biz/paul/qmk-rgb/internal/rgb"
- intvia "netdome.biz/paul/qmk-rgb/internal/via"
- )
- // generateStub is a keyboard that answers an effect range, so the generated
- // scaffold can be checked without hardware. The Vial fields are what a keyboard
- // running Vial firmware would answer; zero versions read as a keyboard that is
- // not Vial.
- type generateStub struct {
- tops map[intvia.Channel]int
- vial bool
- vialIDs []uint16
- vialErr error
- }
- func (g generateStub) VialVersion() (uint32, bool, error) {
- if !g.vial {
- return 0, false, nil
- }
- return 6, true, nil
- }
- func (g generateStub) VialEffectIDs() ([]uint16, error) {
- if g.vialErr != nil {
- return nil, g.vialErr
- }
- return g.vialIDs, nil
- }
- func (g generateStub) EffectTop(ch intvia.Channel) (int, error) {
- return g.tops[ch], nil
- }
- func (g generateStub) GetValue(intvia.Channel, uint8) ([]byte, error) { return []byte{0}, nil }
- func (g generateStub) SetValue(intvia.Channel, uint8, uint8) error { return nil }
- func (g generateStub) SetColor(intvia.Channel, uint8, uint8) error { return nil }
- func (g generateStub) DetectChannels() ([]intvia.Channel, error) { return nil, nil }
- func (g generateStub) Close() error { return nil }
- // stubGenerateTarget makes the connected keyboard a fixed one. The identifiers
- // are a parameter because a board the binary carries a definition for is the
- // case `generate` has to refuse, and a stub for the wrong board would test
- // nothing.
- func stubGenerateTarget(t *testing.T, vendorID, productID uint16, channels []intvia.Channel, tops map[intvia.Channel]int) {
- t.Helper()
- original := openTarget
- t.Cleanup(func() { openTarget = original })
- openTarget = func(string) (rgbProtocol, targetDeviceData, []intvia.Channel, error) {
- return generateStub{tops: tops}, stubTargetData(vendorID, productID), channels, nil
- }
- }
- func forceGenerateRestore(t *testing.T) func() {
- t.Helper()
- original := generateForce
- return func() { generateForce = original }
- }
- // The whole point of the command: a generated file names no effect, so a board
- // with a generated definition reports the same "no names" it reported before one
- // existed. A scaffold that claimed names would be a guess the tool could not
- // read back off the keyboard.
- func TestGeneratedDefinitionNamesNoEffectUntilTheUserFillsItIn(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceGenerateRestore(t))
- stubGenerateTarget(t, 0x1234, 0x5678, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
- cmd := NewKeyboardDefinitionsGenerateCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("definitions generate error = %v (stderr %q)", err, errOut.String())
- }
- path := onlyDefinition(t, dir)
- def, err := intrgb.ParseDefinition(path, []byte(mustRead(t, path)))
- if err != nil {
- t.Fatalf("ParseDefinition(%s) error = %v; the generated file has to load", path, err)
- }
- if got := len(def.Catalog.Effects(intvia.ChannelRgbMatrix)); got != 0 {
- t.Errorf("effects on rgb_matrix = %d, want 0 until the names are written in", got)
- }
- // The slots are still there, which is the other half: the file states which
- // IDs exist and leaves the naming to the user.
- var file struct {
- Menus []struct {
- Content []struct {
- Label string `json:"label"`
- Type string `json:"type"`
- Content []any `json:"content"`
- Options []any `json:"options"`
- } `json:"content"`
- } `json:"menus"`
- }
- if err := json.Unmarshal([]byte(mustRead(t, path)), &file); err != nil {
- t.Fatalf("unmarshal generated file: %v", err)
- }
- var options []any
- for _, menu := range file.Menus {
- for _, entry := range menu.Content {
- if entry.Type == "dropdown" {
- options = entry.Options
- }
- }
- }
- if len(options) != 46 {
- t.Fatalf("effect options = %d, want 46, one per ID from 0 to 45", len(options))
- }
- for i, option := range options {
- pair, ok := option.([]any)
- if !ok || len(pair) != 2 {
- t.Fatalf("option %d = %v, want a name and a number", i, option)
- }
- if name, _ := pair[0].(string); name != "" {
- t.Errorf("option %d is named %q, want a slot with no name", i, name)
- }
- if number, _ := pair[1].(float64); int(number) != i {
- t.Errorf("option %d carries ID %v, want the slot numbered %d", i, pair[1], i)
- }
- }
- // Every control has to be addressed by a value key the parser recognises. A
- // key built by trimming a suffix and appending without the underscore is
- // `id_qmk_rgb_matrixbrightness`, which names nothing, and nothing in the
- // output above would say so.
- wantKeys := map[string]bool{
- "id_qmk_rgb_matrix_brightness": false,
- "id_qmk_rgb_matrix_effect": false,
- "id_qmk_rgb_matrix_effect_speed": false,
- }
- for _, menu := range file.Menus {
- for _, entry := range menu.Content {
- key, _ := entry.Content[0].(string)
- if _, ok := wantKeys[key]; !ok {
- t.Errorf("control %q is addressed by %q, which is not a VIA value key", entry.Label, key)
- continue
- }
- wantKeys[key] = true
- }
- }
- for key, found := range wantKeys {
- if !found {
- t.Errorf("no control addresses %q", key)
- }
- }
- }
- // A definition a user has written is the one command they would have run to write
- // it, so it must survive a second run of the command.
- func TestGenerateDoesNotReplaceAStoredDefinition(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceGenerateRestore(t))
- stubGenerateTarget(t, 0x1234, 0x5678, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
- written := `{"name":"Test Board","vendorId":"0x1234","productId":"0x5678","menus":[],"note":"hand written"}`
- if err := os.WriteFile(filepath.Join(dir, "test_board.json"), []byte(written), 0o644); err != nil {
- t.Fatal(err)
- }
- cmd := NewKeyboardDefinitionsGenerateCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- err := cmd.Execute()
- if err == nil {
- t.Fatal("definitions generate = nil error, want a refusal to replace a stored definition")
- }
- if !strings.Contains(err.Error(), "--force") {
- t.Errorf("error = %q, want it to offer --force", err)
- }
- if got := mustRead(t, filepath.Join(dir, "test_board.json")); got != written {
- t.Errorf("stored file = %q, want it untouched (%q)", got, written)
- }
- }
- // The note beside the file is what carries the names, because a JSON file cannot
- // hold them: the tool would have to read comments and VIA's parser would reject
- // them. It has to say who wrote what, or a name is a guess wearing a count.
- func TestGeneratedNoteCarriesTheSpellingsAndWhoWroteThem(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceGenerateRestore(t))
- stubGenerateTarget(t, 0x1234, 0x5678, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
- cmd := NewKeyboardDefinitionsGenerateCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("definitions generate error = %v", err)
- }
- note := mustRead(t, strings.TrimSuffix(onlyDefinition(t, dir), ".json")+spottedNoteSuffix)
- if !strings.Contains(note, "rgb_matrix (channel 3), 46 slots, IDs 0 to 45") {
- t.Errorf("note = %q, want it to name the channel, the count and the ID range", note)
- }
- if !strings.Contains(note, string(slotsMeasured)) {
- t.Errorf("note = %q, want it to say where the slots came from", note)
- }
- // The measurement behind the names: a spelling, how many boards wrote it, and
- // which manufacturer most of them were.
- if !strings.Contains(note, "rainbow_moving_chevron") {
- t.Errorf("note = %q, want the spellings other definitions use", note)
- }
- if !strings.Contains(note, "boards:") {
- t.Errorf("note = %q, want a count of boards next to every name", note)
- }
- if !strings.Contains(note, "keychron") {
- t.Errorf("note = %q, want the manufacturer behind most of a name's spellings", note)
- }
- // Effect 23 is where the collection disagrees about what the number even is,
- // so the note has to show the runner-up rather than pick a winner.
- if !strings.Contains(note, "ID 23 ") {
- t.Errorf("note = %q, want a line for ID 23", note)
- }
- }
- func onlyDefinition(t *testing.T, dir string) string {
- t.Helper()
- matches, err := filepath.Glob(filepath.Join(dir, "*.json"))
- if err != nil {
- t.Fatal(err)
- }
- if len(matches) != 1 {
- t.Fatalf("definitions dir = %v, want one JSON file", matches)
- }
- return matches[0]
- }
- func mustRead(t *testing.T, path string) string {
- t.Helper()
- data, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- return string(data)
- }
- // A generated scaffold names no effect, so writing one for a board the binary
- // carries a definition for takes that board from 46 named effects to none — and
- // the file in the user directory is the one that is read. This is the whole
- // reason the built-in set is checked and not only the directory.
- func TestGenerateDoesNotShadowABuiltInDefinition(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceGenerateRestore(t))
- // The Impact 80, whose definition is built into the binary.
- stubGenerateTarget(t, 0x36B0, 0x309F, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
- builtIn := 0
- for _, def := range builtInDefinitions() {
- if def.Matches(0x36B0, 0x309F) {
- builtIn = namedEffectCount(def)
- }
- }
- if builtIn == 0 {
- t.Fatal("the binary carries no definition for 0x36B0/0x309F, so there is nothing to shadow")
- }
- cmd := NewKeyboardDefinitionsGenerateCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- err := cmd.Execute()
- if err == nil {
- t.Fatal("definitions generate = nil error, want a refusal to shadow a built-in definition")
- }
- if !strings.Contains(err.Error(), "carries a definition") {
- t.Errorf("error = %q, want it to say the definition is one the binary carries", err)
- }
- if !strings.Contains(err.Error(), strconv.Itoa(builtIn)) {
- t.Errorf("error = %q, want it to name how many effects would be lost (%d)", err, builtIn)
- }
- if entries, _ := filepath.Glob(filepath.Join(dir, "*.json")); len(entries) != 0 {
- t.Errorf("definitions dir = %v, want nothing written", entries)
- }
- }
- // A Vial keyboard lists its own rgb_matrix effect IDs, and the tool must use
- // those rather than writing above the top: the list is the firmware answering
- // without being touched.
- func TestGenerateUsesVialsOwnListWhenTheFirmwareIsVial(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceGenerateRestore(t))
- original := openTarget
- t.Cleanup(func() { openTarget = original })
- openTarget = func(string) (rgbProtocol, targetDeviceData, []intvia.Channel, error) {
- stub := generateStub{
- tops: map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45, intvia.ChannelRgblight: 6},
- vial: true,
- vialIDs: []uint16{0, 1, 2, 40, 45},
- }
- return stub, stubTargetData(0x1234, 0x5678), []intvia.Channel{intvia.ChannelRgbMatrix, intvia.ChannelRgblight}, nil
- }
- cmd := NewKeyboardDefinitionsGenerateCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("definitions generate error = %v (stderr %q)", err, errOut.String())
- }
- if !strings.Contains(out.String(), "Vial firmware") {
- t.Errorf("stdout = %q, want it to say the keyboard is Vial", out.String())
- }
- if !strings.Contains(out.String(), experimentalVial) {
- t.Errorf("stdout = %q, want the Vial path marked %s", out.String(), experimentalVial)
- }
- // rgb_matrix comes from Vial and keeps the firmware's own numbering, gaps and
- // all; rgblight has no Vial list and falls back to the clamp.
- if !strings.Contains(out.String(), "0, 1, 2, 40, 45") {
- t.Errorf("stdout = %q, want the rgb_matrix slots in the firmware's numbering", out.String())
- }
- if !strings.Contains(out.String(), string(slotsReported)) || !strings.Contains(out.String(), string(slotsMeasured)) {
- t.Errorf("stdout = %q, want both sources named per channel", out.String())
- }
- // The note must not put QMK's spellings next to numbers that are not QMK's.
- note := mustRead(t, strings.TrimSuffix(onlyDefinition(t, dir), ".json")+spottedNoteSuffix)
- if strings.Contains(note, "rainbow_moving_chevron") {
- t.Errorf("note = %q, want no QMK spellings beside a Vial numbering", note)
- }
- if !strings.Contains(note, "VIALRGB_EFFECT_*") {
- t.Errorf("note = %q, want it to say the numbering is the firmware's own", note)
- }
- }
- // A Vial keyboard built without VIALRGB_ENABLE answers nothing, and a board that
- // cannot list its effects can still be asked by writing above the top.
- func TestGenerateFallsBackToTheClampWhenVialListsNothing(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceGenerateRestore(t))
- original := openTarget
- t.Cleanup(func() { openTarget = original })
- openTarget = func(string) (rgbProtocol, targetDeviceData, []intvia.Channel, error) {
- stub := generateStub{
- tops: map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45},
- vial: true,
- vialIDs: nil,
- }
- return stub, stubTargetData(0x1234, 0x5678), []intvia.Channel{intvia.ChannelRgbMatrix}, nil
- }
- cmd := NewKeyboardDefinitionsGenerateCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("definitions generate error = %v", err)
- }
- if !strings.Contains(out.String(), string(slotsMeasured)) {
- t.Errorf("stdout = %q, want the clamp used when Vial lists nothing", out.String())
- }
- note := mustRead(t, strings.TrimSuffix(onlyDefinition(t, dir), ".json")+spottedNoteSuffix)
- if !strings.Contains(note, "rainbow_moving_chevron") {
- t.Errorf("note = %q, want the QMK spellings again, which is what the clamp gives", note)
- }
- }
|