main.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package query_terminal
  2. import (
  3. "bytes"
  4. "fmt"
  5. "kitty"
  6. "os"
  7. "slices"
  8. "strings"
  9. "time"
  10. "kitty/tools/cli"
  11. "kitty/tools/tui/loop"
  12. )
  13. var _ = fmt.Print
  14. func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
  15. queries := kitty.QueryNames
  16. if len(args) > 0 && !slices.Contains(args, "all") {
  17. queries = make([]string, len(args))
  18. for i, x := range args {
  19. if !slices.Contains(kitty.QueryNames, x) {
  20. return 1, fmt.Errorf("Unknown query: %s", x)
  21. }
  22. queries[i] = x
  23. }
  24. }
  25. lp, err := loop.New(loop.NoAlternateScreen, loop.NoKeyboardStateChange, loop.NoMouseTracking, loop.NoRestoreColors)
  26. if err != nil {
  27. return 1, err
  28. }
  29. timed_out := false
  30. lp.OnInitialize = func() (string, error) {
  31. lp.QueryTerminal(queries...)
  32. lp.QueueWriteString("\x1b[c")
  33. _, err := lp.AddTimer(time.Duration(opts.WaitFor*float64(time.Second)), false, func(timer_id loop.IdType) error {
  34. timed_out = true
  35. lp.Quit(1)
  36. return nil
  37. })
  38. return "", err
  39. }
  40. buf := strings.Builder{}
  41. lp.OnQueryResponse = func(key, val string, found bool) error {
  42. if found {
  43. fmt.Fprintf(&buf, "%s: %s\n", key, val)
  44. } else {
  45. fmt.Fprintf(&buf, "%s:\n", key)
  46. }
  47. return nil
  48. }
  49. lp.OnEscapeCode = func(typ loop.EscapeCodeType, data []byte) error {
  50. if typ == loop.CSI && bytes.HasSuffix(data, []byte{'c'}) {
  51. lp.Quit(0)
  52. }
  53. return nil
  54. }
  55. err = lp.Run()
  56. rc = lp.ExitCode()
  57. if err != nil {
  58. return 1, err
  59. }
  60. ds := lp.DeathSignalName()
  61. if ds != "" {
  62. fmt.Println("Killed by signal: ", ds)
  63. lp.KillIfSignalled()
  64. return
  65. }
  66. os.Stdout.WriteString(buf.String())
  67. if timed_out {
  68. return 1, fmt.Errorf("timed out waiting for response from terminal")
  69. }
  70. return
  71. }
  72. func EntryPoint(parent *cli.Command) {
  73. create_cmd(parent, main)
  74. }