| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- //
- // cli.cpp
- // ncurses-wrapper
- //
- // Created by Sam Jaffe on 7/23/24.
- //
- #include "ncurses-wrapper/cli.h"
- #include "ncurses-wrapper/window.h"
- namespace curses {
- void Cli::loop(std::function<void(curses::Window &, std::string)> on_enter) {
- window_.printf("%s", prompt_.c_str());
- while (true) {
- int ch;
- switch (ch = window_.getch()) {
- case KEY_UP:
- if (vertical_offset_ + 1 < stack_.size()) {
- ++vertical_offset_;
- horizontal_offset_ = 0;
- window_.clear_line();
- window_.printf("%s%s", prompt_.c_str(), get().c_str());
- }
- break;
- case KEY_DOWN:
- if (vertical_offset_ > 0) {
- --vertical_offset_;
- horizontal_offset_ = 0;
- window_.clear_line();
- window_.printf("%s%s", prompt_.c_str(), get().c_str());
- }
- break;
- case KEY_LEFT:
- if (horizontal_offset_ + 1 < get().size()) {
- ++horizontal_offset_;
- window_.move(Offset{-1, 0});
- }
- break;
- case KEY_RIGHT:
- if (horizontal_offset_ > 0) {
- --horizontal_offset_;
- window_.move(Offset{1, 0});
- }
- break;
- case KEY_BACKSPACE:
- case KEY_DC:
- case 127:
- if (horizontal_offset_ < get().size()) {
- get().erase(get().end() - horizontal_offset_ - 1);
- window_.move(Offset{-1, 0});
- window_.delch();
- }
- break;
- case 10:
- case KEY_ENTER:
- window_.printf("\n");
- if (!get().empty()) {
- on_enter(window_, get());
- stack_.emplace_back();
- }
- window_.printf("%s", prompt_.c_str());
- break;
- default:
- get().insert(get().size() - horizontal_offset_, 1, ch);
- window_.printf("%c", ch);
- if (horizontal_offset_ > 0) {
- window_.printf("%s", get().c_str() + get().size() - horizontal_offset_);
- window_.move(Offset{-horizontal_offset_, 0});
- }
- break;
- }
- }
- }
- }
|