profile.go 13 KB

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