profile.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "sort"
  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. type Profile struct {
  15. Name string `json:"name"`
  16. Version int `json:"version"`
  17. Board *Board `json:"board,omitempty"`
  18. Zones map[string]*ZoneSettings `json:"zones"`
  19. }
  20. // Board identifies the keyboard a profile was saved from. A profile stores
  21. // effect names, and names belong to a board, so without this a profile written
  22. // for one keyboard would be applied to another without a word. The pair is
  23. // spelled as hex strings, the way the VIA definition files
  24. // spell it, so the three can be read side by side.
  25. type Board struct {
  26. VendorID string `json:"vendorId"`
  27. ProductID string `json:"productId"`
  28. }
  29. // boardMatch is what comparing a profile's board to the connected one tells us.
  30. type boardMatch int
  31. const (
  32. // boardUnknown is a profile written before profiles carried a board.
  33. boardUnknown boardMatch = iota
  34. boardSame
  35. boardOther
  36. )
  37. func boardFor(vendorID, productID uint16) *Board {
  38. return &Board{
  39. VendorID: fmt.Sprintf("0x%04X", vendorID),
  40. ProductID: fmt.Sprintf("0x%04X", productID),
  41. }
  42. }
  43. // MatchesBoard reports whether a profile was saved from the connected keyboard,
  44. // was saved from another one, or says nothing about it.
  45. func (p *Profile) MatchesBoard(vendorID, productID uint16) boardMatch {
  46. if p == nil || p.Board == nil {
  47. return boardUnknown
  48. }
  49. if strings.EqualFold(p.Board.VendorID, fmt.Sprintf("0x%04X", vendorID)) &&
  50. strings.EqualFold(p.Board.ProductID, fmt.Sprintf("0x%04X", productID)) {
  51. return boardSame
  52. }
  53. return boardOther
  54. }
  55. // boardMismatchWarning says which profile belongs to which keyboard, because
  56. // the user has to be able to tell which of their profiles is the wrong one.
  57. func (p *Profile) boardMismatchWarning(vendorID, productID uint16) string {
  58. return fmt.Sprintf("Warning: profile %q was saved for keyboard %s/%s, and this keyboard is %s/%s; "+
  59. "its effect names may not exist here\n",
  60. p.Name, p.Board.VendorID, p.Board.ProductID,
  61. fmt.Sprintf("0x%04X", vendorID), fmt.Sprintf("0x%04X", productID))
  62. }
  63. // listLine is one profile as the list command prints it.
  64. func (p *Profile) listLine() string {
  65. if p.Board == nil {
  66. return p.Name
  67. }
  68. return fmt.Sprintf("%s %s/%s", p.Name, p.Board.VendorID, p.Board.ProductID)
  69. }
  70. type ZoneSettings struct {
  71. Enabled bool `json:"enabled"`
  72. Effect string `json:"effect"`
  73. Brightness uint8 `json:"brightness"`
  74. Speed uint8 `json:"speed"`
  75. Color string `json:"color"`
  76. }
  77. // ProfilesPath is the directory the profiles live in.
  78. func ProfilesPath() string {
  79. return profilesPath()
  80. }
  81. // profileFileName is the file a name maps to, without a directory.
  82. func profileFileName(name string) string {
  83. return sanitizeFilename(name) + ".json"
  84. }
  85. // resolveProfileTarget maps one profile argument to the file it names, and to the
  86. // name a profile written there should carry.
  87. //
  88. // An argument ending in .json is a path and is used exactly as given, so
  89. // `load profiles/lava.json` reads that file and `save ./lava.json` writes it. It
  90. // is not a search: the argument names the file, so there is nothing to search
  91. // for, and the same argument names the same file from any working directory.
  92. // The suffix is matched without regard to case so the rule is the same on Linux,
  93. // macOS and Windows, and the file system rather than this code decides whether the
  94. // case is right. No separator is looked for — the Windows file API takes both `/`
  95. // and `\`, so a check for either would be a platform difference with no behaviour
  96. // behind it — and nothing here joins the path to a directory, so a path the
  97. // operating system rejects fails as itself rather than as a name.
  98. //
  99. // Every other argument is a profile name, and a name lives in the per-user
  100. // directory: profilesPath and the sanitized file name. A name is the only way in
  101. // there, and an argument that names a file is never also a name — which is what
  102. // keeps a .json argument from also resolving to `lala-json.json`.
  103. func resolveProfileTarget(arg string) (path string, name string, isPath bool) {
  104. if !strings.HasSuffix(strings.ToLower(arg), ".json") {
  105. return filepath.Join(profilesPath(), profileFileName(arg)), arg, false
  106. }
  107. base := filepath.Base(arg)
  108. return arg, strings.TrimSuffix(base, filepath.Ext(base)), true
  109. }
  110. // Save writes the profile into the per-user directory under its own name, which is
  111. // what every caller that has a name and no path means.
  112. func (p *Profile) Save() error {
  113. return p.saveTo(filepath.Join(profilesPath(), profileFileName(p.Name)))
  114. }
  115. // saveTo writes the profile to one file and creates the directory it is in. It
  116. // resolves nothing: the caller decides where the file goes, so that the rule that
  117. // decides is the only one there is.
  118. func (p *Profile) saveTo(path string) error {
  119. if p.Name == "" {
  120. return fmt.Errorf("profile name is required")
  121. }
  122. if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
  123. return fmt.Errorf("create profiles directory: %w", err)
  124. }
  125. data, err := json.MarshalIndent(p, "", " ")
  126. if err != nil {
  127. return fmt.Errorf("marshal profile: %w", err)
  128. }
  129. if err := os.WriteFile(path, data, 0644); err != nil {
  130. return fmt.Errorf("write profile: %w", err)
  131. }
  132. return nil
  133. }
  134. func LoadProfile(name string) (*Profile, error) {
  135. path, _, isPath := resolveProfileTarget(name)
  136. // A path is stat'd before it is read, so a directory says it is one. Reading a
  137. // directory fails anyway, and reporting that as "not found" would be the one
  138. // answer a user cannot act on.
  139. if isPath {
  140. info, err := os.Stat(path)
  141. switch {
  142. case os.IsNotExist(err):
  143. return nil, fmt.Errorf("profile file %s not found", path)
  144. case err != nil:
  145. return nil, fmt.Errorf("read profile file %s: %w", path, err)
  146. case info.IsDir():
  147. return nil, fmt.Errorf("profile file %s is a directory", path)
  148. }
  149. }
  150. data, err := os.ReadFile(path)
  151. if err != nil {
  152. if os.IsNotExist(err) {
  153. return nil, fmt.Errorf("profile %s not found in %s", name, profilesPath())
  154. }
  155. return nil, fmt.Errorf("read profile %s: %w", name, err)
  156. }
  157. var p Profile
  158. if err := json.Unmarshal(data, &p); err != nil {
  159. return nil, fmt.Errorf("parse profile %s: %w", name, err)
  160. }
  161. return &p, nil
  162. }
  163. func ListProfiles() ([]string, error) {
  164. entries, err := os.ReadDir(profilesPath())
  165. if err != nil {
  166. if os.IsNotExist(err) {
  167. return nil, nil
  168. }
  169. return nil, fmt.Errorf("list profiles: %w", err)
  170. }
  171. var names []string
  172. for _, entry := range entries {
  173. if entry.IsDir() {
  174. continue
  175. }
  176. name := entry.Name()
  177. if !strings.HasSuffix(name, ".json") {
  178. continue
  179. }
  180. names = append(names, strings.TrimSuffix(name, ".json"))
  181. }
  182. return names, nil
  183. }
  184. func DeleteProfile(name string) error {
  185. path := filepath.Join(profilesPath(), profileFileName(name))
  186. if err := os.Remove(path); err != nil {
  187. if os.IsNotExist(err) {
  188. return fmt.Errorf("profile %s not found in %s", name, profilesPath())
  189. }
  190. return fmt.Errorf("delete profile %s: %w", name, err)
  191. }
  192. return nil
  193. }
  194. func sanitizeFilename(name string) string {
  195. name = strings.ToLower(name)
  196. name = strings.Map(func(r rune) rune {
  197. if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
  198. return r
  199. }
  200. return '-'
  201. }, name)
  202. if len(name) > 0 && name[0] == '-' {
  203. name = "unnamed-" + name
  204. }
  205. return name
  206. }
  207. // applyProfile reads RGB state from the device and stores it in a Profile.
  208. func applyProfileToProfile(proto rgbProtocol, channels []via.Channel, display map[uint16]string, catalog *intrgb.Catalog, p *Profile) error {
  209. out, err := readInfo(proto, channels, display, catalog)
  210. if err != nil {
  211. return fmt.Errorf("read device state: %w", err)
  212. }
  213. p.Zones = make(map[string]*ZoneSettings)
  214. for _, zi := range out.Zones {
  215. if zi.Error != "" {
  216. continue
  217. }
  218. p.Zones[zi.Zone] = &ZoneSettings{
  219. Enabled: zi.Enabled,
  220. Effect: zi.Effect,
  221. Brightness: zi.Brightness,
  222. Speed: zi.Speed,
  223. Color: fmt.Sprintf("%02x%02x", zi.Color.Hue, zi.Color.Saturation),
  224. }
  225. }
  226. return nil
  227. }
  228. // loadProfileFromDevice reads RGB state from device and saves it. Every channel
  229. // is recorded, so the profile a `load` applies later is the whole keyboard and
  230. // not the part of it that happened to be named. Warnings go to warn, which is the
  231. // command's stderr. The file is written where path says and the profile is named
  232. // after name, so a `save` of a file writes that file and names the profile for it.
  233. func loadProfileFromDevice(path, name string, warn io.Writer) error {
  234. proto, target, channels, err := openTarget("")
  235. if err != nil {
  236. return err
  237. }
  238. defer proto.Close()
  239. catalog, _, err := resolveCatalog(target)
  240. if err != nil {
  241. return err
  242. }
  243. if catalog == nil {
  244. // The profile stores effect names and a board without a catalog has none
  245. // to store, so every channel is written as "unknown" and cannot be
  246. // restored. Say so here, where the user can still act on it. The way out
  247. // names the zone, because the command takes it as its first argument and
  248. // an index on its own would be read as a channel name.
  249. fmt.Fprintf(warn,
  250. "Warning: this keyboard has no effect names, so the profile records effect %q and cannot restore it; "+
  251. "run `keyboard fetch` for its VIA definition, or set an effect with `effect <zone> <index>`\n", "unknown")
  252. }
  253. p := &Profile{
  254. Name: name,
  255. Version: 1,
  256. Board: boardFor(target.Device.VendorID, target.Device.ProductID),
  257. }
  258. if err := applyProfileToProfile(proto, channels, target.Display, catalog, p); err != nil {
  259. return err
  260. }
  261. return p.saveTo(path)
  262. }
  263. // savedProfileLine is what a save says it did. The path is annotated the way every
  264. // other message here is, and the name is in the line because the file is named
  265. // after it: a save that only reported success would be silent about where a file
  266. // it was told to write by path actually went, which is the one thing about a save
  267. // worth reporting.
  268. func savedProfileLine(name, path string) string {
  269. return fmt.Sprintf("Saved profile %s to %s\n", name, describeDataDir(path))
  270. }
  271. func NewProfileSaveCmd() *cobra.Command {
  272. return &cobra.Command{
  273. Use: "save [name|file]",
  274. Short: "Save current RGB state to a profile",
  275. Long: "Read the current RGB settings from every channel of the keyboard and save\n" +
  276. "them as a JSON profile. A name is written as <name>.json in the per-user\n" +
  277. "profiles/ directory; an argument ending in .json is a path, and that file is\n" +
  278. "written where it says. It reports the file it wrote.\n" +
  279. "\n" +
  280. "A profile is always complete. Recording only some of the channels would let a\n" +
  281. "later `load` apply them and leave the rest as they were, which reads as a\n" +
  282. "zone the profile had nothing to say about.",
  283. Args: cobra.MaximumNArgs(1),
  284. RunE: func(cmd *cobra.Command, args []string) error {
  285. arg := "default"
  286. if len(args) > 0 {
  287. arg = args[0]
  288. }
  289. path, name, _ := resolveProfileTarget(arg)
  290. if err := loadProfileFromDevice(path, name, cmd.ErrOrStderr()); err != nil {
  291. return err
  292. }
  293. fmt.Fprint(cmd.OutOrStdout(), savedProfileLine(name, path))
  294. return nil
  295. },
  296. }
  297. }
  298. func NewProfileLoadCmd() *cobra.Command {
  299. // Not withZoneArgs: the profile name comes first and the zone second, so
  300. // the zone completion only applies once the name has been typed.
  301. cmd := &cobra.Command{
  302. ValidArgsFunction: completeLoadArgs,
  303. Use: "load <name|file> [zone]",
  304. Short: "Load a profile and apply it to the keyboard",
  305. Long: "Read a JSON profile and apply the saved RGB settings to the keyboard. A\n" +
  306. "name is read from the per-user profiles/ directory; an argument ending in\n" +
  307. ".json is a path, and that file is read where it says. Without a zone the\n" +
  308. "profile is applied to every channel it names.",
  309. RunE: func(cmd *cobra.Command, args []string) error {
  310. arg := args[0]
  311. zone := ""
  312. if len(args) == 2 {
  313. zone = args[1]
  314. }
  315. proto, target, selected, err := openTarget(zone)
  316. if err != nil {
  317. return err
  318. }
  319. defer proto.Close()
  320. p, err := LoadProfile(arg)
  321. if err != nil {
  322. return err
  323. }
  324. // A profile belongs to the keyboard it was saved from: its effect
  325. // names are that board's. Applying it elsewhere is allowed, because
  326. // the names that do not exist are reported per key below, but it is
  327. // said out loud, since a mismatch is the likeliest reason.
  328. if p.MatchesBoard(target.Device.VendorID, target.Device.ProductID) == boardOther {
  329. fmt.Fprintln(cmd.ErrOrStderr(), p.boardMismatchWarning(target.Device.VendorID, target.Device.ProductID))
  330. }
  331. catalog, _, err := resolveCatalog(target)
  332. if err != nil {
  333. return err
  334. }
  335. keys := make([]string, 0, len(p.Zones))
  336. for key := range p.Zones {
  337. keys = append(keys, key)
  338. }
  339. sort.Strings(keys)
  340. // A key is a channel name as the file wrote it. Resolving it here
  341. // means a profile written before a board was renamed reports the
  342. // key it cannot place instead of silently applying nothing.
  343. selectedSet := make(map[via.Channel]bool, len(selected))
  344. for _, ch := range selected {
  345. selectedSet[ch] = true
  346. }
  347. // Presence and selection are two different questions. A key the
  348. // selection leaves out is the user's own choice and stays quiet; a
  349. // key naming a channel the keyboard does not have has nowhere to go
  350. // and is reported, whatever the selection says.
  351. present, err := proto.DetectChannels()
  352. if err != nil {
  353. return err
  354. }
  355. presentSet := make(map[via.Channel]bool, len(present))
  356. for _, ch := range present {
  357. presentSet[ch] = true
  358. }
  359. // Without a catalog there are no effect names to look the
  360. // profile's value up in, so the whole load is impossible. Say that
  361. // once instead of reporting every key's name as not found.
  362. if catalog == nil {
  363. fmt.Fprintf(cmd.ErrOrStderr(),
  364. "Warning: profile %q has no effect names for this keyboard, so nothing applied; "+
  365. "run `keyboard fetch` for its VIA definition\n", arg)
  366. return nil
  367. }
  368. applied := 0
  369. for _, key := range keys {
  370. settings := p.Zones[key]
  371. keyChannels, err := resolveZoneName(key, target.Display, target.Alternatives)
  372. if err != nil {
  373. fmt.Fprintf(cmd.ErrOrStderr(),
  374. "Warning: profile %q names zone %q, which this keyboard does not have; skipping\n", arg, key)
  375. continue
  376. }
  377. placed := false
  378. for _, ch := range keyChannels {
  379. if presentSet[ch] {
  380. placed = true
  381. break
  382. }
  383. }
  384. if !placed {
  385. fmt.Fprintf(cmd.ErrOrStderr(),
  386. "Warning: profile %q names zone %q, which this keyboard does not have; skipping\n", arg, key)
  387. continue
  388. }
  389. for _, ch := range keyChannels {
  390. // A key is applied only where the selection allows it, so
  391. // `load <name> logo` leaves the other channels alone.
  392. if !selectedSet[ch] {
  393. continue
  394. }
  395. // A zone the caller named is an explicit request for it, so an
  396. // effect the channel does not have is said rather than skipped;
  397. // without one the whole profile is being applied and a key the
  398. // board cannot do is worth a warning instead of a refusal.
  399. targets, _, err := intrgb.ResolveEffect(catalog, settings.Effect, []via.Channel{ch}, zone != "")
  400. if err != nil {
  401. fmt.Fprintf(cmd.ErrOrStderr(),
  402. "Warning: effect %q not found on %s, skipping\n", settings.Effect, channelName(ch, target.Display))
  403. continue
  404. }
  405. // ResolveEffect can answer with nothing to do and no
  406. // error: the name exists on the board but not on this
  407. // channel, and no zone was named, so it is skipped. Indexing
  408. // its result would crash here instead of saying so.
  409. if len(targets) == 0 {
  410. fmt.Fprintf(cmd.ErrOrStderr(),
  411. "Warning: effect %q not found on %s, skipping\n", settings.Effect, channelName(ch, target.Display))
  412. continue
  413. }
  414. if err := proto.SetValue(ch, uint8(intrgb.EffectID), targets[0].ID); err != nil {
  415. return err
  416. }
  417. if err := proto.SetValue(ch, uint8(intrgb.Brightness), settings.Brightness); err != nil {
  418. return err
  419. }
  420. if err := proto.SetValue(ch, uint8(intrgb.Speed), settings.Speed); err != nil {
  421. return err
  422. }
  423. if settings.Enabled && settings.Color != "" {
  424. hue, sat, err := hexToHSV(settings.Color)
  425. if err != nil {
  426. fmt.Fprintf(cmd.ErrOrStderr(),
  427. "Warning: invalid color %q on zone %s, skipping\n", settings.Color, channelName(ch, target.Display))
  428. } else if err := proto.SetColor(ch, hue, sat); err != nil {
  429. return err
  430. }
  431. }
  432. applied++
  433. }
  434. }
  435. if applied == 0 {
  436. fmt.Fprintf(cmd.ErrOrStderr(),
  437. "Warning: profile %q has no settings for the selected zone(s); nothing applied\n", arg)
  438. }
  439. return nil
  440. },
  441. }
  442. cmd.Args = zoneArgs(1, 2, "a profile name or file and at most a zone")
  443. return cmd
  444. }
  445. func NewProfileListCmd() *cobra.Command {
  446. return &cobra.Command{
  447. Use: "list",
  448. Short: "List saved profiles",
  449. Args: cobra.NoArgs,
  450. RunE: func(cmd *cobra.Command, args []string) error {
  451. names, err := ListProfiles()
  452. if err != nil {
  453. return err
  454. }
  455. if names == nil {
  456. names = []string{}
  457. }
  458. lines := make([]string, 0, len(names))
  459. for _, name := range names {
  460. p, err := LoadProfile(name)
  461. if err != nil {
  462. // A file that cannot be read is still a name in the
  463. // directory; the name is what the user can act on.
  464. lines = append(lines, name)
  465. continue
  466. }
  467. lines = append(lines, p.listLine())
  468. }
  469. if jsonOutput {
  470. return encodeJSON(cmd.OutOrStdout(), struct {
  471. Profiles []string `json:"profiles"`
  472. }{Profiles: names})
  473. }
  474. for _, line := range lines {
  475. fmt.Fprintln(cmd.OutOrStdout(), line)
  476. }
  477. return nil
  478. },
  479. }
  480. }
  481. func NewProfileDeleteCmd() *cobra.Command {
  482. var name string
  483. cmd := &cobra.Command{
  484. ValidArgsFunction: completeProfileNames,
  485. Use: "delete [name]",
  486. Short: "Delete a saved profile",
  487. Args: cobra.MaximumNArgs(1),
  488. RunE: func(cmd *cobra.Command, args []string) error {
  489. if len(args) == 0 {
  490. name = "default"
  491. } else {
  492. name = args[0]
  493. }
  494. return DeleteProfile(name)
  495. },
  496. }
  497. return cmd
  498. }
  499. func hexToHSV(s string) (uint8, uint8, error) {
  500. if len(s) != 4 {
  501. return 0, 0, fmt.Errorf("invalid HSV hex (expected 4 hex digits): %s", s)
  502. }
  503. var hue, sat uint8
  504. _, err := fmt.Sscanf(s, "%02x%02x", &hue, &sat)
  505. return hue, sat, err
  506. }