definition_generate.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strconv"
  7. "strings"
  8. "github.com/spf13/cobra"
  9. intdevice "netdome.biz/paul/qmk-rgb/internal/device"
  10. intrgb "netdome.biz/paul/qmk-rgb/internal/rgb"
  11. "netdome.biz/paul/qmk-rgb/internal/spotted"
  12. "netdome.biz/paul/qmk-rgb/internal/via"
  13. )
  14. // effectRangeProbe is what `keyboard definitions generate` needs from a keyboard:
  15. // the effect IDs each channel takes, a way to close it, and the two Vial calls
  16. // that may answer the question without writing to it.
  17. //
  18. // It is deliberately not a method on rgbProtocol, because that interface is what
  19. // every other command's test stub implements and a probe is not something
  20. // brightness and colour have to know about.
  21. type effectRangeProbe interface {
  22. EffectTop(via.Channel) (int, error)
  23. VialVersion() (uint32, bool, error)
  24. VialEffectIDs() ([]uint16, error)
  25. Close() error
  26. }
  27. // slotsFrom is where a channel's effect slots came from. It is reported per
  28. // channel because the two answers are not the same kind of thing: one is the
  29. // firmware listing what it compiled in, the other is the firmware's answer to a
  30. // value written above the top.
  31. type slotsFrom string
  32. const (
  33. // slotsMeasured means the range was found by writing above the top and
  34. // reading back what the firmware clamped to.
  35. slotsMeasured slotsFrom = "measured by clamping"
  36. // slotsReported means the firmware listed them itself, which is Vial's
  37. // vialrgb_get_supported and nothing else.
  38. slotsReported slotsFrom = "reported by the firmware"
  39. )
  40. // experimentalVial marks the Vial path. It is written from Vial's source and
  41. // tested against a scripted keyboard, and nobody has run it against a Vial
  42. // keyboard, so every command that uses it says so rather than presenting an
  43. // unverified answer as a measurement. Remove the word when a real one has.
  44. const experimentalVial = "experimental"
  45. // generateForce replaces a definition that is already stored. It is the same
  46. // rule `keyboard fetch` follows, for the same reason: the file may be one the
  47. // user has written themselves, and this command is the one they would have run
  48. // to write it.
  49. var generateForce bool
  50. // The value IDs a VIA lighting menu addresses, from quantum/via.h. They are the
  51. // same bytes on every lighting subsystem, which is why one scaffold covers every
  52. // channel.
  53. const (
  54. viaValueBrightness = 0x01
  55. viaValueEffect = 0x02
  56. viaValueSpeed = 0x03
  57. )
  58. // NewKeyboardDefinitionsGenerateCmd is `keyboard definitions generate`. It writes
  59. // a names file for the connected board: one line per effect ID the keyboard
  60. // reports, with no names in them, plus a note beside it saying which spellings
  61. // other keyboards' definitions use for the same numbers.
  62. //
  63. // It writes a names file and not a definition file, because a definition belongs
  64. // to the manufacturer. Writing one meant authoring a menu description for
  65. // someone else's keyboard and handing the user a nested JSON array to type a
  66. // single name into, and a name the tool put in a file it had written itself would
  67. // read as the manufacturer's own. A names file is flat — a channel, an effect ID
  68. // and a name — and it overrides the definition where it has one, so the same
  69. // command starts a board nobody published a file for and corrects a name on a
  70. // board they did.
  71. //
  72. // The names are the user's to write. A name is the one value this tool cannot
  73. // read back off a keyboard, so a name the tool chose would be indistinguishable
  74. // from one the board's vendor published. An empty name states a slot without
  75. // naming it, and is skipped, so the channel reports no effects until one is
  76. // filled in.
  77. func NewKeyboardDefinitionsGenerateCmd() *cobra.Command {
  78. cmd := &cobra.Command{
  79. Use: "generate",
  80. Short: "Write a names file for the connected keyboard, with the effect names left to you",
  81. Long: experimentalVial + ": the Vial path below has not been run against a Vial keyboard.\n\n" +
  82. "Ask the keyboard how many effect IDs each of its lighting channels takes, then\n" +
  83. "write a names file with one line per ID and no name in it, and a note beside it\n" +
  84. "saying which spellings other keyboards' definitions use for the same numbers.\n\n" +
  85. "The names are yours to write: open the file and put one on each line, and the\n" +
  86. "channel starts resolving them. A name you write for an ID the board's definition\n" +
  87. "also names replaces that one name and leaves the rest alone, so this also corrects\n" +
  88. "a board whose definition this tool has.\n\n" +
  89. "A names file already stored for this keyboard is not replaced, because it is\n" +
  90. "probably the one you wrote. Edit it, or pass --force.\n\n" +
  91. "A keyboard running Vial firmware is asked for its rgb_matrix effect IDs instead of\n" +
  92. "being written to, which is the better answer, and it numbers them in its own\n" +
  93. "namespace rather than QMK's. Every channel says where its slots came from.",
  94. Args: cobra.NoArgs,
  95. RunE: runKeyboardDefinitionsGenerate,
  96. }
  97. cmd.Flags().BoolVar(&generateForce, "force", false,
  98. "Replace a definition that is already stored, discarding whatever that file holds")
  99. return cmd
  100. }
  101. func runKeyboardDefinitionsGenerate(cmd *cobra.Command, args []string) error {
  102. proto, target, channels, err := openTarget("")
  103. if err != nil {
  104. return err
  105. }
  106. defer proto.Close()
  107. probe, ok := proto.(effectRangeProbe)
  108. if !ok {
  109. return fmt.Errorf("this build cannot read a keyboard's effect range")
  110. }
  111. stored := storedNamesFor(target.Device.VendorID, target.Device.ProductID)
  112. if len(stored) > 0 && !generateForce {
  113. return fmt.Errorf("a names file for 0x%04X/0x%04X is already at %s; it is probably the one you "+
  114. "wrote, so generate does not replace it, use --force to overwrite it or edit that file",
  115. target.Device.VendorID, target.Device.ProductID, describeDataDir(stored[0].Path))
  116. }
  117. if len(channels) == 0 {
  118. return fmt.Errorf("this keyboard exposes no VIA lighting channels, so there is nothing to " +
  119. "generate a definition for")
  120. }
  121. name := scaffoldName(target.Device.Name)
  122. doc := scaffoldDefinition{
  123. Name: name,
  124. VendorID: fmt.Sprintf("0x%04X", target.Device.VendorID),
  125. ProductID: fmt.Sprintf("0x%04X", target.Device.ProductID),
  126. }
  127. notes := &strings.Builder{}
  128. // Vial can list the rgb_matrix effect IDs without the keyboard being written
  129. // to. It is asked first because its answer is the better one, and only where
  130. // the firmware serves it: VIALRGB_ENABLE is a build option, and a Vial
  131. // keyboard without it answers nothing.
  132. version, isVial, err := probe.VialVersion()
  133. if err != nil {
  134. return err
  135. }
  136. if isVial {
  137. fmt.Fprintf(cmd.OutOrStdout(), "This keyboard answers as Vial firmware, protocol version %d (%s: not run against real hardware)\n",
  138. version, experimentalVial)
  139. }
  140. sources := map[via.Channel]slotsFrom{}
  141. slots := map[via.Channel][]uint16{}
  142. for _, ch := range channels {
  143. ids, from, err := slotsFor(probe, ch, isVial)
  144. if err != nil {
  145. return err
  146. }
  147. if menu := scaffoldMenu(ch, ids); len(menu.Content) > 0 {
  148. doc.Menus = append(doc.Menus, menu)
  149. }
  150. sources[ch] = from
  151. slots[ch] = ids
  152. writeCandidates(notes, ch, ids, from)
  153. }
  154. dir, err := ensureNamesDir()
  155. if err != nil {
  156. return err
  157. }
  158. path := filepath.Join(dir, namesFileName(target.Device))
  159. body, err := renderNamesFile(name, target.Device, slots)
  160. if err != nil {
  161. return err
  162. }
  163. if err := os.WriteFile(path, body, 0o644); err != nil {
  164. return fmt.Errorf("write %s: %w", path, err)
  165. }
  166. notePath := strings.TrimSuffix(path, ".json") + spottedNoteSuffix
  167. if err := os.WriteFile(notePath, []byte(notes.String()), 0o644); err != nil {
  168. return fmt.Errorf("write %s: %w", notePath, err)
  169. }
  170. verb := "Wrote"
  171. if len(stored) > 0 {
  172. verb = "Replaced"
  173. }
  174. fmt.Fprintf(cmd.OutOrStdout(), "%s a names file for %s (%04X/%04X) to %s\n",
  175. verb, name, target.Device.VendorID, target.Device.ProductID, describeDataDir(path))
  176. fmt.Fprintf(cmd.OutOrStdout(), "Every effect is a line with no name in it. Open the file and write one in:\n")
  177. for _, ch := range channels {
  178. ids, ok := slots[ch]
  179. if !ok {
  180. continue
  181. }
  182. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %d slots, IDs %s (%s)\n",
  183. ch.Subsystem(), len(ids), describeSlotRange(ids), sources[ch])
  184. }
  185. fmt.Fprintf(cmd.OutOrStdout(), "\nWhat other keyboards call the same numbers is in %s\n", describeDataDir(notePath))
  186. if def := loadedDefinition(target.Device.VendorID, target.Device.ProductID); def != nil {
  187. fmt.Fprintf(cmd.OutOrStdout(), "\nThis board also has a definition naming %d effects; a name you write here\nreplaces that one name and leaves the others alone.\n", namedEffectCount(def))
  188. }
  189. return nil
  190. }
  191. // spottedNoteSuffix names the note beside a generated definition. It is not a
  192. // .json file, so the definitions directory does not read it as one: it carries
  193. // no definition, only what was seen.
  194. const spottedNoteSuffix = ".spotted.txt"
  195. // scaffoldName is the board's name in a generated definition. A keyboard that
  196. // reports no product string gets a name that says so rather than an empty one,
  197. // which would match nothing and read as a broken file.
  198. func scaffoldName(productString string) string {
  199. if strings.TrimSpace(productString) == "" {
  200. return "Unnamed keyboard"
  201. }
  202. return productString
  203. }
  204. // scaffoldDefinition is the shape of a VIA definition with nothing in it yet.
  205. // The identifiers are the board's, so the file is matched to it the way any
  206. // other definition is.
  207. type scaffoldDefinition struct {
  208. Name string `json:"name"`
  209. // The identifiers are hex strings, which is how a definition file spells them
  210. // and how the parser reads them back. VIA's own served files carry the
  211. // packed number instead; both are read and this is the one a human edits.
  212. VendorID string `json:"vendorId"`
  213. ProductID string `json:"productId"`
  214. Menus []scaffoldMenuT `json:"menus"`
  215. }
  216. type scaffoldMenuT struct {
  217. Label string `json:"label"`
  218. Content []scaffoldEntry `json:"content"`
  219. }
  220. type scaffoldEntry struct {
  221. Label string `json:"label"`
  222. Type string `json:"type"`
  223. Content []any `json:"content"`
  224. Options any `json:"options,omitempty"`
  225. }
  226. // slotsFor returns the effect IDs a channel has and where that came from.
  227. //
  228. // Vial is asked only for rgb_matrix, because VialRGB is an rgb_matrix extension:
  229. // there is no Vial list for backlight, rgblight, audio or led_matrix, and those
  230. // keep the clamping answer. A Vial keyboard without VIALRGB_ENABLE answers
  231. // nothing, which is an error rather than an empty list, and it falls back to the
  232. // measurement because a board that cannot list its effects can still be asked.
  233. func slotsFor(probe effectRangeProbe, ch via.Channel, isVial bool) ([]uint16, slotsFrom, error) {
  234. if isVial && ch == via.ChannelRgbMatrix {
  235. ids, err := probe.VialEffectIDs()
  236. if err == nil && len(ids) > 0 {
  237. return ids, slotsReported, nil
  238. }
  239. if err != nil {
  240. fmt.Fprintf(os.Stderr, "vialrgb effect list on %s unavailable (%v), falling back to the clamp\n", ch.Subsystem(), err)
  241. }
  242. }
  243. top, err := probe.EffectTop(ch)
  244. if err != nil {
  245. return nil, "", err
  246. }
  247. ids := make([]uint16, 0, top+1)
  248. for id := 0; id <= top; id++ {
  249. ids = append(ids, uint16(id))
  250. }
  251. return ids, slotsMeasured, nil
  252. }
  253. // describeSlotRange writes a list of IDs as a range when it is one, because
  254. // "0 to 45" says in six characters what a list of forty-six does not.
  255. func describeSlotRange(ids []uint16) string {
  256. if len(ids) == 0 {
  257. return "none"
  258. }
  259. runs := true
  260. for i := 1; i < len(ids); i++ {
  261. if ids[i] != ids[i-1]+1 {
  262. runs = false
  263. break
  264. }
  265. }
  266. if runs {
  267. return fmt.Sprintf("%d to %d", ids[0], ids[len(ids)-1])
  268. }
  269. shown := ids
  270. if len(shown) > 8 {
  271. shown = append(append([]uint16{}, ids[:8]...), 0xFFFF)
  272. }
  273. parts := make([]string, 0, len(shown))
  274. for _, id := range shown {
  275. if id == 0xFFFF {
  276. parts = append(parts, "...")
  277. continue
  278. }
  279. parts = append(parts, strconv.Itoa(int(id)))
  280. }
  281. return strings.Join(parts, ", ")
  282. }
  283. // scaffoldMenu is one lighting channel as a VIA menu: the three controls the
  284. // value IDs name, with the effect list holding one unnamed option per slot. The
  285. // name is the channel's own, so the file names it the way the tool does rather
  286. // than inventing a label — a board the user fills in can rename it.
  287. func scaffoldMenu(ch via.Channel, ids []uint16) scaffoldMenuT {
  288. valueKey, ok := intrgb.EffectValueKey(ch)
  289. if !ok {
  290. // A channel with no registered value key has no list this tool reads, so
  291. // it is left out rather than written as something that would not load.
  292. return scaffoldMenuT{}
  293. }
  294. channel := int(ch)
  295. // The three controls address different value IDs under keys that share the
  296. // effect key's prefix, and the prefix ends where "_effect" starts. Trimming
  297. // the suffix and putting the underscore back is what keeps a key spelled
  298. // `id_qmk_rgb_matrix_brightness` rather than one the parser will not find.
  299. prefix := strings.TrimSuffix(valueKey, "_effect")
  300. options := make([][]any, 0, len(ids))
  301. for _, id := range ids {
  302. // The empty name is the point: it states a slot without naming it, and the
  303. // parser skips it, so the channel reports no effects until a name is
  304. // written here.
  305. options = append(options, []any{"", id})
  306. }
  307. return scaffoldMenuT{
  308. Label: ch.Subsystem(),
  309. Content: []scaffoldEntry{
  310. {
  311. Label: "Brightness",
  312. Type: "range",
  313. Content: []any{prefix + "_brightness", channel, viaValueBrightness},
  314. Options: []any{0, 255},
  315. },
  316. {
  317. Label: "Effect",
  318. Type: "dropdown",
  319. Content: []any{valueKey, channel, viaValueEffect},
  320. Options: options,
  321. },
  322. {
  323. Label: "Effect Speed",
  324. Type: "range",
  325. Content: []any{prefix + "_effect_speed", channel, viaValueSpeed},
  326. Options: []any{0, 255},
  327. },
  328. },
  329. }
  330. }
  331. // writeCandidates records what other keyboards' definitions were seen to call
  332. // each ID, with the counts and the manufacturer, because a name without those is
  333. // a guess wearing a number.
  334. func writeCandidates(out *strings.Builder, ch via.Channel, ids []uint16, from slotsFrom) {
  335. valueKey, ok := intrgb.EffectValueKey(ch)
  336. if !ok {
  337. return
  338. }
  339. fmt.Fprintf(out, "\n%s (channel %d), %d slots, IDs %s (%s)\n",
  340. ch.Subsystem(), ch, len(ids), describeSlotRange(ids), from)
  341. if from == slotsReported {
  342. // The firmware that listed these numbers numbers them in its own
  343. // namespace, and the measurement below is QMK's. Saying "here is what
  344. // other boards call ID 7" next to a slot that is not QMK's ID 7 is the one
  345. // thing this note must not do.
  346. fmt.Fprintf(out, " These IDs are the firmware's own numbering, not QMK's: the list the firmware sends\n")
  347. fmt.Fprintf(out, " is VIALRGB_EFFECT_* and the translation to QMK's stays inside the firmware. The\n")
  348. fmt.Fprintf(out, " spellings other keyboards use are indexed by QMK's numbers, so they are not listed here.\n")
  349. return
  350. }
  351. seen := 0
  352. for _, id := range ids {
  353. obs, ok := spotted.Candidates(valueKey, int(id))
  354. if !ok {
  355. continue
  356. }
  357. seen++
  358. names := make([]string, 0, len(obs.Candidates))
  359. for _, c := range obs.Candidates {
  360. names = append(names, fmt.Sprintf("%s (%d)", c.Name, c.Count))
  361. }
  362. line := fmt.Sprintf(" ID %-3d seen on %3d boards: %s", id, obs.Boards, strings.Join(names, ", "))
  363. if obs.TopVendor != "" && obs.TopVendorCount > 0 {
  364. line += fmt.Sprintf(" most of them %s (%d)", obs.TopVendor, obs.TopVendorCount)
  365. }
  366. fmt.Fprintln(out, line)
  367. }
  368. if seen == 0 {
  369. fmt.Fprintf(out, " no definition anywhere names an effect on this channel\n")
  370. }
  371. }
  372. // namedEffectCount is how many effects a definition names across the channels it
  373. // covers. A file is a board's whole catalog, so the number the user loses is the
  374. // total and not the largest channel.
  375. func namedEffectCount(def *intrgb.Definition) int {
  376. total := 0
  377. for _, ch := range via.LightingChannels {
  378. total += len(def.Catalog.Effects(ch))
  379. }
  380. return total
  381. }
  382. // storedNamesFor returns the names files already in the per-user directory that
  383. // describe a board.
  384. func storedNamesFor(vendorID, productID uint16) []*intrgb.Names {
  385. var out []*intrgb.Names
  386. for _, names := range candidateNames() {
  387. if names.Matches(vendorID, productID) {
  388. out = append(out, names)
  389. }
  390. }
  391. return out
  392. }
  393. // namesFileName names a names file after the board, the same way a definition
  394. // file is named so that a directory of either is readable.
  395. func namesFileName(device intdevice.Device) string {
  396. var b strings.Builder
  397. for _, r := range strings.ToLower(device.Name) {
  398. switch {
  399. case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
  400. b.WriteRune(r)
  401. default:
  402. b.WriteRune('_')
  403. }
  404. }
  405. slug := strings.Trim(b.String(), "_")
  406. if slug == "" {
  407. slug = "keyboard"
  408. }
  409. return fmt.Sprintf("%s_0x%04X_0x%04X.json", slug, device.VendorID, device.ProductID)
  410. }
  411. // renderNamesFile writes the file as a person edits it: one effect ID per line,
  412. // with an empty name to fill in. A generated file therefore has no names in it
  413. // and the board reports none, which is the state it was in before the file
  414. // existed. The keys are written in ID order because that is the order a person
  415. // works through them in, and the channels in channel order for the same reason.
  416. func renderNamesFile(name string, device intdevice.Device, slots map[via.Channel][]uint16) ([]byte, error) {
  417. var b strings.Builder
  418. fmt.Fprintf(&b, "{\n")
  419. // The kind is what tells a names file apart from a definition file. Both are
  420. // JSON, both carry the board's identifiers, and a names file in a definitions
  421. // directory would otherwise parse as a definition and take the board's place.
  422. fmt.Fprintf(&b, " \"kind\": %q,\n", intrgb.NamesFileKind)
  423. fmt.Fprintf(&b, " \"name\": %q,\n", name)
  424. fmt.Fprintf(&b, " \"vendorId\": \"0x%04X\",\n", device.VendorID)
  425. fmt.Fprintf(&b, " \"productId\": \"0x%04X\",\n", device.ProductID)
  426. fmt.Fprintf(&b, " \"channels\": {\n")
  427. written := 0
  428. for _, ch := range via.LightingChannels {
  429. ids, ok := slots[ch]
  430. if !ok || len(ids) == 0 {
  431. continue
  432. }
  433. if written > 0 {
  434. fmt.Fprintf(&b, ",\n")
  435. }
  436. written++
  437. fmt.Fprintf(&b, " %q: {\n", ch.Subsystem())
  438. for i, id := range ids {
  439. comma := ","
  440. if i == len(ids)-1 {
  441. comma = ""
  442. }
  443. fmt.Fprintf(&b, " \"%d\": \"%s\"%s\n", id, "", comma)
  444. }
  445. fmt.Fprintf(&b, " }")
  446. }
  447. fmt.Fprintf(&b, "\n }\n}\n")
  448. return []byte(b.String()), nil
  449. }