ui_kitten.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package tui
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "sync"
  8. "kitty/tools/cli"
  9. "kitty/tools/utils"
  10. "kitty/tools/utils/base85"
  11. )
  12. var _ = fmt.Print
  13. var RunningAsUI = sync.OnceValue(func() bool {
  14. defer func() { os.Unsetenv("KITTEN_RUNNING_AS_UI") }()
  15. return os.Getenv("KITTEN_RUNNING_AS_UI") != ""
  16. })
  17. type BasicColors struct {
  18. Foreground uint32 `json:"foreground"`
  19. Background uint32 `json:"background"`
  20. Color0 uint32 `json:"color0"`
  21. Color1 uint32 `json:"color1"`
  22. Color2 uint32 `json:"color2"`
  23. Color3 uint32 `json:"color3"`
  24. Color4 uint32 `json:"color4"`
  25. Color5 uint32 `json:"color5"`
  26. Color6 uint32 `json:"color6"`
  27. Color7 uint32 `json:"color7"`
  28. Color8 uint32 `json:"color8"`
  29. Color9 uint32 `json:"color9"`
  30. Color10 uint32 `json:"color10"`
  31. Color11 uint32 `json:"color11"`
  32. Color12 uint32 `json:"color12"`
  33. Color13 uint32 `json:"color13"`
  34. Color14 uint32 `json:"color14"`
  35. Color15 uint32 `json:"color15"`
  36. }
  37. func ReadBasicColors() (ans BasicColors, err error) {
  38. q := os.Getenv("KITTY_BASIC_COLORS")
  39. if q == "" {
  40. err = fmt.Errorf("No KITTY_BASIC_COLORS env var")
  41. } else {
  42. err = json.Unmarshal(utils.UnsafeStringToBytes(q), &ans)
  43. }
  44. return
  45. }
  46. func PrepareRootCmd(root *cli.Command) {
  47. if RunningAsUI() {
  48. root.CallbackOnError = func(cmd *cli.Command, err error, during_parsing bool, exit_code int) int {
  49. cli.ShowError(err)
  50. os.Stdout.WriteString("\x1bP@kitty-overlay-ready|\x1b\\")
  51. HoldTillEnter(true)
  52. return exit_code
  53. }
  54. }
  55. }
  56. func KittenOutputSerializer() func(any) (string, error) {
  57. if RunningAsUI() {
  58. return func(what any) (string, error) {
  59. data, err := json.Marshal(what)
  60. if err != nil {
  61. return "", err
  62. }
  63. return "\x1bP@kitty-kitten-result|" + base85.EncodeToString(data) + "\x1b\\", nil
  64. }
  65. }
  66. return func(what any) (string, error) {
  67. if sval, ok := what.(string); ok {
  68. return sval, nil
  69. }
  70. data, err := json.MarshalIndent(what, "", " ")
  71. if err != nil {
  72. return "", err
  73. }
  74. return utils.UnsafeBytesToString(data), nil
  75. }
  76. }