cli.cxx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // cli.cpp
  3. // ncurses-wrapper
  4. //
  5. // Created by Sam Jaffe on 7/23/24.
  6. //
  7. #include "ncurses-wrapper/cli.h"
  8. #include "ncurses-wrapper/window.h"
  9. namespace curses {
  10. void Cli::loop(std::function<void(curses::Window &, std::string)> on_enter) {
  11. window_.printf("%s", prompt_.c_str());
  12. while (true) {
  13. int ch;
  14. switch (ch = window_.getch()) {
  15. case KEY_UP:
  16. if (vertical_offset_ + 1 < stack_.size()) {
  17. ++vertical_offset_;
  18. horizontal_offset_ = 0;
  19. window_.clear_line();
  20. window_.printf("%s%s", prompt_.c_str(), get().c_str());
  21. }
  22. break;
  23. case KEY_DOWN:
  24. if (vertical_offset_ > 0) {
  25. --vertical_offset_;
  26. horizontal_offset_ = 0;
  27. window_.clear_line();
  28. window_.printf("%s%s", prompt_.c_str(), get().c_str());
  29. }
  30. break;
  31. case KEY_LEFT:
  32. if (horizontal_offset_ + 1 < get().size()) {
  33. ++horizontal_offset_;
  34. window_.move(Offset{-1, 0});
  35. }
  36. break;
  37. case KEY_RIGHT:
  38. if (horizontal_offset_ > 0) {
  39. --horizontal_offset_;
  40. window_.move(Offset{1, 0});
  41. }
  42. break;
  43. case KEY_BACKSPACE:
  44. case KEY_DC:
  45. case 127:
  46. if (horizontal_offset_ < get().size()) {
  47. get().erase(get().end() - horizontal_offset_ - 1);
  48. window_.move(Offset{-1, 0});
  49. window_.delch();
  50. }
  51. break;
  52. case 10:
  53. case KEY_ENTER:
  54. window_.printf("\n");
  55. if (!get().empty()) {
  56. on_enter(window_, get());
  57. stack_.emplace_back();
  58. }
  59. window_.printf("%s", prompt_.c_str());
  60. break;
  61. default:
  62. get().insert(get().size() - horizontal_offset_, 1, ch);
  63. window_.printf("%c", ch);
  64. if (horizontal_offset_ > 0) {
  65. window_.printf("%s", get().c_str() + get().size() - horizontal_offset_);
  66. window_.move(Offset{-horizontal_offset_, 0});
  67. }
  68. break;
  69. }
  70. }
  71. }
  72. }