kitty.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package show_key
  3. import (
  4. "fmt"
  5. "strings"
  6. "kitty/tools/cli/markup"
  7. "kitty/tools/tui/loop"
  8. )
  9. var _ = fmt.Print
  10. func csi(csi string) string {
  11. return "CSI " + strings.NewReplacer(":", " : ", ";", " ; ").Replace(csi[:len(csi)-1]) + " " + csi[len(csi)-1:]
  12. }
  13. func run_kitty_loop(_ *Options) (err error) {
  14. lp, err := loop.New(loop.FullKeyboardProtocol)
  15. if err != nil {
  16. return err
  17. }
  18. ctx := markup.New(true)
  19. lp.OnInitialize = func() (string, error) {
  20. lp.SetCursorVisible(false)
  21. lp.SetWindowTitle("kitty extended keyboard protocol demo")
  22. lp.Println("Press any keys - Ctrl+C or Ctrl+D will terminate")
  23. return "", nil
  24. }
  25. lp.OnKeyEvent = func(e *loop.KeyEvent) (err error) {
  26. e.Handled = true
  27. if e.MatchesPressOrRepeat("ctrl+c") || e.MatchesPressOrRepeat("ctrl+d") {
  28. lp.Quit(0)
  29. return
  30. }
  31. mods := e.Mods.String()
  32. if mods != "" {
  33. mods += "+"
  34. }
  35. etype := e.Type.String()
  36. key := e.Key
  37. if key == " " {
  38. key = "space"
  39. }
  40. key = mods + key
  41. lp.Printf("%s %s %s\r\n", ctx.Green(key), ctx.Yellow(etype), e.Text)
  42. lp.Println(ctx.Cyan(csi(e.CSI)))
  43. if e.AlternateKey != "" || e.ShiftedKey != "" {
  44. if e.ShiftedKey != "" {
  45. lp.QueueWriteString(ctx.Dim("Shifted key: "))
  46. lp.QueueWriteString(e.ShiftedKey + " ")
  47. }
  48. if e.AlternateKey != "" {
  49. lp.QueueWriteString(ctx.Dim("Alternate key: "))
  50. lp.QueueWriteString(e.AlternateKey + " ")
  51. }
  52. lp.Println()
  53. }
  54. lp.Println()
  55. return
  56. }
  57. lp.OnText = func(text string, from_key_event bool, in_bracketed_paste bool) error {
  58. if from_key_event {
  59. return nil
  60. }
  61. lp.Printf("%s: %s\n\n", ctx.Green("Text"), text)
  62. return nil
  63. }
  64. err = lp.Run()
  65. if err != nil {
  66. return
  67. }
  68. ds := lp.DeathSignalName()
  69. if ds != "" {
  70. fmt.Println("Killed by signal: ", ds)
  71. lp.KillIfSignalled()
  72. return
  73. }
  74. return
  75. }