profile.go 15 KB

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