profile.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. Warnings go
  183. // to warn, which is the command's stderr.
  184. func loadProfileFromDevice(name string, warn io.Writer) error {
  185. proto, target, channels, err := openTarget()
  186. if err != nil {
  187. return err
  188. }
  189. defer proto.Close()
  190. catalog, _, err := resolveCatalog(target)
  191. if err != nil {
  192. return err
  193. }
  194. if catalog == nil {
  195. // The profile stores effect names and a board without a catalog has none
  196. // to store, so every channel is written as "unknown" and cannot be
  197. // restored. Say so here, where the user can still act on it.
  198. fmt.Fprintf(warn,
  199. "Warning: this keyboard has no effect names, so the profile records effect %q and cannot restore it; "+
  200. "run `keyboard fetch` for its VIA definition, or set an effect with `effect <index>`\n", "unknown")
  201. }
  202. p := &Profile{
  203. Name: name,
  204. Version: 1,
  205. Board: boardFor(target.Device.VendorID, target.Device.ProductID),
  206. }
  207. if err := applyProfileToProfile(proto, channels, target.Display, catalog, p); err != nil {
  208. return err
  209. }
  210. return p.Save()
  211. }
  212. func NewProfileSaveCmd() *cobra.Command {
  213. var name string
  214. cmd := &cobra.Command{
  215. Use: "save [name]",
  216. Short: "Save current RGB state to a profile",
  217. Long: "Read the current RGB settings from the keyboard and save them as a JSON profile in the profiles/ directory.",
  218. Args: cobra.MaximumNArgs(1),
  219. RunE: func(cmd *cobra.Command, args []string) error {
  220. if len(args) == 0 {
  221. name = "default"
  222. } else {
  223. name = args[0]
  224. }
  225. return loadProfileFromDevice(name, cmd.ErrOrStderr())
  226. },
  227. }
  228. return cmd
  229. }
  230. func NewProfileLoadCmd() *cobra.Command {
  231. var name string
  232. cmd := &cobra.Command{
  233. ValidArgsFunction: completeProfileNames,
  234. Use: "load [name]",
  235. Short: "Load a profile and apply it to the keyboard",
  236. Long: "Read a JSON profile from the profiles/ directory and apply the saved RGB settings to the keyboard.",
  237. Args: cobra.MaximumNArgs(1),
  238. RunE: func(cmd *cobra.Command, args []string) error {
  239. if len(args) == 0 {
  240. name = "default"
  241. } else {
  242. name = args[0]
  243. }
  244. proto, target, selected, err := openTarget()
  245. if err != nil {
  246. return err
  247. }
  248. defer proto.Close()
  249. p, err := LoadProfile(name)
  250. if err != nil {
  251. return err
  252. }
  253. // A profile belongs to the keyboard it was saved from: its effect
  254. // names are that board's. Applying it elsewhere is allowed, because
  255. // the names that do not exist are reported per key below, but it is
  256. // said out loud, since a mismatch is the likeliest reason.
  257. if p.MatchesBoard(target.Device.VendorID, target.Device.ProductID) == boardOther {
  258. fmt.Fprintln(cmd.ErrOrStderr(), p.boardMismatchWarning(target.Device.VendorID, target.Device.ProductID))
  259. }
  260. catalog, _, err := resolveCatalog(target)
  261. if err != nil {
  262. return err
  263. }
  264. keys := make([]string, 0, len(p.Zones))
  265. for key := range p.Zones {
  266. keys = append(keys, key)
  267. }
  268. sort.Strings(keys)
  269. // A key is a channel name as the file wrote it. Resolving it here
  270. // means a profile written before a board was renamed reports the
  271. // key it cannot place instead of silently applying nothing.
  272. selectedSet := make(map[via.Channel]bool, len(selected))
  273. for _, ch := range selected {
  274. selectedSet[ch] = true
  275. }
  276. // Presence and selection are two different questions. A key the
  277. // selection leaves out is the user's own choice and stays quiet; a
  278. // key naming a channel the keyboard does not have has nowhere to go
  279. // and is reported, whatever the selection says.
  280. present, err := proto.DetectChannels()
  281. if err != nil {
  282. return err
  283. }
  284. presentSet := make(map[via.Channel]bool, len(present))
  285. for _, ch := range present {
  286. presentSet[ch] = true
  287. }
  288. // Without a catalog there are no effect names to look the
  289. // profile's value up in, so the whole load is impossible. Say that
  290. // once instead of reporting every key's name as not found.
  291. if catalog == nil {
  292. fmt.Fprintf(cmd.ErrOrStderr(),
  293. "Warning: profile %q has no effect names for this keyboard, so nothing applied; "+
  294. "run `keyboard fetch` for its VIA definition\n", name)
  295. return nil
  296. }
  297. applied := 0
  298. for _, key := range keys {
  299. settings := p.Zones[key]
  300. keyChannels, err := resolveZoneName(key, target.Display, target.Alternatives)
  301. if err != nil {
  302. fmt.Fprintf(cmd.ErrOrStderr(),
  303. "Warning: profile %q names zone %q, which this keyboard does not have; skipping\n", name, key)
  304. continue
  305. }
  306. placed := false
  307. for _, ch := range keyChannels {
  308. if presentSet[ch] {
  309. placed = true
  310. break
  311. }
  312. }
  313. if !placed {
  314. fmt.Fprintf(cmd.ErrOrStderr(),
  315. "Warning: profile %q names zone %q, which this keyboard does not have; skipping\n", name, key)
  316. continue
  317. }
  318. for _, ch := range keyChannels {
  319. // A key is applied only where the selection allows it, so
  320. // `--zone logo load <name>` leaves the other channels alone.
  321. if !selectedSet[ch] {
  322. continue
  323. }
  324. targets, _, err := intrgb.ResolveEffect(catalog, settings.Effect, []via.Channel{ch}, targetZone != "")
  325. if err != nil {
  326. fmt.Fprintf(cmd.ErrOrStderr(),
  327. "Warning: effect %q not found on %s, skipping\n", settings.Effect, channelName(ch, target.Display))
  328. continue
  329. }
  330. // ResolveEffect can answer with nothing to do and no
  331. // error: the name exists on the board but not on this
  332. // channel, and no zone was named, so it is skipped. Indexing
  333. // its result would crash here instead of saying so.
  334. if len(targets) == 0 {
  335. fmt.Fprintf(cmd.ErrOrStderr(),
  336. "Warning: effect %q not found on %s, skipping\n", settings.Effect, channelName(ch, target.Display))
  337. continue
  338. }
  339. if err := proto.SetValue(ch, uint8(intrgb.EffectID), targets[0].ID); err != nil {
  340. return err
  341. }
  342. if err := proto.SetValue(ch, uint8(intrgb.Brightness), settings.Brightness); err != nil {
  343. return err
  344. }
  345. if err := proto.SetValue(ch, uint8(intrgb.Speed), settings.Speed); err != nil {
  346. return err
  347. }
  348. if settings.Enabled && settings.Color != "" {
  349. hue, sat, err := hexToHSV(settings.Color)
  350. if err != nil {
  351. fmt.Fprintf(cmd.ErrOrStderr(),
  352. "Warning: invalid color %q on zone %s, skipping\n", settings.Color, channelName(ch, target.Display))
  353. } else if err := proto.SetColor(ch, hue, sat); err != nil {
  354. return err
  355. }
  356. }
  357. applied++
  358. }
  359. }
  360. if applied == 0 {
  361. fmt.Fprintf(cmd.ErrOrStderr(),
  362. "Warning: profile %q has no settings for the selected zone(s); nothing applied\n", name)
  363. }
  364. return nil
  365. },
  366. }
  367. return cmd
  368. }
  369. func NewProfileListCmd() *cobra.Command {
  370. return &cobra.Command{
  371. Use: "list",
  372. Short: "List saved profiles",
  373. Args: cobra.NoArgs,
  374. RunE: func(cmd *cobra.Command, args []string) error {
  375. names, err := ListProfiles()
  376. if err != nil {
  377. return err
  378. }
  379. if names == nil {
  380. names = []string{}
  381. }
  382. lines := make([]string, 0, len(names))
  383. for _, name := range names {
  384. p, err := LoadProfile(name)
  385. if err != nil {
  386. // A file that cannot be read is still a name in the
  387. // directory; the name is what the user can act on.
  388. lines = append(lines, name)
  389. continue
  390. }
  391. lines = append(lines, p.listLine())
  392. }
  393. if jsonOutput {
  394. return encodeJSON(cmd.OutOrStdout(), struct {
  395. Profiles []string `json:"profiles"`
  396. }{Profiles: names})
  397. }
  398. for _, line := range lines {
  399. fmt.Fprintln(cmd.OutOrStdout(), line)
  400. }
  401. return nil
  402. },
  403. }
  404. }
  405. func NewProfileDeleteCmd() *cobra.Command {
  406. var name string
  407. cmd := &cobra.Command{
  408. ValidArgsFunction: completeProfileNames,
  409. Use: "delete [name]",
  410. Short: "Delete a saved profile",
  411. Args: cobra.MaximumNArgs(1),
  412. RunE: func(cmd *cobra.Command, args []string) error {
  413. if len(args) == 0 {
  414. name = "default"
  415. } else {
  416. name = args[0]
  417. }
  418. return DeleteProfile(name)
  419. },
  420. }
  421. return cmd
  422. }
  423. func hexToHSV(s string) (uint8, uint8, error) {
  424. if len(s) != 4 {
  425. return 0, 0, fmt.Errorf("invalid HSV hex (expected 4 hex digits): %s", s)
  426. }
  427. var hue, sat uint8
  428. _, err := fmt.Sscanf(s, "%02x%02x", &hue, &sat)
  429. return hue, sat, err
  430. }