definition_generate.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/spf13/cobra"
  9. intrgb "netdome.biz/paul/qmk-rgb/internal/rgb"
  10. "netdome.biz/paul/qmk-rgb/internal/spotted"
  11. "netdome.biz/paul/qmk-rgb/internal/via"
  12. )
  13. // effectRangeProbe is what `keyboard definitions generate` needs from a
  14. // keyboard: the highest effect ID each channel takes, and a way to close it.
  15. // It is deliberately not a method on rgbProtocol, because that interface is what
  16. // every other command's test stub implements and a probe is not something
  17. // brightness and colour have to know about.
  18. type effectRangeProbe interface {
  19. EffectTop(via.Channel) (int, error)
  20. Close() error
  21. }
  22. // generateForce replaces a definition that is already stored. It is the same
  23. // rule `keyboard fetch` follows, for the same reason: the file may be one the
  24. // user has written themselves, and this command is the one they would have run
  25. // to write it.
  26. var generateForce bool
  27. // The value IDs a VIA lighting menu addresses, from quantum/via.h. They are the
  28. // same bytes on every lighting subsystem, which is why one scaffold covers every
  29. // channel.
  30. const (
  31. viaValueBrightness = 0x01
  32. viaValueEffect = 0x02
  33. viaValueSpeed = 0x03
  34. )
  35. // NewKeyboardDefinitionsGenerateCmd is `keyboard definitions generate`. It writes
  36. // a definition for a board that has none, with the effect slots the keyboard
  37. // reports and no names in them, plus a note beside it saying which spellings
  38. // other keyboards' definitions use for the same numbers.
  39. //
  40. // The names are the user's to write, and the command does not write them into
  41. // the definition: a name it put there would read as the manufacturer's own, and
  42. // nothing in a file can be read back off a keyboard to check it. An option with
  43. // an empty name is a slot without a name, so the channel reports no effects
  44. // until one is filled in — which is the honest state, and the same one a board
  45. // with no definition reports.
  46. func NewKeyboardDefinitionsGenerateCmd() *cobra.Command {
  47. cmd := &cobra.Command{
  48. Use: "generate",
  49. Short: "Write a definition for the connected keyboard, with the effect names left to you",
  50. Long: "Ask the keyboard how many effect IDs each of its lighting channels takes, then\n" +
  51. "write a definition file with one unnamed option per ID, and a note beside it\n" +
  52. "saying which spellings other keyboards' definitions use for the same numbers.\n\n" +
  53. "The names are yours to write: open the file and put one in each options entry,\n" +
  54. "and the channel starts resolving them. Nothing in a file can be read back off a\n" +
  55. "keyboard, so a name the tool wrote would be indistinguishable from the\n" +
  56. "manufacturer's, and a wrong name is worse than none: the tool reports an effect\n" +
  57. "as unknown and set by number until you fill it in.\n\n" +
  58. "A definition already stored for this keyboard is not replaced, because it is\n" +
  59. "probably the one you wrote. Edit it, or pass --force.",
  60. Args: cobra.NoArgs,
  61. RunE: runKeyboardDefinitionsGenerate,
  62. }
  63. cmd.Flags().BoolVar(&generateForce, "force", false,
  64. "Replace a definition that is already stored, discarding whatever that file holds")
  65. return cmd
  66. }
  67. func runKeyboardDefinitionsGenerate(cmd *cobra.Command, args []string) error {
  68. proto, target, channels, err := openTarget("")
  69. if err != nil {
  70. return err
  71. }
  72. defer proto.Close()
  73. probe, ok := proto.(effectRangeProbe)
  74. if !ok {
  75. return fmt.Errorf("this build cannot read a keyboard's effect range")
  76. }
  77. stored := storedDefinitionsFor(definitionsPath(), target.Device.VendorID, target.Device.ProductID)
  78. if len(stored) > 0 && !generateForce {
  79. return fmt.Errorf("a definition for %s (0x%04X/0x%04X) is already at %s; it is probably the one "+
  80. "you wrote, so generate does not replace it, use --force to overwrite it or edit that file",
  81. stored[0].Name, target.Device.VendorID, target.Device.ProductID, describeDataDir(stored[0].Path))
  82. }
  83. if len(channels) == 0 {
  84. return fmt.Errorf("this keyboard exposes no VIA lighting channels, so there is nothing to " +
  85. "generate a definition for")
  86. }
  87. name := scaffoldName(target.Device.Name)
  88. doc := scaffoldDefinition{
  89. Name: name,
  90. VendorID: fmt.Sprintf("0x%04X", target.Device.VendorID),
  91. ProductID: fmt.Sprintf("0x%04X", target.Device.ProductID),
  92. }
  93. notes := &strings.Builder{}
  94. tops := map[via.Channel]int{}
  95. for _, ch := range channels {
  96. top, err := probe.EffectTop(ch)
  97. if err != nil {
  98. return err
  99. }
  100. if menu := scaffoldMenu(ch, top); len(menu.Content) > 0 {
  101. doc.Menus = append(doc.Menus, menu)
  102. }
  103. tops[ch] = top
  104. writeCandidates(notes, ch, top)
  105. }
  106. dir, err := ensureDefinitionsDir()
  107. if err != nil {
  108. return err
  109. }
  110. base := definitionFileName(&fetchedDefinition{
  111. Definition: &intrgb.Definition{
  112. Name: name,
  113. VendorID: target.Device.VendorID,
  114. ProductID: target.Device.ProductID,
  115. },
  116. })
  117. encoded, err := json.MarshalIndent(doc, "", " ")
  118. if err != nil {
  119. return err
  120. }
  121. path := filepath.Join(dir, base)
  122. if err := os.WriteFile(path, append(encoded, '\n'), 0o644); err != nil {
  123. return fmt.Errorf("write %s: %w", path, err)
  124. }
  125. notePath := strings.TrimSuffix(path, ".json") + spottedNoteSuffix
  126. if err := os.WriteFile(notePath, []byte(notes.String()), 0o644); err != nil {
  127. return fmt.Errorf("write %s: %w", notePath, err)
  128. }
  129. verb := "Wrote"
  130. if len(stored) > 0 {
  131. verb = "Replaced"
  132. }
  133. fmt.Fprintf(cmd.OutOrStdout(), "%s a definition for %s (%s/%s) to %s\n",
  134. verb, doc.Name, doc.VendorID, doc.ProductID, describeDataDir(path))
  135. fmt.Fprintf(cmd.OutOrStdout(), "Every effect is an unnamed option. Open the file and write a name into each one:\n")
  136. for _, ch := range channels {
  137. if _, ok := intrgb.EffectValueKey(ch); !ok {
  138. continue
  139. }
  140. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %d slots, IDs 0 to %d\n", ch.Subsystem(), tops[ch]+1, tops[ch])
  141. }
  142. fmt.Fprintf(cmd.OutOrStdout(), "\nWhat other keyboards call the same numbers is in %s\n", describeDataDir(notePath))
  143. return nil
  144. }
  145. // spottedNoteSuffix names the note beside a generated definition. It is not a
  146. // .json file, so the definitions directory does not read it as one: it carries
  147. // no definition, only what was seen.
  148. const spottedNoteSuffix = ".spotted.txt"
  149. // scaffoldName is the board's name in a generated definition. A keyboard that
  150. // reports no product string gets a name that says so rather than an empty one,
  151. // which would match nothing and read as a broken file.
  152. func scaffoldName(productString string) string {
  153. if strings.TrimSpace(productString) == "" {
  154. return "Unnamed keyboard"
  155. }
  156. return productString
  157. }
  158. // scaffoldDefinition is the shape of a VIA definition with nothing in it yet.
  159. // The identifiers are the board's, so the file is matched to it the way any
  160. // other definition is.
  161. type scaffoldDefinition struct {
  162. Name string `json:"name"`
  163. // The identifiers are hex strings, which is how a definition file spells them
  164. // and how the parser reads them back. VIA's own served files carry the
  165. // packed number instead; both are read and this is the one a human edits.
  166. VendorID string `json:"vendorId"`
  167. ProductID string `json:"productId"`
  168. Menus []scaffoldMenuT `json:"menus"`
  169. }
  170. type scaffoldMenuT struct {
  171. Label string `json:"label"`
  172. Content []scaffoldEntry `json:"content"`
  173. }
  174. type scaffoldEntry struct {
  175. Label string `json:"label"`
  176. Type string `json:"type"`
  177. Content []any `json:"content"`
  178. Options any `json:"options,omitempty"`
  179. }
  180. // scaffoldMenu is one lighting channel as a VIA menu: the three controls the
  181. // value IDs name, with the effect list holding one unnamed option per slot. The
  182. // name is the channel's own, so the file names it the way the tool does rather
  183. // than inventing a label — a board the user fills in can rename it.
  184. func scaffoldMenu(ch via.Channel, top int) scaffoldMenuT {
  185. valueKey, ok := intrgb.EffectValueKey(ch)
  186. if !ok {
  187. // A channel with no registered value key has no list this tool reads, so
  188. // it is left out rather than written as something that would not load.
  189. return scaffoldMenuT{}
  190. }
  191. channel := int(ch)
  192. // The three controls address different value IDs under keys that share the
  193. // effect key's prefix, and the prefix ends where "_effect" starts. Trimming
  194. // the suffix and putting the underscore back is what keeps a key spelled
  195. // `id_qmk_rgb_matrix_brightness` rather than one the parser will not find.
  196. prefix := strings.TrimSuffix(valueKey, "_effect")
  197. options := make([][]any, 0, top+1)
  198. for id := 0; id <= top; id++ {
  199. // The empty name is the point: it states a slot without naming it, and the
  200. // parser skips it, so the channel reports no effects until a name is
  201. // written here.
  202. options = append(options, []any{"", id})
  203. }
  204. return scaffoldMenuT{
  205. Label: ch.Subsystem(),
  206. Content: []scaffoldEntry{
  207. {
  208. Label: "Brightness",
  209. Type: "range",
  210. Content: []any{prefix + "_brightness", channel, viaValueBrightness},
  211. Options: []any{0, 255},
  212. },
  213. {
  214. Label: "Effect",
  215. Type: "dropdown",
  216. Content: []any{valueKey, channel, viaValueEffect},
  217. Options: options,
  218. },
  219. {
  220. Label: "Effect Speed",
  221. Type: "range",
  222. Content: []any{prefix + "_effect_speed", channel, viaValueSpeed},
  223. Options: []any{0, 255},
  224. },
  225. },
  226. }
  227. }
  228. // writeCandidates records what other keyboards' definitions were seen to call
  229. // each ID, with the counts and the manufacturer, because a name without those is
  230. // a guess wearing a number.
  231. func writeCandidates(out *strings.Builder, ch via.Channel, top int) {
  232. valueKey, ok := intrgb.EffectValueKey(ch)
  233. if !ok {
  234. return
  235. }
  236. fmt.Fprintf(out, "\n%s (channel %d), IDs 0 to %d\n", ch.Subsystem(), ch, top)
  237. seen := 0
  238. for id := 0; id <= top; id++ {
  239. obs, ok := spotted.Candidates(valueKey, id)
  240. if !ok {
  241. continue
  242. }
  243. seen++
  244. names := make([]string, 0, len(obs.Candidates))
  245. for _, c := range obs.Candidates {
  246. names = append(names, fmt.Sprintf("%s (%d)", c.Name, c.Count))
  247. }
  248. line := fmt.Sprintf(" ID %-3d seen on %3d boards: %s", id, obs.Boards, strings.Join(names, ", "))
  249. if obs.TopVendor != "" && obs.TopVendorCount > 0 {
  250. line += fmt.Sprintf(" most of them %s (%d)", obs.TopVendor, obs.TopVendorCount)
  251. }
  252. fmt.Fprintln(out, line)
  253. }
  254. if seen == 0 {
  255. fmt.Fprintf(out, " no definition anywhere names an effect on this channel\n")
  256. }
  257. }