Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1fd763cc4c | ||
|
|
ca220ccd92 | ||
|
|
6d8b86076a | ||
|
|
ccf1c75526 | ||
|
|
2c7c0f05fe | ||
|
|
3c0c87f9d9 | ||
|
|
2c36572401 | ||
|
|
6884c53568 | ||
|
|
310ff34c47 | ||
|
|
1e2e6f8692 | ||
|
|
e171fa9946 | ||
|
|
e280653c45 | ||
|
|
f30b285b00 | ||
|
|
4c998e7888 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
fdesigner
|
||||
*.o
|
||||
tests/gen_matrix
|
||||
tests/debugger/work/
|
||||
tests/out/
|
||||
@@ -1,403 +0,0 @@
|
||||
# FDesigner — C++/GTK conversion design
|
||||
|
||||
## What we're building
|
||||
|
||||
A C++ rebuild of Chris's fdesigner (Tkinter Rapid Designer). The original is a
|
||||
~7,000-line Python/Tkinter app (`original/tkinter_designer/fdesigner7.py`):
|
||||
place widgets on a canvas at absolute positions, edit their properties, then
|
||||
generate runnable source code for the layout.
|
||||
|
||||
Per Chris's decision (2026-11-25) the C++ version **generates C++/GTK code**,
|
||||
not Tkinter Python. The designer's own UI is also GTK, defined in Glade .ui
|
||||
files. No Qt anywhere.
|
||||
|
||||
## Stack
|
||||
|
||||
- **GTK 3.24** — Glade's target toolkit. (GTK 4 has no Glade; its successor is
|
||||
Cambalache. Glade means GTK 3.)
|
||||
- **C++ with the GTK C API**, windows loaded via **GtkBuilder** from .ui files
|
||||
authored in Glade. No gtkmm: GtkBuilder is the native path, and this keeps
|
||||
the generated code and the designer itself on the same API.
|
||||
- Runs on **X11** (GTK 3's X11 backend), same as the original Tk app.
|
||||
- Build: g++ + pkg-config (`gtk+-3.0`), plain Makefile, like Chris's other
|
||||
tools.
|
||||
- Toolchain verified on Muse's VM 2026-11-25: GTK 3.24.41 headers + Glade
|
||||
installed; a C++ test program including <gtk/gtk.h> compiles, links, and
|
||||
runs under Xvfb. (VM quirk: apt's libzstd-dev version pin conflicts with the
|
||||
VM's patched libzstd1, so the -dev packages were installed from downloaded
|
||||
.debs with `dpkg --force-depends` — headers only, no runtime change. On
|
||||
Chris's Parrot box a plain `apt install libgtk-3-dev glade` should work.)
|
||||
|
||||
## Generated output
|
||||
|
||||
For each designed window the generator emits two files, mirroring the spirit
|
||||
of the Python tool's generated class + stub handlers:
|
||||
|
||||
1. **`<name>.ui`** — a Glade/GtkBuilder file holding the layout: a GtkWindow
|
||||
containing a GtkFixed, with each widget placed at its designed x/y and
|
||||
sized with width/height requests (the GTK equivalent of Tk's `.place()`).
|
||||
2. **`<name>.h` / `<name>.cpp`** — a C++ class that loads the .ui with
|
||||
GtkBuilder, fetches each widget by id, and declares one stub signal
|
||||
handler per connected signal (`// Code block here`, like the original's
|
||||
stubs), ready for the user to fill in.
|
||||
|
||||
The generated project compiles standalone with:
|
||||
`g++ -o app *.cpp $(pkg-config --cflags --libs gtk+-3.0)`
|
||||
|
||||
## Widget mapping (Tk -> GTK)
|
||||
|
||||
| Tk (original palette) | GTK 3 |
|
||||
|---|---|
|
||||
| Root / Toplevel | GtkWindow |
|
||||
| Frame / Labelframe | GtkFrame |
|
||||
| Button | GtkButton |
|
||||
| Label | GtkLabel |
|
||||
| Entry | GtkEntry |
|
||||
| Checkbutton | GtkCheckButton |
|
||||
| Radiobutton | GtkRadioButton |
|
||||
| Combobox (ttk) | GtkComboBoxText |
|
||||
| Listbox | GtkListBox (inside GtkScrolledWindow) |
|
||||
| Menu | GtkMenu / GtkMenuBar |
|
||||
| Menubutton | GtkMenuButton |
|
||||
| Canvas | GtkDrawingArea |
|
||||
| Scale | GtkScale |
|
||||
| Scrollbar | GtkScrollbar |
|
||||
| Text | GtkTextView (inside GtkScrolledWindow) |
|
||||
| Spreadsheet (custom) | GtkGrid of GtkEntry (later phase) |
|
||||
|
||||
## Internal model
|
||||
|
||||
```cpp
|
||||
struct Widget {
|
||||
std::string name; // e.g. "Button_001"
|
||||
std::string type; // palette type key, e.g. "Button"
|
||||
int x, y, width, height; // canvas geometry
|
||||
std::map<std::string,std::string> props; // GTK properties, as strings
|
||||
std::vector<std::string> signals; // signals to stub out in generated code
|
||||
};
|
||||
struct Project {
|
||||
std::string title, class_name;
|
||||
int win_width, win_height;
|
||||
std::string background; // window background colour
|
||||
std::vector<Widget> widgets; // Root is implicit (the window itself)
|
||||
};
|
||||
```
|
||||
|
||||
## Project file format
|
||||
|
||||
**JSON** (`.fdj`), replacing Python pickle, which C++ cannot read. If Chris
|
||||
has old .pkl designs he wants to keep, a one-off Python converter script
|
||||
(pkl -> fdj) can be written later; pickle stays on the Python side only.
|
||||
|
||||
## What does not port directly
|
||||
|
||||
- **pickle** save/load -> JSON (above).
|
||||
- **pyperclip** -> GtkClipboard (built into GTK).
|
||||
- **openpyxl** spreadsheet modeller -> later phase; the on-canvas spreadsheet
|
||||
widget is a GtkGrid; xlsx import, if wanted, needs a separate library.
|
||||
- The huge generated colour files in `library/` (super_color.py ~31k lines,
|
||||
colormenu.py ~15k lines) are data, not logic: they become colour-name data
|
||||
tables / GTK colour chooser integration, not hand-ported code.
|
||||
|
||||
## Phases
|
||||
|
||||
1. **Skeleton + canvas**: main window from Glade .ui; palette adds widgets to
|
||||
a GtkFixed canvas; click to select, drag to move, delete. *(skeleton done)*
|
||||
2. **Property editor**: per-type property tables (ported from the original's
|
||||
Entry_001..019 mapping), plus the original's bulk operations — set
|
||||
parameter on all / selected / filtered widgets, clear parameter.
|
||||
3. **Code generator**: emit .ui + .h/.cpp per the format above; generated
|
||||
project compiles and runs.
|
||||
4. **Save/load**: JSON project files; optional .pkl -> .fdj converter.
|
||||
5. **Extras**: colour palette, menu designer, spreadsheet widget, canvas
|
||||
widget (drawing area) support.
|
||||
|
||||
**Status 2026-11-25: all five phases built and verified.** The self-test
|
||||
(`FDESIGNER_SELFTEST=1 ./fdesigner`) exercises placement, properties, bulk
|
||||
ops, generation, save/load round-trips, and the Phase 5 extras; generated
|
||||
projects compile with their own Makefile and run. Known v1 limits:
|
||||
designing *inside* a Toplevel or a generated menu's submenus is not
|
||||
supported (Toplevel content starts as an empty GtkFixed; menus are a
|
||||
one-level text spec), and there is no .pkl converter unless old designs
|
||||
need importing.
|
||||
|
||||
**Generator revision 2026-11-25 (Chris's direction):** generated projects
|
||||
are ALL CODE (no .ui — so a stepping debugger can walk construction) and
|
||||
every widget is a STANDALONE CLASS in its own .h/.cpp pair, mirroring the
|
||||
Python generator's boilerplate: per-widget `// #region`, creation +
|
||||
`.place()`-equivalent + config in the constructor, a `util_error_print`
|
||||
helper, and the same nine mouse handlers per widget (buttonPress1-3,
|
||||
dblbuttonPress1-3, buttonRelease1-3) routed by two dispatchers; the
|
||||
window class keeps the Root_001 handler set and just instantiates the
|
||||
widget classes. Verified by `tests/run_matrix.sh`: 13 generated designs
|
||||
(every type, every property, every enum value, menus, hostile strings,
|
||||
class-name edge cases, 40 widgets, spreadsheet extremes) each compile
|
||||
with -Wall -Wextra, zero warnings, and run clean. The matrix caught a
|
||||
real bug: property ranges (e.g. Label xalign 0..1) were not enforced, so
|
||||
an out-of-range value could reach GTK — canonicalize() now enforces the
|
||||
property tables' lo/hi for Int and Double.
|
||||
|
||||
**StockChart widget added 2026-11-25:** a candle chart for Massive
|
||||
aggregates CSVs (header `ticker,volume,open,close,high,low,window_start,
|
||||
transactions`, matched by column name). Properties: `data-file`,
|
||||
`up-color`, `down-color`, `max-candles`. The designer plots a built-in
|
||||
preview series on the canvas and swaps in real data when data-file is
|
||||
set; the generated StockChart class is self-contained — it embeds the
|
||||
CSV loader (`load_csv`, plus `set_candles`/`candle_count`) and cairo
|
||||
plotting (wicks + bodies, min/max scaled). Fake data for trying it:
|
||||
`tests/data/SPY_fake.csv` (120 synthetic SPY minute bars). The matrix
|
||||
grew to 14 cases plus a render test that draws the generated chart
|
||||
offscreen and counts up/down-coloured pixels, proving it plots.
|
||||
|
||||
**Indicator submodules added 2026-11-25:** `src/indicators.h` is ONE
|
||||
self-contained header holding **250 named technical indicators** —
|
||||
moving averages and Ehlers/Hilbert filters, bands/channels, five pivot
|
||||
families, momentum oscillators, volume indicators, volatility and
|
||||
statistics, and all 61 TA-Lib candlestick patterns plus 5 extras. Each
|
||||
is a registry module (namespace `fdi`) that consumes the chart's OHLCV
|
||||
bars and draws itself: price-pane overlays share the price scale,
|
||||
oscillators get their own labelled pane strip, patterns draw markers.
|
||||
They have no palette button; a StockChart enables them via its
|
||||
`indicators` property (`"SMA(20), RSI, MACD(12,26,9), Engulfing"`) in
|
||||
the designer, or `add_indicator("SMA(20)")` in generated code. The
|
||||
generator embeds the header text (via `src/indicators_embedded.h`,
|
||||
regenerated by `tools/embed_indicators.sh` from the Makefile rule) and
|
||||
copies it into any generated project that contains a StockChart.
|
||||
Candle structs carry `volume` (OBV/VWAP/MFI need it). Testing:
|
||||
`tests/indicator_test.cpp` computes and renders every indicator over
|
||||
`tests/data/SPY_fake_long.csv` (1,170 bars, 3 days), counts palette-ink
|
||||
pixels per render, hand-checks 18 patterns on crafted candle sequences
|
||||
and bounded oscillators against their legal ranges, and writes a
|
||||
labelled contact sheet of all 250 plots to
|
||||
`tests/out/indicators_contact_sheet.png`. Result: 244 render-verified
|
||||
on data; 6 ultra-rare gap patterns verified by crafted sequences.
|
||||
Matrix case 15 covers a generated chart with indicators attached.
|
||||
|
||||
**StockChart Pro added 2026-11-25:** the chart gained a full
|
||||
annotation system, comparative plotting, a percent scale, a time axis
|
||||
and wheel zoom, in both the designer preview and generated code.
|
||||
|
||||
- `src/drawings.h` is ONE self-contained header (namespace `fdw`)
|
||||
holding the drawing module: 11 kinds — trend, ray, horizontal and
|
||||
vertical lines, rectangle, ellipse, arrow, text labels, Fibonacci
|
||||
retracement, freehand, and a measure tool (Δ price / % / bars).
|
||||
Anchors are DATA coordinates (bar index, price), never pixels, so
|
||||
annotations survive widget resizes, zooms and pans; every render
|
||||
re-maps through `fdw::Map`. Drawings come from text specs
|
||||
(`"trend 10 655 200 672.5 red; hline 650 blue dash"`) via
|
||||
`fdw::parse_specs`, or interactively in generated apps: keys
|
||||
T H V R L A X F D M E S select trend/hline/vline/rect/ellipse/arrow/
|
||||
text/fib/freehand/measure/erase/select-move, Esc returns to pan,
|
||||
Delete removes the selected drawing, and a text tool click asks for
|
||||
the label in a dialog. The generator embeds the header
|
||||
(`src/drawings_embedded.h` via `tools/embed_drawings.sh`) and copies
|
||||
`drawings.h` into StockChart projects, like indicators.h.
|
||||
- New StockChart properties: `scale-mode` (Price|Percent — percent
|
||||
relabels the right axis as change from the first visible close),
|
||||
`compare-files` (comma-separated CSVs of other tickers, aligned by
|
||||
timestamp and rebased onto the first visible close, drawn as
|
||||
coloured lines with a legend), and `drawings` (semicolon-separated
|
||||
specs). The bottom axis plots UTC time from `window_start` (date
|
||||
shown at day changes); gridlines use nice 1/2/5 steps.
|
||||
- View: the mouse wheel zooms around the cursor (`zoom_at(factor,
|
||||
frac)` in code), drag pans with no tool active, `reset_view()`
|
||||
restores the max-candles window. The designer preview zooms with
|
||||
the wheel too.
|
||||
- Testing: `tests/drawings_test.cpp` renders every kind and checks
|
||||
palette ink, verifies a trend line's endpoints remap at 1x and 2x
|
||||
plot sizes, and exercises hit testing. Matrix case 16
|
||||
(`16_stockchart_pro`, a 1024x768 window) designs a percent-mode
|
||||
chart with a QQQ comparison (`tests/data/QQQ_fake_long.csv`, same
|
||||
timestamp grid as SPY, made by `tests/make_compare_data.py`), SMA +
|
||||
RSI and 7 annotations; `tests/chart_pro_render_test.cpp` asserts
|
||||
candle/comparison/arrow/fib ink, percent and time axis labels,
|
||||
zoom in/out/clamp/reset, and that arrow + fib still draw after the
|
||||
widget is resized smaller. `tests/chart_screenshot.cpp` captures
|
||||
the generated app at exactly 1024x768 to
|
||||
`tests/out/chart_pro_1024x768.png`. Full regression after the
|
||||
change: designer self-test PASS, matrix 21/21.
|
||||
- Gotcha found by the matrix: the generated chart's event handlers
|
||||
must not be named `on_press`/`on_release` — those are the widget
|
||||
stub dispatchers. They are `on_chart_press` etc.
|
||||
|
||||
## Layout of this workspace
|
||||
|
||||
- `original/` — the Python source, read-only reference (do not run it here).
|
||||
- `ui/designer.ui` — the designer's own main window (Glade).
|
||||
- `src/main.cpp` — entry point; loads the .ui via GtkBuilder.
|
||||
- `Makefile` — builds `./fdesigner`.
|
||||
|
||||
## Stepping debugger (GDB/MI)
|
||||
|
||||
**Debug menu → Open Debugger…** opens a separate debugger window (not a
|
||||
panel in the main window). It drives real gdb over the MI protocol
|
||||
(`gdb -q -i=mi2`, see `src/debugger.h` / `src/debugger.cpp`).
|
||||
|
||||
- **Toolbar:** Run, Continue, Step Over, Step Into, Step Out, Stop
|
||||
(interrupts a running target; press again to kill it), Restart, Settings.
|
||||
- **Breakpoints:** type `file.cpp:123` or a function name and press Add BP;
|
||||
the list shows id / location / enabled toggle / hit count. Enable/disable
|
||||
via the toggle, Remove deletes. Breakpoints are saved to
|
||||
`~/.config/fdesigner/debugger_bps.conf` and restored on the next run.
|
||||
- **Variables:** Locals (name / type / value) and a watch list (add any
|
||||
expression, e.g. `sum + 1`) refresh on every stop; the Stack pane shows
|
||||
the current frames, and the status line shows the stopped file:line and
|
||||
function. Target stdout/stderr appears in the bottom pane.
|
||||
- **Settings:** the Settings toolbar button, **Debug → Debugger Settings…**,
|
||||
and the **Debug → Debugger** sub-menu (which also has Break on main /
|
||||
Stop on entry / Pretty-print values toggles). Settings live in
|
||||
`~/.config/fdesigner/debugger.conf`: `gdb_path`, `break_on_main`,
|
||||
`stop_on_entry`, `pretty_print`, `print_all_locals`, `default_args`.
|
||||
They take effect on the next Run (pretty-printing is applied when the
|
||||
gdb session starts). The same settings are honoured by the backend
|
||||
(`GdbSession`), so the headless tests exercise them too.
|
||||
- **Targets:** any program compiled with `-g` — console programs and GTK
|
||||
apps alike (the GTK app runs under the same X display as the designer).
|
||||
- **Tests:** `tests/debugger_tests.sh` (console suite, GTK suite under
|
||||
Xvfb, GUI smoke test) — see `tests/debugger/` for the targets and the
|
||||
headless harness `dbg_harness.cpp`, which drives `GdbSession` directly.
|
||||
|
||||
## CMake handling (2026-11-26)
|
||||
|
||||
The generator now also emits a `CMakeLists.txt` next to the `Makefile` in
|
||||
every generated project, so a generated project builds with either tool.
|
||||
The file sets `cmake_minimum_required(VERSION 3.10)`,
|
||||
`project(<ClassName> CXX)`, C++17, `find_package(PkgConfig)` /
|
||||
`pkg_check_modules(GTK3 REQUIRED gtk+-3.0)`, lists every generated `.cpp`
|
||||
explicitly in `add_executable(app …)`, and wires the GTK include dirs /
|
||||
compile options / libraries onto that target. The executable is named
|
||||
`app`, matching the Makefile target. Build it with
|
||||
`cmake -S . -B build && cmake --build build`.
|
||||
|
||||
In the designer, **File → Generate C++/GTK…** now offers **Build with
|
||||
CMake** right after generating (CMake is the default build path for a
|
||||
generated project); **File → Build with CMake…** rebuilds the last
|
||||
generated project (or asks for a folder), and **File → Open CMake
|
||||
Project…** points the designer at any directory holding a
|
||||
`CMakeLists.txt` — generated or hand-written — and builds it (configure +
|
||||
build), reporting success/failure plus the executable path in a log
|
||||
dialog. A missing or broken `CMakeLists.txt`, or a compile error, is
|
||||
reported as a failure, never as success.
|
||||
|
||||
The logic lives in new files `src/cmake_build.h/.cpp`
|
||||
(`cmake_lists_text`, `cmake_build_project`, `cmake_project_exists`,
|
||||
`CMakeSettings`); the generator only gains the emit call, `main.cpp`
|
||||
only the menu callbacks, and `ui/designer.ui` the three File-menu items.
|
||||
Settings (cmake command, generator — empty = CMake default, build type,
|
||||
build directory) persist in `~/.config/fdesigner/cmake.conf` (key=value,
|
||||
same pattern as `debugger.conf`; `FDESIGNER_CMAKE_CONF` overrides the
|
||||
path for tests) and are edited via **File → CMake Settings…**.
|
||||
|
||||
Tests: `tests/cmake_tests.sh` builds a headless probe
|
||||
(`tests/cmake_probe.cpp`) that checks the generated `CMakeLists.txt`
|
||||
contents, configures + builds a generated GTK project and runs it under
|
||||
Xvfb, builds + runs a hand-written console CMake project and a
|
||||
hand-written GTK one, verifies settings save/load and custom build
|
||||
directories, checks failure reporting (missing/broken `CMakeLists.txt`,
|
||||
compile error), and builds a project in a directory with a space in its
|
||||
name. The designer self-test gained a CMake phase (settings round-trip,
|
||||
`CMakeLists.txt` markers, real console build, broken-file failure, and a
|
||||
cmake build of the generated GTK project).
|
||||
|
||||
## Lazarus-style widgets (2026-11-25)
|
||||
|
||||
Twenty Lazarus-palette widgets were added alongside the original Tk set.
|
||||
Each is placeable from the palette (grouped sections in the left pane),
|
||||
selectable/draggable/deletable, has a per-type property table in `props.h`,
|
||||
and is emitted by the generator as a standalone class with working GTK code.
|
||||
|
||||
| Lazarus | GTK 3 | Key properties |
|
||||
|---|---|---|
|
||||
| Memo | GtkTextView in GtkScrolledWindow | text, editable, wrap-mode |
|
||||
| GroupBox | GtkFrame | label, shadow-type |
|
||||
| Panel | GtkFrame | label, shadow-type |
|
||||
| Image | GtkImage (file, else missing-image icon) | file, pixel-size |
|
||||
| Shape | GtkDrawingArea, cairo draw | shape (Rectangle/Ellipse/Line/Triangle), fill-color |
|
||||
| Notebook (PageControl) | GtkNotebook | pages ("Tab 1|Tab 2"), page |
|
||||
| ScrollBox | GtkScrolledWindow + GtkBox | label |
|
||||
| Splitter | GtkPaned | position, orientation |
|
||||
| StatusBar | GtkStatusbar | text |
|
||||
| ToolBar | GtkToolbar | items ("New|Open|Save"), toolbar-style |
|
||||
| MainMenu (MenuBar) | GtkMenuBar | menus ("File|Edit|Help") |
|
||||
| SpinEdit | GtkSpinButton | minimum, maximum, step, value, digits, numeric, wrap |
|
||||
| TrackBar | GtkScale | minimum, maximum, step, value, orientation |
|
||||
| ProgressBar | GtkProgressBar | fraction, show-text, text |
|
||||
| DateTimePicker | GtkCalendar + entry | date (YYYY-MM-DD), show-heading, show-day-names |
|
||||
| ColorBox | GtkColorButton | color, use-alpha, title |
|
||||
| ListView | GtkTreeView + GtkListStore | columns ("Name|Value"), items ("a,1;b,2"), headers-visible |
|
||||
| TreeView | GtkTreeView + GtkTreeStore | items ("Root/Child;Other"), headers-visible |
|
||||
| StringGrid | GtkTreeView + GtkListStore | rows, columns, headers-visible |
|
||||
| Plot | GtkDrawingArea, cairo sine wave | title, line-color |
|
||||
|
||||
Already present before this change: Button, Label, Entry (Edit), CheckButton,
|
||||
RadioButton, ComboBox, ListBox, Frame, Scale, Text, StockChart (chart/plot),
|
||||
Spreadsheet, Toplevel, Canvas, Scrollbar, MenuButton.
|
||||
|
||||
Tests: the self-test gained a Phase 7 block (place + edit + drag/delete +
|
||||
generate + per-widget code markers); `tests/widget_tests.sh` builds a
|
||||
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`.
|
||||
|
||||
## Global font settings (2026-11-26)
|
||||
|
||||
**Edit → Preferences…** opens a font dialog (interface font + code /
|
||||
text-view font, via GtkFontButton). Choices persist in
|
||||
`~/.config/fdesigner/settings.conf` (`font=`, `code_font=`, Pango
|
||||
descriptions; `FDESIGNER_SETTINGS_CONF` overrides the path for tests) and
|
||||
are applied live at startup and on Apply: the interface font via a
|
||||
screen-wide CSS provider, the code font via a `textview` CSS rule (so
|
||||
Text/Memo views and any other GtkTextView use it). Invalid sizes are
|
||||
clamped to 6–48 pt and empty values fall back to the defaults. Logic lives
|
||||
in `src/preferences.h/.cpp`; tests: a font block in the self-test plus
|
||||
`tests/font_tests.sh` (harness + self-test + Preferences dialog smoke test).
|
||||
## 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` (bare, and the
|
||||
`// #region` comment form the generator emits), 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).
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 cnmcdee
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,17 +0,0 @@
|
||||
CXX ?= g++
|
||||
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/cmake_build.cpp src/project_io.cpp src/debugger.cpp src/debugger_ui.cpp src/preferences.cpp src/theme.cpp src/codeview.cpp src/model.h src/props.h src/events.h src/generator.h src/cmake_build.h src/project_io.h src/debugger.h src/debugger_ui.h src/preferences.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/cmake_build.cpp src/project_io.cpp src/debugger.cpp src/debugger_ui.cpp src/preferences.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 $@
|
||||
|
||||
src/drawings_embedded.h: src/drawings.h tools/embed_drawings.sh
|
||||
sh tools/embed_drawings.sh src/drawings.h $@
|
||||
|
||||
clean:
|
||||
rm -f fdesigner
|
||||
|
||||
.PHONY: clean
|
||||
@@ -0,0 +1,11 @@
|
||||
# cfree — moved to lightgui
|
||||
|
||||
**This project has moved. Its successor is [lightgui](https://github.com/cnmcdee/lightgui).**
|
||||
|
||||
FDesigner (this repository, cfree) was renamed to **lightgui** and merged with the
|
||||
expanded CWidgets widget set — **547 widgets** across 11 sections, a combined palette
|
||||
of 583 entries, a separate Object Inspector window, and a GDB debugger.
|
||||
|
||||
Please go to **https://github.com/cnmcdee/lightgui** for the code, documentation,
|
||||
and all future development. This repository is kept only as a pointer, and its full
|
||||
history remains available in git.
|
||||
|
Before Width: | Height: | Size: 145 KiB |
|
Before Width: | Height: | Size: 2.3 MiB |
|
Before Width: | Height: | Size: 159 KiB |
|
Before Width: | Height: | Size: 146 KiB |
|
Before Width: | Height: | Size: 291 KiB |
|
Before Width: | Height: | Size: 229 KiB |
|
Before Width: | Height: | Size: 254 KiB |
|
Before Width: | Height: | Size: 308 KiB |
|
Before Width: | Height: | Size: 329 KiB |
|
Before Width: | Height: | Size: 168 KiB |
|
Before Width: | Height: | Size: 164 KiB |
|
Before Width: | Height: | Size: 51 KiB |
@@ -1,176 +0,0 @@
|
||||
// FDesigner CMake handling — see cmake_build.h.
|
||||
#include "cmake_build.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
// ---------------------------------------------------------------- settings
|
||||
|
||||
static std::string home_dir() {
|
||||
const char* h = std::getenv("HOME");
|
||||
return h ? h : "";
|
||||
}
|
||||
|
||||
std::string CMakeSettings::default_path() {
|
||||
const char* e = std::getenv("FDESIGNER_CMAKE_CONF");
|
||||
if (e && *e) return e;
|
||||
return home_dir() + "/.config/fdesigner/cmake.conf";
|
||||
}
|
||||
|
||||
static bool ensure_parent_dir(const std::string& path) {
|
||||
std::error_code ec;
|
||||
size_t slash = path.rfind('/');
|
||||
if (slash == std::string::npos) return true;
|
||||
fs::create_directories(path.substr(0, slash), ec);
|
||||
return !ec;
|
||||
}
|
||||
|
||||
static 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);
|
||||
}
|
||||
|
||||
bool CMakeSettings::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 << "# FDesigner CMake settings\n";
|
||||
f << "cmake_path=" << cmake_path << "\n";
|
||||
f << "generator=" << generator << "\n";
|
||||
f << "build_type=" << build_type << "\n";
|
||||
f << "build_dir=" << build_dir << "\n";
|
||||
return (bool)f;
|
||||
}
|
||||
|
||||
bool CMakeSettings::load(const std::string& path) {
|
||||
std::string p = path.empty() ? default_path() : path;
|
||||
std::ifstream f(p);
|
||||
if (!f) return false;
|
||||
std::string line;
|
||||
while (std::getline(f, line)) {
|
||||
line = trim_s(line);
|
||||
if (line.empty() || line[0] == '#') continue;
|
||||
size_t eq = line.find('=');
|
||||
if (eq == std::string::npos) continue;
|
||||
std::string key = trim_s(line.substr(0, eq));
|
||||
std::string val = trim_s(line.substr(eq + 1));
|
||||
if (key == "cmake_path") cmake_path = val;
|
||||
else if (key == "generator") generator = val;
|
||||
else if (key == "build_type") build_type = val;
|
||||
else if (key == "build_dir") build_dir = val;
|
||||
// Unknown keys are ignored, so newer settings files stay readable.
|
||||
}
|
||||
if (cmake_path.empty()) cmake_path = "cmake";
|
||||
if (build_type.empty()) build_type = "Release";
|
||||
if (build_dir.empty()) build_dir = "build";
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- emitter
|
||||
|
||||
std::string cmake_lists_text(const std::string& project_name,
|
||||
const std::vector<std::string>& sources) {
|
||||
std::ostringstream o;
|
||||
o << "# Generated by FDesigner (C++/GTK). Build with:\n"
|
||||
<< "# cmake -S . -B build && cmake --build build\n"
|
||||
<< "# (or use File -> Build with CMake in the designer).\n"
|
||||
<< "cmake_minimum_required(VERSION 3.10)\n"
|
||||
<< "project(" << project_name << " CXX)\n\n"
|
||||
<< "set(CMAKE_CXX_STANDARD 17)\n"
|
||||
<< "set(CMAKE_CXX_STANDARD_REQUIRED ON)\n\n"
|
||||
<< "find_package(PkgConfig REQUIRED)\n"
|
||||
<< "pkg_check_modules(GTK3 REQUIRED gtk+-3.0)\n\n"
|
||||
<< "add_executable(app\n";
|
||||
for (const std::string& s : sources) o << " " << s << "\n";
|
||||
o << ")\n\n"
|
||||
<< "target_include_directories(app PRIVATE ${GTK3_INCLUDE_DIRS})\n"
|
||||
<< "target_compile_options(app PRIVATE ${GTK3_CFLAGS_OTHER})\n"
|
||||
<< "target_link_libraries(app PRIVATE ${GTK3_LIBRARIES})\n";
|
||||
return o.str();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- building
|
||||
|
||||
bool cmake_project_exists(const std::string& dir) {
|
||||
std::error_code ec;
|
||||
return fs::is_regular_file(fs::path(dir) / "CMakeLists.txt", ec);
|
||||
}
|
||||
|
||||
std::string cmake_shell_quote(const std::string& s) {
|
||||
std::string out = "'";
|
||||
for (char c : s) {
|
||||
if (c == '\'') out += "'\\''";
|
||||
else out += c;
|
||||
}
|
||||
out += "'";
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string cmake_exe_path(const std::string& dir,
|
||||
const CMakeSettings& settings) {
|
||||
fs::path d(dir);
|
||||
if (d.is_relative()) d = fs::absolute(d);
|
||||
return (d / settings.build_dir / "app").string();
|
||||
}
|
||||
|
||||
// Run `cmd`, appending its combined stdout+stderr to `out`; true on exit 0.
|
||||
static bool run_capture(const std::string& cmd, std::string& out) {
|
||||
std::string full = cmd + " 2>&1";
|
||||
FILE* p = ::popen(full.c_str(), "r");
|
||||
if (!p) {
|
||||
out += "cannot run: " + cmd + "\n";
|
||||
return false;
|
||||
}
|
||||
char buf[4096];
|
||||
size_t n;
|
||||
while ((n = std::fread(buf, 1, sizeof buf, p)) > 0) out.append(buf, n);
|
||||
int rc = ::pclose(p);
|
||||
return rc == 0;
|
||||
}
|
||||
|
||||
CMakeBuildResult cmake_build_project(const std::string& dir,
|
||||
const CMakeSettings& settings) {
|
||||
CMakeBuildResult r;
|
||||
fs::path d(dir);
|
||||
if (d.is_relative()) d = fs::absolute(d);
|
||||
r.build_dir = (d / settings.build_dir).string();
|
||||
r.exe_path = cmake_exe_path(dir, settings);
|
||||
if (!cmake_project_exists(d.string())) {
|
||||
r.output = "no CMakeLists.txt in " + d.string() + "\n";
|
||||
return r;
|
||||
}
|
||||
std::string cmake = settings.cmake_path.empty()
|
||||
? std::string("cmake")
|
||||
: settings.cmake_path;
|
||||
std::string gen;
|
||||
if (!settings.generator.empty())
|
||||
gen = " -G " + cmake_shell_quote(settings.generator);
|
||||
std::string cfg = cmake_shell_quote(cmake) + " -S " +
|
||||
cmake_shell_quote(d.string()) + " -B " +
|
||||
cmake_shell_quote(r.build_dir) + gen +
|
||||
" -DCMAKE_BUILD_TYPE=" +
|
||||
cmake_shell_quote(settings.build_type.empty()
|
||||
? std::string("Release")
|
||||
: settings.build_type);
|
||||
r.output += "$ " + cfg + "\n";
|
||||
r.configured = run_capture(cfg, r.output);
|
||||
if (!r.configured) return r;
|
||||
std::string bld = cmake_shell_quote(cmake) + " --build " +
|
||||
cmake_shell_quote(r.build_dir);
|
||||
r.output += "$ " + bld + "\n";
|
||||
bool built = run_capture(bld, r.output);
|
||||
std::error_code ec;
|
||||
r.ok = built && fs::is_regular_file(r.exe_path, ec);
|
||||
if (built && !r.ok)
|
||||
r.output += "build reported success but " + r.exe_path +
|
||||
" is missing\n";
|
||||
return r;
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
// FDesigner CMake handling — no GTK dependency.
|
||||
// Emits CMakeLists.txt text for generated projects, builds any directory
|
||||
// containing one (configure + build), and persists the CMake settings
|
||||
// (generator / build type / build directory) in
|
||||
// ~/.config/fdesigner/cmake.conf, following the debugger.conf pattern
|
||||
// (key=value; FDESIGNER_CMAKE_CONF overrides the path, used by tests).
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct CMakeSettings {
|
||||
std::string cmake_path = "cmake"; // cmake binary (PATH lookup or path)
|
||||
std::string generator; // "" = CMake default generator
|
||||
std::string build_type = "Release";
|
||||
std::string build_dir = "build"; // relative to the project directory
|
||||
|
||||
static std::string default_path(); // ~/.config/fdesigner/cmake.conf
|
||||
bool save(const std::string& path = "") const;
|
||||
bool load(const std::string& path = "");
|
||||
};
|
||||
|
||||
// CMakeLists.txt text for a generated project: project <name>, GTK 3 via
|
||||
// PkgConfig, C++17, and add_executable(app <sources>). `sources` are the
|
||||
// generated .cpp file names (e.g. main.cpp, MyWindow.cpp, Button_001.cpp).
|
||||
std::string cmake_lists_text(const std::string& project_name,
|
||||
const std::vector<std::string>& sources);
|
||||
|
||||
// True when <dir>/CMakeLists.txt exists.
|
||||
bool cmake_project_exists(const std::string& dir);
|
||||
|
||||
// Shell-quote one argument for /bin/sh.
|
||||
std::string cmake_shell_quote(const std::string& s);
|
||||
|
||||
struct CMakeBuildResult {
|
||||
bool ok = false; // configure AND build both succeeded
|
||||
bool configured = false; // configure step succeeded
|
||||
std::string output; // combined stdout+stderr of both steps
|
||||
std::string build_dir; // absolute build directory used
|
||||
std::string exe_path; // <build_dir>/app when it exists after build
|
||||
};
|
||||
|
||||
// Configure + build the CMake project in `dir` (which must contain a
|
||||
// CMakeLists.txt). The executable is <dir>/<build_dir>/app, matching the
|
||||
// generated Makefile's `app` target. Blocking; captures all output.
|
||||
CMakeBuildResult cmake_build_project(const std::string& dir,
|
||||
const CMakeSettings& settings);
|
||||
|
||||
// Absolute path of the executable a successful cmake_build_project leaves
|
||||
// behind for `dir` under `settings`.
|
||||
std::string cmake_exe_path(const std::string& dir,
|
||||
const CMakeSettings& settings);
|
||||
@@ -1,665 +0,0 @@
|
||||
// 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 == '/' && i + 1 < n && text[i + 1] == '/') {
|
||||
// Comment-style directive (`// #region` / `// #endregion`,
|
||||
// the form the generator emits): parse it as a directive.
|
||||
size_t j = i + 2;
|
||||
while (j < n && (text[j] == ' ' || text[j] == '\t')) ++j;
|
||||
if (j < n && text[j] == '#') {
|
||||
i = j;
|
||||
c = '#';
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
// 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);
|
||||
@@ -1,274 +0,0 @@
|
||||
// FDesigner stepping debugger — GDB/MI backend (no GTK dependency).
|
||||
// Drives a real gdb process over the machine interface (gdb -i=mi2):
|
||||
// launch target, breakpoints, step over/into/out, continue, kill, restart,
|
||||
// locals / watches / stack frames, target stdout/stderr capture.
|
||||
//
|
||||
// Target output: in MI mode gdb forwards the inferior's stdout/stderr as
|
||||
// bare lines on gdb's stdout (not @"..." records); the parser treats any
|
||||
// line with no MI prefix as target output. Breakpoints may resolve to
|
||||
// several locations (e.g. a one-line function body); the breakpoint id
|
||||
// reported is the parent number.
|
||||
//
|
||||
// Breakpoint handlers: every breakpoint carries a kind — plain, conditional
|
||||
// (stops only when a gdb expression is true, via -break-condition) or
|
||||
// logpoint (a gdb dprintf: prints a message and never stops). Any kind may
|
||||
// also carry an ignore count (first N hits are skipped, via -break-after;
|
||||
// gdb counts every reach, ignored or not, in the breakpoint's `times`
|
||||
// hit count) and a group label. A logpoint message is a template:
|
||||
// literal text plus {expr} placeholders, printed as integers by default;
|
||||
// {s:expr} prints a string, {f:expr} a float, {x:expr} hex, {p:expr} a
|
||||
// pointer. A conditional breakpoint's `times` counts stops only — reaches
|
||||
// where the condition is false are not hits at all.
|
||||
//
|
||||
// Settings live in ~/.config/fdesigner/debugger.conf (key=value, see
|
||||
// DebuggerSettings::save/load). FDESIGNER_DEBUGGER_CONF overrides the
|
||||
// path (used by tests). Breakpoints are persisted per session in
|
||||
// ~/.config/fdesigner/debugger_bps.conf, one per line:
|
||||
// location|enabled|kind|condition|ignore|log_message|group
|
||||
// (\, | and newline inside fields are backslash-escaped.) Old two-field
|
||||
// lines (location|enabled) still load as plain breakpoints.
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
|
||||
struct DebuggerSettings {
|
||||
std::string gdb_path = "/usr/bin/gdb";
|
||||
bool break_on_main = false; // insert a breakpoint at main before run
|
||||
bool stop_on_entry = false; // stop at main on entry (temp bp at main)
|
||||
bool pretty_print = true; // -enable-pretty-printing on session start
|
||||
bool print_all_locals = true; // refresh locals on every stop
|
||||
std::string default_args; // args passed to the target by default
|
||||
int stop_timeout_ms = 10000; // how long to wait for a stop event
|
||||
int cmd_timeout_ms = 5000; // how long to wait for a ^done/^error
|
||||
|
||||
static std::string default_path(); // ~/.config/fdesigner/debugger.conf
|
||||
bool save(const std::string& path = "") const;
|
||||
bool load(const std::string& path = "");
|
||||
};
|
||||
|
||||
// What a breakpoint does when its location is reached.
|
||||
enum class BpKind { Plain, Conditional, Logpoint };
|
||||
|
||||
// Display name for a breakpoint kind ("plain"/"conditional"/"logpoint").
|
||||
const char* bp_kind_name(BpKind kind);
|
||||
// Parse a kind name; accepts "plain", "conditional"/"cond",
|
||||
// "logpoint"/"log"/"dprintf". Returns false for anything else.
|
||||
bool bp_kind_from_name(const std::string& name, BpKind& kind);
|
||||
|
||||
struct Breakpoint {
|
||||
int id = 0; // gdb breakpoint number
|
||||
std::string location; // as requested: "file:line" or "func"
|
||||
std::string file; // resolved file (may be empty)
|
||||
int line = 0; // resolved line (0 if by function)
|
||||
std::string function; // resolved function (may be empty)
|
||||
bool enabled = true;
|
||||
int hits = 0; // gdb `times`: reaches (conditional: stops)
|
||||
// Multiple-handler fields (see the header comment above).
|
||||
BpKind kind = BpKind::Plain;
|
||||
std::string condition; // conditional: gdb expression, e.g. "i == 5"
|
||||
int ignore_count = 0; // skip the first N hits (-break-after)
|
||||
std::string log_message; // logpoint template, e.g. "i={i} sum={sum}"
|
||||
std::string group; // optional group label (organisation only)
|
||||
};
|
||||
|
||||
struct Variable {
|
||||
std::string name, type, value;
|
||||
};
|
||||
|
||||
struct StackFrame {
|
||||
int level = 0;
|
||||
std::string function, file;
|
||||
int line = 0;
|
||||
std::string address;
|
||||
};
|
||||
|
||||
struct StopInfo {
|
||||
std::string reason; // breakpoint-hit, end-stepping-range, exited-normally, ...
|
||||
int breakpoint_id = 0;
|
||||
StackFrame frame;
|
||||
int exit_code = -1; // >=0 once the target has exited
|
||||
bool exited = false;
|
||||
};
|
||||
|
||||
enum class DbgState { Idle, Starting, Running, Stopped, Exited, Error };
|
||||
|
||||
// Minimal MI value: string, tuple {k=v,...} or list [v,...].
|
||||
struct MiValue {
|
||||
std::string str;
|
||||
std::map<std::string, MiValue> tuple;
|
||||
std::vector<MiValue> list;
|
||||
bool is_list = false;
|
||||
bool is_tuple = false;
|
||||
const MiValue* get(const std::string& key) const {
|
||||
auto it = tuple.find(key);
|
||||
return it == tuple.end() ? nullptr : &it->second;
|
||||
}
|
||||
std::string get_str(const std::string& key,
|
||||
const std::string& dflt = "") const {
|
||||
const MiValue* v = get(key);
|
||||
return v ? v->str : dflt;
|
||||
}
|
||||
};
|
||||
|
||||
// Parse one MI value starting at s[pos]; advances pos. Exposed for tests.
|
||||
bool mi_parse_value(const std::string& s, size_t& pos, MiValue& out);
|
||||
// Decode an MI C-escaped string body (no surrounding quotes).
|
||||
std::string mi_unescape(const std::string& s);
|
||||
// Parse a "file:line" or "function" breakpoint location. Returns false if
|
||||
// the text is not a plausible location (empty, no colon/function chars).
|
||||
bool parse_breakpoint_location(const std::string& text, std::string& file,
|
||||
int& line, std::string& function);
|
||||
// Convert a logpoint message template ("reached loop, i={i} name={s:name}")
|
||||
// to a gdb printf format string plus the argument expressions, in order.
|
||||
// {expr} prints as %d; {s:expr} %s, {f:expr} %f, {x:expr} %#x, {p:expr} %p.
|
||||
// Literal % in the template is escaped to %%. Returns false on an
|
||||
// unbalanced brace or an empty placeholder. Exposed for tests.
|
||||
bool logpoint_to_printf(const std::string& tmpl, std::string& fmt,
|
||||
std::vector<std::string>& args);
|
||||
|
||||
class GdbSession {
|
||||
public:
|
||||
explicit GdbSession(const DebuggerSettings& settings = DebuggerSettings());
|
||||
~GdbSession();
|
||||
GdbSession(const GdbSession&) = delete;
|
||||
GdbSession& operator=(const GdbSession&) = delete;
|
||||
|
||||
const DebuggerSettings& settings() const { return settings_; }
|
||||
void set_settings(const DebuggerSettings& s) { settings_ = s; }
|
||||
|
||||
// Start gdb on the target. Returns false + err on failure (bad gdb
|
||||
// path, missing executable, gdb died). Applies pretty-print and
|
||||
// break_on_main/stop_on_entry breakpoints when set.
|
||||
bool start(const std::string& executable, const std::string& args,
|
||||
std::string& err);
|
||||
// Start gdb only (no target yet); load_executable() then run().
|
||||
bool start_gdb_only(std::string& err);
|
||||
bool load_executable(const std::string& executable, std::string& err);
|
||||
void shutdown(); // kill gdb, reap child
|
||||
|
||||
bool is_alive() const;
|
||||
bool target_running() const { return state_ == DbgState::Running; }
|
||||
DbgState state() const { return state_; }
|
||||
const std::string& executable() const { return executable_; }
|
||||
int exit_code() const { return last_stop_.exit_code; }
|
||||
|
||||
// Execution control. Each returns false + err if gdb rejects it or
|
||||
// the target is not in a state where it applies.
|
||||
bool run(std::string& err); // (re)run from the start
|
||||
bool cont(std::string& err); // continue
|
||||
bool step_over(std::string& err); // -exec-next
|
||||
bool step_into(std::string& err); // -exec-step
|
||||
bool step_out(std::string& err); // -exec-finish
|
||||
bool kill_target(std::string& err); // -exec-kill (target keeps gdb)
|
||||
bool restart(std::string& err); // kill (if running) + run again
|
||||
bool interrupt(std::string& err); // SIGINT to the inferior
|
||||
|
||||
// Wait until the target stops (breakpoint/step/exit) or timeout_ms
|
||||
// elapses. Returns true if a stop event arrived.
|
||||
bool wait_for_stop(int timeout_ms = -1);
|
||||
// Non-blocking drain of pending MI output (used by the GUI poll tick).
|
||||
void poll_events();
|
||||
const StopInfo& last_stop() const { return last_stop_; }
|
||||
|
||||
// Breakpoints.
|
||||
// Remember a breakpoint before gdb is running (e.g. typed in the UI
|
||||
// before Run); start() inserts it into gdb. Returns false if the
|
||||
// location does not parse.
|
||||
bool stage_breakpoint(const std::string& location);
|
||||
// As above, with handler options (kind/condition/ignore/log/group).
|
||||
// Replaces the options of an already-staged entry at the same
|
||||
// location; a live breakpoint at the location is left alone.
|
||||
bool stage_breakpoint_opts(const std::string& location,
|
||||
const Breakpoint& opts);
|
||||
// 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);
|
||||
// As above, with handler options. A conditional breakpoint needs a
|
||||
// non-empty condition, a logpoint a non-empty message; gdb validates
|
||||
// the condition expression (unknown variable -> error, and the
|
||||
// breakpoint is rolled back). The breakpoint is created disabled
|
||||
// when opts.enabled is false.
|
||||
bool add_breakpoint_opts(const std::string& location,
|
||||
const Breakpoint& opts, Breakpoint& out,
|
||||
std::string& err);
|
||||
bool remove_breakpoint(int id, std::string& err);
|
||||
bool enable_breakpoint(int id, bool enable, std::string& err);
|
||||
// Replace a breakpoint's handler options (location is unchanged).
|
||||
// Live: delete + re-insert with the new options (the gdb id may
|
||||
// change; `out` carries the new breakpoint). Staged (id 0, gdb not
|
||||
// running): updated in place. Returns false + err when the id is
|
||||
// unknown or gdb rejects the new options.
|
||||
bool update_breakpoint(int id, const Breakpoint& opts, Breakpoint& out,
|
||||
std::string& err);
|
||||
bool refresh_breakpoints(std::string& err); // re-list from gdb
|
||||
const std::vector<Breakpoint>& breakpoints() const { return bps_; }
|
||||
// Breakpoints kept across sessions (saved to disk by the UI).
|
||||
bool save_breakpoints(const std::string& path = "") const;
|
||||
bool load_breakpoints(const std::string& path = "");
|
||||
static std::string default_bps_path();
|
||||
|
||||
// Inspection (valid while stopped).
|
||||
bool list_locals(std::vector<Variable>& out, std::string& err);
|
||||
bool list_frames(std::vector<StackFrame>& out, std::string& err);
|
||||
bool evaluate(const std::string& expr, std::string& value,
|
||||
std::string& err);
|
||||
// Watch expressions: kept in-session, refreshed by refresh_watches().
|
||||
bool add_watch(const std::string& expr, std::string& err);
|
||||
bool remove_watch(const std::string& expr);
|
||||
bool refresh_watches(std::string& err);
|
||||
const std::vector<Variable>& watches() const { return watches_; }
|
||||
const std::vector<Variable>& locals() const { return locals_; }
|
||||
const std::vector<StackFrame>& frames() const { return frames_; }
|
||||
// Refresh locals+frames+watches after a stop (best effort).
|
||||
void refresh_on_stop();
|
||||
|
||||
// Output accumulated so far (target stdout/stderr + gdb console text).
|
||||
// Logpoint (dprintf) output arrives on gdb's console stream, so it
|
||||
// lands in gdb_log(), not target_output().
|
||||
const std::string& target_output() const { return target_output_; }
|
||||
const std::string& gdb_log() const { return gdb_log_; }
|
||||
void clear_output() { target_output_.clear(); gdb_log_.clear(); }
|
||||
const std::string& last_error() const { return last_error_; }
|
||||
|
||||
// Low-level: send one MI command, wait for its ^done/^error.
|
||||
// Public so the GUI/tests can run extra MI commands.
|
||||
bool command(const std::string& mi_cmd, MiValue& result,
|
||||
std::string& err, int timeout_ms = -1);
|
||||
|
||||
private:
|
||||
bool spawn_gdb(std::string& err);
|
||||
bool pump(int timeout_ms); // read available MI lines for up to timeout
|
||||
void handle_line(const std::string& line);
|
||||
bool wait_result(int token, MiValue& result, std::string& err,
|
||||
int timeout_ms);
|
||||
bool send_raw(const std::string& text);
|
||||
// Send an -exec-* command; move to Running unless a fresh *stopped
|
||||
// arrived while waiting for the ^running reply (see debugger.cpp).
|
||||
bool issue_exec(const std::string& mi_cmd, std::string& err);
|
||||
// Apply a breakpoint's condition (-break-condition) and ignore count
|
||||
// (-break-after) to a breakpoint that already exists in gdb.
|
||||
bool apply_bp_options(int id, const Breakpoint& opts, std::string& err);
|
||||
|
||||
DebuggerSettings settings_;
|
||||
unsigned long stop_seq_ = 0; // incremented on every *stopped event
|
||||
pid_t gdb_pid_ = -1;
|
||||
pid_t inferior_pid_ = -1; // target pid, from =thread-group-started
|
||||
int gdb_stdin_ = -1, gdb_stdout_ = -1;
|
||||
int next_token_ = 1;
|
||||
DbgState state_ = DbgState::Idle;
|
||||
std::string executable_, args_;
|
||||
std::string read_buf_;
|
||||
std::string target_output_, gdb_log_, last_error_;
|
||||
StopInfo last_stop_;
|
||||
std::vector<Breakpoint> bps_;
|
||||
std::vector<std::string> watch_exprs_;
|
||||
std::vector<Variable> watches_, locals_;
|
||||
std::vector<StackFrame> frames_;
|
||||
// Pending synchronous results, keyed by token.
|
||||
std::map<int, std::pair<bool, MiValue>> pending_results_;
|
||||
std::string pending_error_;
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
// FDesigner stepping debugger — GTK window (separate from the main window).
|
||||
// Open with debugger_window_open(parent). The window owns a GdbSession and
|
||||
// polls it on a GTK timeout; all gdb traffic stays in the backend.
|
||||
#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).
|
||||
#include "debugger.h"
|
||||
DebuggerSettings debugger_current_settings();
|
||||
@@ -1,597 +0,0 @@
|
||||
// drawings.h — chart annotation module for the StockChart widget.
|
||||
//
|
||||
// One self-contained header (namespace fdw), in the same spirit as
|
||||
// indicators.h. A Drawing is stored in DATA coordinates — an anchor is
|
||||
// (bar index, price) — never in pixels, so annotations stay glued to
|
||||
// the candles they were drawn on through widget resizes, zooms and
|
||||
// pans: every render re-maps data -> pixels through the current Map.
|
||||
//
|
||||
// Kinds: trend line, ray, horizontal line, vertical line, rectangle,
|
||||
// ellipse, arrow, text label, Fibonacci retracement, freehand stroke,
|
||||
// and a measure tool (delta price / percent / bars between two points).
|
||||
//
|
||||
// Drawings can be created three ways: interactively (the generated
|
||||
// StockChart's mouse tools build them), from a text spec via
|
||||
// parse_spec()/parse_specs(), or directly in code. Spec grammar
|
||||
// (semicolon-separated in parse_specs):
|
||||
//
|
||||
// trend x1 y1 x2 y2 [colour] [dash]
|
||||
// ray x1 y1 x2 y2 [colour] [dash]
|
||||
// arrow x1 y1 x2 y2 [colour] [dash]
|
||||
// rect x1 y1 x2 y2 [colour] [dash]
|
||||
// ellipse x1 y1 x2 y2 [colour] [dash]
|
||||
// fib x1 y1 x2 y2 [colour]
|
||||
// measure x1 y1 x2 y2 [colour]
|
||||
// hline price [colour] [dash]
|
||||
// vline bar [colour] [dash]
|
||||
// text x y [colour] label words...
|
||||
// free x1 y1 x2 y2 ... [colour]
|
||||
//
|
||||
// x is a bar index (fractional allowed), y a price. Colours by name:
|
||||
// blue red green orange purple teal magenta brown black slate.
|
||||
#pragma once
|
||||
|
||||
#include <cairo.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace fdw {
|
||||
|
||||
// One anchor point in data coordinates.
|
||||
struct Anchor {
|
||||
double bar = 0; // bar index (fractional = between bars)
|
||||
double price = 0; // price
|
||||
};
|
||||
|
||||
enum class Kind {
|
||||
Trend,
|
||||
Ray,
|
||||
HLine,
|
||||
VLine,
|
||||
Rect,
|
||||
Ellipse,
|
||||
Arrow,
|
||||
Text,
|
||||
Fib,
|
||||
Freehand,
|
||||
Measure
|
||||
};
|
||||
|
||||
struct Drawing {
|
||||
Kind kind = Kind::Trend;
|
||||
std::vector<Anchor> pts; // 1 for hline/vline/text, 2 for most,
|
||||
// N for freehand
|
||||
int color = 0; // palette index
|
||||
double width = 1.5; // line width, px
|
||||
bool dash = false;
|
||||
std::string text; // Text kind only
|
||||
};
|
||||
|
||||
// Drawing palette (strong, saturated colours that read on white).
|
||||
inline const double kPalette[][3] = {
|
||||
{0.10, 0.25, 0.80}, // 0 blue
|
||||
{0.85, 0.10, 0.20}, // 1 red
|
||||
{0.00, 0.55, 0.15}, // 2 green
|
||||
{0.95, 0.50, 0.05}, // 3 orange
|
||||
{0.55, 0.20, 0.75}, // 4 purple
|
||||
{0.00, 0.60, 0.60}, // 5 teal
|
||||
{0.85, 0.20, 0.65}, // 6 magenta
|
||||
{0.55, 0.35, 0.15}, // 7 brown
|
||||
{0.10, 0.10, 0.10}, // 8 black
|
||||
{0.35, 0.40, 0.50}, // 9 slate
|
||||
};
|
||||
inline const int kPaletteSize = 10;
|
||||
|
||||
inline int color_index_of(const std::string& name) {
|
||||
static const char* kNames[] = {"blue", "red", "green", "orange",
|
||||
"purple", "teal", "magenta", "brown",
|
||||
"black", "slate"};
|
||||
std::string low;
|
||||
for (char c : name) low += (char)std::tolower((unsigned char)c);
|
||||
for (int i = 0; i < kPaletteSize; ++i)
|
||||
if (low == kNames[i]) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
inline const char* kind_name(Kind k) {
|
||||
switch (k) {
|
||||
case Kind::Trend: return "trend";
|
||||
case Kind::Ray: return "ray";
|
||||
case Kind::HLine: return "hline";
|
||||
case Kind::VLine: return "vline";
|
||||
case Kind::Rect: return "rect";
|
||||
case Kind::Ellipse: return "ellipse";
|
||||
case Kind::Arrow: return "arrow";
|
||||
case Kind::Text: return "text";
|
||||
case Kind::Fib: return "fib";
|
||||
case Kind::Freehand: return "freehand";
|
||||
case Kind::Measure: return "measure";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
inline bool kind_from_name(const std::string& s, Kind& out) {
|
||||
std::string low;
|
||||
for (char c : s) low += (char)std::tolower((unsigned char)c);
|
||||
if (low == "trend") out = Kind::Trend;
|
||||
else if (low == "ray") out = Kind::Ray;
|
||||
else if (low == "hline" || low == "horizontal") out = Kind::HLine;
|
||||
else if (low == "vline" || low == "vertical") out = Kind::VLine;
|
||||
else if (low == "rect" || low == "rectangle") out = Kind::Rect;
|
||||
else if (low == "ellipse" || low == "oval") out = Kind::Ellipse;
|
||||
else if (low == "arrow") out = Kind::Arrow;
|
||||
else if (low == "text" || low == "label") out = Kind::Text;
|
||||
else if (low == "fib" || low == "fibonacci") out = Kind::Fib;
|
||||
else if (low == "free" || low == "freehand") out = Kind::Freehand;
|
||||
else if (low == "measure") out = Kind::Measure;
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// The data -> pixel mapping for one render. x/y/w/h is the price-pane
|
||||
// plot rectangle in pixels; begin/count is the visible window in bar
|
||||
// units; lo/hi is the visible price range. Bar centres sit at
|
||||
// (bar - begin + 0.5) slots, matching the candle layout.
|
||||
struct Map {
|
||||
double x = 0, y = 0, w = 0, h = 0;
|
||||
double begin = 0, count = 1;
|
||||
double lo = 0, hi = 1;
|
||||
|
||||
double px(double bar) const {
|
||||
return x + (bar - begin + 0.5) * (w / count);
|
||||
}
|
||||
double py(double price) const {
|
||||
return y + (hi - price) / (hi - lo) * h;
|
||||
}
|
||||
double bar_at(double px_) const {
|
||||
return begin + (px_ - x) / (w / count) - 0.5;
|
||||
}
|
||||
double price_at(double py_) const {
|
||||
return hi - (py_ - y) / h * (hi - lo);
|
||||
}
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
|
||||
inline void set_style(cairo_t* cr, const Drawing& d, bool selected) {
|
||||
int ci = ((d.color % kPaletteSize) + kPaletteSize) % kPaletteSize;
|
||||
const double* c = kPalette[ci];
|
||||
cairo_set_source_rgba(cr, c[0], c[1], c[2], 0.92);
|
||||
cairo_set_line_width(cr, d.width + (selected ? 1.0 : 0.0));
|
||||
if (d.dash) {
|
||||
static const double kDash[] = {6, 4};
|
||||
cairo_set_dash(cr, kDash, 2, 0);
|
||||
} else {
|
||||
cairo_set_dash(cr, nullptr, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
inline double seg_dist(double px, double py, double x1, double y1,
|
||||
double x2, double y2) {
|
||||
double dx = x2 - x1, dy = y2 - y1;
|
||||
double len2 = dx * dx + dy * dy;
|
||||
double t = len2 > 0 ? ((px - x1) * dx + (py - y1) * dy) / len2 : 0;
|
||||
t = std::max(0.0, std::min(1.0, t));
|
||||
double ex = x1 + t * dx - px, ey = y1 + t * dy - py;
|
||||
return std::sqrt(ex * ex + ey * ey);
|
||||
}
|
||||
|
||||
// A small filled label with a light backing box (text + measure).
|
||||
inline void label_box(cairo_t* cr, double x, double y,
|
||||
const std::string& s, const double* col) {
|
||||
cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL,
|
||||
CAIRO_FONT_WEIGHT_NORMAL);
|
||||
cairo_set_font_size(cr, 11);
|
||||
cairo_text_extents_t te;
|
||||
cairo_text_extents(cr, s.c_str(), &te);
|
||||
cairo_set_source_rgba(cr, 1, 1, 1, 0.85);
|
||||
cairo_rectangle(cr, x - 3, y - te.height - 4, te.width + 6,
|
||||
te.height + 5);
|
||||
cairo_fill(cr);
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 1.0);
|
||||
cairo_move_to(cr, x, y - 3);
|
||||
cairo_show_text(cr, s.c_str());
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
// Render one drawing. Clips to the plot rectangle (rays and lines may
|
||||
// run off the edge). `selected` draws it slightly bolder.
|
||||
inline void draw(cairo_t* cr, const Map& m, const Drawing& d,
|
||||
bool selected = false) {
|
||||
if (d.pts.empty() || m.w < 2 || m.h < 2 || m.hi - m.lo < 1e-12)
|
||||
return;
|
||||
int ci = ((d.color % kPaletteSize) + kPaletteSize) % kPaletteSize;
|
||||
const double* col = kPalette[ci];
|
||||
cairo_save(cr);
|
||||
cairo_rectangle(cr, m.x - 40, m.y - 40, m.w + 80, m.h + 80);
|
||||
cairo_clip(cr);
|
||||
detail::set_style(cr, d, selected);
|
||||
auto X = [&](const Anchor& a) { return m.px(a.bar); };
|
||||
auto Y = [&](const Anchor& a) { return m.py(a.price); };
|
||||
switch (d.kind) {
|
||||
case Kind::Trend:
|
||||
case Kind::Measure: {
|
||||
if (d.pts.size() < 2) break;
|
||||
cairo_move_to(cr, X(d.pts[0]), Y(d.pts[0]));
|
||||
cairo_line_to(cr, X(d.pts[1]), Y(d.pts[1]));
|
||||
cairo_stroke(cr);
|
||||
if (d.kind == Kind::Measure) {
|
||||
double dp = d.pts[1].price - d.pts[0].price;
|
||||
double pct = d.pts[0].price != 0
|
||||
? dp / std::fabs(d.pts[0].price) * 100
|
||||
: 0;
|
||||
long bars = std::lround(d.pts[1].bar - d.pts[0].bar);
|
||||
char buf[96];
|
||||
std::snprintf(buf, sizeof buf, "%+.2f (%+.2f%%) / %ld bars",
|
||||
dp, pct, bars);
|
||||
detail::label_box(cr,
|
||||
(X(d.pts[0]) + X(d.pts[1])) / 2,
|
||||
(Y(d.pts[0]) + Y(d.pts[1])) / 2 - 4,
|
||||
buf, col);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Kind::Ray: {
|
||||
if (d.pts.size() < 2) break;
|
||||
double x1 = X(d.pts[0]), y1 = Y(d.pts[0]);
|
||||
double x2 = x1 + (X(d.pts[1]) - x1) * 1000;
|
||||
double y2 = y1 + (Y(d.pts[1]) - y1) * 1000;
|
||||
cairo_move_to(cr, x1, y1);
|
||||
cairo_line_to(cr, x2, y2);
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::Arrow: {
|
||||
if (d.pts.size() < 2) break;
|
||||
double x1 = X(d.pts[0]), y1 = Y(d.pts[0]);
|
||||
double x2 = X(d.pts[1]), y2 = Y(d.pts[1]);
|
||||
cairo_move_to(cr, x1, y1);
|
||||
cairo_line_to(cr, x2, y2);
|
||||
cairo_stroke(cr);
|
||||
double ang = std::atan2(y2 - y1, x2 - x1);
|
||||
double alen = 11;
|
||||
cairo_move_to(cr, x2, y2);
|
||||
cairo_line_to(cr, x2 - alen * std::cos(ang - 0.42),
|
||||
y2 - alen * std::sin(ang - 0.42));
|
||||
cairo_move_to(cr, x2, y2);
|
||||
cairo_line_to(cr, x2 - alen * std::cos(ang + 0.42),
|
||||
y2 - alen * std::sin(ang + 0.42));
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::HLine: {
|
||||
double y = Y(d.pts[0]);
|
||||
cairo_move_to(cr, m.x, y);
|
||||
cairo_line_to(cr, m.x + m.w, y);
|
||||
cairo_stroke(cr);
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof buf, "%.2f", d.pts[0].price);
|
||||
detail::label_box(cr, m.x + 4, y - 2, buf, col);
|
||||
break;
|
||||
}
|
||||
case Kind::VLine: {
|
||||
double x = X(d.pts[0]);
|
||||
cairo_move_to(cr, x, m.y);
|
||||
cairo_line_to(cr, x, m.y + m.h);
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::Rect:
|
||||
case Kind::Ellipse: {
|
||||
if (d.pts.size() < 2) break;
|
||||
double x1 = X(d.pts[0]), y1 = Y(d.pts[0]);
|
||||
double x2 = X(d.pts[1]), y2 = Y(d.pts[1]);
|
||||
double rx = std::min(x1, x2), ry = std::min(y1, y2);
|
||||
double rw = std::fabs(x2 - x1), rh = std::fabs(y2 - y1);
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 0.08);
|
||||
if (d.kind == Kind::Rect) {
|
||||
cairo_rectangle(cr, rx, ry, rw, rh);
|
||||
cairo_fill(cr);
|
||||
detail::set_style(cr, d, selected);
|
||||
cairo_rectangle(cr, rx, ry, rw, rh);
|
||||
cairo_stroke(cr);
|
||||
} else {
|
||||
cairo_save(cr);
|
||||
cairo_translate(cr, rx + rw / 2, ry + rh / 2);
|
||||
cairo_scale(cr, std::max(rw, 0.1), std::max(rh, 0.1));
|
||||
cairo_arc(cr, 0, 0, 0.5, 0, 2 * M_PI);
|
||||
cairo_restore(cr);
|
||||
cairo_fill(cr);
|
||||
detail::set_style(cr, d, selected);
|
||||
cairo_save(cr);
|
||||
cairo_translate(cr, rx + rw / 2, ry + rh / 2);
|
||||
cairo_scale(cr, std::max(rw, 0.1), std::max(rh, 0.1));
|
||||
cairo_arc(cr, 0, 0, 0.5, 0, 2 * M_PI);
|
||||
cairo_restore(cr);
|
||||
cairo_stroke(cr);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Kind::Text: {
|
||||
if (d.text.empty()) break;
|
||||
detail::label_box(cr, X(d.pts[0]) + 2, Y(d.pts[0]) - 2,
|
||||
d.text, col);
|
||||
// Anchor dot.
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 1.0);
|
||||
cairo_arc(cr, X(d.pts[0]), Y(d.pts[0]), 2.5, 0, 2 * M_PI);
|
||||
cairo_fill(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::Fib: {
|
||||
if (d.pts.size() < 2) break;
|
||||
static const double kLevels[] = {0, 0.236, 0.382, 0.5,
|
||||
0.618, 0.786, 1.0};
|
||||
double x1 = X(d.pts[0]);
|
||||
cairo_set_line_width(cr, 1.0);
|
||||
for (double lv : kLevels) {
|
||||
double price =
|
||||
d.pts[0].price + (d.pts[1].price - d.pts[0].price) * lv;
|
||||
double y = m.py(price);
|
||||
static const double kDash[] = {4, 3};
|
||||
cairo_set_dash(cr, kDash, 2, 0);
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 0.75);
|
||||
cairo_move_to(cr, x1, y);
|
||||
cairo_line_to(cr, m.x + m.w, y);
|
||||
cairo_stroke(cr);
|
||||
cairo_set_dash(cr, nullptr, 0, 0);
|
||||
char buf[48];
|
||||
std::snprintf(buf, sizeof buf, "%.1f%% %.2f", lv * 100,
|
||||
price);
|
||||
detail::label_box(cr, x1 + 4, y - 2, buf, col);
|
||||
}
|
||||
// Connector between the anchors.
|
||||
detail::set_style(cr, d, selected);
|
||||
cairo_move_to(cr, X(d.pts[0]), Y(d.pts[0]));
|
||||
cairo_line_to(cr, X(d.pts[1]), Y(d.pts[1]));
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::Freehand: {
|
||||
if (d.pts.size() < 2) break;
|
||||
cairo_move_to(cr, X(d.pts[0]), Y(d.pts[0]));
|
||||
for (size_t i = 1; i < d.pts.size(); ++i)
|
||||
cairo_line_to(cr, X(d.pts[i]), Y(d.pts[i]));
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (selected) {
|
||||
// Corner dots on the anchors.
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 1.0);
|
||||
for (const Anchor& a : d.pts) {
|
||||
cairo_arc(cr, X(a), Y(a), 3, 0, 2 * M_PI);
|
||||
cairo_fill(cr);
|
||||
}
|
||||
}
|
||||
cairo_restore(cr);
|
||||
}
|
||||
|
||||
// Is pixel (px, py) within `tol` px of the drawing? Used by the
|
||||
// select/move and erase tools.
|
||||
inline bool hit_test(const Map& m, const Drawing& d, double px,
|
||||
double py, double tol = 6) {
|
||||
if (d.pts.empty()) return false;
|
||||
auto X = [&](const Anchor& a) { return m.px(a.bar); };
|
||||
auto Y = [&](const Anchor& a) { return m.py(a.price); };
|
||||
switch (d.kind) {
|
||||
case Kind::Trend:
|
||||
case Kind::Ray:
|
||||
case Kind::Arrow:
|
||||
case Kind::Measure:
|
||||
if (d.pts.size() < 2) return false;
|
||||
return detail::seg_dist(px, py, X(d.pts[0]), Y(d.pts[0]),
|
||||
X(d.pts[1]), Y(d.pts[1])) <= tol;
|
||||
case Kind::HLine:
|
||||
return std::fabs(py - Y(d.pts[0])) <= tol && px >= m.x &&
|
||||
px <= m.x + m.w;
|
||||
case Kind::VLine:
|
||||
return std::fabs(px - X(d.pts[0])) <= tol && py >= m.y &&
|
||||
py <= m.y + m.h;
|
||||
case Kind::Rect:
|
||||
case Kind::Ellipse: {
|
||||
if (d.pts.size() < 2) return false;
|
||||
double x1 = X(d.pts[0]), y1 = Y(d.pts[0]);
|
||||
double x2 = X(d.pts[1]), y2 = Y(d.pts[1]);
|
||||
bool inside = px >= std::min(x1, x2) && px <= std::max(x1, x2) &&
|
||||
py >= std::min(y1, y2) && py <= std::max(y1, y2);
|
||||
bool near_edge =
|
||||
detail::seg_dist(px, py, x1, y1, x2, y1) <= tol ||
|
||||
detail::seg_dist(px, py, x2, y1, x2, y2) <= tol ||
|
||||
detail::seg_dist(px, py, x2, y2, x1, y2) <= tol ||
|
||||
detail::seg_dist(px, py, x1, y2, x1, y1) <= tol;
|
||||
return inside || near_edge;
|
||||
}
|
||||
case Kind::Text: {
|
||||
double x = X(d.pts[0]), y = Y(d.pts[0]);
|
||||
double w = 10 + (double)d.text.size() * 6.5;
|
||||
return px >= x - 4 && px <= x + w && py >= y - 16 &&
|
||||
py <= y + 4;
|
||||
}
|
||||
case Kind::Fib: {
|
||||
if (d.pts.size() < 2) return false;
|
||||
static const double kLevels[] = {0, 0.236, 0.382, 0.5,
|
||||
0.618, 0.786, 1.0};
|
||||
for (double lv : kLevels) {
|
||||
double price =
|
||||
d.pts[0].price + (d.pts[1].price - d.pts[0].price) * lv;
|
||||
if (std::fabs(py - m.py(price)) <= tol && px >= X(d.pts[0]))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case Kind::Freehand:
|
||||
for (size_t i = 1; i < d.pts.size(); ++i)
|
||||
if (detail::seg_dist(px, py, X(d.pts[i - 1]),
|
||||
Y(d.pts[i - 1]), X(d.pts[i]),
|
||||
Y(d.pts[i])) <= tol)
|
||||
return true;
|
||||
return d.pts.size() == 1 &&
|
||||
std::hypot(px - X(d.pts[0]), py - Y(d.pts[0])) <= tol;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Shift every anchor by a data-space delta (select/move drags).
|
||||
inline void move(Drawing& d, double dbar, double dprice) {
|
||||
for (Anchor& a : d.pts) {
|
||||
a.bar += dbar;
|
||||
a.price += dprice;
|
||||
}
|
||||
if (d.kind == Kind::HLine)
|
||||
for (Anchor& a : d.pts) a.bar -= dbar; // bar is meaningless
|
||||
if (d.kind == Kind::VLine)
|
||||
for (Anchor& a : d.pts) a.price -= dprice;
|
||||
}
|
||||
|
||||
// Parse one spec (grammar in the header comment).
|
||||
inline std::optional<Drawing> parse_spec(const std::string& spec) {
|
||||
// Tokenize on whitespace, remembering where the tail starts (text).
|
||||
std::vector<std::string> tok;
|
||||
std::vector<size_t> tok_pos;
|
||||
size_t i = 0;
|
||||
while (i < spec.size()) {
|
||||
while (i < spec.size() &&
|
||||
(spec[i] == ' ' || spec[i] == '\t'))
|
||||
++i;
|
||||
if (i >= spec.size()) break;
|
||||
size_t s = i;
|
||||
while (i < spec.size() && spec[i] != ' ' && spec[i] != '\t')
|
||||
++i;
|
||||
tok.push_back(spec.substr(s, i - s));
|
||||
tok_pos.push_back(s);
|
||||
}
|
||||
if (tok.empty()) return std::nullopt;
|
||||
Drawing d;
|
||||
if (!kind_from_name(tok[0], d.kind)) return std::nullopt;
|
||||
size_t t = 1;
|
||||
auto number = [&](double& v) {
|
||||
if (t >= tok.size()) return false;
|
||||
char* end = nullptr;
|
||||
v = std::strtod(tok[t].c_str(), &end);
|
||||
if (end == tok[t].c_str()) return false;
|
||||
++t;
|
||||
return true;
|
||||
};
|
||||
auto anchor = [&](Anchor& a) {
|
||||
return number(a.bar) && number(a.price);
|
||||
};
|
||||
auto tail_options = [&]() {
|
||||
while (t < tok.size()) {
|
||||
int ci = color_index_of(tok[t]);
|
||||
if (ci >= 0) {
|
||||
d.color = ci;
|
||||
++t;
|
||||
} else if (tok[t] == "dash") {
|
||||
d.dash = true;
|
||||
++t;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
switch (d.kind) {
|
||||
case Kind::HLine: {
|
||||
double p;
|
||||
if (!number(p)) return std::nullopt;
|
||||
d.pts.push_back({0, p});
|
||||
tail_options();
|
||||
return d;
|
||||
}
|
||||
case Kind::VLine: {
|
||||
double b;
|
||||
if (!number(b)) return std::nullopt;
|
||||
d.pts.push_back({b, 0});
|
||||
tail_options();
|
||||
return d;
|
||||
}
|
||||
case Kind::Text: {
|
||||
Anchor a;
|
||||
if (!anchor(a)) return std::nullopt;
|
||||
d.pts.push_back(a);
|
||||
tail_options();
|
||||
if (t < tok.size())
|
||||
d.text = spec.substr(tok_pos[t]);
|
||||
if (d.text.empty()) return std::nullopt;
|
||||
return d;
|
||||
}
|
||||
case Kind::Freehand: {
|
||||
while (t < tok.size()) {
|
||||
char* end = nullptr;
|
||||
double v = std::strtod(tok[t].c_str(), &end);
|
||||
if (end == tok[t].c_str()) break;
|
||||
Anchor a;
|
||||
a.bar = v;
|
||||
++t;
|
||||
if (!number(a.price)) return std::nullopt;
|
||||
d.pts.push_back(a);
|
||||
}
|
||||
tail_options();
|
||||
if (d.pts.size() < 2) return std::nullopt;
|
||||
return d;
|
||||
}
|
||||
default: { // two-anchor kinds
|
||||
Anchor a, b;
|
||||
if (!anchor(a) || !anchor(b)) return std::nullopt;
|
||||
d.pts.push_back(a);
|
||||
d.pts.push_back(b);
|
||||
tail_options();
|
||||
return d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse a semicolon-separated list of specs; bad entries are skipped.
|
||||
inline std::vector<Drawing> parse_specs(const std::string& specs) {
|
||||
std::vector<Drawing> out;
|
||||
size_t start = 0;
|
||||
for (size_t i = 0; i <= specs.size(); ++i) {
|
||||
if (i == specs.size() || specs[i] == ';') {
|
||||
auto d = parse_spec(specs.substr(start, i - start));
|
||||
if (d) out.push_back(*d);
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Canonical spec for a drawing (parse_spec(to_spec(d)) round-trips).
|
||||
inline std::string to_spec(const Drawing& d) {
|
||||
static const char* kNames[] = {"blue", "red", "green", "orange",
|
||||
"purple", "teal", "magenta", "brown",
|
||||
"black", "slate"};
|
||||
int ci = ((d.color % kPaletteSize) + kPaletteSize) % kPaletteSize;
|
||||
char buf[64];
|
||||
std::string s = kind_name(d.kind);
|
||||
auto num = [&](double v) {
|
||||
std::snprintf(buf, sizeof buf, " %g", v);
|
||||
s += buf;
|
||||
};
|
||||
if (d.kind == Kind::HLine) {
|
||||
num(d.pts.empty() ? 0 : d.pts[0].price);
|
||||
} else if (d.kind == Kind::VLine) {
|
||||
num(d.pts.empty() ? 0 : d.pts[0].bar);
|
||||
} else {
|
||||
for (const Anchor& a : d.pts) {
|
||||
num(a.bar);
|
||||
num(a.price);
|
||||
}
|
||||
}
|
||||
s += " ";
|
||||
s += kNames[ci];
|
||||
if (d.dash) s += " dash";
|
||||
if (d.kind == Kind::Text) {
|
||||
s += " ";
|
||||
s += d.text;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
} // namespace fdw
|
||||
@@ -1,602 +0,0 @@
|
||||
// Generated from src/drawings.h by tools/embed_drawings.sh.
|
||||
// Do not edit; run 'make' to regenerate.
|
||||
#pragma once
|
||||
static const char kDrawingsHeader[] = R"FDDRAWINGS9b2c(
|
||||
// drawings.h — chart annotation module for the StockChart widget.
|
||||
//
|
||||
// One self-contained header (namespace fdw), in the same spirit as
|
||||
// indicators.h. A Drawing is stored in DATA coordinates — an anchor is
|
||||
// (bar index, price) — never in pixels, so annotations stay glued to
|
||||
// the candles they were drawn on through widget resizes, zooms and
|
||||
// pans: every render re-maps data -> pixels through the current Map.
|
||||
//
|
||||
// Kinds: trend line, ray, horizontal line, vertical line, rectangle,
|
||||
// ellipse, arrow, text label, Fibonacci retracement, freehand stroke,
|
||||
// and a measure tool (delta price / percent / bars between two points).
|
||||
//
|
||||
// Drawings can be created three ways: interactively (the generated
|
||||
// StockChart's mouse tools build them), from a text spec via
|
||||
// parse_spec()/parse_specs(), or directly in code. Spec grammar
|
||||
// (semicolon-separated in parse_specs):
|
||||
//
|
||||
// trend x1 y1 x2 y2 [colour] [dash]
|
||||
// ray x1 y1 x2 y2 [colour] [dash]
|
||||
// arrow x1 y1 x2 y2 [colour] [dash]
|
||||
// rect x1 y1 x2 y2 [colour] [dash]
|
||||
// ellipse x1 y1 x2 y2 [colour] [dash]
|
||||
// fib x1 y1 x2 y2 [colour]
|
||||
// measure x1 y1 x2 y2 [colour]
|
||||
// hline price [colour] [dash]
|
||||
// vline bar [colour] [dash]
|
||||
// text x y [colour] label words...
|
||||
// free x1 y1 x2 y2 ... [colour]
|
||||
//
|
||||
// x is a bar index (fractional allowed), y a price. Colours by name:
|
||||
// blue red green orange purple teal magenta brown black slate.
|
||||
#pragma once
|
||||
|
||||
#include <cairo.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace fdw {
|
||||
|
||||
// One anchor point in data coordinates.
|
||||
struct Anchor {
|
||||
double bar = 0; // bar index (fractional = between bars)
|
||||
double price = 0; // price
|
||||
};
|
||||
|
||||
enum class Kind {
|
||||
Trend,
|
||||
Ray,
|
||||
HLine,
|
||||
VLine,
|
||||
Rect,
|
||||
Ellipse,
|
||||
Arrow,
|
||||
Text,
|
||||
Fib,
|
||||
Freehand,
|
||||
Measure
|
||||
};
|
||||
|
||||
struct Drawing {
|
||||
Kind kind = Kind::Trend;
|
||||
std::vector<Anchor> pts; // 1 for hline/vline/text, 2 for most,
|
||||
// N for freehand
|
||||
int color = 0; // palette index
|
||||
double width = 1.5; // line width, px
|
||||
bool dash = false;
|
||||
std::string text; // Text kind only
|
||||
};
|
||||
|
||||
// Drawing palette (strong, saturated colours that read on white).
|
||||
inline const double kPalette[][3] = {
|
||||
{0.10, 0.25, 0.80}, // 0 blue
|
||||
{0.85, 0.10, 0.20}, // 1 red
|
||||
{0.00, 0.55, 0.15}, // 2 green
|
||||
{0.95, 0.50, 0.05}, // 3 orange
|
||||
{0.55, 0.20, 0.75}, // 4 purple
|
||||
{0.00, 0.60, 0.60}, // 5 teal
|
||||
{0.85, 0.20, 0.65}, // 6 magenta
|
||||
{0.55, 0.35, 0.15}, // 7 brown
|
||||
{0.10, 0.10, 0.10}, // 8 black
|
||||
{0.35, 0.40, 0.50}, // 9 slate
|
||||
};
|
||||
inline const int kPaletteSize = 10;
|
||||
|
||||
inline int color_index_of(const std::string& name) {
|
||||
static const char* kNames[] = {"blue", "red", "green", "orange",
|
||||
"purple", "teal", "magenta", "brown",
|
||||
"black", "slate"};
|
||||
std::string low;
|
||||
for (char c : name) low += (char)std::tolower((unsigned char)c);
|
||||
for (int i = 0; i < kPaletteSize; ++i)
|
||||
if (low == kNames[i]) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
inline const char* kind_name(Kind k) {
|
||||
switch (k) {
|
||||
case Kind::Trend: return "trend";
|
||||
case Kind::Ray: return "ray";
|
||||
case Kind::HLine: return "hline";
|
||||
case Kind::VLine: return "vline";
|
||||
case Kind::Rect: return "rect";
|
||||
case Kind::Ellipse: return "ellipse";
|
||||
case Kind::Arrow: return "arrow";
|
||||
case Kind::Text: return "text";
|
||||
case Kind::Fib: return "fib";
|
||||
case Kind::Freehand: return "freehand";
|
||||
case Kind::Measure: return "measure";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
inline bool kind_from_name(const std::string& s, Kind& out) {
|
||||
std::string low;
|
||||
for (char c : s) low += (char)std::tolower((unsigned char)c);
|
||||
if (low == "trend") out = Kind::Trend;
|
||||
else if (low == "ray") out = Kind::Ray;
|
||||
else if (low == "hline" || low == "horizontal") out = Kind::HLine;
|
||||
else if (low == "vline" || low == "vertical") out = Kind::VLine;
|
||||
else if (low == "rect" || low == "rectangle") out = Kind::Rect;
|
||||
else if (low == "ellipse" || low == "oval") out = Kind::Ellipse;
|
||||
else if (low == "arrow") out = Kind::Arrow;
|
||||
else if (low == "text" || low == "label") out = Kind::Text;
|
||||
else if (low == "fib" || low == "fibonacci") out = Kind::Fib;
|
||||
else if (low == "free" || low == "freehand") out = Kind::Freehand;
|
||||
else if (low == "measure") out = Kind::Measure;
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// The data -> pixel mapping for one render. x/y/w/h is the price-pane
|
||||
// plot rectangle in pixels; begin/count is the visible window in bar
|
||||
// units; lo/hi is the visible price range. Bar centres sit at
|
||||
// (bar - begin + 0.5) slots, matching the candle layout.
|
||||
struct Map {
|
||||
double x = 0, y = 0, w = 0, h = 0;
|
||||
double begin = 0, count = 1;
|
||||
double lo = 0, hi = 1;
|
||||
|
||||
double px(double bar) const {
|
||||
return x + (bar - begin + 0.5) * (w / count);
|
||||
}
|
||||
double py(double price) const {
|
||||
return y + (hi - price) / (hi - lo) * h;
|
||||
}
|
||||
double bar_at(double px_) const {
|
||||
return begin + (px_ - x) / (w / count) - 0.5;
|
||||
}
|
||||
double price_at(double py_) const {
|
||||
return hi - (py_ - y) / h * (hi - lo);
|
||||
}
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
|
||||
inline void set_style(cairo_t* cr, const Drawing& d, bool selected) {
|
||||
int ci = ((d.color % kPaletteSize) + kPaletteSize) % kPaletteSize;
|
||||
const double* c = kPalette[ci];
|
||||
cairo_set_source_rgba(cr, c[0], c[1], c[2], 0.92);
|
||||
cairo_set_line_width(cr, d.width + (selected ? 1.0 : 0.0));
|
||||
if (d.dash) {
|
||||
static const double kDash[] = {6, 4};
|
||||
cairo_set_dash(cr, kDash, 2, 0);
|
||||
} else {
|
||||
cairo_set_dash(cr, nullptr, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
inline double seg_dist(double px, double py, double x1, double y1,
|
||||
double x2, double y2) {
|
||||
double dx = x2 - x1, dy = y2 - y1;
|
||||
double len2 = dx * dx + dy * dy;
|
||||
double t = len2 > 0 ? ((px - x1) * dx + (py - y1) * dy) / len2 : 0;
|
||||
t = std::max(0.0, std::min(1.0, t));
|
||||
double ex = x1 + t * dx - px, ey = y1 + t * dy - py;
|
||||
return std::sqrt(ex * ex + ey * ey);
|
||||
}
|
||||
|
||||
// A small filled label with a light backing box (text + measure).
|
||||
inline void label_box(cairo_t* cr, double x, double y,
|
||||
const std::string& s, const double* col) {
|
||||
cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL,
|
||||
CAIRO_FONT_WEIGHT_NORMAL);
|
||||
cairo_set_font_size(cr, 11);
|
||||
cairo_text_extents_t te;
|
||||
cairo_text_extents(cr, s.c_str(), &te);
|
||||
cairo_set_source_rgba(cr, 1, 1, 1, 0.85);
|
||||
cairo_rectangle(cr, x - 3, y - te.height - 4, te.width + 6,
|
||||
te.height + 5);
|
||||
cairo_fill(cr);
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 1.0);
|
||||
cairo_move_to(cr, x, y - 3);
|
||||
cairo_show_text(cr, s.c_str());
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
// Render one drawing. Clips to the plot rectangle (rays and lines may
|
||||
// run off the edge). `selected` draws it slightly bolder.
|
||||
inline void draw(cairo_t* cr, const Map& m, const Drawing& d,
|
||||
bool selected = false) {
|
||||
if (d.pts.empty() || m.w < 2 || m.h < 2 || m.hi - m.lo < 1e-12)
|
||||
return;
|
||||
int ci = ((d.color % kPaletteSize) + kPaletteSize) % kPaletteSize;
|
||||
const double* col = kPalette[ci];
|
||||
cairo_save(cr);
|
||||
cairo_rectangle(cr, m.x - 40, m.y - 40, m.w + 80, m.h + 80);
|
||||
cairo_clip(cr);
|
||||
detail::set_style(cr, d, selected);
|
||||
auto X = [&](const Anchor& a) { return m.px(a.bar); };
|
||||
auto Y = [&](const Anchor& a) { return m.py(a.price); };
|
||||
switch (d.kind) {
|
||||
case Kind::Trend:
|
||||
case Kind::Measure: {
|
||||
if (d.pts.size() < 2) break;
|
||||
cairo_move_to(cr, X(d.pts[0]), Y(d.pts[0]));
|
||||
cairo_line_to(cr, X(d.pts[1]), Y(d.pts[1]));
|
||||
cairo_stroke(cr);
|
||||
if (d.kind == Kind::Measure) {
|
||||
double dp = d.pts[1].price - d.pts[0].price;
|
||||
double pct = d.pts[0].price != 0
|
||||
? dp / std::fabs(d.pts[0].price) * 100
|
||||
: 0;
|
||||
long bars = std::lround(d.pts[1].bar - d.pts[0].bar);
|
||||
char buf[96];
|
||||
std::snprintf(buf, sizeof buf, "%+.2f (%+.2f%%) / %ld bars",
|
||||
dp, pct, bars);
|
||||
detail::label_box(cr,
|
||||
(X(d.pts[0]) + X(d.pts[1])) / 2,
|
||||
(Y(d.pts[0]) + Y(d.pts[1])) / 2 - 4,
|
||||
buf, col);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Kind::Ray: {
|
||||
if (d.pts.size() < 2) break;
|
||||
double x1 = X(d.pts[0]), y1 = Y(d.pts[0]);
|
||||
double x2 = x1 + (X(d.pts[1]) - x1) * 1000;
|
||||
double y2 = y1 + (Y(d.pts[1]) - y1) * 1000;
|
||||
cairo_move_to(cr, x1, y1);
|
||||
cairo_line_to(cr, x2, y2);
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::Arrow: {
|
||||
if (d.pts.size() < 2) break;
|
||||
double x1 = X(d.pts[0]), y1 = Y(d.pts[0]);
|
||||
double x2 = X(d.pts[1]), y2 = Y(d.pts[1]);
|
||||
cairo_move_to(cr, x1, y1);
|
||||
cairo_line_to(cr, x2, y2);
|
||||
cairo_stroke(cr);
|
||||
double ang = std::atan2(y2 - y1, x2 - x1);
|
||||
double alen = 11;
|
||||
cairo_move_to(cr, x2, y2);
|
||||
cairo_line_to(cr, x2 - alen * std::cos(ang - 0.42),
|
||||
y2 - alen * std::sin(ang - 0.42));
|
||||
cairo_move_to(cr, x2, y2);
|
||||
cairo_line_to(cr, x2 - alen * std::cos(ang + 0.42),
|
||||
y2 - alen * std::sin(ang + 0.42));
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::HLine: {
|
||||
double y = Y(d.pts[0]);
|
||||
cairo_move_to(cr, m.x, y);
|
||||
cairo_line_to(cr, m.x + m.w, y);
|
||||
cairo_stroke(cr);
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof buf, "%.2f", d.pts[0].price);
|
||||
detail::label_box(cr, m.x + 4, y - 2, buf, col);
|
||||
break;
|
||||
}
|
||||
case Kind::VLine: {
|
||||
double x = X(d.pts[0]);
|
||||
cairo_move_to(cr, x, m.y);
|
||||
cairo_line_to(cr, x, m.y + m.h);
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::Rect:
|
||||
case Kind::Ellipse: {
|
||||
if (d.pts.size() < 2) break;
|
||||
double x1 = X(d.pts[0]), y1 = Y(d.pts[0]);
|
||||
double x2 = X(d.pts[1]), y2 = Y(d.pts[1]);
|
||||
double rx = std::min(x1, x2), ry = std::min(y1, y2);
|
||||
double rw = std::fabs(x2 - x1), rh = std::fabs(y2 - y1);
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 0.08);
|
||||
if (d.kind == Kind::Rect) {
|
||||
cairo_rectangle(cr, rx, ry, rw, rh);
|
||||
cairo_fill(cr);
|
||||
detail::set_style(cr, d, selected);
|
||||
cairo_rectangle(cr, rx, ry, rw, rh);
|
||||
cairo_stroke(cr);
|
||||
} else {
|
||||
cairo_save(cr);
|
||||
cairo_translate(cr, rx + rw / 2, ry + rh / 2);
|
||||
cairo_scale(cr, std::max(rw, 0.1), std::max(rh, 0.1));
|
||||
cairo_arc(cr, 0, 0, 0.5, 0, 2 * M_PI);
|
||||
cairo_restore(cr);
|
||||
cairo_fill(cr);
|
||||
detail::set_style(cr, d, selected);
|
||||
cairo_save(cr);
|
||||
cairo_translate(cr, rx + rw / 2, ry + rh / 2);
|
||||
cairo_scale(cr, std::max(rw, 0.1), std::max(rh, 0.1));
|
||||
cairo_arc(cr, 0, 0, 0.5, 0, 2 * M_PI);
|
||||
cairo_restore(cr);
|
||||
cairo_stroke(cr);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Kind::Text: {
|
||||
if (d.text.empty()) break;
|
||||
detail::label_box(cr, X(d.pts[0]) + 2, Y(d.pts[0]) - 2,
|
||||
d.text, col);
|
||||
// Anchor dot.
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 1.0);
|
||||
cairo_arc(cr, X(d.pts[0]), Y(d.pts[0]), 2.5, 0, 2 * M_PI);
|
||||
cairo_fill(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::Fib: {
|
||||
if (d.pts.size() < 2) break;
|
||||
static const double kLevels[] = {0, 0.236, 0.382, 0.5,
|
||||
0.618, 0.786, 1.0};
|
||||
double x1 = X(d.pts[0]);
|
||||
cairo_set_line_width(cr, 1.0);
|
||||
for (double lv : kLevels) {
|
||||
double price =
|
||||
d.pts[0].price + (d.pts[1].price - d.pts[0].price) * lv;
|
||||
double y = m.py(price);
|
||||
static const double kDash[] = {4, 3};
|
||||
cairo_set_dash(cr, kDash, 2, 0);
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 0.75);
|
||||
cairo_move_to(cr, x1, y);
|
||||
cairo_line_to(cr, m.x + m.w, y);
|
||||
cairo_stroke(cr);
|
||||
cairo_set_dash(cr, nullptr, 0, 0);
|
||||
char buf[48];
|
||||
std::snprintf(buf, sizeof buf, "%.1f%% %.2f", lv * 100,
|
||||
price);
|
||||
detail::label_box(cr, x1 + 4, y - 2, buf, col);
|
||||
}
|
||||
// Connector between the anchors.
|
||||
detail::set_style(cr, d, selected);
|
||||
cairo_move_to(cr, X(d.pts[0]), Y(d.pts[0]));
|
||||
cairo_line_to(cr, X(d.pts[1]), Y(d.pts[1]));
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
case Kind::Freehand: {
|
||||
if (d.pts.size() < 2) break;
|
||||
cairo_move_to(cr, X(d.pts[0]), Y(d.pts[0]));
|
||||
for (size_t i = 1; i < d.pts.size(); ++i)
|
||||
cairo_line_to(cr, X(d.pts[i]), Y(d.pts[i]));
|
||||
cairo_stroke(cr);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (selected) {
|
||||
// Corner dots on the anchors.
|
||||
cairo_set_source_rgba(cr, col[0], col[1], col[2], 1.0);
|
||||
for (const Anchor& a : d.pts) {
|
||||
cairo_arc(cr, X(a), Y(a), 3, 0, 2 * M_PI);
|
||||
cairo_fill(cr);
|
||||
}
|
||||
}
|
||||
cairo_restore(cr);
|
||||
}
|
||||
|
||||
// Is pixel (px, py) within `tol` px of the drawing? Used by the
|
||||
// select/move and erase tools.
|
||||
inline bool hit_test(const Map& m, const Drawing& d, double px,
|
||||
double py, double tol = 6) {
|
||||
if (d.pts.empty()) return false;
|
||||
auto X = [&](const Anchor& a) { return m.px(a.bar); };
|
||||
auto Y = [&](const Anchor& a) { return m.py(a.price); };
|
||||
switch (d.kind) {
|
||||
case Kind::Trend:
|
||||
case Kind::Ray:
|
||||
case Kind::Arrow:
|
||||
case Kind::Measure:
|
||||
if (d.pts.size() < 2) return false;
|
||||
return detail::seg_dist(px, py, X(d.pts[0]), Y(d.pts[0]),
|
||||
X(d.pts[1]), Y(d.pts[1])) <= tol;
|
||||
case Kind::HLine:
|
||||
return std::fabs(py - Y(d.pts[0])) <= tol && px >= m.x &&
|
||||
px <= m.x + m.w;
|
||||
case Kind::VLine:
|
||||
return std::fabs(px - X(d.pts[0])) <= tol && py >= m.y &&
|
||||
py <= m.y + m.h;
|
||||
case Kind::Rect:
|
||||
case Kind::Ellipse: {
|
||||
if (d.pts.size() < 2) return false;
|
||||
double x1 = X(d.pts[0]), y1 = Y(d.pts[0]);
|
||||
double x2 = X(d.pts[1]), y2 = Y(d.pts[1]);
|
||||
bool inside = px >= std::min(x1, x2) && px <= std::max(x1, x2) &&
|
||||
py >= std::min(y1, y2) && py <= std::max(y1, y2);
|
||||
bool near_edge =
|
||||
detail::seg_dist(px, py, x1, y1, x2, y1) <= tol ||
|
||||
detail::seg_dist(px, py, x2, y1, x2, y2) <= tol ||
|
||||
detail::seg_dist(px, py, x2, y2, x1, y2) <= tol ||
|
||||
detail::seg_dist(px, py, x1, y2, x1, y1) <= tol;
|
||||
return inside || near_edge;
|
||||
}
|
||||
case Kind::Text: {
|
||||
double x = X(d.pts[0]), y = Y(d.pts[0]);
|
||||
double w = 10 + (double)d.text.size() * 6.5;
|
||||
return px >= x - 4 && px <= x + w && py >= y - 16 &&
|
||||
py <= y + 4;
|
||||
}
|
||||
case Kind::Fib: {
|
||||
if (d.pts.size() < 2) return false;
|
||||
static const double kLevels[] = {0, 0.236, 0.382, 0.5,
|
||||
0.618, 0.786, 1.0};
|
||||
for (double lv : kLevels) {
|
||||
double price =
|
||||
d.pts[0].price + (d.pts[1].price - d.pts[0].price) * lv;
|
||||
if (std::fabs(py - m.py(price)) <= tol && px >= X(d.pts[0]))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case Kind::Freehand:
|
||||
for (size_t i = 1; i < d.pts.size(); ++i)
|
||||
if (detail::seg_dist(px, py, X(d.pts[i - 1]),
|
||||
Y(d.pts[i - 1]), X(d.pts[i]),
|
||||
Y(d.pts[i])) <= tol)
|
||||
return true;
|
||||
return d.pts.size() == 1 &&
|
||||
std::hypot(px - X(d.pts[0]), py - Y(d.pts[0])) <= tol;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Shift every anchor by a data-space delta (select/move drags).
|
||||
inline void move(Drawing& d, double dbar, double dprice) {
|
||||
for (Anchor& a : d.pts) {
|
||||
a.bar += dbar;
|
||||
a.price += dprice;
|
||||
}
|
||||
if (d.kind == Kind::HLine)
|
||||
for (Anchor& a : d.pts) a.bar -= dbar; // bar is meaningless
|
||||
if (d.kind == Kind::VLine)
|
||||
for (Anchor& a : d.pts) a.price -= dprice;
|
||||
}
|
||||
|
||||
// Parse one spec (grammar in the header comment).
|
||||
inline std::optional<Drawing> parse_spec(const std::string& spec) {
|
||||
// Tokenize on whitespace, remembering where the tail starts (text).
|
||||
std::vector<std::string> tok;
|
||||
std::vector<size_t> tok_pos;
|
||||
size_t i = 0;
|
||||
while (i < spec.size()) {
|
||||
while (i < spec.size() &&
|
||||
(spec[i] == ' ' || spec[i] == '\t'))
|
||||
++i;
|
||||
if (i >= spec.size()) break;
|
||||
size_t s = i;
|
||||
while (i < spec.size() && spec[i] != ' ' && spec[i] != '\t')
|
||||
++i;
|
||||
tok.push_back(spec.substr(s, i - s));
|
||||
tok_pos.push_back(s);
|
||||
}
|
||||
if (tok.empty()) return std::nullopt;
|
||||
Drawing d;
|
||||
if (!kind_from_name(tok[0], d.kind)) return std::nullopt;
|
||||
size_t t = 1;
|
||||
auto number = [&](double& v) {
|
||||
if (t >= tok.size()) return false;
|
||||
char* end = nullptr;
|
||||
v = std::strtod(tok[t].c_str(), &end);
|
||||
if (end == tok[t].c_str()) return false;
|
||||
++t;
|
||||
return true;
|
||||
};
|
||||
auto anchor = [&](Anchor& a) {
|
||||
return number(a.bar) && number(a.price);
|
||||
};
|
||||
auto tail_options = [&]() {
|
||||
while (t < tok.size()) {
|
||||
int ci = color_index_of(tok[t]);
|
||||
if (ci >= 0) {
|
||||
d.color = ci;
|
||||
++t;
|
||||
} else if (tok[t] == "dash") {
|
||||
d.dash = true;
|
||||
++t;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
switch (d.kind) {
|
||||
case Kind::HLine: {
|
||||
double p;
|
||||
if (!number(p)) return std::nullopt;
|
||||
d.pts.push_back({0, p});
|
||||
tail_options();
|
||||
return d;
|
||||
}
|
||||
case Kind::VLine: {
|
||||
double b;
|
||||
if (!number(b)) return std::nullopt;
|
||||
d.pts.push_back({b, 0});
|
||||
tail_options();
|
||||
return d;
|
||||
}
|
||||
case Kind::Text: {
|
||||
Anchor a;
|
||||
if (!anchor(a)) return std::nullopt;
|
||||
d.pts.push_back(a);
|
||||
tail_options();
|
||||
if (t < tok.size())
|
||||
d.text = spec.substr(tok_pos[t]);
|
||||
if (d.text.empty()) return std::nullopt;
|
||||
return d;
|
||||
}
|
||||
case Kind::Freehand: {
|
||||
while (t < tok.size()) {
|
||||
char* end = nullptr;
|
||||
double v = std::strtod(tok[t].c_str(), &end);
|
||||
if (end == tok[t].c_str()) break;
|
||||
Anchor a;
|
||||
a.bar = v;
|
||||
++t;
|
||||
if (!number(a.price)) return std::nullopt;
|
||||
d.pts.push_back(a);
|
||||
}
|
||||
tail_options();
|
||||
if (d.pts.size() < 2) return std::nullopt;
|
||||
return d;
|
||||
}
|
||||
default: { // two-anchor kinds
|
||||
Anchor a, b;
|
||||
if (!anchor(a) || !anchor(b)) return std::nullopt;
|
||||
d.pts.push_back(a);
|
||||
d.pts.push_back(b);
|
||||
tail_options();
|
||||
return d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse a semicolon-separated list of specs; bad entries are skipped.
|
||||
inline std::vector<Drawing> parse_specs(const std::string& specs) {
|
||||
std::vector<Drawing> out;
|
||||
size_t start = 0;
|
||||
for (size_t i = 0; i <= specs.size(); ++i) {
|
||||
if (i == specs.size() || specs[i] == ';') {
|
||||
auto d = parse_spec(specs.substr(start, i - start));
|
||||
if (d) out.push_back(*d);
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Canonical spec for a drawing (parse_spec(to_spec(d)) round-trips).
|
||||
inline std::string to_spec(const Drawing& d) {
|
||||
static const char* kNames[] = {"blue", "red", "green", "orange",
|
||||
"purple", "teal", "magenta", "brown",
|
||||
"black", "slate"};
|
||||
int ci = ((d.color % kPaletteSize) + kPaletteSize) % kPaletteSize;
|
||||
char buf[64];
|
||||
std::string s = kind_name(d.kind);
|
||||
auto num = [&](double v) {
|
||||
std::snprintf(buf, sizeof buf, " %g", v);
|
||||
s += buf;
|
||||
};
|
||||
if (d.kind == Kind::HLine) {
|
||||
num(d.pts.empty() ? 0 : d.pts[0].price);
|
||||
} else if (d.kind == Kind::VLine) {
|
||||
num(d.pts.empty() ? 0 : d.pts[0].bar);
|
||||
} else {
|
||||
for (const Anchor& a : d.pts) {
|
||||
num(a.bar);
|
||||
num(a.price);
|
||||
}
|
||||
}
|
||||
s += " ";
|
||||
s += kNames[ci];
|
||||
if (d.dash) s += " dash";
|
||||
if (d.kind == Kind::Text) {
|
||||
s += " ";
|
||||
s += d.text;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
} // namespace fdw
|
||||
)FDDRAWINGS9b2c";
|
||||
@@ -1,227 +0,0 @@
|
||||
// FDesigner event table — the natural GTK signal(s) for every widget type.
|
||||
//
|
||||
// Every palette type is listed here exactly once: either with the signals
|
||||
// a user can connect (each gets a generated stub handler, connected via
|
||||
// g_signal_connect in the generated widget class) or with an explicit
|
||||
// "no events" note saying why it has none. NONE is left unexamined.
|
||||
// The table drives three things: the designer's Events pane (main.cpp),
|
||||
// the code generator (generator.cpp), and the event tests.
|
||||
//
|
||||
// Signal kinds (how the generator wires each one):
|
||||
// Simple — void on_x(); trampoline (GtkWidget*, gpointer)
|
||||
// SwitchPage — void on_x(guint page); notebook "switch-page"
|
||||
// RowActivated — void on_x(GtkTreePath* path); tree "row-activated"
|
||||
// RowSelected — void on_x(); trampoline (GtkListBox*, GtkListBoxRow*, gpointer)
|
||||
// BufferChanged — void on_x(); connected to the TextView's GtkTextBuffer
|
||||
// DeleteEvent — bool on_x(); trampoline (GtkWidget*, GdkEvent*, gpointer)
|
||||
// Draw — static gboolean on_draw(GtkWidget*, cairo_t*, gpointer)
|
||||
// ItemClicked — ToolBar: one void on_<item>_clicked() per tool button
|
||||
// ItemActivate — MenuBar: one void on_<item>_activate() per menu item
|
||||
// CellChanged — Spreadsheet: void on_x() on every cell entry
|
||||
// A builtin event is already wired by the generator for other reasons
|
||||
// (Shape/Plot/StockChart draw); the table documents it and the generator
|
||||
// must not connect it a second time.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "model.h"
|
||||
|
||||
enum class EventKind {
|
||||
Simple,
|
||||
SwitchPage,
|
||||
RowActivated,
|
||||
RowSelected,
|
||||
BufferChanged,
|
||||
DeleteEvent,
|
||||
Draw,
|
||||
ItemClicked,
|
||||
ItemActivate,
|
||||
CellChanged,
|
||||
};
|
||||
|
||||
struct EventDef {
|
||||
const char* signal; // GTK signal name, e.g. "clicked"
|
||||
const char* handler; // member handler name, e.g. "on_clicked"
|
||||
const char* label; // short human label for the Events pane
|
||||
EventKind kind;
|
||||
bool builtin = false; // already wired; document only, do not reconnect
|
||||
};
|
||||
|
||||
inline const std::vector<EventDef>& events_for(const std::string& type) {
|
||||
using K = EventKind;
|
||||
static const std::vector<EventDef> none;
|
||||
static const std::vector<EventDef> button = {
|
||||
{"clicked", "on_clicked", "Clicked", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> entry = {
|
||||
{"changed", "on_changed", "Text changed", K::Simple},
|
||||
{"activate", "on_activate", "Enter pressed (activate)", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> checkbutton = {
|
||||
{"toggled", "on_toggled", "Toggled", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> radiobutton = {
|
||||
{"toggled", "on_toggled", "Toggled", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> combobox = {
|
||||
{"changed", "on_changed", "Selection changed", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> listbox = {
|
||||
{"row-selected", "on_row_selected", "Row selected", K::RowSelected},
|
||||
};
|
||||
static const std::vector<EventDef> menubutton = {
|
||||
{"clicked", "on_clicked", "Clicked", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> canvas = {
|
||||
{"draw", "on_draw", "Draw (redraw)", K::Draw},
|
||||
};
|
||||
static const std::vector<EventDef> scale = {
|
||||
{"value-changed", "on_value_changed", "Value changed", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> scrollbar = {
|
||||
{"value-changed", "on_value_changed", "Value changed", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> text = {
|
||||
{"changed", "on_changed", "Text changed", K::BufferChanged},
|
||||
};
|
||||
static const std::vector<EventDef> toplevel = {
|
||||
{"delete-event", "on_delete_event", "Window close (delete-event)",
|
||||
K::DeleteEvent},
|
||||
};
|
||||
static const std::vector<EventDef> spreadsheet = {
|
||||
{"changed", "on_cell_changed", "Cell text changed", K::CellChanged},
|
||||
};
|
||||
static const std::vector<EventDef> stockchart = {
|
||||
// Draw, wheel zoom, drag pan and the drawing tools are already
|
||||
// wired by the generator (on_draw, on_chart_scroll, on_chart_press,
|
||||
// on_chart_motion, on_chart_release, on_chart_key).
|
||||
{"draw", "on_draw", "Draw (redraw)", K::Draw, true},
|
||||
};
|
||||
static const std::vector<EventDef> memo = {
|
||||
{"changed", "on_changed", "Text changed", K::BufferChanged},
|
||||
};
|
||||
static const std::vector<EventDef> shape = {
|
||||
{"draw", "on_draw", "Draw (redraw)", K::Draw, true},
|
||||
};
|
||||
static const std::vector<EventDef> notebook = {
|
||||
{"switch-page", "on_switch_page", "Page switched", K::SwitchPage},
|
||||
};
|
||||
static const std::vector<EventDef> toolbar = {
|
||||
{"clicked", "on_clicked", "Tool button clicked", K::ItemClicked},
|
||||
};
|
||||
static const std::vector<EventDef> menubar = {
|
||||
{"activate", "on_activate", "Menu item activated", K::ItemActivate},
|
||||
};
|
||||
static const std::vector<EventDef> spinedit = {
|
||||
{"value-changed", "on_value_changed", "Value changed", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> trackbar = {
|
||||
{"value-changed", "on_value_changed", "Value changed", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> datetimepicker = {
|
||||
{"day-selected", "on_day_selected", "Day selected", K::Simple},
|
||||
{"month-changed", "on_month_changed", "Month changed", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> colorbox = {
|
||||
{"color-set", "on_color_set", "Colour chosen", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> listview = {
|
||||
{"row-activated", "on_row_activated", "Row activated (double-click)",
|
||||
K::RowActivated},
|
||||
{"cursor-changed", "on_cursor_changed", "Cursor moved", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> treeview = {
|
||||
{"row-activated", "on_row_activated", "Row activated (double-click)",
|
||||
K::RowActivated},
|
||||
{"cursor-changed", "on_cursor_changed", "Cursor moved", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> stringgrid = {
|
||||
{"row-activated", "on_row_activated", "Row activated (double-click)",
|
||||
K::RowActivated},
|
||||
{"cursor-changed", "on_cursor_changed", "Cursor moved", K::Simple},
|
||||
};
|
||||
static const std::vector<EventDef> plot = {
|
||||
{"draw", "on_draw", "Draw (redraw)", K::Draw, true},
|
||||
};
|
||||
if (type == "Button") return button;
|
||||
if (type == "Entry") return entry;
|
||||
if (type == "Checkbutton") return checkbutton;
|
||||
if (type == "Radiobutton") return radiobutton;
|
||||
if (type == "Combobox") return combobox;
|
||||
if (type == "Listbox") return listbox;
|
||||
if (type == "Menubutton") return menubutton;
|
||||
if (type == "Canvas") return canvas;
|
||||
if (type == "Scale") return scale;
|
||||
if (type == "Scrollbar") return scrollbar;
|
||||
if (type == "Text") return text;
|
||||
if (type == "Toplevel") return toplevel;
|
||||
if (type == "Spreadsheet") return spreadsheet;
|
||||
if (type == "StockChart") return stockchart;
|
||||
if (type == "Memo") return memo;
|
||||
if (type == "Shape") return shape;
|
||||
if (type == "Notebook") return notebook;
|
||||
if (type == "ToolBar") return toolbar;
|
||||
if (type == "MenuBar") return menubar;
|
||||
if (type == "SpinEdit") return spinedit;
|
||||
if (type == "TrackBar") return trackbar;
|
||||
if (type == "DateTimePicker") return datetimepicker;
|
||||
if (type == "ColorBox") return colorbox;
|
||||
if (type == "ListView") return listview;
|
||||
if (type == "TreeView") return treeview;
|
||||
if (type == "StringGrid") return stringgrid;
|
||||
if (type == "Plot") return plot;
|
||||
return none; // Label, Frame, GroupBox, Panel, Image, ScrollBox,
|
||||
// Splitter, StatusBar, ProgressBar — see no_events_note()
|
||||
}
|
||||
|
||||
// Why a type with no events has none (shown in the Events pane so the
|
||||
// absence is explicit, not an omission).
|
||||
inline std::string no_events_note(const std::string& type) {
|
||||
if (type == "Label")
|
||||
return "Display-only: no widget-specific signal "
|
||||
"(mouse handlers still apply).";
|
||||
if (type == "Frame" || type == "GroupBox" || type == "Panel")
|
||||
return "Container: no widget-specific signal — connect the "
|
||||
"signals of the widgets placed inside it.";
|
||||
if (type == "Image")
|
||||
return "Display-only: no widget-specific signal "
|
||||
"(mouse handlers still apply).";
|
||||
if (type == "ScrollBox")
|
||||
return "Container: no widget-specific signal — connect the "
|
||||
"signals of the widgets placed inside it.";
|
||||
if (type == "Splitter")
|
||||
return "GTK 3 GtkPaned exposes no position signal: no "
|
||||
"widget-specific signal.";
|
||||
if (type == "StatusBar")
|
||||
return "Display-only: no widget-specific signal.";
|
||||
if (type == "ProgressBar")
|
||||
return "Display-only: no widget-specific signal — set its "
|
||||
"fraction from another widget's handler.";
|
||||
return "No widget-specific signal.";
|
||||
}
|
||||
|
||||
// Find one event definition for a type by GTK signal name.
|
||||
inline const EventDef* find_event(const std::string& type,
|
||||
const std::string& signal) {
|
||||
for (const EventDef& d : events_for(type))
|
||||
if (signal == d.signal) return &d;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Connect/disconnect one signal on a widget model; false if the signal
|
||||
// is not one of the type's events.
|
||||
inline bool set_widget_signal(Widget& w, const std::string& signal,
|
||||
bool connect) {
|
||||
if (!find_event(w.type, signal)) return false;
|
||||
auto it = std::find(w.signals.begin(), w.signals.end(), signal);
|
||||
if (connect) {
|
||||
if (it == w.signals.end()) w.signals.push_back(signal);
|
||||
} else if (it != w.signals.end()) {
|
||||
w.signals.erase(it);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
// FDesigner code generator.
|
||||
// Turns the designed window (Project + widgets) into a compilable C++/GTK
|
||||
// project. The output is ALL CODE — no .ui file — and every widget is a
|
||||
// STANDALONE CLASS in its own .h/.cpp pair, mirroring the Python
|
||||
// generator's boilerplate: the class creates and configures its widget in
|
||||
// its constructor and carries the same nine mouse-event stub handlers
|
||||
// (buttonPress1-3, dblbuttonPress1-3, buttonRelease1-3) plus a
|
||||
// util_error_print helper. The generated window class just instantiates
|
||||
// one widget class per designed widget. Because construction is ordinary
|
||||
// sequential code in per-widget classes, a stepping debugger can walk it
|
||||
// line by line, and adding a widget by hand means copying one class.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "model.h"
|
||||
|
||||
struct GenResult {
|
||||
bool ok = false;
|
||||
std::string error;
|
||||
std::vector<std::string> files; // paths written, in order
|
||||
};
|
||||
|
||||
// Writes the project into out_dir (created if needed).
|
||||
GenResult generate_project(const Project& project,
|
||||
const std::vector<Widget>& widgets,
|
||||
const std::string& out_dir);
|
||||
@@ -1,86 +0,0 @@
|
||||
// FDesigner model — the designed window as data.
|
||||
// Mirrors the Python original's widget dict: every placed widget has a name,
|
||||
// a type, absolute geometry (Tk .place() style), and a property map.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct Widget {
|
||||
std::string name; // e.g. "Button_001"
|
||||
std::string type; // palette type key, e.g. "Button"
|
||||
int x = 0, y = 0;
|
||||
int width = 100, height = 30;
|
||||
std::map<std::string, std::string> props; // GTK properties, as strings
|
||||
std::vector<std::string> signals; // signals to stub in generated code
|
||||
};
|
||||
|
||||
struct Project {
|
||||
std::string title = "Main Window";
|
||||
std::string class_name = "MyWindow";
|
||||
int win_width = 800;
|
||||
int win_height = 600;
|
||||
std::string background; // window background colour, "" = default
|
||||
// Menu bar spec, one menu per line: "File: New | Open | - | Quit"
|
||||
// ("-" is a separator). Empty = no menu bar.
|
||||
std::string menubar;
|
||||
std::vector<Widget> widgets;
|
||||
};
|
||||
|
||||
// One row of the palette: type key, button label in the .ui, default size,
|
||||
// and whether this phase implements it (Toplevel/Spreadsheet arrive later).
|
||||
struct TypeInfo {
|
||||
const char* key;
|
||||
const char* palette_id; // GtkBuilder id of the palette button
|
||||
int def_width;
|
||||
int def_height;
|
||||
bool phase1;
|
||||
};
|
||||
|
||||
inline const TypeInfo kTypes[] = {
|
||||
{"Button", "pal_button", 100, 30, true },
|
||||
{"Label", "pal_label", 100, 24, true },
|
||||
{"Entry", "pal_entry", 160, 28, true },
|
||||
{"Checkbutton", "pal_checkbutton", 120, 26, true },
|
||||
{"Radiobutton", "pal_radiobutton", 120, 26, true },
|
||||
{"Frame", "pal_frame", 200, 120, true },
|
||||
{"Combobox", "pal_combobox", 160, 28, true },
|
||||
{"Listbox", "pal_listbox", 180, 110, true },
|
||||
{"Menubutton", "pal_menubutton", 110, 30, true },
|
||||
{"Canvas", "pal_canvas", 200, 140, true },
|
||||
{"Scale", "pal_scale", 160, 28, true },
|
||||
{"Scrollbar", "pal_scrollbar", 160, 18, true },
|
||||
{"Text", "pal_text", 220, 120, true },
|
||||
{"Toplevel", "pal_toplevel", 300, 200, true },
|
||||
{"Spreadsheet", "pal_spreadsheet", 320, 180, true },
|
||||
{"StockChart", "pal_stockchart", 320, 200, true },
|
||||
// Lazarus-style widgets (Lazarus palette -> GTK 3 equivalent).
|
||||
{"Memo", "pal_memo", 220, 120, true },
|
||||
{"GroupBox", "pal_groupbox", 200, 120, true },
|
||||
{"Panel", "pal_panel", 200, 120, true },
|
||||
{"Image", "pal_image", 160, 120, true },
|
||||
{"Shape", "pal_shape", 160, 120, true },
|
||||
{"Notebook", "pal_notebook", 320, 200, true },
|
||||
{"ScrollBox", "pal_scrollbox", 240, 160, true },
|
||||
{"Splitter", "pal_splitter", 280, 160, true },
|
||||
{"StatusBar", "pal_statusbar", 320, 24, true },
|
||||
{"ToolBar", "pal_toolbar", 320, 36, true },
|
||||
{"MenuBar", "pal_menubar", 320, 28, true },
|
||||
{"SpinEdit", "pal_spinedit", 120, 28, true },
|
||||
{"TrackBar", "pal_trackbar", 160, 28, true },
|
||||
{"ProgressBar", "pal_progressbar", 200, 24, true },
|
||||
{"DateTimePicker","pal_datetimepicker",240, 200, true },
|
||||
{"ColorBox", "pal_colorbox", 120, 28, true },
|
||||
{"ListView", "pal_listview", 240, 140, true },
|
||||
{"TreeView", "pal_treeview", 240, 140, true },
|
||||
{"StringGrid", "pal_stringgrid", 280, 160, true },
|
||||
{"Plot", "pal_plot", 280, 180, true },
|
||||
};
|
||||
|
||||
inline const TypeInfo* find_type(const std::string& key) {
|
||||
for (const TypeInfo& t : kTypes)
|
||||
if (key == t.key) return &t;
|
||||
return nullptr;
|
||||
}
|
||||
@@ -1,283 +0,0 @@
|
||||
// FDesigner global font settings — implementation. See preferences.h.
|
||||
#include "preferences.h"
|
||||
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
|
||||
namespace {
|
||||
|
||||
// Same persistence pattern as DebuggerSettings in debugger.cpp.
|
||||
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);
|
||||
}
|
||||
|
||||
// Escape a font family for a quoted CSS string value.
|
||||
std::string css_quote(const std::string& family) {
|
||||
std::string out;
|
||||
for (char c : family) {
|
||||
if (c == '"' || c == '\\') out += '\\';
|
||||
out += c;
|
||||
}
|
||||
return "\"" + out + "\"";
|
||||
}
|
||||
|
||||
void load_css(GtkCssProvider* provider, const std::string& css) {
|
||||
GError* error = nullptr;
|
||||
gtk_css_provider_load_from_data(provider, css.c_str(), -1, &error);
|
||||
if (error) {
|
||||
std::fprintf(stderr, "fdesigner: font CSS failed: %s\n",
|
||||
error->message);
|
||||
g_error_free(error);
|
||||
}
|
||||
}
|
||||
|
||||
FontSettings g_current;
|
||||
bool g_current_loaded = false;
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string FontSettings::default_path() {
|
||||
const char* e = std::getenv("FDESIGNER_SETTINGS_CONF");
|
||||
if (e && *e) return e;
|
||||
return home_dir() + "/.config/fdesigner/settings.conf";
|
||||
}
|
||||
|
||||
std::string FontSettings::sanitized(const std::string& desc,
|
||||
const std::string& fallback) {
|
||||
PangoFontDescription* d =
|
||||
pango_font_description_from_string(desc.c_str());
|
||||
const char* family =
|
||||
d ? pango_font_description_get_family(d) : nullptr;
|
||||
if (!d || !family || !*family) {
|
||||
if (d) pango_font_description_free(d);
|
||||
if (desc == fallback) return "Sans 10"; // fallback itself is bad
|
||||
return sanitized(fallback, fallback);
|
||||
}
|
||||
int size = pango_font_description_get_size(d); // Pango units, 0 = unset
|
||||
int fallback_size = size_of(fallback);
|
||||
if (size <= 0)
|
||||
size = (fallback_size > 0 ? fallback_size : 10) * PANGO_SCALE;
|
||||
else if (size < 6 * PANGO_SCALE)
|
||||
size = 6 * PANGO_SCALE;
|
||||
else if (size > 48 * PANGO_SCALE)
|
||||
size = 48 * PANGO_SCALE;
|
||||
pango_font_description_set_size(d, size);
|
||||
char* s = pango_font_description_to_string(d);
|
||||
std::string out = s ? s : fallback;
|
||||
g_free(s);
|
||||
pango_font_description_free(d);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string FontSettings::family_of(const std::string& desc) {
|
||||
PangoFontDescription* d =
|
||||
pango_font_description_from_string(desc.c_str());
|
||||
if (!d) return "";
|
||||
const char* family = pango_font_description_get_family(d);
|
||||
std::string out = family ? family : "";
|
||||
pango_font_description_free(d);
|
||||
return out;
|
||||
}
|
||||
|
||||
int FontSettings::size_of(const std::string& desc) {
|
||||
PangoFontDescription* d =
|
||||
pango_font_description_from_string(desc.c_str());
|
||||
if (!d) return 0;
|
||||
int size = pango_font_description_get_size(d);
|
||||
pango_font_description_free(d);
|
||||
return size > 0 ? size / PANGO_SCALE : 0;
|
||||
}
|
||||
|
||||
std::string FontSettings::ui_css() const {
|
||||
return "* { font-family: " + css_quote(family_of(font)) +
|
||||
"; font-size: " + std::to_string(size_of(font)) + "pt; }";
|
||||
}
|
||||
|
||||
std::string FontSettings::code_css() const {
|
||||
return "textview { font-family: " + css_quote(family_of(code_font)) +
|
||||
"; font-size: " + std::to_string(size_of(code_font)) + "pt; }";
|
||||
}
|
||||
|
||||
bool FontSettings::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 << "# FDesigner settings\n";
|
||||
f << "font=" << sanitized(font, "Sans 10") << "\n";
|
||||
f << "code_font=" << sanitized(code_font, "Monospace 11") << "\n";
|
||||
return (bool)f;
|
||||
}
|
||||
|
||||
bool FontSettings::load(const std::string& path) {
|
||||
std::string p = path.empty() ? default_path() : path;
|
||||
std::ifstream f(p);
|
||||
if (!f) return false;
|
||||
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;
|
||||
std::string key = trim_s(t.substr(0, eq));
|
||||
std::string value = trim_s(t.substr(eq + 1));
|
||||
if (key == "font")
|
||||
font = sanitized(value, font);
|
||||
else if (key == "code_font")
|
||||
code_font = sanitized(value, code_font);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
FontSettings preferences_current() {
|
||||
if (!g_current_loaded) {
|
||||
g_current.load(); // keeps defaults when no file exists
|
||||
g_current_loaded = true;
|
||||
}
|
||||
return g_current;
|
||||
}
|
||||
|
||||
void preferences_apply(const FontSettings& s) {
|
||||
static GtkCssProvider* ui_provider = nullptr;
|
||||
static GtkCssProvider* code_provider = nullptr;
|
||||
static bool providers_added = false;
|
||||
if (!ui_provider) ui_provider = gtk_css_provider_new();
|
||||
if (!code_provider) code_provider = gtk_css_provider_new();
|
||||
load_css(ui_provider, s.ui_css());
|
||||
load_css(code_provider, s.code_css());
|
||||
if (!providers_added) {
|
||||
GdkScreen* screen = gdk_screen_get_default();
|
||||
if (screen) {
|
||||
gtk_style_context_add_provider_for_screen(
|
||||
screen, GTK_STYLE_PROVIDER(ui_provider),
|
||||
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
gtk_style_context_add_provider_for_screen(
|
||||
screen, GTK_STYLE_PROVIDER(code_provider),
|
||||
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
providers_added = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void preferences_apply_to_text_view(GtkWidget* view,
|
||||
const FontSettings& s) {
|
||||
if (!view) return;
|
||||
GtkCssProvider* provider = gtk_css_provider_new();
|
||||
load_css(provider,
|
||||
"* { font-family: " + css_quote(FontSettings::family_of(
|
||||
s.code_font)) +
|
||||
"; font-size: " +
|
||||
std::to_string(FontSettings::size_of(s.code_font)) +
|
||||
"pt; }");
|
||||
gtk_style_context_add_provider(
|
||||
gtk_widget_get_style_context(view), GTK_STYLE_PROVIDER(provider),
|
||||
GTK_STYLE_PROVIDER_PRIORITY_USER);
|
||||
g_object_unref(provider); // style context holds its own reference
|
||||
}
|
||||
|
||||
std::string preferences_applied_font(GtkWidget* widget) {
|
||||
if (!widget) return "";
|
||||
PangoContext* ctx = gtk_widget_get_pango_context(widget);
|
||||
if (!ctx) return "";
|
||||
const PangoFontDescription* d = pango_context_get_font_description(ctx);
|
||||
if (!d) return "";
|
||||
char* s = pango_font_description_to_string(d);
|
||||
std::string out = s ? s : "";
|
||||
g_free(s);
|
||||
return out;
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Response id for the dialog's "Reset to Defaults" button.
|
||||
const int kResetResponse = 100;
|
||||
} // namespace
|
||||
|
||||
bool preferences_open(GtkWidget* parent) {
|
||||
FontSettings s = preferences_current();
|
||||
GtkWidget* d = gtk_dialog_new_with_buttons(
|
||||
"Preferences", GTK_WINDOW(parent), GTK_DIALOG_MODAL, "_Cancel",
|
||||
GTK_RESPONSE_CANCEL, "_Apply", GTK_RESPONSE_ACCEPT, nullptr);
|
||||
gtk_dialog_add_button(GTK_DIALOG(d), "_Reset to Defaults",
|
||||
kResetResponse);
|
||||
GtkWidget* content = gtk_dialog_get_content_area(GTK_DIALOG(d));
|
||||
GtkWidget* grid = gtk_grid_new();
|
||||
gtk_grid_set_row_spacing(GTK_GRID(grid), 6);
|
||||
gtk_grid_set_column_spacing(GTK_GRID(grid), 8);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(grid), 10);
|
||||
gtk_container_add(GTK_CONTAINER(content), grid);
|
||||
|
||||
GtkWidget* ui_btn = gtk_font_button_new_with_font(s.font.c_str());
|
||||
gtk_font_button_set_use_font(GTK_FONT_BUTTON(ui_btn), TRUE);
|
||||
gtk_widget_set_hexpand(ui_btn, TRUE);
|
||||
gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Interface font:"), 0, 0,
|
||||
1, 1);
|
||||
gtk_grid_attach(GTK_GRID(grid), ui_btn, 1, 0, 1, 1);
|
||||
|
||||
GtkWidget* code_btn =
|
||||
gtk_font_button_new_with_font(s.code_font.c_str());
|
||||
gtk_font_button_set_use_font(GTK_FONT_BUTTON(code_btn), TRUE);
|
||||
gtk_widget_set_hexpand(code_btn, TRUE);
|
||||
gtk_grid_attach(GTK_GRID(grid),
|
||||
gtk_label_new("Code / text-view font:"), 0, 1, 1, 1);
|
||||
gtk_grid_attach(GTK_GRID(grid), code_btn, 1, 1, 1, 1);
|
||||
|
||||
std::string note_text =
|
||||
"Fonts apply immediately to the designer interface and to\n"
|
||||
"code / text views, and are saved to " +
|
||||
FontSettings::default_path() + ".";
|
||||
GtkWidget* note = gtk_label_new(note_text.c_str());
|
||||
gtk_label_set_xalign(GTK_LABEL(note), 0.0);
|
||||
gtk_grid_attach(GTK_GRID(grid), note, 0, 2, 2, 1);
|
||||
|
||||
gtk_widget_show_all(d);
|
||||
int resp;
|
||||
while ((resp = gtk_dialog_run(GTK_DIALOG(d))) == kResetResponse) {
|
||||
gtk_font_chooser_set_font(GTK_FONT_CHOOSER(ui_btn), "Sans 10");
|
||||
gtk_font_chooser_set_font(GTK_FONT_CHOOSER(code_btn),
|
||||
"Monospace 11");
|
||||
}
|
||||
if (resp == GTK_RESPONSE_ACCEPT) {
|
||||
gchar* ui_font = gtk_font_chooser_get_font(GTK_FONT_CHOOSER(ui_btn));
|
||||
gchar* code_font =
|
||||
gtk_font_chooser_get_font(GTK_FONT_CHOOSER(code_btn));
|
||||
s.font = FontSettings::sanitized(ui_font ? ui_font : "",
|
||||
s.font);
|
||||
s.code_font = FontSettings::sanitized(code_font ? code_font : "",
|
||||
s.code_font);
|
||||
g_free(ui_font);
|
||||
g_free(code_font);
|
||||
s.save();
|
||||
g_current = s;
|
||||
g_current_loaded = true;
|
||||
preferences_apply(s);
|
||||
gtk_widget_destroy(d);
|
||||
return true;
|
||||
}
|
||||
gtk_widget_destroy(d);
|
||||
return false;
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
// FDesigner global font settings — Edit -> Preferences...
|
||||
//
|
||||
// One interface font and one code/text-view font, chosen with GtkFontButton
|
||||
// widgets. Persisted in ~/.config/fdesigner/settings.conf (key=value, the
|
||||
// same pattern as the debugger's debugger.conf); FDESIGNER_SETTINGS_CONF
|
||||
// overrides the path (used by tests).
|
||||
//
|
||||
// Application is live and visible: the interface font is installed as a
|
||||
// screen-wide CSS provider ("* { font-family...; font-size... }") and the
|
||||
// code font as a "textview" CSS rule, so Text/Memo views (and any other
|
||||
// GtkTextView) pick it up, as does the rest of the designer UI. Sizes are
|
||||
// clamped to 6-48 pt; an empty or unparseable description falls back to
|
||||
// the default instead of breaking the UI.
|
||||
#pragma once
|
||||
|
||||
#include <gtk/gtk.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
struct FontSettings {
|
||||
std::string font = "Sans 10"; // interface font (Pango description)
|
||||
std::string code_font = "Monospace 11"; // code / text-view font
|
||||
|
||||
static std::string default_path(); // ~/.config/fdesigner/settings.conf
|
||||
bool save(const std::string& path = "") const;
|
||||
bool load(const std::string& path = "");
|
||||
|
||||
// CSS snippets that apply each font (used by preferences_apply()).
|
||||
std::string ui_css() const; // "* { font-family...; font-size... }"
|
||||
std::string code_css() const; // "textview { font-family...; ... }"
|
||||
|
||||
// Helpers, exposed for tests.
|
||||
// Parse desc as a Pango font description; fall back to `fallback`
|
||||
// when it is empty/unparseable, and clamp the size to 6-48 pt.
|
||||
static std::string sanitized(const std::string& desc,
|
||||
const std::string& fallback);
|
||||
static std::string family_of(const std::string& desc); // "" if none
|
||||
static int size_of(const std::string& desc); // pt, 0 if none
|
||||
};
|
||||
|
||||
// Settings currently in effect (loaded from disk on first call).
|
||||
FontSettings preferences_current();
|
||||
// Install the fonts as screen-wide CSS providers (re-appliable).
|
||||
void preferences_apply(const FontSettings& s);
|
||||
// Apply the code font to one text view (e.g. a code display).
|
||||
void preferences_apply_to_text_view(GtkWidget* view, const FontSettings& s);
|
||||
// Pango description of the font a widget is currently showing
|
||||
// ("" if it cannot be determined). Test helper.
|
||||
std::string preferences_applied_font(GtkWidget* widget);
|
||||
// Open the Preferences dialog; on Accept saves the choice, applies it
|
||||
// live, and returns true. On Cancel returns false.
|
||||
bool preferences_open(GtkWidget* parent);
|
||||
@@ -1,368 +0,0 @@
|
||||
// FDesigner project files (.fdj) — see project_io.h.
|
||||
|
||||
#include "project_io.h"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
// ---------------------------------------------------------------- writing
|
||||
|
||||
static std::string json_escape(const std::string& s) {
|
||||
std::string out;
|
||||
for (unsigned char c : s) {
|
||||
switch (c) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
char buf[8];
|
||||
std::snprintf(buf, sizeof buf, "\\u%04x", c);
|
||||
out += buf;
|
||||
} else {
|
||||
out += (char)c;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool save_project_file(const std::string& path, const Project& p,
|
||||
std::string& err) {
|
||||
std::ostringstream o;
|
||||
o << "{\n"
|
||||
<< " \"format\": \"fdesigner\",\n"
|
||||
<< " \"version\": 1,\n"
|
||||
<< " \"window\": {\n"
|
||||
<< " \"title\": \"" << json_escape(p.title) << "\",\n"
|
||||
<< " \"class_name\": \"" << json_escape(p.class_name) << "\",\n"
|
||||
<< " \"width\": " << p.win_width << ",\n"
|
||||
<< " \"height\": " << p.win_height << ",\n"
|
||||
<< " \"background\": \"" << json_escape(p.background) << "\",\n"
|
||||
<< " \"menubar\": \"" << json_escape(p.menubar) << "\"\n"
|
||||
<< " },\n"
|
||||
<< " \"widgets\": [";
|
||||
for (size_t i = 0; i < p.widgets.size(); ++i) {
|
||||
const Widget& w = p.widgets[i];
|
||||
o << (i ? ",\n" : "\n") << " {\n"
|
||||
<< " \"name\": \"" << json_escape(w.name) << "\",\n"
|
||||
<< " \"type\": \"" << json_escape(w.type) << "\",\n"
|
||||
<< " \"x\": " << w.x << ", \"y\": " << w.y
|
||||
<< ", \"width\": " << w.width << ", \"height\": " << w.height
|
||||
<< ",\n"
|
||||
<< " \"props\": {";
|
||||
bool first = true;
|
||||
for (const auto& [k, v] : w.props) {
|
||||
o << (first ? "" : ",") << "\n \"" << json_escape(k)
|
||||
<< "\": \"" << json_escape(v) << "\"";
|
||||
first = false;
|
||||
}
|
||||
o << (w.props.empty() ? "" : "\n ") << "},\n"
|
||||
<< " \"signals\": [";
|
||||
for (size_t j = 0; j < w.signals.size(); ++j)
|
||||
o << (j ? ", " : "") << "\"" << json_escape(w.signals[j])
|
||||
<< "\"";
|
||||
o << "]\n"
|
||||
<< " }";
|
||||
}
|
||||
o << (p.widgets.empty() ? "" : "\n ") << "]\n}\n";
|
||||
|
||||
std::ofstream f(path);
|
||||
if (!f) {
|
||||
err = "cannot open " + path + " for writing";
|
||||
return false;
|
||||
}
|
||||
f << o.str();
|
||||
if (!f) {
|
||||
err = "write failed for " + path;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- reading
|
||||
|
||||
struct Json {
|
||||
enum Type { Null, Bool, Num, Str, Arr, Obj } type = Null;
|
||||
bool boolean = false;
|
||||
double num = 0;
|
||||
std::string str;
|
||||
std::vector<Json> arr;
|
||||
std::map<std::string, Json> obj;
|
||||
const Json* find(const std::string& key) const {
|
||||
if (type != Obj) return nullptr;
|
||||
auto it = obj.find(key);
|
||||
return it == obj.end() ? nullptr : &it->second;
|
||||
}
|
||||
};
|
||||
|
||||
struct Parser {
|
||||
const char* p;
|
||||
std::string err;
|
||||
|
||||
void ws() {
|
||||
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') ++p;
|
||||
}
|
||||
bool consume(char c) {
|
||||
ws();
|
||||
if (*p == c) {
|
||||
++p;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
static void utf8_encode(std::string& out, unsigned cp) {
|
||||
if (cp < 0x80) {
|
||||
out += (char)cp;
|
||||
} else if (cp < 0x800) {
|
||||
out += (char)(0xC0 | (cp >> 6));
|
||||
out += (char)(0x80 | (cp & 0x3F));
|
||||
} else if (cp < 0x10000) {
|
||||
out += (char)(0xE0 | (cp >> 12));
|
||||
out += (char)(0x80 | ((cp >> 6) & 0x3F));
|
||||
out += (char)(0x80 | (cp & 0x3F));
|
||||
} else {
|
||||
out += (char)(0xF0 | (cp >> 18));
|
||||
out += (char)(0x80 | ((cp >> 12) & 0x3F));
|
||||
out += (char)(0x80 | ((cp >> 6) & 0x3F));
|
||||
out += (char)(0x80 | (cp & 0x3F));
|
||||
}
|
||||
}
|
||||
bool parse_string(std::string& out) {
|
||||
if (*p != '"') {
|
||||
err = "expected string";
|
||||
return false;
|
||||
}
|
||||
++p;
|
||||
while (*p && *p != '"') {
|
||||
unsigned char c = (unsigned char)*p;
|
||||
if (c == '\\') {
|
||||
++p;
|
||||
switch (*p) {
|
||||
case 'n': out += '\n'; break;
|
||||
case 't': out += '\t'; break;
|
||||
case 'r': out += '\r'; break;
|
||||
case 'b': out += '\b'; break;
|
||||
case 'f': out += '\f'; break;
|
||||
case '/': out += '/'; break;
|
||||
case '\\': out += '\\'; break;
|
||||
case '"': out += '"'; break;
|
||||
case 'u': {
|
||||
unsigned cp = 0;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
++p;
|
||||
if (!std::isxdigit((unsigned char)*p)) {
|
||||
err = "bad \\u escape";
|
||||
return false;
|
||||
}
|
||||
cp = cp * 16 +
|
||||
(unsigned)(std::isdigit((unsigned char)*p)
|
||||
? *p - '0'
|
||||
: (std::tolower(
|
||||
(unsigned char)*p) -
|
||||
'a' + 10));
|
||||
}
|
||||
// Surrogate pair?
|
||||
if (cp >= 0xD800 && cp <= 0xDBFF && p[1] == '\\' &&
|
||||
p[2] == 'u') {
|
||||
unsigned lo = 0;
|
||||
bool okpair = true;
|
||||
const char* save = p;
|
||||
p += 2;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
++p;
|
||||
if (!std::isxdigit((unsigned char)*p)) {
|
||||
okpair = false;
|
||||
break;
|
||||
}
|
||||
lo = lo * 16 +
|
||||
(unsigned)(std::isdigit(
|
||||
(unsigned char)*p)
|
||||
? *p - '0'
|
||||
: (std::tolower(
|
||||
(unsigned char)*p) -
|
||||
'a' + 10));
|
||||
}
|
||||
if (okpair && lo >= 0xDC00 && lo <= 0xDFFF)
|
||||
cp = 0x10000 + ((cp - 0xD800) << 10) +
|
||||
(lo - 0xDC00);
|
||||
else
|
||||
p = save;
|
||||
}
|
||||
utf8_encode(out, cp);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
err = "bad escape";
|
||||
return false;
|
||||
}
|
||||
++p;
|
||||
} else {
|
||||
out += (char)c;
|
||||
++p;
|
||||
}
|
||||
}
|
||||
if (*p != '"') {
|
||||
err = "unterminated string";
|
||||
return false;
|
||||
}
|
||||
++p;
|
||||
return true;
|
||||
}
|
||||
bool parse_value(Json& v) {
|
||||
ws();
|
||||
if (*p == '{') {
|
||||
++p;
|
||||
v.type = Json::Obj;
|
||||
if (consume('}')) return true;
|
||||
while (true) {
|
||||
ws();
|
||||
std::string key;
|
||||
if (!parse_string(key)) return false;
|
||||
if (!consume(':')) {
|
||||
err = "expected ':'";
|
||||
return false;
|
||||
}
|
||||
Json child;
|
||||
if (!parse_value(child)) return false;
|
||||
v.obj[key] = child;
|
||||
if (consume(',')) continue;
|
||||
if (consume('}')) return true;
|
||||
err = "expected ',' or '}'";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (*p == '[') {
|
||||
++p;
|
||||
v.type = Json::Arr;
|
||||
if (consume(']')) return true;
|
||||
while (true) {
|
||||
Json child;
|
||||
if (!parse_value(child)) return false;
|
||||
v.arr.push_back(child);
|
||||
if (consume(',')) continue;
|
||||
if (consume(']')) return true;
|
||||
err = "expected ',' or ']'";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (*p == '"') {
|
||||
v.type = Json::Str;
|
||||
return parse_string(v.str);
|
||||
}
|
||||
if (std::strncmp(p, "true", 4) == 0) {
|
||||
p += 4;
|
||||
v.type = Json::Bool;
|
||||
v.boolean = true;
|
||||
return true;
|
||||
}
|
||||
if (std::strncmp(p, "false", 5) == 0) {
|
||||
p += 5;
|
||||
v.type = Json::Bool;
|
||||
v.boolean = false;
|
||||
return true;
|
||||
}
|
||||
if (std::strncmp(p, "null", 4) == 0) {
|
||||
p += 4;
|
||||
v.type = Json::Null;
|
||||
return true;
|
||||
}
|
||||
char* end = nullptr;
|
||||
v.num = std::strtod(p, &end);
|
||||
if (end == p) {
|
||||
err = "unexpected character";
|
||||
return false;
|
||||
}
|
||||
p = end;
|
||||
v.type = Json::Num;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
static std::string jstr(const Json* j, const std::string& dflt) {
|
||||
return j && j->type == Json::Str ? j->str : dflt;
|
||||
}
|
||||
static int jint(const Json* j, int dflt) {
|
||||
return j && j->type == Json::Num ? (int)j->num : dflt;
|
||||
}
|
||||
|
||||
bool load_project_file(const std::string& path, Project& out,
|
||||
std::string& err) {
|
||||
std::ifstream f(path);
|
||||
if (!f) {
|
||||
err = "cannot open " + path;
|
||||
return false;
|
||||
}
|
||||
std::stringstream ss;
|
||||
ss << f.rdbuf();
|
||||
std::string text = ss.str();
|
||||
|
||||
Parser parser{text.c_str(), ""};
|
||||
Json root;
|
||||
if (!parser.parse_value(root)) {
|
||||
err = "invalid JSON in " + path + ": " + parser.err;
|
||||
return false;
|
||||
}
|
||||
parser.ws();
|
||||
if (*parser.p) {
|
||||
err = "trailing data after JSON in " + path;
|
||||
return false;
|
||||
}
|
||||
if (jstr(root.find("format"), "") != "fdesigner") {
|
||||
err = path + " is not an fdesigner project file";
|
||||
return false;
|
||||
}
|
||||
if (jint(root.find("version"), 0) != 1) {
|
||||
err = path + " has an unsupported format version";
|
||||
return false;
|
||||
}
|
||||
|
||||
Project p;
|
||||
if (const Json* win = root.find("window")) {
|
||||
p.title = jstr(win->find("title"), p.title);
|
||||
p.class_name = jstr(win->find("class_name"), p.class_name);
|
||||
p.win_width = jint(win->find("width"), p.win_width);
|
||||
p.win_height = jint(win->find("height"), p.win_height);
|
||||
p.background = jstr(win->find("background"), "");
|
||||
p.menubar = jstr(win->find("menubar"), "");
|
||||
}
|
||||
if (p.win_width < 50 || p.win_width > 20000) p.win_width = 800;
|
||||
if (p.win_height < 50 || p.win_height > 20000) p.win_height = 600;
|
||||
|
||||
if (const Json* widgets = root.find("widgets");
|
||||
widgets && widgets->type == Json::Arr) {
|
||||
for (const Json& jw : widgets->arr) {
|
||||
Widget w;
|
||||
w.name = jstr(jw.find("name"), "");
|
||||
w.type = jstr(jw.find("type"), "");
|
||||
if (w.name.empty() || w.type.empty()) continue;
|
||||
w.x = jint(jw.find("x"), 0);
|
||||
w.y = jint(jw.find("y"), 0);
|
||||
w.width = jint(jw.find("width"), 100);
|
||||
w.height = jint(jw.find("height"), 30);
|
||||
if (w.width < 10) w.width = 10;
|
||||
if (w.height < 10) w.height = 10;
|
||||
if (const Json* props = jw.find("props");
|
||||
props && props->type == Json::Obj) {
|
||||
for (const auto& [k, v] : props->obj)
|
||||
if (v.type == Json::Str) w.props[k] = v.str;
|
||||
}
|
||||
if (const Json* sigs = jw.find("signals");
|
||||
sigs && sigs->type == Json::Arr) {
|
||||
for (const Json& s : sigs->arr)
|
||||
if (s.type == Json::Str) w.signals.push_back(s.str);
|
||||
}
|
||||
p.widgets.push_back(w);
|
||||
}
|
||||
}
|
||||
out = p;
|
||||
return true;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
// FDesigner project files (.fdj) — JSON save/load, replacing the Python
|
||||
// original's pickle files. Hand-rolled JSON (the model is small; no new
|
||||
// dependencies). Format version 1:
|
||||
//
|
||||
// { "format": "fdesigner", "version": 1,
|
||||
// "window": { "title", "class_name", "width", "height", "background" },
|
||||
// "widgets": [ { "name", "type", "x", "y", "width", "height",
|
||||
// "props": { name: value, ... } } ] }
|
||||
//
|
||||
// Loading is tolerant of unknown keys and missing fields, but strict about
|
||||
// the format tag. Property values are NOT validated here — the designer
|
||||
// re-validates every property through set_prop() when it rebuilds the
|
||||
// canvas, so a hand-edited file can't smuggle in bad values.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "model.h"
|
||||
|
||||
bool save_project_file(const std::string& path, const Project& project,
|
||||
std::string& err);
|
||||
bool load_project_file(const std::string& path, Project& project_out,
|
||||
std::string& err);
|
||||
@@ -1,277 +0,0 @@
|
||||
// FDesigner property tables — the GTK counterpart of the original's
|
||||
// per-widget parameter mapping (the Entry_001..019 tables in fdesigner7.py).
|
||||
// Each palette type lists the properties the designer can edit; values are
|
||||
// stored in Widget.props as canonical strings and applied live with
|
||||
// g_object_set (or, for the two pseudo-properties background/foreground,
|
||||
// through a per-widget CSS provider — GTK's equivalent of Tk's bg/fg config).
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
enum class PropKind { Str, Bool, Int, Double, Color, Enum };
|
||||
|
||||
struct PropDef {
|
||||
const char* name; // GTK property name, or background/foreground
|
||||
PropKind kind;
|
||||
const char* def; // default value (canonical string), "" = none
|
||||
double lo = 0, hi = 0; // spin range for Int/Double
|
||||
const char* enum_labels = nullptr; // Enum: "Label A|Label B|..."
|
||||
const int* enum_values = nullptr; // Enum: value per label
|
||||
};
|
||||
|
||||
// Enum value tables (GTK 3 constants, written out so this header stays
|
||||
// independent of the GTK headers).
|
||||
inline const int kReliefValues[] = {0, 1, 2}; // NORMAL, HALF, NONE
|
||||
inline const int kShadowValues[] = {0, 1, 2, 3, 4}; // NONE, IN, OUT, ETCHED_IN, ETCHED_OUT
|
||||
inline const int kSelModeValues[] = {0, 1, 2, 3}; // NONE, SINGLE, BROWSE, MULTIPLE
|
||||
inline const int kArrowValues[] = {0, 1, 2, 3, 4}; // UP, DOWN, LEFT, RIGHT, NONE
|
||||
inline const int kWrapValues[] = {0, 1, 2, 3}; // NONE, CHAR, WORD, WORD_CHAR
|
||||
inline const int kScaleModeValues[] = {0, 1}; // PRICE, PERCENT
|
||||
inline const int kOrientationValues[] = {0, 1}; // HORIZONTAL, VERTICAL
|
||||
inline const int kToolbarStyleValues[] = {0, 1, 2, 3}; // ICONS, TEXT, BOTH, BOTH_HORIZ
|
||||
inline const int kShapeValues[] = {0, 1, 2, 3}; // RECTANGLE, ELLIPSE, LINE, TRIANGLE
|
||||
|
||||
// Properties every widget gets (the original configures bg/fg on nearly
|
||||
// every widget type).
|
||||
inline const std::vector<PropDef>& common_props() {
|
||||
static const std::vector<PropDef> v = {
|
||||
{"background", PropKind::Color, ""},
|
||||
{"foreground", PropKind::Color, ""},
|
||||
{"tooltip-text", PropKind::Str, ""},
|
||||
};
|
||||
return v;
|
||||
}
|
||||
|
||||
inline const std::vector<PropDef>& props_for(const std::string& type) {
|
||||
using K = PropKind;
|
||||
static const std::vector<PropDef> none;
|
||||
static const std::vector<PropDef> button = {
|
||||
{"label", K::Str, ""},
|
||||
{"relief", K::Enum, "0", 0, 0, "Normal|Half|None", kReliefValues},
|
||||
{"focus-on-click", K::Bool, "true"},
|
||||
};
|
||||
static const std::vector<PropDef> label = {
|
||||
{"label", K::Str, ""},
|
||||
{"xalign", K::Double, "0.5", 0.0, 1.0},
|
||||
{"selectable", K::Bool, "false"},
|
||||
{"wrap", K::Bool, "false"},
|
||||
};
|
||||
static const std::vector<PropDef> entry = {
|
||||
{"text", K::Str, ""},
|
||||
{"placeholder-text", K::Str, ""},
|
||||
{"max-length", K::Int, "0", 0, 100000},
|
||||
{"width-chars", K::Int, "-1", -1, 1000},
|
||||
{"editable", K::Bool, "true"},
|
||||
{"visibility", K::Bool, "true"},
|
||||
};
|
||||
static const std::vector<PropDef> checkbutton = {
|
||||
{"label", K::Str, ""},
|
||||
{"active", K::Bool, "false"},
|
||||
{"inconsistent", K::Bool, "false"},
|
||||
};
|
||||
static const std::vector<PropDef> radiobutton = {
|
||||
{"label", K::Str, ""},
|
||||
{"active", K::Bool, "false"},
|
||||
};
|
||||
static const std::vector<PropDef> frame = {
|
||||
{"label", K::Str, ""},
|
||||
{"shadow-type", K::Enum, "3", 0, 0, "None|In|Out|Etched in|Etched out",
|
||||
kShadowValues},
|
||||
};
|
||||
static const std::vector<PropDef> combobox = {
|
||||
{"active", K::Int, "0", -1, 1000},
|
||||
};
|
||||
static const std::vector<PropDef> listbox = {
|
||||
{"selection-mode", K::Enum, "1", 0, 0, "None|Single|Browse|Multiple",
|
||||
kSelModeValues},
|
||||
};
|
||||
static const std::vector<PropDef> menubutton = {
|
||||
{"label", K::Str, ""},
|
||||
{"direction", K::Enum, "1", 0, 0, "Up|Down|Left|Right|None",
|
||||
kArrowValues},
|
||||
};
|
||||
static const std::vector<PropDef> scale = {
|
||||
{"value", K::Double, "0", 0, 100},
|
||||
{"digits", K::Int, "1", -1, 10},
|
||||
{"draw-value", K::Bool, "true"},
|
||||
{"inverted", K::Bool, "false"},
|
||||
};
|
||||
static const std::vector<PropDef> scrollbar = {
|
||||
{"value", K::Double, "0", 0, 100},
|
||||
{"inverted", K::Bool, "false"},
|
||||
};
|
||||
static const std::vector<PropDef> text = {
|
||||
{"editable", K::Bool, "true"},
|
||||
{"cursor-visible", K::Bool, "true"},
|
||||
{"wrap-mode", K::Enum, "0", 0, 0, "None|Char|Word|Word-char",
|
||||
kWrapValues},
|
||||
};
|
||||
static const std::vector<PropDef> memo = {
|
||||
{"text", K::Str, ""},
|
||||
{"editable", K::Bool, "true"},
|
||||
{"wrap-mode", K::Enum, "0", 0, 0, "None|Char|Word|Word-char",
|
||||
kWrapValues},
|
||||
};
|
||||
static const std::vector<PropDef> groupbox = {
|
||||
{"label", K::Str, ""},
|
||||
{"shadow-type", K::Enum, "3", 0, 0, "None|In|Out|Etched in|Etched out",
|
||||
kShadowValues},
|
||||
};
|
||||
static const std::vector<PropDef> panel = {
|
||||
{"label", K::Str, ""},
|
||||
{"shadow-type", K::Enum, "3", 0, 0, "None|In|Out|Etched in|Etched out",
|
||||
kShadowValues},
|
||||
};
|
||||
static const std::vector<PropDef> image = {
|
||||
{"file", K::Str, ""},
|
||||
{"pixel-size", K::Int, "-1", -1, 512},
|
||||
};
|
||||
static const std::vector<PropDef> shape = {
|
||||
{"shape", K::Enum, "0", 0, 0, "Rectangle|Ellipse|Line|Triangle",
|
||||
kShapeValues},
|
||||
{"fill-color", K::Color, "rgb(53,132,228)"},
|
||||
};
|
||||
static const std::vector<PropDef> notebook = {
|
||||
{"pages", K::Str, "Tab 1|Tab 2|Tab 3"},
|
||||
{"page", K::Int, "0", 0, 100},
|
||||
};
|
||||
static const std::vector<PropDef> scrollbox = {
|
||||
{"label", K::Str, ""},
|
||||
};
|
||||
static const std::vector<PropDef> splitter = {
|
||||
{"position", K::Int, "100", 0, 10000},
|
||||
{"orientation", K::Enum, "0", 0, 0, "Horizontal|Vertical",
|
||||
kOrientationValues},
|
||||
};
|
||||
static const std::vector<PropDef> statusbar = {
|
||||
{"text", K::Str, ""},
|
||||
};
|
||||
static const std::vector<PropDef> toolbar = {
|
||||
{"items", K::Str, "New|Open|Save"},
|
||||
{"toolbar-style", K::Enum, "2", 0, 0, "Icons|Text|Both|Both horizontal",
|
||||
kToolbarStyleValues},
|
||||
};
|
||||
static const std::vector<PropDef> menubar = {
|
||||
{"menus", K::Str, "File|Edit|Help"},
|
||||
};
|
||||
static const std::vector<PropDef> spinedit = {
|
||||
{"minimum", K::Int, "0", -1000000, 1000000},
|
||||
{"maximum", K::Int, "100", -1000000, 1000000},
|
||||
{"step", K::Int, "1", 1, 1000},
|
||||
{"value", K::Double, "0", -1000000, 1000000},
|
||||
{"digits", K::Int, "0", 0, 10},
|
||||
{"numeric", K::Bool, "true"},
|
||||
{"wrap", K::Bool, "false"},
|
||||
};
|
||||
static const std::vector<PropDef> trackbar = {
|
||||
{"minimum", K::Int, "0", -1000000, 1000000},
|
||||
{"maximum", K::Int, "100", -1000000, 1000000},
|
||||
{"step", K::Int, "1", 1, 1000},
|
||||
{"value", K::Double, "0", 0, 100},
|
||||
{"digits", K::Int, "1", 0, 10},
|
||||
{"draw-value", K::Bool, "true"},
|
||||
{"inverted", K::Bool, "false"},
|
||||
{"orientation", K::Enum, "0", 0, 0, "Horizontal|Vertical",
|
||||
kOrientationValues},
|
||||
};
|
||||
static const std::vector<PropDef> progressbar = {
|
||||
{"fraction", K::Double, "0", 0, 1},
|
||||
{"show-text", K::Bool, "false"},
|
||||
{"text", K::Str, ""},
|
||||
};
|
||||
static const std::vector<PropDef> datetimepicker = {
|
||||
{"date", K::Str, ""},
|
||||
{"show-heading", K::Bool, "true"},
|
||||
{"show-day-names", K::Bool, "true"},
|
||||
};
|
||||
static const std::vector<PropDef> colorbox = {
|
||||
{"color", K::Color, "rgb(53,132,228)"},
|
||||
{"use-alpha", K::Bool, "false"},
|
||||
{"title", K::Str, ""},
|
||||
};
|
||||
static const std::vector<PropDef> listview = {
|
||||
{"columns", K::Str, "Name|Value"},
|
||||
{"items", K::Str, "Row 1,Value 1;Row 2,Value 2"},
|
||||
{"headers-visible", K::Bool, "true"},
|
||||
};
|
||||
static const std::vector<PropDef> treeview = {
|
||||
{"items", K::Str, "Root/Child 1;Root/Child 2;Other"},
|
||||
{"headers-visible", K::Bool, "true"},
|
||||
};
|
||||
static const std::vector<PropDef> stringgrid = {
|
||||
{"rows", K::Int, "5", 1, 50},
|
||||
{"columns", K::Int, "4", 1, 26},
|
||||
{"headers-visible", K::Bool, "true"},
|
||||
};
|
||||
static const std::vector<PropDef> plot = {
|
||||
{"title", K::Str, ""},
|
||||
{"line-color", K::Color, "rgb(220,0,0)"},
|
||||
};
|
||||
if (type == "Button") return button;
|
||||
if (type == "Label") return label;
|
||||
if (type == "Entry") return entry;
|
||||
if (type == "Checkbutton") return checkbutton;
|
||||
if (type == "Radiobutton") return radiobutton;
|
||||
if (type == "Frame") return frame;
|
||||
if (type == "Combobox") return combobox;
|
||||
if (type == "Listbox") return listbox;
|
||||
if (type == "Menubutton") return menubutton;
|
||||
if (type == "Scale") return scale;
|
||||
if (type == "Scrollbar") return scrollbar;
|
||||
if (type == "Text") return text;
|
||||
if (type == "Memo") return memo;
|
||||
if (type == "GroupBox") return groupbox;
|
||||
if (type == "Panel") return panel;
|
||||
if (type == "Image") return image;
|
||||
if (type == "Shape") return shape;
|
||||
if (type == "Notebook") return notebook;
|
||||
if (type == "ScrollBox") return scrollbox;
|
||||
if (type == "Splitter") return splitter;
|
||||
if (type == "StatusBar") return statusbar;
|
||||
if (type == "ToolBar") return toolbar;
|
||||
if (type == "MenuBar") return menubar;
|
||||
if (type == "SpinEdit") return spinedit;
|
||||
if (type == "TrackBar") return trackbar;
|
||||
if (type == "ProgressBar") return progressbar;
|
||||
if (type == "DateTimePicker") return datetimepicker;
|
||||
if (type == "ColorBox") return colorbox;
|
||||
if (type == "ListView") return listview;
|
||||
if (type == "TreeView") return treeview;
|
||||
if (type == "StringGrid") return stringgrid;
|
||||
if (type == "Plot") return plot;
|
||||
static const std::vector<PropDef> toplevel = {
|
||||
{"title", K::Str, ""},
|
||||
{"resizable", K::Bool, "true"},
|
||||
};
|
||||
static const std::vector<PropDef> spreadsheet = {
|
||||
{"rows", K::Int, "5", 1, 50},
|
||||
{"columns", K::Int, "4", 1, 26},
|
||||
};
|
||||
if (type == "Toplevel") return toplevel;
|
||||
if (type == "Spreadsheet") return spreadsheet;
|
||||
static const std::vector<PropDef> stockchart = {
|
||||
{"data-file", K::Str, ""},
|
||||
{"up-color", K::Color, "rgb(0,200,0)"},
|
||||
{"down-color", K::Color, "rgb(220,0,0)"},
|
||||
{"max-candles", K::Int, "120", 1, 5000},
|
||||
{"indicators", K::Str, ""},
|
||||
{"scale-mode", K::Enum, "0", 0, 0, "Price|Percent",
|
||||
kScaleModeValues},
|
||||
{"compare-files", K::Str, ""},
|
||||
{"drawings", K::Str, ""},
|
||||
};
|
||||
if (type == "StockChart") return stockchart;
|
||||
return none; // Canvas: common props only
|
||||
}
|
||||
|
||||
// Find a property definition for a widget type (type table, then common).
|
||||
inline const PropDef* find_prop(const std::string& type,
|
||||
const std::string& name) {
|
||||
for (const PropDef& d : props_for(type))
|
||||
if (name == d.name) return &d;
|
||||
for (const PropDef& d : common_props())
|
||||
if (name == d.name) return &d;
|
||||
return nullptr;
|
||||
}
|
||||
@@ -1,509 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
// 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);
|
||||
@@ -1,50 +0,0 @@
|
||||
// Renders the generated StockChart class offscreen and verifies that
|
||||
// up-coloured and down-coloured candle pixels actually appear — i.e. the
|
||||
// widget doesn't just compile, it PLOTS.
|
||||
#include <gtk/gtk.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#include "StockChart_001.h"
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
gtk_init(&argc, &argv);
|
||||
GtkWidget* win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
|
||||
GtkWidget* fixed = gtk_fixed_new();
|
||||
gtk_container_add(GTK_CONTAINER(win), fixed);
|
||||
gtk_window_set_default_size(GTK_WINDOW(win), 900, 700);
|
||||
StockChart_001 chart(fixed);
|
||||
if (chart.candle_count() == 0) {
|
||||
std::printf("NO DATA LOADED\n");
|
||||
return 1;
|
||||
}
|
||||
gtk_widget_show_all(win);
|
||||
for (int i = 0; i < 20; ++i)
|
||||
while (gtk_events_pending()) gtk_main_iteration();
|
||||
GtkWidget* w = chart.widget();
|
||||
int width = gtk_widget_get_allocated_width(w);
|
||||
int height = gtk_widget_get_allocated_height(w);
|
||||
if (width < 50 || height < 50) {
|
||||
std::printf("BAD SIZE %dx%d\n", width, height);
|
||||
return 1;
|
||||
}
|
||||
cairo_surface_t* surf =
|
||||
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
|
||||
cairo_t* cr = cairo_create(surf);
|
||||
gtk_widget_draw(w, cr);
|
||||
cairo_destroy(cr);
|
||||
cairo_surface_flush(surf);
|
||||
unsigned char* px = cairo_image_surface_get_data(surf);
|
||||
int stride = cairo_image_surface_get_stride(surf);
|
||||
long green = 0, red = 0;
|
||||
for (int y = 0; y < height; ++y)
|
||||
for (int x = 0; x < width; ++x) {
|
||||
unsigned char* p = px + y * stride + x * 4; // BGRA
|
||||
int b = p[0], g = p[1], r = p[2];
|
||||
if (g > 150 && r < 110 && b < 110) ++green;
|
||||
if (r > 170 && g < 110 && b < 110) ++red;
|
||||
}
|
||||
std::printf("candles=%d size=%dx%d GREEN %ld RED %ld\n",
|
||||
chart.candle_count(), width, height, green, red);
|
||||
return (green > 200 && red > 200) ? 0 : 1;
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
// Renders the generated StockChart Pro (matrix case 16: percent scale,
|
||||
// QQQ comparison, seven annotations, SMA + RSI) offscreen and verifies
|
||||
// every feature actually draws — then exercises wheel-zoom math via
|
||||
// zoom_at() and re-renders at a smaller size to prove the annotations
|
||||
// survive resizes.
|
||||
#include <gtk/gtk.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
#include "StockChart_001.h"
|
||||
|
||||
static void pump() {
|
||||
for (int i = 0; i < 25; ++i)
|
||||
while (gtk_events_pending()) gtk_main_iteration();
|
||||
}
|
||||
|
||||
struct Counts {
|
||||
long green = 0, red = 0, orange = 0, magenta = 0, purple = 0;
|
||||
long axis_text = 0, time_text = 0;
|
||||
};
|
||||
|
||||
static Counts render(StockChart_001& chart, int W, int H) {
|
||||
GtkWidget* w = chart.widget();
|
||||
gtk_widget_queue_draw(w);
|
||||
pump();
|
||||
int width = gtk_widget_get_allocated_width(w);
|
||||
int height = gtk_widget_get_allocated_height(w);
|
||||
cairo_surface_t* surf =
|
||||
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
|
||||
cairo_t* cr = cairo_create(surf);
|
||||
gtk_widget_draw(w, cr);
|
||||
cairo_destroy(cr);
|
||||
cairo_surface_flush(surf);
|
||||
unsigned char* px = cairo_image_surface_get_data(surf);
|
||||
int stride = cairo_image_surface_get_stride(surf);
|
||||
Counts c;
|
||||
(void)W;
|
||||
(void)H;
|
||||
for (int y = 0; y < height; ++y)
|
||||
for (int x = 0; x < width; ++x) {
|
||||
unsigned char* p = px + y * stride + x * 4; // BGRA
|
||||
int b = p[0], g = p[1], r = p[2];
|
||||
if (g > 150 && r < 110 && b < 110) ++c.green;
|
||||
if (r > 170 && g < 110 && b < 110) ++c.red;
|
||||
if (r > 200 && g > 80 && g < 170 && b < 90) ++c.orange;
|
||||
if (r > 180 && g > 30 && g < 95 && b > 130 && b < 210)
|
||||
++c.magenta;
|
||||
if (r > 105 && r < 175 && g > 25 && g < 85 && b > 165)
|
||||
++c.purple;
|
||||
// Axis labels are anti-aliased 0.35-grey text on white:
|
||||
// count unsaturated mid-grey pixels (gridlines at 0.08
|
||||
// alpha land ~235 and stay excluded).
|
||||
bool grey_text = r > 50 && r < 205 && std::abs(r - g) < 15 &&
|
||||
std::abs(g - b) < 15;
|
||||
// In the right strip nothing but label text draws (grid-
|
||||
// lines stop at the plot edge), so a looser bound is safe.
|
||||
bool axis_grey = r > 40 && r < 225 && std::abs(r - g) < 18 &&
|
||||
std::abs(g - b) < 18;
|
||||
if (axis_grey && x >= width - 56 && y < height - 18)
|
||||
++c.axis_text;
|
||||
if (grey_text && y >= height - 18) ++c.time_text;
|
||||
}
|
||||
cairo_surface_destroy(surf);
|
||||
return c;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
gtk_init(&argc, &argv);
|
||||
int fails = 0;
|
||||
auto check = [&](bool cond, const char* what) {
|
||||
std::printf("%s %s\n", cond ? "OK " : "FAIL", what);
|
||||
if (!cond) ++fails;
|
||||
};
|
||||
GtkWidget* win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
|
||||
GtkWidget* fixed = gtk_fixed_new();
|
||||
gtk_container_add(GTK_CONTAINER(win), fixed);
|
||||
gtk_window_set_default_size(GTK_WINDOW(win), 1024, 768);
|
||||
StockChart_001 chart(fixed);
|
||||
check(chart.candle_count() == 1170, "1170 candles loaded");
|
||||
check(chart.compare_count() == 1, "QQQ comparison loaded");
|
||||
check(chart.drawing_count() == 7, "7 annotations from design");
|
||||
check(chart.scale_mode() == 1, "percent scale mode");
|
||||
check(chart.visible_count() == 400, "initial window = max-candles");
|
||||
gtk_widget_show_all(win);
|
||||
pump();
|
||||
|
||||
Counts c = render(chart, 1024, 768);
|
||||
std::printf(" green=%ld red=%ld orange=%ld magenta=%ld "
|
||||
"purple=%ld axis=%ld time=%ld\n",
|
||||
c.green, c.red, c.orange, c.magenta, c.purple,
|
||||
c.axis_text, c.time_text);
|
||||
check(c.green > 200 && c.red > 200, "candles plotted");
|
||||
check(c.orange > 100, "QQQ comparison line plotted");
|
||||
check(c.magenta > 25, "arrow annotation plotted");
|
||||
check(c.purple > 25, "fib annotation plotted");
|
||||
check(c.axis_text > 40, "percent axis labels plotted");
|
||||
check(c.time_text > 60, "time axis labels plotted");
|
||||
|
||||
// Wheel-zoom math (what on_scroll calls): in, back out, clamp.
|
||||
chart.zoom_at(0.5, 0.5);
|
||||
check(chart.visible_count() == 200, "zoom in halves the window");
|
||||
chart.zoom_at(2.0, 0.5);
|
||||
check(chart.visible_count() == 400, "zoom out restores the window");
|
||||
chart.zoom_at(10.0, 0.5);
|
||||
check(chart.visible_count() == 1170, "zoom clamps at the full series");
|
||||
chart.reset_view();
|
||||
check(chart.visible_count() == 400, "reset_view restores max-candles");
|
||||
|
||||
// Resize: shrink the chart widget itself (its frame in the fixed
|
||||
// layout); annotations are data-anchored, so the arrow and fib
|
||||
// must still draw at their remapped positions.
|
||||
gtk_widget_set_size_request(gtk_widget_get_parent(chart.widget()),
|
||||
620, 460);
|
||||
gtk_window_resize(GTK_WINDOW(win), 660, 520);
|
||||
pump();
|
||||
check(gtk_widget_get_allocated_width(chart.widget()) < 700,
|
||||
"chart widget actually resized");
|
||||
Counts s = render(chart, 640, 480);
|
||||
std::printf(" small: magenta=%ld purple=%ld orange=%ld\n",
|
||||
s.magenta, s.purple, s.orange);
|
||||
check(s.magenta > 12, "arrow survives resize");
|
||||
check(s.purple > 12, "fib survives resize");
|
||||
check(s.orange > 50, "comparison survives resize");
|
||||
|
||||
std::printf("CHART PRO TEST %s (%d failures)\n",
|
||||
fails ? "FAIL" : "PASS", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// Captures the generated case-16 application window (MyWindow with
|
||||
// the StockChart Pro) at exactly 1024x768 to a PNG, for a visual
|
||||
// check of the whole feature set working together.
|
||||
#include <gtk/gtk.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#include "MyWindow.h"
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const char* out = argc > 1 ? argv[1] : "chart_pro_1024x768.png";
|
||||
gtk_init(&argc, &argv);
|
||||
MyWindow app;
|
||||
app.show();
|
||||
GtkWidget* win = app.window();
|
||||
gtk_window_resize(GTK_WINDOW(win), 1024, 768);
|
||||
// Let layout + first draws settle.
|
||||
for (int i = 0; i < 60; ++i) {
|
||||
while (gtk_events_pending()) gtk_main_iteration();
|
||||
g_usleep(10000);
|
||||
}
|
||||
GdkWindow* gw = gtk_widget_get_window(win);
|
||||
int w = gdk_window_get_width(gw);
|
||||
int h = gdk_window_get_height(gw);
|
||||
GdkPixbuf* pb = gdk_pixbuf_get_from_window(gw, 0, 0, w, h);
|
||||
if (!pb) {
|
||||
std::printf("SCREENSHOT FAIL: no pixbuf\n");
|
||||
return 1;
|
||||
}
|
||||
GError* err = nullptr;
|
||||
if (!gdk_pixbuf_save(pb, out, "png", &err, nullptr)) {
|
||||
std::printf("SCREENSHOT FAIL: %s\n", err ? err->message : "?");
|
||||
return 1;
|
||||
}
|
||||
std::printf("SCREENSHOT OK %s (%dx%d)\n", out, w, h);
|
||||
return (w == 1024 && h == 768) ? 0 : 1;
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
// CMake test probe — drives src/cmake_build.h + src/generator.h headlessly
|
||||
// (no GUI): generates a project, checks the CMakeLists.txt, configures +
|
||||
// builds it with cmake, runs the built GTK app under Xvfb, builds a
|
||||
// hand-written console CMake project and a hand-written GTK one, and
|
||||
// checks settings persistence and failure reporting.
|
||||
// Usage: cmake_probe <workdir> ; exit 0 = all pass. Prints PASS/FAIL lines.
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <sys/wait.h>
|
||||
|
||||
#include "cmake_build.h"
|
||||
#include "generator.h"
|
||||
#include "model.h"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
static int g_pass = 0, g_fail = 0;
|
||||
static void check(bool ok, const char* name) {
|
||||
std::printf("%s %s\n", ok ? "PASS" : "FAIL", name);
|
||||
if (ok) ++g_pass; else ++g_fail;
|
||||
}
|
||||
|
||||
static std::string read_file(const std::string& p) {
|
||||
std::ifstream f(p);
|
||||
if (!f) return "";
|
||||
return std::string(std::istreambuf_iterator<char>(f),
|
||||
std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
static void write_file(const std::string& p, const std::string& c) {
|
||||
std::ofstream f(p);
|
||||
f << c;
|
||||
}
|
||||
|
||||
static int run(const std::string& cmd) {
|
||||
// std::system returns the wait status, not the exit code.
|
||||
int rc = std::system(cmd.c_str());
|
||||
if (rc == -1) return -1;
|
||||
if (WIFEXITED(rc)) return WEXITSTATUS(rc);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
std::string base = argc > 1 ? argv[1] : "/tmp/fdesigner_cmake_tests";
|
||||
std::error_code ec;
|
||||
fs::remove_all(base, ec);
|
||||
fs::create_directories(base, ec);
|
||||
|
||||
// 1. Generate a project (Button + Label + Entry) and inspect its
|
||||
// CMakeLists.txt.
|
||||
Project p;
|
||||
p.class_name = "MyWindow";
|
||||
Widget b;
|
||||
b.name = "Button_001"; b.type = "Button";
|
||||
b.props["label"] = "Click me";
|
||||
Widget l;
|
||||
l.name = "Label_001"; l.type = "Label";
|
||||
l.props["label"] = "Hello";
|
||||
Widget e;
|
||||
e.name = "Entry_001"; e.type = "Entry";
|
||||
p.widgets = {b, l, e};
|
||||
std::string gen_dir = base + "/generated";
|
||||
GenResult r = generate_project(p, p.widgets, gen_dir);
|
||||
check(r.ok, "generate-project");
|
||||
check(r.files.size() == 5 + 2 * p.widgets.size(),
|
||||
"generate-file-count-includes-cmakelists");
|
||||
std::string cm = read_file(gen_dir + "/CMakeLists.txt");
|
||||
check(!cm.empty(), "cmakelists-exists");
|
||||
check(cm.find("cmake_minimum_required(VERSION 3.10)") !=
|
||||
std::string::npos,
|
||||
"cmakelists-minimum-required");
|
||||
check(cm.find("project(MyWindow CXX)") != std::string::npos,
|
||||
"cmakelists-project");
|
||||
check(cm.find("find_package(PkgConfig REQUIRED)") != std::string::npos,
|
||||
"cmakelists-find-pkgconfig");
|
||||
check(cm.find("pkg_check_modules(GTK3 REQUIRED gtk+-3.0)") !=
|
||||
std::string::npos,
|
||||
"cmakelists-pkg-check-gtk3");
|
||||
check(cm.find("add_executable(app") != std::string::npos,
|
||||
"cmakelists-add-executable");
|
||||
check(cm.find("main.cpp") != std::string::npos &&
|
||||
cm.find("MyWindow.cpp") != std::string::npos &&
|
||||
cm.find("Button_001.cpp") != std::string::npos &&
|
||||
cm.find("Label_001.cpp") != std::string::npos &&
|
||||
cm.find("Entry_001.cpp") != std::string::npos,
|
||||
"cmakelists-lists-all-sources");
|
||||
check(cm.find("target_include_directories(app PRIVATE "
|
||||
"${GTK3_INCLUDE_DIRS})") != std::string::npos,
|
||||
"cmakelists-include-dirs");
|
||||
check(cm.find("target_link_libraries(app PRIVATE ${GTK3_LIBRARIES})") !=
|
||||
std::string::npos,
|
||||
"cmakelists-link-libs");
|
||||
check(cm.find("CMAKE_CXX_STANDARD 17") != std::string::npos,
|
||||
"cmakelists-cxx17");
|
||||
check(cmake_project_exists(gen_dir), "cmake-project-detected");
|
||||
check(!cmake_project_exists(base), "cmake-project-absent-elsewhere");
|
||||
|
||||
// 2. Configure + build the generated project with cmake, then run
|
||||
// the built GTK app briefly under Xvfb (timeout kills it: exit 124).
|
||||
CMakeSettings def;
|
||||
CMakeBuildResult br = cmake_build_project(gen_dir, def);
|
||||
check(br.ok && br.configured, "cmake-configure-build-generated");
|
||||
check(br.exe_path == gen_dir + "/build/app", "cmake-exe-path");
|
||||
check(fs::is_regular_file(br.exe_path), "cmake-exe-exists");
|
||||
check(run("timeout 3 xvfb-run -a '" + br.exe_path +
|
||||
"' >/dev/null 2>&1") == 124,
|
||||
"cmake-built-gtk-app-runs");
|
||||
// Rebuild is a no-op success (idempotent configure+build).
|
||||
CMakeBuildResult br2 = cmake_build_project(gen_dir, def);
|
||||
check(br2.ok, "cmake-rebuild-idempotent");
|
||||
|
||||
// 3. Hand-written console CMake project (existing project, not
|
||||
// generated): configure + build + run, output must be exact.
|
||||
std::string console_dir = base + "/console";
|
||||
fs::create_directories(console_dir, ec);
|
||||
write_file(console_dir + "/CMakeLists.txt",
|
||||
"cmake_minimum_required(VERSION 3.10)\n"
|
||||
"project(console_demo CXX)\n"
|
||||
"add_executable(app main.cpp)\n");
|
||||
write_file(console_dir + "/main.cpp",
|
||||
"#include <cstdio>\n"
|
||||
"int main() { std::printf(\"cmake-console-ok\\n\"); "
|
||||
"return 0; }\n");
|
||||
CMakeBuildResult cr = cmake_build_project(console_dir, def);
|
||||
check(cr.ok, "cmake-build-handwritten-console");
|
||||
check(run("'" + console_dir + "/build/app' > '" + console_dir +
|
||||
"/run.log' 2>&1") == 0 &&
|
||||
read_file(console_dir + "/run.log") == "cmake-console-ok\n",
|
||||
"cmake-console-app-output");
|
||||
|
||||
// 4. Hand-written GTK CMake project (uses PkgConfig like generated).
|
||||
std::string gtk_dir = base + "/gtk";
|
||||
fs::create_directories(gtk_dir, ec);
|
||||
write_file(gtk_dir + "/CMakeLists.txt",
|
||||
"cmake_minimum_required(VERSION 3.10)\n"
|
||||
"project(gtk_demo CXX)\n"
|
||||
"find_package(PkgConfig REQUIRED)\n"
|
||||
"pkg_check_modules(GTK3 REQUIRED gtk+-3.0)\n"
|
||||
"add_executable(app main.cpp)\n"
|
||||
"target_include_directories(app PRIVATE "
|
||||
"${GTK3_INCLUDE_DIRS})\n"
|
||||
"target_link_libraries(app PRIVATE ${GTK3_LIBRARIES})\n");
|
||||
write_file(gtk_dir + "/main.cpp",
|
||||
"#include <gtk/gtk.h>\n"
|
||||
"int main(int argc, char** argv) {\n"
|
||||
" gtk_init(&argc, &argv);\n"
|
||||
" GtkWidget* w = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n"
|
||||
" gtk_widget_show_all(w);\n"
|
||||
" gtk_main();\n"
|
||||
" return 0;\n"
|
||||
"}\n");
|
||||
CMakeBuildResult gr = cmake_build_project(gtk_dir, def);
|
||||
check(gr.ok, "cmake-build-handwritten-gtk");
|
||||
check(run("timeout 3 xvfb-run -a '" + gtk_dir + "/build/app' "
|
||||
"> /dev/null 2>&1") == 124,
|
||||
"cmake-handwritten-gtk-app-runs");
|
||||
|
||||
// 5. Settings round-trip (custom path, so ~/.config is untouched).
|
||||
CMakeSettings s;
|
||||
s.cmake_path = "cmake";
|
||||
s.generator = "Unix Makefiles";
|
||||
s.build_type = "Debug";
|
||||
s.build_dir = "out";
|
||||
check(s.save(base + "/cmake.conf"), "cmake-settings-save");
|
||||
CMakeSettings s2;
|
||||
check(s2.load(base + "/cmake.conf") &&
|
||||
s2.generator == "Unix Makefiles" &&
|
||||
s2.build_type == "Debug" && s2.build_dir == "out" &&
|
||||
s2.cmake_path == "cmake",
|
||||
"cmake-settings-load");
|
||||
// Custom build dir + build type are honoured by a real build.
|
||||
CMakeBuildResult dbg = cmake_build_project(console_dir, s);
|
||||
check(dbg.ok && dbg.build_dir == console_dir + "/out" &&
|
||||
fs::is_regular_file(console_dir + "/out/app"),
|
||||
"cmake-settings-custom-build-dir");
|
||||
// Defaults load: unknown keys ignored, empty file loads as defaults.
|
||||
write_file(base + "/cmake2.conf", "# comment\nunknown_key=1\n");
|
||||
CMakeSettings s3;
|
||||
check(s3.load(base + "/cmake2.conf") &&
|
||||
s3.build_type == "Release" && s3.build_dir == "build",
|
||||
"cmake-settings-unknown-keys-ignored");
|
||||
|
||||
// 6. Failure reporting: missing CMakeLists.txt, broken CMakeLists.txt,
|
||||
// and a project whose sources fail to compile must all report !ok.
|
||||
CMakeBuildResult nofile = cmake_build_project(base, def);
|
||||
check(!nofile.ok && !nofile.configured,
|
||||
"cmake-missing-cmakelists-fails");
|
||||
std::string broken_dir = base + "/broken";
|
||||
fs::create_directories(broken_dir, ec);
|
||||
write_file(broken_dir + "/CMakeLists.txt", "this is not valid cmake (\n");
|
||||
CMakeBuildResult bad = cmake_build_project(broken_dir, def);
|
||||
check(!bad.ok && !bad.configured, "cmake-broken-cmakelists-fails");
|
||||
std::string badsrc_dir = base + "/badsrc";
|
||||
fs::create_directories(badsrc_dir, ec);
|
||||
write_file(badsrc_dir + "/CMakeLists.txt",
|
||||
"cmake_minimum_required(VERSION 3.10)\n"
|
||||
"project(bad CXX)\n"
|
||||
"add_executable(app main.cpp)\n");
|
||||
write_file(badsrc_dir + "/main.cpp", "int main( { syntax error\n");
|
||||
CMakeBuildResult badsrc = cmake_build_project(badsrc_dir, def);
|
||||
check(!badsrc.ok && badsrc.configured,
|
||||
"cmake-compile-error-fails-after-configure");
|
||||
|
||||
// 7. Shell quoting: a project dir with a space in its name builds.
|
||||
std::string spaced = base + "/dir with space";
|
||||
fs::create_directories(spaced, ec);
|
||||
write_file(spaced + "/CMakeLists.txt",
|
||||
"cmake_minimum_required(VERSION 3.10)\n"
|
||||
"project(spaced CXX)\n"
|
||||
"add_executable(app main.cpp)\n");
|
||||
write_file(spaced + "/main.cpp", "int main() { return 0; }\n");
|
||||
CMakeBuildResult sp = cmake_build_project(spaced, def);
|
||||
check(sp.ok, "cmake-dir-with-space-builds");
|
||||
|
||||
std::printf("== cmake probe: %d passed, %d failed ==\n", g_pass, g_fail);
|
||||
return g_fail == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# CMake tests for FDesigner: generated CMakeLists.txt contents, real
|
||||
# configure+build of generated and hand-written CMake projects (GTK under
|
||||
# Xvfb, console run), settings persistence, and failure reporting.
|
||||
# Usage: tests/cmake_tests.sh (run from the repo root; builds fdesigner
|
||||
# first so the self-test's CMake phase is exercised too.)
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
pass=0; fail=0
|
||||
note() { if [ "$1" = 0 ]; then pass=$((pass+1)); else fail=$((fail+1)); fi; }
|
||||
|
||||
echo "== building fdesigner =="
|
||||
make > /tmp/fdesigner_cmake_make.log 2>&1
|
||||
note $?
|
||||
if [ $fail -ne 0 ]; then echo "FAIL make — see /tmp/fdesigner_cmake_make.log"; exit 1; fi
|
||||
echo "PASS make"
|
||||
|
||||
echo "== building cmake probe =="
|
||||
g++ -O2 -Wall -Wextra -std=c++17 -o /tmp/cmake_probe tests/cmake_probe.cpp \
|
||||
src/generator.cpp src/cmake_build.cpp -I src \
|
||||
$(pkg-config --cflags --libs gtk+-3.0) > /tmp/cmake_probe_build.log 2>&1
|
||||
note $?
|
||||
if [ $fail -ne 0 ]; then echo "FAIL probe build — see /tmp/cmake_probe_build.log"; exit 1; fi
|
||||
echo "PASS probe build"
|
||||
|
||||
echo "== probe (generate + cmake configure/build + run + settings + failures) =="
|
||||
/tmp/cmake_probe /tmp/fdesigner_cmake_tests
|
||||
rc=$?
|
||||
note $rc
|
||||
|
||||
echo "== designer self-test (includes CMake Phase 9) =="
|
||||
FDESIGNER_SELFTEST=1 timeout 120 xvfb-run -a ./fdesigner > /tmp/fdesigner_cmake_selftest.log 2>&1
|
||||
rc=$?
|
||||
if [ $rc -eq 0 ] && grep -q "SELFTEST PASS" /tmp/fdesigner_cmake_selftest.log; then
|
||||
echo "PASS selftest"; pass=$((pass+1))
|
||||
else
|
||||
echo "FAIL selftest (rc=$rc) — see /tmp/fdesigner_cmake_selftest.log"; fail=$((fail+1))
|
||||
fi
|
||||
|
||||
echo "== cmake tests: $pass passed, $fail failed =="
|
||||
[ $fail -eq 0 ]
|
||||
@@ -1,121 +0,0 @@
|
||||
ticker,volume,open,close,high,low,window_start,transactions
|
||||
SPY,17171,660.00,659.49,660.24,659.31,1794493800000000000,1561
|
||||
SPY,31882,659.49,660.23,660.35,659.32,1794493860000000000,1275
|
||||
SPY,2460,660.23,659.71,660.35,659.51,1794493920000000000,102
|
||||
SPY,17173,659.71,659.37,659.77,659.06,1794493980000000000,1561
|
||||
SPY,1878,659.37,659.11,659.75,658.68,1794494040000000000,170
|
||||
SPY,27854,659.11,659.36,659.52,658.72,1794494100000000000,1392
|
||||
SPY,42048,659.36,659.00,659.40,658.66,1794494160000000000,2628
|
||||
SPY,37479,659.00,658.42,659.05,658.12,1794494220000000000,3747
|
||||
SPY,15216,658.42,658.14,658.62,658.02,1794494280000000000,1268
|
||||
SPY,16665,658.14,658.42,658.44,657.88,1794494340000000000,724
|
||||
SPY,10169,658.42,658.37,658.82,658.33,1794494400000000000,635
|
||||
SPY,31564,658.37,658.67,658.93,658.17,1794494460000000000,2630
|
||||
SPY,12123,658.67,658.20,658.98,657.98,1794494520000000000,505
|
||||
SPY,10316,658.20,657.57,658.27,657.32,1794494580000000000,1289
|
||||
SPY,10175,657.57,657.13,657.91,656.92,1794494640000000000,484
|
||||
SPY,35318,657.13,656.29,657.25,655.89,1794494700000000000,3924
|
||||
SPY,28367,656.29,657.04,657.30,655.92,1794494760000000000,1289
|
||||
SPY,30316,657.04,657.20,657.37,656.74,1794494820000000000,3368
|
||||
SPY,10098,657.20,658.09,658.44,657.15,1794494880000000000,1262
|
||||
SPY,42874,658.09,658.94,659.35,657.86,1794494940000000000,2256
|
||||
SPY,10492,658.94,659.24,659.41,658.54,1794495000000000000,1165
|
||||
SPY,35345,659.24,659.39,659.80,659.01,1794495060000000000,2718
|
||||
SPY,25115,659.39,659.97,660.00,659.33,1794495120000000000,1793
|
||||
SPY,22783,659.97,659.91,660.30,659.71,1794495180000000000,1340
|
||||
SPY,19127,659.91,660.09,660.54,659.73,1794495240000000000,796
|
||||
SPY,4644,660.09,659.78,660.18,659.47,1794495300000000000,258
|
||||
SPY,16670,659.78,660.12,660.52,659.64,1794495360000000000,1515
|
||||
SPY,14061,660.12,660.54,660.81,659.91,1794495420000000000,937
|
||||
SPY,4331,660.54,661.48,661.89,660.28,1794495480000000000,188
|
||||
SPY,11557,661.48,661.81,661.89,661.22,1794495540000000000,502
|
||||
SPY,32484,661.81,662.63,662.85,661.65,1794495600000000000,4060
|
||||
SPY,44926,662.63,661.75,662.94,661.40,1794495660000000000,4492
|
||||
SPY,30274,661.75,661.76,662.08,661.50,1794495720000000000,3784
|
||||
SPY,33649,661.76,661.11,662.06,660.93,1794495780000000000,2243
|
||||
SPY,35639,661.11,661.90,662.00,661.04,1794495840000000000,2969
|
||||
SPY,38016,661.90,661.09,662.30,660.98,1794495900000000000,2000
|
||||
SPY,42237,661.09,662.00,662.12,660.89,1794495960000000000,3249
|
||||
SPY,14868,662.00,661.48,662.32,661.38,1794496020000000000,1062
|
||||
SPY,15920,661.48,662.33,662.57,661.31,1794496080000000000,796
|
||||
SPY,6394,662.33,662.69,663.13,661.97,1794496140000000000,710
|
||||
SPY,23912,662.69,661.86,663.07,661.81,1794496200000000000,1494
|
||||
SPY,3717,661.86,660.98,661.92,660.67,1794496260000000000,154
|
||||
SPY,40972,660.98,660.67,661.38,660.49,1794496320000000000,2926
|
||||
SPY,9986,660.67,660.44,660.86,660.31,1794496380000000000,907
|
||||
SPY,39576,660.44,660.91,660.95,660.21,1794496440000000000,2826
|
||||
SPY,22013,660.91,660.02,661.01,659.99,1794496500000000000,1000
|
||||
SPY,42255,660.02,660.22,660.31,660.00,1794496560000000000,3521
|
||||
SPY,42488,660.22,659.69,660.45,659.40,1794496620000000000,1847
|
||||
SPY,26294,659.69,659.54,659.78,659.20,1794496680000000000,2921
|
||||
SPY,24471,659.54,658.85,659.70,658.44,1794496740000000000,2447
|
||||
SPY,26095,658.85,659.61,659.86,658.53,1794496800000000000,1863
|
||||
SPY,30384,659.61,659.45,659.67,659.36,1794496860000000000,3798
|
||||
SPY,21961,659.45,659.31,659.76,659.20,1794496920000000000,1464
|
||||
SPY,21675,659.31,659.60,659.67,658.94,1794496980000000000,2709
|
||||
SPY,42310,659.60,659.60,659.84,659.43,1794497040000000000,2115
|
||||
SPY,32772,659.60,659.97,660.01,659.21,1794497100000000000,1724
|
||||
SPY,2744,659.97,659.15,660.08,659.02,1794497160000000000,182
|
||||
SPY,35643,659.15,658.31,659.34,657.92,1794497220000000000,3960
|
||||
SPY,36255,658.31,658.98,659.18,657.95,1794497280000000000,1812
|
||||
SPY,22461,658.98,658.82,659.20,658.57,1794497340000000000,2041
|
||||
SPY,36668,658.82,659.34,659.37,658.43,1794497400000000000,1666
|
||||
SPY,22626,659.34,659.97,660.35,659.06,1794497460000000000,1740
|
||||
SPY,24273,659.97,660.81,660.99,659.68,1794497520000000000,1213
|
||||
SPY,30522,660.81,660.99,661.40,660.54,1794497580000000000,1526
|
||||
SPY,35566,660.99,660.46,661.25,660.36,1794497640000000000,3951
|
||||
SPY,14789,660.46,660.05,660.77,659.92,1794497700000000000,821
|
||||
SPY,36057,660.05,660.49,660.53,659.79,1794497760000000000,3004
|
||||
SPY,42294,660.49,660.65,660.71,660.16,1794497820000000000,2226
|
||||
SPY,40939,660.65,660.81,660.94,660.53,1794497880000000000,4093
|
||||
SPY,35446,660.81,661.01,661.18,660.55,1794497940000000000,2085
|
||||
SPY,22412,661.01,660.74,661.45,660.42,1794498000000000000,974
|
||||
SPY,15587,660.74,659.93,660.78,659.65,1794498060000000000,677
|
||||
SPY,37522,659.93,659.15,660.01,659.03,1794498120000000000,4169
|
||||
SPY,44124,659.15,659.29,659.32,658.71,1794498180000000000,2595
|
||||
SPY,30318,659.29,659.35,659.44,659.13,1794498240000000000,2165
|
||||
SPY,14773,659.35,659.57,659.65,659.12,1794498300000000000,984
|
||||
SPY,17174,659.57,660.12,660.19,659.23,1794498360000000000,2146
|
||||
SPY,15354,660.12,660.79,661.12,659.80,1794498420000000000,1096
|
||||
SPY,16247,660.79,660.53,661.20,660.42,1794498480000000000,1477
|
||||
SPY,12390,660.53,660.84,660.89,660.46,1794498540000000000,516
|
||||
SPY,41682,660.84,660.93,661.13,660.44,1794498600000000000,2977
|
||||
SPY,19672,660.93,660.14,661.35,659.99,1794498660000000000,894
|
||||
SPY,3291,660.14,659.43,660.51,659.30,1794498720000000000,205
|
||||
SPY,42129,659.43,658.99,659.63,658.66,1794498780000000000,5266
|
||||
SPY,6277,658.99,659.32,659.37,658.79,1794498840000000000,251
|
||||
SPY,20502,659.32,659.61,659.74,659.05,1794498900000000000,976
|
||||
SPY,24747,659.61,658.86,659.88,658.78,1794498960000000000,1455
|
||||
SPY,33696,658.86,658.99,659.21,658.47,1794499020000000000,2246
|
||||
SPY,21472,658.99,658.22,659.07,657.94,1794499080000000000,894
|
||||
SPY,24628,658.22,657.72,658.31,657.40,1794499140000000000,1231
|
||||
SPY,21257,657.72,657.38,658.12,657.03,1794499200000000000,1180
|
||||
SPY,43832,657.38,657.07,657.51,656.73,1794499260000000000,5479
|
||||
SPY,13251,657.07,656.61,657.20,656.44,1794499320000000000,662
|
||||
SPY,22692,656.61,657.09,657.34,656.49,1794499380000000000,1031
|
||||
SPY,19955,657.09,656.62,657.43,656.26,1794499440000000000,1425
|
||||
SPY,20763,656.62,655.86,656.92,655.62,1794499500000000000,1038
|
||||
SPY,22494,655.86,655.01,656.13,654.79,1794499560000000000,1730
|
||||
SPY,6533,655.01,654.72,655.19,654.32,1794499620000000000,435
|
||||
SPY,27082,654.72,655.13,655.39,654.32,1794499680000000000,1593
|
||||
SPY,43522,655.13,655.23,655.58,655.04,1794499740000000000,3108
|
||||
SPY,31582,655.23,655.56,655.61,654.83,1794499800000000000,1503
|
||||
SPY,10061,655.56,656.47,656.65,655.51,1794499860000000000,914
|
||||
SPY,14964,656.47,656.26,656.62,656.06,1794499920000000000,598
|
||||
SPY,16125,656.26,655.51,656.64,655.13,1794499980000000000,645
|
||||
SPY,21701,655.51,654.91,655.72,654.67,1794500040000000000,1085
|
||||
SPY,36817,654.91,655.68,655.92,654.71,1794500100000000000,1753
|
||||
SPY,39741,655.68,655.68,655.84,655.53,1794500160000000000,2207
|
||||
SPY,13451,655.68,656.26,656.47,655.24,1794500220000000000,791
|
||||
SPY,26108,656.26,656.23,656.57,655.86,1794500280000000000,2610
|
||||
SPY,40304,656.23,655.80,656.45,655.71,1794500340000000000,3664
|
||||
SPY,17056,655.80,655.48,655.87,655.27,1794500400000000000,682
|
||||
SPY,2739,655.48,654.67,655.80,654.24,1794500460000000000,210
|
||||
SPY,34501,654.67,654.78,655.03,654.45,1794500520000000000,3450
|
||||
SPY,6849,654.78,655.44,655.49,654.50,1794500580000000000,342
|
||||
SPY,2777,655.44,655.19,655.54,655.13,1794500640000000000,173
|
||||
SPY,35876,655.19,654.85,655.57,654.77,1794500700000000000,2562
|
||||
SPY,17708,654.85,655.57,655.93,654.44,1794500760000000000,1180
|
||||
SPY,27839,655.57,656.02,656.21,655.26,1794500820000000000,2141
|
||||
SPY,14012,656.02,656.12,656.14,655.81,1794500880000000000,1401
|
||||
SPY,15679,656.12,655.88,656.53,655.62,1794500940000000000,1742
|
||||
|
@@ -1,32 +0,0 @@
|
||||
// Debugger test target: console C++ program.
|
||||
// Markers (// MARK:xxx) are found by the harness to get line numbers, so
|
||||
// edits here do not break the tests. Compile with: g++ -g -O0 -o console console.cpp
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
int helper(int v) {
|
||||
int r = v * 2 + 1; // MARK:HELPER
|
||||
return r;
|
||||
}
|
||||
|
||||
int compute(int a, int b) {
|
||||
int s = a + b; // MARK:COMPUTE
|
||||
int d = helper(s); // MARK:COMPUTE_CALL
|
||||
return d;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc > 1) std::printf("ARG=%s\n", argv[1]); // MARK:ARG
|
||||
int sum = 0;
|
||||
std::vector<int> vals = {1, 2, 3};
|
||||
for (int i = 0; i < 3; i++) {
|
||||
int x = helper(i); // MARK:LOOP
|
||||
sum += x; // MARK:LOOP_NEXT
|
||||
std::printf("i=%d x=%d sum=%d\n", i, x, sum);
|
||||
std::fflush(stdout); // line-buffered for the debugger's live view
|
||||
}
|
||||
int total = compute(10, 20); // MARK:CALL
|
||||
std::printf("TOTAL total=%d sum=%d\n", total, sum); // MARK:AFTER_CALL
|
||||
std::printf("DONE sum=%d\n", sum);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,844 +0,0 @@
|
||||
// Headless driver for the FDesigner debugger backend (GdbSession).
|
||||
// Usage: dbg_harness console <dir> — console C++ tests
|
||||
// dbg_harness gtk <dir> — GTK app tests (run under xvfb-run)
|
||||
// Each test prints PASS/FAIL with its name; exit code is non-zero if any
|
||||
// test fails. Line numbers come from // MARK:xxx comments in the targets,
|
||||
// so editing the targets does not silently shift the expectations.
|
||||
#include "../../src/debugger.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
static std::string g_dir;
|
||||
static int g_pass = 0, g_fail = 0;
|
||||
static std::vector<std::string> g_failed;
|
||||
|
||||
static void report(const std::string& name, bool ok, const std::string& detail = "") {
|
||||
if (ok) {
|
||||
++g_pass;
|
||||
std::printf("PASS %s\n", name.c_str());
|
||||
} else {
|
||||
++g_fail;
|
||||
g_failed.push_back(name);
|
||||
std::printf("FAIL %s%s%s\n", name.c_str(),
|
||||
detail.empty() ? "" : " — ", detail.c_str());
|
||||
}
|
||||
std::fflush(stdout);
|
||||
}
|
||||
|
||||
static int mark_line(const std::string& file, const std::string& mark) {
|
||||
std::ifstream f(file);
|
||||
std::string line;
|
||||
int n = 0;
|
||||
while (std::getline(f, line)) {
|
||||
++n;
|
||||
if (line.find(mark) != std::string::npos) return n;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static std::string loc(const std::string& file, int line) {
|
||||
return file + ":" + std::to_string(line);
|
||||
}
|
||||
|
||||
static bool has(const std::vector<Variable>& vars, const std::string& name,
|
||||
const std::string& value) {
|
||||
for (const auto& v : vars)
|
||||
if (v.name == name && v.value == value) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
static std::string var_value(const std::vector<Variable>& vars,
|
||||
const std::string& name) {
|
||||
for (const auto& v : vars)
|
||||
if (v.name == name) return v.value;
|
||||
return "<missing>";
|
||||
}
|
||||
|
||||
// ---- console tests -------------------------------------------------------
|
||||
|
||||
static void console_tests() {
|
||||
std::string console = g_dir + "/console";
|
||||
std::string src = g_dir + "/console.cpp";
|
||||
std::string spin = g_dir + "/spin";
|
||||
int L_LOOP = mark_line(src, "MARK:LOOP");
|
||||
int L_LOOP_NEXT = mark_line(src, "MARK:LOOP_NEXT");
|
||||
int L_CALL = mark_line(src, "MARK:CALL");
|
||||
int L_AFTER = mark_line(src, "MARK:AFTER_CALL");
|
||||
int L_COMPUTE = mark_line(src, "MARK:COMPUTE");
|
||||
int L_HELPER = mark_line(src, "MARK:HELPER");
|
||||
report("marks_found", L_LOOP > 0 && L_LOOP_NEXT > 0 && L_CALL > 0 &&
|
||||
L_AFTER > 0 && L_COMPUTE > 0 && L_HELPER > 0);
|
||||
|
||||
// 1. gdb exists at the default path
|
||||
{
|
||||
DebuggerSettings s;
|
||||
report("gdb_default_path_executable",
|
||||
::access(s.gdb_path.c_str(), X_OK) == 0, s.gdb_path);
|
||||
}
|
||||
// 2. settings save/load round-trip
|
||||
{
|
||||
DebuggerSettings s;
|
||||
s.gdb_path = "/usr/bin/gdb";
|
||||
s.break_on_main = true;
|
||||
s.stop_on_entry = false;
|
||||
s.pretty_print = false;
|
||||
s.default_args = "a b";
|
||||
std::string p = "/tmp/dbgtest_conf";
|
||||
bool ok = s.save(p);
|
||||
DebuggerSettings s2;
|
||||
ok = ok && s2.load(p);
|
||||
ok = ok && s2.gdb_path == "/usr/bin/gdb" && s2.break_on_main &&
|
||||
!s2.pretty_print && s2.default_args == "a b";
|
||||
report("settings_save_load", ok);
|
||||
}
|
||||
// 3. bad gdb path fails cleanly
|
||||
{
|
||||
DebuggerSettings s;
|
||||
s.gdb_path = "/nonexistent/gdb";
|
||||
GdbSession sess(s);
|
||||
std::string err;
|
||||
bool ok = !sess.start(console, "", err) && !err.empty();
|
||||
report("bad_gdb_path_fails", ok, err);
|
||||
}
|
||||
// 4. run to completion, no breakpoints
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
bool ok = sess.start(console, "", err);
|
||||
ok = ok && sess.wait_for_stop(10000);
|
||||
ok = ok && sess.state() == DbgState::Exited &&
|
||||
sess.exit_code() == 0;
|
||||
ok = ok && sess.target_output().find("DONE sum=9") != std::string::npos;
|
||||
report("run_to_completion", ok, err + " | out: " + sess.target_output());
|
||||
}
|
||||
// 5. breakpoint by file:line is hit
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
bool ok = sess.start(console, "", err);
|
||||
ok = ok && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().reason == "breakpoint-hit" &&
|
||||
sess.last_stop().frame.line == L_LOOP &&
|
||||
sess.last_stop().frame.function == "main";
|
||||
report("bp_file_line_hit", ok,
|
||||
err + " reason=" + sess.last_stop().reason +
|
||||
" line=" + std::to_string(sess.last_stop().frame.line));
|
||||
}
|
||||
// 6. locals at the breakpoint (first iteration: i=0, sum=0)
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
sess.refresh_on_stop();
|
||||
bool ok = has(sess.locals(), "i", "0") && has(sess.locals(), "sum", "0");
|
||||
report("locals_at_bp", ok,
|
||||
"i=" + var_value(sess.locals(), "i") +
|
||||
" sum=" + var_value(sess.locals(), "sum"));
|
||||
}
|
||||
// 7. watch expression + evaluate
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
sess.refresh_on_stop();
|
||||
bool ok = sess.add_watch("sum + 1", err);
|
||||
std::string v, e;
|
||||
ok = ok && sess.evaluate("i + 5", v, e) && v == "5";
|
||||
ok = ok && has(sess.watches(), "sum + 1", "1");
|
||||
report("watch_and_evaluate", ok, "i+5=" + v + " err=" + e);
|
||||
}
|
||||
// 8. step over: LOOP -> LOOP_NEXT, x == 1 after the call
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
bool ok = sess.step_over(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.last_stop().frame.line == L_LOOP_NEXT;
|
||||
std::string v, e;
|
||||
ok = ok && sess.evaluate("x", v, e) && v == "1";
|
||||
report("step_over", ok,
|
||||
"line=" + std::to_string(sess.last_stop().frame.line) +
|
||||
" x=" + v);
|
||||
}
|
||||
// 9. step into: CALL line -> inside compute()
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_CALL));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
bool ok = sess.step_into(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.last_stop().frame.function.find("compute") !=
|
||||
std::string::npos;
|
||||
report("step_into", ok,
|
||||
"func=" + sess.last_stop().frame.function);
|
||||
}
|
||||
// 10. step out: from compute() back to main, line after the call
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_CALL));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
sess.step_into(err);
|
||||
sess.wait_for_stop();
|
||||
bool ok = sess.step_out(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.last_stop().frame.function == "main" &&
|
||||
(sess.last_stop().frame.line == L_AFTER ||
|
||||
sess.last_stop().frame.line == L_CALL);
|
||||
std::string v, e;
|
||||
if (sess.last_stop().frame.line == L_CALL) {
|
||||
// finish stops on the call-site assignment line; one step
|
||||
// over executes the store, landing on the line after.
|
||||
ok = ok && sess.step_over(e) && sess.wait_for_stop() &&
|
||||
sess.last_stop().frame.line == L_AFTER;
|
||||
}
|
||||
ok = ok && sess.evaluate("total", v, e) && v == "61";
|
||||
report("step_out", ok,
|
||||
"func=" + sess.last_stop().frame.function +
|
||||
" line=" + std::to_string(sess.last_stop().frame.line) +
|
||||
" total=" + v);
|
||||
}
|
||||
// 11. continue to the next breakpoint (loop bp, then helper bp)
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.stage_breakpoint(loc(src, L_HELPER));
|
||||
sess.start(console, "", err);
|
||||
bool ok = sess.wait_for_stop() &&
|
||||
sess.last_stop().frame.line == L_LOOP;
|
||||
ok = ok && sess.cont(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.last_stop().reason == "breakpoint-hit" &&
|
||||
sess.last_stop().frame.function.find("helper") !=
|
||||
std::string::npos;
|
||||
report("continue_to_next_bp", ok,
|
||||
"func=" + sess.last_stop().frame.function);
|
||||
}
|
||||
// 12. multiple breakpoints listed with ids
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.stage_breakpoint(loc(src, L_HELPER));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
bool ok = sess.refresh_breakpoints(err) &&
|
||||
sess.breakpoints().size() >= 2;
|
||||
report("multiple_bps_listed", ok,
|
||||
"count=" + std::to_string(sess.breakpoints().size()));
|
||||
}
|
||||
// 13. disable a breakpoint: it is not hit
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.stage_breakpoint(loc(src, L_HELPER));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop(); // at LOOP
|
||||
int loop_id = 0;
|
||||
for (const auto& b : sess.breakpoints())
|
||||
if (b.line == L_LOOP) loop_id = b.id;
|
||||
bool ok = loop_id > 0;
|
||||
ok = ok && sess.enable_breakpoint(loop_id, false, err);
|
||||
ok = ok && sess.cont(err) && sess.wait_for_stop();
|
||||
// Next stop must be the helper bp, not the loop bp.
|
||||
ok = ok && sess.last_stop().frame.function.find("helper") !=
|
||||
std::string::npos;
|
||||
report("disable_bp_skips", ok,
|
||||
"func=" + sess.last_stop().frame.function);
|
||||
}
|
||||
// 14. re-enable: the breakpoint is hit again
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
int loop_id = 0;
|
||||
for (const auto& b : sess.breakpoints())
|
||||
if (b.line == L_LOOP) loop_id = b.id;
|
||||
bool ok = sess.enable_breakpoint(loop_id, false, err);
|
||||
ok = ok && sess.cont(err) && sess.wait_for_stop();
|
||||
// Disabled: runs to completion (no more bps).
|
||||
ok = ok && sess.state() == DbgState::Exited;
|
||||
// Restart with the bp re-enabled: must stop at LOOP again.
|
||||
ok = ok && sess.enable_breakpoint(loop_id, true, err);
|
||||
ok = ok && sess.restart(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().frame.line == L_LOOP;
|
||||
report("enable_bp_hits_again", ok,
|
||||
"state=" + std::to_string((int)sess.state()));
|
||||
}
|
||||
// 15. delete a breakpoint: gone from the list, never hit
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
int loop_id = 0;
|
||||
for (const auto& b : sess.breakpoints())
|
||||
if (b.line == L_LOOP) loop_id = b.id;
|
||||
bool ok = sess.remove_breakpoint(loop_id, err);
|
||||
ok = ok && sess.refresh_breakpoints(err) &&
|
||||
sess.breakpoints().empty();
|
||||
ok = ok && sess.cont(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Exited;
|
||||
report("delete_bp", ok, "remaining=" +
|
||||
std::to_string(sess.breakpoints().size()));
|
||||
}
|
||||
// 16. breakpoint by function name
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint("compute");
|
||||
sess.start(console, "", err);
|
||||
bool ok = sess.wait_for_stop();
|
||||
ok = ok && sess.last_stop().frame.function.find("compute") !=
|
||||
std::string::npos &&
|
||||
sess.last_stop().frame.line == L_COMPUTE;
|
||||
report("bp_by_function", ok,
|
||||
"func=" + sess.last_stop().frame.function +
|
||||
" line=" + std::to_string(sess.last_stop().frame.line));
|
||||
}
|
||||
// 17. invalid breakpoints fail gracefully
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
bool ok = !sess.stage_breakpoint("");
|
||||
ok = ok && !sess.stage_breakpoint("not a location!!!");
|
||||
// gdb-side rejection of a nonexistent file
|
||||
sess.start_gdb_only(err);
|
||||
sess.load_executable(console, err);
|
||||
Breakpoint b;
|
||||
std::string e2;
|
||||
ok = ok && !sess.add_breakpoint("no_such_file.cpp:9999", b, e2) &&
|
||||
!e2.empty();
|
||||
report("invalid_bp_rejected", ok, e2);
|
||||
}
|
||||
// 18. stack frames at a stop
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
sess.refresh_on_stop();
|
||||
bool ok = !sess.frames().empty() &&
|
||||
sess.frames()[0].function == "main" &&
|
||||
sess.frames()[0].line == L_LOOP;
|
||||
report("frames_at_stop", ok,
|
||||
"n=" + std::to_string(sess.frames().size()));
|
||||
}
|
||||
// 19. stack depth inside nested calls (main > compute > helper)
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_HELPER));
|
||||
sess.start(console, "", err);
|
||||
bool ok19 = sess.wait_for_stop();
|
||||
// Hits 1-3 are helper() called from the loop (depth 2); hit 4 is
|
||||
// helper() called from compute() (depth 3: main > compute > helper).
|
||||
for (int i = 0; i < 3 && ok19; ++i)
|
||||
ok19 = sess.cont(err) && sess.wait_for_stop();
|
||||
sess.refresh_on_stop();
|
||||
bool ok = ok19 && sess.frames().size() >= 3;
|
||||
if (ok) {
|
||||
ok = sess.frames()[0].function.find("helper") != std::string::npos &&
|
||||
sess.frames()[1].function.find("compute") != std::string::npos &&
|
||||
sess.frames()[2].function == "main";
|
||||
}
|
||||
report("stack_depth_nested", ok,
|
||||
"n=" + std::to_string(sess.frames().size()));
|
||||
}
|
||||
// 20. kill a running (spinning) target
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
bool ok = sess.start(spin, "", err);
|
||||
::usleep(500000);
|
||||
ok = ok && sess.target_running();
|
||||
ok = ok && sess.kill_target(err);
|
||||
ok = ok && sess.wait_for_stop(5000);
|
||||
ok = ok && !sess.target_running() && sess.is_alive();
|
||||
report("kill_running_target", ok,
|
||||
"state=" + std::to_string((int)sess.state()));
|
||||
}
|
||||
// 21. restart after exit hits the breakpoint again
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.start(console, "", err);
|
||||
bool ok = sess.wait_for_stop();
|
||||
// The loop bp fires once per iteration (i=0,1,2): three continues
|
||||
// run the program to completion.
|
||||
for (int i = 0; i < 3 && ok; ++i)
|
||||
ok = sess.cont(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Exited;
|
||||
ok = ok && sess.restart(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().frame.line == L_LOOP;
|
||||
report("restart_after_exit", ok, "");
|
||||
}
|
||||
// 22. restart after kill: target runs again, can be killed again
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
bool ok = sess.start(spin, "", err);
|
||||
::usleep(300000);
|
||||
ok = ok && sess.kill_target(err) && sess.wait_for_stop(5000);
|
||||
ok = ok && sess.restart(err);
|
||||
::usleep(300000);
|
||||
ok = ok && sess.target_running();
|
||||
ok = ok && sess.kill_target(err) && sess.wait_for_stop(5000);
|
||||
ok = ok && !sess.target_running();
|
||||
report("restart_after_kill", ok, "");
|
||||
}
|
||||
// 23. break_on_main setting stops at main
|
||||
{
|
||||
DebuggerSettings s;
|
||||
s.break_on_main = true;
|
||||
GdbSession sess(s);
|
||||
std::string err;
|
||||
bool ok = sess.start(console, "", err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().reason == "breakpoint-hit" &&
|
||||
sess.last_stop().frame.function == "main";
|
||||
report("setting_break_on_main", ok,
|
||||
"func=" + sess.last_stop().frame.function +
|
||||
" reason=" + sess.last_stop().reason);
|
||||
}
|
||||
// 24. stop_on_entry setting stops at main
|
||||
{
|
||||
DebuggerSettings s;
|
||||
s.stop_on_entry = true;
|
||||
GdbSession sess(s);
|
||||
std::string err;
|
||||
bool ok = sess.start(console, "", err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().frame.function == "main";
|
||||
report("setting_stop_on_entry", ok,
|
||||
"func=" + sess.last_stop().frame.function);
|
||||
}
|
||||
// 25. pretty-print: vector value comes back expanded
|
||||
{
|
||||
DebuggerSettings s;
|
||||
s.pretty_print = true;
|
||||
GdbSession sess(s);
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
bool ok = sess.start(console, "", err) && sess.wait_for_stop();
|
||||
sess.refresh_on_stop();
|
||||
std::string v, e;
|
||||
ok = ok && sess.evaluate("vals", v, e);
|
||||
ok = ok && v.find("1") != std::string::npos &&
|
||||
v.find("3") != std::string::npos;
|
||||
// And the setting is what got saved to disk.
|
||||
DebuggerSettings s2;
|
||||
s2.pretty_print = true;
|
||||
ok = ok && s2.save("/tmp/dbgtest_conf2");
|
||||
DebuggerSettings s3;
|
||||
ok = ok && s3.load("/tmp/dbgtest_conf2") && s3.pretty_print;
|
||||
report("setting_pretty_print", ok, "vals=" + v);
|
||||
}
|
||||
// 26. settings file is actually read and applied (break_on_main via file)
|
||||
{
|
||||
DebuggerSettings s;
|
||||
s.gdb_path = "/usr/bin/gdb";
|
||||
s.break_on_main = true;
|
||||
s.save("/tmp/dbgtest_conf3");
|
||||
DebuggerSettings loaded;
|
||||
bool ok = loaded.load("/tmp/dbgtest_conf3") && loaded.break_on_main;
|
||||
GdbSession sess(loaded);
|
||||
std::string err;
|
||||
ok = ok && sess.start(console, "", err) && sess.wait_for_stop();
|
||||
ok = ok && sess.last_stop().frame.function == "main";
|
||||
report("settings_file_applied", ok, "");
|
||||
}
|
||||
// 27. target stdout/stderr captured
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
bool ok = sess.start(console, "", err) && sess.wait_for_stop(10000);
|
||||
ok = ok && sess.target_output().find("i=0 x=1 sum=1") != std::string::npos &&
|
||||
sess.target_output().find("i=2 x=5 sum=9") != std::string::npos &&
|
||||
sess.target_output().find("TOTAL total=61 sum=9") != std::string::npos;
|
||||
report("target_output_captured", ok, sess.target_output());
|
||||
}
|
||||
// 28. evaluate arithmetic at a stop
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.start(console, "", err);
|
||||
sess.wait_for_stop();
|
||||
std::string v, e;
|
||||
bool ok = sess.evaluate("sum + 100", v, e) && v == "100";
|
||||
ok = ok && sess.evaluate("vals[2]", v, e) && v == "3";
|
||||
ok = ok && sess.evaluate("vals.size()", v, e) && v == "3";
|
||||
report("evaluate_arithmetic", ok, "sum+100=" + v);
|
||||
}
|
||||
// 29. target args are passed through
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
bool ok = sess.start(console, "hello", err) && sess.wait_for_stop(10000);
|
||||
ok = ok && sess.target_output().find("ARG=hello") != std::string::npos;
|
||||
report("target_args_passed", ok, sess.target_output());
|
||||
}
|
||||
// 30. breakpoints persist to disk and load back
|
||||
{
|
||||
GdbSession sess;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
sess.stage_breakpoint("compute");
|
||||
bool ok = sess.save_breakpoints("/tmp/dbgtest_bps");
|
||||
GdbSession sess2;
|
||||
ok = ok && sess2.load_breakpoints("/tmp/dbgtest_bps");
|
||||
ok = ok && sess2.breakpoints().size() == 2 &&
|
||||
sess2.breakpoints()[0].location == loc(src, L_LOOP) &&
|
||||
sess2.breakpoints()[1].location == "compute";
|
||||
report("bps_persist_to_disk", ok, "");
|
||||
}
|
||||
// 31. conditional breakpoint: fires only when i == 2, never before
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
Breakpoint opts;
|
||||
opts.kind = BpKind::Conditional;
|
||||
opts.condition = "i == 2";
|
||||
bool ok = sess.stage_breakpoint_opts(loc(src, L_LOOP), opts);
|
||||
ok = ok && sess.start(console, "", err);
|
||||
ok = ok && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().reason == "breakpoint-hit" &&
|
||||
sess.last_stop().frame.line == L_LOOP;
|
||||
std::string v, e;
|
||||
ok = ok && sess.evaluate("i", v, e) && v == "2";
|
||||
// It must NOT have stopped at i=0/1: both iterations printed
|
||||
// before the first (and only) stop.
|
||||
ok = ok && sess.target_output().find("i=0 x=1 sum=1") !=
|
||||
std::string::npos &&
|
||||
sess.target_output().find("i=1 x=3 sum=4") != std::string::npos;
|
||||
// Hit count from gdb: a conditional breakpoint counts stops
|
||||
// only (reaches with a false condition are not hits) -> 1.
|
||||
ok = ok && sess.refresh_breakpoints(err);
|
||||
int hits = -1;
|
||||
for (const auto& b : sess.breakpoints())
|
||||
if (b.line == L_LOOP) hits = b.hits;
|
||||
ok = ok && hits == 1;
|
||||
ok = ok && sess.cont(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Exited;
|
||||
report("bp_conditional_only_when_true", ok,
|
||||
"i=" + v + " hits=" + std::to_string(hits));
|
||||
}
|
||||
// 32. ignore count: first 2 hits skipped, stops on the 3rd (i == 2)
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
Breakpoint opts;
|
||||
opts.ignore_count = 2;
|
||||
bool ok = sess.stage_breakpoint_opts(loc(src, L_LOOP), opts);
|
||||
ok = ok && sess.start(console, "", err);
|
||||
ok = ok && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().frame.line == L_LOOP;
|
||||
std::string v, e;
|
||||
ok = ok && sess.evaluate("i", v, e) && v == "2";
|
||||
ok = ok && sess.target_output().find("i=0 x=1 sum=1") !=
|
||||
std::string::npos &&
|
||||
sess.target_output().find("i=1 x=3 sum=4") != std::string::npos;
|
||||
// gdb counts every reach, ignored or not, in `times` -> 3.
|
||||
ok = ok && sess.refresh_breakpoints(err);
|
||||
int hits = -1;
|
||||
for (const auto& b : sess.breakpoints())
|
||||
if (b.line == L_LOOP) hits = b.hits;
|
||||
ok = ok && hits == 3;
|
||||
ok = ok && sess.cont(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Exited;
|
||||
report("bp_ignore_count_skips", ok,
|
||||
"i=" + v + " hits=" + std::to_string(hits));
|
||||
}
|
||||
// 33. logpoint: prints its message at every hit, never stops
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
Breakpoint opts;
|
||||
opts.kind = BpKind::Logpoint;
|
||||
opts.log_message = "LOG i={i}";
|
||||
bool ok = sess.stage_breakpoint_opts(loc(src, L_LOOP), opts);
|
||||
ok = ok && sess.start(console, "", err);
|
||||
ok = ok && sess.wait_for_stop(10000);
|
||||
// No stop at all: straight to a clean exit.
|
||||
ok = ok && sess.state() == DbgState::Exited &&
|
||||
sess.exit_code() == 0;
|
||||
// dprintf output arrives on gdb's console stream (-> gdb_log()).
|
||||
ok = ok && sess.gdb_log().find("LOG i=0") != std::string::npos &&
|
||||
sess.gdb_log().find("LOG i=1") != std::string::npos &&
|
||||
sess.gdb_log().find("LOG i=2") != std::string::npos;
|
||||
ok = ok && sess.target_output().find("DONE sum=9") !=
|
||||
std::string::npos;
|
||||
report("bp_logpoint_prints_no_stop", ok, sess.gdb_log());
|
||||
}
|
||||
// 34. logpoint template with several placeholders and formats
|
||||
{
|
||||
// Template conversion is pure string work: check it directly.
|
||||
std::string fmt;
|
||||
std::vector<std::string> args;
|
||||
bool ok = logpoint_to_printf("i={i} s={s:name} x={x:v}", fmt, args);
|
||||
ok = ok && fmt == "i=%d s=%s x=%#x\\n" && args.size() == 3 &&
|
||||
args[0] == "i" && args[1] == "name" && args[2] == "v";
|
||||
ok = ok && logpoint_to_printf("100% done", fmt, args) &&
|
||||
fmt == "100%% done\\n" && args.empty();
|
||||
ok = ok && !logpoint_to_printf("oops {i", fmt, args);
|
||||
ok = ok && !logpoint_to_printf("oops {}", fmt, args);
|
||||
// And end to end: two placeholders print at the loop.
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
Breakpoint opts;
|
||||
opts.kind = BpKind::Logpoint;
|
||||
opts.log_message = "LP i={i} sum={sum}";
|
||||
ok = ok && sess.stage_breakpoint_opts(loc(src, L_LOOP), opts);
|
||||
ok = ok && sess.start(console, "", err);
|
||||
ok = ok && sess.wait_for_stop(10000);
|
||||
ok = ok && sess.state() == DbgState::Exited;
|
||||
ok = ok && sess.gdb_log().find("LP i=0 sum=0") != std::string::npos &&
|
||||
sess.gdb_log().find("LP i=2 sum=4") != std::string::npos;
|
||||
report("bp_logpoint_template", ok, sess.gdb_log());
|
||||
}
|
||||
// 35. edit a live breakpoint: plain -> conditional, takes effect
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_LOOP));
|
||||
bool ok = sess.start(console, "", err);
|
||||
ok = ok && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Stopped;
|
||||
std::string v, e;
|
||||
ok = ok && sess.evaluate("i", v, e) && v == "0"; // plain: stops at 0
|
||||
int loop_id = 0;
|
||||
for (const auto& b : sess.breakpoints())
|
||||
if (b.line == L_LOOP) loop_id = b.id;
|
||||
ok = ok && loop_id > 0;
|
||||
Breakpoint upd;
|
||||
upd.kind = BpKind::Conditional;
|
||||
upd.condition = "i == 2";
|
||||
upd.location = loc(src, L_LOOP);
|
||||
Breakpoint out;
|
||||
ok = ok && sess.update_breakpoint(loop_id, upd, out, err);
|
||||
ok = ok && out.kind == BpKind::Conditional &&
|
||||
out.condition == "i == 2";
|
||||
ok = ok && sess.cont(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().frame.line == L_LOOP;
|
||||
ok = ok && sess.evaluate("i", v, e) && v == "2";
|
||||
ok = ok && sess.cont(err) && sess.wait_for_stop();
|
||||
ok = ok && sess.state() == DbgState::Exited;
|
||||
report("bp_update_plain_to_conditional", ok, "i=" + v);
|
||||
}
|
||||
// 36. handler fields persist to disk and load back; old two-field
|
||||
// files still load as plain breakpoints.
|
||||
{
|
||||
GdbSession sess;
|
||||
Breakpoint c;
|
||||
c.kind = BpKind::Conditional;
|
||||
c.condition = "i == 2 || sum > 3"; // exercises | escaping
|
||||
c.group = "loop";
|
||||
Breakpoint l;
|
||||
l.kind = BpKind::Logpoint;
|
||||
l.log_message = "LOG i={i} | sum={sum}";
|
||||
l.group = "trace";
|
||||
Breakpoint p;
|
||||
p.ignore_count = 3;
|
||||
bool ok = sess.stage_breakpoint_opts(loc(src, L_LOOP), c);
|
||||
ok = ok && sess.stage_breakpoint_opts(loc(src, L_HELPER), l);
|
||||
ok = ok && sess.stage_breakpoint_opts("compute", p);
|
||||
ok = ok && sess.save_breakpoints("/tmp/dbgtest_bps2");
|
||||
GdbSession sess2;
|
||||
ok = ok && sess2.load_breakpoints("/tmp/dbgtest_bps2");
|
||||
ok = ok && sess2.breakpoints().size() == 3;
|
||||
if (ok) {
|
||||
const auto& b0 = sess2.breakpoints()[0];
|
||||
const auto& b1 = sess2.breakpoints()[1];
|
||||
const auto& b2 = sess2.breakpoints()[2];
|
||||
ok = b0.kind == BpKind::Conditional &&
|
||||
b0.condition == "i == 2 || sum > 3" && b0.group == "loop" &&
|
||||
b0.file == src && b0.line == L_LOOP &&
|
||||
b1.kind == BpKind::Logpoint &&
|
||||
b1.log_message == "LOG i={i} | sum={sum}" &&
|
||||
b1.group == "trace" && b1.file == src &&
|
||||
b1.line == L_HELPER && b2.kind == BpKind::Plain &&
|
||||
b2.ignore_count == 3 && b2.location == "compute" &&
|
||||
b2.file.empty() && b2.line == 0;
|
||||
}
|
||||
// Old format: location|enabled, nothing else.
|
||||
{
|
||||
std::ofstream f("/tmp/dbgtest_bps_old");
|
||||
f << loc(src, L_LOOP) << "|1\ncompute|0\n";
|
||||
}
|
||||
GdbSession sess3;
|
||||
ok = ok && sess3.load_breakpoints("/tmp/dbgtest_bps_old");
|
||||
ok = ok && sess3.breakpoints().size() == 2 &&
|
||||
sess3.breakpoints()[0].kind == BpKind::Plain &&
|
||||
sess3.breakpoints()[0].enabled &&
|
||||
sess3.breakpoints()[0].file == src &&
|
||||
sess3.breakpoints()[0].line == L_LOOP &&
|
||||
sess3.breakpoints()[1].kind == BpKind::Plain &&
|
||||
!sess3.breakpoints()[1].enabled &&
|
||||
sess3.breakpoints()[1].file.empty();
|
||||
// A bad condition is rejected and leaves no breakpoint behind.
|
||||
{
|
||||
GdbSession s4;
|
||||
std::string e2;
|
||||
s4.start_gdb_only(e2);
|
||||
s4.load_executable(console, e2);
|
||||
Breakpoint bad;
|
||||
bad.kind = BpKind::Conditional;
|
||||
bad.condition = "nosuchvar == 2";
|
||||
Breakpoint out;
|
||||
ok = ok && !s4.add_breakpoint_opts(loc(src, L_LOOP), bad, out,
|
||||
e2) &&
|
||||
!e2.empty() && s4.breakpoints().empty();
|
||||
}
|
||||
report("bp_handlers_persist_roundtrip", ok, "");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- GTK tests (run under xvfb-run) ---------------------------------------
|
||||
|
||||
static void gtk_tests() {
|
||||
std::string app = g_dir + "/gtkapp";
|
||||
std::string src = g_dir + "/gtkapp.cpp";
|
||||
int L_CB = mark_line(src, "MARK:CB");
|
||||
int L_CB_NEXT = mark_line(src, "MARK:CB_NEXT");
|
||||
report("gtk_marks_found", L_CB > 0 && L_CB_NEXT > 0);
|
||||
// 31. breakpoint in the button callback is hit on auto-click
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
sess.stage_breakpoint(loc(src, L_CB));
|
||||
bool ok = sess.start(app, "", err);
|
||||
ok = ok && sess.wait_for_stop(15000);
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().reason == "breakpoint-hit" &&
|
||||
sess.last_stop().frame.function.find("on_clicked") !=
|
||||
std::string::npos &&
|
||||
sess.last_stop().frame.line == L_CB;
|
||||
report("gtk_bp_in_callback", ok,
|
||||
"func=" + sess.last_stop().frame.function +
|
||||
" line=" + std::to_string(sess.last_stop().frame.line) +
|
||||
" reason=" + sess.last_stop().reason);
|
||||
if (ok) {
|
||||
// 32. step through the callback: counter becomes 1. (At the
|
||||
// CB line `before` is still unassigned, so step to the next
|
||||
// line first, where before == 0.)
|
||||
std::string e;
|
||||
bool ok2 = sess.step_over(e) && sess.wait_for_stop();
|
||||
ok2 = ok2 && sess.last_stop().frame.line == L_CB_NEXT;
|
||||
sess.refresh_on_stop();
|
||||
ok2 = ok2 && has(sess.locals(), "before", "0");
|
||||
ok2 = ok2 && sess.step_over(e) && sess.wait_for_stop();
|
||||
std::string v;
|
||||
ok2 = ok2 && sess.evaluate("counter", v, e) && v == "1";
|
||||
report("gtk_step_in_callback", ok2,
|
||||
"before=" + var_value(sess.locals(), "before") +
|
||||
" counter=" + v);
|
||||
// 33. continue: app finishes on its own timer, exit 0
|
||||
bool ok3 = sess.cont(e) && sess.wait_for_stop(15000);
|
||||
ok3 = ok3 && sess.state() == DbgState::Exited &&
|
||||
sess.exit_code() == 0;
|
||||
ok3 = ok3 && sess.target_output().find("CLICKS=1") !=
|
||||
std::string::npos;
|
||||
report("gtk_continue_to_exit", ok3, sess.target_output());
|
||||
} else {
|
||||
report("gtk_step_in_callback", false, "callback bp never hit");
|
||||
report("gtk_continue_to_exit", false, "callback bp never hit");
|
||||
}
|
||||
}
|
||||
// 34. GTK app runs to completion with no breakpoints
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
bool ok = sess.start(app, "", err) && sess.wait_for_stop(15000);
|
||||
ok = ok && sess.state() == DbgState::Exited && sess.exit_code() == 0;
|
||||
ok = ok && sess.target_output().find("CLICKS=1") != std::string::npos;
|
||||
report("gtk_run_to_completion", ok, sess.target_output());
|
||||
}
|
||||
// 35. logpoint in the callback: prints, never stops, app exits 0
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
Breakpoint opts;
|
||||
opts.kind = BpKind::Logpoint;
|
||||
opts.log_message = "CLICK counter={counter}";
|
||||
bool ok = sess.stage_breakpoint_opts(loc(src, L_CB), opts);
|
||||
ok = ok && sess.start(app, "", err);
|
||||
ok = ok && sess.wait_for_stop(15000);
|
||||
ok = ok && sess.state() == DbgState::Exited && sess.exit_code() == 0;
|
||||
ok = ok && sess.target_output().find("CLICKS=1") !=
|
||||
std::string::npos;
|
||||
// At the callback entry counter is still 0 (the click has not
|
||||
// been counted yet); the dprintf output is on gdb's console
|
||||
// stream (-> gdb_log()).
|
||||
ok = ok && sess.gdb_log().find("CLICK counter=0") !=
|
||||
std::string::npos;
|
||||
report("gtk_logpoint_no_stop", ok, sess.gdb_log());
|
||||
}
|
||||
// 36. conditional breakpoint in the callback: fires when counter == 0
|
||||
{
|
||||
GdbSession sess;
|
||||
std::string err;
|
||||
Breakpoint opts;
|
||||
opts.kind = BpKind::Conditional;
|
||||
opts.condition = "counter == 0";
|
||||
bool ok = sess.stage_breakpoint_opts(loc(src, L_CB), opts);
|
||||
ok = ok && sess.start(app, "", err);
|
||||
ok = ok && sess.wait_for_stop(15000);
|
||||
ok = ok && sess.state() == DbgState::Stopped &&
|
||||
sess.last_stop().reason == "breakpoint-hit" &&
|
||||
sess.last_stop().frame.line == L_CB;
|
||||
ok = ok && sess.cont(err) && sess.wait_for_stop(15000);
|
||||
ok = ok && sess.state() == DbgState::Exited && sess.exit_code() == 0;
|
||||
ok = ok && sess.target_output().find("CLICKS=1") !=
|
||||
std::string::npos;
|
||||
report("gtk_conditional_in_callback", ok,
|
||||
"reason=" + sess.last_stop().reason);
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 3) {
|
||||
std::fprintf(stderr, "usage: %s console|gtk <tests/debugger dir>\n",
|
||||
argv[0]);
|
||||
return 2;
|
||||
}
|
||||
g_dir = argv[2];
|
||||
if (!std::strcmp(argv[1], "console")) console_tests();
|
||||
else if (!std::strcmp(argv[1], "gtk")) gtk_tests();
|
||||
else {
|
||||
std::fprintf(stderr, "unknown mode %s\n", argv[1]);
|
||||
return 2;
|
||||
}
|
||||
std::printf("SUMMARY pass=%d fail=%d\n", g_pass, g_fail);
|
||||
if (!g_failed.empty()) {
|
||||
std::printf("FAILED:");
|
||||
for (const auto& f : g_failed) std::printf(" %s", f.c_str());
|
||||
std::printf("\n");
|
||||
}
|
||||
return g_fail == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
// Debugger test target: small GTK app with a button callback.
|
||||
// The button auto-clicks itself 800 ms after startup (so the test can
|
||||
// drive it headlessly under Xvfb), and the app quits 4 s after startup.
|
||||
// Compile with: g++ -g -O0 -o gtkapp gtkapp.cpp $(pkg-config --cflags --libs gtk+-3.0)
|
||||
#include <gtk/gtk.h>
|
||||
#include <cstdio>
|
||||
|
||||
static int counter = 0;
|
||||
static GtkWidget* label = nullptr;
|
||||
static GtkWidget* button = nullptr;
|
||||
|
||||
static void on_clicked(GtkButton*, gpointer) {
|
||||
int before = counter; // MARK:CB
|
||||
counter = before + 1; // MARK:CB_NEXT
|
||||
char buf[64];
|
||||
std::snprintf(buf, sizeof buf, "Clicks: %d", counter);
|
||||
gtk_label_set_text(GTK_LABEL(label), buf);
|
||||
}
|
||||
|
||||
static gboolean auto_click(gpointer) {
|
||||
gtk_button_clicked(GTK_BUTTON(button));
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
|
||||
static gboolean quit_app(gpointer) {
|
||||
gtk_main_quit();
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
gtk_init(&argc, &argv);
|
||||
GtkWidget* win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
|
||||
gtk_window_set_title(GTK_WINDOW(win), "Debugger GTK Test");
|
||||
gtk_window_set_default_size(GTK_WINDOW(win), 300, 120);
|
||||
g_signal_connect(win, "destroy", G_CALLBACK(gtk_main_quit), nullptr);
|
||||
GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
|
||||
gtk_container_add(GTK_CONTAINER(win), box);
|
||||
label = gtk_label_new("Clicks: 0");
|
||||
gtk_box_pack_start(GTK_BOX(box), label, TRUE, TRUE, 0);
|
||||
button = gtk_button_new_with_label("Click me");
|
||||
g_signal_connect(button, "clicked", G_CALLBACK(on_clicked), nullptr);
|
||||
gtk_box_pack_start(GTK_BOX(box), button, TRUE, TRUE, 0);
|
||||
gtk_widget_show_all(win);
|
||||
g_timeout_add(800, auto_click, nullptr);
|
||||
g_timeout_add(4000, quit_app, nullptr);
|
||||
gtk_main();
|
||||
std::printf("CLICKS=%d\n", counter);
|
||||
std::fflush(stdout);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
// Debugger test target: never exits on its own (kill/restart tests).
|
||||
// Compile with: g++ -g -O0 -o spin spin.cpp
|
||||
#include <cstdio>
|
||||
int main() {
|
||||
volatile long n = 0;
|
||||
std::printf("SPINNING\n");
|
||||
std::fflush(stdout);
|
||||
while (1) {
|
||||
n++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
#!/bin/sh
|
||||
# FDesigner debugger test suite.
|
||||
# tests/debugger_tests.sh [--no-gui]
|
||||
# Builds the console + GTK test targets and the headless harness, runs the
|
||||
# console suite, the GTK suite under Xvfb, and a GUI smoke test (the real
|
||||
# fdesigner opens its debugger window and the Settings dialog path is
|
||||
# exercised through the Debug menu ids in ui/designer.ui).
|
||||
# Prints a PASS/FAIL summary; exits non-zero if anything fails.
|
||||
# Run from the repo root.
|
||||
set -u
|
||||
ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
D="$ROOT/tests/debugger"
|
||||
WORK="$D/work"
|
||||
mkdir -p "$WORK"
|
||||
FAIL=0
|
||||
|
||||
say() { printf '%s\n' "$*"; }
|
||||
|
||||
# --- build test targets ----------------------------------------------------
|
||||
say "== building debugger test targets =="
|
||||
cp "$D/console.cpp" "$WORK/console.cpp"
|
||||
cp "$D/spin.cpp" "$WORK/spin.cpp"
|
||||
cp "$D/gtkapp.cpp" "$WORK/gtkapp.cpp"
|
||||
# Compile from the work-dir paths so DWARF records the same absolute
|
||||
# source paths the harness uses for file:line breakpoints.
|
||||
g++ -g -O0 -o "$WORK/console" "$WORK/console.cpp" || FAIL=1
|
||||
g++ -g -O0 -o "$WORK/spin" "$WORK/spin.cpp" || FAIL=1
|
||||
g++ -g -O0 -o "$WORK/gtkapp" "$WORK/gtkapp.cpp" $(pkg-config --cflags --libs gtk+-3.0) || FAIL=1
|
||||
g++ -O2 -Wall -Wextra -std=c++17 -o "$WORK/dbg_harness" "$D/dbg_harness.cpp" "$ROOT/src/debugger.cpp" || FAIL=1
|
||||
# fdesigner itself (with the debugger window) must build clean
|
||||
(cd "$ROOT" && make >/tmp/dbg_make.log 2>&1) || { say "FAIL fdesigner build"; cat /tmp/dbg_make.log; FAIL=1; }
|
||||
|
||||
if [ "$FAIL" != "0" ]; then say "BUILD FAILED"; exit 1; fi
|
||||
|
||||
# --- console suite ---------------------------------------------------------
|
||||
say "== console debugger suite =="
|
||||
"$WORK/dbg_harness" console "$WORK" > "$WORK/console.log" 2>&1
|
||||
RC=$?
|
||||
cat "$WORK/console.log"
|
||||
[ "$RC" != "0" ] && FAIL=1
|
||||
|
||||
# --- GTK suite (needs X) ---------------------------------------------------
|
||||
say "== GTK debugger suite (under Xvfb) =="
|
||||
xvfb-run -a "$WORK/dbg_harness" gtk "$WORK" > "$WORK/gtk.log" 2>&1
|
||||
RC=$?
|
||||
cat "$WORK/gtk.log"
|
||||
[ "$RC" != "0" ] && FAIL=1
|
||||
|
||||
# --- GUI smoke test --------------------------------------------------------
|
||||
if [ "${1:-}" != "--no-gui" ]; then
|
||||
say "== GUI smoke test: fdesigner + debugger window =="
|
||||
# Debug menu + Debugger sub-menu ids must exist in the .ui
|
||||
for id in menu_debug mi_debug_open mi_dbg_settings mi_debug_settings \
|
||||
menu_debugger_sub mi_dbg_break_main mi_dbg_stop_entry mi_dbg_pretty; do
|
||||
grep -q "id=\"$id\"" "$ROOT/ui/designer.ui" || { say "FAIL ui missing id $id"; FAIL=1; }
|
||||
done
|
||||
say "ui menu ids present"
|
||||
# Launch fdesigner on a fixed Xvfb display with the debugger window
|
||||
# auto-opened, then verify the window exists via xdotool.
|
||||
Xvfb :99 -screen 0 1280x900x24 >/dev/null 2>&1 &
|
||||
XVPID=$!
|
||||
sleep 2
|
||||
(cd "$ROOT" && DISPLAY=:99 FDESIGNER_OPEN_DEBUGGER=1 timeout 25 ./fdesigner >"$WORK/gui.log" 2>&1) &
|
||||
APID=$!
|
||||
OK=0
|
||||
for i in $(seq 1 20); do
|
||||
sleep 1
|
||||
if DISPLAY=:99 xdotool search --name "FDesigner Debugger" >/dev/null 2>&1; then OK=1; break; fi
|
||||
done
|
||||
if [ "$OK" = "1" ]; then
|
||||
DISPLAY=:99 xdotool search --name "FDesigner Debugger" getwindowname %@ 2>/dev/null | head -3
|
||||
# Screenshot for the record (xwd if present, else skip gracefully).
|
||||
if command -v xwd >/dev/null 2>&1; then
|
||||
DISPLAY=:99 xwd -root -silent -out "$WORK/debugger_window.xwd" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
kill $APID 2>/dev/null
|
||||
pkill -x fdesigner 2>/dev/null
|
||||
wait $APID 2>/dev/null
|
||||
if [ "$OK" = "1" ]; then say "PASS gui_debugger_window_opens"; else say "FAIL gui_debugger_window_opens"; cat "$WORK/gui.log"; FAIL=1; fi
|
||||
# Settings dialog: launch with the settings hook and look for its window.
|
||||
(cd "$ROOT" && DISPLAY=:99 FDESIGNER_OPEN_DEBUGGER_SETTINGS=1 timeout 25 ./fdesigner >"$WORK/gui_settings.log" 2>&1) &
|
||||
APID=$!
|
||||
OK2=0
|
||||
for i in $(seq 1 20); do
|
||||
sleep 1
|
||||
if DISPLAY=:99 xdotool search --name "Debugger Settings" >/dev/null 2>&1; then OK2=1; break; fi
|
||||
done
|
||||
kill $APID 2>/dev/null
|
||||
pkill -x fdesigner 2>/dev/null
|
||||
wait $APID 2>/dev/null
|
||||
kill $XVPID 2>/dev/null
|
||||
if [ "$OK2" = "1" ]; then say "PASS gui_debugger_settings_dialog_opens"; else say "FAIL gui_debugger_settings_dialog_opens"; cat "$WORK/gui_settings.log"; FAIL=1; fi
|
||||
fi
|
||||
|
||||
say "== debugger_tests.sh: $([ "$FAIL" = 0 ] && echo ALL PASS || echo FAILURES PRESENT) =="
|
||||
exit $FAIL
|
||||
@@ -1,155 +0,0 @@
|
||||
// Unit + render test for the drawings.h annotation module: every
|
||||
// kind parses from its spec and draws visible ink in its palette
|
||||
// colour; a trend line re-maps correctly when the plot size changes
|
||||
// (resize safety, since anchors are data coordinates); hit testing
|
||||
// finds lines and misses empty space.
|
||||
#include <cairo.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include "drawings.h"
|
||||
|
||||
static long count_ink(cairo_surface_t* surf, int ci) {
|
||||
const double* col = fdw::kPalette[ci];
|
||||
int w = cairo_image_surface_get_width(surf);
|
||||
int h = cairo_image_surface_get_height(surf);
|
||||
int stride = cairo_image_surface_get_stride(surf);
|
||||
unsigned char* d = cairo_image_surface_get_data(surf);
|
||||
long n = 0;
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x) {
|
||||
unsigned char* px = d + y * stride + x * 4; // BGRA
|
||||
double r = px[2] / 255.0, g = px[1] / 255.0, b = px[0] / 255.0;
|
||||
double dr = r - col[0], dg = g - col[1], db = b - col[2];
|
||||
if (dr * dr + dg * dg + db * db < 0.09) ++n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static long count_dark(cairo_surface_t* surf) {
|
||||
int w = cairo_image_surface_get_width(surf);
|
||||
int h = cairo_image_surface_get_height(surf);
|
||||
int stride = cairo_image_surface_get_stride(surf);
|
||||
unsigned char* d = cairo_image_surface_get_data(surf);
|
||||
long n = 0;
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x) {
|
||||
unsigned char* px = d + y * stride + x * 4;
|
||||
if (px[0] < 90 && px[1] < 90 && px[2] < 90) ++n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// Ink of palette colour ci within a small box around (cx, cy).
|
||||
static long ink_near(cairo_surface_t* surf, int ci, double cx, double cy) {
|
||||
const double* col = fdw::kPalette[ci];
|
||||
int stride = cairo_image_surface_get_stride(surf);
|
||||
unsigned char* d = cairo_image_surface_get_data(surf);
|
||||
long n = 0;
|
||||
for (int y = (int)cy - 6; y <= (int)cy + 6; ++y)
|
||||
for (int x = (int)cx - 6; x <= (int)cx + 6; ++x) {
|
||||
if (x < 0 || y < 0) continue;
|
||||
unsigned char* px = d + y * stride + x * 4;
|
||||
double r = px[2] / 255.0, g = px[1] / 255.0, b = px[0] / 255.0;
|
||||
double dr = r - col[0], dg = g - col[1], db = b - col[2];
|
||||
if (dr * dr + dg * dg + db * db < 0.09) ++n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = 0;
|
||||
auto check = [&](bool cond, const char* what) {
|
||||
std::printf("%s %s\n", cond ? "OK " : "FAIL", what);
|
||||
if (!cond) ++fails;
|
||||
};
|
||||
fdw::Map map;
|
||||
map.x = 0;
|
||||
map.y = 0;
|
||||
map.w = 480;
|
||||
map.h = 300;
|
||||
map.begin = 0;
|
||||
map.count = 100;
|
||||
map.lo = 90;
|
||||
map.hi = 110;
|
||||
|
||||
struct Case {
|
||||
const char* spec;
|
||||
int color; // palette index, or -1 for dark-text check
|
||||
};
|
||||
const Case cases[] = {
|
||||
{"trend 5 95 90 108 red", 1},
|
||||
{"ray 5 95 20 100 orange", 3},
|
||||
{"hline 105 blue", 0},
|
||||
{"vline 50 green", 2},
|
||||
{"rect 10 96 60 106 teal", 5},
|
||||
{"ellipse 10 96 60 106 purple", 4},
|
||||
{"arrow 5 95 90 108 magenta", 6},
|
||||
{"text 10 100 black Hello chart", -1},
|
||||
{"fib 5 95 90 108 brown", 7},
|
||||
{"free 5 95 30 108 60 97 90 104 slate", 9},
|
||||
{"measure 5 95 90 108 red", 1},
|
||||
};
|
||||
for (const Case& c : cases) {
|
||||
auto d = fdw::parse_spec(c.spec);
|
||||
check(d.has_value(), c.spec);
|
||||
if (!d) continue;
|
||||
cairo_surface_t* surf =
|
||||
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 480, 300);
|
||||
cairo_t* cr = cairo_create(surf);
|
||||
cairo_set_source_rgb(cr, 1, 1, 1);
|
||||
cairo_paint(cr);
|
||||
fdw::draw(cr, map, *d);
|
||||
cairo_destroy(cr);
|
||||
cairo_surface_flush(surf);
|
||||
long ink = c.color >= 0 ? count_ink(surf, c.color) : count_dark(surf);
|
||||
std::printf(" ink=%ld\n", ink);
|
||||
check(ink > 15, " draws ink");
|
||||
cairo_surface_destroy(surf);
|
||||
}
|
||||
|
||||
// Resize safety: the same trend line rendered at 480x300 and at
|
||||
// 960x600 must put ink at the scaled endpoint positions.
|
||||
auto trend = fdw::parse_spec("trend 10 95 90 108 red");
|
||||
check(trend.has_value(), "resize trend parses");
|
||||
for (double scale : {1.0, 2.0}) {
|
||||
int W = (int)(480 * scale), H = (int)(300 * scale);
|
||||
fdw::Map m2 = map;
|
||||
m2.w = W;
|
||||
m2.h = H;
|
||||
cairo_surface_t* surf =
|
||||
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, W, H);
|
||||
cairo_t* cr = cairo_create(surf);
|
||||
cairo_set_source_rgb(cr, 1, 1, 1);
|
||||
cairo_paint(cr);
|
||||
fdw::draw(cr, m2, *trend);
|
||||
cairo_destroy(cr);
|
||||
cairo_surface_flush(surf);
|
||||
double x1 = m2.px(10), y1 = m2.py(95);
|
||||
double x2 = m2.px(90), y2 = m2.py(108);
|
||||
long a = ink_near(surf, 1, x1, y1);
|
||||
long b = ink_near(surf, 1, x2, y2);
|
||||
std::printf(" scale=%.0f endpoints ink=%ld/%ld\n", scale, a, b);
|
||||
check(a > 2 && b > 2, " endpoints remapped");
|
||||
cairo_surface_destroy(surf);
|
||||
}
|
||||
|
||||
// Hit testing: on the line / off the line.
|
||||
{
|
||||
double mx = map.px(47.5), my = map.py(101.5);
|
||||
check(fdw::hit_test(map, *trend, mx, my), "hit on trend midpoint");
|
||||
check(!fdw::hit_test(map, *trend, map.px(47.5), map.py(92)),
|
||||
"miss away from trend");
|
||||
auto hl = fdw::parse_spec("hline 105 blue");
|
||||
check(hl && fdw::hit_test(map, *hl, 200, map.py(105)),
|
||||
"hit on hline");
|
||||
check(hl && !fdw::hit_test(map, *hl, 200, map.py(100)),
|
||||
"miss away from hline");
|
||||
}
|
||||
|
||||
std::printf("DRAWINGS TEST %s (%d failures)\n",
|
||||
fails ? "FAIL" : "PASS", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
// Runtime event harness: instantiate every generated widget class,
|
||||
// trigger each connected signal through the GTK API, and check the EVENT
|
||||
// trace lines the stubs print to stderr. The shell script runs this under
|
||||
// Xvfb with stderr redirected to argv[1]; the harness reads that file
|
||||
// back and prints a per-widget pass/fail table to stdout.
|
||||
// Usage: event_handler_runtime <event-log-path>
|
||||
// (Compile with -DFDESIGNER_EVENT_TRACE and -I <generated dir>, linking
|
||||
// the generated widget .cpp files except main.cpp.)
|
||||
#include <gtk/gtk.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "Button_001.h"
|
||||
#include "Label_001.h"
|
||||
#include "Entry_001.h"
|
||||
#include "Checkbutton_001.h"
|
||||
#include "Radiobutton_001.h"
|
||||
#include "Frame_001.h"
|
||||
#include "Combobox_001.h"
|
||||
#include "Listbox_001.h"
|
||||
#include "Menubutton_001.h"
|
||||
#include "Canvas_001.h"
|
||||
#include "Scale_001.h"
|
||||
#include "Scrollbar_001.h"
|
||||
#include "Text_001.h"
|
||||
#include "Toplevel_001.h"
|
||||
#include "Spreadsheet_001.h"
|
||||
#include "StockChart_001.h"
|
||||
#include "Memo_001.h"
|
||||
#include "GroupBox_001.h"
|
||||
#include "Panel_001.h"
|
||||
#include "Image_001.h"
|
||||
#include "Shape_001.h"
|
||||
#include "Notebook_001.h"
|
||||
#include "ScrollBox_001.h"
|
||||
#include "Splitter_001.h"
|
||||
#include "StatusBar_001.h"
|
||||
#include "ToolBar_001.h"
|
||||
#include "MenuBar_001.h"
|
||||
#include "SpinEdit_001.h"
|
||||
#include "TrackBar_001.h"
|
||||
#include "ProgressBar_001.h"
|
||||
#include "DateTimePicker_001.h"
|
||||
#include "ColorBox_001.h"
|
||||
#include "ListView_001.h"
|
||||
#include "TreeView_001.h"
|
||||
#include "StringGrid_001.h"
|
||||
#include "Plot_001.h"
|
||||
|
||||
static void pump() {
|
||||
while (gtk_events_pending()) gtk_main_iteration();
|
||||
}
|
||||
|
||||
struct Expect {
|
||||
const char* type;
|
||||
const char* signal; // "" = no-events type (pass by design)
|
||||
const char* line; // substring to find in the trace log
|
||||
};
|
||||
|
||||
static const Expect kExpect[] = {
|
||||
{"Button", "clicked", "EVENT Button_001 clicked"},
|
||||
{"Entry", "changed", "EVENT Entry_001 changed"},
|
||||
{"Entry", "activate", "EVENT Entry_001 activate"},
|
||||
{"Checkbutton", "toggled", "EVENT Checkbutton_001 toggled"},
|
||||
{"Radiobutton", "toggled", "EVENT Radiobutton_001 toggled"},
|
||||
{"Combobox", "changed", "EVENT Combobox_001 changed"},
|
||||
{"Listbox", "row-selected", "EVENT Listbox_001 row-selected"},
|
||||
{"Menubutton", "clicked", "EVENT Menubutton_001 clicked"},
|
||||
{"Canvas", "draw", "EVENT Canvas_001 draw"},
|
||||
{"Scale", "value-changed", "EVENT Scale_001 value-changed"},
|
||||
{"Scrollbar", "value-changed", "EVENT Scrollbar_001 value-changed"},
|
||||
{"Text", "changed", "EVENT Text_001 changed"},
|
||||
{"Toplevel", "delete-event", "EVENT Toplevel_001 delete-event"},
|
||||
{"Spreadsheet", "changed", "EVENT Spreadsheet_001 changed"},
|
||||
{"StockChart", "draw", "EVENT StockChart_001 draw"},
|
||||
{"Memo", "changed", "EVENT Memo_001 changed"},
|
||||
{"Shape", "draw", "EVENT Shape_001 draw"},
|
||||
{"Notebook", "switch-page", "EVENT Notebook_001 switch-page"},
|
||||
{"ToolBar", "clicked", "EVENT ToolBar_001 clicked"},
|
||||
{"MenuBar", "activate", "EVENT MenuBar_001 activate"},
|
||||
{"SpinEdit", "value-changed", "EVENT SpinEdit_001 value-changed"},
|
||||
{"TrackBar", "value-changed", "EVENT TrackBar_001 value-changed"},
|
||||
{"DateTimePicker", "day-selected",
|
||||
"EVENT DateTimePicker_001 day-selected"},
|
||||
{"DateTimePicker", "month-changed",
|
||||
"EVENT DateTimePicker_001 month-changed"},
|
||||
{"ColorBox", "color-set", "EVENT ColorBox_001 color-set"},
|
||||
{"ListView", "row-activated", "EVENT ListView_001 row-activated"},
|
||||
{"ListView", "cursor-changed", "EVENT ListView_001 cursor-changed"},
|
||||
{"TreeView", "row-activated", "EVENT TreeView_001 row-activated"},
|
||||
{"TreeView", "cursor-changed", "EVENT TreeView_001 cursor-changed"},
|
||||
{"StringGrid", "row-activated", "EVENT StringGrid_001 row-activated"},
|
||||
{"StringGrid", "cursor-changed", "EVENT StringGrid_001 cursor-changed"},
|
||||
{"Plot", "draw", "EVENT Plot_001 draw"},
|
||||
// No natural signal — pass by design, with the explicit note.
|
||||
{"Label", "", ""},
|
||||
{"Frame", "", ""},
|
||||
{"GroupBox", "", ""},
|
||||
{"Panel", "", ""},
|
||||
{"Image", "", ""},
|
||||
{"ScrollBox", "", ""},
|
||||
{"Splitter", "", ""},
|
||||
{"StatusBar", "", ""},
|
||||
{"ProgressBar", "", ""},
|
||||
};
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
gtk_init(&argc, &argv);
|
||||
std::string log_path = argc > 1 ? argv[1] : "/tmp/event_trace.log";
|
||||
|
||||
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
|
||||
GtkWidget* fixed = gtk_fixed_new();
|
||||
gtk_container_add(GTK_CONTAINER(window), fixed);
|
||||
|
||||
Button_001 btn(fixed);
|
||||
Label_001 lbl(fixed);
|
||||
Entry_001 ent(fixed);
|
||||
Checkbutton_001 chk(fixed);
|
||||
Radiobutton_001 radio(fixed);
|
||||
Frame_001 frm(fixed);
|
||||
Combobox_001 combo(fixed);
|
||||
Listbox_001 lbox(fixed);
|
||||
Menubutton_001 mbtn(fixed);
|
||||
Canvas_001 canvas(fixed);
|
||||
Scale_001 scale(fixed);
|
||||
Scrollbar_001 sbar(fixed);
|
||||
Text_001 text(fixed);
|
||||
Toplevel_001 top; // own window; not shown
|
||||
Spreadsheet_001 sheet(fixed);
|
||||
StockChart_001 chart(fixed);
|
||||
Memo_001 memo(fixed);
|
||||
GroupBox_001 gbox(fixed);
|
||||
Panel_001 panel(fixed);
|
||||
Image_001 img(fixed);
|
||||
Shape_001 shape(fixed);
|
||||
Notebook_001 nb(fixed);
|
||||
ScrollBox_001 sbox(fixed);
|
||||
Splitter_001 split(fixed);
|
||||
StatusBar_001 status(fixed);
|
||||
ToolBar_001 tbar(fixed);
|
||||
MenuBar_001 mbar(fixed);
|
||||
SpinEdit_001 spin(fixed);
|
||||
TrackBar_001 track(fixed);
|
||||
ProgressBar_001 prog(fixed);
|
||||
DateTimePicker_001 dtp(fixed);
|
||||
ColorBox_001 cbox(fixed);
|
||||
ListView_001 lview(fixed);
|
||||
TreeView_001 tview(fixed);
|
||||
StringGrid_001 grid(fixed);
|
||||
Plot_001 plot(fixed);
|
||||
|
||||
gtk_widget_show_all(window);
|
||||
pump();
|
||||
|
||||
// No-events widgets are constructed (they must build + run) but have
|
||||
// no signal to trigger; keep the build warning-free.
|
||||
(void)lbl.widget();
|
||||
(void)frm.widget();
|
||||
(void)gbox.widget();
|
||||
(void)panel.widget();
|
||||
(void)img.widget();
|
||||
(void)sbox.widget();
|
||||
(void)split.widget();
|
||||
(void)status.widget();
|
||||
(void)prog.widget();
|
||||
|
||||
// --- trigger every signal through the GTK API ---
|
||||
gtk_button_clicked(GTK_BUTTON(btn.widget()));
|
||||
gtk_entry_set_text(GTK_ENTRY(ent.widget()), "hello");
|
||||
g_signal_emit_by_name(ent.widget(), "activate");
|
||||
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(chk.widget()), TRUE);
|
||||
// A lone radio button can never leave its group active: GTK keeps
|
||||
// the sole member on (set_active(FALSE) and clicking are both
|
||||
// no-ops). Toggle it by activating a second button in its group.
|
||||
{
|
||||
GtkWidget* radio2 = gtk_radio_button_new_with_label_from_widget(
|
||||
GTK_RADIO_BUTTON(radio.widget()), "Radiobutton_002");
|
||||
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(radio2), TRUE);
|
||||
}
|
||||
gtk_combo_box_set_active(GTK_COMBO_BOX(combo.widget()), 1);
|
||||
{
|
||||
GtkListBoxRow* row = gtk_list_box_get_row_at_index(
|
||||
GTK_LIST_BOX(lbox.widget()), 0);
|
||||
gtk_list_box_select_row(GTK_LIST_BOX(lbox.widget()), row);
|
||||
}
|
||||
gtk_button_clicked(GTK_BUTTON(mbtn.widget()));
|
||||
gtk_range_set_value(GTK_RANGE(scale.widget()), 42.0);
|
||||
gtk_range_set_value(GTK_RANGE(sbar.widget()), 55.0);
|
||||
gtk_text_buffer_set_text(
|
||||
gtk_text_view_get_buffer(GTK_TEXT_VIEW(text.widget())), "hi", -1);
|
||||
{
|
||||
GdkEvent* ev = gdk_event_new(GDK_DELETE);
|
||||
gboolean ret = FALSE;
|
||||
g_signal_emit_by_name(top.widget(), "delete-event", ev, &ret);
|
||||
gdk_event_free(ev);
|
||||
}
|
||||
{
|
||||
GList* kids =
|
||||
gtk_container_get_children(GTK_CONTAINER(sheet.widget()));
|
||||
if (kids) {
|
||||
gtk_entry_set_text(GTK_ENTRY(kids->data), "9");
|
||||
g_list_free(kids);
|
||||
}
|
||||
}
|
||||
gtk_text_buffer_set_text(
|
||||
gtk_text_view_get_buffer(GTK_TEXT_VIEW(memo.widget())), "memo", -1);
|
||||
gtk_notebook_set_current_page(GTK_NOTEBOOK(nb.widget()), 1);
|
||||
{
|
||||
GList* kids =
|
||||
gtk_container_get_children(GTK_CONTAINER(tbar.widget()));
|
||||
if (kids) {
|
||||
g_signal_emit_by_name(kids->data, "clicked");
|
||||
g_list_free(kids);
|
||||
}
|
||||
}
|
||||
{
|
||||
GList* kids =
|
||||
gtk_container_get_children(GTK_CONTAINER(mbar.widget()));
|
||||
if (kids) {
|
||||
g_signal_emit_by_name(kids->data, "activate");
|
||||
g_list_free(kids);
|
||||
}
|
||||
}
|
||||
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spin.widget()), 7.0);
|
||||
gtk_range_set_value(GTK_RANGE(track.widget()), 33.0);
|
||||
gtk_calendar_select_day(GTK_CALENDAR(dtp.widget()), 15);
|
||||
gtk_calendar_select_month(GTK_CALENDAR(dtp.widget()), 5, 2026);
|
||||
g_signal_emit_by_name(cbox.widget(), "color-set");
|
||||
auto trigger_tree = [](GtkWidget* tv) {
|
||||
GtkTreePath* path = gtk_tree_path_new_from_string("0");
|
||||
gtk_tree_view_set_cursor(GTK_TREE_VIEW(tv), path, nullptr, FALSE);
|
||||
GtkTreeViewColumn* col = gtk_tree_view_get_column(
|
||||
GTK_TREE_VIEW(tv), 0);
|
||||
g_signal_emit_by_name(tv, "row-activated", path, col);
|
||||
gtk_tree_path_free(path);
|
||||
};
|
||||
trigger_tree(lview.widget());
|
||||
trigger_tree(tview.widget());
|
||||
trigger_tree(grid.widget());
|
||||
// Draw events need a main-loop pass after the expose is queued.
|
||||
gtk_widget_queue_draw(canvas.widget());
|
||||
gtk_widget_queue_draw(chart.widget());
|
||||
gtk_widget_queue_draw(shape.widget());
|
||||
gtk_widget_queue_draw(plot.widget());
|
||||
pump();
|
||||
|
||||
// --- read the trace log back and score it ---
|
||||
std::ifstream in(log_path);
|
||||
std::string log((std::istreambuf_iterator<char>(in)),
|
||||
std::istreambuf_iterator<char>());
|
||||
int pass = 0, fail = 0;
|
||||
for (const Expect& e : kExpect) {
|
||||
if (e.signal[0] == '\0') {
|
||||
std::printf("PASS %-16s (no events — by design)\n", e.type);
|
||||
++pass;
|
||||
continue;
|
||||
}
|
||||
if (log.find(e.line) != std::string::npos) {
|
||||
std::printf("PASS %-16s %s\n", e.type, e.signal);
|
||||
++pass;
|
||||
} else {
|
||||
std::printf("FAIL %-16s %s: no \"%s\" in trace log\n", e.type,
|
||||
e.signal, e.line);
|
||||
++fail;
|
||||
}
|
||||
}
|
||||
std::printf("== event_handler_runtime: %d passed, %d failed ==\n", pass,
|
||||
fail);
|
||||
return fail ? 1 : 0;
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
// Event handler tests: one project holding every widget type with every
|
||||
// natural signal connected; generate it and check per-widget markers in
|
||||
// the emitted code — a handler declaration in <Name>.h, a g_signal_connect
|
||||
// for the signal in <Name>.cpp, and the stub definition (with its EVENT
|
||||
// trace line). Types with no natural signal must emit no event stubs.
|
||||
// The companion shell script (tests/event_handler_tests.sh) compiles the
|
||||
// generated app and runs the runtime harness, which triggers each signal
|
||||
// for real. Usage: event_handler_tests [out_dir]
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../src/events.h"
|
||||
#include "../src/generator.h"
|
||||
#include "../src/model.h"
|
||||
#include "../src/props.h"
|
||||
|
||||
static const char* kEventTypes[] = {
|
||||
"Button", "Label", "Entry", "Checkbutton", "Radiobutton", "Frame",
|
||||
"Combobox", "Listbox", "Menubutton", "Canvas", "Scale", "Scrollbar",
|
||||
"Text", "Toplevel", "Spreadsheet", "StockChart",
|
||||
"Memo", "GroupBox", "Panel", "Image", "Shape", "Notebook",
|
||||
"ScrollBox", "Splitter", "StatusBar", "ToolBar", "MenuBar",
|
||||
"SpinEdit", "TrackBar", "ProgressBar", "DateTimePicker", "ColorBox",
|
||||
"ListView", "TreeView", "StringGrid", "Plot",
|
||||
};
|
||||
|
||||
static std::string read_file(const std::string& path) {
|
||||
std::ifstream f(path);
|
||||
if (!f) return "";
|
||||
return std::string(std::istreambuf_iterator<char>(f),
|
||||
std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
// Count non-overlapping occurrences of needle in haystack.
|
||||
static int count_of(const std::string& hay, const std::string& needle) {
|
||||
int n = 0;
|
||||
size_t pos = 0;
|
||||
while ((pos = hay.find(needle, pos)) != std::string::npos) {
|
||||
++n;
|
||||
pos += needle.size();
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// First item id of a per-item event ("New" -> "new"), "" if not per-item.
|
||||
static std::string first_item_id(const Widget& w, const EventDef& d) {
|
||||
if (d.kind != EventKind::ItemClicked &&
|
||||
d.kind != EventKind::ItemActivate)
|
||||
return "";
|
||||
std::string spec = w.type == "ToolBar"
|
||||
? "New|Open|Save"
|
||||
: "File|Edit|Help";
|
||||
auto bar = spec.find('|');
|
||||
std::string first = spec.substr(0, bar);
|
||||
std::string out;
|
||||
for (unsigned char c : first) {
|
||||
if (std::isalnum(c))
|
||||
out += (char)std::tolower(c);
|
||||
else if (!out.empty() && out.back() != '_')
|
||||
out += '_';
|
||||
}
|
||||
while (!out.empty() && out.back() == '_') out.pop_back();
|
||||
return out.empty() ? "item" : out;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
std::string out = argc > 1 ? argv[1] : "/tmp/fdesigner_events_gen";
|
||||
Project p;
|
||||
p.title = "Event Test";
|
||||
p.class_name = "MyWindow";
|
||||
int i = 0;
|
||||
for (const char* type : kEventTypes) {
|
||||
Widget w;
|
||||
w.name = std::string(type) + "_001";
|
||||
w.type = type;
|
||||
const TypeInfo* t = find_type(type);
|
||||
w.width = t ? t->def_width : 100;
|
||||
w.height = t ? t->def_height : 30;
|
||||
w.x = (i % 6) * 140;
|
||||
w.y = (i / 6) * 110;
|
||||
if (w.type == "ToolBar") w.props["items"] = "New|Open|Save";
|
||||
if (w.type == "MenuBar") w.props["menus"] = "File|Edit|Help";
|
||||
if (w.type == "DateTimePicker") w.props["date"] = "2026-11-25";
|
||||
// Connect every natural signal (builtin draw included: the
|
||||
// generator must wire it exactly once, not twice).
|
||||
for (const EventDef& d : events_for(w.type))
|
||||
w.signals.push_back(d.signal);
|
||||
p.widgets.push_back(w);
|
||||
++i;
|
||||
}
|
||||
|
||||
GenResult gr = generate_project(p, p.widgets, out);
|
||||
if (!gr.ok) {
|
||||
std::printf("FAIL generate: %s\n", gr.error.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int pass = 0, fail = 0;
|
||||
for (const Widget& w : p.widgets) {
|
||||
std::string cpp = read_file(out + "/" + w.name + ".cpp");
|
||||
std::string hdr = read_file(out + "/" + w.name + ".h");
|
||||
std::string why;
|
||||
if (cpp.empty()) why = "missing " + w.name + ".cpp";
|
||||
if (hdr.empty()) why = "missing " + w.name + ".h";
|
||||
const std::vector<EventDef>& evs = events_for(w.type);
|
||||
if (why.empty() && evs.empty()) {
|
||||
// No natural signal: no event stubs at all.
|
||||
if (cpp.find("EVENT ") != std::string::npos)
|
||||
why = "unexpected event stub in " + w.name + ".cpp";
|
||||
}
|
||||
for (const EventDef& d : evs) {
|
||||
if (!why.empty()) break;
|
||||
std::string handler = d.handler + first_item_id(w, d);
|
||||
if (d.kind == EventKind::ItemClicked ||
|
||||
d.kind == EventKind::ItemActivate)
|
||||
handler = std::string(d.handler) + "_" + first_item_id(w, d);
|
||||
std::string sig = "\"" + std::string(d.signal) + "\"";
|
||||
if (hdr.find(handler) == std::string::npos) {
|
||||
why = "no decl " + handler + " in " + w.name + ".h";
|
||||
} else if (cpp.find(sig) == std::string::npos) {
|
||||
why = "no signal " + sig + " in " + w.name + ".cpp";
|
||||
} else if (cpp.find("g_signal_connect") == std::string::npos) {
|
||||
why = "no g_signal_connect in " + w.name + ".cpp";
|
||||
} else if (cpp.find(w.name + "::" + handler) ==
|
||||
std::string::npos) {
|
||||
why = "no stub " + w.name + "::" + handler;
|
||||
} else if (cpp.find("EVENT " + w.name + " " + d.signal) ==
|
||||
std::string::npos) {
|
||||
why = std::string("no EVENT trace for ") + d.signal;
|
||||
}
|
||||
if (d.builtin && why.empty()) {
|
||||
// Builtin draw must be wired exactly once.
|
||||
int n = count_of(cpp, "g_signal_connect");
|
||||
int draws = count_of(cpp, "\"draw\"");
|
||||
if (draws != 1)
|
||||
why = "draw connected " + std::to_string(draws) +
|
||||
" times (want 1)";
|
||||
(void)n;
|
||||
}
|
||||
}
|
||||
if (why.empty()) {
|
||||
std::printf("PASS %-16s %-18s (%zu event%s)\n", w.type.c_str(),
|
||||
w.name.c_str(), evs.size(),
|
||||
evs.size() == 1 ? "" : "s");
|
||||
++pass;
|
||||
} else {
|
||||
std::printf("FAIL %-16s %-18s: %s\n", w.type.c_str(),
|
||||
w.name.c_str(), why.c_str());
|
||||
++fail;
|
||||
}
|
||||
}
|
||||
std::printf("== event_handler_tests: %d passed, %d failed ==\n", pass,
|
||||
fail);
|
||||
return fail ? 1 : 0;
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Event handler tests: designer self-test (Phase 8 connects every signal),
|
||||
# generator-API checks for all 36 widget types (per-widget markers), a
|
||||
# -Wall -Wextra compile of the generated app, and a runtime harness that
|
||||
# triggers every signal through the GTK API under Xvfb and checks the
|
||||
# handler ran (EVENT trace lines). Draw handlers are verified via queued
|
||||
# exposes; ColorBox "color-set" and TreeView "row-activated" have no
|
||||
# programmatic GTK trigger, so the harness emits them by name.
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
pass=0; fail=0; failed=""
|
||||
ok() { echo "PASS $1"; pass=$((pass+1)); }
|
||||
bad() { echo "FAIL $1"; fail=$((fail+1)); failed="$failed $1"; }
|
||||
|
||||
echo "== building fdesigner =="
|
||||
if make > /tmp/events_make.log 2>&1; then ok make; else
|
||||
bad make; cat /tmp/events_make.log; exit 1
|
||||
fi
|
||||
|
||||
echo "== designer self-test (Phase 8: event handlers) =="
|
||||
if FDESIGNER_SELFTEST=1 timeout 60 xvfb-run -a ./fdesigner \
|
||||
> /tmp/events_selftest.log 2>&1; then
|
||||
if grep -q "SELFTEST PASS" /tmp/events_selftest.log; then ok selftest;
|
||||
else bad "selftest(no PASS line)"; tail -20 /tmp/events_selftest.log; fi
|
||||
else
|
||||
bad selftest; tail -20 /tmp/events_selftest.log
|
||||
fi
|
||||
grep -E "GENERATED8" /tmp/events_selftest.log || true
|
||||
|
||||
echo "== event generator test (all 36 widget types) =="
|
||||
if g++ -O2 -Wall -Wextra -std=c++17 -o /tmp/event_handler_tests \
|
||||
tests/event_handler_tests.cpp src/generator.cpp src/cmake_build.cpp src/project_io.cpp; then
|
||||
rm -rf /tmp/fdesigner_events_gen
|
||||
if /tmp/event_handler_tests /tmp/fdesigner_events_gen; then
|
||||
ok event-markers
|
||||
else
|
||||
bad event-markers
|
||||
fi
|
||||
else
|
||||
bad event-tests-build
|
||||
fi
|
||||
|
||||
echo "== compile generated project (all widgets + handlers) =="
|
||||
if (cd /tmp/fdesigner_events_gen && \
|
||||
make CXXFLAGS="-O2 -Wall -Wextra -std=c++17" >build.log 2>&1); then
|
||||
if grep -q "warning" /tmp/fdesigner_events_gen/build.log; then
|
||||
bad "generated-compile(warnings)"
|
||||
grep "warning" /tmp/fdesigner_events_gen/build.log | head
|
||||
else ok generated-compile; fi
|
||||
else
|
||||
bad generated-compile; cat /tmp/fdesigner_events_gen/build.log
|
||||
fi
|
||||
|
||||
echo "== run generated project briefly =="
|
||||
timeout 3 xvfb-run -a /tmp/fdesigner_events_gen/app \
|
||||
> /tmp/fdesigner_events_gen/run.log 2>&1
|
||||
rc=$?
|
||||
if [ $rc -ne 124 ]; then
|
||||
bad "generated-run(exit $rc)"; cat /tmp/fdesigner_events_gen/run.log
|
||||
else
|
||||
badlog=$(grep -E "CRITICAL|WARNING \*\*" \
|
||||
/tmp/fdesigner_events_gen/run.log | grep -v "Could not load a pixbuf" || true)
|
||||
if [ -n "$badlog" ]; then
|
||||
bad "generated-run(runtime warnings)"; echo "$badlog"
|
||||
else ok generated-run; fi
|
||||
fi
|
||||
|
||||
echo "== runtime harness: trigger every signal, check handlers ran =="
|
||||
GEN_SRCS=$(cd /tmp/fdesigner_events_gen && ls *.cpp | grep -v '^main.cpp$')
|
||||
# shellcheck disable=SC2086
|
||||
if g++ -O2 -Wall -Wextra -std=c++17 -DFDESIGNER_EVENT_TRACE \
|
||||
-I/tmp/fdesigner_events_gen -o /tmp/event_handler_runtime \
|
||||
tests/event_handler_runtime.cpp \
|
||||
$(for s in $GEN_SRCS; do echo "/tmp/fdesigner_events_gen/$s"; done) \
|
||||
$(pkg-config --cflags --libs gtk+-3.0) \
|
||||
> /tmp/event_runtime_build.log 2>&1; then
|
||||
if grep -q "warning" /tmp/event_runtime_build.log; then
|
||||
echo "note: harness build warnings (not fatal):"
|
||||
grep "warning" /tmp/event_runtime_build.log | head
|
||||
fi
|
||||
rm -f /tmp/event_trace.log
|
||||
if timeout 30 xvfb-run -a /tmp/event_handler_runtime /tmp/event_trace.log \
|
||||
> /tmp/event_runtime.log 2> /tmp/event_trace.log; then
|
||||
ok event-runtime
|
||||
cat /tmp/event_runtime.log
|
||||
else
|
||||
bad event-runtime; cat /tmp/event_runtime.log
|
||||
fi
|
||||
else
|
||||
bad event-runtime-build; cat /tmp/event_runtime_build.log
|
||||
fi
|
||||
|
||||
echo "== event_handler_tests: $pass passed, $fail failed ==$failed"
|
||||
[ $fail -eq 0 ]
|
||||
@@ -1,136 +0,0 @@
|
||||
// Font settings test harness — exercises src/preferences.cpp directly
|
||||
// (no main window needed). Run under Xvfb: xvfb-run -a ./font_tests
|
||||
// Prints one PASS/FAIL line per check; exit 0 only if all pass.
|
||||
#include <gtk/gtk.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
#include "preferences.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);
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
gtk_init(&argc, &argv);
|
||||
|
||||
// 1. Defaults.
|
||||
FontSettings def;
|
||||
check(def.font == "Sans 10", "defaults-ui-font");
|
||||
check(def.code_font == "Monospace 11", "defaults-code-font");
|
||||
|
||||
// 2. Save / load round-trip at an explicit path.
|
||||
FontSettings fs;
|
||||
fs.font = "DejaVu Sans 14";
|
||||
fs.code_font = "DejaVu Sans Mono 13";
|
||||
const char* path = "/tmp/fdesigner_font_harness.conf";
|
||||
check(fs.save(path), "save-roundtrip");
|
||||
FontSettings fs2;
|
||||
check(fs2.load(path), "load-roundtrip");
|
||||
check(fs2.font == "DejaVu Sans 14" &&
|
||||
fs2.code_font == "DejaVu Sans Mono 13",
|
||||
"roundtrip-values");
|
||||
|
||||
// 3. Missing file: load fails, defaults kept.
|
||||
FontSettings fs3;
|
||||
check(!fs3.load("/tmp/fdesigner_font_no_such_file.conf"),
|
||||
"load-missing-fails");
|
||||
check(fs3.font == "Sans 10", "load-missing-keeps-defaults");
|
||||
|
||||
// 4. Garbage in the file does not break loading.
|
||||
{
|
||||
FILE* f = std::fopen("/tmp/fdesigner_font_garbage.conf", "w");
|
||||
std::fprintf(f, "# comment\nnot-a-kv-line\nfont=\ncode_font=\n");
|
||||
std::fclose(f);
|
||||
}
|
||||
FontSettings fs4;
|
||||
check(fs4.load("/tmp/fdesigner_font_garbage.conf"),
|
||||
"load-garbage-file");
|
||||
check(fs4.font == "Sans 10" && fs4.code_font == "Monospace 11",
|
||||
"garbage-falls-back-to-defaults");
|
||||
|
||||
// 5. Sanitising: empty -> fallback, sizes clamped to 6-48 pt.
|
||||
check(FontSettings::sanitized("", "Sans 10") == "Sans 10",
|
||||
"sanitize-empty");
|
||||
check(FontSettings::size_of(FontSettings::sanitized("Sans 99",
|
||||
"Sans 10")) == 48,
|
||||
"sanitize-clamp-high");
|
||||
check(FontSettings::size_of(FontSettings::sanitized("Sans 2",
|
||||
"Sans 10")) == 6,
|
||||
"sanitize-clamp-low");
|
||||
check(FontSettings::family_of(
|
||||
FontSettings::sanitized("DejaVu Sans Mono 13",
|
||||
"Sans 10")) == "DejaVu Sans Mono",
|
||||
"sanitize-keeps-family");
|
||||
|
||||
// 6. Env override for the default path (mirrors debugger.conf).
|
||||
::setenv("FDESIGNER_SETTINGS_CONF", "/tmp/fdesigner_font_env.conf", 1);
|
||||
check(FontSettings::default_path() ==
|
||||
"/tmp/fdesigner_font_env.conf",
|
||||
"env-override-path");
|
||||
::unsetenv("FDESIGNER_SETTINGS_CONF");
|
||||
|
||||
// 7. CSS generation.
|
||||
check(fs.ui_css().find("DejaVu Sans") != std::string::npos &&
|
||||
fs.ui_css().find("14pt") != std::string::npos,
|
||||
"ui-css-content");
|
||||
check(fs.code_css().find("textview") != std::string::npos &&
|
||||
fs.code_css().find("DejaVu Sans Mono") != std::string::npos &&
|
||||
fs.code_css().find("13pt") != std::string::npos,
|
||||
"code-css-content");
|
||||
|
||||
// 8. Live apply to a text view: the widget really shows the font.
|
||||
GtkWidget* tv = gtk_text_view_new();
|
||||
gtk_widget_show(tv);
|
||||
preferences_apply_to_text_view(tv, fs);
|
||||
while (gtk_events_pending()) gtk_main_iteration();
|
||||
std::string applied = preferences_applied_font(tv);
|
||||
check(FontSettings::family_of(applied) == "DejaVu Sans Mono" &&
|
||||
FontSettings::size_of(applied) == 13,
|
||||
"apply-to-text-view");
|
||||
gtk_widget_destroy(tv);
|
||||
|
||||
// 9. Screen-wide apply: a fresh text view and a label pick it up.
|
||||
preferences_apply(fs);
|
||||
GtkWidget* tv2 = gtk_text_view_new();
|
||||
GtkWidget* lbl = gtk_label_new("probe");
|
||||
gtk_widget_show(tv2);
|
||||
gtk_widget_show(lbl);
|
||||
while (gtk_events_pending()) gtk_main_iteration();
|
||||
std::string applied2 = preferences_applied_font(tv2);
|
||||
check(FontSettings::family_of(applied2) == "DejaVu Sans Mono" &&
|
||||
FontSettings::size_of(applied2) == 13,
|
||||
"screen-apply-text-view");
|
||||
std::string applied_lbl = preferences_applied_font(lbl);
|
||||
check(FontSettings::family_of(applied_lbl) == "DejaVu Sans" &&
|
||||
FontSettings::size_of(applied_lbl) == 14,
|
||||
"screen-apply-label");
|
||||
gtk_widget_destroy(tv2);
|
||||
gtk_widget_destroy(lbl);
|
||||
|
||||
// 10. Re-applying defaults restores the defaults (no crash, no leak
|
||||
// of the old providers).
|
||||
preferences_apply(FontSettings());
|
||||
GtkWidget* tv3 = gtk_text_view_new();
|
||||
gtk_widget_show(tv3);
|
||||
while (gtk_events_pending()) gtk_main_iteration();
|
||||
std::string applied3 = preferences_applied_font(tv3);
|
||||
check(FontSettings::family_of(applied3) == "Monospace" &&
|
||||
FontSettings::size_of(applied3) == 11,
|
||||
"reapply-defaults");
|
||||
gtk_widget_destroy(tv3);
|
||||
|
||||
std::printf("FONT TESTS %s pass=%d fail=%d\n",
|
||||
g_fail == 0 ? "PASS" : "FAIL", g_pass, g_fail);
|
||||
return g_fail == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
#!/bin/sh
|
||||
# FDesigner font settings tests.
|
||||
# tests/font_tests.sh
|
||||
# Builds + runs the preferences harness (tests/font_tests.cpp, needs Xvfb),
|
||||
# runs the fdesigner self-test (which has its own font block), and smoke
|
||||
# tests the real Preferences dialog (FDESIGNER_OPEN_PREFERENCES=1) 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 font harness =="
|
||||
g++ -O2 -Wall -Wextra -std=c++17 -I src -o /tmp/font_tests tests/font_tests.cpp \
|
||||
src/preferences.cpp $(pkg-config --cflags --libs gtk+-3.0) \
|
||||
2>/tmp/font_tests_build.log || {
|
||||
say "FAIL font harness build"; cat /tmp/font_tests_build.log; exit 1
|
||||
}
|
||||
say "== font harness (under Xvfb) =="
|
||||
xvfb-run -a /tmp/font_tests || FAIL=1
|
||||
|
||||
say "== building fdesigner =="
|
||||
make >/tmp/font_make.log 2>&1 || {
|
||||
say "FAIL fdesigner build"; cat /tmp/font_make.log; FAIL=1
|
||||
}
|
||||
if [ "$FAIL" = "0" ]; then
|
||||
say "== fdesigner self-test (includes font block) =="
|
||||
FDESIGNER_SELFTEST=1 xvfb-run -a ./fdesigner || FAIL=1
|
||||
fi
|
||||
|
||||
say "== Preferences dialog smoke test =="
|
||||
if ! command -v xdotool >/dev/null 2>&1; then
|
||||
say "SKIP dialog smoke test (xdotool not installed)"
|
||||
else
|
||||
# Launch under a fresh Xvfb; the env hook opens the dialog at startup.
|
||||
# The dialog is modal, so the app stays up until we close it with Esc.
|
||||
xvfb-run -a sh -c '
|
||||
FDESIGNER_OPEN_PREFERENCES=1 ./fdesigner >/tmp/font_dlg.log 2>&1 &
|
||||
APP=$!
|
||||
FOUND=""
|
||||
i=0
|
||||
while [ $i -lt 50 ]; do
|
||||
FOUND=$(xdotool search --name "^Preferences$" 2>/dev/null | head -1)
|
||||
[ -n "$FOUND" ] && break
|
||||
sleep 0.2; i=$((i+1))
|
||||
done
|
||||
if [ -n "$FOUND" ]; then
|
||||
echo "PASS dialog-opened (window $FOUND)"
|
||||
xdotool windowactivate "$FOUND" key Escape
|
||||
sleep 0.5
|
||||
else
|
||||
echo "FAIL 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
|
||||
# The Edit -> Preferences menu item must exist in the .ui and be wired.
|
||||
grep -q 'id="mi_preferences"' ui/designer.ui &&
|
||||
grep -q 'mi_preferences' src/main.cpp &&
|
||||
say "PASS menu-item-wired" ||
|
||||
{ say "FAIL menu-item-wired"; FAIL=1; }
|
||||
# Apply path: open the dialog with a scratch conf path, press Alt+A
|
||||
# (the _Apply mnemonic), and check the file was written.
|
||||
say "== Preferences dialog Apply test =="
|
||||
rm -f /tmp/font_gui_apply.conf
|
||||
xvfb-run -a sh -c '
|
||||
FDESIGNER_SETTINGS_CONF=/tmp/font_gui_apply.conf FDESIGNER_OPEN_PREFERENCES=1 ./fdesigner >/tmp/font_apply.log 2>&1 &
|
||||
APP=$!
|
||||
FOUND=""
|
||||
i=0
|
||||
while [ $i -lt 50 ]; do
|
||||
FOUND=$(xdotool search --name "^Preferences$" 2>/dev/null | head -1)
|
||||
[ -n "$FOUND" ] && break
|
||||
sleep 0.2; i=$((i+1))
|
||||
done
|
||||
[ -n "$FOUND" ] && xdotool windowfocus "$FOUND" key alt+a
|
||||
sleep 1
|
||||
kill $APP 2>/dev/null
|
||||
wait $APP 2>/dev/null
|
||||
'
|
||||
grep -q '^font=Sans 10$' /tmp/font_gui_apply.conf &&
|
||||
grep -q '^code_font=Monospace 11$' /tmp/font_gui_apply.conf &&
|
||||
say "PASS dialog-apply-saves" ||
|
||||
{ say "FAIL dialog-apply-saves"; cat /tmp/font_gui_apply.conf 2>/dev/null; FAIL=1; }
|
||||
fi
|
||||
|
||||
if [ "$FAIL" = "0" ]; then say "FONT TESTS: ALL PASS"; else say "FONT TESTS: FAILURES (see above)"; fi
|
||||
exit "$FAIL"
|
||||
@@ -1,340 +0,0 @@
|
||||
// Extensive generator test matrix: builds many designs through the real
|
||||
// generator API and writes each as a project under tests/out/<case>/.
|
||||
// run_matrix.sh then compiles every project (with -Wextra) and runs it.
|
||||
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../src/generator.h"
|
||||
#include "../src/props.h"
|
||||
|
||||
static int g_case = 0;
|
||||
static std::string g_base;
|
||||
|
||||
static Widget mk(const std::string& type, const std::string& name, int x,
|
||||
int y) {
|
||||
Widget w;
|
||||
w.name = name;
|
||||
w.type = type;
|
||||
w.x = x;
|
||||
w.y = y;
|
||||
const TypeInfo* t = find_type(type);
|
||||
w.width = t ? t->def_width : 100;
|
||||
w.height = t ? t->def_height : 30;
|
||||
for (const PropDef& d : props_for(type))
|
||||
if (d.def && d.def[0]) w.props[d.name] = d.def;
|
||||
for (const PropDef& d : common_props())
|
||||
if (d.def && d.def[0]) w.props[d.name] = d.def;
|
||||
if (find_prop(type, "label")) w.props["label"] = name;
|
||||
return w;
|
||||
}
|
||||
|
||||
static void emit(const std::string& case_name, Project p) {
|
||||
std::string dir = g_base + "/" + case_name;
|
||||
GenResult r = generate_project(p, p.widgets, dir);
|
||||
std::printf("case %-28s %s (%zu files)\n", case_name.c_str(),
|
||||
r.ok ? "generated" : ("FAILED: " + r.error).c_str(),
|
||||
r.files.size());
|
||||
if (!r.ok) ++g_case; // count failures in exit code via marker
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
g_base = argc > 1 ? argv[1] : "tests/out";
|
||||
|
||||
// 1. Empty design.
|
||||
emit("01_empty", Project());
|
||||
|
||||
// 2. One of every widget type, default properties.
|
||||
{
|
||||
Project p;
|
||||
int i = 0;
|
||||
for (const TypeInfo& t : kTypes) {
|
||||
std::string name = std::string(t.key) + "_001";
|
||||
p.widgets.push_back(mk(t.key, name, 10 + (i % 4) * 190,
|
||||
10 + (i / 4) * 130));
|
||||
++i;
|
||||
}
|
||||
emit("02_all_types", p);
|
||||
}
|
||||
|
||||
// 3. Every property of every type set to a non-default test value.
|
||||
{
|
||||
Project p;
|
||||
int i = 0;
|
||||
for (const TypeInfo& t : kTypes) {
|
||||
Widget w = mk(t.key, std::string(t.key) + "_001",
|
||||
10 + (i % 4) * 190, 10 + (i / 4) * 130);
|
||||
std::vector<const PropDef*> defs;
|
||||
for (const PropDef& d : props_for(t.key)) defs.push_back(&d);
|
||||
for (const PropDef& d : common_props()) defs.push_back(&d);
|
||||
for (const PropDef* d : defs) {
|
||||
switch (d->kind) {
|
||||
case PropKind::Str:
|
||||
w.props[d->name] = "Test value";
|
||||
break;
|
||||
case PropKind::Bool:
|
||||
w.props[d->name] =
|
||||
std::string(d->def) == "true" ? "false" : "true";
|
||||
break;
|
||||
case PropKind::Int:
|
||||
w.props[d->name] = d->def;
|
||||
break;
|
||||
case PropKind::Double: {
|
||||
// 42.5, clamped into the property's valid range
|
||||
// (the designer's set_prop rejects out-of-range).
|
||||
double v = 42.5;
|
||||
if (d->hi > d->lo) {
|
||||
if (v < d->lo) v = d->lo;
|
||||
if (v > d->hi) v = d->hi;
|
||||
}
|
||||
char buf[64];
|
||||
std::snprintf(buf, sizeof buf, "%g", v);
|
||||
w.props[d->name] = buf;
|
||||
break;
|
||||
}
|
||||
case PropKind::Enum: {
|
||||
int last = 0;
|
||||
for (int k = 0; d->enum_values && d->enum_values[k];
|
||||
++k)
|
||||
last = d->enum_values[k];
|
||||
w.props[d->name] = std::to_string(last);
|
||||
break;
|
||||
}
|
||||
case PropKind::Color:
|
||||
w.props[d->name] = "#336699";
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (find_prop(t.key, "label")) w.props["label"] = "Test value";
|
||||
w.props["background"] = "#336699";
|
||||
w.props["foreground"] = "white";
|
||||
w.props["tooltip-text"] = "tip with \"quotes\" and \\ slash";
|
||||
p.widgets.push_back(w);
|
||||
++i;
|
||||
}
|
||||
emit("03_all_props", p);
|
||||
}
|
||||
|
||||
// 4. Every enum property at every value.
|
||||
{
|
||||
Project p;
|
||||
int x = 10;
|
||||
auto add = [&](const std::string& type, const std::string& name,
|
||||
const std::string& prop, const std::string& val) {
|
||||
Widget w = mk(type, name, x, 10);
|
||||
w.props[prop] = val;
|
||||
p.widgets.push_back(w);
|
||||
x += 130;
|
||||
};
|
||||
for (int v = 0; v <= 2; ++v)
|
||||
add("Button", "Btn_relief_" + std::to_string(v), "relief",
|
||||
std::to_string(v));
|
||||
for (int v = 0; v <= 4; ++v)
|
||||
add("Frame", "Frm_shadow_" + std::to_string(v), "shadow-type",
|
||||
std::to_string(v));
|
||||
for (int v = 0; v <= 3; ++v)
|
||||
add("Listbox", "Lst_sel_" + std::to_string(v), "selection-mode",
|
||||
std::to_string(v));
|
||||
for (int v = 0; v <= 4; ++v)
|
||||
add("Menubutton", "Mnu_dir_" + std::to_string(v), "direction",
|
||||
std::to_string(v));
|
||||
for (int v = 0; v <= 3; ++v)
|
||||
add("Text", "Txt_wrap_" + std::to_string(v), "wrap-mode",
|
||||
std::to_string(v));
|
||||
emit("04_enum_values", p);
|
||||
}
|
||||
|
||||
// 5. Menus: several menus, separators, spaces and symbols in labels,
|
||||
// plus junk lines that must be ignored.
|
||||
{
|
||||
Project p;
|
||||
p.menubar =
|
||||
"File: New | Open | Save As | - | Quit\n"
|
||||
"Edit: Cut | Copy & Paste | Select All\n"
|
||||
"this line has no colon and is ignored\n"
|
||||
": empty menu label ignored\n"
|
||||
"Help: About FDesigner\n";
|
||||
p.widgets.push_back(mk("Button", "Button_001", 10, 10));
|
||||
emit("05_menus", p);
|
||||
}
|
||||
|
||||
// 6. Hostile strings: quotes, backslashes, newline, tab, UTF-8,
|
||||
// format-specifier lookalikes.
|
||||
{
|
||||
Project p;
|
||||
p.title = "My \"Quoted\" \\ App\nSecond line";
|
||||
p.background = "#102030";
|
||||
Widget b = mk("Button", "Button_001", 10, 10);
|
||||
b.props["label"] = "Click \"me\" \\ 100% %s %d";
|
||||
p.widgets.push_back(b);
|
||||
Widget l = mk("Label", "Label_001", 10, 60);
|
||||
l.props["label"] = "café — ☕\t tabbed";
|
||||
p.widgets.push_back(l);
|
||||
Widget e = mk("Entry", "Entry_001", 10, 110);
|
||||
e.props["text"] = "a\"b\\c\nd";
|
||||
e.props["placeholder-text"] = "type \"here\"";
|
||||
p.widgets.push_back(e);
|
||||
emit("06_hostile_strings", p);
|
||||
}
|
||||
|
||||
// 7. Class-name sanitization: spaces/punctuation, leading digit,
|
||||
// empty (falls back to MyWindow).
|
||||
{
|
||||
Project p;
|
||||
p.class_name = "my cool app!";
|
||||
p.widgets.push_back(mk("Button", "Button_001", 10, 10));
|
||||
emit("07_class_spaces", p);
|
||||
}
|
||||
{
|
||||
Project p;
|
||||
p.class_name = "9lives";
|
||||
p.widgets.push_back(mk("Label", "Label_001", 10, 10));
|
||||
emit("08_class_digit", p);
|
||||
}
|
||||
{
|
||||
Project p;
|
||||
p.class_name = "";
|
||||
p.widgets.push_back(mk("Entry", "Entry_001", 10, 10));
|
||||
emit("09_class_empty", p);
|
||||
}
|
||||
|
||||
// 8. Spreadsheet extremes + several toplevels.
|
||||
{
|
||||
Project p;
|
||||
Widget big = mk("Spreadsheet", "Spreadsheet_001", 10, 10);
|
||||
big.props["rows"] = "50";
|
||||
big.props["columns"] = "26";
|
||||
big.width = 900;
|
||||
big.height = 500;
|
||||
p.widgets.push_back(big);
|
||||
Widget tiny = mk("Spreadsheet", "Spreadsheet_002", 10, 520);
|
||||
tiny.props["rows"] = "1";
|
||||
tiny.props["columns"] = "1";
|
||||
p.widgets.push_back(tiny);
|
||||
for (int i = 1; i <= 3; ++i) {
|
||||
Widget t = mk("Toplevel", "Toplevel_00" + std::to_string(i),
|
||||
100 * i, 100 * i);
|
||||
t.props["title"] = "Window " + std::to_string(i);
|
||||
t.props["resizable"] = i == 2 ? "false" : "true";
|
||||
p.widgets.push_back(t);
|
||||
}
|
||||
emit("10_spreadsheet_toplevels", p);
|
||||
}
|
||||
|
||||
// 9. Forty mixed widgets.
|
||||
{
|
||||
Project p;
|
||||
const char* types[] = {"Button", "Label", "Entry", "Checkbutton",
|
||||
"Frame", "Combobox", "Scale", "Text"};
|
||||
for (int i = 0; i < 40; ++i) {
|
||||
std::string type = types[i % 8];
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof buf, "%s_%03d", type.c_str(), i + 1);
|
||||
p.widgets.push_back(
|
||||
mk(type, buf, 10 + (i % 5) * 170, 10 + (i / 5) * 70));
|
||||
}
|
||||
emit("11_forty_widgets", p);
|
||||
}
|
||||
|
||||
// 10. Window variations: no background, huge size, tiny size.
|
||||
{
|
||||
Project p;
|
||||
p.win_width = 3840;
|
||||
p.win_height = 2160;
|
||||
p.widgets.push_back(mk("Label", "Label_001", 10, 10));
|
||||
emit("12_window_huge", p);
|
||||
}
|
||||
{
|
||||
Project p;
|
||||
p.win_width = 50;
|
||||
p.win_height = 50;
|
||||
p.background = "red";
|
||||
emit("13_window_tiny", p);
|
||||
}
|
||||
|
||||
// 11. StockChart fed with the fake Massive-format CSV.
|
||||
{
|
||||
Project p;
|
||||
Widget chart = mk("StockChart", "StockChart_001", 10, 10);
|
||||
chart.width = 640;
|
||||
chart.height = 320;
|
||||
std::string csv = std::filesystem::absolute(
|
||||
g_base + "/14_stockchart/SPY_fake.csv").string();
|
||||
chart.props["data-file"] = csv;
|
||||
p.widgets.push_back(chart);
|
||||
p.widgets.push_back(mk("Label", "Label_001", 10, 340));
|
||||
emit("14_stockchart", p);
|
||||
std::ifstream src("tests/data/SPY_fake.csv", std::ios::binary);
|
||||
std::ofstream dst(g_base + "/14_stockchart/SPY_fake.csv",
|
||||
std::ios::binary);
|
||||
dst << src.rdbuf();
|
||||
}
|
||||
|
||||
// 12. StockChart with indicator submodules attached (overlay + pane
|
||||
// + markers), fed with the 3-day series.
|
||||
{
|
||||
Project p;
|
||||
Widget chart = mk("StockChart", "StockChart_001", 10, 10);
|
||||
chart.width = 900;
|
||||
chart.height = 500;
|
||||
std::string csv = std::filesystem::absolute(
|
||||
g_base + "/15_stockchart_indicators/SPY_fake_long.csv")
|
||||
.string();
|
||||
chart.props["data-file"] = csv;
|
||||
chart.props["max-candles"] = "400";
|
||||
chart.props["indicators"] =
|
||||
"SMA(20), EMA(50), Bollinger Bands, RSI, MACD, Engulfing";
|
||||
p.widgets.push_back(chart);
|
||||
emit("15_stockchart_indicators", p);
|
||||
std::ifstream src("tests/data/SPY_fake_long.csv",
|
||||
std::ios::binary);
|
||||
std::ofstream dst(g_base +
|
||||
"/15_stockchart_indicators/SPY_fake_long.csv",
|
||||
std::ios::binary);
|
||||
dst << src.rdbuf();
|
||||
}
|
||||
|
||||
// 13. StockChart Pro: percent scale, QQQ comparison series, and a
|
||||
// full set of annotations, in a 1024x768 window.
|
||||
{
|
||||
Project p;
|
||||
p.win_width = 1024;
|
||||
p.win_height = 768;
|
||||
Widget chart = mk("StockChart", "StockChart_001", 10, 10);
|
||||
chart.width = 1004;
|
||||
chart.height = 748;
|
||||
std::string csv = std::filesystem::absolute(
|
||||
g_base + "/16_stockchart_pro/SPY_fake_long.csv").string();
|
||||
std::string qqq = std::filesystem::absolute(
|
||||
g_base + "/16_stockchart_pro/QQQ_fake_long.csv").string();
|
||||
chart.props["data-file"] = csv;
|
||||
chart.props["max-candles"] = "400";
|
||||
chart.props["indicators"] = "SMA(20), RSI";
|
||||
chart.props["scale-mode"] = "1";
|
||||
chart.props["compare-files"] = qqq;
|
||||
chart.props["drawings"] =
|
||||
"trend 790 676 1150 690 red; hline 688 blue; "
|
||||
"fib 800 674 1000 692 purple; "
|
||||
"text 830 691 orange Resistance zone; "
|
||||
"rect 860 678 960 684 teal; "
|
||||
"arrow 920 690 1090 680 magenta; "
|
||||
"measure 840 677 1010 689 black";
|
||||
p.widgets.push_back(chart);
|
||||
emit("16_stockchart_pro", p);
|
||||
std::ifstream src("tests/data/SPY_fake_long.csv",
|
||||
std::ios::binary);
|
||||
std::ofstream dst(g_base + "/16_stockchart_pro/SPY_fake_long.csv",
|
||||
std::ios::binary);
|
||||
dst << src.rdbuf();
|
||||
std::ifstream src2("tests/data/QQQ_fake_long.csv",
|
||||
std::ios::binary);
|
||||
std::ofstream dst2(g_base + "/16_stockchart_pro/QQQ_fake_long.csv",
|
||||
std::ios::binary);
|
||||
dst2 << src2.rdbuf();
|
||||
}
|
||||
|
||||
return g_case == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
// Renders the generated StockChart (matrix case 15, with indicator
|
||||
// submodules attached by design) offscreen and verifies the indicators
|
||||
// actually PLOT: the SMA's palette-blue line must appear in the price
|
||||
// pane, and palette-coloured pixels must appear in the oscillator pane
|
||||
// strip at the bottom (RSI/MACD live there).
|
||||
#include <gtk/gtk.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#include "StockChart_001.h"
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
gtk_init(&argc, &argv);
|
||||
GtkWidget* win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
|
||||
GtkWidget* fixed = gtk_fixed_new();
|
||||
gtk_container_add(GTK_CONTAINER(win), fixed);
|
||||
gtk_window_set_default_size(GTK_WINDOW(win), 1000, 700);
|
||||
StockChart_001 chart(fixed);
|
||||
if (chart.candle_count() == 0) {
|
||||
std::printf("NO DATA LOADED\n");
|
||||
return 1;
|
||||
}
|
||||
gtk_widget_show_all(win);
|
||||
for (int i = 0; i < 20; ++i)
|
||||
while (gtk_events_pending()) gtk_main_iteration();
|
||||
GtkWidget* w = chart.widget();
|
||||
int width = gtk_widget_get_allocated_width(w);
|
||||
int height = gtk_widget_get_allocated_height(w);
|
||||
if (width < 50 || height < 50) {
|
||||
std::printf("BAD SIZE %dx%d\n", width, height);
|
||||
return 1;
|
||||
}
|
||||
cairo_surface_t* surf =
|
||||
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
|
||||
cairo_t* cr = cairo_create(surf);
|
||||
gtk_widget_draw(w, cr);
|
||||
cairo_destroy(cr);
|
||||
cairo_surface_flush(surf);
|
||||
unsigned char* px = cairo_image_surface_get_data(surf);
|
||||
int stride = cairo_image_surface_get_stride(surf);
|
||||
// Palette blue (SMA and RSI line colour): b high, r low, g mid.
|
||||
long blue_top = 0, blue_bottom = 0;
|
||||
int split = (int)(height * 0.66);
|
||||
for (int y = 0; y < height; ++y)
|
||||
for (int x = 0; x < width; ++x) {
|
||||
unsigned char* p = px + y * stride + x * 4; // BGRA
|
||||
int b = p[0], g = p[1], r = p[2];
|
||||
if (b > 150 && r < 110 && g > 40 && g < 170) {
|
||||
if (y < split)
|
||||
++blue_top;
|
||||
else
|
||||
++blue_bottom;
|
||||
}
|
||||
}
|
||||
std::printf("candles=%d size=%dx%d BLUE price-pane %ld pane %ld\n",
|
||||
chart.candle_count(), width, height, blue_top,
|
||||
blue_bottom);
|
||||
return (blue_top > 100 && blue_bottom > 50) ? 0 : 1;
|
||||
}
|
||||
@@ -1,433 +0,0 @@
|
||||
// indicator_test.cpp — visual + numeric test of all 250 StockChart
|
||||
// indicator submodules in src/indicators.h.
|
||||
//
|
||||
// For every registered indicator:
|
||||
// 1. compute() over the 3-day fake Massive series must produce finite
|
||||
// values (line/bar indicators) — patterns may legitimately not fire;
|
||||
// 2. the indicator is rendered (with candles) onto its own cairo
|
||||
// surface and we count pixels painted in the indicator's palette
|
||||
// colours — proof it actually draws;
|
||||
// 3. a labelled contact sheet of all 250 renders is written to
|
||||
// tests/out/indicators_contact_sheet.png for eyeballing.
|
||||
// Plus crafted-bar detection checks for famous patterns and range
|
||||
// checks for bounded oscillators.
|
||||
//
|
||||
// Build: g++ -O2 -std=c++17 -I src tests/indicator_test.cpp -o /tmp/itest
|
||||
// $(pkg-config --cflags --libs gtk+-3.0)
|
||||
// Run: /tmp/itest tests/data/SPY_fake_long.csv tests/out
|
||||
|
||||
#include <cairo.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "indicators.h"
|
||||
|
||||
using fdi::Bar;
|
||||
|
||||
static std::vector<Bar> load_csv(const std::string& path) {
|
||||
std::ifstream in(path);
|
||||
std::vector<Bar> out;
|
||||
std::string line;
|
||||
if (!std::getline(in, line)) return out; // header
|
||||
while (std::getline(in, line)) {
|
||||
std::stringstream ss(line);
|
||||
std::string f[8];
|
||||
for (int i = 0; i < 8; ++i)
|
||||
if (!std::getline(ss, f[i], ',')) f[i] = "0";
|
||||
Bar b;
|
||||
b.volume = std::atof(f[1].c_str());
|
||||
b.open = std::atof(f[2].c_str());
|
||||
b.close = std::atof(f[3].c_str());
|
||||
b.high = std::atof(f[4].c_str());
|
||||
b.low = std::atof(f[5].c_str());
|
||||
b.time = std::atoll(f[6].c_str());
|
||||
out.push_back(b);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Draw light-grey candles for bars [begin, begin+count) into an area.
|
||||
static void draw_candles(cairo_t* cr, const std::vector<Bar>& bars,
|
||||
size_t begin, size_t count, double x, double y,
|
||||
double w, double h, double& lo, double& hi) {
|
||||
lo = 1e300;
|
||||
hi = -1e300;
|
||||
for (size_t i = begin; i < begin + count && i < bars.size(); ++i) {
|
||||
lo = std::min(lo, bars[i].low);
|
||||
hi = std::max(hi, bars[i].high);
|
||||
}
|
||||
if (hi - lo < 1e-9) hi = lo + 1;
|
||||
double slot = w / count;
|
||||
for (size_t k = 0; k < count && begin + k < bars.size(); ++k) {
|
||||
const Bar& b = bars[begin + k];
|
||||
double cx = x + slot * k + slot / 2;
|
||||
auto Y = [&](double v) { return y + (hi - v) / (hi - lo) * h; };
|
||||
cairo_set_source_rgb(cr, 0.78, 0.78, 0.78);
|
||||
cairo_set_line_width(cr, 1.0);
|
||||
cairo_move_to(cr, cx, Y(b.high));
|
||||
cairo_line_to(cr, cx, Y(b.low));
|
||||
cairo_stroke(cr);
|
||||
double y1 = Y(std::max(b.open, b.close));
|
||||
double y2 = Y(std::min(b.open, b.close));
|
||||
if (y2 - y1 < 1) y2 = y1 + 1;
|
||||
cairo_rectangle(cr, cx - std::max(0.5, slot * 0.35), y1,
|
||||
std::max(1.0, slot * 0.7), y2 - y1);
|
||||
cairo_fill(cr);
|
||||
}
|
||||
}
|
||||
|
||||
// Count pixels close to any palette colour (indicator ink).
|
||||
static long count_ink(cairo_surface_t* surf) {
|
||||
int w = cairo_image_surface_get_width(surf);
|
||||
int h = cairo_image_surface_get_height(surf);
|
||||
int stride = cairo_image_surface_get_stride(surf);
|
||||
unsigned char* data = cairo_image_surface_get_data(surf);
|
||||
long ink = 0;
|
||||
for (int yy = 0; yy < h; ++yy) {
|
||||
for (int xx = 0; xx < w; ++xx) {
|
||||
unsigned char* px = data + yy * stride + xx * 4;
|
||||
double r = px[2] / 255.0, g = px[1] / 255.0, b = px[0] / 255.0;
|
||||
for (int c = 0; c < fdi::kPaletteSize; ++c) {
|
||||
double dr = r - fdi::kPalette[c][0];
|
||||
double dg = g - fdi::kPalette[c][1];
|
||||
double db = b - fdi::kPalette[c][2];
|
||||
if (dr * dr + dg * dg + db * db < 0.09) {
|
||||
++ink;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ink;
|
||||
}
|
||||
|
||||
// A pattern-rich synthetic series: overnight gaps, varied bodies and
|
||||
// occasional dojis — minute bars from a continuous feed rarely gap, so
|
||||
// gap patterns (Kicking, Abandoned Baby, stars...) can never fire on
|
||||
// the plain random walk. Patterns are tested on both series.
|
||||
static std::vector<Bar> make_gapped_bars() {
|
||||
std::vector<Bar> out;
|
||||
unsigned long long s = 88172645463325252ULL;
|
||||
auto rnd = [&]() {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 7;
|
||||
s ^= s << 17;
|
||||
return (s >> 11) / 9007199254740992.0;
|
||||
};
|
||||
double price = 100;
|
||||
for (int i = 0; i < 3000; ++i) {
|
||||
Bar b;
|
||||
double gap = (rnd() - 0.5) * 1.6;
|
||||
b.open = price + gap;
|
||||
double body = (rnd() - 0.48) * 3.0;
|
||||
if (i % 37 == 0) body = (rnd() - 0.5) * 0.06; // forced doji
|
||||
if (i % 53 == 0) body = (rnd() > 0.5 ? 1 : -1) * (2.5 + rnd());
|
||||
b.close = b.open + body;
|
||||
b.high = std::max(b.open, b.close) + rnd() * 0.9;
|
||||
b.low = std::min(b.open, b.close) - rnd() * 0.9;
|
||||
b.volume = 1000 + rnd() * 40000;
|
||||
b.time = (long long)i * 60000000000LL;
|
||||
out.push_back(b);
|
||||
price = b.close;
|
||||
if (price < 20) price = 100;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
std::string csv = argc > 1 ? argv[1] : "tests/data/SPY_fake_long.csv";
|
||||
std::string outdir = argc > 2 ? argv[2] : "tests/out";
|
||||
std::vector<Bar> bars = load_csv(csv);
|
||||
if (bars.size() < 200) {
|
||||
std::printf("FAIL: only %zu bars loaded from %s\n", bars.size(),
|
||||
csv.c_str());
|
||||
return 1;
|
||||
}
|
||||
std::printf("loaded %zu bars\n", bars.size());
|
||||
std::vector<Bar> gapped = make_gapped_bars();
|
||||
std::printf("plus %zu gapped pattern-test bars\n", gapped.size());
|
||||
const size_t VISIBLE = 400;
|
||||
size_t begin = bars.size() - VISIBLE;
|
||||
|
||||
int passed = 0, failed = 0, nofire = 0;
|
||||
std::vector<std::string> fail_names, nofire_names;
|
||||
|
||||
// Contact sheet geometry: 5 columns x 50 rows.
|
||||
const int COLS = 5, CELL_W = 380, CELL_H = 112;
|
||||
int rows = (int)((fdi::all_defs().size() + COLS - 1) / COLS);
|
||||
cairo_surface_t* sheet = cairo_image_surface_create(
|
||||
CAIRO_FORMAT_ARGB32, COLS * CELL_W, rows * CELL_H);
|
||||
cairo_t* scr = cairo_create(sheet);
|
||||
cairo_set_source_rgb(scr, 1, 1, 1);
|
||||
cairo_paint(scr);
|
||||
|
||||
size_t idx = 0;
|
||||
for (const fdi::Def& def : fdi::all_defs()) {
|
||||
auto ind = fdi::make_indicator(def.name);
|
||||
if (!ind) {
|
||||
std::printf("FAIL %-28s cannot construct\n", def.name);
|
||||
++failed;
|
||||
fail_names.push_back(def.name);
|
||||
++idx;
|
||||
continue;
|
||||
}
|
||||
// 1. Compute. Patterns also run on the gapped series.
|
||||
fdi::Lines lines = ind->compute(bars);
|
||||
long finite = 0, markers_fired = 0;
|
||||
for (const auto& s : lines)
|
||||
for (double v : s) {
|
||||
if (std::isfinite(v)) ++finite;
|
||||
if (def.kind == fdi::PlotKind::Markers && v != 0 &&
|
||||
std::isfinite(v))
|
||||
++markers_fired;
|
||||
}
|
||||
// Render dataset: patterns render on the gapped series, windowed
|
||||
// to end at the last firing so a triangle is in view.
|
||||
const std::vector<Bar>* rbars = &bars;
|
||||
size_t rbegin = begin;
|
||||
if (def.kind == fdi::PlotKind::Markers) {
|
||||
fdi::Lines gl = ind->compute(gapped);
|
||||
long gfired = 0;
|
||||
size_t last_fire = 0;
|
||||
if (!gl.empty())
|
||||
for (size_t i = 0; i < gl[0].size(); ++i)
|
||||
if (gl[0][i] != 0 && std::isfinite(gl[0][i])) {
|
||||
++gfired;
|
||||
last_fire = i;
|
||||
}
|
||||
markers_fired += gfired;
|
||||
if (gfired > 0) {
|
||||
rbars = &gapped;
|
||||
rbegin = last_fire >= VISIBLE - 1 ? last_fire - VISIBLE + 1
|
||||
: 0;
|
||||
}
|
||||
}
|
||||
// 2. Render on its own surface and count ink.
|
||||
cairo_surface_t* surf =
|
||||
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 480, 300);
|
||||
cairo_t* cr = cairo_create(surf);
|
||||
cairo_set_source_rgb(cr, 1, 1, 1);
|
||||
cairo_paint(cr);
|
||||
double lo, hi;
|
||||
bool is_pane = def.kind == fdi::PlotKind::Pane;
|
||||
draw_candles(cr, *rbars, rbegin, VISIBLE, 4, 4, 472,
|
||||
is_pane ? 190 : 292, lo, hi);
|
||||
fdi::PlotArea area;
|
||||
area.cr = cr;
|
||||
area.begin = rbegin;
|
||||
area.count = VISIBLE;
|
||||
if (is_pane) {
|
||||
area.x = 4;
|
||||
area.y = 206;
|
||||
area.w = 472;
|
||||
area.h = 90;
|
||||
} else {
|
||||
area.x = 4;
|
||||
area.y = 4;
|
||||
area.w = 472;
|
||||
area.h = 292;
|
||||
area.lo = lo;
|
||||
area.hi = hi;
|
||||
}
|
||||
ind->draw(area, *rbars);
|
||||
cairo_surface_flush(surf);
|
||||
long ink = count_ink(surf);
|
||||
cairo_destroy(cr);
|
||||
cairo_surface_destroy(surf);
|
||||
|
||||
bool ok = true;
|
||||
const char* note = "";
|
||||
if (def.kind == fdi::PlotKind::Markers) {
|
||||
if (markers_fired == 0) {
|
||||
ok = false;
|
||||
note = "pattern did not fire on this data";
|
||||
++nofire;
|
||||
nofire_names.push_back(def.name);
|
||||
} else if (ink == 0) {
|
||||
ok = false;
|
||||
note = "fired but drew nothing";
|
||||
}
|
||||
} else {
|
||||
if (finite == 0) {
|
||||
ok = false;
|
||||
note = "no finite values";
|
||||
} else if (ink == 0) {
|
||||
ok = false;
|
||||
note = "computed but drew nothing";
|
||||
}
|
||||
}
|
||||
if (ok) {
|
||||
++passed;
|
||||
} else if (def.kind != fdi::PlotKind::Markers ||
|
||||
markers_fired > 0) {
|
||||
++failed;
|
||||
fail_names.push_back(std::string(def.name) + " (" + note + ")");
|
||||
}
|
||||
std::printf("%-4s %-28s finite=%-7ld fired=%-4ld ink=%-6ld %s\n",
|
||||
ok ? "PASS" : (def.kind == fdi::PlotKind::Markers &&
|
||||
markers_fired == 0
|
||||
? "NOFIRE"
|
||||
: "FAIL"),
|
||||
def.name, finite, markers_fired, ink, note);
|
||||
|
||||
// 3. Contact sheet cell.
|
||||
int cx = (int)(idx % COLS) * CELL_W, cy = (int)(idx / COLS) * CELL_H;
|
||||
cairo_set_source_rgb(scr, 1, 1, 1);
|
||||
cairo_rectangle(scr, cx, cy, CELL_W, CELL_H);
|
||||
cairo_fill(scr);
|
||||
cairo_set_source_rgb(scr, 0.6, 0.6, 0.6);
|
||||
cairo_set_line_width(scr, 0.5);
|
||||
cairo_rectangle(scr, cx + 0.5, cy + 0.5, CELL_W - 1, CELL_H - 1);
|
||||
cairo_stroke(scr);
|
||||
cairo_set_source_rgb(scr, 0.15, 0.15, 0.15);
|
||||
cairo_select_font_face(scr, "Sans", CAIRO_FONT_SLANT_NORMAL,
|
||||
CAIRO_FONT_WEIGHT_BOLD);
|
||||
cairo_set_font_size(scr, 10);
|
||||
cairo_move_to(scr, cx + 5, cy + 13);
|
||||
cairo_show_text(scr, def.name);
|
||||
size_t sbegin = bars.size() - 300;
|
||||
const std::vector<Bar>* cbars = &bars;
|
||||
if (def.kind == fdi::PlotKind::Markers && rbars == &gapped) {
|
||||
cbars = &gapped;
|
||||
sbegin = rbegin + 100;
|
||||
}
|
||||
double slo, shi;
|
||||
draw_candles(scr, *cbars, sbegin, 300, cx + 4, cy + 18, CELL_W - 8,
|
||||
is_pane ? 52 : CELL_H - 24, slo, shi);
|
||||
fdi::PlotArea cell;
|
||||
cell.cr = scr;
|
||||
cell.begin = sbegin;
|
||||
cell.count = 300;
|
||||
if (is_pane) {
|
||||
cell.x = cx + 4;
|
||||
cell.y = cy + 74;
|
||||
cell.w = CELL_W - 8;
|
||||
cell.h = CELL_H - 78;
|
||||
} else {
|
||||
cell.x = cx + 4;
|
||||
cell.y = cy + 18;
|
||||
cell.w = CELL_W - 8;
|
||||
cell.h = CELL_H - 24;
|
||||
cell.lo = slo;
|
||||
cell.hi = shi;
|
||||
}
|
||||
ind->draw(cell, *cbars);
|
||||
++idx;
|
||||
}
|
||||
std::string sheet_path = outdir + "/indicators_contact_sheet.png";
|
||||
cairo_surface_write_to_png(sheet, sheet_path.c_str());
|
||||
cairo_destroy(scr);
|
||||
cairo_surface_destroy(sheet);
|
||||
std::printf("contact sheet: %s\n", sheet_path.c_str());
|
||||
|
||||
// 4. Crafted-bar pattern detection checks.
|
||||
auto mk = [](double o, double h, double l, double c) {
|
||||
Bar b;
|
||||
b.open = o;
|
||||
b.high = h;
|
||||
b.low = l;
|
||||
b.close = c;
|
||||
b.volume = 1000;
|
||||
return b;
|
||||
};
|
||||
int crafted_fail = 0;
|
||||
auto expect = [&](const char* name, const std::vector<Bar>& seq,
|
||||
size_t at, double sign) {
|
||||
auto ind = fdi::make_indicator(name);
|
||||
fdi::Lines lines = ind->compute(seq);
|
||||
double got = lines.empty() || at >= lines[0].size() ? 0 : lines[0][at];
|
||||
bool ok = (sign > 0 && got > 0) || (sign < 0 && got < 0);
|
||||
std::printf("crafted %-16s at %zu: got %+.0f %s\n", name, at, got,
|
||||
ok ? "OK" : "MISMATCH");
|
||||
if (!ok) ++crafted_fail;
|
||||
};
|
||||
expect("Doji", {mk(100, 101, 99, 100.05)}, 0, +1);
|
||||
expect("Engulfing",
|
||||
{mk(102, 102.5, 99.5, 100), mk(99.5, 103, 99, 102.5)}, 1, +1);
|
||||
expect("Hammer",
|
||||
{mk(100, 100.5, 96.5, 97), mk(100, 100.5, 96.8, 100.4)}, 1, +1);
|
||||
expect("Morning Star",
|
||||
{mk(110, 110.5, 99.5, 100), mk(98, 98.8, 97.5, 98.5),
|
||||
mk(99, 107.5, 98.5, 107)},
|
||||
2, +1);
|
||||
expect("Shooting Star",
|
||||
{mk(100, 101, 99, 100.8), mk(102, 105, 101.9, 102.15)}, 1,
|
||||
-1);
|
||||
expect("Takuri",
|
||||
{mk(100, 101.3, 99.7, 101), mk(101, 102.3, 100.7, 102),
|
||||
mk(102, 103.3, 101.7, 103), mk(100, 100.4, 97.5, 100.3)},
|
||||
3, +1);
|
||||
expect("Thrusting",
|
||||
{mk(100, 110.4, 99.6, 110), mk(111, 111.3, 106.5, 107)}, 1,
|
||||
-1);
|
||||
expect("Two Crows",
|
||||
{mk(100, 110.4, 99.6, 110), mk(112, 112.3, 107.6, 108),
|
||||
mk(111, 111.3, 104.6, 105)},
|
||||
2, -1);
|
||||
expect("Concealing Baby Swallow",
|
||||
{mk(110, 110.2, 103.8, 104), mk(103, 103.4, 98.6, 99),
|
||||
mk(100.5, 101, 96.6, 97), mk(102, 102.3, 94.7, 95)},
|
||||
3, +1);
|
||||
expect("Kicking By Length",
|
||||
{mk(103, 103.2, 99.8, 100), mk(106, 112.2, 105.8, 112)}, 1,
|
||||
+1);
|
||||
expect("Gap Side Side White",
|
||||
{mk(100, 101.3, 99.7, 101), mk(103, 105.4, 102.5, 105),
|
||||
mk(103.1, 106.3, 102.9, 106)},
|
||||
2, +1);
|
||||
expect("Piercing Line",
|
||||
{mk(110, 110.5, 99.5, 100), mk(99, 106.5, 98.8, 106)}, 1, +1);
|
||||
expect("Dark Cloud Cover",
|
||||
{mk(100, 110.5, 99.5, 110), mk(111, 111.5, 103.5, 104)}, 1,
|
||||
-1);
|
||||
expect("Three White Soldiers",
|
||||
{mk(100, 104.5, 99.5, 104), mk(103, 107.5, 102.5, 107),
|
||||
mk(106, 110.5, 105.5, 110)},
|
||||
2, +1);
|
||||
expect("Abandoned Baby",
|
||||
{mk(110, 110.5, 99.5, 100), mk(97, 97.3, 96.7, 97.05),
|
||||
mk(99, 106.5, 98.5, 106)},
|
||||
2, +1);
|
||||
expect("Kicking",
|
||||
{mk(105, 105.2, 99.8, 100), mk(107, 112.2, 106.8, 112)}, 1,
|
||||
+1);
|
||||
expect("Tristar",
|
||||
{mk(100, 100.6, 99.4, 100), mk(102, 102.6, 101.4, 102),
|
||||
mk(100, 100.6, 99.4, 100)},
|
||||
2, -1);
|
||||
|
||||
// 5. Bounded-oscillator range checks.
|
||||
auto range_check = [&](const char* name, double lo, double hi) {
|
||||
auto ind = fdi::make_indicator(name);
|
||||
fdi::Lines lines = ind->compute(bars);
|
||||
bool ok = true, any = false;
|
||||
for (const auto& s : lines)
|
||||
for (double v : s)
|
||||
if (std::isfinite(v)) {
|
||||
any = true;
|
||||
if (v < lo - 1e-6 || v > hi + 1e-6) ok = false;
|
||||
}
|
||||
std::printf("range %-16s in [%g, %g]: %s\n", name, lo, hi,
|
||||
ok && any ? "OK" : "MISMATCH");
|
||||
if (!ok || !any) ++crafted_fail;
|
||||
};
|
||||
range_check("RSI", 0, 100);
|
||||
range_check("Stochastic Fast", 0, 100);
|
||||
range_check("Williams %R", -100, 0);
|
||||
range_check("MFI", 0, 100);
|
||||
range_check("Stochastic RSI", 0, 100);
|
||||
|
||||
std::printf("\nSUMMARY: %d passed, %d failed, %d patterns not fired, "
|
||||
"%d crafted/range mismatches\n",
|
||||
passed, failed, nofire, crafted_fail);
|
||||
for (auto& f : fail_names) std::printf(" FAIL: %s\n", f.c_str());
|
||||
for (auto& f : nofire_names) std::printf(" NOFIRE: %s\n", f.c_str());
|
||||
return (failed || crafted_fail) ? 1 : 0;
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate QQQ_fake_long.csv: a comparison series on the exact same
|
||||
window_start grid as SPY_fake_long.csv (different ticker, price level
|
||||
and walk), for testing the StockChart comparative plot."""
|
||||
import csv
|
||||
import random
|
||||
import sys
|
||||
|
||||
src_path = sys.argv[1] if len(sys.argv) > 1 else "tests/data/SPY_fake_long.csv"
|
||||
dst_path = sys.argv[2] if len(sys.argv) > 2 else "tests/data/QQQ_fake_long.csv"
|
||||
|
||||
with open(src_path) as f:
|
||||
rows = list(csv.DictReader(f))
|
||||
|
||||
random.seed(424242)
|
||||
price = 512.0
|
||||
out = []
|
||||
for r in rows:
|
||||
o = price
|
||||
c = price + (random.random() - 0.475) * 2.6
|
||||
h = max(o, c) + random.random() * 0.7
|
||||
lo = min(o, c) - random.random() * 0.7
|
||||
vol = int(3000 + random.random() * 30000)
|
||||
out.append(
|
||||
{
|
||||
"ticker": "QQQ",
|
||||
"volume": vol,
|
||||
"open": f"{o:.2f}",
|
||||
"close": f"{c:.2f}",
|
||||
"high": f"{h:.2f}",
|
||||
"low": f"{lo:.2f}",
|
||||
"window_start": r["window_start"],
|
||||
"transactions": int(vol / 7),
|
||||
}
|
||||
)
|
||||
price = c
|
||||
|
||||
with open(dst_path, "w", newline="") as f:
|
||||
w = csv.DictWriter(
|
||||
f,
|
||||
fieldnames=[
|
||||
"ticker",
|
||||
"volume",
|
||||
"open",
|
||||
"close",
|
||||
"high",
|
||||
"low",
|
||||
"window_start",
|
||||
"transactions",
|
||||
],
|
||||
)
|
||||
w.writeheader()
|
||||
w.writerows(out)
|
||||
print(f"wrote {len(out)} QQQ bars to {dst_path}")
|
||||
@@ -1,162 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Palette-window tests: the widget palette is its own top-level window
|
||||
# ("FDesigner — Widgets"), tight 2-column Lazarus-style grid, opens with
|
||||
# the designer, closes (hide, app survives) and reopens from View menu.
|
||||
# Uses a tiny Xlib helper to send a real WM_DELETE_WINDOW (xdotool
|
||||
# windowclose destroys the X window outright under bare Xvfb, which is
|
||||
# not what a window manager does).
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
pass=0; fail=0; failed=""
|
||||
ok() { echo "PASS $1"; pass=$((pass+1)); }
|
||||
bad() { echo "FAIL $1"; fail=$((fail+1)); failed="$failed $1"; }
|
||||
|
||||
# Re-run the body under Xvfb when no display is set.
|
||||
if [ -z "${DISPLAY:-}" ]; then
|
||||
PALETTE_TEST_IN_XVFB=1 xvfb-run -a -s "-screen 0 2560x1440x24" "$0"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
echo "== building fdesigner =="
|
||||
if make > /tmp/palette_make.log 2>&1; then ok make; else
|
||||
bad make; cat /tmp/palette_make.log; exit 1
|
||||
fi
|
||||
|
||||
echo "== building Xlib close helper =="
|
||||
cat > /tmp/palette_wmclose.c << "C_EOF"
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xatom.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
int main(int argc, char** argv) {
|
||||
Display* d = XOpenDisplay(NULL);
|
||||
if (!d) return 2;
|
||||
Window w = (Window)strtoul(argv[1], NULL, 0);
|
||||
Atom trans = XInternAtom(d, "WM_TRANSIENT_FOR", False);
|
||||
Atom actual; int fmt; unsigned long n, extra; unsigned char* prop = NULL;
|
||||
XGetWindowProperty(d, w, trans, 0, 1, False, XA_WINDOW,
|
||||
&actual, &fmt, &n, &extra, &prop);
|
||||
printf("TRANSIENT=%lu\n", n);
|
||||
if (prop) XFree(prop);
|
||||
Atom protos = XInternAtom(d, "WM_PROTOCOLS", False);
|
||||
Atom del = XInternAtom(d, "WM_DELETE_WINDOW", False);
|
||||
Atom* plist = NULL; int count = 0, has_del = 0;
|
||||
if (XGetWMProtocols(d, w, &plist, &count)) {
|
||||
for (int i = 0; i < count; i++) if (plist[i] == del) has_del = 1;
|
||||
XFree(plist);
|
||||
}
|
||||
printf("DELETE_PROTOCOL=%d\n", has_del);
|
||||
if (argc > 2 && !strcmp(argv[2], "close")) {
|
||||
XEvent ev; memset(&ev, 0, sizeof(ev));
|
||||
ev.xclient.type = ClientMessage;
|
||||
ev.xclient.window = w;
|
||||
ev.xclient.message_type = protos;
|
||||
ev.xclient.format = 32;
|
||||
ev.xclient.data.l[0] = del;
|
||||
ev.xclient.data.l[1] = CurrentTime;
|
||||
XSendEvent(d, w, False, NoEventMask, &ev);
|
||||
XSync(d, False);
|
||||
printf("SENT_CLOSE\n");
|
||||
}
|
||||
XCloseDisplay(d);
|
||||
return 0;
|
||||
}
|
||||
C_EOF
|
||||
if gcc -O2 -Wall -Wextra -o /tmp/palette_wmclose /tmp/palette_wmclose.c -lX11 \
|
||||
> /tmp/palette_wmclose_build.log 2>&1; then ok wmclose-helper-build;
|
||||
else bad wmclose-helper-build; cat /tmp/palette_wmclose_build.log; exit 1; fi
|
||||
|
||||
echo "== launching designer under Xvfb ($DISPLAY) =="
|
||||
./fdesigner > /tmp/palette_app.log 2>&1 &
|
||||
APP_PID=$!
|
||||
trap 'kill $APP_PID 2>/dev/null || true' EXIT
|
||||
sleep 3
|
||||
if ! kill -0 $APP_PID 2>/dev/null; then
|
||||
bad "app-start"; cat /tmp/palette_app.log; exit 1
|
||||
fi
|
||||
ok app-start
|
||||
|
||||
MAIN=$(xdotool search --name "FDesigner — C\+\+/GTK" | head -1)
|
||||
PAL=$(xdotool search --name "FDesigner — Widgets" | head -1)
|
||||
[ -n "$MAIN" ] && ok main-window || bad main-window
|
||||
[ -n "$PAL" ] && ok palette-window || bad palette-window
|
||||
if [ -n "$MAIN" ] && [ -n "$PAL" ] && [ "$MAIN" != "$PAL" ]; then
|
||||
ok distinct-windows
|
||||
else bad distinct-windows; fi
|
||||
|
||||
# Palette must be a plain top-level window, not transient/modal.
|
||||
if [ -n "$PAL" ]; then
|
||||
OUT=$(/tmp/palette_wmclose "$PAL")
|
||||
echo "$OUT" | grep -q "TRANSIENT=0" && ok not-transient || bad not-transient
|
||||
echo "$OUT" | grep -q "DELETE_PROTOCOL=1" && ok delete-protocol || \
|
||||
bad delete-protocol
|
||||
fi
|
||||
|
||||
# Palette parked beside the designer (left or right, not overlapping it).
|
||||
geom() { # $1 = window id, $2/$3 = name prefix for X/Y/W/H vars
|
||||
eval "$(xdotool getwindowgeometry "$1" | sed -n \
|
||||
-e 's/ *Position: \([0-9]*\),\([0-9]*\).*/'"$2"'X=\1; '"$2"'Y=\2/p' \
|
||||
-e 's/ *Geometry: \([0-9]*\)x\([0-9]*\)/'"$2"'W=\1; '"$2"'H=\2/p')"
|
||||
}
|
||||
if [ -n "$MAIN" ] && [ -n "$PAL" ]; then
|
||||
geom "$MAIN" M
|
||||
geom "$PAL" P
|
||||
echo "main ${MW}x${MH}@${MX},${MY} palette ${PW}x${PH}@${PX},${PY}"
|
||||
if [ "$PX" -eq $((MX - PW - 12)) ] || [ "$PX" -eq $((MX + MW + 12)) ]; then
|
||||
ok palette-beside-main
|
||||
else bad palette-beside-main; fi
|
||||
if [ "$PW" -ge 200 ] && [ "$PW" -le 300 ]; then ok palette-width;
|
||||
else bad palette-width; fi
|
||||
fi
|
||||
|
||||
# Clicking palette buttons places widgets on the canvas: screenshot the
|
||||
# canvas corner before/after clicking Button, then Memo (Lazarus).
|
||||
if [ -n "$PAL" ] && [ -n "$MAIN" ]; then
|
||||
CX=$((MX + 10)); CY=$((MY + 30))
|
||||
import -window root -crop 500x220+${CX}+${CY} /tmp/palette_before.png
|
||||
# First button (Button, left column, first grid row).
|
||||
xdotool mousemove $((PX + 62)) $((PY + 39)) click 1; sleep 0.7
|
||||
# Memo button (Lazarus — Basic, left column).
|
||||
xdotool mousemove $((PX + 62)) $((PY + 350)) click 1; sleep 0.7
|
||||
import -window root -crop 500x220+${CX}+${CY} /tmp/palette_after.png
|
||||
DIFF=$(compare -metric AE -fuzz 5% /tmp/palette_before.png \
|
||||
/tmp/palette_after.png /tmp/palette_diff.png 2>&1 || true)
|
||||
echo "canvas pixel diff: $DIFF"
|
||||
if [ "${DIFF:-0}" -gt 1000 ] 2>/dev/null; then ok palette-places-widgets;
|
||||
else bad palette-places-widgets; fi
|
||||
fi
|
||||
|
||||
# Closing the palette (real WM close) hides it; the app stays alive.
|
||||
if [ -n "$PAL" ]; then
|
||||
/tmp/palette_wmclose "$PAL" close > /tmp/palette_close.log 2>&1
|
||||
sleep 1
|
||||
if [ -z "$(xdotool search --onlyvisible --name "FDesigner — Widgets")" ]; then
|
||||
ok palette-hides-on-close
|
||||
else bad palette-hides-on-close; fi
|
||||
if kill -0 $APP_PID 2>/dev/null && \
|
||||
[ -n "$(xdotool search --onlyvisible --name "FDesigner — C\+\+/GTK")" ]; then
|
||||
ok app-alive-after-close
|
||||
else bad app-alive-after-close; fi
|
||||
# Reopen from View -> Widget Palette (menu coords from main geometry).
|
||||
xdotool mousemove $((MX + 110)) $((MY + 12)) click 1; sleep 0.8
|
||||
xdotool mousemove $((MX + 141)) $((MY + 89)) click 1; sleep 1
|
||||
if [ -n "$(xdotool search --onlyvisible --name "FDesigner — Widgets")" ]; then
|
||||
ok palette-reopens-from-view-menu
|
||||
else bad palette-reopens-from-view-menu; fi
|
||||
# Clicking the canvas still works after palette + design interplay.
|
||||
xdotool mousemove $((MX + 300)) $((MY + 400)) click 1; sleep 0.5
|
||||
kill -0 $APP_PID 2>/dev/null && ok canvas-click-after-reopen || \
|
||||
bad canvas-click-after-reopen
|
||||
fi
|
||||
|
||||
# No GTK warnings/criticals from the palette windows in the app log.
|
||||
if grep -qE "Gtk-CRITICAL|Gdk-WARNING" /tmp/palette_app.log; then
|
||||
bad "app-log-warnings"; grep -E "Gtk-CRITICAL|Gdk-WARNING" /tmp/palette_app.log
|
||||
else ok app-log-clean; fi
|
||||
|
||||
kill $APP_PID 2>/dev/null || true
|
||||
trap - EXIT
|
||||
echo "== palette_window_tests: $pass passed, $fail failed ==$failed"
|
||||
[ $fail -eq 0 ]
|
||||
@@ -1,123 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Extensive generator compile test: generate the matrix of designs, then
|
||||
# compile EVERY generated project with -Wall -Wextra and run it briefly
|
||||
# under a virtual display. A generated app that starts and stays up
|
||||
# (killed by timeout, exit 124) counts as a run pass.
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
echo "== building harness =="
|
||||
g++ -O2 -Wall -std=c++17 -o tests/gen_matrix tests/gen_matrix.cpp src/generator.cpp src/cmake_build.cpp || exit 1
|
||||
|
||||
rm -rf tests/out
|
||||
echo "== generating =="
|
||||
tests/gen_matrix tests/out || exit 1
|
||||
|
||||
pass=0; fail=0; failed=""
|
||||
for d in tests/out/*/; do
|
||||
name=$(basename "$d")
|
||||
if ! (cd "$d" && make CXXFLAGS="-O2 -Wall -Wextra -std=c++17" >build.log 2>&1); then
|
||||
echo "FAIL $name (compile) — see $d/build.log"
|
||||
fail=$((fail+1)); failed="$failed $name(compile)"; continue
|
||||
fi
|
||||
if grep -q "warning" "$d/build.log"; then
|
||||
echo "FAIL $name (warnings) — see $d/build.log"
|
||||
fail=$((fail+1)); failed="$failed $name(warnings)"; continue
|
||||
fi
|
||||
timeout 3 xvfb-run -a "$d/app" >"$d/run.log" 2>&1
|
||||
rc=$?
|
||||
if [ $rc -ne 124 ]; then
|
||||
echo "FAIL $name (run exit $rc) — see $d/run.log"
|
||||
fail=$((fail+1)); failed="$failed $name(run:$rc)"; continue
|
||||
fi
|
||||
# The Adwaita pixbuf-loader warning is VM environment noise (missing
|
||||
# mime database under Xvfb), not a defect in generated code; any other
|
||||
# CRITICAL/WARNING fails the case.
|
||||
bad=$(grep -E "CRITICAL|WARNING \*\*" "$d/run.log" | grep -v "Could not load a pixbuf" || true)
|
||||
if [ -n "$bad" ]; then
|
||||
echo "FAIL $name (runtime warnings) — see $d/run.log"
|
||||
fail=$((fail+1)); failed="$failed $name(runtime)"; continue
|
||||
fi
|
||||
echo "PASS $name"
|
||||
pass=$((pass+1))
|
||||
done
|
||||
echo "== candle render test =="
|
||||
if g++ -O2 -Wall -std=c++17 -o tests/out/14_stockchart/render_test \
|
||||
tests/candle_render_test.cpp tests/out/14_stockchart/StockChart_001.cpp \
|
||||
-Itests/out/14_stockchart $(pkg-config --cflags --libs gtk+-3.0) \
|
||||
2>tests/out/14_stockchart/render_build.log; then
|
||||
if timeout 10 xvfb-run -a tests/out/14_stockchart/render_test; then
|
||||
echo "PASS candle-render"; pass=$((pass+1))
|
||||
else
|
||||
echo "FAIL candle-render"; fail=$((fail+1))
|
||||
fi
|
||||
else
|
||||
echo "FAIL candle-render (build) — see tests/out/14_stockchart/render_build.log"
|
||||
fail=$((fail+1))
|
||||
fi
|
||||
|
||||
echo "== indicator render test =="
|
||||
if g++ -O2 -Wall -std=c++17 -o tests/out/15_stockchart_indicators/render_test \
|
||||
tests/indicator_render_test.cpp tests/out/15_stockchart_indicators/StockChart_001.cpp \
|
||||
-Itests/out/15_stockchart_indicators $(pkg-config --cflags --libs gtk+-3.0) \
|
||||
2>tests/out/15_stockchart_indicators/render_build.log; then
|
||||
if timeout 10 xvfb-run -a tests/out/15_stockchart_indicators/render_test; then
|
||||
echo "PASS indicator-render"; pass=$((pass+1))
|
||||
else
|
||||
echo "FAIL indicator-render"; fail=$((fail+1))
|
||||
fi
|
||||
else
|
||||
echo "FAIL indicator-render (build) — see tests/out/15_stockchart_indicators/render_build.log"
|
||||
fail=$((fail+1))
|
||||
fi
|
||||
|
||||
echo "== drawings module test =="
|
||||
if g++ -O2 -Wall -Wextra -std=c++17 -o tests/out/drawings_test \
|
||||
tests/drawings_test.cpp -I src \
|
||||
$(pkg-config --cflags --libs cairo) \
|
||||
2>tests/out/drawings_build.log; then
|
||||
if tests/out/drawings_test >tests/out/drawings_test.log 2>&1; then
|
||||
echo "PASS drawings"; pass=$((pass+1))
|
||||
else
|
||||
echo "FAIL drawings — see tests/out/drawings_test.log"
|
||||
fail=$((fail+1))
|
||||
fi
|
||||
else
|
||||
echo "FAIL drawings (build) — see tests/out/drawings_build.log"
|
||||
fail=$((fail+1))
|
||||
fi
|
||||
|
||||
echo "== chart pro render test =="
|
||||
if g++ -O2 -Wall -std=c++17 -o tests/out/16_stockchart_pro/render_test \
|
||||
tests/chart_pro_render_test.cpp tests/out/16_stockchart_pro/StockChart_001.cpp \
|
||||
-Itests/out/16_stockchart_pro $(pkg-config --cflags --libs gtk+-3.0) \
|
||||
2>tests/out/16_stockchart_pro/render_build.log; then
|
||||
if timeout 15 xvfb-run -a tests/out/16_stockchart_pro/render_test; then
|
||||
echo "PASS chart-pro-render"; pass=$((pass+1))
|
||||
else
|
||||
echo "FAIL chart-pro-render"; fail=$((fail+1))
|
||||
fi
|
||||
else
|
||||
echo "FAIL chart-pro-render (build) — see tests/out/16_stockchart_pro/render_build.log"
|
||||
fail=$((fail+1))
|
||||
fi
|
||||
|
||||
echo "== chart pro screenshot (1024x768) =="
|
||||
if g++ -O2 -Wall -std=c++17 -o tests/out/16_stockchart_pro/screenshot \
|
||||
tests/chart_screenshot.cpp tests/out/16_stockchart_pro/MyWindow.cpp \
|
||||
tests/out/16_stockchart_pro/StockChart_001.cpp \
|
||||
-Itests/out/16_stockchart_pro $(pkg-config --cflags --libs gtk+-3.0) \
|
||||
2>tests/out/16_stockchart_pro/shot_build.log; then
|
||||
if timeout 20 xvfb-run -a tests/out/16_stockchart_pro/screenshot \
|
||||
tests/out/chart_pro_1024x768.png; then
|
||||
echo "PASS chart-pro-screenshot"; pass=$((pass+1))
|
||||
else
|
||||
echo "FAIL chart-pro-screenshot"; fail=$((fail+1))
|
||||
fi
|
||||
else
|
||||
echo "FAIL chart-pro-screenshot (build) — see tests/out/16_stockchart_pro/shot_build.log"
|
||||
fail=$((fail+1))
|
||||
fi
|
||||
|
||||
echo "== matrix: $pass passed, $fail failed =="
|
||||
[ $fail -eq 0 ]
|
||||
@@ -1,341 +0,0 @@
|
||||
// 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");
|
||||
// Comment-style region markers (the form the generator emits:
|
||||
// `// #region Name` / `// #endregion`) fold like bare #region.
|
||||
// An unclosed one and one inside a string open no fold.
|
||||
std::vector<std::string> clines = {
|
||||
" // #region Widget", // 0
|
||||
" int x = 1;", // 1
|
||||
" // #endregion", // 2
|
||||
" // #region Open", // 3: unclosed, no fold
|
||||
" int y = 2;", // 4
|
||||
"const char* s = \"// #region nope\";", // 5: in a string
|
||||
};
|
||||
std::vector<FoldRegion> cregs = codeview_find_regions(clines);
|
||||
bool cok = false;
|
||||
for (const auto& r : cregs)
|
||||
if (r.start_line == 0 && r.end_line == 2 && r.kind == "region")
|
||||
cok = true;
|
||||
check(cok, "comment-region-folds");
|
||||
check(cregs.size() == 1, "comment-region-count-1");
|
||||
|
||||
// 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;
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
#!/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"
|
||||
@@ -1,131 +0,0 @@
|
||||
// Widget tests: one project holding every Lazarus-style widget with
|
||||
// non-default properties; generate it, check per-widget markers in the
|
||||
// emitted code, and report PASS/FAIL per widget. The companion shell
|
||||
// script (tests/widget_tests.sh) compiles the generated app and runs it.
|
||||
// Usage: widget_tests [out_dir]
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../src/generator.h"
|
||||
#include "../src/project_io.h"
|
||||
#include "../src/props.h"
|
||||
|
||||
struct Spec {
|
||||
const char* type;
|
||||
const char* prop;
|
||||
const char* value;
|
||||
const char* marker; // must appear in <Name>.cpp
|
||||
};
|
||||
|
||||
static const Spec kSpecs[] = {
|
||||
{"Memo", "text", "Hello memo", "gtk_text_buffer_set_text"},
|
||||
{"GroupBox", "label", "Options", "gtk_frame_new"},
|
||||
{"Panel", "label", "Panel A", "gtk_frame_new"},
|
||||
{"Image", "file", "chart_pro_1024x768.png", "gtk_image_set_from_file"},
|
||||
{"Shape", "shape", "1", "cairo_arc"},
|
||||
{"Notebook", "pages", "One|Two|Three", "gtk_notebook_append_page"},
|
||||
{"ScrollBox", "label", "Scroll me", "gtk_scrolled_window_new"},
|
||||
{"Splitter", "position", "150", "gtk_paned_new"},
|
||||
{"StatusBar", "text", "All good", "gtk_statusbar_push"},
|
||||
{"ToolBar", "items", "Cut|Copy|Paste", "gtk_tool_button_new"},
|
||||
{"MenuBar", "menus", "File|Tools", "gtk_menu_item_new_with_label"},
|
||||
{"SpinEdit", "value", "42", "gtk_spin_button_new_with_range"},
|
||||
{"TrackBar", "value", "70", "gtk_scale_new_with_range"},
|
||||
{"ProgressBar", "fraction", "0.5", "gtk_progress_bar_new"},
|
||||
{"DateTimePicker", "date", "2026-11-25", "gtk_calendar_select_day"},
|
||||
{"ColorBox", "color", "#00ff00", "gtk_color_chooser_set_rgba"},
|
||||
{"ListView", "items", "x,1;y,2", "gtk_list_store_new"},
|
||||
{"TreeView", "items", "Root/Leaf;Other", "gtk_tree_store_new"},
|
||||
{"StringGrid", "rows", "3", "gtk_list_store_new"},
|
||||
{"Plot", "title", "Sine", "sin("},
|
||||
};
|
||||
|
||||
static std::string read_file(const std::string& path) {
|
||||
std::ifstream f(path);
|
||||
if (!f) return "";
|
||||
return std::string(std::istreambuf_iterator<char>(f),
|
||||
std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
std::string out = argc > 1 ? argv[1] : "/tmp/fdesigner_widgets_gen";
|
||||
Project p;
|
||||
p.title = "Widget Test";
|
||||
p.class_name = "MyWindow";
|
||||
int i = 0;
|
||||
for (const Spec& s : kSpecs) {
|
||||
Widget w;
|
||||
w.name = std::string(s.type) + "_001";
|
||||
w.type = s.type;
|
||||
w.x = 10 + (i % 4) * 210;
|
||||
w.y = 10 + (i / 4) * 150;
|
||||
const TypeInfo* t = find_type(s.type);
|
||||
w.width = t ? t->def_width : 100;
|
||||
w.height = t ? t->def_height : 30;
|
||||
for (const PropDef& d : props_for(s.type))
|
||||
if (d.def && d.def[0]) w.props[d.name] = d.def;
|
||||
for (const PropDef& d : common_props())
|
||||
if (d.def && d.def[0]) w.props[d.name] = d.def;
|
||||
if (find_prop(s.type, "label")) w.props["label"] = w.name;
|
||||
w.props[s.prop] = s.value;
|
||||
p.widgets.push_back(w);
|
||||
++i;
|
||||
}
|
||||
GenResult r = generate_project(p, p.widgets, out);
|
||||
if (!r.ok) {
|
||||
std::printf("FAIL generate: %s\n", r.error.c_str());
|
||||
return 1;
|
||||
}
|
||||
int pass = 0, fail = 0;
|
||||
for (const Spec& s : kSpecs) {
|
||||
std::string name = std::string(s.type) + "_001";
|
||||
std::string code = read_file(out + "/" + name + ".cpp");
|
||||
bool ok = !code.empty() &&
|
||||
code.find(s.marker) != std::string::npos;
|
||||
std::printf("%s %-16s marker '%s' in %s.cpp\n",
|
||||
ok ? "PASS" : "FAIL", s.type, s.marker, name.c_str());
|
||||
if (ok) ++pass; else ++fail;
|
||||
}
|
||||
// Every widget class file must exist, plus window + main + Makefile.
|
||||
for (const Spec& s : kSpecs) {
|
||||
std::string h = out + "/" + std::string(s.type) + "_001.h";
|
||||
if (!std::filesystem::exists(h)) {
|
||||
std::printf("FAIL %-16s missing %s\n", s.type, h.c_str());
|
||||
++fail;
|
||||
}
|
||||
}
|
||||
// Save/load round-trip (.fdj) for every new widget type.
|
||||
{
|
||||
std::string err;
|
||||
if (!save_project_file("/tmp/fdesigner_widgets.fdj", p, err)) {
|
||||
std::printf("FAIL save %s\n", err.c_str());
|
||||
++fail;
|
||||
} else {
|
||||
Project q;
|
||||
if (!load_project_file("/tmp/fdesigner_widgets.fdj", q, err)) {
|
||||
std::printf("FAIL load %s\n", err.c_str());
|
||||
++fail;
|
||||
} else if (q.widgets.size() != p.widgets.size()) {
|
||||
std::printf("FAIL round-trip count %zu != %zu\n",
|
||||
q.widgets.size(), p.widgets.size());
|
||||
++fail;
|
||||
} else {
|
||||
for (size_t k = 0; k < q.widgets.size(); ++k) {
|
||||
bool ok = q.widgets[k].type == p.widgets[k].type &&
|
||||
q.widgets[k].name == p.widgets[k].name &&
|
||||
q.widgets[k].props == p.widgets[k].props;
|
||||
std::printf("%s %-16s .fdj round-trip\n",
|
||||
ok ? "PASS" : "FAIL",
|
||||
q.widgets[k].type.c_str());
|
||||
if (ok) ++pass; else ++fail;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::printf("== widget_tests: %d passed, %d failed ==\n", pass, fail);
|
||||
return fail ? 1 : 0;
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lazarus-widget tests: designer self-test (Phase 7 places, edits, drags,
|
||||
# deletes and generates every new widget), then a generator-API project
|
||||
# holding every new widget: per-widget code markers, a -Wall -Wextra
|
||||
# compile of the generated app, and a brief run under Xvfb.
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
pass=0; fail=0; failed=""
|
||||
ok() { echo "PASS $1"; pass=$((pass+1)); }
|
||||
bad() { echo "FAIL $1"; fail=$((fail+1)); failed="$failed $1"; }
|
||||
|
||||
echo "== building fdesigner =="
|
||||
if make > /tmp/widget_make.log 2>&1; then ok make; else
|
||||
bad make; cat /tmp/widget_make.log; exit 1
|
||||
fi
|
||||
|
||||
echo "== designer self-test (includes Phase 7 Lazarus widgets) =="
|
||||
if FDESIGNER_SELFTEST=1 timeout 60 xvfb-run -a ./fdesigner \
|
||||
> /tmp/widget_selftest.log 2>&1; then
|
||||
if grep -q "SELFTEST PASS" /tmp/widget_selftest.log; then ok selftest;
|
||||
else bad "selftest(no PASS line)"; tail -20 /tmp/widget_selftest.log; fi
|
||||
else
|
||||
bad selftest; tail -20 /tmp/widget_selftest.log
|
||||
fi
|
||||
grep -E "GENERATED7" /tmp/widget_selftest.log || true
|
||||
|
||||
echo "== widget generator test (per-widget markers) =="
|
||||
if g++ -O2 -Wall -Wextra -std=c++17 -o /tmp/widget_tests \
|
||||
tests/widget_tests.cpp src/generator.cpp src/cmake_build.cpp src/project_io.cpp; then
|
||||
rm -rf /tmp/fdesigner_widgets_gen
|
||||
if /tmp/widget_tests /tmp/fdesigner_widgets_gen; then
|
||||
ok widget-markers
|
||||
else
|
||||
bad widget-markers
|
||||
fi
|
||||
else
|
||||
bad widget-tests-build
|
||||
fi
|
||||
|
||||
echo "== compile generated project (all new widgets) =="
|
||||
if (cd /tmp/fdesigner_widgets_gen && \
|
||||
make CXXFLAGS="-O2 -Wall -Wextra -std=c++17" >build.log 2>&1); then
|
||||
if grep -q "warning" /tmp/fdesigner_widgets_gen/build.log; then
|
||||
bad "generated-compile(warnings)"
|
||||
grep "warning" /tmp/fdesigner_widgets_gen/build.log | head
|
||||
else ok generated-compile; fi
|
||||
else
|
||||
bad generated-compile; cat /tmp/fdesigner_widgets_gen/build.log
|
||||
fi
|
||||
|
||||
echo "== run generated project briefly =="
|
||||
timeout 3 xvfb-run -a /tmp/fdesigner_widgets_gen/app \
|
||||
> /tmp/fdesigner_widgets_gen/run.log 2>&1
|
||||
rc=$?
|
||||
if [ $rc -ne 124 ]; then
|
||||
bad "generated-run(exit $rc)"; cat /tmp/fdesigner_widgets_gen/run.log
|
||||
else
|
||||
badlog=$(grep -E "CRITICAL|WARNING \*\*" \
|
||||
/tmp/fdesigner_widgets_gen/run.log | grep -v "Could not load a pixbuf" || true)
|
||||
if [ -n "$badlog" ]; then
|
||||
bad "generated-run(runtime warnings)"; echo "$badlog"
|
||||
else ok generated-run; fi
|
||||
fi
|
||||
|
||||
echo "== widget_tests: $pass passed, $fail failed ==$failed"
|
||||
[ $fail -eq 0 ]
|
||||
@@ -1,17 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Wrap src/drawings.h as a C++ raw-string header so the generator can
|
||||
# emit it into generated projects. Usage: embed_drawings.sh IN OUT
|
||||
set -e
|
||||
delim="FDDRAWINGS9b2c"
|
||||
if grep -q "$delim" "$1"; then
|
||||
echo "embed_drawings: delimiter collision in $1" >&2
|
||||
exit 1
|
||||
fi
|
||||
{
|
||||
echo "// Generated from src/drawings.h by tools/embed_drawings.sh."
|
||||
echo "// Do not edit; run 'make' to regenerate."
|
||||
echo "#pragma once"
|
||||
printf 'static const char kDrawingsHeader[] = R"%s(\n' "$delim"
|
||||
cat "$1"
|
||||
printf ')%s";\n' "$delim"
|
||||
} > "$2"
|
||||
@@ -1,17 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Wrap src/indicators.h as a C++ raw-string header so the generator can
|
||||
# emit it into generated projects. Usage: embed_indicators.sh IN OUT
|
||||
set -e
|
||||
delim="FDINDICATORS7f3a"
|
||||
if grep -q "$delim" "$1"; then
|
||||
echo "embed_indicators: delimiter collision in $1" >&2
|
||||
exit 1
|
||||
fi
|
||||
{
|
||||
echo "// Generated from src/indicators.h by tools/embed_indicators.sh."
|
||||
echo "// Do not edit; run 'make' to regenerate."
|
||||
echo "#pragma once"
|
||||
printf 'static const char kIndicatorsHeader[] = R"%s(\n' "$delim"
|
||||
cat "$1"
|
||||
printf ')%s";\n' "$delim"
|
||||
} > "$2"
|
||||
@@ -1,812 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- FDesigner main window. Authored for Glade / GtkBuilder, GTK 3.24. -->
|
||||
<interface>
|
||||
<requires lib="gtk+" version="3.24"/>
|
||||
<object class="GtkWindow" id="main_window">
|
||||
<property name="title">FDesigner — C++/GTK</property>
|
||||
<property name="default_width">1150</property>
|
||||
<property name="default_height">720</property>
|
||||
<child>
|
||||
<object class="GtkBox" id="root_box">
|
||||
<property name="orientation">vertical</property>
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkMenuBar" id="menubar">
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="menu_file">
|
||||
<property name="label">File</property>
|
||||
<property name="visible">True</property>
|
||||
<child type="submenu">
|
||||
<object class="GtkMenu" id="file_menu">
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_new">
|
||||
<property name="label">New</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_open">
|
||||
<property name="label">Open…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_save">
|
||||
<property name="label">Save…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkSeparatorMenuItem" id="mi_sep1">
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_generate">
|
||||
<property name="label">Generate C++/GTK…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_cmake_build">
|
||||
<property name="label">Build with CMake…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_cmake_open">
|
||||
<property name="label">Open CMake Project…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_cmake_settings">
|
||||
<property name="label">CMake Settings…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkSeparatorMenuItem" id="mi_sep2">
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_quit">
|
||||
<property name="label">Quit</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="menu_edit">
|
||||
<property name="label">Edit</property>
|
||||
<property name="visible">True</property>
|
||||
<child type="submenu">
|
||||
<object class="GtkMenu" id="edit_menu">
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_preferences">
|
||||
<property name="label">Preferences…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</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>
|
||||
<child>
|
||||
<object class="GtkCheckMenuItem" id="mi_view_palette">
|
||||
<property name="label">Widget Palette</property>
|
||||
<property name="visible">True</property>
|
||||
<property name="active">True</property>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="menu_debug">
|
||||
<property name="label">Debug</property>
|
||||
<property name="visible">True</property>
|
||||
<child type="submenu">
|
||||
<object class="GtkMenu" id="debug_menu">
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_debug_open">
|
||||
<property name="label">Open Debugger…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkSeparatorMenuItem" id="mi_debug_sep1">
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="menu_debugger_sub">
|
||||
<property name="label">Debugger</property>
|
||||
<property name="visible">True</property>
|
||||
<child type="submenu">
|
||||
<object class="GtkMenu" id="debugger_submenu">
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkCheckMenuItem" id="mi_dbg_break_main">
|
||||
<property name="label">Break on main</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkCheckMenuItem" id="mi_dbg_stop_entry">
|
||||
<property name="label">Stop on entry</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkCheckMenuItem" id="mi_dbg_pretty">
|
||||
<property name="label">Pretty-print values</property>
|
||||
<property name="visible">True</property>
|
||||
<property name="active">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkSeparatorMenuItem" id="mi_dbg_sep">
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_dbg_settings">
|
||||
<property name="label">Settings…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkMenuItem" id="mi_debug_settings">
|
||||
<property name="label">Debugger Settings…</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="expand">False</property>
|
||||
<property name="fill">True</property>
|
||||
<property name="position">0</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkPaned" id="main_paned">
|
||||
<property name="orientation">horizontal</property>
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkPaned" id="canvas_props_paned">
|
||||
<property name="orientation">horizontal</property>
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkScrolledWindow" id="canvas_scroll">
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkFixed" id="canvas">
|
||||
<property name="width_request">800</property>
|
||||
<property name="height_request">600</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="resize">True</property>
|
||||
<property name="shrink">True</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkBox" id="props_box">
|
||||
<property name="orientation">vertical</property>
|
||||
<property name="width_request">280</property>
|
||||
<property name="spacing">4</property>
|
||||
<property name="margin_start">6</property>
|
||||
<property name="margin_end">6</property>
|
||||
<property name="margin_top">6</property>
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkLabel" id="props_label">
|
||||
<property name="label"><b>Properties</b></property>
|
||||
<property name="use_markup">True</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkLabel" id="selected_label">
|
||||
<property name="label">No widget selected</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkGrid" id="props_grid">
|
||||
<property name="row_spacing">4</property>
|
||||
<property name="column_spacing">6</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="resize">False</property>
|
||||
<property name="shrink">False</property>
|
||||
</packing>
|
||||
</child>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="resize">True</property>
|
||||
<property name="shrink">True</property>
|
||||
</packing>
|
||||
</child>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="expand">True</property>
|
||||
<property name="fill">True</property>
|
||||
<property name="position">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkStatusbar" id="statusbar">
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="expand">False</property>
|
||||
<property name="fill">True</property>
|
||||
<property name="position">2</property>
|
||||
</packing>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
<object class="GtkWindow" id="palette_window">
|
||||
<property name="title">FDesigner — Widgets</property>
|
||||
<property name="default_width">250</property>
|
||||
<property name="default_height">780</property>
|
||||
<child>
|
||||
<object class="GtkScrolledWindow" id="palette_scroll">
|
||||
<property name="width_request">230</property>
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkGrid" id="palette_box">
|
||||
<property name="row_spacing">2</property>
|
||||
<property name="column_spacing">2</property>
|
||||
<property name="margin_start">2</property>
|
||||
<property name="margin_end">2</property>
|
||||
<property name="margin_top">2</property>
|
||||
<property name="margin_bottom">2</property>
|
||||
<property name="visible">True</property>
|
||||
<child>
|
||||
<object class="GtkLabel" id="palette_label">
|
||||
<property name="label"><b>Widgets</b></property>
|
||||
<property name="use_markup">True</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">0</property>
|
||||
<property name="width">2</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_button">
|
||||
<property name="label">Button</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">1</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_label">
|
||||
<property name="label">Label</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">1</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_entry">
|
||||
<property name="label">Entry</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">2</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_checkbutton">
|
||||
<property name="label">CheckButton</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">2</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_radiobutton">
|
||||
<property name="label">RadioButton</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">3</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_frame">
|
||||
<property name="label">Frame</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">3</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_combobox">
|
||||
<property name="label">ComboBox</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">4</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_listbox">
|
||||
<property name="label">ListBox</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">4</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_menubutton">
|
||||
<property name="label">MenuButton</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">5</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_canvas">
|
||||
<property name="label">Canvas</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">5</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_scale">
|
||||
<property name="label">Scale</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">6</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_scrollbar">
|
||||
<property name="label">Scrollbar</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">6</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_text">
|
||||
<property name="label">Text</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">7</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_toplevel">
|
||||
<property name="label">Toplevel</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">7</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_spreadsheet">
|
||||
<property name="label">Spreadsheet</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">8</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_stockchart">
|
||||
<property name="label">StockChart</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">8</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkLabel" id="pal_section_lazarus">
|
||||
<property name="label"><b>Lazarus — Basic</b></property>
|
||||
<property name="use_markup">True</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">9</property>
|
||||
<property name="width">2</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_memo">
|
||||
<property name="label">Memo</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">10</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_groupbox">
|
||||
<property name="label">GroupBox</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">10</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_panel">
|
||||
<property name="label">Panel</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">11</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_image">
|
||||
<property name="label">Image</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">11</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_shape">
|
||||
<property name="label">Shape</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">12</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkLabel" id="pal_section_containers">
|
||||
<property name="label"><b>Containers</b></property>
|
||||
<property name="use_markup">True</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">13</property>
|
||||
<property name="width">2</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_notebook">
|
||||
<property name="label">Notebook</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">14</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_scrollbox">
|
||||
<property name="label">ScrollBox</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">14</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_splitter">
|
||||
<property name="label">Splitter</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">15</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_statusbar">
|
||||
<property name="label">StatusBar</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">15</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_toolbar">
|
||||
<property name="label">ToolBar</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">16</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_menubar">
|
||||
<property name="label">MenuBar</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">16</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkLabel" id="pal_section_input">
|
||||
<property name="label"><b>Input</b></property>
|
||||
<property name="use_markup">True</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">17</property>
|
||||
<property name="width">2</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_spinedit">
|
||||
<property name="label">SpinEdit</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">18</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_trackbar">
|
||||
<property name="label">TrackBar</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">18</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_progressbar">
|
||||
<property name="label">ProgressBar</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">19</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_datetimepicker">
|
||||
<property name="label">DateTimePicker</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">19</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_colorbox">
|
||||
<property name="label">ColorBox</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">20</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkLabel" id="pal_section_data">
|
||||
<property name="label"><b>Data / Display</b></property>
|
||||
<property name="use_markup">True</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">21</property>
|
||||
<property name="width">2</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_listview">
|
||||
<property name="label">ListView</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">22</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_treeview">
|
||||
<property name="label">TreeView</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">22</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_stringgrid">
|
||||
<property name="label">StringGrid</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">0</property>
|
||||
<property name="top_attach">23</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkButton" id="pal_plot">
|
||||
<property name="label">Plot</property>
|
||||
<property name="visible">True</property>
|
||||
</object>
|
||||
<packing>
|
||||
<property name="left_attach">1</property>
|
||||
<property name="top_attach">23</property>
|
||||
<property name="width">1</property>
|
||||
<property name="height">1</property>
|
||||
</packing>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</interface>
|
||||