kakoune

Fork of kakoune, an acceptable text editor
git clone git://git.laack.co/kakoune.git
Log | Files | Refs

terminal_ui.cc (53917B)


      1 #include "terminal_ui.hh"
      2 
      3 #include "display_buffer.hh"
      4 #include "event_manager.hh"
      5 #include "exception.hh"
      6 #include "file.hh"
      7 #include "keys.hh"
      8 #include "ranges.hh"
      9 #include "format.hh"
     10 #include "diff.hh"
     11 #include "string_utils.hh"
     12 
     13 #include <algorithm>
     14 
     15 #include <fcntl.h>
     16 #include <csignal>
     17 #include <sys/ioctl.h>
     18 #include <unistd.h>
     19 #include <strings.h>
     20 
     21 namespace Kakoune
     22 {
     23 
     24 using std::min;
     25 using std::max;
     26 
     27 static String fix_atom_text(StringView str)
     28 {
     29     String res;
     30     auto pos = str.begin();
     31     for (auto it = str.begin(), end = str.end(); it != end; ++it)
     32     {
     33         unsigned char c = *it;
     34         if (c <= 0x1F)
     35         {
     36             res += StringView{pos, it};
     37             res += String{Codepoint{(uint32_t)(0x2400 + c)}};
     38             pos = it+1;
     39         }
     40     }
     41     res += StringView{pos, str.end()};
     42     return res;
     43 }
     44 
     45 struct TerminalUI::Window::Line
     46 {
     47     struct Atom
     48     {
     49         String text;
     50         ColumnCount skip = 0;
     51         Face face;
     52 
     53         ColumnCount length() const { return text.column_length() + skip; }
     54         void resize(ColumnCount size)
     55         {
     56             auto it = text.begin(), end = text.end();
     57             while (it != end and size > 0)
     58                 size -= codepoint_width(utf8::read_codepoint(it, end));
     59 
     60             if (size < 0) // possible if resizing to the middle of a double-width codepoint
     61             {
     62                 kak_assert(size == -1);
     63                 utf8::to_previous(it, text.begin());
     64                 skip = 1;
     65             }
     66             else
     67                 skip = size;
     68             text.resize(it - text.begin(), 0);
     69         }
     70 
     71         friend bool operator==(const Atom& lhs, const Atom& rhs) = default;
     72         friend size_t hash_value(const Atom& atom) { return hash_values(atom.text, atom.skip, atom.face); }
     73     };
     74 
     75     void append(StringView text, ColumnCount skip, Face face)
     76     {
     77         if (not atoms.empty() and atoms.back().face == face and (atoms.back().skip == 0 or text.empty()))
     78         {
     79             atoms.back().text += fix_atom_text(text);
     80             atoms.back().skip += skip;
     81         }
     82         else
     83             atoms.push_back({fix_atom_text(text), skip, face});
     84     }
     85 
     86     void resize(ColumnCount width)
     87     {
     88         auto it = atoms.begin();
     89         ColumnCount column = 0;
     90         for (; it != atoms.end() and column < width; ++it)
     91             column += it->length();
     92 
     93         if (column < width)
     94             append({}, width - column, atoms.empty() ? Face{} : atoms.back().face);
     95         else
     96         {
     97             atoms.erase(it, atoms.end());
     98             if (column > width)
     99                 atoms.back().resize(atoms.back().length() - (column - width));
    100         }
    101     }
    102 
    103     Vector<Atom>::iterator erase_range(ColumnCount pos, ColumnCount len)
    104     {
    105         struct Pos{ Vector<Atom>::iterator it; ColumnCount column; };
    106         auto find_col = [pos=0_col, it=atoms.begin(), end=atoms.end()](ColumnCount col) mutable {
    107             for (; it != end; ++it)
    108             {
    109                 auto atom_len = it->length();
    110                 if (pos + atom_len >= col)
    111                     return Pos{it, col - pos};
    112                 pos += atom_len;
    113             }
    114             return Pos{it, 0_col};
    115         };
    116         Pos begin = find_col(pos);
    117         Pos end = find_col(pos+len);
    118 
    119         auto make_tail = [](const Atom& atom, ColumnCount from) {
    120             auto it = atom.text.begin(), end = atom.text.end();
    121             while (it != end and from > 0)
    122                 from -= codepoint_width(utf8::read_codepoint(it, end));
    123 
    124             if (from < 0) // can happen if tail starts in the middle of a double-width codepoint
    125             {
    126                 kak_assert(from == -1);
    127                 return Atom{" " + StringView{it, end}, atom.skip, atom.face};
    128             }
    129             return Atom{{it, end}, atom.skip - from, atom.face};
    130         };
    131 
    132         if (begin.it == end.it)
    133         {
    134             Atom tail = make_tail(*begin.it, end.column);
    135             begin.it->resize(begin.column);
    136             return (tail.text.empty() and tail.skip == 0) ? begin.it+1 : atoms.insert(begin.it+1, tail);
    137         }
    138 
    139         begin.it->resize(begin.column);
    140         if (end.column > 0)
    141         {
    142             if (end.column == end.it->length())
    143                 ++end.it;
    144             else
    145                 *end.it = make_tail(*end.it, end.column);
    146         }
    147         return atoms.erase(begin.it+1, end.it);
    148     }
    149 
    150     Vector<Atom> atoms;
    151 };
    152 
    153 void TerminalUI::Window::create(const DisplayCoord& p, const DisplayCoord& s)
    154 {
    155     kak_assert(p.line >= 0 and p.column >= 0);
    156     kak_assert(s.line >= 0 and s.column >= 0);
    157     pos = p;
    158     size = s;
    159     lines.reset(new Line[(int)size.line]);
    160 }
    161 
    162 void TerminalUI::Window::destroy()
    163 {
    164     pos = DisplayCoord{};
    165     size = DisplayCoord{};
    166     lines.reset();
    167 }
    168 
    169 void TerminalUI::Window::blit(Window& target)
    170 {
    171     kak_assert(pos.line < target.size.line);
    172     LineCount line_index = pos.line;
    173     for (auto& line : ArrayView{lines.get(), (size_t)size.line})
    174     {
    175         line.resize(size.column);
    176         auto& target_line = target.lines[(size_t)line_index];
    177         target_line.resize(target.size.column);
    178         target_line.atoms.insert(target_line.erase_range(pos.column, size.column), line.atoms.begin(), line.atoms.end());
    179         if (++line_index == target.size.line)
    180             break;
    181     }
    182 }
    183 
    184 void TerminalUI::Window::draw(DisplayCoord pos,
    185                               ConstArrayView<DisplayAtom> atoms,
    186                               const Face& default_face)
    187 {
    188     if (pos.line >= size.line) // We might receive an out of date draw command after a resize
    189         return;
    190 
    191     lines[(size_t)pos.line].resize(pos.column);
    192     for (const DisplayAtom& atom : atoms)
    193     {
    194         StringView content = atom.content();
    195         if (content.empty())
    196             continue;
    197 
    198         auto face = merge_faces(default_face, atom.face);
    199         if (content.back() == '\n')
    200             lines[(int)pos.line].append(content.substr(0, content.length()-1), 1, face);
    201         else
    202             lines[(int)pos.line].append(content, 0, face);
    203         pos.column += content.column_length();
    204     }
    205 
    206     if (pos.column < size.column)
    207         lines[(int)pos.line].append({}, size.column - pos.column, default_face);
    208 }
    209 
    210 struct Writer : BufferedWriter<true>
    211 {
    212     using Writer::BufferedWriter::BufferedWriter;
    213     ~Writer() noexcept(false) = default;
    214 };
    215 
    216 template<typename... Args>
    217 static void format_with(Writer& writer, StringView format, Args&&... args)
    218 {
    219     format_with([&](StringView s) { writer.write(s); }, format, std::forward<Args>(args)...);
    220 }
    221 
    222 void TerminalUI::Screen::set_face(const Face& face, Writer& writer)
    223 {
    224     static constexpr int fg_table[]{ 39, 30, 31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96, 97 };
    225     static constexpr int bg_table[]{ 49, 40, 41, 42, 43, 44, 45, 46, 47, 100, 101, 102, 103, 104, 105, 106, 107 };
    226     static constexpr int ul_table[]{ 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
    227     static constexpr const char* attr_table[]{ "0", "4", "4:3", "21", "7", "5", "1", "2", "3", "9" };
    228 
    229     auto set_color = [&](bool fg, const Color& color, bool join) {
    230         if (join)
    231             writer.write(";");
    232         if (color.isRGB())
    233             format_with(writer, "{};2;{};{};{}", fg ? 38 : 48, color.r, color.g, color.b);
    234         else
    235             format_with(writer, "{}", (fg ? fg_table : bg_table)[(int)(char)color.color]);
    236     };
    237 
    238     if (m_active_face == face)
    239         return;
    240 
    241     writer.write("\033[");
    242     bool join = false;
    243     if (face.attributes != m_active_face.attributes)
    244     {
    245         for (int i = 0; i < std::size(attr_table); ++i)
    246         {
    247             if (face.attributes & (Attribute)(1 << i))
    248                 format_with(writer, ";{}", attr_table[i]);
    249         }
    250         m_active_face.fg = m_active_face.bg = m_active_face.underline = Color::Default;
    251         join = true;
    252     }
    253     if (m_active_face.fg != face.fg)
    254     {
    255         set_color(true, face.fg, join);
    256         join = true;
    257     }
    258     if (m_active_face.bg != face.bg)
    259     {
    260         set_color(false, face.bg, join);
    261         join = true;
    262     }
    263     if (m_active_face.underline != face.underline)
    264     {
    265         if (join)
    266             writer.write(";");
    267         if (face.underline != Color::Default)
    268         {
    269             if (face.underline.isRGB())
    270                 format_with(writer, "58:2::{}:{}:{}", face.underline.r, face.underline.g, face.underline.b);
    271             else
    272                 format_with(writer, "58:5:{}", ul_table[(int)(char)face.underline.color]);
    273         }
    274         else
    275             format_with(writer, "59");
    276     }
    277     writer.write("m");
    278 
    279     m_active_face = face;
    280 }
    281 
    282 void TerminalUI::Screen::output(bool force, bool synchronized, Writer& writer)
    283 {
    284     if (not lines)
    285         return;
    286 
    287     if (force)
    288     {
    289         std::fill_n(hashes.get(), (size_t)size.line, 0);
    290         writer.write("\033[m");
    291         m_active_face = Face{};
    292     }
    293 
    294     auto hash_line = [](const Line& line) {
    295         return (hash_value(line.atoms) << 1) | 1; // ensure non-zero
    296     };
    297 
    298     auto output_line = [&](const Line& line) {
    299         ColumnCount pending_move = 0;
    300         for (auto& [text, skip, face] : line.atoms)
    301         {
    302             if (text.empty() and skip == 0)
    303                 continue;
    304 
    305             if (pending_move != 0)
    306             {
    307                 format_with(writer, "\033[{}C", (int)pending_move);
    308                 pending_move = 0;
    309             }
    310             set_face(face, writer);
    311             writer.write(text);
    312             if (skip > 3 and face.attributes == Attribute{})
    313             {
    314                 writer.write("\033[K");
    315                 pending_move = skip;
    316             }
    317             else if (skip > 0)
    318                 writer.write(String{' ', skip});
    319         }
    320     };
    321 
    322     if (synchronized)
    323     {
    324         writer.write("\033[?2026h"); // begin synchronized update
    325 
    326         struct Change { int keep; int add; int del; };
    327         Vector<Change> changes{Change{}};
    328         auto new_hashes = ArrayView{lines.get(), (size_t)size.line} | transform(hash_line);
    329         for_each_diff(hashes.get(), (int)size.line,
    330                       new_hashes.begin(), (int)size.line,
    331                       [&changes](DiffOp op, int len) mutable {
    332             switch (op)
    333             {
    334                 case DiffOp::Keep:
    335                     changes.push_back({len, 0, 0});
    336                     break;
    337                 case DiffOp::Add:
    338                     changes.back().add += len;
    339                     break;
    340                 case DiffOp::Remove:
    341                     changes.back().del += len;
    342                     break;
    343             }
    344         });
    345         std::copy(new_hashes.begin(), new_hashes.end(), hashes.get());
    346 
    347         int line = 0;
    348         for (auto& change : changes)
    349         {
    350             line += change.keep;
    351             if (int del = change.del - change.add; del > 0)
    352             {
    353                 format_with(writer, "\033[{}H\033[{}M", line + 1, del);
    354                 line -= del;
    355             }
    356             line += change.del;
    357         }
    358 
    359         line = 0;
    360         for (auto& change : changes)
    361         {
    362             line += change.keep;
    363             for (int i = 0; i < change.add; ++i)
    364             {
    365                 if (int add = change.add - change.del; i == 0 and add > 0)
    366                     format_with(writer, "\033[{}H\033[{}L", line + 1, add);
    367                 else
    368                     format_with(writer, "\033[{}H", line + 1);
    369 
    370                 output_line(lines[line++]);
    371             }
    372         }
    373 
    374         writer.write("\033[?2026l"); // end synchronized update
    375     }
    376     else
    377     {
    378         for (int line = 0; line < (int)size.line; ++line)
    379         {
    380             auto hash = hash_line(lines[line]);
    381             if (hash == hashes[line])
    382                 continue;
    383             hashes[line] = hash;
    384 
    385             format_with(writer, "\033[{}H", line + 1);
    386             output_line(lines[line]);
    387         }
    388     }
    389 }
    390 
    391 constexpr int TerminalUI::default_shift_function_key;
    392 
    393 static constexpr StringView assistant_cat[] =
    394     { R"(  ___            )",
    395       R"( (__ \           )",
    396       R"(   / /          ╭)",
    397       R"(  .' '·.        │)",
    398       R"( '      ”       │)",
    399       R"( ╰       /\_/|  │)",
    400       R"(  | .         \ │)",
    401       R"(  ╰_J`    | | | ╯)",
    402       R"(      ' \__- _/  )",
    403       R"(      \_\   \_\  )",
    404       R"(                 )"};
    405 
    406 static constexpr StringView assistant_clippy[] =
    407     { " ╭──╮   ",
    408       " │  │   ",
    409       " @  @  ╭",
    410       " ││ ││ │",
    411       " ││ ││ ╯",
    412       " │╰─╯│  ",
    413       " ╰───╯  ",
    414       "        " };
    415 
    416 static constexpr StringView assistant_dilbert[] =
    417     { R"(  დოოოოოდ   )",
    418       R"(  |     |   )",
    419       R"(  |     |  ╭)",
    420       R"(  |-ᱛ ᱛ-|  │)",
    421       R"( Ͼ   ∪   Ͽ │)",
    422       R"(  |     |  ╯)",
    423       R"( ˏ`-.ŏ.-´ˎ  )",
    424       R"(     @      )",
    425       R"(      @     )",
    426       R"(            )"};
    427 
    428 template<typename T> T sq(T x) { return x * x; }
    429 
    430 static sig_atomic_t resize_pending = 0;
    431 static sig_atomic_t terminal_hungup = 0;
    432 
    433 template<sig_atomic_t* signal_flag>
    434 static void signal_handler(int)
    435 {
    436     *signal_flag = 1;
    437     EventManager::instance().force_signal(0);
    438 }
    439 
    440 TerminalUI::TerminalUI()
    441     : m_cursor_pos{},
    442       m_stdin_watcher{STDIN_FILENO, FdEvents::Read, EventMode::Urgent,
    443                       [this](FDWatcher&, FdEvents, EventMode) {
    444         if (not m_on_key)
    445             return;
    446 
    447         while (auto key = get_next_key())
    448         {
    449             if (*key == ctrl('z'))
    450                 kill(0, SIGTSTP); // We suspend at this line
    451             else if (*key != Key::Invalid)
    452                 m_on_key(*key);
    453         }
    454       }},
    455       m_assistant(assistant_clippy)
    456 {
    457     if (not isatty(1))
    458         throw runtime_error("stdout is not a tty");
    459 
    460     tcgetattr(STDIN_FILENO, &m_original_termios);
    461 
    462     setup_terminal();
    463     set_raw_mode();
    464     enable_mouse(true);
    465 
    466     set_signal_handler(SIGWINCH, &signal_handler<&resize_pending>);
    467     set_signal_handler(SIGHUP, &signal_handler<&terminal_hungup>);
    468     set_signal_handler(SIGTSTP, [](int){ TerminalUI::instance().suspend(); });
    469 
    470     check_resize(true);
    471     redraw(false);
    472 }
    473 
    474 TerminalUI::~TerminalUI()
    475 {
    476     if (not terminal_hungup) {
    477         enable_mouse(false);
    478         restore_terminal();
    479         tcsetattr(STDIN_FILENO, TCSAFLUSH, &m_original_termios);
    480     }
    481     set_signal_handler(SIGWINCH, SIG_DFL);
    482     set_signal_handler(SIGHUP, SIG_IGN);
    483     set_signal_handler(SIGTSTP, SIG_DFL);
    484 }
    485 
    486 void TerminalUI::suspend()
    487 {
    488     if (m_on_key)
    489         m_on_key(Key::FocusOut);
    490 
    491     bool mouse_enabled = m_mouse_enabled;
    492     enable_mouse(false);
    493     tcsetattr(STDIN_FILENO, TCSAFLUSH, &m_original_termios);
    494     restore_terminal();
    495 
    496     auto current = set_signal_handler(SIGTSTP, SIG_DFL);
    497     sigset_t unblock_sigtstp, old_mask;
    498     sigemptyset(&unblock_sigtstp);
    499     sigaddset(&unblock_sigtstp, SIGTSTP);
    500     sigprocmask(SIG_UNBLOCK, &unblock_sigtstp, &old_mask);
    501 
    502     raise(SIGTSTP); // suspend here
    503 
    504     set_signal_handler(SIGTSTP, current);
    505     sigprocmask(SIG_SETMASK, &old_mask, nullptr);
    506 
    507     setup_terminal();
    508     check_resize(true);
    509     set_raw_mode();
    510     enable_mouse(mouse_enabled);
    511 
    512     refresh(true);
    513 
    514     if (m_on_key)
    515         m_on_key(Key::FocusIn);
    516 }
    517 
    518 void TerminalUI::set_raw_mode() const
    519 {
    520     termios attr = m_original_termios;
    521     attr.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    522     attr.c_oflag &= ~OPOST;
    523     attr.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    524     attr.c_lflag |= NOFLSH;
    525     attr.c_cflag &= ~(CSIZE | PARENB);
    526     attr.c_cflag |= CS8;
    527     attr.c_cc[VMIN] = attr.c_cc[VTIME] = 0;
    528 
    529     tcsetattr(STDIN_FILENO, TCSANOW, &attr);
    530 }
    531 
    532 void TerminalUI::redraw(bool force)
    533 {
    534     m_window.blit(m_screen);
    535 
    536     if (m_menu.columns != 0 or m_menu.pos.column > m_status_len)
    537         m_menu.blit(m_screen);
    538 
    539     m_info.blit(m_screen);
    540 
    541     Writer writer{STDOUT_FILENO};
    542     m_screen.output(force, (bool)m_synchronized, writer);
    543 
    544     auto set_cursor_pos = [&](DisplayCoord c) {
    545         format_with(writer, "\033[{};{}H", (int)c.line + 1, (int)c.column + 1);
    546     };
    547     if (m_status_cursor_pos > 0)
    548         set_cursor_pos({m_status_on_top ? 0 : m_dimensions.line, m_status_cursor_pos});
    549     else
    550         set_cursor_pos(m_cursor_pos + content_line_offset());
    551 }
    552 
    553 void TerminalUI::refresh(bool force)
    554 {
    555     if (m_dirty or force)
    556         redraw(force);
    557     m_dirty = false;
    558 }
    559 
    560 static const DisplayLine empty_line = { String(" "), {} };
    561 
    562 void TerminalUI::draw(const DisplayBuffer& display_buffer,
    563                       DisplayCoord cursor_pos,
    564                       const Face& default_face,
    565                       const Face& padding_face,
    566                       ColumnCount)
    567 {
    568     check_resize();
    569 
    570     const DisplayCoord dim = dimensions();
    571     const LineCount line_offset = content_line_offset();
    572     LineCount line_index = line_offset;
    573     for (const DisplayLine& line : display_buffer.lines())
    574         m_window.draw(line_index++, line.atoms(), default_face);
    575 
    576     auto face = merge_faces(default_face, padding_face);
    577 
    578     DisplayAtom padding{String{m_padding_char, m_padding_fill ? dim.column : 1}};
    579 
    580     while (line_index < dim.line + line_offset)
    581         m_window.draw(line_index++, padding, face);
    582 
    583     m_cursor_pos = cursor_pos;
    584 
    585     m_dirty = true;
    586 }
    587 
    588 void TerminalUI::draw_status(const DisplayLine& prompt,
    589                              const DisplayLine& content,
    590                              const ColumnCount cursor_pos,
    591                              const DisplayLine& mode_line,
    592                              const Face& default_face,
    593                              StatusStyle)
    594 {
    595     const LineCount status_line_pos = m_status_on_top ? 0 : m_dimensions.line;
    596 
    597     auto status_width = m_dimensions.column - prompt.length();
    598     if (cursor_pos < m_status_pos)
    599         m_status_pos = cursor_pos;
    600     if (cursor_pos >= m_status_pos + status_width)
    601         m_status_pos = cursor_pos + 1 - status_width;
    602 
    603     m_status_cursor_pos = cursor_pos >= 0 ? prompt.length() + cursor_pos : -1;
    604 
    605     auto trimmed_content = content;
    606     trimmed_content.trim(m_status_pos, status_width);
    607     m_window.draw(status_line_pos, prompt.atoms(), default_face);
    608     m_window.draw(DisplayCoord{status_line_pos, prompt.length()}, trimmed_content.atoms(), default_face);
    609 
    610     const auto mode_len = mode_line.length();
    611     m_status_len = prompt.length() + trimmed_content.length();
    612     const auto remaining = m_dimensions.column - m_status_len;
    613     if (mode_len < remaining)
    614     {
    615         ColumnCount col = m_dimensions.column - mode_len;
    616         m_window.draw({status_line_pos, col}, mode_line.atoms(), default_face);
    617     }
    618     else if (remaining > 2)
    619     {
    620         DisplayLine trimmed_mode_line = mode_line;
    621         trimmed_mode_line.trim(mode_len + 2 - remaining, remaining - 2);
    622         trimmed_mode_line.insert(trimmed_mode_line.begin(), { "…", {} });
    623         kak_assert(trimmed_mode_line.length() == remaining - 1);
    624 
    625         ColumnCount col = m_dimensions.column - remaining + 1;
    626         m_window.draw({status_line_pos, col}, trimmed_mode_line.atoms(), default_face);
    627     }
    628 
    629     if (m_set_title)
    630     {
    631         Writer writer{STDOUT_FILENO};
    632         writer.write("\033]2;");
    633         auto write_escaped = [&](StringView str) {
    634             for (auto it = str.begin(), end = str.end(); it != end; utf8::to_next(it, end))
    635                 writer.write((*it >= 0x20 and *it <= 0x7e) ? *it : '?');
    636         };
    637         if (not m_title)
    638         {
    639             for (auto& atom : mode_line)
    640                 write_escaped(atom.content());
    641             writer.write(" - Kakoune");
    642         }
    643         else
    644             write_escaped(*m_title);
    645         writer.write("\007");
    646     }
    647 
    648     m_dirty = true;
    649 }
    650 
    651 void TerminalUI::check_resize(bool force)
    652 {
    653     if (not force and not resize_pending)
    654         return;
    655 
    656     resize_pending = 0;
    657 
    658     const int fd = open("/dev/tty", O_RDWR);
    659     if (fd < 0)
    660         return;
    661     auto close_fd = OnScopeEnd([fd]{ ::close(fd); });
    662 
    663     DisplayCoord terminal_size{24_line, 80_col};
    664     if (winsize ws; ioctl(fd, TIOCGWINSZ, &ws) == 0 and ws.ws_row > 0 and ws.ws_col > 0)
    665         terminal_size = {ws.ws_row, ws.ws_col};
    666 
    667     const bool info = (bool)m_info;
    668     const bool menu = (bool)m_menu;
    669     if (m_window) m_window.destroy();
    670     if (info) m_info.destroy();
    671     if (menu) m_menu.destroy();
    672 
    673     m_window.create({0, 0}, terminal_size);
    674     m_screen.create({0, 0}, terminal_size);
    675     m_screen.hashes.reset(new size_t[(int)terminal_size.line]{});
    676     kak_assert(m_window);
    677 
    678     m_dimensions = terminal_size - 1_line;
    679 
    680     // if (char* csr = tigetstr((char*)"csr"))
    681     //     putp(tparm(csr, 0, ws.ws_row));
    682 
    683     if (menu)
    684         menu_show(Vector<DisplayLine>(std::move(m_menu.items)),
    685                   m_menu.anchor, m_menu.fg, m_menu.bg, m_menu.style);
    686     if (info)
    687         info_show(m_info.title, m_info.content, m_info.anchor, m_info.face, m_info.style);
    688 
    689     set_resize_pending();
    690 }
    691 
    692 Optional<Key> TerminalUI::get_next_key()
    693 {
    694     if (terminal_hungup)
    695     {
    696         set_signal_handler(SIGWINCH, SIG_DFL);
    697         set_signal_handler(SIGHUP, SIG_IGN);
    698         if (m_window)
    699             m_window.destroy();
    700         m_stdin_watcher.disable();
    701         return {};
    702     }
    703 
    704     check_resize();
    705 
    706     if (m_resize_pending)
    707     {
    708         m_resize_pending = false;
    709         return resize(dimensions());
    710     }
    711 
    712     static auto get_char = []() -> Optional<unsigned char> {
    713         if (not fd_readable(STDIN_FILENO))
    714             return {};
    715 
    716         if (unsigned char c = 0; read(STDIN_FILENO, &c, 1) == 1)
    717             return c;
    718 
    719         terminal_hungup = 1;
    720         return {};
    721     };
    722 
    723     const auto c = get_char();
    724     if (not c)
    725         return {};
    726 
    727     static constexpr auto control = [](char c) { return c & 037; };
    728 
    729     auto convert = [this](Codepoint c) -> Codepoint {
    730         if (c == control('m'))
    731             return Key::Return;
    732         if (c == control('i'))
    733             return Key::Tab;
    734         if (c == ' ')
    735             return Key::Space;
    736         if (c == m_original_termios.c_cc[VERASE])
    737             return Key::Backspace;
    738         if (c == 127) // when it's not backspace
    739             return Key::Delete;
    740         if (c == 27)
    741             return Key::Escape;
    742         return c;
    743     };
    744     auto parse_key = [&convert](unsigned char c) -> Key {
    745         if (Codepoint cp = convert(c); cp > 255)
    746             return Key{cp};
    747         // Special case: you can type NUL with Ctrl-2 or Ctrl-Shift-2 or
    748         // Ctrl-Backtick, but the most straightforward way is Ctrl-Space.
    749         if (c == 0)
    750             return ctrl(Key::Space);
    751         // Represent Ctrl-letter combinations in lower-case, to be clear
    752         // that Shift is not involved.
    753         if (c < 27)
    754             return ctrl(c - 1 + 'a');
    755         // Represent Ctrl-symbol combinations in "upper-case", as they are
    756         // traditionally-rendered.
    757         // Note that Escape is handled elsewhere.
    758         if (c < 32)
    759             return ctrl(c - 1 + 'A');
    760 
    761        struct Sentinel{};
    762        struct CharIterator
    763        {
    764            unsigned char operator*() { if (not c) c = get_char().value_or((unsigned char)0); return *c; }
    765            CharIterator& operator++() { c.reset(); return *this; }
    766            bool operator==(const Sentinel&) const { return false; }
    767            Optional<unsigned char> c;
    768        };
    769        return Key{utf8::codepoint(CharIterator{c}, Sentinel{})};
    770     };
    771 
    772     static auto parse_mask = [](int mask) {
    773         Key::Modifiers mod = Key::Modifiers::None;
    774         if (mask & 1)
    775             mod |= Key::Modifiers::Shift;
    776         if (mask & 2)
    777             mod |= Key::Modifiers::Alt;
    778         if (mask & 4)
    779             mod |= Key::Modifiers::Control;
    780         return mod;
    781     };
    782 
    783     auto parse_csi = [this, &convert]() -> Optional<Key> {
    784         auto next_char = [] { return get_char().value_or((unsigned char)0xff); };
    785         int params[16][4] = {};
    786         auto c = next_char();
    787         char private_mode = 0;
    788         if (c == '?' or c == '<' or c == '=' or c == '>')
    789         {
    790             private_mode = c;
    791             c = next_char();
    792         }
    793         for (int count = 0, subcount = 0; count < 16 and c >= 0x30 and c <= 0x3f; c = next_char())
    794         {
    795             if (isdigit(c))
    796                 params[count][subcount] = params[count][subcount] * 10 + c - '0';
    797             else if (c == ':' and subcount < 3)
    798                 ++subcount;
    799             else if (c == ';')
    800             {
    801                 ++count;
    802                 subcount = 0;
    803             }
    804             else
    805                 return {};
    806         }
    807         if (c != '$' and (c < 0x40 or c > 0x7e))
    808             return {};
    809 
    810         auto mouse_button = [this](Key::Modifiers mod, Key::MouseButton button, Codepoint coord, bool release) {
    811             auto mask = 1 << (int)button;
    812             if (not release)
    813             {
    814                 mod |= (m_mouse_state & mask) ? Key::Modifiers::MousePos : Key::Modifiers::MousePress;
    815                 m_mouse_state |= mask;
    816             }
    817             else
    818             {
    819                 mod |= Key::Modifiers::MouseRelease;
    820                 m_mouse_state &= ~mask;
    821             }
    822             return Key{mod | Key::to_modifier(button), coord};
    823         };
    824 
    825         auto mouse_scroll = [this](Key::Modifiers mod, Codepoint coord, bool down) -> Key {
    826             return {mod | Key::Modifiers::Scroll | (Key::Modifiers)((down ? m_wheel_scroll_amount : -1 * m_wheel_scroll_amount) << 16), coord};
    827         };
    828 
    829         auto masked_key = [&](Codepoint key, Codepoint shifted_key = 0) {
    830             int mask = std::max(params[1][0] - 1, 0);
    831             Key::Modifiers modifiers = parse_mask(mask);
    832             if (shifted_key != 0 and (modifiers & Key::Modifiers::Shift))
    833             {
    834                 modifiers &= ~Key::Modifiers::Shift;
    835                 key = shifted_key;
    836             }
    837             return Key{modifiers, key};
    838         };
    839 
    840         switch (c)
    841         {
    842         case '$':
    843             if (private_mode == '?' and next_char() == 'y') // DECRPM
    844             {
    845                 if (params[0][0] == 2026)
    846                     m_synchronized.supported = (params[1][0] == 1 or params[1][0] == 2);
    847                 return Key{Key::Invalid};
    848             }
    849             switch (params[0][0])
    850             {
    851             case 23: case 24:
    852                 return Key{Key::Modifiers::Shift, Key::F11 + params[0][0] - 23}; // rxvt style
    853             }
    854             return {};
    855         case 'A': return masked_key(Key::Up);
    856         case 'B': return masked_key(Key::Down);
    857         case 'C': return masked_key(Key::Right);
    858         case 'D': return masked_key(Key::Left);
    859         case 'E': return masked_key('5');        // Numeric keypad 5
    860         case 'F': return masked_key(Key::End);   // PC/xterm style
    861         case 'H': return masked_key(Key::Home);  // PC/xterm style
    862         case 'P': return masked_key(Key::F1);
    863         case 'Q': return masked_key(Key::F2);
    864         case 'R': return masked_key(Key::F3);
    865         case 'S': return masked_key(Key::F4);
    866         case '~':
    867             switch (params[0][0])
    868             {
    869             case 1: return masked_key(Key::Home);     // VT220/tmux style
    870             case 2: return masked_key(Key::Insert);
    871             case 3: return masked_key(Key::Delete);
    872             case 4: return masked_key(Key::End);      // VT220/tmux style
    873             case 5: return masked_key(Key::PageUp);
    874             case 6: return masked_key(Key::PageDown);
    875             case 7: return masked_key(Key::Home);     // rxvt style
    876             case 8: return masked_key(Key::End);      // rxvt style
    877             case 11: case 12: case 13: case 14: case 15:
    878                 return masked_key(Key::F1 + params[0][0] - 11);
    879             case 17: case 18: case 19: case 20: case 21:
    880                 return masked_key(Key::F6 + params[0][0] - 17);
    881             case 23: case 24:
    882                 return masked_key(Key::F11 + params[0][0] - 23);
    883             case 25: case 26:
    884                 return Key{Key::Modifiers::Shift, Key::F3 + params[0][0] - 25}; // rxvt style
    885             case 27:
    886                 return masked_key(convert(static_cast<Codepoint>(params[2][0])));
    887             case 28: case 29:
    888                 return Key{Key::Modifiers::Shift, Key::F5 + params[0][0] - 28}; // rxvt style
    889             case 31: case 32:
    890                 return Key{Key::Modifiers::Shift, Key::F7 + params[0][0] - 31}; // rxvt style
    891             case 33: case 34:
    892                 return Key{Key::Modifiers::Shift, Key::F9 + params[0][0] - 33}; // rxvt style
    893             case 200:
    894                 m_paste_buffer = String{};
    895                 return Key{Key::Invalid};
    896             case 201:
    897                 if (m_paste_buffer)
    898                 {
    899                     m_on_paste(*m_paste_buffer);
    900                     m_paste_buffer.reset();
    901                 }
    902                 return Key{Key::Invalid};
    903             }
    904             return {};
    905         case 'u':
    906         {
    907             Codepoint key;
    908             switch (params[0][0])
    909             {
    910                 // Treat numpad keys the same as their non-numpad counterparts. Could add a numpad modifier here.
    911                 case 57399: key = '0'; break;
    912                 case 57400: key = '1'; break;
    913                 case 57401: key = '2'; break;
    914                 case 57402: key = '3'; break;
    915                 case 57403: key = '4'; break;
    916                 case 57404: key = '5'; break;
    917                 case 57405: key = '6'; break;
    918                 case 57406: key = '7'; break;
    919                 case 57407: key = '8'; break;
    920                 case 57408: key = '9'; break;
    921                 case 57409: key = '.'; break;
    922                 case 57410: key = '/'; break;
    923                 case 57411: key = '*'; break;
    924                 case 57412: key = '-'; break;
    925                 case 57413: key = '+'; break;
    926                 case 57414: key = Key::Return; break;
    927                 case 57415: key = '='; break;
    928                 case 57417: key = Key::Left; break;
    929                 case 57418: key = Key::Right; break;
    930                 case 57419: key = Key::Up; break;
    931                 case 57420: key = Key::Down; break;
    932                 case 57421: key = Key::PageUp; break;
    933                 case 57422: key = Key::PageDown; break;
    934                 case 57423: key = Key::Home; break;
    935                 case 57424: key = Key::End; break;
    936                 case 57425: key = Key::Insert; break;
    937                 case 57426: key = Key::Delete; break;
    938                 default: key = convert(static_cast<Codepoint>(params[0][0])); break;
    939             }
    940             return masked_key(key, convert(static_cast<Codepoint>(params[0][1])));
    941         }
    942         case 'Z': return shift(Key::Tab);
    943         case 'I': return {Key::FocusIn};
    944         case 'O': return {Key::FocusOut};
    945         case 'M': case 'm':
    946             const bool sgr = private_mode == '<';
    947             if (not sgr and c != 'M')
    948                 return {};
    949 
    950             const Codepoint b = sgr ? params[0][0] : next_char() - 32;
    951             const int x = (sgr ? params[1][0] : next_char() - 32) - 1;
    952             const int y = (sgr ? params[2][0] : next_char() - 32) - 1;
    953             auto coord = encode_coord({y - content_line_offset(), x});
    954             Key::Modifiers mod = parse_mask((b >> 2) & 0x7);
    955             switch (const int code = b & 0x43; code)
    956             {
    957             case 0: case 1: case 2:
    958                 return mouse_button(mod, Key::MouseButton{code}, coord, c == 'm');
    959             case 3:
    960                 if (sgr)
    961                     return {};
    962                 else if (int guess = ffs(m_mouse_state) - 1; 0 <= guess and guess < 3)
    963                     return mouse_button(mod, Key::MouseButton{guess}, coord, true);
    964                 break;
    965             case 64: return mouse_scroll(mod, coord, false);
    966             case 65: return mouse_scroll(mod, coord, true);
    967             }
    968             return Key{Key::Modifiers::MousePos, coord};
    969         }
    970         return {};
    971     };
    972 
    973     static auto parse_ss3 = []() -> Optional<Key> {
    974         int raw_mask = 0;
    975         char code = '0';
    976         do {
    977             raw_mask = raw_mask * 10 + (code - '0');
    978             code = get_char().value_or((unsigned char)0xff);
    979         } while (code >= '0' and code <= '9');
    980         Key::Modifiers mod = parse_mask(std::max(raw_mask - 1, 0));
    981 
    982         switch (code)
    983         {
    984         case ' ': return Key{mod, Key::Space};
    985         case 'A': return Key{mod, Key::Up};
    986         case 'B': return Key{mod, Key::Down};
    987         case 'C': return Key{mod, Key::Right};
    988         case 'D': return Key{mod, Key::Left};
    989         case 'F': return Key{mod, Key::End};
    990         case 'H': return Key{mod, Key::Home};
    991         case 'I': return Key{mod, Key::Tab};
    992         case 'M': return Key{mod, Key::Return};
    993         case 'P': return Key{mod, Key::F1};
    994         case 'Q': return Key{mod, Key::F2};
    995         case 'R': return Key{mod, Key::F3};
    996         case 'S': return Key{mod, Key::F4};
    997         case 'X': return Key{mod, '='};
    998         case 'j': return Key{mod, '*'};
    999         case 'k': return Key{mod, '+'};
   1000         case 'l': return Key{mod, ','};
   1001         case 'm': return Key{mod, '-'};
   1002         case 'n': return Key{mod, '.'};
   1003         case 'o': return Key{mod, '/'};
   1004         case 'p': return Key{mod, '0'};
   1005         case 'q': return Key{mod, '1'};
   1006         case 'r': return Key{mod, '2'};
   1007         case 's': return Key{mod, '3'};
   1008         case 't': return Key{mod, '4'};
   1009         case 'u': return Key{mod, '5'};
   1010         case 'v': return Key{mod, '6'};
   1011         case 'w': return Key{mod, '7'};
   1012         case 'x': return Key{mod, '8'};
   1013         case 'y': return Key{mod, '9'};
   1014         default: return {};
   1015         }
   1016     };
   1017 
   1018     if (*c == 27)
   1019     {
   1020         if (auto next = get_char())
   1021         {
   1022             if (*next == '[') // potential CSI
   1023                 return parse_csi().value_or(alt('['));
   1024             if (*next == 'O') // potential SS3
   1025                 return parse_ss3().value_or(alt('O'));
   1026             return alt(parse_key(*next));
   1027         }
   1028         else if (not m_paste_buffer)
   1029             return Key{Key::Escape};
   1030     }
   1031 
   1032     if (m_paste_buffer)
   1033     {
   1034         auto paste_convert = [](char c) {
   1035             switch (c)
   1036             {
   1037                 case '\r': return '\n';
   1038                 default: return c;
   1039             }
   1040         };
   1041 
   1042         m_paste_buffer->push_back(paste_convert(*c));
   1043         return Key{Key::Invalid};
   1044     }
   1045     return parse_key(*c);
   1046 }
   1047 
   1048 template<typename T>
   1049 T div_round_up(T a, T b)
   1050 {
   1051     return (a - T(1)) / b + T(1);
   1052 }
   1053 
   1054 void TerminalUI::draw_menu()
   1055 {
   1056     // menu show may have not created the window if it did not fit.
   1057     // so be tolerant.
   1058     if (not m_menu)
   1059         return;
   1060 
   1061     const int item_count = (int)m_menu.items.size();
   1062     if (m_menu.columns == 0)
   1063     {
   1064         const auto win_width = m_menu.size.column - 4;
   1065         kak_assert(m_menu.size.line == 1);
   1066         ColumnCount pos = 0;
   1067 
   1068         m_menu.draw({0, 0}, DisplayAtom(m_menu.first_item > 0 ? "< " : ""), m_menu.bg);
   1069 
   1070         int i = m_menu.first_item;
   1071         for (; i < item_count and pos < win_width; ++i)
   1072         {
   1073             const DisplayLine& item = m_menu.items[i];
   1074             const ColumnCount item_width = item.length();
   1075             auto& face = i == m_menu.selected_item ? m_menu.fg : m_menu.bg;
   1076             m_menu.draw({0, pos+2}, item.atoms(), face);
   1077             if (pos + item_width >= win_width)
   1078                 m_menu.draw({0, win_width+2}, DisplayAtom("…"), m_menu.bg);
   1079             pos += item_width + 1;
   1080         }
   1081 
   1082         if (i != item_count)
   1083             m_menu.draw({0, win_width+3}, DisplayAtom(">"), m_menu.bg);
   1084 
   1085         m_dirty = true;
   1086         return;
   1087     }
   1088 
   1089     const LineCount menu_lines = div_round_up(item_count, m_menu.columns);
   1090     const LineCount win_height = m_menu.size.line;
   1091     kak_assert(win_height <= menu_lines);
   1092 
   1093     const ColumnCount column_width = (m_menu.size.column - 1) / m_menu.columns;
   1094 
   1095     const LineCount mark_height = min(div_round_up(sq(win_height), menu_lines),
   1096                                       win_height);
   1097 
   1098     const int menu_cols = div_round_up(item_count, (int)m_menu.size.line);
   1099     const int first_col = m_menu.first_item / (int)m_menu.size.line;
   1100 
   1101     const LineCount mark_line = (win_height - mark_height) * first_col / max(1, menu_cols - m_menu.columns);
   1102 
   1103     for (auto line = 0_line; line < win_height; ++line)
   1104     {
   1105         for (int col = 0; col < m_menu.columns; ++col)
   1106         {
   1107             int item_idx = (first_col + col) * (int)m_menu.size.line + (int)line;
   1108             auto& face = item_idx < item_count and item_idx == m_menu.selected_item ? m_menu.fg : m_menu.bg;
   1109             auto atoms = item_idx < item_count ? m_menu.items[item_idx].atoms() : ConstArrayView<DisplayAtom>{};
   1110             m_menu.draw({line, col * column_width}, atoms, face);
   1111         }
   1112         const bool is_mark = line >= mark_line and line < mark_line + mark_height;
   1113         m_menu.draw({line, m_menu.size.column - 1}, DisplayAtom(is_mark ? "█" : "░"), m_menu.bg);
   1114     }
   1115     m_dirty = true;
   1116 }
   1117 
   1118 static LineCount height_limit(MenuStyle style)
   1119 {
   1120     switch (style)
   1121     {
   1122         case MenuStyle::Inline: return 10_line;
   1123         case MenuStyle::Prompt: return 10_line;
   1124         case MenuStyle::Search: return 3_line;
   1125     }
   1126     kak_assert(false);
   1127     return 0_line;
   1128 }
   1129 
   1130 void TerminalUI::menu_show(ConstArrayView<DisplayLine> items,
   1131                            DisplayCoord anchor, Face fg, Face bg,
   1132                            MenuStyle style)
   1133 {
   1134     if (m_menu)
   1135     {
   1136         m_menu.destroy();
   1137         m_dirty = true;
   1138     }
   1139 
   1140     m_menu.fg = fg;
   1141     m_menu.bg = bg;
   1142     m_menu.style = style;
   1143     m_menu.anchor = anchor;
   1144 
   1145     if (m_dimensions.column <= 2)
   1146         return;
   1147 
   1148     const int item_count = items.size();
   1149     m_menu.items.clear(); // make sure it is empty
   1150     m_menu.items.reserve(item_count);
   1151     const auto longest = accumulate(items | transform(&DisplayLine::length),
   1152                                     1_col, [](auto&& lhs, auto&& rhs) { return std::max(lhs, rhs); });
   1153 
   1154     const ColumnCount max_width = m_dimensions.column - 1;
   1155     const bool is_inline = style == MenuStyle::Inline;
   1156     const bool is_search = style == MenuStyle::Search;
   1157     m_menu.columns = is_search ? 0 : (is_inline ? 1 : max((int)(max_width / (longest+1)), 1));
   1158 
   1159     const LineCount max_height = min(height_limit(style), max(anchor.line, m_dimensions.line - anchor.line - 1));
   1160     const LineCount height = is_search ?
   1161         1 : (min<LineCount>(max_height, div_round_up(item_count, m_menu.columns)));
   1162 
   1163     if (height == 0)
   1164         return;
   1165 
   1166     const ColumnCount maxlen = (m_menu.columns > 1 and item_count > 1) ?
   1167         max_width / m_menu.columns - 1 : max_width;
   1168 
   1169     for (auto& item : items)
   1170     {
   1171         m_menu.items.push_back(item);
   1172         m_menu.items.back().trim(0, maxlen);
   1173         kak_assert(m_menu.items.back().length() <= maxlen);
   1174     }
   1175 
   1176     if (is_inline)
   1177         anchor.line += content_line_offset();
   1178 
   1179     LineCount line = anchor.line + 1;
   1180     ColumnCount column = std::max(0_col, std::min(anchor.column, m_dimensions.column - longest - 1));
   1181     if (is_search)
   1182     {
   1183         line = m_status_on_top ? 0_line : m_dimensions.line;
   1184         column = m_dimensions.column / 2;
   1185     }
   1186     else if (not is_inline)
   1187         line = m_status_on_top ? 1_line : m_dimensions.line - height;
   1188     else if (line + height > m_dimensions.line and anchor.line >= height)
   1189         line = anchor.line - height;
   1190 
   1191     const auto width = is_search ? m_dimensions.column - m_dimensions.column / 2
   1192                                  : (is_inline ? min(longest+1, m_dimensions.column)
   1193                                               : m_dimensions.column);
   1194     m_menu.create({line, column}, {height, width});
   1195     m_menu.selected_item = item_count;
   1196     m_menu.first_item = 0;
   1197 
   1198     draw_menu();
   1199 
   1200     if (m_info)
   1201         info_show(m_info.title, m_info.content,
   1202                   m_info.anchor, m_info.face, m_info.style);
   1203 }
   1204 
   1205 void TerminalUI::menu_select(int selected)
   1206 {
   1207     const int item_count = m_menu.items.size();
   1208     if (selected < 0 or selected >= item_count)
   1209     {
   1210         m_menu.selected_item = -1;
   1211         m_menu.first_item = 0;
   1212     }
   1213     else if (m_menu.columns == 0) // Do not columnize
   1214     {
   1215         m_menu.selected_item = selected;
   1216         const ColumnCount width = m_menu.size.column - 3;
   1217         int first = 0;
   1218         ColumnCount item_col = 0;
   1219         for (int i = 0; i <= selected; ++i)
   1220         {
   1221             const ColumnCount item_width = m_menu.items[i].length() + 1;
   1222             if (item_col + item_width > width)
   1223             {
   1224                 first = i;
   1225                 item_col = item_width;
   1226             }
   1227             else
   1228                 item_col += item_width;
   1229         }
   1230         m_menu.first_item = first;
   1231     }
   1232     else
   1233     {
   1234         m_menu.selected_item = selected;
   1235         const int menu_cols = div_round_up(item_count, (int)m_menu.size.line);
   1236         const int first_col = m_menu.first_item / (int)m_menu.size.line;
   1237         const int selected_col = m_menu.selected_item / (int)m_menu.size.line;
   1238         if (selected_col < first_col)
   1239             m_menu.first_item = selected_col * (int)m_menu.size.line;
   1240         if (selected_col >= first_col + m_menu.columns)
   1241             m_menu.first_item = min(selected_col, menu_cols - m_menu.columns) * (int)m_menu.size.line;
   1242     }
   1243     draw_menu();
   1244 }
   1245 
   1246 void TerminalUI::menu_hide()
   1247 {
   1248     if (not m_menu)
   1249         return;
   1250 
   1251     m_menu.items.clear();
   1252     m_menu.destroy();
   1253     m_dirty = true;
   1254 
   1255     // Recompute info as it does not have to avoid the menu anymore
   1256     if (m_info)
   1257         info_show(m_info.title, m_info.content, m_info.anchor, m_info.face, m_info.style);
   1258 }
   1259 
   1260 static DisplayCoord compute_pos(DisplayCoord anchor, DisplayCoord size,
   1261                                 TerminalUI::Rect rect, TerminalUI::Rect to_avoid,
   1262                                 bool prefer_above)
   1263 {
   1264     DisplayCoord pos;
   1265     if (prefer_above)
   1266     {
   1267         pos = anchor - DisplayCoord{size.line};
   1268         if (pos.line < 0)
   1269             prefer_above = false;
   1270     }
   1271     auto rect_end = rect.pos + rect.size;
   1272     if (not prefer_above)
   1273     {
   1274         pos = anchor + DisplayCoord{1_line};
   1275         if (pos.line + size.line >= rect_end.line)
   1276             pos.line = max(rect.pos.line, anchor.line - size.line);
   1277     }
   1278     if (pos.column + size.column >= rect_end.column)
   1279         pos.column = max(rect.pos.column, rect_end.column - size.column);
   1280 
   1281     if (to_avoid.size != DisplayCoord{})
   1282     {
   1283         DisplayCoord to_avoid_end = to_avoid.pos + to_avoid.size;
   1284 
   1285         DisplayCoord end = pos + size;
   1286 
   1287         // check intersection
   1288         if (not (end.line < to_avoid.pos.line or end.column < to_avoid.pos.column or
   1289                  pos.line > to_avoid_end.line or pos.column > to_avoid_end.column))
   1290         {
   1291             pos.line = min(to_avoid.pos.line, anchor.line) - size.line;
   1292             // if above does not work, try below
   1293             if (pos.line < 0)
   1294                 pos.line = max(to_avoid_end.line, anchor.line);
   1295         }
   1296     }
   1297 
   1298     return pos;
   1299 }
   1300 
   1301 static DisplayLineList wrap_lines(const DisplayLineList& lines, ColumnCount max_width)
   1302 {
   1303     DisplayLineList result;
   1304     for (auto line : lines)
   1305     {
   1306         ColumnCount column = 0;
   1307         for (auto it = line.begin(); it != line.end(); )
   1308         {
   1309             auto length = it->length();
   1310             column += length;
   1311             if (column > max_width)
   1312             {
   1313                 auto content = it->content().substr(0, length - (column - max_width));
   1314                 auto pos = find_if(content | reverse(), [](char c) { return not is_word(c); });
   1315                 if (pos != content.rend())
   1316                     content = {content.begin(), pos.base()};
   1317 
   1318                 if (not content.empty())
   1319                     it = ++line.split(it, content.column_length());
   1320                 result.push_back(AtomList(std::make_move_iterator(line.begin()),
   1321                                           std::make_move_iterator(it)));
   1322                 it = line.erase(line.begin(), it);
   1323                 column = 0;
   1324             }
   1325             else
   1326                 ++it;
   1327         }
   1328         result.push_back(std::move(line));
   1329     }
   1330     return result;
   1331 }
   1332 
   1333 void TerminalUI::info_show(const DisplayLine& title, const DisplayLineList& content,
   1334                            DisplayCoord anchor, Face face, InfoStyle style)
   1335 {
   1336     info_hide();
   1337 
   1338     m_info.title = title;
   1339     m_info.content = content;
   1340     m_info.anchor = anchor;
   1341     m_info.face = face;
   1342     m_info.style = style;
   1343 
   1344     const bool framed = style == InfoStyle::Prompt or style == InfoStyle::Modal;
   1345     const bool assisted = style == InfoStyle::Prompt and m_assistant.size() != 0;
   1346 
   1347     DisplayCoord max_size = m_dimensions;
   1348     if (style == InfoStyle::MenuDoc)
   1349         max_size.column = std::max(m_dimensions.column - (m_menu.pos.column + m_menu.size.column),
   1350                                    m_menu.pos.column);
   1351     else if (style != InfoStyle::Modal)
   1352         max_size.line -= m_menu.size.line;
   1353 
   1354     const auto max_content_width = (m_info_max_width > 0 ? std::min(max_size.column, m_info_max_width) : max_size.column) -
   1355                                    (framed ? 4 : 0) -
   1356                                    (assisted ? m_assistant[0].column_length() : 0);
   1357     if (max_content_width <= 0)
   1358         return;
   1359 
   1360     auto compute_size = [](const DisplayLineList& lines) -> DisplayCoord {
   1361         return {(int)lines.size(), accumulate(lines, 0_col, [](ColumnCount c, const DisplayLine& l) { return std::max(c, l.length()); })};
   1362     };
   1363 
   1364     DisplayCoord content_size = compute_size(content);
   1365     const bool wrap = content_size.column > max_content_width;
   1366     DisplayLineList wrapped_content;
   1367     if (wrap)
   1368     {
   1369         wrapped_content = wrap_lines(content, max_content_width);
   1370         content_size = compute_size(wrapped_content);
   1371     }
   1372     const auto& lines = wrap ? wrapped_content : content;
   1373 
   1374     DisplayCoord size{content_size.line, std::max(content_size.column, title.length() + (framed ? 2 : 0))};
   1375     if (framed)
   1376         size += {2, 4};
   1377     if (assisted)
   1378         size = {std::max(LineCount{(int)m_assistant.size()-1}, size.line), size.column + m_assistant[0].column_length()};
   1379     size = {std::min(max_size.line, size.line), std::min(max_size.column, size.column)};
   1380 
   1381     if ((framed and size.line < 3) or size.line <= 0)
   1382         return;
   1383 
   1384     const Rect rect = {content_line_offset(), m_dimensions};
   1385     if (style == InfoStyle::Prompt)
   1386     {
   1387         anchor = DisplayCoord{m_status_on_top ? 0 : m_dimensions.line, m_dimensions.column-1};
   1388         anchor = compute_pos(anchor, size, rect, m_menu, style == InfoStyle::InlineAbove);
   1389     }
   1390     else if (style == InfoStyle::Modal)
   1391     {
   1392         auto half = [](const DisplayCoord& c) { return DisplayCoord{c.line / 2, c.column / 2}; };
   1393         anchor = rect.pos + half(rect.size) - half(size);
   1394     }
   1395     else if (style == InfoStyle::MenuDoc)
   1396     {
   1397         const auto right_max_width = m_dimensions.column - (m_menu.pos.column + m_menu.size.column);
   1398         const auto left_max_width = m_menu.pos.column;
   1399         anchor.line = m_menu.pos.line;
   1400         if (size.column <= right_max_width or right_max_width >= left_max_width)
   1401             anchor.column = m_menu.pos.column + m_menu.size.column;
   1402         else
   1403             anchor.column = m_menu.pos.column - size.column;
   1404     }
   1405     else
   1406     {
   1407         anchor = compute_pos(anchor, size, rect, m_menu, style == InfoStyle::InlineAbove);
   1408         anchor.line += content_line_offset();
   1409     }
   1410 
   1411     m_info.create(anchor, size);
   1412     for (auto line = 0_line; line < size.line; ++line)
   1413     {
   1414         auto draw_atoms = [&, this, pos=DisplayCoord{line}](auto&&... args) mutable {
   1415             auto draw = overload(
   1416                 [&](ColumnCount padding) {
   1417                     pos.column += padding;
   1418                 },
   1419                 [&](String str) {
   1420                     auto len = str.column_length();
   1421                     m_info.draw(pos, DisplayAtom{std::move(str)}, face);
   1422                     pos.column += len;
   1423                 },
   1424                 [&](const DisplayLine& atoms) {
   1425                     m_info.draw(pos, atoms.atoms(), face);
   1426                     pos.column += atoms.length();
   1427                 });
   1428             (draw(args), ...);
   1429         };
   1430 
   1431         constexpr Codepoint dash{L'─'};
   1432         constexpr Codepoint dotted_dash{L'┄'};
   1433         if (assisted)
   1434         {
   1435             const auto assistant_top_margin = (size.line - m_assistant.size()+1) / 2;
   1436             StringView assistant_line = (line >= assistant_top_margin) ?
   1437                 m_assistant[(int)min(line - assistant_top_margin, LineCount{(int)m_assistant.size()}-1)]
   1438               : m_assistant[(int)m_assistant.size()-1];
   1439 
   1440             draw_atoms(assistant_line.str());
   1441         }
   1442         if (not framed)
   1443             draw_atoms(lines[(int)line]);
   1444         else if (line == 0)
   1445         {
   1446             if (title.atoms().empty() or content_size.column < 2)
   1447                 draw_atoms("╭─" + String{dash, content_size.column} + "─╮");
   1448             else
   1449             {
   1450                 auto trimmed_title = title;
   1451                 trimmed_title.trim(0, content_size.column - 2);
   1452                 auto dash_count = content_size.column - trimmed_title.length() - 2;
   1453                 String left{dash, dash_count / 2};
   1454                 String right{dash, dash_count - dash_count / 2};
   1455                 draw_atoms("╭─" + left + "┤", trimmed_title, "├" + right +"─╮");
   1456             }
   1457         }
   1458         else if (line < size.line - 1 and line <= lines.size())
   1459         {
   1460             auto info_line = lines[(int)line - 1];
   1461             const bool trimmed = info_line.trim(0, content_size.column);
   1462             const ColumnCount padding = content_size.column - info_line.length();
   1463             draw_atoms("│ ", info_line, padding, (trimmed ? "…│" : " │"));
   1464         }
   1465         else if (line == std::min<LineCount>((int)lines.size() + 1, size.line - 1))
   1466             draw_atoms("╰─", String(line > lines.size() ? dash : dotted_dash, content_size.column), "─╯");
   1467     }
   1468     m_dirty = true;
   1469 }
   1470 
   1471 void TerminalUI::info_hide()
   1472 {
   1473     if (not m_info)
   1474         return;
   1475     m_info.destroy();
   1476     m_dirty = true;
   1477 }
   1478 
   1479 void TerminalUI::set_on_key(OnKeyCallback callback)
   1480 {
   1481     m_on_key = std::move(callback);
   1482     EventManager::instance().force_signal(0);
   1483 }
   1484 
   1485 void TerminalUI::set_on_paste(OnPasteCallback callback)
   1486 {
   1487     m_on_paste = std::move(callback);
   1488 }
   1489 
   1490 DisplayCoord TerminalUI::dimensions()
   1491 {
   1492     return m_dimensions;
   1493 }
   1494 
   1495 LineCount TerminalUI::content_line_offset() const
   1496 {
   1497     return m_status_on_top ? 1 : 0;
   1498 }
   1499 
   1500 void TerminalUI::set_resize_pending()
   1501 {
   1502     m_resize_pending = true;
   1503     EventManager::instance().force_signal(0);
   1504 }
   1505 
   1506 void TerminalUI::setup_terminal()
   1507 {
   1508     write(STDOUT_FILENO,
   1509         "\033[?1049h" // enable alternative screen buffer
   1510         "\033[?1004h" // enable focus notify
   1511         "\033[>4;1m"  // request CSI u style key reporting
   1512         "\033[>5u"    // kitty progressive enhancement - report shifted key codes
   1513         "\033[22t"    // save the current window title
   1514         "\033[?25l"   // hide cursor
   1515         "\033="       // set application keypad mode, so the keypad keys send unique codes
   1516         "\033[?2004h" // force enable bracketed-paste events
   1517     );
   1518 }
   1519 
   1520 void TerminalUI::restore_terminal()
   1521 {
   1522     write(STDOUT_FILENO,
   1523         "\033>"
   1524         "\033[?25h"
   1525         "\033[23t"
   1526         "\033[<u"
   1527         "\033[>4;0m"
   1528         "\033[?1004l"
   1529         "\033[?1049l"
   1530         "\033[?2004l"
   1531         "\033[m" // set the terminal output back to default colours and style
   1532     );
   1533 }
   1534 
   1535 void TerminalUI::enable_mouse(bool enabled)
   1536 {
   1537     if (enabled == m_mouse_enabled)
   1538         return;
   1539 
   1540     m_mouse_enabled = enabled;
   1541     if (enabled)
   1542     {
   1543         write(STDOUT_FILENO,
   1544             "\033[?1006h" // force SGR mode
   1545             "\033[?1000h" // enable mouse
   1546             "\033[?1002h" // force enable report mouse position
   1547         );
   1548     }
   1549     else
   1550     {
   1551         write(STDOUT_FILENO,
   1552             "\033[?1002l"
   1553             "\033[?1000l"
   1554             "\033[?1006l"
   1555         );
   1556     }
   1557 }
   1558 
   1559 void TerminalUI::set_ui_options(const Options& options)
   1560 {
   1561     auto find = [&](StringView name) -> Optional<StringView> {
   1562         if (auto it = options.find(name); it != options.end())
   1563             return StringView{it->value};
   1564         return {};
   1565     };
   1566 
   1567     auto assistant = find("terminal_assistant").value_or("clippy");
   1568     if (assistant == "clippy")
   1569         m_assistant = assistant_clippy;
   1570     else if (assistant == "cat")
   1571         m_assistant = assistant_cat;
   1572     else if (assistant == "dilbert")
   1573         m_assistant = assistant_dilbert;
   1574     else if (assistant == "none" or assistant == "off")
   1575         m_assistant = ConstArrayView<StringView>{};
   1576 
   1577     auto to_bool = [](StringView s) { return s == "yes" or s == "true"; };
   1578 
   1579     m_status_on_top = find("terminal_status_on_top").map(to_bool).value_or(false);
   1580     m_set_title = find("terminal_set_title").map(to_bool).value_or(true);
   1581     m_title = find("terminal_title").map([](StringView s) { return String{s}; });
   1582 
   1583     auto synchronized = find("terminal_synchronized").map(to_bool);
   1584     m_synchronized.set = (bool)synchronized;
   1585     m_synchronized.requested = synchronized.value_or(false);
   1586     if (not m_synchronized.queried and not m_synchronized.set) {
   1587         write(STDOUT_FILENO, "\033[?2026$p");
   1588         m_synchronized.queried = true;
   1589     }
   1590 
   1591     m_shift_function_key = find("terminal_shift_function_key").map(str_to_int_ifp).value_or(default_shift_function_key);
   1592 
   1593     enable_mouse(find("terminal_enable_mouse").map(to_bool).value_or(true));
   1594     m_wheel_scroll_amount = find("terminal_wheel_scroll_amount").map(str_to_int_ifp).value_or(3);
   1595 
   1596     m_padding_char = find("terminal_padding_char").map([](StringView s) { return s.column_length() < 1 ? ' ' : s[0_char]; }).value_or(Codepoint{'~'});
   1597     m_padding_fill = find("terminal_padding_fill").map(to_bool).value_or(false);
   1598 
   1599     bool new_cursor_native = find("terminal_cursor_native").map(to_bool).value_or(false);
   1600     if (new_cursor_native != m_cursor_native)
   1601     {
   1602         m_cursor_native = new_cursor_native;
   1603         write(STDOUT_FILENO, m_cursor_native ? "\033[?25h" : "\033[?25l");
   1604     }
   1605 
   1606     m_info_max_width = find("terminal_info_max_width").map(str_to_int_ifp).value_or(0);
   1607 }
   1608 
   1609 }