profile.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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 profileFilePath(arg), arg, false
  106. }
  107. base := filepath.Base(arg)
  108. return arg, strings.TrimSuffix(base, filepath.Ext(base)), true
  109. }
  110. // profileFilePath is the file a name maps to, in the per-user directory. It is the
  111. // name form of resolveProfileTarget on its own, for the commands that take no path
  112. // at all: `delete` and `list` are name-only, so `delete lava.json` names the
  113. // profile `lava-json` and not a file, and the one that says which file it removed
  114. // must not be the one that could remove a file outside the per-user directory.
  115. func profileFilePath(name string) string {
  116. return filepath.Join(profilesPath(), profileFileName(name))
  117. }
  118. // Save writes the profile into the per-user directory under its own name, which is
  119. // what every caller that has a name and no path means.
  120. func (p *Profile) Save() error {
  121. return p.saveTo(profileFilePath(p.Name))
  122. }
  123. // saveTo writes the profile to one file and creates the directory it is in. It
  124. // resolves nothing: the caller decides where the file goes, so that the rule that
  125. // decides is the only one there is.
  126. func (p *Profile) saveTo(path string) error {
  127. if p.Name == "" {
  128. return fmt.Errorf("profile name is required")
  129. }
  130. if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
  131. return fmt.Errorf("create profiles directory: %w", err)
  132. }
  133. data, err := json.MarshalIndent(p, "", " ")
  134. if err != nil {
  135. return fmt.Errorf("marshal profile: %w", err)
  136. }
  137. if err := os.WriteFile(path, data, 0644); err != nil {
  138. return fmt.Errorf("write profile: %w", err)
  139. }
  140. return nil
  141. }
  142. func LoadProfile(name string) (*Profile, error) {
  143. path, _, isPath := resolveProfileTarget(name)
  144. // A path is stat'd before it is read, so a directory says it is one. Reading a
  145. // directory fails anyway, and reporting that as "not found" would be the one
  146. // answer a user cannot act on.
  147. if isPath {
  148. info, err := os.Stat(path)
  149. switch {
  150. case os.IsNotExist(err):
  151. return nil, fmt.Errorf("profile file %s not found", path)
  152. case err != nil:
  153. return nil, fmt.Errorf("read profile file %s: %w", path, err)
  154. case info.IsDir():
  155. return nil, fmt.Errorf("profile file %s is a directory", path)
  156. }
  157. }
  158. data, err := os.ReadFile(path)
  159. if err != nil {
  160. if os.IsNotExist(err) {
  161. return nil, fmt.Errorf("profile %s not found in %s", name, profilesPath())
  162. }
  163. return nil, fmt.Errorf("read profile %s: %w", name, err)
  164. }
  165. var p Profile
  166. if err := json.Unmarshal(data, &p); err != nil {
  167. return nil, fmt.Errorf("parse profile %s: %w", name, err)
  168. }
  169. return &p, nil
  170. }
  171. func ListProfiles() ([]string, error) {
  172. entries, err := os.ReadDir(profilesPath())
  173. if err != nil {
  174. if os.IsNotExist(err) {
  175. return nil, nil
  176. }
  177. return nil, fmt.Errorf("list profiles: %w", err)
  178. }
  179. var names []string
  180. for _, entry := range entries {
  181. if entry.IsDir() {
  182. continue
  183. }
  184. name := entry.Name()
  185. if !strings.HasSuffix(name, ".json") {
  186. continue
  187. }
  188. names = append(names, strings.TrimSuffix(name, ".json"))
  189. }
  190. return names, nil
  191. }
  192. // DeleteProfile removes the profile of that name from the per-user directory and
  193. // returns the file it removed, so a command that reports the deletion says which
  194. // file it was. A name only: nothing here resolves a path, so an argument ending in
  195. // .json names the profile `lava-json`.
  196. func DeleteProfile(name string) (string, error) {
  197. path := profileFilePath(name)
  198. if err := os.Remove(path); err != nil {
  199. if os.IsNotExist(err) {
  200. return "", fmt.Errorf("profile %s not found in %s", name, profilesPath())
  201. }
  202. return "", fmt.Errorf("delete profile %s: %w", name, err)
  203. }
  204. return path, nil
  205. }
  206. func sanitizeFilename(name string) string {
  207. name = strings.ToLower(name)
  208. name = strings.Map(func(r rune) rune {
  209. if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
  210. return r
  211. }
  212. return '-'
  213. }, name)
  214. if len(name) > 0 && name[0] == '-' {
  215. name = "unnamed-" + name
  216. }
  217. return name
  218. }
  219. // applyProfile reads RGB state from the device and stores it in a Profile.
  220. func applyProfileToProfile(proto rgbProtocol, channels []via.Channel, display map[uint16]string, catalog *intrgb.Catalog, p *Profile) error {
  221. out, err := readInfo(proto, channels, display, catalog)
  222. if err != nil {
  223. return fmt.Errorf("read device state: %w", err)
  224. }
  225. p.Zones = make(map[string]*ZoneSettings)
  226. for _, zi := range out.Zones {
  227. if zi.Error != "" {
  228. continue
  229. }
  230. p.Zones[zi.Zone] = &ZoneSettings{
  231. Enabled: zi.Enabled,
  232. Effect: zi.Effect,
  233. Brightness: zi.Brightness,
  234. Speed: zi.Speed,
  235. Color: fmt.Sprintf("%02x%02x", zi.Color.Hue, zi.Color.Saturation),
  236. }
  237. }
  238. return nil
  239. }
  240. // loadProfileFromDevice reads RGB state from device and saves it. Every channel
  241. // is recorded, so the profile a `load` applies later is the whole keyboard and
  242. // not the part of it that happened to be named. Warnings go to warn, which is the
  243. // command's stderr. The file is written where path says and the profile is named
  244. // after name, so a `save` of a file writes that file and names the profile for it.
  245. func loadProfileFromDevice(path, name string, warn io.Writer) error {
  246. proto, target, channels, err := openTarget("")
  247. if err != nil {
  248. return err
  249. }
  250. defer proto.Close()
  251. catalog, _, err := resolveCatalog(target)
  252. if err != nil {
  253. return err
  254. }
  255. if catalog == nil {
  256. // The profile stores effect names and a board without a catalog has none
  257. // to store, so every channel is written as "unknown" and cannot be
  258. // restored. Say so here, where the user can still act on it. The way out
  259. // names the zone, because the command takes it as its first argument and
  260. // an index on its own would be read as a channel name.
  261. fmt.Fprintf(warn,
  262. "Warning: this keyboard has no effect names, so the profile records effect %q and cannot restore it; "+
  263. "run `keyboard fetch` for its VIA definition, or set an effect with `effect <zone> <index>`\n", "unknown")
  264. }
  265. p := &Profile{
  266. Name: name,
  267. Version: 1,
  268. Board: boardFor(target.Device.VendorID, target.Device.ProductID),
  269. }
  270. if err := applyProfileToProfile(proto, channels, target.Display, catalog, p); err != nil {
  271. return err
  272. }
  273. return p.saveTo(path)
  274. }
  275. // savedProfileLine is what a save says it did. The path is annotated the way every
  276. // other message here is, and the name is in the line because the file is named
  277. // after it: a save that only reported success would be silent about where a file
  278. // it was told to write by path actually went, which is the one thing about a save
  279. // worth reporting.
  280. func savedProfileLine(name, path string) string {
  281. return fmt.Sprintf("Saved profile %s to %s\n", name, describeDataDir(path))
  282. }
  283. // deletedProfileLine is what a delete says it did, in the same words as the save:
  284. // the name and the file it removed, and the file annotated as the user's when that
  285. // is where it was. A delete that printed nothing is a command that has run and
  286. // cannot be told apart from one that removed something else.
  287. func deletedProfileLine(name, path string) string {
  288. return fmt.Sprintf("Deleted profile %s from %s\n", name, describeDataDir(path))
  289. }
  290. func NewProfileSaveCmd() *cobra.Command {
  291. return &cobra.Command{
  292. Use: "save [name|file]",
  293. Short: "Save current RGB state to a profile",
  294. Long: "Read the current RGB settings from every channel of the keyboard and save\n" +
  295. "them as a JSON profile. A name is written as <name>.json in the per-user\n" +
  296. "profiles/ directory; an argument ending in .json is a path, and that file is\n" +
  297. "written where it says. It reports the file it wrote.\n" +
  298. "\n" +
  299. "A profile is always complete. Recording only some of the channels would let a\n" +
  300. "later `load` apply them and leave the rest as they were, which reads as a\n" +
  301. "zone the profile had nothing to say about.",
  302. Args: cobra.MaximumNArgs(1),
  303. RunE: func(cmd *cobra.Command, args []string) error {
  304. arg := "default"
  305. if len(args) > 0 {
  306. arg = args[0]
  307. }
  308. path, name, _ := resolveProfileTarget(arg)
  309. if err := loadProfileFromDevice(path, name, cmd.ErrOrStderr()); err != nil {
  310. return err
  311. }
  312. fmt.Fprint(cmd.OutOrStdout(), savedProfileLine(name, path))
  313. return nil
  314. },
  315. }
  316. }
  317. func NewProfileLoadCmd() *cobra.Command {
  318. // Not withZoneArgs: the profile name comes first and the zone second, so
  319. // the zone completion only applies once the name has been typed.
  320. cmd := &cobra.Command{
  321. ValidArgsFunction: completeLoadArgs,
  322. Use: "load <name|file> [zone]",
  323. Short: "Load a profile and apply it to the keyboard",
  324. Long: "Read a JSON profile and apply the saved RGB settings to the keyboard. A\n" +
  325. "name is read from the per-user profiles/ directory; an argument ending in\n" +
  326. ".json is a path, and that file is read where it says. Without a zone the\n" +
  327. "profile is applied to every channel it names.",
  328. RunE: func(cmd *cobra.Command, args []string) error {
  329. arg := args[0]
  330. zone := ""
  331. if len(args) == 2 {
  332. zone = args[1]
  333. }
  334. proto, target, selected, err := openTarget(zone)
  335. if err != nil {
  336. return err
  337. }
  338. defer proto.Close()
  339. p, err := LoadProfile(arg)
  340. if err != nil {
  341. return err
  342. }
  343. // A profile belongs to the keyboard it was saved from: its effect
  344. // names are that board's. Applying it elsewhere is allowed, because
  345. // the names that do not exist are reported per key below, but it is
  346. // said out loud, since a mismatch is the likeliest reason.
  347. if p.MatchesBoard(target.Device.VendorID, target.Device.ProductID) == boardOther {
  348. fmt.Fprintln(cmd.ErrOrStderr(), p.boardMismatchWarning(target.Device.VendorID, target.Device.ProductID))
  349. }
  350. catalog, _, err := resolveCatalog(target)
  351. if err != nil {
  352. return err
  353. }
  354. keys := make([]string, 0, len(p.Zones))
  355. for key := range p.Zones {
  356. keys = append(keys, key)
  357. }
  358. sort.Strings(keys)
  359. // A key is a channel name as the file wrote it. Resolving it here
  360. // means a profile written before a board was renamed reports the
  361. // key it cannot place instead of silently applying nothing.
  362. selectedSet := make(map[via.Channel]bool, len(selected))
  363. for _, ch := range selected {
  364. selectedSet[ch] = true
  365. }
  366. // Presence and selection are two different questions. A key the
  367. // selection leaves out is the user's own choice and stays quiet; a
  368. // key naming a channel the keyboard does not have has nowhere to go
  369. // and is reported, whatever the selection says.
  370. present, err := proto.DetectChannels()
  371. if err != nil {
  372. return err
  373. }
  374. presentSet := make(map[via.Channel]bool, len(present))
  375. for _, ch := range present {
  376. presentSet[ch] = true
  377. }
  378. // Without a catalog there are no effect names to look the
  379. // profile's value up in, so the whole load is impossible. Say that
  380. // once instead of reporting every key's name as not found.
  381. if catalog == nil {
  382. fmt.Fprintf(cmd.ErrOrStderr(),
  383. "Warning: profile %q has no effect names for this keyboard, so nothing applied; "+
  384. "run `keyboard fetch` for its VIA definition\n", arg)
  385. return nil
  386. }
  387. applied := 0
  388. for _, key := range keys {
  389. settings := p.Zones[key]
  390. keyChannels, err := resolveZoneName(key, target.Display, target.Alternatives)
  391. if err != nil {
  392. fmt.Fprintf(cmd.ErrOrStderr(),
  393. "Warning: profile %q names zone %q, which this keyboard does not have; skipping\n", arg, key)
  394. continue
  395. }
  396. placed := false
  397. for _, ch := range keyChannels {
  398. if presentSet[ch] {
  399. placed = true
  400. break
  401. }
  402. }
  403. if !placed {
  404. fmt.Fprintf(cmd.ErrOrStderr(),
  405. "Warning: profile %q names zone %q, which this keyboard does not have; skipping\n", arg, key)
  406. continue
  407. }
  408. for _, ch := range keyChannels {
  409. // A key is applied only where the selection allows it, so
  410. // `load <name> logo` leaves the other channels alone.
  411. if !selectedSet[ch] {
  412. continue
  413. }
  414. // A zone the caller named is an explicit request for it, so an
  415. // effect the channel does not have is said rather than skipped;
  416. // without one the whole profile is being applied and a key the
  417. // board cannot do is worth a warning instead of a refusal.
  418. targets, _, err := intrgb.ResolveEffect(catalog, settings.Effect, []via.Channel{ch}, zone != "")
  419. if err != nil {
  420. fmt.Fprintf(cmd.ErrOrStderr(),
  421. "Warning: effect %q not found on %s, skipping\n", settings.Effect, channelName(ch, target.Display))
  422. continue
  423. }
  424. // ResolveEffect can answer with nothing to do and no
  425. // error: the name exists on the board but not on this
  426. // channel, and no zone was named, so it is skipped. Indexing
  427. // its result would crash here instead of saying so.
  428. if len(targets) == 0 {
  429. fmt.Fprintf(cmd.ErrOrStderr(),
  430. "Warning: effect %q not found on %s, skipping\n", settings.Effect, channelName(ch, target.Display))
  431. continue
  432. }
  433. if err := proto.SetValue(ch, uint8(intrgb.EffectID), targets[0].ID); err != nil {
  434. return err
  435. }
  436. if err := proto.SetValue(ch, uint8(intrgb.Brightness), settings.Brightness); err != nil {
  437. return err
  438. }
  439. if err := proto.SetValue(ch, uint8(intrgb.Speed), settings.Speed); err != nil {
  440. return err
  441. }
  442. if settings.Enabled && settings.Color != "" {
  443. hue, sat, err := hexToHSV(settings.Color)
  444. if err != nil {
  445. fmt.Fprintf(cmd.ErrOrStderr(),
  446. "Warning: invalid color %q on zone %s, skipping\n", settings.Color, channelName(ch, target.Display))
  447. } else if err := proto.SetColor(ch, hue, sat); err != nil {
  448. return err
  449. }
  450. }
  451. applied++
  452. }
  453. }
  454. if applied == 0 {
  455. fmt.Fprintf(cmd.ErrOrStderr(),
  456. "Warning: profile %q has no settings for the selected zone(s); nothing applied\n", arg)
  457. }
  458. return nil
  459. },
  460. }
  461. cmd.Args = zoneArgs(1, 2, "a profile name or file and at most a zone")
  462. return cmd
  463. }
  464. func NewProfileListCmd() *cobra.Command {
  465. return &cobra.Command{
  466. Use: "list",
  467. Short: "List saved profiles",
  468. Args: cobra.NoArgs,
  469. RunE: func(cmd *cobra.Command, args []string) error {
  470. names, err := ListProfiles()
  471. if err != nil {
  472. return err
  473. }
  474. if names == nil {
  475. names = []string{}
  476. }
  477. lines := make([]string, 0, len(names))
  478. for _, name := range names {
  479. p, err := LoadProfile(name)
  480. if err != nil {
  481. // A file that cannot be read is still a name in the
  482. // directory; the name is what the user can act on.
  483. lines = append(lines, name)
  484. continue
  485. }
  486. lines = append(lines, p.listLine())
  487. }
  488. if jsonOutput {
  489. return encodeJSON(cmd.OutOrStdout(), struct {
  490. Profiles []string `json:"profiles"`
  491. }{Profiles: names})
  492. }
  493. for _, line := range lines {
  494. fmt.Fprintln(cmd.OutOrStdout(), line)
  495. }
  496. return nil
  497. },
  498. }
  499. }
  500. func NewProfileDeleteCmd() *cobra.Command {
  501. cmd := &cobra.Command{
  502. ValidArgsFunction: completeProfileNames,
  503. Use: "delete [name]",
  504. Short: "Delete a saved profile",
  505. Long: "Delete a profile from the per-user profiles/ directory, by name; without a\n" +
  506. "name it deletes `default`. A path is not accepted, so an argument ending in\n" +
  507. ".json names the profile without the dots rather than a file to remove. It\n" +
  508. "reports the file it removed.",
  509. Args: cobra.MaximumNArgs(1),
  510. RunE: func(cmd *cobra.Command, args []string) error {
  511. name := "default"
  512. if len(args) > 0 {
  513. name = args[0]
  514. }
  515. path, err := DeleteProfile(name)
  516. if err != nil {
  517. return err
  518. }
  519. fmt.Fprint(cmd.OutOrStdout(), deletedProfileLine(name, path))
  520. return nil
  521. },
  522. }
  523. return cmd
  524. }
  525. func hexToHSV(s string) (uint8, uint8, error) {
  526. if len(s) != 4 {
  527. return 0, 0, fmt.Errorf("invalid HSV hex (expected 4 hex digits): %s", s)
  528. }
  529. var hue, sat uint8
  530. _, err := fmt.Sscanf(s, "%02x%02x", &hue, &sat)
  531. return hue, sat, err
  532. }