Add color themes + code view with gutter and folding

Color themes (src/theme.h/.cpp): four built-ins (Light, Dark, Monokai,
Solarized Dark) colouring keywords, types, strings, comments, numbers,
preprocessor lines, background/foreground and the current line. View ->
Color Theme... opens the picker (built-in combo + per-role colour
buttons); the choice persists to ~/.config/fdesigner/theme.conf
(FDESIGNER_THEME_CONF overrides). Deliberately separate from the
font-settings branch settings.conf so the two merge cleanly.

Code view (src/codeview.h/.cpp): View -> Code View shows the generated
C++ with a gutter (line numbers, red-dot breakpoints, [-]/[+] fold
toggles) and themed highlighting. Gutter clicks toggle breakpoints
through the real debugger backend (debugger_toggle_breakpoint() in
debugger_ui, new GdbSession::remove_staged_breakpoint() for the
not-yet-live case) and persist to debugger_bps.conf.

Folding covers #region/#endregion, every matched-brace span
(functions, if/else, loops, classes, structs, namespaces,
initializers), multi-line /* */ comments and #if...#endif blocks,
nested in all directions. Braces in strings/chars/raw strings/comments
are ignored; unbalanced input fails gracefully (extra } ignored,
unclosed {/region/#if at EOF produces no fold). Folded lines hide via
an invisible tag (proven to collapse to zero height), so file line
numbers stay exact.

Tests: tests/theme_tests.sh (harness 57 checks) + self-test Phase 8 +
xdotool smoke tests for the code view window and theme dialog.
Clean build, zero warnings; matrix 21/0; debugger 31/31 + 5/5;
widget 40/40 + 5/5.
This commit is contained in:
Muse committed 2026-11-25 12:11:44 -05:00
1 parent 7828ced3d6
commit ad0cd68bf5
14 files changed
+2180 -2

No files matched your search

+49
View File
@@ -297,3 +297,52 @@ project holding every new widget, checks the markers, compiles the
generated app with `-Wall -Wextra`, and runs it briefly. The generator
matrix (`tests/run_matrix.sh` cases 02/03) also covers every new type
automatically via `kTypes`.
## Color themes + code view (2026-11-26)
View -> Code View shows the generated C++ for the current canvas in a
`CodeView` (`src/codeview.h/.cpp`): a `GtkTextView` with a gutter
(`GtkDrawingArea` beside it in one `GtkScrolledWindow`, so it scrolls in
lockstep). The gutter shows line numbers, red-dot breakpoints, and `[-]` /
`[+]` fold toggles. Clicking the fold-marker column folds/unfolds; clicking
elsewhere in the gutter toggles a breakpoint at that line through the real
debugger backend (`debugger_toggle_breakpoint()` in `src/debugger_ui.h/.cpp`,
which stages/inserts into the shared `GdbSession` and persists to
`debugger_bps.conf`); `GdbSession::remove_staged_breakpoint()` was added
because `remove_breakpoint()` needs a live gdb. The current execution line
can be highlighted via `codeview_set_current_line()`.
Color themes (`src/theme.h/.cpp`): four built-ins — Light, Dark, Monokai,
Solarized Dark — colouring keywords, types, strings, comments, numbers,
preprocessor lines, background/foreground and the current line. View ->
Color Theme... opens the picker (built-in combo + per-role colour buttons);
the choice persists to `~/.config/fdesigner/theme.conf`
(`FDESIGNER_THEME_CONF` overrides). Deliberately separate from the
font-settings branch's `settings.conf` / Preferences dialog so the two
merge cleanly; a later pass can move the picker into Preferences.
Gotcha: GTK 3.20+ draws the text area from the `text` subnode, so the
theme CSS must set `textview text`, not just `textview`, or the
background stays white while the tag colours change. Also on this GTK,
`GtkTextTag` "foreground" is write-only and "foreground-rgba" does not
read back — tests read the colour via "foreground-gdk" instead.
Folding (`codeview_find_regions()`, pure, unit-tested) covers every
natural foldable unit: `#region` / `#endregion`, every matched-brace span
(functions, if/else, loops, classes, structs, namespaces, initializers),
multi-line `/* */` comments, and `#if` / `#ifdef` / `#ifndef` ... `#endif`
blocks; nesting works in all directions (braces in regions and vice
versa). Braces in strings, character literals, raw strings and comments
are ignored. Unbalanced input fails gracefully: an unmatched `}` is
ignored and an unclosed `{` / `#region` / `#if` at EOF produces no fold.
Folded lines are hidden with an `invisible` text tag (proven to collapse
them to zero height), so file line numbers stay exact. The fold end line
stays visible (e.g. the closing `}`).
Tests: `tests/theme_tests.sh` (harness `tests/theme_tests.cpp`, 57 checks:
themes, persistence incl. default path, tokeniser, regions incl. nested
and unbalanced, visible lines, widget-level fold/gutter/current-line,
real gutter->debugger toggle with HOME redirected) + self-test Phase 8 +
xdotool smoke tests for the Code View window and the theme dialog.
A live xdotool gutter click on the real app set
`/tmp/fdesigner_codeview/MyWindow.cpp:6|1` in the persisted bps file, and
a fold click collapsed the constructor body (lines 7-20 hidden, 6 -> 21).
+2 -2
View File
@@ -3,8 +3,8 @@ CXXFLAGS ?= -O2 -Wall -Wextra -std=c++17
GTKFLAGS := $(shell pkg-config --cflags gtk+-3.0)
GTKLIBS := $(shell pkg-config --libs gtk+-3.0)
fdesigner: src/main.cpp src/generator.cpp src/project_io.cpp src/debugger.cpp src/debugger_ui.cpp src/model.h src/props.h src/generator.h src/project_io.h src/debugger.h src/debugger_ui.h src/indicators.h src/indicators_embedded.h src/drawings.h src/drawings_embedded.h ui/designer.ui
$(CXX) $(CXXFLAGS) -o $@ src/main.cpp src/generator.cpp src/project_io.cpp src/debugger.cpp src/debugger_ui.cpp $(GTKFLAGS) $(GTKLIBS)
fdesigner: src/main.cpp src/generator.cpp src/project_io.cpp src/debugger.cpp src/debugger_ui.cpp src/theme.cpp src/codeview.cpp src/model.h src/props.h src/generator.h src/project_io.h src/debugger.h src/debugger_ui.h src/theme.h src/codeview.h src/indicators.h src/indicators_embedded.h src/drawings.h src/drawings_embedded.h ui/designer.ui
$(CXX) $(CXXFLAGS) -o $@ src/main.cpp src/generator.cpp src/project_io.cpp src/debugger.cpp src/debugger_ui.cpp src/theme.cpp src/codeview.cpp $(GTKFLAGS) $(GTKLIBS)
src/indicators_embedded.h: src/indicators.h tools/embed_indicators.sh
sh tools/embed_indicators.sh src/indicators.h $@
+655
View File
@@ -0,0 +1,655 @@
// FDesigner code view — implementation. See codeview.h.
#include "codeview.h"
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <map>
namespace {
// ------------------------------------------------------------ pure logic
std::string trim2(const std::string& s) {
size_t a = s.find_first_not_of(" \t\r");
if (a == std::string::npos) return "";
size_t b = s.find_last_not_of(" \t\r");
return s.substr(a, b - a + 1);
}
} // namespace
std::vector<std::string> codeview_split_lines(const std::string& text) {
std::vector<std::string> out;
size_t start = 0;
while (start <= text.size()) {
size_t nl = text.find('\n', start);
if (nl == std::string::npos) {
if (start < text.size()) out.push_back(text.substr(start));
break;
}
std::string ln = text.substr(start, nl - start);
if (!ln.empty() && ln.back() == '\r') ln.pop_back();
out.push_back(ln);
start = nl + 1;
if (start == text.size()) break; // trailing \n: no phantom line
}
return out;
}
std::vector<FoldRegion> codeview_find_regions(
const std::vector<std::string>& lines) {
// Rejoin for a single character stream so strings/comments/braces
// are tracked across line boundaries with exact line numbers.
std::string text;
for (const auto& l : lines) { text += l; text += '\n'; }
std::vector<FoldRegion> out;
std::vector<int> brace_stack;
std::vector<std::pair<int, std::string>> region_stack; // start, label
std::vector<int> if_stack;
auto open_count = [&]() {
return (int)(brace_stack.size() + region_stack.size() +
if_stack.size());
};
size_t n = text.size(), i = 0;
int line = 0; // 0-based line of text[i]
bool line_start = true;
bool in_block_comment = false, in_line_comment = false;
bool in_string = false, in_char = false;
int comment_start = -1;
while (i < n) {
char c = text[i];
if (c == '\n') {
in_line_comment = false;
in_string = false; // unterminated string ends at EOL
in_char = false;
++line;
line_start = true;
++i;
continue;
}
if (in_line_comment) { ++i; continue; }
if (in_block_comment) {
if (c == '*' && i + 1 < n && text[i + 1] == '/') {
in_block_comment = false;
if (line > comment_start)
out.push_back({comment_start, line, "comment",
open_count(), "/* ... */"});
i += 2;
line_start = false;
continue;
}
++i;
continue;
}
if (in_string) {
if (c == '\\' && i + 1 < n) { i += 2; continue; }
if (c == '"') in_string = false;
++i;
continue;
}
if (in_char) {
if (c == '\\' && i + 1 < n) { i += 2; continue; }
if (c == '\'') in_char = false;
++i;
continue;
}
if (line_start && (c == ' ' || c == '\t' || c == '\r')) { ++i; continue; }
if (line_start && c == '#') {
// Preprocessor directive: parse the word, handle the
// foldable ones, then skip the whole line (no braces counted
// inside a directive line).
size_t j = i + 1;
while (j < n && (text[j] == ' ' || text[j] == '\t')) ++j;
size_t ws = j;
while (j < n && std::isalpha((unsigned char)text[j])) ++j;
std::string word = text.substr(ws, j - ws);
std::string rest;
if (word == "region" || word == "if" || word == "ifdef" ||
word == "ifndef") {
size_t eol = text.find('\n', j);
rest = trim2(text.substr(
j, (eol == std::string::npos ? n : eol) - j));
if (rest.size() > 48) rest = rest.substr(0, 48);
}
if (word == "region") {
region_stack.push_back(
{line, rest.empty() ? std::string("#region")
: "#region " + rest});
} else if (word == "endregion") {
if (!region_stack.empty()) {
auto st = region_stack.back();
region_stack.pop_back();
if (line > st.first)
out.push_back({st.first, line, "region",
(int)(brace_stack.size() +
region_stack.size() +
if_stack.size()),
st.second});
}
} else if (word == "if" || word == "ifdef" || word == "ifndef") {
if_stack.push_back(line);
} else if (word == "endif") {
if (!if_stack.empty()) {
int st = if_stack.back();
if_stack.pop_back();
if (line > st)
out.push_back({st, line, "preproc",
(int)(brace_stack.size() +
region_stack.size() +
if_stack.size()),
"#" + word + " " + rest});
}
}
// Skip to end of line.
while (i < n && text[i] != '\n') ++i;
continue;
}
line_start = false;
if (c == '/' && i + 1 < n && text[i + 1] == '/') {
in_line_comment = true;
i += 2;
continue;
}
if (c == '/' && i + 1 < n && text[i + 1] == '*') {
in_block_comment = true;
comment_start = line;
i += 2;
continue;
}
if (c == '"') {
// Raw string? R"delim( ... )delim" — also u8R/uR/UR/LR.
bool raw = false;
std::string delim;
if (i >= 1 && text[i - 1] == 'R' &&
(i < 2 || !std::isalnum((unsigned char)text[i - 2]) ||
text[i - 2] == 'u' || text[i - 2] == 'U' ||
text[i - 2] == 'L')) {
size_t p = i + 1;
while (p < n && text[p] != '(' && text[p] != '\n' &&
text[p] != ' ' && text[p] != '\t')
++p;
if (p < n && text[p] == '(') {
raw = true;
delim = text.substr(i + 1, p - (i + 1));
}
}
if (raw) {
std::string close = ")" + delim + "\"";
size_t f = text.find(close, i + 1);
if (f == std::string::npos) {
i = n; // unterminated raw string: rest is string
break;
}
for (size_t k = i; k < f + close.size(); ++k)
if (text[k] == '\n') ++line;
i = f + close.size();
continue;
}
in_string = true;
++i;
continue;
}
if (c == '\'') {
// Digit separator (1'000) is not a character literal.
bool sep = i > 0 && (std::isalnum((unsigned char)text[i - 1]) ||
text[i - 1] == '_');
if (!sep) in_char = true;
++i;
continue;
}
if (c == '{') {
brace_stack.push_back(line);
++i;
continue;
}
if (c == '}') {
if (!brace_stack.empty()) {
int st = brace_stack.back();
brace_stack.pop_back();
if (line > st) {
std::string label = trim2(lines[(size_t)st]);
if (label.size() > 48) label = label.substr(0, 48);
out.push_back({st, line, "brace",
(int)(brace_stack.size() +
region_stack.size() +
if_stack.size()),
label});
}
}
// Unmatched '}': ignored — graceful, no fold, no crash.
++i;
continue;
}
++i;
}
// Unclosed '{', #region, #if, /* at EOF: dropped, no wrong fold.
// Depths: recompute properly — a region's depth is the number of
// other regions strictly containing it.
for (auto& r : out) {
int d = 0;
for (const auto& o : out)
if (&o != &r && o.start_line < r.start_line &&
o.end_line > r.end_line)
++d;
r.depth = d;
}
std::sort(out.begin(), out.end(), [](const FoldRegion& a,
const FoldRegion& b) {
if (a.start_line != b.start_line) return a.start_line < b.start_line;
return a.end_line > b.end_line; // outermost first at same start
});
return out;
}
bool codeview_line_hidden(int line, const std::vector<FoldRegion>& regions,
const std::set<int>& folded_starts) {
for (const auto& r : regions)
if (folded_starts.count(r.start_line) && line > r.start_line &&
line < r.end_line)
return true;
return false;
}
std::vector<int> codeview_visible_lines(
const std::vector<std::string>& lines,
const std::set<int>& folded_starts) {
std::vector<FoldRegion> regions = codeview_find_regions(lines);
std::vector<int> out;
for (int l = 0; l < (int)lines.size(); ++l)
if (!codeview_line_hidden(l, regions, folded_starts)) out.push_back(l);
return out;
}
namespace {
// ------------------------------------------------------------ widget
struct CodeViewData {
GtkWidget* box = nullptr;
GtkWidget* gutter = nullptr;
GtkWidget* scroll = nullptr;
GtkWidget* view = nullptr;
std::string file_path;
std::vector<std::string> lines;
std::vector<FoldRegion> regions;
std::set<int> folded; // 0-based region start lines
std::set<int> breakpoints; // 1-based file lines
int current_line = 0; // 1-based, 0 = none
CodeTheme theme;
std::function<bool(const std::string&, int)> bp_cb;
GtkTextTag* fold_tag = nullptr;
GtkTextTag* cur_tag = nullptr;
};
CodeViewData* data_of(GtkWidget* cv) {
return (CodeViewData*)g_object_get_data(G_OBJECT(cv), "codeview-data");
}
void free_data(gpointer p) { delete (CodeViewData*)p; }
bool parse_hex(const std::string& s, double& r, double& g, double& b) {
if (s.size() != 7 || s[0] != '#') return false;
auto hv = [](char c) -> int {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
int v[6];
for (int k = 0; k < 6; ++k) {
v[k] = hv(s[1 + k]);
if (v[k] < 0) return false;
}
r = (v[0] * 16 + v[1]) / 255.0;
g = (v[2] * 16 + v[3]) / 255.0;
b = (v[4] * 16 + v[5]) / 255.0;
return true;
}
bool is_dark_theme(const CodeTheme& t) {
double r = 1, g = 1, b = 1;
if (!parse_hex(t.background, r, g, b)) return false;
return (0.299 * r + 0.587 * g + 0.114 * b) < 0.5;
}
void apply_folds(CodeViewData* d) {
GtkTextBuffer* buf =
gtk_text_view_get_buffer(GTK_TEXT_VIEW(d->view));
if (!d->fold_tag) return;
GtkTextIter a, b;
gtk_text_buffer_get_bounds(buf, &a, &b);
gtk_text_buffer_remove_tag(buf, d->fold_tag, &a, &b);
for (int start : d->folded) {
for (const auto& r : d->regions) {
if (r.start_line != start) continue;
if (r.end_line <= r.start_line + 1) continue; // nothing to hide
GtkTextIter sa, sb;
gtk_text_buffer_get_iter_at_line(buf, &sa, r.start_line + 1);
gtk_text_buffer_get_iter_at_line(buf, &sb, r.end_line);
gtk_text_buffer_apply_tag(buf, d->fold_tag, &sa, &sb);
}
}
}
void apply_current_line(CodeViewData* d) {
GtkTextBuffer* buf =
gtk_text_view_get_buffer(GTK_TEXT_VIEW(d->view));
if (!d->cur_tag) return;
GtkTextIter a, b;
gtk_text_buffer_get_bounds(buf, &a, &b);
gtk_text_buffer_remove_tag(buf, d->cur_tag, &a, &b);
if (d->current_line >= 1 &&
d->current_line <= gtk_text_buffer_get_line_count(buf)) {
GtkTextIter sa, sb;
gtk_text_buffer_get_iter_at_line(buf, &sa, d->current_line - 1);
if (d->current_line < gtk_text_buffer_get_line_count(buf))
gtk_text_buffer_get_iter_at_line(buf, &sb, d->current_line);
else
gtk_text_buffer_get_end_iter(buf, &sb);
gtk_text_buffer_apply_tag(buf, d->cur_tag, &sa, &sb);
}
}
void queue_redraw(CodeViewData* d) {
gtk_widget_queue_draw(d->gutter);
gtk_widget_queue_draw(d->view);
}
bool region_starts_at(CodeViewData* d, int line0) {
for (const auto& r : d->regions)
if (r.start_line == line0) return true;
return false;
}
// Buffer line (0-based) at a gutter y in widget coordinates; -1 if none.
int gutter_line_at_y(CodeViewData* d, double y) {
GtkTextBuffer* buf =
gtk_text_view_get_buffer(GTK_TEXT_VIEW(d->view));
int count = gtk_text_buffer_get_line_count(buf);
for (int ln = 0; ln < count; ++ln) {
GtkTextIter it;
gtk_text_buffer_get_iter_at_line(buf, &it, ln);
gint ly, lh;
gtk_text_view_get_line_yrange(GTK_TEXT_VIEW(d->view), &it, &ly, &lh);
if (lh > 0 && y >= ly && y < ly + lh) return ln;
}
return -1;
}
void toggle_fold_line(CodeViewData* d, int line0) {
if (!region_starts_at(d, line0)) return;
if (d->folded.count(line0)) d->folded.erase(line0);
else d->folded.insert(line0);
apply_folds(d);
queue_redraw(d);
}
void toggle_bp_line(CodeViewData* d, int line1) {
bool now_set;
if (d->bp_cb) now_set = d->bp_cb(d->file_path, line1);
else now_set = !d->breakpoints.count(line1);
if (now_set) d->breakpoints.insert(line1);
else d->breakpoints.erase(line1);
queue_redraw(d);
}
gboolean on_gutter_draw(GtkWidget* gutter, cairo_t* cr, gpointer user) {
CodeViewData* d = (CodeViewData*)user;
GtkAllocation alloc;
gtk_widget_get_allocation(gutter, &alloc);
bool dark = is_dark_theme(d->theme);
if (dark) cairo_set_source_rgb(cr, 0.17, 0.17, 0.17);
else cairo_set_source_rgb(cr, 0.93, 0.93, 0.93);
cairo_rectangle(cr, 0, 0, alloc.width, alloc.height);
cairo_fill(cr);
// Divider between gutter and code.
cairo_set_source_rgb(cr, dark ? 0.35 : 0.75, dark ? 0.35 : 0.75,
dark ? 0.35 : 0.75);
cairo_rectangle(cr, alloc.width - 1, 0, 1, alloc.height);
cairo_fill(cr);
double fr, fg, fb;
if (!parse_hex(d->theme.foreground, fr, fg, fb)) { fr = fg = fb = 0.2; }
double cr_, cg, cb;
if (!parse_hex(d->theme.current_line, cr_, cg, cb)) { cr_ = cg = cb = 0.9; }
GtkTextBuffer* buf =
gtk_text_view_get_buffer(GTK_TEXT_VIEW(d->view));
int count = gtk_text_buffer_get_line_count(buf);
cairo_select_font_face(cr, "monospace", CAIRO_FONT_SLANT_NORMAL,
CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size(cr, 11);
for (int ln = 0; ln < count; ++ln) {
GtkTextIter it;
gtk_text_buffer_get_iter_at_line(buf, &it, ln);
gint y, h;
gtk_text_view_get_line_yrange(GTK_TEXT_VIEW(d->view), &it, &y, &h);
if (h <= 0) continue; // folded away
if (d->current_line == ln + 1) {
cairo_set_source_rgb(cr, cr_, cg, cb);
cairo_rectangle(cr, 0, y, alloc.width, h);
cairo_fill(cr);
}
bool is_start = region_starts_at(d, ln);
if (is_start) {
bool folded = d->folded.count(ln) != 0;
cairo_set_source_rgb(cr, dark ? 0.75 : 0.4, dark ? 0.75 : 0.4,
dark ? 0.75 : 0.4);
cairo_rectangle(cr, 3, y + (h - 12) / 2, 12, 12);
cairo_stroke(cr);
cairo_move_to(cr, 6, y + (h - 12) / 2 + 9);
cairo_show_text(cr, folded ? "+" : "-");
}
if (d->breakpoints.count(ln + 1)) {
cairo_set_source_rgb(cr, 0.88, 0.11, 0.14);
cairo_arc(cr, 26, y + h / 2.0, 5, 0, 2 * 3.14159265);
cairo_fill(cr);
}
char num[16];
std::snprintf(num, sizeof num, "%d", ln + 1);
cairo_text_extents_t ext;
cairo_text_extents(cr, num, &ext);
cairo_set_source_rgba(cr, fr, fg, fb, 0.65);
cairo_move_to(cr, alloc.width - 6 - ext.width, y + h - 4);
cairo_show_text(cr, num);
}
return FALSE;
}
gboolean on_gutter_press(GtkWidget*, GdkEventButton* ev, gpointer user) {
CodeViewData* d = (CodeViewData*)user;
if (ev->button != 1) return FALSE;
int ln = gutter_line_at_y(d, ev->y);
if (ln < 0) return FALSE;
if (ev->x < 18) {
if (region_starts_at(d, ln)) toggle_fold_line(d, ln);
} else {
toggle_bp_line(d, ln + 1);
}
return TRUE;
}
void on_view_size_allocate(GtkWidget*, GtkAllocation* alloc,
gpointer user) {
CodeViewData* d = (CodeViewData*)user;
gtk_widget_set_size_request(d->gutter, 76, alloc->height);
}
void on_scroll_changed(GtkAdjustment*, gpointer user) {
CodeViewData* d = (CodeViewData*)user;
gtk_widget_queue_draw(d->gutter);
}
} // namespace
// ------------------------------------------------------------ public API
GtkWidget* codeview_new() {
CodeViewData* d = new CodeViewData();
d->theme = theme_current();
GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
d->box = box;
d->gutter = gtk_drawing_area_new();
gtk_widget_set_size_request(d->gutter, 76, 100);
gtk_widget_add_events(d->gutter, GDK_BUTTON_PRESS_MASK);
g_signal_connect(d->gutter, "draw", G_CALLBACK(on_gutter_draw), d);
g_signal_connect(d->gutter, "button-press-event",
G_CALLBACK(on_gutter_press), d);
d->view = gtk_text_view_new();
gtk_text_view_set_editable(GTK_TEXT_VIEW(d->view), FALSE);
gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(d->view), FALSE);
gtk_text_view_set_monospace(GTK_TEXT_VIEW(d->view), TRUE);
gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(d->view), GTK_WRAP_NONE);
gtk_text_view_set_left_margin(GTK_TEXT_VIEW(d->view), 8);
d->scroll = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(d->scroll),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
GtkWidget* inner = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
gtk_box_pack_start(GTK_BOX(inner), d->gutter, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(inner), d->view, TRUE, TRUE, 0);
gtk_container_add(GTK_CONTAINER(d->scroll), inner);
gtk_box_pack_start(GTK_BOX(box), d->scroll, TRUE, TRUE, 0);
g_signal_connect(d->view, "size-allocate",
G_CALLBACK(on_view_size_allocate), d);
GtkAdjustment* vadj = gtk_scrolled_window_get_vadjustment(
GTK_SCROLLED_WINDOW(d->scroll));
g_signal_connect(vadj, "value-changed", G_CALLBACK(on_scroll_changed), d);
g_object_set_data_full(G_OBJECT(box), "codeview-data", d, free_data);
return box;
}
GtkWidget* codeview_text_view(GtkWidget* cv) {
CodeViewData* d = data_of(cv);
return d ? d->view : nullptr;
}
void codeview_set_text(GtkWidget* cv, const std::string& text,
const std::string& file_path) {
CodeViewData* d = data_of(cv);
if (!d) return;
d->file_path = file_path;
d->lines = codeview_split_lines(text);
d->regions = codeview_find_regions(d->lines);
d->folded.clear();
d->breakpoints.clear();
d->current_line = 0;
GtkTextBuffer* buf =
gtk_text_view_get_buffer(GTK_TEXT_VIEW(d->view));
gtk_text_buffer_set_text(buf, text.c_str(), -1);
GtkTextTagTable* table = gtk_text_buffer_get_tag_table(buf);
d->fold_tag = gtk_text_tag_table_lookup(table, "theme-fold-hidden");
if (!d->fold_tag)
d->fold_tag = gtk_text_buffer_create_tag(buf, "theme-fold-hidden",
"invisible", TRUE, NULL);
d->cur_tag = gtk_text_tag_table_lookup(table, "theme-current-line");
if (!d->cur_tag)
d->cur_tag = gtk_text_buffer_create_tag(
buf, "theme-current-line", "background",
d->theme.current_line.c_str(), NULL);
else
g_object_set(d->cur_tag, "background", d->theme.current_line.c_str(),
NULL);
theme_highlight_buffer(buf, d->theme);
theme_apply_to_view(d->view, d->theme);
apply_folds(d);
queue_redraw(d);
}
std::string codeview_file_path(GtkWidget* cv) {
CodeViewData* d = data_of(cv);
return d ? d->file_path : "";
}
int codeview_line_count(GtkWidget* cv) {
CodeViewData* d = data_of(cv);
if (!d) return 0;
// File lines, not the buffer count: a trailing newline makes the
// buffer report one extra empty line.
return (int)d->lines.size();
}
void codeview_set_theme(GtkWidget* cv, const CodeTheme& theme) {
CodeViewData* d = data_of(cv);
if (!d) return;
d->theme = theme;
GtkTextBuffer* buf =
gtk_text_view_get_buffer(GTK_TEXT_VIEW(d->view));
if (d->cur_tag)
g_object_set(d->cur_tag, "background", theme.current_line.c_str(),
NULL);
theme_highlight_buffer(buf, theme);
theme_apply_to_view(d->view, theme);
queue_redraw(d);
}
CodeTheme codeview_theme(GtkWidget* cv) {
CodeViewData* d = data_of(cv);
return d ? d->theme : CodeTheme();
}
void codeview_set_current_line(GtkWidget* cv, int line_1based) {
CodeViewData* d = data_of(cv);
if (!d) return;
d->current_line = line_1based;
apply_current_line(d);
queue_redraw(d);
}
int codeview_current_line(GtkWidget* cv) {
CodeViewData* d = data_of(cv);
return d ? d->current_line : 0;
}
void codeview_set_breakpoint_callback(
GtkWidget* cv,
const std::function<bool(const std::string&, int)>& cb) {
CodeViewData* d = data_of(cv);
if (d) d->bp_cb = cb;
}
void codeview_set_breakpoint_lines(GtkWidget* cv,
const std::set<int>& lines_1based) {
CodeViewData* d = data_of(cv);
if (!d) return;
d->breakpoints = lines_1based;
queue_redraw(d);
}
std::set<int> codeview_breakpoint_lines(GtkWidget* cv) {
CodeViewData* d = data_of(cv);
return d ? d->breakpoints : std::set<int>();
}
std::vector<FoldRegion> codeview_regions(GtkWidget* cv) {
CodeViewData* d = data_of(cv);
return d ? d->regions : std::vector<FoldRegion>();
}
bool codeview_toggle_fold_at(GtkWidget* cv, int line_1based) {
CodeViewData* d = data_of(cv);
if (!d) return false;
int line0 = line_1based - 1;
if (!region_starts_at(d, line0)) return false;
toggle_fold_line(d, line0);
return true;
}
bool codeview_is_folded(GtkWidget* cv, int line_1based) {
CodeViewData* d = data_of(cv);
return d && d->folded.count(line_1based - 1) != 0;
}
void codeview_gutter_click(GtkWidget* cv, int line_1based, bool in_fold_zone) {
CodeViewData* d = data_of(cv);
if (!d) return;
int line0 = line_1based - 1;
if (in_fold_zone && region_starts_at(d, line0)) toggle_fold_line(d, line0);
else if (!in_fold_zone) toggle_bp_line(d, line_1based);
}
void codeview_toggle_breakpoint_at(GtkWidget* cv, int line_1based) {
CodeViewData* d = data_of(cv);
if (d) toggle_bp_line(d, line_1based);
}
+94
View File
@@ -0,0 +1,94 @@
// FDesigner code view — GtkTextView showing generated code, with a
// gutter (line numbers, red-dot breakpoints, fold toggles) and syntax
// highlighting from a CodeTheme (src/theme.h).
//
// Folding covers every natural foldable unit the scanner can find:
// * #region / #endregion blocks (nested)
// * every matched-brace span: functions, if/else, loops, classes,
// structs, namespaces, initializer blocks, any other {} block
// * multi-line /* */ comments
// * preprocessor #if / #ifdef / #ifndef ... #endif blocks
// Braces inside strings, character literals, raw strings and comments
// are ignored, so a '{' in a string never opens a fold. Unbalanced
// input fails gracefully: an unmatched '}' is ignored and an unclosed
// '{' / #region / #if at end of file simply produces no fold — never a
// crash and never a wrong (over-long) fold.
//
// Foldable regions are found by the pure function
// codeview_find_regions(); the widget hides folded lines with an
// invisible text tag (proven to collapse them to zero height), so file
// line numbers stay exact and breakpoint lines keep their meaning.
// The gutter is a GtkDrawingArea beside the text view inside one
// GtkScrolledWindow, so it scrolls in lockstep. Clicking the fold
// marker column toggles the fold; clicking anywhere else in the gutter
// toggles a breakpoint at that line via the callback installed with
// codeview_set_breakpoint_callback() — main wires it to
// debugger_toggle_breakpoint(), i.e. the real GdbSession machinery.
#pragma once
#include <gtk/gtk.h>
#include <functional>
#include <set>
#include <string>
#include <vector>
#include "theme.h"
// One foldable span. Lines are 0-based, inclusive at both ends; only
// spans longer than one line are reported (a single-line {} has
// nothing to hide). kind is "region", "brace", "comment" or "preproc".
// depth is the nesting depth (0 = outermost). label is a short human
// hint (region name, "#if ...", or the trimmed first line).
struct FoldRegion {
int start_line = 0;
int end_line = 0;
std::string kind;
int depth = 0;
std::string label;
};
// Pure fold logic (no GTK) — unit-testable.
std::vector<std::string> codeview_split_lines(const std::string& text);
std::vector<FoldRegion> codeview_find_regions(
const std::vector<std::string>& lines);
// True when 0-based `line` is strictly inside any region whose start
// line is in `folded_starts` (start/end lines themselves stay visible).
bool codeview_line_hidden(int line, const std::vector<FoldRegion>& regions,
const std::set<int>& folded_starts);
// 0-based lines that stay visible given the folded start lines.
std::vector<int> codeview_visible_lines(
const std::vector<std::string>& lines,
const std::set<int>& folded_starts);
// Widget: a GtkBox (gutter + scrolled text view). All line numbers in
// the widget API are 1-based file lines.
GtkWidget* codeview_new();
GtkWidget* codeview_text_view(GtkWidget* cv); // inner GtkTextView
void codeview_set_text(GtkWidget* cv, const std::string& text,
const std::string& file_path);
std::string codeview_file_path(GtkWidget* cv);
int codeview_line_count(GtkWidget* cv);
void codeview_set_theme(GtkWidget* cv, const CodeTheme& theme);
CodeTheme codeview_theme(GtkWidget* cv);
// Highlight this file line as the current execution line (0 = none).
void codeview_set_current_line(GtkWidget* cv, int line_1based);
int codeview_current_line(GtkWidget* cv);
// Breakpoint dots (1-based file lines). The widget does not own the
// debugger; toggling goes through the callback, which returns true
// when the breakpoint is now set. With no callback, toggling just
// flips the local dot (test mode).
void codeview_set_breakpoint_callback(
GtkWidget* cv,
const std::function<bool(const std::string&, int)>& cb);
void codeview_set_breakpoint_lines(GtkWidget* cv,
const std::set<int>& lines_1based);
std::set<int> codeview_breakpoint_lines(GtkWidget* cv);
// Fold state (0-based start lines in the pure API; 1-based here).
std::vector<FoldRegion> codeview_regions(GtkWidget* cv);
bool codeview_toggle_fold_at(GtkWidget* cv, int line_1based);
bool codeview_is_folded(GtkWidget* cv, int line_1based);
// Test helpers: simulate a gutter click at a file line. `in_fold_zone`
// mimics clicking the [-]/[+] marker column.
void codeview_gutter_click(GtkWidget* cv, int line_1based, bool in_fold_zone);
void codeview_toggle_breakpoint_at(GtkWidget* cv, int line_1based);
+9
View File
@@ -806,6 +806,15 @@ bool GdbSession::add_breakpoint(const std::string& location, Breakpoint& out,
return true;
}
bool GdbSession::remove_staged_breakpoint(const std::string& location) {
auto it = std::find_if(bps_.begin(), bps_.end(), [&](const Breakpoint& b) {
return b.location == location && b.id == 0;
});
if (it == bps_.end()) return false;
bps_.erase(it);
return true;
}
bool GdbSession::remove_breakpoint(int id, std::string& err) {
MiValue r;
if (!command("-break-delete " + std::to_string(id), r, err)) return false;
+4
View File
@@ -141,6 +141,10 @@ public:
// before Run); start() inserts it into gdb. Returns false if the
// location does not parse.
bool stage_breakpoint(const std::string& location);
// Erase a staged (not yet inserted into gdb, id == 0) breakpoint
// by location. Used by the code-view gutter toggle: remove_breakpoint
// needs a live gdb, this one does not. Returns false if not staged.
bool remove_staged_breakpoint(const std::string& location);
bool add_breakpoint(const std::string& location, Breakpoint& out,
std::string& err);
bool remove_breakpoint(int id, std::string& err);
+64
View File
@@ -705,3 +705,67 @@ void debugger_window_open(GtkWidget* parent) {
}
refresh_buttons();
}
// ------------------------------------------------------- gutter integration
// Code-view gutter toggles a file:line breakpoint in the shared session.
// See debugger_ui.h. The session is created on demand (restoring saved
// breakpoints) so a gutter click works before the debugger window opens.
namespace {
const Breakpoint* find_bp(const GdbSession& sess, const std::string& file,
int line) {
std::string loc = file + ":" + std::to_string(line);
for (const auto& b : sess.breakpoints()) {
if (b.location == loc) return &b;
if (!b.file.empty() && b.file == file && b.line == line) return &b;
}
return nullptr;
}
} // namespace
bool debugger_toggle_breakpoint(const std::string& file, int line) {
std::string err;
if (!ensure_session(err)) return false;
std::string loc = file + ":" + std::to_string(line);
const Breakpoint* hit = find_bp(*g_session, file, line);
if (hit) {
if (hit->id == 0) {
g_session->remove_staged_breakpoint(loc);
} else if (g_session->is_alive()) {
if (!g_session->remove_breakpoint(hit->id, err)) return true;
} else {
g_session->remove_staged_breakpoint(loc);
}
g_session->save_breakpoints();
if (g_dbg_window) sync_ui_from_session();
return false;
}
bool ok;
if (g_session->is_alive()) {
Breakpoint b;
ok = g_session->add_breakpoint(loc, b, err);
} else {
ok = g_session->stage_breakpoint(loc);
}
if (ok) {
g_session->save_breakpoints();
if (g_dbg_window) sync_ui_from_session();
}
return ok;
}
bool debugger_has_breakpoint(const std::string& file, int line) {
std::string err;
if (!ensure_session(err)) return false;
return find_bp(*g_session, file, line) != nullptr;
}
std::vector<int> debugger_breakpoint_lines(const std::string& file) {
std::vector<int> out;
std::string err;
if (!ensure_session(err)) return out;
for (const auto& b : g_session->breakpoints())
if (!b.file.empty() && b.file == file && b.line > 0)
out.push_back(b.line);
return out;
}
+12
View File
@@ -4,11 +4,23 @@
#pragma once
#include <gtk/gtk.h>
#include <string>
#include <vector>
// Show the debugger window (creates it on first call, raises it after).
void debugger_window_open(GtkWidget* parent);
// Open the debugger settings dialog (also reachable from the Debug menu's
// "Debugger" sub-menu and the Settings button in the debugger window).
void debugger_settings_open(GtkWidget* parent);
// Code-view gutter integration: toggle a file:line breakpoint in the
// shared debugger session (creates the session and restores persisted
// breakpoints first if needed, persists the change). Returns true when
// the breakpoint is now set. With gdb running the breakpoint is inserted
// / deleted live; otherwise it is staged for the next Run.
bool debugger_toggle_breakpoint(const std::string& file, int line);
bool debugger_has_breakpoint(const std::string& file, int line);
// 1-based lines in `file` that currently have breakpoints.
std::vector<int> debugger_breakpoint_lines(const std::string& file);
// True once the debugger window has been created (used by the GUI smoke test).
bool debugger_window_is_open();
// For tests: the settings currently in effect (loaded from disk at open).
+258
View File
@@ -37,6 +37,8 @@
#include "project_io.h"
#include "debugger.h"
#include "debugger_ui.h"
#include "theme.h"
#include "codeview.h"
// ---------------------------------------------------------------- state
@@ -2372,6 +2374,80 @@ static Project snapshot_project() {
return p;
}
// ------------------------------------------------------- code view (View menu)
//
// View -> Code View shows the generated C++ for the current canvas in a
// CodeView (line numbers, breakpoint dots, folding, themed highlighting).
// View -> Color Theme opens the theme picker; applying repaints this view.
static GtkWidget* g_codeview_window = nullptr;
static GtkWidget* g_codeview = nullptr;
static void refresh_code_view() {
if (!g_codeview) return;
Project p = snapshot_project();
GenResult r = generate_project(p, p.widgets, "/tmp/fdesigner_codeview");
std::string path, text;
if (r.ok) {
for (const auto& f : r.files)
if (f.size() > 4 && f.compare(f.size() - 4, 4, ".cpp") == 0 &&
f.find("MyWindow") != std::string::npos) {
path = f;
break;
}
if (path.empty())
for (const auto& f : r.files)
if (f.size() > 4 && f.compare(f.size() - 4, 4, ".cpp") == 0) {
path = f;
break;
}
if (!path.empty()) {
gchar* c = nullptr;
if (g_file_get_contents(path.c_str(), &c, nullptr, nullptr) &&
c) {
text = c;
g_free(c);
}
}
}
if (path.empty()) {
path = "/tmp/fdesigner_codeview/MyWindow.cpp";
text = "// Generate a design first: File -> Generate C++/GTK...\n";
}
codeview_set_text(g_codeview, text, path);
std::set<int> bps;
for (int ln : debugger_breakpoint_lines(path)) bps.insert(ln);
codeview_set_breakpoint_lines(g_codeview, bps);
status("Code view - " + path);
}
static void open_code_view() {
if (!g_codeview_window) {
g_codeview_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(g_codeview_window),
"Code - generated C++");
gtk_window_set_default_size(GTK_WINDOW(g_codeview_window), 900, 600);
gtk_window_set_transient_for(GTK_WINDOW(g_codeview_window),
GTK_WINDOW(g_window));
g_codeview = codeview_new();
codeview_set_theme(g_codeview, theme_current());
codeview_set_breakpoint_callback(g_codeview,
debugger_toggle_breakpoint);
gtk_container_add(GTK_CONTAINER(g_codeview_window), g_codeview);
g_signal_connect(
g_codeview_window, "destroy",
G_CALLBACK(+[](GtkWidget*, gpointer) {
g_codeview_window = nullptr;
g_codeview = nullptr;
}),
nullptr);
gtk_widget_show_all(g_codeview_window);
} else {
gtk_window_present(GTK_WINDOW(g_codeview_window));
}
refresh_code_view();
}
static void on_generate(GtkMenuItem*, gpointer) {
GtkWidget* dlg = gtk_file_chooser_dialog_new(
"Generate C++/GTK — choose a folder", GTK_WINDOW(g_window),
@@ -3025,6 +3101,152 @@ static gboolean selftest_step(gpointer) {
sess2.breakpoints()[0].location == "main");
}
// Phase 8: color themes + code-view gutter / folding.
{
// Four distinct built-ins; unknown name falls back to Light.
std::vector<std::string> tnames = CodeTheme::builtin_names();
check(tnames.size() == 4);
CodeTheme light = CodeTheme::builtin("Light");
CodeTheme dark = CodeTheme::builtin("Dark");
CodeTheme mono = CodeTheme::builtin("Monokai");
CodeTheme solar = CodeTheme::builtin("Solarized Dark");
check(light.keyword != dark.keyword &&
dark.keyword != mono.keyword &&
mono.keyword != solar.keyword);
check(light.background != dark.background);
check(CodeTheme::builtin("Nope").name == "Light");
check(CodeTheme::valid_color("#1a2b3c") &&
!CodeTheme::valid_color("red") &&
!CodeTheme::valid_color("#12345"));
// Persistence, including a customised colour on a named base.
CodeTheme custom = dark;
custom.keyword = "#ff0000";
check(custom.save("/tmp/fdesigner_theme.conf"));
CodeTheme reloaded;
check(reloaded.load("/tmp/fdesigner_theme.conf"));
check(reloaded.name == "Dark" && reloaded.keyword == "#ff0000" &&
reloaded.background == dark.background);
// Missing file: load fails, defaults kept.
CodeTheme missing;
check(!missing.load("/tmp/fdesigner_theme_no_such.conf"));
check(missing.name == "Light");
// Tokeniser spans on a representative snippet.
std::string sample =
"#include <gtk/gtk.h>\n// hi\nint main() { const char* s = "
"\"x\"; return 42; }\n";
std::vector<HlSpan> spans = theme_tokenize(sample);
auto has_span = [&](const std::string& kind,
const std::string& word) {
for (const auto& sp : spans)
if (sp.kind == kind &&
sample.substr(sp.start, sp.end - sp.start) == word)
return true;
return false;
};
check(has_span("preprocessor", "#include <gtk/gtk.h>"));
check(has_span("comment", "// hi"));
check(has_span("type", "int"));
check(has_span("keyword", "return"));
check(has_span("string", "\"x\""));
check(has_span("number", "42"));
// Folding: nested braces, region in/around braces, multi-line
// comment, #if block, unbalanced braces fail gracefully.
std::vector<std::string> flines = {
"#region Outer", // 0
"class Foo {", // 1
" void bar() {", // 2
" if (x) {", // 3
" work();", // 4
" }", // 5
" /* multi", // 6
" line */", // 7
" }", // 8
"};", // 9
"#endregion", // 10
"#if DEBUG", // 11
"int d = 1;", // 12
"#endif", // 13
"}", // 14: extra close, ignored
"int leftover() {", // 15: never closed, no fold
" return 1;", // 16
};
std::vector<FoldRegion> regs = codeview_find_regions(flines);
check(regs.size() == 6);
auto has_region = [&](int st, int en, const std::string& kind) {
for (const auto& r : regs)
if (r.start_line == st && r.end_line == en &&
r.kind == kind)
return true;
return false;
};
check(has_region(0, 10, "region"));
check(has_region(1, 9, "brace"));
check(has_region(2, 8, "brace"));
check(has_region(3, 5, "brace"));
check(has_region(6, 7, "comment"));
check(has_region(11, 13, "preproc"));
// Depths nest: region 0, class 1, method 2, if 3.
for (const auto& r : regs) {
if (r.start_line == 0) check(r.depth == 0);
if (r.start_line == 1) check(r.depth == 1);
if (r.start_line == 3) check(r.depth == 3);
}
// Visible lines: folding the region hides 1..9 only.
std::vector<int> vis = codeview_visible_lines(flines, {0});
check(vis.size() == 8 && vis[0] == 0 && vis[1] == 10);
vis = codeview_visible_lines(flines, {2});
check(vis.size() == 12);
vis = codeview_visible_lines(flines, {0, 2});
check(vis.size() == 8); // inner fold adds nothing under outer
// Widget level: fold toggle, gutter clicks, current line, theme.
std::string ftext;
for (const auto& l : flines) ftext += l + "\n";
GtkWidget* cv = codeview_new();
codeview_set_text(cv, ftext, "/tmp/fdesigner_codeview_test.cpp");
check(codeview_line_count(cv) == 17);
check(codeview_regions(cv).size() == 6);
check(codeview_toggle_fold_at(cv, 3)); // bar() starts line 3
check(codeview_is_folded(cv, 3));
check(!codeview_toggle_fold_at(cv, 5)); // line 5: no region start
codeview_gutter_click(cv, 3, true); // fold-zone click unfolds
check(!codeview_is_folded(cv, 3));
codeview_gutter_click(cv, 5, false); // breakpoint dot on line 5
check(codeview_breakpoint_lines(cv).count(5) == 1);
codeview_gutter_click(cv, 5, false);
check(codeview_breakpoint_lines(cv).empty());
codeview_set_current_line(cv, 4);
check(codeview_current_line(cv) == 4);
codeview_set_theme(cv, dark);
GtkTextBuffer* cbuf = gtk_text_view_get_buffer(
GTK_TEXT_VIEW(codeview_text_view(cv)));
GtkTextTag* kw = gtk_text_tag_table_lookup(
gtk_text_buffer_get_tag_table(cbuf), "theme-keyword");
// "foreground" is write-only on GtkTextTag and
// "foreground-rgba" does not read back on this GTK; the
// readable form is "foreground-gdk" (16-bit channels, 8-bit
// values stored as v*257). Dark keyword #569cd6.
GdkColor* col = nullptr;
if (kw) g_object_get(kw, "foreground-gdk", &col, NULL);
check(kw && col && col->red / 257 == 0x56 &&
col->green / 257 == 0x9c && col->blue / 257 == 0xd6);
if (col) g_boxed_free(g_type_from_name("GdkColor"), col);
gtk_widget_destroy(cv);
// Breakpoint staging through the real backend (temp file only).
GdbSession bsess;
check(bsess.stage_breakpoint("foo.cpp:42"));
check(bsess.stage_breakpoint("foo.cpp:42")); // dedup, still 1
check(bsess.breakpoints().size() == 1);
check(bsess.remove_staged_breakpoint("foo.cpp:42"));
check(!bsess.remove_staged_breakpoint("foo.cpp:42"));
check(bsess.breakpoints().empty());
check(bsess.stage_breakpoint("foo.cpp:7"));
check(bsess.save_breakpoints("/tmp/fdesigner_theme_bps.conf"));
GdbSession bsess2;
check(bsess2.load_breakpoints("/tmp/fdesigner_theme_bps.conf"));
check(bsess2.breakpoints().size() == 1 &&
bsess2.breakpoints()[0].location == "foo.cpp:7");
}
std::printf("SELFTEST %s items=%zu\n", ok ? "PASS" : "FAIL",
g_items.size());
std::fflush(stdout);
@@ -3111,6 +3333,27 @@ int main(int argc, char** argv) {
if (mi_save)
g_signal_connect(mi_save, "activate", G_CALLBACK(on_save), nullptr);
// View menu -> code view window / theme picker.
GObject* mi_code = gtk_builder_get_object(builder, "mi_view_code");
if (mi_code)
g_signal_connect(mi_code, "activate",
G_CALLBACK(+[](GtkMenuItem*, gpointer) {
open_code_view();
}),
nullptr);
GObject* mi_theme = gtk_builder_get_object(builder, "mi_view_theme");
if (mi_theme)
g_signal_connect(mi_theme, "activate",
G_CALLBACK(+[](GtkMenuItem*, gpointer) {
theme_picker_open(g_window,
+[](const CodeTheme& t) {
if (g_codeview)
codeview_set_theme(
g_codeview, t);
});
}),
nullptr);
// Debug menu -> stepping debugger window / settings.
GObject* mi_dbg = gtk_builder_get_object(builder, "mi_debug_open");
if (mi_dbg)
@@ -3192,6 +3435,21 @@ int main(int argc, char** argv) {
},
nullptr);
// Test hooks (also used by tests/theme_tests.sh): open the code
// view / theme picker at startup.
if (std::getenv("FDESIGNER_OPEN_CODEVIEW") != nullptr)
g_idle_add(+[](gpointer) -> gboolean {
open_code_view();
return G_SOURCE_REMOVE;
},
nullptr);
if (std::getenv("FDESIGNER_OPEN_THEME") != nullptr)
g_idle_add(+[](gpointer) -> gboolean {
theme_picker_open(g_window, nullptr);
return G_SOURCE_REMOVE;
},
nullptr);
bool selftest = std::getenv("FDESIGNER_SELFTEST") != nullptr;
if (selftest) g_idle_add(selftest_step, nullptr);
+509
View File
@@ -0,0 +1,509 @@
// FDesigner code-view color themes — implementation. See theme.h.
#include "theme.h"
#include <sys/stat.h>
#include <algorithm>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <map>
#include <set>
namespace {
std::string home_dir() {
const char* h = std::getenv("HOME");
return h ? h : "";
}
bool ensure_parent_dir(const std::string& path) {
size_t slash = path.rfind('/');
if (slash == std::string::npos) return true;
std::string dir = path.substr(0, slash);
std::string cur;
for (size_t i = 1; i <= dir.size(); ++i) {
if (i == dir.size() || dir[i] == '/') {
cur = dir.substr(0, i);
if (!cur.empty()) ::mkdir(cur.c_str(), 0755);
}
}
return true;
}
std::string trim_s(const std::string& s) {
size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos) return "";
size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
// C++ type words get the "type" colour; the rest of the reserved words
// get "keyword". Words in neither set stay plain foreground.
const std::set<std::string>& type_words() {
static const std::set<std::string> t = {
"bool", "char", "char8_t", "char16_t", "char32_t", "double", "float",
"int", "long", "short", "signed", "unsigned", "void", "wchar_t",
"size_t", "ssize_t", "string", "vector", "map", "set", "list",
"array", "pair", "tuple", "optional", "uint8_t", "uint16_t",
"uint32_t", "uint64_t", "int8_t", "int16_t", "int32_t", "int64_t",
"nullptr_t", "GtkWidget", "GtkTextBuffer", "GtkTextIter",
};
return t;
}
const std::set<std::string>& keyword_words() {
static const std::set<std::string> k = {
"alignas", "alignof", "and", "and_eq", "asm", "auto", "break",
"case", "catch", "class", "concept", "const", "consteval",
"constexpr", "constinit", "continue", "decltype", "default",
"delete", "do", "else", "enum", "explicit", "export", "extern",
"false", "for", "friend", "goto", "if", "inline", "mutable",
"namespace", "new", "noexcept", "not", "not_eq", "operator", "or",
"or_eq", "private", "protected", "public", "register",
"reinterpret_cast", "requires", "return", "sizeof", "static",
"static_assert", "static_cast", "struct", "switch", "template",
"this", "thread_local", "throw", "true", "try", "typedef",
"typeid", "typename", "union", "using", "virtual", "volatile",
"while", "xor", "xor_eq", "override", "final",
};
return k;
}
bool ident_start(char c) {
return std::isalpha((unsigned char)c) || c == '_';
}
bool ident_char(char c) {
return std::isalnum((unsigned char)c) || c == '_';
}
bool is_digit(char c) { return c >= '0' && c <= '9'; }
bool is_hex(char c) {
return is_digit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
CodeTheme g_current;
bool g_current_loaded = false;
} // namespace
bool CodeTheme::valid_color(const std::string& s) {
if (s.size() != 7 || s[0] != '#') return false;
for (size_t i = 1; i < 7; ++i)
if (!is_hex(s[i])) return false;
return true;
}
std::vector<std::string> CodeTheme::builtin_names() {
return {"Light", "Dark", "Monokai", "Solarized Dark"};
}
CodeTheme CodeTheme::builtin(const std::string& name) {
CodeTheme t;
if (name == "Dark") {
t.name = "Dark";
t.background = "#1e1e1e"; t.foreground = "#d4d4d4";
t.keyword = "#569cd6"; t.type = "#4ec9b0"; t.string = "#ce9178";
t.comment = "#6a9955"; t.number = "#b5cea8";
t.preprocessor = "#c586c0"; t.current_line = "#2a2d2e";
} else if (name == "Monokai") {
t.name = "Monokai";
t.background = "#272822"; t.foreground = "#f8f8f2";
t.keyword = "#f92672"; t.type = "#66d9ef"; t.string = "#e6db74";
t.comment = "#75715e"; t.number = "#ae81ff";
t.preprocessor = "#fd971f"; t.current_line = "#3e3d32";
} else if (name == "Solarized Dark") {
t.name = "Solarized Dark";
t.background = "#002b36"; t.foreground = "#839496";
t.keyword = "#859900"; t.type = "#2aa198"; t.string = "#b58900";
t.comment = "#586e75"; t.number = "#d33682";
t.preprocessor = "#cb4b16"; t.current_line = "#073642";
} else {
t.name = "Light"; // default, incl. unknown names
}
return t;
}
bool CodeTheme::is_builtin(const std::string& name) {
for (const auto& n : builtin_names())
if (n == name) return true;
return false;
}
std::string CodeTheme::default_path() {
const char* e = std::getenv("FDESIGNER_THEME_CONF");
if (e && *e) return e;
return home_dir() + "/.config/fdesigner/theme.conf";
}
bool CodeTheme::save(const std::string& path) const {
std::string p = path.empty() ? default_path() : path;
ensure_parent_dir(p);
std::ofstream f(p);
if (!f) return false;
f << "theme=" << name << "\n"
<< "background=" << background << "\n"
<< "foreground=" << foreground << "\n"
<< "keyword=" << keyword << "\n"
<< "type=" << type << "\n"
<< "string=" << string << "\n"
<< "comment=" << comment << "\n"
<< "number=" << number << "\n"
<< "preprocessor=" << preprocessor << "\n"
<< "current_line=" << current_line << "\n";
return (bool)f;
}
bool CodeTheme::load(const std::string& path) {
std::string p = path.empty() ? default_path() : path;
std::ifstream f(p);
if (!f) return false;
std::map<std::string, std::string> kv;
std::string line;
while (std::getline(f, line)) {
std::string t = trim_s(line);
if (t.empty() || t[0] == '#') continue;
size_t eq = t.find('=');
if (eq == std::string::npos) continue;
kv[trim_s(t.substr(0, eq))] = trim_s(t.substr(eq + 1));
}
std::string nm = kv.count("theme") ? kv["theme"] : "Light";
CodeTheme base = (nm == "Custom") ? builtin("Dark") : builtin(nm);
base.name = nm; // keep the stored name, even if customised
auto take = [&](const char* key, std::string& field) {
auto it = kv.find(key);
if (it != kv.end() && valid_color(it->second)) field = it->second;
};
take("background", base.background);
take("foreground", base.foreground);
take("keyword", base.keyword);
take("type", base.type);
take("string", base.string);
take("comment", base.comment);
take("number", base.number);
take("preprocessor", base.preprocessor);
take("current_line", base.current_line);
*this = base;
return true;
}
std::string CodeTheme::css() const {
// GTK 3.20+ draws the text area from the "text" subnode of the
// textview: setting background/color on "textview" alone leaves
// the text area at the default white. Set both nodes.
return "textview text { background-color: " + background +
"; color: " + foreground + "; }"
" textview { background-color: " + background +
"; color: " + foreground + "; }";
}
CodeTheme theme_current() {
if (!g_current_loaded) {
g_current = CodeTheme();
g_current.load(); // missing file: defaults stand
g_current_loaded = true;
}
return g_current;
}
void theme_set_current(const CodeTheme& t) {
g_current = t;
g_current_loaded = true;
g_current.save();
}
// ------------------------------------------------------------ tokeniser
std::vector<HlSpan> theme_tokenize(const std::string& code) {
std::vector<HlSpan> out;
size_t n = code.size(), i = 0;
bool line_start = true; // only whitespace seen so far on this line
while (i < n) {
char c = code[i];
if (c == '\n') { line_start = true; ++i; continue; }
if (line_start && (c == ' ' || c == '\t' || c == '\r')) { ++i; continue; }
if (line_start && c == '#') {
size_t s = i;
while (i < n && code[i] != '\n') ++i;
out.push_back({s, i, "preprocessor"});
continue;
}
line_start = false;
if (c == '/' && i + 1 < n && code[i + 1] == '/') {
size_t s = i;
while (i < n && code[i] != '\n') ++i;
out.push_back({s, i, "comment"});
continue;
}
if (c == '/' && i + 1 < n && code[i + 1] == '*') {
size_t s = i;
i += 2;
while (i + 1 < n && !(code[i] == '*' && code[i + 1] == '/')) ++i;
if (i + 1 < n) i += 2;
else i = n;
out.push_back({s, i, "comment"});
continue;
}
if (c == '"') {
size_t s = i++;
while (i < n && code[i] != '"' && code[i] != '\n') {
if (code[i] == '\\' && i + 1 < n) ++i;
++i;
}
if (i < n && code[i] == '"') ++i;
out.push_back({s, i, "string"});
continue;
}
if (c == '\'') {
// A ' between identifier/digit chars is a C++14 digit
// separator (1'000), not a character literal.
bool sep = i > 0 && (ident_char(code[i - 1]));
if (!sep) {
size_t s = i++;
while (i < n && code[i] != '\'' && code[i] != '\n') {
if (code[i] == '\\' && i + 1 < n) ++i;
++i;
}
if (i < n && code[i] == '\'') ++i;
out.push_back({s, i, "string"});
continue;
}
++i;
continue;
}
if (is_digit(c) || (c == '.' && i + 1 < n && is_digit(code[i + 1]))) {
size_t s = i;
if (c == '0' && i + 1 < n &&
(code[i + 1] == 'x' || code[i + 1] == 'X')) {
i += 2;
while (i < n && (is_hex(code[i]) || code[i] == '\'')) ++i;
} else {
while (i < n &&
(is_digit(code[i]) || code[i] == '.' ||
code[i] == '_' || code[i] == '\'' ||
code[i] == 'e' || code[i] == 'E' ||
((code[i] == '+' || code[i] == '-') &&
i > s && (code[i - 1] == 'e' || code[i - 1] == 'E'))))
++i;
while (i < n && std::isalpha((unsigned char)code[i])) ++i;
}
out.push_back({s, i, "number"});
continue;
}
if (ident_start(c)) {
size_t s = i;
while (i < n && ident_char(code[i])) ++i;
std::string w = code.substr(s, i - s);
if (type_words().count(w))
out.push_back({s, i, "type"});
else if (keyword_words().count(w))
out.push_back({s, i, "keyword"});
continue;
}
++i;
}
return out;
}
// ------------------------------------------------------------ GTK apply
namespace {
GtkTextTag* ensure_tag(GtkTextBuffer* buf, const char* name,
const std::string& color) {
GtkTextTagTable* table = gtk_text_buffer_get_tag_table(buf);
GtkTextTag* tag = gtk_text_tag_table_lookup(table, name);
if (!tag) {
tag = gtk_text_buffer_create_tag(buf, name, "foreground", color.c_str(),
NULL);
} else {
g_object_set(tag, "foreground", color.c_str(), NULL);
}
return tag;
}
} // namespace
void theme_highlight_buffer(GtkTextBuffer* buf, const CodeTheme& theme) {
if (!buf) return;
GtkTextIter a, b;
gtk_text_buffer_get_bounds(buf, &a, &b);
gchar* text = gtk_text_buffer_get_text(buf, &a, &b, FALSE);
std::string code = text ? text : "";
g_free(text);
static const char* kinds[] = {"keyword", "type", "string", "comment",
"number", "preprocessor"};
std::map<std::string, GtkTextTag*> tags;
for (const char* k : kinds) {
std::string color;
if (!std::strcmp(k, "keyword")) color = theme.keyword;
else if (!std::strcmp(k, "type")) color = theme.type;
else if (!std::strcmp(k, "string")) color = theme.string;
else if (!std::strcmp(k, "comment")) color = theme.comment;
else if (!std::strcmp(k, "number")) color = theme.number;
else color = theme.preprocessor;
std::string tagname = std::string("theme-") + k;
tags[k] = ensure_tag(buf, tagname.c_str(), color);
gtk_text_buffer_remove_tag(buf, tags[k], &a, &b);
}
for (const HlSpan& s : theme_tokenize(code)) {
auto it = tags.find(s.kind);
if (it == tags.end()) continue;
GtkTextIter sa, sb;
gtk_text_buffer_get_iter_at_offset(buf, &sa, (gint)s.start);
gtk_text_buffer_get_iter_at_offset(buf, &sb, (gint)s.end);
gtk_text_buffer_apply_tag(buf, it->second, &sa, &sb);
}
}
void theme_apply_to_view(GtkWidget* view, const CodeTheme& theme) {
if (!view) return;
GtkCssProvider* provider = (GtkCssProvider*)g_object_get_data(
G_OBJECT(view), "theme-css-provider");
if (!provider) {
provider = gtk_css_provider_new();
gtk_style_context_add_provider(
gtk_widget_get_style_context(view), GTK_STYLE_PROVIDER(provider),
GTK_STYLE_PROVIDER_PRIORITY_USER);
g_object_set_data_full(G_OBJECT(view), "theme-css-provider", provider,
(GDestroyNotify)g_object_unref);
}
GError* error = nullptr;
gtk_css_provider_load_from_data(provider, theme.css().c_str(), -1, &error);
if (error) {
std::fprintf(stderr, "fdesigner: theme CSS failed: %s\n",
error->message);
g_error_free(error);
}
}
// ------------------------------------------------------------ picker dialog
namespace {
struct PickerCtx {
CodeTheme edited;
GtkWidget* combo = nullptr;
std::map<std::string, GtkWidget*> buttons; // role -> GtkColorButton
std::map<std::string, std::string*> fields; // role -> CodeTheme field
};
std::string color_of_button(GtkWidget* b) {
GdkRGBA rgba;
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(b), &rgba);
char buf[16];
std::snprintf(buf, sizeof buf, "#%02x%02x%02x",
(int)(rgba.red * 255 + 0.5), (int)(rgba.green * 255 + 0.5),
(int)(rgba.blue * 255 + 0.5));
return buf;
}
void set_button_color(GtkWidget* b, const std::string& hex) {
GdkRGBA rgba;
if (!gdk_rgba_parse(&rgba, hex.c_str()))
gdk_rgba_parse(&rgba, "#000000");
gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(b), &rgba);
}
void picker_refresh_from_combo(PickerCtx* ctx) {
gchar* name = gtk_combo_box_text_get_active_text(
GTK_COMBO_BOX_TEXT(ctx->combo));
if (!name) return;
CodeTheme base = CodeTheme::builtin(name);
g_free(name);
// Switching the built-in resets the colours to that theme; the
// user then customises from there.
ctx->edited = base;
for (const auto& kv : ctx->fields)
set_button_color(ctx->buttons[kv.first], *kv.second);
}
} // namespace
bool theme_picker_open(GtkWidget* parent,
const std::function<void(const CodeTheme&)>& on_apply) {
PickerCtx ctx;
ctx.edited = theme_current();
ctx.fields = {
{"background", &ctx.edited.background},
{"foreground", &ctx.edited.foreground},
{"keyword", &ctx.edited.keyword},
{"type", &ctx.edited.type},
{"string", &ctx.edited.string},
{"comment", &ctx.edited.comment},
{"number", &ctx.edited.number},
{"preprocessor", &ctx.edited.preprocessor},
{"current_line", &ctx.edited.current_line},
};
GtkWidget* dlg = gtk_dialog_new_with_buttons(
"Color Theme", GTK_WINDOW(parent), GTK_DIALOG_MODAL, "_Cancel",
GTK_RESPONSE_CANCEL, "_Apply", GTK_RESPONSE_APPLY, NULL);
gtk_window_set_default_size(GTK_WINDOW(dlg), 420, 480);
GtkWidget* content = gtk_dialog_get_content_area(GTK_DIALOG(dlg));
GtkWidget* grid = gtk_grid_new();
gtk_grid_set_row_spacing(GTK_GRID(grid), 6);
gtk_grid_set_column_spacing(GTK_GRID(grid), 12);
gtk_container_set_border_width(GTK_CONTAINER(grid), 12);
gtk_container_add(GTK_CONTAINER(content), grid);
GtkWidget* name_lbl = gtk_label_new("Theme");
gtk_widget_set_halign(name_lbl, GTK_ALIGN_START);
gtk_grid_attach(GTK_GRID(grid), name_lbl, 0, 0, 1, 1);
ctx.combo = gtk_combo_box_text_new();
for (const auto& n : CodeTheme::builtin_names())
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(ctx.combo),
n.c_str());
{
// Select by index: a text combo has no per-row ids.
int active = 0;
const std::vector<std::string> names = CodeTheme::builtin_names();
for (size_t k = 0; k < names.size(); ++k)
if (names[k] == ctx.edited.name) active = (int)k;
gtk_combo_box_set_active(GTK_COMBO_BOX(ctx.combo), active);
}
gtk_grid_attach(GTK_GRID(grid), ctx.combo, 1, 0, 1, 1);
static const char* roles[][2] = {
{"background", "Background"}, {"foreground", "Foreground"},
{"keyword", "Keyword"}, {"type", "Type"},
{"string", "String"}, {"comment", "Comment"},
{"number", "Number"}, {"preprocessor", "Preprocessor"},
{"current_line", "Current line"},
};
int row = 1;
for (const auto& r : roles) {
GtkWidget* lbl = gtk_label_new(r[1]);
gtk_widget_set_halign(lbl, GTK_ALIGN_START);
gtk_grid_attach(GTK_GRID(grid), lbl, 0, row, 1, 1);
GtkWidget* btn = gtk_color_button_new();
gtk_color_button_set_title(GTK_COLOR_BUTTON(btn), r[1]);
set_button_color(btn, *ctx.fields[r[0]]);
ctx.buttons[r[0]] = btn;
gtk_grid_attach(GTK_GRID(grid), btn, 1, row, 1, 1);
++row;
}
GtkWidget* note = gtk_label_new(
"Pick a built-in theme, then tweak any colour.\n"
"Apply saves to ~/.config/fdesigner/theme.conf.");
gtk_label_set_line_wrap(GTK_LABEL(note), TRUE);
gtk_widget_set_halign(note, GTK_ALIGN_START);
gtk_grid_attach(GTK_GRID(grid), note, 0, row, 2, 1);
g_signal_connect(ctx.combo, "changed",
G_CALLBACK(+[](GtkComboBox*, gpointer d) {
picker_refresh_from_combo((PickerCtx*)d);
}),
&ctx);
gtk_widget_show_all(dlg);
gint resp = gtk_dialog_run(GTK_DIALOG(dlg));
bool applied = false;
if (resp == GTK_RESPONSE_APPLY) {
for (const auto& kv : ctx.fields) *kv.second = color_of_button(ctx.buttons[kv.first]);
// If colours were tweaked away from the named built-in, the
// stored name still records the base theme.
theme_set_current(ctx.edited);
if (on_apply) on_apply(ctx.edited);
applied = true;
}
gtk_widget_destroy(dlg);
return applied;
}
+80
View File
@@ -0,0 +1,80 @@
// FDesigner code-view color themes — syntax-highlighting themes for the
// code view (src/codeview.h). Four built-ins: Light, Dark, Monokai,
// Solarized Dark. Each theme colours keywords, types, strings, comments,
// numbers, preprocessor lines, plus the view background/foreground and
// the current-execution-line background.
//
// Persistence: ~/.config/fdesigner/theme.conf (key=value, same pattern
// as the debugger settings); FDESIGNER_THEME_CONF overrides the path
// (used by tests). The file stores the theme name plus every colour, so
// a hand-edited or picker-customised colour survives a restart: on load
// the named built-in is taken as the base and any colour keys present
// override it. A theme whose colours differ from its named built-in is
// a custom variant of that base; name "Custom" starts from Dark.
//
// NOTE (merge): the font-settings branch owns Edit -> Preferences and
// ~/.config/fdesigner/settings.conf. The theme picker lives under
// View -> Color Theme... and its own theme.conf, deliberately, so the
// two branches merge without touching each other; a later pass can move
// the picker into Preferences.
#pragma once
#include <gtk/gtk.h>
#include <functional>
#include <string>
#include <vector>
struct CodeTheme {
std::string name = "Light";
std::string background = "#ffffff";
std::string foreground = "#1a1a1a";
std::string keyword = "#0000ff";
std::string type = "#008080";
std::string string = "#a31515";
std::string comment = "#008000";
std::string number = "#098658";
std::string preprocessor = "#af00db";
std::string current_line = "#e8f2ff";
static std::vector<std::string> builtin_names(); // Light, Dark, ...
static CodeTheme builtin(const std::string& name); // unknown -> Light
static bool is_builtin(const std::string& name);
// Strict "#rrggbb" (case-insensitive hex). Exposed for tests.
static bool valid_color(const std::string& s);
static std::string default_path(); // ~/.config/fdesigner/theme.conf
bool save(const std::string& path = "") const;
bool load(const std::string& path = "");
// CSS for the view (sets both "textview" and "textview text":
// the text area background lives on the "text" subnode).
std::string css() const;
};
// One highlighted span of C++ source: [start, end) byte offsets, kind
// is one of "keyword", "type", "string", "comment", "number",
// "preprocessor". Pure function of the text (no GTK) — unit-testable.
struct HlSpan {
size_t start = 0, end = 0;
std::string kind;
};
std::vector<HlSpan> theme_tokenize(const std::string& code);
// Apply the theme's token colours to a buffer: creates/updates tags
// named "theme-keyword" etc., clears them over the whole buffer, then
// applies theme_tokenize() spans. The buffer text is unchanged.
void theme_highlight_buffer(GtkTextBuffer* buf, const CodeTheme& theme);
// Install the theme background/foreground on one text view (per-view
// CSS provider, re-appliable).
void theme_apply_to_view(GtkWidget* view, const CodeTheme& theme);
// Theme currently in effect (loaded from disk on first call).
CodeTheme theme_current();
// Make `t` current and persist it.
void theme_set_current(const CodeTheme& t);
// Open the theme picker dialog (theme combo + per-role colour buttons).
// On Apply/OK the choice is saved, made current, and on_apply (if set)
// is called so the caller can repaint open code views. Returns true on
// Apply/OK, false on Cancel.
bool theme_picker_open(GtkWidget* parent,
const std::function<void(const CodeTheme&)>& on_apply);
+323
View File
@@ -0,0 +1,323 @@
// Theme + code-view gutter/folding test harness — exercises
// src/theme.cpp, src/codeview.cpp and the debugger gutter toggle
// (src/debugger_ui.cpp) directly. Run under Xvfb:
// xvfb-run -a ./theme_tests
// Prints one PASS/FAIL line per check; exit 0 only if all pass.
// HOME is redirected to a scratch dir so the debugger toggle test
// never touches the real ~/.config/fdesigner/debugger_bps.conf.
#include <gtk/gtk.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
#include <vector>
#include "codeview.h"
#include "debugger_ui.h"
#include "theme.h"
static int g_pass = 0, g_fail = 0;
static void check(bool cond, const char* name) {
if (cond) {
++g_pass;
std::printf("PASS %s\n", name);
} else {
++g_fail;
std::printf("FAIL %s\n", name);
}
}
static bool file_contains(const std::string& path, const std::string& needle) {
std::ifstream f(path);
if (!f) return false;
std::string all((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
return all.find(needle) != std::string::npos;
}
// The fold sample used by both the pure-logic and widget checks.
// 0 #region Outer 9 };
// 1 class Foo { 10 #endregion
// 2 void bar() { 11 #if DEBUG
// 3 if (x) { 12 int d = 1;
// 4 work(); 13 #endif
// 5 } 14 } <- extra close, ignored
// 6 /* multi 15 int leftover() { <- never closed, no fold
// 7 line */ 16 return 1;
// 8 }
static std::vector<std::string> fold_lines() {
return {"#region Outer",
"class Foo {",
" void bar() {",
" if (x) {",
" work();",
" }",
" /* multi",
" line */",
" }",
"};",
"#endregion",
"#if DEBUG",
"int d = 1;",
"#endif",
"}",
"int leftover() {",
" return 1;"};
}
static std::string join_lines(const std::vector<std::string>& lines) {
std::string out;
for (const auto& l : lines) out += l + "\n";
return out;
}
int main(int argc, char** argv) {
// Isolate all HOME-based config (debugger bps file, theme file).
::setenv("HOME", "/tmp/fdesigner_theme_home", 1);
::setenv("FDESIGNER_THEME_CONF", "", 1);
gtk_init(&argc, &argv);
// 1. Built-in themes.
std::vector<std::string> names = CodeTheme::builtin_names();
check(names.size() == 4, "builtins-count-4");
check(names[0] == "Light" && names[1] == "Dark" &&
names[2] == "Monokai" && names[3] == "Solarized Dark",
"builtins-names");
CodeTheme light = CodeTheme::builtin("Light");
CodeTheme dark = CodeTheme::builtin("Dark");
CodeTheme mono = CodeTheme::builtin("Monokai");
CodeTheme solar = CodeTheme::builtin("Solarized Dark");
check(light.keyword != dark.keyword &&
dark.keyword != mono.keyword &&
mono.keyword != solar.keyword,
"builtins-distinct-keywords");
check(light.background != dark.background &&
dark.background != mono.background,
"builtins-distinct-backgrounds");
check(CodeTheme::builtin("Nope").name == "Light", "builtin-unknown-light");
check(CodeTheme::is_builtin("Dark") && !CodeTheme::is_builtin("Custom"),
"is-builtin");
// 2. Colour validation.
check(CodeTheme::valid_color("#1a2b3c") &&
CodeTheme::valid_color("#FFFFFF") &&
!CodeTheme::valid_color("red") &&
!CodeTheme::valid_color("#12345") &&
!CodeTheme::valid_color("#gggggg") &&
!CodeTheme::valid_color(""),
"valid-color");
// 3. Save / load round-trip at an explicit path, incl. custom colour.
CodeTheme custom = dark;
custom.keyword = "#ff0000";
const char* tpath = "/tmp/fdesigner_theme_harness.conf";
check(custom.save(tpath), "save-roundtrip");
CodeTheme reloaded;
check(reloaded.load(tpath), "load-roundtrip");
check(reloaded.name == "Dark" && reloaded.keyword == "#ff0000" &&
reloaded.background == dark.background,
"roundtrip-values");
// Missing file: load fails, defaults kept.
CodeTheme miss;
check(!miss.load("/tmp/fdesigner_theme_no_such.conf"),
"load-missing-fails");
check(miss.name == "Light", "load-missing-keeps-defaults");
// Garbage in the file does not break loading; bad colours ignored.
{
FILE* f = std::fopen("/tmp/fdesigner_theme_garbage.conf", "w");
std::fprintf(f, "# comment\nnot-a-kv-line\ntheme=Dark\nkeyword=red\n"
"background=#1e1e1e\n");
std::fclose(f);
}
CodeTheme garb;
check(garb.load("/tmp/fdesigner_theme_garbage.conf"),
"load-garbage-file");
check(garb.name == "Dark" && garb.keyword == dark.keyword &&
garb.background == "#1e1e1e",
"garbage-bad-colour-ignored");
// 4. Default-path persistence (HOME is redirected above).
CodeTheme dp = CodeTheme::builtin("Monokai");
theme_set_current(dp);
check(file_contains(
"/tmp/fdesigner_theme_home/.config/fdesigner/theme.conf",
"theme=Monokai"),
"default-path-persists");
CodeTheme cur = theme_current();
check(cur.name == "Monokai" && cur.keyword == mono.keyword,
"theme-current-roundtrip");
// 5. Tokeniser spans.
std::string sample =
"#include <gtk/gtk.h>\n// hi\nint main() { const char* s = \"x\"; "
"return 42; }\n";
std::vector<HlSpan> spans = theme_tokenize(sample);
auto has_span = [&](const std::string& kind, const std::string& word) {
for (const auto& sp : spans)
if (sp.kind == kind &&
sample.substr(sp.start, sp.end - sp.start) == word)
return true;
return false;
};
check(has_span("preprocessor", "#include <gtk/gtk.h>"),
"token-preprocessor");
check(has_span("comment", "// hi"), "token-line-comment");
check(has_span("type", "int"), "token-type");
check(has_span("keyword", "return"), "token-keyword");
check(has_span("string", "\"x\""), "token-string");
check(has_span("number", "42"), "token-number");
// Block comment, char literal, digit separator, string with brace.
std::string sample2 =
"/* { not a fold */\nchar c = 'x';\nint n = 1'000;\n"
"const char* s = \"a{b\";\nfloat f = 1.5e-3;\n";
std::vector<HlSpan> spans2 = theme_tokenize(sample2);
bool block_ok = false, char_ok = false, num_ok = false;
for (const auto& sp : spans2) {
std::string w = sample2.substr(sp.start, sp.end - sp.start);
if (sp.kind == "comment" && w == "/* { not a fold */") block_ok = true;
if (sp.kind == "string" && w == "'x'") char_ok = true;
if (sp.kind == "number" && w == "1'000") num_ok = true;
}
check(block_ok, "token-block-comment");
check(char_ok, "token-char-literal");
check(num_ok, "token-digit-separator");
// 6. Fold regions: braces, region, comment, #if, nesting, unbalanced.
std::vector<std::string> flines = fold_lines();
std::vector<FoldRegion> regs = codeview_find_regions(flines);
check(regs.size() == 6, "regions-count-6");
auto has_region = [&](int st, int en, const std::string& kind) {
for (const auto& r : regs)
if (r.start_line == st && r.end_line == en && r.kind == kind)
return true;
return false;
};
check(has_region(0, 10, "region"), "region-outer");
check(has_region(1, 9, "brace"), "brace-class");
check(has_region(2, 8, "brace"), "brace-method");
check(has_region(3, 5, "brace"), "brace-if");
check(has_region(6, 7, "comment"), "region-comment");
check(has_region(11, 13, "preproc"), "region-if");
int depth_of[17];
for (int k = 0; k < 17; ++k) depth_of[k] = -1;
for (const auto& r : regs) depth_of[r.start_line] = r.depth;
check(depth_of[0] == 0 && depth_of[1] == 1 && depth_of[2] == 2 &&
depth_of[3] == 3 && depth_of[6] == 3 && depth_of[11] == 0,
"regions-depths-nested");
// No region starts at the extra close (14) or the unclosed brace (15).
bool bad_start = false;
for (const auto& r : regs)
if (r.start_line == 14 || r.start_line == 15) bad_start = true;
check(!bad_start, "unbalanced-no-bogus-region");
// A brace inside a string / comment opens no fold.
std::vector<std::string> trick = {
"const char* s = \"{\";", // 0: brace in string
"/* { */", // 1: brace in comment
"int ok() {", // 2: real brace
" return 0;", // 3
"}", // 4
};
std::vector<FoldRegion> tregs = codeview_find_regions(trick);
check(tregs.size() == 1 && tregs[0].start_line == 2 &&
tregs[0].end_line == 4,
"braces-in-string-comment-ignored");
// Single-line block: nothing to fold.
std::vector<FoldRegion> sregs =
codeview_find_regions({"int f() { return 0; }"});
check(sregs.empty(), "single-line-block-no-fold");
// 7. Visible lines under folds.
std::vector<int> vis = codeview_visible_lines(flines, {0});
check(vis.size() == 8 && vis[0] == 0 && vis[1] == 10,
"visible-fold-region");
vis = codeview_visible_lines(flines, {2});
check(vis.size() == 12, "visible-fold-method");
vis = codeview_visible_lines(flines, {0, 2});
check(vis.size() == 8, "visible-nested-fold-same-as-outer");
vis = codeview_visible_lines(flines, {3});
check(vis.size() == 16 && vis[3] == 3 && vis[4] == 5,
"visible-fold-if-only");
// 8. Widget level: regions, fold toggle, gutter clicks, current
// line, theme switch changing the tag colour, real fold collapse.
GtkWidget* win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
GtkWidget* cv = codeview_new();
gtk_container_add(GTK_CONTAINER(win), cv);
gtk_widget_show_all(win);
while (gtk_events_pending()) gtk_main_iteration();
codeview_set_text(cv, join_lines(flines),
"/tmp/fdesigner_codeview_test.cpp");
while (gtk_events_pending()) gtk_main_iteration();
check(codeview_line_count(cv) == 17, "widget-line-count");
check(codeview_regions(cv).size() == 6, "widget-regions");
check(codeview_toggle_fold_at(cv, 3), "widget-fold-toggle-ok");
check(codeview_is_folded(cv, 3), "widget-folded");
check(!codeview_toggle_fold_at(cv, 5), "widget-fold-no-region-start");
codeview_gutter_click(cv, 3, true);
check(!codeview_is_folded(cv, 3), "widget-gutter-fold-click-unfolds");
codeview_gutter_click(cv, 5, false);
check(codeview_breakpoint_lines(cv).count(5) == 1,
"widget-gutter-bp-click-sets");
codeview_gutter_click(cv, 5, false);
check(codeview_breakpoint_lines(cv).empty(),
"widget-gutter-bp-click-clears");
codeview_set_current_line(cv, 4);
check(codeview_current_line(cv) == 4, "widget-current-line");
// Theme switch changes the keyword tag colour. "foreground" is
// write-only and "foreground-rgba" does not read back on this GTK;
// "foreground-gdk" (16-bit, 8-bit values as v*257) is the readable
// form. Dark keyword #569cd6.
codeview_set_theme(cv, dark);
GtkTextBuffer* cbuf = gtk_text_view_get_buffer(
GTK_TEXT_VIEW(codeview_text_view(cv)));
GtkTextTag* kw = gtk_text_tag_table_lookup(
gtk_text_buffer_get_tag_table(cbuf), "theme-keyword");
GdkColor* col = nullptr;
if (kw) g_object_get(kw, "foreground-gdk", &col, NULL);
check(kw && col && col->red / 257 == 0x56 &&
col->green / 257 == 0x9c && col->blue / 257 == 0xd6,
"widget-theme-switch-changes-tag");
if (col) g_boxed_free(g_type_from_name("GdkColor"), col);
// Real collapse: fold bar() (lines 3..8, 1-based) and check the
// hidden buffer lines report zero height.
codeview_toggle_fold_at(cv, 3);
while (gtk_events_pending()) gtk_main_iteration();
{
GtkTextView* tv = GTK_TEXT_VIEW(codeview_text_view(cv));
gint y4, h4, y7, h7;
GtkTextIter it4, it7;
gtk_text_buffer_get_iter_at_line(cbuf, &it4, 3); // file line 4
gtk_text_view_get_line_yrange(tv, &it4, &y4, &h4);
gtk_text_buffer_get_iter_at_line(cbuf, &it7, 6); // file line 7
gtk_text_view_get_line_yrange(tv, &it7, &y7, &h7);
check(h4 == 0 && h7 == 0, "widget-fold-collapses-lines");
}
gtk_widget_destroy(win);
// 9. Gutter -> debugger backend toggle (HOME redirected: the bps
// file lands in the scratch dir, never the real config).
const std::string bpfile =
"/tmp/fdesigner_theme_home/.config/fdesigner/debugger_bps.conf";
::remove(bpfile.c_str());
check(debugger_toggle_breakpoint("/tmp/fdesigner_codeview_test.cpp",
42),
"dbg-toggle-sets");
check(debugger_has_breakpoint("/tmp/fdesigner_codeview_test.cpp", 42),
"dbg-has-after-set");
check(file_contains(bpfile, "/tmp/fdesigner_codeview_test.cpp:42"),
"dbg-toggle-persists");
check(!debugger_toggle_breakpoint("/tmp/fdesigner_codeview_test.cpp",
42),
"dbg-toggle-clears");
check(!debugger_has_breakpoint("/tmp/fdesigner_codeview_test.cpp",
42),
"dbg-has-after-clear");
check(!file_contains(bpfile, "/tmp/fdesigner_codeview_test.cpp:42"),
"dbg-clear-persists");
std::printf("THEME TESTS: %d pass, %d fail\n", g_pass, g_fail);
return g_fail == 0 ? 0 : 1;
}
+98
View File
@@ -0,0 +1,98 @@
#!/bin/sh
# FDesigner color themes + code-view gutter/folding tests.
# tests/theme_tests.sh
# Builds + runs the theme harness (tests/theme_tests.cpp, needs Xvfb),
# runs the fdesigner self-test (which has its own theme/folding block),
# and smoke tests the real Code View window and Color Theme dialog
# (FDESIGNER_OPEN_CODEVIEW / FDESIGNER_OPEN_THEME) with xdotool if
# available. Prints a PASS/FAIL summary; exits non-zero on any failure.
# Run from the repo root.
set -u
ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT"
FAIL=0
say() { printf '%s\n' "$*"; }
say "== building theme harness =="
g++ -O2 -Wall -Wextra -std=c++17 -I src -o /tmp/theme_tests tests/theme_tests.cpp \
src/theme.cpp src/codeview.cpp src/debugger.cpp src/debugger_ui.cpp \
$(pkg-config --cflags --libs gtk+-3.0) \
2>/tmp/theme_tests_build.log || {
say "FAIL theme harness build"; cat /tmp/theme_tests_build.log; exit 1
}
if grep -q "warning" /tmp/theme_tests_build.log; then
say "FAIL theme harness build has warnings"; cat /tmp/theme_tests_build.log
FAIL=1
fi
say "== theme harness (under Xvfb) =="
rm -rf /tmp/fdesigner_theme_home
xvfb-run -a /tmp/theme_tests || FAIL=1
say "== building fdesigner =="
make >/tmp/theme_make.log 2>&1 || {
say "FAIL fdesigner build"; cat /tmp/theme_make.log; FAIL=1
}
if grep -q "warning" /tmp/theme_make.log; then
say "FAIL fdesigner build has warnings"
grep "warning" /tmp/theme_make.log
FAIL=1
fi
if [ "$FAIL" = "0" ]; then
say "== fdesigner self-test (includes theme/folding block) =="
FDESIGNER_SELFTEST=1 xvfb-run -a ./fdesigner || FAIL=1
fi
say "== View menu wiring =="
grep -q 'id="mi_view_code"' ui/designer.ui &&
grep -q 'id="mi_view_theme"' ui/designer.ui &&
grep -q 'mi_view_code' src/main.cpp &&
grep -q 'mi_view_theme' src/main.cpp &&
say "PASS menu-items-wired" ||
{ say "FAIL menu-items-wired"; FAIL=1; }
if ! command -v xdotool >/dev/null 2>&1; then
say "SKIP GUI smoke tests (xdotool not installed)"
else
say "== Code View window smoke test =="
xvfb-run -a sh -c '
FDESIGNER_OPEN_CODEVIEW=1 ./fdesigner >/tmp/theme_codeview.log 2>&1 &
APP=$!
FOUND=""
i=0
while [ $i -lt 50 ]; do
FOUND=$(xdotool search --name "Code - generated C\+\+" 2>/dev/null | head -1)
[ -n "$FOUND" ] && break
sleep 0.2; i=$((i+1))
done
if [ -n "$FOUND" ]; then echo "PASS codeview-opened (window $FOUND)"; else echo "FAIL codeview-did-not-open"; fi
kill $APP 2>/dev/null
wait $APP 2>/dev/null
[ -n "$FOUND" ]
' || FAIL=1
say "== Color Theme dialog smoke test =="
xvfb-run -a sh -c '
FDESIGNER_OPEN_THEME=1 ./fdesigner >/tmp/theme_dlg.log 2>&1 &
APP=$!
FOUND=""
i=0
while [ $i -lt 50 ]; do
FOUND=$(xdotool search --name "^Color Theme$" 2>/dev/null | head -1)
[ -n "$FOUND" ] && break
sleep 0.2; i=$((i+1))
done
if [ -n "$FOUND" ]; then
echo "PASS theme-dialog-opened (window $FOUND)"
xdotool windowactivate "$FOUND" key Escape
sleep 0.5
else
echo "FAIL theme-dialog-did-not-open"
xdotool search --name ".*" getwindowname %@ 2>/dev/null | head -5
fi
kill $APP 2>/dev/null
wait $APP 2>/dev/null
[ -n "$FOUND" ]
' || FAIL=1
fi
if [ "$FAIL" = "0" ]; then say "THEME TESTS: ALL PASS"; else say "THEME TESTS: FAILURES (see above)"; fi
exit "$FAIL"
+23
View File
@@ -64,6 +64,29 @@
</child>
</object>
</child>
<child>
<object class="GtkMenuItem" id="menu_view">
<property name="label">View</property>
<property name="visible">True</property>
<child type="submenu">
<object class="GtkMenu" id="view_menu">
<property name="visible">True</property>
<child>
<object class="GtkMenuItem" id="mi_view_code">
<property name="label">Code View…</property>
<property name="visible">True</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="mi_view_theme">
<property name="label">Color Theme…</property>
<property name="visible">True</property>
</object>
</child>
</object>
</child>
</object>
</child>
<child>
<object class="GtkMenuItem" id="menu_debug">
<property name="label">Debug</property>