Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

v4.0.3 update

tilakpatel227a7d54d3c519
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index c49850022..f787d2945 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -1528,6 +1528,7 @@ set(APP_SOURCES
src/app/ScreenRouter.cpp
src/app/DockScreenRouter.cpp
src/app/TerminalShell.cpp
+ src/app/MonitorPickerDialog.cpp
)
# All screen files compiled individually — they have local statics/functions that
diff --git a/fincept-qt/src/app/DockScreenRouter.cpp b/fincept-qt/src/app/DockScreenRouter.cpp
index 12e7c38d0..e399d4a8c 100644
--- a/fincept-qt/src/app/DockScreenRouter.cpp
+++ b/fincept-qt/src/app/DockScreenRouter.cpp
@@ -319,7 +319,8 @@ void DockScreenRouter::navigate(const QString& id, bool exclusive) {
apply_ads_theme();
current_id_ = id;
- SessionManager::instance().set_last_screen(id);
+ if (auto* frame = qobject_cast<WindowFrame*>(parent()))
+ SessionManager::instance().set_last_screen(frame->window_id(), id);
LOG_INFO("DockRouter", "Navigated to: " + id);
emit screen_changed(id);
}
@@ -378,7 +379,8 @@ void DockScreenRouter::tab_into(const QString& id) {
dw->setAsCurrentTab();
current_id_ = id;
- SessionManager::instance().set_last_screen(id);
+ if (auto* frame = qobject_cast<WindowFrame*>(parent()))
+ SessionManager::instance().set_last_screen(frame->window_id(), id);
LOG_INFO("DockRouter", "Tabbed into: " + id);
emit screen_changed(id);
}
@@ -482,6 +484,10 @@ void DockScreenRouter::ensure_all_registered() {
all_ids.append(it.key());
}
+ // Bulk register all factories. The transient visibilityChanged(true)
+ // each addDockWidget emits would otherwise eagerly materialise every
+ // screen — see suppress_visibility_materialize_ docs.
+ suppress_visibility_materialize_ = true;
ads::CDockAreaWidget* first_area = nullptr;
for (const QString& id : all_ids) {
if (!dock_widgets_.contains(id)) {
@@ -496,6 +502,7 @@ void DockScreenRouter::ensure_all_registered() {
dw->toggleView(false); // start hidden
}
}
+ suppress_visibility_materialize_ = false;
// Apply theme directly to all title bars and tabs created above.
apply_ads_theme();
}
@@ -1209,6 +1216,14 @@ ads::CDockWidget* DockScreenRouter::create_dock_widget(const QString& id) {
// Materialize on first show; save state on hide.
connect(dw, &ads::CDockWidget::visibilityChanged, this, [this, id](bool visible) {
if (visible) {
+ // Bulk-register paths (ensure_all_registered, prepare_dock_widget)
+ // transiently make the widget visible just to register it with the
+ // manager before hiding it again with toggleView(false). Skip the
+ // factory call in that window — the user hasn't asked to see this
+ // panel yet, and materialising every registered screen at startup
+ // is the cold-boot bug we're guarding against.
+ if (suppress_visibility_materialize_)
+ return;
materialize_screen(id);
} else {
save_screen_state(id);
@@ -1240,8 +1255,13 @@ void DockScreenRouter::prepare_dock_widget(const QString& id) {
// ensure_all_registered's "tab into shared area, hide" pattern so
// we don't generate N vertical splits during the pre-restore pass.
if (manager_) {
+ // Same rationale as ensure_all_registered: the transient
+ // visibilityChanged(true) the addDockWidget emits must not
+ // materialise the screen factory before the layout is restored.
+ suppress_visibility_materialize_ = true;
manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
dw->toggleView(false); // hidden until restoreState repositions it
+ suppress_visibility_materialize_ = false;
}
}
diff --git a/fincept-qt/src/app/DockScreenRouter.h b/fincept-qt/src/app/DockScreenRouter.h
index 6bf8be92c..614e84f90 100644
--- a/fincept-qt/src/app/DockScreenRouter.h
+++ b/fincept-qt/src/app/DockScreenRouter.h
@@ -196,6 +196,16 @@ class DockScreenRouter : public QObject {
/// by `~DockScreenRouter` indirectly via PanelRegistry::unregister_panel.
QHash<QString, PanelInstanceId> instance_ids_;
+ /// When true, the visibilityChanged-→-materialize_screen autowire on
+ /// every CDockWidget short-circuits. Set during bulk widget registration
+ /// (ensure_all_registered / prepare_dock_widget) so adding a freshly-
+ /// created dock widget — which transiently emits visibilityChanged(true)
+ /// before toggleView(false) hides it — doesn't cascade into eagerly
+ /// instantiating every screen factory. Without this guard a multi-window
+ /// session's startup constructs all ~46 screens up front (DataHub
+ /// subscriptions, OpenGL surfaces, etc.), defeating the lazy intent.
+ bool suppress_visibility_materialize_ = false;
+
// Phase 4 grid removal: the four `grid_*_` CDockAreaWidget pointers and
// `panel_count_` int are gone. ADS handles arbitrary splits natively;
// navigate() now tabs new panels into the focused dock area or creates
diff --git a/fincept-qt/src/app/MonitorPickerDialog.cpp b/fincept-qt/src/app/MonitorPickerDialog.cpp
new file mode 100644
index 000000000..670abd731
--- /dev/null
+++ b/fincept-qt/src/app/MonitorPickerDialog.cpp
@@ -0,0 +1,218 @@
+#include "app/MonitorPickerDialog.h"
+
+#include "ui/theme/Theme.h"
+
+#include <QDialogButtonBox>
+#include <QGuiApplication>
+#include <QLabel>
+#include <QMouseEvent>
+#include <QPaintEvent>
+#include <QPainter>
+#include <QPen>
+#include <QScreen>
+#include <QVBoxLayout>
+
+#include <algorithm>
+#include <functional>
+
+namespace fincept {
+
+namespace {
+
+// Internal widget that paints all connected screens as a proportional map.
+// Hovering highlights a monitor; clicking invokes the callback with the
+// chosen QScreen*. No signals — kept Q_OBJECT-free so MOC doesn't need to
+// see this anonymous-namespace type.
+class MonitorMapWidget : public QWidget {
+ public:
+ using ClickHandler = std::function<void(QScreen*)>;
+
+ MonitorMapWidget(QScreen* current, ClickHandler on_click, QWidget* parent)
+ : QWidget(parent), current_(current), on_click_(std::move(on_click)) {
+ setMouseTracking(true);
+ setMinimumSize(560, 320);
+ }
+
+ protected:
+ void paintEvent(QPaintEvent*) override {
+ const auto screens = QGuiApplication::screens();
+ if (screens.isEmpty())
+ return;
+
+ // Virtual desktop bounds — union of every screen's geometry.
+ QRect bounds = screens.first()->geometry();
+ for (QScreen* s : screens)
+ bounds = bounds.united(s->geometry());
+
+ const int margin = 20;
+ const QRect content = rect().adjusted(margin, margin, -margin, -margin);
+ if (content.width() <= 0 || content.height() <= 0 || bounds.isEmpty())
+ return;
+
+ const qreal scale = std::min(static_cast<qreal>(content.width()) / bounds.width(),
+ static_cast<qreal>(content.height()) / bounds.height());
+ const qreal off_x = content.left() + (content.width() - bounds.width() * scale) / 2.0
+ - bounds.left() * scale;
+ const qreal off_y = content.top() + (content.height() - bounds.height() * scale) / 2.0
+ - bounds.top() * scale;
+
+ QPainter p(this);
+ p.setRenderHint(QPainter::Antialiasing, true);
+ p.setRenderHint(QPainter::TextAntialiasing, true);
+ p.fillRect(rect(), QColor(ui::colors::BG_SURFACE()));
+
+ screen_rects_.clear();
+ screen_rects_.reserve(screens.size());
+
+ const QScreen* primary = QGuiApplication::primaryScreen();
+
+ for (int i = 0; i < screens.size(); ++i) {
+ QScreen* s = screens[i];
+ const QRect g = s->geometry();
+ const QRectF mapped(g.left() * scale + off_x, g.top() * scale + off_y,
+ g.width() * scale, g.height() * scale);
+ const QRect mapped_int = mapped.toRect();
+ screen_rects_.append(mapped_int);
+
+ const bool is_hover = (i == hover_idx_);
+ const bool is_current = (s == current_);
+ const bool is_primary = (s == primary);
+
+ QColor fill = QColor(ui::colors::BG_BASE());
+ QColor border = QColor(ui::colors::BORDER_DIM());
+ int border_w = 1;
+ if (is_hover) {
+ fill = QColor(ui::colors::AMBER_DIM());
+ border = QColor(ui::colors::AMBER());
+ border_w = 2;
+ } else if (is_current) {
+ border = QColor(ui::colors::AMBER());
+ border_w = 2;
+ }
+
+ p.setPen(QPen(border, border_w));
+ p.setBrush(fill);
+ const QRectF body = mapped.adjusted(border_w * 0.5, border_w * 0.5,
+ -border_w * 0.5, -border_w * 0.5);
+ p.drawRect(body);
+
+ QFont label_font = font();
+ label_font.setPixelSize(28);
+ label_font.setBold(true);
+ p.setFont(label_font);
+ p.setPen(is_hover ? QColor(ui::colors::TEXT_PRIMARY())
+ : QColor(ui::colors::TEXT_PRIMARY()));
+ const QString label =
+ QString::number(i + 1) + (is_primary ? QStringLiteral(" ★") : QString());
+ p.drawText(mapped_int, Qt::AlignCenter, label);
+
+ QFont sub_font = font();
+ sub_font.setPixelSize(10);
+ p.setFont(sub_font);
+ p.setPen(QColor(ui::colors::TEXT_SECONDARY()));
+ const QString sub = QStringLiteral("%1×%2").arg(g.width()).arg(g.height());
+ p.drawText(mapped_int.adjusted(4, 4, -4, -4),
+ Qt::AlignHCenter | Qt::AlignBottom, sub);
+
+ if (is_current) {
+ QFont tag_font = sub_font;
+ tag_font.setBold(true);
+ p.setFont(tag_font);
+ p.setPen(QColor(ui::colors::AMBER()));
+ p.drawText(mapped_int.adjusted(4, 4, -4, -4),
+ Qt::AlignHCenter | Qt::AlignTop, tr("CURRENT"));
+ }
+ }
+ }
+
+ void mouseMoveEvent(QMouseEvent* e) override {
+ int new_idx = -1;
+ for (int i = 0; i < screen_rects_.size(); ++i) {
+ if (screen_rects_[i].contains(e->pos())) {
+ new_idx = i;
+ break;
+ }
+ }
+ if (new_idx != hover_idx_) {
+ hover_idx_ = new_idx;
+ setCursor(new_idx >= 0 ? Qt::PointingHandCursor : Qt::ArrowCursor);
+ update();
+ }
+ }
+
+ void leaveEvent(QEvent*) override {
+ if (hover_idx_ != -1) {
+ hover_idx_ = -1;
+ unsetCursor();
+ update();
+ }
+ }
+
+ void mousePressEvent(QMouseEvent* e) override {
+ if (e->button() != Qt::LeftButton)
+ return;
+ const auto screens = QGuiApplication::screens();
+ for (int i = 0; i < screen_rects_.size() && i < screens.size(); ++i) {
+ if (screen_rects_[i].contains(e->pos())) {
+ if (on_click_)
+ on_click_(screens[i]);
+ return;
+ }
+ }
+ }
+
+ private:
+ QScreen* current_ = nullptr;
+ ClickHandler on_click_;
+ int hover_idx_ = -1;
+ QList<QRect> screen_rects_;
+};
+
+} // namespace
+
+MonitorPickerDialog::MonitorPickerDialog(QWidget* parent, QScreen* current) : QDialog(parent) {
+ setWindowTitle(tr("Choose Monitor"));
+ setModal(true);
+ setMinimumSize(620, 420);
+
+ auto* vl = new QVBoxLayout(this);
+ vl->setContentsMargins(16, 14, 16, 14);
+ vl->setSpacing(10);
+
+ auto* title = new QLabel(tr("Open new window on:"), this);
+ title->setStyleSheet(QStringLiteral("color: %1; font-size: 13px; font-weight: 600;")
+ .arg(QString(ui::colors::TEXT_PRIMARY())));
+ vl->addWidget(title);
+
+ auto* map = new MonitorMapWidget(
+ current,
+ [this](QScreen* s) {
+ picked_ = s;
+ accept();
+ },
+ this);
+ vl->addWidget(map, /*stretch=*/1);
+
+ auto* hint = new QLabel(
+ tr("★ = primary monitor. Click a monitor to open the new window there."), this);
+ hint->setStyleSheet(QStringLiteral("color: %1; font-size: 10px;")
+ .arg(QString(ui::colors::TEXT_SECONDARY())));
+ vl->addWidget(hint);
+
+ auto* bb = new QDialogButtonBox(QDialogButtonBox::Cancel, this);
+ connect(bb, &QDialogButtonBox::rejected, this, &QDialog::reject);
+ vl->addWidget(bb);
+}
+
+QScreen* MonitorPickerDialog::pick(QWidget* parent, QScreen* current) {
+ const auto screens = QGuiApplication::screens();
+ if (screens.size() <= 1)
+ return screens.isEmpty() ? nullptr : screens.first();
+
+ MonitorPickerDialog dlg(parent, current);
+ if (dlg.exec() == QDialog::Accepted)
+ return dlg.picked_screen();
+ return nullptr;
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/app/MonitorPickerDialog.h b/fincept-qt/src/app/MonitorPickerDialog.h
new file mode 100644
index 000000000..98ee35a72
--- /dev/null
+++ b/fincept-qt/src/app/MonitorPickerDialog.h
@@ -0,0 +1,33 @@
+#pragma once
+// MonitorPickerDialog — visual monitor map shown when the user requests a
+// new window on a multi-monitor system. The dialog draws each connected
+// QScreen as a scaled rectangle (preserving the virtual-desktop layout) and
+// lets the user click the monitor where the new window should appear.
+//
+// Use MonitorPickerDialog::pick() instead of constructing directly — it
+// short-circuits the dialog when only one monitor is connected.
+
+#include <QDialog>
+
+class QScreen;
+
+namespace fincept {
+
+class MonitorPickerDialog : public QDialog {
+ Q_OBJECT
+ public:
+ explicit MonitorPickerDialog(QWidget* parent, QScreen* current);
+
+ QScreen* picked_screen() const { return picked_; }
+
+ /// Returns the chosen screen, or nullptr if the user cancelled. If only
+ /// a single monitor is connected the dialog is skipped and that monitor
+ /// is returned directly. `current` is visually highlighted as "the
+ /// monitor the request came from" (purely a cue — does not pre-select).
+ static QScreen* pick(QWidget* parent, QScreen* current);
+
+ private:
+ QScreen* picked_ = nullptr;
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/app/ScreenRouter.cpp b/fincept-qt/src/app/ScreenRouter.cpp
index c15d26448..fbc0769ab 100644
--- a/fincept-qt/src/app/ScreenRouter.cpp
+++ b/fincept-qt/src/app/ScreenRouter.cpp
@@ -1,5 +1,6 @@
#include "app/ScreenRouter.h"
+#include "app/WindowFrame.h"
#include "core/logging/Logger.h"
#include "core/session/SessionManager.h"
@@ -22,7 +23,8 @@ void ScreenRouter::navigate(const QString& id) {
if (it != screens_.end()) {
current_id_ = id;
stack_->setCurrentWidget(it.value());
- SessionManager::instance().set_last_screen(id);
+ if (auto* frame = qobject_cast<WindowFrame*>(parent()))
+ SessionManager::instance().set_last_screen(frame->window_id(), id);
LOG_INFO("Router", "Navigated to: " + id);
emit screen_changed(id);
return;
diff --git a/fincept-qt/src/app/TerminalShell.cpp b/fincept-qt/src/app/TerminalShell.cpp
index e8b45aa6d..d0c8bcf6d 100644
--- a/fincept-qt/src/app/TerminalShell.cpp
+++ b/fincept-qt/src/app/TerminalShell.cpp
@@ -1,6 +1,7 @@
#include "app/TerminalShell.h"
#include "ai_chat/ChatBubbleController.h"
+#include "app/WindowFrame.h"
#include "auth/AuthManager.h"
#include "auth/InactivityGuard.h"
#include "auth/PinManager.h"
@@ -25,6 +26,8 @@
#include "storage/workspace/WorkspaceSnapshotRing.h"
#include <QDateTime>
+#include <QGuiApplication>
+#include <QScreen>
#include <QUuid>
namespace fincept {
@@ -89,6 +92,51 @@ void TerminalShell::initialise() {
// connections are in place before any frame restores. Phase 6's full
// workspace-variant matcher will subscribe to topology_changed.
(void) MonitorWatcher::instance();
+ // Rescue off-screen windows when monitors come or go at runtime. The
+ // raw `screenAdded` / `screenRemoved` signals fire mid-burst (some
+ // OSes emit removed-then-added on dock unplug/replug); MonitorWatcher
+ // debounces to a single topology_changed once the dust has settled.
+ QObject::connect(&MonitorWatcher::instance(), &MonitorWatcher::topology_changed,
+ &MonitorWatcher::instance(), [](const layout::MonitorTopologyKey&) {
+ const auto screens = QGuiApplication::screens();
+ if (screens.isEmpty())
+ return;
+ for (WindowFrame* w : WindowRegistry::instance().frames()) {
+ if (!w)
+ continue;
+ const QRect frame = w->frameGeometry();
+ // A window is "rescued" only if no currently-connected screen's
+ // available geometry intersects it at all — i.e. it would be
+ // completely invisible. Partial overlap is fine; the user can
+ // still grab the title bar.
+ bool on_some_screen = false;
+ for (QScreen* s : screens) {
+ if (s && s->availableGeometry().intersects(frame)) {
+ on_some_screen = true;
+ break;
+ }
+ }
+ if (on_some_screen)
+ continue;
+ QScreen* target = QGuiApplication::primaryScreen();
+ if (!target)
+ target = screens.first();
+ if (!target)
+ continue;
+ const QRect ag = target->availableGeometry();
+ // Keep the window's size if it fits, otherwise clamp to 9/10
+ // of the target screen (same heuristic the constructor and the
+ // new-window path use).
+ QSize sz = w->size();
+ sz.setWidth(qMin(sz.width(), ag.width() * 9 / 10));
+ sz.setHeight(qMin(sz.height(), ag.height() * 9 / 10));
+ w->resize(sz);
+ w->move(ag.center() - QPoint(sz.width() / 2, sz.height() / 2));
+ LOG_INFO(kShellTag,
+ QString("Rescued window %1 onto '%2' after topology change")
+ .arg(w->window_id()).arg(target->name()));
+ }
+ });
FT_TS(109);
// Phase 1b skeleton: LockOverlayController construction. Currently a
// no-op — the full lift is deferred (see auth/lock/LockOverlayController.h
diff --git a/fincept-qt/src/app/WindowFrame.cpp b/fincept-qt/src/app/WindowFrame.cpp
index 3449d9e16..472dce101 100644
--- a/fincept-qt/src/app/WindowFrame.cpp
+++ b/fincept-qt/src/app/WindowFrame.cpp
@@ -4,6 +4,7 @@
#include "ai_chat/AiChatScreen.h"
#include "ai_chat/LlmService.h"
#include "app/DockScreenRouter.h"
+#include "app/MonitorPickerDialog.h"
#include "auth/AuthManager.h"
#include "auth/InactivityGuard.h"
#include "auth/PinManager.h"
@@ -481,22 +482,18 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
return;
}
if (action == "new_window") {
+ // Ask the user which monitor when more than one is connected.
+ // pick() returns the only screen if there's just one, and
+ // nullptr if the user cancels the dialog — in which case no
+ // window is created.
+ QScreen* target = MonitorPickerDialog::pick(this, this->screen());
+ if (!target)
+ return;
auto* w = new WindowFrame(WindowFrame::next_window_id());
w->setAttribute(Qt::WA_DeleteOnClose);
- // Place on the next available screen, or alongside this window
- const QList<QScreen*> screens = QGuiApplication::screens();
- if (screens.size() > 1) {
- // Find a screen that doesn't already contain this window's centre
- const QPoint this_centre = geometry().center();
- for (QScreen* s : screens) {
- if (!s->geometry().contains(this_centre)) {
- const QRect sg = s->availableGeometry();
- w->resize(sg.width() * 9 / 10, sg.height() * 9 / 10);
- w->move(sg.center() - w->rect().center());
- break;
- }
- }
- }
+ const QRect sg = target->availableGeometry();
+ w->resize(sg.width() * 9 / 10, sg.height() * 9 / 10);
+ w->move(sg.center() - w->rect().center());
w->show();
w->raise();
w->activateWindow();
@@ -781,14 +778,25 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
// Otherwise, navigate to dashboard as default.
auto& auth_mgr = auth::AuthManager::instance();
if (auth_mgr.is_authenticated() || auth_mgr.is_loading()) {
- // If user is authenticated and has a PIN, show lock screen first.
- // If no PIN, on_auth_state_changed will route to PIN setup.
- if (auth_mgr.is_authenticated() && auth::PinManager::instance().has_pin()) {
+ // If user is authenticated and has a PIN, show lock screen first —
+ // UNLESS this is an additional window opened while an existing
+ // window has already cleared the PIN gate this session.
+ // pin_gate_cleared_ was bootstrapped above from the process-wide
+ // InactivityGuard flag (which is the single source of truth for
+ // "is the terminal locked?"); skipping the prompt here just
+ // mirrors the unlocked state into the new frame.
+ if (auth_mgr.is_authenticated() && auth::PinManager::instance().has_pin()
+ && !pin_gate_cleared_) {
LOG_INFO("WindowFrame", "Session restored — showing PIN unlock");
lock_screen_->show_unlock();
locked_ = true;
set_shell_visible(false);
stack_->setCurrentIndex(3);
+ } else if (auth_mgr.is_authenticated() && auth::PinManager::instance().has_pin()) {
+ LOG_INFO("WindowFrame",
+ "Session already unlocked — skipping PIN prompt for additional window");
+ set_shell_visible(true);
+ stack_->setCurrentIndex(1);
} else if (auth_mgr.is_authenticated()) {
// Authenticated but no PIN yet — will be caught by on_auth_state_changed
on_auth_state_changed();
@@ -801,8 +809,9 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
dock_router_->navigate("dashboard");
LOG_INFO("WindowFrame", "Applied clean default dock layout");
} else {
- // Restore last-active screen as the focused tab and sync tab bar
- const QString last = SessionManager::instance().last_screen();
+ // Restore last-active screen as the focused tab and sync tab bar.
+ // Per-window key so multi-window users don't override each other.
+ const QString last = SessionManager::instance().last_screen(window_id_);
if (!last.isEmpty()) {
auto* dw = dock_router_->find_dock_widget(last);
if (dw && !dw->isClosed()) {
@@ -1545,15 +1554,25 @@ layout::FrameLayout WindowFrame::capture_layout() const {
fl.active_panel = uuid;
}
- // Per-panel state. Walk every dock widget the manager knows about
- // (not just openedDockWidgets) — closed-but-registered panels still
- // belong in the layout so reopen restores their state. The router's
- // panel_uuid_for() returns the stable PanelInstanceId minted at
- // create_dock_widget() time.
+ // Per-panel state. Walk every dock widget the manager knows about,
+ // but skip the ones currently closed. The dock manager holds two
+ // populations:
+ // 1. Panels the user has actually opened (visible, or visible then
+ // user-closed).
+ // 2. Placeholder shells pre-registered by ensure_all_registered() so
+ // restoreState can match them by objectName — these sit as hidden
+ // tabs in a single shared dock area and were never user-opened.
+ //
+ // Capturing population (2) silently poisoned the autosave: on the next
+ // apply_layout() the placeholders were re-injected as visible tabs in
+ // the source window (Profile, About, etc. would all appear next to
+ // the user's actual panel). Per-panel state for genuinely user-closed
+ // tabs is already persisted via save_screen_state(), so dropping them
+ // here is non-destructive — reopen restores the screen state from disk.
for (const auto& entry : dock_manager_->dockWidgetsMap().toStdMap()) {
const QString& id = entry.first;
ads::CDockWidget* dw = entry.second;
- if (!dw)
+ if (!dw || dw->isClosed())
continue;
layout::PanelState ps;
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 339787462..9a3b288e0 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -1,6 +1,8 @@
#include "ai_chat/LlmService.h"
+#include "app/MonitorPickerDialog.h"
#include "app/WindowFrame.h"
#include "app/TerminalShell.h"
+#include "core/keys/WindowCycler.h"
#include "auth/AuthManager.h"
#include "auth/InactivityGuard.h"
#include "auth/PinManager.h"
@@ -108,11 +110,12 @@
static void wire_app_lifecycle(QApplication& app, fincept::InstanceLock& lock) {
QObject::connect(&lock, &fincept::InstanceLock::message_received,
[](const QStringList& /*args*/) {
- auto* w = new fincept::WindowFrame(fincept::WindowFrame::next_window_id());
- w->setAttribute(Qt::WA_DeleteOnClose);
- w->show();
- w->raise();
- w->activateWindow();
+ // Route through the same picker the toolbar uses so
+ // secondary-instance launches respect the user's
+ // monitor choice on multi-monitor setups. Picker
+ // short-circuits on single-monitor systems, so this
+ // is a no-op cost there.
+ fincept::WindowCycler::instance().new_window_on_next_monitor();
LOG_INFO("App", "New window opened via secondary instance request");
});
QObject::connect(&app, &QApplication::lastWindowClosed, &app, []() {
@@ -317,6 +320,57 @@ int main(int argc, char* argv[]) {
fincept::wallet::TokenMetadataService::instance().load_from_storage();
FT_MARK(35);
+ // ── Pre-warm the dashboard topics ────────────────────────────────────────
+ // The user spends real time on the login / setup / recovery flow before
+ // the dashboard ever paints. Kick the hub now so producers start fetching
+ // immediately; by the time the dashboard widgets subscribe in showEvent,
+ // peek() returns a fresh value and deliver_initial_value() paints it on
+ // the first frame instead of showing the loading overlay.
+ //
+ // Set is the union of topics used by every widget in the default
+ // `portfolio_manager` template plus the global indices/forex/crypto/
+ // commodities universes (so any user-customised default still hits the
+ // warm cache). Late-registered producers (the QTimer::singleShot(0)
+ // batch below) warm themselves on their own next scheduler pass once
+ // subscribers exist; pre-warming them here would orphan-log because
+ // ensure_registered_with_hub() hasn't run for them yet.
+ QTimer::singleShot(0, qApp, []() {
+ auto& hub = fincept::datahub::DataHub::instance();
+ QStringList topics;
+
+ auto add_quotes = [&](const QStringList& syms) {
+ topics.reserve(topics.size() + syms.size());
+ for (const auto& s : syms)
+ topics.append(QStringLiteral("market:quote:") + s);
+ };
+
+ // Default-template widget symbol sets (kept aligned with the widget
+ // source — if a widget's hardcoded list changes, update here too).
+ add_quotes(fincept::services::MarketDataService::indices_symbols());
+ add_quotes(fincept::services::MarketDataService::forex_symbols());
+ add_quotes(fincept::services::MarketDataService::crypto_symbols());
+ add_quotes(fincept::services::MarketDataService::commodity_symbols());
+ add_quotes({"^GSPC", "^IXIC", "^DJI", "^RUT", "^VIX", "GC=F"}); // performance
+ add_quotes({"^VIX", "SPY", "QQQ", "IWM", "TLT",
+ "NVDA", "TSLA", "AMD", "META", "PLTR", "COIN"}); // risk_metrics
+ add_quotes({"AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "TSLA", "META",
+ "JPM"}); // watchlist default
+
+ // Non-quote topics used by the default template.
+ topics.append(QStringLiteral("news:general"));
+ topics.append(QStringLiteral("econ:fincept:upcoming_events"));
+
+ // De-duplicate (several add_quotes calls overlap on common symbols).
+ topics.removeDuplicates();
+
+ // force=true bypasses min_interval_ms so the very first cold-start
+ // fetch isn't gated by an unrelated test refresh; producer rate
+ // limits still apply at dispatch (DataHub::flush_coalesced_requests).
+ hub.request(topics, /*force=*/true);
+ LOG_INFO("App", QString("Pre-warmed %1 dashboard topics during login screen")
+ .arg(topics.size()));
+ });
+
// ── Deferred service init — fires after first window paint ───────────────
// These services back tab-specific screens (F&O, prediction markets,
// alpha arena, agents, wallet/treasury/staking, etc.) — none of them is
diff --git a/fincept-qt/src/core/keys/WindowCycler.cpp b/fincept-qt/src/core/keys/WindowCycler.cpp
index 4bec86ee1..086ce4e3a 100644
--- a/fincept-qt/src/core/keys/WindowCycler.cpp
+++ b/fincept-qt/src/core/keys/WindowCycler.cpp
@@ -1,6 +1,7 @@
#include "core/keys/WindowCycler.h"
#include "app/DockScreenRouter.h"
+#include "app/MonitorPickerDialog.h"
#include "app/WindowFrame.h"
#include "core/logging/Logger.h"
#include "core/window/WindowRegistry.h"
@@ -73,53 +74,22 @@ void WindowCycler::cycle_panels_in_current_window(bool forward) {
}
void WindowCycler::new_window_on_next_monitor() {
+ // When more than one monitor is connected, ask the user which one. If
+ // they cancel, no window is created. With a single monitor the picker
+ // short-circuits and returns it directly. (Used by the toolbar action,
+ // Ctrl+Shift+N, the Launchpad "New Window" button, and right-click
+ // "Tear off into new window" — so the prompt covers all paths.)
auto* src = current_focused();
+ QScreen* target = MonitorPickerDialog::pick(src, src ? src->screen() : nullptr);
+ if (!target)
+ return;
+
auto* w = new WindowFrame(WindowFrame::next_window_id());
w->setAttribute(Qt::WA_DeleteOnClose);
- // Decision 5.6: prefer the first monitor that has no frames at all,
- // since that's the case the user most often wants ("put it on my empty
- // 3rd monitor"). Fall back to "first monitor not containing focused
- // window's centre" (the pre-Phase 1 behaviour) when every monitor is
- // populated. Final fallback: don't reposition, let the constructor's
- // default placement run.
- const auto screens = QGuiApplication::screens();
- QScreen* target = nullptr;
-
- if (screens.size() > 1) {
- // Build a set of screens currently hosting at least one frame.
- const auto frames = WindowRegistry::instance().frames();
- QList<QScreen*> occupied;
- for (WindowFrame* mw : frames) {
- if (QScreen* s = mw->screen()) {
- if (!occupied.contains(s))
- occupied.append(s);
- }
- }
- // Tier 1: empty monitor.
- for (QScreen* s : screens) {
- if (!occupied.contains(s)) {
- target = s;
- break;
- }
- }
- // Tier 2: monitor not containing source centre.
- if (!target && src) {
- const QPoint centre = src->geometry().center();
- for (QScreen* s : screens) {
- if (!s->geometry().contains(centre)) {
- target = s;
- break;
- }
- }
- }
- }
-
- if (target) {
- const QRect sg = target->availableGeometry();
- w->resize(sg.width() * 9 / 10, sg.height() * 9 / 10);
- w->move(sg.center() - w->rect().center());
- }
+ const QRect sg = target->availableGeometry();
+ w->resize(sg.width() * 9 / 10, sg.height() * 9 / 10);
+ w->move(sg.center() - w->rect().center());
w->show();
w->raise();
diff --git a/fincept-qt/src/core/layout/WorkspaceShell.cpp b/fincept-qt/src/core/layout/WorkspaceShell.cpp
index 399be56f8..6d8437b50 100644
--- a/fincept-qt/src/core/layout/WorkspaceShell.cpp
+++ b/fincept-qt/src/core/layout/WorkspaceShell.cpp
@@ -185,6 +185,7 @@ int WorkspaceShell::apply(const Workspace& workspace) {
// Find an existing frame matching this window_id (and not already
// claimed by an earlier FrameLayout in this same apply() call).
fincept::WindowFrame* target = nullptr;
+ bool spawned = false;
for (auto* f : frames_now) {
if (f && !bound.contains(f) && f->frame_uuid() == fl.window_id) {
target = f;
@@ -204,16 +205,23 @@ int WorkspaceShell::apply(const Workspace& workspace) {
target->setAttribute(Qt::WA_DeleteOnClose);
target->show();
frames_now.append(target);
+ spawned = true;
}
bound.insert(target);
- // Apply geometry from the matched variant (if any). With UUID
- // round-trip the lookup hits both for reused live frames and for
- // freshly-spawned ones. We bind the frame to its saved monitor
- // FIRST (via stable_id lookup), then apply geometry — that way the
- // saved coords are interpreted on the correct screen even when the
- // user has reordered monitors since the layout was saved.
- if (variant) {
+ // Apply geometry from the matched variant — but ONLY when we just
+ // spawned the frame. For an already-live frame the user is looking
+ // at, its position was set by the WindowFrame constructor's
+ // QSettings restore (and the user may have moved it). Re-applying
+ // the workspace's saved screen here teleports the window mid-
+ // session — e.g. on PIN unlock, load_last_or_default() runs and
+ // would yank the window from monitor 1 (where the lock screen sat)
+ // to monitor 2 (where the snapshot says it lived last). The user
+ // experiences this as the app "jumping" to another monitor.
+ //
+ // Freshly-spawned frames need the geometry hint because their
+ // constructor had no QSettings row for the adopted UUID.
+ if (variant && spawned) {
const auto scr_it = variant->frame_screens.constFind(fl.window_id);
if (scr_it != variant->frame_screens.constEnd()) {
if (QScreen* saved_screen =
diff --git a/fincept-qt/src/core/session/SessionManager.cpp b/fincept-qt/src/core/session/SessionManager.cpp
index 3cd44ed29..08feb7666 100644
--- a/fincept-qt/src/core/session/SessionManager.cpp
+++ b/fincept-qt/src/core/session/SessionManager.cpp
@@ -213,11 +213,22 @@ void SessionManager::load_perspectives(QSettings& target) const {
settings_.endGroup();
}
-void SessionManager::set_last_screen(const QString& screen_id) {
- settings_.setValue("session/last_screen", screen_id);
+void SessionManager::set_last_screen(int window_id, const QString& screen_id) {
+ const QString key = QString("window_%1/last_screen").arg(window_id);
+ settings_.setValue(key, screen_id);
+ // Legacy global key is no longer authoritative — clear it so future
+ // reads don't fall back to a stale window's choice. Keeping the per-
+ // window key alone is the new contract.
+ settings_.remove("session/last_screen");
}
-QString SessionManager::last_screen() const {
+QString SessionManager::last_screen(int window_id) const {
+ const QString key = QString("window_%1/last_screen").arg(window_id);
+ const QString v = settings_.value(key).toString();
+ if (!v.isEmpty())
+ return v;
+ // Back-compat: fall back to the legacy global key once on first launch
+ // after upgrading. set_last_screen will overwrite it on the next nav.
return settings_.value("session/last_screen", "dashboard").toString();
}
diff --git a/fincept-qt/src/core/session/SessionManager.h b/fincept-qt/src/core/session/SessionManager.h
index 9d82d12e4..1186382c8 100644
--- a/fincept-qt/src/core/session/SessionManager.h
+++ b/fincept-qt/src/core/session/SessionManager.h
@@ -60,9 +60,12 @@ class SessionManager : public QObject {
void save_perspectives(QSettings& source);
void load_perspectives(QSettings& target) const;
- // Last active screen
- void set_last_screen(const QString& screen_id);
- QString last_screen() const;
+ // Last active screen — scoped per window_id so multi-window users don't
+ // overwrite each other's restore target. Reads fall back to the legacy
+ // global key when no per-window value is recorded (migration path for
+ // existing users; auto-cleaned the first time the new key is written).
+ void set_last_screen(int window_id, const QString& screen_id);
+ QString last_screen(int window_id) const;
/// Force an immediate snapshot of the current QSettings-backed state
/// into the WorkspaceDb ring buffer. Used by closeEvent paths that
diff --git a/fincept-qt/src/datahub/DataHub.cpp b/fincept-qt/src/datahub/DataHub.cpp
index dce347164..535b0d25e 100644
--- a/fincept-qt/src/datahub/DataHub.cpp
+++ b/fincept-qt/src/datahub/DataHub.cpp
@@ -804,17 +804,24 @@ void DataHub::request(const QString& topic, bool force) {
}
void DataHub::request(const QStringList& topics, bool force) {
- // Apply gates under the lock, then buffer into coalesce_pending_. The
- // coalesce timer (kCoalesceWindowMs) merges bursts of request() calls —
- // e.g., dashboard + markets subscribing simultaneously — into one
- // producer->refresh() per producer.
+ // Apply per-topic gates under the lock, then buffer into
+ // coalesce_pending_. The coalesce timer (kCoalesceWindowMs) merges
+ // bursts of request() calls — e.g., dashboard + markets subscribing
+ // simultaneously — into one producer->refresh() per producer.
//
- // Gates applied here (same as before — gating is at buffer time, not
- // flush time, because in_flight/min_interval reflect intent to fetch):
+ // Per-topic gates applied here (intent-to-fetch):
// - in_flight: always skip; the producer is already working.
// - min_interval_ms: skipped when `force=true` (user-driven refresh).
- // - max_requests_per_sec: always honoured — force doesn't open the
- // rate-limit floodgate.
+ //
+ // Per-producer rate limit (`max_requests_per_sec`) is enforced at
+ // dispatch in flush_coalesced_requests(), NOT here. A single
+ // coalesce flush issues exactly one refresh() call per producer
+ // regardless of how many topics it batches, so the rate limit only
+ // needs to gate dispatch. Gating at intake silently dropped every
+ // topic past the first when a widget cold-started N subscriptions
+ // back-to-back within the rate window — only the first cleared, the
+ // rest fell off the floor and spun in their loading state until the
+ // next 1 s scheduler tick (which had the same per-topic bug).
int accepted = 0;
bool need_arm = false;
QStringList orphan_topics;
@@ -834,15 +841,8 @@ void DataHub::request(const QStringList& topics, bool force) {
orphan_topics.append(topic);
continue;
}
- const int rps = p->max_requests_per_sec();
- if (rps > 0) {
- const qint64 last = producer_last_refresh_ms_.value(p, 0);
- const qint64 min_gap = 1000 / std::max(1, rps);
- if (last > 0 && (t - last) < min_gap) continue;
- }
st.in_flight = true;
st.last_refresh_request_ms = t;
- producer_last_refresh_ms_[p] = t;
// Buffer instead of dispatching — duplicate topics within the
// window are naturally prevented by the in_flight gate above.
coalesce_pending_[p].append(topic);
@@ -882,10 +882,45 @@ void DataHub::request(const QStringList& topics, bool force) {
void DataHub::flush_coalesced_requests() {
QHash<Producer*, QStringList> work;
+ bool defer_remaining = false;
{
QMutexLocker lock(&mutex_);
- work.swap(coalesce_pending_);
+ if (coalesce_pending_.isEmpty())
+ return;
+ const qint64 t = now_ms();
+ // Per-producer rate limit enforced HERE (at the dispatch boundary)
+ // rather than per-topic at intake. One refresh() per producer per
+ // flush, so checking once per producer is the correct granularity.
+ // Producers caught inside the rate window keep their topics in
+ // coalesce_pending_ and the timer is re-armed below.
+ for (auto it = coalesce_pending_.begin(); it != coalesce_pending_.end(); ) {
+ Producer* p = it.key();
+ const int rps = p->max_requests_per_sec();
+ if (rps > 0) {
+ const qint64 last = producer_last_refresh_ms_.value(p, 0);
+ const qint64 min_gap = 1000 / std::max(1, rps);
+ if (last > 0 && (t - last) < min_gap) {
+ defer_remaining = true;
+ ++it;
+ continue;
+ }
+ }
+ work.insert(p, std::move(it.value()));
+ producer_last_refresh_ms_[p] = t;
+ it = coalesce_pending_.erase(it);
+ }
}
+
+ if (defer_remaining) {
+ // Re-arm the timer on the hub thread so the deferred batch flushes
+ // after another coalesce window. Producer rate limits this short
+ // (10 rps → 100 ms) almost always clear inside one window.
+ QMetaObject::invokeMethod(this, [this]() {
+ if (!coalesce_timer_.isActive())
+ coalesce_timer_.start();
+ }, Qt::QueuedConnection);
+ }
+
if (work.isEmpty())
return;
@@ -937,6 +972,11 @@ void DataHub::scheduler_body() {
++it;
}
+ // Phase 1 — collect eligible topics by producer (no rate-limit
+ // gate yet). The per-producer rate limit applies to refresh()
+ // *calls*, not to topic enrolment; one refresh() carries the
+ // whole batch.
+ QHash<Producer*, QStringList> candidates;
for (auto it = subscriptions_.begin(); it != subscriptions_.end(); ++it) {
const QString& topic = it.key();
if (it.value().isEmpty()) continue;
@@ -954,20 +994,31 @@ void DataHub::scheduler_body() {
Producer* p = find_producer(topic);
if (!p) continue;
+ candidates[p].append(topic);
+ }
- // Per-producer rate limit: if producer caps at N req/sec,
- // ensure at least (1000/N) ms between refresh() calls to it.
+ // Phase 2 — apply per-producer rate limit ONCE, then promote
+ // the producer's whole batch into `work`. If a producer is
+ // inside its rate window, skip it this tick; its topics stay
+ // subscribed and will be picked up on the next tick (1 s away,
+ // well past any reasonable min_gap).
+ for (auto it = candidates.begin(); it != candidates.end(); ++it) {
+ Producer* p = it.key();
const int rps = p->max_requests_per_sec();
if (rps > 0) {
const qint64 last = producer_last_refresh_ms_.value(p, 0);
const qint64 min_gap = 1000 / std::max(1, rps);
if (last > 0 && (t - last) < min_gap) continue;
}
-
- st.in_flight = true;
- st.last_refresh_request_ms = t;
+ QStringList& batch = work[p];
+ batch.reserve(batch.size() + it.value().size());
+ for (const QString& topic : it.value()) {
+ auto& st = state_for(topic);
+ st.in_flight = true;
+ st.last_refresh_request_ms = t;
+ batch.append(topic);
+ }
producer_last_refresh_ms_[p] = t;
- work[p].append(topic);
}
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
index 4c3a5df4e..34fdfab4a 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
@@ -1,22 +1,26 @@
#include "screens/dashboard/widgets/PortfolioSummaryWidget.h"
-#include "storage/repositories/PortfolioHoldingsRepository.h"
+#include "datahub/DataHub.h"
+#include "datahub/DataHubMetaTypes.h"
+#include "services/portfolio/PortfolioService.h"
+#include "storage/repositories/PortfolioRepository.h"
#include "ui/theme/Theme.h"
-# include "datahub/DataHub.h"
-# include "datahub/DataHubMetaTypes.h"
-
+#include <QComboBox>
+#include <QDialog>
+#include <QDialogButtonBox>
+#include <QFormLayout>
#include <QFrame>
#include <QHBoxLayout>
+#include <QJsonObject>
+#include <QLabel>
#include <QScrollArea>
namespace fincept::screens::widgets {
-// Empty-state placeholder used when portfolio_holdings is empty. Previously
-// this fell back to a hardcoded `{AAPL, MSFT, NVDA, GOOGL, TSLA, SPY}` list,
-// which looked indistinguishable from a real portfolio — confusing for users
-// who'd just connected a broker. We now render a clear empty-state banner
-// instead so there's no ambiguity about what data they're looking at.
+namespace {
+constexpr const char* kConfigKeyPortfolioId = "portfolio_id";
+} // namespace
PortfolioSummaryWidget::PortfolioSummaryWidget(QWidget* parent)
: BaseWidget("PORTFOLIO SUMMARY", parent, ui::colors::POSITIVE) {
@@ -24,6 +28,14 @@ PortfolioSummaryWidget::PortfolioSummaryWidget(QWidget* parent)
vl->setContentsMargins(8, 8, 8, 8);
vl->setSpacing(6);
+ // ── Selected-portfolio label ────────────────────────────────────────────
+ // Sits above the summary card so the user always knows which portfolio
+ // the numbers belong to. Updated by load_holdings(); hidden until then.
+ portfolio_name_lbl_ = new QLabel(this);
+ portfolio_name_lbl_->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
+ portfolio_name_lbl_->hide();
+ vl->addWidget(portfolio_name_lbl_);
+
// ── Summary card ──
summary_card_ = new QWidget(this);
auto* sl = new QGridLayout(summary_card_);
@@ -80,11 +92,65 @@ PortfolioSummaryWidget::PortfolioSummaryWidget(QWidget* parent)
scroll_area_->setWidget(list_widget);
vl->addWidget(scroll_area_, 1);
+ // Enable the BaseWidget gear icon — make_config_dialog() handles the rest.
+ set_configurable(true);
+
+ // Manual refresh button on the title bar → reload holdings.
connect(this, &BaseWidget::refresh_requested, this, [this] { load_holdings(); });
+ // ── Cross-tab sync ─────────────────────────────────────────────────────
+ // When the Portfolio screen mutates data (add/sell asset, create/delete
+ // portfolio), the user expects this tile to update without a manual
+ // refresh. PortfolioService is the single source of truth; we listen to
+ // its signals rather than polling.
+ auto& svc = services::PortfolioService::instance();
+ connect(&svc, &services::PortfolioService::asset_added, this,
+ [this](const QString& pid) {
+ if (pid == selected_portfolio_id_)
+ load_holdings();
+ });
+ connect(&svc, &services::PortfolioService::asset_sold, this,
+ [this](const QString& pid) {
+ if (pid == selected_portfolio_id_)
+ load_holdings();
+ });
+ connect(&svc, &services::PortfolioService::portfolio_created, this,
+ [this](const portfolio::Portfolio&) {
+ refresh_portfolio_cache();
+ // If we had no selection yet, pick the first one now.
+ if (selected_portfolio_id_.isEmpty())
+ load_holdings();
+ });
+ connect(&svc, &services::PortfolioService::portfolio_deleted, this,
+ [this](const QString& deleted_id) {
+ refresh_portfolio_cache();
+ if (deleted_id == selected_portfolio_id_) {
+ selected_portfolio_id_.clear();
+ selected_portfolio_name_.clear();
+ emit config_changed(config());
+ load_holdings();
+ }
+ });
+
apply_styles();
set_loading(true);
+}
+QJsonObject PortfolioSummaryWidget::config() const {
+ QJsonObject cfg;
+ if (!selected_portfolio_id_.isEmpty())
+ cfg.insert(kConfigKeyPortfolioId, selected_portfolio_id_);
+ return cfg;
+}
+
+void PortfolioSummaryWidget::apply_config(const QJsonObject& cfg) {
+ const QString pid = cfg.value(kConfigKeyPortfolioId).toString();
+ if (pid == selected_portfolio_id_)
+ return;
+ selected_portfolio_id_ = pid;
+ selected_portfolio_name_.clear();
+ if (isVisible())
+ load_holdings();
}
void PortfolioSummaryWidget::showEvent(QShowEvent* e) {
@@ -111,6 +177,10 @@ void PortfolioSummaryWidget::apply_styles() {
for (auto* lbl : header_labels_)
lbl->setStyleSheet(QString("color: %1; font-size: 9px; font-weight: bold; background: transparent;")
.arg(ui::colors::TEXT_TERTIARY()));
+ if (portfolio_name_lbl_)
+ portfolio_name_lbl_->setStyleSheet(
+ QString("color: %1; font-size: 10px; font-weight: 600; background: transparent; padding: 0 2px;")
+ .arg(ui::colors::TEXT_SECONDARY()));
scroll_area_->setStyleSheet(
QString("QScrollArea { border: none; background: transparent; }"
"QScrollBar:vertical { width: 4px; background: transparent; }"
@@ -125,58 +195,107 @@ void PortfolioSummaryWidget::on_theme_changed() {
render(last_holdings_, last_quotes_);
}
+void PortfolioSummaryWidget::refresh_portfolio_cache() {
+ auto r = fincept::PortfolioRepository::instance().list_portfolios();
+ if (r.is_ok())
+ portfolio_cache_ = r.value();
+ else
+ portfolio_cache_.clear();
+}
+
void PortfolioSummaryWidget::load_holdings() {
- QVector<Holding> holdings;
+ refresh_portfolio_cache();
+
+ if (portfolio_cache_.isEmpty()) {
+ render_empty("No portfolios yet.\nCreate one from the Portfolio tab.");
+ return;
+ }
- // Read from portfolio_holdings via repository
- auto result = fincept::PortfolioHoldingsRepository::instance().get_active();
- if (result.is_ok()) {
- for (const auto& ph : result.value()) {
+ // Resolve selection. If the configured portfolio no longer exists
+ // (deleted from another tab), fall through to the first available.
+ const portfolio::Portfolio* picked = nullptr;
+ if (!selected_portfolio_id_.isEmpty()) {
+ for (const auto& p : portfolio_cache_) {
+ if (p.id == selected_portfolio_id_) {
+ picked = &p;
+ break;
+ }
+ }
+ }
+ if (!picked) {
+ picked = &portfolio_cache_.first();
+ selected_portfolio_id_ = picked->id;
+ emit config_changed(config());
+ }
+ selected_portfolio_name_ = picked->name;
+ portfolio_name_lbl_->setText(picked->name.toUpper());
+ portfolio_name_lbl_->setVisible(true);
+
+ auto assets_r = fincept::PortfolioRepository::instance().get_assets(selected_portfolio_id_);
+ QVector<Holding> holdings;
+ if (assets_r.is_ok()) {
+ for (const auto& a : assets_r.value()) {
+ if (a.symbol.isEmpty() || a.quantity <= 0)
+ continue;
Holding h;
- h.symbol = ph.symbol;
- h.shares = ph.shares;
- h.avg_cost = ph.avg_cost;
- if (!h.symbol.isEmpty() && h.shares > 0)
- holdings.append(h);
+ h.symbol = a.symbol;
+ h.shares = a.quantity;
+ h.avg_cost = a.avg_buy_price;
+ holdings.append(h);
}
}
if (holdings.isEmpty()) {
- // Render empty-state instead of fake demo holdings.
- set_loading(false);
- last_holdings_.clear();
- last_quotes_.clear();
- hub_unsubscribe_all();
- // Wipe rows + zero the summary counters.
- while (list_layout_->count() > 0) {
- auto* item = list_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
- }
- auto* empty = new QLabel(QStringLiteral(
- "No holdings configured.\nAdd positions via the Portfolio screen."));
- empty->setAlignment(Qt::AlignCenter);
- empty->setWordWrap(true);
- empty->setStyleSheet(QString("color: %1; font-size: 11px; padding: 20px; background: transparent;")
- .arg(ui::colors::TEXT_TERTIARY()));
- list_layout_->addWidget(empty);
- list_layout_->addStretch();
- total_value_lbl_->setText(QStringLiteral("$0"));
- day_pnl_lbl_->setText(QStringLiteral("$0"));
- total_pnl_lbl_->setText(QStringLiteral("$0"));
- num_holdings_lbl_->setText(QStringLiteral("0"));
+ render_empty(QStringLiteral("'%1' has no holdings.\nAdd positions from the Portfolio tab.")
+ .arg(picked->name));
return;
}
- fetch_prices(holdings);
-}
-
-void PortfolioSummaryWidget::fetch_prices(const QVector<Holding>& holdings) {
last_holdings_ = holdings;
hub_resubscribe(holdings);
}
+void PortfolioSummaryWidget::render_empty(const QString& message) {
+ set_loading(false);
+ last_holdings_.clear();
+ last_quotes_.clear();
+ hub_unsubscribe_all();
+
+ // Wipe rows + zero the summary counters so old numbers don't linger
+ // after a portfolio switch / deletion.
+ while (list_layout_->count() > 0) {
+ auto* item = list_layout_->takeAt(0);
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+ auto* empty = new QLabel(message);
+ empty->setAlignment(Qt::AlignCenter);
+ empty->setWordWrap(true);
+ empty->setStyleSheet(QString("color: %1; font-size: 11px; padding: 20px; background: transparent;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ list_layout_->addWidget(empty);
+ list_layout_->addStretch();
+ total_value_lbl_->setText(QStringLiteral("$0"));
+ day_pnl_lbl_->setText(QStringLiteral("$0"));
+ total_pnl_lbl_->setText(QStringLiteral("$0"));
+ num_holdings_lbl_->setText(QStringLiteral("0"));
+
+ // Reset the colour overrides applied during a populated render so the
+ // zeroed-out P&L labels don't get stuck red/green from the prior state.
+ const QString default_value_css =
+ QString("color: %1; font-size: 13px; font-weight: bold; background: transparent;")
+ .arg(ui::colors::TEXT_PRIMARY());
+ day_pnl_lbl_->setStyleSheet(default_value_css);
+ total_pnl_lbl_->setStyleSheet(default_value_css);
+
+ if (!selected_portfolio_name_.isEmpty()) {
+ portfolio_name_lbl_->setText(selected_portfolio_name_.toUpper());
+ portfolio_name_lbl_->setVisible(true);
+ } else {
+ portfolio_name_lbl_->setVisible(false);
+ }
+}
void PortfolioSummaryWidget::hub_resubscribe(const QVector<Holding>& holdings) {
auto& hub = datahub::DataHub::instance();
@@ -215,8 +334,8 @@ void PortfolioSummaryWidget::rebuild_from_cache() {
render(last_holdings_, quotes);
}
-
-void PortfolioSummaryWidget::render(const QVector<Holding>& holdings, const QVector<services::QuoteData>& quotes) {
+void PortfolioSummaryWidget::render(const QVector<Holding>& holdings,
+ const QVector<services::QuoteData>& quotes) {
last_holdings_ = holdings;
last_quotes_ = quotes;
@@ -249,7 +368,6 @@ void PortfolioSummaryWidget::render(const QVector<Holding>& holdings, const QVec
total_cost += cost;
day_pnl += day_chg;
- // Row
auto* row = new QWidget(this);
row->setStyleSheet(QString("background: %1;").arg(alt ? ui::colors::BG_RAISED() : "transparent"));
auto* rl = new QHBoxLayout(row);
@@ -276,7 +394,6 @@ void PortfolioSummaryWidget::render(const QVector<Holding>& holdings, const QVec
}
list_layout_->addStretch();
- // Update summary labels
total_value_lbl_->setText(QString("$%1").arg(total_value, 0, 'f', 0));
num_holdings_lbl_->setText(QString::number(holdings.size()));
@@ -294,4 +411,44 @@ void PortfolioSummaryWidget::render(const QVector<Holding>& holdings, const QVec
.arg(total_pnl >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
}
+QDialog* PortfolioSummaryWidget::make_config_dialog(QWidget* parent) {
+ auto* dlg = new QDialog(parent);
+ dlg->setWindowTitle(tr("Configure — Portfolio Summary"));
+ auto* form = new QFormLayout(dlg);
+
+ // Ensure the cache reflects the current state of the DB (the Portfolio
+ // tab may have added/renamed entries since the widget was constructed).
+ refresh_portfolio_cache();
+
+ auto* combo = new QComboBox(dlg);
+ if (portfolio_cache_.isEmpty()) {
+ combo->addItem(tr("(no portfolios — create one in the Portfolio tab)"), QString());
+ combo->setEnabled(false);
+ } else {
+ for (const auto& p : portfolio_cache_) {
+ const QString label = p.name + (p.currency.isEmpty() ? QString() : QStringLiteral(" (%1)").arg(p.currency));
+ combo->addItem(label, p.id);
+ if (p.id == selected_portfolio_id_)
+ combo->setCurrentIndex(combo->count() - 1);
+ }
+ }
+ form->addRow(tr("Portfolio"), combo);
+
+ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dlg);
+ form->addRow(buttons);
+
+ connect(buttons, &QDialogButtonBox::accepted, dlg, [this, dlg, combo]() {
+ const QString picked = combo->currentData().toString();
+ if (!picked.isEmpty() && picked != selected_portfolio_id_) {
+ QJsonObject cfg;
+ cfg.insert(kConfigKeyPortfolioId, picked);
+ apply_config(cfg);
+ emit config_changed(cfg);
+ }
+ dlg->accept();
+ });
+ connect(buttons, &QDialogButtonBox::rejected, dlg, &QDialog::reject);
+ return dlg;
+}
+
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h
index 0f982922d..7df0a3628 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h
@@ -1,5 +1,6 @@
#pragma once
#include "screens/dashboard/widgets/BaseWidget.h"
+#include "screens/portfolio/PortfolioTypes.h"
#include "services/markets/MarketDataService.h"
#include <QGridLayout>
@@ -10,13 +11,13 @@
namespace fincept::screens::widgets {
-/// Portfolio Summary Widget — reads holdings from SQLite (portfolio table),
-/// fetches live prices via yfinance, computes P&L and portfolio value.
-/// Falls back to a demo portfolio if no DB holdings are found.
-///
-/// Once `load_holdings()` produces the holdings set the widget subscribes
-/// to `market:quote:<sym>` on the DataHub for each holding. Any change to
-/// the holdings set (e.g., refresh after a DB write) rewires subscriptions.
+/// Portfolio Summary Widget — reads from the v006 multi-portfolio store
+/// (`portfolios` + `portfolio_assets`) shared with the Portfolio screen, so
+/// holdings added/sold in the Portfolio tab show up here automatically. A
+/// gear icon in the title bar lets the user pick which portfolio this tile
+/// displays; the choice is persisted via the dashboard canvas's config
+/// round-trip. Live quotes still come through DataHub `market:quote:<sym>`
+/// subscriptions, one per holding, so P&L updates in real time.
class PortfolioSummaryWidget : public BaseWidget {
Q_OBJECT
public:
@@ -28,45 +29,67 @@ class PortfolioSummaryWidget : public BaseWidget {
double avg_cost = 0;
};
+ // ── BaseWidget config hooks ─────────────────────────────────────────────
+ QJsonObject config() const override;
+ void apply_config(const QJsonObject& cfg) override;
+
protected:
void on_theme_changed() override;
void showEvent(QShowEvent* e) override;
void hideEvent(QHideEvent* e) override;
+ QDialog* make_config_dialog(QWidget* parent) override;
private:
void apply_styles();
- public:
+ /// Resolve which portfolio to display, then load its assets. Picks the
+ /// first available portfolio when `selected_portfolio_id_` is empty or
+ /// no longer exists. Renders the empty-state when zero portfolios.
void load_holdings();
- void fetch_prices(const QVector<Holding>& holdings);
- void render(const QVector<Holding>& holdings, const QVector<services::QuoteData>& quotes);
/// Re-subscribe to `market:quote:<sym>` for every holding. Drops old
/// subscriptions first — holdings set may have changed since last call.
void hub_resubscribe(const QVector<Holding>& holdings);
void hub_unsubscribe_all();
+
/// Rebuild quotes vector from `row_cache_` in `last_holdings_` order
/// and re-render.
void rebuild_from_cache();
- // Summary labels
+ void render(const QVector<Holding>& holdings, const QVector<services::QuoteData>& quotes);
+
+ /// Render the "no portfolios / no holdings" placeholder + zero out the
+ /// summary metric cards. Idempotent.
+ void render_empty(const QString& message);
+
+ /// Pull the current list of portfolios from `PortfolioRepository` and
+ /// cache it for the picker dialog. Cheap (a single SELECT).
+ void refresh_portfolio_cache();
+
+ // ── Selected portfolio ─────────────────────────────────────────────────
+ QString selected_portfolio_id_;
+ QString selected_portfolio_name_;
+ QVector<portfolio::Portfolio> portfolio_cache_;
+
+ // ── Summary labels ──────────────────────────────────────────────────────
QLabel* total_value_lbl_ = nullptr;
QLabel* day_pnl_lbl_ = nullptr;
QLabel* total_pnl_lbl_ = nullptr;
QLabel* num_holdings_lbl_ = nullptr;
- // Holdings list layout
+ // ── Holdings list layout ────────────────────────────────────────────────
QVBoxLayout* list_layout_ = nullptr;
- // Widgets needing theme refresh
+ // ── Theme-tracked widgets ──────────────────────────────────────────────
QWidget* summary_card_ = nullptr;
QWidget* header_row_ = nullptr;
QScrollArea* scroll_area_ = nullptr;
+ QLabel* portfolio_name_lbl_ = nullptr;
QVector<QLabel*> metric_labels_;
QVector<QLabel*> metric_values_;
QVector<QLabel*> header_labels_;
- // Cached for theme-change re-render
+ // ── Cached for theme-change re-render ──────────────────────────────────
QVector<Holding> last_holdings_;
QVector<services::QuoteData> last_quotes_;
diff --git a/fincept-qt/src/trading/AccountDataStream.cpp b/fincept-qt/src/trading/AccountDataStream.cpp
index 4c1e674b2..fff8b72f9 100644
--- a/fincept-qt/src/trading/AccountDataStream.cpp
+++ b/fincept-qt/src/trading/AccountDataStream.cpp
@@ -175,17 +175,21 @@ void AccountDataStream::async_fetch_quote() {
const QString symbol = selected_symbol_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid, symbol]() {
+ // Load credentials on the calling (main) thread. QSqlDatabase is bound
+ // to the thread that opened it; calling SecureStorage::retrieve from a
+ // QtConcurrent worker corrupts SQLite memory and crashes.
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) {
+ quote_fetching_ = false;
+ return;
+ }
+
+ (void)QtConcurrent::run([self, acct_id, bid, symbol, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) {
if (self) self->quote_fetching_ = false;
return;
}
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) {
- if (self) self->quote_fetching_ = false;
- return;
- }
auto result = broker->get_quotes(creds, {symbol});
if (self) self->quote_fetching_ = false;
if (!result.success || !result.data || result.data->isEmpty()) {
@@ -209,11 +213,12 @@ void AccountDataStream::async_fetch_positions() {
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) return;
+
+ (void)QtConcurrent::run([self, acct_id, bid, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) return;
auto result = broker->get_positions(creds);
if (!result.success || !result.data) {
if (result.error.startsWith("[TOKEN_EXPIRED]") && self)
@@ -235,11 +240,12 @@ void AccountDataStream::async_fetch_holdings() {
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) return;
+
+ (void)QtConcurrent::run([self, acct_id, bid, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) return;
auto result = broker->get_holdings(creds);
if (!result.success || !result.data) {
if (result.error.startsWith("[TOKEN_EXPIRED]") && self)
@@ -261,11 +267,12 @@ void AccountDataStream::async_fetch_orders() {
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) return;
+
+ (void)QtConcurrent::run([self, acct_id, bid, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) return;
auto result = broker->get_orders(creds);
if (!result.success || !result.data) {
if (result.error.startsWith("[TOKEN_EXPIRED]") && self)
@@ -287,11 +294,12 @@ void AccountDataStream::async_fetch_funds() {
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) return;
+
+ (void)QtConcurrent::run([self, acct_id, bid, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) return;
auto result = broker->get_funds(creds);
if (!result.success || !result.data) {
if (result.error.startsWith("[TOKEN_EXPIRED]") && self)
@@ -316,11 +324,12 @@ void AccountDataStream::async_fetch_watchlist_quotes() {
const QStringList symbols = watchlist_symbols_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid, symbols]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) return;
+
+ (void)QtConcurrent::run([self, acct_id, bid, symbols, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) return;
auto result = broker->get_quotes(creds, symbols.toVector());
if (!result.success || !result.data) return;
QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {
@@ -341,17 +350,18 @@ void AccountDataStream::fetch_candles(const QString& symbol, const QString& time
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid, symbol, timeframe]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) {
+ candles_fetching_ = false;
+ return;
+ }
+
+ (void)QtConcurrent::run([self, acct_id, bid, symbol, timeframe, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) {
if (self) self->candles_fetching_ = false;
return;
}
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) {
- if (self) self->candles_fetching_ = false;
- return;
- }
// Build date range
const QString to_dt = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm");
QString from_dt;
@@ -389,11 +399,12 @@ void AccountDataStream::fetch_orderbook(const QString& symbol) {
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid, symbol]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) return;
+
+ (void)QtConcurrent::run([self, acct_id, bid, symbol, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) return;
// Try L2 depth from historical quotes
const QString today = QDate::currentDate().toString("yyyy-MM-dd");
@@ -451,11 +462,12 @@ void AccountDataStream::fetch_time_sales(const QString& symbol) {
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid, symbol]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) return;
+
+ (void)QtConcurrent::run([self, acct_id, bid, symbol, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) return;
const QString today = QDate::currentDate().toString("yyyy-MM-dd");
auto result = broker->get_historical_trades_single(creds, symbol, today + "T00:00:00Z", "", 500);
if (!result.success || !result.data) return;
@@ -471,11 +483,12 @@ void AccountDataStream::fetch_latest_trade(const QString& symbol) {
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid, symbol]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+ if (creds.api_key.isEmpty()) return;
+
+ (void)QtConcurrent::run([self, acct_id, bid, symbol, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) return;
auto result = broker->get_latest_trade(creds, symbol);
if (!result.success || !result.data) return;
QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {
@@ -490,10 +503,11 @@ void AccountDataStream::fetch_calendar() {
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+
+ (void)QtConcurrent::run([self, acct_id, bid, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
const QString start = QDate::currentDate().addDays(-5).toString("yyyy-MM-dd");
const QString end = QDate::currentDate().addDays(30).toString("yyyy-MM-dd");
auto result = broker->get_calendar(creds, start, end);
@@ -510,10 +524,11 @@ void AccountDataStream::fetch_clock() {
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
- (void)QtConcurrent::run([self, acct_id, bid]() {
+ auto creds = AccountManager::instance().load_credentials(acct_id);
+
+ (void)QtConcurrent::run([self, acct_id, bid, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
if (!broker) return;
- auto creds = AccountManager::instance().load_credentials(acct_id);
auto result = broker->get_clock(creds);
if (!result.success || !result.data) return;
QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {
diff --git a/fincept-qt/src/ui/navigation/CommandBar.cpp b/fincept-qt/src/ui/navigation/CommandBar.cpp
index 11edc4225..5d292ed07 100644
--- a/fincept-qt/src/ui/navigation/CommandBar.cpp
+++ b/fincept-qt/src/ui/navigation/CommandBar.cpp
@@ -670,8 +670,68 @@ void CommandBar::refresh_theme() {
// ── event filter (keyboard nav in input) ─────────────────────────────────────
bool CommandBar::eventFilter(QObject* obj, QEvent* event) {
- // Navigation keys are handled via KeyConfigManager QActions (connected in setup_key_actions)
- return QWidget::eventFilter(obj, event);
+ // The Nav* QActions in KeyConfigManager (Up/Down/Tab/Esc) are created with
+ // Qt::ApplicationShortcut context but never addAction()-ed to any widget
+ // (WindowFrame's loop skips them because action_id_for(NavNext)=="").
+ // So Qt's shortcut machinery never fires them. We intercept the keys
+ // here instead, by raw key code — that's portable across Qt versions
+ // / platforms and dodges the QKeySequence-equality quirks where the
+ // bound sequence is constructed differently than `key|modifiers`.
+
+ // QLineEdit also receives QEvent::ShortcutOverride for some keys before
+ // KeyPress; accepting it ensures KeyPress is delivered to us instead of
+ // being routed to the shortcut machinery. (Tab in particular hits
+ // QWidget::focusNextPrevChild via QEvent::KeyPress; consuming it in
+ // KeyPress is enough.)
+ if (obj != input_)
+ return QWidget::eventFilter(obj, event);
+
+ if (event->type() != QEvent::KeyPress && event->type() != QEvent::ShortcutOverride)
+ return QWidget::eventFilter(obj, event);
+
+ auto* ke = static_cast<QKeyEvent*>(event);
+ const int key = ke->key();
+ const Qt::KeyboardModifiers mods = ke->modifiers() & ~Qt::KeypadModifier;
+
+ // Map raw key to the corresponding nav handler. We only handle the
+ // default bindings here; user rebindings via Settings → Keybindings
+ // currently can't fire either (same orphan-QAction issue), so the
+ // default bindings are the de-facto contract.
+ const bool is_down = (key == Qt::Key_Down) && mods == Qt::NoModifier;
+ const bool is_up = (key == Qt::Key_Up) && mods == Qt::NoModifier;
+ const bool is_tab = (key == Qt::Key_Tab) && mods == Qt::NoModifier;
+ const bool is_btab = (key == Qt::Key_Backtab); // Shift+Tab arrives as Backtab
+ const bool is_esc = (key == Qt::Key_Escape) && mods == Qt::NoModifier;
+
+ if (!is_down && !is_up && !is_tab && !is_btab && !is_esc)
+ return QWidget::eventFilter(obj, event);
+
+ // Escape works even when dropdown is hidden (it clears + drops focus).
+ // The others only meaningfully act on a visible dropdown.
+ const bool dropdown_visible = dropdown_ && dropdown_->isVisible();
+ if (!dropdown_visible && !is_esc)
+ return QWidget::eventFilter(obj, event);
+
+ // For ShortcutOverride: accept it so the event is routed back to us as
+ // KeyPress instead of being claimed by any global shortcut. Don't run
+ // the actual handler here — that's KeyPress's job.
+ if (event->type() == QEvent::ShortcutOverride) {
+ event->accept();
+ return true;
+ }
+
+ auto trigger = [](KeyAction a) {
+ if (auto* act = KeyConfigManager::instance().action(a))
+ act->trigger();
+ };
+
+ if (is_down) trigger(KeyAction::NavNext);
+ else if (is_up) trigger(KeyAction::NavPrev);
+ else if (is_btab) trigger(KeyAction::NavPrev);
+ else if (is_tab) trigger(KeyAction::NavAccept);
+ else if (is_esc) trigger(KeyAction::NavEscape);
+
+ return true; // consume — keep Tab from walking focus, etc.
}
// ── slots ────────────────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/ui/theme/ThemeManager.cpp b/fincept-qt/src/ui/theme/ThemeManager.cpp
index df6137620..11ea99571 100644
--- a/fincept-qt/src/ui/theme/ThemeManager.cpp
+++ b/fincept-qt/src/ui/theme/ThemeManager.cpp
@@ -3,6 +3,7 @@
#include "core/logging/Logger.h"
#include <QApplication>
+#include <QFontInfo>
#include <QWidget>
namespace fincept::ui {
@@ -48,13 +49,77 @@ ThemeManager& ThemeManager::instance() {
return inst;
}
+QString ThemeManager::qss_font_family_list() const {
+ QStringList parts;
+ parts.reserve(font_families_.size());
+ for (const QString& f : font_families_) {
+ // CSS spec: generic families (monospace, serif, sans-serif) are
+ // unquoted; named families get double-quoted to survive families
+ // with spaces ("SF Mono", "Cascadia Mono").
+ if (f.compare("monospace", Qt::CaseInsensitive) == 0 ||
+ f.compare("serif", Qt::CaseInsensitive) == 0 ||
+ f.compare("sans-serif", Qt::CaseInsensitive) == 0) {
+ parts.append(f.toLower());
+ } else {
+ parts.append(QStringLiteral("\"%1\"").arg(f));
+ }
+ }
+ return parts.join(QStringLiteral(", "));
+}
+
+QStringList ThemeManager::build_font_chain(const QString& preferred) {
+ // Cross-platform monospace fallback cascade. Qt's font matcher walks
+ // this list and picks the first family installed on the running
+ // system. The macOS entries (SF Mono / Menlo / Monaco) come first
+ // because that's where the original "Consolas only" default broke —
+ // macOS doesn't ship Consolas, the silent fallback was a proportional
+ // system font, and QLineEdit/QTextEdit rendered with mismatched
+ // glyph metrics (the visible "fragmented" text symptom).
+ static const QStringList kDefaults = {
+ QStringLiteral("SF Mono"), // macOS Mojave+ (system monospace)
+ QStringLiteral("Menlo"), // macOS standard
+ QStringLiteral("Monaco"), // macOS classic
+ QStringLiteral("Cascadia Mono"), // Windows 11 + Terminal
+ QStringLiteral("Cascadia Code"), // Windows 11
+ QStringLiteral("Consolas"), // Windows
+ QStringLiteral("DejaVu Sans Mono"), // Linux (Debian/Ubuntu)
+ QStringLiteral("Liberation Mono"), // Linux (Fedora/RHEL)
+ QStringLiteral("Source Code Pro"), // Adobe — common 3rd-party
+ QStringLiteral("Courier New"), // universal but ugly last resort
+ QStringLiteral("monospace"), // Qt generic family
+ };
+ QStringList chain;
+ const QString trimmed = preferred.trimmed();
+ if (!trimmed.isEmpty()) {
+ // Allow the caller to pass a CSS-style list like
+ // "'Consolas','Courier New',monospace" without breaking the
+ // single-string font matcher — split, strip quotes, dedup.
+ const auto parts = trimmed.split(',', Qt::SkipEmptyParts);
+ for (const QString& raw : parts) {
+ QString name = raw.trimmed();
+ if (name.startsWith('\'') || name.startsWith('"'))
+ name = name.mid(1);
+ if (name.endsWith('\'') || name.endsWith('"'))
+ name.chop(1);
+ name = name.trimmed();
+ if (!name.isEmpty() && !chain.contains(name, Qt::CaseInsensitive))
+ chain.append(name);
+ }
+ }
+ for (const QString& f : kDefaults) {
+ if (!chain.contains(f, Qt::CaseInsensitive))
+ chain.append(f);
+ }
+ return chain;
+}
+
void ThemeManager::apply_theme(const QString& /*name*/) {
current_ = THEME_OBSIDIAN;
rebuild_and_apply();
}
void ThemeManager::apply_font(const QString& family, int size_px) {
- font_family_ = family;
+ font_families_ = build_font_chain(family);
font_size_px_ = (size_px > 0) ? size_px : 14;
rebuild_and_apply();
}
@@ -73,7 +138,7 @@ void ThemeManager::apply_density(const QString& density) {
void ThemeManager::apply_typography_and_density(const QString& family, int size_px,
const QString& density) {
if (!family.isEmpty())
- font_family_ = family;
+ font_families_ = build_font_chain(family);
font_size_px_ = (size_px > 0) ? size_px : 14;
if (density == "Compact")
density_pad_ = 2;
@@ -93,20 +158,36 @@ QStringList ThemeManager::available_densities() {
}
QFont ThemeManager::current_font() const {
- QFont f(font_family_);
+ QFont f;
+ // setFamilies (Qt 5.13+) accepts an explicit fallback list — Qt walks
+ // it natively and picks the first available family. This is the right
+ // primitive on macOS where the legacy single-string ctor with a
+ // missing primary (e.g. "Consolas") silently resolved to a proportional
+ // system font.
+ f.setFamilies(font_families_);
+ f.setStyleHint(QFont::Monospace);
+ f.setStyleStrategy(QFont::PreferAntialias);
f.setPixelSize(font_size_px_);
return f;
}
void ThemeManager::rebuild_and_apply() {
- LOG_INFO("ThemeManager", QString("rebuild_and_apply: font=%1 size=%2px density_pad=%3")
- .arg(font_family_).arg(font_size_px_).arg(density_pad_));
+ LOG_INFO("ThemeManager", QString("rebuild_and_apply: families=[%1] size=%2px density_pad=%3")
+ .arg(font_families_.join(", ")).arg(font_size_px_).arg(density_pad_));
- QFont f(font_family_);
+ QFont f;
+ f.setFamilies(font_families_);
f.setStyleHint(QFont::Monospace);
+ // PreferAntialias forces grayscale AA over subpixel, which on macOS
+ // dark themes is noticeably cleaner — subpixel AA on dark backgrounds
+ // produces coloured fringes around glyphs that look "fragmented" on
+ // small text sizes. Cross-platform safe (Windows/Linux ignore where
+ // the system chooses the AA strategy itself).
+ f.setStyleStrategy(QFont::PreferAntialias);
f.setPixelSize(font_size_px_);
if (qApp->font() != f) {
- LOG_INFO("ThemeManager", "Applying new QFont to qApp");
+ LOG_INFO("ThemeManager", QString("Applying new QFont to qApp (resolved family: %1)")
+ .arg(QFontInfo(f).family()));
qApp->setFont(f);
}
@@ -441,7 +522,7 @@ QString ThemeManager::build_global_qss() const {
.arg(t.bg_raised) // %12
.arg(t.text_dim) // %13
.arg(t.row_alt) // %14
- .arg(font_family_) // %15
+ .arg(qss_font_family_list()) // %15
.arg(font_size_px_) // %16
.arg(t.text_on_accent) // %17
.arg(t.icon_dim) // %18
diff --git a/fincept-qt/src/ui/theme/ThemeManager.h b/fincept-qt/src/ui/theme/ThemeManager.h
index bf0d01e18..fa991ab83 100644
--- a/fincept-qt/src/ui/theme/ThemeManager.h
+++ b/fincept-qt/src/ui/theme/ThemeManager.h
@@ -4,6 +4,7 @@
#include <QFont>
#include <QObject>
#include <QString>
+#include <QStringList>
namespace fincept::ui {
@@ -66,8 +67,25 @@ class ThemeManager : public QObject {
void rebuild_and_apply();
QString build_global_qss() const;
+ /// Build a platform-aware monospace fallback chain by prepending the
+ /// user's preferred family (if any) to a cross-platform default list.
+ /// Qt's QFont::setFamilies / QSS resolver picks the first available
+ /// font on the running system. Including the macOS natives (SF Mono,
+ /// Menlo) is what stops text fields from "fragmenting" — on macOS,
+ /// Consolas isn't installed and the silent fallback to a proportional
+ /// system font breaks the glyph metrics QLineEdit/QTextEdit assume.
+ static QStringList build_font_chain(const QString& preferred);
+
+ /// Format `font_families_` as a CSS `font-family` value
+ /// (`"Family1", "Family2", monospace`) for the global QSS output. Qt's
+ /// CSS resolver walks the same way QFont::setFamilies does.
+ QString qss_font_family_list() const;
+
ThemeTokens current_;
- QString font_family_ = "Consolas";
+ /// Resolved font fallback chain. `font_families_.first()` is the user's
+ /// preferred family (or the cross-platform default head); subsequent
+ /// entries are the fallback cascade.
+ QStringList font_families_ = build_font_chain({});
int font_size_px_ = 14;
int density_pad_ = 4; // px padding driven by density setting
mutable QString cached_qss_; // last built QSS — skip rebuild if tokens unchanged
diff --git a/fincept-qt/src/ui/widgets/LoadingOverlay.cpp b/fincept-qt/src/ui/widgets/LoadingOverlay.cpp
index e9864605a..8c8d519d9 100644
--- a/fincept-qt/src/ui/widgets/LoadingOverlay.cpp
+++ b/fincept-qt/src/ui/widgets/LoadingOverlay.cpp
@@ -89,7 +89,17 @@ void LoadingOverlay::paintEvent(QPaintEvent*) {
QColor text_color = accent_color;
text_color.setAlpha(200);
p.setPen(text_color);
- p.setFont(QFont(tokens_.font_family, 10, QFont::Bold));
+ // Use the app's resolved font (ThemeManager owns the proper
+ // cross-platform fallback chain). QFont(const QString&, …) takes
+ // a single family and fails silently for the CSS-style list
+ // stored in tokens_.font_family — on macOS that fell back to a
+ // proportional system font, which is the "fragmented" look the
+ // user reported. current_font() returns a QFont built via
+ // setFamilies() so Qt resolves the first available monospace.
+ QFont f = ThemeManager::instance().current_font();
+ f.setPixelSize(10);
+ f.setBold(true);
+ p.setFont(f);
QRect text_rect(0, base_y + 14, width(), 24);
p.drawText(text_rect, Qt::AlignHCenter | Qt::AlignTop, message_);
}