Files
alkane-toolkit/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp
T
noahandClaude Opus 4.8 6e785275da
source / check (pull_request) Skipped
verify / verify (pull_request) Canceled after 12m59s
feat(gui): two-choice restore, dialogs-during-scan, creds-from-settings
Restore-to-stock dialog overhaul (issues #46, #47, #48, #51): a two-source
restore -- the board's on-board stock backup (checkbox, auto-detected via the
merged alkane-flash onboard_stock_backup_present and greyed out with
set_enabled when absent) or a Bitmain stock firmware file picked with a Browse
button (OTA .tar.gz or SD .zip, any X17-series model). The alkane root login
comes from Settings (no per-dialog password field); on-board restore uses the
new stock_ops::start_restore_onboard over DSH's restore_from_onboard_backup.

Install dialog: password field removed too (#46); the login comes from Settings.

Dialogs during scan (#43): install/uninstall dialogs open and can be prepared
while a scan runs (new flash_busy gate); the scan is stopped only when the
operation actually starts (stop_scan_for_op) so the two never touch a board at
once.

Bug report (#50): the always-present "Open issue" button is gone; filing turns
it into a clickable "View issue #N" link.

wx-rs: add set_enabled (grey out a control); captured as patch 0013. Merges
DSH's alkane-flash on-board backup/restore method (sealed in stock_method.rs).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 13:53:28 -06:00

2370 lines
96 KiB
C++

// widgets_bridge.cpp — alkane-toolkit extension to wx-rs
// Adds the widget/event surface the toolkit UI needs on top of the upstream
// render-callback bridge (which is kept untouched).
// See thirdparty/wx-rs/patches/ for the patch queue that carries this file.
#include <wx/wx.h>
#include <wx/dataview.h>
#include <wx/checklst.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/button.h>
#include <wx/checkbox.h>
#include <wx/dialog.h>
#include <wx/timer.h>
#include <wx/vector.h>
#include <wx/gauge.h>
#include <wx/settings.h>
#include <wx/utils.h>
#include <wx/app.h>
#include <wx/rearrangectrl.h>
#include <wx/listctrl.h>
#include <wx/menu.h>
#include <wx/choice.h>
#include <wx/bmpbuttn.h>
#include <wx/bitmap.h>
#include <wx/bmpbndl.h>
#include <wx/image.h>
#include <wx/dcmemory.h>
#include <wx/dcgraph.h>
#include <wx/graphics.h>
#include <wx/wrapsizer.h>
#include <wx/filedlg.h>
#include <wx/statusbr.h>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <map>
#include <memory>
#include <vector>
#ifdef __WXMSW__
// Themed list-view colours, to draw selected rows the way the native renderer does.
#include <wx/msw/uxtheme.h>
#include <vssym32.h>
#endif
#ifdef __WXGTK__
// For native GtkTreeView rubber-band (click-drag) selection, which wx does not
// enable and which cannot be done via wx mouse events on GTK (the native widget
// grabs the pointer during a drag). Guarded so non-GTK builds are unaffected.
#include <gtk/gtk.h>
#endif
typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
static WxWidgetEventFn g_widget_event = nullptr;
#ifndef __WXGTK__
// Anchor row per data-view control for the wx-mouse-event rubber-band selection
// used with the generic wxDataViewCtrl (wxMSW and any other non-GTK port; GTK
// uses native GtkTreeView rubber-banding instead).
static std::map<wxDataViewCtrl*, int> g_drag_anchor;
#endif
// Event kinds (must match Rust WxEventKind in src/widgets.rs)
enum WxWidgetEventKind {
WxEV_BUTTON_CLICKED = 1,
WxEV_CLB_TOGGLED = 3,
WxEV_DVLC_VALUE_CHANGED = 4,
WxEV_DVLC_HEADER_CLICK = 5,
WxEV_DVLC_REORDERED = 6,
WxEV_TIMER_TICK = 7,
WxEV_DVLC_ACTIVATED = 8,
WxEV_DVLC_SELECTION_CHANGED = 9,
WxEV_DVLC_CONTEXT_MENU = 10,
WxEV_MENU_ITEM = 11,
WxEV_CHOICE_CHANGED = 12,
WxEV_SYS_COLOUR = 13,
WxEV_DEFERRED = 14,
WxEV_DVLC_HEADER_RIGHT_CLICK = 15,
WxEV_SIZE = 16, // p1 = new client width, p2 = new client height
};
// Sizes cross the Rust <-> C++ boundary in DIPs (device-independent pixels,
// 1/96 inch: the size at 100 % display scale). The bridge converts them for the
// window they apply to. wxGTK and wxOSX lay out in logical pixels already, so
// FromDIP/ToDIP are the identity there and nothing changes; per-monitor-DPI-
// aware wxMSW works in physical pixels, where a 180 px column must become
// 270 px at 150 % or text clips. Non-positive values (wxDefaultCoord and the
// like) pass through untouched.
static wxWindow* DipWindow(wxWindow* win) {
if (win) return win;
return wxTheApp ? wxTheApp->GetTopWindow() : nullptr;
}
static int PxFromDip(wxWindow* win, int dip) {
wxWindow* w = DipWindow(win);
return (w && dip > 0) ? w->FromDIP(dip) : dip;
}
static int DipFromPx(wxWindow* win, int px) {
wxWindow* w = DipWindow(win);
return (w && px > 0) ? w->ToDIP(px) : px;
}
// A list store that carries an optional per-row foreground colour plus an
// alternating-row (zebra) background, surfaced to the native control via
// GetAttrByRow. The zebra background is set on odd rows only; because it is a
// BACKGROUND attr (not a foreground one), it does not affect the SegmentRenderer
// "no explicit colour -> default text colour" path, and the native selection
// highlight still paints over it for selected rows.
class AttrListStore : public wxDataViewListStore {
public:
std::vector<wxColour> row_fg;
wxColour zebra; // odd-row background; unset (=off) unless the app sets it
// Per-cell hover tooltip text, keyed by (row, model column). Used for the
// Errors column's full-message tooltip (see the GTK query-tooltip handler).
std::map<std::pair<unsigned, unsigned>, wxString> cell_tip;
// Per-ICON hover tooltips for a cell (round 15 #15): the Health column stores
// one tooltip per component icon so the tooltip pertains to the icon under the
// pointer, not the whole cell.
std::map<std::pair<unsigned, unsigned>, std::vector<wxString>> icon_tip;
bool GetAttrByRow(unsigned int row, unsigned int col,
wxDataViewItemAttr& attr) const override {
(void)col;
bool set = false;
if (row < row_fg.size() && row_fg[row].IsOk()) {
attr.SetColour(row_fg[row]);
set = true;
}
if (zebra.IsOk() && (row % 2 == 1)) {
attr.SetBackgroundColour(zebra);
set = true;
}
return set;
}
};
// A wxDataViewCustomRenderer that draws a cell value made of coloured text
// runs. The encoding matches alkane_gui::model::encode_segments: segments are
// joined by U+001F (ASCII unit separator); each segment is an optional
// 6-hex-digit RRGGBB colour followed by U+001E (ASCII record separator) and
// then its plain text. A value containing no U+001E at all -- e.g. any
// ordinary string -- is drawn as a single run in the default text colour, so
// this renderer is safe to use in place of a plain text column.
namespace {
struct ColorSegment {
bool has_colour = false;
wxColour colour;
wxString text;
};
std::vector<ColorSegment> ParseColorSegments(const wxString& value) {
std::vector<ColorSegment> segs;
if (value.Find(wxUniChar(0x1e)) == wxNOT_FOUND) {
ColorSegment s;
s.text = value;
segs.push_back(s);
return segs;
}
wxString rest = value;
for (;;) {
int sep = rest.Find(wxUniChar(0x1f));
wxString piece = (sep == wxNOT_FOUND) ? rest : rest.Left(sep);
ColorSegment s;
int csep = piece.Find(wxUniChar(0x1e));
if (csep == wxNOT_FOUND) {
s.text = piece;
} else {
wxString hex = piece.Left(csep);
s.text = piece.Mid(csep + 1);
unsigned long v;
if (hex.length() == 6 && hex.ToULong(&v, 16)) {
s.colour = wxColour((unsigned char)((v >> 16) & 0xff),
(unsigned char)((v >> 8) & 0xff),
(unsigned char)(v & 0xff));
s.has_colour = true;
}
}
segs.push_back(s);
if (sep == wxNOT_FOUND) break;
rest = rest.Mid(sep + 1);
}
return segs;
}
// Shape sentinels a segment's text may carry instead of glyphs (round 11
// #10/#13): a single control char selects a small vector icon drawn in the
// segment's colour. These are control characters (never emoji/pictographs) so
// they are safe in source and independent of the font's glyph coverage.
const wxUniChar SHAPE_DOT = 0x07; // filled status dot (hashboards, locate light)
const wxUniChar SHAPE_LOCK = 0x02; // closed padlock (locked / view-only)
const wxUniChar SHAPE_UNLOCK = 0x03; // open padlock (unlocked / writable)
// Status-column KPI icons (round 12 #11): each renders the same Font Awesome
// glyph as its dashboard KPI card, drawn from an SVG registered by the Rust side
// (see wxbr_register_shape_svg). No vector fallback -- if unregistered the cell
// is simply blank.
const wxUniChar SHAPE_HASHING = 0x04; // rabbit (hashing)
const wxUniChar SHAPE_SLOW = 0x05; // turtle (slow)
const wxUniChar SHAPE_NOTHASHING = 0x06; // cracked wine glass (not hashing)
const wxUniChar SHAPE_PAUSED = 0x08; // otter (paused)
const wxUniChar SHAPE_PULSE_DOT = 0x0B; // locate-light dot that fades in/out (round 12 #6)
// Component-health icons (round 13 #3): SVG-backed and registered from the Rust
// side, recoloured per component state (grey/red/yellow/green) by DrawShape's
// SVG path. Blank if unregistered.
const wxUniChar SHAPE_BOLT = 0x0C; // power supply
const wxUniChar SHAPE_BRAIN = 0x0E; // control board
const wxUniChar SHAPE_FAN = 0x0F; // cooling fan
const wxUniChar SHAPE_CHIP = 0x10; // hashboard
// Locate-light beacon (round 15 #6): a green dot above a red dot, both flashing
// quickly while the miner's locate light is on.
const wxUniChar SHAPE_LIGHT_BEACON = 0x11;
// Health-column alignment gap (round 15 #5): draws nothing but advances by one
// health-icon width, so component icons line up in fixed slots across rows even
// when a miner has fewer fans/boards than the widest in the fleet.
const wxUniChar SHAPE_GAP = 0x12;
const int SHAPE_ADVANCE = 15; // horizontal space one shape occupies
// Table zoom factor (round 14 #3), 1.0 = 100%. A status-bar slider scales the
// table font (native columns) and, through this factor, the custom-renderer
// icon sizes so the whole table zooms together.
double g_table_zoom = 1.0;
static wxDataViewCtrl* g_zoom_table = nullptr; // the table the zoom scales
static wxFont g_zoom_base_font; // its font at 100% (captured lazily)
static wxVector<int> g_zoom_base_w; // column widths at 100% (per column)
static wxSlider* g_zoom_slider = nullptr; // the status-bar zoom slider
static wxTextCtrl* g_zoom_entry = nullptr; // the editable "100%" field next to it
// Display density for the custom-drawn shapes and icons. wxGTK and wxOSX draw
// in DPI-independent logical pixels, so FromDIP() is the identity there and
// these change nothing. Per-monitor-DPI-aware wxMSW draws in physical pixels,
// so a 15 px shape slot has to become 23 px at 150 % to keep the same physical
// size as the (already scaled) text beside it.
static double DipFactor() {
return g_zoom_table ? g_zoom_table->FromDIP(1000) / 1000.0 : 1.0;
}
static int Dip(int px) { return (int)(px * DipFactor() + 0.5); }
// Space one vector shape occupies, at the current display density.
static int ShapeAdvance() { return Dip(SHAPE_ADVANCE); }
// Icon size factor: the table zoom (round 14 #3) times the display density.
static double ShapeScale() { return g_table_zoom * DipFactor(); }
// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
// the timer can invalidate exactly it.
double g_pulse_phase = 0.0;
wxDataViewCtrl* g_pulse_target = nullptr;
bool IsShapeSentinel(const wxString& s, wxUniChar& out) {
if (s.length() != 1) return false;
wxUniChar c = s[0];
if (c == SHAPE_DOT || c == SHAPE_LOCK || c == SHAPE_UNLOCK ||
c == SHAPE_HASHING || c == SHAPE_SLOW || c == SHAPE_NOTHASHING ||
c == SHAPE_PAUSED || c == SHAPE_PULSE_DOT || c == SHAPE_LIGHT_BEACON ||
c == SHAPE_GAP ||
c == SHAPE_BOLT || c == SHAPE_BRAIN || c == SHAPE_FAN || c == SHAPE_CHIP) {
out = c;
return true;
}
return false;
}
// Blend `fg` toward `bg` by alpha (1.0 = fully fg), used to fade the locate dot.
wxColour BlendColour(const wxColour& bg, const wxColour& fg, double a) {
auto mix = [a](unsigned char b, unsigned char f) {
double v = (double)b * (1.0 - a) + (double)f * a + 0.5;
if (v < 0) v = 0;
if (v > 255) v = 255;
return (unsigned char)v;
};
return wxColour(mix(bg.Red(), fg.Red()), mix(bg.Green(), fg.Green()), mix(bg.Blue(), fg.Blue()));
}
// Drives the locate-light dot's fade (round 12 #6): while running it advances the
// phase and repaints the treeview so the SHAPE_PULSE_DOT cells re-render at the
// new opacity. Runs only while at least one locate light is flashing.
class PulseTimer : public wxTimer {
public:
void Notify() override {
g_pulse_phase += 0.4; // ~1.6 s cycle at the 100 ms tick below
if (!g_pulse_target) return;
// A plain Refresh() does not re-invoke the custom cell renderer under wxGTK
// (GtkTreeView caches rendered cells); emitting a row change does, so the
// SHAPE_PULSE_DOT cells re-render at the new phase. The timer only runs while
// a light is flashing, so touching every row here is cheap.
AttrListStore* store = dynamic_cast<AttrListStore*>(g_pulse_target->GetModel());
if (store) {
unsigned int n = store->GetItemCount();
for (unsigned int r = 0; r < n; r++) store->RowChanged(r);
} else {
g_pulse_target->Refresh();
}
}
};
PulseTimer* g_pulse_timer = nullptr;
void SetLightPulse(bool on) {
if (!g_pulse_timer) g_pulse_timer = new PulseTimer();
if (on) {
if (!g_pulse_timer->IsRunning()) g_pulse_timer->Start(100);
} else {
g_pulse_timer->Stop();
if (g_pulse_target) g_pulse_target->Refresh();
}
}
// Registry of SVG-backed shape icons (round 12 #9 access padlocks, #11 status
// icons). The Rust side registers a raw SVG (with its viewBox dims for aspect)
// per sentinel; DrawShape recolours it to the segment colour, rasterises once
// per (sentinel, colour, height), caches the bitmap, and draws it. The access
// padlocks (0x02/0x03) fall back to a hand-drawn vector when unregistered.
struct ShapeSvg {
wxString svg;
int vbw;
int vbh;
};
std::map<int, ShapeSvg> g_shape_svgs;
std::map<uint64_t, wxBitmap> g_shape_bmp_cache;
const ShapeSvg* LookupShapeSvg(wxUniChar shape) {
auto it = g_shape_svgs.find((int)shape.GetValue());
return it == g_shape_svgs.end() ? nullptr : &it->second;
}
// Recolour an SVG to `c`, matching the Rust svg_recolored(): replace
// fill="currentColor" and inject a root fill so shapes that omit a fill inherit
// the colour too (e.g. the Font Awesome Free otter).
wxString RecolorShapeSvg(const wxString& svg, const wxColour& c) {
wxString hex = wxString::Format("#%02X%02X%02X", (int)c.Red(), (int)c.Green(), (int)c.Blue());
wxString s = svg;
s.Replace("currentColor", hex);
int pos = s.Find("<svg ");
if (pos != wxNOT_FOUND) s.insert((size_t)pos + 5, wxString("fill=\"") + hex + "\" ");
return s;
}
const wxBitmap& ShapeBitmap(wxUniChar shape, const ShapeSvg& sv, const wxColour& col,
int w, int h) {
uint64_t rgb = ((uint64_t)col.Red() << 16) | ((uint64_t)col.Green() << 8) | (uint64_t)col.Blue();
uint64_t key = ((uint64_t)(unsigned)shape.GetValue() << 40) | (rgb << 8) | (uint64_t)(h & 0xFF);
auto it = g_shape_bmp_cache.find(key);
if (it != g_shape_bmp_cache.end()) return it->second;
wxString colored = RecolorShapeSvg(sv.svg, col);
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(colored.ToUTF8().data(), wxSize(w, h));
wxBitmap bmp = bundle.GetBitmap(wxSize(w, h));
return g_shape_bmp_cache.emplace(key, bmp).first->second;
}
// Draw one shape sentinel centred at x; returns the horizontal space it used
// (SHAPE_ADVANCE for the vector shapes, the icon width for a wider SVG icon).
// `bg` is the cell background the shape sits on, used to fade the pulsing dot.
int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
const wxColour& colour, const wxColour& bg) {
int cy = cell.y + cell.height / 2;
// Health-column alignment gap (round 15 #5): occupy one health-icon width but
// draw nothing, so component icons line up in fixed slots across rows. The
// health icons are square, so the advance is (h - 3) just like a real one.
if (shape == SHAPE_GAP) {
int h = cell.height - 1;
int cap = (int)(28 * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
int adv = h - 3;
return adv < 1 ? 1 : adv;
}
// SVG-backed icon (access padlocks #9, status KPI icons #11): recolour to the
// segment colour, rasterise (cached), and draw centred in its slot.
if (const ShapeSvg* sv = LookupShapeSvg(shape)) {
// Component-health icons render bigger (nearly the full row height) and pack
// tighter than a padlock/status icon, so a row of power/control/fan/board
// icons stays large and compact (round 14 #1).
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
int h = cell.height - (health ? 1 : 4);
int cap = (int)((health ? 28 : 15) * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
int w = (sv->vbh > 0) ? (int)((double)h * sv->vbw / sv->vbh + 0.5) : h;
if (w < 1) w = 1;
// The Font Awesome fan and brain glyphs fill their square box more than the
// other health icons (chip/bolt), so at the shared size they read as oversized.
// Draw them a bit smaller, centred in their full-size slot, so the slot advance
// and the per-icon tooltip hit-test (both keyed to the full width) are
// unchanged (round 17 R1; round 18 #1 brain).
int dw = w, dh = h;
double glyph_scale = (shape == SHAPE_FAN) ? 0.80 : (shape == SHAPE_BRAIN) ? 0.82 : 1.0;
if (glyph_scale < 1.0) {
dh = (int)(h * glyph_scale + 0.5);
if (dh < 8) dh = 8;
dw = (sv->vbh > 0) ? (int)((double)dh * sv->vbw / sv->vbh + 0.5) : dh;
if (dw < 1) dw = 1;
}
const wxBitmap& bmp = ShapeBitmap(shape, *sv, colour, dw, dh);
if (bmp.IsOk()) {
if (health) {
// UNIFORM fixed-width slot (round 19): every health icon (and the
// alignment gap) advances by the same amount -- the square (h - 3) -- so
// power/control/fan/board icons line up in fixed columns across rows
// regardless of each glyph's aspect ratio (a narrow bolt or a shrunk fan
// no longer shifts the icons after it). Each glyph is centred in its slot.
// This matches SHAPE_GAP's advance and the per-icon tooltip hit-test.
int adv = h - 3;
if (adv < 1) adv = 1;
dc->DrawBitmap(bmp, x + (adv - dw) / 2, cy - dh / 2, true);
return adv;
}
int slot = (w > ShapeAdvance()) ? w : ShapeAdvance();
dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
return slot;
}
}
#ifdef __WXMSW__
// GDI does not anti-alias, so the dots and the padlock came out jagged next
// to the smooth SVG icons. Draw the vector shapes through GDI+ instead, as
// Cairo already does on GTK; the context inherits the DC's origin, scale and
// clip (the same approach wx's own generic markup renderer takes).
std::unique_ptr<wxGCDC> smooth;
if (wxGraphicsContext* gc = wxGraphicsContext::CreateFromUnknownDC(*dc)) {
smooth.reset(new wxGCDC(gc));
dc = smooth.get();
}
#endif
const int adv = ShapeAdvance();
int cx = x + adv / 2;
if (shape == SHAPE_LIGHT_BEACON) {
// A green dot above a red dot, both flashing quickly (round 15 #6). The blink
// is a fast on/off (~0.5 s) driven by the shared pulse phase.
double a = (std::sin(g_pulse_phase * 3.0) > 0.0) ? 1.0 : 0.18;
wxColour green = BlendColour(bg, wxColour(30, 175, 70), a);
wxColour red = BlendColour(bg, wxColour(215, 45, 40), a);
int r = Dip(3);
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(green));
dc->DrawCircle(cx, cy - (r + 1), r);
dc->SetBrush(wxBrush(red));
dc->DrawCircle(cx, cy + (r + 1), r);
return adv;
}
if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
wxColour fill = colour;
if (shape == SHAPE_PULSE_DOT) {
// Fade between ~0.3 and 1.0 opacity over a ~1.6 s cycle (round 12 #6).
double a = 0.3 + 0.7 * (0.5 + 0.5 * std::sin(g_pulse_phase));
fill = BlendColour(bg, colour, a);
}
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(fill));
dc->DrawCircle(cx, cy, Dip(4));
return adv;
}
// Padlock: a filled body with a staple shackle above. The colour carries the
// state (green = unlocked, red = locked); the shackle is drawn ajar when open.
bool open = (shape == SHAPE_UNLOCK);
int bw = Dip(9), bh = Dip(7);
int bx = cx - bw / 2;
int by = cy - bh / 2 + 1;
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(colour));
dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5 * DipFactor());
dc->SetBrush(*wxTRANSPARENT_BRUSH);
dc->SetPen(wxPen(colour, Dip(2)));
int sr = Dip(3);
int legTop = by - sr - 1;
int lx = cx - sr, rx = cx + sr;
dc->DrawLine(lx, by, lx, legTop); // left leg
dc->DrawLine(lx, legTop, rx, legTop); // top bar
if (open)
dc->DrawLine(rx, legTop, rx, legTop + sr); // ajar: right leg lifted
else
dc->DrawLine(rx, legTop, rx, by); // closed: right leg to body
return adv;
}
} // namespace
// True when selected rows keep their own background under a light, translucent
// highlight (the Explorer list-view style of Windows 10/11 with visual styles)
// rather than a solid highlight colour.
static bool SelectionIsTranslucent(wxWindow* win) {
#ifdef __WXMSW__
if (win && wxUxThemeIsActive()) {
wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
return ::IsThemePartDefined(theme, LVP_LISTITEM, 0) != 0;
}
#else
(void)win;
#endif
return false;
}
// Text colour for a selected row, matching the platform's native data-view text
// renderer. Windows 10/11 (visual styles on) draw the Explorer list-view
// selection: a light translucent highlight under the normal dark text, taken
// from the theme (dark-mode aware). Elsewhere -- GTK, or Windows with visual
// styles off / high contrast -- the selection is a solid highlight, so the text
// switches to the system highlight-text colour.
static wxColour SelectedTextColour(wxWindow* win) {
#ifdef __WXMSW__
if (SelectionIsTranslucent(win)) {
wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
wxColour c = theme.GetColour(LVP_LISTITEM, TMT_TEXTCOLOR, LISS_SELECTED);
if (c.IsOk()) return c;
}
#else
(void)win;
#endif
return wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
}
class SegmentRenderer : public wxDataViewCustomRenderer {
public:
SegmentRenderer()
: wxDataViewCustomRenderer(wxASCII_STR("string"), wxDATAVIEW_CELL_INERT) {}
bool SetValue(const wxVariant& value) override {
m_value = value.GetString();
return true;
}
bool GetValue(wxVariant& value) const override {
value = m_value;
return true;
}
bool Render(wxRect cell, wxDC* dc, int state) override {
bool selected = (state & wxDATAVIEW_CELL_SELECTED) != 0;
// wxGTK does NOT paint a custom renderer's cell background, so the per-row
// (zebra) background set via GetAttrByRow shows on the native columns but
// not here -- the zebra looked inconsistent across columns. Paint it here so
// every column stripes the same (skip when the row is selected: the control
// already drew the selection highlight).
if (!selected && GetAttr().HasBackgroundColour()) {
dc->SetBrush(wxBrush(GetAttr().GetBackgroundColour()));
dc->SetPen(*wxTRANSPARENT_PEN);
// The `cell` rect wx hands a custom renderer is shrunk to the content
// (text/shape) size in BOTH dimensions by the alignment logic, so filling
// it alone left the zebra covering only a content-sized band -- and since
// shape cells (dots) and text cells have different content heights, the
// stripes ended up unequal across columns. Fill an over-sized rect (full
// column width, and well beyond the row vertically); wxGTK clips the cell
// DC to the real cell background area, so this lands exactly on the full
// row height of this cell without bleeding into neighbours (round 11 #1/#3).
wxRect bg = cell;
if (wxDataViewColumn* owner = const_cast<SegmentRenderer*>(this)->GetOwner()) {
int cw = owner->GetWidth();
// Extend BOTH directions by the column width. For a right-aligned column
// (round 19 #21) wx anchors `cell` at the content's left edge (near the
// column's right side), so extending only rightward left the column's left
// portion unstriped; over-spanning both sides and letting the cell-DC clip
// trim it fills the whole cell regardless of alignment (round 19 review M1).
bg.x -= cw;
bg.width += 2 * cw;
}
bg.y -= 40;
bg.height += 80;
dc->DrawRectangle(bg);
}
wxDataViewColumn* owner_col = const_cast<SegmentRenderer*>(this)->GetOwner();
wxColour highlight =
SelectedTextColour(owner_col ? owner_col->GetOwner() : nullptr);
// An uncoloured (default) segment -- the "/" in a combined cell, a "Stock"
// firmware family, etc. -- must dim exactly like the native columns when the
// top-level window is backdropped. wxGTK dims a native cell's text via the
// widget's themed state colour, but a custom renderer's DC keeps the normal
// WINDOWTEXT, so ask the tree widget for its themed text colour AT ITS
// CURRENT STATE (which carries GTK_STATE_FLAG_BACKDROP while unfocused) and
// use that; off-GTK (or if the widget isn't reachable) fall back to the DC
// then the system colour (round 11 #1/#7).
wxColour plain;
if (GetAttr().HasColour()) {
plain = GetAttr().GetColour();
} else {
plain = ThemedTextColour();
}
if (!plain.IsOk()) {
plain = dc->GetTextForeground();
}
if (!plain.IsOk()) {
plain = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
}
// Draw segment text in the control's current font so it scales with the
// table zoom exactly like the native columns (round 14 #3); the DC otherwise
// keeps a default font that ignores SetFont on the control.
if (g_zoom_table && g_zoom_table->GetFont().IsOk()) {
dc->SetFont(g_zoom_table->GetFont());
}
wxCoord x = cell.x;
for (const ColorSegment& seg : ParseColorSegments(m_value)) {
// Shape segments (status dots, access padlock) keep their own semantic
// colour even on a selected row, so the green/red reading survives the
// selection highlight (round 11 #10/#13).
wxUniChar shape;
if (IsShapeSentinel(seg.text, shape)) {
// Background the shape sits on, so the pulsing locate dot fades toward it.
wxColour cellbg;
if (selected && !SelectionIsTranslucent(owner_col ? owner_col->GetOwner() : nullptr)) {
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
} else if (GetAttr().HasBackgroundColour()) {
cellbg = GetAttr().GetBackgroundColour();
} else {
#ifdef __WXOSX__
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
#else
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
#endif
}
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
continue;
}
if (seg.text.IsEmpty()) continue;
dc->SetTextForeground(selected ? highlight : (seg.has_colour ? seg.colour : plain));
wxSize extent = dc->GetTextExtent(seg.text);
wxCoord y = cell.y + (cell.height - extent.GetHeight()) / 2;
dc->DrawText(seg.text, x, y);
x += extent.GetWidth();
}
return true;
}
wxSize GetSize() const override {
int w = 0, h = 0;
for (const ColorSegment& seg : ParseColorSegments(m_value)) {
wxUniChar shape;
if (IsShapeSentinel(seg.text, shape)) {
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
int adv = ShapeAdvance();
// Health icons measure bigger and pack tighter, and report a taller
// content height so the row grows to fit them (round 14 #1). Sizes scale
// with the table zoom (round 14 #3).
int hh = (int)((health ? 22 : 15) * ShapeScale() + 0.5);
if (hh < 8) hh = 8;
// The alignment gap is one health-icon-width slot that draws nothing
// (round 15 #5); health icons are square, so its advance is hh - 3.
if (shape == SHAPE_GAP) {
adv = hh - 3;
if (adv < 1) adv = 1;
} else if (const ShapeSvg* sv = LookupShapeSvg(shape)) {
int ww = (sv->vbh > 0) ? (int)((double)hh * sv->vbw / sv->vbh + 0.5) : hh;
if (health) {
// UNIFORM fixed-width slot (round 19), matching DrawShape + the gap, so
// every health icon lines up in fixed columns across rows regardless of
// its glyph aspect. Width is measured square (hh - 3), not per-glyph.
adv = hh - 3;
if (adv < 1) adv = 1;
} else if (ww > adv) {
adv = ww;
}
}
w += adv;
if (h < hh) h = hh;
continue;
}
wxSize e = GetTextExtent(seg.text);
w += e.GetWidth();
if (e.GetHeight() > h) h = e.GetHeight();
}
if (w < 1) w = 1;
if (h < 1) h = 1;
return wxSize(w, h);
}
private:
// The owning tree widget's themed text colour at its current GTK state, so
// uncoloured segments dim on window-backdrop like the native columns
// (round 11 #1/#7). Returns an invalid colour off wxGTK or when the widget is
// unreachable, so the caller falls back to the DC / system colour.
wxColour ThemedTextColour() const {
#ifdef __WXGTK__
wxDataViewColumn* col = const_cast<SegmentRenderer*>(this)->GetOwner();
if (col && col->GetOwner()) {
GtkWidget* tv = col->GetOwner()->GtkGetTreeView();
if (tv && GTK_IS_WIDGET(tv)) {
// The treeview's own state flags do NOT reliably carry
// GTK_STATE_FLAG_BACKDROP (that lives on the toplevel), so query the
// toplevel window's active state directly and force BACKDROP onto the
// style-context state when it is inactive. Then the themed cell text
// colour matches what GTK paints on the native columns when the window
// loses focus (round 11 #1/#7).
GtkWidget* top = gtk_widget_get_toplevel(tv);
bool active = GTK_IS_WINDOW(top) && gtk_window_is_active(GTK_WINDOW(top));
GtkStyleContext* ctx = gtk_widget_get_style_context(tv);
GtkStateFlags st = gtk_widget_get_state_flags(tv);
st = active ? (GtkStateFlags)(st & ~GTK_STATE_FLAG_BACKDROP)
: (GtkStateFlags)(st | GTK_STATE_FLAG_BACKDROP);
GdkRGBA c;
gtk_style_context_save(ctx);
gtk_style_context_set_state(ctx, st);
gtk_style_context_get_color(ctx, gtk_style_context_get_state(ctx), &c);
gtk_style_context_restore(ctx);
return wxColour((unsigned char)(c.red * 255.0 + 0.5),
(unsigned char)(c.green * 255.0 + 0.5),
(unsigned char)(c.blue * 255.0 + 0.5));
}
}
#elif defined(__WXOSX__)
// The DC arrives with the control's foreground colour, which is not the
// theme-aware label colour native cells use; take the list text colour so
// uncoloured segments follow light/dark like the native columns.
return wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT);
#endif
return wxColour();
}
wxString m_value;
};
extern "C" {
void wxbr_set_widget_event_fn(WxWidgetEventFn f) { g_widget_event = f; }
// ---- window tree / sizers -------------------------------------------------
void* wxbr_main_frame() { return (void*)wxTheApp->GetTopWindow(); }
void* wxbr_panel(void* parent) {
return (void*)new wxPanel((wxWindow*)parent, wxID_ANY);
}
void* wxbr_box_sizer(int vertical) {
return (void*)new wxBoxSizer(vertical ? wxVERTICAL : wxHORIZONTAL);
}
// A box sizer that wraps its items onto additional lines instead of shrinking
// them when the available space runs out. wxWrapSizer is a wxBoxSizer
// subclass, so it accepts the same add/add_sizer/add_spacer/add_stretch and
// set_sizer_on calls as wxbr_box_sizer's result.
void* wxbr_wrap_sizer(int vertical) {
// wxREMOVE_LEADING_SPACES only: drop the default wxEXTEND_LAST_ON_EACH_LINE so
// the last item on a line is NOT stretched to fill the row (keeps fixed-size
// items -- e.g. the uniform KPI cards -- the same size).
return (void*)new wxWrapSizer(vertical ? wxVERTICAL : wxHORIZONTAL,
wxREMOVE_LEADING_SPACES);
}
// flag bits (must match Rust sizer_flags):
// 1 = EXPAND, 2 = ALIGN_CENTRE_VERTICAL, 4 = wxALL, 8 = wxTOP,
// 16 = wxBOTTOM, 32 = wxLEFT, 64 = wxRIGHT
void wxbr_sizer_add(void* sizer, void* win, int proportion, int flags, int border) {
int f = 0;
if (flags & 1) f |= wxEXPAND;
if (flags & 2) f |= wxALIGN_CENTRE_VERTICAL;
if (flags & 4) f |= wxALL;
if (flags & 8) f |= wxTOP;
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, PxFromDip((wxWindow*)win, border));
}
void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags, int border) {
int f = 0;
if (flags & 1) f |= wxEXPAND;
if (flags & 2) f |= wxALIGN_CENTRE_VERTICAL;
if (flags & 4) f |= wxALL;
if (flags & 8) f |= wxTOP;
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f,
PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), border));
}
void wxbr_sizer_add_spacer(void* sizer, int px) {
((wxSizer*)sizer)->AddSpacer(PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), px));
}
void wxbr_sizer_add_stretch(void* sizer, int proportion) {
((wxSizer*)sizer)->AddStretchSpacer(proportion);
}
void wxbr_set_sizer(void* win, void* sizer) {
((wxWindow*)win)->SetSizer((wxSizer*)sizer);
}
// Re-run this window's sizer to (re)position its children. Needed after a
// child window is added to an already-installed sizer (e.g. the table, which
// is created after the frame's sizer is set and rebuilt on column changes).
void wxbr_layout(void* win) { ((wxWindow*)win)->Layout(); }
// Remove a child window from a sizer without destroying the window. Call this
// before destroying a sizer-managed window so the sizer keeps no dangling item.
void wxbr_sizer_detach(void* sizer, void* win) {
((wxSizer*)sizer)->Detach((wxWindow*)win);
}
// Show or hide a sizer-managed child window AND reclaim (or restore) its space
// on the next Layout(). Used to collapse the wide KPI cards when the window is
// too narrow (round 11 #2).
void wxbr_sizer_show(void* sizer, void* win, int show) {
((wxSizer*)sizer)->Show((wxWindow*)win, show != 0);
}
// Emit WxEV_SIZE (p1 = new client width, p2 = height) whenever this window is
// resized. e.Skip() keeps the normal sizer layout running (round 11 #2).
void wxbr_bind_size(void* win) {
wxWindow* w = (wxWindow*)win;
w->Bind(wxEVT_SIZE, [w](wxSizeEvent& e) {
if (g_widget_event)
g_widget_event(WxEV_SIZE, (long)DipFromPx(w, e.GetSize().GetWidth()),
(long)DipFromPx(w, e.GetSize().GetHeight()));
e.Skip();
});
}
void wxbr_fit(void* win) { ((wxWindow*)win)->Fit(); }
void wxbr_set_min_size(void* win, int w, int h) {
wxWindow* window = (wxWindow*)win;
window->SetMinSize(wxSize(PxFromDip(window, w), PxFromDip(window, h)));
}
// Attach a hover tooltip to any widget (round 15 #10). An empty string clears it.
void wxbr_set_tooltip(void* win, const char* text) {
wxWindow* w = (wxWindow*)win;
if (text && *text) {
w->SetToolTip(wxString::FromUTF8(text));
} else {
w->UnsetToolTip();
}
}
// ---- static text / fonts --------------------------------------------------
void* wxbr_static_text(void* parent, const char* label) {
return (void*)new wxStaticText((wxWindow*)parent, wxID_ANY,
wxString::FromUTF8(label));
}
void wxbr_set_label(void* win, const char* label) {
wxStaticText* st = dynamic_cast<wxStaticText*>((wxWindow*)win);
if (st) st->SetLabel(wxString::FromUTF8(label));
else ((wxWindow*)win)->SetLabel(wxString::FromUTF8(label));
}
// Read a control's current label text (used by the headless self-test to read
// back what a KPI static text actually displays).
int wxbr_get_label(void* win, char* buf, int cap) {
wxWindow* w = (wxWindow*)win;
wxStaticText* st = dynamic_cast<wxStaticText*>(w);
wxString s = st ? st->GetLabel() : w->GetLabel();
wxCharBuffer b = s.ToUTF8();
int n = (int)strlen(b.data());
if (n >= cap) n = cap - 1;
memcpy(buf, b.data(), n);
buf[n] = 0;
return n + 1;
}
void wxbr_set_bold(void* win) {
wxWindow* w = (wxWindow*)win;
wxFont f = w->GetFont();
wxFontInfo info(f.GetPointSize());
info.Bold();
w->SetFont(wxFont(info));
}
void wxbr_set_font_size(void* win, int pts) {
wxWindow* w = (wxWindow*)win;
wxFontInfo info(pts);
if (w->GetFont().GetWeight() == wxFONTWEIGHT_BOLD) info.Bold();
w->SetFont(wxFont(info));
}
// ---- button ---------------------------------------------------------------
void* wxbr_button(void* parent, const char* label, int id) {
wxButton* b = new wxButton((wxWindow*)parent, id, wxString::FromUTF8(label));
b->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) {
if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
});
return (void*)b;
}
// Make an arbitrary window (e.g. a KPI card panel) clickable: a left mouse
// down on it emits the same WxEV_BUTTON_CLICKED event a real button would,
// carrying `id`. Bind this on the panel itself; a child wxStaticText label
// swallows its own mouse events, so the caller binds each child that should
// also act as part of the click target rather than relying on propagation.
void wxbr_bind_click(void* win, int id) {
((wxWindow*)win)->Bind(wxEVT_LEFT_DOWN, [id](wxMouseEvent&) {
if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
});
}
// ---- text ctrl ------------------------------------------------------------
void* wxbr_text_ctrl(void* parent, int multiline) {
long style = multiline ? (wxTE_MULTILINE | wxTE_DONTWRAP) : 0;
return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
wxDefaultPosition, wxSize(-1, -1), style);
}
// A multiline text control that word-wraps at the control's width instead of
// scrolling horizontally (no wxTE_DONTWRAP). For prose entry such as the bug
// report box, where long lines should wrap rather than run off the edge.
void* wxbr_text_ctrl_wrap(void* parent) {
return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
wxDefaultPosition, wxSize(-1, -1),
wxTE_MULTILINE | wxTE_BESTWRAP);
}
// A single-line text control that masks its content (wxTE_PASSWORD), for secret
// entry so a saved password is never rendered in the clear (round 18 #12).
void* wxbr_text_ctrl_password(void* parent) {
return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
wxDefaultPosition, wxSize(-1, -1), wxTE_PASSWORD);
}
int wxbr_text_ctrl_get(void* win, char* buf, int cap) {
wxTextCtrl* t = (wxTextCtrl*)win;
wxString v = t->GetValue();
wxCharBuffer b = v.ToUTF8();
int n = (int)strlen(b.data());
if (n >= cap) n = cap - 1;
memcpy(buf, b.data(), n);
buf[n] = 0;
return n + 1; // total length needed if truncated
}
void wxbr_text_ctrl_set(void* win, const char* value) {
((wxTextCtrl*)win)->SetValue(wxString::FromUTF8(value));
}
// Insert text at the current cursor position, replacing any selection (round 15
// #1: worker-name placeholders are inserted, not overwritten). Leaves focus + the
// cursor after the inserted text.
void wxbr_text_ctrl_write(void* win, const char* value) {
wxTextCtrl* t = (wxTextCtrl*)win;
t->WriteText(wxString::FromUTF8(value));
t->SetFocus();
}
// ---- checkbox -------------------------------------------------------------
void* wxbr_check_box(void* parent, const char* label) {
return (void*)new wxCheckBox((wxWindow*)parent, wxID_ANY,
wxString::FromUTF8(label));
}
int wxbr_check_box_get(void* win) {
return ((wxCheckBox*)win)->GetValue() ? 1 : 0;
}
void wxbr_check_box_set(void* win, int v) {
((wxCheckBox*)win)->SetValue(v != 0);
}
// Enable or disable (grey out) any window/control.
void wxbr_enable(void* win, int on) {
((wxWindow*)win)->Enable(on != 0);
}
// ---- check list box ---------------------------------------------------------
void* wxbr_check_list_box(void* parent) {
// wxLB_EXTENDED so several rows can be selected at once (ctrl/shift-click and
// rubber-band drag, native to wxListBox); a checkbox toggle on any selected
// row then applies to every selected row (see the handler below). This is the
// Excel-style batch-check the filter menu needs (round 12 #7).
wxCheckListBox* clb = new wxCheckListBox((wxWindow*)parent, wxID_ANY,
wxDefaultPosition, wxSize(-1, -1),
0, NULL, wxLB_EXTENDED | wxLB_NEEDED_SB);
clb->Bind(wxEVT_CHECKLISTBOX, [clb](wxCommandEvent& e) {
int idx = e.GetInt();
// Batch toggle: if the clicked row is part of a multi-row selection, give
// every selected row the clicked row's new state. Check() does not itself
// fire wxEVT_CHECKLISTBOX, so there is no recursion.
wxArrayInt sel;
clb->GetSelections(sel);
if (sel.GetCount() > 1) {
bool inSel = false;
for (size_t i = 0; i < sel.GetCount(); i++)
if (sel[i] == idx) { inSel = true; break; }
if (inSel) {
bool state = clb->IsChecked(idx);
for (size_t i = 0; i < sel.GetCount(); i++) clb->Check(sel[i], state);
}
}
if (g_widget_event)
g_widget_event(WxEV_CLB_TOGGLED, (long)(intptr_t)clb, idx);
});
return (void*)clb;
}
void wxbr_clb_append(void* win, const char* label) {
((wxCheckListBox*)win)->Append(wxString::FromUTF8(label));
}
void wxbr_clb_clear(void* win) { ((wxCheckListBox*)win)->Clear(); }
int wxbr_clb_count(void* win) { return (int)((wxCheckListBox*)win)->GetCount(); }
int wxbr_clb_checked(void* win, int i) {
return ((wxCheckListBox*)win)->IsChecked(i) ? 1 : 0;
}
void wxbr_clb_set_checked(void* win, int i, int v) {
wxCheckListBox* clb = (wxCheckListBox*)win;
if (v)
clb->Check(i);
else
clb->Check(i, false);
}
int wxbr_clb_string(void* win, int i, char* buf, int cap) {
wxCheckListBox* clb = (wxCheckListBox*)win;
if (i < 0 || i >= (int)clb->GetCount()) return 0;
wxCharBuffer b = clb->GetString(i).ToUTF8();
int n = (int)strlen(b.data());
if (n >= cap) n = cap - 1;
memcpy(buf, b.data(), n);
buf[n] = 0;
return n + 1;
}
// ---- dialog -----------------------------------------------------------------
void* wxbr_dialog(void* parent, const char* title) {
return (void*)new wxDialog((wxWindow*)parent, wxID_ANY,
wxString::FromUTF8(title), wxDefaultPosition,
DipWindow((wxWindow*)parent)->FromDIP(wxSize(360, 480)),
wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
}
int wxbr_dialog_show_modal(void* win) {
return ((wxDialog*)win)->ShowModal();
}
void wxbr_dialog_close(void* win, int code) {
((wxDialog*)win)->EndModal(code);
}
// ---- file dialog -------------------------------------------------------------
// Show a native "open file, must exist" dialog. On OK, copies the chosen
// path (UTF-8) into buf (capped at cap) and returns its length + 1, like the
// other buffer-filling bridge functions; on Cancel returns 0 and leaves buf
// untouched.
int wxbr_file_dialog(void* parent, const char* title, char* buf, int cap) {
wxFileDialog dlg((wxWindow*)parent, wxString::FromUTF8(title), wxEmptyString,
wxEmptyString, wxFileSelectorDefaultWildcardStr,
wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if (dlg.ShowModal() != wxID_OK) return 0;
wxCharBuffer b = dlg.GetPath().ToUTF8();
int n = (int)strlen(b.data());
if (n >= cap) n = cap - 1;
memcpy(buf, b.data(), n);
buf[n] = 0;
return n + 1;
}
// Save-file dialog (round 15 #14). `default_name` prefills the filename;
// `wildcard` is a wxWidgets filter string (e.g. "CSV files (*.csv)|*.csv").
// Returns the chosen path in `buf` (length+1), or 0 if cancelled.
int wxbr_save_file_dialog(void* parent, const char* title, const char* default_name,
const char* wildcard, char* buf, int cap) {
wxString wc = (wildcard && *wildcard) ? wxString::FromUTF8(wildcard)
: wxString(wxFileSelectorDefaultWildcardStr);
wxFileDialog dlg((wxWindow*)parent, wxString::FromUTF8(title), wxEmptyString,
wxString::FromUTF8(default_name ? default_name : ""), wc,
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (dlg.ShowModal() != wxID_OK) return 0;
wxCharBuffer b = dlg.GetPath().ToUTF8();
int n = (int)strlen(b.data());
if (n >= cap) n = cap - 1;
memcpy(buf, b.data(), n);
buf[n] = 0;
return n + 1;
}
// ---- data view list ctrl ------------------------------------------------------
static AttrListStore* dvlc_store(void* win) {
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
}
// Per-icon tooltip hit-testing for a Health-style cell (round 15 #15), shared by
// the GTK and generic tooltip paths so both pick the same icon. The slot advance
// must match DrawShape's UNIFORM health-icon slot: (row height - 1, capped at
// 28*zoom) - 3 for every glyph and gap alike (round 19 #2). A right-aligned
// column (round 19 #21) draws the icon block flush to the cell's right edge, so
// slots are measured from the block's left, not the cell's left.
struct IconSlots {
int left; // x of the first slot, in the same coordinates as the cell
int adv; // width of one slot
};
static IconSlots HealthIconSlots(int cell_x, int cell_w, int cell_h, int n,
bool right_aligned) {
int h = cell_h - 1;
int cap = (int)(28 * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
int adv = h - 3;
if (adv < 1) adv = 1;
int left = cell_x;
if (right_aligned) {
int content_w = n * adv;
if (content_w < cell_w) left = cell_x + (cell_w - content_w);
}
return IconSlots{left, adv};
}
static int HealthIconSlotAt(const IconSlots& slots, int x, int n) {
int off = x - slots.left;
if (off < 0) off = 0;
int slot = off / slots.adv;
if (slot >= n) slot = n - 1;
return slot < 0 ? 0 : slot;
}
#ifndef __WXGTK__
// Generic wxDataViewCtrl (wxMSW): per-cell and per-icon hover tooltips.
// The control draws its rows in an inner main window, which is where mouse
// events arrive, so the tooltip lives on that window. Windows only re-shows a
// tooltip when its text is re-set, so the handler tracks the (row, column,
// icon slot) under the pointer and replaces the tooltip only when it changes;
// moving from one Health icon to the next therefore pops the right text.
struct DvTipKey {
int row = -1;
unsigned col = (unsigned)-1;
int slot = -1;
bool operator==(const DvTipKey& o) const {
return row == o.row && col == o.col && slot == o.slot;
}
};
static std::map<wxDataViewCtrl*, DvTipKey> g_tip_key;
// Padding the generic renderer leaves on each side of a cell (PADDING_RIGHTLEFT
// in src/generic/datavgen.cpp); custom renderers draw inside it.
static const int GENERIC_CELL_PADDING = 3;
static void dvlc_update_tooltip(wxDataViewCtrl* dv, wxWindow* area, wxPoint area_pos) {
const wxPoint p = dv->ScreenToClient(area->ClientToScreen(area_pos));
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(p, item, col);
DvTipKey key;
wxString tip;
if (item.IsOk() && col) {
AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
key.row = (int)store->GetRow(item);
key.col = col->GetModelColumn();
auto iit = store->icon_tip.find({(unsigned)key.row, key.col});
if (iit != store->icon_tip.end() && !iit->second.empty()) {
wxRect r = dv->GetItemRect(item, col);
int pad = dv->FromDIP(GENERIC_CELL_PADDING);
int n = (int)iit->second.size();
IconSlots slots = HealthIconSlots(r.x + pad, r.width - 2 * pad, r.height, n,
col->GetAlignment() == wxALIGN_RIGHT);
key.slot = HealthIconSlotAt(slots, p.x, n);
tip = iit->second[(size_t)key.slot];
} else {
auto it = store->cell_tip.find({(unsigned)key.row, key.col});
if (it != store->cell_tip.end()) tip = it->second;
}
}
DvTipKey& last = g_tip_key[dv];
if (last == key) return;
last = key;
area->UnsetToolTip();
if (!tip.IsEmpty()) area->SetToolTip(tip);
}
#endif
#ifdef __WXGTK__
// GtkTreeView "query-tooltip" handler: show the per-cell tooltip stored for the
// (row, model column) under the pointer (used by the Errors column). wx does
// not surface per-cell tooltips on wxDataViewCtrl, and mouse-motion events are
// not delivered to wx handlers on the native GTK control, so this hooks the
// native signal directly.
static gboolean dvlc_query_tooltip(GtkWidget* tv, gint x, gint y, gboolean keyboard,
GtkTooltip* tooltip, gpointer user_data) {
(void)keyboard;
wxDataViewCtrl* dv = static_cast<wxDataViewCtrl*>(user_data);
gint bx = 0, by = 0;
gtk_tree_view_convert_widget_to_bin_window_coords(GTK_TREE_VIEW(tv), x, y, &bx, &by);
GtkTreePath* path = nullptr;
GtkTreeViewColumn* gcol = nullptr;
if (!gtk_tree_view_get_path_at_pos(GTK_TREE_VIEW(tv), bx, by, &path, &gcol, nullptr, nullptr))
return FALSE;
gint* idx = gtk_tree_path_get_indices(path);
int row = idx ? idx[0] : -1;
if (row < 0 || !gcol) { gtk_tree_path_free(path); return FALSE; }
wxDataViewColumn* wxcol = dv->GTKColumnToWX(gcol);
if (!wxcol) { gtk_tree_path_free(path); return FALSE; }
AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
unsigned mcol = wxcol->GetModelColumn();
// Per-icon tooltip (round 15 #15): if this cell has one tooltip per icon, pick
// the one under the pointer from the icon slot the x-offset falls in.
auto iit = store->icon_tip.find({(unsigned)row, mcol});
if (iit != store->icon_tip.end() && !iit->second.empty()) {
GdkRectangle crect;
gtk_tree_view_get_cell_area(GTK_TREE_VIEW(tv), path, gcol, &crect);
gtk_tree_path_free(path);
int n = (int)iit->second.size();
IconSlots slots = HealthIconSlots(crect.x, crect.width, crect.height, n,
wxcol->GetAlignment() == wxALIGN_RIGHT);
int slot = HealthIconSlotAt(slots, bx, n);
int adv = slots.adv;
int block_left = slots.left;
const wxString& tip = iit->second[(size_t)slot];
if (tip.IsEmpty()) return FALSE;
// Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
// Without a tip area GTK defaults it to the whole widget, so it never re-queries
// or moves the tooltip as the pointer crosses from one icon to the next -- the
// old tooltip just stays put with stale text. Setting a per-slot area makes GTK
// hide + re-show + reposition the tooltip for each icon.
//
// CRITICAL (round 19 #2, the reason the health tooltips never showed): the slot
// geometry above (block_left, crect) is in BIN-WINDOW coordinates (what
// gtk_tree_view_get_cell_area and get_path_at_pos use), but
// gtk_tooltip_set_tip_area expects WIDGET coordinates. Feeding it bin-window
// coords offsets the area upward by the header height, so it does not contain
// the pointer -- and GTK then suppresses the tooltip entirely (it only shows a
// tooltip whose tip area contains the cursor). The Errors column worked because
// it sets no tip area. Convert the slot rect back to widget coordinates.
gint area_wx = 0, area_wy = 0;
gtk_tree_view_convert_bin_window_to_widget_coords(
GTK_TREE_VIEW(tv), block_left + slot * adv, crect.y, &area_wx, &area_wy);
GdkRectangle area;
area.x = area_wx;
area.y = area_wy;
area.width = adv;
area.height = crect.height;
gtk_tooltip_set_tip_area(tooltip, &area);
gtk_tooltip_set_text(tooltip, tip.utf8_str());
return TRUE;
}
gtk_tree_path_free(path);
auto it = store->cell_tip.find({(unsigned)row, mcol});
if (it == store->cell_tip.end() || it->second.IsEmpty()) return FALSE;
gtk_tooltip_set_text(tooltip, it->second.utf8_str());
return TRUE;
}
#endif
void* wxbr_dvlc(void* parent) {
// Multi-select (ctrl/shift-click) + row lines. Selection replaces the old
// checkbox column. A custom AttrListStore backs it so rows can be coloured by
// status while the native selection highlight still shows through.
wxDataViewCtrl* dv =
new wxDataViewCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
wxSize(-1, -1),
wxDV_ROW_LINES | wxDV_VERT_RULES | wxDV_MULTIPLE);
AttrListStore* store = new AttrListStore();
dv->AssociateModel(store);
store->DecRef(); // the control owns a reference now
g_pulse_target = dv; // the locate-dot pulse timer repaints this control
g_zoom_table = dv; // the status-bar zoom slider scales this control (#3)
dv->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) {
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
});
dv->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, [](wxDataViewEvent&) {
if (g_widget_event) g_widget_event(WxEV_DVLC_CONTEXT_MENU, 0, 0);
});
dv->Bind(wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, [](wxDataViewEvent& e) {
if (g_widget_event) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (!dv) return;
wxDataViewItem item = e.GetItem();
if (!item.IsOk()) return;
int row = ((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
g_widget_event(WxEV_DVLC_VALUE_CHANGED, row, (long)e.GetColumn());
}
});
dv->Bind(wxEVT_DATAVIEW_COLUMN_HEADER_CLICK, [](wxDataViewEvent& e) {
if (g_widget_event) g_widget_event(WxEV_DVLC_HEADER_CLICK, (long)e.GetColumn(), 0);
});
// Right-click on a column header: Excel-style per-column menu (hide/sort/...).
dv->Bind(wxEVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK, [](wxDataViewEvent& e) {
if (g_widget_event) g_widget_event(WxEV_DVLC_HEADER_RIGHT_CLICK, (long)e.GetColumn(), 0);
});
dv->Bind(wxEVT_DATAVIEW_COLUMN_REORDERED, [](wxDataViewEvent&) {
if (g_widget_event) g_widget_event(WxEV_DVLC_REORDERED, 0, 0);
});
// Rubber-band (click-drag) range selection. wxDataViewCtrl has none natively.
#ifdef __WXGTK__
// On GTK the control wraps a GtkTreeView, which supports native rubber-band
// selection -- just not enabled by wx. Enable it directly. (wx delivers no
// MOTION events during the native drag, so the mouse-event fallback below is
// inapplicable on GTK.)
{
GtkWidget* tv = dv->GtkGetTreeView();
if (tv) {
gtk_tree_view_set_rubber_banding(GTK_TREE_VIEW(tv), TRUE);
// Per-cell hover tooltips (Errors column) via the native signal.
gtk_widget_set_has_tooltip(tv, TRUE);
g_signal_connect(tv, "query-tooltip", G_CALLBACK(dvlc_query_tooltip), dv);
}
}
#else
// Generic wxDataViewCtrl (wxMSW): no native rubber-banding, so track a drag
// anchor and extend the selection to the row under the cursor. The generic
// control draws and receives mouse input in an inner "main window", not in
// the wxDataViewCtrl itself (mouse events do not propagate to parents), so
// the handlers bind there; HitTest wants control coordinates.
{
wxWindow* area = dv->GetMainWindow();
auto row_at = [dv, area](const wxPoint& area_pos, int& row) {
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(dv->ScreenToClient(area->ClientToScreen(area_pos)), item, col);
if (!item.IsOk()) return false;
row = (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
return true;
};
area->Bind(wxEVT_LEFT_DOWN, [dv, row_at](wxMouseEvent& e) {
// Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
int row = -1;
if (!e.ControlDown() && !e.ShiftDown() && row_at(e.GetPosition(), row)) {
g_drag_anchor[dv] = row;
} else {
g_drag_anchor.erase(dv);
}
e.Skip(); // let the control select the anchor row
});
area->Bind(wxEVT_MOTION, [dv, area, row_at](wxMouseEvent& e) {
e.Skip();
dvlc_update_tooltip(dv, area, e.GetPosition());
auto it = g_drag_anchor.find(dv);
int cur = -1;
if (!e.LeftIsDown() || it == g_drag_anchor.end() || !row_at(e.GetPosition(), cur))
return;
int lo = it->second < cur ? it->second : cur;
int hi = it->second < cur ? cur : it->second;
wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
wxDataViewItemArray sel;
for (int r = lo; r <= hi; ++r) sel.push_back(model->GetItem((unsigned)r));
dv->SetSelections(sel);
// Selecting programmatically does not emit SELECTION_CHANGED, so notify.
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
});
area->Bind(wxEVT_LEFT_UP, [dv](wxMouseEvent& e) {
g_drag_anchor.erase(dv);
e.Skip();
});
area->Bind(wxEVT_LEAVE_WINDOW, [dv](wxMouseEvent& e) {
g_tip_key.erase(dv);
e.Skip();
});
dv->Bind(wxEVT_DESTROY, [dv](wxWindowDestroyEvent& e) {
g_drag_anchor.erase(dv);
g_tip_key.erase(dv);
e.Skip();
});
}
#endif
// Row activation (double-click / Enter): report the row + column so the app
// can, e.g., open the miner's IP in a browser.
dv->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) {
if (g_widget_event) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (!dv) return;
wxDataViewItem item = e.GetItem();
if (!item.IsOk()) return;
int row = ((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
g_widget_event(WxEV_DVLC_ACTIVATED, row, (long)e.GetColumn());
}
});
return (void*)dv;
}
// Map the bridge alignment code (0 left, 1 right, 2 centre) to a wxAlignment.
static wxAlignment dvlc_wx_align(int align) {
switch (align) {
case 1: return wxALIGN_RIGHT;
case 2: return wxALIGN_CENTER;
default: return wxALIGN_NOT;
}
}
void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reorderable, int align) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
int flags = wxDATAVIEW_COL_RESIZABLE;
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
width = PxFromDip(dv, width);
dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
width, dvlc_wx_align(align), flags);
// Record the 100% column width for the zoom (round 14 #3); the first column of
// a (re)built table resets the list.
if (col == 0) g_zoom_base_w.clear();
g_zoom_base_w.push_back(width);
}
// Same bookkeeping as wxbr_dvlc_append_text_col, but the column is drawn by a
// SegmentRenderer so its cell values can carry the '\x1f'/'\x1e' colour-run
// encoding produced by alkane_gui::model::encode_segments. An ordinary string
// with no encoding in it still renders fine (single default-coloured run).
void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int reorderable, int align) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
int flags = wxDATAVIEW_COL_RESIZABLE;
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
SegmentRenderer* renderer = new SegmentRenderer();
width = PxFromDip(dv, width);
wxAlignment al = dvlc_wx_align(align);
renderer->SetAlignment(al);
wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
width, al, flags);
dv->AppendColumn(c);
// Record the 100% column width for the zoom (round 14 #3).
if (col == 0) g_zoom_base_w.clear();
g_zoom_base_w.push_back(width);
return (void*)c;
}
void wxbr_dvlc_append_toggle_col(void* win, int width) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
unsigned col = dv->GetColumnCount();
dvlc_store(win)->AppendColumn("bool");
dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, PxFromDip(dv, width),
wxALIGN_CENTRE, 0);
}
void wxbr_dvlc_append_row(void* win, int nvals, const char** vals) {
// All columns are text now (row selection replaced the checkbox column).
wxVector<wxVariant> values;
for (int i = 0; i < nvals; i++) {
values.push_back(wxVariant(vals[i] ? wxString::FromUTF8(vals[i]) : wxString()));
}
AttrListStore* store = dvlc_store(win);
store->AppendItem(values);
store->row_fg.push_back(wxColour()); // no per-row colour until set
}
void wxbr_dvlc_delete_row(void* win, unsigned row) {
AttrListStore* store = dvlc_store(win);
store->DeleteItem(row);
if (row < store->row_fg.size()) store->row_fg.erase(store->row_fg.begin() + row);
}
void wxbr_dvlc_clear(void* win) {
AttrListStore* store = dvlc_store(win);
store->DeleteAllItems();
store->row_fg.clear();
store->cell_tip.clear();
store->icon_tip.clear();
}
// Set per-icon tooltips for one cell (round 15 #15): `joined` is the tooltips for
// each icon in draw order, separated by 0x1f. An empty string clears them.
void wxbr_dvlc_set_icon_tooltips(void* win, unsigned row, unsigned col, const char* joined) {
AttrListStore* store = dvlc_store(win);
if (!joined || !joined[0]) {
store->icon_tip.erase({row, col});
return;
}
std::vector<wxString> tips;
wxString s = wxString::FromUTF8(joined);
wxString cur;
for (size_t i = 0; i < s.length(); i++) {
if (s[i] == wxUniChar(0x1f)) {
tips.push_back(cur);
cur.clear();
} else {
cur += s[i];
}
}
tips.push_back(cur);
store->icon_tip[{row, col}] = tips;
}
// Set (or clear, with an empty string) the hover tooltip for one cell,
// addressed by (row, model column). Used for the Errors column's full text.
void wxbr_dvlc_set_cell_tooltip(void* win, unsigned row, unsigned col, const char* text) {
AttrListStore* store = dvlc_store(win);
if (text && text[0]) {
store->cell_tip[{row, col}] = wxString::FromUTF8(text);
} else {
store->cell_tip.erase({row, col});
}
}
// Set (or clear, when r<0) a row's text colour; used to paint rows by status.
void wxbr_dvlc_set_row_color(void* win, unsigned row, int r, int g, int b) {
AttrListStore* store = dvlc_store(win);
if (row >= store->row_fg.size()) return;
store->row_fg[row] = (r < 0) ? wxColour() : wxColour(r, g, b);
store->RowChanged(row);
}
// Set (or clear, when r<0) the alternating-row (zebra) background colour. The
// app passes a theme-aware colour; odd rows get it (see AttrListStore).
#ifdef __WXOSX__
extern "C" void wxbr_osx_set_alternating_rows(void* win, int on);
#endif
void wxbr_dvlc_set_zebra(void* win, int r, int g, int b) {
#ifdef __WXOSX__
// wxOSX draws custom cells without clipping them to the cell, so the
// renderer's over-sized background fill (which GTK/MSW clip) painted over
// neighbouring cells and hid their text until a row was selected. Use the
// table's native alternating rows instead: AppKit paints them under every
// cell, in the theme's colours, and no row carries a background attribute.
dvlc_store(win)->zebra = wxColour();
wxbr_osx_set_alternating_rows(win, r >= 0 ? 1 : 0);
#else
dvlc_store(win)->zebra = (r < 0) ? wxColour() : wxColour(r, g, b);
#endif
}
// The model-row index of the first (top) visible row, or -1 if none. Used to
// hold the scroll position across a full clear+refill during a live scan.
int wxbr_dvlc_get_top_row(void* win) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewItem item = dv->GetTopItem();
if (!item.IsOk()) return -1;
return (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
}
// Scroll so `row` is visible (used with wxbr_dvlc_get_top_row to restore the
// scroll position after a refill). Out-of-range rows are ignored -- GetItem()
// itself asserts on row >= count, so the bound MUST be checked before calling.
void wxbr_dvlc_ensure_visible(void* win, unsigned row) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
if (row >= (unsigned)dvlc_store(win)->GetItemCount()) return;
wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
if (item.IsOk()) dv->EnsureVisible(item);
}
int wxbr_dvlc_row_count(void* win) {
return (int)dvlc_store(win)->GetItemCount();
}
void wxbr_dvlc_set_cell(void* win, unsigned row, unsigned col, const char* value) {
AttrListStore* store = dvlc_store(win);
store->SetValueByRow(wxVariant(wxString::FromUTF8(value)), row, col);
store->RowValueChanged(row, col);
}
int wxbr_dvlc_get_cell(void* win, unsigned row, unsigned col, char* buf, int cap) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
AttrListStore* store = dvlc_store(win);
if (row >= store->GetItemCount() || (int)col >= (int)dv->GetColumnCount())
return 0;
wxVariant v;
store->GetValueByRow(v, row, col);
wxString s = v.GetString();
wxCharBuffer b = s.ToUTF8();
int n = (int)strlen(b.data());
if (n >= cap) n = cap - 1;
memcpy(buf, b.data(), n);
buf[n] = 0;
return n + 1;
}
int wxbr_dvlc_col_count(void* win) {
return (int)((wxDataViewCtrl*)win)->GetColumnCount();
}
// Auto-size a column (by display position) to fit its content + header.
void wxbr_dvlc_autosize_col(void* win, int pos) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
if (pos < 0 || (unsigned)pos >= dv->GetColumnCount()) return;
wxDataViewColumn* c = dv->GetColumn((unsigned)pos);
if (c) c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
}
// Size a column to fit its content + header, then clamp to cap_px so the default
// width is min(reasonable cap, content-fit) -- a short column shrinks to its
// content, a long one is capped at the caller's sensible default (round 18 #10).
// A small floor keeps a column from collapsing to nothing.
void wxbr_dvlc_autosize_col_capped(void* win, int pos, int cap_px) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
if (pos < 0 || (unsigned)pos >= dv->GetColumnCount()) return;
wxDataViewColumn* c = dv->GetColumn((unsigned)pos);
if (!c) return;
c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
int w = c->GetWidth();
cap_px = PxFromDip(dv, cap_px);
const int floor_px = PxFromDip(dv, 24);
if (w < floor_px) w = floor_px;
if (cap_px > 0 && w > cap_px) w = cap_px;
c->SetWidth(w);
}
// Update a column's header text in place (creation index) without recreating
// the control -- used to refresh the ASCII sort marker on a sort click.
void wxbr_dvlc_set_col_title(void* win, int col, const char* title) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
if (col < 0 || (unsigned)col >= dv->GetColumnCount()) return;
wxDataViewColumn* c = dv->GetColumn(col);
if (c) c->SetTitle(wxString::FromUTF8(title));
}
// Show/clear the native sort arrow on a column (creation index). The app does
// its own sorting; this only draws the indicator so the header shows which
// column is the sort key and in which direction.
void wxbr_dvlc_set_sort_indicator(void* win, int col, int active, int ascending) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
if (col < 0 || (unsigned)col >= dv->GetColumnCount()) return;
wxDataViewColumn* c = dv->GetColumn(col);
if (!c) return;
if (active) {
c->SetSortOrder(ascending != 0);
} else if (c->IsSortKey()) {
c->UnsetAsSortKey();
}
}
// model column index (creation order) currently shown at display position pos
int wxbr_dvlc_col_at_pos(void* win, int pos) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
unsigned n = dv->GetColumnCount();
if (pos < 0 || (unsigned)pos >= n) return -1;
#ifdef __WXGTK__
// wxGTK's GetColumnPosition() does NOT reflect a native GtkTreeView column
// drag, so after the user reorders columns it reports the creation order and
// the reorder is silently lost. Read the real display order from the
// GtkTreeView instead, then map the column back to its wx creation index.
GtkWidget* tvw = dv->GtkGetTreeView();
if (tvw) {
GList* cols = gtk_tree_view_get_columns(GTK_TREE_VIEW(tvw)); // display order
GtkTreeViewColumn* gcol = (GtkTreeViewColumn*)g_list_nth_data(cols, (guint)pos);
g_list_free(cols);
if (gcol) {
wxDataViewColumn* wxcol = dv->GTKColumnToWX(gcol);
for (unsigned i = 0; i < n; i++) {
if (dv->GetColumn(i) == wxcol) return (int)i;
}
}
return -1;
}
#endif
for (unsigned i = 0; i < n; i++) {
wxDataViewColumn* c = dv->GetColumn(i);
if (c && dv->GetColumnPosition(c) == (unsigned)pos) return (int)i;
}
return -1;
}
long wxbr_dvlc_selected_row(void* win) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewItem it = dv->GetSelection();
if (!it.IsOk()) return -1;
return (long)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(it);
}
// Fill `buf` with the selected row indices (multi-select); returns the count.
int wxbr_dvlc_get_selections(void* win, int* buf, int cap) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
wxDataViewItemArray items;
int n = (int)dv->GetSelections(items);
int out = 0;
for (int i = 0; i < n && out < cap; i++) {
int row = m->GetRow(items[i]);
if (row >= 0) buf[out++] = row;
}
return out;
}
void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
int count = (int)dvlc_store(win)->GetItemCount();
dv->UnselectAll();
for (int i = 0; i < n; i++) {
// GetItem() asserts on an out-of-range row, so bound both ends.
if (rows[i] >= 0 && rows[i] < count) dv->Select(m->GetItem((unsigned)rows[i]));
}
}
// Retained for ABI; per-row colour is handled by the store (GetAttrByRow) and
// the native selection highlight, so these row-background hacks are no-ops now
// (they fought the selection highlight on GTK 3.3).
void wxbr_dvlc_set_alt_row_color(void* win, int r, int g, int b) {
(void)win; (void)r; (void)g; (void)b;
}
void wxbr_apply_zebra_css(int r, int g, int b) {
(void)r; (void)g; (void)b;
}
void wxbr_dvlc_select_row(void* win, long row) {
if (row < 0) return;
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
if (row >= (long)dvlc_store(win)->GetItemCount()) return;
dv->Select(m->GetItem((unsigned)row));
}
// ---- timer -----------------------------------------------------------------
void* wxbr_timer(int id, int ms) {
wxTimer* t = new wxTimer;
t->Bind(wxEVT_TIMER, [id](wxTimerEvent&) {
if (g_widget_event) g_widget_event(WxEV_TIMER_TICK, id, 0);
});
t->Start(ms);
return (void*)t;
}
// ---- gauge (progress bar) ---------------------------------------------------
void* wxbr_gauge(void* parent, int range) {
wxGauge* g = new wxGauge((wxWindow*)parent, wxID_ANY, range < 1 ? 1 : range,
wxDefaultPosition, wxSize(-1, PxFromDip((wxWindow*)parent, 6)),
wxGA_HORIZONTAL | wxGA_SMOOTH);
return (void*)g;
}
void wxbr_gauge_set_range(void* win, int range) {
((wxGauge*)win)->SetRange(range < 1 ? 1 : range);
}
void wxbr_gauge_set_value(void* win, int value) {
((wxGauge*)win)->SetValue(value);
}
void wxbr_gauge_pulse(void* win) { ((wxGauge*)win)->Pulse(); }
// ---- show / hide any window -------------------------------------------------
void wxbr_show(void* win, int shown) { ((wxWindow*)win)->Show(shown != 0); }
// ---- open a URL in the default browser --------------------------------------
int wxbr_launch_browser(const char* url) {
return wxLaunchDefaultBrowser(wxString::FromUTF8(url)) ? 1 : 0;
}
// ---- appearance / dark mode -------------------------------------------------
// init_app() now sets the appearance before the frame exists (the only point
// at which wxMSW honours it, and where ALKANE_APPEARANCE is applied); this is
// kept for API compatibility and does nothing further.
void wxbr_set_appearance_system() {}
int wxbr_is_dark() {
return wxSystemSettings::GetAppearance().IsDark() ? 1 : 0;
}
// Fetch a theme colour so custom widgets follow light/dark. which:
// 0=window bg, 1=window text, 2=highlight, 3=button face, 4=grey text.
void wxbr_system_color(int which, unsigned char* r, unsigned char* g,
unsigned char* b) {
wxSystemColour idx = wxSYS_COLOUR_WINDOW;
switch (which) {
case 0: idx = wxSYS_COLOUR_WINDOW; break;
case 1: idx = wxSYS_COLOUR_WINDOWTEXT; break;
case 2: idx = wxSYS_COLOUR_HIGHLIGHT; break;
case 3: idx = wxSYS_COLOUR_BTNFACE; break;
case 4: idx = wxSYS_COLOUR_GRAYTEXT; break;
default: idx = wxSYS_COLOUR_WINDOW; break;
}
wxColour c = wxSystemSettings::GetColour(idx);
*r = c.Red();
*g = c.Green();
*b = c.Blue();
}
// ---- widget colours (for the KPI cards) -------------------------------------
void wxbr_set_bg(void* win, int r, int g, int b) {
((wxWindow*)win)->SetBackgroundColour(wxColour(r, g, b));
}
void wxbr_set_fg(void* win, int r, int g, int b) {
((wxWindow*)win)->SetForegroundColour(wxColour(r, g, b));
}
// ---- rearrangeable check-list (Choose columns, drag/reorder + check) ---------
// order[i] encodes the item at display position i: value v >= 0 means original
// item v, checked; a negative value ~v means original item v, unchecked.
void* wxbr_rearrange_list(void* parent, int n, const int* order, const char** items) {
wxArrayInt aorder;
wxArrayString aitems;
for (int i = 0; i < n; i++) {
aorder.Add(order[i]);
aitems.Add(wxString::FromUTF8(items[i]));
}
wxRearrangeCtrl* ctrl =
new wxRearrangeCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
wxSize(-1, -1), aorder, aitems);
return (void*)ctrl;
}
// Read back the current order (same encoding as above) into buf; returns count.
int wxbr_rearrange_get_order(void* win, int* buf, int cap) {
wxRearrangeCtrl* ctrl = (wxRearrangeCtrl*)win;
const wxArrayInt& order = ctrl->GetList()->GetCurrentOrder();
int n = (int)order.GetCount();
for (int i = 0; i < n && i < cap; i++) buf[i] = order[i];
return n < cap ? n : cap;
}
// ---- reorder list: a checkable, multi-select, drag-reorderable column list
// for the Columns dialog (round 11 #4). Replaces wxRearrangeCtrl (which had
// up/down buttons and no drag / multi-select). It is a single-column headerless
// wxListCtrl with native checkboxes; rows carry their base model index as item
// data, and the check state + row order encode the same [idx | ~idx] contract
// as wxbr_rearrange_get_order. All pointer interaction is handled explicitly
// (round 13 #1) so a single control supports both drag-to-reorder AND
// drag-to-select: a drag that starts on an already-selected row moves that group
// (reorder), a drag that starts on an unselected row rubber-band-selects the
// range it sweeps. Keyboard: Ctrl+A selects all, Ctrl/Shift+Up/Down extend the
// selection. (The old wxEVT_LIST_BEGIN_DRAG binding intercepted every drag as a
// reorder, which silently disabled rubber-band selection.)
static wxVector<long> g_reorder_drag; // item DATA currently being reordered
static wxListCtrl* g_reorder_list = nullptr;
static long g_press_row = -1; // row under the last left-press (-1 = none/checkbox)
static wxPoint g_press_pos; // position of that press
static bool g_press_row_selected = false;
static int g_reorder_mode = 0; // 0 = none, 1 = reorder, 2 = rubber-band
static long g_rubber_anchor = -1;
// Set the selection to the inclusive row range [a,b] (order-independent). When
// `additive` (Ctrl held) the existing selection is kept and the range added.
static void ReorderSelectRange(wxListCtrl* lc, long a, long b, bool additive) {
if (a < 0) a = 0;
long lo = a < b ? a : b;
long hi = a < b ? b : a;
int count = lc->GetItemCount();
for (int i = 0; i < count; i++) {
bool inRange = (i >= lo && i <= hi);
bool keep = additive && (lc->GetItemState(i, wxLIST_STATE_SELECTED) & wxLIST_STATE_SELECTED);
lc->SetItemState(i, (inRange || keep) ? wxLIST_STATE_SELECTED : 0, wxLIST_STATE_SELECTED);
}
}
// Move the rows whose DATA is in g_reorder_drag so they land just before the row
// under `pos` (or at the end when dropped past the last row / onto a dragged row),
// preserving each row's checked state.
static void ReorderMoveTo(wxListCtrl* lc, const wxPoint& pos) {
struct Row { long data; bool checked; wxString text; };
int count = lc->GetItemCount();
wxVector<Row> rows;
for (int i = 0; i < count; i++) {
Row r;
r.data = lc->GetItemData(i);
r.checked = lc->IsItemChecked(i);
r.text = lc->GetItemText(i);
rows.push_back(r);
}
auto isDragged = [](long d) {
for (size_t i = 0; i < g_reorder_drag.size(); i++)
if (g_reorder_drag[i] == d) return true;
return false;
};
int flags = 0;
long targetRow = lc->HitTest(pos, flags);
long anchor = (targetRow >= 0 && targetRow < count) ? rows[targetRow].data : -1;
if (anchor >= 0 && isDragged(anchor)) anchor = -1;
wxVector<Row> remaining, moved;
for (size_t i = 0; i < rows.size(); i++) {
if (isDragged(rows[i].data)) moved.push_back(rows[i]);
else remaining.push_back(rows[i]);
}
int insertAt = (int)remaining.size();
if (anchor >= 0) {
for (size_t i = 0; i < remaining.size(); i++)
if (remaining[i].data == anchor) { insertAt = (int)i; break; }
}
wxVector<Row> result;
for (int i = 0; i < insertAt; i++) result.push_back(remaining[i]);
for (size_t i = 0; i < moved.size(); i++) result.push_back(moved[i]);
for (int i = insertAt; i < (int)remaining.size(); i++) result.push_back(remaining[i]);
lc->DeleteAllItems();
for (size_t i = 0; i < result.size(); i++) {
long row = lc->InsertItem((long)i, result[i].text);
lc->SetItemData(row, result[i].data);
lc->CheckItem(row, result[i].checked);
if (isDragged(result[i].data))
lc->SetItemState((long)i, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
}
}
void* wxbr_reorder_list(void* parent, int n, const int* order, const char** items) {
wxListCtrl* lc = new wxListCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
wxSize(-1, PxFromDip((wxWindow*)parent, 240)),
wxLC_REPORT | wxLC_NO_HEADER);
lc->EnableCheckBoxes(true);
// Narrower than before so the picker dialog is not over-wide (round 13 #1).
lc->InsertColumn(0, wxT("Column"), wxLIST_FORMAT_LEFT, 190);
for (int i = 0; i < n; i++) {
int enc = order[i];
int idx = enc < 0 ? ~enc : enc;
long row = lc->InsertItem(i, wxString::FromUTF8(items[idx]));
lc->SetItemData(row, (long)idx);
lc->CheckItem(row, enc >= 0);
}
// Batch checkbox toggle: checking/unchecking a row that is part of a
// multi-row selection applies the same state to every selected row, so the
// user can ctrl/shift-click several columns and show/hide them together
// (round 12 #7). CheckItem() re-enters this handler, so guard against it.
auto batchCheck = [lc](long item, bool state) {
static bool busy = false;
if (busy) return;
if (!(lc->GetItemState(item, wxLIST_STATE_SELECTED) & wxLIST_STATE_SELECTED))
return;
wxVector<long> sel;
long it = -1;
for (;;) {
it = lc->GetNextItem(it, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (it == -1) break;
sel.push_back(it);
}
if (sel.size() <= 1) return;
busy = true;
for (size_t i = 0; i < sel.size(); i++)
if (sel[i] != item) lc->CheckItem(sel[i], state);
busy = false;
};
lc->Bind(wxEVT_LIST_ITEM_CHECKED, [batchCheck](wxListEvent& e) {
batchCheck(e.GetIndex(), true);
});
lc->Bind(wxEVT_LIST_ITEM_UNCHECKED, [batchCheck](wxListEvent& e) {
batchCheck(e.GetIndex(), false);
});
// Left-press: remember the row and whether it was already selected, so a
// following drag can choose reorder vs rubber-band. A press on the checkbox
// (state icon) never starts a drag, so toggling still works. Skip() so the
// control still does its normal focus/selection/checkbox handling.
lc->Bind(wxEVT_LEFT_DOWN, [lc](wxMouseEvent& e) {
int flags = 0;
long row = lc->HitTest(e.GetPosition(), flags);
g_reorder_list = lc;
g_reorder_mode = 0;
if (flags & wxLIST_HITTEST_ONITEMSTATEICON) {
g_press_row = -1; // checkbox click: don't drag
} else {
g_press_row = row;
g_press_pos = e.GetPosition();
g_press_row_selected =
(row >= 0) && (lc->GetItemState(row, wxLIST_STATE_SELECTED) & wxLIST_STATE_SELECTED);
}
e.Skip();
});
// Motion with the left button down: once past a small threshold, start either a
// reorder (press began on a selected row) or a rubber-band selection.
lc->Bind(wxEVT_MOTION, [lc](wxMouseEvent& e) {
if (!e.LeftIsDown() || g_reorder_list != lc || g_press_row < 0) { e.Skip(); return; }
wxPoint pos = e.GetPosition();
if (g_reorder_mode == 0) {
long dx = pos.x - g_press_pos.x, dy = pos.y - g_press_pos.y;
if (dx < 0) dx = -dx;
if (dy < 0) dy = -dy;
if (dx < 4 && dy < 4) { e.Skip(); return; }
if (g_press_row_selected) {
g_reorder_mode = 1; // reorder the current selection
g_reorder_drag.clear();
long it = -1;
for (;;) {
it = lc->GetNextItem(it, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (it == -1) break;
g_reorder_drag.push_back(lc->GetItemData(it));
}
if (g_reorder_drag.empty()) g_reorder_mode = 0;
} else {
g_reorder_mode = 2; // rubber-band select from the press row
g_rubber_anchor = g_press_row;
}
}
if (g_reorder_mode == 2) {
int flags = 0;
long cur = lc->HitTest(pos, flags);
if (cur < 0) cur = (pos.y < 0) ? 0 : (lc->GetItemCount() - 1);
ReorderSelectRange(lc, g_rubber_anchor, cur, e.ControlDown());
return; // we own the selection during a rubber-band; don't Skip
}
e.Skip();
});
// Release: complete a reorder if one was in progress, then reset.
lc->Bind(wxEVT_LEFT_UP, [lc](wxMouseEvent& e) {
if (g_reorder_list == lc && g_reorder_mode == 1 && !g_reorder_drag.empty())
ReorderMoveTo(lc, e.GetPosition());
g_reorder_drag.clear();
g_reorder_mode = 0;
g_press_row = -1;
e.Skip();
});
// Keyboard: Ctrl+A selects all; Ctrl/Shift+Down/Up extend the selection one row
// (round 13 #1). Everything else falls through to the control.
lc->Bind(wxEVT_CHAR_HOOK, [lc](wxKeyEvent& e) {
int key = e.GetKeyCode();
int count = lc->GetItemCount();
if (e.ControlDown() && (key == 'A' || key == 'a')) {
for (int i = 0; i < count; i++)
lc->SetItemState(i, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
return; // consume
}
if ((key == WXK_DOWN || key == WXK_UP) && (e.ControlDown() || e.ShiftDown()) && count > 0) {
long focus = lc->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_FOCUSED);
if (focus < 0) focus = lc->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (focus < 0) focus = (key == WXK_DOWN) ? -1 : count;
long next = (key == WXK_DOWN) ? focus + 1 : focus - 1;
if (next < 0) next = 0;
if (next > count - 1) next = count - 1;
lc->SetItemState(next, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED,
wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED);
lc->EnsureVisible(next);
return; // consume
}
e.Skip();
});
return (void*)lc;
}
int wxbr_reorder_get_order(void* win, int* buf, int cap) {
wxListCtrl* lc = (wxListCtrl*)win;
int count = lc->GetItemCount();
int n = 0;
for (int i = 0; i < count && n < cap; i++) {
int idx = (int)lc->GetItemData(i);
buf[n++] = lc->IsItemChecked(i) ? idx : ~idx;
}
return n;
}
// Repopulate the list in a new order (round 13 #1: the Alphabetical / Categories
// sort buttons). Same [idx | ~idx] encoding as construction; `items` is the same
// base-index-keyed title array. The Rust side preserves each row's checked state
// by carrying it in the sign of the order entries.
void wxbr_reorder_set_order(void* win, int n, const int* order, const char** items) {
wxListCtrl* lc = (wxListCtrl*)win;
lc->DeleteAllItems();
for (int i = 0; i < n; i++) {
int enc = order[i];
int idx = enc < 0 ? ~enc : enc;
long row = lc->InsertItem(i, wxString::FromUTF8(items[idx]));
lc->SetItemData(row, (long)idx);
lc->CheckItem(row, enc >= 0);
}
}
// ---- popup menu (right-click context menu) ----------------------------------
void* wxbr_menu_new() { return (void*)new wxMenu(); }
void wxbr_menu_append(void* menu, int id, const char* label) {
((wxMenu*)menu)->Append(id, wxString::FromUTF8(label));
}
// Append `submenu` under `menu` as a labelled sub-menu (round 15 #13); `menu`
// takes ownership of `submenu`.
void wxbr_menu_append_submenu(void* menu, const char* label, void* submenu) {
((wxMenu*)menu)->AppendSubMenu((wxMenu*)submenu, wxString::FromUTF8(label));
}
void wxbr_menu_append_separator(void* menu) {
((wxMenu*)menu)->AppendSeparator();
}
// Show the menu at the current mouse position on `win`; blocks until dismissed.
// The chosen item id is delivered via WxEV_MENU_ITEM before this returns.
void wxbr_popup_menu(void* win, void* menu) {
wxWindow* w = (wxWindow*)win;
wxMenu* m = (wxMenu*)menu;
m->Bind(wxEVT_MENU, [](wxCommandEvent& e) {
if (g_widget_event) g_widget_event(WxEV_MENU_ITEM, e.GetId(), 0);
});
w->PopupMenu(m);
delete m;
}
// ---- choice (dropdown) ------------------------------------------------------
void* wxbr_choice(void* parent, int id) {
wxChoice* c = new wxChoice((wxWindow*)parent, id);
c->Bind(wxEVT_CHOICE, [id](wxCommandEvent& e) {
if (g_widget_event)
g_widget_event(WxEV_CHOICE_CHANGED, id, (long)e.GetSelection());
});
return (void*)c;
}
void wxbr_choice_append(void* win, const char* label) {
((wxChoice*)win)->Append(wxString::FromUTF8(label));
}
void wxbr_choice_clear(void* win) { ((wxChoice*)win)->Clear(); }
int wxbr_choice_get_selection(void* win) {
return ((wxChoice*)win)->GetSelection();
}
void wxbr_choice_set_selection(void* win, int i) {
((wxChoice*)win)->SetSelection(i);
}
// ---- media (icon) button: play / pause / stop -------------------------------
// kind: 0=play (triangle), 1=pause (two bars), 2=stop (square). Drawn in the
// given colour on a transparent bitmap so it reads as a coloured glyph on the
// native button. Emits WxEV_BUTTON_CLICKED with `id`, like a normal button.
void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
// The glyph is designed on a 20x20 DIP grid and drawn at the display scale.
const int sz = PxFromDip((wxWindow*)parent, 20);
const double scale = sz / 20.0;
wxImage img(sz, sz);
img.InitAlpha();
unsigned char* a = img.GetAlpha();
if (a) memset(a, 0, (size_t)sz * sz); // fully transparent
wxBitmap bmp(img);
{
wxMemoryDC mdc(bmp);
wxGraphicsContext* gc = wxGraphicsContext::Create(mdc);
if (gc) {
gc->SetAntialiasMode(wxANTIALIAS_DEFAULT);
gc->Scale(scale, scale);
wxColour col(r, g, b);
gc->SetBrush(wxBrush(col));
gc->SetPen(wxPen(col, 1.0));
if (kind == 0) {
wxGraphicsPath p = gc->CreatePath();
p.MoveToPoint(5, 4);
p.AddLineToPoint(16, 10);
p.AddLineToPoint(5, 16);
p.CloseSubpath();
gc->FillPath(p);
} else if (kind == 1) {
gc->DrawRectangle(5, 4, 3.5, 12);
gc->DrawRectangle(11.5, 4, 3.5, 12);
} else {
gc->DrawRectangle(5, 5, 10, 10);
}
delete gc;
}
}
wxBitmapButton* btn = new wxBitmapButton((wxWindow*)parent, id, bmp);
btn->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) {
if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
});
return (void*)btn;
}
// Render an SVG (already recoloured on the Rust side -- its fill is an explicit
// #RRGGBB) into a wxStaticBitmap for the KPI cards (round 11 #15). The caller
// passes the target pixel size (w chosen from the SVG aspect ratio, h fixed).
void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
// A bitmap bundle (w x h DIPs) rather than a fixed bitmap, so the icon is
// rasterised for the window's actual display scale.
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
}
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
// shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's
// segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces
// any prior registration for that sentinel and invalidates the bitmap cache.
void wxbr_register_shape_svg(int sentinel, const char* svg, int vbw, int vbh) {
ShapeSvg s;
s.svg = wxString::FromUTF8(svg);
s.vbw = vbw;
s.vbh = vbh;
g_shape_svgs[sentinel] = s;
g_shape_bmp_cache.clear();
}
// Start/stop the locate-light dot fade animation (round 12 #6). The Rust side
// calls this after each refresh with whether any miner's locate light is
// flashing, so the repaint timer only runs when there is a dot to animate.
void wxbr_set_light_pulse(int on) { SetLightPulse(on != 0); }
// ---- live theme changes -----------------------------------------------------
// Emit WxEV_SYS_COLOUR when the OS light/dark theme changes so the app can
// repaint custom-coloured widgets (KPI cards, table rows).
void wxbr_bind_sys_colour(void* win) {
((wxWindow*)win)->Bind(wxEVT_SYS_COLOUR_CHANGED, [](wxSysColourChangedEvent& e) {
e.Skip();
if (g_widget_event) g_widget_event(WxEV_SYS_COLOUR, 0, 0);
});
}
// Run a deferred action after the current event finishes unwinding: emits
// WxEV_DEFERRED with `id` from the main event loop. Used to rebuild a control
// from outside its own event handler (destroying a widget mid-event is unsafe).
void wxbr_call_after(int id) {
if (wxTheApp) {
wxTheApp->CallAfter([id]() {
if (g_widget_event) g_widget_event(WxEV_DEFERRED, id, 0);
});
}
}
// ---- status-bar error/warning indicator -------------------------------------
// A colour-tinted static text pinned to the RIGHT-hand field of the frame's
// status bar, so scan/apply errors surface in the bottom-right corner without
// overwriting the main (left) scan-status text. The status bar is reconfigured
// to two fields: field 0 (stretch) carries the scan status set via the upstream
// SetStatusText path; field 1 (fixed) hosts this coloured label, which we
// reposition into that field's rect whenever the bar is resized.
static wxStaticText* g_status_indicator = nullptr;
static void reposition_status_indicator() {
wxStatusBar* sb = nullptr;
if (g_status_indicator) sb = wxDynamicCast(g_status_indicator->GetParent(), wxStatusBar);
if (!sb && g_zoom_slider) sb = wxDynamicCast(g_zoom_slider->GetParent(), wxStatusBar);
if (!sb) return;
// Scan/apply indicator in field 1.
if (g_status_indicator) {
wxRect r;
if (sb->GetFieldRect(1, r)) {
wxSize best = g_status_indicator->GetBestSize();
int h = best.GetHeight();
int y = r.y + (r.height - h) / 2;
g_status_indicator->SetSize(r.x + 4, y, r.width - 8, h);
}
}
// Zoom slider + editable "NNN%" entry in the far-right field (round 14 #3, #4):
// the entry at the right edge, slider filling the space to its left.
if (g_zoom_slider && g_zoom_entry) {
int fld = (sb->GetFieldsCount() >= 3) ? 2 : 1;
wxRect r;
if (sb->GetFieldRect(fld, r)) {
int ew = PxFromDip(sb, 52);
int eh = g_zoom_entry->GetBestSize().GetHeight();
if (eh > r.height - 2) eh = r.height - 2;
g_zoom_entry->SetSize(r.x + r.width - ew - 2, r.y + (r.height - eh) / 2, ew, eh);
int sw = r.width - ew - 10;
if (sw < 20) sw = 20;
int sh = r.height - 2;
g_zoom_slider->SetSize(r.x + 2, r.y + (r.height - sh) / 2, sw, sh);
}
}
}
// Scale the table (round 14 #3): the font (native columns) and, via g_table_zoom,
// the custom-renderer icon sizes. Purely a view change; no model or Rust state.
static void apply_table_zoom(double factor) {
if (factor < 0.5) factor = 0.5;
if (factor > 2.5) factor = 2.5;
g_table_zoom = factor;
if (g_zoom_table) {
if (!g_zoom_base_font.IsOk()) g_zoom_base_font = g_zoom_table->GetFont();
wxFont base = g_zoom_base_font.IsOk() ? g_zoom_base_font : *wxNORMAL_FONT;
wxFont f = base;
int pt = (int)(base.GetPointSize() * factor + 0.5);
if (pt < 5) pt = 5;
f.SetPointSize(pt);
g_zoom_table->SetFont(f);
// Scale every column width from its 100% width (recorded at append time) so
// text does not clip when zoomed (round 14 #3).
unsigned int nc = g_zoom_table->GetColumnCount();
for (unsigned int i = 0; i < nc && i < g_zoom_base_w.size(); i++) {
int w = (int)(g_zoom_base_w[i] * factor + 0.5);
if (w < 8) w = 8;
g_zoom_table->GetColumn(i)->SetWidth(w);
}
// Recompute row heights / re-request renderer sizes, then repaint.
g_zoom_table->InvalidateBestSize();
g_zoom_table->Refresh();
g_zoom_table->Update();
}
if (g_zoom_entry) {
// ChangeValue does not fire wxEVT_TEXT, so this never loops back into a zoom.
g_zoom_entry->ChangeValue(wxString::Format(wxT("%d%%"), (int)(factor * 100 + 0.5)));
}
}
void wxbr_status_indicator_init(void* frame_ptr) {
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
int widths[2] = { -1, PxFromDip(frame, 340) };
sb->SetFieldsCount(2);
sb->SetStatusWidths(2, widths);
if (!g_status_indicator) {
g_status_indicator = new wxStaticText(sb, wxID_ANY, wxEmptyString,
wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT | wxST_NO_AUTORESIZE);
sb->Bind(wxEVT_SIZE, [](wxSizeEvent& ev) {
reposition_status_indicator();
ev.Skip();
});
}
reposition_status_indicator();
}
// Set the bottom-right indicator text and its colour. An empty string clears it.
void wxbr_status_indicator_set(const char* text, int r, int g, int b) {
if (!g_status_indicator) return;
g_status_indicator->SetLabel(wxString::FromUTF8(text ? text : ""));
g_status_indicator->SetForegroundColour(
wxColour((unsigned char)r, (unsigned char)g, (unsigned char)b));
reposition_status_indicator();
g_status_indicator->Refresh();
}
// Add the table-zoom slider + percent label to the frame's status bar (round 14
// #3). Widens the bar to three fields (status | indicator | zoom) and wires the
// slider straight to apply_table_zoom -- no Rust round-trip. Call after the table
// exists so the slider can find it.
void wxbr_table_set_zoom(double factor); // defined below; used by the handlers here
void wxbr_status_zoom_init(void* frame_ptr) {
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
int widths[3] = { -1, PxFromDip(frame, 240), PxFromDip(frame, 190) };
sb->SetFieldsCount(3);
sb->SetStatusWidths(3, widths);
// A native slider needs more vertical room than a default status bar gives, so
// grow the bar to fit it (round 14 #3).
sb->SetMinHeight(PxFromDip(frame, 30));
if (!g_zoom_slider) {
g_zoom_slider = new wxSlider(sb, wxID_ANY, 100, 50, 250);
g_zoom_slider->SetToolTip(wxT("Table zoom"));
// Editable percent field (round 15 #4): type an exact scale and press Enter.
g_zoom_entry = new wxTextCtrl(sb, wxID_ANY, wxT("100%"), wxDefaultPosition,
wxDefaultSize, wxTE_PROCESS_ENTER | wxTE_RIGHT);
g_zoom_entry->SetToolTip(wxT("Table zoom (type a %, Enter)"));
g_zoom_slider->Bind(wxEVT_SLIDER, [](wxCommandEvent& e) {
apply_table_zoom(e.GetInt() / 100.0);
});
g_zoom_entry->Bind(wxEVT_TEXT_ENTER, [](wxCommandEvent&) {
if (!g_zoom_entry) return;
wxString s = g_zoom_entry->GetValue();
s.Replace("%", "");
s.Trim(true).Trim(false);
long pct = 0;
if (s.ToLong(&pct) && pct > 0) wxbr_table_set_zoom(pct / 100.0);
});
sb->Bind(wxEVT_SIZE, [](wxSizeEvent& ev) {
reposition_status_indicator();
ev.Skip();
});
// Ctrl +/- / Ctrl+0 zoom the table from anywhere in the window (round 15 #4).
frame->Bind(wxEVT_CHAR_HOOK, [](wxKeyEvent& e) {
if (e.ControlDown()) {
int k = e.GetKeyCode();
if (k == '=' || k == '+' || k == WXK_NUMPAD_ADD) {
wxbr_table_set_zoom(g_table_zoom + 0.1);
return;
}
if (k == '-' || k == WXK_NUMPAD_SUBTRACT) {
wxbr_table_set_zoom(g_table_zoom - 0.1);
return;
}
if (k == '0' || k == WXK_NUMPAD0) {
wxbr_table_set_zoom(1.0);
return;
}
}
e.Skip();
});
}
reposition_status_indicator();
}
// Set the table zoom programmatically (e.g. to restore a saved value); also moves
// the slider to match.
void wxbr_table_set_zoom(double factor) {
if (g_zoom_slider) g_zoom_slider->SetValue((int)(factor * 100 + 0.5));
apply_table_zoom(factor);
}
// Re-apply the current zoom to freshly-rebuilt columns (round 14 #3). Called from
// Rust right after the table's columns are recreated (they come back at their
// 100% widths), so a non-100% zoom survives a column show/hide/reorder rebuild.
void wxbr_table_zoom_reapply() {
// g_zoom_base_w was repopulated by the column appends during the rebuild.
apply_table_zoom(g_table_zoom);
}
// ---- deferred destroy (safe from event handlers) ----------------------------
void wxbr_destroy(void* win) { ((wxWindow*)win)->Destroy(); }
// Destroy a window's children immediately (used to rebuild a panel's dynamic
// contents in place, e.g. the filter dialog's per-column controls).
void wxbr_destroy_children(void* win) { ((wxWindow*)win)->DestroyChildren(); }
} // extern "C"