definition.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. // forceFetch replaces a definition that is already stored. It is the only way to
  30. // do so, because a file in the user directory may be one the user has edited and
  31. // nothing on disk says which it is.
  32. var forceFetch bool
  33. // NewKeyboardFetchCmd is `keyboard fetch`. It belongs to the keyboard command
  34. // because what it fetches belongs to a board: the file is looked up by the
  35. // board's vendor and product ID, so there is nothing to fetch without one.
  36. func NewKeyboardFetchCmd() *cobra.Command {
  37. cmd := &cobra.Command{
  38. Use: "fetch",
  39. Short: "Download the definition file for the connected keyboard",
  40. Long: "Identify the connected keyboard, then download its VIA definition into the\n" +
  41. "data directory. VIA does not carry a definition for every board, and answers\n" +
  42. "an unknown one with its own web page, so a downloaded file is parsed and\n" +
  43. "matched against the keyboard before it is stored.\n\n" +
  44. "A definition that is already stored for this keyboard is not replaced, because\n" +
  45. "it may be one you have edited. Edit that file, or pass --force to overwrite it.",
  46. Args: cobra.NoArgs,
  47. RunE: runKeyboardFetch,
  48. }
  49. cmd.Flags().BoolVar(&forceFetch, "force", false,
  50. "Replace a definition that is already stored, discarding whatever that file holds")
  51. return cmd
  52. }
  53. // NewKeyboardDefinitionsCmd is `keyboard definitions`, and the name is the noun
  54. // rather than a verb on purpose. `keyboard list` reads as listing the
  55. // keyboards, which is what `keyboard info` does, and the root already has a
  56. // `list` that means the profile store; one verb must not mean two stores.
  57. func NewKeyboardDefinitionsCmd() *cobra.Command {
  58. return &cobra.Command{
  59. Use: "definitions",
  60. Short: "List the definition files in the data directory, and those built in",
  61. Args: cobra.NoArgs,
  62. RunE: runKeyboardDefinitions,
  63. }
  64. }
  65. func runKeyboardFetch(cmd *cobra.Command, args []string) error {
  66. // A definition is a property of a board, not of a lighting channel, so this
  67. // asks for the board alone and names no zone.
  68. target, err := prepareTarget("")
  69. if err != nil {
  70. return err
  71. }
  72. dir, err := ensureDefinitionsDir()
  73. if err != nil {
  74. return err
  75. }
  76. // The check comes before the download, so a user whose definition is already
  77. // there is told so without waiting on the network and without the answer
  78. // depending on VIA still carrying the board. It matches by content rather
  79. // than by file name, because what identifies a definition is the vendor and
  80. // product ID inside it and the name of the file is only a label.
  81. stored := storedDefinitionsFor(dir, target.Device.VendorID, target.Device.ProductID)
  82. if len(stored) > 0 && !forceFetch {
  83. return fmt.Errorf("a definition for %s (0x%04X/0x%04X) is already at %s; it may hold your "+
  84. "edits, so fetch does not replace it, use --force to overwrite it or edit that file",
  85. stored[0].Name, target.Device.VendorID, target.Device.ProductID, describeDataDir(stored[0].Path))
  86. }
  87. def, err := fetchDefinition(target.Device.VendorID, target.Device.ProductID)
  88. if err != nil {
  89. return err
  90. }
  91. path := filepath.Join(dir, definitionFileName(def))
  92. if err := os.WriteFile(path, []byte(def.raw), 0o644); err != nil {
  93. return fmt.Errorf("write %s: %w", path, err)
  94. }
  95. // A definition that was replaced under a different file name is removed
  96. // rather than left standing beside the new one: two files describing one
  97. // board leave which of them is read to the order the directory happens to
  98. // come back in. The removal follows the write, so a write that failed keeps
  99. // what was there.
  100. for _, old := range stored {
  101. if old.Path == path {
  102. continue
  103. }
  104. if err := os.Remove(old.Path); err != nil {
  105. return fmt.Errorf("remove replaced %s: %w", old.Path, err)
  106. }
  107. }
  108. verb := "Saved"
  109. if len(stored) > 0 {
  110. verb = "Replaced"
  111. }
  112. fmt.Fprintf(cmd.OutOrStdout(), "%s definition for %s (0x%04X/0x%04X) to %s\n",
  113. verb, def.Definition.Name, def.Definition.VendorID, def.Definition.ProductID, describeDataDir(path))
  114. for _, ch := range def.channels {
  115. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %d effects\n", ch.Subsystem(), len(def.Definition.Catalog.Effects(ch)))
  116. }
  117. return nil
  118. }
  119. // storedDefinitionsFor returns the definitions the user directory already holds
  120. // for a board. It is a slice because two files can describe one board: the
  121. // vendor issues the same vendor and product ID to two models, which
  122. // definitions/README.md records, and only one of the two files is read.
  123. //
  124. // A directory that cannot be read is not an answer. A file in it may be
  125. // unreadable, and "nothing stored" is what a fetch acts on, so an unreadable
  126. // directory leaves the fetch to write rather than refuse.
  127. func storedDefinitionsFor(dir string, vendorID, productID uint16) []*intrgb.Definition {
  128. defs, err := intrgb.LoadDefinitionsDir(dir)
  129. if err != nil {
  130. return nil
  131. }
  132. var out []*intrgb.Definition
  133. for _, def := range defs {
  134. if def.Matches(vendorID, productID) {
  135. out = append(out, def)
  136. }
  137. }
  138. return out
  139. }
  140. func runKeyboardDefinitions(cmd *cobra.Command, args []string) error {
  141. dir := definitionsPath()
  142. // Both sources are listed, not just the directory: the file built into the
  143. // binary is where the names for a board that cannot be fetched come from, and
  144. // a listing that did not show it would say the tool has no definition for a
  145. // board it has one for.
  146. userDefs, dirErr := intrgb.LoadDefinitionsDir(dir)
  147. switch {
  148. case dirErr == nil, errors.Is(dirErr, os.ErrNotExist):
  149. // A directory that is not there yet is not an error: a user who has never
  150. // fetched one has none. A file inside it that cannot be read is, because
  151. // a definition the user placed and that does not work is worth saying.
  152. default:
  153. return dirErr
  154. }
  155. builtIn := builtInDefinitions()
  156. lines := make([]definitionLine, 0, len(userDefs)+len(builtIn))
  157. for _, def := range userDefs {
  158. lines = append(lines, definitionLineFor(def, "user"))
  159. }
  160. for _, def := range builtIn {
  161. lines = append(lines, definitionLineFor(def, "built-in"))
  162. }
  163. if jsonOutput {
  164. return encodeJSON(cmd.OutOrStdout(), struct {
  165. Directory string `json:"directory"`
  166. Definitions []definitionLine `json:"definitions"`
  167. }{Directory: dir, Definitions: lines})
  168. }
  169. if len(lines) == 0 {
  170. fmt.Fprintf(cmd.OutOrStdout(),
  171. "No definition files, in %s and none built into this binary\n", describeDataDir(dir))
  172. return nil
  173. }
  174. fmt.Fprintf(cmd.OutOrStdout(), "Definitions\n\n user %s\n built into this binary\n", describeDataDir(dir))
  175. for _, line := range lines {
  176. shadowed := ""
  177. if line.Source == "user" && isShadowed(line, builtIn) {
  178. shadowed = " (shadows the built-in copy)"
  179. }
  180. fmt.Fprintf(cmd.OutOrStdout(), "\n%s (%s/%s) %s %s%s\n",
  181. line.Name, line.VendorID, line.ProductID, line.Source, line.Path, shadowed)
  182. for _, ch := range line.Channels {
  183. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %-10s %d effects\n", ch.Name, ch.Subsystem, ch.Effects)
  184. }
  185. }
  186. return nil
  187. }
  188. // definitionLineFor is one definition file in the shape the list command reports.
  189. // The source is carried on the line because the path alone does not say where it
  190. // is: a file built into the binary has a path relative to the build, not one a
  191. // user can open.
  192. func definitionLineFor(def *intrgb.Definition, source string) definitionLine {
  193. line := definitionLine{
  194. Name: def.Name,
  195. VendorID: fmt.Sprintf("0x%04X", def.VendorID),
  196. ProductID: fmt.Sprintf("0x%04X", def.ProductID),
  197. Path: def.Path,
  198. Source: source,
  199. }
  200. for _, ch := range via.LightingChannels {
  201. effects := def.Catalog.Effects(ch)
  202. if len(effects) == 0 {
  203. continue
  204. }
  205. // The label is what VIA calls the channel, so the name here is the
  206. // name the user sees there. The subsystem stays as the fallback and
  207. // as the spelling that works everywhere.
  208. name := def.Labels[uint16(ch)]
  209. if name == "" {
  210. name = ch.Subsystem()
  211. }
  212. line.Channels = append(line.Channels, definitionChannel{
  213. Name: name,
  214. Subsystem: ch.Subsystem(),
  215. Channel: uint8(ch),
  216. Effects: len(effects),
  217. })
  218. }
  219. return line
  220. }
  221. // isShadowed reports whether the built-in set holds a definition for the same
  222. // board, which the file in the user directory overrides. Saying so is the point:
  223. // the two files disagree, and only one of them is read.
  224. func isShadowed(line definitionLine, builtIn []*intrgb.Definition) bool {
  225. for _, def := range builtIn {
  226. if fmt.Sprintf("0x%04X", def.VendorID) == line.VendorID &&
  227. fmt.Sprintf("0x%04X", def.ProductID) == line.ProductID {
  228. return true
  229. }
  230. }
  231. return false
  232. }
  233. // definitionLine is one definition file as the list command reports it. The
  234. // identifiers are hex strings, the way the files themselves spell them, so the
  235. // two can be compared by eye. Source is "user" for a file in the user directory
  236. // and "built-in" for one compiled into the binary, and it is what says which
  237. // file is read when both describe the same board.
  238. type definitionLine struct {
  239. Name string `json:"name"`
  240. VendorID string `json:"vendorId"`
  241. ProductID string `json:"productId"`
  242. Path string `json:"path"`
  243. Source string `json:"source"`
  244. Channels []definitionChannel `json:"channels"`
  245. }
  246. // definitionChannel is one lighting channel a definition names effects for.
  247. type definitionChannel struct {
  248. Name string `json:"name"`
  249. Subsystem string `json:"subsystem"`
  250. Channel uint8 `json:"channel"`
  251. Effects int `json:"effects"`
  252. }
  253. // fetchedDefinition is a definition together with the bytes it came from, so it
  254. // can be stored exactly as it was served.
  255. type fetchedDefinition struct {
  256. Definition *intrgb.Definition
  257. raw string
  258. channels []via.Channel
  259. }
  260. // fetchDefinition downloads the definition for a board. It is separate from the
  261. // command so the download and the checks can be tested on their own.
  262. func fetchDefinition(vendorID, productID uint16) (*fetchedDefinition, error) {
  263. vpid := intrgb.VendorProductID(vendorID, productID)
  264. var lastReason string
  265. for _, version := range []string{"v3", "v2"} {
  266. url := fmt.Sprintf("%s/definitions/%s/%d.json", definitionHost, version, vpid)
  267. body, status, err := httpGet(url)
  268. if err != nil {
  269. lastReason = err.Error()
  270. continue
  271. }
  272. if status != http.StatusOK {
  273. lastReason = fmt.Sprintf("HTTP %d", status)
  274. continue
  275. }
  276. def, err := intrgb.ParseDefinition(url, body)
  277. if err != nil {
  278. lastReason = "the server did not return a definition"
  279. continue
  280. }
  281. if !def.Matches(vendorID, productID) {
  282. lastReason = fmt.Sprintf("it is a definition for 0x%04X/0x%04X", def.VendorID, def.ProductID)
  283. continue
  284. }
  285. return &fetchedDefinition{
  286. Definition: def,
  287. raw: string(body),
  288. channels: via.LightingChannels,
  289. }, nil
  290. }
  291. return nil, fmt.Errorf("no definition for this keyboard (0x%04X/0x%04X) at %s: %s; "+
  292. "if the manufacturer publishes one, put it in %s or pass --definition",
  293. vendorID, productID, definitionHost, lastReason, ensureDefinitionsDirHint())
  294. }
  295. // ensureDefinitionsDirHint is the directory a message can name, with the user
  296. // directory named outright so the advice to put a file somewhere is actionable.
  297. // A directory that cannot be created is not this message's problem, so the
  298. // lookup is not created here.
  299. func ensureDefinitionsDirHint() string {
  300. return describeDataDir(definitionsPath())
  301. }
  302. // definitionFileName names a stored definition after the board, so a directory
  303. // of them is readable.
  304. func definitionFileName(def *fetchedDefinition) string {
  305. name := def.Definition.Name
  306. var b strings.Builder
  307. for _, r := range strings.ToLower(name) {
  308. switch {
  309. case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
  310. b.WriteRune(r)
  311. default:
  312. b.WriteRune('_')
  313. }
  314. }
  315. slug := strings.Trim(b.String(), "_")
  316. if slug == "" {
  317. slug = "keyboard"
  318. }
  319. return fmt.Sprintf("%s_0x%04X_0x%04X.json", slug, def.Definition.VendorID, def.Definition.ProductID)
  320. }