nyble

A snake game for the terminal.


nyble

/

src

/

ob

/

readline.hh

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
/*
                                    88888888
                                  888888888888
                                 88888888888888
                                8888888888888888
                               888888888888888888
                              888888  8888  888888
                              88888    88    88888
                              888888  8888  888888
                              88888888888888888888
                              88888888888888888888
                             8888888888888888888888
                          8888888888888888888888888888
                        88888888888888888888888888888888
                              88888888888888888888
                            888888888888888888888888
                           888888  8888888888  888888
                           888     8888  8888     888
                                   888    888

                                   OCTOBANANA

Licensed under the MIT License

Copyright (c) 2019 Brett Robinson <https://octobanana.com/>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef OB_READLINE_HH
#define OB_READLINE_HH

#include "ob/term.hh"
#include "ob/text.hh"
#include "ob/string.hh"

#include <cstddef>

#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <limits>
#include <fstream>
#include <filesystem>

namespace OB
{

namespace fs = std::filesystem;
namespace aec = OB::Term::ANSI_Escape_Codes;

class Readline
{
public:

  Readline() = default;

  friend std::ostream& operator<<(std::ostream& os, Readline const& obj);

  void autocomplete(std::function<std::vector<std::string>()> const& val_);
  void boundaries(std::string const& val_);
  std::string word_under_cursor(std::string const& delimiters);
  Readline& style(std::string const& style_ = {});
  Readline& prompt(std::string const& str_, std::string const& style_ = {});
  Readline& size(std::size_t const width_, std::size_t const height_);
  bool operator()(OB::Text::Char32 input);
  std::string render() const;
  std::string get();
  Readline& clear();
  Readline& refresh();
  Readline& normal();

  void hist_push(std::string const& str);
  void hist_load(fs::path const& path);

// private:

  // cursor
  void curs_begin();
  void curs_end();
  void curs_left();
  void curs_right();

  // edit
  void edit_clear();
  bool edit_delete();
  void edit_insert(std::string const& str);
  bool edit_backspace();
  // TODO autopair should not run when pasting
  void edit_insert_autopair(OB::Text::Char32 const& val);
  void edit_backspace_autopair();

  // history
  void hist_prev();
  void hist_next();
  void hist_reset();
  void hist_search(std::string const& str);
  void hist_open(fs::path const& path);
  void hist_save(std::string const& str);

  // autocomplete
  void ac_init();
  void ac_sync();
  void ac_begin();
  void ac_end();
  void ac_prev();
  void ac_next();
  void ac_prev_section();
  void ac_next_section();

  std::string normalize(std::string const& str) const;

  enum class Mode
  {
    normal,
    history_init,
    history,
    autocomplete_init,
    autocomplete,
  };

  void mode(Mode const mode_);

  Mode _mode {Mode::normal};
  Mode _mode_prev {Mode::normal};

  std::string _boundaries {" "};

  // width and height of the terminal
  std::size_t _width {0};
  std::size_t _height {0};

  std::string _res;

  struct Style
  {
    std::string prompt;
    std::string input;
  } _style;

  struct Prompt
  {
    std::string lhs;
    std::string rhs;
    std::string fmt;
    std::string str {":"};
  } _prompt;

  struct Input
  {
    bool save_local {true};
    bool save_file {true};
    bool clear_input {false};
    std::size_t offp {0};
    std::size_t idxp {0};
    std::size_t off {0};
    std::size_t idx {0};
    std::size_t cur {0};
    std::string buf;
    std::string clipboard;
    OB::Text::String str;
    OB::Text::String fmt;
  } _input;

  struct History
  {
    static std::size_t constexpr npos {std::numeric_limits<std::size_t>::max()};

    struct Search
    {
      struct Result
      {
        Result(std::size_t s, std::size_t i) noexcept :
          score {s},
          idx {i}
        {
        }

        std::size_t score {0};
        std::size_t idx {0};
      };

      using value_type = std::deque<Result>;

      value_type& operator()()
      {
        return val;
      }

      bool empty()
      {
        return val.empty();
      }

      void clear()
      {
        idx = History::npos;
        val.clear();
      }

      std::size_t idx {0};
      value_type val;
    } search;

    using value_type = std::deque<std::string>;

    value_type& operator()()
    {
      return val;
    }

    value_type val;
    std::size_t idx {npos};

    std::ofstream file;
  } _history;

  struct Autocomplete
  {
    friend std::ostream& operator<<(std::ostream& os, Autocomplete const& obj)
    {
      os << obj.render();

      return os;
    }

    void width(std::size_t const width_)
    {
      _width = width_;
    }

    std::string render() const
    {
      return _value;
    }

    Autocomplete& refresh()
    {
      _lhs = _off ? "<" : "";
      _rhs = _off + _max != _match.size() ? ">" : " ";

      std::ostringstream ss;

      for (std::size_t i = 0, n = _off ? 1ul : 0ul; i < _max; ++i)
      {
        if (i == _idx)
        {
          _hli = n;
          _hls = _view.at(i + _off).cols();
          ss << _match.at(i + _off);
        }
        else
        {
          ss << _match.at(i + _off);
        }

        if (i + 1 < _max)
        {
          ss << " ";
        }

        if (i < _idx)
        {
          n += _view.at(i + _off).cols() + 1;
        }
      }

      _text = ss.str();

      return *this;
    }

    // Autocomplete& refresh()
    // {
    //   std::ostringstream ss;

    //   if (_off)
    //   {
    //     ss
    //     << aec::clear
    //     << _style.prompt
    //     << "<"
    //     << aec::clear
    //     << _style.normal
    //     << OB::String::repeat(_width - 2, aec::space)
    //     << aec::clear
    //     << _style.prompt
    //     << (_off + _max != _match.size() ? ">" : " ")
    //     << aec::clear
    //     << _style.normal
    //     << aec::cr << aec::cursor_right(1);
    //   }
    //   else
    //   {
    //     ss
    //     << aec::clear
    //     << _style.normal
    //     << OB::String::repeat(_width - 1, aec::space)
    //     << aec::clear
    //     << _style.prompt
    //     << (_off + _max != _match.size() ? ">" : " ")
    //     << aec::clear
    //     << _style.normal
    //     << aec::cr;
    //   }

    //   for (std::size_t i = 0; i < _max; ++i)
    //   {
    //     if (i == _idx)
    //     {
    //       ss
    //       << aec::clear
    //       << _style.select
    //       << _match.at(i + _off)
    //       << aec::clear
    //       << _style.normal;
    //     }
    //     else
    //     {
    //       ss
    //       << _match.at(i + _off);
    //     }

    //     if (i + 1 < _max)
    //     {
    //       ss
    //       << aec::space;
    //     }
    //   }

    //   ss
    //   << aec::clear;

    //   _value = ss.str();

    //   return *this;
    // }

    Autocomplete& begin()
    {
      // move to begin of list
      // idx = 0
      // off = 0
      while (_off)
      {
        prev_section();
      }

      return *this;
    }

    Autocomplete& end()
    {
      while (_off + _max < _match.size())
      {
        next_section();
      }

      return *this;
    }

    Autocomplete& next()
    {
      if (_idx + 1 < _max)
      {
        ++_idx;
      }
      else if (_off + _max < _match.size())
      {
        _off += _max;
        _maxp.push(_max);
        setup();
      }

      return *this;
    }

    Autocomplete& prev()
    {
      if (_idx)
      {
        --_idx;
      }
      else if (_off)
      {
        _off -= _maxp.top();
        _maxp.pop();
        setup();
        _idx = _max - 1;
      }

      return *this;
    }

    Autocomplete& next_section()
    {
      _idx = _max - 1;
      next();

      return *this;
    }

    Autocomplete& prev_section()
    {
      _idx = 0;
      prev();
      _idx = 0;

      return *this;
    }

    void setup()
    {
      _idx = 0;
      _max = 0;

      if (_view.empty())
      {
        return;
      }

      std::size_t constexpr space {1};
      std::size_t len {_off ? 1ul : 0ul};
      std::size_t tmp {len};
      for (std::size_t i = 0; i < _view.size() && _off + i < _view.size(); ++i, ++_max)
      {
        tmp += _view.at(_off + i).cols() + space;
        if (tmp > _width)
        {
          break;
        }
        len += tmp;
      }
    }

    Autocomplete& word(std::string const& str_)
    {
      _word = str_;

      return *this;
    }

    std::string const& word()
    {
      return _word;
    }

    // call each time autocomplete mode is entered
    Autocomplete& generate()
    {
      _idx = 0;
      _off = 0;
      _max = 0;
      _maxp = {};
      _match.clear();
      _view.clear();

      if (! _update)
      {
        return *this;
      }

      // TODO remove duplicates there could be same named vars in different scopes
      if (_word.size())
      {
        _match = find_similar(_word, _update());
      }
      else
      {
        _match = _update();
        std::sort(_match.begin(), _match.end(),
        [](auto const& lhs, auto const& rhs)
        {
          return (lhs.size() == rhs.size()) ?
            (lhs < rhs) :
            (lhs.size() < rhs.size());
        });
      }

      for (auto const& e : _match)
      {
        _view.emplace_back(OB::Text::View(e));
      }

      setup();

      return *this;
    }

    std::vector<std::string> find_similar(
      std::string const& key, std::vector<std::string> const& values) const
    {
      int const weight_max {8};
      size_t const similar_max {1024};

      // TODO use single vec and erase elements that are > weight_max
      std::vector<std::string> results;
      std::vector<std::pair<int, std::string>> dist;

      for (auto const& val : values)
      {
        if (val.size() < key.size())
        {
          continue;
        }

        int const weight = OB::String::starts_with(val, key) ? 0 :
          OB::String::damerau_levenshtein(key, val, 1, 2, 4, 0);

        if (weight < weight_max)
        {
          dist.emplace_back(weight, val);
        }
      }

      std::sort(dist.begin(), dist.end(),
      [](auto const& lhs, auto const& rhs)
      {
        return (lhs.first == rhs.first) ?
          (lhs.second.size() == rhs.second.size() ?
           lhs.second < rhs.second :
           lhs.second.size() < rhs.second.size()) :
          (lhs.first < rhs.first);
      });

      for (auto const& [key, val] : dist)
      {
        results.emplace_back(val);
      }

      if (results.size() > similar_max)
      {
        results.erase(results.begin() + similar_max, results.end());
      }

      return results;
    }

    struct Style
    {
      std::string prompt;
      std::string normal;
      std::string select {aec::reverse};
    } _style;

    std::size_t _hli {0}; // highlight index
    std::size_t _hls {0}; // highlight size
    std::string _lhs;
    std::string _rhs;
    std::string _text;

    // string value
    std::string _value;

    // word to autocomplete on
    std::string _word;

    // word offset
    std::size_t _off {0};

    // current selected word index
    std::size_t _idx {0};

    // current max number of words that fit on the current screen width
    std::size_t _max {0};

    // previous max number of words that fit on the current screen width
    std::stack<std::size_t> _maxp;

    // screen width
    std::size_t _width {0};

    std::vector<std::string> _match;
    std::vector<OB::Text::View> _view;
    std::function<std::vector<std::string>()> _update;
  } _autocomplete;
};

} // namespace OB

#endif // OB_READLINE_HH
Back to Top