Files
htab/ui/app_window.cpp
T

1746 lines
60 KiB
C++
Raw Normal View History

#include "ui/app_window.hpp"
#include "engine/address.hpp"
#include "engine/io_csv.hpp"
#include "engine/io_native.hpp"
#include <X11/Xutil.h>
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <vector>
namespace htab::ui {
namespace {
struct MenuItemDef {
const char* label;
};
constexpr MenuItemDef kMenuItems[] = {
{"New Workbook"},
{"Open File..."},
{"Save (.htab)..."},
{"Export CSV (Values)..."},
{"Export CSV (Formulas)..."},
{"Insert Row"},
{"Delete Row"},
{"Insert Column"},
{"Delete Column"},
{"Format Cell..."},
{"Add Sheet"},
{"Rename Sheet..."},
{"Delete Sheet"},
{"Go To Cell..."},
{"Keyboard Hints (F1)"},
{"Quit"},
};
constexpr int kMenuItemCount = static_cast<int>(sizeof(kMenuItems) / sizeof(kMenuItems[0]));
struct HelpItemDef {
const char* key;
const char* compact_desc;
const char* desc;
};
constexpr HelpItemDef kHelpItems[] = {
{"F1", "Keyboard hints", "Show or hide these keyboard hints"},
{"F10", "Main menu", "Open main menu"},
{"Arrows", "Move / Shift sel", "Move cell (Shift extends selection)"},
{"Enter / Tab", "Confirm & move", "Commit edit & move (Shift reverses)"},
{"PgUp / PgDn", "Jump 10 rows", "Move active cell 10 rows up/down"},
{"Home / ^Home", "Col A / Cell A1", "Jump to Col A (Ctrl+Home -> A1)"},
{"F2 / Type", "Edit cell", "Edit active cell in place"},
{"Esc", "Cancel / close", "Cancel cell edit or close dialog"},
{"Del / BkSp", "Clear cells", "Clear selected cell contents"},
{"Ctrl+C/X/V", "Copy/Cut/Paste", "Copy, cut, or paste (relative refs)"},
{"Ctrl+Z / Y", "Undo / Redo", "Undo or redo last change"},
{"Ctrl+N", "New workbook", "Start a new blank workbook"},
{"Ctrl+O", "Open file", "Open .htab, .json, or .csv file"},
{"Ctrl+S", "Save (.htab)", "Save workbook natively"},
{"Ctrl+E", "Export CSV", "Export active sheet to CSV (Values)"},
{"Ctrl+G", "Go to cell", "Jump to cell/range (or click cell box)"},
{"^PgUp / ^PgDn", "Switch sheet", "Switch to previous / next sheet"},
{"Ctrl+Q", "Quit (confirm)", "Quit HTab (asks if unsaved)"},
{"Right-click", "Context menu", "Actions for cell, header, or tab"},
{"Mid-click tab", "Close sheet", "Close clicked worksheet tab"},
};
constexpr int kHelpItemCount = static_cast<int>(sizeof(kHelpItems) / sizeof(kHelpItems[0]));
struct FormatPreset {
const char* label;
const char* fmt;
};
constexpr FormatPreset kFormatPresets[] = {
{"General", ""},
{"Fixed (0.00)", "0.00"},
{"Integer (#,##0)", "#,##0"},
{"Currency ($#,##0.00)", "$#,##0.00"},
{"Percentage (0.00%)", "0.00%"},
{"Date (yyyy-mm-dd)", "yyyy-mm-dd"},
{"Time (hh:mm:ss)", "hh:mm:ss"},
};
constexpr int kFormatPresetCount =
static_cast<int>(sizeof(kFormatPresets) / sizeof(kFormatPresets[0]));
void draw_ui_button(gemui_app_t* app,
cairo_t* cr,
gemui_rect_t r,
const char* label,
int logical_font_px,
const UiScale& ui,
int hit_id,
int hit_val,
bool primary,
bool active,
bool focused) {
const gemui_theme_t* t = gemui_theme(app);
gemui_color_t bg = active ? t->sel_bg : (primary ? t->accent : t->bg_button);
double bg_lum = 0.299 * bg.r + 0.587 * bg.g + 0.114 * bg.b;
gemui_color_t fg = (bg_lum > 0.58) ? t->bg_main : ((active || primary) ? t->sel_fg : t->fg_bright);
gemui_color_t bd = focused ? t->highlight : (active ? t->accent : t->border);
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, bg);
gemui_stroke_round(cr, r, rad, lw, bd);
int pad = spx(2, ui);
if (r.w > pad * 2 + 4 && r.h > 4) {
gemui_draw_text(cr, t, gemui_rect_t{r.x + pad, r.y, r.w - pad * 2, r.h}, label,
pt_delta_for_ui(t, logical_font_px, ui), primary || active,
GEMUI_ALIGN_CENTER, fg);
}
if (hit_id >= 0) {
gemui_hit_add(app, r, hit_id, hit_val);
}
}
std::string compact_tab_label(const std::string& name) {
if (name.rfind("Sheet", 0) == 0 && name.size() > 5) {
bool all_digits = true;
for (size_t i = 5; i < name.size(); ++i) {
if (!std::isdigit(static_cast<unsigned char>(name[i]))) {
all_digits = false;
break;
}
}
if (all_digits) return "S" + name.substr(5);
}
if (name.size() <= 5) return name;
return name.substr(0, 5);
}
KeySym normalize_ctrl_keysym(KeySym ks) {
if (ks >= XK_A && ks <= XK_Z) return ks - XK_A + XK_a;
return ks;
}
bool ends_with_ci(std::string_view s, std::string_view suffix) {
if (s.size() < suffix.size()) return false;
return iequals_ascii(s.substr(s.size() - suffix.size()), suffix);
}
bool point_in_rect(gemui_rect_t r, int x, int y) {
return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h;
}
} // namespace
void AppWindow::cb_draw(gemui_app_t*, cairo_t* cr, int w, int h, void* ud) {
static_cast<AppWindow*>(ud)->draw(cr, w, h);
}
void AppWindow::cb_key(gemui_app_t*, KeySym ks, unsigned int state, const char* utf8, void* ud) {
static_cast<AppWindow*>(ud)->handle_key(ks, state, utf8);
}
void AppWindow::cb_ptr(gemui_app_t*, int type, int x, int y, unsigned int btn, void* ud) {
static_cast<AppWindow*>(ud)->handle_ptr(type, x, y, btn);
}
void AppWindow::cb_resize(gemui_app_t*, int, int, void* ud) {
auto* self = static_cast<AppWindow*>(ud);
self->grid_.ensure_visible(self->wb_, self->grid_.active_row(), self->grid_.active_col());
gemui_request_redraw(self->app_);
}
void AppWindow::cb_theme(gemui_app_t*, void* ud) {
auto* self = static_cast<AppWindow*>(ud);
self->grid_.ensure_visible(self->wb_, self->grid_.active_row(), self->grid_.active_col());
gemui_request_redraw(self->app_);
}
bool AppWindow::cb_close(gemui_app_t*, void* ud) {
static_cast<AppWindow*>(ud)->request_quit();
return false;
}
void AppWindow::cb_open_file_done(gemui_app_t*, bool accepted, const char* path, void* ud) {
if (accepted && path && path[0]) {
static_cast<AppWindow*>(ud)->load_file_auto(path);
}
}
void AppWindow::cb_save_native_done(gemui_app_t*, bool accepted, const char* path, void* ud) {
auto* self = static_cast<AppWindow*>(ud);
bool should_quit = self->quit_after_save_;
self->quit_after_save_ = false;
if (accepted && path && path[0]) {
if (self->save_native_to(path) && should_quit) {
gemui_quit(self->app_, 0);
}
}
}
void AppWindow::cb_export_csv_values_done(gemui_app_t*, bool accepted, const char* path, void* ud) {
if (accepted && path && path[0]) {
static_cast<AppWindow*>(ud)->export_csv_to(path, false);
}
}
void AppWindow::cb_export_csv_formulas_done(gemui_app_t*, bool accepted, const char* path, void* ud) {
if (accepted && path && path[0]) {
static_cast<AppWindow*>(ud)->export_csv_to(path, true);
}
}
int AppWindow::run(int req_w, int req_h, bool explicit_geometry, const std::string& initial_file) {
app_ = gemui_create("htab", "HTab", req_w, req_h, false);
if (!app_) return 1;
if (explicit_geometry) {
Display* dpy = gemui_display(app_);
Window win = gemui_window(app_);
int scr = DefaultScreen(dpy);
XSizeHints* sh = XAllocSizeHints();
if (sh) {
sh->flags = PMinSize | PSize;
sh->min_width = 200;
sh->min_height = 200;
sh->width = req_w;
sh->height = req_h;
XSetWMNormalHints(dpy, win, sh);
XFree(sh);
}
if (req_w >= DisplayWidth(dpy, scr) || req_h >= DisplayHeight(dpy, scr)) {
XMoveResizeWindow(dpy, win, 0, 0, static_cast<unsigned int>(req_w),
static_cast<unsigned int>(req_h));
} else {
XResizeWindow(dpy, win, static_cast<unsigned int>(req_w), static_cast<unsigned int>(req_h));
}
XFlush(dpy);
}
clipboard_.init(app_);
gemui_handlers_t handlers{};
handlers.on_draw = &AppWindow::cb_draw;
handlers.on_key = &AppWindow::cb_key;
handlers.on_ptr = &AppWindow::cb_ptr;
handlers.on_resize = &AppWindow::cb_resize;
handlers.on_theme = &AppWindow::cb_theme;
gemui_set_handlers(app_, &handlers, this);
gemui_set_close_handler(app_, &AppWindow::cb_close, this);
if (!initial_file.empty()) {
load_file_auto(initial_file);
}
grid_.sync_editor_from_cell(wb_);
update_title();
int code = gemui_run(app_);
clipboard_.shutdown(app_);
gemui_destroy(app_);
app_ = nullptr;
return code;
}
AppWindow::Layout AppWindow::compute_layout(int w, int h) const {
Layout lay;
lay.ui = compute_ui_scale(app_, w, h);
const UiScale& ui = lay.ui;
int top_h = ui.compact ? spx(20, ui) : spx(ui.touch ? 38 : 34, ui);
int fbar_h = ui.compact ? spx(22, ui) : spx(ui.touch ? 36 : 32, ui);
int bot_h = ui.compact ? spx(20, ui) : spx(ui.touch ? 34 : 30, ui);
int grid_h = std::max(spx(30, ui), h - top_h - fbar_h - bot_h);
lay.top_bar = gemui_rect_t{0, 0, w, top_h};
lay.formula_bar = gemui_rect_t{0, top_h, w, fbar_h};
lay.grid = gemui_rect_t{0, top_h + fbar_h, w, grid_h};
lay.bottom_bar = gemui_rect_t{0, top_h + fbar_h + grid_h, w, bot_h};
int tabs_w = ui.compact ? std::max(spx(80, ui), (w * 60) / 100)
: std::max(spx(140, ui), (w * 55) / 100);
lay.tabs_area = gemui_rect_t{0, lay.bottom_bar.y, tabs_w, bot_h};
int hs_pad = spx(3, ui);
int hscroll_w = std::max(spx(24, ui), w - tabs_w - hs_pad * 2);
if (!ui.compact) hscroll_w = std::min(spx(240, ui), hscroll_w);
lay.hscroll = gemui_rect_t{w - hscroll_w - hs_pad, lay.bottom_bar.y + hs_pad,
hscroll_w, std::max(4, bot_h - hs_pad * 2)};
return lay;
}
std::string AppWindow::display_filename() const {
if (current_path_.empty()) return "untitled";
size_t slash = current_path_.find_last_of('/');
std::string base = (slash == std::string::npos) ? current_path_ : current_path_.substr(slash + 1);
return base.empty() ? "untitled" : base;
}
void AppWindow::update_title() {
if (!app_) return;
std::string title = "HTab - " + display_filename() + (dirty_ ? " *" : "");
gemui_set_title(app_, title.c_str());
}
void AppWindow::draw_top_bar(cairo_t* cr, const Layout& lay) {
const gemui_theme_t* t = gemui_theme(app_);
const UiScale& ui = lay.ui;
int div_h = std::max(1, spx(1, ui));
gemui_fill_rect(cr, lay.top_bar, t->bg_header);
gemui_fill_rect(cr, gemui_rect_t{0, lay.top_bar.h - div_h, lay.top_bar.w, div_h}, t->divider);
int x = spx(ui.compact ? 2 : 6, ui);
int y = spx(ui.compact ? 2 : 4, ui);
int bh = std::max(6, lay.top_bar.h - y * 2 - div_h);
int fpx = ui.compact ? 10 : 13;
int gap = spx(ui.compact ? 2 : 4, ui);
auto add_btn = [&](const char* lbl, int fixed_logical_w, HitId id, bool primary = false) {
int bw = (fixed_logical_w > 0)
? spx(fixed_logical_w, ui)
: (measure_text_px(cr, t, lbl, fpx, ui, primary) + spx(14, ui));
if (x + bw > lay.top_bar.w - spx(2, ui)) return;
draw_ui_button(app_, cr, gemui_rect_t{x, y, bw, bh}, lbl, fpx, ui, id, 0,
primary, false, false);
x += bw + gap;
};
if (ui.compact) {
add_btn("Menu", 40, HIT_MENU_BTN, true);
add_btn("<", 20, HIT_UNDO_BTN);
add_btn(">", 20, HIT_REDO_BTN);
add_btn("Fmt", 30, HIT_FORMAT_BTN);
} else {
add_btn("Menu", 0, HIT_MENU_BTN, true);
add_btn("Open", 0, HIT_OPEN_BTN);
add_btn("Save", 0, HIT_SAVE_BTN);
add_btn("CSV", 0, HIT_CSV_BTN);
add_btn("Undo", 0, HIT_UNDO_BTN);
add_btn("Redo", 0, HIT_REDO_BTN);
add_btn("Fmt", 0, HIT_FORMAT_BTN);
add_btn("+Row", 0, HIT_INS_ROW_BTN);
add_btn("-Row", 0, HIT_DEL_ROW_BTN);
add_btn("+Col", 0, HIT_INS_COL_BTN);
add_btn("-Col", 0, HIT_DEL_COL_BTN);
}
int rpad = spx(4, ui);
int rem_w = lay.top_bar.w - x - rpad;
if (rem_w > spx(16, ui)) {
std::string fname = display_filename() + (dirty_ ? "*" : "");
gemui_draw_text(cr, t, gemui_rect_t{x, y, rem_w, bh}, fname.c_str(),
pt_delta_for_ui(t, fpx, ui), false, GEMUI_ALIGN_RIGHT, t->fg_muted);
}
}
void AppWindow::draw_bottom_bar(cairo_t* cr, const Layout& lay) {
const gemui_theme_t* t = gemui_theme(app_);
const UiScale& ui = lay.ui;
int div_h = std::max(1, spx(1, ui));
gemui_fill_rect(cr, lay.bottom_bar, t->bg_footer);
gemui_fill_rect(cr, gemui_rect_t{0, lay.bottom_bar.y, lay.bottom_bar.w, div_h}, t->divider);
int fpx = ui.compact ? 9 : 12;
int y = lay.bottom_bar.y + spx(2, ui);
int bh = std::max(6, lay.bottom_bar.h - spx(4, ui));
int x = spx(2, ui);
int add_btn_w = spx(ui.compact ? 18 : 26, ui);
int tab_gap = spx(2, ui);
int max_tabs_x = lay.tabs_area.x + lay.tabs_area.w - add_btn_w - spx(4, ui);
if (tab_scroll_ >= wb_.sheet_count()) tab_scroll_ = 0;
last_tab_rects_.clear();
for (int i = tab_scroll_; i < wb_.sheet_count(); ++i) {
bool active = (i == wb_.active_sheet());
bool show_close = (wb_.sheet_count() > 1) && (!ui.compact || active);
int close_w = show_close ? spx(ui.compact ? 12 : 18, ui) : 0;
std::string lbl = ui.compact ? compact_tab_label(wb_.sheet(i).name) : wb_.sheet(i).name;
int tw = measure_text_px(cr, t, lbl, fpx, ui, active) +
spx(ui.compact ? 10 : 18, ui) + close_w;
tw = std::clamp(tw, spx(ui.compact ? 24 : 52, ui), spx(ui.compact ? 64 : 156, ui));
if (x + tw > max_tabs_x) break;
gemui_rect_t tab_r{x, y, tw, bh};
last_tab_rects_.emplace_back(tab_r, i);
gemui_color_t bg = active ? t->sel_bg : t->bg_button;
gemui_color_t bd = active ? t->highlight : t->border;
gemui_color_t fg = active ? t->sel_fg : t->fg_bright;
double rad = 3.0 * ui.scale;
double lw = std::max(1.0, (active ? 1.5 : 1.0) * ui.scale);
gemui_fill_round(cr, tab_r, rad, bg);
gemui_stroke_round(cr, tab_r, rad, lw, bd);
gemui_hit_add(app_, tab_r, HIT_SHEET_TAB, i);
int lpad = spx(ui.compact ? 3 : 6, ui);
int label_w = std::max(1, tab_r.w - lpad - close_w - spx(2, ui));
gemui_draw_text(cr, t, gemui_rect_t{tab_r.x + lpad, tab_r.y, label_w, tab_r.h},
lbl.c_str(), pt_delta_for_ui(t, fpx, ui), active,
show_close ? GEMUI_ALIGN_LEFT : GEMUI_ALIGN_CENTER, fg);
if (show_close) {
gemui_rect_t close_r{tab_r.x + tab_r.w - close_w - spx(2, ui),
tab_r.y + spx(1, ui),
close_w,
std::max(4, tab_r.h - spx(2, ui))};
gemui_draw_text(cr, t, close_r, "x", pt_delta_for_ui(t, fpx, ui), false,
GEMUI_ALIGN_CENTER, active ? t->sel_fg : t->fg_muted);
gemui_hit_add(app_, close_r, HIT_SHEET_CLOSE, i);
}
x += tw + tab_gap;
}
if (x + add_btn_w <= lay.tabs_area.x + lay.tabs_area.w) {
draw_ui_button(app_, cr, gemui_rect_t{x, y, add_btn_w, bh}, "+", fpx, ui,
HIT_ADD_SHEET, 0, false, false, false);
}
if (!ui.compact) {
CellRange sel = grid_.selection_range(wb_.active_sheet());
int cells_checked = 0;
int num_count = 0;
double num_sum = 0.0;
for (int r = sel.r1; r <= sel.r2 && cells_checked < 2000; ++r) {
for (int c = sel.c1; c <= sel.c2 && cells_checked < 2000; ++c) {
++cells_checked;
Value v = wb_.get_scalar_value(sel.sheet, r, c);
if (v.is_number()) {
++num_count;
num_sum += v.as_number();
}
}
}
int status_x = lay.tabs_area.x + lay.tabs_area.w + spx(4, ui);
int status_w = lay.hscroll.x - status_x - spx(6, ui);
if (status_w > spx(40, ui) && num_count > 0) {
char buf[96];
std::snprintf(buf, sizeof(buf), "N:%d Sum:%.6g", num_count, num_sum);
gemui_draw_text(cr, t, gemui_rect_t{status_x, y, status_w, bh}, buf,
pt_delta_for_ui(t, fpx, ui), false, GEMUI_ALIGN_RIGHT, t->fg_muted);
}
}
last_hscroll_r_ = lay.hscroll;
grid_.draw_hscroll(app_, cr, wb_, lay.hscroll, ui, HIT_HSCROLL);
}
void AppWindow::draw_modal(cairo_t* cr, int w, int h, const UiScale& ui) {
if (modal_ == ModalKind::Closed) return;
const gemui_theme_t* t = gemui_theme(app_);
int fpx = ui.compact ? 10 : 13;
int font_delta = pt_delta_for_ui(t, fpx, ui);
double box_rad = 5.0 * ui.scale;
double box_lw = std::max(1.5, 1.5 * ui.scale);
int pad = spx(8, ui);
int margin_x = spx(12, ui);
int margin_y = spx(16, ui);
if (modal_ == ModalKind::ContextMenu) {
// Transparent click-catcher outside context menu
gemui_hit_add(app_, gemui_rect_t{0, 0, w, h}, HIT_MODAL_BACKDROP, 0);
if (ctx_items_.empty()) return;
int row_h = spx(ui.compact ? 18 : (ui.touch ? 32 : 26), ui);
int max_text_w = 0;
for (const auto& item : ctx_items_) {
int tw = measure_text_px(cr, t, item.label, fpx, ui, false);
if (tw > max_text_w) max_text_w = tw;
}
int mw = std::clamp(max_text_w + spx(28, ui), spx(130, ui),
std::max(spx(130, ui), w - spx(8, ui)));
int mh = std::min(h - spx(8, ui),
static_cast<int>(ctx_items_.size()) * row_h + spx(8, ui));
int edge = spx(4, ui);
int bx = std::clamp(ctx_x_, edge, std::max(edge, w - mw - edge));
int by = std::clamp(ctx_y_, edge, std::max(edge, h - mh - edge));
gemui_rect_t box{bx, by, mw, mh};
gemui_fill_round(cr, box, box_rad, t->bg_overlay);
gemui_stroke_round(cr, box, box_rad, box_lw, t->accent);
gemui_hit_add(app_, box, HIT_NONE, 0);
int item_inset = spx(4, ui);
int text_inset = spx(6, ui);
for (size_t i = 0; i < ctx_items_.size(); ++i) {
int iy = box.y + spx(4, ui) + static_cast<int>(i) * row_h;
if (iy + row_h > box.y + box.h) break;
gemui_rect_t ir{box.x + item_inset, iy, box.w - item_inset * 2, std::max(4, row_h - 1)};
bool sel = (static_cast<int>(i) == ctx_sel_);
if (sel) gemui_fill_round(cr, ir, 3.0 * ui.scale, t->sel_bg);
gemui_draw_text(cr, t,
gemui_rect_t{ir.x + text_inset, ir.y,
std::max(1, ir.w - text_inset * 2), ir.h},
ctx_items_[i].label, font_delta, sel, GEMUI_ALIGN_LEFT,
sel ? t->sel_fg : t->fg_main);
gemui_hit_add(app_, ir, HIT_CTX_ITEM, static_cast<int>(i));
}
return;
}
cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 0.55);
cairo_rectangle(cr, 0, 0, w, h);
cairo_fill(cr);
gemui_hit_add(app_, gemui_rect_t{0, 0, w, h}, HIT_MODAL_BACKDROP, 0);
if (modal_ == ModalKind::Menu) {
int mw = std::min(w - margin_x, spx(ui.compact ? 224 : 280, ui));
int row_h = spx(ui.compact ? 18 : (ui.touch ? 32 : 28), ui);
int title_h = spx(ui.compact ? 20 : 28, ui);
int max_h = std::max(spx(60, ui), h - margin_y);
int vis_rows = std::min(kMenuItemCount,
std::max(3, (max_h - title_h - spx(8, ui)) / std::max(1, row_h)));
int mh = title_h + vis_rows * row_h + spx(6, ui);
gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh};
gemui_fill_round(cr, box, box_rad, t->bg_overlay);
gemui_stroke_round(cr, box, box_rad, box_lw, t->accent);
gemui_hit_add(app_, box, HIT_NONE, 0);
gemui_draw_text(cr, t, gemui_rect_t{box.x + pad, box.y + spx(2, ui), box.w - pad * 2, title_h},
"Menu (Up/Down, Enter)", font_delta, true, GEMUI_ALIGN_LEFT, t->fg_bright);
gemui_fill_rect(cr, gemui_rect_t{box.x + spx(4, ui), box.y + title_h,
box.w - spx(8, ui), std::max(1, spx(1, ui))},
t->divider);
if (menu_sel_ < menu_scroll_) menu_scroll_ = menu_sel_;
if (menu_sel_ >= menu_scroll_ + vis_rows) menu_scroll_ = menu_sel_ - vis_rows + 1;
menu_scroll_ = std::clamp(menu_scroll_, 0, std::max(0, kMenuItemCount - vis_rows));
int item_inset = spx(4, ui);
int text_inset = spx(6, ui);
for (int i = 0; i < vis_rows; ++i) {
int idx = menu_scroll_ + i;
if (idx >= kMenuItemCount) break;
gemui_rect_t ir{box.x + item_inset, box.y + title_h + spx(3, ui) + i * row_h,
box.w - item_inset * 2, std::max(4, row_h - 1)};
bool sel = (idx == menu_sel_);
if (sel) gemui_fill_round(cr, ir, 3.0 * ui.scale, t->sel_bg);
gemui_draw_text(cr, t,
gemui_rect_t{ir.x + text_inset, ir.y,
std::max(1, ir.w - text_inset * 2), ir.h},
kMenuItems[idx].label, font_delta, sel, GEMUI_ALIGN_LEFT,
sel ? t->sel_fg : t->fg_main);
gemui_hit_add(app_, ir, HIT_MENU_ITEM, idx);
}
return;
}
if (modal_ == ModalKind::FormatCell) {
int mw = std::min(w - margin_x, spx(ui.compact ? 224 : 280, ui));
int row_h = spx(ui.compact ? 18 : (ui.touch ? 32 : 28), ui);
int title_h = spx(ui.compact ? 20 : 28, ui);
int mh = std::min(h - margin_y, title_h + kFormatPresetCount * row_h + spx(8, ui));
gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh};
gemui_fill_round(cr, box, box_rad, t->bg_overlay);
gemui_stroke_round(cr, box, box_rad, box_lw, t->accent);
gemui_hit_add(app_, box, HIT_NONE, 0);
gemui_draw_text(cr, t, gemui_rect_t{box.x + pad, box.y + spx(2, ui), box.w - pad * 2, title_h},
"Cell Format", font_delta, true, GEMUI_ALIGN_LEFT, t->fg_bright);
gemui_fill_rect(cr, gemui_rect_t{box.x + spx(4, ui), box.y + title_h,
box.w - spx(8, ui), std::max(1, spx(1, ui))},
t->divider);
int item_inset = spx(4, ui);
int text_inset = spx(6, ui);
for (int i = 0; i < kFormatPresetCount; ++i) {
gemui_rect_t ir{box.x + item_inset, box.y + title_h + spx(4, ui) + i * row_h,
box.w - item_inset * 2, std::max(4, row_h - 1)};
bool sel = (i == format_sel_);
if (sel) gemui_fill_round(cr, ir, 3.0 * ui.scale, t->sel_bg);
gemui_draw_text(cr, t,
gemui_rect_t{ir.x + text_inset, ir.y,
std::max(1, ir.w - text_inset * 2), ir.h},
kFormatPresets[i].label, font_delta, sel, GEMUI_ALIGN_LEFT,
sel ? t->sel_fg : t->fg_main);
gemui_hit_add(app_, ir, HIT_FORMAT_ITEM, i);
}
return;
}
if (modal_ == ModalKind::Help) {
int edge_pad = spx(ui.compact ? 4 : 8, ui);
int inner_pad = spx(ui.compact ? 4 : 8, ui);
int mw = std::min(w - edge_pad * 2, spx(ui.compact ? 232 : 540, ui));
int mh = std::min(h - edge_pad * 2, spx(ui.compact ? 284 : 460, ui));
gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh};
gemui_fill_round(cr, box, box_rad, t->bg_overlay);
gemui_stroke_round(cr, box, box_rad, box_lw, t->accent);
gemui_hit_add(app_, box, HIT_NONE, 0);
int gap = spx(ui.compact ? 3 : 6, ui);
int title_h = spx(ui.compact ? 20 : 28, ui);
int foot_h = spx(ui.compact ? 20 : (ui.touch ? 32 : 26), ui);
int close_w = spx(ui.compact ? 20 : 28, ui);
int ix = box.x + inner_pad;
int iw = box.w - inner_pad * 2;
int y = box.y + inner_pad;
gemui_draw_text(cr, t, gemui_rect_t{ix + 2, y, std::max(1, iw - close_w - gap), title_h},
ui.compact ? "Shortcuts (F1)" : "Keyboard Hints (F1)", font_delta, true,
GEMUI_ALIGN_LEFT, t->fg_bright);
draw_ui_button(app_, cr, gemui_rect_t{ix + iw - close_w, y, close_w, title_h}, "x", fpx, ui,
HIT_MODAL_CANCEL, 0, false, false, false);
y += title_h + spx(2, ui);
gemui_fill_rect(cr, gemui_rect_t{ix, y, iw, std::max(1, spx(1, ui))}, t->divider);
y += gap;
int foot_y = box.y + box.h - inner_pad - foot_h;
int list_h = std::max(spx(30, ui), foot_y - gap - y);
gemui_rect_t list_r{ix, y, iw, list_h};
gemui_fill_round(cr, list_r, 3.0 * ui.scale, t->bg_main);
gemui_stroke_round(cr, list_r, 3.0 * ui.scale, std::max(1.0, ui.scale), t->border);
int row_h = spx(ui.compact ? 17 : (ui.touch ? 28 : 22), ui);
int vis = std::max(1, (list_r.h - 4) / std::max(1, row_h));
help_visible_rows_ = vis;
int max_scroll = std::max(0, kHelpItemCount - vis);
help_scroll_ = std::clamp(help_scroll_, 0, max_scroll);
bool need_sb = (kHelpItemCount > vis);
int sb_w = need_sb ? spx(ui.compact ? 5 : 8, ui) : 0;
int row_w = std::max(10, list_r.w - 4 - sb_w - (need_sb ? 2 : 0));
int key_w = spx(ui.compact ? 84 : 155, ui);
int desc_x_off = key_w + spx(ui.compact ? 4 : 10, ui);
int small_delta = pt_delta_for_ui(t, ui.compact ? 9 : 12, ui);
for (int i = 0; i < vis; ++i) {
int idx = help_scroll_ + i;
if (idx >= kHelpItemCount) break;
int ry = list_r.y + 2 + i * row_h;
gemui_rect_t rr{list_r.x + 2, ry, row_w, std::max(4, row_h - 1)};
if ((idx % 2) == 1) {
gemui_fill_rect(cr, rr, t->bg_bar);
}
gemui_draw_text(cr, t, gemui_rect_t{rr.x + spx(3, ui), rr.y, key_w, rr.h},
kHelpItems[idx].key, small_delta, true, GEMUI_ALIGN_LEFT, t->accent);
const char* desc = ui.compact ? kHelpItems[idx].compact_desc : kHelpItems[idx].desc;
int dw = std::max(4, rr.w - desc_x_off - spx(2, ui));
gemui_draw_text(cr, t, gemui_rect_t{rr.x + desc_x_off, rr.y, dw, rr.h},
desc, small_delta, false, GEMUI_ALIGN_LEFT, t->fg_main);
}
if (need_sb) {
gemui_rect_t sb_r{list_r.x + list_r.w - sb_w - 2, list_r.y + 2, sb_w,
std::max(8, list_r.h - 4)};
gemui_fill_round(cr, sb_r, sb_w * 0.5, t->bg_bar);
int thumb_h = std::max(spx(14, ui), (sb_r.h * vis) / kHelpItemCount);
thumb_h = std::min(sb_r.h, thumb_h);
int thumb_y = sb_r.y;
if (max_scroll > 0 && sb_r.h > thumb_h) {
thumb_y += ((sb_r.h - thumb_h) * help_scroll_) / max_scroll;
}
gemui_fill_round(cr, gemui_rect_t{sb_r.x + 1, thumb_y, std::max(2, sb_r.w - 2), thumb_h},
sb_w * 0.5, t->accent);
}
int close_btn_w = spx(ui.compact ? 56 : 86, ui);
int hint_w = std::max(1, iw - close_btn_w - gap);
gemui_draw_text(cr, t, gemui_rect_t{ix, foot_y, hint_w, foot_h},
ui.compact ? "Up/Dn Esc:Close" : "Scroll: Up/Down Close: F1 or Esc",
small_delta, false, GEMUI_ALIGN_LEFT, t->fg_muted);
draw_ui_button(app_, cr, gemui_rect_t{ix + iw - close_btn_w, foot_y, close_btn_w, foot_h},
"Close", fpx, ui, HIT_MODAL_CANCEL, 0, true, false, true);
return;
}
if (modal_ == ModalKind::ConfirmExit) {
int edge_pad = spx(ui.compact ? 4 : 12, ui);
int inner_pad = spx(ui.compact ? 6 : 12, ui);
int gap = spx(ui.compact ? 4 : 8, ui);
int mw = std::min(w - edge_pad * 2, spx(ui.compact ? 232 : 420, ui));
int title_h = spx(ui.compact ? 20 : 28, ui);
int msg_h = spx(ui.compact ? 26 : 36, ui);
int btn_h = spx(ui.compact ? 22 : (ui.touch ? 32 : 28), ui);
int mh = title_h + msg_h + btn_h + inner_pad * 2 + gap * 2 + spx(4, ui);
gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh};
gemui_fill_round(cr, box, box_rad, t->bg_overlay);
gemui_stroke_round(cr, box, box_rad, box_lw, t->accent);
gemui_hit_add(app_, box, HIT_NONE, 0);
int ix = box.x + inner_pad;
int iw = box.w - inner_pad * 2;
int y = box.y + inner_pad;
gemui_draw_text(cr, t, gemui_rect_t{ix, y, iw, title_h},
"Unsaved Changes", font_delta, true, GEMUI_ALIGN_LEFT, t->fg_bright);
y += title_h + spx(2, ui);
gemui_fill_rect(cr, gemui_rect_t{ix, y, iw, std::max(1, spx(1, ui))}, t->divider);
y += gap;
std::string fname = display_filename();
std::string prompt = ui.compact ? ("Save " + fname + "?")
: ("Save changes to " + fname + " before exiting?");
gemui_draw_text(cr, t, gemui_rect_t{ix, y, iw, msg_h}, prompt.c_str(), font_delta, false,
GEMUI_ALIGN_LEFT, t->fg_main);
int btn_y = box.y + box.h - inner_pad - btn_h;
int btn_gap = spx(ui.compact ? 4 : 8, ui);
int btn_w = std::max(spx(32, ui), (iw - btn_gap * 2) / 3);
draw_ui_button(app_, cr, gemui_rect_t{ix, btn_y, btn_w, btn_h}, "Save", fpx, ui,
HIT_EXIT_SAVE, 0, true, false, exit_sel_ == 0);
draw_ui_button(app_, cr, gemui_rect_t{ix + btn_w + btn_gap, btn_y, btn_w, btn_h}, "Discard",
fpx, ui, HIT_EXIT_DISCARD, 0, false, false, exit_sel_ == 1);
draw_ui_button(app_, cr, gemui_rect_t{ix + (btn_w + btn_gap) * 2, btn_y,
iw - (btn_w + btn_gap) * 2, btn_h},
"Cancel", fpx, ui, HIT_EXIT_CANCEL, 0, false, false, exit_sel_ == 2);
return;
}
const char* title = "Rename Sheet";
const char* ph = "Sheet name";
if (modal_ == ModalKind::GoToCell) {
title = "Go To Cell";
ph = ui.compact ? "C25 or Sheet2!A1" : "e.g. C25, Sheet2!B4, A1:C10";
}
int mw = std::min(w - spx(10, ui), spx(ui.compact ? 300 : 380, ui));
int title_h = spx(ui.compact ? 20 : 26, ui);
int inp_h = spx(ui.compact ? 22 : 32, ui);
int btn_h = spx(ui.compact ? 20 : (ui.touch ? 32 : 28), ui);
int btn_w = spx(ui.compact ? 64 : 88, ui);
int mh = title_h + inp_h + btn_h + spx(22, ui);
gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh};
gemui_fill_round(cr, box, box_rad, t->bg_overlay);
gemui_stroke_round(cr, box, box_rad, box_lw, t->accent);
gemui_hit_add(app_, box, HIT_NONE, 0);
gemui_draw_text(cr, t, gemui_rect_t{box.x + pad, box.y + spx(3, ui), box.w - pad * 2, title_h},
title, font_delta, true, GEMUI_ALIGN_LEFT, t->fg_bright);
gemui_rect_t inp_r{box.x + pad, box.y + title_h + spx(6, ui), box.w - pad * 2, inp_h};
draw_single_line_editor(cr, t, inp_r, modal_editor_, ph, true, fpx, ui);
gemui_hit_add(app_, inp_r, HIT_MODAL_INPUT, 0);
int btn_y = box.y + box.h - btn_h - pad;
gemui_rect_t cancel_r{box.x + box.w - btn_w - pad, btn_y, btn_w, btn_h};
gemui_rect_t ok_r{cancel_r.x - btn_w - spx(6, ui), btn_y, btn_w, btn_h};
draw_ui_button(app_, cr, ok_r, "OK", fpx, ui, HIT_MODAL_OK, 0, true, false, false);
draw_ui_button(app_, cr, cancel_r, "Cancel", fpx, ui, HIT_MODAL_CANCEL, 0, false, false, false);
}
void AppWindow::draw(cairo_t* cr, int w, int h) {
Layout lay = compute_layout(w, h);
draw_top_bar(cr, lay);
std::string addr = col_to_letters(grid_.active_col()) + std::to_string(grid_.active_row() + 1);
formula_bar_.draw(app_, cr, lay.formula_bar, addr, grid_.editor(),
grid_.is_editing() && grid_.is_formula_bar_focused(), lay.ui,
HIT_ADDR_BOX, HIT_FORMULA_INPUT);
grid_.draw(app_, cr, wb_, lay.grid, lay.ui);
draw_bottom_bar(cr, lay);
draw_modal(cr, w, h, lay.ui);
}
void AppWindow::commit_edit_if_active() {
if (!grid_.is_editing()) return;
const Cell* c = wb_.get_cell(wb_.active_sheet(), grid_.active_row(), grid_.active_col());
std::string prev = c ? c->raw_input : "";
std::string next = grid_.editor().text;
grid_.commit_edit(wb_);
if (next != prev) {
dirty_ = true;
update_title();
}
}
void AppWindow::open_modal(ModalKind kind, const std::string& initial_text) {
commit_edit_if_active();
modal_ = kind;
if (kind == ModalKind::Menu) {
menu_sel_ = 0;
menu_scroll_ = 0;
} else if (kind == ModalKind::Help) {
help_scroll_ = 0;
} else if (kind == ModalKind::ConfirmExit) {
exit_sel_ = 0;
quit_after_save_ = false;
} else if (kind == ModalKind::FormatCell) {
format_sel_ = 0;
const Cell* c = wb_.get_cell(wb_.active_sheet(), grid_.active_row(), grid_.active_col());
std::string cur = c ? c->number_format : "";
for (int i = 0; i < kFormatPresetCount; ++i) {
if (cur == kFormatPresets[i].fmt) {
format_sel_ = i;
break;
}
}
} else if (kind != ModalKind::ContextMenu) {
modal_editor_.set_text(initial_text);
}
gemui_request_redraw(app_);
}
void AppWindow::close_modal() {
modal_ = ModalKind::Closed;
ctx_items_.clear();
gemui_request_redraw(app_);
}
void AppWindow::request_quit() {
commit_edit_if_active();
if (gemui_file_dialog_active(app_)) {
gemui_file_dialog_close(app_);
}
if (!dirty_) {
gemui_quit(app_, 0);
return;
}
open_modal(ModalKind::ConfirmExit);
}
void AppWindow::confirm_exit_save() {
close_modal();
if (!current_path_.empty() &&
(ends_with_ci(current_path_, ".htab") || ends_with_ci(current_path_, ".json"))) {
if (save_native_to(current_path_)) {
gemui_quit(app_, 0);
}
return;
}
quit_after_save_ = true;
save_native_dialog();
}
std::string AppWindow::dialog_initial_dir() const {
if (current_path_.empty()) return "";
size_t slash = current_path_.find_last_of('/');
if (slash == std::string::npos) return "";
if (slash == 0) return "/";
return current_path_.substr(0, slash);
}
std::string AppWindow::dialog_initial_name(const std::string& default_name,
const std::string& ext_override,
const std::string& suffix_before_ext) const {
if (current_path_.empty()) return default_name;
size_t slash = current_path_.find_last_of('/');
std::string base = (slash == std::string::npos) ? current_path_ : current_path_.substr(slash + 1);
if (base.empty()) return default_name;
size_t dot = base.find_last_of('.');
std::string stem = (dot == std::string::npos) ? base : base.substr(0, dot);
if (stem.empty()) return default_name;
return stem + suffix_before_ext + ext_override;
}
void AppWindow::open_file_dialog() {
if (grid_.is_editing()) grid_.commit_edit(wb_);
if (modal_ != ModalKind::Closed) close_modal();
std::string dir = dialog_initial_dir();
gemui_open_file_dialog(app_, "Open Workbook / CSV", dir.empty() ? nullptr : dir.c_str(),
".htab,.csv,.json", &AppWindow::cb_open_file_done, this);
}
void AppWindow::save_native_dialog() {
if (grid_.is_editing()) grid_.commit_edit(wb_);
if (modal_ != ModalKind::Closed) close_modal();
std::string dir = dialog_initial_dir();
std::string name = dialog_initial_name("workbook.htab", ".htab");
gemui_save_file_dialog(app_, "Save Workbook (.htab)",
dir.empty() ? nullptr : dir.c_str(), name.c_str(),
".htab,.json", ".htab", &AppWindow::cb_save_native_done, this);
}
void AppWindow::export_csv_dialog(bool formulas) {
if (grid_.is_editing()) grid_.commit_edit(wb_);
if (modal_ != ModalKind::Closed) close_modal();
std::string dir = dialog_initial_dir();
std::string name = dialog_initial_name(formulas ? "export_formulas.csv" : "export.csv",
".csv", formulas ? "_formulas" : "");
gemui_save_file_dialog(app_,
formulas ? "Export CSV (Formulas)" : "Export CSV (Values)",
dir.empty() ? nullptr : dir.c_str(), name.c_str(),
".csv", ".csv",
formulas ? &AppWindow::cb_export_csv_formulas_done
: &AppWindow::cb_export_csv_values_done,
this);
}
void AppWindow::delete_selected_rows() {
if (grid_.is_editing()) grid_.commit_edit(wb_);
int sheet = wb_.active_sheet();
CellRange sel = grid_.selection_range(sheet);
wb_.delete_rows(sheet, sel.r1, sel.row_count());
grid_.set_active_cell(wb_, sel.r1, grid_.active_col(), false);
grid_.sync_editor_from_cell(wb_);
dirty_ = true;
update_title();
}
void AppWindow::delete_selected_cols() {
if (grid_.is_editing()) grid_.commit_edit(wb_);
int sheet = wb_.active_sheet();
CellRange sel = grid_.selection_range(sheet);
wb_.delete_cols(sheet, sel.c1, sel.col_count());
grid_.set_active_cell(wb_, grid_.active_row(), sel.c1, false);
grid_.sync_editor_from_cell(wb_);
dirty_ = true;
update_title();
}
void AppWindow::close_sheet(int idx) {
if (grid_.is_editing()) grid_.commit_edit(wb_);
if (wb_.delete_sheet(idx)) {
dirty_ = true;
if (tab_scroll_ >= wb_.sheet_count()) {
tab_scroll_ = std::max(0, wb_.sheet_count() - 1);
}
grid_.reset_for_sheet(wb_, wb_.active_sheet());
update_title();
gemui_show_toast(app_, "Sheet closed", 1400);
} else {
gemui_show_toast(app_, "Cannot delete last sheet", 1800);
}
gemui_request_redraw(app_);
}
void AppWindow::execute_menu_action(int index) {
close_modal();
switch (index) {
case 0: {
std::vector<Sheet> fresh(1);
fresh[0].name = "Sheet1";
wb_.replace_all_sheets(std::move(fresh), 0);
current_path_.clear();
dirty_ = false;
grid_.reset_for_sheet(wb_, 0);
update_title();
gemui_show_toast(app_, "New workbook", 1500);
break;
}
case 1:
open_file_dialog();
break;
case 2:
save_native_dialog();
break;
case 3:
export_csv_dialog(false);
break;
case 4:
export_csv_dialog(true);
break;
case 5:
wb_.insert_rows(wb_.active_sheet(), grid_.active_row(), 1);
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
break;
case 6:
delete_selected_rows();
break;
case 7:
wb_.insert_cols(wb_.active_sheet(), grid_.active_col(), 1);
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
break;
case 8:
delete_selected_cols();
break;
case 9:
open_modal(ModalKind::FormatCell);
break;
case 10:
add_new_sheet();
break;
case 11:
open_modal(ModalKind::RenameSheet, wb_.sheet(wb_.active_sheet()).name);
break;
case 12:
close_sheet(wb_.active_sheet());
break;
case 13:
open_modal(ModalKind::GoToCell);
break;
case 14:
open_modal(ModalKind::Help);
break;
case 15:
request_quit();
break;
default:
break;
}
gemui_request_redraw(app_);
}
void AppWindow::execute_ctx_action(CtxAction action) {
int target_sheet = ctx_target_sheet_;
close_modal();
int active = wb_.active_sheet();
CellRange sel = grid_.selection_range(active);
switch (action) {
case CtxAction::Copy:
do_copy(false);
break;
case CtxAction::Cut:
do_copy(true);
break;
case CtxAction::Paste:
do_paste();
break;
case CtxAction::ClearCells:
clear_selection();
break;
case CtxAction::FormatCell:
open_modal(ModalKind::FormatCell);
break;
case CtxAction::InsertRowAbove:
wb_.insert_rows(active, sel.r1, 1);
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
break;
case CtxAction::InsertRowBelow:
wb_.insert_rows(active, sel.r2 + 1, 1);
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
break;
case CtxAction::DeleteRow:
delete_selected_rows();
break;
case CtxAction::InsertColLeft:
wb_.insert_cols(active, sel.c1, 1);
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
break;
case CtxAction::InsertColRight:
wb_.insert_cols(active, sel.c2 + 1, 1);
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
break;
case CtxAction::DeleteCol:
delete_selected_cols();
break;
case CtxAction::RenameSheet:
if (target_sheet >= 0 && target_sheet < wb_.sheet_count()) {
switch_sheet(target_sheet);
open_modal(ModalKind::RenameSheet, wb_.sheet(target_sheet).name);
}
break;
case CtxAction::AddSheet:
add_new_sheet();
break;
case CtxAction::DeleteSheet:
close_sheet(target_sheet);
break;
}
gemui_request_redraw(app_);
}
void AppWindow::handle_right_click(int x, int y) {
if (modal_ == ModalKind::ContextMenu) {
close_modal();
} else if (modal_ != ModalKind::Closed) {
return;
}
if (grid_.is_editing()) {
grid_.commit_edit(wb_);
}
// Check sheet tabs first
for (const auto& [rect, sidx] : last_tab_rects_) {
if (point_in_rect(rect, x, y)) {
ctx_items_.clear();
ctx_items_.push_back({"Rename Sheet...", CtxAction::RenameSheet});
ctx_items_.push_back({"Add Sheet", CtxAction::AddSheet});
if (wb_.sheet_count() > 1) {
ctx_items_.push_back({"Close Sheet", CtxAction::DeleteSheet});
}
ctx_x_ = x;
ctx_y_ = y;
ctx_sel_ = 0;
ctx_target_sheet_ = sidx;
open_modal(ModalKind::ContextMenu);
return;
}
}
int r = 0, c = 0;
GridHitRegion reg = grid_.hit_region(wb_, x, y, r, c);
if (reg == GridHitRegion::Outside) return;
int active = wb_.active_sheet();
CellRange sel = grid_.selection_range(active);
ctx_items_.clear();
if (reg == GridHitRegion::RowHeader) {
if (r < sel.r1 || r > sel.r2) {
grid_.set_active_cell(wb_, r, grid_.active_col(), false);
}
ctx_items_.push_back({"Insert Row Above", CtxAction::InsertRowAbove});
ctx_items_.push_back({"Insert Row Below", CtxAction::InsertRowBelow});
ctx_items_.push_back({"Delete Row", CtxAction::DeleteRow});
ctx_items_.push_back({"Format Cell...", CtxAction::FormatCell});
} else if (reg == GridHitRegion::ColHeader) {
if (c < sel.c1 || c > sel.c2) {
grid_.set_active_cell(wb_, grid_.active_row(), c, false);
}
ctx_items_.push_back({"Insert Column Left", CtxAction::InsertColLeft});
ctx_items_.push_back({"Insert Column Right", CtxAction::InsertColRight});
ctx_items_.push_back({"Delete Column", CtxAction::DeleteCol});
ctx_items_.push_back({"Format Cell...", CtxAction::FormatCell});
} else { // DataCell
if (!sel.contains(active, r, c)) {
grid_.set_active_cell(wb_, r, c, false);
}
ctx_items_.push_back({"Copy", CtxAction::Copy});
ctx_items_.push_back({"Cut", CtxAction::Cut});
ctx_items_.push_back({"Paste", CtxAction::Paste});
ctx_items_.push_back({"Clear Cell(s)", CtxAction::ClearCells});
ctx_items_.push_back({"Format Cell...", CtxAction::FormatCell});
ctx_items_.push_back({"Insert Row Above", CtxAction::InsertRowAbove});
ctx_items_.push_back({"Delete Row", CtxAction::DeleteRow});
ctx_items_.push_back({"Insert Column Left", CtxAction::InsertColLeft});
ctx_items_.push_back({"Delete Column", CtxAction::DeleteCol});
}
ctx_x_ = x;
ctx_y_ = y;
ctx_sel_ = 0;
ctx_target_sheet_ = active;
open_modal(ModalKind::ContextMenu);
}
bool AppWindow::jump_to_address(const std::string& raw) {
std::string s(trim_ascii(raw));
if (s.empty()) return false;
// Skip over optional sheet prefix before searching for range separator ':'.
size_t search_from = 0;
if (s[0] == '\'') {
size_t pos = 1;
while (pos < s.size()) {
if (s[pos] == '\'') {
if (pos + 1 < s.size() && s[pos + 1] == '\'') {
pos += 2;
} else {
++pos;
break;
}
} else {
++pos;
}
}
if (pos < s.size() && s[pos] == '!') search_from = pos + 1;
} else {
size_t bang = s.find('!');
if (bang != std::string::npos) search_from = bang + 1;
}
size_t colon = s.find(':', search_from);
std::string_view left_sv =
(colon == std::string::npos)
? std::string_view(s)
: trim_ascii(std::string_view(s).substr(0, colon));
auto left = parse_cell_ref(left_sv);
if (!left.has_value() || left->invalid) {
gemui_show_toast(app_, "Invalid cell reference", 1800);
return false;
}
std::optional<CellRef> right;
if (colon != std::string::npos) {
std::string_view right_sv = trim_ascii(std::string_view(s).substr(colon + 1));
right = parse_cell_ref(right_sv);
if (!right.has_value() || right->invalid ||
(!right->sheet_name.empty() && right->sheet_name != left->sheet_name)) {
gemui_show_toast(app_, "Invalid cell reference", 1800);
return false;
}
}
if (!left->sheet_name.empty()) {
int sidx = wb_.find_sheet(left->sheet_name);
if (sidx < 0) {
gemui_show_toast(app_, "Sheet not found", 1800);
return false;
}
if (sidx != wb_.active_sheet()) {
switch_sheet(sidx);
}
}
if (right.has_value()) {
grid_.set_active_cell(wb_, right->row, right->col, false);
grid_.set_active_cell(wb_, left->row, left->col, true);
} else {
grid_.set_active_cell(wb_, left->row, left->col, false);
}
gemui_request_redraw(app_);
return true;
}
void AppWindow::accept_modal_dialog() {
std::string val(trim_ascii(modal_editor_.text));
ModalKind kind = modal_;
close_modal();
if (val.empty()) return;
if (kind == ModalKind::GoToCell) {
jump_to_address(val);
} else if (kind == ModalKind::RenameSheet) {
if (wb_.rename_sheet(wb_.active_sheet(), val)) {
dirty_ = true;
update_title();
gemui_show_toast(app_, "Sheet renamed", 1500);
} else {
gemui_show_toast(app_, "Invalid or duplicate sheet name", 2000);
}
}
}
bool AppWindow::load_file_auto(const std::string& path) {
std::string err;
bool ok = false;
if (ends_with_ci(path, ".csv")) {
ok = import_csv_file(wb_, wb_.active_sheet(), path, &err);
} else {
ok = load_native_file(wb_, path, &err);
if (!ok && !ends_with_ci(path, ".htab") && !ends_with_ci(path, ".json")) {
std::string csv_err;
if (import_csv_file(wb_, wb_.active_sheet(), path, &csv_err)) {
ok = true;
}
}
}
if (ok) {
current_path_ = path;
dirty_ = false;
grid_.reset_for_sheet(wb_, wb_.active_sheet());
update_title();
gemui_show_toast(app_, "Loaded", 1200);
} else {
gemui_show_toast(app_, err.empty() ? "Load failed" : err.c_str(), 2200);
}
gemui_request_redraw(app_);
return ok;
}
bool AppWindow::save_native_to(const std::string& path) {
std::string err;
if (save_native_file(wb_, path, &err)) {
current_path_ = path;
dirty_ = false;
update_title();
gemui_show_toast(app_, "Saved", 1200);
gemui_request_redraw(app_);
return true;
}
gemui_show_toast(app_, err.empty() ? "Save failed" : err.c_str(), 2500);
gemui_request_redraw(app_);
return false;
}
void AppWindow::export_csv_to(const std::string& path, bool formulas) {
std::string err;
if (export_csv_file(wb_, wb_.active_sheet(), path, formulas, &err)) {
gemui_show_toast(app_, "CSV exported", 1800);
} else {
gemui_show_toast(app_, err.c_str(), 2500);
}
}
void AppWindow::do_copy(bool is_cut) {
CellRange sel = grid_.selection_range(wb_.active_sheet());
ClipboardGrid grid = wb_.copy_range(wb_.active_sheet(), sel, is_cut);
clipboard_.copy_grid(grid);
gemui_show_toast(app_, is_cut ? "Cut" : "Copied", 1000);
}
void AppWindow::do_paste() {
if (clipboard_.has_internal()) {
wb_.paste_range(wb_.active_sheet(), grid_.active_row(), grid_.active_col(),
clipboard_.internal_grid(), true);
clipboard_.clear_cut_flag();
} else {
std::string ext = clipboard_.get_external_text(app_);
if (ext.empty()) return;
auto edits = X11Clipboard::parse_tsv_to_edits(ext, grid_.active_row(), grid_.active_col());
wb_.apply_cell_edits(wb_.active_sheet(), edits);
}
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
}
void AppWindow::clear_selection() {
int sheet = wb_.active_sheet();
CellRange sel = grid_.selection_range(sheet);
if (static_cast<int64_t>(sel.row_count()) * sel.col_count() > 10000) return;
std::vector<CellEdit> edits;
for (int r = sel.r1; r <= sel.r2; ++r) {
for (int c = sel.c1; c <= sel.c2; ++c) {
if (wb_.get_cell(sheet, r, c)) {
edits.push_back(CellEdit{r, c, "", std::nullopt});
}
}
}
if (!edits.empty()) {
wb_.apply_cell_edits(sheet, edits);
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
}
}
void AppWindow::switch_sheet(int idx) {
if (idx < 0 || idx >= wb_.sheet_count()) return;
if (grid_.is_editing()) grid_.commit_edit(wb_);
wb_.set_active_sheet(idx);
grid_.reset_for_sheet(wb_, idx);
if (idx < tab_scroll_) tab_scroll_ = idx;
gemui_request_redraw(app_);
}
void AppWindow::add_new_sheet() {
if (grid_.is_editing()) grid_.commit_edit(wb_);
int idx = wb_.add_sheet();
if (idx >= 0) {
dirty_ = true;
wb_.set_active_sheet(idx);
grid_.reset_for_sheet(wb_, idx);
update_title();
gemui_show_toast(app_, wb_.sheet(idx).name.c_str(), 1000);
}
}
void AppWindow::handle_modal_key(KeySym ks, unsigned int state, const char* utf8) {
if (ks == XK_Escape) {
close_modal();
return;
}
if (modal_ == ModalKind::ContextMenu) {
if (ctx_items_.empty()) {
close_modal();
return;
}
int n = static_cast<int>(ctx_items_.size());
if (ks == XK_Up) {
ctx_sel_ = (ctx_sel_ - 1 + n) % n;
} else if (ks == XK_Down) {
ctx_sel_ = (ctx_sel_ + 1) % n;
} else if (ks == XK_Return || ks == XK_KP_Enter) {
execute_ctx_action(ctx_items_[static_cast<size_t>(ctx_sel_)].action);
}
gemui_request_redraw(app_);
return;
}
if (modal_ == ModalKind::Menu) {
if (ks == XK_Up) {
menu_sel_ = (menu_sel_ - 1 + kMenuItemCount) % kMenuItemCount;
} else if (ks == XK_Down) {
menu_sel_ = (menu_sel_ + 1) % kMenuItemCount;
} else if (ks == XK_Return || ks == XK_KP_Enter) {
execute_menu_action(menu_sel_);
}
gemui_request_redraw(app_);
return;
}
if (modal_ == ModalKind::FormatCell) {
if (ks == XK_Up) {
format_sel_ = (format_sel_ - 1 + kFormatPresetCount) % kFormatPresetCount;
} else if (ks == XK_Down) {
format_sel_ = (format_sel_ + 1) % kFormatPresetCount;
} else if (ks == XK_Return || ks == XK_KP_Enter) {
CellRange sel = grid_.selection_range(wb_.active_sheet());
wb_.apply_range_format(wb_.active_sheet(), sel, kFormatPresets[format_sel_].fmt);
dirty_ = true;
close_modal();
update_title();
}
gemui_request_redraw(app_);
return;
}
if (modal_ == ModalKind::Help) {
int max_scroll = std::max(0, kHelpItemCount - std::max(1, help_visible_rows_));
if (ks == XK_F1 || ks == XK_Return || ks == XK_KP_Enter || ks == XK_q || ks == XK_Q) {
close_modal();
return;
}
if (ks == XK_Up) {
help_scroll_ = std::max(0, help_scroll_ - 1);
} else if (ks == XK_Down) {
help_scroll_ = std::min(max_scroll, help_scroll_ + 1);
} else if (ks == XK_Page_Up) {
help_scroll_ = std::max(0, help_scroll_ - std::max(1, help_visible_rows_ - 1));
} else if (ks == XK_Page_Down) {
help_scroll_ = std::min(max_scroll, help_scroll_ + std::max(1, help_visible_rows_ - 1));
} else if (ks == XK_Home) {
help_scroll_ = 0;
} else if (ks == XK_End) {
help_scroll_ = max_scroll;
}
gemui_request_redraw(app_);
return;
}
if (modal_ == ModalKind::ConfirmExit) {
bool shift = (state & ShiftMask) != 0;
if (ks == XK_Left || (ks == XK_Tab && shift) || ks == XK_ISO_Left_Tab) {
exit_sel_ = (exit_sel_ + 2) % 3;
gemui_request_redraw(app_);
return;
}
if (ks == XK_Right || ks == XK_Tab) {
exit_sel_ = (exit_sel_ + 1) % 3;
gemui_request_redraw(app_);
return;
}
if (ks == XK_s || ks == XK_S) {
confirm_exit_save();
return;
}
if (ks == XK_d || ks == XK_D) {
gemui_quit(app_, 0);
return;
}
if (ks == XK_c || ks == XK_C) {
close_modal();
return;
}
if (ks == XK_Return || ks == XK_KP_Enter) {
if (exit_sel_ == 0) confirm_exit_save();
else if (exit_sel_ == 1) gemui_quit(app_, 0);
else close_modal();
return;
}
return;
}
if (ks == XK_Return || ks == XK_KP_Enter) {
accept_modal_dialog();
return;
}
bool ctrl = (state & ControlMask) != 0;
if (ctrl && normalize_ctrl_keysym(ks) == XK_v) {
std::string ext = clipboard_.get_external_text(app_);
if (!ext.empty()) modal_editor_.insert_utf8(ext.c_str());
gemui_request_redraw(app_);
return;
}
if (modal_editor_.handle_key(ks, state, utf8)) {
gemui_request_redraw(app_);
}
}
void AppWindow::handle_key(KeySym ks, unsigned int state, const char* utf8) {
if (modal_ != ModalKind::Closed) {
handle_modal_key(ks, state, utf8);
return;
}
bool shift = (state & ShiftMask) != 0;
bool ctrl = (state & ControlMask) != 0;
bool alt = (state & Mod1Mask) != 0;
if (grid_.is_editing()) {
if (ctrl && normalize_ctrl_keysym(ks) == XK_q) {
request_quit();
return;
}
if (ctrl && normalize_ctrl_keysym(ks) == XK_g) {
open_modal(ModalKind::GoToCell);
return;
}
if (ks == XK_F1) {
open_modal(ModalKind::Help);
return;
}
if (ks == XK_Escape) {
grid_.cancel_edit(wb_);
gemui_request_redraw(app_);
return;
}
if (ks == XK_Return || ks == XK_KP_Enter) {
grid_.commit_edit(wb_);
dirty_ = true;
grid_.move_active(wb_, shift ? -1 : 1, 0, false);
update_title();
gemui_request_redraw(app_);
return;
}
if (ks == XK_Tab || ks == XK_ISO_Left_Tab) {
bool rev = shift || (ks == XK_ISO_Left_Tab);
grid_.commit_edit(wb_);
dirty_ = true;
grid_.move_active(wb_, 0, rev ? -1 : 1, false);
update_title();
gemui_request_redraw(app_);
return;
}
if (ctrl && normalize_ctrl_keysym(ks) == XK_v) {
std::string ext = clipboard_.get_external_text(app_);
if (!ext.empty()) grid_.editor().insert_utf8(ext.c_str());
gemui_request_redraw(app_);
return;
}
if (grid_.editor().handle_key(ks, state, utf8)) {
gemui_request_redraw(app_);
}
return;
}
if (ctrl) {
KeySym ck = normalize_ctrl_keysym(ks);
if (ck == XK_c) { do_copy(false); gemui_request_redraw(app_); return; }
if (ck == XK_x) { do_copy(true); gemui_request_redraw(app_); return; }
if (ck == XK_v) { do_paste(); gemui_request_redraw(app_); return; }
if (ck == XK_z) {
if (wb_.undo()) {
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
gemui_show_toast(app_, "Undo", 900);
}
gemui_request_redraw(app_);
return;
}
if (ck == XK_y) {
if (wb_.redo()) {
dirty_ = true;
grid_.sync_editor_from_cell(wb_);
update_title();
gemui_show_toast(app_, "Redo", 900);
}
gemui_request_redraw(app_);
return;
}
if (ck == XK_s) {
if (!current_path_.empty() &&
(ends_with_ci(current_path_, ".htab") || ends_with_ci(current_path_, ".json"))) {
save_native_to(current_path_);
} else {
save_native_dialog();
}
return;
}
if (ck == XK_o) { open_file_dialog(); return; }
if (ck == XK_e) { export_csv_dialog(false); return; }
if (ck == XK_g) { open_modal(ModalKind::GoToCell); return; }
if (ck == XK_n) { execute_menu_action(0); return; }
if (ck == XK_q) { request_quit(); return; }
if (ks == XK_Page_Up) {
if (wb_.active_sheet() > 0) switch_sheet(wb_.active_sheet() - 1);
return;
}
if (ks == XK_Page_Down) {
if (wb_.active_sheet() + 1 < wb_.sheet_count()) switch_sheet(wb_.active_sheet() + 1);
return;
}
if (ks == XK_Home) {
grid_.set_active_cell(wb_, 0, 0, shift);
gemui_request_redraw(app_);
return;
}
}
if (ks == XK_F1) { open_modal(ModalKind::Help); return; }
if (ks == XK_F10) { open_modal(ModalKind::Menu); return; }
if (ks == XK_F2) { grid_.start_edit(wb_, false); gemui_request_redraw(app_); return; }
if (ks == XK_Up) { grid_.move_active(wb_, -1, 0, shift); gemui_request_redraw(app_); return; }
if (ks == XK_Down) { grid_.move_active(wb_, 1, 0, shift); gemui_request_redraw(app_); return; }
if (ks == XK_Left) { grid_.move_active(wb_, 0, -1, shift); gemui_request_redraw(app_); return; }
if (ks == XK_Right) { grid_.move_active(wb_, 0, 1, shift); gemui_request_redraw(app_); return; }
if (ks == XK_Return || ks == XK_KP_Enter) {
grid_.move_active(wb_, shift ? -1 : 1, 0, false);
gemui_request_redraw(app_);
return;
}
if (ks == XK_Tab || ks == XK_ISO_Left_Tab) {
bool rev = shift || (ks == XK_ISO_Left_Tab);
grid_.move_active(wb_, 0, rev ? -1 : 1, false);
gemui_request_redraw(app_);
return;
}
if (ks == XK_Page_Up) {
grid_.move_active(wb_, -10, 0, shift);
gemui_request_redraw(app_);
return;
}
if (ks == XK_Page_Down) {
grid_.move_active(wb_, 10, 0, shift);
gemui_request_redraw(app_);
return;
}
if (ks == XK_Home) {
grid_.set_active_cell(wb_, grid_.active_row(), 0, shift);
gemui_request_redraw(app_);
return;
}
if (ks == XK_Delete || ks == XK_BackSpace) {
clear_selection();
gemui_request_redraw(app_);
return;
}
if (!ctrl && !alt && utf8 && utf8[0]) {
std::string init(utf8);
grid_.start_edit(wb_, false, &init);
gemui_request_redraw(app_);
}
}
void AppWindow::handle_ptr(int type, int x, int y, unsigned int btn) {
if (type == GEMUI_PTR_UP && hscroll_dragging_) {
hscroll_dragging_ = false;
gemui_request_redraw(app_);
return;
}
if (type == GEMUI_PTR_MOVE && hscroll_dragging_) {
grid_.handle_hscroll_drag(wb_, x, last_hscroll_r_);
gemui_request_redraw(app_);
return;
}
if (type == GEMUI_PTR_DOWN && btn == Button3) {
handle_right_click(x, y);
return;
}
if (modal_ != ModalKind::Closed) {
if (type == GEMUI_PTR_SCROLL_UP || type == GEMUI_PTR_SCROLL_DOWN) {
int delta = (type == GEMUI_PTR_SCROLL_UP) ? -2 : 2;
if (modal_ == ModalKind::Help) {
int max_scroll = std::max(0, kHelpItemCount - std::max(1, help_visible_rows_));
help_scroll_ = std::clamp(help_scroll_ + delta, 0, max_scroll);
gemui_request_redraw(app_);
} else if (modal_ == ModalKind::Menu) {
menu_sel_ = std::clamp(menu_sel_ + (delta > 0 ? 1 : -1), 0, kMenuItemCount - 1);
gemui_request_redraw(app_);
}
return;
}
if (type == GEMUI_PTR_DOWN && btn == Button1) {
const gemui_hit_t* hit = gemui_hit_test(app_, x, y);
if (!hit) return;
if (hit->id == HIT_MODAL_BACKDROP || hit->id == HIT_MODAL_CANCEL ||
hit->id == HIT_EXIT_CANCEL) {
close_modal();
} else if (hit->id == HIT_EXIT_SAVE) {
confirm_exit_save();
return;
} else if (hit->id == HIT_EXIT_DISCARD) {
gemui_quit(app_, 0);
return;
} else if (hit->id == HIT_MENU_ITEM) {
execute_menu_action(hit->val);
} else if (hit->id == HIT_FORMAT_ITEM) {
CellRange sel = grid_.selection_range(wb_.active_sheet());
wb_.apply_range_format(wb_.active_sheet(), sel, kFormatPresets[hit->val].fmt);
dirty_ = true;
close_modal();
update_title();
} else if (hit->id == HIT_CTX_ITEM) {
if (hit->val >= 0 && hit->val < static_cast<int>(ctx_items_.size())) {
execute_ctx_action(ctx_items_[static_cast<size_t>(hit->val)].action);
}
} else if (hit->id == HIT_MODAL_OK) {
accept_modal_dialog();
}
gemui_request_redraw(app_);
}
return;
}
if (type == GEMUI_PTR_DOWN) {
const gemui_hit_t* hit = gemui_hit_test(app_, x, y);
if (hit) {
if (btn == Button2 && hit->id == HIT_SHEET_TAB) {
close_sheet(hit->val);
return;
}
if (btn == Button1) {
switch (hit->id) {
case HIT_MENU_BTN: open_modal(ModalKind::Menu); return;
case HIT_OPEN_BTN: open_file_dialog(); return;
case HIT_SAVE_BTN: save_native_dialog(); return;
case HIT_CSV_BTN: export_csv_dialog(false); return;
case HIT_UNDO_BTN:
if (wb_.undo()) { dirty_ = true; grid_.sync_editor_from_cell(wb_); update_title(); }
gemui_request_redraw(app_);
return;
case HIT_REDO_BTN:
if (wb_.redo()) { dirty_ = true; grid_.sync_editor_from_cell(wb_); update_title(); }
gemui_request_redraw(app_);
return;
case HIT_FORMAT_BTN: open_modal(ModalKind::FormatCell); return;
case HIT_INS_ROW_BTN: execute_menu_action(5); return;
case HIT_DEL_ROW_BTN: delete_selected_rows(); return;
case HIT_INS_COL_BTN: execute_menu_action(7); return;
case HIT_DEL_COL_BTN: delete_selected_cols(); return;
case HIT_ADDR_BOX:
open_modal(ModalKind::GoToCell);
return;
case HIT_FORMULA_INPUT:
if (!grid_.is_editing()) grid_.start_edit(wb_, true);
else grid_.start_edit(wb_, true, &grid_.editor().text);
gemui_request_redraw(app_);
return;
case HIT_SHEET_TAB:
switch_sheet(hit->val);
return;
case HIT_SHEET_CLOSE:
close_sheet(hit->val);
return;
case HIT_ADD_SHEET:
add_new_sheet();
gemui_request_redraw(app_);
return;
case HIT_HSCROLL:
hscroll_dragging_ = true;
grid_.handle_hscroll_drag(wb_, x, last_hscroll_r_);
gemui_request_redraw(app_);
return;
default:
break;
}
}
}
}
bool committed = false;
if (grid_.handle_pointer(wb_, type, x, y, btn, last_hscroll_r_, committed)) {
if (committed) {
dirty_ = true;
update_title();
}
gemui_request_redraw(app_);
}
}
} // namespace htab::ui