hold.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package tui
  3. import (
  4. "errors"
  5. "fmt"
  6. "os"
  7. "os/exec"
  8. "kitty/tools/tui/loop"
  9. )
  10. var _ = fmt.Print
  11. func HoldTillEnter(start_with_newline bool) {
  12. lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors, loop.NoMouseTracking)
  13. if err != nil {
  14. return
  15. }
  16. lp.OnInitialize = func() (string, error) {
  17. lp.SetCursorVisible(false)
  18. if start_with_newline {
  19. lp.QueueWriteString("\r\n")
  20. }
  21. lp.QueueWriteString("\x1b[1;32mPress Enter or Esc to exit\x1b[m")
  22. return "", nil
  23. }
  24. lp.OnFinalize = func() string {
  25. lp.SetCursorVisible(true)
  26. return ""
  27. }
  28. lp.OnKeyEvent = func(event *loop.KeyEvent) error {
  29. if event.MatchesPressOrRepeat("enter") || event.MatchesPressOrRepeat("kp_enter") || event.MatchesPressOrRepeat("esc") || event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("ctrl+d") {
  30. event.Handled = true
  31. lp.Quit(0)
  32. }
  33. return nil
  34. }
  35. lp.Run()
  36. }
  37. func ExecAndHoldTillEnter(cmdline []string) {
  38. if len(cmdline) == 0 {
  39. HoldTillEnter(false)
  40. os.Exit(0)
  41. }
  42. var cmd *exec.Cmd
  43. if len(cmdline) == 1 {
  44. cmd = exec.Command(cmdline[0])
  45. } else {
  46. cmd = exec.Command(cmdline[0], cmdline[1:]...)
  47. }
  48. cmd.Stdin = os.Stdin
  49. cmd.Stdout = os.Stdout
  50. cmd.Stderr = os.Stderr
  51. var ee *exec.ExitError
  52. err := cmd.Run()
  53. is_exit_error := err != nil && errors.As(err, &ee)
  54. if err != nil && !is_exit_error {
  55. fmt.Fprintln(os.Stderr, err)
  56. }
  57. HoldTillEnter(true)
  58. if err == nil {
  59. os.Exit(0)
  60. }
  61. if is_exit_error {
  62. os.Exit(ee.ExitCode())
  63. }
  64. os.Exit(1)
  65. }