definition.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. // A definition is a property of a board, not of a lighting channel, so this
  58. // asks for the board alone and names no zone.
  59. target, err := prepareTarget("")
  60. if err != nil {
  61. return err
  62. }
  63. def, err := fetchDefinition(target.Device.VendorID, target.Device.ProductID)
  64. if err != nil {
  65. return err
  66. }
  67. dir, err := ensureDefinitionsDir()
  68. if err != nil {
  69. return err
  70. }
  71. path := filepath.Join(dir, definitionFileName(def))
  72. if err := os.WriteFile(path, []byte(def.raw), 0o644); err != nil {
  73. return fmt.Errorf("write %s: %w", path, err)
  74. }
  75. fmt.Fprintf(cmd.OutOrStdout(), "Saved definition for %s (0x%04X/0x%04X) to %s\n",
  76. def.Definition.Name, def.Definition.VendorID, def.Definition.ProductID, describeDataDir(path))
  77. for _, ch := range def.channels {
  78. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %d effects\n", ch.Subsystem(), len(def.Definition.Catalog.Effects(ch)))
  79. }
  80. return nil
  81. }
  82. func runKeyboardDefinitions(cmd *cobra.Command, args []string) error {
  83. dir := definitionsPath()
  84. // Both sources are listed, not just the directory: the file built into the
  85. // binary is where the names for a board that cannot be fetched come from, and
  86. // a listing that did not show it would say the tool has no definition for a
  87. // board it has one for.
  88. userDefs, dirErr := intrgb.LoadDefinitionsDir(dir)
  89. switch {
  90. case dirErr == nil, errors.Is(dirErr, os.ErrNotExist):
  91. // A directory that is not there yet is not an error: a user who has never
  92. // fetched one has none. A file inside it that cannot be read is, because
  93. // a definition the user placed and that does not work is worth saying.
  94. default:
  95. return dirErr
  96. }
  97. builtIn := builtInDefinitions()
  98. lines := make([]definitionLine, 0, len(userDefs)+len(builtIn))
  99. for _, def := range userDefs {
  100. lines = append(lines, definitionLineFor(def, "user"))
  101. }
  102. for _, def := range builtIn {
  103. lines = append(lines, definitionLineFor(def, "built-in"))
  104. }
  105. if jsonOutput {
  106. return encodeJSON(cmd.OutOrStdout(), struct {
  107. Directory string `json:"directory"`
  108. Definitions []definitionLine `json:"definitions"`
  109. }{Directory: dir, Definitions: lines})
  110. }
  111. if len(lines) == 0 {
  112. fmt.Fprintf(cmd.OutOrStdout(),
  113. "No definition files, in %s and none built into this binary\n", describeDataDir(dir))
  114. return nil
  115. }
  116. fmt.Fprintf(cmd.OutOrStdout(), "Definitions\n\n user %s\n built into this binary\n", describeDataDir(dir))
  117. for _, line := range lines {
  118. shadowed := ""
  119. if line.Source == "user" && isShadowed(line, builtIn) {
  120. shadowed = " (shadows the built-in copy)"
  121. }
  122. fmt.Fprintf(cmd.OutOrStdout(), "\n%s (%s/%s) %s %s%s\n",
  123. line.Name, line.VendorID, line.ProductID, line.Source, line.Path, shadowed)
  124. for _, ch := range line.Channels {
  125. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %-10s %d effects\n", ch.Name, ch.Subsystem, ch.Effects)
  126. }
  127. }
  128. return nil
  129. }
  130. // definitionLineFor is one definition file in the shape the list command reports.
  131. // The source is carried on the line because the path alone does not say where it
  132. // is: a file built into the binary has a path relative to the build, not one a
  133. // user can open.
  134. func definitionLineFor(def *intrgb.Definition, source string) definitionLine {
  135. line := definitionLine{
  136. Name: def.Name,
  137. VendorID: fmt.Sprintf("0x%04X", def.VendorID),
  138. ProductID: fmt.Sprintf("0x%04X", def.ProductID),
  139. Path: def.Path,
  140. Source: source,
  141. }
  142. for _, ch := range via.LightingChannels {
  143. effects := def.Catalog.Effects(ch)
  144. if len(effects) == 0 {
  145. continue
  146. }
  147. // The label is what VIA calls the channel, so the name here is the
  148. // name the user sees there. The subsystem stays as the fallback and
  149. // as the spelling that works everywhere.
  150. name := def.Labels[uint16(ch)]
  151. if name == "" {
  152. name = ch.Subsystem()
  153. }
  154. line.Channels = append(line.Channels, definitionChannel{
  155. Name: name,
  156. Subsystem: ch.Subsystem(),
  157. Channel: uint8(ch),
  158. Effects: len(effects),
  159. })
  160. }
  161. return line
  162. }
  163. // isShadowed reports whether the built-in set holds a definition for the same
  164. // board, which the file in the user directory overrides. Saying so is the point:
  165. // the two files disagree, and only one of them is read.
  166. func isShadowed(line definitionLine, builtIn []*intrgb.Definition) bool {
  167. for _, def := range builtIn {
  168. if fmt.Sprintf("0x%04X", def.VendorID) == line.VendorID &&
  169. fmt.Sprintf("0x%04X", def.ProductID) == line.ProductID {
  170. return true
  171. }
  172. }
  173. return false
  174. }
  175. // definitionLine is one definition file as the list command reports it. The
  176. // identifiers are hex strings, the way the files themselves spell them, so the
  177. // two can be compared by eye. Source is "user" for a file in the user directory
  178. // and "built-in" for one compiled into the binary, and it is what says which
  179. // file is read when both describe the same board.
  180. type definitionLine struct {
  181. Name string `json:"name"`
  182. VendorID string `json:"vendorId"`
  183. ProductID string `json:"productId"`
  184. Path string `json:"path"`
  185. Source string `json:"source"`
  186. Channels []definitionChannel `json:"channels"`
  187. }
  188. // definitionChannel is one lighting channel a definition names effects for.
  189. type definitionChannel struct {
  190. Name string `json:"name"`
  191. Subsystem string `json:"subsystem"`
  192. Channel uint8 `json:"channel"`
  193. Effects int `json:"effects"`
  194. }
  195. // fetchedDefinition is a definition together with the bytes it came from, so it
  196. // can be stored exactly as it was served.
  197. type fetchedDefinition struct {
  198. Definition *intrgb.Definition
  199. raw string
  200. channels []via.Channel
  201. }
  202. // fetchDefinition downloads the definition for a board. It is separate from the
  203. // command so the download and the checks can be tested on their own.
  204. func fetchDefinition(vendorID, productID uint16) (*fetchedDefinition, error) {
  205. vpid := intrgb.VendorProductID(vendorID, productID)
  206. var lastReason string
  207. for _, version := range []string{"v3", "v2"} {
  208. url := fmt.Sprintf("%s/definitions/%s/%d.json", definitionHost, version, vpid)
  209. body, status, err := httpGet(url)
  210. if err != nil {
  211. lastReason = err.Error()
  212. continue
  213. }
  214. if status != http.StatusOK {
  215. lastReason = fmt.Sprintf("HTTP %d", status)
  216. continue
  217. }
  218. def, err := intrgb.ParseDefinition(url, body)
  219. if err != nil {
  220. lastReason = "the server did not return a definition"
  221. continue
  222. }
  223. if !def.Matches(vendorID, productID) {
  224. lastReason = fmt.Sprintf("it is a definition for 0x%04X/0x%04X", def.VendorID, def.ProductID)
  225. continue
  226. }
  227. return &fetchedDefinition{
  228. Definition: def,
  229. raw: string(body),
  230. channels: via.LightingChannels,
  231. }, nil
  232. }
  233. return nil, fmt.Errorf("no definition for this keyboard (0x%04X/0x%04X) at %s: %s; "+
  234. "if the manufacturer publishes one, put it in %s or pass --definition",
  235. vendorID, productID, definitionHost, lastReason, ensureDefinitionsDirHint())
  236. }
  237. // ensureDefinitionsDirHint is the directory a message can name, with the user
  238. // directory named outright so the advice to put a file somewhere is actionable.
  239. // A directory that cannot be created is not this message's problem, so the
  240. // lookup is not created here.
  241. func ensureDefinitionsDirHint() string {
  242. return describeDataDir(definitionsPath())
  243. }
  244. // definitionFileName names a stored definition after the board, so a directory
  245. // of them is readable.
  246. func definitionFileName(def *fetchedDefinition) string {
  247. name := def.Definition.Name
  248. var b strings.Builder
  249. for _, r := range strings.ToLower(name) {
  250. switch {
  251. case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
  252. b.WriteRune(r)
  253. default:
  254. b.WriteRune('_')
  255. }
  256. }
  257. slug := strings.Trim(b.String(), "_")
  258. if slug == "" {
  259. slug = "keyboard"
  260. }
  261. return fmt.Sprintf("%s_0x%04X_0x%04X.json", slug, def.Definition.VendorID, def.Definition.ProductID)
  262. }