definition.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "github.com/spf13/cobra"
  11. intrgb "netdome.biz/paul/qmk-rgb/internal/rgb"
  12. "netdome.biz/paul/qmk-rgb/internal/via"
  13. )
  14. // definitionHost serves the definitions VIA ships, one file per board, named by
  15. // vendor and product ID. The path segment is the definition generation, not the
  16. // protocol version: a board gets v3 and falls back to v2.
  17. const definitionHost = "https://www.usevia.app"
  18. // httpGet is a seam so a fetch can be tested without a network. It returns the
  19. // body and the status code.
  20. var httpGet = func(url string) ([]byte, int, error) {
  21. resp, err := http.Get(url)
  22. if err != nil {
  23. return nil, 0, err
  24. }
  25. defer resp.Body.Close()
  26. body, err := io.ReadAll(resp.Body)
  27. return body, resp.StatusCode, err
  28. }
  29. // NewKeyboardFetchCmd is `keyboard fetch`. It belongs to the keyboard command
  30. // because what it fetches belongs to a board: the file is looked up by the
  31. // board's vendor and product ID, so there is nothing to fetch without one.
  32. func NewKeyboardFetchCmd() *cobra.Command {
  33. return &cobra.Command{
  34. Use: "fetch",
  35. Short: "Download the definition file for the connected keyboard",
  36. Long: "Identify the connected keyboard, then download its VIA definition into the\n" +
  37. "data directory. VIA does not carry a definition for every board, and answers\n" +
  38. "an unknown one with its own web page, so a downloaded file is parsed and\n" +
  39. "matched against the keyboard before it is stored.",
  40. Args: cobra.NoArgs,
  41. RunE: runKeyboardFetch,
  42. }
  43. }
  44. // NewKeyboardDefinitionsCmd is `keyboard definitions`, and the name is the noun
  45. // rather than a verb on purpose. `keyboard list` reads as listing the
  46. // keyboards, which is what `keyboard info` does, and the root already has a
  47. // `list` that means the profile store; one verb must not mean two stores.
  48. func NewKeyboardDefinitionsCmd() *cobra.Command {
  49. return &cobra.Command{
  50. Use: "definitions",
  51. Short: "List the definition files in the data directory, and those built in",
  52. Args: cobra.NoArgs,
  53. RunE: runKeyboardDefinitions,
  54. }
  55. }
  56. func runKeyboardFetch(cmd *cobra.Command, args []string) error {
  57. target, err := prepareTarget()
  58. if err != nil {
  59. return err
  60. }
  61. def, err := fetchDefinition(target.Device.VendorID, target.Device.ProductID)
  62. if err != nil {
  63. return err
  64. }
  65. dir, err := ensureDefinitionsDir()
  66. if err != nil {
  67. return err
  68. }
  69. path := filepath.Join(dir, definitionFileName(def))
  70. if err := os.WriteFile(path, []byte(def.raw), 0o644); err != nil {
  71. return fmt.Errorf("write %s: %w", path, err)
  72. }
  73. fmt.Fprintf(cmd.OutOrStdout(), "Saved definition for %s (0x%04X/0x%04X) to %s\n",
  74. def.Definition.Name, def.Definition.VendorID, def.Definition.ProductID, describeDataDir(path))
  75. for _, ch := range def.channels {
  76. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %d effects\n", ch.Subsystem(), len(def.Definition.Catalog.Effects(ch)))
  77. }
  78. return nil
  79. }
  80. func runKeyboardDefinitions(cmd *cobra.Command, args []string) error {
  81. dir := definitionsPath()
  82. // Both sources are listed, not just the directory: the file built into the
  83. // binary is where the names for a board that cannot be fetched come from, and
  84. // a listing that did not show it would say the tool has no definition for a
  85. // board it has one for.
  86. userDefs, dirErr := intrgb.LoadDefinitionsDir(dir)
  87. switch {
  88. case dirErr == nil, errors.Is(dirErr, os.ErrNotExist):
  89. // A directory that is not there yet is not an error: a user who has never
  90. // fetched one has none. A file inside it that cannot be read is, because
  91. // a definition the user placed and that does not work is worth saying.
  92. default:
  93. return dirErr
  94. }
  95. builtIn := builtInDefinitions()
  96. lines := make([]definitionLine, 0, len(userDefs)+len(builtIn))
  97. for _, def := range userDefs {
  98. lines = append(lines, definitionLineFor(def, "user"))
  99. }
  100. for _, def := range builtIn {
  101. lines = append(lines, definitionLineFor(def, "built-in"))
  102. }
  103. if jsonOutput {
  104. return encodeJSON(cmd.OutOrStdout(), struct {
  105. Directory string `json:"directory"`
  106. Definitions []definitionLine `json:"definitions"`
  107. }{Directory: dir, Definitions: lines})
  108. }
  109. if len(lines) == 0 {
  110. fmt.Fprintf(cmd.OutOrStdout(),
  111. "No definition files, in %s and none built into this binary\n", describeDataDir(dir))
  112. return nil
  113. }
  114. fmt.Fprintf(cmd.OutOrStdout(), "Definitions\n\n user %s\n built into this binary\n", describeDataDir(dir))
  115. for _, line := range lines {
  116. shadowed := ""
  117. if line.Source == "user" && isShadowed(line, builtIn) {
  118. shadowed = " (shadows the built-in copy)"
  119. }
  120. fmt.Fprintf(cmd.OutOrStdout(), "\n%s (%s/%s) %s %s%s\n",
  121. line.Name, line.VendorID, line.ProductID, line.Source, line.Path, shadowed)
  122. for _, ch := range line.Channels {
  123. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %-10s %d effects\n", ch.Name, ch.Subsystem, ch.Effects)
  124. }
  125. }
  126. return nil
  127. }
  128. // definitionLineFor is one definition file in the shape the list command reports.
  129. // The source is carried on the line because the path alone does not say where it
  130. // is: a file built into the binary has a path relative to the build, not one a
  131. // user can open.
  132. func definitionLineFor(def *intrgb.Definition, source string) definitionLine {
  133. line := definitionLine{
  134. Name: def.Name,
  135. VendorID: fmt.Sprintf("0x%04X", def.VendorID),
  136. ProductID: fmt.Sprintf("0x%04X", def.ProductID),
  137. Path: def.Path,
  138. Source: source,
  139. }
  140. for _, ch := range via.LightingChannels {
  141. effects := def.Catalog.Effects(ch)
  142. if len(effects) == 0 {
  143. continue
  144. }
  145. // The label is what VIA calls the channel, so the name here is the
  146. // name the user sees there. The subsystem stays as the fallback and
  147. // as the spelling that works everywhere.
  148. name := def.Labels[uint16(ch)]
  149. if name == "" {
  150. name = ch.Subsystem()
  151. }
  152. line.Channels = append(line.Channels, definitionChannel{
  153. Name: name,
  154. Subsystem: ch.Subsystem(),
  155. Channel: uint8(ch),
  156. Effects: len(effects),
  157. })
  158. }
  159. return line
  160. }
  161. // isShadowed reports whether the built-in set holds a definition for the same
  162. // board, which the file in the user directory overrides. Saying so is the point:
  163. // the two files disagree, and only one of them is read.
  164. func isShadowed(line definitionLine, builtIn []*intrgb.Definition) bool {
  165. for _, def := range builtIn {
  166. if fmt.Sprintf("0x%04X", def.VendorID) == line.VendorID &&
  167. fmt.Sprintf("0x%04X", def.ProductID) == line.ProductID {
  168. return true
  169. }
  170. }
  171. return false
  172. }
  173. // definitionLine is one definition file as the list command reports it. The
  174. // identifiers are hex strings, the way the files themselves spell them, so the
  175. // two can be compared by eye. Source is "user" for a file in the user directory
  176. // and "built-in" for one compiled into the binary, and it is what says which
  177. // file is read when both describe the same board.
  178. type definitionLine struct {
  179. Name string `json:"name"`
  180. VendorID string `json:"vendorId"`
  181. ProductID string `json:"productId"`
  182. Path string `json:"path"`
  183. Source string `json:"source"`
  184. Channels []definitionChannel `json:"channels"`
  185. }
  186. // definitionChannel is one lighting channel a definition names effects for.
  187. type definitionChannel struct {
  188. Name string `json:"name"`
  189. Subsystem string `json:"subsystem"`
  190. Channel uint8 `json:"channel"`
  191. Effects int `json:"effects"`
  192. }
  193. // fetchedDefinition is a definition together with the bytes it came from, so it
  194. // can be stored exactly as it was served.
  195. type fetchedDefinition struct {
  196. Definition *intrgb.Definition
  197. raw string
  198. channels []via.Channel
  199. }
  200. // fetchDefinition downloads the definition for a board. It is separate from the
  201. // command so the download and the checks can be tested on their own.
  202. func fetchDefinition(vendorID, productID uint16) (*fetchedDefinition, error) {
  203. vpid := intrgb.VendorProductID(vendorID, productID)
  204. var lastReason string
  205. for _, version := range []string{"v3", "v2"} {
  206. url := fmt.Sprintf("%s/definitions/%s/%d.json", definitionHost, version, vpid)
  207. body, status, err := httpGet(url)
  208. if err != nil {
  209. lastReason = err.Error()
  210. continue
  211. }
  212. if status != http.StatusOK {
  213. lastReason = fmt.Sprintf("HTTP %d", status)
  214. continue
  215. }
  216. def, err := intrgb.ParseDefinition(url, body)
  217. if err != nil {
  218. lastReason = "the server did not return a definition"
  219. continue
  220. }
  221. if !def.Matches(vendorID, productID) {
  222. lastReason = fmt.Sprintf("it is a definition for 0x%04X/0x%04X", def.VendorID, def.ProductID)
  223. continue
  224. }
  225. return &fetchedDefinition{
  226. Definition: def,
  227. raw: string(body),
  228. channels: via.LightingChannels,
  229. }, nil
  230. }
  231. return nil, fmt.Errorf("no definition for this keyboard (0x%04X/0x%04X) at %s: %s; "+
  232. "if the manufacturer publishes one, put it in %s or pass --definition",
  233. vendorID, productID, definitionHost, lastReason, ensureDefinitionsDirHint())
  234. }
  235. // ensureDefinitionsDirHint is the directory a message can name, with the user
  236. // directory named outright so the advice to put a file somewhere is actionable.
  237. // A directory that cannot be created is not this message's problem, so the
  238. // lookup is not created here.
  239. func ensureDefinitionsDirHint() string {
  240. return describeDataDir(definitionsPath())
  241. }
  242. // definitionFileName names a stored definition after the board, so a directory
  243. // of them is readable.
  244. func definitionFileName(def *fetchedDefinition) string {
  245. name := def.Definition.Name
  246. var b strings.Builder
  247. for _, r := range strings.ToLower(name) {
  248. switch {
  249. case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
  250. b.WriteRune(r)
  251. default:
  252. b.WriteRune('_')
  253. }
  254. }
  255. slug := strings.Trim(b.String(), "_")
  256. if slug == "" {
  257. slug = "keyboard"
  258. }
  259. return fmt.Sprintf("%s_0x%04X_0x%04X.json", slug, def.Definition.VendorID, def.Definition.ProductID)
  260. }