From d74dd98e1a28ea4adf056077a3d212c8f0ca5fbe Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Sat, 11 Apr 2026 04:12:56 +0800 Subject: feat: implement interactive TUI with scrolling and add OpenSSL dependency support --- ricochet/src/tui/terminal.cc | 62 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 ricochet/src/tui/terminal.cc (limited to 'ricochet/src/tui') diff --git a/ricochet/src/tui/terminal.cc b/ricochet/src/tui/terminal.cc new file mode 100644 index 0000000..8fdb585 --- /dev/null +++ b/ricochet/src/tui/terminal.cc @@ -0,0 +1,62 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "ricochet/tui/terminal.hh" +#include +#include +#include + +namespace ricochet::tui { + +Terminal::Terminal() { + // get terminal attributes + tcgetattr(STDIN_FILENO, &original_termios_); + + struct termios raw = original_termios_; + + // close echo, close canonical mode + // close terminal signals (ISIG disable Ctrl+C and Ctrl+Z, let the program handle it) + raw.c_lflag &= ~(ECHO | ICANON | ISIG); + + // close software flow control (Ctrl+S, Ctrl+Q) + raw.c_iflag &= ~(IXON | ICRNL); + + // apply new terminal attributes + tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); +} + +Terminal::~Terminal() { + // RAII: restore terminal attributes when program exits + tcsetattr(STDIN_FILENO, TCSAFLUSH, &original_termios_); +} + +char Terminal::read_key() const { // NOLINT(readability-convert-member-functions-to-static) + char c = '\0'; + // read 1 byte + if (read(STDIN_FILENO, &c, 1) == -1) { + return '\0'; + } + return c; +} + +void Terminal::clear_screen() const { // NOLINT(readability-convert-member-functions-to-static) + // ANSI escape codes: \x1b[2J clear screen, \x1b[H move cursor to (1,1) + std::cout << "\x1b[2J\x1b[H"; +} + +} // namespace ricochet::tui \ No newline at end of file -- cgit v1.2.3 From 12188f045a3f6ccce4359d946167066e3b584939 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Sat, 11 Apr 2026 05:36:22 +0800 Subject: feat: implement SSLSocket for encrypted connections and add terminal size detection utility --- ricochet/include/ricochet/net/ssl_socket.hh | 93 +++++++++++++++++++ ricochet/include/ricochet/tui/terminal.hh | 31 ++++--- ricochet/src/core/browser.cc | 32 ++++--- ricochet/src/net/http_client.cc | 135 ++++++++++++++++++++++++---- ricochet/src/net/ssl_socket.cc | 118 ++++++++++++++++++++++++ ricochet/src/render/renderer.cc | 38 ++++++-- ricochet/src/tui/terminal.cc | 71 +++++++++------ 7 files changed, 439 insertions(+), 79 deletions(-) create mode 100644 ricochet/include/ricochet/net/ssl_socket.hh create mode 100644 ricochet/src/net/ssl_socket.cc (limited to 'ricochet/src/tui') diff --git a/ricochet/include/ricochet/net/ssl_socket.hh b/ricochet/include/ricochet/net/ssl_socket.hh new file mode 100644 index 0000000..36a92b6 --- /dev/null +++ b/ricochet/include/ricochet/net/ssl_socket.hh @@ -0,0 +1,93 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "sys/address.hh" +#include "sys/socket.hh" +#include +#include +#include + +extern "C" { +using SSL_CTX = struct ssl_ctx_st; +using SSL = struct ssl_st; +} + +namespace ricochet::net { + +struct SslCtxDeleter +{ + void operator()( SSL_CTX* ptr ) const; +}; +struct SslDeleter +{ + void operator()( SSL* ptr ) const; +}; + +using UniqueSslCtx = std::unique_ptr; +using UniqueSsl = std::unique_ptr; + +/** + * @brief Socket wrapper that supports TLS/SSL encrypted handshake + */ +class SSLSocket +{ +public: + SSLSocket(); + ~SSLSocket() = default; + + SSLSocket( const SSLSocket& ) = delete; + SSLSocket& operator=( const SSLSocket& ) = delete; + SSLSocket( SSLSocket&& ) = delete; + SSLSocket& operator=( SSLSocket&& ) = delete; + + /** + * @brief Connect to a remote host using TLS/SSL + * @param host The hostname to connect to + * @param port The port to connect to + * @return True if the connection was successful, false otherwise + */ + void connect( const Address& address, const std::string& hostname ); + + /** + * @brief Send data over the TLS/SSL connection + * @param data The data to send + * @return The number of bytes sent, or -1 if an error occurred + */ + std::size_t write( std::string_view data ); + + /** + * @brief Receive data from the TLS/SSL connection + * @param buffer The buffer to store the received data + */ + void read( std::string& buffer ); + + /** + * @brief Check if the TLS/SSL connection is closed + * @return True if the connection is closed, false otherwise + */ + bool eof() const; + +private: + TCPSocket underlying_socket_ {}; // TCP Socket + UniqueSslCtx ctx_ { nullptr }; // OpenSSL global context + UniqueSsl ssl_ { nullptr }; // Current connection's SSL state + bool eof_ { false }; // EOF flag +}; +} // namespace ricochet::net \ No newline at end of file diff --git a/ricochet/include/ricochet/tui/terminal.hh b/ricochet/include/ricochet/tui/terminal.hh index 5388845..59ca298 100644 --- a/ricochet/include/ricochet/tui/terminal.hh +++ b/ricochet/include/ricochet/tui/terminal.hh @@ -19,27 +19,32 @@ #pragma once #include +#include namespace ricochet::tui { -class Terminal { +class Terminal +{ public: - Terminal(); - ~Terminal(); + Terminal(); + ~Terminal(); - Terminal(const Terminal&) = delete; - Terminal& operator=(const Terminal&) = delete; - Terminal(Terminal&&) = delete; - Terminal& operator=(Terminal&&) = delete; + Terminal( const Terminal& ) = delete; + Terminal& operator=( const Terminal& ) = delete; + Terminal( Terminal&& ) = delete; + Terminal& operator=( Terminal&& ) = delete; - // Read a single key - char read_key() const; - - // Clear screen and move cursor to top-left - void clear_screen() const; + // Read a single key + char read_key() const; + + // Clear screen and move cursor to top-left + void clear_screen() const; + + // Get terminal size + std::pair get_size() const; private: - struct termios original_termios_{}; // Save terminal original state + struct termios original_termios_ {}; // Save terminal original state }; } // namespace ricochet::tui \ No newline at end of file diff --git a/ricochet/src/core/browser.cc b/ricochet/src/core/browser.cc index 0636de6..650ebcf 100644 --- a/ricochet/src/core/browser.cc +++ b/ricochet/src/core/browser.cc @@ -54,44 +54,48 @@ int Browser::run( std::string_view initial_url ) const std::string rendered_text = renderer.render( dom_root ); std::vector lines; - std::stringstream ss(rendered_text); + std::stringstream ss( rendered_text ); std::string line; - while (std::getline(ss, line, '\n')) { - lines.push_back(line); + while ( std::getline( ss, line, '\n' ) ) { + lines.push_back( line ); } + std::cout << "DEBUG: Status Code: " << response.status_code << "\r\n"; + std::cout << "DEBUG: Raw Body Length: " << response.body.length() << "\r\n"; + // TUI Event Loop const tui::Terminal terminal; std::size_t scroll_y = 0; - const std::size_t screen_height = 24; - while (true) { + while ( true ) { terminal.clear_screen(); - for (std::size_t i = 0; i < screen_height - 1; ++i) { + const auto [term_width, term_height] = terminal.get_size(); + const std::size_t usable_height = ( term_height > 1 ) ? ( term_height - 1 ) : 1; + + for ( std::size_t i = 0; i < usable_height; ++i ) { const std::size_t line_idx = scroll_y + i; - if (line_idx < lines.size()) { + if ( line_idx < lines.size() ) { std::cout << lines[line_idx] << "\r\n"; } else { std::cout << "~\r\n"; } } - std::cout << "\033[7m" << " URL: " << initial_url - << " | [j] Down [k] Up [q] Quit " << "\033[0m"; + std::cout << "\033[7m" << " URL: " << initial_url << " | [j] Down [k] Up [q] Quit " << "\033[0m"; std::cout.flush(); const char c = terminal.read_key(); - if (c == 'q') { + if ( c == 'q' ) { break; // Break loop, terminal destructor will restore terminal } - if (c == 'j') { - if (scroll_y + screen_height - 1 < lines.size()) { + if ( c == 'j' ) { + if ( scroll_y + usable_height < lines.size() ) { scroll_y++; // Scroll down } - } else if (c == 'k') { - if (scroll_y > 0) { + } else if ( c == 'k' ) { + if ( scroll_y > 0 ) { scroll_y--; // Scroll up } } diff --git a/ricochet/src/net/http_client.cc b/ricochet/src/net/http_client.cc index b31073c..b31976f 100644 --- a/ricochet/src/net/http_client.cc +++ b/ricochet/src/net/http_client.cc @@ -17,6 +17,7 @@ */ #include "ricochet/net/http_client.hh" +#include "ricochet/net/ssl_socket.hh" #include "ricochet/net/sys/address.hh" #include "ricochet/net/sys/socket.hh" @@ -37,13 +38,17 @@ struct ParsedUrl std::expected parse_url( std::string_view url ) { - const std::string_view http_prefix = "http://"; + std::string_view prefix = "http://"; - if ( !url.starts_with( http_prefix ) ) { - return std::unexpected( "Only 'http://' URLs are supported in MVP. (e.g., http://example.com)" ); + if ( url.starts_with( "https://" ) ) { + prefix = "https://"; + } else if ( url.starts_with( "http://" ) ) { + prefix = "http://"; + } else { + return std::unexpected( "Only 'http://' or 'https://' URLs are supported." ); } - url.remove_prefix( http_prefix.length() ); + url.remove_prefix( prefix.length() ); auto slash_pos = url.find( '/' ); ParsedUrl result; @@ -57,6 +62,77 @@ std::expected parse_url( std::string_view url ) return result; } + +std::string dechunk( std::string_view body ) // NOLINT(readability-convert-member-functions-to-static) +{ + std::string result; + std::size_t pos = 0; + while ( pos < body.size() ) { + // find hex length end with \r\n + auto line_end = body.find( "\r\n", pos ); + if ( line_end == std::string_view::npos ) { + break; + } + + // parse hex length + const std::string len_str( body.substr( pos, line_end - pos ) ); + unsigned int chunk_size = 0; + try { + chunk_size = std::stoul( len_str, nullptr, 16 ); + } catch ( ... ) { + break; + } + + if ( chunk_size == 0 ) { + break; // end of stream + } + + // extract data block (skip \r\n) + pos = line_end + 2; + if ( pos + chunk_size > body.size() ) { + break; + } + result.append( body.substr( pos, chunk_size ) ); + + // skip data block's \r\n + pos += chunk_size + 2; + } + return result; +} + +std::string remove_html_comments( std::string html ) // NOLINT(readability-convert-member-functions-to-static) +{ + std::size_t start_pos = 0; + while ( ( start_pos = html.find( "", start_pos ); + if ( end_pos != std::string::npos ) { + html.erase( start_pos, end_pos - start_pos + 3 ); + } else { + html.erase( start_pos ); + break; + } + } + return html; +} + +std::string remove_tag_blocks( std::string html, const std::string& tag_name ) // NOLINT +{ + const std::string open_tag = "<" + tag_name; + const std::string close_tag = ""; + std::size_t start_pos = 0; + + while ( ( start_pos = html.find( open_tag, start_pos ) ) != std::string::npos ) { + const std::size_t end_pos = html.find( close_tag, start_pos ); + if ( end_pos != std::string::npos ) { + html.erase( start_pos, end_pos - start_pos + close_tag.length() ); + } else { + html.erase( start_pos ); + break; + } + } + return html; +} + } // namespace std::expected @@ -69,30 +145,46 @@ HttpClient::fetch( // NOLINT(readability-convert-member-functions-to-static) } auto [host, path] = parsed_url.value(); + const bool is_https = url.starts_with( "https://" ); + const std::string service = is_https ? "https" : "http"; try { - const Address server_addr( host, "http" ); - - TCPSocket socket; - socket.connect( server_addr ); + const Address server_addr( host, service ); const std::string request = std::format( "GET {} HTTP/1.1\r\n" "Host: {}\r\n" - "User-Agent: Ricochet/0.1.0\r\n" + "User-Agent: Mozilla/5.0 (Ricochet/0.1.0)\r\n" + "Accept: text/html\r\n" + "Accept-Encoding: identity\r\n" "Connection: close\r\n\r\n", path, host ); - size_t bytes_written = 0; - while ( bytes_written < request.size() ) { - bytes_written += socket.write( request.substr( bytes_written ) ); - } - std::string raw_response; - while ( !socket.eof() ) { - std::string buffer; - socket.read( buffer ); - raw_response += buffer; + if ( is_https ) { + SSLSocket ssl_socket; + ssl_socket.connect( server_addr, host ); + size_t bytes_written = 0; + while ( bytes_written < request.size() ) { + bytes_written += ssl_socket.write( request.substr( bytes_written ) ); + } + while ( !ssl_socket.eof() ) { + std::string buffer; + ssl_socket.read( buffer ); + raw_response += buffer; + } + } else { + TCPSocket tcp_socket; + tcp_socket.connect( server_addr ); + size_t bytes_written = 0; + while ( bytes_written < request.size() ) { + bytes_written += tcp_socket.write( request.substr( bytes_written ) ); + } + while ( !tcp_socket.eof() ) { + std::string buffer; + tcp_socket.read( buffer ); + raw_response += buffer; + } } HttpResponse response; @@ -111,6 +203,13 @@ HttpClient::fetch( // NOLINT(readability-convert-member-functions-to-static) response.body = raw_response; } + if ( raw_response.contains( "Transfer-Encoding: chunked" ) ) { + response.body = dechunk( response.body ); + } + + response.body = remove_html_comments( response.body ); + response.body = remove_tag_blocks( response.body, "script" ); + response.body = remove_tag_blocks( response.body, "style" ); return response; } catch ( const std::exception& e ) { return std::unexpected( std::string( "Network Error: " ) + e.what() ); diff --git a/ricochet/src/net/ssl_socket.cc b/ricochet/src/net/ssl_socket.cc new file mode 100644 index 0000000..a31b564 --- /dev/null +++ b/ricochet/src/net/ssl_socket.cc @@ -0,0 +1,118 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "ricochet/net/ssl_socket.hh" +#include +#include +#include +#include + +namespace ricochet::net { + +// --- RAII Deleters --- + +void SslCtxDeleter::operator()( SSL_CTX* ptr ) const +{ + if ( ptr != nullptr ) { + SSL_CTX_free( ptr ); + } +} + +void SslDeleter::operator()( SSL* ptr ) const +{ + if ( ptr != nullptr ) { + SSL_free( ptr ); + } +} + +// SSLSocket Implementation + +SSLSocket::SSLSocket() +{ + const SSL_METHOD* method = TLS_client_method(); + ctx_.reset( SSL_CTX_new( method ) ); + if ( !ctx_ ) { + throw std::runtime_error( "Failed to create SSL_CTX" ); + } + + if ( SSL_CTX_set_default_verify_paths( ctx_.get() ) != 1 ) { + throw std::runtime_error( "Failed to load default CA certificates" ); + } +} + +void SSLSocket::connect( const Address& address, const std::string& hostname ) +{ + // TCP Connect + underlying_socket_.connect( address ); + + ssl_.reset( SSL_new( ctx_.get() ) ); + if ( !ssl_ ) { + throw std::runtime_error( "Failed to create SSL object" ); + } + + // Setup SNI (Server Name Indication) + if ( SSL_set_tlsext_host_name( ssl_.get(), hostname.c_str() ) != 1 ) { + // Some old servers do not support SNI, here we can ignore the error or throw an exception, depending on the + // requirements + std::cerr << "Warning: Failed to set SNI" << '\n'; + } + + SSL_set_fd( ssl_.get(), underlying_socket_.fd_num() ); + + if ( SSL_connect( ssl_.get() ) != 1 ) { + throw std::runtime_error( "TLS Handshake failed!" ); + } +} + +std::size_t SSLSocket::write( std::string_view data ) +{ + if ( !ssl_ ) { + return 0; + } + + const int bytes_written = SSL_write( ssl_.get(), data.data(), static_cast( data.size() ) ); + if ( bytes_written <= 0 ) { + throw std::runtime_error( "SSL write failed" ); + } + return static_cast( bytes_written ); +} + +void SSLSocket::read( std::string& buffer ) +{ + if ( !ssl_ ) { + return; + } + + std::array buf {}; + // Read decrypted data from the encrypted channel + const int bytes_read = SSL_read( ssl_.get(), buf.data(), static_cast( buf.size() ) ); + + if ( bytes_read > 0 ) { + buffer.append( buf.data(), static_cast( bytes_read ) ); + } else { + // Read 0 or negative, representing the server closed the connection (EOF) + eof_ = true; + } +} + +bool SSLSocket::eof() const +{ + return eof_; +} + +} // namespace ricochet::net \ No newline at end of file diff --git a/ricochet/src/render/renderer.cc b/ricochet/src/render/renderer.cc index 0a91d49..2115ee1 100644 --- a/ricochet/src/render/renderer.cc +++ b/ricochet/src/render/renderer.cc @@ -23,6 +23,25 @@ namespace ricochet::render { namespace { +std::string decode_entities( std::string text ) // NOLINT(readability-convert-member-functions-to-static) +{ + constexpr std::array, 24> entities + = { { { " ", " " }, { "<", "<" }, { ">", ">" }, { "&", "&" }, { """, "\"" }, + { "©", "©" }, { "®", "®" }, { "™", "™" }, { "€", "€" }, { "£", "£" }, + { "¥", "¥" }, { "¢", "¢" }, { "§", "§" }, { "¶", "¶" }, { "…", "…" }, + { "†", "†" }, { "‡", "‡" }, { "•", "•" }, { "′", "′" }, { "″", "″" }, + { "‹", "‹" }, { "›", "›" }, { "‾", "‾" }, { "⁄", "⁄" } } }; + + for ( const auto& [entity, replacement] : entities ) { + std::size_t pos = 0; + while ( ( pos = text.find( entity, pos ) ) != std::string::npos ) { + text.replace( pos, entity.length(), replacement ); + pos += replacement.length(); + } + } + return text; +} + void render_node( const parser::DomNode& node, std::string& output ) // NOLINT(misc-no-recursion) { if ( node.tag_name == "head" || node.tag_name == "style" || node.tag_name == "script" || node.tag_name == "meta" @@ -31,21 +50,27 @@ void render_node( const parser::DomNode& node, std::string& output ) // NOLINT(m } if ( node.tag_name.empty() ) { - output += node.text_content; + output += decode_entities( node.text_content ); return; } - if ( node.tag_name == "h1" ) { + + const bool is_header + = ( node.tag_name == "h1" || node.tag_name == "h2" || node.tag_name == "h3" || node.tag_name == "h4" ); + + if ( is_header ) { output += "\n\n\033[1;31m"; } else if ( node.tag_name == "a" ) { std::cout << "\033[4;34m"; - } else if ( node.tag_name == "p" || node.tag_name == "div" ) { - output += "\n"; + } else if ( node.tag_name == "p" || node.tag_name == "div" || is_header ) { + if ( !output.empty() && output.back() != '\n' ) { + output += "\n"; + } } for ( const auto& child : node.children ) { render_node( child, output ); } - if ( node.tag_name == "h1" || node.tag_name == "a" ) { + if ( is_header || node.tag_name == "a" ) { output += "\033[0m"; } @@ -56,7 +81,8 @@ void render_node( const parser::DomNode& node, std::string& output ) // NOLINT(m } // namespace -std::string Renderer::render( const parser::DomNode& node ) const // NOLINT(readability-convert-member-functions-to-static) +std::string Renderer::render( // NOLINT(readability-convert-member-functions-to-static) + const parser::DomNode& node ) const { std::string output; render_node( node, output ); diff --git a/ricochet/src/tui/terminal.cc b/ricochet/src/tui/terminal.cc index 8fdb585..75c6c1f 100644 --- a/ricochet/src/tui/terminal.cc +++ b/ricochet/src/tui/terminal.cc @@ -19,44 +19,59 @@ #include "ricochet/tui/terminal.hh" #include #include +#include #include namespace ricochet::tui { -Terminal::Terminal() { - // get terminal attributes - tcgetattr(STDIN_FILENO, &original_termios_); - - struct termios raw = original_termios_; - - // close echo, close canonical mode - // close terminal signals (ISIG disable Ctrl+C and Ctrl+Z, let the program handle it) - raw.c_lflag &= ~(ECHO | ICANON | ISIG); - - // close software flow control (Ctrl+S, Ctrl+Q) - raw.c_iflag &= ~(IXON | ICRNL); - - // apply new terminal attributes - tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); +Terminal::Terminal() +{ + // get terminal attributes + tcgetattr( STDIN_FILENO, &original_termios_ ); + + struct termios raw = original_termios_; + + // close echo, close canonical mode + // close terminal signals (ISIG disable Ctrl+C and Ctrl+Z, let the program handle it) + raw.c_lflag &= ~( ECHO | ICANON | ISIG ); + + // close software flow control (Ctrl+S, Ctrl+Q) + raw.c_iflag &= ~( IXON | ICRNL ); + + // apply new terminal attributes + tcsetattr( STDIN_FILENO, TCSAFLUSH, &raw ); +} + +Terminal::~Terminal() +{ + // RAII: restore terminal attributes when program exits + tcsetattr( STDIN_FILENO, TCSAFLUSH, &original_termios_ ); } -Terminal::~Terminal() { - // RAII: restore terminal attributes when program exits - tcsetattr(STDIN_FILENO, TCSAFLUSH, &original_termios_); +char Terminal::read_key() const // NOLINT(readability-convert-member-functions-to-static) +{ + char c = '\0'; + // read 1 byte + if ( read( STDIN_FILENO, &c, 1 ) == -1 ) { + return '\0'; + } + return c; } -char Terminal::read_key() const { // NOLINT(readability-convert-member-functions-to-static) - char c = '\0'; - // read 1 byte - if (read(STDIN_FILENO, &c, 1) == -1) { - return '\0'; - } - return c; +void Terminal::clear_screen() const // NOLINT(readability-convert-member-functions-to-static) +{ + // ANSI escape codes: \x1b[2J clear screen, \x1b[H move cursor to (1,1) + std::cout << "\x1b[2J\x1b[H"; } -void Terminal::clear_screen() const { // NOLINT(readability-convert-member-functions-to-static) - // ANSI escape codes: \x1b[2J clear screen, \x1b[H move cursor to (1,1) - std::cout << "\x1b[2J\x1b[H"; +std::pair Terminal::get_size() // NOLINT(readability-convert-member-functions-to-static) + const +{ + struct winsize w {}; + if ( ioctl( STDOUT_FILENO, TIOCGWINSZ, &w ) == -1 ) { + return { 80, 24 }; + } + return { static_cast( w.ws_col ), static_cast( w.ws_row ) }; } } // namespace ricochet::tui \ No newline at end of file -- cgit v1.2.3 From 3fbda8903b809e50a8e96acd66b2b80b54e1b6bf Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Sat, 11 Apr 2026 06:08:38 +0800 Subject: feat: implement URL navigation and input handling in browser TUI --- ricochet/include/ricochet/tui/terminal.hh | 6 ++ ricochet/src/core/browser.cc | 154 ++++++++++++++++++++---------- ricochet/src/tui/terminal.cc | 12 +++ 3 files changed, 122 insertions(+), 50 deletions(-) (limited to 'ricochet/src/tui') diff --git a/ricochet/include/ricochet/tui/terminal.hh b/ricochet/include/ricochet/tui/terminal.hh index 59ca298..2942a2a 100644 --- a/ricochet/include/ricochet/tui/terminal.hh +++ b/ricochet/include/ricochet/tui/terminal.hh @@ -43,6 +43,12 @@ public: // Get terminal size std::pair get_size() const; + // Move cursor to a specific position + void move_cursor( std::size_t row, std::size_t col ) const; + + // Show or hide cursor + void show_cursor( bool visible ) const; + private: struct termios original_termios_ {}; // Save terminal original state }; diff --git a/ricochet/src/core/browser.cc b/ricochet/src/core/browser.cc index 650ebcf..4225986 100644 --- a/ricochet/src/core/browser.cc +++ b/ricochet/src/core/browser.cc @@ -24,79 +24,133 @@ #include "ricochet/tui/terminal.hh" #include #include -#include namespace ricochet::core { -int Browser::run( std::string_view initial_url ) +namespace { +std::vector load_page( std::string_view url ) { - std::cout << "-> Fetching: " << initial_url << "...\n"; - const net::HttpClient client; - auto response_result = client.fetch( initial_url ); - + auto response_result = client.fetch( url ); if ( !response_result.has_value() ) { - std::cerr << "[!] Ricochet failed to load page: " << response_result.error() << "\n"; - return 1; + return { "[!] Failed to load: " + std::string( url ) }; } - const auto& response = response_result.value(); - const parser::HtmlLexer lexer; - const auto tokens = lexer.tokenize( response.body ); - const parser::TreeBuilder builder; - const auto dom_root = builder.build( tokens ); - - // std::cout << "\033[2J\033[1;1H"; - const render::Renderer renderer; - const std::string rendered_text = renderer.render( dom_root ); + + const auto dom_root = builder.build( lexer.tokenize( response_result.value().body ) ); + const std::string text = renderer.render( dom_root ); std::vector lines; - std::stringstream ss( rendered_text ); - std::string line; - while ( std::getline( ss, line, '\n' ) ) { - lines.push_back( line ); + std::size_t start = 0; + while ( start < text.length() ) { + const std::size_t end = text.find( '\n', start ); + if ( end == std::string::npos ) { + lines.push_back( text.substr( start ) ); + break; + } + lines.push_back( text.substr( start, end - start ) ); + start = end + 1; } + return lines; +} - std::cout << "DEBUG: Status Code: " << response.status_code << "\r\n"; - std::cout << "DEBUG: Raw Body Length: " << response.body.length() << "\r\n"; - - // TUI Event Loop - const tui::Terminal terminal; +void draw_view( const tui::Terminal& terminal, + const std::vector& lines, + std::size_t scroll_y, + std::string_view url ) +{ + terminal.clear_screen(); + auto [width, height] = terminal.get_size(); + const std::size_t usable_height = ( height > 1 ) ? ( height - 1 ) : 1; + + for ( std::size_t i = 0; i < usable_height; ++i ) { + if ( scroll_y + i < lines.size() ) { + std::cout << lines[scroll_y + i] << "\r\n"; + } else { + std::cout << "~\r\n"; + } + } + std::cout << "\033[7m URL: " << url << " | [j/k] Scroll [/] Jump [q] Quit \033[0m"; + std::cout.flush(); +} - std::size_t scroll_y = 0; +std::string get_url_input( const tui::Terminal& terminal ) +{ + auto [width, height] = terminal.get_size(); + terminal.move_cursor( height, 1 ); + std::cout << "\x1b[2K\033[7m URL: \033[0m "; + std::cout.flush(); + std::string input; + terminal.show_cursor( true ); while ( true ) { - terminal.clear_screen(); - - const auto [term_width, term_height] = terminal.get_size(); - const std::size_t usable_height = ( term_height > 1 ) ? ( term_height - 1 ) : 1; - - for ( std::size_t i = 0; i < usable_height; ++i ) { - const std::size_t line_idx = scroll_y + i; - if ( line_idx < lines.size() ) { - std::cout << lines[line_idx] << "\r\n"; - } else { - std::cout << "~\r\n"; + const char ch = terminal.read_key(); + if ( ch == '\r' || ch == '\n' ) { + break; + } + if ( ch == 27 ) { + input.clear(); + break; + } + if ( ch == 127 || ch == 8 ) { + if ( !input.empty() ) { + input.pop_back(); + std::cout << "\b \b"; + std::cout.flush(); } + } else if ( std::isprint( static_cast( ch ) ) ) { + input += ch; + std::cout << ch; + std::cout.flush(); } + } + terminal.show_cursor( false ); - std::cout << "\033[7m" << " URL: " << initial_url << " | [j] Down [k] Up [q] Quit " << "\033[0m"; - std::cout.flush(); + if ( !input.empty() && !input.starts_with( "http://" ) && !input.starts_with( "https://" ) ) { + input.insert( 0, "https://" ); + } + return input; +} - const char c = terminal.read_key(); - if ( c == 'q' ) { - break; // Break loop, terminal destructor will restore terminal - } - if ( c == 'j' ) { - if ( scroll_y + usable_height < lines.size() ) { - scroll_y++; // Scroll down +} // namespace + +int Browser::run( std::string_view initial_url ) +{ + std::cout << "-> Fetching: " << initial_url << "...\n"; + + std::string current_url { initial_url }; + const tui::Terminal terminal; + terminal.clear_screen(); + + while ( !current_url.empty() ) { + auto lines = load_page( current_url ); + std::size_t scroll_y = 0; + bool navigate = false; + + while ( !navigate ) { + draw_view( terminal, lines, scroll_y, current_url ); + + const char c = terminal.read_key(); + auto [width, height] = terminal.get_size(); + const std::size_t view_h = ( height > 1 ) ? ( height - 1 ) : 1; + + if ( c == 'q' ) { + terminal.clear_screen(); + return 0; } - } else if ( c == 'k' ) { - if ( scroll_y > 0 ) { - scroll_y--; // Scroll up + if ( c == 'j' && scroll_y + view_h < lines.size() ) { + scroll_y++; + } else if ( c == 'k' && scroll_y > 0 ) { + scroll_y--; + } else if ( c == '/' ) { + std::string next_url = get_url_input( terminal ); + if ( !next_url.empty() ) { + current_url = std::move( next_url ); + navigate = true; + } } } } diff --git a/ricochet/src/tui/terminal.cc b/ricochet/src/tui/terminal.cc index 75c6c1f..9e78a02 100644 --- a/ricochet/src/tui/terminal.cc +++ b/ricochet/src/tui/terminal.cc @@ -74,4 +74,16 @@ std::pair Terminal::get_size() // NOLINT(readability-c return { static_cast( w.ws_col ), static_cast( w.ws_row ) }; } +void Terminal::move_cursor( std::size_t row, std::size_t col ) const // NOLINT +{ + // ANSI: \x1b[H move to 1,1; \x1b[row;colH move to specified row and column + std::cout << "\x1b[" << row << ";" << col << "H"; +} + +void Terminal::show_cursor( bool visible ) const // NOLINT +{ + // \x1b[?25h show cursor, \x1b[?25l hide cursor + std::cout << ( visible ? "\x1b[?25h" : "\x1b[?25l" ); +} + } // namespace ricochet::tui \ No newline at end of file -- cgit v1.2.3 From 79ab6fcb6e74109c46e836594b2cc1ead87d7b30 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Sun, 12 Apr 2026 16:43:23 +0800 Subject: feat: implement HTTP redirect support, URL search formatting, image alt text rendering, and improved terminal cursor management --- ricochet/src/core/browser.cc | 131 +++++++++++++++++++++++++++++++--------- ricochet/src/main.cc | 7 ++- ricochet/src/net/http_client.cc | 126 +++++++++++++++++++++++++++----------- ricochet/src/render/renderer.cc | 16 ++++- ricochet/src/tui/terminal.cc | 1 + 5 files changed, 214 insertions(+), 67 deletions(-) (limited to 'ricochet/src/tui') diff --git a/ricochet/src/core/browser.cc b/ricochet/src/core/browser.cc index 8bd921c..2968ab1 100644 --- a/ricochet/src/core/browser.cc +++ b/ricochet/src/core/browser.cc @@ -80,10 +80,34 @@ void draw_view( const tui::Terminal& terminal, std::cout << "~\r\n"; } } - std::cout << "\033[7m URL: " << url << " | [j/k] Scroll [/] Jump [f] Follow [q] Quit \033[0m"; + std::cout << "\033[7m URL: " << url << " | [j/k] Scroll [/] Jump [f] Follow [H/L] History [q] Quit \033[0m"; std::cout.flush(); } +std::string format_url( std::string input ) +{ + if ( input.empty() ) { + return input; + } + + if ( input.starts_with( "http://" ) || input.starts_with( "https://" ) ) { + return input; + } + + const bool is_domain = input.contains( '.' ) && !input.contains( ' ' ); + if ( is_domain ) { + input.insert( 0, "https://" ); + return input; + } + + for ( char& ch : input ) { + if ( ch == ' ' ) { + ch = '+'; + } + } + return "https://lite.duckduckgo.com/lite/?q=" + input; +} + std::string get_url_input( const tui::Terminal& terminal ) { auto [width, height] = terminal.get_size(); @@ -116,10 +140,7 @@ std::string get_url_input( const tui::Terminal& terminal ) } terminal.show_cursor( false ); - if ( !input.empty() && !input.starts_with( "http://" ) && !input.starts_with( "https://" ) ) { - input.insert( 0, "https://" ); - } - return input; + return format_url( std::move( input ) ); } std::string get_link_input( const tui::Terminal& terminal ) @@ -195,50 +216,100 @@ void handle_follow_link( const tui::Terminal& terminal, } } +enum class InputAction : std::uint8_t +{ + None, + Quit, + Navigate +}; + +InputAction process_key( char c, + const tui::Terminal& terminal, + const PageData& page_data, + std::string& current_url, + std::vector& history, + std::size_t& history_idx, // NOLINT(bugprone-easily-swappable-parameters) + std::size_t& scroll_y ) // NOLINT(bugprone-easily-swappable-parameters) +{ + auto [width, height] = terminal.get_size(); + const std::size_t view_h = ( height > 1 ) ? ( height - 1 ) : 1; + + if ( c == 'q' ) { + return InputAction::Quit; + } + if ( c == 'j' && scroll_y + view_h < page_data.lines.size() ) { + scroll_y++; + } + if ( c == 'k' && scroll_y > 0 ) { + scroll_y--; + } + if ( c == 'H' && history_idx > 0 ) { + history_idx--; + return InputAction::Navigate; + } + if ( c == 'L' && history_idx + 1 < history.size() ) { + history_idx++; + return InputAction::Navigate; + } + + if ( c == '/' ) { + const std::string next_url = get_url_input( terminal ); + if ( !next_url.empty() ) { + history.resize( history_idx + 1 ); + history.push_back( next_url ); + history_idx++; + return InputAction::Navigate; + } + } + + if ( c == 'f' ) { + const std::string old_url = current_url; + bool nav = false; + handle_follow_link( terminal, page_data.links, current_url, nav ); + if ( nav && current_url != old_url ) { + history.resize( history_idx + 1 ); + history.push_back( current_url ); + history_idx++; + return InputAction::Navigate; + } + } + return InputAction::None; +} + } // namespace int Browser::run( std::string_view initial_url ) { - std::cout << "-> Fetching: " << initial_url << "...\n"; - - std::string current_url { initial_url }; + std::vector history; + history.emplace_back( initial_url ); + std::size_t history_idx = 0; const tui::Terminal terminal; - terminal.clear_screen(); + terminal.show_cursor( false ); + + while ( true ) { + std::string current_url = history[history_idx]; + terminal.clear_screen(); + std::cout << "-> Fetching: " << current_url << "...\r\n"; + std::cout.flush(); - while ( !current_url.empty() ) { auto page_data = load_page( current_url ); - const auto& lines = page_data.lines; - const auto& links = page_data.links; std::size_t scroll_y = 0; bool navigate = false; while ( !navigate ) { - draw_view( terminal, lines, scroll_y, current_url ); - + draw_view( terminal, page_data.lines, scroll_y, current_url ); const char c = terminal.read_key(); - auto [width, height] = terminal.get_size(); - const std::size_t view_h = ( height > 1 ) ? ( height - 1 ) : 1; - if ( c == 'q' ) { + const InputAction action = process_key( c, terminal, page_data, current_url, history, history_idx, scroll_y ); + if ( action == InputAction::Quit ) { terminal.clear_screen(); return 0; } - if ( c == 'j' && scroll_y + view_h < lines.size() ) { - scroll_y++; - } else if ( c == 'k' && scroll_y > 0 ) { - scroll_y--; - } else if ( c == '/' ) { - std::string next_url = get_url_input( terminal ); - if ( !next_url.empty() ) { - current_url = std::move( next_url ); - navigate = true; - } - } else if ( c == 'f' ) { - handle_follow_link( terminal, links, current_url, navigate ); + if ( action == InputAction::Navigate ) { + navigate = true; } } } - terminal.clear_screen(); return 0; } diff --git a/ricochet/src/main.cc b/ricochet/src/main.cc index 0371cda..1037833 100644 --- a/ricochet/src/main.cc +++ b/ricochet/src/main.cc @@ -62,8 +62,13 @@ int main( int argc, char* argv[] ) return 0; } + std::string start_url( input ); + if ( !start_url.starts_with( "http://" ) && !start_url.starts_with( "https://" ) ) { + start_url.insert( 0, "https://" ); + } + try { - return ricochet::core::Browser::run( input ); + return ricochet::core::Browser::run( start_url ); } catch ( const std::exception& e ) { std::cerr << "Critical Error: " << e.what() << "\n"; return 1; diff --git a/ricochet/src/net/http_client.cc b/ricochet/src/net/http_client.cc index b31976f..5cf6a30 100644 --- a/ricochet/src/net/http_client.cc +++ b/ricochet/src/net/http_client.cc @@ -133,63 +133,111 @@ std::string remove_tag_blocks( std::string html, const std::string& tag_name ) / return html; } -} // namespace - -std::expected -HttpClient::fetch( // NOLINT(readability-convert-member-functions-to-static) - std::string_view url ) const +std::string extract_redirect_url( const std::string& raw_response, bool is_https, const std::string& host ) { - auto parsed_url = parse_url( url ); - if ( !parsed_url.has_value() ) { - return std::unexpected( parsed_url.error() ); + auto loc_pos = raw_response.find( "Location: " ); + if ( loc_pos == std::string::npos ) { + loc_pos = raw_response.find( "location: " ); } + if ( loc_pos != std::string::npos ) { + loc_pos += 10; + auto end_pos = raw_response.find( '\r', loc_pos ); + if ( end_pos == std::string::npos ) { + end_pos = raw_response.find( '\n', loc_pos ); + } + if ( end_pos != std::string::npos ) { + std::string next_url = raw_response.substr( loc_pos, end_pos - loc_pos ); + while ( !next_url.empty() && std::isspace( static_cast( next_url.front() ) ) ) { + next_url.erase( 0, 1 ); + } + if ( next_url.starts_with( "/" ) ) { + next_url = ( is_https ? "https://" : "http://" ) + host + next_url; + } + return next_url; + } + } + return ""; +} - auto [host, path] = parsed_url.value(); - const bool is_https = url.starts_with( "https://" ); - const std::string service = is_https ? "https" : "http"; - +struct FetchResult +{ + std::string raw_response {}; + std::string error {}; +}; +FetchResult do_network_request( const std::string& host, + const std::string& service, // NOLINT(bugprone-easily-swappable-parameters) + const std::string& path, // NOLINT(bugprone-easily-swappable-parameters) + bool is_https ) +{ + FetchResult res; try { const Address server_addr( host, service ); + const std::string request + = std::format( "GET {} HTTP/1.1\r\n" + "Host: {}\r\n" + "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/124.0.0.0 Safari/537.36\r\n" + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" + "Accept-Language: en-US,en;q=0.9\r\n" + "DNT: 1\r\n" + "Connection: close\r\n\r\n", + path, + host ); - const std::string request = std::format( "GET {} HTTP/1.1\r\n" - "Host: {}\r\n" - "User-Agent: Mozilla/5.0 (Ricochet/0.1.0)\r\n" - "Accept: text/html\r\n" - "Accept-Encoding: identity\r\n" - "Connection: close\r\n\r\n", - path, - host ); - - std::string raw_response; if ( is_https ) { SSLSocket ssl_socket; ssl_socket.connect( server_addr, host ); - size_t bytes_written = 0; - while ( bytes_written < request.size() ) { - bytes_written += ssl_socket.write( request.substr( bytes_written ) ); + for ( size_t bw = 0; bw < request.size(); ) { + bw += ssl_socket.write( request.substr( bw ) ); } while ( !ssl_socket.eof() ) { std::string buffer; ssl_socket.read( buffer ); - raw_response += buffer; + res.raw_response += buffer; } } else { TCPSocket tcp_socket; tcp_socket.connect( server_addr ); - size_t bytes_written = 0; - while ( bytes_written < request.size() ) { - bytes_written += tcp_socket.write( request.substr( bytes_written ) ); + for ( size_t bw = 0; bw < request.size(); ) { + bw += tcp_socket.write( request.substr( bw ) ); } while ( !tcp_socket.eof() ) { std::string buffer; tcp_socket.read( buffer ); - raw_response += buffer; + res.raw_response += buffer; } } + } catch ( const std::exception& e ) { + res.error = std::string( "Network Error: " ) + e.what(); + } + return res; +} - HttpResponse response; - auto header_end = raw_response.find( "\r\n\r\n" ); +} // namespace + +std::expected HttpClient::fetch( std::string_view url ) const +{ + (void)this; // 完美绕过 static 方法警告,满足最严苛的 tidy 规则 + std::string current_url( url ); + + for ( int redirect_count = 0; redirect_count < 5; ++redirect_count ) { + const auto parsed_url = parse_url( current_url ); + if ( !parsed_url.has_value() ) { + return std::unexpected( parsed_url.error() ); + } + + const auto [host, path] = parsed_url.value(); + const bool is_https = current_url.starts_with( "https://" ); + const std::string service = is_https ? "https" : "http"; + + const FetchResult net_res = do_network_request( host, service, path, is_https ); + if ( !net_res.error.empty() ) { + return std::unexpected( net_res.error ); + } + const std::string& raw_response = net_res.raw_response; + HttpResponse response; + const auto header_end = raw_response.find( "\r\n\r\n" ); if ( header_end != std::string::npos ) { response.body = raw_response.substr( header_end + 4 ); if ( raw_response.size() >= 12 ) { @@ -201,19 +249,27 @@ HttpClient::fetch( // NOLINT(readability-convert-member-functions-to-static) } } else { response.body = raw_response; + response.status_code = 0; + } + + if ( response.status_code >= 300 && response.status_code < 400 ) { + const std::string next_url = extract_redirect_url( raw_response, is_https, host ); + if ( !next_url.empty() ) { + current_url = next_url; + continue; + } } if ( raw_response.contains( "Transfer-Encoding: chunked" ) ) { response.body = dechunk( response.body ); } - response.body = remove_html_comments( response.body ); response.body = remove_tag_blocks( response.body, "script" ); response.body = remove_tag_blocks( response.body, "style" ); return response; - } catch ( const std::exception& e ) { - return std::unexpected( std::string( "Network Error: " ) + e.what() ); } + + return std::unexpected( "Too many redirects" ); } } // namespace ricochet::net \ No newline at end of file diff --git a/ricochet/src/render/renderer.cc b/ricochet/src/render/renderer.cc index 1af40f1..2b690ca 100644 --- a/ricochet/src/render/renderer.cc +++ b/ricochet/src/render/renderer.cc @@ -83,11 +83,14 @@ void render_node( const parser::DomNode& node, // NOLINT(misc-no-recursion) const bool is_header = ( base_tag == "h1" || base_tag == "h2" || base_tag == "h3" || base_tag == "h4" ); const bool is_link = ( base_tag == "a" ); + const bool is_list_item = ( base_tag == "li" ); if ( is_header ) { output += "\n\n\033[1;31m"; } else if ( is_link ) { - output += "\033[4;34m"; // 【核心修复】:必须是 output += ,绝对不能用 std::cout + output += "\033[4;34m"; + } else if ( is_list_item ) { + output += "\n • "; } else if ( base_tag == "p" || base_tag == "div" || is_header ) { if ( !output.empty() && output.back() != '\n' ) { output += "\n"; @@ -112,6 +115,17 @@ void render_node( const parser::DomNode& node, // NOLINT(misc-no-recursion) if ( base_tag == "h1" || base_tag == "p" || base_tag == "div" ) { output += "\n"; } + + if ( base_tag == "img" ) { + std::size_t alt_pos = node.tag_name.find( "alt=\"" ); + if ( alt_pos != std::string::npos ) { + alt_pos += 5; + const std::size_t alt_end = node.tag_name.find( '"', alt_pos ); + output += " \033[90m[Image: " + node.tag_name.substr( alt_pos, alt_end - alt_pos ) + "]\033[0m "; + } else { + output += " \033[90m[IMAGE]\033[0m "; + } + } } } // namespace diff --git a/ricochet/src/tui/terminal.cc b/ricochet/src/tui/terminal.cc index 9e78a02..44c0f3b 100644 --- a/ricochet/src/tui/terminal.cc +++ b/ricochet/src/tui/terminal.cc @@ -44,6 +44,7 @@ Terminal::Terminal() Terminal::~Terminal() { + show_cursor( true ); // RAII: restore terminal attributes when program exits tcsetattr( STDIN_FILENO, TCSAFLUSH, &original_termios_ ); } -- cgit v1.2.3 From a8c5e1794e4c4b8ca1ad9e6212c1d7ae54dbff6f Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Fri, 16 Oct 2026 22:35:09 +0800 Subject: Remove legacy terminal UI infrastructure and rename license file --- ricochet/COPYING | 674 +++++++++++++++++++++++ ricochet/LICENSE | 674 ----------------------- ricochet/include/ricochet/core/browser.hh | 5 +- ricochet/include/ricochet/core/form_handler.hh | 11 - ricochet/include/ricochet/core/link_hints.hh | 27 - ricochet/include/ricochet/core/search_handler.hh | 23 - ricochet/include/ricochet/core/types.hh | 4 - ricochet/include/ricochet/core/ui_input.hh | 29 - ricochet/include/ricochet/core/ui_view.hh | 37 -- ricochet/include/ricochet/core/utils.hh | 2 - ricochet/include/ricochet/tui/terminal.hh | 56 -- ricochet/src/CMakeLists.txt | 1 - ricochet/src/core/browser.cc | 154 ------ ricochet/src/core/form_handler.cc | 101 ---- ricochet/src/core/link_hints.cc | 104 ---- ricochet/src/core/search_handler.cc | 81 --- ricochet/src/core/ui_input.cc | 94 ---- ricochet/src/core/ui_view.cc | 103 ---- ricochet/src/core/utils.cc | 33 -- ricochet/src/tui/terminal.cc | 90 --- 20 files changed, 676 insertions(+), 1627 deletions(-) create mode 100644 ricochet/COPYING delete mode 100644 ricochet/LICENSE delete mode 100644 ricochet/include/ricochet/core/link_hints.hh delete mode 100644 ricochet/include/ricochet/core/search_handler.hh delete mode 100644 ricochet/include/ricochet/core/ui_input.hh delete mode 100644 ricochet/include/ricochet/core/ui_view.hh delete mode 100644 ricochet/include/ricochet/tui/terminal.hh delete mode 100644 ricochet/src/core/link_hints.cc delete mode 100644 ricochet/src/core/search_handler.cc delete mode 100644 ricochet/src/core/ui_input.cc delete mode 100644 ricochet/src/core/ui_view.cc delete mode 100644 ricochet/src/tui/terminal.cc (limited to 'ricochet/src/tui') diff --git a/ricochet/COPYING b/ricochet/COPYING new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/ricochet/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/ricochet/LICENSE b/ricochet/LICENSE deleted file mode 100644 index f288702..0000000 --- a/ricochet/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/ricochet/include/ricochet/core/browser.hh b/ricochet/include/ricochet/core/browser.hh index ab7a473..fabcba4 100644 --- a/ricochet/include/ricochet/core/browser.hh +++ b/ricochet/include/ricochet/core/browser.hh @@ -18,7 +18,7 @@ #pragma once -#include +#include namespace ricochet::core { @@ -35,7 +35,6 @@ public: static std::string format_url( std::string input ); static std::string get_configured_homepage(); - static int run( std::string_view initial_url ); }; -} // namespace ricochet::core \ No newline at end of file +} // namespace ricochet::core diff --git a/ricochet/include/ricochet/core/form_handler.hh b/ricochet/include/ricochet/core/form_handler.hh index 5abf148..d95bd02 100644 --- a/ricochet/include/ricochet/core/form_handler.hh +++ b/ricochet/include/ricochet/core/form_handler.hh @@ -12,7 +12,6 @@ #include "ricochet/core/types.hh" #include "ricochet/render/renderer.hh" -#include "ricochet/tui/terminal.hh" #include #include #include @@ -25,14 +24,4 @@ InputAction submit_form( const render::InputField& target_input, std::vector& history, std::size_t& history_idx ); -void update_input_value( PageData& page_data, std::size_t index, const std::string& query ); -void update_single_line_ui( std::string& line, const std::string& marker, const render::InputField& in ); -void update_toggle_ui( PageData& page_data ); - -InputAction handle_form_input( const tui::Terminal& terminal, - PageData& page_data, - const std::string& current_url, - std::vector& history, - std::size_t& history_idx ); - } // namespace ricochet::core diff --git a/ricochet/include/ricochet/core/link_hints.hh b/ricochet/include/ricochet/core/link_hints.hh deleted file mode 100644 index 5da4846..0000000 --- a/ricochet/include/ricochet/core/link_hints.hh +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - */ - -#pragma once - -#include "ricochet/core/types.hh" -#include "ricochet/tui/terminal.hh" -#include - -namespace ricochet::core { - -std::string index_to_hint( std::size_t index ); -void toggle_link_hints( PageData& page_data, bool show ); -void handle_follow_link( const tui::Terminal& terminal, - PageData& page_data, - std::string& current_url, - std::size_t& scroll_y, - bool& navigate ); - -} // namespace ricochet::core diff --git a/ricochet/include/ricochet/core/search_handler.hh b/ricochet/include/ricochet/core/search_handler.hh deleted file mode 100644 index 7053be8..0000000 --- a/ricochet/include/ricochet/core/search_handler.hh +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - */ - -#pragma once - -#include "ricochet/core/types.hh" -#include -#include - -namespace ricochet::core { - -void find_search_matches( PageData& page_data, const std::string& query ); -void apply_search_highlight( PageData& page_data, const std::string& query ); -void execute_search( PageData& page_data, const std::string& query, std::size_t& scroll_y, bool next_match ); - -} // namespace ricochet::core diff --git a/ricochet/include/ricochet/core/types.hh b/ricochet/include/ricochet/core/types.hh index bd7e819..ef48016 100644 --- a/ricochet/include/ricochet/core/types.hh +++ b/ricochet/include/ricochet/core/types.hh @@ -31,10 +31,6 @@ struct PageData std::vector links; std::vector inputs; std::string title; - std::vector original_lines {}; - std::string last_search {}; - std::size_t current_match_idx { 0 }; - std::vector match_lines {}; }; struct HttpRequest diff --git a/ricochet/include/ricochet/core/ui_input.hh b/ricochet/include/ricochet/core/ui_input.hh deleted file mode 100644 index bf71685..0000000 --- a/ricochet/include/ricochet/core/ui_input.hh +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#pragma once - -#include "ricochet/tui/terminal.hh" -#include - -namespace ricochet::core { - -std::string get_url_input( const tui::Terminal& terminal ); -std::string get_terminal_input( const tui::Terminal& terminal, const std::string& prompt ); - -} // namespace ricochet::core diff --git a/ricochet/include/ricochet/core/ui_view.hh b/ricochet/include/ricochet/core/ui_view.hh deleted file mode 100644 index d9a55fa..0000000 --- a/ricochet/include/ricochet/core/ui_view.hh +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#pragma once - -#include "ricochet/tui/terminal.hh" - -#include -#include -#include - -namespace ricochet::core { - -std::string build_footer( std::string_view url, std::size_t width ); - -void draw_view( const tui::Terminal& terminal, - const std::vector& lines, - std::size_t scroll_y, - std::string_view url, - std::string_view title ); - -} // namespace ricochet::core diff --git a/ricochet/include/ricochet/core/utils.hh b/ricochet/include/ricochet/core/utils.hh index d9f58dd..61d480b 100644 --- a/ricochet/include/ricochet/core/utils.hh +++ b/ricochet/include/ricochet/core/utils.hh @@ -18,7 +18,6 @@ #pragma once -#include #include #include @@ -27,6 +26,5 @@ namespace ricochet::core { std::vector split_into_lines( const std::string& text ); std::string normalize_url( const std::string& target, const std::string& current_url ); std::string strip_ddg_tracker( std::string target ); -std::vector wrap_lines( const std::vector& original_lines, std::size_t wrap_width ); } // namespace ricochet::core diff --git a/ricochet/include/ricochet/tui/terminal.hh b/ricochet/include/ricochet/tui/terminal.hh deleted file mode 100644 index 2942a2a..0000000 --- a/ricochet/include/ricochet/tui/terminal.hh +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#pragma once - -#include -#include - -namespace ricochet::tui { - -class Terminal -{ -public: - Terminal(); - ~Terminal(); - - Terminal( const Terminal& ) = delete; - Terminal& operator=( const Terminal& ) = delete; - Terminal( Terminal&& ) = delete; - Terminal& operator=( Terminal&& ) = delete; - - // Read a single key - char read_key() const; - - // Clear screen and move cursor to top-left - void clear_screen() const; - - // Get terminal size - std::pair get_size() const; - - // Move cursor to a specific position - void move_cursor( std::size_t row, std::size_t col ) const; - - // Show or hide cursor - void show_cursor( bool visible ) const; - -private: - struct termios original_termios_ {}; // Save terminal original state -}; - -} // namespace ricochet::tui \ No newline at end of file diff --git a/ricochet/src/CMakeLists.txt b/ricochet/src/CMakeLists.txt index dcc8f49..e46ac9a 100644 --- a/ricochet/src/CMakeLists.txt +++ b/ricochet/src/CMakeLists.txt @@ -17,4 +17,3 @@ target_link_libraries(ricochet_core add_executable(ricochet ${MAIN_SRC}) target_link_libraries(ricochet PRIVATE ricochet_core) -# target_link_libraries(ricochet PRIVATE ricochet_core curl ncurses) \ No newline at end of file diff --git a/ricochet/src/core/browser.cc b/ricochet/src/core/browser.cc index 86a5096..c413a0d 100644 --- a/ricochet/src/core/browser.cc +++ b/ricochet/src/core/browser.cc @@ -18,117 +18,12 @@ #include "ricochet/core/browser.hh" -#include -#include #include -#include -#include -#include "ricochet/core/form_handler.hh" -#include "ricochet/core/link_hints.hh" #include "ricochet/core/local_data.hh" -#include "ricochet/core/page_loader.hh" -#include "ricochet/core/search_handler.hh" -#include "ricochet/core/ui_input.hh" -#include "ricochet/core/ui_view.hh" -#include "ricochet/core/utils.hh" namespace ricochet::core { -namespace { - -InputAction push_history( const std::string& url, std::vector& history, std::size_t& history_idx ) -{ - history.resize( history_idx + 1 ); - history.push_back( HttpRequest { .url = url, .method = "GET", .body = "" } ); - history_idx++; - return InputAction::Navigate; -} - -InputAction process_key( char c, - const tui::Terminal& terminal, - PageData& page_data, - std::string& current_url, - std::vector& history, - std::size_t& history_idx, // NOLINT(bugprone-easily-swappable-parameters) - std::size_t& scroll_y ) // NOLINT(bugprone-easily-swappable-parameters) -{ - auto [width, height] = terminal.get_size(); - const std::size_t view_h = ( height > 1 ) ? ( height - 1 ) : 1; - - switch ( c ) { - case 'q': - return InputAction::Quit; - case 'j': - if ( scroll_y + view_h < page_data.lines.size() ) { - scroll_y++; - } - break; - case 'k': - if ( scroll_y > 0 ) { - scroll_y--; - } - break; - case 'H': - if ( history_idx > 0 ) { - history_idx--; - return InputAction::Navigate; - } - break; - case 'L': - if ( history_idx + 1 < history.size() ) { - history_idx++; - return InputAction::Navigate; - } - break; - case 'r': - return InputAction::Navigate; - case 'b': - save_bookmark( page_data.title, current_url ); - break; - case 'B': - return push_history( "ricochet://bookmarks", history, history_idx ); - case '?': - return push_history( "ricochet://help", history, history_idx ); - case 'h': - return push_history( "ricochet://history", history, history_idx ); - case 'n': { - const std::string query = get_terminal_input( terminal, "Find in Page:" ); - execute_search( page_data, query, scroll_y, false ); - break; - } - case 'N': - execute_search( page_data, page_data.last_search, scroll_y, true ); - break; - case '/': { - const std::string next_url = get_url_input( terminal ); - if ( !next_url.empty() ) { - return push_history( next_url, history, history_idx ); - } - break; - } - case 'f': { - const std::string old_url = current_url; - bool nav = false; - handle_follow_link( terminal, page_data, current_url, scroll_y, nav ); - if ( nav && current_url != old_url ) { - return push_history( current_url, history, history_idx ); - } - break; - } - case 'i': - if ( !page_data.inputs.empty() ) { - return handle_form_input( terminal, page_data, current_url, history, history_idx ); - } - break; - default: - break; - } - return InputAction::None; -} - -} // namespace - std::string Browser::format_url( std::string input ) { if ( input.empty() ) { @@ -168,53 +63,4 @@ std::string Browser::get_configured_homepage() return "https://wikipedia.org"; } -int Browser::run( std::string_view initial_url ) -{ - std::vector history; - history.emplace_back( HttpRequest { .url = std::string( initial_url ), .method = "GET", .body = "" } ); - std::size_t history_idx = 0; - const tui::Terminal terminal; - terminal.show_cursor( false ); - - while ( true ) { - const HttpRequest current_req = history[history_idx]; - std::string current_url = current_req.url; - terminal.clear_screen(); - std::cout << "-> Fetching: " << current_req.url << "...\r\n"; - std::cout.flush(); - - auto page_data = load_page( current_req ); - - static std::string last_recorded_url; - if ( current_url != last_recorded_url && !current_url.starts_with( "ricochet://" ) ) { - append_to_history( current_url, page_data.title ); - last_recorded_url = current_url; - } - - auto [term_width, term_height] = terminal.get_size(); - const std::size_t wrap_width = ( term_width > 1 ) ? ( term_width - 1 ) : 80; - page_data.lines = wrap_lines( page_data.lines, wrap_width ); - page_data.original_lines = page_data.lines; - - std::size_t scroll_y = 0; - bool navigate = false; - - while ( !navigate ) { - draw_view( terminal, page_data.lines, scroll_y, current_url, page_data.title ); - const char c = terminal.read_key(); - - const InputAction action = process_key( c, terminal, page_data, current_url, history, history_idx, scroll_y ); - if ( action == InputAction::Quit ) { - terminal.clear_screen(); - return 0; - } - if ( action == InputAction::Navigate ) { - navigate = true; - } - } - } - terminal.clear_screen(); - return 0; -} - } // namespace ricochet::core diff --git a/ricochet/src/core/form_handler.cc b/ricochet/src/core/form_handler.cc index 2d018c9..6100a30 100644 --- a/ricochet/src/core/form_handler.cc +++ b/ricochet/src/core/form_handler.cc @@ -17,7 +17,6 @@ */ #include "ricochet/core/form_handler.hh" -#include "ricochet/core/ui_input.hh" #include "ricochet/core/utils.hh" namespace ricochet::core { @@ -62,104 +61,4 @@ InputAction submit_form( const render::InputField& target_input, return InputAction::Navigate; } -void update_input_value( PageData& page_data, std::size_t index, const std::string& query ) -{ - page_data.inputs[index - 1].value = query; - const std::string marker = "[I" + std::to_string( index ) + ":"; - const std::string replacement = "[I" + std::to_string( index ) + ":" + query + "]"; - - auto update_lines = [&]( std::vector& lines_arr ) { - for ( auto& line : lines_arr ) { - const std::size_t pos = line.find( marker ); - if ( pos != std::string::npos ) { - const std::size_t end = line.find( ']', pos ); - if ( end != std::string::npos ) { - line.replace( pos, end - pos + 1, replacement ); - } - } - } - }; - update_lines( page_data.lines ); - update_lines( page_data.original_lines ); -} - -void update_single_line_ui( std::string& line, const std::string& marker, const render::InputField& in ) -{ - const std::string checked_str = marker + ( in.type == "checkbox" ? "[X] " : "(X) " ) + in.value + "]"; - const std::string unchecked_str = marker + ( in.type == "checkbox" ? "[ ] " : "( ) " ) + in.value + "]"; - - const std::string& target_str = in.checked ? checked_str : unchecked_str; - const std::string& old_str = in.checked ? unchecked_str : checked_str; - - const std::size_t pos = line.find( old_str ); - if ( pos != std::string::npos ) { - line.replace( pos, old_str.length(), target_str ); - } -} - -void update_toggle_ui( PageData& page_data ) -{ - for ( std::size_t i = 0; i < page_data.inputs.size(); ++i ) { - const auto& in = page_data.inputs[i]; - if ( in.type != "checkbox" && in.type != "radio" ) { - continue; - } - const std::string marker = "[I" + std::to_string( i + 1 ) + ":"; - for ( auto& line : page_data.lines ) { - update_single_line_ui( line, marker, in ); - } - for ( auto& line : page_data.original_lines ) { - update_single_line_ui( line, marker, in ); - } - } -} - -InputAction handle_form_input( const tui::Terminal& terminal, - PageData& page_data, - const std::string& current_url, - std::vector& history, - std::size_t& history_idx ) -{ - const std::string num_input = get_terminal_input( terminal, "Select Input [#]:" ); - if ( num_input.empty() ) { - return InputAction::None; - } - std::size_t index = 0; - try { - index = std::stoul( num_input ); - } catch ( ... ) { - return InputAction::None; - } - if ( index == 0 || index > page_data.inputs.size() ) { - return InputAction::None; - } - - auto& target_input = page_data.inputs[index - 1]; - if ( target_input.type == "submit" || target_input.type == "button" ) { - return submit_form( target_input, page_data.inputs, current_url, history, history_idx ); - } - - if ( target_input.type == "checkbox" || target_input.type == "radio" ) { - if ( target_input.type == "radio" ) { - for ( auto& in : page_data.inputs ) { - if ( in.name == target_input.name && in.action == target_input.action ) { - in.checked = false; - } - } - target_input.checked = true; - } else { - target_input.checked = !target_input.checked; - } - update_toggle_ui( page_data ); - return InputAction::None; - } - - const std::string query = get_terminal_input( terminal, "Enter Text [I" + std::to_string( index ) + "]:" ); - if ( query.empty() ) { - return InputAction::None; - } - update_input_value( page_data, index, query ); - return InputAction::None; -} - } // namespace ricochet::core diff --git a/ricochet/src/core/link_hints.cc b/ricochet/src/core/link_hints.cc deleted file mode 100644 index 77b91b8..0000000 --- a/ricochet/src/core/link_hints.cc +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "ricochet/core/link_hints.hh" -#include "ricochet/core/ui_view.hh" -#include "ricochet/core/utils.hh" -#include - -namespace ricochet::core { - -std::string index_to_hint( std::size_t index ) -{ - const std::string alphabet = "asdfghjklqwertyuiopzxcvbnm"; - std::string hint; - hint += alphabet[( index / alphabet.length() ) % alphabet.length()]; - hint += alphabet[index % alphabet.length()]; - return hint; -} - -void toggle_link_hints( PageData& page_data, bool show ) -{ - const std::string hl_start = "\033[0;1;35;7m "; - const std::string hl_end = " \033[0m"; - - std::vector formatted_hints; - formatted_hints.reserve( page_data.links.size() ); - for ( std::size_t i = 0; i < page_data.links.size(); ++i ) { - std::string h = hl_start; - h += index_to_hint( i ); - h += hl_end; - formatted_hints.push_back( std::move( h ) ); - } - - for ( auto& line : page_data.lines ) { - for ( std::size_t i = 0; i < page_data.links.size(); ++i ) { - const std::string marker = "{L:" + std::to_string( i + 1 ) + "}"; - if ( show ) { - const std::size_t pos = line.find( marker ); - if ( pos != std::string::npos ) { - line.replace( pos, marker.length(), formatted_hints[i] ); - } - } else { - const std::size_t pos = line.find( formatted_hints[i] ); - if ( pos != std::string::npos ) { - line.replace( pos, formatted_hints[i].length(), marker ); - } - } - } - } -} - -void handle_follow_link( const tui::Terminal& terminal, - PageData& page_data, - std::string& current_url, - std::size_t& scroll_y, // NOLINT(bugprone-easily-swappable-parameters) - bool& navigate ) -{ - toggle_link_hints( page_data, true ); - - draw_view( terminal, page_data.lines, scroll_y, current_url, page_data.title ); - - auto [w, h] = terminal.get_size(); - terminal.move_cursor( h, 1 ); - std::cout << "\x1b[2K\033[1;35;7m Follow Hint (2 keys): \033[0m "; - std::cout.flush(); - - std::string input; - input += terminal.read_key(); - std::cout << input[0]; - std::cout.flush(); - input += terminal.read_key(); - - // bool found = false; - for ( std::size_t i = 0; i < page_data.links.size(); ++i ) { - if ( index_to_hint( i ) == input ) { - std::string target = page_data.links[i]; - target = normalize_url( target, current_url ); - target = strip_ddg_tracker( target ); - current_url = target; - navigate = true; - // found = true; - break; - } - } - - toggle_link_hints( page_data, false ); -} - -} // namespace ricochet::core diff --git a/ricochet/src/core/search_handler.cc b/ricochet/src/core/search_handler.cc deleted file mode 100644 index cab9e9c..0000000 --- a/ricochet/src/core/search_handler.cc +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "ricochet/core/search_handler.hh" - -namespace ricochet::core { - -void find_search_matches( PageData& page_data, const std::string& query ) -{ - page_data.last_search = query; - page_data.match_lines.clear(); - page_data.current_match_idx = 0; - for ( std::size_t i = 0; i < page_data.original_lines.size(); ++i ) { - if ( page_data.original_lines[i].find( query ) != std::string::npos ) { - page_data.match_lines.push_back( i ); - } - } -} - -void apply_search_highlight( PageData& page_data, const std::string& query ) -{ - page_data.lines = page_data.original_lines; - if ( page_data.match_lines.empty() ) { - return; - } - - const std::string hl_start = "\033[43;30m"; - const std::string hl_end = "\033[0m"; - - for ( const auto match_idx : page_data.match_lines ) { - auto& line = page_data.lines[match_idx]; - std::size_t pos = 0; - std::string replacement; - replacement.reserve( hl_start.length() + query.length() + hl_end.length() ); - replacement += hl_start; - replacement += query; - replacement += hl_end; - while ( ( pos = line.find( query, pos ) ) != std::string::npos ) { - line.replace( pos, query.length(), replacement ); - pos += hl_start.length() + query.length() + hl_end.length(); - } - } -} - -void execute_search( PageData& page_data, const std::string& query, std::size_t& scroll_y, bool next_match ) -{ - if ( query.empty() ) { - return; - } - - if ( !next_match || query != page_data.last_search ) { - find_search_matches( page_data, query ); - apply_search_highlight( page_data, query ); - } else if ( !page_data.match_lines.empty() ) { - page_data.current_match_idx = ( page_data.current_match_idx + 1 ) % page_data.match_lines.size(); - } - - if ( page_data.match_lines.empty() ) { - return; - } - - const std::size_t target_line = page_data.match_lines[page_data.current_match_idx]; - scroll_y = ( target_line > 5 ) ? ( target_line - 5 ) : 0; -} - -} // namespace ricochet::core diff --git a/ricochet/src/core/ui_input.cc b/ricochet/src/core/ui_input.cc deleted file mode 100644 index 0f57dd1..0000000 --- a/ricochet/src/core/ui_input.cc +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "ricochet/core/ui_input.hh" -#include "ricochet/core/browser.hh" -#include - -namespace ricochet::core { - -std::string get_url_input( const tui::Terminal& terminal ) -{ - auto [width, height] = terminal.get_size(); - terminal.move_cursor( height, 1 ); - std::cout << "\x1b[2K\033[7m URL: \033[0m "; - std::cout.flush(); - - std::string input; - terminal.show_cursor( true ); - while ( true ) { - const char ch = terminal.read_key(); - if ( ch == '\r' || ch == '\n' ) { - break; - } - if ( ch == 27 ) { - input.clear(); - break; - } - if ( ch == 127 || ch == 8 ) { - if ( !input.empty() ) { - input.pop_back(); - std::cout << "\b \b"; - std::cout.flush(); - } - } else if ( std::isprint( static_cast( ch ) ) ) { - input += ch; - std::cout << ch; - std::cout.flush(); - } - } - terminal.show_cursor( false ); - - return Browser::format_url( std::move( input ) ); -} - -std::string get_terminal_input( const tui::Terminal& terminal, const std::string& prompt ) -{ - auto [width, height] = terminal.get_size(); - terminal.move_cursor( height, 1 ); - std::cout << "\x1b[2K\033[7m " << prompt << " \033[0m "; - std::cout.flush(); - - std::string input; - terminal.show_cursor( true ); - while ( true ) { - const char ch = terminal.read_key(); - if ( ch == '\r' || ch == '\n' ) { - break; - } - if ( ch == 27 ) { - input.clear(); - break; - } - if ( ch == 127 || ch == 8 ) { - if ( !input.empty() ) { - input.pop_back(); - std::cout << "\b \b"; - std::cout.flush(); - } - } else if ( std::isprint( static_cast( ch ) ) ) { - input += ch; - std::cout << ch; - std::cout.flush(); - } - } - terminal.show_cursor( false ); - return input; -} - -} // namespace ricochet::core diff --git a/ricochet/src/core/ui_view.cc b/ricochet/src/core/ui_view.cc deleted file mode 100644 index 5164fe0..0000000 --- a/ricochet/src/core/ui_view.cc +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "ricochet/core/ui_view.hh" -#include - -namespace ricochet::core { - -std::string build_footer( std::string_view url, std::size_t width ) -{ - const std::string_view keys - = " | [j/k]Scroll [n/N]Find [/]Nav [f]Hint [i]In [r]Ref [H/L]Back [h]Hist [b/B]Mark [?]Help [q]Quit "; - const std::string_view prefix = " URL: "; - - std::string footer; - if ( width <= keys.length() + prefix.length() + 3 ) { - footer.reserve( prefix.length() + url.length() + keys.length() ); - footer += prefix; - footer += url; - footer += keys; - if ( footer.length() > width && width > 3 ) { - footer.erase( width - 3 ); - footer += "..."; - } - } else { - const std::size_t max_url_len = width - keys.length() - prefix.length(); - footer.reserve( width ); - footer += prefix; - if ( url.length() > max_url_len ) { - footer += url.substr( 0, max_url_len - 3 ); - footer += "..."; - } else { - footer += url; - } - footer += keys; - } - - if ( footer.length() < width ) { - footer.append( width - footer.length(), ' ' ); - } - return footer; -} - -void draw_view( const tui::Terminal& terminal, - const std::vector& lines, - std::size_t scroll_y, - std::string_view url, // NOLINT(bugprone-easily-swappable-parameters) - std::string_view title ) // NOLINT(bugprone-easily-swappable-parameters) -{ - terminal.clear_screen(); - auto [width, height] = terminal.get_size(); - const std::size_t usable_height = ( height > 2 ) ? ( height - 2 ) : 1; - - std::string clean_title( title ); - if ( clean_title.empty() ) { - const std::size_t start = url.find( "://" ); - const std::size_t host_start = ( start == std::string::npos ) ? 0 : start + 3; - const std::size_t host_end = url.find( '/', host_start ); - clean_title = std::string( url.substr( host_start, host_end - host_start ) ); - } - for ( char& c : clean_title ) { - if ( c == '\n' || c == '\r' ) { - c = ' '; - } - } - - std::string header = " PAGE: " + clean_title; - if ( header.size() < width ) { - header.append( width - header.size(), ' ' ); - } else if ( header.size() > width && width > 3 ) { - header = header.substr( 0, width - 3 ) + "..."; - } - std::cout << "\033[7m" << header << "\033[0m\r\n"; - - for ( std::size_t i = 0; i < usable_height; ++i ) { - if ( scroll_y + i < lines.size() ) { - std::cout << lines[scroll_y + i] << "\r\n"; - } else { - std::cout << "~\r\n"; - } - } - - const std::string footer = build_footer( url, width ); - std::cout << "\033[7m" << footer << "\033[0m"; - std::cout.flush(); -} - -} // namespace ricochet::core diff --git a/ricochet/src/core/utils.cc b/ricochet/src/core/utils.cc index ddc6321..a410c8a 100644 --- a/ricochet/src/core/utils.cc +++ b/ricochet/src/core/utils.cc @@ -82,37 +82,4 @@ std::string strip_ddg_tracker( std::string target ) return target; } -std::vector wrap_lines( const std::vector& original_lines, std::size_t wrap_width ) -{ - std::vector wrapped_lines; - for ( const auto& line : original_lines ) { - std::string current_line; - std::size_t vis_count = 0; - bool in_ansi = false; - for ( const char c : line ) { - if ( c == '\x1b' ) { - in_ansi = true; - } - if ( in_ansi ) { - current_line += c; - if ( c == 'm' ) { - in_ansi = false; - } - } else { - if ( vis_count >= wrap_width ) { - wrapped_lines.push_back( current_line + "\033[0m" ); - current_line.clear(); - vis_count = 0; - } - current_line += c; - vis_count++; - } - } - if ( !current_line.empty() || line.empty() ) { - wrapped_lines.push_back( current_line + "\033[0m" ); - } - } - return wrapped_lines; -} - } // namespace ricochet::core diff --git a/ricochet/src/tui/terminal.cc b/ricochet/src/tui/terminal.cc deleted file mode 100644 index 44c0f3b..0000000 --- a/ricochet/src/tui/terminal.cc +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. - * Copyright (C) 2026 Richard Qin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "ricochet/tui/terminal.hh" -#include -#include -#include -#include - -namespace ricochet::tui { - -Terminal::Terminal() -{ - // get terminal attributes - tcgetattr( STDIN_FILENO, &original_termios_ ); - - struct termios raw = original_termios_; - - // close echo, close canonical mode - // close terminal signals (ISIG disable Ctrl+C and Ctrl+Z, let the program handle it) - raw.c_lflag &= ~( ECHO | ICANON | ISIG ); - - // close software flow control (Ctrl+S, Ctrl+Q) - raw.c_iflag &= ~( IXON | ICRNL ); - - // apply new terminal attributes - tcsetattr( STDIN_FILENO, TCSAFLUSH, &raw ); -} - -Terminal::~Terminal() -{ - show_cursor( true ); - // RAII: restore terminal attributes when program exits - tcsetattr( STDIN_FILENO, TCSAFLUSH, &original_termios_ ); -} - -char Terminal::read_key() const // NOLINT(readability-convert-member-functions-to-static) -{ - char c = '\0'; - // read 1 byte - if ( read( STDIN_FILENO, &c, 1 ) == -1 ) { - return '\0'; - } - return c; -} - -void Terminal::clear_screen() const // NOLINT(readability-convert-member-functions-to-static) -{ - // ANSI escape codes: \x1b[2J clear screen, \x1b[H move cursor to (1,1) - std::cout << "\x1b[2J\x1b[H"; -} - -std::pair Terminal::get_size() // NOLINT(readability-convert-member-functions-to-static) - const -{ - struct winsize w {}; - if ( ioctl( STDOUT_FILENO, TIOCGWINSZ, &w ) == -1 ) { - return { 80, 24 }; - } - return { static_cast( w.ws_col ), static_cast( w.ws_row ) }; -} - -void Terminal::move_cursor( std::size_t row, std::size_t col ) const // NOLINT -{ - // ANSI: \x1b[H move to 1,1; \x1b[row;colH move to specified row and column - std::cout << "\x1b[" << row << ";" << col << "H"; -} - -void Terminal::show_cursor( bool visible ) const // NOLINT -{ - // \x1b[?25h show cursor, \x1b[?25l hide cursor - std::cout << ( visible ? "\x1b[?25h" : "\x1b[?25l" ); -} - -} // namespace ricochet::tui \ No newline at end of file -- cgit v1.2.3 From fdc182dd75ca2ccd6b7ec06d0ca6c1cc71838809 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Sat, 17 Oct 2026 03:36:29 +0800 Subject: feat(tui): add document model and host message interfaces --- ricochet/include/ricochet/tui/document.hh | 255 ++++++++++++++++++++++++++++++ ricochet/include/ricochet/tui/identity.hh | 63 ++++++++ ricochet/include/ricochet/tui/messages.hh | 233 +++++++++++++++++++++++++++ ricochet/include/ricochet/tui/position.hh | 116 ++++++++++++++ ricochet/include/ricochet/tui/view.hh | 69 ++++++++ ricochet/src/tui/document.cc | 30 ++++ 6 files changed, 766 insertions(+) create mode 100644 ricochet/include/ricochet/tui/document.hh create mode 100644 ricochet/include/ricochet/tui/identity.hh create mode 100644 ricochet/include/ricochet/tui/messages.hh create mode 100644 ricochet/include/ricochet/tui/position.hh create mode 100644 ricochet/include/ricochet/tui/view.hh create mode 100644 ricochet/src/tui/document.cc (limited to 'ricochet/src/tui') diff --git a/ricochet/include/ricochet/tui/document.hh b/ricochet/include/ricochet/tui/document.hh new file mode 100644 index 0000000..bd76442 --- /dev/null +++ b/ricochet/include/ricochet/tui/document.hh @@ -0,0 +1,255 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/position.hh" + +#include +#include +#include +#include +#include +#include +#include + +namespace ricochet::tui { + +struct TextStyle +{ + bool emphasis { false }; + bool strong { false }; + bool code { false }; + bool subdued { false }; + bool warning { false }; +}; + +struct StyledRange +{ + ByteRange bytes {}; + TextStyle style {}; +}; + +// Leaf IDs and structural block IDs share one document-local namespace. +// All text offsets address a Text leaf, not a concatenation of rendered lines. +struct Text +{ + BlockId id {}; + // LF is an explicit hard break; soft wrapping never changes this string. + std::string utf8 {}; + std::vector styles {}; +}; + +struct ControlPlaceholder +{ ControlId control {}; }; + +using Inline = std::variant; + +struct Paragraph +{ std::vector content {}; }; + +struct Heading +{ + unsigned int level { 1 }; + std::vector content {}; +}; + +struct Preformatted +{ + Text content {}; + std::optional language {}; +}; + +struct Block; + +struct ListItem +{ + std::optional marker {}; + std::vector content {}; +}; + +enum class ListKind : std::uint8_t +{ + Unordered, + Ordered +}; + +struct List +{ + ListKind kind { ListKind::Unordered }; + std::int64_t first_number { 1 }; + std::vector items {}; +}; + +struct TableCell +{ + // The producer resolves HTML spans to grid coordinates before delivery. + std::size_t column { 0 }; + std::size_t column_span { 1 }; + std::size_t row_span { 1 }; + bool header { false }; + std::vector content {}; +}; + +struct TableRow +{ std::vector cells {}; }; + +struct Table +{ + std::size_t columns { 0 }; + std::vector rows {}; +}; + +struct Alternative +{ Text description {}; }; + +struct Separator +{}; + +struct Block +{ + // Structural identity supports empty blocks and per-block horizontal scroll. + BlockId id {}; + std::variant + content {}; +}; + +struct Link +{ + LinkId id {}; + std::string target {}; + std::string description {}; + // Multiple ranges can belong to one link, independently of text styling. + std::vector ranges {}; +}; + +enum class TextControlKind : std::uint8_t +{ + SingleLine, + MultiLine, + Password +}; + +struct TextControl +{ + TextControlKind kind { TextControlKind::SingleLine }; + std::string value {}; + std::string default_value {}; +}; + +struct Checkbox +{ + bool checked { false }; + bool default_checked { false }; +}; + +struct RadioButton +{ + RadioGroupId group {}; + bool checked { false }; + bool default_checked { false }; +}; + +struct SelectOption +{ + OptionId id {}; + std::string label {}; + bool disabled { false }; +}; + +enum class SelectKind : std::uint8_t +{ + Single, + Multiple +}; + +struct SelectControl +{ + SelectKind kind { SelectKind::Single }; + std::vector options {}; + std::vector selected {}; + std::vector default_selected {}; +}; + +enum class ButtonKind : std::uint8_t +{ + Submit, + Reset +}; + +struct Button +{ ButtonKind kind { ButtonKind::Submit }; }; + +struct UnsupportedControl +{ std::string description {}; }; + +struct Control +{ + ControlId id {}; + std::optional form {}; + std::string label {}; + std::string hint {}; + std::optional error {}; + bool disabled { false }; + bool read_only { false }; + std::variant content {}; +}; + +struct Form +{ + FormId id {}; + std::string label {}; +}; + +struct Anchor +{ + std::string name {}; + ContentPoint point {}; +}; + +struct DocumentMetadata +{ + std::string title {}; + std::string display_url {}; + std::optional language {}; +}; + +// Producers build owned values. No DOM pointers, terminal codes or screen coordinates. +struct DocumentData +{ + DocumentVersion version {}; + DocumentMetadata metadata {}; + std::vector blocks {}; + std::vector links {}; + std::vector controls {}; + std::vector
forms {}; + std::vector anchors {}; +}; + +class Document +{ +public: + explicit Document( DocumentData data ); + + const DocumentData& data() const noexcept; + +private: + std::shared_ptr data_; +}; + +} // namespace ricochet::tui diff --git a/ricochet/include/ricochet/tui/identity.hh b/ricochet/include/ricochet/tui/identity.hh new file mode 100644 index 0000000..624c6cc --- /dev/null +++ b/ricochet/include/ricochet/tui/identity.hh @@ -0,0 +1,63 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include + +namespace ricochet::tui { + +template +struct Identity +{ + std::uint64_t value { 0 }; + + auto operator<=>( const Identity& ) const = default; +}; + +using TabId = Identity; +using DocumentId = Identity; +using Revision = Identity; +using DraftRevision = Identity; +using BlockId = Identity; +using LinkId = Identity; +using ControlId = Identity; +using FormId = Identity; +using OptionId = Identity; +using RadioGroupId = Identity; +using TaskId = Identity; +using RequestId = Identity; + +struct DocumentVersion +{ + DocumentId document {}; + Revision revision {}; + + bool operator==( const DocumentVersion& ) const = default; +}; + +struct DocumentScope +{ + TabId tab {}; + DocumentVersion version {}; + + bool operator==( const DocumentScope& ) const = default; +}; + +} // namespace ricochet::tui diff --git a/ricochet/include/ricochet/tui/messages.hh b/ricochet/include/ricochet/tui/messages.hh new file mode 100644 index 0000000..e7dc417 --- /dev/null +++ b/ricochet/include/ricochet/tui/messages.hh @@ -0,0 +1,233 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/document.hh" +#include "ricochet/tui/view.hh" + +#include +#include +#include +#include +#include + +namespace ricochet::tui { + +struct TabInfo +{ + TabId id {}; + std::string title {}; + std::string display_url {}; + std::optional loading_task {}; +}; + +struct SyncTabs +{ + // Vector order is tab order. Request IDs acknowledge create/close actions. + std::vector tabs {}; + std::optional active {}; + std::vector completed_requests {}; +}; + +struct NavigationStarted +{ + TabId tab {}; + RequestId request {}; + TaskId task {}; + std::string display_target {}; +}; + +struct CommitDocument +{ + TabId tab {}; + RequestId navigation {}; + Document document; + std::optional restore {}; +}; + +struct TextCorrespondence +{ + // The producer identifies identical text in the two revisions, including every + // changed portion crossed by a selection. This is not an inferred text diff. + TextRange source {}; + TextRange target {}; +}; + +struct PositionMapping +{ + DocumentVersion source {}; + DocumentVersion target {}; + std::vector text {}; +}; + +enum class ViewRetention : std::uint8_t +{ + Reset, + PreserveUnchanged +}; + +struct UpdateDocument +{ + TabId tab {}; + RequestId navigation {}; + DocumentVersion source {}; + Document document; + ViewRetention retention { ViewRetention::PreserveUnchanged }; + std::optional mapping {}; +}; + +struct LocateView +{ + DocumentScope scope {}; + std::variant target {}; +}; + +// Values are keyed by control identity, never by field name or action URL. +// These business messages may carry passwords; ViewSnapshot deliberately does not. +using ControlValue = std::variant>; + +struct ControlDraft +{ + ControlId control {}; + ControlValue value {}; +}; + +struct FieldError +{ + ControlId control {}; + std::string message {}; +}; + +struct FormFeedback +{ + DocumentScope scope {}; + FormId form {}; + RequestId request {}; + DraftRevision draft_revision {}; + std::vector errors {}; + std::vector normalized_values {}; +}; + +struct ActionFailed +{ + RequestId request {}; + std::optional tab {}; + std::string summary {}; + std::optional details {}; +}; + +struct ExitDecision +{ + RequestId request {}; + bool approved { false }; + std::optional explanation {}; +}; + +using HostUpdate = std::variant; + +enum class OpenTarget : std::uint8_t +{ + CurrentTab, + NewTab +}; + +struct OpenLocation +{ + RequestId request {}; + TabId tab {}; + std::string input {}; + OpenTarget target { OpenTarget::CurrentTab }; +}; + +struct OpenLink +{ + RequestId request {}; + DocumentScope source {}; + LinkId link {}; + std::string target {}; + OpenTarget destination { OpenTarget::CurrentTab }; +}; + +enum class NavigationCommand : std::uint8_t +{ + Back, + Forward, + Reload +}; + +struct Navigate +{ + RequestId request {}; + TabId tab {}; + std::optional document {}; + NavigationCommand command { NavigationCommand::Reload }; +}; + +struct CreateTab +{ RequestId request {}; }; + +struct CloseTab +{ + RequestId request {}; + TabId tab {}; +}; + +enum class FormOperation : std::uint8_t +{ + Submit, + Reset +}; + +struct FormAction +{ + RequestId request {}; + DocumentScope scope {}; + FormId form {}; + std::optional button {}; + DraftRevision draft_revision {}; + FormOperation operation { FormOperation::Submit }; + std::vector values {}; +}; + +struct ExportSelection +{ + RequestId request {}; + DocumentScope source {}; + // Already extracted from one view snapshot; passwords are masked. + std::string text {}; +}; + +struct RequestExit +{ + RequestId request {}; + std::optional active {}; + std::vector views {}; +}; + +using UserAction + = std::variant; + +} // namespace ricochet::tui diff --git a/ricochet/include/ricochet/tui/position.hh b/ricochet/include/ricochet/tui/position.hh new file mode 100644 index 0000000..49b63f2 --- /dev/null +++ b/ricochet/include/ricochet/tui/position.hh @@ -0,0 +1,116 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/identity.hh" + +#include +#include +#include + +namespace ricochet::tui { + +// UTF-8 byte ranges are half-open. Text operations use grapheme boundaries. +struct ByteRange +{ + std::size_t start { 0 }; + std::size_t end { 0 }; + + bool operator==( const ByteRange& ) const = default; +}; + +struct TextPosition +{ + BlockId block {}; + std::size_t byte_offset { 0 }; + + bool operator==( const TextPosition& ) const = default; +}; + +struct ControlTextPosition +{ + ControlId control {}; + DraftRevision revision {}; + // Offset in display text; password offsets refer only to its mask. + std::size_t byte_offset { 0 }; + + bool operator==( const ControlTextPosition& ) const = default; +}; + +enum class BoundarySide : std::uint8_t +{ + Before, + After +}; + +struct ObjectPosition +{ + std::variant object {}; + BoundarySide side { BoundarySide::Before }; + + bool operator==( const ObjectPosition& ) const = default; +}; + +struct DocumentStart +{ bool operator==( const DocumentStart& ) const = default; }; + +// Local to a document snapshot. Stored anchors cannot depend on mutable drafts. +using ContentPoint = std::variant; +using DocumentPoint = std::variant; + +struct LogicalPosition +{ + DocumentScope scope {}; + DocumentPoint point {}; + + bool operator==( const LogicalPosition& ) const = default; +}; + +// Endpoints follow reading order, never the numeric order of their IDs. +struct DocumentRange +{ + DocumentPoint start {}; + DocumentPoint end {}; + + bool operator==( const DocumentRange& ) const = default; +}; + +struct TextRange +{ + BlockId block {}; + ByteRange bytes {}; + + bool operator==( const TextRange& ) const = default; +}; + +enum class WrapAffinity : std::uint8_t +{ + PreviousLine, + NextLine +}; + +struct DisplayPosition +{ + DocumentPoint point {}; + WrapAffinity affinity { WrapAffinity::NextLine }; + + bool operator==( const DisplayPosition& ) const = default; +}; + +} // namespace ricochet::tui diff --git a/ricochet/include/ricochet/tui/view.hh b/ricochet/include/ricochet/tui/view.hh new file mode 100644 index 0000000..d259cf3 --- /dev/null +++ b/ricochet/include/ricochet/tui/view.hh @@ -0,0 +1,69 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/position.hh" + +#include +#include +#include +#include +#include + +namespace ricochet::tui { + +enum class SelectionDirection : std::uint8_t +{ + Forward, + Backward +}; + +struct SelectionSnapshot +{ + // The normalized half-open range also covers any controls between its endpoints. + DocumentRange range {}; + SelectionDirection direction { SelectionDirection::Forward }; +}; + +struct HorizontalScroll +{ + BlockId block {}; + std::size_t columns { 0 }; +}; + +struct SearchSnapshot +{ + std::string query {}; + std::optional current_match {}; +}; + +// All positions and ranges belong to scope and draft_revision. +// Editing sessions and control values (including passwords) are not exported here. +struct ViewSnapshot +{ + DocumentScope scope {}; + DraftRevision draft_revision {}; + DisplayPosition cursor {}; + DisplayPosition viewport_anchor {}; + std::optional selection {}; + std::vector horizontal_scroll {}; + SearchSnapshot search {}; +}; + +} // namespace ricochet::tui diff --git a/ricochet/src/tui/document.cc b/ricochet/src/tui/document.cc new file mode 100644 index 0000000..335c6d6 --- /dev/null +++ b/ricochet/src/tui/document.cc @@ -0,0 +1,30 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "ricochet/tui/document.hh" + +#include + +namespace ricochet::tui { + +Document::Document( DocumentData data ) : data_( std::make_shared( std::move( data ) ) ) {} + +const DocumentData& Document::data() const noexcept +{ return *data_; } + +} // namespace ricochet::tui -- cgit v1.2.3 From b1c08a55448a6e363eddba88cbc58e61de630dc9 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Sat, 17 Oct 2026 03:37:11 +0800 Subject: feat(tui): add ncurses backend and session loop --- ricochet/include/ricochet/tui/input.hh | 119 +++++++ ricochet/include/ricochet/tui/session.hh | 110 ++++++ ricochet/src/CMakeLists.txt | 12 +- ricochet/src/tui/CMakeLists.txt | 8 + ricochet/src/tui/mailbox.cc | 93 +++++ ricochet/src/tui/mailbox.hh | 50 +++ ricochet/src/tui/screen.cc | 592 +++++++++++++++++++++++++++++++ ricochet/src/tui/screen.hh | 76 ++++ ricochet/src/tui/session.cc | 380 ++++++++++++++++++++ 9 files changed, 1437 insertions(+), 3 deletions(-) create mode 100644 ricochet/include/ricochet/tui/input.hh create mode 100644 ricochet/include/ricochet/tui/session.hh create mode 100644 ricochet/src/tui/CMakeLists.txt create mode 100644 ricochet/src/tui/mailbox.cc create mode 100644 ricochet/src/tui/mailbox.hh create mode 100644 ricochet/src/tui/screen.cc create mode 100644 ricochet/src/tui/screen.hh create mode 100644 ricochet/src/tui/session.cc (limited to 'ricochet/src/tui') diff --git a/ricochet/include/ricochet/tui/input.hh b/ricochet/include/ricochet/tui/input.hh new file mode 100644 index 0000000..df5b458 --- /dev/null +++ b/ricochet/include/ricochet/tui/input.hh @@ -0,0 +1,119 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include +#include + +namespace ricochet::tui { + +struct ScreenSize +{ + int rows { 0 }; + int columns { 0 }; + bool operator==( const ScreenSize& ) const = default; +}; + +struct CellPoint +{ + int row { 0 }; + int column { 0 }; +}; + +struct Modifiers +{ + bool shift { false }; + bool control { false }; + bool alt { false }; + bool operator==( const Modifiers& ) const = default; +}; + +enum class KeyCode : std::uint8_t +{ + Character, + Escape, + Enter, + Tab, + Backspace, + Delete, + Insert, + Left, + Right, + Up, + Down, + Home, + End, + PageUp, + PageDown, + Function, + Unsupported +}; + +struct Key +{ + KeyCode code { KeyCode::Unsupported }; + Modifiers modifiers {}; + char32_t character { 0 }; + unsigned int function { 0 }; +}; + +struct TextInput +{ char32_t character { 0 }; }; + +struct Paste +{ std::u32string text {}; }; + +struct MouseButtons +{ + bool left { false }; + bool middle { false }; + bool right { false }; +}; + +struct Mouse +{ + // Screen coordinates; the view router converts these to region-local coordinates. + CellPoint position {}; + Modifiers modifiers {}; + MouseButtons pressed {}; + MouseButtons released {}; + bool motion { false }; + int wheel_steps { 0 }; // Positive scrolls down. +}; + +struct Resize +{ ScreenSize size {}; }; + +struct Tick +{ std::chrono::steady_clock::time_point now {}; }; + +enum class TerminalCloseReason : std::uint8_t +{ + Disconnected, + TerminationSignal +}; + +struct TerminalClosed +{ TerminalCloseReason reason { TerminalCloseReason::Disconnected }; }; + +using InputEvent = std::variant; + +} // namespace ricochet::tui diff --git a/ricochet/include/ricochet/tui/session.hh b/ricochet/include/ricochet/tui/session.hh new file mode 100644 index 0000000..9968178 --- /dev/null +++ b/ricochet/include/ricochet/tui/session.hh @@ -0,0 +1,110 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/input.hh" +#include "ricochet/tui/messages.hh" + +#include +#include +#include +#include +#include +#include + +namespace ricochet::tui { + +namespace detail { +class Mailbox; +} + +struct TerminalOptions +{ + bool capture_mouse { true }; + // Explicit host opt-in: terminfo does not establish bracketed-paste support. + bool bracketed_paste { false }; + std::chrono::milliseconds escape_delay { 25 }; +}; + +struct TerminalCapabilities +{ + bool colors { false }; + bool mouse_buttons { false }; + bool mouse_motion { false }; + bool bracketed_paste { false }; +}; + +enum class PostResult : std::uint8_t +{ + Queued, + Closed +}; + +// A sender can outlive the UI session. Posting is thread-safe; it never calls curses. +class UpdateSender +{ +public: + PostResult post_update( HostUpdate update ) const; + +private: + friend class Session; + explicit UpdateSender( std::shared_ptr mailbox ); + std::shared_ptr mailbox_; +}; + +struct StepResult +{ + bool running { true }; + // Content editing/layout handlers are subsequent milestones. Until they exist, + // unsupported updates are returned intact rather than silently acknowledged. + std::vector unhandled_updates {}; + std::optional terminal_closed {}; + std::optional error {}; +}; + +class Session +{ +public: + explicit Session( TerminalOptions options = {} ); + // Streams must remain open until destruction. Construction, step, close and + // destruction run on the same UI thread; only one terminal session may exist. + Session( std::FILE& input, std::FILE& output, TerminalOptions options = {} ); + ~Session(); + + Session( const Session& ) = delete; + Session& operator=( const Session& ) = delete; + Session( Session&& ) = delete; + Session& operator=( Session&& ) = delete; + + UpdateSender sender() const; + PostResult post_update( HostUpdate update ); + // max_wait bounds idle waiting. Decoding a partial terminal key sequence can + // additionally wait for escape_delay; processing batches is bounded separately. + StepResult step( std::chrono::milliseconds max_wait ); + std::vector take_actions(); + std::optional snapshot( TabId tab ) const; + TerminalCapabilities capabilities() const; + void close() noexcept; + +private: + class Impl; + std::unique_ptr impl_; +}; + +} // namespace ricochet::tui diff --git a/ricochet/src/CMakeLists.txt b/ricochet/src/CMakeLists.txt index e46ac9a..fece630 100644 --- a/ricochet/src/CMakeLists.txt +++ b/ricochet/src/CMakeLists.txt @@ -1,13 +1,19 @@ -file(GLOB_RECURSE ALL_SOURCES CONFIGURE_DEPENDS "*.cc") +add_subdirectory(tui) + +file(GLOB_RECURSE CORE_SOURCES CONFIGURE_DEPENDS + "core/*.cc" + "net/*.cc" + "parser/*.cc" + "render/*.cc" +) set(MAIN_SRC "${CMAKE_CURRENT_SOURCE_DIR}/main.cc") -list(REMOVE_ITEM ALL_SOURCES ${MAIN_SRC}) find_package(OpenSSL REQUIRED) message(STATUS "Found OpenSSL Version: ${OPENSSL_VERSION}") message(STATUS "OpenSSL Include dir: ${OPENSSL_INCLUDE_DIR}") -add_library(ricochet_core STATIC ${ALL_SOURCES}) +add_library(ricochet_core STATIC ${CORE_SOURCES}) target_include_directories(ricochet_core PUBLIC ${PROJECT_SOURCE_DIR}/include) target_link_libraries(ricochet_core PUBLIC diff --git a/ricochet/src/tui/CMakeLists.txt b/ricochet/src/tui/CMakeLists.txt new file mode 100644 index 0000000..908448e --- /dev/null +++ b/ricochet/src/tui/CMakeLists.txt @@ -0,0 +1,8 @@ +find_package(PkgConfig REQUIRED) +pkg_check_modules(NCURSESW REQUIRED IMPORTED_TARGET ncursesw) +find_package(Threads REQUIRED) + +add_library(ricochet_tui STATIC document.cc mailbox.cc screen.cc session.cc) +target_include_directories(ricochet_tui PUBLIC ${PROJECT_SOURCE_DIR}/include) +target_compile_features(ricochet_tui PUBLIC cxx_std_23) +target_link_libraries(ricochet_tui PRIVATE PkgConfig::NCURSESW Threads::Threads) diff --git a/ricochet/src/tui/mailbox.cc b/ricochet/src/tui/mailbox.cc new file mode 100644 index 0000000..89e2c19 --- /dev/null +++ b/ricochet/src/tui/mailbox.cc @@ -0,0 +1,93 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "mailbox.hh" + +#include +#include +#include +#include +#include +#include + +namespace ricochet::tui::detail { + +Mailbox::Mailbox() : event_fd_( eventfd( 0, EFD_CLOEXEC | EFD_NONBLOCK ) ) +{ + if ( event_fd_ == -1 ) { + throw std::system_error( errno, std::generic_category(), "eventfd" ); + } +} + +Mailbox::~Mailbox() +{ ::close( event_fd_ ); } + +PostResult Mailbox::post( HostUpdate update ) +{ + const std::lock_guard lock( mutex_ ); + // Closing rejects later producers while existing sender handles remain alive. + if ( closed_ ) { + return PostResult::Closed; + } + updates_.push_back( std::move( update ) ); + int result; + do { + result = eventfd_write( event_fd_, 1 ); + } while ( result == -1 && errno == EINTR ); + // EAGAIN means the counter is already readable, so the loop is already awake. + if ( result == -1 && errno != EAGAIN ) { + const int error = errno; + updates_.pop_back(); + throw std::system_error( error, std::generic_category(), "eventfd_write" ); + } + return PostResult::Queued; +} + +std::vector Mailbox::take( std::size_t limit ) +{ + const std::lock_guard lock( mutex_ ); + eventfd_t counter {}; + int result; + do { + result = eventfd_read( event_fd_, &counter ); + } while ( result == -1 && errno == EINTR ); + // An empty queue has no wake token. Other read errors are transport failures. + if ( result == -1 && errno != EAGAIN ) { + throw std::system_error( errno, std::generic_category(), "eventfd_read" ); + } + const auto count = std::min( limit, updates_.size() ); + std::vector batch; + batch.reserve( count ); + for ( std::size_t i = 0; i < count; ++i ) { + batch.push_back( std::move( updates_.front() ) ); + updates_.pop_front(); + } + return batch; +} + +int Mailbox::descriptor() const noexcept +{ return event_fd_; } + +void Mailbox::close() noexcept +{ + const std::lock_guard lock( mutex_ ); + closed_ = true; + updates_.clear(); +} + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/mailbox.hh b/ricochet/src/tui/mailbox.hh new file mode 100644 index 0000000..099c5aa --- /dev/null +++ b/ricochet/src/tui/mailbox.hh @@ -0,0 +1,50 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/session.hh" + +#include +#include +#include +#include + +namespace ricochet::tui::detail { + +class Mailbox +{ +public: + Mailbox(); + ~Mailbox(); + Mailbox( const Mailbox& ) = delete; + Mailbox& operator=( const Mailbox& ) = delete; + + PostResult post( HostUpdate update ); + std::vector take( std::size_t limit ); + int descriptor() const noexcept; + void close() noexcept; + +private: + int event_fd_; + std::mutex mutex_ {}; + std::deque updates_ {}; + bool closed_ { false }; +}; + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/screen.cc b/ricochet/src/tui/screen.cc new file mode 100644 index 0000000..43582cd --- /dev/null +++ b/ricochet/src/tui/screen.cc @@ -0,0 +1,592 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "screen.hh" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ricochet::tui::detail { + +namespace { + +using Clock = std::chrono::steady_clock; +using namespace std::chrono_literals; + +std::mutex terminal_mutex; +// atomic_flag is guaranteed lock-free. Clear means pending; test_and_set consumes +// the signal without a read/reset race, including delivery on a worker thread. +std::atomic_flag interrupt_clear = ATOMIC_FLAG_INIT; +std::atomic_flag termination_clear = ATOMIC_FLAG_INIT; + +extern "C" void record_signal( int signal ) +{ + switch ( signal ) { + case SIGINT: + interrupt_clear.clear( std::memory_order_relaxed ); + break; + case SIGTERM: + case SIGHUP: + termination_clear.clear( std::memory_order_relaxed ); + break; + default: + break; + } +} + +std::unique_lock acquire_terminal() +{ + std::unique_lock lock( terminal_mutex, std::try_to_lock ); + // The non-reentrant ncurses build has process-global current-screen state. + if ( !lock.owns_lock() ) { + throw std::runtime_error( "A terminal session is already active" ); + } + return lock; +} + +class ThreadLocale +{ +public: + ThreadLocale() : locale_( newlocale( LC_CTYPE_MASK, "", nullptr ), freelocale ), previous_( nullptr ) + { + if ( !locale_ ) { + throw std::system_error( errno, std::generic_category(), "newlocale" ); + } + previous_ = uselocale( locale_.get() ); + if ( previous_ == nullptr ) { + throw std::system_error( errno, std::generic_category(), "uselocale" ); + } + } + + ~ThreadLocale() { uselocale( previous_ ); } + ThreadLocale( const ThreadLocale& ) = delete; + ThreadLocale& operator=( const ThreadLocale& ) = delete; + +private: + std::unique_ptr, decltype( &freelocale )> locale_; + locale_t previous_; +}; + +class Signals +{ +public: + Signals() + { + for ( std::size_t i = 0; i < numbers_.size(); ++i ) { + if ( sigaction( numbers_[i], nullptr, &previous_[i] ) == -1 ) { + throw std::system_error( errno, std::generic_category(), "Reading signal disposition" ); + } + } + } + + ~Signals() + { + for ( std::size_t i = 0; i < numbers_.size(); ++i ) { + sigaction( numbers_[i], &previous_[i], nullptr ); + } + } + + Signals( const Signals& ) = delete; + Signals& operator=( const Signals& ) = delete; + + void prepare() + { + interrupt_clear.test_and_set( std::memory_order_relaxed ); + termination_clear.test_and_set( std::memory_order_relaxed ); + struct sigaction action {}; + sigemptyset( &action.sa_mask ); + action.sa_handler = SIG_DFL; + // newterm owns SIGWINCH during the session; restore the host's handler later. + if ( sigaction( SIGWINCH, &action, nullptr ) == -1 ) { + throw std::system_error( errno, std::generic_category(), "Preparing resize signal disposition" ); + } + } + + void install() + { + for ( const auto number : numbers_ ) { + if ( number == SIGWINCH ) { + continue; // Keep the resize handler installed by newterm. + } + struct sigaction action {}; + sigemptyset( &action.sa_mask ); + switch ( number ) { + case SIGTSTP: + case SIGPIPE: + // No suspend support; output errors must reach the normal cleanup path. + action.sa_handler = SIG_IGN; + break; + default: + action.sa_handler = record_signal; + break; + } + if ( sigaction( number, &action, nullptr ) == -1 ) { + throw std::system_error( errno, std::generic_category(), "Installing signal disposition" ); + } + } + } + +private: + static constexpr std::array numbers_ { SIGINT, SIGTERM, SIGHUP, SIGTSTP, SIGWINCH, SIGPIPE }; + std::array previous_ {}; +}; + +struct ScreenDeleter +{ + std::FILE* output; + bool paste_enabled { false }; + + void operator()( SCREEN* screen ) const noexcept + { + // Only undo the extension this session enabled. The rest belongs to ncurses. + if ( paste_enabled ) { + std::fputs( "\x1b[?2004l", output ); + std::fflush( output ); + } + mousemask( 0, nullptr ); + endwin(); + delscreen( screen ); + } +}; + +Key character_key( char32_t character, Modifiers modifiers ) +{ return { .code = KeyCode::Character, .modifiers = modifiers, .character = character }; } + +InputEvent character_event( char32_t character ) +{ + // These aliases are indistinguishable in the traditional terminal encoding. + switch ( character ) { + case U'\r': + case U'\n': + return Key { .code = KeyCode::Enter }; + case U'\t': + return Key { .code = KeyCode::Tab }; + case U'\b': + case 127: + return Key { .code = KeyCode::Backspace }; + case 27: + return Key { .code = KeyCode::Escape }; + case 0: + return character_key( U' ', { .control = true } ); + case 28: + return character_key( U'\\', { .control = true } ); + case 29: + return character_key( U']', { .control = true } ); + case 30: + return character_key( U'^', { .control = true } ); + case 31: + return character_key( U'_', { .control = true } ); + default: + break; + } + // The remaining C0 letters encode Ctrl+A through Ctrl+Z. + if ( character >= 1 && character <= 26 ) { + return character_key( U'a' + character - 1, { .control = true } ); + } + return TextInput { character }; +} + +Mouse mouse_event( const MEVENT& mouse ) +{ + return { .position = { mouse.y, mouse.x }, + .modifiers = { ( mouse.bstate & BUTTON_SHIFT ) != 0, + ( mouse.bstate & BUTTON_CTRL ) != 0, + ( mouse.bstate & BUTTON_ALT ) != 0 }, + .pressed = { ( mouse.bstate & BUTTON1_PRESSED ) != 0, + ( mouse.bstate & BUTTON2_PRESSED ) != 0, + ( mouse.bstate & BUTTON3_PRESSED ) != 0 }, + .released = { ( mouse.bstate & BUTTON1_RELEASED ) != 0, + ( mouse.bstate & BUTTON2_RELEASED ) != 0, + ( mouse.bstate & BUTTON3_RELEASED ) != 0 }, + .motion = ( mouse.bstate & REPORT_MOUSE_POSITION ) != 0, + .wheel_steps = static_cast( ( mouse.bstate & BUTTON5_PRESSED ) != 0 ) + - static_cast( ( mouse.bstate & BUTTON4_PRESSED ) != 0 ) }; +} + +} // namespace + +class Screen::Impl +{ +public: + Impl( std::FILE& input, std::FILE& output, TerminalOptions options ) + : lock_( acquire_terminal() ) + , locale_() + , signals_() + , screen_( nullptr, ScreenDeleter { &output } ) + , input_fd_( fileno( &input ) ) + , options_( options ) + { + // This backend requires a terminal, not a pipe with EOF-looking input. + if ( isatty( input_fd_ ) != 1 || isatty( fileno( &output ) ) != 1 ) { + throw std::runtime_error( "The TUI requires terminal input and output" ); + } + if ( std::string_view( nl_langinfo( CODESET ) ) != "UTF-8" ) { + throw std::runtime_error( "The TUI requires a UTF-8 locale" ); + } + signals_.prepare(); + use_env( false ); + use_tioctl( true ); + screen_.reset( newterm( nullptr, &output, &input ) ); + // Unlike initscr, newterm reports failure without exiting the host process. + if ( !screen_ ) { + throw std::runtime_error( "ncurses newterm failed" ); + } + // ncurses documents application signal handlers being installed after newterm. + signals_.install(); + if ( raw() == ERR || noecho() == ERR || nonl() == ERR || meta( stdscr, true ) == ERR + || keypad( stdscr, true ) == ERR ) { + throw std::runtime_error( "ncurses input-mode setup failed" ); + } + const auto delay = std::min( options.escape_delay.count(), INT_MAX ); + if ( set_escdelay( static_cast( delay ) ) == ERR ) { + throw std::runtime_error( "ncurses rejected the escape delay" ); + } + options_.escape_delay = std::chrono::milliseconds( delay ); + wtimeout( stdscr, 0 ); + curs_set( 0 ); // ERR means cursor visibility cannot be changed on this terminal. + mouseinterval( 0 ); // Deliver press/release immediately; no click aggregation delay. + capabilities_.colors = has_colors() && start_color() != ERR; + if ( options.capture_mouse ) { + const auto mask = mousemask( ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION, nullptr ); + capabilities_.mouse_buttons = ( mask & BUTTON1_PRESSED ) != 0; + capabilities_.mouse_motion = ( mask & REPORT_MOUSE_POSITION ) != 0; + } + install_keys(); + if ( options.bracketed_paste ) { + if ( define_key( "\x1b[200~", paste_key_ ) == ERR ) { + throw std::runtime_error( "ncurses could not register the paste delimiter" ); + } + // Mark before writing so partial initialization also disables the extension. + screen_.get_deleter().paste_enabled = true; + if ( std::fputs( "\x1b[?2004h", &output ) == EOF || std::fflush( &output ) == EOF ) { + throw std::system_error( errno, std::generic_category(), "Enabling bracketed paste" ); + } + capabilities_.bracketed_paste = true; + } + } + + ScreenSize size() const { return { getmaxy( stdscr ), getmaxx( stdscr ) }; } + + void install_keys() + { + keys_ = { { KEY_ENTER, { .code = KeyCode::Enter } }, + { KEY_BACKSPACE, { .code = KeyCode::Backspace } }, + { KEY_BTAB, { .code = KeyCode::Tab, .modifiers = { .shift = true } } }, + { KEY_LEFT, { .code = KeyCode::Left } }, + { KEY_RIGHT, { .code = KeyCode::Right } }, + { KEY_UP, { .code = KeyCode::Up } }, + { KEY_DOWN, { .code = KeyCode::Down } }, + { KEY_HOME, { .code = KeyCode::Home } }, + { KEY_END, { .code = KeyCode::End } }, + { KEY_PPAGE, { .code = KeyCode::PageUp } }, + { KEY_NPAGE, { .code = KeyCode::PageDown } }, + { KEY_IC, { .code = KeyCode::Insert } }, + { KEY_DC, { .code = KeyCode::Delete } }, + { KEY_SLEFT, { .code = KeyCode::Left, .modifiers = { .shift = true } } }, + { KEY_SRIGHT, { .code = KeyCode::Right, .modifiers = { .shift = true } } }, + { KEY_SR, { .code = KeyCode::Up, .modifiers = { .shift = true } } }, + { KEY_SF, { .code = KeyCode::Down, .modifiers = { .shift = true } } }, + { KEY_SHOME, { .code = KeyCode::Home, .modifiers = { .shift = true } } }, + { KEY_SEND, { .code = KeyCode::End, .modifiers = { .shift = true } } } }; + for ( unsigned int n = 1; n <= 63; ++n ) { + keys_.emplace( KEY_F( n ), Key { .code = KeyCode::Function, .function = n } ); + } + const std::array extended { std::pair { "kLFT3", Key { .code = KeyCode::Left, .modifiers = { .alt = true } } }, + std::pair { "kRIT3", Key { .code = KeyCode::Right, .modifiers = { .alt = true } } }, + std::pair { "kUP3", Key { .code = KeyCode::Up, .modifiers = { .alt = true } } }, + std::pair { "kDN3", Key { .code = KeyCode::Down, .modifiers = { .alt = true } } } }; + int code = paste_key_ + 1; + for ( const auto& [name, key] : extended ) { + const char* sequence = tigetstr( name ); + // tigetstr distinguishes absent capabilities from a non-string capability. + if ( sequence == nullptr || sequence == reinterpret_cast( -1 ) ) { + continue; + } + if ( define_key( sequence, code ) == ERR ) { + throw std::runtime_error( "ncurses could not register an extended key" ); + } + keys_.emplace( code++, key ); + } + } + + void append_event( InputEvent event, std::vector& events ) + { + // Decoding a function key can itself consume the remaining Escape deadline. + if ( escape_deadline_ && Clock::now() >= *escape_deadline_ ) { + events.emplace_back( Key { .code = KeyCode::Escape } ); + escape_deadline_.reset(); + } + // An Escape prefix combines only with a key arriving inside its deadline. + if ( escape_deadline_ ) { + if ( auto* text = std::get_if( &event ) ) { + event = character_key( text->character, { .alt = true } ); + } else if ( auto* key = std::get_if( &event ); key != nullptr && key->code != KeyCode::Escape ) { + key->modifiers.alt = true; + } else { + events.emplace_back( Key { .code = KeyCode::Escape } ); + } + escape_deadline_.reset(); + } + if ( const auto* key = std::get_if( &event ); key != nullptr && key->code == KeyCode::Escape ) { + escape_deadline_ = Clock::now() + options_.escape_delay; + return; + } + events.push_back( std::move( event ) ); + } + + void append_character( char32_t character, std::vector& events ) + { + if ( paste_ ) { + paste_->push_back( character ); + constexpr std::u32string_view end = U"\x1b[201~"; + if ( paste_->ends_with( end ) ) { + paste_->resize( paste_->size() - end.size() ); + events.emplace_back( Paste { std::move( *paste_ ) } ); + paste_.reset(); + if ( keypad( stdscr, true ) == ERR ) { + throw std::runtime_error( "ncurses could not leave paste input mode" ); + } + } + } else { + append_event( character_event( character ), events ); + } + } + + void decode_byte( unsigned char byte, std::vector& events ) + { + // wget_wch keeps its conversion buffer local to one call; nodelay can split a + // character across calls. Retain the standard conversion state across steps. + // Evidence: ncurses/widechar/lib_get_wch.c, wget_wch's local count/buffer. + const bool had_partial = std::mbsinit( &text_state_ ) == 0; + const char input = static_cast( byte ); + wchar_t character {}; + const auto converted = std::mbrtowc( &character, &input, 1, &text_state_ ); + if ( converted == static_cast( -2 ) ) { + return; // The standard library needs continuation bytes, possibly next step. + } + if ( converted == static_cast( -1 ) ) { + text_state_ = {}; + append_character( U'\uFFFD', events ); + // Retry the offending byte as a new sequence so an ASCII character following + // an incomplete sequence is not lost. Reset state bounds this to one retry. + if ( had_partial ) { + decode_byte( byte, events ); + } + return; + } + append_character( static_cast( character ), events ); + } + + InputBatch read_events( std::size_t limit ) + { + InputBatch batch; + if ( !termination_clear.test_and_set( std::memory_order_relaxed ) ) { + batch.events.emplace_back( TerminalClosed { TerminalCloseReason::TerminationSignal } ); + return batch; + } + // Check disconnection even when continuous host updates prevent an idle wait. + if ( const auto closed = wait( -1, 0ms ) ) { + batch.events.emplace_back( *closed ); + return batch; + } + if ( !interrupt_clear.test_and_set( std::memory_order_relaxed ) ) { + batch.events.emplace_back( character_key( U'c', { .control = true } ) ); + escape_deadline_.reset(); + } + if ( escape_deadline_ && Clock::now() >= *escape_deadline_ ) { + batch.events.emplace_back( Key { .code = KeyCode::Escape } ); + escape_deadline_.reset(); + } + for ( std::size_t n = 0; n < limit; ++n ) { + errno = 0; + const int value = wgetch( stdscr ); + if ( value == ERR ) { + // nodelay has no byte available; signals may interrupt the ncurses reader. + if ( errno != 0 && errno != EAGAIN && errno != EINTR ) { + throw std::system_error( errno, std::generic_category(), "ncurses input" ); + } + break; + } + batch.consumed = true; + // wgetch returns bytes below KEY_MIN and decoded function keys above it. + if ( value >= KEY_MIN ) { + // Resize is out-of-band and can occur between UTF-8 continuation bytes. + // Other function keys interrupt an unfinished text sequence. + if ( value != KEY_RESIZE && std::mbsinit( &text_state_ ) == 0 ) { + text_state_ = {}; + append_character( U'\uFFFD', batch.events ); + } + switch ( value ) { + case KEY_RESIZE: + batch.events.emplace_back( Resize { size() } ); + break; + case KEY_MOUSE: { + MEVENT mouse {}; + if ( getmouse( &mouse ) == ERR ) { + throw std::runtime_error( "ncurses mouse event could not be read" ); + } + append_event( mouse_event( mouse ), batch.events ); + break; + } + case paste_key_: + // A preceding standalone Escape cannot become a modifier on pasted text. + if ( escape_deadline_ ) { + batch.events.emplace_back( Key { .code = KeyCode::Escape } ); + escape_deadline_.reset(); + } + paste_.emplace(); + // Preserve literal escape sequences inside pasted text. Only ncurses + // reads bytes; the backend recognizes the protocol's end delimiter. + if ( keypad( stdscr, false ) == ERR ) { + throw std::runtime_error( "ncurses could not enter paste input mode" ); + } + break; + default: { + const auto found = keys_.find( static_cast( value ) ); + if ( found != keys_.end() ) { + append_event( found->second, batch.events ); + } else { + append_event( Key { .code = KeyCode::Unsupported }, batch.events ); + } + break; + } + } + } else { + decode_byte( static_cast( value ), batch.events ); + } + } + return batch; + } + + std::optional wait( int wake_fd, std::chrono::milliseconds max_wait ) const + { + // The signal may arrive on a producer thread. This bound also lets wgetch + // observe ncurses' SIGWINCH flag when no terminal bytes have arrived. + auto delay = std::clamp( max_wait, 0ms, 50ms ); + if ( escape_deadline_ ) { + delay = std::min( + delay, std::max( 0ms, std::chrono::ceil( *escape_deadline_ - Clock::now() ) ) ); + } + std::array descriptors { pollfd { input_fd_, POLLIN, 0 }, pollfd { wake_fd, POLLIN, 0 } }; + const int result = poll( descriptors.data(), descriptors.size(), static_cast( delay.count() ) ); + if ( result == -1 && errno != EINTR ) { + throw std::system_error( errno, std::generic_category(), "poll" ); + } + if ( ( descriptors[0].revents & ( POLLHUP | POLLERR | POLLNVAL ) ) != 0 ) { + return TerminalClosed { TerminalCloseReason::Disconnected }; + } + if ( ( descriptors[1].revents & ( POLLHUP | POLLERR | POLLNVAL ) ) != 0 ) { + throw std::runtime_error( "The UI wake channel was disconnected" ); + } + return std::nullopt; + } + + void draw( const Frame& frame ) const + { + const auto dimensions = size(); + if ( werase( stdscr ) == ERR ) { + throw std::runtime_error( "ncurses could not clear its window buffer" ); + } + for ( const auto& glyph : frame.glyphs ) { + const auto [row, column] = glyph.position; + // A resize can clip a previously prepared frame. Never wrap clipped glyphs. + if ( row < 0 || row >= dimensions.rows || column < 0 || column >= dimensions.columns + || glyph.width > dimensions.columns - column ) { + continue; + } + // setcchar would silently truncate longer combining sequences. + if ( glyph.text.size() >= CCHARW_MAX ) { + throw std::runtime_error( "Glyph exceeds the ncurses complex-character capacity" ); + } + const attr_t attributes + = ( glyph.style.strong ? A_BOLD : A_NORMAL ) | ( glyph.style.emphasis ? A_UNDERLINE : A_NORMAL ) + | ( glyph.style.subdued ? A_DIM : A_NORMAL ) | ( glyph.style.warning ? A_REVERSE : A_NORMAL ); + cchar_t cell {}; + if ( setcchar( &cell, glyph.text.c_str(), attributes, 0, nullptr ) == ERR + || mvwadd_wchnstr( stdscr, row, column, &cell, 1 ) == ERR ) { + throw std::runtime_error( "ncurses could not paint a glyph" ); + } + } + // add_wchnstr does not advance or wrap the cursor at the bottom-right cell. + if ( frame.cursor && frame.cursor->row >= 0 && frame.cursor->row < dimensions.rows && frame.cursor->column >= 0 + && frame.cursor->column < dimensions.columns ) { + if ( wmove( stdscr, frame.cursor->row, frame.cursor->column ) == ERR ) { + throw std::runtime_error( "ncurses could not position the cursor" ); + } + curs_set( 1 ); + } else { + curs_set( 0 ); + } + if ( wnoutrefresh( stdscr ) == ERR || doupdate() == ERR ) { + throw std::runtime_error( "ncurses screen refresh failed" ); + } + } + + std::unique_lock lock_; + ThreadLocale locale_; + Signals signals_; + std::unique_ptr screen_; + int input_fd_; + TerminalOptions options_; + TerminalCapabilities capabilities_ {}; + std::map keys_ {}; + std::optional escape_deadline_ {}; + std::optional paste_ {}; + std::mbstate_t text_state_ {}; + static constexpr int paste_key_ = 0x10000; +}; + +Screen::Screen( std::FILE& input, std::FILE& output, TerminalOptions options ) + : impl_( std::make_unique( input, output, options ) ) +{} + +Screen::~Screen() = default; + +ScreenSize Screen::size() const +{ return impl_->size(); } + +TerminalCapabilities Screen::capabilities() const +{ return impl_->capabilities_; } + +InputBatch Screen::read_events( std::size_t limit ) +{ return impl_->read_events( limit ); } + +std::optional Screen::wait( int wake_fd, std::chrono::milliseconds max_wait ) +{ return impl_->wait( wake_fd, max_wait ); } + +void Screen::draw( const Frame& frame ) +{ impl_->draw( frame ); } + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/screen.hh b/ricochet/src/tui/screen.hh new file mode 100644 index 0000000..f0df278 --- /dev/null +++ b/ricochet/src/tui/screen.hh @@ -0,0 +1,76 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/document.hh" +#include "ricochet/tui/session.hh" + +#include +#include +#include +#include +#include +#include +#include + +namespace ricochet::tui::detail { + +// Layout supplies one printable spacing character and its combining marks per +// glyph, with a measured width. Raw document text never goes directly to curses. +struct PaintGlyph +{ + CellPoint position {}; + int width { 1 }; + std::wstring text {}; + TextStyle style {}; +}; + +struct Frame +{ + std::vector glyphs {}; + std::optional cursor {}; +}; + +struct InputBatch +{ + std::vector events {}; + bool consumed { false }; +}; + +class Screen +{ +public: + Screen( std::FILE& input, std::FILE& output, TerminalOptions options ); + ~Screen(); + Screen( const Screen& ) = delete; + Screen& operator=( const Screen& ) = delete; + + ScreenSize size() const; + TerminalCapabilities capabilities() const; + InputBatch read_events( std::size_t limit ); + // Wait only polls descriptors; wgetch remains the sole terminal reader. + std::optional wait( int wake_fd, std::chrono::milliseconds max_wait ); + void draw( const Frame& frame ); + +private: + class Impl; + std::unique_ptr impl_; +}; + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/session.cc b/ricochet/src/tui/session.cc new file mode 100644 index 0000000..38d501e --- /dev/null +++ b/ricochet/src/tui/session.cc @@ -0,0 +1,380 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "ricochet/tui/session.hh" + +#include "mailbox.hh" +#include "screen.hh" + +#include +#include +#include +#include +#include + +namespace ricochet::tui { + +namespace { + +struct TabState +{ + TabInfo info {}; + std::optional navigation {}; + std::optional document {}; + std::optional view {}; + std::optional failure {}; +}; + +// Only fixed ASCII chrome uses this helper. Document text goes through the +// forthcoming Unicode layout service, not a second ad-hoc text renderer. +void append_chrome( detail::Frame& frame, CellPoint start, std::wstring_view text, TextStyle style = {} ) +{ + int column = start.column; + for ( const wchar_t character : text ) { + frame.glyphs.push_back( + { .position = { start.row, column++ }, .text = std::wstring( 1, character ), .style = style } ); + } +} + +} // namespace + +class Session::Impl +{ +public: + Impl( std::FILE& input, std::FILE& output, TerminalOptions options ) + : mailbox_( std::make_shared() ) + , screen_( std::make_unique( input, output, options ) ) + , capabilities_( screen_->capabilities() ) + {} + + ~Impl() { close(); } + + void close() noexcept + { + mailbox_->close(); + screen_.reset(); + } + + void request_exit() + { + // A held key or repeated SIGINT must not create concurrent exit requests. + if ( exit_request_ ) { + return; + } + const RequestId request { next_request_++ }; + std::vector views; + for ( const auto id : tab_order_ ) { + const auto& tab = tabs_.at( id ); + if ( tab.view ) { + views.push_back( *tab.view ); + } + } + actions_.emplace_back( RequestExit { request, active_, std::move( views ) } ); + exit_request_ = request; + dirty_ = true; + } + + void apply( SyncTabs update, StepResult& ) + { + std::map retained; + std::vector order; + order.reserve( update.tabs.size() ); + for ( auto& info : update.tabs ) { + order.push_back( info.id ); + auto node = tabs_.extract( info.id ); + if ( node.empty() ) { + const auto id = info.id; + retained.emplace( id, TabState { .info = std::move( info ) } ); + } else { + node.mapped().info = std::move( info ); + retained.insert( std::move( node ) ); + } + } + tabs_ = std::move( retained ); + tab_order_ = std::move( order ); + active_ = update.active; + dirty_ = true; + } + + void apply( NavigationStarted update, StepResult& ) + { + const auto found = tabs_.find( update.tab ); + // Closed-tab results are stale; they must not recreate a tab. + if ( found == tabs_.end() ) { + return; + } + found->second.navigation = update.request; + found->second.info.loading_task = update.task; + found->second.failure.reset(); + dirty_ = true; + } + + void apply( CommitDocument update, StepResult& ) + { + const auto found = tabs_.find( update.tab ); + if ( found == tabs_.end() || found->second.navigation != update.navigation ) { + return; + } + auto& tab = found->second; + const auto version = update.document.data().version; + if ( tab.document && tab.document->data().version.document == version.document + && version.revision < tab.document->data().version.revision ) { + return; + } + const DocumentScope scope { update.tab, version }; + tab.view = ViewSnapshot { .scope = scope }; + // Initial drafts are revision zero. A history view referring to edited values + // cannot be restored without the corresponding draft snapshot/mapping. + if ( update.restore && update.restore->scope == scope && update.restore->draft_revision == DraftRevision {} ) { + tab.view = std::move( update.restore ); + } + tab.info.title = update.document.data().metadata.title; + tab.info.display_url = update.document.data().metadata.display_url; + tab.info.loading_task.reset(); + tab.document = std::move( update.document ); + tab.failure.reset(); + dirty_ = true; + } + + void apply( ActionFailed update, StepResult& ) + { + if ( !update.tab && exit_request_ == update.request ) { + exit_request_.reset(); + dirty_ = true; + return; + } + if ( !update.tab ) { + return; + } + const auto found = tabs_.find( *update.tab ); + if ( found == tabs_.end() || found->second.navigation != update.request ) { + return; + } + found->second.info.loading_task.reset(); + found->second.failure = std::move( update ); + dirty_ = true; + } + + void apply( ExitDecision update, StepResult& ) + { + if ( exit_request_ != update.request ) { + return; + } + exit_request_.reset(); + if ( update.approved ) { + close(); + } + dirty_ = true; + } + + // These messages require document-view/editor state, which this backend stage + // does not implement. Returning ownership keeps the incomplete boundary explicit. + void apply( UpdateDocument update, StepResult& result ) + { result.unhandled_updates.emplace_back( std::move( update ) ); } + + void apply( LocateView update, StepResult& result ) + { result.unhandled_updates.emplace_back( std::move( update ) ); } + + void apply( FormFeedback update, StepResult& result ) + { result.unhandled_updates.emplace_back( std::move( update ) ); } + + std::size_t receive( StepResult& result ) + { + // A finite batch prevents continuous producers from starving terminal input. + auto updates = mailbox_->take( 64 ); + const auto count = updates.size(); + for ( auto& update : updates ) { + std::visit( [this, &result]( auto message ) { apply( std::move( message ), result ); }, std::move( update ) ); + if ( !screen_ ) { + break; // An approved exit ends this batch before any further UI work. + } + } + return count; + } + + void dispatch( const InputEvent& event, StepResult& result ) + { + if ( const auto* closed = std::get_if( &event ) ) { + result.terminal_closed = *closed; + close(); + } else if ( std::holds_alternative( event ) ) { + dirty_ = true; + } else if ( std::holds_alternative( event ) ) { + // The baseline session is Browse: a paste never executes its text as keys. + notice_ = L"Enter an input field before pasting"; + dirty_ = true; + } else if ( const auto* text = std::get_if( &event ) ) { + if ( text->character == U'q' ) { + request_exit(); + } + } else if ( const auto* key = std::get_if( &event ) ) { + if ( key->code == KeyCode::Character && key->modifiers == Modifiers { .control = true } ) { + switch ( key->character ) { + case U'c': + request_exit(); + break; + case U'z': + notice_ = L"Suspend is unavailable"; + dirty_ = true; + break; + default: + break; + } + } + } + // Mouse/navigation/editor bindings belong to the upcoming document-view layer. + } + + bool read_input( StepResult& result ) + { + const auto batch = screen_->read_events( 64 ); + for ( const auto& event : batch.events ) { + dispatch( event, result ); + if ( !screen_ ) { + break; + } + } + return batch.consumed || !batch.events.empty(); + } + + void draw() + { + detail::Frame frame; + const auto dimensions = screen_->size(); + // With fewer than three rows, header/body/footer cannot coexist. + if ( dimensions.rows < 3 ) { + append_chrome( frame, { 0, 0 }, L"Resize | q quit" ); + } else { + append_chrome( frame, { 0, 0 }, L"Ricochet", { .strong = true } ); + std::wstring_view status = L"Browse | q quit"; + if ( !capabilities_.bracketed_paste ) { + status = L"Paste boundaries unavailable; multiline paste may confirm input | q quit"; + } + if ( !notice_.empty() ) { + status = notice_; + } + if ( active_ ) { + const auto found = tabs_.find( *active_ ); + if ( found != tabs_.end() ) { + if ( found->second.info.loading_task ) { + status = L"Loading | q quit"; + } + if ( found->second.failure ) { + status = L"Navigation failed | q quit"; + } + } + } + if ( exit_request_ ) { + status = L"Waiting for exit decision"; + } + append_chrome( frame, { dimensions.rows - 1, 0 }, status ); + } + screen_->draw( frame ); + dirty_ = false; + } + + StepResult step( std::chrono::milliseconds max_wait ) + { + StepResult result; + // Repeated step/close calls are part of the closed-session contract. + if ( !screen_ ) { + result.running = false; + return result; + } + try { + const auto received = receive( result ); + if ( screen_ ) { + const bool input = read_input( result ); + if ( screen_ && received == 0 && !input && !dirty_ ) { + const auto closed = screen_->wait( mailbox_->descriptor(), max_wait ); + if ( closed ) { + dispatch( *closed, result ); + } else { + receive( result ); + if ( screen_ ) { + read_input( result ); + } + } + } + } + if ( screen_ && dirty_ ) { + draw(); + } + } catch ( const std::exception& error ) { + // Restore the terminal before the host can print or present the failure. + close(); + result.error = error.what(); + } + result.running = screen_ != nullptr; + return result; + } + + std::shared_ptr mailbox_; + std::unique_ptr screen_; + TerminalCapabilities capabilities_; + std::map tabs_ {}; + std::vector tab_order_ {}; + std::optional active_ {}; + std::optional exit_request_ {}; + std::uint64_t next_request_ { 1 }; + std::vector actions_ {}; + std::wstring notice_ {}; + bool dirty_ { true }; +}; + +UpdateSender::UpdateSender( std::shared_ptr mailbox ) : mailbox_( std::move( mailbox ) ) {} + +PostResult UpdateSender::post_update( HostUpdate update ) const +{ return mailbox_->post( std::move( update ) ); } + +Session::Session( TerminalOptions options ) : Session( *stdin, *stdout, options ) {} + +Session::Session( std::FILE& input, std::FILE& output, TerminalOptions options ) + : impl_( std::make_unique( input, output, options ) ) +{} + +Session::~Session() = default; + +UpdateSender Session::sender() const +{ return UpdateSender( impl_->mailbox_ ); } + +PostResult Session::post_update( HostUpdate update ) +{ return impl_->mailbox_->post( std::move( update ) ); } + +StepResult Session::step( std::chrono::milliseconds max_wait ) +{ return impl_->step( max_wait ); } + +std::vector Session::take_actions() +{ return std::exchange( impl_->actions_, {} ); } + +std::optional Session::snapshot( TabId tab ) const +{ + const auto found = impl_->tabs_.find( tab ); + if ( found == impl_->tabs_.end() ) { + return std::nullopt; + } + return found->second.view; +} + +TerminalCapabilities Session::capabilities() const +{ return impl_->capabilities_; } + +void Session::close() noexcept +{ impl_->close(); } + +} // namespace ricochet::tui -- cgit v1.2.3 From b84c87ef820976cc541586a09ec6f845726580f2 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Sat, 17 Oct 2026 03:54:06 +0800 Subject: feat(tui): add Unicode text service and document layout --- ricochet/include/ricochet/tui/session.hh | 2 +- ricochet/src/tui/CMakeLists.txt | 6 +- ricochet/src/tui/layout.cc | 677 +++++++++++++++++++++++++++++++ ricochet/src/tui/layout.hh | 98 +++++ ricochet/src/tui/paint.hh | 46 +++ ricochet/src/tui/screen.cc | 3 + ricochet/src/tui/screen.hh | 20 +- ricochet/src/tui/session.cc | 29 +- ricochet/src/tui/text.cc | 138 +++++++ ricochet/src/tui/text.hh | 75 ++++ 10 files changed, 1072 insertions(+), 22 deletions(-) create mode 100644 ricochet/src/tui/layout.cc create mode 100644 ricochet/src/tui/layout.hh create mode 100644 ricochet/src/tui/paint.hh create mode 100644 ricochet/src/tui/text.cc create mode 100644 ricochet/src/tui/text.hh (limited to 'ricochet/src/tui') diff --git a/ricochet/include/ricochet/tui/session.hh b/ricochet/include/ricochet/tui/session.hh index 9968178..94cae68 100644 --- a/ricochet/include/ricochet/tui/session.hh +++ b/ricochet/include/ricochet/tui/session.hh @@ -71,7 +71,7 @@ private: struct StepResult { bool running { true }; - // Content editing/layout handlers are subsequent milestones. Until they exist, + // Incremental document updates and editing are subsequent milestones. Until then, // unsupported updates are returned intact rather than silently acknowledged. std::vector unhandled_updates {}; std::optional terminal_closed {}; diff --git a/ricochet/src/tui/CMakeLists.txt b/ricochet/src/tui/CMakeLists.txt index 908448e..8b49cf1 100644 --- a/ricochet/src/tui/CMakeLists.txt +++ b/ricochet/src/tui/CMakeLists.txt @@ -1,8 +1,10 @@ find_package(PkgConfig REQUIRED) pkg_check_modules(NCURSESW REQUIRED IMPORTED_TARGET ncursesw) find_package(Threads REQUIRED) +# ICU 76.1 supplies UTF-8 grapheme/line boundaries and Unicode properties. +pkg_check_modules(ICU REQUIRED IMPORTED_TARGET icu-uc>=76.1 icu-i18n>=76.1) -add_library(ricochet_tui STATIC document.cc mailbox.cc screen.cc session.cc) +add_library(ricochet_tui STATIC document.cc mailbox.cc screen.cc session.cc text.cc layout.cc) target_include_directories(ricochet_tui PUBLIC ${PROJECT_SOURCE_DIR}/include) target_compile_features(ricochet_tui PUBLIC cxx_std_23) -target_link_libraries(ricochet_tui PRIVATE PkgConfig::NCURSESW Threads::Threads) +target_link_libraries(ricochet_tui PRIVATE PkgConfig::NCURSESW PkgConfig::ICU Threads::Threads) diff --git a/ricochet/src/tui/layout.cc b/ricochet/src/tui/layout.cc new file mode 100644 index 0000000..5aebe17 --- /dev/null +++ b/ricochet/src/tui/layout.cc @@ -0,0 +1,677 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "layout.hh" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ricochet::tui::detail { +namespace { + +constexpr int tab_columns = 8; +constexpr std::int64_t cell_gap = 3; +constexpr std::int64_t minimum_cell_columns = 4; + +TextStyle overlay( TextStyle base, TextStyle extra ) +{ + return { base.emphasis || extra.emphasis, + base.strong || extra.strong, + base.code || extra.code, + base.subdued || extra.subdued, + base.warning || extra.warning }; +} + +struct Atom +{ + Grapheme glyph {}; + DocumentRange source {}; + TextStyle style {}; + std::optional target {}; + bool decoration { false }; +}; + +struct TextSpan +{ + const Text* leaf; + ByteRange bytes; +}; + +DocumentPoint text_point( std::span spans, std::size_t offset, bool end ) +{ + for ( const auto& span : spans ) { + // At an inline seam an end belongs to the preceding leaf, a start to the next. + if ( offset < span.bytes.end || ( end && offset == span.bytes.end ) ) { + return TextPosition { span.leaf->id, offset - span.bytes.start }; + } + } + const auto& last = spans.back(); + return TextPosition { last.leaf->id, last.leaf->utf8.size() }; +} + +LayoutGlyph anchor( DocumentPoint point, LayoutPoint location, std::int64_t width ) +{ return { .position = location, .source = { point, point }, .clip_right = width }; } + +void append_box( LayoutData& destination, LayoutData source, std::size_t row, std::int64_t column ) +{ + destination.rows = std::max( destination.rows, row + source.rows ); + destination.extent = std::max( destination.extent, column + source.extent ); + for ( auto& glyph : source.glyphs ) { + glyph.position.row += row; + glyph.position.column += column; + glyph.line_start += column; + glyph.clip_left += column; + glyph.clip_right += column; + destination.glyphs.push_back( std::move( glyph ) ); + } +} + +class LayoutBuilder +{ +public: + LayoutBuilder( const DocumentData& document, const TextService& text, std::span scrolls ) + : document_( document ), text_( text ), scrolls_( scrolls ) + { + for ( const auto& control : document.controls ) { + controls_.emplace( control.id, &control ); + } + } + + LayoutData blocks( std::span content, std::int64_t width, TextStyle style = {} ) const + { + LayoutData result; + std::size_t row = 0; + for ( const auto& block : content ) { + auto box = block_box( block, width, style ); + const auto height = box.rows; + append_box( result, std::move( box ), row, 0 ); + row += height; + } + return result; + } + +private: + void text_run( std::vector& atoms, + std::span spans, + const std::string& utf8, + bool tabs, + TextStyle base ) const + { + const auto analysis = text_.analyze( utf8, true, tabs ); + for ( const auto& glyph : analysis.graphemes ) { + Atom atom { .glyph = glyph, + .source + = { text_point( spans, glyph.bytes.start, false ), text_point( spans, glyph.bytes.end, true ) }, + .style = base }; + for ( const auto& span : spans ) { + // Only source portions intersecting this grapheme can contribute style/link. + if ( span.bytes.start >= glyph.bytes.end || span.bytes.end <= glyph.bytes.start ) { + continue; + } + const ByteRange local { std::max( span.bytes.start, glyph.bytes.start ) - span.bytes.start, + std::min( span.bytes.end, glyph.bytes.end ) - span.bytes.start }; + for ( const auto& styled : span.leaf->styles ) { + if ( styled.bytes.start < local.end && local.start < styled.bytes.end ) { + atom.style = overlay( atom.style, styled.style ); + } + } + for ( const auto& link : document_.links ) { + for ( const auto& range : link.ranges ) { + if ( range.block == span.leaf->id && range.bytes.start < local.end && local.start < range.bytes.end ) { + const HitTarget target = link.id; + // One grapheme cannot activate two links, including across leaf seams. + if ( atom.target && atom.target != target ) { + throw std::invalid_argument( "Overlapping links address the same grapheme" ); + } + atom.target = target; + atom.style.emphasis = true; + } + } + } + } + atoms.push_back( std::move( atom ) ); + } + // Empty text still has a real byte boundary; no fabricated display character. + if ( utf8.empty() ) { + const auto point = text_point( spans, 0, false ); + atoms.push_back( { .glyph = { .columns = 0 }, .source = { point, point }, .style = base } ); + } + } + + std::string control_text( const Control& control ) const + { + return std::visit( + [this, &control]( const auto& value ) -> std::string { + using Value = std::decay_t; + if constexpr ( std::is_same_v ) { + if ( value.kind == TextControlKind::Password ) { + return std::string( text_.analyze( value.value, true, false ).graphemes.size(), '*' ); + } + return value.value; + } else if constexpr ( std::is_same_v || std::is_same_v ) { + return control.label; + } else if constexpr ( std::is_same_v ) { + std::string result; + for ( const auto& option : value.options ) { + if ( std::ranges::find( value.selected, option.id ) != value.selected.end() ) { + if ( !result.empty() ) { + result += ", "; + } + result += option.label; + } + } + return result; + } else if constexpr ( std::is_same_v ) { + return control.label; + } else { + return value.description; + } + }, + control.content ); + } + + void control_atoms( std::vector& atoms, ControlId id, TextStyle base ) const + { + // A missing ID is a malformed document reference; map::at reports it directly. + const auto& control = *controls_.at( id ); + const auto* input = std::get_if( &control.content ); + const bool multiline = input && input->kind == TextControlKind::MultiLine; + const auto before = ObjectPosition { id, BoundarySide::Before }; + const auto after = ObjectPosition { id, BoundarySide::After }; + const auto style = overlay( base, { .subdued = control.disabled, .warning = control.error.has_value() } ); + std::wstring_view opening = L"["; + std::wstring_view closing = L"]"; + if ( const auto* checkbox = std::get_if( &control.content ) ) { + opening = checkbox->checked ? L"[x] " : L"[ ] "; + closing = L""; + } else if ( const auto* radio = std::get_if( &control.content ) ) { + opening = radio->checked ? L"(*) " : L"( ) "; + closing = L""; + } + for ( const auto character : opening ) { + atoms.push_back( { .glyph = { .display = std::wstring( 1, character ) }, + .source = { before, before }, + .style = style, + .target = id } ); + } + const auto display = control_text( control ); + const auto analysis = text_.analyze( display, multiline, false ); + for ( const auto& glyph : analysis.graphemes ) { + atoms.push_back( { .glyph = glyph, + .source = { ControlTextPosition { id, {}, glyph.bytes.start }, + ControlTextPosition { id, {}, glyph.bytes.end } }, + .style = style, + .target = id } ); + } + if ( display.empty() ) { + const auto point = ControlTextPosition { id, {}, 0 }; + atoms.push_back( { .glyph = { .display = L" " }, .source = { point, point }, .style = style, .target = id } ); + } + for ( const auto character : closing ) { + atoms.push_back( { .glyph = { .display = std::wstring( 1, character ), .break_after = true }, + .source = { after, after }, + .style = style, + .target = id } ); + } + // Checkbox/radio controls have no closing bracket but still have an after boundary. + atoms.push_back( { .glyph = { .columns = 0, .break_after = true }, + .source = { after, after }, + .style = style, + .target = id } ); + } + + std::vector inline_atoms( std::span content, TextStyle style ) const + { + std::vector result; + std::vector spans; + std::string utf8; + const auto flush = [&] { + if ( !spans.empty() ) { + text_run( result, spans, utf8, false, style ); + spans.clear(); + utf8.clear(); + } + }; + for ( const auto& item : content ) { + if ( const auto* text = std::get_if( &item ) ) { + const auto start = utf8.size(); + utf8 += text->utf8; + spans.push_back( { text, { start, utf8.size() } } ); + } else { + flush(); + control_atoms( result, std::get( item ).control, style ); + } + } + flush(); + return result; + } + + LayoutData flow( std::span atoms, std::int64_t width, bool wrap ) const + { + LayoutData result; + std::size_t start = 0; + std::size_t row = 0; + while ( start < atoms.size() ) { + std::size_t end = start; + std::size_t opportunity = start; + std::int64_t column = 0; + while ( end < atoms.size() && atoms[end].glyph.kind != TextUnitKind::LineBreak ) { + const auto& glyph = atoms[end].glyph; + const int cells = glyph.kind == TextUnitKind::Tab ? tab_columns - column % tab_columns : glyph.columns; + if ( wrap && column + cells > width && end > start ) { + break; + } + column += cells; + ++end; + if ( glyph.break_after ) { + opportunity = end; + } + } + // Prefer a Unicode line boundary; an overlong word breaks at a grapheme. + if ( end < atoms.size() && atoms[end].glyph.kind != TextUnitKind::LineBreak && opportunity > start ) { + end = opportunity; + } + column = 0; + for ( auto index = start; index < end; ++index ) { + const auto& atom = atoms[index]; + const bool tab = atom.glyph.kind == TextUnitKind::Tab; + const int cells = tab ? tab_columns - column % tab_columns : atom.glyph.columns; + result.glyphs.push_back( { .position = { row, column }, + .columns = cells, + .text = atom.glyph.display, + .style = atom.style, + .source = atom.source, + .target = atom.target, + .clip_right = wrap ? width : std::numeric_limits::max(), + .decoration = atom.decoration, + .fill = tab } ); + column += cells; + } + result.extent = std::max( result.extent, column ); + if ( end < atoms.size() && atoms[end].glyph.kind == TextUnitKind::LineBreak ) { + const auto& atom = atoms[end++]; + result.glyphs.push_back( { .position = { row, column }, + .source = atom.source, + .target = atom.target, + .clip_right = width, + .line_break = true } ); + // The endpoint of a hard LF belongs to the next line, including a + // trailing empty line; it must also be reachable by hit testing. + auto boundary = anchor( atom.source.end, { row + 1, 0 }, width ); + boundary.target = atom.target; + result.glyphs.push_back( std::move( boundary ) ); + result.rows = row + 2; + } else { + result.rows = row + 1; + } + start = end; + ++row; + } + return result; + } + + void horizontal( LayoutData& box, BlockId block, std::int64_t width ) const + { + const auto scroll = std::ranges::find( scrolls_, block, &HorizontalScroll::block ); + const auto requested = scroll == scrolls_.end() ? 0 : scroll->columns; + const auto maximum = std::max( 0, box.extent - width ); + const auto shift = static_cast( std::min( requested, maximum ) ); + for ( auto& glyph : box.glyphs ) { + glyph.position.column -= shift; + glyph.line_start -= shift; + glyph.clip_left = std::max( 0, glyph.clip_left - shift ); + glyph.clip_right = std::min( width, glyph.clip_right - shift ); + } + } + + LayoutData list_box( const List& list, std::int64_t width, TextStyle style ) const + { + LayoutData result; + std::size_t row = 0; + auto number = list.first_number; + for ( const auto& item : list.items ) { + const auto marker + = item.marker.value_or( list.kind == ListKind::Ordered ? std::to_string( number ) + "." : "-" ); + const auto analysis = text_.analyze( marker, false, false ); + const auto marker_width + = std::accumulate( analysis.graphemes.begin(), + analysis.graphemes.end(), + std::int64_t { 0 }, + []( auto total, const auto& glyph ) { return total + glyph.columns; } ); + // Deep nesting must leave at least one body cell; clipped markers stay decoration. + const auto indent = std::min( marker_width + 1, width - 1 ); + auto body = blocks( item.content, width - indent, style ); + const auto height = body.rows; + append_box( result, std::move( body ), row, indent ); + std::int64_t column = 0; + for ( const auto& glyph : analysis.graphemes ) { + result.glyphs.push_back( { .position = { row, column }, + .columns = glyph.columns, + .text = glyph.display, + .style = style, + .clip_right = indent, + .decoration = true } ); + column += glyph.columns; + } + row += height; + // Ordered counters can start at the model's largest int64 value. + if ( number < std::numeric_limits::max() ) { + ++number; + } + } + return result; + } + + LayoutData table_box( const Table& table, BlockId id, std::int64_t width, TextStyle style ) const + { + if ( table.columns == 0 ) { + return {}; + } + std::vector widths( table.columns, 1 ); + std::vector desired( table.columns, 1 ); + for ( std::size_t row = 0; row < table.rows.size(); ++row ) { + for ( const auto& cell : table.rows[row].cells ) { + // Spans index the supplied grid. Reject zero/out-of-grid spans before indexing. + if ( cell.column >= table.columns || cell.column_span == 0 || cell.row_span == 0 + || cell.column_span > table.columns - cell.column || cell.row_span > table.rows.size() - row ) { + throw std::invalid_argument( "Table cell span lies outside its resolved grid" ); + } + const auto measure = blocks( cell.content, width, style ); + const auto span = static_cast( cell.column_span ); + const auto preferred = std::max( 1, ( measure.extent + span - 1 ) / span ); + for ( auto column = cell.column; column < cell.column + cell.column_span; ++column ) { + desired[column] = std::max( desired[column], preferred ); + widths[column] = std::max( widths[column], std::min( preferred, minimum_cell_columns ) ); + } + } + } + const auto gaps = cell_gap * static_cast( table.columns - 1 ); + auto remaining = width - gaps - std::accumulate( widths.begin(), widths.end(), std::int64_t { 0 } ); + // Grow content-bearing columns toward their preferred width, within the viewport. + while ( remaining > 0 ) { + bool grew = false; + for ( std::size_t column = 0; column < widths.size() && remaining > 0; ++column ) { + if ( widths[column] < desired[column] ) { + ++widths[column]; + --remaining; + grew = true; + } + } + if ( !grew ) { + break; + } + } + struct CellBox + { + const TableCell* cell; + std::size_t row; + LayoutData box; + }; + std::vector cells; + std::vector heights( table.rows.size(), 1 ); + for ( std::size_t row = 0; row < table.rows.size(); ++row ) { + for ( const auto& cell : table.rows[row].cells ) { + const auto first = widths.begin() + static_cast( cell.column ); + const auto last = first + static_cast( cell.column_span ); + const auto cell_width = std::accumulate( first, last, std::int64_t { 0 } ) + + cell_gap * static_cast( cell.column_span - 1 ); + auto box = blocks( cell.content, cell_width, overlay( style, { .strong = cell.header } ) ); + const auto begin = heights.begin() + static_cast( row ); + const auto end = begin + static_cast( cell.row_span ); + const auto height = std::accumulate( begin, end, std::size_t { 0 } ); + if ( box.rows > height ) { + heights[row + cell.row_span - 1] += box.rows - height; + } + cells.push_back( { &cell, row, std::move( box ) } ); + } + } + std::vector row_offsets( heights.size() + 1, 0 ); + std::partial_sum( heights.begin(), heights.end(), row_offsets.begin() + 1 ); + std::vector column_offsets( widths.size(), 0 ); + for ( std::size_t column = 1; column < widths.size(); ++column ) { + column_offsets[column] = column_offsets[column - 1] + widths[column - 1] + cell_gap; + } + LayoutData result; + result.extent = std::accumulate( widths.begin(), widths.end(), gaps ); + result.rows = std::max( 1, row_offsets.back() ); + for ( auto& cell : cells ) { + const auto column = column_offsets[cell.cell->column]; + append_box( result, std::move( cell.box ), row_offsets[cell.row], column ); + if ( cell.cell->column != 0 ) { + for ( auto row = row_offsets[cell.row]; row < row_offsets[cell.row + cell.cell->row_span]; ++row ) { + result.glyphs.push_back( { .position = { row, column - 2 }, + .columns = 1, + .text = L"|", + .style = { .subdued = true }, + .clip_right = result.extent, + .decoration = true } ); + } + } + } + // A nested preformatted block scrolls inside its cell; its natural extent + // must not enlarge the enclosing table's horizontal scroll range. + result.extent = std::accumulate( widths.begin(), widths.end(), gaps ); + horizontal( result, id, width ); + return result; + } + + LayoutData block_box( const Block& block, std::int64_t width, TextStyle style ) const + { + auto result = std::visit( + [this, &block, width, style]( const auto& value ) -> LayoutData { + using Value = std::decay_t; + if constexpr ( std::is_same_v ) { + return flow( inline_atoms( value.content, style ), width, true ); + } else if constexpr ( std::is_same_v ) { + return flow( inline_atoms( value.content, overlay( style, { .strong = true } ) ), width, true ); + } else if constexpr ( std::is_same_v || std::is_same_v ) { + const Text& leaf = [&]() -> const Text& { + if constexpr ( std::is_same_v ) { + return value.content; + } else { + return value.description; + } + }(); + const TextSpan span { &leaf, { 0, leaf.utf8.size() } }; + std::vector atoms; + constexpr bool preformatted = std::is_same_v; + text_run( + atoms, std::span( &span, 1 ), leaf.utf8, preformatted, overlay( style, { .code = preformatted } ) ); + auto box = flow( atoms, width, !preformatted ); + if constexpr ( preformatted ) { + horizontal( box, block.id, width ); + } + return box; + } else if constexpr ( std::is_same_v ) { + return list_box( value, width, style ); + } else if constexpr ( std::is_same_v ) { + return table_box( value, block.id, width, style ); + } else if constexpr ( std::is_same_v ) { + std::vector atoms; + control_atoms( atoms, value.control, style ); + return flow( atoms, width, true ); + } else { + LayoutData box; + box.extent = width; + for ( std::int64_t column = 0; column < width; ++column ) { + box.glyphs.push_back( { .position = { 0, column }, + .columns = 1, + .text = L"-", + .style = { .subdued = true }, + .clip_right = width, + .decoration = true } ); + } + return box; + } + }, + block.content ); + const bool has_text + = std::ranges::any_of( result.glyphs, []( const auto& glyph ) { return !glyph.decoration; } ); + auto before = anchor( ObjectPosition { block.id, BoundarySide::Before }, {}, width ); + auto after = anchor( ObjectPosition { block.id, BoundarySide::After }, + { result.rows - 1, std::min( result.extent, width ) }, + width ); + before.boundary_only = has_text; + after.boundary_only = has_text; + result.glyphs.push_back( std::move( before ) ); + result.glyphs.push_back( std::move( after ) ); + return result; + } + + const DocumentData& document_; + const TextService& text_; + std::span scrolls_; + std::map controls_ {}; +}; + +LayoutPoint end_point( const LayoutGlyph& glyph ) +{ + // Object decorations and empty fields do not create a second text boundary. + if ( glyph.source.start == glyph.source.end ) { + return glyph.position; + } + if ( glyph.line_break ) { + return { glyph.position.row + 1, glyph.line_start }; + } + return { glyph.position.row, glyph.position.column + glyph.columns }; +} + +} // namespace + +DocumentLayout::DocumentLayout( const Document& document, + const TextService& text, + int columns, + std::span scrolls ) + : columns_( std::max( 1, columns ) ) + , data_( LayoutBuilder( document.data(), text, scrolls ).blocks( document.data().blocks, columns_ ) ) +{ + // An empty document still has a location for its cursor/viewport anchor. + if ( data_.glyphs.empty() ) { + data_.glyphs.push_back( anchor( DocumentStart {}, {}, columns_ ) ); + } +} + +int DocumentLayout::columns() const +{ return columns_; } +std::size_t DocumentLayout::rows() const +{ return data_.rows; } + +std::optional DocumentLayout::locate( const DisplayPosition& position ) const +{ + if ( std::holds_alternative( position.point ) ) { + return LayoutPoint {}; + } + std::optional fallback; + for ( const auto& glyph : data_.glyphs ) { + if ( glyph.decoration ) { + continue; + } + if ( position.point == glyph.source.start ) { + if ( position.affinity == WrapAffinity::NextLine ) { + return glyph.position; + } + fallback = glyph.position; + } + if ( position.point == glyph.source.end ) { + if ( position.affinity == WrapAffinity::PreviousLine ) { + return end_point( glyph ); + } + fallback = end_point( glyph ); + } + } + return fallback; +} + +std::optional DocumentLayout::hit( LayoutPoint point ) const +{ + const LayoutGlyph* nearest = nullptr; + auto distance + = std::tuple { std::numeric_limits::max(), std::numeric_limits::max(), true }; + for ( const auto& glyph : data_.glyphs ) { + // Decorations and partially clipped wide glyphs have no independent text hit. + if ( glyph.decoration || glyph.boundary_only ) { + continue; + } + const auto left = std::max( glyph.position.column, glyph.clip_left ); + const auto edge = std::min( glyph.position.column + glyph.columns, glyph.clip_right ); + // Tab blanks may be clipped individually; a wide glyph remains indivisible. + if ( ( glyph.fill && left >= edge ) + || ( !glyph.fill + && ( glyph.position.column < glyph.clip_left + || glyph.position.column + glyph.columns > glyph.clip_right ) ) ) { + continue; + } + const auto row_distance + = glyph.position.row > point.row ? glyph.position.row - point.row : point.row - glyph.position.row; + const auto right = std::max( left, edge - 1 ); + const auto column_distance = std::max( { left - point.column, point.column - right, std::int64_t { 0 } } ); + const auto candidate = std::tuple { row_distance, column_distance, glyph.columns == 0 }; + if ( candidate < distance ) { + nearest = &glyph; + distance = candidate; + } + } + if ( !nearest ) { + return std::nullopt; + } + const bool after = !nearest->line_break && point.column >= nearest->position.column + nearest->columns; + return LayoutHit { .position = { after ? nearest->source.end : nearest->source.start, + after ? WrapAffinity::PreviousLine : WrapAffinity::NextLine }, + .unit = nearest->source, + .target = nearest->target }; +} + +void DocumentLayout::append_frame( Frame& frame, + std::size_t first_row, + CellPoint origin, + ScreenSize viewport ) const +{ + for ( const auto& glyph : data_.glyphs ) { + if ( glyph.text.empty() || glyph.position.row < first_row + || glyph.position.row - first_row >= static_cast( std::max( 0, viewport.rows ) ) ) { + continue; + } + const auto left = std::max( 0, glyph.clip_left ); + const auto right = std::min( viewport.columns, glyph.clip_right ); + const auto row = origin.row + static_cast( glyph.position.row - first_row ); + if ( glyph.fill ) { + // Expanded tabs are many blank cells but keep a single source range/hit unit. + for ( auto column = std::max( left, glyph.position.column ); + column < std::min( right, glyph.position.column + glyph.columns ); + ++column ) { + frame.glyphs.push_back( + { .position = { row, origin.column + static_cast( column ) }, .text = L" ", .style = glyph.style } ); + } + } else if ( glyph.position.column >= left && glyph.position.column + glyph.columns <= right ) { + frame.glyphs.push_back( { .position = { row, origin.column + static_cast( glyph.position.column ) }, + .width = glyph.columns, + .text = glyph.text, + .style = glyph.style } ); + } + } +} + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/layout.hh b/ricochet/src/tui/layout.hh new file mode 100644 index 0000000..5feb0cd --- /dev/null +++ b/ricochet/src/tui/layout.hh @@ -0,0 +1,98 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "paint.hh" +#include "ricochet/tui/view.hh" +#include "text.hh" + +#include +#include +#include +#include +#include +#include + +namespace ricochet::tui::detail { + +using HitTarget = std::variant; + +struct LayoutPoint +{ + std::size_t row { 0 }; + std::int64_t column { 0 }; +}; + +struct LayoutHit +{ + DisplayPosition position {}; + DocumentRange unit {}; + std::optional target {}; +}; + +struct LayoutGlyph +{ + LayoutPoint position {}; + int columns { 0 }; + std::wstring text {}; + TextStyle style {}; + DocumentRange source {}; + std::optional target {}; + // Clip bounds are in document-layout columns and also constrain hit testing. + std::int64_t clip_left { 0 }; + std::int64_t clip_right { 0 }; + // Structural boundaries locate anchors but do not displace nearby text hits. + bool boundary_only { false }; + std::int64_t line_start { 0 }; + bool decoration { false }; + bool line_break { false }; + bool fill { false }; +}; + +struct LayoutData +{ + // Reading order, including table cells in row/cell order; not screen order. + std::vector glyphs {}; + std::size_t rows { 1 }; + std::int64_t extent { 0 }; +}; + +// A derived snapshot for one Document + initial control values + width/scrolls. +// Editing will supply a separate draft snapshot; this stage uses revision zero. +// No ncurses headers, terminal objects or business-module dependencies. +class DocumentLayout +{ +public: + DocumentLayout( const Document& document, + const TextService& text, + int columns, + std::span scrolls ); + + int columns() const; + std::size_t rows() const; + std::optional locate( const DisplayPosition& position ) const; + std::optional hit( LayoutPoint point ) const; + void append_frame( Frame& frame, std::size_t first_row, CellPoint origin, ScreenSize viewport ) const; + +private: + int columns_; + LayoutData data_; +}; + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/paint.hh b/ricochet/src/tui/paint.hh new file mode 100644 index 0000000..549718d --- /dev/null +++ b/ricochet/src/tui/paint.hh @@ -0,0 +1,46 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/document.hh" +#include "ricochet/tui/input.hh" + +#include +#include +#include + +namespace ricochet::tui::detail { + +// Layout supplies one printable spacing character and its combining marks per +// glyph, with a measured width. Raw document text never goes directly to curses. +struct PaintGlyph +{ + CellPoint position {}; + int width { 1 }; + std::wstring text {}; + TextStyle style {}; +}; + +struct Frame +{ + std::vector glyphs {}; + std::optional cursor {}; +}; + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/screen.cc b/ricochet/src/tui/screen.cc index 43582cd..34a8542 100644 --- a/ricochet/src/tui/screen.cc +++ b/ricochet/src/tui/screen.cc @@ -574,6 +574,9 @@ Screen::Screen( std::FILE& input, std::FILE& output, TerminalOptions options ) Screen::~Screen() = default; +std::size_t Screen::glyph_capacity() +{ return CCHARW_MAX - 1; } + ScreenSize Screen::size() const { return impl_->size(); } diff --git a/ricochet/src/tui/screen.hh b/ricochet/src/tui/screen.hh index f0df278..9677eb0 100644 --- a/ricochet/src/tui/screen.hh +++ b/ricochet/src/tui/screen.hh @@ -18,7 +18,7 @@ #pragma once -#include "ricochet/tui/document.hh" +#include "paint.hh" #include "ricochet/tui/session.hh" #include @@ -26,27 +26,10 @@ #include #include #include -#include #include namespace ricochet::tui::detail { -// Layout supplies one printable spacing character and its combining marks per -// glyph, with a measured width. Raw document text never goes directly to curses. -struct PaintGlyph -{ - CellPoint position {}; - int width { 1 }; - std::wstring text {}; - TextStyle style {}; -}; - -struct Frame -{ - std::vector glyphs {}; - std::optional cursor {}; -}; - struct InputBatch { std::vector events {}; @@ -62,6 +45,7 @@ public: Screen& operator=( const Screen& ) = delete; ScreenSize size() const; + static std::size_t glyph_capacity(); TerminalCapabilities capabilities() const; InputBatch read_events( std::size_t limit ); // Wait only polls descriptors; wgetch remains the sole terminal reader. diff --git a/ricochet/src/tui/session.cc b/ricochet/src/tui/session.cc index 38d501e..a596c87 100644 --- a/ricochet/src/tui/session.cc +++ b/ricochet/src/tui/session.cc @@ -18,6 +18,7 @@ #include "ricochet/tui/session.hh" +#include "layout.hh" #include "mailbox.hh" #include "screen.hh" @@ -36,12 +37,13 @@ struct TabState TabInfo info {}; std::optional navigation {}; std::optional document {}; + std::optional layout {}; std::optional view {}; std::optional failure {}; }; // Only fixed ASCII chrome uses this helper. Document text goes through the -// forthcoming Unicode layout service, not a second ad-hoc text renderer. +// Unicode text service and document layout. void append_chrome( detail::Frame& frame, CellPoint start, std::wstring_view text, TextStyle style = {} ) { int column = start.column; @@ -147,6 +149,7 @@ public: tab.info.display_url = update.document.data().metadata.display_url; tab.info.loading_task.reset(); tab.document = std::move( update.document ); + tab.layout.reset(); tab.failure.reset(); dirty_ = true; } @@ -252,6 +255,26 @@ public: return batch.consumed || !batch.events.empty(); } + void draw_document( TabState& tab, detail::Frame& frame, ScreenSize dimensions ) + { + // The cached layout belongs to the committed snapshot and terminal width. + // CommitDocument drops it; resizing rebuilds it from logical view anchors. + if ( !tab.layout || tab.layout->columns() != dimensions.columns ) { + tab.layout.emplace( *tab.document, text_, dimensions.columns, tab.view->horizontal_scroll ); + } + const auto& layout = *tab.layout; + const auto anchor = layout.locate( tab.view->viewport_anchor ).value_or( detail::LayoutPoint {} ); + const auto body_rows = dimensions.rows - 2; + const auto first_row = std::min( anchor.row, layout.rows() - 1 ); + layout.append_frame( frame, first_row, { 1, 0 }, { body_rows, dimensions.columns } ); + const auto cursor = layout.locate( tab.view->cursor ); + if ( cursor && cursor->row >= first_row && cursor->row - first_row < static_cast( body_rows ) + && cursor->column >= 0 && cursor->column < dimensions.columns ) { + frame.cursor + = CellPoint { 1 + static_cast( cursor->row - first_row ), static_cast( cursor->column ) }; + } + } + void draw() { detail::Frame frame; @@ -271,6 +294,9 @@ public: if ( active_ ) { const auto found = tabs_.find( *active_ ); if ( found != tabs_.end() ) { + if ( found->second.document ) { + draw_document( found->second, frame, dimensions ); + } if ( found->second.info.loading_task ) { status = L"Loading | q quit"; } @@ -327,6 +353,7 @@ public: std::shared_ptr mailbox_; std::unique_ptr screen_; TerminalCapabilities capabilities_; + detail::TextService text_ { detail::Screen::glyph_capacity() }; std::map tabs_ {}; std::vector tab_order_ {}; std::optional active_ {}; diff --git a/ricochet/src/tui/text.cc b/ricochet/src/tui/text.cc new file mode 100644 index 0000000..14f0e09 --- /dev/null +++ b/ricochet/src/tui/text.cc @@ -0,0 +1,138 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "text.hh" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ricochet::tui::detail { +namespace { + +using UnicodeText = std::unique_ptr; +using Breaks = std::unique_ptr; + +Breaks breaks_for( UBreakIteratorType type, UText& text ) +{ + UErrorCode status = U_ZERO_ERROR; + Breaks breaks( ubrk_open( type, "root", nullptr, 0, &status ), &ubrk_close ); + if ( U_FAILURE( status ) ) { + throw std::runtime_error( u_errorName( status ) ); + } + ubrk_setUText( breaks.get(), &text, &status ); + if ( U_FAILURE( status ) ) { + throw std::runtime_error( u_errorName( status ) ); + } + return breaks; +} + +WordKind word_kind( UChar32 codepoint ) +{ + if ( u_isUWhiteSpace( codepoint ) ) { + return WordKind::Space; + } + if ( u_hasBinaryProperty( codepoint, UCHAR_IDEOGRAPHIC ) ) { + return WordKind::Ideograph; + } + if ( codepoint == '_' || u_isalnum( codepoint ) ) { + return WordKind::Word; + } + return WordKind::Punctuation; +} + +} // namespace + +TextService::TextService( std::size_t glyph_capacity ) : glyph_capacity_( glyph_capacity ) {} + +TextAnalysis TextService::analyze( std::string_view utf8, bool line_breaks, bool tabs ) const +{ + // ICU BreakIterator exposes int32_t native offsets even with a UTF-8 UText. + if ( utf8.size() > INT32_MAX ) { + throw std::length_error( "Text exceeds ICU break-iterator offset capacity" ); + } + UErrorCode status = U_ZERO_ERROR; + UnicodeText text( + utext_openUTF8( nullptr, utf8.empty() ? "" : utf8.data(), static_cast( utf8.size() ), &status ), + &utext_close ); + if ( U_FAILURE( status ) ) { + throw std::runtime_error( u_errorName( status ) ); + } + auto characters = breaks_for( UBRK_CHARACTER, *text ); + auto lines = breaks_for( UBRK_LINE, *text ); + TextAnalysis result; + int32_t begin = ubrk_first( characters.get() ); + int32_t line_end = ubrk_next( lines.get() ); + WordKind previous = WordKind::Space; + for ( int32_t end = ubrk_next( characters.get() ); end != UBRK_DONE; + begin = end, end = ubrk_next( characters.get() ) ) { + while ( line_end != UBRK_DONE && line_end < end ) { + line_end = ubrk_next( lines.get() ); + } + Grapheme glyph { .bytes = { static_cast( begin ), static_cast( end ) }, + .break_after = line_end == end }; + utext_setNativeIndex( text.get(), begin ); + const auto first = utext_next32( text.get() ); + glyph.word = word_kind( first ); + const auto source = utf8.substr( glyph.bytes.start, glyph.bytes.end - glyph.bytes.start ); + if ( line_breaks && ( source == "\n" || source == "\r\n" ) ) { + glyph.kind = TextUnitKind::LineBreak; + glyph.columns = 0; + } else if ( tabs && source == "\t" ) { + glyph.kind = TextUnitKind::Tab; + glyph.display = L" "; + } else { + const int width = ::wcwidth( static_cast( first ) ); + glyph.display.push_back( static_cast( first ) ); + bool representable = width > 0 && !u_hasBinaryProperty( first, UCHAR_DEFAULT_IGNORABLE_CODE_POINT ) + && !u_hasBinaryProperty( first, UCHAR_EMOJI_PRESENTATION ); + while ( utext_getNativeIndex( text.get() ) < end ) { + const auto codepoint = utext_next32( text.get() ); + glyph.display.push_back( static_cast( codepoint ) ); + // ncurses accepts one spacing character followed by nonspacing marks. + // Joiners, selectors and extra spacing characters use one visible fallback. + representable = representable && ::wcwidth( static_cast( codepoint ) ) == 0 + && u_charType( codepoint ) == U_NON_SPACING_MARK + && !u_hasBinaryProperty( codepoint, UCHAR_DEFAULT_IGNORABLE_CODE_POINT ); + } + if ( !representable || glyph.display.size() > glyph_capacity_ ) { + glyph.display = L"?"; + glyph.columns = 1; + } else { + glyph.columns = width; + } + } + if ( glyph.word != WordKind::Space ) { + if ( glyph.word == previous && glyph.word != WordKind::Ideograph ) { + result.words.back().end = glyph.bytes.end; + } else { + result.words.push_back( glyph.bytes ); + } + } + previous = glyph.word; + result.graphemes.push_back( std::move( glyph ) ); + } + return result; +} + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/text.hh b/ricochet/src/tui/text.hh new file mode 100644 index 0000000..c2d4af9 --- /dev/null +++ b/ricochet/src/tui/text.hh @@ -0,0 +1,75 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/position.hh" + +#include +#include +#include +#include +#include + +namespace ricochet::tui::detail { + +enum class TextUnitKind : std::uint8_t +{ + Glyph, + LineBreak, + Tab +}; +enum class WordKind : std::uint8_t +{ + Space, + Word, + Ideograph, + Punctuation +}; + +struct Grapheme +{ + ByteRange bytes {}; + std::wstring display {}; + int columns { 1 }; + TextUnitKind kind { TextUnitKind::Glyph }; + WordKind word { WordKind::Punctuation }; + bool break_after { false }; +}; + +struct TextAnalysis +{ + std::vector graphemes {}; + // Vim-style reading units: letters/numbers/underscore, punctuation runs, + // individual ideographs. Whitespace is excluded; offsets remain UTF-8 bytes. + std::vector words {}; +}; + +// Called on the UI thread in the same UTF-8 locale as Screen. ICU owns Unicode +// segmentation/properties; POSIX wcwidth owns terminal widths. No curses types. +class TextService +{ +public: + explicit TextService( std::size_t glyph_capacity ); + TextAnalysis analyze( std::string_view utf8, bool line_breaks, bool tabs ) const; + +private: + std::size_t glyph_capacity_; +}; + +} // namespace ricochet::tui::detail -- cgit v1.2.3 From 2063bf09fa8828c602ca1726a1188f0c95ae8adb Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Sun, 18 Oct 2026 00:45:42 +0800 Subject: feat(tui): add structured selection text and clipboard messages --- ricochet/include/ricochet/tui/messages.hh | 39 ++++- ricochet/include/ricochet/tui/view.hh | 3 + ricochet/src/tui/CMakeLists.txt | 2 +- ricochet/src/tui/document_text.cc | 231 ++++++++++++++++++++++++++++++ ricochet/src/tui/document_text.hh | 66 +++++++++ ricochet/src/tui/layout.cc | 35 +---- 6 files changed, 340 insertions(+), 36 deletions(-) create mode 100644 ricochet/src/tui/document_text.cc create mode 100644 ricochet/src/tui/document_text.hh (limited to 'ricochet/src/tui') diff --git a/ricochet/include/ricochet/tui/messages.hh b/ricochet/include/ricochet/tui/messages.hh index e7dc417..9d51fa3 100644 --- a/ricochet/include/ricochet/tui/messages.hh +++ b/ricochet/include/ricochet/tui/messages.hh @@ -139,12 +139,30 @@ struct ExitDecision std::optional explanation {}; }; +enum class CopyStatus : std::uint8_t +{ + Confirmed, + Dispatched, + Unavailable, + Failed +}; + +// The host's injected clipboard provider completes a CopySelection request once. +// Dispatched must not be used as confirmation that a terminal accepted the text. +struct CopyResult +{ + RequestId request {}; + CopyStatus status { CopyStatus::Unavailable }; + std::string summary {}; +}; + using HostUpdate = std::variant; @@ -220,6 +238,16 @@ struct ExportSelection std::string text {}; }; +struct CopySelection +{ + RequestId request {}; + DocumentScope source {}; + DraftRevision draft_revision {}; + // Frozen before dispatch; later cursor/selection changes cannot change this copy. + // Password content is already masked. Clipboard providers never receive drafts. + std::string text {}; +}; + struct RequestExit { RequestId request {}; @@ -227,7 +255,14 @@ struct RequestExit std::vector views {}; }; -using UserAction - = std::variant; +using UserAction = std::variant; } // namespace ricochet::tui diff --git a/ricochet/include/ricochet/tui/view.hh b/ricochet/include/ricochet/tui/view.hh index d259cf3..f5f33d4 100644 --- a/ricochet/include/ricochet/tui/view.hh +++ b/ricochet/include/ricochet/tui/view.hh @@ -39,6 +39,9 @@ struct SelectionSnapshot // The normalized half-open range also covers any controls between its endpoints. DocumentRange range {}; SelectionDirection direction { SelectionDirection::Forward }; + // Inclusive endpoint units retain the anchor through reversal and history restore. + DocumentRange anchor {}; + DocumentRange active {}; }; struct HorizontalScroll diff --git a/ricochet/src/tui/CMakeLists.txt b/ricochet/src/tui/CMakeLists.txt index 8b49cf1..ed7b067 100644 --- a/ricochet/src/tui/CMakeLists.txt +++ b/ricochet/src/tui/CMakeLists.txt @@ -4,7 +4,7 @@ find_package(Threads REQUIRED) # ICU 76.1 supplies UTF-8 grapheme/line boundaries and Unicode properties. pkg_check_modules(ICU REQUIRED IMPORTED_TARGET icu-uc>=76.1 icu-i18n>=76.1) -add_library(ricochet_tui STATIC document.cc mailbox.cc screen.cc session.cc text.cc layout.cc) +add_library(ricochet_tui STATIC document_text.cc document.cc mailbox.cc screen.cc session.cc text.cc layout.cc) target_include_directories(ricochet_tui PUBLIC ${PROJECT_SOURCE_DIR}/include) target_compile_features(ricochet_tui PUBLIC cxx_std_23) target_link_libraries(ricochet_tui PRIVATE PkgConfig::NCURSESW PkgConfig::ICU Threads::Threads) diff --git a/ricochet/src/tui/document_text.cc b/ricochet/src/tui/document_text.cc new file mode 100644 index 0000000..dd0c64d --- /dev/null +++ b/ricochet/src/tui/document_text.cc @@ -0,0 +1,231 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "document_text.hh" + +#include +#include +#include + +namespace ricochet::tui::detail { + +std::string control_display_text( const Control& control, const TextService& text ) +{ + return std::visit( + [&control, &text]( const auto& value ) -> std::string { + using Value = std::decay_t; + if constexpr ( std::is_same_v ) { + if ( value.kind == TextControlKind::Password ) { + return std::string( text.analyze( value.value, true, false ).graphemes.size(), '*' ); + } + return value.value; + } else if constexpr ( std::is_same_v || std::is_same_v + || std::is_same_v ) { + return control.label; + } else if constexpr ( std::is_same_v ) { + std::string result; + for ( const auto& option : value.options ) { + if ( std::ranges::find( value.selected, option.id ) != value.selected.end() ) { + if ( !result.empty() ) { + result += ", "; + } + result += option.label; + } + } + return result; + } else { + return value.description; + } + }, + control.content ); +} + +DocumentText::DocumentText( const Document& document, const TextService& text ) : service_( text ) +{ + for ( const auto& control : document.data().controls ) { + definitions_.emplace( control.id, &control ); + } + append_blocks( document.data().blocks, 0 ); +} + +void DocumentText::append_text( const Text& text ) +{ + const auto start = text_.size(); + text_ += text.utf8; + blocks_.emplace( text.id, ByteRange { start, text_.size() } ); +} + +void DocumentText::append_control( ControlId id ) +{ + const auto& control = *definitions_.at( id ); + const auto start = text_.size(); + // State is semantic content when selection crosses the object's opening boundary. + if ( const auto* checkbox = std::get_if( &control.content ) ) { + text_ += checkbox->checked ? "checked " : "unchecked "; + } else if ( const auto* radio = std::get_if( &control.content ) ) { + text_ += radio->checked ? "selected " : "unselected "; + } + const auto display = text_.size(); + text_ += control_display_text( control, service_ ); + controls_.emplace( id, ControlSpan { { start, text_.size() }, { display, text_.size() } } ); +} + +void DocumentText::append_inline( std::span content ) +{ + for ( const auto& item : content ) { + std::visit( + [this]( const auto& value ) { + using Value = std::decay_t; + if constexpr ( std::is_same_v ) { + append_text( value ); + } else { + append_control( value.control ); + } + }, + item ); + } +} + +void DocumentText::append_blocks( std::span blocks, std::size_t depth ) +{ + for ( std::size_t index = 0; index < blocks.size(); ++index ) { + if ( index != 0 ) { + text_ += "\n\n"; + } + append_block( blocks[index], depth ); + } +} + +void DocumentText::append_block( const Block& block, std::size_t depth ) +{ + const auto start = text_.size(); + std::visit( + [this, depth]( const auto& value ) { + using Value = std::decay_t; + if constexpr ( std::is_same_v || std::is_same_v ) { + append_inline( value.content ); + } else if constexpr ( std::is_same_v ) { + append_text( value.content ); + } else if constexpr ( std::is_same_v ) { + append_text( value.description ); + } else if constexpr ( std::is_same_v ) { + append_control( value.control ); + } else if constexpr ( std::is_same_v ) { + auto number = value.first_number; + for ( std::size_t index = 0; index < value.items.size(); ++index ) { + if ( index != 0 ) { + text_ += '\n'; + } + const auto& item = value.items[index]; + const auto prefix = text_.size(); + text_.append( depth * 2, ' ' ); + text_ += item.marker.value_or( value.kind == ListKind::Ordered ? std::to_string( number ) + "." : "-" ); + text_ += ' '; + prefixes_.push_back( { prefix, text_.size() } ); + append_blocks( item.content, depth + 1 ); + // Match layout's saturating counter at the model's largest list number. + if ( number < std::numeric_limits::max() ) { + ++number; + } + } + } else if constexpr ( std::is_same_v ) { + for ( std::size_t row = 0; row < value.rows.size(); ++row ) { + if ( row != 0 ) { + text_ += '\n'; + } + const auto& cells = value.rows[row].cells; + for ( std::size_t cell = 0; cell < cells.size(); ++cell ) { + if ( cell != 0 ) { + text_ += '\t'; + } + append_blocks( cells[cell].content, depth ); + } + } + } + // Separators carry positions but no copied decoration. + }, + block.content ); + blocks_.emplace( block.id, ByteRange { start, text_.size() } ); +} + +std::size_t DocumentText::offset( const DocumentPoint& point ) const +{ + return std::visit( + [this]( const auto& value ) -> std::size_t { + using Value = std::decay_t; + if constexpr ( std::is_same_v ) { + return blocks_.at( value.block ).start + value.byte_offset; + } else if constexpr ( std::is_same_v ) { + return controls_.at( value.control ).display.start + value.byte_offset; + } else if constexpr ( std::is_same_v ) { + const auto span = std::visit( + [this]( const auto& id ) -> ByteRange { + using Id = std::decay_t; + if constexpr ( std::is_same_v ) { + return blocks_.at( id ); + } else { + return controls_.at( id ).object; + } + }, + value.object ); + return value.side == BoundarySide::Before ? span.start : span.end; + } else { + return 0; + } + }, + point ); +} + +ByteRange DocumentText::offsets( const DocumentRange& range ) const +{ return { offset( range.start ), offset( range.end ) }; } + +SelectionSnapshot DocumentText::select( const DocumentRange& anchor, const DocumentRange& active ) const +{ + const bool backward = offset( active.start ) < offset( anchor.start ); + // A zero-width boundary can coincide with a nonempty endpoint unit. Keep the + // whole anchored unit even when the active endpoint comes back to that boundary. + return { .range = { backward ? active.start : anchor.start, + offset( active.end ) > offset( anchor.end ) ? active.end : anchor.end }, + .direction = backward ? SelectionDirection::Backward : SelectionDirection::Forward, + .anchor = anchor, + .active = active }; +} + +std::string DocumentText::extract( const DocumentRange& range ) const +{ + auto bytes = offsets( range ); + if ( bytes.start == bytes.end ) { + return {}; + } + // Include a semantic marker only when selection includes the item's start. + // Inner prefixes expand first, including a surrounding item with a nested list. + for ( auto prefix = prefixes_.rbegin(); prefix != prefixes_.rend(); ++prefix ) { + if ( prefix->end == bytes.start ) { + bytes.start = prefix->start; + } + } + auto result = text_.substr( bytes.start, bytes.end - bytes.start ); + // CRLF is one hard-break grapheme; copied hard breaks use one LF. + for ( auto position = result.find( "\r\n" ); position != std::string::npos; + position = result.find( "\r\n", position + 1 ) ) { + result.erase( position, 1 ); + } + return result; +} + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/document_text.hh b/ricochet/src/tui/document_text.hh new file mode 100644 index 0000000..d490c9d --- /dev/null +++ b/ricochet/src/tui/document_text.hh @@ -0,0 +1,66 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "ricochet/tui/document.hh" +#include "ricochet/tui/view.hh" +#include "text.hh" + +#include +#include +#include + +namespace ricochet::tui::detail { + +// Shared by layout and extraction: password positions address only this mask. +std::string control_display_text( const Control& control, const TextService& text ); + +// Logical reading-order text, independent of wrapping, clipping and decorations. +// Owned together with one immutable document and its revision-zero control values. +class DocumentText +{ +public: + DocumentText( const Document& document, const TextService& text ); + ByteRange offsets( const DocumentRange& range ) const; + SelectionSnapshot select( const DocumentRange& anchor, const DocumentRange& active ) const; + std::string extract( const DocumentRange& range ) const; + +private: + struct ControlSpan + { + ByteRange object {}; + ByteRange display {}; + }; + std::size_t offset( const DocumentPoint& point ) const; + void append_blocks( std::span blocks, std::size_t depth ); + void append_block( const Block& block, std::size_t depth ); + void append_inline( std::span content ); + void append_text( const Text& text ); + void append_control( ControlId id ); + + std::string text_ {}; + std::map blocks_ {}; + std::map controls_ {}; + std::map definitions_ {}; + // Prefix ends coincide with item starts; selecting that start includes its marker. + std::vector prefixes_ {}; + const TextService& service_; +}; + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/layout.cc b/ricochet/src/tui/layout.cc index 5aebe17..fa6eaa6 100644 --- a/ricochet/src/tui/layout.cc +++ b/ricochet/src/tui/layout.cc @@ -17,6 +17,7 @@ */ #include "layout.hh" +#include "document_text.hh" #include #include @@ -161,38 +162,6 @@ private: } } - std::string control_text( const Control& control ) const - { - return std::visit( - [this, &control]( const auto& value ) -> std::string { - using Value = std::decay_t; - if constexpr ( std::is_same_v ) { - if ( value.kind == TextControlKind::Password ) { - return std::string( text_.analyze( value.value, true, false ).graphemes.size(), '*' ); - } - return value.value; - } else if constexpr ( std::is_same_v || std::is_same_v ) { - return control.label; - } else if constexpr ( std::is_same_v ) { - std::string result; - for ( const auto& option : value.options ) { - if ( std::ranges::find( value.selected, option.id ) != value.selected.end() ) { - if ( !result.empty() ) { - result += ", "; - } - result += option.label; - } - } - return result; - } else if constexpr ( std::is_same_v ) { - return control.label; - } else { - return value.description; - } - }, - control.content ); - } - void control_atoms( std::vector& atoms, ControlId id, TextStyle base ) const { // A missing ID is a malformed document reference; map::at reports it directly. @@ -217,7 +186,7 @@ private: .style = style, .target = id } ); } - const auto display = control_text( control ); + const auto display = control_display_text( control, text_ ); const auto analysis = text_.analyze( display, multiline, false ); for ( const auto& glyph : analysis.graphemes ) { atoms.push_back( { .glyph = glyph, -- cgit v1.2.3 From 2e6dc81391c5dbb787cfd793ad5823904b3b9c94 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Mon, 26 Oct 2026 20:37:52 +0800 Subject: feat(tui): add document navigation and text selection --- ricochet/include/ricochet/tui/view.hh | 2 + ricochet/src/tui/CMakeLists.txt | 2 +- ricochet/src/tui/document_view.cc | 377 +++++++++++++++++++++++++ ricochet/src/tui/document_view.hh | 107 +++++++ ricochet/src/tui/layout.cc | 272 +++++++++++++++++- ricochet/src/tui/layout.hh | 53 +++- ricochet/src/tui/paint.hh | 2 + ricochet/src/tui/screen.cc | 3 +- ricochet/src/tui/session.cc | 515 ++++++++++++++++++++++++++++++---- ricochet/src/tui/text.cc | 3 + ricochet/src/tui/text.hh | 2 + 11 files changed, 1262 insertions(+), 76 deletions(-) create mode 100644 ricochet/src/tui/document_view.cc create mode 100644 ricochet/src/tui/document_view.hh (limited to 'ricochet/src/tui') diff --git a/ricochet/include/ricochet/tui/view.hh b/ricochet/include/ricochet/tui/view.hh index f5f33d4..cc1d0fd 100644 --- a/ricochet/include/ricochet/tui/view.hh +++ b/ricochet/include/ricochet/tui/view.hh @@ -64,6 +64,8 @@ struct ViewSnapshot DraftRevision draft_revision {}; DisplayPosition cursor {}; DisplayPosition viewport_anchor {}; + // Relative visual row for blank table space with no text at the exact top. + std::int64_t viewport_row_offset { 0 }; std::optional selection {}; std::vector horizontal_scroll {}; SearchSnapshot search {}; diff --git a/ricochet/src/tui/CMakeLists.txt b/ricochet/src/tui/CMakeLists.txt index ed7b067..98dcee2 100644 --- a/ricochet/src/tui/CMakeLists.txt +++ b/ricochet/src/tui/CMakeLists.txt @@ -4,7 +4,7 @@ find_package(Threads REQUIRED) # ICU 76.1 supplies UTF-8 grapheme/line boundaries and Unicode properties. pkg_check_modules(ICU REQUIRED IMPORTED_TARGET icu-uc>=76.1 icu-i18n>=76.1) -add_library(ricochet_tui STATIC document_text.cc document.cc mailbox.cc screen.cc session.cc text.cc layout.cc) +add_library(ricochet_tui STATIC document_text.cc document.cc document_view.cc mailbox.cc screen.cc session.cc text.cc layout.cc) target_include_directories(ricochet_tui PUBLIC ${PROJECT_SOURCE_DIR}/include) target_compile_features(ricochet_tui PUBLIC cxx_std_23) target_link_libraries(ricochet_tui PRIVATE PkgConfig::NCURSESW PkgConfig::ICU Threads::Threads) diff --git a/ricochet/src/tui/document_view.cc b/ricochet/src/tui/document_view.cc new file mode 100644 index 0000000..ee74e53 --- /dev/null +++ b/ricochet/src/tui/document_view.cc @@ -0,0 +1,377 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "document_view.hh" + +#include +#include + +namespace ricochet::tui::detail { +namespace { + +ScreenSize body_size( ScreenSize viewport ) +{ return { std::max( 1, viewport.rows ), std::max( 1, viewport.columns ) }; } + +std::size_t shifted_row( std::size_t row, std::int64_t distance, std::size_t last ) +{ + // Clamp the displacement before addition; restored relative offsets can be signed. + const auto origin = static_cast( row ); + return static_cast( origin + + std::clamp( distance, -origin, static_cast( last ) - origin ) ); +} + +} // namespace + +DocumentView::DocumentView( Document document, ViewSnapshot snapshot, const TextService& text, ScreenSize viewport ) + : document_( std::move( document ) ) + , snapshot_( std::move( snapshot ) ) + , text_( text ) + , content_( document_, text_ ) + , viewport_( body_size( viewport ) ) + , layout_( document_, text_, viewport_.columns, snapshot_.horizontal_scroll ) +{ + // A history snapshot can name a removed boundary. The new document starts at + // its first reading unit; it never manufactures a byte offset into that text. + if ( std::holds_alternative( snapshot_.cursor.point ) || !layout_.locate( snapshot_.cursor ) ) { + snapshot_.cursor = layout_.first(); + } + desired_column_ = layout_.locate( snapshot_.cursor ).value().column; + restore_viewport(); + if ( snapshot_.selection ) { + const auto& selection = *snapshot_.selection; + // History endpoints must still be layout boundaries in this exact document/draft. + if ( layout_.locate( { selection.anchor.start } ) && layout_.locate( { selection.anchor.end } ) + && layout_.locate( { selection.active.start } ) && layout_.locate( { selection.active.end } ) ) { + snapshot_.selection = content_.select( selection.anchor, selection.active ); + } else { + snapshot_.selection.reset(); + } + } +} + +const Document& DocumentView::document() const +{ return document_; } +const ViewSnapshot& DocumentView::snapshot() const +{ return snapshot_; } + +std::size_t DocumentView::last_top_row() const +{ return layout_.rows() - std::min( layout_.rows(), static_cast( viewport_.rows ) ); } + +void DocumentView::set_top_row( std::size_t row ) +{ + top_row_ = std::min( row, last_top_row() ); + snapshot_.viewport_anchor = layout_.on_row( { top_row_, 0 } ); + const auto anchor = layout_.locate( snapshot_.viewport_anchor ).value(); + snapshot_.viewport_row_offset = static_cast( top_row_ ) - static_cast( anchor.row ); +} + +void DocumentView::restore_viewport() +{ + auto anchor = layout_.locate( snapshot_.viewport_anchor ); + if ( !anchor ) { + snapshot_.viewport_anchor = layout_.first(); + snapshot_.viewport_row_offset = 0; + anchor = layout_.locate( snapshot_.viewport_anchor ); + } + set_top_row( shifted_row( anchor->row, snapshot_.viewport_row_offset, last_top_row() ) ); +} + +void DocumentView::resize( ScreenSize viewport ) +{ + const auto next = body_size( viewport ); + if ( next == viewport_ ) { + return; + } + stop_drag(); + const bool reflow = next.columns != viewport_.columns; + viewport_ = next; + if ( reflow ) { + layout_ = DocumentLayout( document_, text_, viewport_.columns, snapshot_.horizontal_scroll ); + desired_column_ = layout_.locate( snapshot_.cursor ).value().column; + } + restore_viewport(); + // A wheel/pan action deliberately allows the cursor to stay outside the view. + if ( follow_cursor_ ) { + reveal_cursor(); + } +} + +void DocumentView::apply_scrolls( std::span changes ) +{ + if ( changes.empty() ) { + return; + } + for ( const auto& change : changes ) { + const auto found = std::ranges::find( snapshot_.horizontal_scroll, change.block, &HorizontalScroll::block ); + if ( found == snapshot_.horizontal_scroll.end() ) { + snapshot_.horizontal_scroll.push_back( change ); + } else { + *found = change; + } + } + layout_ = DocumentLayout( document_, text_, viewport_.columns, snapshot_.horizontal_scroll ); + restore_viewport(); +} + +void DocumentView::reveal_cursor() +{ + apply_scrolls( layout_.reveal( snapshot_.cursor ) ); + const auto point = layout_.locate( snapshot_.cursor ).value(); + if ( point.row < top_row_ ) { + set_top_row( point.row ); + } else if ( point.row - top_row_ >= static_cast( viewport_.rows ) ) { + set_top_row( point.row - static_cast( viewport_.rows - 1 ) ); + } +} + +void DocumentView::finish_move( bool preserve_column ) +{ + follow_cursor_ = true; + extend_selection(); + reveal_cursor(); + if ( !preserve_column ) { + desired_column_ = layout_.locate( snapshot_.cursor ).value().column; + } +} + +void DocumentView::move_rows( std::int64_t distance, bool page ) +{ + const auto origin = layout_.locate( snapshot_.cursor ).value(); + const auto row = shifted_row( origin.row, distance, layout_.rows() - 1 ); + snapshot_.cursor = layout_.on_row( { row, desired_column_ } ); + if ( page ) { + // Shift both by the same amount before revealing, retaining screen-relative + // cursor position wherever document boundaries permit it. + set_top_row( shifted_row( top_row_, distance, last_top_row() ) ); + } + finish_move( true ); +} + +void DocumentView::move( ViewMotion motion ) +{ + stop_drag(); + switch ( motion ) { + case ViewMotion::Left: + snapshot_.cursor = layout_.adjacent( snapshot_.cursor, -1 ); + break; + case ViewMotion::Right: + snapshot_.cursor = layout_.adjacent( snapshot_.cursor, 1 ); + break; + case ViewMotion::NextWord: + snapshot_.cursor = layout_.word( snapshot_.cursor, WordMotion::Next ); + break; + case ViewMotion::PreviousWord: + snapshot_.cursor = layout_.word( snapshot_.cursor, WordMotion::Previous ); + break; + case ViewMotion::WordEnd: + snapshot_.cursor = layout_.word( snapshot_.cursor, WordMotion::End ); + break; + case ViewMotion::LineStart: + snapshot_.cursor = layout_.line_edge( snapshot_.cursor, false ); + break; + case ViewMotion::LineEnd: + snapshot_.cursor = layout_.line_edge( snapshot_.cursor, true ); + break; + case ViewMotion::DocumentStart: + snapshot_.cursor = layout_.first(); + break; + case ViewMotion::DocumentEnd: + snapshot_.cursor = layout_.last(); + break; + case ViewMotion::Up: + move_rows( -1, false ); + return; + case ViewMotion::Down: + move_rows( 1, false ); + return; + case ViewMotion::PageUp: + move_rows( -std::max( 1, viewport_.rows - 1 ), true ); + return; + case ViewMotion::PageDown: + move_rows( std::max( 1, viewport_.rows - 1 ), true ); + return; + case ViewMotion::HalfPageUp: + move_rows( -std::max( 1, viewport_.rows / 2 ), true ); + return; + case ViewMotion::HalfPageDown: + move_rows( std::max( 1, viewport_.rows / 2 ), true ); + return; + case ViewMotion::PanLeft: + case ViewMotion::PanRight: { + const auto changes = layout_.pan( snapshot_.cursor, motion == ViewMotion::PanLeft ? -1 : 1 ); + if ( changes.empty() ) { + return; + } + const auto old_column = layout_.locate( snapshot_.cursor ).value().column; + apply_scrolls( changes ); + // Panning changes screen coordinates, not the desired logical column for + // the next vertical move (including one remembered across a short line). + desired_column_ += layout_.locate( snapshot_.cursor ).value().column - old_column; + follow_cursor_ = false; + return; + } + } + finish_move( false ); +} + +void DocumentView::begin_selection() +{ + stop_drag(); + const auto unit = layout_.unit( snapshot_.cursor ); + snapshot_.selection = content_.select( unit, unit ); +} + +void DocumentView::cancel_selection() +{ + stop_drag(); + snapshot_.selection.reset(); +} + +void DocumentView::extend_selection() +{ + if ( snapshot_.selection ) { + snapshot_.selection = content_.select( snapshot_.selection->anchor, layout_.unit( snapshot_.cursor ) ); + } +} + +std::optional DocumentView::selected_text() const +{ + if ( !snapshot_.selection ) { + return std::nullopt; + } + return content_.extract( snapshot_.selection->range ); +} + +void DocumentView::press( CellPoint point, std::chrono::steady_clock::time_point now ) +{ + const auto hit = layout_.hit( { top_row_ + static_cast( point.row ), point.column } ); + // A completely clipped wide glyph has no visible cell to hit. + if ( !hit ) { + return; + } + snapshot_.cursor = hit->position; + cancel_selection(); + desired_column_ = layout_.locate( snapshot_.cursor ).value().column; + follow_cursor_ = false; + drag_ = Drag { point, point, layout_.unit( snapshot_.cursor ), false, now + std::chrono::milliseconds( 100 ) }; +} + +void DocumentView::drag_to_pointer() +{ + const auto row = std::clamp( drag_->pointer.row, 0, viewport_.rows - 1 ); + const auto column = std::clamp( drag_->pointer.column, 0, viewport_.columns - 1 ); + const auto hit = layout_.hit( { top_row_ + static_cast( row ), column } ); + if ( !hit ) { + return; + } + snapshot_.cursor = hit->position; + snapshot_.selection = content_.select( drag_->anchor, layout_.unit( snapshot_.cursor ) ); + desired_column_ = layout_.locate( snapshot_.cursor ).value().column; + follow_cursor_ = false; +} + +void DocumentView::drag( CellPoint point ) +{ + drag_->pointer = point; + // One cell is the terminal's movement threshold; wide halves still share a unit. + drag_->selecting = drag_->selecting || point.row != drag_->press.row || point.column != drag_->press.column; + if ( drag_->selecting ) { + drag_to_pointer(); + } +} + +void DocumentView::release( CellPoint point ) +{ + drag( point ); + stop_drag(); +} + +void DocumentView::stop_drag() +{ drag_.reset(); } + +bool DocumentView::dragging() const +{ return drag_.has_value(); } + +bool DocumentView::tick( std::chrono::steady_clock::time_point now ) +{ + if ( !drag_ || !drag_->selecting || now < drag_->next_scroll ) { + return false; + } + drag_->next_scroll = now + std::chrono::milliseconds( 100 ); + // With a one-row body both edges coincide; leaving it above/below disambiguates. + const int direction = drag_->pointer.row < 0 ? -1 + : drag_->pointer.row >= viewport_.rows ? 1 + : viewport_.rows == 1 ? 0 + : drag_->pointer.row == 0 ? -1 + : drag_->pointer.row == viewport_.rows - 1 ? 1 + : 0; + const auto next = shifted_row( top_row_, direction, last_top_row() ); + if ( next == top_row_ ) { + return false; + } + set_top_row( next ); + drag_to_pointer(); + return true; +} + +void DocumentView::wheel( int steps ) +{ + set_top_row( shifted_row( top_row_, static_cast( steps ) * 3, last_top_row() ) ); + follow_cursor_ = false; + if ( drag_ && drag_->selecting ) { + drag_to_pointer(); + } +} + +bool DocumentView::locate( const DocumentPoint& point ) +{ + const DisplayPosition requested { point, WrapAffinity::NextLine }; + const auto location = layout_.locate( requested ); + // Host jumps can refer to absent anchors, removed leaves or non-grapheme offsets. + if ( !location ) { + return false; + } + snapshot_.cursor = requested; + if ( std::holds_alternative( point ) ) { + snapshot_.cursor = layout_.first(); + } else if ( const auto* object = std::get_if( &point ); + object && std::holds_alternative( object->object ) ) { + snapshot_.cursor = layout_.on_row( *location ); + } + cancel_selection(); + finish_move( false ); + return true; +} + +std::optional DocumentView::focused_target() const +{ return layout_.target( snapshot_.cursor ); } + +void DocumentView::draw( Frame& frame, CellPoint origin ) const +{ + const auto selection = snapshot_.selection ? std::optional( snapshot_.selection->range ) : std::nullopt; + layout_.append_frame( + frame, top_row_, origin, viewport_, content_, selection, snapshot_.cursor, focused_target() ); + const auto cursor = layout_.cursor_cell( snapshot_.cursor ); + if ( cursor && cursor->row >= top_row_ && cursor->row - top_row_ < static_cast( viewport_.rows ) + && cursor->column >= 0 && cursor->column < viewport_.columns ) { + frame.cursor = CellPoint { origin.row + static_cast( cursor->row - top_row_ ), + origin.column + static_cast( cursor->column ) }; + } +} + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/document_view.hh b/ricochet/src/tui/document_view.hh new file mode 100644 index 0000000..587f419 --- /dev/null +++ b/ricochet/src/tui/document_view.hh @@ -0,0 +1,107 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "document_text.hh" +#include "layout.hh" + +#include + +namespace ricochet::tui::detail { + +enum class ViewMotion : std::uint8_t +{ + Left, + Right, + Up, + Down, + NextWord, + PreviousWord, + WordEnd, + LineStart, + LineEnd, + DocumentStart, + DocumentEnd, + PageUp, + PageDown, + HalfPageUp, + HalfPageDown, + PanLeft, + PanRight +}; + +// One tab's reading state. It owns the logical snapshot; screen rows are caches. +// Keyboard, mouse and host navigation all use the same layout/source mappings. +class DocumentView +{ +public: + DocumentView( Document document, ViewSnapshot snapshot, const TextService& text, ScreenSize viewport ); + + const Document& document() const; + const ViewSnapshot& snapshot() const; + void resize( ScreenSize viewport ); + void move( ViewMotion motion ); + void press( CellPoint point, std::chrono::steady_clock::time_point now ); + // The session routes these only while dragging() owns mouse capture. + void drag( CellPoint point ); + void release( CellPoint point ); + void stop_drag(); + bool dragging() const; + bool tick( std::chrono::steady_clock::time_point now ); + void begin_selection(); + void cancel_selection(); + std::optional selected_text() const; + void wheel( int steps ); + bool locate( const DocumentPoint& point ); + std::optional focused_target() const; + void draw( Frame& frame, CellPoint origin ) const; + +private: + std::size_t last_top_row() const; + void set_top_row( std::size_t row ); + void restore_viewport(); + void apply_scrolls( std::span changes ); + void reveal_cursor(); + void finish_move( bool preserve_column ); + void move_rows( std::int64_t distance, bool page ); + void extend_selection(); + void drag_to_pointer(); + + struct Drag + { + CellPoint press {}; + CellPoint pointer {}; + DocumentRange anchor {}; + bool selecting { false }; + std::chrono::steady_clock::time_point next_scroll {}; + }; + + Document document_; + ViewSnapshot snapshot_; + const TextService& text_; + DocumentText content_; + ScreenSize viewport_; + DocumentLayout layout_; + std::size_t top_row_ { 0 }; + std::int64_t desired_column_ { 0 }; + bool follow_cursor_ { false }; + std::optional drag_ {}; +}; + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/layout.cc b/ricochet/src/tui/layout.cc index fa6eaa6..e12c8d0 100644 --- a/ricochet/src/tui/layout.cc +++ b/ricochet/src/tui/layout.cc @@ -84,6 +84,9 @@ void append_box( LayoutData& destination, LayoutData source, std::size_t row, st glyph.position.row += row; glyph.position.column += column; glyph.line_start += column; + for ( auto& window : glyph.scrolls ) { + window.left += column; + } glyph.clip_left += column; glyph.clip_right += column; destination.glyphs.push_back( std::move( glyph ) ); @@ -276,7 +279,9 @@ private: .target = atom.target, .clip_right = wrap ? width : std::numeric_limits::max(), .decoration = atom.decoration, - .fill = tab } ); + .fill = tab, + .word_start = atom.glyph.word_start, + .word_end = atom.glyph.word_end } ); column += cells; } result.extent = std::max( result.extent, column ); @@ -309,6 +314,10 @@ private: const auto maximum = std::max( 0, box.extent - width ); const auto shift = static_cast( std::min( requested, maximum ) ); for ( auto& glyph : box.glyphs ) { + for ( auto& window : glyph.scrolls ) { + window.left -= shift; + } + glyph.scrolls.push_back( { block, 0, width, shift, maximum } ); glyph.position.column -= shift; glyph.line_start -= shift; glyph.clip_left = std::max( 0, glyph.clip_left - shift ); @@ -504,7 +513,7 @@ private: { result.rows - 1, std::min( result.extent, width ) }, width ); before.boundary_only = has_text; - after.boundary_only = has_text; + after.boundary_only = true; result.glyphs.push_back( std::move( before ) ); result.glyphs.push_back( std::move( after ) ); return result; @@ -541,6 +550,21 @@ DocumentLayout::DocumentLayout( const Document& document, if ( data_.glyphs.empty() ) { data_.glyphs.push_back( anchor( DocumentStart {}, {}, columns_ ) ); } + for ( std::size_t index = 0; index < data_.glyphs.size(); ++index ) { + const auto& glyph = data_.glyphs[index]; + if ( glyph.decoration || glyph.boundary_only ) { + continue; + } + // Wrapped object borders and hard-break anchors can repeat a logical point. + // Keep one reading stop, preferring actual text over its zero-width anchor. + if ( !stops_.empty() && data_.glyphs[stops_.back()].source.start == glyph.source.start ) { + if ( data_.glyphs[stops_.back()].columns == 0 ) { + stops_.back() = index; + } + } else { + stops_.push_back( index ); + } + } } int DocumentLayout::columns() const @@ -551,7 +575,7 @@ std::size_t DocumentLayout::rows() const std::optional DocumentLayout::locate( const DisplayPosition& position ) const { if ( std::holds_alternative( position.point ) ) { - return LayoutPoint {}; + return data_.glyphs[stops_.front()].position; } std::optional fallback; for ( const auto& glyph : data_.glyphs ) { @@ -576,6 +600,12 @@ std::optional DocumentLayout::locate( const DisplayPosition& positi std::optional DocumentLayout::hit( LayoutPoint point ) const { + // Blank space below the document means its last reading position, independent + // of the mouse column (especially when the final block is a table). + if ( point.row >= data_.rows ) { + const auto& glyph = data_.glyphs[stops_.back()]; + return LayoutHit { last(), glyph.source, glyph.target }; + } const LayoutGlyph* nearest = nullptr; auto distance = std::tuple { std::numeric_limits::max(), std::numeric_limits::max(), true }; @@ -613,32 +643,252 @@ std::optional DocumentLayout::hit( LayoutPoint point ) const .target = nearest->target }; } +DisplayPosition DocumentLayout::stop( std::size_t index ) const +{ return { data_.glyphs[stops_[index]].source.start, WrapAffinity::NextLine }; } + +DisplayPosition DocumentLayout::first() const +{ return stop( 0 ); } +DisplayPosition DocumentLayout::last() const +{ return stop( stops_.size() - 1 ); } + +std::size_t DocumentLayout::nearest_stop( LayoutPoint point ) const +{ + std::size_t nearest = 0; + auto distance = std::pair { std::numeric_limits::max(), std::numeric_limits::max() }; + for ( std::size_t index = 0; index < stops_.size(); ++index ) { + const auto& glyph = data_.glyphs[stops_[index]]; + const auto row = glyph.position.row; + const auto right = glyph.position.column + std::max( 1, glyph.columns ) - 1; + const auto candidate = std::pair { + row > point.row ? row - point.row : point.row - row, + std::max( { glyph.position.column - point.column, point.column - right, std::int64_t { 0 } } ) }; + if ( candidate < distance ) { + nearest = index; + distance = candidate; + } + } + return nearest; +} + +DocumentLayout::ReadingPosition DocumentLayout::reading_position( const DisplayPosition& position ) const +{ + std::optional endpoint; + for ( std::size_t index = 0; index < stops_.size(); ++index ) { + const auto& glyph = data_.glyphs[stops_[index]]; + if ( glyph.source.start == position.point ) { + return { index, position.affinity == WrapAffinity::NextLine }; + } + if ( glyph.source.end == position.point ) { + endpoint = index + 1; + } + } + if ( endpoint ) { + return { *endpoint, false }; + } + // Structural block anchors have coordinates but are not extra character stops. + return { nearest_stop( locate( position ).value() ), true }; +} + +DisplayPosition DocumentLayout::adjacent( const DisplayPosition& position, int direction ) const +{ + const auto current = reading_position( position ); + if ( direction < 0 ) { + return stop( current.index == 0 ? 0 : current.index - 1 ); + } + return stop( std::min( stops_.size() - 1, current.index + static_cast( current.at_start ) ) ); +} + +DisplayPosition DocumentLayout::word( const DisplayPosition& position, WordMotion motion ) const +{ + const auto current = reading_position( position ); + if ( motion == WordMotion::Previous ) { + for ( auto index = current.index; index > 0; ) { + --index; + if ( data_.glyphs[stops_[index]].word_start ) { + return stop( index ); + } + } + return first(); + } + auto begin = current.index; + if ( current.at_start && ( motion == WordMotion::Next || data_.glyphs[stops_[begin]].word_end ) ) { + ++begin; + } + for ( auto index = begin; index < stops_.size(); ++index ) { + const auto& glyph = data_.glyphs[stops_[index]]; + if ( motion == WordMotion::Next ? glyph.word_start : glyph.word_end ) { + return stop( index ); + } + } + return last(); +} + +DisplayPosition DocumentLayout::on_row( LayoutPoint point ) const +{ return stop( nearest_stop( point ) ); } + +DisplayPosition DocumentLayout::line_edge( const DisplayPosition& position, bool end ) const +{ + const auto row = locate( position ).value().row; + auto chosen = nearest_stop( { row, 0 } ); + for ( std::size_t index = 0; index < stops_.size(); ++index ) { + const auto& glyph = data_.glyphs[stops_[index]]; + const auto column = data_.glyphs[stops_[chosen]].position.column; + if ( glyph.position.row == row && ( end ? glyph.position.column > column : glyph.position.column < column ) ) { + chosen = index; + } + } + return stop( chosen ); +} + +const LayoutGlyph& DocumentLayout::cursor_glyph( const DisplayPosition& position ) const +{ + const auto current = reading_position( position ); + const auto index = current.at_start || current.index == 0 ? current.index : current.index - 1; + return data_.glyphs[stops_[std::min( index, stops_.size() - 1 )]]; +} + +std::optional DocumentLayout::target( const DisplayPosition& position ) const +{ return cursor_glyph( position ).target; } + +std::optional DocumentLayout::cursor_cell( const DisplayPosition& position ) const +{ + const auto& glyph = cursor_glyph( position ); + auto point = locate( position ).value(); + if ( glyph.fill ) { + // Any visible part of an expanded tab represents the same logical unit. + const auto left = std::max( glyph.position.column, glyph.clip_left ); + const auto right = std::min( glyph.position.column + glyph.columns, glyph.clip_right ); + if ( left >= right ) { + return std::nullopt; + } + point.column = std::clamp( point.column, left, right - 1 ); + return point; + } + if ( point.column == glyph.clip_right && point.row == glyph.position.row ) { + // An insertion boundary or LF immediately after a full row has no cell. + // Use the preceding complete glyph; do not reveal a cursor further offscreen. + auto column = glyph.clip_right - 1; + for ( const auto index : stops_ ) { + const auto& candidate = data_.glyphs[index]; + if ( candidate.position.row == point.row && candidate.columns > 0 + && candidate.position.column >= glyph.clip_left + && candidate.position.column + candidate.columns == glyph.clip_right ) { + column = candidate.position.column; + } + } + point.column = column; + } + // In a one-cell viewport a wide glyph is clipped entirely. Its cursor occupies + // the blank fallback cell, never paints half of the character. + const auto width = point.column == glyph.position.column + ? std::min( std::max( 1, glyph.columns ), glyph.clip_right - glyph.clip_left ) + : 1; + if ( point.column < glyph.clip_left || point.column >= glyph.clip_right + || point.column + width > glyph.clip_right ) { + return std::nullopt; + } + return point; +} + +std::vector DocumentLayout::reveal( const DisplayPosition& position ) const +{ + const auto& glyph = cursor_glyph( position ); + auto column = glyph.position.column; + const auto width = std::max( 1, glyph.columns ); + std::vector result; + for ( const auto& window : glyph.scrolls ) { + const auto delta + = column < window.left + ? column - window.left + : std::max( + 0, column + std::min( width, window.width ) - window.left - window.width ); + const auto offset = std::clamp( window.offset + delta, std::int64_t { 0 }, window.maximum ); + if ( offset != window.offset ) { + result.push_back( { window.block, static_cast( offset ) } ); + column -= offset - window.offset; + } + } + return result; +} + +std::vector DocumentLayout::pan( const DisplayPosition& position, int direction ) const +{ + for ( const auto& window : cursor_glyph( position ).scrolls ) { + if ( window.maximum > 0 ) { + const auto offset = std::clamp( window.offset + direction, std::int64_t { 0 }, window.maximum ); + if ( offset == window.offset ) { + return {}; + } + return { { window.block, static_cast( offset ) } }; + } + } + return {}; +} + +DocumentRange DocumentLayout::unit( const DisplayPosition& position ) const +{ + const auto reading = reading_position( position ); + if ( !reading.at_start ) { + return { position.point, position.point }; + } + return data_.glyphs[stops_[reading.index]].source; +} + void DocumentLayout::append_frame( Frame& frame, std::size_t first_row, CellPoint origin, - ScreenSize viewport ) const + ScreenSize viewport, + const DocumentText& content, + std::optional selection, + const DisplayPosition& cursor, + std::optional focus ) const { + const auto selected = selection ? content.offsets( *selection ) : ByteRange {}; + const auto caret = cursor_cell( cursor ); for ( const auto& glyph : data_.glyphs ) { - if ( glyph.text.empty() || glyph.position.row < first_row + if ( glyph.position.row < first_row || glyph.position.row - first_row >= static_cast( std::max( 0, viewport.rows ) ) ) { continue; } + bool highlighted = false; + if ( selection && !glyph.decoration && !glyph.boundary_only ) { + const auto bytes = content.offsets( glyph.source ); + highlighted = bytes.start < selected.end && selected.start < bytes.end; + // A control border has an object position but contributes no decoration to copy. + if ( bytes.start == bytes.end && std::holds_alternative( glyph.source.start ) ) { + highlighted = selected.start <= bytes.start && bytes.start < selected.end; + } + } + const bool newline = glyph.line_break && highlighted; + if ( glyph.text.empty() && !newline ) { + continue; + } + auto style = glyph.style; + style.strong = style.strong || ( focus && glyph.target == focus ); const auto left = std::max( 0, glyph.clip_left ); const auto right = std::min( viewport.columns, glyph.clip_right ); const auto row = origin.row + static_cast( glyph.position.row - first_row ); + const bool at_cursor = caret && caret->row == glyph.position.row && caret->column >= glyph.position.column + && caret->column < glyph.position.column + std::max( 1, glyph.columns ); if ( glyph.fill ) { // Expanded tabs are many blank cells but keep a single source range/hit unit. for ( auto column = std::max( left, glyph.position.column ); column < std::min( right, glyph.position.column + glyph.columns ); ++column ) { - frame.glyphs.push_back( - { .position = { row, origin.column + static_cast( column ) }, .text = L" ", .style = glyph.style } ); + frame.glyphs.push_back( { .position = { row, origin.column + static_cast( column ) }, + .text = L" ", + .style = style, + .selected = highlighted, + .cursor = at_cursor && column == caret->column } ); } - } else if ( glyph.position.column >= left && glyph.position.column + glyph.columns <= right ) { + } else if ( glyph.position.column >= left + && glyph.position.column + ( newline ? 1 : glyph.columns ) <= right ) { frame.glyphs.push_back( { .position = { row, origin.column + static_cast( glyph.position.column ) }, - .width = glyph.columns, - .text = glyph.text, - .style = glyph.style } ); + .width = newline ? 1 : glyph.columns, + .text = newline ? L" " : glyph.text, + .style = style, + .selected = highlighted, + .cursor = at_cursor } ); } } } diff --git a/ricochet/src/tui/layout.hh b/ricochet/src/tui/layout.hh index 5feb0cd..7e02e76 100644 --- a/ricochet/src/tui/layout.hh +++ b/ricochet/src/tui/layout.hh @@ -31,6 +31,8 @@ namespace ricochet::tui::detail { +class DocumentText; + using HitTarget = std::variant; struct LayoutPoint @@ -46,6 +48,22 @@ struct LayoutHit std::optional target {}; }; +struct ScrollWindow +{ + BlockId block {}; + std::int64_t left { 0 }; + std::int64_t width { 0 }; + std::int64_t offset { 0 }; + std::int64_t maximum { 0 }; +}; + +enum class WordMotion : std::uint8_t +{ + Next, + Previous, + End +}; + struct LayoutGlyph { LayoutPoint position {}; @@ -63,6 +81,10 @@ struct LayoutGlyph bool decoration { false }; bool line_break { false }; bool fill { false }; + bool word_start { false }; + bool word_end { false }; + // Inner-to-outer windows allow a code block inside a table to be revealed. + std::vector scrolls {}; }; struct LayoutData @@ -88,11 +110,40 @@ public: std::size_t rows() const; std::optional locate( const DisplayPosition& position ) const; std::optional hit( LayoutPoint point ) const; - void append_frame( Frame& frame, std::size_t first_row, CellPoint origin, ScreenSize viewport ) const; + DisplayPosition first() const; + DisplayPosition last() const; + DisplayPosition adjacent( const DisplayPosition& position, int direction ) const; + DisplayPosition word( const DisplayPosition& position, WordMotion motion ) const; + DisplayPosition on_row( LayoutPoint point ) const; + DisplayPosition line_edge( const DisplayPosition& position, bool end ) const; + DocumentRange unit( const DisplayPosition& position ) const; + std::optional target( const DisplayPosition& position ) const; + std::optional cursor_cell( const DisplayPosition& position ) const; + std::vector reveal( const DisplayPosition& position ) const; + std::vector pan( const DisplayPosition& position, int direction ) const; + void append_frame( Frame& frame, + std::size_t first_row, + CellPoint origin, + ScreenSize viewport, + const DocumentText& content, + std::optional selection, + const DisplayPosition& cursor, + std::optional focus = {} ) const; private: + struct ReadingPosition + { + std::size_t index { 0 }; + bool at_start { true }; + }; + ReadingPosition reading_position( const DisplayPosition& position ) const; + std::size_t nearest_stop( LayoutPoint point ) const; + const LayoutGlyph& cursor_glyph( const DisplayPosition& position ) const; + DisplayPosition stop( std::size_t index ) const; + int columns_; LayoutData data_; + std::vector stops_ {}; }; } // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/paint.hh b/ricochet/src/tui/paint.hh index 549718d..43bdf89 100644 --- a/ricochet/src/tui/paint.hh +++ b/ricochet/src/tui/paint.hh @@ -35,6 +35,8 @@ struct PaintGlyph int width { 1 }; std::wstring text {}; TextStyle style {}; + bool selected { false }; + bool cursor { false }; }; struct Frame diff --git a/ricochet/src/tui/screen.cc b/ricochet/src/tui/screen.cc index 34a8542..99d4e36 100644 --- a/ricochet/src/tui/screen.cc +++ b/ricochet/src/tui/screen.cc @@ -532,7 +532,8 @@ public: } const attr_t attributes = ( glyph.style.strong ? A_BOLD : A_NORMAL ) | ( glyph.style.emphasis ? A_UNDERLINE : A_NORMAL ) - | ( glyph.style.subdued ? A_DIM : A_NORMAL ) | ( glyph.style.warning ? A_REVERSE : A_NORMAL ); + | ( glyph.style.subdued ? A_DIM : A_NORMAL ) | ( glyph.style.warning ? A_REVERSE : A_NORMAL ) + | ( glyph.selected ? A_REVERSE | A_UNDERLINE : A_NORMAL ) | ( glyph.cursor ? A_BOLD : A_NORMAL ); cchar_t cell {}; if ( setcchar( &cell, glyph.text.c_str(), attributes, 0, nullptr ) == ERR || mvwadd_wchnstr( stdscr, row, column, &cell, 1 ) == ERR ) { diff --git a/ricochet/src/tui/session.cc b/ricochet/src/tui/session.cc index a596c87..069c938 100644 --- a/ricochet/src/tui/session.cc +++ b/ricochet/src/tui/session.cc @@ -18,11 +18,12 @@ #include "ricochet/tui/session.hh" -#include "layout.hh" +#include "document_view.hh" #include "mailbox.hh" #include "screen.hh" #include +#include #include #include #include @@ -32,14 +33,22 @@ namespace ricochet::tui { namespace { +using Clock = std::chrono::steady_clock; + +struct KeyPrefix +{ + char32_t character; + Clock::time_point deadline; +}; + struct TabState { TabInfo info {}; std::optional navigation {}; - std::optional document {}; - std::optional layout {}; - std::optional view {}; + std::optional view {}; std::optional failure {}; + std::optional copy_request {}; + std::string copy_feedback {}; }; // Only fixed ASCII chrome uses this helper. Document text goes through the @@ -78,12 +87,13 @@ public: if ( exit_request_ ) { return; } + prefix_.reset(); const RequestId request { next_request_++ }; std::vector views; for ( const auto id : tab_order_ ) { const auto& tab = tabs_.at( id ); if ( tab.view ) { - views.push_back( *tab.view ); + views.push_back( tab.view->snapshot() ); } } actions_.emplace_back( RequestExit { request, active_, std::move( views ) } ); @@ -93,6 +103,9 @@ public: void apply( SyncTabs update, StepResult& ) { + if ( active_ != update.active ) { + stop_drag(); + } std::map retained; std::vector order; order.reserve( update.tabs.size() ); @@ -109,6 +122,10 @@ public: } tabs_ = std::move( retained ); tab_order_ = std::move( order ); + if ( active_ != update.active ) { + prefix_.reset(); + notice_.clear(); + } active_ = update.active; dirty_ = true; } @@ -134,28 +151,74 @@ public: } auto& tab = found->second; const auto version = update.document.data().version; - if ( tab.document && tab.document->data().version.document == version.document - && version.revision < tab.document->data().version.revision ) { + if ( tab.view && tab.view->document().data().version.document == version.document + && version.revision < tab.view->document().data().version.revision ) { return; } const DocumentScope scope { update.tab, version }; - tab.view = ViewSnapshot { .scope = scope }; + ViewSnapshot snapshot { .scope = scope }; // Initial drafts are revision zero. A history view referring to edited values // cannot be restored without the corresponding draft snapshot/mapping. if ( update.restore && update.restore->scope == scope && update.restore->draft_revision == DraftRevision {} ) { - tab.view = std::move( update.restore ); + snapshot = std::move( *update.restore ); } tab.info.title = update.document.data().metadata.title; tab.info.display_url = update.document.data().metadata.display_url; tab.info.loading_task.reset(); - tab.document = std::move( update.document ); - tab.layout.reset(); + const auto dimensions = screen_->size(); + tab.view.emplace( std::move( update.document ), + std::move( snapshot ), + text_, + ScreenSize { dimensions.rows - 2, dimensions.columns } ); + if ( active_ == update.tab ) { + prefix_.reset(); + notice_.clear(); + } tab.failure.reset(); + tab.copy_request.reset(); + tab.copy_feedback.clear(); + dirty_ = true; + } + + void apply( CopyResult update, StepResult& ) + { + const auto found = std::ranges::find_if( + tabs_, [&update]( const auto& entry ) { return entry.second.copy_request == update.request; } ); + // Superseded requests, replaced documents, closed tabs and duplicate results + // have no pending request; they cannot replace the current operation's feedback. + if ( found == tabs_.end() ) { + return; + } + auto& tab = found->second; + tab.copy_request.reset(); + switch ( update.status ) { + case CopyStatus::Confirmed: + tab.copy_feedback = "Copied"; + break; + case CopyStatus::Dispatched: + tab.copy_feedback = "Copy request sent; clipboard acceptance unconfirmed"; + break; + case CopyStatus::Unavailable: + tab.copy_feedback = "Clipboard unavailable; disable mouse capture for terminal selection"; + break; + case CopyStatus::Failed: + tab.copy_feedback = "Copy failed | y retry"; + break; + } + if ( !update.summary.empty() ) { + tab.copy_feedback += ": " + update.summary; + } dirty_ = true; } - void apply( ActionFailed update, StepResult& ) + void apply( ActionFailed update, StepResult& result ) { + const auto copy = std::ranges::find_if( + tabs_, [&update]( const auto& entry ) { return entry.second.copy_request == update.request; } ); + if ( copy != tabs_.end() ) { + apply( CopyResult { update.request, CopyStatus::Failed, std::move( update.summary ) }, result ); + return; + } if ( !update.tab && exit_request_ == update.request ) { exit_request_.reset(); dirty_ = true; @@ -185,13 +248,37 @@ public: dirty_ = true; } - // These messages require document-view/editor state, which this backend stage - // does not implement. Returning ownership keeps the incomplete boundary explicit. + // Incremental updates and form editing still require the later editing layer. void apply( UpdateDocument update, StepResult& result ) { result.unhandled_updates.emplace_back( std::move( update ) ); } - void apply( LocateView update, StepResult& result ) - { result.unhandled_updates.emplace_back( std::move( update ) ); } + void apply( LocateView update, StepResult& ) + { + const auto found = tabs_.find( update.scope.tab ); + // A late anchor request must never move another tab/document revision. + if ( found == tabs_.end() || !found->second.view || found->second.view->snapshot().scope != update.scope ) { + return; + } + auto& view = *found->second.view; + const auto dimensions = screen_->size(); + view.resize( { dimensions.rows - 2, dimensions.columns } ); + std::optional point; + if ( const auto* name = std::get_if( &update.target ) ) { + const auto& anchors = view.document().data().anchors; + const auto anchor = std::ranges::find( anchors, *name, &Anchor::name ); + if ( anchor != anchors.end() ) { + point = std::visit( []( const auto& value ) -> DocumentPoint { return value; }, anchor->point ); + } + } else { + point = std::get( update.target ); + } + const bool located = point && view.locate( *point ); + if ( active_ == update.scope.tab ) { + prefix_.reset(); + notice_ = located ? L"" : L"Location not found"; + } + dirty_ = true; + } void apply( FormFeedback update, StepResult& result ) { result.unhandled_updates.emplace_back( std::move( update ) ); } @@ -210,81 +297,352 @@ public: return count; } + detail::DocumentView* active_view() + { + if ( !active_ ) { + return nullptr; + } + const auto found = tabs_.find( *active_ ); + const auto dimensions = screen_->size(); + // Selection/copy/cancel still address the active document in compact mode. + if ( found == tabs_.end() || !found->second.view ) { + return nullptr; + } + auto& view = *found->second.view; + view.resize( { dimensions.rows - 2, dimensions.columns } ); + return &view; + } + + void move( detail::ViewMotion motion ) + { + const auto dimensions = screen_->size(); + if ( dimensions.rows < 3 || dimensions.columns < 1 ) { + return; // No body rows exist for a visual-row/page motion. + } + if ( auto* view = active_view() ) { + view->move( motion ); + tabs_.at( view->snapshot().scope.tab ).copy_feedback.clear(); + notice_.clear(); + dirty_ = true; + } + } + + void stop_drag() + { + if ( auto* view = active_view() ) { + view->stop_drag(); + } + } + + void copy_selection() + { + auto* view = active_view(); + if ( !view ) { + return; + } + auto selected = view->selected_text(); + if ( !selected || selected->empty() ) { + notice_ = selected ? L"Selection is empty" : L"No selection | v select"; + dirty_ = true; + return; + } + const RequestId request { next_request_++ }; + const auto& snapshot = view->snapshot(); + actions_.emplace_back( + CopySelection { request, snapshot.scope, snapshot.draft_revision, std::move( *selected ) } ); + auto& tab = tabs_.at( snapshot.scope.tab ); + tab.copy_request = request; + tab.copy_feedback = "Copy pending"; + notice_.clear(); + dirty_ = true; + } + + void expire_prefix() + { + if ( prefix_ && Clock::now() >= prefix_->deadline ) { + prefix_.reset(); + dirty_ = true; + } + } + + void browse_text( char32_t character ) + { + using Motion = detail::ViewMotion; + if ( prefix_ ) { + const auto prefix = std::exchange( prefix_, std::nullopt )->character; + dirty_ = true; + if ( prefix == U'g' && character == U'g' ) { + move( Motion::DocumentStart ); + } else if ( prefix == U'z' && character == U'h' ) { + move( Motion::PanLeft ); + } else if ( prefix == U'z' && character == U'l' ) { + move( Motion::PanRight ); + } + // A mismatched sequence is consumed; gq must not turn into a quit action. + return; + } + switch ( character ) { + case U'h': + move( Motion::Left ); + break; + case U'j': + move( Motion::Down ); + break; + case U'k': + move( Motion::Up ); + break; + case U'l': + move( Motion::Right ); + break; + case U'w': + move( Motion::NextWord ); + break; + case U'b': + move( Motion::PreviousWord ); + break; + case U'e': + move( Motion::WordEnd ); + break; + case U'G': + move( Motion::DocumentEnd ); + break; + case U'g': + case U'z': + prefix_ = KeyPrefix { character, Clock::now() + std::chrono::seconds( 1 ) }; + dirty_ = true; + break; + case U'v': + if ( auto* view = active_view(); view && !view->snapshot().selection ) { + view->begin_selection(); + tabs_.at( view->snapshot().scope.tab ).copy_feedback.clear(); + notice_.clear(); + dirty_ = true; + } + break; + case U'y': + copy_selection(); + break; + case U' ': { + auto* view = active_view(); + if ( view ) { + const auto target = view->focused_target(); + // Selection owns Space; browse mode reserves control Space for activation. + if ( view->snapshot().selection || !target || !std::holds_alternative( *target ) ) { + move( Motion::PageDown ); + } + } + break; + } + case U'q': { + const auto* view = active_view(); + if ( !view || !view->snapshot().selection ) { + request_exit(); + } + break; + } + default: + break; + } + } + + void browse_key( const Key& key ) + { + using Motion = detail::ViewMotion; + if ( key.code == KeyCode::Escape ) { + // A pending prefix is the top input layer; one Esc cancels only that layer. + if ( !prefix_ ) { + if ( auto* view = active_view() ) { + view->cancel_selection(); + tabs_.at( view->snapshot().scope.tab ).copy_feedback.clear(); + } + } + prefix_.reset(); + notice_.clear(); + dirty_ = true; + return; + } + if ( prefix_ ) { + // Ctrl+C cancels the prefix first; no key falls through into another action. + prefix_.reset(); + dirty_ = true; + return; + } + if ( key.modifiers == Modifiers { .control = true } && key.code == KeyCode::Character ) { + switch ( key.character ) { + case U'c': + if ( auto* view = active_view(); view && view->snapshot().selection ) { + view->cancel_selection(); + tabs_.at( view->snapshot().scope.tab ).copy_feedback.clear(); + notice_.clear(); + dirty_ = true; + } else { + request_exit(); + } + break; + case U'u': + move( Motion::HalfPageUp ); + break; + case U'd': + move( Motion::HalfPageDown ); + break; + case U'z': + notice_ = L"Suspend is unavailable"; + dirty_ = true; + break; + default: + break; + } + return; + } + if ( key.modifiers == Modifiers { .alt = true } + && ( key.code == KeyCode::Left || key.code == KeyCode::Right ) ) { + const auto* view = active_view(); + if ( view && view->snapshot().selection ) { + return; // Selection mode does not turn navigation into implicit activation. + } + if ( active_ ) { + const auto found = tabs_.find( *active_ ); + if ( found != tabs_.end() ) { + std::optional version; + if ( found->second.view ) { + version = found->second.view->document().data().version; + } + actions_.emplace_back( + Navigate { RequestId { next_request_++ }, + *active_, + version, + key.code == KeyCode::Left ? NavigationCommand::Back : NavigationCommand::Forward } ); + } + } + return; + } + if ( key.modifiers != Modifiers {} ) { + return; // Modified keys have distinct bindings; do not alias them to arrows. + } + switch ( key.code ) { + case KeyCode::Left: + move( Motion::Left ); + break; + case KeyCode::Right: + move( Motion::Right ); + break; + case KeyCode::Up: + move( Motion::Up ); + break; + case KeyCode::Down: + move( Motion::Down ); + break; + case KeyCode::Home: + move( Motion::LineStart ); + break; + case KeyCode::End: + move( Motion::LineEnd ); + break; + case KeyCode::PageUp: + move( Motion::PageUp ); + break; + case KeyCode::PageDown: + move( Motion::PageDown ); + break; + default: + break; + } + } + + void browse_mouse( const Mouse& mouse ) + { + auto* view = active_view(); + if ( !view ) { + return; + } + const CellPoint point { mouse.position.row - 1, mouse.position.column }; + // Capture owns motion/release outside the body as well, so releasing on the + // header/footer cannot leave a background autoscroll running. + if ( view->dragging() ) { + if ( mouse.released.left ) { + view->release( point ); + } else if ( mouse.motion || mouse.pressed.left ) { + view->drag( point ); + } else if ( mouse.wheel_steps != 0 ) { + view->wheel( mouse.wheel_steps ); + } + dirty_ = true; + return; + } + const auto dimensions = screen_->size(); + if ( point.row < 0 || point.row >= dimensions.rows - 2 || point.column < 0 || point.column >= dimensions.columns + || mouse.modifiers != Modifiers {} ) { + return; + } + if ( mouse.wheel_steps != 0 ) { + prefix_.reset(); + view->wheel( mouse.wheel_steps ); + dirty_ = true; + } else if ( mouse.pressed.left ) { + prefix_.reset(); + view->press( point, Clock::now() ); + tabs_.at( view->snapshot().scope.tab ).copy_feedback.clear(); + notice_.clear(); + dirty_ = true; + } + } + void dispatch( const InputEvent& event, StepResult& result ) { if ( const auto* closed = std::get_if( &event ) ) { result.terminal_closed = *closed; close(); } else if ( std::holds_alternative( event ) ) { + stop_drag(); dirty_ = true; + } else if ( const auto* tick = std::get_if( &event ) ) { + if ( auto* view = active_view() ) { + dirty_ = view->tick( tick->now ) || dirty_; + } } else if ( std::holds_alternative( event ) ) { - // The baseline session is Browse: a paste never executes its text as keys. + stop_drag(); + prefix_.reset(); notice_ = L"Enter an input field before pasting"; dirty_ = true; } else if ( const auto* text = std::get_if( &event ) ) { - if ( text->character == U'q' ) { - request_exit(); - } + stop_drag(); + browse_text( text->character ); } else if ( const auto* key = std::get_if( &event ) ) { - if ( key->code == KeyCode::Character && key->modifiers == Modifiers { .control = true } ) { - switch ( key->character ) { - case U'c': - request_exit(); - break; - case U'z': - notice_ = L"Suspend is unavailable"; - dirty_ = true; - break; - default: - break; - } - } + stop_drag(); + browse_key( *key ); + } else if ( const auto* mouse = std::get_if( &event ) ) { + browse_mouse( *mouse ); } - // Mouse/navigation/editor bindings belong to the upcoming document-view layer. } bool read_input( StepResult& result ) { const auto batch = screen_->read_events( 64 ); for ( const auto& event : batch.events ) { + expire_prefix(); dispatch( event, result ); if ( !screen_ ) { break; } } + expire_prefix(); return batch.consumed || !batch.events.empty(); } - void draw_document( TabState& tab, detail::Frame& frame, ScreenSize dimensions ) - { - // The cached layout belongs to the committed snapshot and terminal width. - // CommitDocument drops it; resizing rebuilds it from logical view anchors. - if ( !tab.layout || tab.layout->columns() != dimensions.columns ) { - tab.layout.emplace( *tab.document, text_, dimensions.columns, tab.view->horizontal_scroll ); - } - const auto& layout = *tab.layout; - const auto anchor = layout.locate( tab.view->viewport_anchor ).value_or( detail::LayoutPoint {} ); - const auto body_rows = dimensions.rows - 2; - const auto first_row = std::min( anchor.row, layout.rows() - 1 ); - layout.append_frame( frame, first_row, { 1, 0 }, { body_rows, dimensions.columns } ); - const auto cursor = layout.locate( tab.view->cursor ); - if ( cursor && cursor->row >= first_row && cursor->row - first_row < static_cast( body_rows ) - && cursor->column >= 0 && cursor->column < dimensions.columns ) { - frame.cursor - = CellPoint { 1 + static_cast( cursor->row - first_row ), static_cast( cursor->column ) }; - } - } - void draw() { detail::Frame frame; const auto dimensions = screen_->size(); // With fewer than three rows, header/body/footer cannot coexist. if ( dimensions.rows < 3 ) { - append_chrome( frame, { 0, 0 }, L"Resize | q quit" ); + const auto* view = active_view(); + append_chrome( frame, + { 0, 0 }, + view && view->snapshot().selection ? L"Resize | Esc cancel selection" : L"Resize | q quit" ); } else { append_chrome( frame, { 0, 0 }, L"Ricochet", { .strong = true } ); - std::wstring_view status = L"Browse | q quit"; + std::wstring_view status = L"Browse | v select | q quit"; + std::string_view copy_feedback; if ( !capabilities_.bracketed_paste ) { status = L"Paste boundaries unavailable; multiline paste may confirm input | q quit"; } @@ -294,9 +652,14 @@ public: if ( active_ ) { const auto found = tabs_.find( *active_ ); if ( found != tabs_.end() ) { - if ( found->second.document ) { - draw_document( found->second, frame, dimensions ); + if ( found->second.view ) { + found->second.view->resize( { dimensions.rows - 2, dimensions.columns } ); + found->second.view->draw( frame, { 1, 0 } ); + if ( found->second.view->snapshot().selection && notice_.empty() ) { + status = L"Select | move extends | y copy | Esc cancel"; + } } + copy_feedback = found->second.copy_feedback; if ( found->second.info.loading_task ) { status = L"Loading | q quit"; } @@ -305,10 +668,25 @@ public: } } } + if ( prefix_ ) { + status = prefix_->character == U'g' ? L"g ... | Esc cancel" : L"z ... | Esc cancel"; + } if ( exit_request_ ) { status = L"Waiting for exit decision"; } - append_chrome( frame, { dimensions.rows - 1, 0 }, status ); + if ( !copy_feedback.empty() && notice_.empty() && !prefix_ && !exit_request_ ) { + int column = 0; + for ( const auto& glyph : text_.analyze( copy_feedback, false, false ).graphemes ) { + if ( glyph.columns > dimensions.columns - column ) { + break; // Provider messages are clipped at a complete grapheme boundary. + } + frame.glyphs.push_back( + { .position = { dimensions.rows - 1, column }, .width = glyph.columns, .text = glyph.display } ); + column += glyph.columns; + } + } else { + append_chrome( frame, { dimensions.rows - 1, 0 }, status ); + } } screen_->draw( frame ); dirty_ = false; @@ -323,11 +701,19 @@ public: return result; } try { + expire_prefix(); const auto received = receive( result ); if ( screen_ ) { const bool input = read_input( result ); if ( screen_ && received == 0 && !input && !dirty_ ) { - const auto closed = screen_->wait( mailbox_->descriptor(), max_wait ); + auto wait = max_wait; + if ( prefix_ ) { + wait = std::min( + wait, + std::max( std::chrono::milliseconds::zero(), + std::chrono::ceil( prefix_->deadline - Clock::now() ) ) ); + } + const auto closed = screen_->wait( mailbox_->descriptor(), wait ); if ( closed ) { dispatch( *closed, result ); } else { @@ -338,6 +724,10 @@ public: } } } + if ( screen_ ) { + // Advance drag dwell even on a quiet terminal or a continuously busy input queue. + dispatch( Tick { Clock::now() }, result ); + } if ( screen_ && dirty_ ) { draw(); } @@ -358,6 +748,7 @@ public: std::vector tab_order_ {}; std::optional active_ {}; std::optional exit_request_ {}; + std::optional prefix_ {}; std::uint64_t next_request_ { 1 }; std::vector actions_ {}; std::wstring notice_ {}; @@ -392,10 +783,10 @@ std::vector Session::take_actions() std::optional Session::snapshot( TabId tab ) const { const auto found = impl_->tabs_.find( tab ); - if ( found == impl_->tabs_.end() ) { + if ( found == impl_->tabs_.end() || !found->second.view ) { return std::nullopt; } - return found->second.view; + return found->second.view->snapshot(); } TerminalCapabilities Session::capabilities() const diff --git a/ricochet/src/tui/text.cc b/ricochet/src/tui/text.cc index 14f0e09..b2c64b8 100644 --- a/ricochet/src/tui/text.cc +++ b/ricochet/src/tui/text.cc @@ -125,10 +125,13 @@ TextAnalysis TextService::analyze( std::string_view utf8, bool line_breaks, bool if ( glyph.word != WordKind::Space ) { if ( glyph.word == previous && glyph.word != WordKind::Ideograph ) { result.words.back().end = glyph.bytes.end; + result.graphemes.back().word_end = false; } else { result.words.push_back( glyph.bytes ); + glyph.word_start = true; } } + glyph.word_end = glyph.word != WordKind::Space; previous = glyph.word; result.graphemes.push_back( std::move( glyph ) ); } diff --git a/ricochet/src/tui/text.hh b/ricochet/src/tui/text.hh index c2d4af9..3c0b103 100644 --- a/ricochet/src/tui/text.hh +++ b/ricochet/src/tui/text.hh @@ -50,6 +50,8 @@ struct Grapheme TextUnitKind kind { TextUnitKind::Glyph }; WordKind word { WordKind::Punctuation }; bool break_after { false }; + bool word_start { false }; + bool word_end { false }; }; struct TextAnalysis -- cgit v1.2.3 From 032b82c13e157a048ac13a540dfd18be9667fe49 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Mon, 26 Oct 2026 20:38:32 +0800 Subject: feat(tui): add object focus traversal and link activation --- ricochet/src/tui/document_view.cc | 22 ++++++++++++++ ricochet/src/tui/document_view.hh | 10 ++++++ ricochet/src/tui/layout.cc | 43 ++++++++++++++++++++++++++ ricochet/src/tui/layout.hh | 15 +++++++++ ricochet/src/tui/session.cc | 64 +++++++++++++++++++++++++++++++++++++-- 5 files changed, 151 insertions(+), 3 deletions(-) (limited to 'ricochet/src/tui') diff --git a/ricochet/src/tui/document_view.cc b/ricochet/src/tui/document_view.cc index ee74e53..13a5d5f 100644 --- a/ricochet/src/tui/document_view.cc +++ b/ricochet/src/tui/document_view.cc @@ -361,6 +361,28 @@ bool DocumentView::locate( const DocumentPoint& point ) std::optional DocumentView::focused_target() const { return layout_.target( snapshot_.cursor ); } +FocusResult DocumentView::focus( bool backward ) +{ + const auto next = layout_.focus( snapshot_.cursor, backward ); + if ( !next ) { + return FocusResult::Empty; + } + stop_drag(); + snapshot_.cursor = next->position; + finish_move( false ); + return next->wrapped ? FocusResult::Wrapped : FocusResult::Moved; +} + +const Link* DocumentView::focused_link() const +{ + const auto target = focused_target(); + if ( !target || !std::holds_alternative( *target ) ) { + return nullptr; + } + // Layout link targets originate from this same immutable document. + return &*std::ranges::find( document_.data().links, std::get( *target ), &Link::id ); +} + void DocumentView::draw( Frame& frame, CellPoint origin ) const { const auto selection = snapshot_.selection ? std::optional( snapshot_.selection->range ) : std::nullopt; diff --git a/ricochet/src/tui/document_view.hh b/ricochet/src/tui/document_view.hh index 587f419..5f5e331 100644 --- a/ricochet/src/tui/document_view.hh +++ b/ricochet/src/tui/document_view.hh @@ -46,6 +46,13 @@ enum class ViewMotion : std::uint8_t PanRight }; +enum class FocusResult : std::uint8_t +{ + Empty, + Moved, + Wrapped +}; + // One tab's reading state. It owns the logical snapshot; screen rows are caches. // Keyboard, mouse and host navigation all use the same layout/source mappings. class DocumentView @@ -70,6 +77,9 @@ public: void wheel( int steps ); bool locate( const DocumentPoint& point ); std::optional focused_target() const; + // Browse/field-editor routing owns mode eligibility; this follows the shared order. + FocusResult focus( bool backward ); + const Link* focused_link() const; void draw( Frame& frame, CellPoint origin ) const; private: diff --git a/ricochet/src/tui/layout.cc b/ricochet/src/tui/layout.cc index e12c8d0..46bd626 100644 --- a/ricochet/src/tui/layout.cc +++ b/ricochet/src/tui/layout.cc @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -565,6 +566,20 @@ DocumentLayout::DocumentLayout( const Document& document, stops_.push_back( index ); } } + std::set omitted; + for ( const auto& control : document.data().controls ) { + if ( control.disabled ) { + omitted.insert( control.id ); + } + } + for ( std::size_t index = 0; index < stops_.size(); ++index ) { + const auto& target = data_.glyphs[stops_[index]].target; + // Skip ordinary text and disabled/previously encountered objects. A link's + // later fragments never create extra Tab stops, including across blocks. + if ( target && omitted.insert( *target ).second ) { + focus_.push_back( { *target, index } ); + } + } } int DocumentLayout::columns() const @@ -750,6 +765,34 @@ const LayoutGlyph& DocumentLayout::cursor_glyph( const DisplayPosition& position std::optional DocumentLayout::target( const DisplayPosition& position ) const { return cursor_glyph( position ).target; } +std::optional DocumentLayout::focus( const DisplayPosition& position, bool backward ) const +{ + if ( focus_.empty() ) { + return std::nullopt; + } + const auto object = target( position ); + const auto current + = std::ranges::find_if( focus_, [&object]( const auto& entry ) { return object == entry.target; } ); + auto origin = reading_position( position ); + // Any fragment of an object uses that object's single place in the focus order. + // Plain text and disabled controls instead start from the current reading stop. + if ( current != focus_.end() ) { + origin = { current->stop, true }; + } + if ( backward ) { + const auto previous = std::find_if( + focus_.rbegin(), focus_.rend(), [&origin]( const auto& entry ) { return entry.stop < origin.index; } ); + const bool wrapped = previous == focus_.rend(); + return FocusStep { stop( wrapped ? focus_.back().stop : previous->stop ), wrapped }; + } + const auto next = std::ranges::find_if( focus_, [&origin]( const auto& entry ) { + // A line-end insertion boundary is before the next stop, not on its glyph. + return entry.stop > origin.index || ( !origin.at_start && entry.stop == origin.index ); + } ); + const bool wrapped = next == focus_.end(); + return FocusStep { stop( wrapped ? focus_.front().stop : next->stop ), wrapped }; +} + std::optional DocumentLayout::cursor_cell( const DisplayPosition& position ) const { const auto& glyph = cursor_glyph( position ); diff --git a/ricochet/src/tui/layout.hh b/ricochet/src/tui/layout.hh index 7e02e76..f5db28c 100644 --- a/ricochet/src/tui/layout.hh +++ b/ricochet/src/tui/layout.hh @@ -48,6 +48,12 @@ struct LayoutHit std::optional target {}; }; +struct FocusStep +{ + DisplayPosition position {}; + bool wrapped { false }; +}; + struct ScrollWindow { BlockId block {}; @@ -118,6 +124,7 @@ public: DisplayPosition line_edge( const DisplayPosition& position, bool end ) const; DocumentRange unit( const DisplayPosition& position ) const; std::optional target( const DisplayPosition& position ) const; + std::optional focus( const DisplayPosition& position, bool backward ) const; std::optional cursor_cell( const DisplayPosition& position ) const; std::vector reveal( const DisplayPosition& position ) const; std::vector pan( const DisplayPosition& position, int direction ) const; @@ -141,9 +148,17 @@ private: const LayoutGlyph& cursor_glyph( const DisplayPosition& position ) const; DisplayPosition stop( std::size_t index ) const; + struct FocusEntry + { + HitTarget target {}; + std::size_t stop { 0 }; + }; + int columns_; LayoutData data_; std::vector stops_ {}; + // First reading stop per enabled object, independent of viewport clipping. + std::vector focus_ {}; }; } // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/session.cc b/ricochet/src/tui/session.cc index 069c938..f54d382 100644 --- a/ricochet/src/tui/session.cc +++ b/ricochet/src/tui/session.cc @@ -334,6 +334,54 @@ public: } } + void focus( bool backward ) + { + const auto dimensions = screen_->size(); + if ( dimensions.rows < 3 || dimensions.columns < 1 ) { + return; // Object positioning requires a visible document region. + } + auto* view = active_view(); + if ( !view || view->snapshot().selection ) { + return; // Tab must not move the cursor or extend/cancel an active selection. + } + const auto result = view->focus( backward ); + switch ( result ) { + case detail::FocusResult::Empty: + notice_ = L"No focusable links or controls"; + break; + case detail::FocusResult::Moved: + notice_.clear(); + break; + case detail::FocusResult::Wrapped: + notice_ = backward ? L"Focus wrapped to last object" : L"Focus wrapped to first object"; + break; + } + tabs_.at( view->snapshot().scope.tab ).copy_feedback.clear(); + dirty_ = true; + } + + void activate_link() + { + auto* view = active_view(); + if ( !view || view->snapshot().selection ) { + return; // Selection mode consumes activation without navigating. + } + const auto* link = view->focused_link(); + if ( !link ) { + return; // Plain text and controls do not produce link navigation requests. + } + const RequestId request { next_request_++ }; + const auto source = view->snapshot().scope; + actions_.emplace_back( OpenLink { request, source, link->id, link->target, OpenTarget::CurrentTab } ); + auto& tab = tabs_.at( source.tab ); + // Correlate rejection even when the host fails before NavigationStarted. + tab.navigation = request; + tab.failure.reset(); + tab.copy_feedback.clear(); + notice_.clear(); + dirty_ = true; + } + void copy_selection() { auto* view = active_view(); @@ -516,10 +564,18 @@ public: } return; } + if ( key.code == KeyCode::Tab + && ( key.modifiers == Modifiers {} || key.modifiers == Modifiers { .shift = true } ) ) { + focus( key.modifiers.shift ); + return; + } if ( key.modifiers != Modifiers {} ) { return; // Modified keys have distinct bindings; do not alias them to arrows. } switch ( key.code ) { + case KeyCode::Enter: + activate_link(); + break; case KeyCode::Left: move( Motion::Left ); break; @@ -646,9 +702,6 @@ public: if ( !capabilities_.bracketed_paste ) { status = L"Paste boundaries unavailable; multiline paste may confirm input | q quit"; } - if ( !notice_.empty() ) { - status = notice_; - } if ( active_ ) { const auto found = tabs_.find( *active_ ); if ( found != tabs_.end() ) { @@ -668,6 +721,11 @@ public: } } } + // Immediate input feedback (including focus wrap) must remain visible while + // the page has a background navigation status. + if ( !notice_.empty() ) { + status = notice_; + } if ( prefix_ ) { status = prefix_->character == U'g' ? L"g ... | Esc cancel" : L"z ... | Esc cancel"; } -- cgit v1.2.3 From e138e537bfb18a48391a973723940eec544dd8e1 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Mon, 26 Oct 2026 21:27:00 +0800 Subject: feat(tui): add reusable text input component --- ricochet/src/tui/CMakeLists.txt | 2 +- ricochet/src/tui/editor.cc | 629 ++++++++++++++++++++++++++++++++++++++++ ricochet/src/tui/editor.hh | 169 +++++++++++ ricochet/src/tui/text.cc | 20 ++ ricochet/src/tui/text.hh | 1 + 5 files changed, 820 insertions(+), 1 deletion(-) create mode 100644 ricochet/src/tui/editor.cc create mode 100644 ricochet/src/tui/editor.hh (limited to 'ricochet/src/tui') diff --git a/ricochet/src/tui/CMakeLists.txt b/ricochet/src/tui/CMakeLists.txt index 98dcee2..27820e8 100644 --- a/ricochet/src/tui/CMakeLists.txt +++ b/ricochet/src/tui/CMakeLists.txt @@ -4,7 +4,7 @@ find_package(Threads REQUIRED) # ICU 76.1 supplies UTF-8 grapheme/line boundaries and Unicode properties. pkg_check_modules(ICU REQUIRED IMPORTED_TARGET icu-uc>=76.1 icu-i18n>=76.1) -add_library(ricochet_tui STATIC document_text.cc document.cc document_view.cc mailbox.cc screen.cc session.cc text.cc layout.cc) +add_library(ricochet_tui STATIC editor.cc document_text.cc document.cc document_view.cc mailbox.cc screen.cc session.cc text.cc layout.cc) target_include_directories(ricochet_tui PUBLIC ${PROJECT_SOURCE_DIR}/include) target_compile_features(ricochet_tui PUBLIC cxx_std_23) target_link_libraries(ricochet_tui PRIVATE PkgConfig::NCURSESW PkgConfig::ICU Threads::Threads) diff --git a/ricochet/src/tui/editor.cc b/ricochet/src/tui/editor.cc new file mode 100644 index 0000000..aa0545b --- /dev/null +++ b/ricochet/src/tui/editor.cc @@ -0,0 +1,629 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "editor.hh" + +#include +#include +#include + +namespace ricochet::tui::detail { +namespace { + +ScreenSize editor_size( ScreenSize viewport ) +{ return { std::max( 1, viewport.rows ), std::max( 1, viewport.columns ) }; } + +} // namespace + +TextEditor::TextEditor( std::string value, EditorOptions options, const TextService& text, ScreenSize viewport ) + : options_( options ), text_( text ), viewport_( editor_size( viewport ) ) +{ + state_.value = std::move( value ); + state_.cursor = state_.value.size(); + analyze(); + desired_column_ = carets_.back().column; + reveal(); +} + +const std::string& TextEditor::value() const +{ return state_.value; } +std::uint64_t TextEditor::revision() const +{ return revision_; } +std::size_t TextEditor::cursor() const +{ return state_.cursor; } + +ByteRange TextEditor::selection() const +{ + const auto anchor = state_.anchor.value_or( state_.cursor ); + return { std::min( anchor, state_.cursor ), std::max( anchor, state_.cursor ) }; +} + +std::optional TextEditor::copy_selection() +{ + killing_ = false; + prefix_.reset(); + const auto range = selection(); + if ( options_.kind == EditorKind::Password || range.start == range.end ) { + return std::nullopt; + } + return state_.value.substr( range.start, range.end - range.start ); +} + +std::optional TextEditor::prefix_deadline() const +{ return prefix_; } + +std::string TextEditor::normalize( std::string_view value ) const +{ + std::string result; + result.reserve( value.size() ); + for ( std::size_t index = 0; index < value.size(); ++index ) { + const auto character = value[index]; + if ( character == '\r' ) { + if ( index + 1 < value.size() && value[index + 1] == '\n' ) { + ++index; + } + result += options_.kind == EditorKind::MultiLine ? '\n' : ' '; + } else if ( character == '\n' && options_.kind != EditorKind::MultiLine ) { + result += ' '; + } else { + result += character; + } + } + return result; +} + +std::size_t TextEditor::unit_index() const +{ + return static_cast( + std::ranges::lower_bound( + analysis_.graphemes, state_.cursor, {}, []( const auto& glyph ) { return glyph.bytes.start; } ) + - analysis_.graphemes.begin() ); +} + +std::size_t TextEditor::boundary( std::size_t index ) const +{ return index == analysis_.graphemes.size() ? state_.value.size() : analysis_.graphemes[index].bytes.start; } + +std::size_t TextEditor::line_start() const +{ + const auto newline + = std::find_if( analysis_.graphemes.rbegin(), analysis_.graphemes.rend(), [this]( const auto& unit ) { + return unit.kind == TextUnitKind::LineBreak && unit.bytes.end <= state_.cursor; + } ); + return newline == analysis_.graphemes.rend() ? 0 : newline->bytes.end; +} + +std::size_t TextEditor::line_end() const +{ + const auto newline = std::ranges::find_if( analysis_.graphemes, [this]( const auto& unit ) { + return unit.kind == TextUnitKind::LineBreak && unit.bytes.start >= state_.cursor; + } ); + return newline == analysis_.graphemes.end() ? state_.value.size() : newline->bytes.start; +} + +void TextEditor::analyze() +{ + analysis_ = text_.analyze( state_.value, options_.kind == EditorKind::MultiLine, true ); + layout(); +} + +void TextEditor::layout() +{ + glyphs_.clear(); + carets_.assign( analysis_.graphemes.size() + 1, {} ); + Point point; + for ( std::size_t index = 0; index < analysis_.graphemes.size(); ++index ) { + const auto& unit = analysis_.graphemes[index]; + const bool password = options_.kind == EditorKind::Password; + if ( unit.kind == TextUnitKind::LineBreak && !password ) { + // A hard break after a full row stays on that row. Reuse the preceding + // complete glyph's cell for its insertion cursor instead of wrapping twice. + carets_[index] = point.column == viewport_.columns ? glyphs_.back().point : point; + glyphs_.push_back( { point, 0 } ); + ++point.row; + point.column = 0; + } else { + const auto width_at = [&]( std::int64_t column ) { + const auto width = password ? 1 + : unit.kind == TextUnitKind::Tab ? 8 - static_cast( column % 8 ) + : unit.columns; + return options_.kind == EditorKind::MultiLine ? std::min( width, viewport_.columns ) : width; + }; + int width = width_at( point.column ); + if ( options_.kind == EditorKind::MultiLine && point.column > 0 + && point.column + width > viewport_.columns ) { + ++point.row; + point.column = 0; + width = width_at( 0 ); + } + carets_[index] = point; + glyphs_.push_back( { point, width } ); + point.column += width; + } + carets_[index + 1] = point; + } + // A full final soft row needs a real insertion cell after its final grapheme. + if ( options_.kind == EditorKind::MultiLine && point.column == viewport_.columns ) { + carets_.back() = { point.row + 1, 0 }; + } +} + +void TextEditor::reveal() +{ + const auto point = carets_[unit_index()]; + const auto height = static_cast( viewport_.rows ); + const auto rows = carets_.back().row + 1; + top_row_ = std::min( top_row_, rows - std::min( rows, height ) ); + if ( point.row < top_row_ ) { + top_row_ = point.row; + } else if ( point.row - top_row_ >= height ) { + top_row_ = point.row - height + 1; + } + if ( options_.kind == EditorKind::MultiLine ) { + left_column_ = 0; + } else { + left_column_ = std::min( left_column_, point.column ); + left_column_ = std::max( left_column_, point.column - viewport_.columns + 1 ); + } +} + +void TextEditor::resize( ScreenSize viewport ) +{ + const auto next = editor_size( viewport ); + if ( next == viewport_ ) { + return; + } + viewport_ = next; + layout(); + desired_column_ = carets_[unit_index()].column; + reveal(); +} + +std::size_t TextEditor::nearest( Point point ) const +{ + std::size_t chosen = 0; + auto distance = std::pair { std::numeric_limits::max(), std::numeric_limits::max() }; + for ( std::size_t index = 0; index < carets_.size(); ++index ) { + const auto& candidate = carets_[index]; + const auto delta = std::pair { + candidate.row > point.row ? candidate.row - point.row : point.row - candidate.row, + candidate.column > point.column ? candidate.column - point.column : point.column - candidate.column }; + if ( delta < distance ) { + chosen = index; + distance = delta; + } + } + return boundary( chosen ); +} + +void TextEditor::move( std::size_t destination, bool extend, bool preserve_column ) +{ + if ( extend || state_.selecting ) { + state_.anchor = state_.anchor.value_or( state_.cursor ); + } else { + state_.anchor.reset(); + } + state_.cursor = destination; + if ( !preserve_column ) { + desired_column_ = carets_[unit_index()].column; + } + reveal(); +} + +void TextEditor::replace( ByteRange range, std::string_view replacement ) +{ + auto next = state_.value; + next.replace( range.start, range.end - range.start, replacement ); + if ( next != state_.value ) { + past_.push_back( state_ ); + future_.clear(); + ++revision_; + } + state_.value = std::move( next ); + state_.cursor = range.start + replacement.size(); + state_.anchor.reset(); + state_.selecting = false; + analyze(); + // Insertion/deletion can join surrounding graphemes. Snap to the next boundary + // in the new text, never retain an offset inside a new combining/ZWJ cluster. + state_.cursor = boundary( unit_index() ); + desired_column_ = carets_[unit_index()].column; + reveal(); +} + +void TextEditor::insert( std::u32string_view input ) +{ + killing_ = false; + prefix_.reset(); + if ( input.empty() ) { + return; // An empty paste must not delete an existing selection. + } + const auto value = normalize( text_.encode( input ) ); + replace( selection(), value ); +} + +void TextEditor::replace_value( std::string value ) +{ + killing_ = false; + prefix_.reset(); + replace( { 0, state_.value.size() }, value ); +} + +void TextEditor::kill( ByteRange range ) +{ + if ( range.start == range.end ) { + return; // Empty kills preserve both the buffer and the current kill chain. + } + auto removed = state_.value.substr( range.start, range.end - range.start ); + if ( !killing_ ) { + killed_ = std::move( removed ); + } else if ( range.end <= state_.cursor ) { + killed_.insert( 0, removed ); + } else { + killed_ += removed; + } + replace( range, {} ); + killing_ = true; +} + +void TextEditor::undo( bool redo ) +{ + auto& source = redo ? future_ : past_; + auto& destination = redo ? past_ : future_; + if ( source.empty() ) { + return; + } + destination.push_back( std::move( state_ ) ); + state_ = std::move( source.back() ); + source.pop_back(); + ++revision_; + analyze(); + desired_column_ = carets_[unit_index()].column; + reveal(); +} + +void TextEditor::execute( EditorCommand command, bool extend ) +{ + prefix_.reset(); + const bool killing = command == EditorCommand::KillToStart || command == EditorCommand::KillToEnd + || command == EditorCommand::KillWord; + killing_ = killing_ && killing; + const auto range = selection(); + auto index = unit_index(); + switch ( command ) { + case EditorCommand::Left: + move( !extend && !state_.selecting && range.start != range.end ? range.start + : boundary( index == 0 ? 0 : index - 1 ), + extend, + false ); + break; + case EditorCommand::Right: + move( !extend && !state_.selecting && range.start != range.end + ? range.end + : boundary( std::min( index + 1, analysis_.graphemes.size() ) ), + extend, + false ); + break; + case EditorCommand::Up: + case EditorCommand::Down: { + if ( options_.kind != EditorKind::MultiLine ) { + break; + } + auto row = carets_[index].row; + row = command == EditorCommand::Up ? ( row == 0 ? 0 : row - 1 ) : std::min( row + 1, carets_.back().row ); + move( nearest( { row, desired_column_ } ), extend, true ); + break; + } + case EditorCommand::LineStart: + move( line_start(), extend, false ); + break; + case EditorCommand::LineEnd: + move( line_end(), extend, false ); + break; + case EditorCommand::PreviousWord: { + const auto word = std::find_if( analysis_.words.rbegin(), analysis_.words.rend(), [this]( const auto& item ) { + return item.start < state_.cursor; + } ); + move( word == analysis_.words.rend() ? 0 : word->start, extend, false ); + break; + } + case EditorCommand::NextWord: { + const auto word + = std::ranges::find_if( analysis_.words, [this]( const auto& item ) { return item.end > state_.cursor; } ); + move( word == analysis_.words.end() ? state_.value.size() : word->end, extend, false ); + break; + } + case EditorCommand::Backspace: + replace( range.start != range.end ? range + : ByteRange { boundary( index == 0 ? 0 : index - 1 ), state_.cursor }, + {} ); + break; + case EditorCommand::Delete: + replace( range.start != range.end + ? range + : ByteRange { state_.cursor, boundary( std::min( index + 1, analysis_.graphemes.size() ) ) }, + {} ); + break; + case EditorCommand::KillToStart: + kill( range.start != range.end ? range : ByteRange { line_start(), state_.cursor } ); + break; + case EditorCommand::KillToEnd: + kill( range.start != range.end ? range : ByteRange { state_.cursor, line_end() } ); + break; + case EditorCommand::KillWord: + while ( index > 0 && analysis_.graphemes[index - 1].word == WordKind::Space ) { + --index; + } + while ( index > 0 && analysis_.graphemes[index - 1].word != WordKind::Space ) { + --index; + } + kill( range.start != range.end ? range : ByteRange { boundary( index ), state_.cursor } ); + break; + case EditorCommand::Yank: + if ( !killed_.empty() ) { + replace( range, killed_ ); + } + break; + case EditorCommand::BeginSelection: + state_.anchor = state_.cursor; + state_.selecting = true; + break; + case EditorCommand::SelectAll: + state_.anchor = 0; + state_.cursor = state_.value.size(); + state_.selecting = false; + desired_column_ = carets_.back().column; + reveal(); + break; + case EditorCommand::CancelSelection: + state_.anchor.reset(); + state_.selecting = false; + break; + case EditorCommand::Clear: + replace( { 0, state_.value.size() }, {} ); + break; + case EditorCommand::Newline: + if ( options_.kind == EditorKind::MultiLine ) { + replace( range, "\n" ); + } + break; + case EditorCommand::Undo: + undo( false ); + break; + case EditorCommand::Redo: + undo( true ); + break; + } +} + +void TextEditor::place( CellPoint point, bool extend ) +{ + prefix_.reset(); + killing_ = false; + // The owner routes body clicks/dragging; outside drag coordinates clamp to this viewport. + const Point location { top_row_ + static_cast( std::clamp( point.row, 0, viewport_.rows - 1 ) ), + left_column_ + std::clamp( point.column, 0, viewport_.columns - 1 ) }; + state_.selecting = false; + move( nearest( location ), extend, false ); +} + +EditorIntent TextEditor::key( const Key& input, std::chrono::steady_clock::time_point now ) +{ + if ( prefix_ ) { + prefix_.reset(); + if ( input.code == KeyCode::Character && input.modifiers == Modifiers { .control = true } + && input.character == U'u' ) { + execute( EditorCommand::Undo ); + } + return EditorIntent::Consumed; // Mismatches never execute a second command. + } + const bool kill_key = input.code == KeyCode::Character && input.modifiers == Modifiers { .control = true } + && ( input.character == U'u' || input.character == U'k' || input.character == U'w' ); + killing_ = killing_ && kill_key; + if ( input.code == KeyCode::Character && input.modifiers == Modifiers { .control = true } ) { + switch ( input.character ) { + case U'b': + execute( EditorCommand::Left ); + break; + case U'f': + execute( EditorCommand::Right ); + break; + case U'p': + case U'n': + if ( options_.kind == EditorKind::SingleLine && options_.history ) { + return input.character == U'p' ? EditorIntent::HistoryPrevious : EditorIntent::HistoryNext; + } + execute( input.character == U'p' ? EditorCommand::Up : EditorCommand::Down ); + break; + case U'a': + execute( EditorCommand::LineStart ); + break; + case U'e': + execute( EditorCommand::LineEnd ); + break; + case U'd': + execute( EditorCommand::Delete ); + break; + case U'u': + execute( EditorCommand::KillToStart ); + break; + case U'k': + execute( EditorCommand::KillToEnd ); + break; + case U'w': + execute( EditorCommand::KillWord ); + break; + case U'y': + execute( EditorCommand::Yank ); + break; + case U'_': + execute( EditorCommand::Undo ); + break; + case U'x': + prefix_ = now + std::chrono::seconds( 1 ); + break; + case U'l': + return EditorIntent::Redraw; + case U'c': + return EditorIntent::Cancel; + default: + return EditorIntent::Unhandled; + } + return EditorIntent::Consumed; + } + if ( input.code == KeyCode::Character && input.modifiers == Modifiers { .alt = true } ) { + switch ( input.character ) { + case U'b': + execute( EditorCommand::PreviousWord ); + return EditorIntent::Consumed; + case U'f': + execute( EditorCommand::NextWord ); + return EditorIntent::Consumed; + default: + return EditorIntent::Unhandled; + } + } + if ( input.modifiers != Modifiers {} && input.modifiers != Modifiers { .shift = true } ) { + return EditorIntent::Unhandled; + } + switch ( input.code ) { + case KeyCode::Left: + execute( EditorCommand::Left, input.modifiers.shift ); + break; + case KeyCode::Right: + execute( EditorCommand::Right, input.modifiers.shift ); + break; + case KeyCode::Up: + case KeyCode::Down: + if ( options_.kind == EditorKind::SingleLine && options_.history && !input.modifiers.shift ) { + return input.code == KeyCode::Up ? EditorIntent::HistoryPrevious : EditorIntent::HistoryNext; + } + execute( input.code == KeyCode::Up ? EditorCommand::Up : EditorCommand::Down, input.modifiers.shift ); + break; + case KeyCode::Home: + execute( EditorCommand::LineStart, input.modifiers.shift ); + break; + case KeyCode::End: + execute( EditorCommand::LineEnd, input.modifiers.shift ); + break; + case KeyCode::Tab: + return input.modifiers.shift ? EditorIntent::BackTab : EditorIntent::Tab; + default: + if ( input.modifiers.shift ) { + return EditorIntent::Unhandled; + } + switch ( input.code ) { + case KeyCode::Backspace: + execute( EditorCommand::Backspace ); + break; + case KeyCode::Delete: + execute( EditorCommand::Delete ); + break; + case KeyCode::Enter: + return EditorIntent::Enter; + case KeyCode::Escape: + return EditorIntent::Escape; + case KeyCode::Function: + return input.function == 10 ? EditorIntent::Menu : EditorIntent::Unhandled; + default: + return EditorIntent::Unhandled; + } + break; + } + return EditorIntent::Consumed; +} + +EditorIntent TextEditor::handle( const InputEvent& event, std::chrono::steady_clock::time_point now ) +{ + if ( const auto* tick = std::get_if( &event ) ) { + now = tick->now; + } + if ( prefix_ && now >= *prefix_ ) { + prefix_.reset(); + } + if ( const auto* input = std::get_if( &event ) ) { + return key( *input, now ); + } + if ( const auto* input = std::get_if( &event ) ) { + killing_ = false; + if ( prefix_ ) { + prefix_.reset(); + } else { + insert( std::u32string_view( &input->character, 1 ) ); + } + return EditorIntent::Consumed; + } + if ( const auto* paste = std::get_if( &event ) ) { + insert( paste->text ); + return EditorIntent::Consumed; + } + if ( std::holds_alternative( event ) ) { + return EditorIntent::Consumed; + } + return EditorIntent::Unhandled; +} + +void TextEditor::draw( Frame& frame, CellPoint origin ) const +{ + // Fields can overlay an already painted document. Clear their entire region so + // shortening the value cannot expose the old field text beneath the editor. + for ( int row = 0; row < viewport_.rows; ++row ) { + for ( int column = 0; column < viewport_.columns; ++column ) { + frame.glyphs.push_back( { .position = { origin.row + row, origin.column + column }, .text = L" " } ); + } + } + const auto selected = selection(); + const auto cursor_point = carets_[unit_index()]; + for ( std::size_t index = 0; index < glyphs_.size(); ++index ) { + const auto& glyph = glyphs_[index]; + if ( glyph.point.row < top_row_ || glyph.point.row - top_row_ >= static_cast( viewport_.rows ) ) { + continue; + } + const auto& unit = analysis_.graphemes[index]; + const bool password = options_.kind == EditorKind::Password; + const bool selected_unit = unit.bytes.start < selected.end && selected.start < unit.bytes.end; + const int row = origin.row + static_cast( glyph.point.row - top_row_ ); + const auto column = glyph.point.column - left_column_; + const bool at_cursor = cursor_point.row == glyph.point.row && cursor_point.column == glyph.point.column; + if ( unit.kind == TextUnitKind::Tab && !password ) { + for ( auto cell = std::max( 0, column ); + cell < std::min( viewport_.columns, column + glyph.columns ); + ++cell ) { + frame.glyphs.push_back( { .position = { row, origin.column + static_cast( cell ) }, + .text = L" ", + .selected = selected_unit, + .cursor = at_cursor && cell == column } ); + } + } else { + const bool newline = unit.kind == TextUnitKind::LineBreak; + const int width = newline ? 1 : glyph.columns; + if ( column < 0 || column + width > viewport_.columns || ( newline && !selected_unit ) ) { + continue; + } + const auto display = password ? L"*" : newline ? L" " : glyph.columns < unit.columns ? L"?" : unit.display; + frame.glyphs.push_back( { .position = { row, origin.column + static_cast( column ) }, + .width = width, + .text = display, + .selected = selected_unit, + .cursor = at_cursor } ); + } + } + frame.cursor = CellPoint { origin.row + static_cast( cursor_point.row - top_row_ ), + origin.column + static_cast( cursor_point.column - left_column_ ) }; +} + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/editor.hh b/ricochet/src/tui/editor.hh new file mode 100644 index 0000000..457b0ca --- /dev/null +++ b/ricochet/src/tui/editor.hh @@ -0,0 +1,169 @@ +/* + * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "paint.hh" +#include "text.hh" + +#include +#include + +namespace ricochet::tui::detail { + +enum class EditorKind : std::uint8_t +{ + SingleLine, + MultiLine, + Password +}; + +struct EditorOptions +{ + EditorKind kind { EditorKind::SingleLine }; + // The owner supplies history; password and multiline editors never request it. + bool history { false }; +}; + +enum class EditorCommand : std::uint8_t +{ + Left, + Right, + Up, + Down, + LineStart, + LineEnd, + PreviousWord, + NextWord, + Backspace, + Delete, + KillToStart, + KillToEnd, + KillWord, + Yank, + BeginSelection, + SelectAll, + CancelSelection, + Clear, + Newline, + Undo, + Redo +}; + +// Enter/Tab/Escape are context decisions, never implicit submit/finish operations. +// The owner may translate Enter into Newline for a multiline field. +// Unhandled keys stay with the owning editor context, never fall through to Browse. +enum class EditorIntent : std::uint8_t +{ + Consumed, + Unhandled, + Enter, + Tab, + BackTab, + Escape, + Cancel, + Menu, + Redraw, + HistoryPrevious, + HistoryNext +}; + +// One editing session. Owners recreate it when changing fields; its text, undo +// history and kill buffer are never shared with another editor or a view snapshot. +class TextEditor +{ +public: + TextEditor( std::string value, EditorOptions options, const TextService& text, ScreenSize viewport ); + TextEditor( const TextEditor& ) = delete; + TextEditor& operator=( const TextEditor& ) = delete; + TextEditor( TextEditor&& ) = delete; + TextEditor& operator=( TextEditor&& ) = delete; + ~TextEditor() = default; + + // Business value for the owning field; rendering and copying use the methods below. + const std::string& value() const; + std::uint64_t revision() const; + std::size_t cursor() const; + ByteRange selection() const; + std::optional copy_selection(); + std::optional prefix_deadline() const; + + void resize( ScreenSize viewport ); + void insert( std::u32string_view input ); + // Host history replacement is one undoable edit, not a new editing session. + void replace_value( std::string value ); + void execute( EditorCommand command, bool extend = false ); + EditorIntent handle( const InputEvent& event, + std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now() ); + // Region-local mouse positioning, with extend=true while selecting/dragging. + void place( CellPoint point, bool extend ); + void draw( Frame& frame, CellPoint origin ) const; + +private: + struct State + { + std::string value {}; + std::size_t cursor { 0 }; + std::optional anchor {}; + bool selecting { false }; + }; + struct Point + { + std::size_t row { 0 }; + std::int64_t column { 0 }; + }; + struct Glyph + { + Point point {}; + int columns { 0 }; + }; + + std::string normalize( std::string_view value ) const; + std::size_t unit_index() const; + std::size_t boundary( std::size_t index ) const; + std::size_t line_start() const; + std::size_t line_end() const; + std::size_t nearest( Point point ) const; + void analyze(); + void layout(); + void reveal(); + void move( std::size_t destination, bool extend, bool preserve_column ); + void replace( ByteRange range, std::string_view replacement ); + void kill( ByteRange range ); + void undo( bool redo ); + EditorIntent key( const Key& key, std::chrono::steady_clock::time_point now ); + + EditorOptions options_; + const TextService& text_; + ScreenSize viewport_; + State state_ {}; + TextAnalysis analysis_ {}; + std::vector glyphs_ {}; + std::vector carets_ {}; + std::size_t top_row_ { 0 }; + std::int64_t left_column_ { 0 }; + std::int64_t desired_column_ { 0 }; + std::vector past_ {}; + std::vector future_ {}; + std::string killed_ {}; + bool killing_ { false }; + std::uint64_t revision_ { 0 }; + std::optional prefix_ {}; +}; + +} // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/text.cc b/ricochet/src/tui/text.cc index b2c64b8..95b324b 100644 --- a/ricochet/src/tui/text.cc +++ b/ricochet/src/tui/text.cc @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -65,6 +66,25 @@ WordKind word_kind( UChar32 codepoint ) TextService::TextService( std::size_t glyph_capacity ) : glyph_capacity_( glyph_capacity ) {} +std::string TextService::encode( std::u32string_view input ) const +{ + // ICU's UTF-32 conversion takes a signed 32-bit length, like its break iterator. + if ( input.size() > INT32_MAX ) { + throw std::length_error( "Input exceeds ICU conversion length capacity" ); + } + const std::vector codepoints( input.begin(), input.end() ); + // fromUTF32 requires a non-null pointer even for a zero-length input. + const UChar32 empty = 0; + const auto converted = icu::UnicodeString::fromUTF32( codepoints.empty() ? &empty : codepoints.data(), + static_cast( codepoints.size() ) ); + if ( converted.isBogus() ) { + throw std::runtime_error( "ICU could not convert editor input" ); + } + std::string result; + converted.toUTF8String( result ); + return result; +} + TextAnalysis TextService::analyze( std::string_view utf8, bool line_breaks, bool tabs ) const { // ICU BreakIterator exposes int32_t native offsets even with a UTF-8 UText. diff --git a/ricochet/src/tui/text.hh b/ricochet/src/tui/text.hh index 3c0b103..eb0a2bb 100644 --- a/ricochet/src/tui/text.hh +++ b/ricochet/src/tui/text.hh @@ -69,6 +69,7 @@ class TextService public: explicit TextService( std::size_t glyph_capacity ); TextAnalysis analyze( std::string_view utf8, bool line_breaks, bool tabs ) const; + std::string encode( std::u32string_view input ) const; private: std::size_t glyph_capacity_; -- cgit v1.2.3 From bdefdb301db843e87aee8c6c35808d295bb66ee5 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Mon, 26 Oct 2026 23:25:13 +0800 Subject: feat(tui): integrate address input and navigation requests --- ricochet/src/tui/screen.cc | 13 ++- ricochet/src/tui/screen.hh | 2 +- ricochet/src/tui/session.cc | 220 ++++++++++++++++++++++++++++++++++++++++++-- ricochet/src/tui/text.cc | 2 + ricochet/src/tui/text.hh | 2 + 5 files changed, 228 insertions(+), 11 deletions(-) (limited to 'ricochet/src/tui') diff --git a/ricochet/src/tui/screen.cc b/ricochet/src/tui/screen.cc index 99d4e36..2bb9c85 100644 --- a/ricochet/src/tui/screen.cc +++ b/ricochet/src/tui/screen.cc @@ -513,7 +513,7 @@ public: return std::nullopt; } - void draw( const Frame& frame ) const + void draw( const Frame& frame, bool redraw ) const { const auto dimensions = size(); if ( werase( stdscr ) == ERR ) { @@ -550,7 +550,12 @@ public: } else { curs_set( 0 ); } - if ( wnoutrefresh( stdscr ) == ERR || doupdate() == ERR ) { + // An explicit Ctrl+L repairs the physical screen, not just our virtual frame. + // clearok is consumed by wrefresh; ordinary frames retain batched updates. + if ( redraw ) { + clearok( stdscr, TRUE ); + } + if ( redraw ? wrefresh( stdscr ) == ERR : ( wnoutrefresh( stdscr ) == ERR || doupdate() == ERR ) ) { throw std::runtime_error( "ncurses screen refresh failed" ); } } @@ -590,7 +595,7 @@ InputBatch Screen::read_events( std::size_t limit ) std::optional Screen::wait( int wake_fd, std::chrono::milliseconds max_wait ) { return impl_->wait( wake_fd, max_wait ); } -void Screen::draw( const Frame& frame ) -{ impl_->draw( frame ); } +void Screen::draw( const Frame& frame, bool redraw ) +{ impl_->draw( frame, redraw ); } } // namespace ricochet::tui::detail diff --git a/ricochet/src/tui/screen.hh b/ricochet/src/tui/screen.hh index 9677eb0..0ff1c58 100644 --- a/ricochet/src/tui/screen.hh +++ b/ricochet/src/tui/screen.hh @@ -50,7 +50,7 @@ public: InputBatch read_events( std::size_t limit ); // Wait only polls descriptors; wgetch remains the sole terminal reader. std::optional wait( int wake_fd, std::chrono::milliseconds max_wait ); - void draw( const Frame& frame ); + void draw( const Frame& frame, bool redraw = false ); private: class Impl; diff --git a/ricochet/src/tui/session.cc b/ricochet/src/tui/session.cc index f54d382..09af2ce 100644 --- a/ricochet/src/tui/session.cc +++ b/ricochet/src/tui/session.cc @@ -19,6 +19,7 @@ #include "ricochet/tui/session.hh" #include "document_view.hh" +#include "editor.hh" #include "mailbox.hh" #include "screen.hh" @@ -51,6 +52,35 @@ struct TabState std::string copy_feedback {}; }; +enum class AddressEntry : std::uint8_t +{ + Empty, + Current, + Selected +}; + +int address_label_columns( ScreenSize dimensions ) +{ return std::min( 5, std::max( 0, dimensions.columns - 1 ) ); } + +struct AddressInput +{ + TabId tab; + std::optional restore; + detail::TextEditor editor; + bool dragging { false }; + std::wstring notice {}; + + AddressInput( TabId source, + std::optional snapshot, + std::string value, + const detail::TextService& text, + ScreenSize dimensions ) + : tab( source ) + , restore( std::move( snapshot ) ) + , editor( std::move( value ), {}, text, { 1, dimensions.columns - address_label_columns( dimensions ) } ) + {} +}; + // Only fixed ASCII chrome uses this helper. Document text goes through the // Unicode text service and document layout. void append_chrome( detail::Frame& frame, CellPoint start, std::wstring_view text, TextStyle style = {} ) @@ -78,6 +108,7 @@ public: void close() noexcept { mailbox_->close(); + address_.reset(); screen_.reset(); } @@ -103,6 +134,12 @@ public: void apply( SyncTabs update, StepResult& ) { + // Cancel against the old tab map before a switch/removal destroys its view. + if ( address_ + && ( update.active != address_->tab + || std::ranges::find( update.tabs, address_->tab, &TabInfo::id ) == update.tabs.end() ) ) { + finish_address(); + } if ( active_ != update.active ) { stop_drag(); } @@ -170,6 +207,11 @@ public: std::move( snapshot ), text_, ScreenSize { dimensions.rows - 2, dimensions.columns } ); + if ( address_ && address_->tab == update.tab ) { + // Address editing survives a background commit, but cancellation must now + // return to the newly committed page, never restore the old view snapshot. + address_->restore.reset(); + } if ( active_ == update.tab ) { prefix_.reset(); notice_.clear(); @@ -405,6 +447,144 @@ public: dirty_ = true; } + void open_address( AddressEntry entry ) + { + const auto found = active_ ? tabs_.find( *active_ ) : tabs_.end(); + if ( found == tabs_.end() ) { + notice_ = L"No active tab"; + dirty_ = true; + return; + } + auto& tab = found->second; + if ( tab.view && tab.view->snapshot().selection ) { + return; // Address shortcuts belong to Browse, not the document selection mode. + } + stop_drag(); + const auto snapshot = tab.view ? std::optional( tab.view->snapshot() ) : std::nullopt; + address_.emplace( + tab.info.id, snapshot, entry == AddressEntry::Empty ? "" : tab.info.display_url, text_, screen_->size() ); + if ( entry == AddressEntry::Selected ) { + address_->editor.execute( detail::EditorCommand::SelectAll ); + } + prefix_.reset(); + notice_.clear(); + dirty_ = true; + } + + void finish_address() + { + auto& tab = tabs_.at( address_->tab ); + const auto& restore = address_->restore; + if ( restore && tab.view && tab.view->snapshot().scope == restore->scope + && tab.view->snapshot().draft_revision == restore->draft_revision ) { + // Copy the shared document before emplace destroys the current view. + auto document = tab.view->document(); + const auto dimensions = screen_->size(); + tab.view.emplace( + std::move( document ), *restore, text_, ScreenSize { dimensions.rows - 2, dimensions.columns } ); + } + address_.reset(); + notice_.clear(); + dirty_ = true; + } + + void submit_address() + { + const auto& value = address_->editor.value(); + if ( text_.analyze( value, false, false ).whitespace_only ) { + address_->notice = L"Enter an address | Esc cancel"; + dirty_ = true; + return; + } + const RequestId request { next_request_++ }; + actions_.emplace_back( OpenLocation { request, address_->tab, value, OpenTarget::CurrentTab } ); + auto& tab = tabs_.at( address_->tab ); + // A host rejection may precede NavigationStarted, just as for OpenLink. + tab.navigation = request; + tab.failure.reset(); + tab.copy_feedback.clear(); + finish_address(); + } + + void address_mouse( const Mouse& mouse ) + { + const auto dimensions = screen_->size(); + const auto label = address_label_columns( dimensions ); + const CellPoint point { 0, mouse.position.column - label }; + if ( address_->dragging ) { + if ( mouse.released.left || mouse.motion || mouse.pressed.left ) { + address_->editor.place( point, true ); + address_->dragging = !mouse.released.left; + dirty_ = true; + } + return; + } + if ( mouse.pressed.left && mouse.position.row == 0 && mouse.position.column >= label + && mouse.position.column < dimensions.columns + && ( mouse.modifiers == Modifiers {} || mouse.modifiers == Modifiers { .shift = true } ) ) { + address_->editor.place( point, mouse.modifiers.shift ); + address_->dragging = true; + dirty_ = true; + } + // Clicks and wheel events outside the input never reach the document underneath. + } + + void address_input( const InputEvent& event ) + { + if ( const auto* mouse = std::get_if( &event ) ) { + address_mouse( *mouse ); + return; + } + const auto prefix = address_->editor.prefix_deadline(); + const auto intent = address_->editor.handle( event ); + if ( std::holds_alternative( event ) ) { + dirty_ = dirty_ || prefix != address_->editor.prefix_deadline(); + return; + } + address_->dragging = false; + address_->notice.clear(); + dirty_ = true; + switch ( intent ) { + case detail::EditorIntent::Enter: + submit_address(); + break; + case detail::EditorIntent::Escape: + case detail::EditorIntent::Cancel: + finish_address(); + break; + case detail::EditorIntent::Redraw: + redraw_ = true; + break; + case detail::EditorIntent::Menu: + address_->notice = L"Menu unavailable | Enter open | Esc cancel"; + break; + default: + break; // Tab/history/unbound keys have no second recipient in this mode. + } + } + + void draw_address( detail::Frame& frame, ScreenSize dimensions ) + { + const auto label = address_label_columns( dimensions ); + append_chrome( frame, { 0, 0 }, std::wstring_view( L"URL: " ).substr( 0, label ), { .strong = true } ); + address_->editor.resize( { 1, dimensions.columns - label } ); + address_->editor.draw( frame, { 0, label } ); + if ( dimensions.rows > 1 ) { + append_chrome( frame, { dimensions.rows - 1, 0 }, std::wstring( dimensions.columns, L' ' ) ); + std::wstring_view status + = capabilities_.bracketed_paste + ? L"Address | Enter open | Esc cancel" + : L"Enter open | Esc cancel | Paste boundaries unavailable; multiline paste may confirm"; + if ( !address_->notice.empty() ) { + status = address_->notice; + } + if ( address_->editor.prefix_deadline() ) { + status = L"Ctrl+X ... | Ctrl+U undo | Esc cancel prefix"; + } + append_chrome( frame, { dimensions.rows - 1, 0 }, status ); + } + } + void expire_prefix() { if ( prefix_ && Clock::now() >= prefix_->deadline ) { @@ -430,6 +610,12 @@ public: return; } switch ( character ) { + case U'o': + open_address( AddressEntry::Empty ); + break; + case U'O': + open_address( AddressEntry::Current ); + break; case U'h': move( Motion::Left ); break; @@ -517,6 +703,9 @@ public: } if ( key.modifiers == Modifiers { .control = true } && key.code == KeyCode::Character ) { switch ( key.character ) { + case U'l': + open_address( AddressEntry::Selected ); + break; case U'c': if ( auto* view = active_view(); view && view->snapshot().selection ) { view->cancel_selection(); @@ -573,6 +762,11 @@ public: return; // Modified keys have distinct bindings; do not alias them to arrows. } switch ( key.code ) { + case KeyCode::Function: + if ( key.function == 6 ) { + open_address( AddressEntry::Selected ); + } + break; case KeyCode::Enter: activate_link(); break; @@ -650,7 +844,14 @@ public: close(); } else if ( std::holds_alternative( event ) ) { stop_drag(); + if ( address_ ) { + address_->dragging = false; + const auto dimensions = screen_->size(); + address_->editor.resize( { 1, dimensions.columns - address_label_columns( dimensions ) } ); + } dirty_ = true; + } else if ( address_ ) { + address_input( event ); } else if ( const auto* tick = std::get_if( &event ) ) { if ( auto* view = active_view() ) { dirty_ = view->tick( tick->now ) || dirty_; @@ -746,7 +947,10 @@ public: append_chrome( frame, { dimensions.rows - 1, 0 }, status ); } } - screen_->draw( frame ); + if ( address_ ) { + draw_address( frame, dimensions ); + } + screen_->draw( frame, std::exchange( redraw_, false ) ); dirty_ = false; } @@ -765,11 +969,13 @@ public: const bool input = read_input( result ); if ( screen_ && received == 0 && !input && !dirty_ ) { auto wait = max_wait; - if ( prefix_ ) { - wait = std::min( - wait, - std::max( std::chrono::milliseconds::zero(), - std::chrono::ceil( prefix_->deadline - Clock::now() ) ) ); + const auto deadline = address_ ? address_->editor.prefix_deadline() + : prefix_ ? std::optional( prefix_->deadline ) + : std::nullopt; + if ( deadline ) { + wait = std::min( wait, + std::max( std::chrono::milliseconds::zero(), + std::chrono::ceil( *deadline - Clock::now() ) ) ); } const auto closed = screen_->wait( mailbox_->descriptor(), wait ); if ( closed ) { @@ -807,10 +1013,12 @@ public: std::optional active_ {}; std::optional exit_request_ {}; std::optional prefix_ {}; + std::optional address_ {}; std::uint64_t next_request_ { 1 }; std::vector actions_ {}; std::wstring notice_ {}; bool dirty_ { true }; + bool redraw_ { false }; }; UpdateSender::UpdateSender( std::shared_ptr mailbox ) : mailbox_( std::move( mailbox ) ) {} diff --git a/ricochet/src/tui/text.cc b/ricochet/src/tui/text.cc index 95b324b..ba24af2 100644 --- a/ricochet/src/tui/text.cc +++ b/ricochet/src/tui/text.cc @@ -113,6 +113,7 @@ TextAnalysis TextService::analyze( std::string_view utf8, bool line_breaks, bool .break_after = line_end == end }; utext_setNativeIndex( text.get(), begin ); const auto first = utext_next32( text.get() ); + result.whitespace_only = result.whitespace_only && u_isUWhiteSpace( first ); glyph.word = word_kind( first ); const auto source = utf8.substr( glyph.bytes.start, glyph.bytes.end - glyph.bytes.start ); if ( line_breaks && ( source == "\n" || source == "\r\n" ) ) { @@ -128,6 +129,7 @@ TextAnalysis TextService::analyze( std::string_view utf8, bool line_breaks, bool && !u_hasBinaryProperty( first, UCHAR_EMOJI_PRESENTATION ); while ( utext_getNativeIndex( text.get() ) < end ) { const auto codepoint = utext_next32( text.get() ); + result.whitespace_only = result.whitespace_only && u_isUWhiteSpace( codepoint ); glyph.display.push_back( static_cast( codepoint ) ); // ncurses accepts one spacing character followed by nonspacing marks. // Joiners, selectors and extra spacing characters use one visible fallback. diff --git a/ricochet/src/tui/text.hh b/ricochet/src/tui/text.hh index eb0a2bb..99fd7c9 100644 --- a/ricochet/src/tui/text.hh +++ b/ricochet/src/tui/text.hh @@ -57,6 +57,8 @@ struct Grapheme struct TextAnalysis { std::vector graphemes {}; + // All codepoints, including combining marks; an empty input is whitespace-only. + bool whitespace_only { true }; // Vim-style reading units: letters/numbers/underscore, punctuation runs, // individual ideographs. Whitespace is excluded; offsets remain UTF-8 bytes. std::vector words {}; -- cgit v1.2.3