Initial commit: HTab spreadsheet engine and GemUI X11 frontend

This commit is contained in:
Luxferre committed 2026-11-30 17:45:17 +02:00
commit 395f458fee
55 files changed
+12682

No files matched your search

+1746
View File
File diff suppressed because it is too large. Load diff
+177
View File
@@ -0,0 +1,177 @@
#pragma once
#include "engine/workbook.hpp"
#include "ui/clipboard.hpp"
#include "ui/formula_bar.hpp"
#include "ui/grid_widget.hpp"
#include "ui/text_edit.hpp"
#include <gemui.h>
#include <cairo/cairo.h>
#include <string>
#include <utility>
#include <vector>
namespace htab::ui {
class AppWindow {
public:
int run(int req_w, int req_h, bool explicit_geometry, const std::string& initial_file);
private:
enum HitId {
HIT_NONE = 0,
HIT_MENU_BTN,
HIT_UNDO_BTN,
HIT_REDO_BTN,
HIT_FORMAT_BTN,
HIT_OPEN_BTN,
HIT_SAVE_BTN,
HIT_CSV_BTN,
HIT_INS_ROW_BTN,
HIT_DEL_ROW_BTN,
HIT_INS_COL_BTN,
HIT_DEL_COL_BTN,
HIT_ADDR_BOX,
HIT_FORMULA_INPUT,
HIT_SHEET_TAB,
HIT_SHEET_CLOSE,
HIT_ADD_SHEET,
HIT_HSCROLL,
HIT_MENU_ITEM,
HIT_FORMAT_ITEM,
HIT_CTX_ITEM,
HIT_MODAL_INPUT,
HIT_MODAL_OK,
HIT_MODAL_CANCEL,
HIT_MODAL_BACKDROP,
HIT_EXIT_SAVE,
HIT_EXIT_DISCARD,
HIT_EXIT_CANCEL,
};
enum class ModalKind {
Closed,
Menu,
ContextMenu,
FormatCell,
RenameSheet,
GoToCell,
Help,
ConfirmExit,
};
enum class CtxAction {
Copy,
Cut,
Paste,
ClearCells,
FormatCell,
InsertRowAbove,
InsertRowBelow,
DeleteRow,
InsertColLeft,
InsertColRight,
DeleteCol,
RenameSheet,
AddSheet,
DeleteSheet,
};
struct CtxItem {
const char* label;
CtxAction action;
};
struct Layout {
UiScale ui;
gemui_rect_t top_bar{0, 0, 0, 0};
gemui_rect_t formula_bar{0, 0, 0, 0};
gemui_rect_t grid{0, 0, 0, 0};
gemui_rect_t bottom_bar{0, 0, 0, 0};
gemui_rect_t tabs_area{0, 0, 0, 0};
gemui_rect_t hscroll{0, 0, 0, 0};
};
static void cb_draw(gemui_app_t* app, cairo_t* cr, int w, int h, void* ud);
static void cb_key(gemui_app_t* app, KeySym ks, unsigned int state, const char* utf8, void* ud);
static void cb_ptr(gemui_app_t* app, int type, int x, int y, unsigned int btn, void* ud);
static void cb_resize(gemui_app_t* app, int w, int h, void* ud);
static void cb_theme(gemui_app_t* app, void* ud);
static bool cb_close(gemui_app_t* app, void* ud);
static void cb_open_file_done(gemui_app_t* app, bool accepted, const char* path, void* ud);
static void cb_save_native_done(gemui_app_t* app, bool accepted, const char* path, void* ud);
static void cb_export_csv_values_done(gemui_app_t* app, bool accepted, const char* path, void* ud);
static void cb_export_csv_formulas_done(gemui_app_t* app, bool accepted, const char* path, void* ud);
Layout compute_layout(int w, int h) const;
void draw(cairo_t* cr, int w, int h);
void draw_top_bar(cairo_t* cr, const Layout& lay);
void draw_bottom_bar(cairo_t* cr, const Layout& lay);
void draw_modal(cairo_t* cr, int w, int h, const UiScale& ui);
void handle_key(KeySym ks, unsigned int state, const char* utf8);
void handle_modal_key(KeySym ks, unsigned int state, const char* utf8);
void handle_ptr(int type, int x, int y, unsigned int btn);
void handle_right_click(int x, int y);
void execute_menu_action(int index);
void execute_ctx_action(CtxAction action);
void accept_modal_dialog();
void commit_edit_if_active();
bool jump_to_address(const std::string& raw);
void open_modal(ModalKind kind, const std::string& initial_text = "");
void close_modal();
void request_quit();
void confirm_exit_save();
void open_file_dialog();
void save_native_dialog();
void export_csv_dialog(bool formulas);
std::string dialog_initial_dir() const;
std::string dialog_initial_name(const std::string& default_name,
const std::string& ext_override,
const std::string& suffix_before_ext = "") const;
bool load_file_auto(const std::string& path);
bool save_native_to(const std::string& path);
void export_csv_to(const std::string& path, bool formulas);
void do_copy(bool is_cut);
void do_paste();
void clear_selection();
void delete_selected_rows();
void delete_selected_cols();
void switch_sheet(int idx);
void add_new_sheet();
void close_sheet(int idx);
void update_title();
std::string display_filename() const;
Workbook wb_;
gemui_app_t* app_ = nullptr;
X11Clipboard clipboard_;
FormulaBar formula_bar_;
GridWidget grid_;
ModalKind modal_ = ModalKind::Closed;
int menu_sel_ = 0;
int menu_scroll_ = 0;
int format_sel_ = 0;
int help_scroll_ = 0;
int help_visible_rows_ = 12;
int exit_sel_ = 0;
bool quit_after_save_ = false;
std::vector<CtxItem> ctx_items_;
int ctx_x_ = 0;
int ctx_y_ = 0;
int ctx_sel_ = 0;
int ctx_target_sheet_ = 0;
TextEditor modal_editor_;
int tab_scroll_ = 0;
bool hscroll_dragging_ = false;
std::string current_path_;
bool dirty_ = false;
gemui_rect_t last_hscroll_r_{0, 0, 0, 0};
std::vector<std::pair<gemui_rect_t, int>> last_tab_rects_;
};
} // namespace htab::ui
+174
View File
@@ -0,0 +1,174 @@
#include "ui/clipboard.hpp"
#include <X11/Xatom.h>
#include <cstring>
#include <vector>
namespace htab::ui {
X11Clipboard::~X11Clipboard() {
if (dpy_) {
if (win_ != None) XDestroyWindow(dpy_, win_);
XCloseDisplay(dpy_);
dpy_ = nullptr;
}
}
void X11Clipboard::init(gemui_app_t* app) {
if (dpy_) return;
dpy_ = XOpenDisplay(nullptr);
if (!dpy_) return;
int screen = DefaultScreen(dpy_);
win_ = XCreateSimpleWindow(dpy_, RootWindow(dpy_, screen), -10, -10, 1, 1, 0, 0, 0);
XSelectInput(dpy_, win_, PropertyChangeMask);
atom_clipboard_ = XInternAtom(dpy_, "CLIPBOARD", False);
atom_targets_ = XInternAtom(dpy_, "TARGETS", False);
atom_utf8_ = XInternAtom(dpy_, "UTF8_STRING", False);
atom_text_ = XInternAtom(dpy_, "TEXT", False);
xfd_ = ConnectionNumber(dpy_);
if (app && xfd_ >= 0) {
gemui_add_fd(app, xfd_, &X11Clipboard::on_fd_ready, this);
}
}
void X11Clipboard::shutdown(gemui_app_t* app) {
if (app && xfd_ >= 0) {
gemui_del_fd(app, xfd_);
}
if (dpy_) {
if (win_ != None) {
XDestroyWindow(dpy_, win_);
win_ = None;
}
XCloseDisplay(dpy_);
dpy_ = nullptr;
}
xfd_ = -1;
}
void X11Clipboard::on_fd_ready(gemui_app_t*, int, void* ud) {
if (ud) static_cast<X11Clipboard*>(ud)->process_events();
}
void X11Clipboard::process_events() {
if (!dpy_) return;
while (XPending(dpy_) > 0) {
XEvent ev;
XNextEvent(dpy_, &ev);
if (ev.type == SelectionRequest) {
handle_selection_request(ev.xselectionrequest);
} else if (ev.type == SelectionClear) {
if (ev.xselectionclear.selection == atom_clipboard_) {
owns_clipboard_ = false;
}
}
}
}
void X11Clipboard::handle_selection_request(const XSelectionRequestEvent& req) {
XSelectionEvent resp;
std::memset(&resp, 0, sizeof(resp));
resp.type = SelectionNotify;
resp.display = req.display;
resp.requestor = req.requestor;
resp.selection = req.selection;
resp.target = req.target;
resp.time = req.time;
resp.property = None;
if (req.property != None) {
if (req.target == atom_targets_) {
Atom targets[4] = {atom_targets_, atom_utf8_, XA_STRING, atom_text_};
XChangeProperty(dpy_, req.requestor, req.property, XA_ATOM, 32, PropModeReplace,
reinterpret_cast<const unsigned char*>(targets), 4);
resp.property = req.property;
} else if (req.target == atom_utf8_ || req.target == XA_STRING || req.target == atom_text_) {
Atom type = (req.target == XA_STRING) ? XA_STRING : atom_utf8_;
XChangeProperty(dpy_, req.requestor, req.property, type, 8, PropModeReplace,
reinterpret_cast<const unsigned char*>(text_.data()),
static_cast<int>(text_.size()));
resp.property = req.property;
}
}
XSendEvent(dpy_, req.requestor, False, 0, reinterpret_cast<XEvent*>(&resp));
XFlush(dpy_);
}
void X11Clipboard::copy_grid(const ClipboardGrid& grid) {
internal_ = grid;
set_text(grid_to_tsv(grid));
}
void X11Clipboard::set_text(const std::string& text) {
text_ = text;
if (!dpy_ || win_ == None) return;
XSetSelectionOwner(dpy_, atom_clipboard_, win_, CurrentTime);
XSetSelectionOwner(dpy_, XA_PRIMARY, win_, CurrentTime);
XFlush(dpy_);
owns_clipboard_ = (XGetSelectionOwner(dpy_, atom_clipboard_) == win_);
}
std::string X11Clipboard::get_external_text(gemui_app_t* app) const {
if (!app) return "";
std::vector<char> buf(65536, '\0');
if (!gemui_clipboard_get(app, buf.data(), buf.size())) {
return "";
}
return std::string(buf.data());
}
std::string X11Clipboard::grid_to_tsv(const ClipboardGrid& grid) {
int rows = grid.src_range.row_count();
int cols = grid.src_range.col_count();
if (rows <= 0 || cols <= 0) return "";
std::vector<std::vector<std::string>> table(static_cast<size_t>(rows),
std::vector<std::string>(static_cast<size_t>(cols)));
for (const auto& c : grid.cells) {
if (c.dr >= 0 && c.dr < rows && c.dc >= 0 && c.dc < cols) {
auto sv = to_string(c.evaluated_value);
table[static_cast<size_t>(c.dr)][static_cast<size_t>(c.dc)] =
std::holds_alternative<std::string>(sv) ? std::get<std::string>(sv) : c.raw_input;
}
}
std::string out;
for (int r = 0; r < rows; ++r) {
if (r > 0) out.push_back('\n');
for (int c = 0; c < cols; ++c) {
if (c > 0) out.push_back('\t');
out += table[static_cast<size_t>(r)][static_cast<size_t>(c)];
}
}
return out;
}
std::vector<CellEdit> X11Clipboard::parse_tsv_to_edits(const std::string& text,
int dest_row,
int dest_col) {
std::vector<CellEdit> edits;
if (text.empty()) return edits;
int r = dest_row;
int c = dest_col;
size_t start = 0;
for (size_t i = 0; i <= text.size(); ++i) {
bool at_end = (i == text.size());
char ch = at_end ? '\n' : text[i];
if (ch == '\t' || ch == '\n' || ch == '\r') {
if (at_end && start == i && c == dest_col && i > 0 && text[i - 1] == '\n') {
break;
}
edits.push_back(CellEdit{r, c, text.substr(start, i - start), std::nullopt});
if (ch == '\t') {
++c;
} else {
if (ch == '\r' && i + 1 < text.size() && text[i + 1] == '\n') ++i;
++r;
c = dest_col;
}
start = i + 1;
}
}
return edits;
}
} // namespace htab::ui
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include "engine/workbook.hpp"
#include <gemui.h>
#include <X11/Xlib.h>
#include <string>
#include <vector>
namespace htab::ui {
class X11Clipboard {
public:
X11Clipboard() = default;
~X11Clipboard();
X11Clipboard(const X11Clipboard&) = delete;
X11Clipboard& operator=(const X11Clipboard&) = delete;
void init(gemui_app_t* app);
void shutdown(gemui_app_t* app);
void copy_grid(const ClipboardGrid& grid);
void set_text(const std::string& text);
bool owns_clipboard() const { return owns_clipboard_; }
bool has_internal() const { return owns_clipboard_ && !internal_.cells.empty(); }
const ClipboardGrid& internal_grid() const { return internal_; }
void clear_cut_flag() { internal_.is_cut = false; }
std::string get_external_text(gemui_app_t* app) const;
static std::string grid_to_tsv(const ClipboardGrid& grid);
static std::vector<CellEdit> parse_tsv_to_edits(const std::string& text,
int dest_row,
int dest_col);
private:
static void on_fd_ready(gemui_app_t* app, int fd, void* ud);
void process_events();
void handle_selection_request(const XSelectionRequestEvent& req);
Display* dpy_ = nullptr;
Window win_ = None;
int xfd_ = -1;
Atom atom_clipboard_ = None;
Atom atom_targets_ = None;
Atom atom_utf8_ = None;
Atom atom_text_ = None;
bool owns_clipboard_ = false;
std::string text_;
ClipboardGrid internal_;
};
} // namespace htab::ui
+49
View File
@@ -0,0 +1,49 @@
#include "ui/formula_bar.hpp"
#include <algorithm>
namespace htab::ui {
void FormulaBar::draw(gemui_app_t* app,
cairo_t* cr,
gemui_rect_t rect,
const std::string& cell_addr,
const TextEditor& editor,
bool bar_focused,
const UiScale& ui,
int hit_id_addr,
int hit_id_input) {
const gemui_theme_t* t = gemui_theme(app);
int div_h = std::max(1, spx(1, ui));
gemui_fill_rect(cr, rect, t->bg_bar);
gemui_fill_rect(cr, gemui_rect_t{rect.x, rect.y + rect.h - div_h, rect.w, div_h}, t->divider);
int font_px = ui.compact ? 10 : 14;
int pad_x = spx(ui.compact ? 2 : 6, ui);
int pad_y = spx(ui.compact ? 2 : 4, ui);
int addr_w = spx(ui.compact ? 46 : 84, ui);
int inner_h = std::max(6, rect.h - pad_y * 2 - div_h);
gemui_rect_t addr_r{rect.x + pad_x, rect.y + pad_y, addr_w, inner_h};
double rad = 3.0 * ui.scale;
double lw = std::max(1.0, ui.scale);
gemui_fill_round(cr, addr_r, rad, t->bg_button);
gemui_stroke_round(cr, addr_r, rad, lw, t->border);
int addr_pad = spx(2, ui);
gemui_draw_text(cr, t,
gemui_rect_t{addr_r.x + addr_pad, addr_r.y,
std::max(1, addr_r.w - addr_pad * 2), addr_r.h},
cell_addr.c_str(), pt_delta_for_ui(t, font_px, ui), true,
GEMUI_ALIGN_CENTER, t->accent);
if (hit_id_addr >= 0) {
gemui_hit_add(app, addr_r, hit_id_addr, 0);
}
int input_x = addr_r.x + addr_r.w + pad_x;
int input_w = std::max(spx(20, ui), rect.x + rect.w - input_x - pad_x);
gemui_rect_t input_r{input_x, rect.y + pad_y, input_w, inner_h};
draw_single_line_editor(cr, t, input_r, editor, "=formula or value", bar_focused, font_px, ui);
gemui_hit_add(app, input_r, hit_id_input, 0);
}
} // namespace htab::ui
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include "ui/text_edit.hpp"
#include <gemui.h>
#include <cairo/cairo.h>
#include <string>
namespace htab::ui {
class FormulaBar {
public:
void draw(gemui_app_t* app,
cairo_t* cr,
gemui_rect_t rect,
const std::string& cell_addr,
const TextEditor& editor,
bool bar_focused,
const UiScale& ui,
int hit_id_addr,
int hit_id_input);
};
} // namespace htab::ui
+833
View File
@@ -0,0 +1,833 @@
#include "ui/grid_widget.hpp"
#include "engine/address.hpp"
#include <algorithm>
#include <cmath>
#include <ctime>
#include <vector>
namespace htab::ui {
namespace {
uint64_t monotonic_ms() {
struct timespec ts{};
clock_gettime(CLOCK_MONOTONIC, &ts);
return static_cast<uint64_t>(ts.tv_sec) * 1000ULL +
static_cast<uint64_t>(ts.tv_nsec / 1000000L);
}
gemui_color_t blend_color(gemui_color_t bg, gemui_color_t fg, double alpha) {
gemui_color_t out;
out.r = bg.r * (1.0 - alpha) + fg.r * alpha;
out.g = bg.g * (1.0 - alpha) + fg.g * alpha;
out.b = bg.b * (1.0 - alpha) + fg.b * alpha;
out.a = 1.0;
out.argb = 0xFF000000U;
return out;
}
} // namespace
GridMetrics GridWidget::metrics_for(const UiScale& ui) {
if (ui.compact) {
return GridMetrics{
spx(24, ui),
spx(16, ui),
50,
17,
10,
spx(6, ui),
};
}
return GridMetrics{
spx(48, ui),
spx(26, ui),
96,
ui.touch ? 30 : 26,
13,
spx(12, ui),
};
}
int GridWidget::col_w(const Workbook& wb, int col) const {
if (drag_mode_ == DragMode::ResizeCol && resize_index_ == col) {
return resize_live_size_;
}
int logical_w = wb.get_col_width(wb.active_sheet(), col,
metrics_for(last_ui_).default_col_w_logical);
return spx(logical_w, last_ui_);
}
int GridWidget::row_h(const Workbook& wb, int row) const {
if (drag_mode_ == DragMode::ResizeRow && resize_index_ == row) {
return resize_live_size_;
}
int logical_h = wb.get_row_height(wb.active_sheet(), row,
metrics_for(last_ui_).default_row_h_logical);
return spx(logical_h, last_ui_);
}
CellRange GridWidget::selection_range(int sheet_idx) const {
return CellRange{
sheet_idx,
std::min(anchor_row_, active_row_),
std::min(anchor_col_, active_col_),
std::max(anchor_row_, active_row_),
std::max(anchor_col_, active_col_),
};
}
int GridWidget::max_scroll_rows(const Workbook& wb) const {
auto bounds = wb.get_used_bounds(wb.active_sheet());
int used_r = bounds ? bounds->r2 : 0;
return std::max({60, used_r + 30, active_row_ + 20, scroll_row_ + 20});
}
int GridWidget::max_scroll_cols(const Workbook& wb) const {
auto bounds = wb.get_used_bounds(wb.active_sheet());
int used_c = bounds ? bounds->c2 : 0;
return std::max({26, used_c + 10, active_col_ + 10, scroll_col_ + 10});
}
void GridWidget::reset_for_sheet(const Workbook& wb, int) {
editing_ = false;
formula_bar_focused_ = false;
scroll_row_ = 0;
scroll_col_ = 0;
active_row_ = 0;
active_col_ = 0;
anchor_row_ = 0;
anchor_col_ = 0;
sync_editor_from_cell(wb);
}
void GridWidget::sync_editor_from_cell(const Workbook& wb) {
const Cell* c = wb.get_cell(wb.active_sheet(), active_row_, active_col_);
editor_.set_text(c ? c->raw_input : "");
}
void GridWidget::set_active_cell(const Workbook& wb, int row, int col, bool keep_anchor) {
active_row_ = std::clamp(row, 0, kMaxRows - 1);
active_col_ = std::clamp(col, 0, kMaxCols - 1);
if (!keep_anchor) {
anchor_row_ = active_row_;
anchor_col_ = active_col_;
}
ensure_visible(wb, active_row_, active_col_);
if (!editing_) {
sync_editor_from_cell(wb);
}
}
void GridWidget::move_active(const Workbook& wb, int drow, int dcol, bool extend_selection) {
set_active_cell(wb, active_row_ + drow, active_col_ + dcol, extend_selection);
}
void GridWidget::ensure_visible(const Workbook& wb, int row, int col) {
if (row < scroll_row_) {
scroll_row_ = row;
} else if (last_data_rect_.h > 0) {
int y = 0;
int r = scroll_row_;
while (r <= row && y + row_h(wb, r) <= last_data_rect_.h) {
y += row_h(wb, r);
++r;
}
if (r <= row) {
int needed = 0;
int new_top = row;
while (new_top > 0) {
int h = row_h(wb, new_top);
if (needed + h > last_data_rect_.h) break;
needed += h;
--new_top;
}
if (needed + row_h(wb, new_top) <= last_data_rect_.h) {
scroll_row_ = new_top;
} else {
scroll_row_ = std::min(row, new_top + 1);
}
}
}
if (col < scroll_col_) {
scroll_col_ = col;
} else if (last_data_rect_.w > 0) {
int x = 0;
int c = scroll_col_;
while (c <= col && x + col_w(wb, c) <= last_data_rect_.w) {
x += col_w(wb, c);
++c;
}
if (c <= col) {
int needed = 0;
int new_left = col;
while (new_left > 0) {
int w = col_w(wb, new_left);
if (needed + w > last_data_rect_.w) break;
needed += w;
--new_left;
}
if (needed + col_w(wb, new_left) <= last_data_rect_.w) {
scroll_col_ = new_left;
} else {
scroll_col_ = std::min(col, new_left + 1);
}
}
}
}
void GridWidget::start_edit(const Workbook& wb,
bool focus_formula_bar,
const std::string* initial) {
editing_ = true;
formula_bar_focused_ = focus_formula_bar;
if (initial) {
editor_.set_text(*initial);
} else {
sync_editor_from_cell(wb);
}
}
void GridWidget::commit_edit(Workbook& wb) {
if (!editing_) return;
editing_ = false;
formula_bar_focused_ = false;
wb.set_cell_input(wb.active_sheet(), active_row_, active_col_, editor_.text);
sync_editor_from_cell(wb);
}
void GridWidget::cancel_edit(const Workbook& wb) {
editing_ = false;
formula_bar_focused_ = false;
sync_editor_from_cell(wb);
}
CellRange GridWidget::compute_fill_preview(int sheet_idx) const {
CellRange base = selection_range(sheet_idx);
int dr = 0;
if (fill_hover_row_ > base.r2) dr = fill_hover_row_ - base.r2;
else if (fill_hover_row_ < base.r1) dr = base.r1 - fill_hover_row_;
int dc = 0;
if (fill_hover_col_ > base.c2) dc = fill_hover_col_ - base.c2;
else if (fill_hover_col_ < base.c1) dc = base.c1 - fill_hover_col_;
if (dr >= dc && dr > 0) {
if (fill_hover_row_ > base.r2) base.r2 = fill_hover_row_;
else base.r1 = fill_hover_row_;
} else if (dc > 0) {
if (fill_hover_col_ > base.c2) base.c2 = fill_hover_col_;
else base.c1 = fill_hover_col_;
}
return base;
}
void GridWidget::draw(gemui_app_t* app,
cairo_t* cr,
const Workbook& wb,
gemui_rect_t rect,
const UiScale& ui) {
last_rect_ = rect;
last_ui_ = ui;
has_fill_handle_ = false;
if (rect.w < spx(40, ui) || rect.h < spx(30, ui)) return;
const gemui_theme_t* t = gemui_theme(app);
const GridMetrics m = metrics_for(ui);
const int sheet = wb.active_sheet();
gemui_rect_t vscroll_r{rect.x + rect.w - m.vscroll_w, rect.y + m.col_hdr_h,
m.vscroll_w, std::max(1, rect.h - m.col_hdr_h)};
last_vscroll_rect_ = vscroll_r;
gemui_rect_t data_r{rect.x + m.row_hdr_w, rect.y + m.col_hdr_h,
std::max(1, rect.w - m.row_hdr_w - m.vscroll_w),
std::max(1, rect.h - m.col_hdr_h)};
last_data_rect_ = data_r;
// Build visible column & row slices ONLY
std::vector<ColLayout> cols;
{
int x = data_r.x;
int c = scroll_col_;
int end_x = data_r.x + data_r.w;
while (x < end_x && c < kMaxCols) {
int w = col_w(wb, c);
cols.push_back({c, x, w});
x += w;
++c;
}
}
std::vector<RowLayout> rows;
{
int y = data_r.y;
int r = scroll_row_;
int end_y = data_r.y + data_r.h;
while (y < end_y && r < kMaxRows) {
int h = row_h(wb, r);
rows.push_back({r, y, h});
y += h;
++r;
}
}
CellRange sel = selection_range(sheet);
gemui_color_t sel_fill = blend_color(t->bg_main, t->sel_bg, 0.45);
gemui_color_t hdr_sel = blend_color(t->bg_header, t->accent, 0.22);
gemui_color_t spill_fill = blend_color(t->bg_main, t->info, 0.12);
int font_delta = pt_delta_for_ui(t, m.font_logical_px, ui);
gemui_fill_rect(cr, data_r, t->bg_main);
gemui_rect_t corner_r{rect.x, rect.y, m.row_hdr_w, m.col_hdr_h};
gemui_fill_rect(cr, corner_r, t->bg_header);
// Column headers
cairo_save(cr);
cairo_rectangle(cr, data_r.x, rect.y, data_r.w, m.col_hdr_h);
cairo_clip(cr);
for (const auto& cl : cols) {
bool in_sel = (cl.col >= sel.c1 && cl.col <= sel.c2);
gemui_rect_t hr{cl.x, rect.y, cl.w, m.col_hdr_h};
gemui_fill_rect(cr, hr, in_sel ? hdr_sel : t->bg_header);
std::string label = col_to_letters(cl.col);
int hpad = spx(1, ui);
gemui_draw_text(cr, t,
gemui_rect_t{hr.x + hpad, hr.y, std::max(1, hr.w - hpad * 2), hr.h},
label.c_str(), font_delta, in_sel, GEMUI_ALIGN_CENTER,
in_sel ? t->fg_bright : t->fg_muted);
}
cairo_restore(cr);
// Row headers
cairo_save(cr);
cairo_rectangle(cr, rect.x, data_r.y, m.row_hdr_w, data_r.h);
cairo_clip(cr);
for (const auto& rl : rows) {
bool in_sel = (rl.row >= sel.r1 && rl.row <= sel.r2);
gemui_rect_t hr{rect.x, rl.y, m.row_hdr_w, rl.h};
gemui_fill_rect(cr, hr, in_sel ? hdr_sel : t->bg_header);
std::string label = std::to_string(rl.row + 1);
int hpad = spx(1, ui);
gemui_draw_text(cr, t,
gemui_rect_t{hr.x + hpad, hr.y, std::max(1, hr.w - hpad * 2), hr.h},
label.c_str(), font_delta, in_sel, GEMUI_ALIGN_CENTER,
in_sel ? t->fg_bright : t->fg_muted);
}
cairo_restore(cr);
// Visible cells (clipped to data_r)
cairo_save(cr);
cairo_rectangle(cr, data_r.x, data_r.y, data_r.w, data_r.h);
cairo_clip(cr);
int cell_pad_x = spx(ui.compact ? 2 : 5, ui);
int cell_pad_y = std::max(1, spx(1, ui));
for (const auto& rl : rows) {
for (const auto& cl : cols) {
gemui_rect_t cr_rect{cl.x, rl.y, cl.w, rl.h};
bool in_sel = sel.contains(sheet, rl.row, cl.col);
bool is_active = (rl.row == active_row_ && cl.col == active_col_);
bool is_spilled = wb.is_spilled_cell(sheet, rl.row, cl.col);
if (in_sel && !is_active) {
gemui_fill_rect(cr, cr_rect, sel_fill);
} else if (is_spilled) {
gemui_fill_rect(cr, cr_rect, spill_fill);
}
if (editing_ && !formula_bar_focused_ && is_active) {
continue;
}
Value val = wb.get_scalar_value(sheet, rl.row, cl.col);
if (!val.is_empty()) {
std::string txt = wb.get_formatted_value(sheet, rl.row, cl.col);
if (!txt.empty()) {
int align = GEMUI_ALIGN_LEFT;
gemui_color_t fg = t->fg_main;
if (val.is_error()) {
align = GEMUI_ALIGN_CENTER;
fg = t->danger;
} else if (val.is_bool()) {
align = GEMUI_ALIGN_CENTER;
fg = t->info;
} else if (val.is_number()) {
align = GEMUI_ALIGN_RIGHT;
fg = t->fg_bright;
}
gemui_rect_t text_r{cr_rect.x + cell_pad_x, cr_rect.y + cell_pad_y,
std::max(1, cr_rect.w - cell_pad_x * 2),
std::max(1, cr_rect.h - cell_pad_y * 2)};
if (text_r.w > 4 && text_r.h > 4) {
cairo_save(cr);
cairo_rectangle(cr, cr_rect.x + 1, cr_rect.y + 1,
std::max(1, cr_rect.w - 2), std::max(1, cr_rect.h - 2));
cairo_clip(cr);
gemui_draw_text(cr, t, text_r, txt.c_str(), font_delta, false, align, fg);
cairo_restore(cr);
}
}
}
}
}
// Gridlines
double line_w = (ui.scale >= 1.5) ? 1.5 : 1.0;
gemui_set_source(cr, t->divider);
cairo_set_line_width(cr, line_w);
for (const auto& cl : cols) {
double lx = static_cast<double>(cl.x + cl.w) + 0.5;
cairo_move_to(cr, lx, data_r.y);
cairo_line_to(cr, lx, data_r.y + data_r.h);
}
for (const auto& rl : rows) {
double ly = static_cast<double>(rl.y + rl.h) + 0.5;
cairo_move_to(cr, data_r.x, ly);
cairo_line_to(cr, data_r.x + data_r.w, ly);
}
cairo_stroke(cr);
auto col_x_range = [&](int c_idx, int& out_x, int& out_w) -> bool {
for (const auto& cl : cols) {
if (cl.col == c_idx) { out_x = cl.x; out_w = cl.w; return true; }
}
return false;
};
auto row_y_range = [&](int r_idx, int& out_y, int& out_h) -> bool {
for (const auto& rl : rows) {
if (rl.row == r_idx) { out_y = rl.y; out_h = rl.h; return true; }
}
return false;
};
int sx1 = data_r.x, sy1 = data_r.y, sx2 = data_r.x, sy2 = data_r.y;
bool sel_vis = !cols.empty() && !rows.empty() &&
sel.c2 >= cols.front().col && sel.c1 <= cols.back().col &&
sel.r2 >= rows.front().row && sel.r1 <= rows.back().row;
if (sel_vis) {
if (sel.c1 < cols.front().col) sx1 = data_r.x;
else { int w_unused = 0; col_x_range(sel.c1, sx1, w_unused); }
if (sel.c2 > cols.back().col) sx2 = cols.back().x + cols.back().w;
else { int x0 = 0, w0 = 0; col_x_range(sel.c2, x0, w0); sx2 = x0 + w0; }
if (sel.r1 < rows.front().row) sy1 = data_r.y;
else { int h_unused = 0; row_y_range(sel.r1, sy1, h_unused); }
if (sel.r2 > rows.back().row) sy2 = rows.back().y + rows.back().h;
else { int y0 = 0, h0 = 0; row_y_range(sel.r2, y0, h0); sy2 = y0 + h0; }
gemui_set_source(cr, t->accent);
cairo_set_line_width(cr, std::max(1.5, 1.5 * ui.scale));
cairo_rectangle(cr, sx1 + 0.5, sy1 + 0.5, std::max(1, sx2 - sx1 - 1),
std::max(1, sy2 - sy1 - 1));
cairo_stroke(cr);
if (sel.c2 <= cols.back().col && sel.r2 <= rows.back().row) {
int hs = spx(ui.compact ? 5 : 7, ui);
last_fill_handle_ = gemui_rect_t{sx2 - hs / 2 - 1, sy2 - hs / 2 - 1, hs, hs};
has_fill_handle_ = true;
gemui_fill_rect(cr, last_fill_handle_, t->highlight);
}
}
int ax = 0, aw = 0, ay = 0, ah = 0;
if (col_x_range(active_col_, ax, aw) && row_y_range(active_row_, ay, ah)) {
if (editing_ && !formula_bar_focused_) {
int min_ed_w = spx(140, ui);
int edit_w = std::min(std::max(aw, min_ed_w), std::max(aw, data_r.x + data_r.w - ax));
draw_single_line_editor(cr, t, gemui_rect_t{ax, ay, edit_w, ah}, editor_, "", true,
m.font_logical_px, ui);
} else {
double active_lw = std::max(2.0, 2.0 * ui.scale);
gemui_set_source(cr, t->highlight);
cairo_set_line_width(cr, active_lw);
cairo_rectangle(cr, ax + 1.0, ay + 1.0, std::max(1, aw - 2), std::max(1, ah - 2));
cairo_stroke(cr);
}
}
if (drag_mode_ == DragMode::FillHandle && !cols.empty() && !rows.empty()) {
CellRange fp = compute_fill_preview(sheet);
int fx1 = data_r.x, fy1 = data_r.y, fx2 = data_r.x, fy2 = data_r.y;
if (fp.c1 < cols.front().col) fx1 = data_r.x;
else { int wu = 0; if (!col_x_range(fp.c1, fx1, wu)) fx1 = data_r.x; }
if (fp.c2 > cols.back().col) fx2 = cols.back().x + cols.back().w;
else { int x0 = 0, w0 = 0; if (col_x_range(fp.c2, x0, w0)) fx2 = x0 + w0; }
if (fp.r1 < rows.front().row) fy1 = data_r.y;
else { int hu = 0; if (!row_y_range(fp.r1, fy1, hu)) fy1 = data_r.y; }
if (fp.r2 > rows.back().row) fy2 = rows.back().y + rows.back().h;
else { int y0 = 0, h0 = 0; if (row_y_range(fp.r2, y0, h0)) fy2 = y0 + h0; }
const double dash[2] = {4.0 * ui.scale, 3.0 * ui.scale};
gemui_set_source(cr, t->highlight);
cairo_set_dash(cr, dash, 2, 0.0);
cairo_set_line_width(cr, std::max(1.5, 1.5 * ui.scale));
cairo_rectangle(cr, fx1 + 1.0, fy1 + 1.0, std::max(1, fx2 - fx1 - 2),
std::max(1, fy2 - fy1 - 2));
cairo_stroke(cr);
cairo_set_dash(cr, nullptr, 0, 0.0);
}
cairo_restore(cr);
// Header dividers
gemui_set_source(cr, t->border);
cairo_set_line_width(cr, line_w);
for (const auto& cl : cols) {
double lx = static_cast<double>(cl.x + cl.w) + 0.5;
cairo_move_to(cr, lx, rect.y);
cairo_line_to(cr, lx, rect.y + m.col_hdr_h);
}
for (const auto& rl : rows) {
double ly = static_cast<double>(rl.y + rl.h) + 0.5;
cairo_move_to(cr, rect.x, ly);
cairo_line_to(cr, rect.x + m.row_hdr_w, ly);
}
cairo_stroke(cr);
int div_px = std::max(1, spx(1, ui));
gemui_fill_rect(cr, gemui_rect_t{rect.x, rect.y + m.col_hdr_h - div_px, rect.w, div_px},
t->border);
gemui_fill_rect(cr, gemui_rect_t{rect.x + m.row_hdr_w - div_px, rect.y, div_px, rect.h},
t->border);
// Vertical scrollbar
gemui_fill_rect(cr, vscroll_r, t->bg_bar);
int total_rows = max_scroll_rows(wb);
int vis_rows = std::max(1, static_cast<int>(rows.size()));
int min_thumb_h = spx(14, ui);
int thumb_h = std::max(min_thumb_h, (vscroll_r.h * vis_rows) / std::max(1, total_rows));
if (thumb_h > vscroll_r.h) thumb_h = vscroll_r.h;
int max_top = std::max(1, total_rows - vis_rows);
int thumb_y = vscroll_r.y +
((vscroll_r.h - thumb_h) * std::min(scroll_row_, max_top)) / max_top;
int sb_pad = std::max(1, spx(1, ui));
gemui_fill_round(cr,
gemui_rect_t{vscroll_r.x + sb_pad, thumb_y + sb_pad,
std::max(2, vscroll_r.w - sb_pad * 2),
std::max(4, thumb_h - sb_pad * 2)},
2.0 * ui.scale, drag_mode_ == DragMode::ScrollV ? t->accent : t->border);
}
void GridWidget::draw_hscroll(gemui_app_t* app,
cairo_t* cr,
const Workbook& wb,
gemui_rect_t rect,
const UiScale& ui,
int hit_id_hscroll) {
if (rect.w < spx(12, ui) || rect.h < spx(6, ui)) return;
const gemui_theme_t* t = gemui_theme(app);
double rad = 2.0 * ui.scale;
gemui_fill_round(cr, rect, rad, t->bg_input);
gemui_stroke_round(cr, rect, rad, std::max(1.0, ui.scale), t->border);
int total_cols = max_scroll_cols(wb);
int vis_cols = 4;
if (last_data_rect_.w > 0) {
int def_col_px = std::max(1, spx(metrics_for(ui).default_col_w_logical, ui));
vis_cols = std::max(1, last_data_rect_.w / def_col_px);
}
int min_thumb_w = spx(12, ui);
int thumb_w = std::max(min_thumb_w, (rect.w * vis_cols) / std::max(1, total_cols));
if (thumb_w > rect.w) thumb_w = rect.w;
int max_left = std::max(1, total_cols - vis_cols);
int thumb_x = rect.x + ((rect.w - thumb_w) * std::min(scroll_col_, max_left)) / max_left;
int pad = std::max(1, spx(1, ui));
gemui_fill_round(cr,
gemui_rect_t{thumb_x + pad, rect.y + pad,
std::max(4, thumb_w - pad * 2),
std::max(3, rect.h - pad * 2)},
rad, drag_mode_ == DragMode::ScrollH ? t->accent : t->border);
gemui_hit_add(app, rect, hit_id_hscroll, 0);
}
void GridWidget::hit_cell_at(const Workbook& wb, int x, int y, int& out_row, int& out_col) const {
int cx = last_data_rect_.x;
int c = scroll_col_;
while (c + 1 < kMaxCols && cx + col_w(wb, c) <= x) {
cx += col_w(wb, c);
++c;
}
int cy = last_data_rect_.y;
int r = scroll_row_;
while (r + 1 < kMaxRows && cy + row_h(wb, r) <= y) {
cy += row_h(wb, r);
++r;
}
out_row = std::max(0, r);
out_col = std::max(0, c);
}
void GridWidget::update_scroll_v_from_y(const Workbook& wb, int y) {
if (last_vscroll_rect_.h <= 0) return;
double norm = static_cast<double>(y - last_vscroll_rect_.y) /
static_cast<double>(last_vscroll_rect_.h);
norm = std::clamp(norm, 0.0, 1.0);
int max_r = std::max(1, max_scroll_rows(wb) - 5);
scroll_row_ = static_cast<int>(std::llround(norm * max_r));
}
void GridWidget::handle_hscroll_drag(const Workbook& wb, int x, gemui_rect_t hscroll_rect) {
if (hscroll_rect.w <= 0) return;
double norm = static_cast<double>(x - hscroll_rect.x) / static_cast<double>(hscroll_rect.w);
norm = std::clamp(norm, 0.0, 1.0);
int max_c = std::max(1, max_scroll_cols(wb) - 2);
scroll_col_ = static_cast<int>(std::llround(norm * max_c));
}
GridHitRegion GridWidget::hit_region(const Workbook& wb,
int x,
int y,
int& out_row,
int& out_col) const {
if (x >= last_data_rect_.x && x < last_data_rect_.x + last_data_rect_.w &&
y >= last_data_rect_.y && y < last_data_rect_.y + last_data_rect_.h) {
hit_cell_at(wb, x, y, out_row, out_col);
return GridHitRegion::DataCell;
}
if (y >= last_rect_.y && y < last_data_rect_.y &&
x >= last_data_rect_.x && x < last_data_rect_.x + last_data_rect_.w) {
int cx = last_data_rect_.x;
int c = scroll_col_;
while (c + 1 < kMaxCols && cx + col_w(wb, c) <= x) {
cx += col_w(wb, c);
++c;
}
out_row = active_row_;
out_col = c;
return GridHitRegion::ColHeader;
}
if (x >= last_rect_.x && x < last_data_rect_.x &&
y >= last_data_rect_.y && y < last_data_rect_.y + last_data_rect_.h) {
int cy = last_data_rect_.y;
int r = scroll_row_;
while (r + 1 < kMaxRows && cy + row_h(wb, r) <= y) {
cy += row_h(wb, r);
++r;
}
out_row = r;
out_col = active_col_;
return GridHitRegion::RowHeader;
}
return GridHitRegion::Outside;
}
bool GridWidget::handle_pointer(Workbook& wb,
int type,
int x,
int y,
unsigned int btn,
gemui_rect_t hscroll_rect,
bool& edited_or_committed_out) {
edited_or_committed_out = false;
const GridMetrics m = metrics_for(last_ui_);
int hit_tol = spx(5, last_ui_);
auto in_rect = [](gemui_rect_t r, int px, int py) {
return px >= r.x && px < r.x + r.w && py >= r.y && py < r.y + r.h;
};
if (type == GEMUI_PTR_SCROLL_UP || type == GEMUI_PTR_SCROLL_DOWN) {
int delta = (type == GEMUI_PTR_SCROLL_UP) ? -3 : 3;
if (in_rect(hscroll_rect, x, y)) {
scroll_col_ = std::clamp(scroll_col_ + (delta > 0 ? 2 : -2), 0, kMaxCols - 1);
return true;
}
if (in_rect(last_rect_, x, y)) {
scroll_row_ = std::clamp(scroll_row_ + delta, 0, kMaxRows - 1);
return true;
}
return false;
}
if (type == GEMUI_PTR_DOWN) {
if (btn == 6) {
scroll_col_ = std::clamp(scroll_col_ - 2, 0, kMaxCols - 1);
return true;
}
if (btn == 7) {
scroll_col_ = std::clamp(scroll_col_ + 2, 0, kMaxCols - 1);
return true;
}
if (btn != Button1) {
return false;
}
if (in_rect(hscroll_rect, x, y)) {
drag_mode_ = DragMode::ScrollH;
handle_hscroll_drag(wb, x, hscroll_rect);
return true;
}
if (in_rect(last_vscroll_rect_, x, y)) {
drag_mode_ = DragMode::ScrollV;
update_scroll_v_from_y(wb, y);
return true;
}
if (!in_rect(last_rect_, x, y)) {
return false;
}
if (has_fill_handle_ &&
x >= last_fill_handle_.x - hit_tol &&
x <= last_fill_handle_.x + last_fill_handle_.w + hit_tol &&
y >= last_fill_handle_.y - hit_tol &&
y <= last_fill_handle_.y + last_fill_handle_.h + hit_tol) {
if (editing_) { commit_edit(wb); edited_or_committed_out = true; }
drag_mode_ = DragMode::FillHandle;
fill_hover_row_ = active_row_;
fill_hover_col_ = active_col_;
return true;
}
if (y >= last_rect_.y && y < last_data_rect_.y && x >= last_data_rect_.x) {
if (editing_) { commit_edit(wb); edited_or_committed_out = true; }
int cx = last_data_rect_.x;
int c = scroll_col_;
while (cx < last_data_rect_.x + last_data_rect_.w && c < kMaxCols) {
int w = col_w(wb, c);
if (std::abs(x - (cx + w)) <= hit_tol) {
drag_mode_ = DragMode::ResizeCol;
resize_index_ = c;
resize_start_px_ = x;
resize_orig_size_ = w;
resize_live_size_ = w;
return true;
}
if (x >= cx && x < cx + w) {
set_active_cell(wb, active_row_, c, false);
return true;
}
cx += w;
++c;
}
return true;
}
if (x >= last_rect_.x && x < last_data_rect_.x && y >= last_data_rect_.y) {
if (editing_) { commit_edit(wb); edited_or_committed_out = true; }
int cy = last_data_rect_.y;
int r = scroll_row_;
while (cy < last_data_rect_.y + last_data_rect_.h && r < kMaxRows) {
int h = row_h(wb, r);
if (std::abs(y - (cy + h)) <= hit_tol) {
drag_mode_ = DragMode::ResizeRow;
resize_index_ = r;
resize_start_px_ = y;
resize_orig_size_ = h;
resize_live_size_ = h;
return true;
}
if (y >= cy && y < cy + h) {
set_active_cell(wb, r, active_col_, false);
return true;
}
cy += h;
++r;
}
return true;
}
if (in_rect(last_data_rect_, x, y)) {
int r = 0, c = 0;
hit_cell_at(wb, x, y, r, c);
if (editing_ && (r != active_row_ || c != active_col_)) {
commit_edit(wb);
edited_or_committed_out = true;
}
uint64_t now = monotonic_ms();
bool dbl = (r == last_click_row_ && c == last_click_col_ && (now - last_click_ms_) <= 400);
last_click_row_ = r;
last_click_col_ = c;
last_click_ms_ = now;
if (dbl && !editing_) {
set_active_cell(wb, r, c, false);
start_edit(wb, false);
} else {
set_active_cell(wb, r, c, false);
drag_mode_ = DragMode::SelectRange;
}
return true;
}
return true;
}
if (type == GEMUI_PTR_MOVE) {
if (drag_mode_ == DragMode::Idle) return false;
if (drag_mode_ == DragMode::ScrollV) {
update_scroll_v_from_y(wb, y);
return true;
}
if (drag_mode_ == DragMode::ScrollH) {
handle_hscroll_drag(wb, x, hscroll_rect);
return true;
}
if (drag_mode_ == DragMode::ResizeCol) {
resize_live_size_ = std::clamp(resize_orig_size_ + (x - resize_start_px_),
spx(24, last_ui_), spx(360, last_ui_));
return true;
}
if (drag_mode_ == DragMode::ResizeRow) {
resize_live_size_ = std::clamp(resize_orig_size_ + (y - resize_start_px_),
spx(m.font_logical_px + 4, last_ui_), spx(160, last_ui_));
return true;
}
if (drag_mode_ == DragMode::SelectRange) {
int cx = std::clamp(x, last_data_rect_.x, last_data_rect_.x + last_data_rect_.w - 1);
int cy = std::clamp(y, last_data_rect_.y, last_data_rect_.y + last_data_rect_.h - 1);
int r = 0, c = 0;
hit_cell_at(wb, cx, cy, r, c);
if (y > last_data_rect_.y + last_data_rect_.h) ++r;
if (x > last_data_rect_.x + last_data_rect_.w) ++c;
set_active_cell(wb, r, c, true);
return true;
}
if (drag_mode_ == DragMode::FillHandle) {
int cx = std::clamp(x, last_data_rect_.x, last_data_rect_.x + last_data_rect_.w - 1);
int cy = std::clamp(y, last_data_rect_.y, last_data_rect_.y + last_data_rect_.h - 1);
hit_cell_at(wb, cx, cy, fill_hover_row_, fill_hover_col_);
return true;
}
return true;
}
if (type == GEMUI_PTR_UP) {
if (drag_mode_ == DragMode::Idle) return false;
if (drag_mode_ == DragMode::ResizeCol && resize_index_ >= 0) {
int logical_w = std::max(24, static_cast<int>(std::llround(
static_cast<double>(resize_live_size_) / last_ui_.scale)));
wb.set_col_width(wb.active_sheet(), resize_index_, logical_w);
edited_or_committed_out = true;
} else if (drag_mode_ == DragMode::ResizeRow && resize_index_ >= 0) {
int logical_h = std::max(14, static_cast<int>(std::llround(
static_cast<double>(resize_live_size_) / last_ui_.scale)));
wb.set_row_height(wb.active_sheet(), resize_index_, logical_h);
edited_or_committed_out = true;
} else if (drag_mode_ == DragMode::FillHandle) {
int sheet = wb.active_sheet();
CellRange src = selection_range(sheet);
CellRange dst = compute_fill_preview(sheet);
if (!(dst == src)) {
wb.autofill_range(sheet, src, dst);
anchor_row_ = dst.r1;
anchor_col_ = dst.c1;
active_row_ = dst.r2;
active_col_ = dst.c2;
sync_editor_from_cell(wb);
edited_or_committed_out = true;
}
}
drag_mode_ = DragMode::Idle;
resize_index_ = -1;
return true;
}
return false;
}
} // namespace htab::ui
+147
View File
@@ -0,0 +1,147 @@
#pragma once
#include "engine/workbook.hpp"
#include "ui/text_edit.hpp"
#include <gemui.h>
#include <cairo/cairo.h>
#include <cstdint>
#include <optional>
#include <string>
namespace htab::ui {
enum class GridHitRegion {
Outside,
DataCell,
ColHeader,
RowHeader,
};
struct GridMetrics {
int row_hdr_w = 48;
int col_hdr_h = 26;
int default_col_w_logical = 96;
int default_row_h_logical = 26;
int font_logical_px = 13;
int vscroll_w = 12;
};
class GridWidget {
public:
static GridMetrics metrics_for(const UiScale& ui);
int active_row() const { return active_row_; }
int active_col() const { return active_col_; }
int scroll_row() const { return scroll_row_; }
int scroll_col() const { return scroll_col_; }
CellRange selection_range(int sheet_idx) const;
bool is_editing() const { return editing_; }
bool is_formula_bar_focused() const { return formula_bar_focused_; }
TextEditor& editor() { return editor_; }
const TextEditor& editor() const { return editor_; }
void reset_for_sheet(const Workbook& wb, int sheet_idx);
void set_active_cell(const Workbook& wb, int row, int col, bool keep_anchor = false);
void move_active(const Workbook& wb, int drow, int dcol, bool extend_selection);
void ensure_visible(const Workbook& wb, int row, int col);
void start_edit(const Workbook& wb, bool focus_formula_bar, const std::string* initial = nullptr);
void commit_edit(Workbook& wb);
void cancel_edit(const Workbook& wb);
void sync_editor_from_cell(const Workbook& wb);
void draw(gemui_app_t* app,
cairo_t* cr,
const Workbook& wb,
gemui_rect_t rect,
const UiScale& ui);
void draw_hscroll(gemui_app_t* app,
cairo_t* cr,
const Workbook& wb,
gemui_rect_t rect,
const UiScale& ui,
int hit_id_hscroll);
bool handle_pointer(Workbook& wb,
int type,
int x,
int y,
unsigned int btn,
gemui_rect_t hscroll_rect,
bool& edited_or_committed_out);
GridHitRegion hit_region(const Workbook& wb,
int x,
int y,
int& out_row,
int& out_col) const;
void handle_hscroll_drag(const Workbook& wb, int x, gemui_rect_t hscroll_rect);
private:
enum class DragMode {
Idle,
SelectRange,
FillHandle,
ResizeCol,
ResizeRow,
ScrollV,
ScrollH,
};
struct ColLayout {
int col = 0;
int x = 0;
int w = 0;
};
struct RowLayout {
int row = 0;
int y = 0;
int h = 0;
};
int col_w(const Workbook& wb, int col) const;
int row_h(const Workbook& wb, int row) const;
int max_scroll_rows(const Workbook& wb) const;
int max_scroll_cols(const Workbook& wb) const;
CellRange compute_fill_preview(int sheet_idx) const;
void hit_cell_at(const Workbook& wb, int x, int y, int& out_row, int& out_col) const;
void update_scroll_v_from_y(const Workbook& wb, int y);
int scroll_row_ = 0;
int scroll_col_ = 0;
int active_row_ = 0;
int active_col_ = 0;
int anchor_row_ = 0;
int anchor_col_ = 0;
bool editing_ = false;
bool formula_bar_focused_ = false;
TextEditor editor_;
gemui_rect_t last_rect_{0, 0, 0, 0};
gemui_rect_t last_data_rect_{0, 0, 0, 0};
gemui_rect_t last_vscroll_rect_{0, 0, 0, 0};
gemui_rect_t last_fill_handle_{0, 0, 0, 0};
UiScale last_ui_{};
bool has_fill_handle_ = false;
DragMode drag_mode_ = DragMode::Idle;
int resize_index_ = -1;
int resize_start_px_ = 0;
int resize_orig_size_ = 0;
int resize_live_size_ = 0;
int fill_hover_row_ = 0;
int fill_hover_col_ = 0;
int last_click_row_ = -1;
int last_click_col_ = -1;
uint64_t last_click_ms_ = 0;
};
} // namespace htab::ui
+71
View File
@@ -0,0 +1,71 @@
#include "ui/app_window.hpp"
#include <cstdlib>
#include <iostream>
#include <string>
namespace {
bool parse_geometry(const std::string& geom, int& w_out, int& h_out) {
size_t x_pos = geom.find('x');
if (x_pos == std::string::npos) x_pos = geom.find('X');
if (x_pos == std::string::npos || x_pos == 0) return false;
size_t end_h = geom.find_first_of("+-", x_pos + 1);
std::string ws = geom.substr(0, x_pos);
std::string hs = (end_h == std::string::npos)
? geom.substr(x_pos + 1)
: geom.substr(x_pos + 1, end_h - (x_pos + 1));
if (ws.empty() || hs.empty()) return false;
int w = std::atoi(ws.c_str());
int h = std::atoi(hs.c_str());
if (w <= 0 || h <= 0) return false;
w_out = w;
h_out = h;
return true;
}
void print_usage(const char* prog) {
std::cout << "Usage: " << prog << " [OPTIONS] [FILE]\n"
<< "Options:\n"
<< " -g, --geometry WxH Initial window dimensions (e.g. 240x296 or 960x640)\n"
<< " -h, --help Show this help message\n";
}
} // namespace
int main(int argc, char** argv) {
int req_w = 960;
int req_h = 640;
bool explicit_geom = false;
std::string initial_file;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "-h" || arg == "--help") {
print_usage(argv[0]);
return 0;
}
if ((arg == "-g" || arg == "--geometry") && i + 1 < argc) {
if (!parse_geometry(argv[++i], req_w, req_h)) {
std::cerr << "Invalid geometry: " << argv[i] << "\n";
return 1;
}
explicit_geom = true;
continue;
}
if (arg.rfind("--geometry=", 0) == 0) {
if (!parse_geometry(arg.substr(11), req_w, req_h)) {
std::cerr << "Invalid geometry: " << arg.substr(11) << "\n";
return 1;
}
explicit_geom = true;
continue;
}
if (!arg.empty() && arg[0] != '-') {
initial_file = arg;
}
}
htab::ui::AppWindow app;
return app.run(req_w, req_h, explicit_geom, initial_file);
}
+214
View File
@@ -0,0 +1,214 @@
#pragma once
#include <gemui.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <cairo/cairo.h>
#include <algorithm>
#include <cmath>
#include <string>
namespace htab::ui {
struct UiScale {
double scale = 1.0;
bool compact = false;
bool phys_tiny = false;
bool touch = false;
};
inline UiScale compute_ui_scale(const gemui_app_t* app, int w, int h) {
double sys_scale = std::max(0.5, gemui_scale(app));
bool phys_tiny = (w <= 320 || h <= 360);
double eff_scale = phys_tiny ? 1.0 : sys_scale;
bool compact = phys_tiny ||
(static_cast<double>(w) / eff_scale <= 320.0) ||
(static_cast<double>(h) / eff_scale <= 360.0);
bool touch = !phys_tiny && gemui_touch_mode(app);
return UiScale{eff_scale, compact, phys_tiny, touch};
}
inline int spx(int logical_px, const UiScale& ui) {
if (logical_px <= 0) return 0;
int v = static_cast<int>(std::floor(static_cast<double>(logical_px) * ui.scale + 0.5));
return v < 1 ? 1 : v;
}
inline int pt_delta_for_ui(const gemui_theme_t* t, int logical_px, const UiScale& ui) {
double sc = (t && t->scale > 0.0) ? t->scale : 1.0;
int base_px = (t && t->base_font_size > 0) ? t->base_font_size : 15;
int pt_delta = 0;
if (ui.phys_tiny) {
int target = std::max(9, logical_px);
pt_delta = static_cast<int>(std::ceil(static_cast<double>(target - base_px) / sc));
} else {
pt_delta = logical_px - 15;
}
while (base_px + static_cast<int>(std::llround(static_cast<double>(pt_delta) * sc)) < 9) {
++pt_delta;
}
return pt_delta;
}
inline int measure_text_px(cairo_t* cr,
const gemui_theme_t* t,
const std::string& text,
int logical_px,
const UiScale& ui,
bool bold = false) {
if (text.empty()) return 0;
cairo_save(cr);
cairo_rectangle(cr, 0, 0, 0, 0);
cairo_clip(cr);
int tw = gemui_draw_text(cr, t, gemui_rect_t{0, 0, 10000, 128}, text.c_str(),
pt_delta_for_ui(t, logical_px, ui), bold, GEMUI_ALIGN_LEFT,
t->fg_main);
cairo_restore(cr);
return tw;
}
struct TextEditor {
std::string text;
size_t cursor = 0;
void set_text(std::string s) {
text = std::move(s);
cursor = text.size();
}
void clear() {
text.clear();
cursor = 0;
}
size_t prev_cp_pos(size_t pos) const {
if (pos == 0) return 0;
size_t p = pos - 1;
while (p > 0 && (static_cast<unsigned char>(text[p]) & 0xC0) == 0x80) {
--p;
}
return p;
}
size_t next_cp_pos(size_t pos) const {
if (pos >= text.size()) return text.size();
size_t p = pos + 1;
while (p < text.size() && (static_cast<unsigned char>(text[p]) & 0xC0) == 0x80) {
++p;
}
return p;
}
void move_left() { cursor = prev_cp_pos(cursor); }
void move_right() { cursor = next_cp_pos(cursor); }
void move_home() { cursor = 0; }
void move_end() { cursor = text.size(); }
void insert_utf8(const char* utf8) {
if (!utf8 || !utf8[0]) return;
std::string clean;
for (const char* p = utf8; *p; ++p) {
unsigned char uc = static_cast<unsigned char>(*p);
if (uc >= 0x20 && uc != 0x7F) clean.push_back(*p);
}
if (clean.empty()) return;
text.insert(cursor, clean);
cursor += clean.size();
}
void backspace() {
if (cursor == 0) return;
size_t p = prev_cp_pos(cursor);
text.erase(p, cursor - p);
cursor = p;
}
void del_char() {
if (cursor >= text.size()) return;
size_t n = next_cp_pos(cursor);
text.erase(cursor, n - cursor);
}
bool handle_key(KeySym ks, unsigned int state, const char* utf8) {
bool ctrl = (state & ControlMask) != 0;
if (!ctrl) {
if (ks == XK_Left) { move_left(); return true; }
if (ks == XK_Right) { move_right(); return true; }
if (ks == XK_Home) { move_home(); return true; }
if (ks == XK_End) { move_end(); return true; }
if (ks == XK_BackSpace) { backspace(); return true; }
if (ks == XK_Delete) { del_char(); return true; }
if (utf8 && utf8[0]) {
insert_utf8(utf8);
return true;
}
}
return false;
}
};
inline void draw_single_line_editor(cairo_t* cr,
const gemui_theme_t* t,
gemui_rect_t r,
const TextEditor& ed,
const char* placeholder,
bool focused,
int logical_px,
const UiScale& ui) {
double rad = 3.0 * ui.scale;
double lw = std::max(1.0, (focused ? 1.5 : 1.0) * ui.scale);
gemui_fill_round(cr, r, rad, focused ? t->bg_input_focus : t->bg_input);
gemui_stroke_round(cr, r, rad, lw, focused ? t->highlight : t->border);
int pad = spx(4, ui);
int vpad = std::max(1, spx(1, ui));
gemui_rect_t inner{r.x + pad, r.y + vpad, std::max(1, r.w - pad * 2),
std::max(1, r.h - vpad * 2)};
if (inner.w <= 4 || inner.h <= 4) return;
int delta = pt_delta_for_ui(t, logical_px, ui);
if (ed.text.empty() && !focused) {
if (placeholder && placeholder[0]) {
gemui_draw_text(cr, t, inner, placeholder, delta, false, GEMUI_ALIGN_LEFT, t->fg_muted);
}
return;
}
std::string prefix = ed.text.substr(0, std::min(ed.cursor, ed.text.size()));
int caret_x = measure_text_px(cr, t, prefix, logical_px, ui, false);
int edge_guard = spx(4, ui);
int scroll_x = 0;
if (caret_x > inner.w - edge_guard) {
scroll_x = caret_x - (inner.w - edge_guard);
}
cairo_save(cr);
cairo_rectangle(cr, inner.x, inner.y, inner.w, inner.h);
cairo_clip(cr);
if (!ed.text.empty()) {
gemui_rect_t draw_r{inner.x - scroll_x, inner.y,
std::max(inner.w + scroll_x + spx(32, ui), 8000), inner.h};
gemui_draw_text(cr, t, draw_r, ed.text.c_str(), delta, false, GEMUI_ALIGN_LEFT,
t->fg_bright);
} else if (placeholder && placeholder[0]) {
gemui_draw_text(cr, t, inner, placeholder, delta, false, GEMUI_ALIGN_LEFT, t->fg_muted);
}
if (focused) {
int cx = inner.x + caret_x - scroll_x;
if (cx >= inner.x && cx <= inner.x + inner.w - 1) {
int cpad = std::max(1, spx(2, ui));
gemui_set_source(cr, t->highlight);
cairo_set_line_width(cr, std::max(1.5, 1.5 * ui.scale));
cairo_move_to(cr, cx + 0.5, inner.y + cpad);
cairo_line_to(cr, cx + 0.5, inner.y + inner.h - cpad);
cairo_stroke(cr);
}
}
cairo_restore(cr);
}
} // namespace htab::ui