legacy.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package show_key
  3. import (
  4. "errors"
  5. "fmt"
  6. "io"
  7. "kitty/tools/cli/markup"
  8. "kitty/tools/tty"
  9. "os"
  10. "golang.org/x/sys/unix"
  11. )
  12. var _ = fmt.Print
  13. func print_key(buf []byte, ctx *markup.Context) {
  14. const ctrl_keys = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
  15. unix := ""
  16. send_text := ""
  17. for _, ch := range buf {
  18. switch {
  19. case int(ch) < len(ctrl_keys):
  20. unix += "^" + ctrl_keys[ch:ch+1]
  21. case ch == 127:
  22. unix += "^?"
  23. default:
  24. unix += string(rune(ch))
  25. }
  26. }
  27. for _, ch := range string(buf) {
  28. q := fmt.Sprintf("%#v", string(ch))
  29. send_text += q[1 : len(q)-1]
  30. }
  31. os.Stdout.WriteString(unix + "\t\t")
  32. os.Stdout.WriteString(ctx.Yellow(send_text) + "\r\n")
  33. }
  34. func run_legacy_loop(opts *Options) (err error) {
  35. term, err := tty.OpenControllingTerm(tty.SetRaw)
  36. if err != nil {
  37. return err
  38. }
  39. defer func() {
  40. term.RestoreAndClose()
  41. }()
  42. if opts.KeyMode != "unchanged" {
  43. os.Stdout.WriteString("\x1b[?1")
  44. switch opts.KeyMode {
  45. case "normal":
  46. os.Stdout.WriteString("l")
  47. default:
  48. os.Stdout.WriteString("h")
  49. }
  50. defer func() {
  51. os.Stdout.WriteString("\x1b[?1l")
  52. }()
  53. }
  54. fmt.Print("Press any keys - Ctrl+D will terminate this program\r\n")
  55. ctx := markup.New(true)
  56. fmt.Print(ctx.Green("UNIX\t\tsend_text\r\n"))
  57. buf := make([]byte, 64)
  58. for {
  59. n, err := term.Read(buf)
  60. if err != nil {
  61. if errors.Is(err, io.EOF) {
  62. break
  63. }
  64. if !(errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EBUSY)) {
  65. return err
  66. }
  67. }
  68. if n > 0 {
  69. print_key(buf[:n], ctx)
  70. if n == 1 && buf[0] == 4 {
  71. break
  72. }
  73. }
  74. }
  75. return
  76. }