ui_kitten.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. func PrepareRootCmd(root *cli.Command) {
  18. if RunningAsUI() {
  19. root.CallbackOnError = func(cmd *cli.Command, err error, during_parsing bool, exit_code int) int {
  20. cli.ShowError(err)
  21. os.Stdout.WriteString("\x1bP@kitty-overlay-ready|\x1b\\")
  22. HoldTillEnter(true)
  23. return exit_code
  24. }
  25. }
  26. }
  27. func KittenOutputSerializer() func(any) (string, error) {
  28. if RunningAsUI() {
  29. return func(what any) (string, error) {
  30. data, err := json.Marshal(what)
  31. if err != nil {
  32. return "", err
  33. }
  34. return "\x1bP@kitty-kitten-result|" + base85.EncodeToString(data) + "\x1b\\", nil
  35. }
  36. }
  37. return func(what any) (string, error) {
  38. if sval, ok := what.(string); ok {
  39. return sval, nil
  40. }
  41. data, err := json.MarshalIndent(what, "", " ")
  42. if err != nil {
  43. return "", err
  44. }
  45. return utils.UnsafeBytesToString(data), nil
  46. }
  47. }