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.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
v4 update: agent config, backtesting, forum, code editor, economics panels
tilakpatel22b09f88e9e7fe
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex e3adb1b98..15c8348cb 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -400,6 +400,9 @@ set(SCREEN_SOURCESsrc/screens/news/NewsTickerStrip.cppsrc/screens/forum/ForumScreen.cppsrc/screens/forum/ForumFeedPanel.cpp+ src/screens/forum/ForumSidebarPanel.cpp+ src/screens/forum/ForumPostListPanel.cpp+ src/screens/forum/ForumPostReaderPanel.cppsrc/screens/forum/ForumThreadPanel.cppsrc/services/forum/ForumService.cppsrc/screens/crypto_trading/CryptoTradingScreen.cppdiff --git a/fincept-qt/docs/backtesting-provider-process.md b/fincept-qt/docs/backtesting-provider-process.mdnew file mode 100644index 000000000..8a9572bca--- /dev/null+++ b/fincept-qt/docs/backtesting-provider-process.md@@ -0,0 +1,71 @@+# Backtesting Provider Integration Process++Follow this checklist **exactly** for each provider, in order.++## Provider Order+1. ~~BT~~ ✅+2. ~~VectorBT~~ ✅+3. ~~Backtesting.py~~ ✅+4. ~~FastTrade~~ ✅+5. ~~Zipline~~ ✅+6. ~~Fincept~~ ✅++> **Architecture note (applied after providers 1-3):**+> Python is now the single source of truth. `default_strategies()` and `all_indicators()` return `{}`.+> On provider switch, C++ calls `load_strategies()`, `get_indicators`, and `load_command_options()`.+> All combos are populated dynamically. `strategies_from_json()` handles BT and VectorBT shapes.++---++## Step-by-Step Process++### STEP 1 — Audit Python files+- Read all `*_provider.py` + any sibling strategy/indicator files+- List every exposed command (what CLI commands the provider handles)+- List every strategy ID + category + parameters (name, type, options if select)+- List every indicator ID + parameters+- Note any missing library coverage (compare against library docs/pip)++### STEP 2 — Expand Python coverage+- If library has meaningful algos not yet registered, add them+- New strategy files follow pattern: `{provider}_{topic}.py`+- Import new files in `{provider}_provider.py` and `__init__.py`+- Fix any import/path collisions (use aliased imports if needed)+- Test: `python {provider}_provider.py get_strategies '{}'` must return valid JSON++### STEP 3 — Cross-check C++ vs Python (BacktestingTypes.h)+Verify these 5 things strictly:++| Check | What to verify |+|-------|---------------|+| Commands | Provider's command list in `all_providers()` matches what Python actually handles |+| Strategy IDs | Every ID in `default_strategies()` fallback matches a real Python strategy ID |+| Strategy categories | `strategy_categories()` contains all Python categories (exact case/spelling) |+| Indicator IDs | Every ID in `all_indicators()` fallback matches Python INDICATOR_CATALOG |+| Param names | Param `name` fields in C++ structs match exact keys Python reads from JSON |++### STEP 4 — Fix all mismatches+- Fix IDs, categories, param names in `BacktestingTypes.h`+- Remove C++ strategies/indicators with no Python equivalent+- Add C++ fallback entries for Python strategies missing from fallback+- Keep `default_strategies()` as an accurate subset (not exhaustive — dynamic load handles the rest)++### STEP 5 — Check for dead code+- Grep every `inline` function in `BacktestingTypes.h` — confirm each is called in `BacktestingScreen.cpp`+- Remove any that are not referenced anywhere++### STEP 6 — Build & verify+- Build: `cmake --build build --config Debug`+- Zero new errors (pre-existing warnings are acceptable)+- Launch app, navigate to Backtesting tab, select the provider+- Confirm strategy list loads dynamically from Python (not just fallback)+- Confirm indicators load correctly+- Run one backtest end-to-end++---++## Rules+- Never change `all_providers()` command lists without verifying Python handles them+- Category strings must match Python exactly (camelCase where Python uses camelCase)+- Fallback lists exist for offline/error state — keep them accurate but minimal+- One provider at a time — complete all 6 steps before moving to nextdiff --git a/fincept-qt/scripts/Analytics/backtesting/backtestingpy/backtestingpy_provider.py b/fincept-qt/scripts/Analytics/backtesting/backtestingpy/backtestingpy_provider.pyindex e287dcf8f..37d060a8f 100644--- a/fincept-qt/scripts/Analytics/backtesting/backtestingpy/backtestingpy_provider.py+++ b/fincept-qt/scripts/Analytics/backtesting/backtestingpy/backtestingpy_provider.py@@ -526,6 +526,44 @@ class BacktestingPyProvider(BacktestingProviderBase):self._error('Failed to calculate indicator', e)return self._create_error_result(f'Indicator calculation failed: {str(e)}')+ def get_strategies(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return strategy catalog in BT shape: {strategies: {category: [...]}}."""+ import btp_strategies as _strat+ catalog = _strat.get_strategy_catalog()+ return {'success': True, 'data': {'provider': 'backtestingpy', 'strategies': catalog}}++ def get_indicators(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return indicator catalog normalized to {indicators: {Category: [{id, name}]}}."""+ try:+ import btp_indicators as _ind+ flat = _ind.get_catalog()+ grouped: Dict[str, Any] = {}+ for entry in flat:+ cat = entry.get('category', 'Other')+ grouped.setdefault(cat, []).append({+ 'id': entry.get('id', ''),+ 'name': entry.get('label', entry.get('id', '')),+ })+ except Exception:+ grouped = {}+ return {'indicators': grouped}++ def get_command_options(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return provider-specific option lists for all command dropdowns."""+ return {+ 'success': True,+ 'data': {+ 'position_sizing_methods': ['percent', 'fixed', 'kelly'],+ 'optimize_objectives': ['sharpe', 'sortino', 'calmar', 'return'],+ 'optimize_methods': ['grid', 'random'],+ 'label_types': [],+ 'splitter_types': [],+ 'signal_generators': [],+ 'indicator_signal_modes': ['crossover', 'threshold', 'breakout', 'mean_reversion', 'filter'],+ 'returns_analysis_types': [],+ },+ }+# ========================================================================# Helper Methods# ========================================================================@@ -1563,6 +1601,12 @@ def main():result = provider.calculate_indicator(indicator_type, params)elif command == 'optimize':result = provider.optimize(args)+ elif command == 'get_strategies':+ result = provider.get_strategies(args)+ elif command == 'get_indicators':+ result = provider.get_indicators(args)+ elif command == 'get_command_options':+ result = provider.get_command_options(args)elif command == 'disconnect':provider.disconnect()result = {'success': True, 'message': 'Disconnected'}diff --git a/fincept-qt/scripts/Analytics/backtesting/bt/bt_fixed_income.py b/fincept-qt/scripts/Analytics/backtesting/bt/bt_fixed_income.pynew file mode 100644index 000000000..a956de36e--- /dev/null+++ b/fincept-qt/scripts/Analytics/backtesting/bt/bt_fixed_income.py@@ -0,0 +1,252 @@+"""+BT Fixed Income Strategies++Covers bt's fixed-income asset types and related algos:+- FixedIncomeSecurity — basic bond / fixed-income security+- CouponPayingSecurity — bond with periodic coupon payments+- HedgeSecurity — security used purely as a hedge overlay+- CouponPayingHedgeSecurity — coupon-paying hedge security+- FixedIncomeStrategy — strategy subclass for bond portfolios+- ResolveOnTheRun — roll to on-the-run bond each period+- RollPositionsAfterDates — roll positions after specified settlement dates+- ClosePositionsAfterDates — close positions on / after specific dates++All builders follow the same pattern used in bt_strategies.py and bt_risk.py:+ builder(params) -> build(data, name=...) -> bt.Strategy | None+"""++import sys+from pathlib import Path+from typing import Dict, Any, List++_SCRIPT_DIR = Path(__file__).parent+_BACKTESTING_DIR = _SCRIPT_DIR.parent+for _p in [str(_BACKTESTING_DIR), str(_SCRIPT_DIR)]:+ if _p not in sys.path:+ sys.path.insert(0, _p)++from bt_strategies import _STRATEGY_REGISTRY, _register, _rebalance_algo, _BT_AVAILABLE, _bt+++# ============================================================================+# Helpers+# ============================================================================++def _make_fi_strategy(name: str, algos: list, security_type='fixed_income'):+ """Wrap algos in a FixedIncomeStrategy if available, else plain Strategy."""+ if not _BT_AVAILABLE:+ return None+ try:+ return _bt.FixedIncomeStrategy(name, algos)+ except AttributeError:+ return _bt.Strategy(name, algos)+++# ============================================================================+# Basic Fixed-Income Equal-Weight+# ============================================================================++@_register('fi_equal_weight', 'fixedIncome', 'Fixed Income Equal Weight',+ 'Equal-weight bond portfolio using FixedIncomeStrategy',+ [{'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_fi_equal_weight(params):+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='fi_equal_weight'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.Rebalance(),+ ]+ return _make_fi_strategy(name, algos)+ return None+ return build+++# ============================================================================+# Resolve On-the-Run+# ============================================================================++@_register('fi_on_the_run', 'fixedIncome', 'On-the-Run Roll',+ 'Automatically roll to the most recently issued (on-the-run) bond each period',+ [{'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_fi_on_the_run(params):+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='fi_on_the_run'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.ResolveOnTheRun(),+ _bt.algos.WeighEqually(),+ _bt.algos.Rebalance(),+ ]+ return _make_fi_strategy(name, algos)+ return None+ return build+++# ============================================================================+# Roll Positions After Dates+# ============================================================================++@_register('fi_roll_after_dates', 'fixedIncome', 'Roll Positions After Dates',+ 'Roll bond positions after specified settlement / maturity dates',+ [{'name': 'dates', 'label': 'Roll dates (comma-separated YYYY-MM-DD)', 'default': ''},+ {'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_fi_roll_after_dates(params):+ import pandas as pd+ raw = params.get('dates', '')+ dates = [d.strip() for d in raw.split(',') if d.strip()]+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='fi_roll_after_dates'):+ if _BT_AVAILABLE and dates:+ parsed = pd.to_datetime(dates)+ algos = [+ _rebalance_algo(period),+ _bt.algos.RollPositionsAfterDates(dates=parsed),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.Rebalance(),+ ]+ return _make_fi_strategy(name, algos)+ return None+ return build+++# ============================================================================+# Close Positions After Dates+# ============================================================================++@_register('fi_close_after_dates', 'fixedIncome', 'Close Positions After Dates',+ 'Liquidate bond positions on or after specified maturity / expiry dates',+ [{'name': 'dates', 'label': 'Close dates (comma-separated YYYY-MM-DD)', 'default': ''},+ {'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_fi_close_after_dates(params):+ import pandas as pd+ raw = params.get('dates', '')+ dates = [d.strip() for d in raw.split(',') if d.strip()]+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='fi_close_after_dates'):+ if _BT_AVAILABLE and dates:+ parsed = pd.to_datetime(dates)+ algos = [+ _rebalance_algo(period),+ _bt.algos.ClosePositionsAfterDates(dates=parsed),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.Rebalance(),+ ]+ return _make_fi_strategy(name, algos)+ return None+ return build+++# ============================================================================+# Coupon-Paying Bond Strategy+# ============================================================================++@_register('fi_coupon_bond', 'fixedIncome', 'Coupon-Paying Bond Portfolio',+ 'Portfolio of coupon-paying bonds with automatic income reinvestment',+ [{'name': 'couponFreq', 'label': 'Coupon frequency', 'default': 'quarterly',+ 'options': ['monthly', 'quarterly', 'yearly']},+ {'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'quarterly',+ 'options': ['monthly', 'quarterly', 'yearly']}])+def _build_fi_coupon_bond(params):+ period = params.get('rebalancePeriod', 'quarterly')++ def build(data, name='fi_coupon_bond'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.Rebalance(),+ ]+ # Use FixedIncomeStrategy which handles coupon accrual+ return _make_fi_strategy(name, algos, security_type='coupon')+ return None+ return build+++# ============================================================================+# Hedge Overlay (HedgeSecurity-based)+# ============================================================================++@_register('fi_hedge_overlay', 'fixedIncome', 'Bond + Hedge Overlay',+ 'Hold a bond portfolio with a separate hedge security overlay',+ [{'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_fi_hedge_overlay(params):+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='fi_hedge_overlay'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.UpdateRisk(),+ _bt.algos.HedgeRisks(),+ _bt.algos.Rebalance(),+ ]+ return _make_fi_strategy(name, algos)+ return None+ return build+++# ============================================================================+# Duration-Weighted Bond Portfolio+# ============================================================================++@_register('fi_inv_duration', 'fixedIncome', 'Inverse-Duration Weighted Bonds',+ 'Weight bonds inversely by duration (shorter duration = larger weight)',+ [{'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_fi_inv_duration(params):+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='fi_inv_duration'):+ if _BT_AVAILABLE:+ # Proxy duration weighting via inverse volatility (vol ~ duration sensitivity)+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighInvVol(lookback=60),+ _bt.algos.Rebalance(),+ ]+ return _make_fi_strategy(name, algos)+ return None+ return build+++# ============================================================================+# SimulateRFQTransactions — OTC / bond RFQ execution simulation+# ============================================================================++@_register('fi_rfq_simulation', 'fixedIncome', 'OTC RFQ Transaction Simulation',+ 'Simulate OTC bond / derivatives execution via Request-For-Quote (RFQ) model',+ [{'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_fi_rfq_simulation(params):+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='fi_rfq_simulation'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.SimulateRFQTransactions(),+ ]+ return _make_fi_strategy(name, algos)+ return None+ return builddiff --git a/fincept-qt/scripts/Analytics/backtesting/bt/bt_provider.py b/fincept-qt/scripts/Analytics/backtesting/bt/bt_provider.pyindex dde693b50..d453b2219 100644--- a/fincept-qt/scripts/Analytics/backtesting/bt/bt_provider.py+++ b/fincept-qt/scripts/Analytics/backtesting/bt/bt_provider.py@@ -1127,13 +1127,26 @@ class BtProvider(BacktestingProviderBase):}def get_indicators(self, request: Dict[str, Any]) -> Dict[str, Any]:- """Return indicator catalog."""+ """Return indicator catalog normalized to {indicators: {Category: [{id, name}]}}."""from bt_strategies import INDICATOR_CATALOG+ grouped = {}+ for cat, items in INDICATOR_CATALOG.items():+ grouped[cat] = [{'id': it['id'], 'name': it.get('name', it['id'])} for it in items]+ return {'indicators': grouped}++ def get_command_options(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return provider-specific option lists for all command dropdowns."""return {'success': True,'data': {- 'provider': 'bt',- 'indicators': INDICATOR_CATALOG,+ 'position_sizing_methods': ['percent', 'fixed', 'kelly', 'vol_target', 'risk'],+ 'optimize_objectives': ['sharpe', 'sortino', 'calmar', 'return'],+ 'optimize_methods': ['grid', 'random'],+ 'label_types': ['FIXLB', 'MEANLB', 'LEXLB', 'TRENDLB', 'BOLB'],+ 'splitter_types': ['RollingSplitter', 'ExpandingSplitter', 'PurgedKFold'],+ 'signal_generators': ['RAND', 'RANDX', 'RANDNX', 'RPROB', 'RPROBX'],+ 'indicator_signal_modes': ['crossover', 'threshold', 'breakout', 'mean_reversion', 'filter'],+ 'returns_analysis_types': ['cumulative', 'rolling', 'drawdown', 'distribution', 'benchmark_comparison'],},}@@ -1306,6 +1319,9 @@ def main():elif command == 'get_indicators':result = provider.get_indicators(args)result_str = json_response(result)+ elif command == 'get_command_options':+ result = provider.get_command_options(args)+ result_str = json_response(result)elif command == 'get_historical_data':result = provider.get_historical_data(args)result_str = json_response({'success': True, 'data': result})diff --git a/fincept-qt/scripts/Analytics/backtesting/bt/bt_risk.py b/fincept-qt/scripts/Analytics/backtesting/bt/bt_risk.pynew file mode 100644index 000000000..1b0849c64--- /dev/null+++ b/fincept-qt/scripts/Analytics/backtesting/bt/bt_risk.py@@ -0,0 +1,298 @@+"""+BT Risk & Constraint Algos++Strategies and helpers that use bt's risk management algo blocks:+- TargetVol — scale portfolio to hit a target annualised volatility+- LimitWeights — cap any single asset weight+- LimitDeltas — cap turnover / weight change per rebalance+- PTE_Rebalance — rebalance when tracking error exceeds threshold+- CapitalFlow — inject / withdraw capital on a schedule+- SetNotional — fix portfolio notional value+- UpdateRisk — compute per-asset risk metrics+- HedgeRisks — hedge residual portfolio risk+- Margin — apply margin / leverage constraints++All builders follow the same pattern as bt_strategies.py:+ builder(params) -> build(data, name=...) -> bt.Strategy | None+"""++import sys+from pathlib import Path+from typing import Dict, Any++_SCRIPT_DIR = Path(__file__).parent+_BACKTESTING_DIR = _SCRIPT_DIR.parent+for _p in [str(_BACKTESTING_DIR), str(_SCRIPT_DIR)]:+ if _p not in sys.path:+ sys.path.insert(0, _p)++from bt_strategies import _STRATEGY_REGISTRY, _register, _rebalance_algo, _BT_AVAILABLE, _bt+++# ============================================================================+# TargetVol — scale to annualised volatility target+# ============================================================================++@_register('risk_target_vol', 'risk', 'Target Volatility',+ 'Scale portfolio weights so realised vol matches a target',+ [{'name': 'targetVol', 'label': 'Target Ann. Vol (%)', 'default': 10,+ 'min': 1, 'max': 50},+ {'name': 'lookback', 'label': 'Vol Lookback (days)', 'default': 60},+ {'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_risk_target_vol(params):+ target = float(params.get('targetVol', 10)) / 100.0+ lookback = int(params.get('lookback', 60))+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='risk_target_vol'):+ if _BT_AVAILABLE:+ import pandas as pd+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.TargetVol(+ target=target,+ lookback=pd.DateOffset(days=lookback),+ annualization_factor=252,+ ),+ _bt.algos.Rebalance(),+ ]+ return _bt.Strategy(name, algos)+ return None+ return build+++# ============================================================================+# LimitWeights — cap maximum single-asset weight+# ============================================================================++@_register('risk_limit_weights', 'risk', 'Limit Max Weight',+ 'Cap each asset weight at a maximum fraction',+ [{'name': 'maxWeight', 'label': 'Max Weight (fraction)', 'default': 0.2,+ 'min': 0.01, 'max': 1.0},+ {'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_risk_limit_weights(params):+ max_w = float(params.get('maxWeight', 0.2))+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='risk_limit_weights'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.LimitWeights(limit=max_w),+ _bt.algos.Rebalance(),+ ]+ return _bt.Strategy(name, algos)+ return None+ return build+++# ============================================================================+# LimitDeltas — cap turnover per rebalance+# ============================================================================++@_register('risk_limit_deltas', 'risk', 'Limit Weight Changes (Turnover Control)',+ 'Restrict how much any weight can change in a single rebalance',+ [{'name': 'maxDelta', 'label': 'Max Weight Delta', 'default': 0.1,+ 'min': 0.01, 'max': 1.0},+ {'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_risk_limit_deltas(params):+ max_d = float(params.get('maxDelta', 0.1))+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='risk_limit_deltas'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.LimitDeltas(limit=max_d),+ _bt.algos.Rebalance(),+ ]+ return _bt.Strategy(name, algos)+ return None+ return build+++# ============================================================================+# PTE_Rebalance — rebalance when tracking error threshold is breached+# ============================================================================++@_register('risk_pte_rebalance', 'risk', 'PTE Tracking-Error Rebalance',+ 'Trigger rebalance only when portfolio tracking error exceeds threshold',+ [{'name': 'pteThreshold', 'label': 'PTE Threshold', 'default': 0.02,+ 'min': 0.001, 'max': 0.5},+ {'name': 'lookback', 'label': 'Lookback (days)', 'default': 60}])+def _build_risk_pte_rebalance(params):+ pte = float(params.get('pteThreshold', 0.02))+ lookback = int(params.get('lookback', 60))++ def build(data, name='risk_pte_rebalance'):+ if _BT_AVAILABLE:+ import pandas as pd+ algos = [+ _bt.algos.PTE_Rebalance(+ PTE_volatility_target=pte,+ lookback=pd.DateOffset(days=lookback),+ ),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.Rebalance(),+ ]+ return _bt.Strategy(name, algos)+ return None+ return build+++# ============================================================================+# CapitalFlow — inject / withdraw capital on a schedule+# ============================================================================++@_register('risk_capital_flow', 'risk', 'Scheduled Capital Flow',+ 'Inject or withdraw a fixed cash amount each period',+ [{'name': 'amount', 'label': 'Flow amount (positive=inject)', 'default': 0.0},+ {'name': 'rebalancePeriod', 'label': 'Flow Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_risk_capital_flow(params):+ amount = float(params.get('amount', 0.0))+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='risk_capital_flow'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.CapitalFlow(amount),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.Rebalance(),+ ]+ return _bt.Strategy(name, algos)+ return None+ return build+++# ============================================================================+# SetNotional — fix notional portfolio value+# ============================================================================++@_register('risk_set_notional', 'risk', 'Fixed Notional Value',+ 'Pin portfolio notional to a fixed dollar amount each rebalance',+ [{'name': 'notional', 'label': 'Notional ($)', 'default': 100000.0, 'min': 1.0},+ {'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_risk_set_notional(params):+ notional = float(params.get('notional', 100000.0))+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='risk_set_notional'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.SetNotional(notional_value=notional),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.Rebalance(),+ ]+ return _bt.Strategy(name, algos)+ return None+ return build+++# ============================================================================+# Combined: TargetVol + LimitWeights (common real-world combo)+# ============================================================================++@_register('risk_vol_capped', 'risk', 'Target Vol + Weight Cap',+ 'Target volatility with per-asset weight ceiling',+ [{'name': 'targetVol', 'label': 'Target Ann. Vol (%)', 'default': 10,+ 'min': 1, 'max': 50},+ {'name': 'maxWeight', 'label': 'Max Weight', 'default': 0.25,+ 'min': 0.05, 'max': 1.0},+ {'name': 'lookback', 'label': 'Vol Lookback (days)', 'default': 60},+ {'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_risk_vol_capped(params):+ target = float(params.get('targetVol', 10)) / 100.0+ max_w = float(params.get('maxWeight', 0.25))+ lookback = int(params.get('lookback', 60))+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='risk_vol_capped'):+ if _BT_AVAILABLE:+ import pandas as pd+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighInvVol(lookback=lookback),+ _bt.algos.LimitWeights(limit=max_w),+ _bt.algos.TargetVol(+ target=target,+ lookback=pd.DateOffset(days=lookback),+ annualization_factor=252,+ ),+ _bt.algos.Rebalance(),+ ]+ return _bt.Strategy(name, algos)+ return None+ return build+++# ============================================================================+# UpdateRisk + HedgeRisks — risk attribution and hedging pipeline+# ============================================================================++@_register('risk_hedge', 'risk', 'Risk Attribution + Hedge',+ 'Compute per-asset risk metrics then hedge residual portfolio risk',+ [{'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_risk_hedge(params):+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='risk_hedge'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.UpdateRisk(),+ _bt.algos.HedgeRisks(),+ _bt.algos.Rebalance(),+ ]+ return _bt.Strategy(name, algos)+ return None+ return build+++# ============================================================================+# Margin / Leverage+# ============================================================================++@_register('risk_margin', 'risk', 'Leveraged Portfolio',+ 'Apply margin/leverage to an equal-weight strategy',+ [{'name': 'leverage', 'label': 'Leverage (1=no leverage)', 'default': 1.0,+ 'min': 1.0, 'max': 5.0},+ {'name': 'rebalancePeriod', 'label': 'Rebalance Period', 'default': 'monthly',+ 'options': ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']}])+def _build_risk_margin(params):+ leverage = float(params.get('leverage', 1.0))+ period = params.get('rebalancePeriod', 'monthly')++ def build(data, name='risk_margin'):+ if _BT_AVAILABLE:+ algos = [+ _rebalance_algo(period),+ _bt.algos.SelectAll(),+ _bt.algos.WeighEqually(),+ _bt.algos.ScaleWeights(leverage),+ _bt.algos.Margin(ratio=leverage),+ _bt.algos.Rebalance(),+ ]+ return _bt.Strategy(name, algos)+ return None+ return builddiff --git a/fincept-qt/scripts/Analytics/backtesting/fasttrade/fasttrade_provider.py b/fincept-qt/scripts/Analytics/backtesting/fasttrade/fasttrade_provider.pyindex 6a4957dda..688973951 100644--- a/fincept-qt/scripts/Analytics/backtesting/fasttrade/fasttrade_provider.py+++ b/fincept-qt/scripts/Analytics/backtesting/fasttrade/fasttrade_provider.py@@ -630,6 +630,33 @@ class FastTradeProvider(BacktestingProviderBase):"""Optimization - not implemented"""raise NotImplementedError('Optimization not natively supported by Fast-Trade')+ def get_strategies(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return strategy catalog in BT shape: {strategies: {category: [...]}}."""+ from ft_strategies import get_strategy_catalog+ catalog = get_strategy_catalog()+ return {'success': True, 'data': {'provider': 'fasttrade', 'strategies': catalog}}++ def get_indicators(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return indicator catalog normalized to {indicators: {Category: [{id, name}]}}."""+ from ft_indicators import get_catalog+ return get_catalog()++ def get_command_options(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return provider-specific option lists. FastTrade only supports backtest."""+ return {+ 'success': True,+ 'data': {+ 'position_sizing_methods': ['percent', 'fixed'],+ 'optimize_objectives': [],+ 'optimize_methods': [],+ 'label_types': [],+ 'splitter_types': [],+ 'signal_generators': [],+ 'indicator_signal_modes': [],+ 'returns_analysis_types': [],+ },+ }+# ============================================================================# CLI Entry Point@@ -665,6 +692,12 @@ def main():result = provider.calculate_indicator(indicator_type, params)elif command == 'optimize':result = provider.optimize(args)+ elif command == 'get_strategies':+ result = provider.get_strategies(args)+ elif command == 'get_indicators':+ result = provider.get_indicators(args)+ elif command == 'get_command_options':+ result = provider.get_command_options(args)elif command == 'disconnect':provider.disconnect()result = {'success': True, 'message': 'Disconnected'}diff --git a/fincept-qt/scripts/Analytics/backtesting/fasttrade/ft_indicators.py b/fincept-qt/scripts/Analytics/backtesting/fasttrade/ft_indicators.pyindex dc1440b19..fa3a3ae3d 100644--- a/fincept-qt/scripts/Analytics/backtesting/fasttrade/ft_indicators.py+++ b/fincept-qt/scripts/Analytics/backtesting/fasttrade/ft_indicators.py@@ -901,3 +901,62 @@ def list_available_indicators() -> List[str]:Sorted list of indicator name strings"""return sorted(get_transformer_map().keys())+++def get_catalog() -> Dict[str, Any]:+ """+ Return indicator catalog normalized to {indicators: {Category: [{id, name}]}}.+ Used by C++ BacktestingScreen via get_indicators command.+ """+ return {+ 'indicators': {+ 'Moving Average': [+ {'id': 'sma', 'name': 'SMA'},+ {'id': 'ema', 'name': 'EMA'},+ {'id': 'dema', 'name': 'DEMA'},+ {'id': 'tema', 'name': 'TEMA'},+ {'id': 'wma', 'name': 'WMA'},+ {'id': 'hma', 'name': 'HMA'},+ {'id': 'kama', 'name': 'KAMA'},+ {'id': 'alma', 'name': 'ALMA'},+ {'id': 'zlema', 'name': 'ZLEMA'},+ ],+ 'Oscillator': [+ {'id': 'rsi', 'name': 'RSI'},+ {'id': 'stoch', 'name': 'Stochastic'},+ {'id': 'macd', 'name': 'MACD'},+ {'id': 'mom', 'name': 'Momentum'},+ {'id': 'roc', 'name': 'ROC'},+ {'id': 'cci', 'name': 'CCI'},+ {'id': 'williams', 'name': 'Williams %R'},+ {'id': 'uo', 'name': 'Ultimate Oscillator'},+ {'id': 'tsi', 'name': 'TSI'},+ {'id': 'ao', 'name': 'Awesome Oscillator'},+ ],+ 'Volatility': [+ {'id': 'bbands', 'name': 'Bollinger Bands'},+ {'id': 'atr', 'name': 'ATR'},+ {'id': 'tr', 'name': 'True Range'},+ {'id': 'kc', 'name': 'Keltner Channel'},+ ],+ 'Volume': [+ {'id': 'obv', 'name': 'OBV'},+ {'id': 'adl', 'name': 'Accumulation/Distribution'},+ {'id': 'chaikin', 'name': 'Chaikin'},+ {'id': 'mfi', 'name': 'Money Flow Index'},+ ],+ 'Trend': [+ {'id': 'adx', 'name': 'ADX'},+ {'id': 'dmi', 'name': 'DMI'},+ {'id': 'ichimoku', 'name': 'Ichimoku Cloud'},+ {'id': 'psar', 'name': 'Parabolic SAR'},+ {'id': 'vortex', 'name': 'Vortex'},+ ],+ 'Other': [+ {'id': 'tp', 'name': 'Typical Price'},+ {'id': 'bop', 'name': 'Balance of Power'},+ {'id': 'pivot', 'name': 'Pivot Points'},+ {'id': 'vwap', 'name': 'VWAP'},+ ],+ }+ }diff --git a/fincept-qt/scripts/Analytics/backtesting/fasttrade/ft_strategies.py b/fincept-qt/scripts/Analytics/backtesting/fasttrade/ft_strategies.pyindex ddcaf3965..5d2ac2f25 100644--- a/fincept-qt/scripts/Analytics/backtesting/fasttrade/ft_strategies.py+++ b/fincept-qt/scripts/Analytics/backtesting/fasttrade/ft_strategies.py@@ -720,3 +720,94 @@ def list_strategies() -> List[Dict[str, str]]:{'name': 'bb_rsi_combined', 'category': 'Combined', 'description': 'Bollinger + RSI confirmation'},{'name': 'trend_momentum', 'category': 'Combined', 'description': 'ADX + RSI + EMA trend momentum'},]+++def get_strategy_catalog() -> Dict[str, Any]:+ """+ Return strategy catalog in BT shape: {category: [{id, name, params:[{name,label,default,min,max,step}]}]}.+ Used by C++ BacktestingScreen via get_strategies command.+ """+ return {+ 'Moving Average': [+ {'id': 'sma_crossover', 'name': 'SMA Crossover', 'params': [+ {'name': 'fast_period', 'label': 'Fast Period', 'default': 9, 'min': 2, 'max': 100, 'step': 1},+ {'name': 'slow_period', 'label': 'Slow Period', 'default': 21, 'min': 5, 'max': 200, 'step': 1},+ ]},+ {'id': 'ema_crossover', 'name': 'EMA Crossover', 'params': [+ {'name': 'fast_period', 'label': 'Fast Period', 'default': 12, 'min': 2, 'max': 100, 'step': 1},+ {'name': 'slow_period', 'label': 'Slow Period', 'default': 26, 'min': 5, 'max': 200, 'step': 1},+ ]},+ {'id': 'triple_ma', 'name': 'Triple MA', 'params': [+ {'name': 'fast', 'label': 'Fast', 'default': 5, 'min': 2, 'max': 50, 'step': 1},+ {'name': 'medium', 'label': 'Medium', 'default': 13, 'min': 5, 'max': 100, 'step': 1},+ {'name': 'slow', 'label': 'Slow', 'default': 34, 'min': 10, 'max': 200, 'step': 1},+ ]},+ {'id': 'ma_ribbon', 'name': 'MA Ribbon', 'params': []},+ ],+ 'Oscillator': [+ {'id': 'rsi_strategy', 'name': 'RSI', 'params': [+ {'name': 'period', 'label': 'Period', 'default': 14, 'min': 2, 'max': 50, 'step': 1},+ {'name': 'oversold', 'label': 'Oversold', 'default': 30, 'min': 10, 'max': 45, 'step': 1},+ {'name': 'overbought', 'label': 'Overbought', 'default': 70, 'min': 55, 'max': 90, 'step': 1},+ ]},+ {'id': 'stochastic_strategy', 'name': 'Stochastic', 'params': [+ {'name': 'period', 'label': 'Period', 'default': 14, 'min': 5, 'max': 50, 'step': 1},+ ]},+ {'id': 'macd_strategy', 'name': 'MACD', 'params': [+ {'name': 'fast', 'label': 'Fast', 'default': 12, 'min': 2, 'max': 50, 'step': 1},+ {'name': 'slow', 'label': 'Slow', 'default': 26, 'min': 5, 'max': 100, 'step': 1},+ {'name': 'signal', 'label': 'Signal', 'default': 9, 'min': 2, 'max': 50, 'step': 1},+ ]},+ {'id': 'macd_zero_cross', 'name': 'MACD Zero Cross', 'params': [+ {'name': 'fast', 'label': 'Fast', 'default': 12, 'min': 2, 'max': 50, 'step': 1},+ {'name': 'slow', 'label': 'Slow', 'default': 26, 'min': 5, 'max': 100, 'step': 1},+ {'name': 'signal', 'label': 'Signal', 'default': 9, 'min': 2, 'max': 50, 'step': 1},+ ]},+ {'id': 'cci_strategy', 'name': 'CCI', 'params': [+ {'name': 'period', 'label': 'Period', 'default': 20, 'min': 5, 'max': 50, 'step': 1},+ ]},+ ],+ 'Volatility': [+ {'id': 'bollinger_bands_strategy', 'name': 'Bollinger Bands', 'params': [+ {'name': 'period', 'label': 'Period', 'default': 20, 'min': 5, 'max': 50, 'step': 1},+ {'name': 'std_dev', 'label': 'Std Dev', 'default': 2.0, 'min': 0.5, 'max': 4.0, 'step': 0.1},+ ]},+ {'id': 'keltner_channel_strategy', 'name': 'Keltner Channel', 'params': [+ {'name': 'period', 'label': 'Period', 'default': 20, 'min': 5, 'max': 50, 'step': 1},+ ]},+ {'id': 'atr_trailing_stop', 'name': 'ATR Trailing Stop', 'params': [+ {'name': 'period', 'label': 'Period', 'default': 14, 'min': 5, 'max': 50, 'step': 1},+ {'name': 'multiplier', 'label': 'Multiplier', 'default': 2.0, 'min': 0.5, 'max': 5.0, 'step': 0.5},+ ]},+ ],+ 'Volume': [+ {'id': 'obv_strategy', 'name': 'OBV Trend', 'params': []},+ {'id': 'mfi_strategy', 'name': 'Money Flow Index', 'params': [+ {'name': 'period', 'label': 'Period', 'default': 14, 'min': 5, 'max': 50, 'step': 1},+ ]},+ ],+ 'Trend': [+ {'id': 'adx_trend', 'name': 'ADX Trend', 'params': [+ {'name': 'period', 'label': 'Period', 'default': 14, 'min': 5, 'max': 50, 'step': 1},+ {'name': 'threshold', 'label': 'Threshold', 'default': 25, 'min': 10, 'max': 50, 'step': 1},+ ]},+ {'id': 'ichimoku_strategy', 'name': 'Ichimoku Cloud', 'params': []},+ {'id': 'psar_strategy', 'name': 'Parabolic SAR', 'params': []},+ ],+ 'Combined': [+ {'id': 'rsi_macd_combined', 'name': 'RSI + MACD', 'params': [+ {'name': 'rsi_period', 'label': 'RSI Period', 'default': 14, 'min': 5, 'max': 50, 'step': 1},+ {'name': 'macd_fast', 'label': 'MACD Fast', 'default': 12, 'min': 2, 'max': 50, 'step': 1},+ {'name': 'macd_slow', 'label': 'MACD Slow', 'default': 26, 'min': 5, 'max': 100, 'step': 1},+ ]},+ {'id': 'bb_rsi_combined', 'name': 'Bollinger + RSI', 'params': [+ {'name': 'bb_period', 'label': 'BB Period', 'default': 20, 'min': 5, 'max': 50, 'step': 1},+ {'name': 'rsi_period', 'label': 'RSI Period', 'default': 14, 'min': 5, 'max': 50, 'step': 1},+ ]},+ {'id': 'trend_momentum', 'name': 'Trend + Momentum', 'params': [+ {'name': 'adx_period', 'label': 'ADX Period', 'default': 14, 'min': 5, 'max': 50, 'step': 1},+ {'name': 'rsi_period', 'label': 'RSI Period', 'default': 14, 'min': 5, 'max': 50, 'step': 1},+ {'name': 'ma_period', 'label': 'MA Period', 'default': 50, 'min': 10, 'max': 200, 'step': 5},+ ]},+ ],+ }diff --git a/fincept-qt/scripts/Analytics/backtesting/fincept/fincept_provider.py b/fincept-qt/scripts/Analytics/backtesting/fincept/fincept_provider.pyindex 2434c702f..b9b5a4949 100644--- a/fincept-qt/scripts/Analytics/backtesting/fincept/fincept_provider.py+++ b/fincept-qt/scripts/Analytics/backtesting/fincept/fincept_provider.py@@ -28,6 +28,39 @@ class FinceptProvider:def __init__(self):self.runner = FinceptStrategyRunner()+ def get_strategies(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return strategy catalog in BT shape: {strategies: {category: [{id, name, params:[]}]}}."""+ flat = self.runner.list_strategies()+ grouped: Dict[str, List] = {}+ for s in flat:+ cat = s.get('category', 'General Strategy')+ grouped.setdefault(cat, []).append({+ 'id': s['id'],+ 'name': s['name'],+ 'params': [], # Fincept strategies use free-form strategy_params dict+ })+ return {'success': True, 'data': {'provider': 'fincept', 'strategies': grouped}}++ def get_indicators(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Fincept strategies are self-contained — no separate indicator catalog."""+ return {'indicators': {}}++ def get_command_options(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return provider-specific option lists."""+ return {+ 'success': True,+ 'data': {+ 'position_sizing_methods': ['percent', 'fixed', 'kelly', 'vol_target', 'risk'],+ 'optimize_objectives': ['sharpe', 'sortino', 'calmar', 'return'],+ 'optimize_methods': ['grid', 'random'],+ 'label_types': [],+ 'splitter_types': [],+ 'signal_generators': [],+ 'indicator_signal_modes': [],+ 'returns_analysis_types': [],+ },+ }+def run_backtest(self, request: Dict[str, Any]) -> Dict[str, Any]:"""Execute a backtest for a Fincept Engine strategy.@@ -144,10 +177,16 @@ def main():# Route commandif command == "run_backtest" or command == "execute_fincept_strategy":result = provider.run_backtest(args)+ elif command == "get_strategies":+ result = provider.get_strategies(args)+ elif command == "get_indicators":+ result = provider.get_indicators(args)+ elif command == "get_command_options":+ result = provider.get_command_options(args)else:result = {"success": False,- "error": f"Unknown command: {command}. Supported: run_backtest"+ "error": f"Unknown command: {command}"}print(json.dumps(result))diff --git a/fincept-qt/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py b/fincept-qt/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.pyindex 9d9dd0b2b..286a2b05c 100644--- a/fincept-qt/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py+++ b/fincept-qt/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py@@ -408,9 +408,33 @@ class VectorBTProvider(BacktestingProviderBase):return {'success': True, 'data': strat.get_strategy_catalog()}def get_indicators(self, request: Dict[str, Any]) -> Dict[str, Any]:- """Return available indicator catalog."""+ """Return indicator catalog normalized to {indicators: {Category: [{id, name}]}}."""import vbt_indicators as ind- return {'success': True, 'data': ind.get_indicator_catalog()}+ raw = ind.get_indicator_catalog()+ grouped = {}+ for cat in raw.get('categories', []):+ cat_name = cat.get('name', 'Other')+ grouped[cat_name] = [+ {'id': it['id'], 'name': it.get('name', it['id'])}+ for it in cat.get('indicators', [])+ ]+ return {'indicators': grouped}++ def get_command_options(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return provider-specific option lists for all command dropdowns."""+ return {+ 'success': True,+ 'data': {+ 'position_sizing_methods': ['percent', 'fixed', 'kelly', 'vol_target', 'risk'],+ 'optimize_objectives': ['sharpe', 'sortino', 'calmar', 'return', 'omega'],+ 'optimize_methods': ['grid', 'random', 'optuna'],+ 'label_types': ['FIXLB', 'MEANLB', 'LEXLB', 'TRENDLB', 'BOLB'],+ 'splitter_types': ['RollingSplitter', 'ExpandingSplitter', 'PurgedKFold'],+ 'signal_generators': ['RAND', 'RANDX', 'RANDNX', 'RPROB', 'RPROBX'],+ 'indicator_signal_modes': ['crossover', 'threshold', 'breakout', 'mean_reversion', 'filter'],+ 'returns_analysis_types': ['cumulative', 'rolling', 'drawdown', 'distribution', 'benchmark_comparison'],+ },+ }def get_historical_data(self, request: Dict[str, Any]) -> list:"""Get historical data using yfinance."""@@ -1845,6 +1869,9 @@ def main():elif command == 'get_indicators':result = provider.get_indicators(args)result_str = json_response(result)+ elif command == 'get_command_options':+ result = provider.get_command_options(args)+ result_str = json_response(result)elif command == 'generate_signals':result = provider.generate_signals(args)result_str = json_response(result)diff --git a/fincept-qt/scripts/Analytics/backtesting/zipline/zipline_provider.py b/fincept-qt/scripts/Analytics/backtesting/zipline/zipline_provider.pyindex 02fc13948..0cf1e2e63 100644--- a/fincept-qt/scripts/Analytics/backtesting/zipline/zipline_provider.py+++ b/fincept-qt/scripts/Analytics/backtesting/zipline/zipline_provider.py@@ -1589,32 +1589,46 @@ class ZiplineProvider(BacktestingProviderBase):}def get_indicators(self, request: Dict[str, Any]) -> Dict[str, Any]:- """Return comprehensive indicator catalog."""- indicators = {- 'ma': {'name': 'Simple Moving Average', 'params': ['period'], 'category': 'trend'},- 'ema': {'name': 'Exponential Moving Average', 'params': ['period'], 'category': 'trend'},- 'rsi': {'name': 'Relative Strength Index', 'params': ['period'], 'category': 'momentum'},- 'bbands': {'name': 'Bollinger Bands', 'params': ['period', 'alpha'], 'category': 'volatility'},- 'atr': {'name': 'Average True Range', 'params': ['period'], 'category': 'volatility'},- 'mstd': {'name': 'Moving Std Dev', 'params': ['period'], 'category': 'volatility'},- 'macd': {'name': 'MACD', 'params': ['fastPeriod', 'slowPeriod', 'signalPeriod'], 'category': 'momentum'},- 'stochastic': {'name': 'Stochastic Oscillator', 'params': ['kPeriod', 'dPeriod'], 'category': 'momentum'},- 'williams_r': {'name': 'Williams %R', 'params': ['period'], 'category': 'momentum'},- 'cci': {'name': 'Commodity Channel Index', 'params': ['period'], 'category': 'momentum'},- 'obv': {'name': 'On-Balance Volume', 'params': [], 'category': 'volume'},- 'adx': {'name': 'Average Directional Index', 'params': ['period'], 'category': 'trend'},- 'keltner': {'name': 'Keltner Channel', 'params': ['period', 'multiplier'], 'category': 'volatility'},- 'donchian': {'name': 'Donchian Channel', 'params': ['period'], 'category': 'volatility'},- 'momentum': {'name': 'Momentum (ROC)', 'params': ['period'], 'category': 'momentum'},- 'zscore': {'name': 'Z-Score', 'params': ['period'], 'category': 'statistical'},- 'vwap': {'name': 'Volume Weighted Avg Price', 'params': [], 'category': 'volume'},+ """Return indicator catalog normalized to {indicators: {Category: [{id, name}]}}."""+ flat = {+ 'ma': {'name': 'Simple Moving Average', 'category': 'Trend'},+ 'ema': {'name': 'Exponential Moving Average','category': 'Trend'},+ 'adx': {'name': 'ADX', 'category': 'Trend'},+ 'keltner': {'name': 'Keltner Channel', 'category': 'Trend'},+ 'donchian': {'name': 'Donchian Channel', 'category': 'Trend'},+ 'rsi': {'name': 'RSI', 'category': 'Momentum'},+ 'macd': {'name': 'MACD', 'category': 'Momentum'},+ 'stochastic': {'name': 'Stochastic Oscillator', 'category': 'Momentum'},+ 'williams_r': {'name': 'Williams %R', 'category': 'Momentum'},+ 'cci': {'name': 'CCI', 'category': 'Momentum'},+ 'momentum': {'name': 'Momentum (ROC)', 'category': 'Momentum'},+ 'bbands': {'name': 'Bollinger Bands', 'category': 'Volatility'},+ 'atr': {'name': 'ATR', 'category': 'Volatility'},+ 'mstd': {'name': 'Moving Std Dev', 'category': 'Volatility'},+ 'zscore': {'name': 'Z-Score', 'category': 'Volatility'},+ 'obv': {'name': 'On-Balance Volume', 'category': 'Volume'},+ 'vwap': {'name': 'VWAP', 'category': 'Volume'},}+ grouped: Dict[str, Any] = {}+ for ind_id, info in flat.items():+ cat = info['category']+ grouped.setdefault(cat, []).append({'id': ind_id, 'name': info['name']})+ return {'indicators': grouped}++ def get_command_options(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Return provider-specific option lists for all command dropdowns."""return {'success': True,'data': {- 'provider': 'zipline',- 'indicators': indicators,- }+ 'position_sizing_methods': ['percent', 'fixed', 'kelly', 'vol_target', 'risk'],+ 'optimize_objectives': ['sharpe', 'sortino', 'calmar', 'return'],+ 'optimize_methods': ['grid', 'random'],+ 'label_types': [],+ 'splitter_types': [],+ 'signal_generators': [],+ 'indicator_signal_modes': ['crossover', 'threshold', 'breakout', 'mean_reversion', 'filter'],+ 'returns_analysis_types': [],+ },}# ========================================================================@@ -2734,6 +2748,9 @@ def main():elif command == 'get_indicators':result = provider.get_indicators(args)result_str = json_response(result)+ elif command == 'get_command_options':+ result = provider.get_command_options(args)+ result_str = json_response(result)elif command == 'get_historical_data':result = provider.get_historical_data(args)result_str = json_response({'success': True, 'data': result})diff --git a/fincept-qt/src/screens/agent_config/AgentChatPanel.cpp b/fincept-qt/src/screens/agent_config/AgentChatPanel.cppindex 7eb7d5154..edf768ac7 100644--- a/fincept-qt/src/screens/agent_config/AgentChatPanel.cpp+++ b/fincept-qt/src/screens/agent_config/AgentChatPanel.cpp@@ -3,6 +3,7 @@#include "core/logging/Logger.h"#include "services/agents/AgentService.h"+#include "storage/repositories/PortfolioRepository.h"#include "ui/theme/Theme.h"#include <QDateTime>@@ -125,6 +126,24 @@ void AgentChatPanel::build_ui() {hl->addWidget(title);hl->addStretch();+ // Agent selector — lets user target a specific configured agent+ auto* agent_lbl = new QLabel("AGENT:");+ agent_lbl->setStyleSheet(QString("color:%1;font-size:9px;font-weight:600;padding-right:4px;")+ .arg(ui::colors::TEXT_SECONDARY));+ hl->addWidget(agent_lbl);++ agent_selector_ = new QComboBox;+ agent_selector_->addItem("Default", QString{});+ agent_selector_->setMinimumWidth(140);+ agent_selector_->setToolTip("Select a specific agent, or leave as Default to use auto-routing or global default.");+ agent_selector_->setStyleSheet(+ QString("QComboBox{background:%1;color:%2;border:1px solid %3;padding:2px 8px;font-size:10px;}"+ "QComboBox::drop-down{border:none;}"+ "QComboBox QAbstractItemView{background:%1;color:%2;selection-background-color:%4;}")+ .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED, ui::colors::AMBER_DIM));+ hl->addWidget(agent_selector_);+ hl->addSpacing(8);+route_toggle_ = new QPushButton("AUTO-ROUTE: OFF");route_toggle_->setCheckable(true);route_toggle_->setCursor(Qt::PointingHandCursor);@@ -255,8 +274,32 @@ void AgentChatPanel::setup_connections() {connect(route_toggle_, &QPushButton::toggled, this, [this](bool c) {auto_routing_ = c;route_toggle_->setText(c ? "AUTO-ROUTE: ON" : "AUTO-ROUTE: OFF");+ // When auto-routing is on, agent selector is irrelevant+ agent_selector_->setEnabled(!c);});+ // Populate agent selector when agents are discovered+ connect(&services::AgentService::instance(), &services::AgentService::agents_discovered, this,+ [this](QVector<services::AgentInfo> agents, QVector<services::AgentCategory>) {+ const QString prev_id = agent_selector_->currentData().toString();+ agent_selector_->blockSignals(true);+ agent_selector_->clear();+ agent_selector_->addItem("Default", QString{});+ for (const auto& a : agents)+ agent_selector_->addItem(QString("[%1] %2").arg(a.category, a.name), a.id);+ // Restore previous selection+ int restore = 0;+ if (!prev_id.isEmpty()) {+ for (int i = 1; i < agent_selector_->count(); ++i) {+ if (agent_selector_->itemData(i).toString() == prev_id) {+ restore = i; break;+ }+ }+ }+ agent_selector_->blockSignals(false);+ agent_selector_->setCurrentIndex(restore);+ });+// Portfolio quick actionsconnect(analyze_btn_, &QPushButton::clicked, this, [this]() {QString pf = portfolio_combo_->currentText();@@ -284,38 +327,48 @@ void AgentChatPanel::setup_connections() {auto& svc = services::AgentService::instance();connect(&svc, &services::AgentService::routing_result, this, [this](services::RoutingResult r) {+ if (r.request_id != pending_request_id_) return;if (r.success) {add_system_bubble(QString("Routed to: %1 (intent: %2, confidence: %3%)").arg(r.agent_id, r.intent).arg(int(r.confidence * 100)));- services::AgentService::instance().run_agent(last_query_, r.config);+ pending_request_id_ = services::AgentService::instance().run_agent_streaming(last_query_, r.config);} else {add_system_bubble("Routing failed, using default agent.");- services::AgentService::instance().run_agent(last_query_, {});+ pending_request_id_ = services::AgentService::instance().run_agent_streaming(last_query_, {});}});- connect(&svc, &services::AgentService::agent_stream_thinking, this, [this](const QString& status) {- if (!executing_) return;+ connect(&svc, &services::AgentService::agent_stream_thinking, this, [this](const QString& request_id, const QString& status) {+ if (request_id != pending_request_id_) return;status_label_->setText(status);});- connect(&svc, &services::AgentService::agent_stream_token, this, [this](const QString& token) {- if (!executing_) return;- // Append tokens to the last assistant bubble's label if present,- // otherwise fall back to a new bubble finalised on stream_done.+ connect(&svc, &services::AgentService::agent_stream_token, this, [this](const QString& request_id, const QString& token) {+ if (request_id != pending_request_id_) return;+ streaming_text_ += token + " ";status_label_->setText("Streaming...");- // Accumulate in last_query_ temporarily — reset on send_message already saved it- // We use a dedicated streaming_buffer_ approach: just update status here,- // full response rendered on agent_stream_done below.- Q_UNUSED(token)+ // Append token live into the streaming bubble widget+ if (streaming_bubble_widget_) {+ streaming_bubble_widget_->setPlainText(streaming_text_);+ // Resize bubble to fit new content+ streaming_bubble_widget_->setFixedHeight(+ static_cast<int>(streaming_bubble_widget_->document()->size().height()) + 4);+ scroll_to_bottom();+ }});connect(&svc, &services::AgentService::agent_stream_done, this, [this](services::AgentExecutionResult r) {- if (!executing_) return;+ if (r.request_id != pending_request_id_) return;executing_ = false;+ pending_request_id_.clear();send_btn_->setEnabled(true);send_btn_->setText("SEND");+ streaming_bubble_widget_ = nullptr;+ streaming_text_.clear();if (r.success) {- add_assistant_bubble(r.response);+ // Replace the streaming bubble content with the final rendered response+ // The last assistant bubble is already in the layout — just add_assistant_bubble+ // would duplicate it, so we only add a new bubble if streaming never started.+ // Since we streamed live above, the bubble is already there — nothing to add.status_label_->setText(QString("Response received (%1ms)").arg(r.execution_time_ms));} else {add_system_bubble("Error: " + r.error);@@ -323,14 +376,23 @@ void AgentChatPanel::setup_connections() {}});connect(&svc, &services::AgentService::agent_result, this, [this](services::AgentExecutionResult r) {- if (!executing_) return;+ if (r.request_id != pending_request_id_) return;executing_ = false;+ pending_request_id_.clear();send_btn_->setEnabled(true);send_btn_->setText("SEND");- if (r.success) {+ // If a streaming bubble was created, update it with final text; else add a new bubble+ if (streaming_bubble_widget_) {+ if (r.success)+ streaming_bubble_widget_->setPlainText(r.response);+ streaming_bubble_widget_ = nullptr;+ } else if (r.success) {add_assistant_bubble(r.response);+ }+ streaming_text_.clear();+ if (r.success)status_label_->setText(QString("Response received (%1ms)").arg(r.execution_time_ms));- } else {+ else {add_system_bubble("Error: " + r.error);status_label_->setText("Agent execution failed");}@@ -350,11 +412,18 @@ void AgentChatPanel::send_message() {add_user_bubble(text);last_query_ = text;input_edit_->clear();+ start_streaming_bubble(); // create live bubble before streaming begins- if (auto_routing_)- services::AgentService::instance().route_query(last_query_);- else- services::AgentService::instance().run_agent(last_query_, {});+ if (auto_routing_) {+ pending_request_id_ = services::AgentService::instance().route_query(last_query_);+ } else {+ // Build config for the selected agent (empty = global default)+ const QString agent_id = agent_selector_->currentData().toString();+ QJsonObject config;+ if (!agent_id.isEmpty())+ config["agent_id"] = agent_id;+ pending_request_id_ = services::AgentService::instance().run_agent_streaming(last_query_, config);+ }}void AgentChatPanel::add_user_bubble(const QString& text) {@@ -375,6 +444,17 @@ void AgentChatPanel::add_system_bubble(const QString& text) {scroll_to_bottom();}+void AgentChatPanel::start_streaming_bubble() {+ streaming_text_.clear();+ // Create a live assistant bubble with empty text — tokens will append into it+ auto* b = make_bubble("", "assistant", QDateTime::currentDateTime().toString("hh:mm"));+ messages_layout_->insertWidget(messages_layout_->count() - 1, b);+ // The QTextEdit inside the bubble card is the last child of the card's layout+ // make_bubble() structure: bubble > vl > row > card > cl > [hdr_row, content(QTextEdit)]+ streaming_bubble_widget_ = b->findChild<QTextEdit*>();+ scroll_to_bottom();+}+void AgentChatPanel::scroll_to_bottom() {QTimer::singleShot(50, this, [this]() {scroll_area_->verticalScrollBar()->setValue(scroll_area_->verticalScrollBar()->maximum());@@ -397,6 +477,21 @@ void AgentChatPanel::showEvent(QShowEvent* event) {if (!data_loaded_) {data_loaded_ = true;add_system_bubble("Agent Chat ready. Type a message or use the quick actions below.");++ // Populate portfolio combo from repository+ const QString prev = portfolio_combo_->currentText();+ portfolio_combo_->blockSignals(true);+ portfolio_combo_->clear();+ portfolio_combo_->addItem("None");+ const auto result = PortfolioRepository::instance().list_portfolios();+ if (result.is_ok()) {+ for (const auto& p : result.value())+ portfolio_combo_->addItem(p.name, p.id);+ }+ // Restore previous selection if still present+ const int idx = portfolio_combo_->findText(prev);+ portfolio_combo_->setCurrentIndex(idx >= 0 ? idx : 0);+ portfolio_combo_->blockSignals(false);}}diff --git a/fincept-qt/src/screens/agent_config/AgentChatPanel.h b/fincept-qt/src/screens/agent_config/AgentChatPanel.hindex a73400203..c598aee91 100644--- a/fincept-qt/src/screens/agent_config/AgentChatPanel.h+++ b/fincept-qt/src/screens/agent_config/AgentChatPanel.h@@ -33,6 +33,7 @@ class AgentChatPanel : public QWidget {void add_user_bubble(const QString& text);void add_assistant_bubble(const QString& text, const QString& agent_name = {});void add_system_bubble(const QString& text);+ void start_streaming_bubble(); // creates live bubble, sets streaming_bubble_widget_void scroll_to_bottom();void clear_chat();@@ -45,6 +46,7 @@ class AgentChatPanel : public QWidget {QPushButton* clear_btn_ = nullptr;QPushButton* route_toggle_ = nullptr;QLabel* status_label_ = nullptr;+ QComboBox* agent_selector_ = nullptr; // pick a specific agent; empty = global default// Portfolio contextQWidget* portfolio_bar_ = nullptr;@@ -54,10 +56,13 @@ class AgentChatPanel : public QWidget {QPushButton* risk_btn_ = nullptr;// State- bool auto_routing_ = false;- bool executing_ = false;- bool data_loaded_ = false;- QString last_query_; // saved for routed execution+ bool auto_routing_ = false;+ bool executing_ = false;+ bool data_loaded_ = false;+ QString last_query_;+ QString pending_request_id_;+ QString streaming_text_; // accumulates tokens for the live bubble+ QTextEdit* streaming_bubble_widget_ = nullptr; // points into the live bubble while streaming};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/agent_config/AgentConfigScreen.cpp b/fincept-qt/src/screens/agent_config/AgentConfigScreen.cppindex d3947ab34..75e61f63a 100644--- a/fincept-qt/src/screens/agent_config/AgentConfigScreen.cpp+++ b/fincept-qt/src/screens/agent_config/AgentConfigScreen.cpp@@ -27,10 +27,14 @@ struct ViewMeta {};static constexpr ViewMeta kViews[] = {- {services::AgentViewMode::Agents, "AGENTS"}, {services::AgentViewMode::Create, "CREATE"},- {services::AgentViewMode::Teams, "TEAMS"}, {services::AgentViewMode::Workflows, "WORKFLOWS"},- {services::AgentViewMode::Planner, "PLANNER"}, {services::AgentViewMode::Tools, "TOOLS"},- {services::AgentViewMode::Chat, "CHAT"}, {services::AgentViewMode::System, "SYSTEM"},+ {services::AgentViewMode::Agents, "AGENTS"},+ {services::AgentViewMode::Create, "CREATE"},+ {services::AgentViewMode::Teams, "TEAMS"},+ {services::AgentViewMode::Workflows, "WORKFLOWS"},+ {services::AgentViewMode::Planner, "PLANNER"},+ {services::AgentViewMode::Tools, "TOOLS"},+ {services::AgentViewMode::Chat, "CHAT"},+ {services::AgentViewMode::System, "SYSTEM"},};// ── Constructor ──────────────────────────────────────────────────────────────@@ -38,7 +42,7 @@ static constexpr ViewMeta kViews[] = {AgentConfigScreen::AgentConfigScreen(QWidget* parent) : QWidget(parent) {setObjectName("AgentConfigScreen");build_ui();- setup_connections();+ setup_service_connections();}// ── UI construction ──────────────────────────────────────────────────────────@@ -50,27 +54,14 @@ void AgentConfigScreen::build_ui() {build_nav_bar(root);- // ── View stack ───────────────────────────────────────────────────────────view_stack_ = new QStackedWidget;view_stack_->setObjectName("AgentViewStack");root->addWidget(view_stack_, 1);- // Index 0: AGENTS view- agents_panel_ = new AgentsViewPanel;- view_stack_->addWidget(agents_panel_);-- create_panel_ = new CreateAgentPanel;- view_stack_->addWidget(create_panel_); // 1- teams_panel_ = new TeamsViewPanel;- view_stack_->addWidget(teams_panel_); // 2- view_stack_->addWidget(new WorkflowsViewPanel); // 3- view_stack_->addWidget(new PlannerViewPanel); // 4- tools_panel_ = new ToolsViewPanel;- view_stack_->addWidget(tools_panel_); // 5- view_stack_->addWidget(new AgentChatPanel); // 6-- // Index 7: SYSTEM view- view_stack_->addWidget(new SystemViewPanel);+ // Pre-populate stack with 8 empty placeholder widgets so indices are stable.+ // Real panels are swapped in by ensure_panel_built() on first navigation.+ for (int i = 0; i < 8; ++i)+ view_stack_->addWidget(new QWidget);build_status_bar(root);}@@ -86,20 +77,17 @@ void AgentConfigScreen::build_nav_bar(QVBoxLayout* root) {hl->setContentsMargins(12, 0, 12, 0);hl->setSpacing(0);- // Titleauto* title = new QLabel("AGENT STUDIO");title->setStyleSheet(QString("color:%1;font-size:13px;font-weight:700;letter-spacing:2px;padding-right:16px;").arg(ui::colors::AMBER));hl->addWidget(title);- // Separatorauto* sep = new QFrame;sep->setFrameShape(QFrame::VLine);sep->setStyleSheet(QString("color:%1;").arg(ui::colors::BORDER_MED));sep->setFixedWidth(1);hl->addWidget(sep);- // Navigation buttonsfor (const auto& vm : kViews) {auto* btn = make_nav_btn(vm.label, vm.mode);hl->addWidget(btn);@@ -108,7 +96,6 @@ void AgentConfigScreen::build_nav_bar(QVBoxLayout* root) {hl->addStretch();- // Agent count badgeagent_count_label_ = new QLabel;agent_count_label_->setStyleSheet(QString("color:%1;font-size:11px;padding:2px 8px;background:%2;border-radius:2px;")@@ -139,7 +126,6 @@ void AgentConfigScreen::build_status_bar(QVBoxLayout* root) {root->addWidget(bar);- // Update view label when view changesconnect(view_stack_, &QStackedWidget::currentChanged, this, [view_label](int idx) {if (idx >= 0 && idx < static_cast<int>(std::size(kViews)))view_label->setText(kViews[idx].label);@@ -162,21 +148,106 @@ QPushButton* AgentConfigScreen::make_nav_btn(const QString& text, services::Agenreturn btn;}+// ── Lazy panel construction ──────────────────────────────────────────────────++void AgentConfigScreen::ensure_panel_built(services::AgentViewMode mode) {+ const int idx = static_cast<int>(mode);+ if (panel_built_[idx])+ return;+ panel_built_[idx] = true;++ QWidget* panel = nullptr;+ switch (mode) {+ case services::AgentViewMode::Agents:+ agents_panel_ = new AgentsViewPanel;+ panel = agents_panel_;+ break;+ case services::AgentViewMode::Create:+ create_panel_ = new CreateAgentPanel;+ panel = create_panel_;+ break;+ case services::AgentViewMode::Teams:+ teams_panel_ = new TeamsViewPanel;+ panel = teams_panel_;+ break;+ case services::AgentViewMode::Workflows:+ workflows_panel_ = new WorkflowsViewPanel;+ panel = workflows_panel_;+ break;+ case services::AgentViewMode::Planner:+ planner_panel_ = new PlannerViewPanel;+ panel = planner_panel_;+ break;+ case services::AgentViewMode::Tools:+ tools_panel_ = new ToolsViewPanel;+ panel = tools_panel_;+ break;+ case services::AgentViewMode::Chat:+ chat_panel_ = new AgentChatPanel;+ panel = chat_panel_;+ break;+ case services::AgentViewMode::System:+ system_panel_ = new SystemViewPanel;+ panel = system_panel_;+ break;+ }++ // Replace the placeholder widget at this stack index+ QWidget* placeholder = view_stack_->widget(idx);+ view_stack_->insertWidget(idx, panel);+ view_stack_->removeWidget(placeholder);+ placeholder->deleteLater();++ // Wire cross-panel signals now that relevant panels may be available+ wire_cross_panel_signals();++ LOG_INFO("AgentConfigScreen", QString("Built panel: %1").arg(kViews[idx].label));+}++void AgentConfigScreen::wire_cross_panel_signals() {+ // AGENTS → TEAMS: "Add to Team" button+ if (agents_panel_ && teams_panel_)+ connect(agents_panel_, &AgentsViewPanel::add_agent_to_team,+ teams_panel_, &TeamsViewPanel::add_agent_from_panel,+ Qt::UniqueConnection);++ // TOOLS → AGENTS: selection propagation+ if (tools_panel_ && agents_panel_)+ connect(tools_panel_, &ToolsViewPanel::tools_selection_changed,+ agents_panel_, &AgentsViewPanel::apply_tools_selection,+ Qt::UniqueConnection);++ // TOOLS → CREATE: selection propagation+ if (tools_panel_ && create_panel_)+ connect(tools_panel_, &ToolsViewPanel::tools_selection_changed,+ create_panel_, &CreateAgentPanel::apply_tools_selection,+ Qt::UniqueConnection);++ // TOOLS → TEAMS: selection propagation (Task 5)+ if (tools_panel_ && teams_panel_)+ connect(tools_panel_, &ToolsViewPanel::tools_selection_changed,+ teams_panel_, &TeamsViewPanel::apply_tools_selection,+ Qt::UniqueConnection);+}+// ── View switching ───────────────────────────────────────────────────────────void AgentConfigScreen::set_view(services::AgentViewMode mode) {- int idx = static_cast<int>(mode);+ const int idx = static_cast<int>(mode);++ // Build the panel on first visit (P2: lazy construction)+ ensure_panel_built(mode);+view_stack_->setCurrentIndex(idx);current_view_ = mode;- // Update button checked statesfor (int i = 0; i < nav_buttons_.size(); ++i)nav_buttons_[i]->setChecked(i == idx);}-// ── Connections ──────────────────────────────────────────────────────────────+// ── Service-level connections (global signals, no per-panel wiring) ──────────-void AgentConfigScreen::setup_connections() {+void AgentConfigScreen::setup_service_connections() {auto& svc = services::AgentService::instance();connect(&svc, &services::AgentService::agents_discovered, this,@@ -189,17 +260,6 @@ void AgentConfigScreen::setup_connections() {status_label_->setStyleSheet(QString("color:%1;font-size:10px;").arg(ui::colors::NEGATIVE));});- // Wire "Add to Team" button in Agents tab → TeamsViewPanel- connect(agents_panel_, &AgentsViewPanel::add_agent_to_team,- teams_panel_, &TeamsViewPanel::add_agent_from_panel);-- // Wire Tools tab selection → Agents + Create panels- connect(tools_panel_, &ToolsViewPanel::tools_selection_changed,- agents_panel_, &AgentsViewPanel::apply_tools_selection);- connect(tools_panel_, &ToolsViewPanel::tools_selection_changed,- create_panel_, &CreateAgentPanel::apply_tools_selection);-- // Reset status on successful operationsconnect(&svc, &services::AgentService::agent_result, this, [this](services::AgentExecutionResult r) {if (r.success) {status_label_->setText(QString("DONE (%1ms)").arg(r.execution_time_ms));@@ -209,6 +269,17 @@ void AgentConfigScreen::setup_connections() {status_label_->setStyleSheet(QString("color:%1;font-size:10px;").arg(ui::colors::NEGATIVE));}});++ // Task 4 & 9: when an agent is saved/deleted in CREATE, refresh the agent+ // list so AGENTS tab and TEAMS available list stay in sync.+ connect(&svc, &services::AgentService::config_saved, this, [this]() {+ services::AgentService::instance().clear_cache();+ services::AgentService::instance().discover_agents();+ });+ connect(&svc, &services::AgentService::config_deleted, this, [this]() {+ services::AgentService::instance().clear_cache();+ services::AgentService::instance().discover_agents();+ });}// ── Visibility ───────────────────────────────────────────────────────────────@@ -217,6 +288,8 @@ void AgentConfigScreen::showEvent(QShowEvent* event) {QWidget::showEvent(event);if (first_show_) {first_show_ = false;+ // Build the default (AGENTS) panel and kick off discovery once+ ensure_panel_built(services::AgentViewMode::Agents);services::AgentService::instance().discover_agents();}}diff --git a/fincept-qt/src/screens/agent_config/AgentConfigScreen.h b/fincept-qt/src/screens/agent_config/AgentConfigScreen.hindex c94a5c587..69bc5c851 100644--- a/fincept-qt/src/screens/agent_config/AgentConfigScreen.h+++ b/fincept-qt/src/screens/agent_config/AgentConfigScreen.h@@ -1,21 +1,29 @@// src/screens/agent_config/AgentConfigScreen.h#pragma once-#include "screens/agent_config/AgentsViewPanel.h"-#include "screens/agent_config/CreateAgentPanel.h"-#include "screens/agent_config/TeamsViewPanel.h"-#include "screens/agent_config/ToolsViewPanel.h"#include "services/agents/AgentTypes.h"#include <QLabel>#include <QPushButton>#include <QStackedWidget>+#include <QVBoxLayout>#include <QWidget>+// Forward-declare all panels — constructed lazily on first navigation+namespace fincept::screens {+class AgentsViewPanel;+class CreateAgentPanel;+class TeamsViewPanel;+class WorkflowsViewPanel;+class PlannerViewPanel;+class ToolsViewPanel;+class AgentChatPanel;+class SystemViewPanel;+}+namespace fincept::screens {/// Main Agent Studio screen — 8-view navigation shell.-/// Uses QStackedWidget to switch between AGENTS, CREATE, TEAMS,-/// WORKFLOWS, PLANNER, TOOLS, CHAT, SYSTEM sub-panels.+/// Panels are constructed lazily on first navigation (P2 compliance).class AgentConfigScreen : public QWidget {Q_OBJECTpublic:@@ -29,18 +37,31 @@ class AgentConfigScreen : public QWidget {void build_ui();void build_nav_bar(QVBoxLayout* root);void build_status_bar(QVBoxLayout* root);- void setup_connections();+ void setup_service_connections();void set_view(services::AgentViewMode mode);QPushButton* make_nav_btn(const QString& text, services::AgentViewMode mode);- QStackedWidget* view_stack_ = nullptr;+ // Ensure the panel for mode is built; returns its stack index+ void ensure_panel_built(services::AgentViewMode mode);+ void wire_cross_panel_signals();++ QStackedWidget* view_stack_ = nullptr;QVector<QPushButton*> nav_buttons_;- QLabel* status_label_ = nullptr;- QLabel* agent_count_label_ = nullptr;- AgentsViewPanel* agents_panel_ = nullptr;- TeamsViewPanel* teams_panel_ = nullptr;- CreateAgentPanel* create_panel_ = nullptr;- ToolsViewPanel* tools_panel_ = nullptr;+ QLabel* status_label_ = nullptr;+ QLabel* agent_count_label_ = nullptr;++ // Lazily constructed panels (nullptr until first navigation)+ AgentsViewPanel* agents_panel_ = nullptr;+ CreateAgentPanel* create_panel_ = nullptr;+ TeamsViewPanel* teams_panel_ = nullptr;+ WorkflowsViewPanel* workflows_panel_ = nullptr;+ PlannerViewPanel* planner_panel_ = nullptr;+ ToolsViewPanel* tools_panel_ = nullptr;+ AgentChatPanel* chat_panel_ = nullptr;+ SystemViewPanel* system_panel_ = nullptr;++ // Track which stack slots have been populated+ bool panel_built_[8] = {};services::AgentViewMode current_view_ = services::AgentViewMode::Agents;bool first_show_ = true;diff --git a/fincept-qt/src/screens/agent_config/AgentsViewPanel.cpp b/fincept-qt/src/screens/agent_config/AgentsViewPanel.cppindex d02d095b6..eed300dc3 100644--- a/fincept-qt/src/screens/agent_config/AgentsViewPanel.cpp+++ b/fincept-qt/src/screens/agent_config/AgentsViewPanel.cpp@@ -430,7 +430,9 @@ void AgentsViewPanel::setup_connections() {connect(&svc, &services::AgentService::agent_result, this,[this](services::AgentExecutionResult r) {+ if (r.request_id != pending_request_id_) return;executing_ = false;+ pending_request_id_.clear();run_btn_->setEnabled(true);run_btn_->setText("RUN AGENT");if (r.success) {@@ -448,13 +450,14 @@ void AgentsViewPanel::setup_connections() {// ── Streaming signals ─────────────────────────────────────────────────────connect(&svc, &services::AgentService::agent_stream_thinking, this,- [this](const QString& status) {+ [this](const QString& request_id, const QString& status) {+ if (request_id != pending_request_id_) return;result_status_->setText(status);});connect(&svc, &services::AgentService::agent_stream_token, this,- [this](const QString& token) {- // Append token as plain text during streaming — fast, no re-parse+ [this](const QString& request_id, const QString& token) {+ if (request_id != pending_request_id_) return;QTextCursor cursor = result_display_->textCursor();cursor.movePosition(QTextCursor::End);result_display_->setTextCursor(cursor);@@ -463,11 +466,12 @@ void AgentsViewPanel::setup_connections() {connect(&svc, &services::AgentService::agent_stream_done, this,[this](services::AgentExecutionResult r) {+ if (r.request_id != pending_request_id_) return;executing_ = false;+ pending_request_id_.clear();run_btn_->setEnabled(true);run_btn_->setText("RUN AGENT");if (r.success) {- // Re-render full response as markdown now streaming is completeresult_display_->setMarkdown(r.response);result_status_->setText(QString("Completed in %1ms").arg(r.execution_time_ms));result_status_->setStyleSheet(@@ -482,6 +486,7 @@ void AgentsViewPanel::setup_connections() {connect(&svc, &services::AgentService::routing_result, this,[this](services::RoutingResult r) {+ if (r.request_id != pending_request_id_) return;if (r.success) {routing_info_label_->setText(QString("Routed → %1 (intent: %2, confidence: %3%)")@@ -787,14 +792,14 @@ void AgentsViewPanel::run_query() {auto& svc = services::AgentService::instance();if (auto_route_check_->isChecked()) {- svc.route_query(q);+ pending_request_id_ = svc.route_query(q);svc.execute_routed_query(q, config);} else {const QString om = output_model_combo_->currentText();if (om != "text")- svc.run_agent_structured(q, config, om);+ pending_request_id_ = svc.run_agent_structured(q, config, om);else- svc.run_agent_streaming(q, config);+ pending_request_id_ = svc.run_agent_streaming(q, config);}}diff --git a/fincept-qt/src/screens/agent_config/AgentsViewPanel.h b/fincept-qt/src/screens/agent_config/AgentsViewPanel.hindex 4d57183c6..0d580a43d 100644--- a/fincept-qt/src/screens/agent_config/AgentsViewPanel.h+++ b/fincept-qt/src/screens/agent_config/AgentsViewPanel.h@@ -91,8 +91,9 @@ class AgentsViewPanel : public QWidget {// ── State ────────────────────────────────────────────────────────────────QVector<services::AgentInfo> all_agents_;QVector<services::AgentInfo> filtered_agents_;- int selected_agent_idx_ = -1;- bool executing_ = false;+ int selected_agent_idx_ = -1;+ bool executing_ = false;+ QString pending_request_id_; // guards against cross-panel signal contamination};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/agent_config/CreateAgentPanel.cpp b/fincept-qt/src/screens/agent_config/CreateAgentPanel.cppindex de18a3789..7d41c6f2a 100644--- a/fincept-qt/src/screens/agent_config/CreateAgentPanel.cpp+++ b/fincept-qt/src/screens/agent_config/CreateAgentPanel.cpp@@ -538,16 +538,20 @@ void CreateAgentPanel::setup_connections() {editing_id_.clear();load_saved_agents();});- connect(&svc, &services::AgentService::agent_stream_thinking, this, [this](const QString& status) {+ connect(&svc, &services::AgentService::agent_stream_thinking, this, [this](const QString& request_id, const QString& status) {+ if (request_id != pending_request_id_) return;status_label_->setText(status);});- connect(&svc, &services::AgentService::agent_stream_token, this, [this](const QString& token) {+ connect(&svc, &services::AgentService::agent_stream_token, this, [this](const QString& request_id, const QString& token) {+ if (request_id != pending_request_id_) return;QTextCursor cursor = test_result_->textCursor();cursor.movePosition(QTextCursor::End);test_result_->setTextCursor(cursor);test_result_->insertPlainText(token + " ");});connect(&svc, &services::AgentService::agent_stream_done, this, [this](services::AgentExecutionResult r) {+ if (r.request_id != pending_request_id_) return;+ pending_request_id_.clear();test_btn_->setEnabled(true);test_btn_->setText("TEST");if (r.success) {@@ -561,6 +565,8 @@ void CreateAgentPanel::setup_connections() {}});connect(&svc, &services::AgentService::agent_result, this, [this](services::AgentExecutionResult r) {+ if (r.request_id != pending_request_id_) return;+ pending_request_id_.clear();test_btn_->setEnabled(true);test_btn_->setText("TEST");if (r.success) {@@ -861,7 +867,7 @@ void CreateAgentPanel::test_agent() {test_result_->clear();status_label_->setText("Testing agent...");status_label_->setStyleSheet(QString("color:%1;font-size:10px;padding:4px 0;").arg(ui::colors::AMBER));- services::AgentService::instance().run_agent("Hello, introduce yourself briefly.", build_config_json());+ pending_request_id_ = services::AgentService::instance().run_agent_streaming("Hello, introduce yourself briefly.", build_config_json());}void CreateAgentPanel::export_json() {diff --git a/fincept-qt/src/screens/agent_config/CreateAgentPanel.h b/fincept-qt/src/screens/agent_config/CreateAgentPanel.hindex fe4bbd679..ef7610e63 100644--- a/fincept-qt/src/screens/agent_config/CreateAgentPanel.h+++ b/fincept-qt/src/screens/agent_config/CreateAgentPanel.h@@ -118,6 +118,7 @@ class CreateAgentPanel : public QWidget {QVector<AgentConfig> saved_agents_;QStringList available_tools_;QString editing_id_;+ QString pending_request_id_;bool data_loaded_ = false;};diff --git a/fincept-qt/src/screens/agent_config/PlannerViewPanel.cpp b/fincept-qt/src/screens/agent_config/PlannerViewPanel.cppindex b56f5074f..a1e785664 100644--- a/fincept-qt/src/screens/agent_config/PlannerViewPanel.cpp+++ b/fincept-qt/src/screens/agent_config/PlannerViewPanel.cpp@@ -3,10 +3,12 @@#include "core/logging/Logger.h"#include "services/agents/AgentService.h"+#include "storage/repositories/LlmProfileRepository.h"#include "ui/theme/Theme.h"#include <QApplication>#include <QClipboard>+#include <QComboBox>#include <QHBoxLayout>#include <QHeaderView>#include <QJsonArray>@@ -62,6 +64,27 @@ QWidget* PlannerViewPanel::build_templates_panel() {t->setStyleSheet(QString("color:%1;font-size:11px;font-weight:700;letter-spacing:1px;").arg(ui::colors::AMBER));vl->addWidget(t);+ // ── LLM Profile picker ───────────────────────────────────────────────────+ auto* profile_lbl = new QLabel("LLM PROFILE:");+ profile_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;letter-spacing:1px;").arg(ui::colors::TEXT_SECONDARY));+ vl->addWidget(profile_lbl);++ llm_profile_combo_ = new QComboBox;+ llm_profile_combo_->setToolTip("LLM profile used for plan generation and execution");+ llm_profile_combo_->setStyleSheet(+ QString("QComboBox{background:%1;color:%2;border:1px solid %3;padding:4px 8px;font-size:11px;}"+ "QComboBox::drop-down{border:none;}")+ .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED));+ llm_profile_combo_->addItem("Default (Global)", QString{});+ {+ const auto pr = fincept::LlmProfileRepository::instance().list_profiles();+ const auto profiles = pr.is_ok() ? pr.value() : QVector<fincept::LlmProfile>{};+ for (const auto& p : profiles)+ llm_profile_combo_->addItem(p.is_default ? p.name + " [default]" : p.name, p.id);+ }+ vl->addWidget(llm_profile_combo_);+template_list_ = new QListWidget;template_list_->addItems({"Stock Analysis Plan", "Portfolio Rebalance Plan", "Market Overview Plan","Risk Assessment Plan", "Sector Rotation Plan"});@@ -261,7 +284,9 @@ void PlannerViewPanel::setup_connections() {connect(copy_btn_, &QPushButton::clicked, this, &PlannerViewPanel::copy_result);connect(&svc, &services::AgentService::plan_created, this, [this](services::ExecutionPlan plan) {+ if (plan.request_id != pending_request_id_) return;generating_ = false;+ pending_request_id_.clear();generate_btn_->setEnabled(true);generate_btn_->setText("GENERATE PLAN");current_plan_ = plan;@@ -274,7 +299,9 @@ void PlannerViewPanel::setup_connections() {});connect(&svc, &services::AgentService::plan_executed, this, [this](services::ExecutionPlan plan) {+ if (plan.request_id != pending_request_id_) return;executing_ = false;+ pending_request_id_.clear();execute_btn_->setEnabled(true);execute_btn_->setText("EXECUTE PLAN");current_plan_ = plan;@@ -302,8 +329,12 @@ void PlannerViewPanel::setup_connections() {if (ctx == "create_plan" || ctx == "execute_plan") {generating_ = false;executing_ = false;+ pending_request_id_.clear();generate_btn_->setEnabled(true);generate_btn_->setText("GENERATE PLAN");+ execute_btn_->setEnabled(!current_plan_.steps.isEmpty());+ execute_btn_->setText("EXECUTE PLAN");+ progress_bar_->setValue(0);plan_status_->setText("ERROR");plan_status_->setStyleSheet(QString("color:%1;font-size:10px;background:%2;padding:1px 6px;border-radius:2px;")@@ -359,7 +390,13 @@ void PlannerViewPanel::generate_plan() {plan_status_->setText("GENERATING");plan_status_->setStyleSheet(QString("color:%1;font-size:10px;background:%2;padding:1px 6px;border-radius:2px;").arg(ui::colors::AMBER, ui::colors::BG_RAISED));- services::AgentService::instance().create_plan(q);+ QJsonObject cfg;+ if (llm_profile_combo_) {+ const QString pid = llm_profile_combo_->currentData().toString();+ if (!pid.isEmpty())+ cfg["llm_profile_id"] = pid;+ }+ pending_request_id_ = services::AgentService::instance().create_plan(q, cfg);}void PlannerViewPanel::execute_plan() {@@ -391,7 +428,13 @@ void PlannerViewPanel::execute_plan() {steps.append(so);}pj["steps"] = steps;- services::AgentService::instance().execute_plan(pj);+ QJsonObject cfg;+ if (llm_profile_combo_) {+ const QString pid = llm_profile_combo_->currentData().toString();+ if (!pid.isEmpty())+ cfg["llm_profile_id"] = pid;+ }+ pending_request_id_ = services::AgentService::instance().execute_plan(pj, cfg);}void PlannerViewPanel::populate_plan(const services::ExecutionPlan& plan) {diff --git a/fincept-qt/src/screens/agent_config/PlannerViewPanel.h b/fincept-qt/src/screens/agent_config/PlannerViewPanel.hindex b903f427f..dd60d1e01 100644--- a/fincept-qt/src/screens/agent_config/PlannerViewPanel.h+++ b/fincept-qt/src/screens/agent_config/PlannerViewPanel.h@@ -2,6 +2,7 @@#pragma once#include "services/agents/AgentTypes.h"+#include <QComboBox>#include <QLabel>#include <QLineEdit>#include <QListWidget>@@ -43,7 +44,8 @@ class PlannerViewPanel : public QWidget {void copy_result();// Left- QListWidget* template_list_ = nullptr;+ QComboBox* llm_profile_combo_ = nullptr;+ QListWidget* template_list_ = nullptr;QPlainTextEdit* custom_query_ = nullptr;QPushButton* generate_btn_ = nullptr;QListWidget* history_list_ = nullptr;@@ -69,9 +71,10 @@ class PlannerViewPanel : public QWidget {// Stateservices::ExecutionPlan current_plan_;QVector<services::ExecutionPlan> plan_history_;- bool generating_ = false;- bool executing_ = false;- bool data_loaded_ = false;+ bool generating_ = false;+ bool executing_ = false;+ bool data_loaded_ = false;+ QString pending_request_id_;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/agent_config/SystemViewPanel.cpp b/fincept-qt/src/screens/agent_config/SystemViewPanel.cppindex cf7f57cc1..bbf70d3f4 100644--- a/fincept-qt/src/screens/agent_config/SystemViewPanel.cpp+++ b/fincept-qt/src/screens/agent_config/SystemViewPanel.cpp@@ -368,6 +368,17 @@ void SystemViewPanel::refresh_data() {}}+ // Update cache stats immediately from in-process cache+ {+ const QJsonObject stats = svc.get_cache_stats();+ const int agent_cached = svc.cached_agent_count();+ const int resp_cached = stats["response_cache_size"].toInt(0);+ const int total = agent_cached + resp_cached;+ cache_count_->setText(QString::number(total));+ cache_count_->setToolTip(+ QString("Agents: %1 | Responses: %2").arg(agent_cached).arg(resp_cached));+ }+// Trigger async loadssvc.get_system_info();svc.list_tools();diff --git a/fincept-qt/src/screens/agent_config/TeamsViewPanel.cpp b/fincept-qt/src/screens/agent_config/TeamsViewPanel.cppindex 6e8b49dc9..c01318f45 100644--- a/fincept-qt/src/screens/agent_config/TeamsViewPanel.cpp+++ b/fincept-qt/src/screens/agent_config/TeamsViewPanel.cpp@@ -271,9 +271,9 @@ void TeamsViewPanel::setup_connections() {populate_available_agents(agents);});connect(&svc, &services::AgentService::agent_result, this, [this](services::AgentExecutionResult r) {- if (!executing_)- return;+ if (r.request_id != pending_request_id_) return;executing_ = false;+ pending_request_id_.clear();run_btn_->setEnabled(true);run_btn_->setText("RUN TEAM");if (r.success) {@@ -289,13 +289,13 @@ void TeamsViewPanel::setup_connections() {}});- connect(&svc, &services::AgentService::agent_stream_thinking, this, [this](const QString& status) {- if (!executing_) return;+ connect(&svc, &services::AgentService::agent_stream_thinking, this, [this](const QString& request_id, const QString& status) {+ if (request_id != pending_request_id_) return;exec_status_->setText(status);});- connect(&svc, &services::AgentService::agent_stream_token, this, [this](const QString& token) {- if (!executing_) return;+ connect(&svc, &services::AgentService::agent_stream_token, this, [this](const QString& request_id, const QString& token) {+ if (request_id != pending_request_id_) return;QTextCursor cursor = result_display_->textCursor();cursor.movePosition(QTextCursor::End);result_display_->setTextCursor(cursor);@@ -303,8 +303,9 @@ void TeamsViewPanel::setup_connections() {});connect(&svc, &services::AgentService::agent_stream_done, this, [this](services::AgentExecutionResult r) {- if (!executing_) return;+ if (r.request_id != pending_request_id_) return;executing_ = false;+ pending_request_id_.clear();run_btn_->setEnabled(true);run_btn_->setText("RUN TEAM");if (r.success) {@@ -326,6 +327,20 @@ void TeamsViewPanel::setup_connections() {this, &TeamsViewPanel::refresh_team_llm_label);load_team_profile_combo();+ // Reset executing_ if Python crashes before emitting agent_result/stream_done+ connect(&svc, &services::AgentService::error_occurred, this,+ [this](const QString&, const QString& msg) {+ if (!executing_) return;+ executing_ = false;+ pending_request_id_.clear();+ run_btn_->setEnabled(true);+ run_btn_->setText("RUN TEAM");+ exec_status_->setText("ERROR");+ exec_status_->setStyleSheet(+ QString("color:%1;font-size:10px;padding:2px 0;").arg(ui::colors::NEGATIVE));+ log_display_->append("[ERROR] " + msg);+ });+connect(run_btn_, &QPushButton::clicked, this, &TeamsViewPanel::run_team);connect(available_list_, &QListWidget::itemDoubleClicked, this, [this]() {int row = available_list_->currentRow();@@ -504,23 +519,37 @@ void TeamsViewPanel::run_team() {}member["model"] = mc;- if (m.config.contains("tools"))+ // Use agent's own tools if set; otherwise fall back to TOOLS-tab selection+ if (m.config.contains("tools") && !m.config["tools"].toArray().isEmpty()) {member["tools"] = m.config["tools"];+ } else if (!selected_tools_.isEmpty()) {+ QJsonArray ta;+ for (const auto& t : selected_tools_) ta.append(t);+ member["tools"] = ta;+ }if (m.config.contains("instructions"))member["instructions"] = m.config["instructions"];members.append(member);log_display_->append(QString(" [MEMBER] %1").arg(m.name));}tc["members"] = members;- services::AgentService::instance().run_team(q, tc);+ pending_request_id_ = services::AgentService::instance().run_team(q, tc);+}++void TeamsViewPanel::apply_tools_selection(const QStringList& tools) {+ selected_tools_ = tools;+ log_display_->append(QString("[TOOLS] %1 tool(s) selected from TOOLS tab").arg(tools.size()));}void TeamsViewPanel::showEvent(QShowEvent* event) {QWidget::showEvent(event);if (!data_loaded_) {data_loaded_ = true;- if (all_agents_.isEmpty())- services::AgentService::instance().discover_agents();+ // AgentConfigScreen fires discover_agents() on first show and on every+ // config_saved/deleted — TeamsViewPanel just listens to agents_discovered.+ // Do NOT call discover_agents() here to avoid a duplicate Python spawn.+ if (!all_agents_.isEmpty())+ populate_available_agents(all_agents_);}}diff --git a/fincept-qt/src/screens/agent_config/TeamsViewPanel.h b/fincept-qt/src/screens/agent_config/TeamsViewPanel.hindex 61f288249..946fdd73c 100644--- a/fincept-qt/src/screens/agent_config/TeamsViewPanel.h+++ b/fincept-qt/src/screens/agent_config/TeamsViewPanel.h@@ -27,6 +27,7 @@ class TeamsViewPanel : public QWidget {public slots:void add_agent_from_panel(const services::AgentInfo& agent);+ void apply_tools_selection(const QStringList& tools);private:void build_ui();@@ -67,8 +68,10 @@ class TeamsViewPanel : public QWidget {// StateQVector<services::AgentInfo> all_agents_;QVector<services::AgentInfo> team_members_;- bool executing_ = false;- bool data_loaded_ = false;+ QStringList selected_tools_; // synced from TOOLS tab+ bool executing_ = false;+ bool data_loaded_ = false;+ QString pending_request_id_;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/agent_config/WorkflowsViewPanel.cpp b/fincept-qt/src/screens/agent_config/WorkflowsViewPanel.cppindex b8c893240..2d0d4eba5 100644--- a/fincept-qt/src/screens/agent_config/WorkflowsViewPanel.cpp+++ b/fincept-qt/src/screens/agent_config/WorkflowsViewPanel.cpp@@ -3,8 +3,10 @@#include "core/logging/Logger.h"#include "services/agents/AgentService.h"+#include "storage/repositories/LlmProfileRepository.h"#include "ui/theme/Theme.h"+#include <QComboBox>#include <QFrame>#include <QGridLayout>#include <QHBoxLayout>@@ -97,6 +99,28 @@ QWidget* WorkflowsViewPanel::build_workflow_cards() {title->setStyleSheet(QString("color:%1;font-size:13px;font-weight:700;letter-spacing:2px;").arg(ui::colors::AMBER));vl->addWidget(title);+ // ── LLM Profile picker ───────────────────────────────────────────────────+ auto* profile_row = new QHBoxLayout;+ auto* profile_lbl = new QLabel("LLM PROFILE:");+ profile_lbl->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;letter-spacing:1px;")+ .arg(ui::colors::TEXT_SECONDARY));+ llm_profile_combo_ = new QComboBox;+ llm_profile_combo_->setToolTip("LLM profile used by all workflows on this tab");+ llm_profile_combo_->setStyleSheet(+ QString("QComboBox{background:%1;color:%2;border:1px solid %3;padding:4px 8px;font-size:11px;}"+ "QComboBox::drop-down{border:none;}")+ .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED));+ // Populate+ llm_profile_combo_->addItem("Default (Global)", QString{});+ const auto pr = fincept::LlmProfileRepository::instance().list_profiles();+ const auto profiles = pr.is_ok() ? pr.value() : QVector<fincept::LlmProfile>{};+ for (const auto& p : profiles)+ llm_profile_combo_->addItem(p.is_default ? p.name + " [default]" : p.name, p.id);++ profile_row->addWidget(profile_lbl);+ profile_row->addWidget(llm_profile_combo_, 1);+ vl->addLayout(profile_row);+// ── Stock Analysis ───────────────────────────────────────────────────────auto* stock_card = new QFrame;stock_card->setStyleSheet(QString("QFrame { background:%1;border:1px solid %2;padding:12px; }")@@ -228,10 +252,9 @@ void WorkflowsViewPanel::setup_connections() {auto& svc = services::AgentService::instance();connect(&svc, &services::AgentService::agent_result, this, [this](services::AgentExecutionResult r) {- if (!executing_)- return;+ if (r.request_id != pending_request_id_) return;executing_ = false;-+ pending_request_id_.clear();if (r.success) {result_display_->setPlainText(r.response);result_status_->setText(QString("Completed in %1ms").arg(r.execution_time_ms));@@ -242,6 +265,17 @@ void WorkflowsViewPanel::setup_connections() {result_status_->setStyleSheet(QString("color:%1;font-size:10px;padding:2px 0;").arg(ui::colors::NEGATIVE));}});++ connect(&svc, &services::AgentService::error_occurred, this,+ [this](const QString&, const QString& msg) {+ if (!executing_) return;+ executing_ = false;+ pending_request_id_.clear();+ result_display_->setPlainText("Error: " + msg);+ result_status_->setText("ERROR");+ result_status_->setStyleSheet(+ QString("color:%1;font-size:10px;padding:2px 0;").arg(ui::colors::NEGATIVE));+ });}// ── Run workflow ─────────────────────────────────────────────────────────────@@ -256,14 +290,18 @@ void WorkflowsViewPanel::run_workflow(const QString& type, const QJsonObject& paresult_status_->setText("Executing...");result_status_->setStyleSheet(QString("color:%1;font-size:10px;padding:2px 0;").arg(ui::colors::AMBER));- services::AgentService::instance().run_workflow(type, params);+ QJsonObject p = params;+ const QString profile_id = llm_profile_combo_ ? llm_profile_combo_->currentData().toString() : QString{};+ if (!profile_id.isEmpty())+ p["llm_profile_id"] = profile_id;++ pending_request_id_ = services::AgentService::instance().run_workflow(type, p);}void WorkflowsViewPanel::showEvent(QShowEvent* event) {QWidget::showEvent(event);if (!data_loaded_) {data_loaded_ = true;- services::AgentService::instance().discover_agents();}}diff --git a/fincept-qt/src/screens/agent_config/WorkflowsViewPanel.h b/fincept-qt/src/screens/agent_config/WorkflowsViewPanel.hindex 57ee829b0..2e5e1d1b8 100644--- a/fincept-qt/src/screens/agent_config/WorkflowsViewPanel.h+++ b/fincept-qt/src/screens/agent_config/WorkflowsViewPanel.h@@ -2,6 +2,7 @@#pragma once#include "services/agents/AgentTypes.h"+#include <QComboBox>#include <QLabel>#include <QLineEdit>#include <QPushButton>@@ -30,15 +31,17 @@ class WorkflowsViewPanel : public QWidget {const QString& action_text, QVBoxLayout* parent_layout);// Workflow inputs- QLineEdit* symbol_input_ = nullptr;+ QLineEdit* symbol_input_ = nullptr;+ QComboBox* llm_profile_combo_ = nullptr;// ResultsQTextEdit* result_display_ = nullptr;QLabel* result_status_ = nullptr;QLabel* workflow_title_ = nullptr;- bool executing_ = false;- bool data_loaded_ = false;+ bool executing_ = false;+ bool data_loaded_ = false;+ QString pending_request_id_;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cppindex d92a15918..aa7c584b8 100644--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp@@ -2006,7 +2006,7 @@ void QuantModulePanel::on_result(const QString& module_id, const QString& commanauto* lbl = new QLabel(QString("Prediction: %1").arg(pred.isNull() ? "N/A" : QString::number(pred.toDouble(), 'f', 6)), this);lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; font-weight:700;")- .arg(module_.color.name()).arg(ui::fonts::NORMAL).arg(ui::fonts::DATA_FAMILY));+ .arg(module_.color.name()).arg(ui::fonts::SMALL).arg(ui::fonts::DATA_FAMILY));results_layout_->addWidget(lbl);status_label_->setText("Prediction ready");return;diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp b/fincept-qt/src/screens/backtesting/BacktestingScreen.cppindex 86ec0714e..3796c34c3 100644--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp@@ -80,8 +80,8 @@ static void clear_layout(QLayout* layout) {BacktestingScreen::BacktestingScreen(QWidget* parent) : QWidget(parent) {providers_ = all_providers();- commands_ = all_commands();- strategies_ = default_strategies();+ commands_ = all_commands();+ // strategies_ starts empty — populated dynamically per provider via load_strategies()build_ui();connect_service();LOG_INFO("Backtesting", "Screen constructed");@@ -102,8 +102,9 @@ void BacktestingScreen::hideEvent(QHideEvent* e) {void BacktestingScreen::connect_service() {auto& svc = BacktestingService::instance();- connect(&svc, &BacktestingService::result_ready, this, &BacktestingScreen::on_result);- connect(&svc, &BacktestingService::error_occurred, this, &BacktestingScreen::on_error);+ connect(&svc, &BacktestingService::result_ready, this, &BacktestingScreen::on_result);+ connect(&svc, &BacktestingService::error_occurred, this, &BacktestingScreen::on_error);+ connect(&svc, &BacktestingService::command_options_loaded, this, &BacktestingScreen::on_command_options_loaded);}void BacktestingScreen::build_ui() {@@ -254,8 +255,7 @@ QWidget* BacktestingScreen::build_left_panel() {vl->addWidget(cat_lbl);strategy_category_combo_ = new QComboBox(content);strategy_category_combo_->setStyleSheet(combo_style);- for (const auto& cat : strategy_categories())- strategy_category_combo_->addItem(cat);+ // Populated dynamically via on_result("get_strategies")connect(strategy_category_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,[this](int) { populate_strategies(); });vl->addWidget(strategy_category_combo_);@@ -713,8 +713,7 @@ QWidget* BacktestingScreen::build_right_panel() {pl->addWidget(il);indicator_combo_ = new QComboBox(page);indicator_combo_->setStyleSheet(combo_style);- for (const auto& ind : all_indicators())- indicator_combo_->addItem(ind.label, ind.id);+ // Populated dynamically via on_result("get_indicators")pl->addWidget(indicator_combo_);pl->addStretch();@@ -736,8 +735,7 @@ QWidget* BacktestingScreen::build_right_panel() {pl->addWidget(isl);ind_signal_indicator_combo_ = new QComboBox(page);ind_signal_indicator_combo_->setStyleSheet(combo_style);- for (const auto& ind : all_indicators())- ind_signal_indicator_combo_->addItem(ind.label, ind.id);+ // Populated dynamically via on_result("get_indicators")pl->addWidget(ind_signal_indicator_combo_);auto* ml = new QLabel("SIGNAL MODE", page);@@ -951,7 +949,18 @@ void BacktestingScreen::on_provider_changed(int index) {active_provider_ = index;update_provider_buttons();update_command_buttons();- populate_strategies();++ // Clear stale strategies and show loading state+ strategies_.clear();+ strategy_category_combo_->clear();+ strategy_category_combo_->addItem("Loading...");+ strategy_combo_->clear();++ const auto& slug = providers_[index].slug;+ auto& svc = BacktestingService::instance();+ svc.load_strategies(slug);+ svc.load_command_options(slug);+ svc.execute(slug, "get_indicators", {});}void BacktestingScreen::update_provider_buttons() {@@ -1131,11 +1140,12 @@ QJsonObject BacktestingScreen::gather_args() {if (take_profit_spin_->value() > 0)args["takeProfit"] = take_profit_spin_->value() / 100.0;- // Strategy+ // Strategy — type = ID (used by Python), name = display nameQJsonObject strategy;- strategy["name"] = strategy_combo_->currentData().toString();- strategy["type"] = strategy_category_combo_->currentText();- strategy["params"] = gather_strategy_params();+ strategy["type"] = strategy_combo_->currentData().toString(); // strategy ID+ strategy["name"] = strategy_combo_->currentText(); // display name+ strategy["category"] = strategy_category_combo_->currentText();+ strategy["params"] = gather_strategy_params();args["strategy"] = strategy;}@@ -1429,6 +1439,42 @@ void BacktestingScreen::display_error(const QString& msg) {// ── Signal handlers ──────────────────────────────────────────────────────────void BacktestingScreen::on_result(const QString& provider, const QString& command, const QJsonObject& data) {+ // Route background metadata commands — don't touch run state or results UI+ if (command == "get_strategies") {+ // Only apply if result is for the currently-active provider+ if (provider != providers_[active_provider_].slug)+ return;+ strategies_ = services::backtest::strategies_from_json(data);+ auto cats = services::backtest::categories_from_strategies(strategies_);+ strategy_category_combo_->blockSignals(true);+ strategy_category_combo_->clear();+ for (const auto& cat : cats)+ strategy_category_combo_->addItem(cat);+ strategy_category_combo_->blockSignals(false);+ populate_strategies();+ LOG_INFO("Backtesting", QString("[%1] Loaded %2 strategies").arg(provider).arg(strategies_.size()));+ return;+ }+ if (command == "get_indicators") {+ if (provider != providers_[active_provider_].slug)+ return;+ // Populate both indicator combos from {indicators:{Cat:[{id,name}]}}+ auto ind_obj = data.value("indicators").toObject();+ indicator_combo_->clear();+ ind_signal_indicator_combo_->clear();+ for (const auto& cat : ind_obj.keys()) {+ for (const auto& iv : ind_obj.value(cat).toArray()) {+ auto o = iv.toObject();+ auto id = o.value("id").toString();+ auto name = o.value("name").toString(id);+ indicator_combo_->addItem(name, id);+ ind_signal_indicator_combo_->addItem(name, id);+ }+ }+ return;+ }++ // Regular command result — update run state and displayis_running_ = false;run_button_->setEnabled(true);status_label_->setText("READY");@@ -1445,6 +1491,30 @@ void BacktestingScreen::on_result(const QString& provider, const QString& commanLOG_INFO("Backtesting", QString("[%1/%2] Complete").arg(provider, command));}+void BacktestingScreen::on_command_options_loaded(const QString& provider, const QJsonObject& options) {+ if (provider != providers_[active_provider_].slug)+ return;++ auto repopulate = [](QComboBox* combo, const QJsonArray& arr) {+ if (arr.isEmpty()) return;+ combo->clear();+ for (const auto& v : arr)+ combo->addItem(v.toString());+ combo->setCurrentIndex(0);+ };++ repopulate(pos_sizing_combo_, options.value("position_sizing_methods").toArray());+ repopulate(opt_objective_combo_, options.value("optimize_objectives").toArray());+ repopulate(opt_method_combo_, options.value("optimize_methods").toArray());+ repopulate(labels_type_combo_, options.value("label_types").toArray());+ repopulate(splitter_type_combo_, options.value("splitter_types").toArray());+ repopulate(signal_gen_combo_, options.value("signal_generators").toArray());+ repopulate(ind_signal_mode_combo_, options.value("indicator_signal_modes").toArray());+ repopulate(returns_type_combo_, options.value("returns_analysis_types").toArray());++ LOG_INFO("Backtesting", QString("[%1] Command options loaded").arg(provider));+}+void BacktestingScreen::on_error(const QString& context, const QString& message) {is_running_ = false;run_button_->setEnabled(true);diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.h b/fincept-qt/src/screens/backtesting/BacktestingScreen.hindex 1b169bbb2..e533c5724 100644--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.h+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.h@@ -39,6 +39,7 @@ class BacktestingScreen : public QWidget {void on_run();void on_result(const QString& provider, const QString& command, const QJsonObject& data);void on_error(const QString& context, const QString& message);+ void on_command_options_loaded(const QString& provider, const QJsonObject& options);private:void build_ui();diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp b/fincept-qt/src/screens/code_editor/CodeEditorScreen.cppindex 631dd2fd5..9dd0bacf4 100644--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp@@ -1,4 +1,6 @@// src/screens/code_editor/CodeEditorScreen.cpp+// Bloomberg-style Python Colab — Obsidian design system implementation.+// Responsive cells, markdown rendering, keyboard shortcuts, collapsible output.#include "screens/code_editor/CodeEditorScreen.h"#include "core/logging/Logger.h"@@ -6,15 +8,25 @@#include "services/file_manager/FileManagerService.h"#include "ui/theme/Theme.h"+#include <QAbstractTextDocumentLayout>+#include <QApplication>#include <QFileDialog>+#include <QFileInfo>#include <QHBoxLayout>#include <QJsonArray>#include <QJsonDocument>#include <QJsonObject>+#include <QKeyEvent>#include <QLabel>+#include <QListWidget>+#include <QMouseEvent>#include <QPushButton>#include <QScrollArea>+#include <QScrollBar>+#include <QSplitter>+#include <QTextBrowser>#include <QTextEdit>+#include <QTimer>#include <QUuid>#include <QVBoxLayout>@@ -22,118 +34,287 @@ namespace fincept::screens {using namespace fincept::ui;-// Colors matching the Tauri version's FINCEPT theme-static const QString kOrange = "#FF8800";-static const QString kGreen = "#00D66F";-static const QString kRed = "#FF3B3B";-static const QString kYellow = "#FFD700";-static const QString kBlue = "#0088FF";-static const QString kPurple = "#9D4EDD";-static const QString kCyan = "#00E5FF";+// ═════════════════════════════════════════════════════════════════════════════+// CodeTextEdit — editor with keyboard shortcuts+// ═════════════════════════════════════════════════════════════════════════════++CodeTextEdit::CodeTextEdit(QWidget* parent) : QTextEdit(parent) {}++void CodeTextEdit::keyPressEvent(QKeyEvent* event) {+ if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {+ if (event->modifiers() & Qt::ControlModifier) {+ emit run_shortcut();+ return;+ }+ if (event->modifiers() & Qt::ShiftModifier) {+ emit run_and_next();+ return;+ }+ }+ // Tab inserts 4 spaces+ if (event->key() == Qt::Key_Tab && !(event->modifiers() & Qt::ShiftModifier)) {+ insertPlainText(" ");+ return;+ }+ QTextEdit::keyPressEvent(event);+}// ═════════════════════════════════════════════════════════════════════════════// CellWidget// ═════════════════════════════════════════════════════════════════════════════-CellWidget::CellWidget(const NotebookCell& cell, QWidget* parent)- : QWidget(parent), cell_id_(cell.id), cell_type_(cell.cell_type), execution_count_(cell.execution_count) {+CellWidget::CellWidget(const NotebookCell& cell, int index, QWidget* parent)+ : QWidget(parent), cell_id_(cell.id), cell_type_(cell.cell_type),+ execution_count_(cell.execution_count), index_(index) {build_ui();set_cell_data(cell);}void CellWidget::build_ui() {auto* root = new QVBoxLayout(this);- root->setContentsMargins(0, 4, 0, 4);+ root->setContentsMargins(0, 2, 0, 2);root->setSpacing(0);- // Header bar- auto* header = new QWidget(this);- header->setFixedHeight(26);- auto* hhl = new QHBoxLayout(header);- hhl->setContentsMargins(12, 0, 12, 0);- hhl->setSpacing(6);-- header_label_ = new QLabel("In [ ]:", header);- header_label_->setFixedWidth(70);- header_label_->setStyleSheet(- QString("color:%1; font-family:%2; font-size:10px; font-weight:700;").arg(kOrange, fonts::DATA_FAMILY));- hhl->addWidget(header_label_);-- type_badge_ = new QLabel("PYTHON", header);- type_badge_->setStyleSheet(QString("color:%1; font-family:%2; font-size:9px; font-weight:700;"- " background:%3; padding:1px 6px;")- .arg(colors::TEXT_PRIMARY, fonts::DATA_FAMILY, kBlue));- hhl->addWidget(type_badge_);-- hhl->addStretch();-- // Action buttons (compact)- auto make_btn = [&](const QString& text, const QString& color) -> QPushButton* {- auto* btn = new QPushButton(text, header);+ // ── Main cell row: [gutter] [editor] ──+ auto* cell_row = new QWidget(this);+ auto* row_layout = new QHBoxLayout(cell_row);+ row_layout->setContentsMargins(0, 0, 0, 0);+ row_layout->setSpacing(0);++ // ── Gutter ──+ gutter_ = new QWidget(cell_row);+ gutter_->setFixedWidth(56);+ gutter_->setStyleSheet(+ QString("background:%1;").arg(colors::BG_RAISED));+ auto* gutter_layout = new QVBoxLayout(gutter_);+ gutter_layout->setContentsMargins(0, 4, 6, 2);+ gutter_layout->setSpacing(2);+ gutter_layout->setAlignment(Qt::AlignTop | Qt::AlignRight);++ gutter_number_ = new QLabel("[ ]", gutter_);+ gutter_number_->setAlignment(Qt::AlignRight | Qt::AlignTop);+ gutter_number_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:%3px; font-weight:700; background:transparent;")+ .arg(colors::TEXT_TERTIARY, fonts::DATA_FAMILY)+ .arg(fonts::TINY));+ gutter_layout->addWidget(gutter_number_);++ gutter_type_ = new QLabel("PY", gutter_);+ gutter_type_->setAlignment(Qt::AlignRight);+ gutter_type_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:10px; font-weight:600;"+ " letter-spacing:0.5px; background:transparent;")+ .arg(colors::TEXT_DIM, fonts::DATA_FAMILY));+ gutter_layout->addWidget(gutter_type_);+ gutter_layout->addStretch();++ row_layout->addWidget(gutter_);++ // ── Editor container ──+ editor_container_ = new QWidget(cell_row);+ auto* editor_vbox = new QVBoxLayout(editor_container_);+ editor_vbox->setContentsMargins(0, 0, 0, 0);+ editor_vbox->setSpacing(0);++ // Toolbar — always occupies 24px to prevent layout shift; buttons hide/show+ toolbar_ = new QWidget(editor_container_);+ toolbar_->setFixedHeight(24);+ toolbar_->setStyleSheet(+ QString("background:%1;").arg(colors::BG_RAISED));+ auto* tb_layout = new QHBoxLayout(toolbar_);+ tb_layout->setContentsMargins(8, 0, 8, 0);+ tb_layout->setSpacing(2);++ auto make_tool_btn = [&](const QString& text, const QString& fg_color) -> QPushButton* {+ auto* btn = new QPushButton(text, toolbar_);btn->setFixedHeight(20);- btn->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:1px solid %2;"- " font-family:%3; font-size:9px; padding:0 6px; }"- "QPushButton:hover { background:%4; }")- .arg(color, colors::BORDER_DIM, fonts::DATA_FAMILY, colors::BG_HOVER));+ btn->setCursor(Qt::PointingHandCursor);+ btn->setVisible(false); // hidden until hover+ btn->setStyleSheet(+ QString("QPushButton { background:transparent; color:%1; border:none;"+ " font-family:%2; font-size:%3px; font-weight:600; padding:0 8px;"+ " letter-spacing:0.5px; }"+ "QPushButton:hover { background:%4; color:%5; }")+ .arg(fg_color, fonts::DATA_FAMILY)+ .arg(fonts::TINY)+ .arg(colors::BG_HOVER, colors::TEXT_PRIMARY));return btn;};- auto* run_btn = make_btn("RUN", kGreen);+ auto* run_btn = make_tool_btn("RUN", colors::POSITIVE);connect(run_btn, &QPushButton::clicked, this, [this]() { emit run_requested(cell_id_); });- hhl->addWidget(run_btn);+ tb_layout->addWidget(run_btn);- auto* type_btn = make_btn("TYPE", kCyan);+ auto* type_btn = make_tool_btn("TYPE", colors::CYAN);connect(type_btn, &QPushButton::clicked, this, [this]() { emit toggle_type_requested(cell_id_); });- hhl->addWidget(type_btn);+ tb_layout->addWidget(type_btn);- auto* up_btn = make_btn("UP", colors::TEXT_SECONDARY);+ auto* up_btn = make_tool_btn("UP", colors::TEXT_SECONDARY);connect(up_btn, &QPushButton::clicked, this, [this]() { emit move_up_requested(cell_id_); });- hhl->addWidget(up_btn);+ tb_layout->addWidget(up_btn);- auto* dn_btn = make_btn("DN", colors::TEXT_SECONDARY);+ auto* dn_btn = make_tool_btn("DN", colors::TEXT_SECONDARY);connect(dn_btn, &QPushButton::clicked, this, [this]() { emit move_down_requested(cell_id_); });- hhl->addWidget(dn_btn);+ tb_layout->addWidget(dn_btn);++ tb_layout->addStretch();- auto* del_btn = make_btn("DEL", kRed);+ auto* del_btn = make_tool_btn("DEL", colors::NEGATIVE);connect(del_btn, &QPushButton::clicked, this, [this]() { emit delete_requested(cell_id_); });- hhl->addWidget(del_btn);+ tb_layout->addWidget(del_btn);- header->setStyleSheet(- QString("background:%1; border-top:1px solid %2;").arg(colors::BG_RAISED, colors::BORDER_DIM));- root->addWidget(header);+ editor_vbox->addWidget(toolbar_);- // Editor- editor_ = new QTextEdit(this);- editor_->setMinimumHeight(60);- editor_->setMaximumHeight(300);+ // ── Code editor ──+ editor_ = new CodeTextEdit(editor_container_);editor_->setAcceptRichText(false);- editor_->setStyleSheet(QString("QTextEdit { background:#0F0F0F; color:%1; border:none; border-left:3px solid %2;"- " font-family:%3; font-size:12px; padding:8px; }")- .arg(colors::TEXT_PRIMARY, kOrange, fonts::DATA_FAMILY));-- // Ctrl+Enter to run- connect(editor_, &QTextEdit::textChanged, this, [this]() {- // Auto-resize editor height- QTextDocument* doc = editor_->document();- int h = static_cast<int>(doc->size().height()) + 16;- editor_->setFixedHeight(qBound(60, h, 300));+ editor_->setTabStopDistance(28);+ editor_->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);+ editor_->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);+ editor_->setLineWrapMode(QTextEdit::NoWrap);+ editor_->setStyleSheet(+ QString("QTextEdit { background:%1; color:%2; border:none;"+ " font-family:%3; font-size:%4px; padding:2px 6px;"+ " selection-background-color:%5; }"+ "QScrollBar:vertical { background:%1; width:5px; }"+ "QScrollBar::handle:vertical { background:%6; min-height:20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }"+ "QScrollBar:horizontal { background:%1; height:5px; }"+ "QScrollBar::handle:horizontal { background:%6; min-width:20px; }"+ "QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal { width:0; }")+ .arg(colors::BG_SURFACE, colors::TEXT_PRIMARY, fonts::DATA_FAMILY)+ .arg(fonts::DATA)+ .arg(colors::AMBER_DIM, colors::BORDER_BRIGHT));+ editor_->document()->setDocumentMargin(2);++ // Keyboard shortcuts+ connect(editor_, &CodeTextEdit::run_shortcut, this, [this]() { emit run_requested(cell_id_); });+ connect(editor_, &CodeTextEdit::run_and_next, this, [this]() { emit run_and_advance(cell_id_); });++ // Responsive height on every content change+ connect(editor_->document()->documentLayout(), &QAbstractTextDocumentLayout::documentSizeChanged,+ this, [this](const QSizeF&) { adjust_editor_height(); });++ editor_vbox->addWidget(editor_);++ // ── Markdown preview (for MD cells, shown when not editing) ──+ md_preview_ = new QTextBrowser(editor_container_);+ md_preview_->setOpenExternalLinks(true);+ md_preview_->setReadOnly(true);+ md_preview_->setVisible(false);+ md_preview_->setStyleSheet(+ QString("QTextBrowser { background:%1; color:%2; border:none;"+ " font-family:%3; font-size:%4px; padding:10px 12px; }"+ "QScrollBar:vertical { background:%1; width:5px; }"+ "QScrollBar::handle:vertical { background:%5; min-height:20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }")+ .arg(colors::BG_SURFACE, colors::TEXT_PRIMARY, fonts::DATA_FAMILY)+ .arg(fonts::DATA)+ .arg(colors::BORDER_BRIGHT));++ // Click on preview to edit+ md_preview_->installEventFilter(this);++ editor_vbox->addWidget(md_preview_);++ row_layout->addWidget(editor_container_, 1);+ root->addWidget(cell_row);++ // ── Output area ──+ auto* output_row = new QWidget(this);+ auto* output_row_layout = new QHBoxLayout(output_row);+ output_row_layout->setContentsMargins(0, 0, 0, 0);+ output_row_layout->setSpacing(0);++ auto* output_gutter = new QWidget(output_row);+ output_gutter->setFixedWidth(56);+ output_row_layout->addWidget(output_gutter);++ output_area_ = new QWidget(output_row);+ auto* output_vbox = new QVBoxLayout(output_area_);+ output_vbox->setContentsMargins(0, 0, 0, 0);+ output_vbox->setSpacing(0);++ // Output header with collapse toggle+ output_toggle_ = new QPushButton("OUTPUT", output_area_);+ output_toggle_->setFixedHeight(22);+ output_toggle_->setCursor(Qt::PointingHandCursor);+ output_toggle_->setStyleSheet(+ QString("QPushButton { background:%1; color:%2; border:none; border-left:3px solid %3;"+ " font-family:%4; font-size:10px; font-weight:700; letter-spacing:0.5px;"+ " padding:0 10px; text-align:left; }"+ "QPushButton:hover { background:%5; }")+ .arg(colors::BG_RAISED, colors::POSITIVE, colors::BORDER_DIM,+ fonts::DATA_FAMILY, colors::BG_HOVER));+ output_toggle_->setVisible(false);+ connect(output_toggle_, &QPushButton::clicked, this, [this]() {+ output_collapsed_ = !output_collapsed_;+ output_content_->setVisible(!output_collapsed_);+ output_toggle_->setText(output_collapsed_ ? "OUTPUT [collapsed]" : "OUTPUT");});+ output_vbox->addWidget(output_toggle_);++ // Scrollable output content+ output_content_ = new QWidget(output_area_);+ output_content_layout_ = new QVBoxLayout(output_content_);+ output_content_layout_->setContentsMargins(12, 6, 12, 8);+ output_content_layout_->setSpacing(4);+ output_content_->setStyleSheet(+ QString("background:%1; border-left:3px solid %2;")+ .arg(colors::BG_BASE, colors::BORDER_DIM));+ output_content_->setVisible(false);+ output_vbox->addWidget(output_content_);- root->addWidget(editor_);-- // Output area- output_area_ = new QWidget(this);- output_layout_ = new QVBoxLayout(output_area_);- output_layout_->setContentsMargins(12, 4, 12, 4);- output_layout_->setSpacing(4);- output_area_->setStyleSheet(QString("background:%1;").arg(colors::BG_BASE));output_area_->setVisible(false);- root->addWidget(output_area_);-- // Click to select+ output_row_layout->addWidget(output_area_, 1);+ root->addWidget(output_row);++ // ── Insert-below: always-visible dim "+" centered between cells ──+ insert_hint_ = new QWidget(this);+ insert_hint_->setFixedHeight(20);+ auto* insert_layout = new QHBoxLayout(insert_hint_);+ insert_layout->setContentsMargins(56, 0, 0, 0);+ insert_layout->setSpacing(0);++ auto* insert_line = new QWidget(insert_hint_);+ insert_line->setFixedHeight(1);+ insert_line->setStyleSheet(QString("background:%1;").arg(colors::BORDER_DIM));+ insert_layout->addWidget(insert_line, 1);++ auto* insert_btn = new QPushButton("+", insert_hint_);+ insert_btn->setFixedSize(32, 18);+ insert_btn->setCursor(Qt::PointingHandCursor);+ insert_btn->setObjectName("insertBtn");+ insert_btn->setStyleSheet(+ QString("QPushButton { color:%1; font-family:%2; font-size:12px; font-weight:700;"+ " background:%3; border:1px solid %4; }"+ "QPushButton:hover { background:%5; color:%6; border-color:%5; }")+ .arg(colors::TEXT_DIM, fonts::DATA_FAMILY,+ colors::BG_SURFACE, colors::BORDER_DIM,+ colors::AMBER_DIM, colors::AMBER));+ connect(insert_btn, &QPushButton::clicked, this, [this]() { emit insert_below_requested(cell_id_); });+ insert_layout->addWidget(insert_btn);++ auto* insert_line2 = new QWidget(insert_hint_);+ insert_line2->setFixedHeight(1);+ insert_line2->setStyleSheet(QString("background:%1;").arg(colors::BORDER_DIM));+ insert_layout->addWidget(insert_line2, 1);++ root->addWidget(insert_hint_);setMouseTracking(true);}+void CellWidget::adjust_editor_height() {+ if (!editor_->isVisible())+ return;+ // Exact content height from the layout engine + CSS padding (2+2)+ int doc_h = static_cast<int>(editor_->document()->size().height());+ int target = doc_h + 6;+ int max_h = (cell_type_ == "code") ? 600 : 300;+ int h = qBound(28, target, max_h);+ editor_->setFixedHeight(h);+}+void CellWidget::set_cell_data(const NotebookCell& cell) {cell_id_ = cell.id;cell_type_ = cell.cell_type;@@ -144,7 +325,22 @@ void CellWidget::set_cell_data(const NotebookCell& cell) {editor_->setPlainText(cell.source);editor_->blockSignals(false);- update_header();+ // Force document layout so height measurement is accurate+ editor_->document()->adjustSize();+ adjust_editor_height();+ update_gutter();++ // For markdown cells, show rendered preview by default+ if (cell_type_ == "markdown" && !cell.source.trimmed().isEmpty()) {+ md_editing_ = false;+ editor_->setVisible(false);+ md_preview_->setVisible(true);+ render_markdown();+ } else {+ md_editing_ = true;+ editor_->setVisible(true);+ md_preview_->setVisible(false);+ }if (!cell.outputs.isEmpty()) {set_outputs(cell.outputs, cell.execution_count);@@ -162,17 +358,16 @@ NotebookCell CellWidget::cell_data() const {void CellWidget::set_running(bool running) {running_ = running;- update_header();+ update_gutter();}void CellWidget::set_outputs(const QVector<CellOutput>& outputs, int exec_count) {execution_count_ = exec_count;- update_header();- render_outputs();+ update_gutter();- // Clear old output widgets- while (output_layout_->count() > 0) {- auto* item = output_layout_->takeAt(0);+ // Clear old output content+ while (output_content_layout_->count() > 0) {+ auto* item = output_content_layout_->takeAt(0);if (item->widget())item->widget()->deleteLater();delete item;@@ -180,86 +375,388 @@ void CellWidget::set_outputs(const QVector<CellOutput>& outputs, int exec_count)if (outputs.isEmpty()) {output_area_->setVisible(false);+ output_toggle_->setVisible(false);+ output_content_->setVisible(false);return;}output_area_->setVisible(true);-- // Out label- auto* out_label = new QLabel(QString("Out [%1]:").arg(exec_count), output_area_);- out_label->setStyleSheet(- QString("color:%1; font-family:%2; font-size:10px; font-weight:700;").arg(kGreen, fonts::DATA_FAMILY));- output_layout_->addWidget(out_label);+ output_toggle_->setVisible(true);+ output_toggle_->setText(QString("OUT [%1]").arg(exec_count));+ output_collapsed_ = false;+ output_content_->setVisible(true);for (const auto& out : outputs) {if (out.type == "stream" || out.type == "execute_result") {- auto* text_lbl = new QLabel(out.text, output_area_);- text_lbl->setWordWrap(true);- text_lbl->setTextInteractionFlags(Qt::TextSelectableByMouse);- text_lbl->setStyleSheet(QString("color:%1; font-family:%2; font-size:11px; padding:4px 0;")- .arg(colors::TEXT_PRIMARY, fonts::DATA_FAMILY));- output_layout_->addWidget(text_lbl);+ // Use QTextEdit in read-only mode for proper scrolling of long output+ auto* output_view = new QTextEdit(output_content_);+ output_view->setReadOnly(true);+ output_view->setPlainText(out.text);+ output_view->setLineWrapMode(QTextEdit::WidgetWidth);+ output_view->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);+ output_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);++ QString fg = (out.name == "stderr") ? colors::WARNING : colors::TEXT_PRIMARY;+ output_view->setStyleSheet(+ QString("QTextEdit { background:transparent; color:%1; border:none;"+ " font-family:%2; font-size:%3px; padding:2px 0; }"+ "QScrollBar:vertical { background:transparent; width:4px; }"+ "QScrollBar::handle:vertical { background:%4; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }")+ .arg(fg, fonts::DATA_FAMILY)+ .arg(fonts::DATA)+ .arg(colors::BORDER_BRIGHT));++ // Size to content, max 300px then scroll+ int lines = out.text.count('\n') + 1;+ int line_h = QFontMetrics(output_view->font()).lineSpacing();+ int content_h = lines * line_h + 10;+ int clamped = qBound(30, content_h, 300);+ output_view->setFixedHeight(clamped);++ output_content_layout_->addWidget(output_view);+} else if (out.type == "error") {- auto* err_widget = new QWidget(output_area_);- err_widget->setStyleSheet(QString("background:#1a0000; border-left:2px solid %1; padding:8px;").arg(kRed));+ auto* err_widget = new QWidget(output_content_);+ err_widget->setStyleSheet(+ QString("background:#1a0808; border-left:2px solid %1;").arg(colors::NEGATIVE));auto* err_layout = new QVBoxLayout(err_widget);- err_layout->setContentsMargins(8, 4, 8, 4);- err_layout->setSpacing(2);-- auto* err_name = new QLabel(QString("<b>%1</b>: %2").arg(out.error_name, out.error_value), err_widget);- err_name->setStyleSheet(QString("color:%1; font-family:%2; font-size:11px;").arg(kRed, fonts::DATA_FAMILY));- err_layout->addWidget(err_name);+ err_layout->setContentsMargins(10, 6, 10, 6);+ err_layout->setSpacing(4);++ auto* err_header = new QLabel(+ QString("%1: %2").arg(out.error_name, out.error_value), err_widget);+ err_header->setWordWrap(true);+ err_header->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:%3px; font-weight:700;")+ .arg(colors::NEGATIVE, fonts::DATA_FAMILY)+ .arg(fonts::DATA));+ err_layout->addWidget(err_header);if (!out.traceback.isEmpty()) {- auto* tb = new QLabel(out.traceback.join("\n"), err_widget);- tb->setWordWrap(true);- tb->setTextInteractionFlags(Qt::TextSelectableByMouse);- tb->setStyleSheet(QString("color:%1; font-family:%2; font-size:10px;")- .arg(colors::TEXT_SECONDARY, fonts::DATA_FAMILY));- err_layout->addWidget(tb);+ auto* tb_view = new QTextEdit(err_widget);+ tb_view->setReadOnly(true);+ tb_view->setPlainText(out.traceback.join("\n"));+ tb_view->setLineWrapMode(QTextEdit::WidgetWidth);+ tb_view->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);+ tb_view->setStyleSheet(+ QString("QTextEdit { background:transparent; color:%1; border:none;"+ " font-family:%2; font-size:%3px; }"+ "QScrollBar:vertical { background:transparent; width:4px; }"+ "QScrollBar::handle:vertical { background:%4; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }")+ .arg(colors::TEXT_SECONDARY, fonts::DATA_FAMILY)+ .arg(fonts::TINY)+ .arg(colors::BORDER_BRIGHT));++ int tb_lines = out.traceback.join("\n").count('\n') + 1;+ int tb_h = qBound(40, tb_lines * 16 + 10, 200);+ tb_view->setFixedHeight(tb_h);+ err_layout->addWidget(tb_view);}- output_layout_->addWidget(err_widget);+ output_content_layout_->addWidget(err_widget);}}}void CellWidget::set_selected(bool selected) {- QString border_color = selected ? kOrange : colors::BORDER_DIM;- editor_->setStyleSheet(QString("QTextEdit { background:#0F0F0F; color:%1; border:none; border-left:3px solid %2;"- " font-family:%3; font-size:12px; padding:8px; }")- .arg(colors::TEXT_PRIMARY, border_color, fonts::DATA_FAMILY));+ selected_ = selected;++ // Selected: amber left accent, brighter surface. Unselected: dim border, standard surface.+ QString border = selected ? colors::AMBER : colors::BORDER_MED;+ QString bg = selected ? "#0e0e0e" : colors::BG_SURFACE;+ editor_container_->setStyleSheet(+ QString("background:%1; border-left:3px solid %2; border-top:1px solid %3;"+ " border-bottom:1px solid %3; border-right:1px solid %3;")+ .arg(bg, border, colors::BORDER_DIM));++ // Gutter matches cell background+ QString gutter_bg = selected ? "#0e0e0e" : colors::BG_RAISED;+ gutter_->setStyleSheet(QString("background:%1;").arg(gutter_bg));++ QString num_color = selected ? colors::AMBER : colors::TEXT_TERTIARY;+ gutter_number_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:%3px; font-weight:700; background:transparent;")+ .arg(num_color, fonts::DATA_FAMILY)+ .arg(fonts::TINY));++ // For markdown: if selecting, switch to edit mode; if deselecting, render+ if (cell_type_ == "markdown") {+ if (selected && !md_editing_) {+ md_editing_ = true;+ md_preview_->setVisible(false);+ editor_->setVisible(true);+ editor_->setFocus();+ adjust_editor_height();+ } else if (!selected && md_editing_) {+ md_editing_ = false;+ editor_->setVisible(false);+ md_preview_->setVisible(true);+ render_markdown();+ }+ }}-void CellWidget::update_header() {+void CellWidget::set_index(int index) {+ index_ = index;+ update_gutter();+}++void CellWidget::update_gutter() {if (running_) {- header_label_->setText("In [*]:");- header_label_->setStyleSheet(- QString("color:%1; font-family:%2; font-size:10px; font-weight:700;").arg(kYellow, fonts::DATA_FAMILY));+ gutter_number_->setText("[*]");+ gutter_number_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:%3px; font-weight:700;")+ .arg(colors::WARNING, fonts::DATA_FAMILY)+ .arg(fonts::TINY));} else if (execution_count_ > 0) {- header_label_->setText(QString("In [%1]:").arg(execution_count_));- header_label_->setStyleSheet(- QString("color:%1; font-family:%2; font-size:10px; font-weight:700;").arg(kGreen, fonts::DATA_FAMILY));+ gutter_number_->setText(QString("[%1]").arg(execution_count_));+ gutter_number_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:%3px; font-weight:700;")+ .arg(selected_ ? colors::AMBER : colors::POSITIVE, fonts::DATA_FAMILY)+ .arg(fonts::TINY));} else {- header_label_->setText("In [ ]:");- header_label_->setStyleSheet(- QString("color:%1; font-family:%2; font-size:10px; font-weight:700;").arg(kOrange, fonts::DATA_FAMILY));+ gutter_number_->setText(QString("[%1]").arg(index_ + 1));+ gutter_number_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:%3px; font-weight:700;")+ .arg(selected_ ? colors::AMBER : colors::TEXT_TERTIARY, fonts::DATA_FAMILY)+ .arg(fonts::TINY));}if (cell_type_ == "markdown") {- type_badge_->setText("MARKDOWN");- type_badge_->setStyleSheet(QString("color:%1; font-family:%2; font-size:9px; font-weight:700;"- " background:%3; padding:1px 6px;")- .arg(colors::TEXT_PRIMARY, fonts::DATA_FAMILY, kPurple));+ gutter_type_->setText("MD");+ gutter_type_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:10px; font-weight:600; letter-spacing:0.5px;")+ .arg(colors::INFO, fonts::DATA_FAMILY));} else {- type_badge_->setText("PYTHON");- type_badge_->setStyleSheet(QString("color:%1; font-family:%2; font-size:9px; font-weight:700;"- " background:%3; padding:1px 6px;")- .arg(colors::TEXT_PRIMARY, fonts::DATA_FAMILY, kBlue));+ gutter_type_->setText("PY");+ gutter_type_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:10px; font-weight:600; letter-spacing:0.5px;")+ .arg(colors::TEXT_DIM, fonts::DATA_FAMILY));}}-void CellWidget::render_outputs() {- // Handled in set_outputs+void CellWidget::render_markdown() {+ QString src = editor_->toPlainText();+ if (src.trimmed().isEmpty()) {+ md_preview_->setHtml(+ QString("<p style='color:%1; font-style:italic;'>Empty markdown cell — click to edit</p>")+ .arg(colors::TEXT_TERTIARY));+ md_preview_->setMinimumHeight(48);+ md_preview_->setMaximumHeight(48);+ return;+ }++ // Convert basic markdown to HTML for rendering+ // Handles: headers, bold, italic, code blocks, inline code, lists, links, horizontal rules+ QString html;+ html += QString("<style>"+ "body { color:%1; font-family:%2; font-size:%3px; }"+ "h1 { color:%4; font-size:20px; font-weight:700; margin:8px 0 4px; border-bottom:1px solid %5; padding-bottom:4px; }"+ "h2 { color:%4; font-size:17px; font-weight:700; margin:8px 0 4px; }"+ "h3 { color:%4; font-size:15px; font-weight:700; margin:6px 0 3px; }"+ "h4 { color:%6; font-size:14px; font-weight:600; margin:4px 0 2px; }"+ "code { background:%7; color:%4; padding:2px 4px; font-family:%2; }"+ "pre { background:%7; color:%1; padding:8px; font-family:%2; font-size:13px;"+ " border-left:2px solid %5; margin:6px 0; }"+ "a { color:%8; }"+ "strong { color:%1; font-weight:700; }"+ "em { color:%6; font-style:italic; }"+ "ul, ol { margin:4px 0; padding-left:20px; }"+ "li { margin:2px 0; }"+ "hr { border:none; border-top:1px solid %5; margin:8px 0; }"+ "blockquote { border-left:3px solid %4; padding-left:10px; color:%6; margin:6px 0; }"+ "</style>")+ .arg(colors::TEXT_PRIMARY, fonts::DATA_FAMILY)+ .arg(fonts::DATA)+ .arg(colors::AMBER, colors::BORDER_MED, colors::TEXT_SECONDARY,+ colors::BG_RAISED, colors::CYAN);++ bool in_code_block = false;+ QString code_block;+ QStringList lines = src.split('\n');++ for (const auto& line : lines) {+ // Fenced code blocks+ if (line.trimmed().startsWith("```")) {+ if (in_code_block) {+ html += "<pre>" + code_block.toHtmlEscaped() + "</pre>";+ code_block.clear();+ in_code_block = false;+ } else {+ in_code_block = true;+ }+ continue;+ }+ if (in_code_block) {+ if (!code_block.isEmpty()) code_block += "\n";+ code_block += line;+ continue;+ }++ QString trimmed = line.trimmed();++ // Horizontal rule+ if (trimmed == "---" || trimmed == "***" || trimmed == "___") {+ html += "<hr>";+ continue;+ }+ // Headers+ if (trimmed.startsWith("#### ")) { html += "<h4>" + trimmed.mid(5).toHtmlEscaped() + "</h4>"; continue; }+ if (trimmed.startsWith("### ")) { html += "<h3>" + trimmed.mid(4).toHtmlEscaped() + "</h3>"; continue; }+ if (trimmed.startsWith("## ")) { html += "<h2>" + trimmed.mid(3).toHtmlEscaped() + "</h2>"; continue; }+ if (trimmed.startsWith("# ")) { html += "<h1>" + trimmed.mid(2).toHtmlEscaped() + "</h1>"; continue; }+ // Blockquote+ if (trimmed.startsWith("> ")) {+ html += "<blockquote>" + trimmed.mid(2).toHtmlEscaped() + "</blockquote>";+ continue;+ }+ // Unordered list+ if (trimmed.startsWith("- ") || trimmed.startsWith("* ")) {+ html += "<ul><li>" + trimmed.mid(2).toHtmlEscaped() + "</li></ul>";+ continue;+ }+ // Ordered list (simple)+ if (trimmed.length() > 2 && trimmed[0].isDigit() && trimmed[1] == '.') {+ html += "<ol><li>" + trimmed.mid(3).toHtmlEscaped() + "</li></ol>";+ continue;+ }+ // Empty line = paragraph break+ if (trimmed.isEmpty()) {+ html += "<br>";+ continue;+ }++ // Inline formatting: **bold**, *italic*, `code`, [link](url)+ QString escaped = line.toHtmlEscaped();+ // Inline code first (to avoid nested processing)+ escaped.replace(QRegularExpression("`([^`]+)`"), "<code>\\1</code>");+ // Bold+ escaped.replace(QRegularExpression("\\*\\*([^*]+)\\*\\*"), "<strong>\\1</strong>");+ // Italic+ escaped.replace(QRegularExpression("\\*([^*]+)\\*"), "<em>\\1</em>");+ // Links+ escaped.replace(QRegularExpression("\\[([^\\]]+)\\]\\(([^)]+)\\)"), "<a href='\\2'>\\1</a>");++ html += "<p style='margin:2px 0;'>" + escaped + "</p>";+ }++ // Close unclosed code block+ if (in_code_block && !code_block.isEmpty()) {+ html += "<pre>" + code_block.toHtmlEscaped() + "</pre>";+ }++ md_preview_->setHtml(html);++ // Size preview to content+ QTimer::singleShot(0, this, [this]() {+ int h = static_cast<int>(md_preview_->document()->size().height()) + 20;+ int clamped = qBound(48, h, 600);+ md_preview_->setMinimumHeight(clamped);+ md_preview_->setMaximumHeight(clamped);+ });+}++void CellWidget::enterEvent(QEnterEvent* /*event*/) {+ hovered_ = true;+ // Show toolbar buttons+ for (int i = 0; i < toolbar_->layout()->count(); ++i) {+ auto* w = toolbar_->layout()->itemAt(i)->widget();+ if (w) w->setVisible(true);+ }+ toolbar_->setStyleSheet(+ QString("background:%1; border-bottom:1px solid %2;")+ .arg(colors::BG_RAISED, colors::BORDER_DIM));+}++void CellWidget::leaveEvent(QEvent* /*event*/) {+ hovered_ = false;+ // Hide toolbar buttons+ for (int i = 0; i < toolbar_->layout()->count(); ++i) {+ auto* w = toolbar_->layout()->itemAt(i)->widget();+ if (w) w->setVisible(false);+ }+ toolbar_->setStyleSheet(+ QString("background:%1;").arg(colors::BG_RAISED));+}++void CellWidget::mousePressEvent(QMouseEvent* event) {+ emit cell_clicked(cell_id_);+ QWidget::mousePressEvent(event);+}++// ═════════════════════════════════════════════════════════════════════════════+// CellNavigator (sidebar)+// ═════════════════════════════════════════════════════════════════════════════++CellNavigator::CellNavigator(QWidget* parent) : QWidget(parent) {+ auto* layout = new QVBoxLayout(this);+ layout->setContentsMargins(0, 0, 0, 0);+ layout->setSpacing(0);++ auto* header = new QWidget(this);+ header->setFixedHeight(32);+ header->setStyleSheet(+ QString("background:%1; border-bottom:1px solid %2;")+ .arg(colors::BG_RAISED, colors::BORDER_DIM));+ auto* header_layout = new QHBoxLayout(header);+ header_layout->setContentsMargins(10, 0, 10, 0);++ auto* title = new QLabel("CELLS", header);+ title->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:%3px; font-weight:700; letter-spacing:1px;")+ .arg(colors::AMBER, fonts::DATA_FAMILY)+ .arg(fonts::TINY));+ header_layout->addWidget(title);+ layout->addWidget(header);++ list_ = new QListWidget(this);+ list_->setStyleSheet(+ QString("QListWidget { background:%1; border:none; outline:none;"+ " font-family:%2; font-size:%3px; }"+ "QListWidget::item { color:%4; padding:6px 10px;"+ " border-bottom:1px solid %5; }"+ "QListWidget::item:selected { background:%6; color:%7;"+ " border-left:2px solid %7; }"+ "QListWidget::item:hover { background:%8; }")+ .arg(colors::BG_SURFACE, fonts::DATA_FAMILY)+ .arg(fonts::TINY)+ .arg(colors::TEXT_SECONDARY, colors::BORDER_DIM,+ colors::BG_HOVER, colors::AMBER, colors::BG_HOVER));++ connect(list_, &QListWidget::currentRowChanged, this, [this](int row) {+ if (row >= 0 && row < list_->count()) {+ emit cell_selected(list_->item(row)->data(Qt::UserRole).toString());+ }+ });+ layout->addWidget(list_, 1);+}++void CellNavigator::rebuild(const QVector<NotebookCell>& cells, const QString& selected_id) {+ list_->blockSignals(true);+ list_->clear();++ int selected_row = -1;+ for (int i = 0; i < cells.size(); ++i) {+ const auto& cell = cells[i];+ QString type_tag = (cell.cell_type == "code") ? "PY" : "MD";+ QString exec_tag;+ if (cell.execution_count > 0)+ exec_tag = QString(" [%1]").arg(cell.execution_count);++ QString preview = cell.source.split('\n').first().trimmed();+ if (preview.length() > 28) preview = preview.left(25) + "...";+ if (preview.isEmpty()) preview = "(empty)";++ auto* item = new QListWidgetItem(+ QString("%1 %2 %3%4").arg(i + 1, 2).arg(type_tag, -2).arg(preview, exec_tag), list_);+ item->setData(Qt::UserRole, cell.id);++ if (cell.id == selected_id) selected_row = i;+ }++ if (selected_row >= 0) list_->setCurrentRow(selected_row);+ list_->blockSignals(false);}// ═════════════════════════════════════════════════════════════════════════════@@ -268,7 +765,7 @@ void CellWidget::render_outputs() {CodeEditorScreen::CodeEditorScreen(QWidget* parent) : QWidget(parent) {build_ui();- on_new_notebook(); // Start with a fresh notebook+ on_new_notebook();}void CodeEditorScreen::showEvent(QShowEvent* event) {@@ -282,7 +779,9 @@ void CodeEditorScreen::hideEvent(QHideEvent* event) {}void CodeEditorScreen::build_ui() {- setStyleSheet(QString("QWidget { background:%1; color:%2; }").arg("#000000", colors::TEXT_PRIMARY));+ setStyleSheet(+ QString("QWidget { background:%1; color:%2; }")+ .arg(colors::BG_BASE, colors::TEXT_PRIMARY));auto* root = new QVBoxLayout(this);root->setContentsMargins(0, 0, 0, 0);@@ -290,62 +789,83 @@ void CodeEditorScreen::build_ui() {root->addWidget(build_toolbar());- // Scrollable cell area- scroll_area_ = new QScrollArea(this);+ splitter_ = new QSplitter(Qt::Horizontal, this);+ splitter_->setHandleWidth(1);+ splitter_->setStyleSheet(+ QString("QSplitter { background:%1; } QSplitter::handle { background:%2; }")+ .arg(colors::BG_BASE, colors::BORDER_DIM));++ navigator_ = new CellNavigator(splitter_);+ navigator_->setMinimumWidth(180);+ navigator_->setMaximumWidth(300);+ connect(navigator_, &CellNavigator::cell_selected, this, &CodeEditorScreen::on_select_cell);+ splitter_->addWidget(navigator_);++ scroll_area_ = new QScrollArea(splitter_);scroll_area_->setWidgetResizable(true);- scroll_area_->setStyleSheet("QScrollArea { border:none; background:#000000; }"- "QScrollBar:vertical { background:#0F0F0F; width:8px; }"- "QScrollBar::handle:vertical { background:#2A2A2A; min-height:30px; }"- "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }");+ scroll_area_->setStyleSheet(+ QString("QScrollArea { border:none; background:%1; }"+ "QScrollBar:vertical { background:%2; width:6px; margin:0; }"+ "QScrollBar::handle:vertical { background:%3; min-height:40px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }"+ "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background:transparent; }")+ .arg(colors::BG_BASE, colors::BG_SURFACE, colors::BORDER_BRIGHT));cells_container_ = new QWidget(scroll_area_);cells_layout_ = new QVBoxLayout(cells_container_);- cells_layout_->setContentsMargins(40, 8, 40, 8);+ cells_layout_->setContentsMargins(8, 4, 12, 40);cells_layout_->setSpacing(0);cells_layout_->addStretch();scroll_area_->setWidget(cells_container_);- root->addWidget(scroll_area_, 1);-- // Status bar- auto* status_bar = new QWidget(this);- status_bar->setFixedHeight(24);- status_bar->setStyleSheet(QString("background:#0F0F0F; border-top:1px solid %1;").arg(colors::BORDER_DIM));- auto* shl = new QHBoxLayout(status_bar);- shl->setContentsMargins(12, 0, 12, 0);- status_label_ = new QLabel("Ready", status_bar);- status_label_->setStyleSheet(- QString("color:%1; font-family:%2; font-size:9px;").arg(colors::TEXT_SECONDARY, fonts::DATA_FAMILY));- shl->addWidget(status_label_);- shl->addStretch();+ splitter_->addWidget(scroll_area_);- auto* shortcut_label = new QLabel("Ctrl+Enter: Run Cell | Shift+Enter: Run & Next", status_bar);- shortcut_label->setStyleSheet(status_label_->styleSheet());- shl->addWidget(shortcut_label);+ splitter_->setStretchFactor(0, 0);+ splitter_->setStretchFactor(1, 1);+ splitter_->setSizes({200, 800});- root->addWidget(status_bar);+ root->addWidget(splitter_, 1);+ root->addWidget(build_status_bar());}QWidget* CodeEditorScreen::build_toolbar() {auto* bar = new QWidget(this);- bar->setFixedHeight(40);- bar->setStyleSheet(QString("background:%1; border-bottom:1px solid %2;").arg("#1A1A1A", colors::BORDER_DIM));+ bar->setFixedHeight(36);+ bar->setStyleSheet(+ QString("background:%1; border-bottom:1px solid %2;")+ .arg(colors::BG_RAISED, colors::BORDER_DIM));auto* hl = new QHBoxLayout(bar);- hl->setContentsMargins(12, 0, 12, 0);- hl->setSpacing(4);-- auto* title = new QLabel("PYTHON COLAB", bar);- title->setStyleSheet(QString("color:%1; font-family:%2; font-size:11px; font-weight:700; margin-right:12px;")- .arg(kOrange, fonts::DATA_FAMILY));+ hl->setContentsMargins(10, 0, 10, 0);+ hl->setSpacing(0);++ auto* title = new QLabel("PYTHON NOTEBOOK", bar);+ title->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:%3px; font-weight:700;"+ " letter-spacing:1px; padding-right:16px;")+ .arg(colors::AMBER, fonts::DATA_FAMILY)+ .arg(fonts::SMALL));hl->addWidget(title);- auto make_btn = [&](const QString& text) -> QPushButton* {+ auto add_sep = [&]() {+ auto* sep = new QWidget(bar);+ sep->setFixedSize(1, 18);+ sep->setStyleSheet(QString("background:%1;").arg(colors::BORDER_MED));+ hl->addWidget(sep);+ };++ auto make_btn = [&](const QString& text, const QString& fg = QString()) -> QPushButton* {auto* btn = new QPushButton(text, bar);- btn->setStyleSheet(QString("QPushButton { background:#2A2A2A; color:%1; border:none;"- " font-family:%2; font-size:10px; font-weight:600; padding:6px 12px; }"- "QPushButton:hover { background:#3A3A3A; }")- .arg(colors::TEXT_PRIMARY, fonts::DATA_FAMILY));+ btn->setCursor(Qt::PointingHandCursor);+ QString color = fg.isEmpty() ? colors::TEXT_SECONDARY : fg;+ btn->setStyleSheet(+ QString("QPushButton { background:transparent; color:%1; border:none;"+ " font-family:%2; font-size:%3px; font-weight:600; padding:0 10px;"+ " letter-spacing:0.5px; }"+ "QPushButton:hover { color:%4; background:%5; }")+ .arg(color, fonts::DATA_FAMILY)+ .arg(fonts::TINY)+ .arg(colors::TEXT_PRIMARY, colors::BG_HOVER));return btn;};@@ -361,33 +881,82 @@ QWidget* CodeEditorScreen::build_toolbar() {connect(save_btn, &QPushButton::clicked, this, &CodeEditorScreen::on_save_notebook);hl->addWidget(save_btn);- auto* sep = new QWidget(bar);- sep->setFixedSize(1, 20);- sep->setStyleSheet("background:#2A2A2A;");- hl->addWidget(sep);+ add_sep();- auto* add_btn = make_btn("+ CELL");+ auto* add_btn = make_btn("+ CELL", colors::CYAN);connect(add_btn, &QPushButton::clicked, this, &CodeEditorScreen::on_add_cell);hl->addWidget(add_btn);+ auto* clear_btn = make_btn("CLEAR OUT");+ connect(clear_btn, &QPushButton::clicked, this, &CodeEditorScreen::on_clear_outputs);+ hl->addWidget(clear_btn);++ add_sep();+auto* run_all_btn = new QPushButton("RUN ALL", bar);- run_all_btn->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:none;"- " font-family:%3; font-size:10px; font-weight:700; padding:6px 14px; }"- "QPushButton:hover { background:#cc6600; }")- .arg(kOrange, "#000000", fonts::DATA_FAMILY));+ run_all_btn->setCursor(Qt::PointingHandCursor);+ run_all_btn->setStyleSheet(+ QString("QPushButton { background:%1; color:%2; border:none;"+ " font-family:%3; font-size:%4px; font-weight:700; padding:4px 14px;"+ " letter-spacing:0.5px; }"+ "QPushButton:hover { background:%5; }")+ .arg(colors::AMBER, colors::BG_BASE, fonts::DATA_FAMILY)+ .arg(fonts::TINY)+ .arg(colors::ORANGE));connect(run_all_btn, &QPushButton::clicked, this, &CodeEditorScreen::on_run_all);hl->addWidget(run_all_btn);hl->addStretch();- // Python version label+ auto* sidebar_btn = make_btn("SIDEBAR");+ connect(sidebar_btn, &QPushButton::clicked, this, &CodeEditorScreen::on_toggle_sidebar);+ hl->addWidget(sidebar_btn);++ add_sep();++ kernel_label_ = new QLabel("KERNEL: IDLE", bar);+ kernel_label_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:10px; font-weight:600;"+ " letter-spacing:0.5px; padding:0 8px;")+ .arg(colors::POSITIVE, fonts::DATA_FAMILY));+ hl->addWidget(kernel_label_);+auto* py_label = new QLabel("Python 3.12", bar);- py_label->setStyleSheet(QString("color:%1; font-family:%2; font-size:9px;").arg(kBlue, fonts::DATA_FAMILY));+ py_label->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:10px; padding-left:8px;")+ .arg(colors::TEXT_TERTIARY, fonts::DATA_FAMILY));hl->addWidget(py_label);return bar;}+QWidget* CodeEditorScreen::build_status_bar() {+ auto* bar = new QWidget(this);+ bar->setFixedHeight(24);+ bar->setStyleSheet(+ QString("background:%1; border-top:1px solid %2;")+ .arg(colors::BG_RAISED, colors::BORDER_DIM));++ auto* hl = new QHBoxLayout(bar);+ hl->setContentsMargins(10, 0, 10, 0);++ status_label_ = new QLabel("READY", bar);+ status_label_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:10px; font-weight:600; letter-spacing:0.5px;")+ .arg(colors::TEXT_SECONDARY, fonts::DATA_FAMILY));+ hl->addWidget(status_label_);+ hl->addStretch();++ auto* shortcuts = new QLabel(+ "Ctrl+Enter: RUN | Shift+Enter: RUN & NEXT | Tab: 4 SPACES | Ctrl+S: SAVE", bar);+ shortcuts->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:10px; letter-spacing:0.3px;")+ .arg(colors::TEXT_DIM, fonts::DATA_FAMILY));+ hl->addWidget(shortcuts);++ return bar;+}+// ─────────────────────────────────────────────────────────────────────────────// Notebook management// ─────────────────────────────────────────────────────────────────────────────@@ -397,97 +966,148 @@ void CodeEditorScreen::on_new_notebook() {execution_counter_ = 0;notebook_path_.clear();- // Add initial code cellNotebookCell cell;cell.id = new_cell_id();cell.cell_type = "code";- cell.source = "# Welcome to Fincept Python Colab\n# Write Python code and press Ctrl+Enter to run\n\nprint(\"Hello "- "from Fincept Terminal!\")";+ cell.source =+ "# Fincept Python Notebook\n"+ "# Write Python code and press Ctrl+Enter to run\n"+ "\n"+ "print(\"Hello from Fincept Terminal!\")";cells_.append(cell);+ selected_cell_id_ = cell.id;rebuild_cells();update_status();+ update_navigator();}void CodeEditorScreen::on_add_cell() {QString after_id = selected_cell_id_;- if (after_id.isEmpty() && !cells_.isEmpty()) {+ if (after_id.isEmpty() && !cells_.isEmpty())after_id = cells_.last().id;- }add_cell_after(after_id, "code");}+void CodeEditorScreen::on_insert_below(const QString& cell_id) {+ add_cell_after(cell_id, "code");+}+void CodeEditorScreen::add_cell_after(const QString& after_id, const QString& type) {NotebookCell cell;cell.id = new_cell_id();cell.cell_type = type;int idx = find_cell_index(after_id);- if (idx >= 0) {+ if (idx >= 0)cells_.insert(idx + 1, cell);- } else {+ elsecells_.append(cell);- }+ selected_cell_id_ = cell.id;rebuild_cells();update_status();+ update_navigator();}void CodeEditorScreen::on_delete_cell(const QString& cell_id) {- if (cells_.size() <= 1)- return;+ if (cells_.size() <= 1) return;- // Save current cell data first- auto* cw = find_cell_widget(cell_id);int idx = find_cell_index(cell_id);if (idx >= 0) {cells_.removeAt(idx);+ if (idx < cells_.size())+ selected_cell_id_ = cells_[idx].id;+ else if (!cells_.isEmpty())+ selected_cell_id_ = cells_.last().id;+rebuild_cells();update_status();+ update_navigator();}}void CodeEditorScreen::on_move_cell_up(const QString& cell_id) {int idx = find_cell_index(cell_id);- if (idx <= 0)- return;+ if (idx <= 0) return;- // Save current text from widgetauto* cw = find_cell_widget(cell_id);- if (cw)- cells_[idx] = cw->cell_data();+ if (cw) cells_[idx] = cw->cell_data();cells_.swapItemsAt(idx, idx - 1);rebuild_cells();+ update_navigator();}void CodeEditorScreen::on_move_cell_down(const QString& cell_id) {int idx = find_cell_index(cell_id);- if (idx < 0 || idx >= cells_.size() - 1)- return;+ if (idx < 0 || idx >= cells_.size() - 1) return;auto* cw = find_cell_widget(cell_id);- if (cw)- cells_[idx] = cw->cell_data();+ if (cw) cells_[idx] = cw->cell_data();cells_.swapItemsAt(idx, idx + 1);rebuild_cells();+ update_navigator();}void CodeEditorScreen::on_toggle_cell_type(const QString& cell_id) {int idx = find_cell_index(cell_id);- if (idx < 0)- return;+ if (idx < 0) return;auto* cw = find_cell_widget(cell_id);- if (cw)- cells_[idx] = cw->cell_data();+ if (cw) cells_[idx] = cw->cell_data();cells_[idx].cell_type = (cells_[idx].cell_type == "code") ? "markdown" : "code";cells_[idx].outputs.clear();cells_[idx].execution_count = 0;rebuild_cells();+ update_navigator();+}++void CodeEditorScreen::on_select_cell(const QString& cell_id) {+ if (cell_id == selected_cell_id_) return;++ auto* old_cw = find_cell_widget(selected_cell_id_);+ if (old_cw) old_cw->set_selected(false);++ selected_cell_id_ = cell_id;++ auto* new_cw = find_cell_widget(cell_id);+ if (new_cw) {+ new_cw->set_selected(true);+ scroll_area_->ensureWidgetVisible(new_cw, 50, 50);+ }+ update_navigator();+}++void CodeEditorScreen::on_clear_outputs() {+ for (auto& cell : cells_) {+ cell.outputs.clear();+ cell.execution_count = 0;+ }+ execution_counter_ = 0;+ rebuild_cells();+ update_status();+ update_navigator();+}++void CodeEditorScreen::on_toggle_sidebar() {+ sidebar_visible_ = !sidebar_visible_;+ navigator_->setVisible(sidebar_visible_);+}++void CodeEditorScreen::advance_to_next(const QString& current_id) {+ int idx = find_cell_index(current_id);+ if (idx < 0) return;++ if (idx + 1 < cells_.size()) {+ on_select_cell(cells_[idx + 1].id);+ } else {+ // Add a new cell at the end and select it+ add_cell_after(current_id, "code");+ }}// ─────────────────────────────────────────────────────────────────────────────@@ -496,36 +1116,36 @@ void CodeEditorScreen::on_toggle_cell_type(const QString& cell_id) {void CodeEditorScreen::on_run_cell(const QString& cell_id) {int idx = find_cell_index(cell_id);- if (idx < 0)- return;+ if (idx < 0) return;- // Save current text from widgetauto* cw = find_cell_widget(cell_id);if (cw) {cells_[idx] = cw->cell_data();cw->set_running(true);}- if (cells_[idx].cell_type != "code")- return;+ if (cells_[idx].cell_type != "code") return;QString code = cells_[idx].source;- if (code.trimmed().isEmpty())- return;+ if (code.trimmed().isEmpty()) return;++execution_counter_;int exec_num = execution_counter_;+ kernel_label_->setText("KERNEL: BUSY");+ kernel_label_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:10px; font-weight:600;"+ " letter-spacing:0.5px; padding:0 8px;")+ .arg(colors::WARNING, fonts::DATA_FAMILY));+QPointer<CodeEditorScreen> self = this;QString cid = cell_id;python::PythonRunner::instance().run_code(code, [self, cid, exec_num](python::PythonResult result) {- if (!self)- return;+ if (!self) return;int idx = self->find_cell_index(cid);- if (idx < 0)- return;+ if (idx < 0) return;QVector<CellOutput> outputs;@@ -541,13 +1161,13 @@ void CodeEditorScreen::on_run_cell(const QString& cell_id) {CellOutput out;out.type = "error";out.error_name = "ExecutionError";- out.error_value = result.error.isEmpty() ? QString("Process exited with code %1").arg(result.exit_code)- : result.error.split('\n').last();+ out.error_value = result.error.isEmpty()+ ? QString("Process exited with code %1").arg(result.exit_code)+ : result.error.split('\n').last();out.traceback = result.error.split('\n');out.text = result.error;outputs.append(out);- // Also include stdout if anyif (!result.output.isEmpty()) {CellOutput stdout_out;stdout_out.type = "stream";@@ -567,39 +1187,45 @@ void CodeEditorScreen::on_run_cell(const QString& cell_id) {widget->set_running(false);}+ self->kernel_label_->setText("KERNEL: IDLE");+ self->kernel_label_->setStyleSheet(+ QString("color:%1; font-family:%2; font-size:10px; font-weight:600;"+ " letter-spacing:0.5px; padding:0 8px;")+ .arg(colors::POSITIVE, fonts::DATA_FAMILY));+self->update_status();+ self->update_navigator();});}+void CodeEditorScreen::on_run_and_advance(const QString& cell_id) {+ on_run_cell(cell_id);+ advance_to_next(cell_id);+}+void CodeEditorScreen::on_run_all() {- // Run all code cells sequentially (queue them all)for (const auto& cell : cells_) {- if (cell.cell_type == "code") {+ if (cell.cell_type == "code")on_run_cell(cell.id);- }}}// ─────────────────────────────────────────────────────────────────────────────-// File I/O (.ipynb)+// File I/O// ─────────────────────────────────────────────────────────────────────────────void CodeEditorScreen::on_open_notebook() {- QString path =- QFileDialog::getOpenFileName(this, "Open Notebook", {}, "Jupyter Notebooks (*.ipynb);;All Files (*)");- if (path.isEmpty())- return;+ QString path = QFileDialog::getOpenFileName(+ this, "Open Notebook", {}, "Jupyter Notebooks (*.ipynb);;All Files (*)");+ if (path.isEmpty()) return;QFile file(path);- if (!file.open(QIODevice::ReadOnly))- return;+ if (!file.open(QIODevice::ReadOnly)) return;QJsonDocument doc = QJsonDocument::fromJson(file.readAll());- if (doc.isNull())- return;+ if (doc.isNull()) return;- QJsonObject root = doc.object();- QJsonArray json_cells = root["cells"].toArray();+ QJsonArray json_cells = doc.object()["cells"].toArray();cells_.clear();execution_counter_ = 0;@@ -610,13 +1236,11 @@ void CodeEditorScreen::on_open_notebook() {cell.id = new_cell_id();cell.cell_type = co["cell_type"].toString("code");- // Source can be string or array of stringsQJsonValue src = co["source"];if (src.isArray()) {QStringList lines;- for (const auto& line : src.toArray()) {+ for (const auto& line : src.toArray())lines << line.toString();- }cell.source = lines.join("");} else {cell.source = src.toString();@@ -634,45 +1258,40 @@ void CodeEditorScreen::on_open_notebook() {}notebook_path_ = path;+ selected_cell_id_ = cells_.first().id;rebuild_cells();update_status();+ update_navigator();LOG_INFO("CodeEditor", "Opened notebook: " + path);}void CodeEditorScreen::on_save_notebook() {- // Sync cell data from widgetsfor (int i = 0; i < cells_.size(); ++i) {auto* cw = find_cell_widget(cells_[i].id);- if (cw)- cells_[i] = cw->cell_data();+ if (cw) cells_[i] = cw->cell_data();}QString path = notebook_path_;if (path.isEmpty()) {path = QFileDialog::getSaveFileName(this, "Save Notebook", "notebook.ipynb", "Jupyter Notebooks (*.ipynb)");- if (path.isEmpty())- return;+ if (path.isEmpty()) return;}- // Build ipynb JSONQJsonArray json_cells;for (const auto& cell : cells_) {QJsonObject co;co["cell_type"] = cell.cell_type;- // Split source into lines (ipynb format)QJsonArray src_lines;- for (const auto& line : cell.source.split('\n')) {+ for (const auto& line : cell.source.split('\n'))src_lines.append(line + "\n");- }co["source"] = src_lines;co["metadata"] = QJsonObject();if (cell.cell_type == "code") {co["execution_count"] = cell.execution_count > 0 ? QJsonValue(cell.execution_count) : QJsonValue();- co["outputs"] = QJsonArray(); // Don't save outputs+ co["outputs"] = QJsonArray();}-json_cells.append(co);}@@ -695,11 +1314,8 @@ void CodeEditorScreen::on_save_notebook() {file.close();notebook_path_ = path;LOG_INFO("CodeEditor", "Saved notebook: " + path);-- // Register with File Manager so it appears in the Files tabservices::FileManagerService::instance().import_file(path, "code_editor");}-update_status();}@@ -708,42 +1324,41 @@ void CodeEditorScreen::on_save_notebook() {// ─────────────────────────────────────────────────────────────────────────────void CodeEditorScreen::rebuild_cells() {- // Remove old widgets- while (cells_layout_->count() > 1) { // keep the stretch+ while (cells_layout_->count() > 1) {auto* item = cells_layout_->takeAt(0);- if (item->widget())- item->widget()->deleteLater();+ if (item->widget()) item->widget()->deleteLater();delete item;}- // Add cell widgetsfor (int i = 0; i < cells_.size(); ++i) {- auto* cw = new CellWidget(cells_[i], cells_container_);+ auto* cw = new CellWidget(cells_[i], i, cells_container_);+ cw->set_selected(cells_[i].id == selected_cell_id_);+connect(cw, &CellWidget::run_requested, this, &CodeEditorScreen::on_run_cell);+ connect(cw, &CellWidget::run_and_advance, this, &CodeEditorScreen::on_run_and_advance);connect(cw, &CellWidget::delete_requested, this, &CodeEditorScreen::on_delete_cell);connect(cw, &CellWidget::move_up_requested, this, &CodeEditorScreen::on_move_cell_up);connect(cw, &CellWidget::move_down_requested, this, &CodeEditorScreen::on_move_cell_down);connect(cw, &CellWidget::toggle_type_requested, this, &CodeEditorScreen::on_toggle_cell_type);+ connect(cw, &CellWidget::cell_clicked, this, &CodeEditorScreen::on_select_cell);+ connect(cw, &CellWidget::insert_below_requested, this, &CodeEditorScreen::on_insert_below);+cells_layout_->insertWidget(i, cw);}}int CodeEditorScreen::find_cell_index(const QString& cell_id) const {- for (int i = 0; i < cells_.size(); ++i) {- if (cells_[i].id == cell_id)- return i;- }+ for (int i = 0; i < cells_.size(); ++i)+ if (cells_[i].id == cell_id) return i;return -1;}CellWidget* CodeEditorScreen::find_cell_widget(const QString& cell_id) const {for (int i = 0; i < cells_layout_->count(); ++i) {auto* item = cells_layout_->itemAt(i);- if (!item || !item->widget())- continue;+ if (!item || !item->widget()) continue;auto* cw = qobject_cast<CellWidget*>(item->widget());- if (cw && cw->cell_id() == cell_id)- return cw;+ if (cw && cw->cell_id() == cell_id) return cw;}return nullptr;}@@ -753,23 +1368,21 @@ QString CodeEditorScreen::new_cell_id() const {}void CodeEditorScreen::update_status() {- int code_count = 0;- int md_count = 0;- int executed = 0;+ int code_count = 0, md_count = 0, executed = 0;for (const auto& c : cells_) {- if (c.cell_type == "code")- ++code_count;- else- ++md_count;- if (c.execution_count > 0)- ++executed;+ if (c.cell_type == "code") ++code_count; else ++md_count;+ if (c.execution_count > 0) ++executed;}- QString info = QString("%1 CODE | %2 MD | EXECUTED: %3").arg(code_count).arg(md_count).arg(executed);- if (!notebook_path_.isEmpty()) {+ QString info = QString("CELLS: %1 CODE %2 MD | EXECUTED: %3")+ .arg(code_count).arg(md_count).arg(executed);+ if (!notebook_path_.isEmpty())info += " | " + QFileInfo(notebook_path_).fileName();- }status_label_->setText(info);}+void CodeEditorScreen::update_navigator() {+ if (navigator_) navigator_->rebuild(cells_, selected_cell_id_);+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen.h b/fincept-qt/src/screens/code_editor/CodeEditorScreen.hindex 299d20465..b6014c563 100644--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen.h+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen.h@@ -1,23 +1,25 @@// src/screens/code_editor/CodeEditorScreen.h-// Python Colab notebook — Jupyter-style cell-based code execution.-// Supports code/markdown cells, run individual/all, stdout/stderr output,-// .ipynb file I/O, and package management via the bundled Python interpreter.+// Bloomberg-style Python Colab — Jupyter notebook with Obsidian design system.+// Responsive cells, markdown rendering, keyboard shortcuts, collapsible output.#pragma once#include <QHideEvent>#include <QJsonArray>#include <QJsonObject>#include <QLabel>+#include <QListWidget>#include <QPushButton>#include <QScrollArea>#include <QShowEvent>+#include <QSplitter>+#include <QTextBrowser>#include <QTextEdit>#include <QVBoxLayout>#include <QWidget>namespace fincept::screens {-// ── Cell data ────────────────────────────────────────────────────────────────+// -- Cell data ----------------------------------------------------------------struct CellOutput {QString type; // "stream", "error", "execute_result"@@ -37,47 +39,107 @@ struct NotebookCell {bool running = false;};-// ── Cell widget ──────────────────────────────────────────────────────────────+// -- Code editor with line numbers --------------------------------------------++class CodeTextEdit : public QTextEdit {+ Q_OBJECT+ public:+ explicit CodeTextEdit(QWidget* parent = nullptr);++ signals:+ void run_shortcut(); // Ctrl+Enter+ void run_and_next(); // Shift+Enter++ protected:+ void keyPressEvent(QKeyEvent* event) override;+};++// -- Cell widget --------------------------------------------------------------class CellWidget : public QWidget {Q_OBJECTpublic:- explicit CellWidget(const NotebookCell& cell, QWidget* parent = nullptr);+ explicit CellWidget(const NotebookCell& cell, int index, QWidget* parent = nullptr);void set_cell_data(const NotebookCell& cell);NotebookCell cell_data() const;void set_running(bool running);void set_outputs(const QVector<CellOutput>& outputs, int exec_count);void set_selected(bool selected);+ void set_index(int index);QString cell_id() const { return cell_id_; }signals:void run_requested(const QString& cell_id);+ void run_and_advance(const QString& cell_id);void delete_requested(const QString& cell_id);void move_up_requested(const QString& cell_id);void move_down_requested(const QString& cell_id);void toggle_type_requested(const QString& cell_id);- void cell_selected(const QString& cell_id);+ void cell_clicked(const QString& cell_id);+ void insert_below_requested(const QString& cell_id);++ protected:+ void enterEvent(QEnterEvent* event) override;+ void leaveEvent(QEvent* event) override;+ void mousePressEvent(QMouseEvent* event) override;private:void build_ui();- void update_header();- void render_outputs();+ void update_gutter();+ void adjust_editor_height();+ void render_markdown();QString cell_id_;QString cell_type_;int execution_count_ = 0;+ int index_ = 0;bool running_ = false;+ bool selected_ = false;+ bool hovered_ = false;+ bool output_collapsed_ = false;+ bool md_editing_ = false;++ // Gutter+ QWidget* gutter_ = nullptr;+ QLabel* gutter_number_ = nullptr;+ QLabel* gutter_type_ = nullptr;- QLabel* header_label_ = nullptr;- QLabel* type_badge_ = nullptr;- QTextEdit* editor_ = nullptr;+ // Editor area+ QWidget* editor_container_ = nullptr;+ CodeTextEdit* editor_ = nullptr;+ QTextBrowser* md_preview_ = nullptr; // rendered markdown view++ // Hover toolbar+ QWidget* toolbar_ = nullptr;++ // Output areaQWidget* output_area_ = nullptr;QVBoxLayout* output_layout_ = nullptr;- QWidget* action_bar_ = nullptr;+ QPushButton* output_toggle_ = nullptr;+ QWidget* output_content_ = nullptr;+ QVBoxLayout* output_content_layout_ = nullptr;++ // Insert hint+ QWidget* insert_hint_ = nullptr;+};++// -- Sidebar cell navigator ---------------------------------------------------++class CellNavigator : public QWidget {+ Q_OBJECT+ public:+ explicit CellNavigator(QWidget* parent = nullptr);+ void rebuild(const QVector<NotebookCell>& cells, const QString& selected_id);++ signals:+ void cell_selected(const QString& cell_id);++ private:+ QListWidget* list_ = nullptr;};-// ── Main screen ──────────────────────────────────────────────────────────────+// -- Main screen --------------------------------------------------------------class CodeEditorScreen : public QWidget {Q_OBJECT@@ -91,6 +153,7 @@ class CodeEditorScreen : public QWidget {private slots:void on_add_cell();void on_run_cell(const QString& cell_id);+ void on_run_and_advance(const QString& cell_id);void on_run_all();void on_delete_cell(const QString& cell_id);void on_move_cell_up(const QString& cell_id);@@ -99,16 +162,23 @@ class CodeEditorScreen : public QWidget {void on_new_notebook();void on_open_notebook();void on_save_notebook();+ void on_select_cell(const QString& cell_id);+ void on_insert_below(const QString& cell_id);+ void on_clear_outputs();+ void on_toggle_sidebar();private:void build_ui();QWidget* build_toolbar();+ QWidget* build_status_bar();void rebuild_cells();void add_cell_after(const QString& after_id, const QString& type);int find_cell_index(const QString& cell_id) const;CellWidget* find_cell_widget(const QString& cell_id) const;QString new_cell_id() const;void update_status();+ void update_navigator();+ void advance_to_next(const QString& current_id);// Notebook dataQVector<NotebookCell> cells_;@@ -116,11 +186,15 @@ class CodeEditorScreen : public QWidget {QString notebook_path_;// UI+ QSplitter* splitter_ = nullptr;+ CellNavigator* navigator_ = nullptr;QScrollArea* scroll_area_ = nullptr;QWidget* cells_container_ = nullptr;QVBoxLayout* cells_layout_ = nullptr;QLabel* status_label_ = nullptr;+ QLabel* kernel_label_ = nullptr;QString selected_cell_id_;+ bool sidebar_visible_ = true;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cppindex 047fbcb2a..755faadf3 100644--- a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp+++ b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp@@ -251,6 +251,13 @@ static QList<SchemaInfo> g_schemas = build_schemas();// ── Template definitions ────────────────────────────────────────────────────+struct FieldMapping {+ QString target;+ QString expression;+ QString transform;+ QString default_val;+};+struct MappingTemplate {QString id;QString name;@@ -259,66 +266,357 @@ struct MappingTemplate {QString schema;QStringList tags;bool verified;+ // Real API details+ QString base_url;+ QString endpoint;+ QString method;+ QString auth_type;+ QString headers;+ QString body;+ QString parser;+ QList<FieldMapping> field_mappings;};static QList<MappingTemplate> build_templates() {return {- {"upstox_ohlcv",- "Upstox Historical Candles → OHLCV",- "Map Upstox historical candle data to standard OHLCV format",- "Upstox",+ // ── Free Public APIs (no auth) ─────────────────────────────────────++ {"coingecko_quote",+ "CoinGecko Coin Price → QUOTE",+ "Fetch real-time crypto prices from CoinGecko. Free, no API key required. "+ "Returns price, market cap, 24h volume, and change data.",+ "CoinGecko",+ "QUOTE",+ {"crypto", "coingecko", "free", "public"},+ true,+ "https://api.coingecko.com",+ "/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_vol=true&include_24hr_change=true&include_last_updated_at=true",+ "GET",+ "None",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"symbol", "$.bitcoin", "", "bitcoin"},+ {"price", "$.bitcoin.usd", "", "0"},+ {"volume", "$.bitcoin.usd_24h_vol", "", "0"},+ {"changePercent", "$.bitcoin.usd_24h_change", "", "0"},+ {"timestamp", "$.bitcoin.last_updated_at", "unix_to_iso", ""}}},++ {"coingecko_ohlcv",+ "CoinGecko OHLC → OHLCV",+ "Fetch OHLC candlestick data for any crypto from CoinGecko. Free API. "+ "Returns 1/7/14/30/90/180/365 day candles. Array format: [timestamp, O, H, L, C].",+ "CoinGecko","OHLCV",- {"upstox", "historical", "candles", "india"},- true},- {"upstox_quote",- "Upstox Market Quote → QUOTE",- "Map Upstox market quote data to standard QUOTE format",- "Upstox",+ {"crypto", "coingecko", "ohlc", "candles", "free"},+ true,+ "https://api.coingecko.com",+ "/api/v3/coins/bitcoin/ohlc?vs_currency=usd&days=30",+ "GET",+ "None",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"timestamp", "$[*][0]", "unix_ms_to_iso", ""},+ {"open", "$[*][1]", "", "0"},+ {"high", "$[*][2]", "", "0"},+ {"low", "$[*][3]", "", "0"},+ {"close", "$[*][4]", "", "0"},+ {"symbol", "", "", "bitcoin"}}},++ {"yahoo_quote",+ "Yahoo Finance Spark → QUOTE",+ "Fetch real-time stock quotes from Yahoo Finance. Free, no API key. "+ "Returns last price, volume, and market state for any symbol.",+ "Yahoo Finance","QUOTE",- {"upstox", "quote", "realtime", "india"},- true},- {"fyers_quote",- "Fyers Quotes → QUOTE",- "Map Fyers quote data to standard QUOTE format",- "Fyers",+ {"stocks", "yahoo", "free", "public", "us"},+ true,+ "https://query1.finance.yahoo.com",+ "/v8/finance/spark?symbols=AAPL&range=1d&interval=1d",+ "GET",+ "None",+ "Accept: application/json\nUser-Agent: Mozilla/5.0",+ "",+ "JSONPath",+ {{"symbol", "$.spark.result[0].symbol", "", ""},+ {"price", "$.spark.result[0].response[0].meta.regularMarketPrice", "", "0"},+ {"previousClose", "$.spark.result[0].response[0].meta.previousClose", "", "0"},+ {"volume", "$.spark.result[0].response[0].meta.regularMarketVolume", "", "0"},+ {"timestamp", "$.spark.result[0].response[0].meta.regularMarketTime", "unix_to_iso", ""}}},++ {"binance_ohlcv",+ "Binance Klines → OHLCV",+ "Fetch candlestick/kline data from Binance. Free, no API key required for market data. "+ "Supports intervals: 1m, 3m, 5m, 15m, 30m, 1h, 4h, 1d, 1w, 1M.",+ "Binance",+ "OHLCV",+ {"crypto", "binance", "klines", "candles", "free"},+ true,+ "https://api.binance.com",+ "/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=100",+ "GET",+ "None",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"timestamp", "$[*][0]", "unix_ms_to_iso", ""},+ {"open", "$[*][1]", "to_number", "0"},+ {"high", "$[*][2]", "to_number", "0"},+ {"low", "$[*][3]", "to_number", "0"},+ {"close", "$[*][4]", "to_number", "0"},+ {"volume", "$[*][5]", "to_number", "0"},+ {"trades", "$[*][8]", "to_number", "0"},+ {"symbol", "", "", "BTCUSDT"}}},++ {"binance_quote",+ "Binance 24hr Ticker → QUOTE",+ "Fetch 24-hour price statistics from Binance. Free, no API key. "+ "Returns price, bid/ask, volume, and 24h change for any trading pair.",+ "Binance","QUOTE",- {"fyers", "quote", "realtime", "india"},- true},- {"fyers_positions",- "Fyers Positions → POSITION",- "Map Fyers position data to standard POSITION format",- "Fyers",- "POSITION",- {"fyers", "position", "portfolio", "india"},- true},- {"dhan_positions",- "Dhan Positions → POSITION",- "Map Dhan position data to standard POSITION format",- "Dhan",- "POSITION",- {"dhan", "position", "portfolio", "india"},- true},- {"dhan_orders",- "Dhan Orders → ORDER",- "Map Dhan order data to standard ORDER format",- "Dhan",- "ORDER",- {"dhan", "order", "trading", "india"},- true},- {"zerodha_ohlc",- "Zerodha OHLC → OHLCV",- "Map Zerodha Kite OHLC data to standard OHLCV format",- "Zerodha",+ {"crypto", "binance", "ticker", "free"},+ true,+ "https://api.binance.com",+ "/api/v3/ticker/24hr?symbol=BTCUSDT",+ "GET",+ "None",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"symbol", "$.symbol", "", ""},+ {"price", "$.lastPrice", "to_number", "0"},+ {"bid", "$.bidPrice", "to_number", "0"},+ {"ask", "$.askPrice", "to_number", "0"},+ {"bidSize", "$.bidQty", "to_number", "0"},+ {"askSize", "$.askQty", "to_number", "0"},+ {"volume", "$.volume", "to_number", "0"},+ {"change", "$.priceChange", "to_number", "0"},+ {"changePercent", "$.priceChangePercent", "to_number", "0"},+ {"open", "$.openPrice", "to_number", "0"},+ {"high", "$.highPrice", "to_number", "0"},+ {"low", "$.lowPrice", "to_number", "0"},+ {"previousClose", "$.prevClosePrice", "to_number", "0"}}},++ {"kraken_ohlcv",+ "Kraken OHLC → OHLCV",+ "Fetch OHLC data from Kraken. Free public endpoint, no API key required. "+ "Intervals: 1, 5, 15, 30, 60, 240, 1440, 10080, 21600 minutes.",+ "Kraken",+ "OHLCV",+ {"crypto", "kraken", "ohlc", "free"},+ true,+ "https://api.kraken.com",+ "/0/public/OHLC?pair=XBTUSD&interval=60",+ "GET",+ "None",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"timestamp", "$.result.XXBTZUSD[*][0]", "unix_to_iso", ""},+ {"open", "$.result.XXBTZUSD[*][1]", "to_number", "0"},+ {"high", "$.result.XXBTZUSD[*][2]", "to_number", "0"},+ {"low", "$.result.XXBTZUSD[*][3]", "to_number", "0"},+ {"close", "$.result.XXBTZUSD[*][4]", "to_number", "0"},+ {"vwap", "$.result.XXBTZUSD[*][5]", "to_number", "0"},+ {"volume", "$.result.XXBTZUSD[*][6]", "to_number", "0"},+ {"trades", "$.result.XXBTZUSD[*][7]", "to_number", "0"},+ {"symbol", "", "", "XBTUSD"}}},++ // ── API Key Required (Free Tier) ───────────────────────────────────++ {"alphavantage_ohlcv",+ "Alpha Vantage Intraday → OHLCV",+ "Fetch intraday OHLCV from Alpha Vantage. Free tier: 25 requests/day. "+ "Intervals: 1min, 5min, 15min, 30min, 60min. Set your API key in AUTH VALUE.",+ "Alpha Vantage","OHLCV",- {"zerodha", "kite", "ohlc", "india"},- true},- {"angelone_quote",- "Angel One Quote → QUOTE",- "Map Angel One market data to standard QUOTE format",- "Angel One",+ {"stocks", "alphavantage", "intraday", "free-tier"},+ true,+ "https://www.alphavantage.co",+ "/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=YOUR_KEY",+ "GET",+ "API Key",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"timestamp", "$.['Time Series (5min)'].*~", "", ""},+ {"open", "$.['Time Series (5min)'].*.['1. open']", "to_number", "0"},+ {"high", "$.['Time Series (5min)'].*.['2. high']", "to_number", "0"},+ {"low", "$.['Time Series (5min)'].*.['3. low']", "to_number", "0"},+ {"close", "$.['Time Series (5min)'].*.['4. close']", "to_number", "0"},+ {"volume", "$.['Time Series (5min)'].*.['5. volume']", "to_number", "0"},+ {"symbol", "", "", "IBM"}}},++ {"twelvedata_ohlcv",+ "Twelve Data Time Series → OHLCV",+ "Fetch OHLCV time series from Twelve Data. Free tier: 800 requests/day. "+ "Supports stocks, forex, crypto. Set API key in AUTH VALUE field.",+ "Twelve Data",+ "OHLCV",+ {"stocks", "forex", "crypto", "twelvedata", "free-tier"},+ true,+ "https://api.twelvedata.com",+ "/time_series?symbol=AAPL&interval=1h&outputsize=30&apikey=YOUR_KEY",+ "GET",+ "API Key",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"timestamp", "$.values[*].datetime", "", ""},+ {"open", "$.values[*].open", "to_number", "0"},+ {"high", "$.values[*].high", "to_number", "0"},+ {"low", "$.values[*].low", "to_number", "0"},+ {"close", "$.values[*].close", "to_number", "0"},+ {"volume", "$.values[*].volume", "to_number", "0"},+ {"symbol", "$.meta.symbol", "", ""}}},++ {"finnhub_quote",+ "Finnhub Quote → QUOTE",+ "Fetch real-time stock quote from Finnhub. Free tier: 60 calls/min. "+ "Returns current price, change, high/low, open, previous close. Set API key in AUTH VALUE.",+ "Finnhub",+ "QUOTE",+ {"stocks", "finnhub", "free-tier", "us"},+ true,+ "https://finnhub.io",+ "/api/v1/quote?symbol=AAPL&token=YOUR_KEY",+ "GET",+ "API Key",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"price", "$.c", "", "0"},+ {"change", "$.d", "", "0"},+ {"changePercent", "$.dp", "", "0"},+ {"high", "$.h", "", "0"},+ {"low", "$.l", "", "0"},+ {"open", "$.o", "", "0"},+ {"previousClose", "$.pc", "", "0"},+ {"timestamp", "$.t", "unix_to_iso", ""},+ {"symbol", "", "", "AAPL"}}},++ {"coinmarketcap_quote",+ "CoinMarketCap Latest → QUOTE",+ "Fetch latest crypto quotes from CoinMarketCap. Free tier: 10,000 calls/month. "+ "Returns price, volume, market cap, and 24h change. Set API key in AUTH VALUE.",+ "CoinMarketCap",+ "QUOTE",+ {"crypto", "coinmarketcap", "free-tier"},+ true,+ "https://pro-api.coinmarketcap.com",+ "/v1/cryptocurrency/quotes/latest?symbol=BTC&convert=USD",+ "GET",+ "API Key",+ "Accept: application/json\nX-CMC_PRO_API_KEY: YOUR_KEY",+ "",+ "JSONPath",+ {{"symbol", "$.data.BTC.symbol", "", ""},+ {"price", "$.data.BTC.quote.USD.price", "", "0"},+ {"volume", "$.data.BTC.quote.USD.volume_24h", "", "0"},+ {"change", "$.data.BTC.quote.USD.percent_change_24h", "", "0"},+ {"changePercent", "$.data.BTC.quote.USD.percent_change_24h", "", "0"},+ {"timestamp", "$.data.BTC.quote.USD.last_updated", "", ""}}},++ // ── Global Broker APIs (Auth Required) ─────────────────────────────++ {"alpaca_ohlcv",+ "Alpaca Bars → OHLCV",+ "Fetch historical bar data from Alpaca Markets. Free paper trading account available. "+ "Set API key as 'APCA-API-KEY-ID' and secret as 'APCA-API-SECRET-KEY' in headers.",+ "Alpaca",+ "OHLCV",+ {"stocks", "alpaca", "bars", "us"},+ true,+ "https://data.alpaca.markets",+ "/v2/stocks/AAPL/bars?timeframe=1Hour&start=2024-03-01&limit=100",+ "GET",+ "API Key",+ "Accept: application/json\nAPCA-API-KEY-ID: YOUR_KEY\nAPCA-API-SECRET-KEY: YOUR_SECRET",+ "",+ "JSONPath",+ {{"timestamp", "$.bars[*].t", "", ""},+ {"open", "$.bars[*].o", "", "0"},+ {"high", "$.bars[*].h", "", "0"},+ {"low", "$.bars[*].l", "", "0"},+ {"close", "$.bars[*].c", "", "0"},+ {"volume", "$.bars[*].v", "", "0"},+ {"vwap", "$.bars[*].vw", "", "0"},+ {"trades", "$.bars[*].n", "", "0"},+ {"symbol", "$.symbol", "", "AAPL"}}},++ {"alpaca_positions",+ "Alpaca Positions → POSITION",+ "Fetch open positions from Alpaca. Works with paper or live accounts. "+ "Set API credentials in headers.",+ "Alpaca",+ "POSITION",+ {"stocks", "alpaca", "positions", "us"},+ true,+ "https://paper-api.alpaca.markets",+ "/v2/positions",+ "GET",+ "API Key",+ "Accept: application/json\nAPCA-API-KEY-ID: YOUR_KEY\nAPCA-API-SECRET-KEY: YOUR_SECRET",+ "",+ "JSONPath",+ {{"symbol", "$[*].symbol", "", ""},+ {"quantity", "$[*].qty", "to_number", "0"},+ {"averagePrice", "$[*].avg_entry_price", "to_number", "0"},+ {"currentPrice", "$[*].current_price", "to_number", "0"},+ {"marketValue", "$[*].market_value", "to_number", "0"},+ {"costBasis", "$[*].cost_basis", "to_number", "0"},+ {"pnl", "$[*].unrealized_pl", "to_number", "0"},+ {"pnlPercent", "$[*].unrealized_plpc", "to_number", "0"},+ {"exchange", "$[*].exchange", "", ""}}},++ {"tradier_quote",+ "Tradier Quote → QUOTE",+ "Fetch stock quotes from Tradier. Free sandbox available. "+ "Set Bearer token in AUTH VALUE. Use sandbox URL for testing.",+ "Tradier","QUOTE",- {"angelone", "quote", "india"},- true},+ {"stocks", "tradier", "us", "options"},+ true,+ "https://sandbox.tradier.com",+ "/v1/markets/quotes?symbols=AAPL",+ "GET",+ "Bearer Token",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"symbol", "$.quotes.quote.symbol", "", ""},+ {"price", "$.quotes.quote.last", "", "0"},+ {"bid", "$.quotes.quote.bid", "", "0"},+ {"ask", "$.quotes.quote.ask", "", "0"},+ {"volume", "$.quotes.quote.volume", "", "0"},+ {"change", "$.quotes.quote.change", "", "0"},+ {"changePercent", "$.quotes.quote.change_percentage", "", "0"},+ {"open", "$.quotes.quote.open", "", "0"},+ {"high", "$.quotes.quote.high", "", "0"},+ {"low", "$.quotes.quote.low", "", "0"},+ {"previousClose", "$.quotes.quote.prevclose", "", "0"}}},++ // ── Macro / Economic Data ──────────────────────────────────────────++ {"dbnomics_ohlcv",+ "DBnomics Series → OHLCV",+ "Fetch economic time series from DBnomics. Free, no API key. "+ "Access 100M+ series from ECB, Fed, World Bank, IMF. Replace provider/dataset/series in endpoint.",+ "DBnomics",+ "OHLCV",+ {"economics", "macro", "dbnomics", "free"},+ true,+ "https://api.db.nomics.world",+ "/v22/series/IMF/WEO:2024-04/USA.NGDP_RPCH.pcent_change?observations=1",+ "GET",+ "None",+ "Accept: application/json",+ "",+ "JSONPath",+ {{"timestamp", "$.series.docs[0].period", "", ""},+ {"close", "$.series.docs[0].value", "", "0"},+ {"symbol", "$.series.docs[0].series_code", "", ""}}},};}@@ -741,8 +1039,10 @@ QWidget* DataMappingScreen::create_schema_panel() {schema_fields_table_->setItem(i, 2, new QTableWidgetItem(fields[i].required ? "Yes" : "No"));schema_fields_table_->setItem(i, 3, new QTableWidgetItem(fields[i].description));}- right_schema_info_->setText("Schema: " + g_schemas[idx].name);- right_fields_info_->setText("Fields: " + QString::number(fields.size()));+ if (right_schema_info_)+ right_schema_info_->setText("Schema: " + g_schemas[idx].name);+ if (right_fields_info_)+ right_fields_info_->setText("Fields: " + QString::number(fields.size()));}});bl->addWidget(create_form_row("SELECT SCHEMA", schema_select_));@@ -1033,12 +1333,33 @@ QWidget* DataMappingScreen::create_template_view() {connect(use_btn, &QPushButton::clicked, this, [this]() {int row = template_list_->currentRow();if (row >= 0 && row < g_templates.size()) {- // Pre-populate create form from template- api_name_->setText(g_templates[row].name);- schema_select_->setCurrentText(g_templates[row].schema);+ const auto& tmpl = g_templates[row];+ // Pre-populate all form fields from template+ api_name_->setText(tmpl.name);+ api_base_url_->setText(tmpl.base_url);+ api_endpoint_->setText(tmpl.endpoint);+ api_method_->setCurrentText(tmpl.method);+ api_auth_type_->setCurrentText(tmpl.auth_type);+ api_headers_->setPlainText(tmpl.headers);+ api_body_->setPlainText(tmpl.body);+ schema_select_->setCurrentText(tmpl.schema);+ parser_engine_->setCurrentText(tmpl.parser);++ // Pre-populate field mapping table+ mapping_table_->setRowCount(tmpl.field_mappings.size());+ for (int i = 0; i < tmpl.field_mappings.size(); ++i) {+ const auto& fm = tmpl.field_mappings[i];+ auto* name_item = new QTableWidgetItem(fm.target);+ name_item->setFlags(name_item->flags() & ~Qt::ItemIsEditable);+ mapping_table_->setItem(i, 0, name_item);+ mapping_table_->setItem(i, 1, new QTableWidgetItem(fm.expression));+ mapping_table_->setItem(i, 2, new QTableWidgetItem(fm.transform));+ mapping_table_->setItem(i, 3, new QTableWidgetItem(fm.default_val));+ }+on_view_changed(2); // switch to createon_step_changed(0);- LOG_INFO("DataMapping", "Template applied: " + g_templates[row].name);+ LOG_INFO("DataMapping", "Template applied: " + tmpl.name);}});dvl->addWidget(use_btn);@@ -1419,13 +1740,23 @@ void DataMappingScreen::on_template_selected(int index) {const auto& tmpl = g_templates[index];QString detail = QString("NAME: %1\n\n"- "BROKER: %2\n"+ "PROVIDER: %2\n""SCHEMA: %3\n""VERIFIED: %4\n\n""DESCRIPTION:\n%5\n\n"- "TAGS: %6")- .arg(tmpl.name, tmpl.broker, tmpl.schema, tmpl.verified ? "Yes" : "No", tmpl.description,- tmpl.tags.join(", "));+ "API DETAILS:\n"+ " Base URL: %6\n"+ " Endpoint: %7\n"+ " Method: %8\n"+ " Auth: %9\n\n"+ "FIELD MAPPINGS: %10 fields configured\n"+ "PARSER: %11\n\n"+ "TAGS: %12")+ .arg(tmpl.name, tmpl.broker, tmpl.schema,+ tmpl.verified ? "Yes" : "No", tmpl.description,+ tmpl.base_url, tmpl.endpoint, tmpl.method,+ tmpl.auth_type, QString::number(tmpl.field_mappings.size()),+ tmpl.parser, tmpl.tags.join(", "));template_detail_->setText(detail);}diff --git a/fincept-qt/src/screens/economics/panels/AkShareChinaPanel.cpp b/fincept-qt/src/screens/economics/panels/AkShareChinaPanel.cppnew file mode 100644index 000000000..35b49e77e--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/AkShareChinaPanel.cpp@@ -0,0 +1,100 @@+// src/screens/economics/panels/AkShareChinaPanel.cpp+// AkShare China macroeconomic data panel. No API key required.+//+// Response shape: { success:true, data:[{...}], count, timestamp, source }+// Column names are in Chinese — displayed as-is in the table.+// Working commands: cpi, ppi, gdp, pmi+#include "screens/economics/panels/AkShareChinaPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "akshare_economics_china.py";+static constexpr const char* kSourceId = "akshare_cn";+static constexpr const char* kColor = "#DC2626"; // China red++struct AkCnSeries {+ QString label;+ QString command;+ QString description;+};++static const QList<AkCnSeries> kSeries = {+ { "CPI (Consumer Price Index)", "cpi", "Monthly CPI year-on-year & month-on-month" },+ { "PPI (Producer Price Index)", "ppi", "Monthly PPI change rates" },+ { "GDP (Gross Domestic Product)", "gdp", "Quarterly GDP by expenditure approach" },+ { "PMI (Manufacturing & Services)", "pmi", "Monthly PMI — official NBS data" },+};++AkShareChinaPanel::AkShareChinaPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &AkShareChinaPanel::on_result);+}++void AkShareChinaPanel::activate() {+ show_empty("Select a series and click FETCH\n"+ "Source: AkShare — China NBS macroeconomic data (no API key required)\n"+ "Note: column headers are in Chinese as provided by the source");+}++void AkShareChinaPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("SERIES");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ series_combo_ = new QComboBox;+ for (const auto& s : kSeries)+ series_combo_->addItem(s.label, s.command);+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(260);+ series_combo_->setToolTip("Data from China National Bureau of Statistics via AkShare");++ thl->addWidget(lbl);+ thl->addWidget(series_combo_);+}++void AkShareChinaPanel::on_fetch() {+ const int idx = series_combo_->currentIndex();+ const auto& series = kSeries[idx];++ show_loading("Fetching AkShare China: " + series.label + "…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, series.command, {},+ "akcn_" + series.command);+}++void AkShareChinaPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("akcn_")) return;+ if (!result.success) { show_error(result.error); return; }++ // Response: {success, data:[{...}], count}+ QJsonArray rows = result.data["data"].toArray();++ if (rows.isEmpty()) {+ const QString err = result.data["error"].toString();+ show_error(err.isEmpty() ? "No data returned" : err);+ return;+ }++ const int idx = series_combo_->currentIndex();+ const QString title = "AkShare China: "+ + (idx >= 0 && idx < kSeries.size() ? kSeries[idx].label : request_id.mid(6));++ display(rows, title);+ LOG_INFO("AkShareChinaPanel", QString("Displayed %1 rows: %2")+ .arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/AkShareChinaPanel.h b/fincept-qt/src/screens/economics/panels/AkShareChinaPanel.hnew file mode 100644index 000000000..17766f69e--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/AkShareChinaPanel.h@@ -0,0 +1,29 @@+// src/screens/economics/panels/AkShareChinaPanel.h+// AkShare China macroeconomic data — no API key required.+// Script: akshare_economics_china.py+// Working commands: cpi, ppi, gdp, pmi+// Note: column names are in Chinese — displayed as-is in the table.+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class AkShareChinaPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit AkShareChinaPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* series_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/BcbPanel.cpp b/fincept-qt/src/screens/economics/panels/BcbPanel.cppnew file mode 100644index 000000000..efc1bca59--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/BcbPanel.cpp@@ -0,0 +1,137 @@+// src/screens/economics/panels/BcbPanel.cpp+// Brazil Central Bank (Banco Central do Brasil) data panel.+// No API key required.+//+// Response shape: { success:true, series, series_id, name, unit, frequency,+// data:[{date:"DD/MM/YYYY", <value_key>:float}], count, source }+// Normalise: rename value key to "value", parse date to ISO format.+#include "screens/economics/panels/BcbPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "bcb_data.py";+static constexpr const char* kSourceId = "bcb";+static constexpr const char* kColor = "#16A34A"; // green (Brazil flag)++struct BcbSeries {+ QString label;+ QString command;+ QString value_key; // field name in each data record+ QString unit;+};++static const QList<BcbSeries> kSeries = {+ { "Selic Target Rate", "selic", "selic_target", "% p.a." },+ { "IPCA Inflation", "ipca", "ipca", "% monthly" },+ { "GDP Growth Rate", "gdp", "gdp_growth", "% annual" },+ { "Unemployment Rate", "unemployment", "unemployment", "%" },+ { "Total Credit (BRL M)", "credit", "credit_total", "BRL M" },+ { "International Reserves", "reserves", "reserves", "USD M" },+};++// Convert BCB date "DD/MM/YYYY" to ISO "YYYY-MM-DD"+static QString bcb_date_to_iso(const QString& d) {+ // d is "29/03/2021"+ if (d.length() == 10 && d[2] == '/' && d[5] == '/') {+ return d.mid(6, 4) + "-" + d.mid(3, 2) + "-" + d.mid(0, 2);+ }+ return d;+}++BcbPanel::BcbPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &BcbPanel::on_result);+}++void BcbPanel::activate() {+ show_empty("Select a series and click FETCH\n"+ "Source: Banco Central do Brasil — no API key required");+}++void BcbPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("SERIES");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ series_combo_ = new QComboBox;+ for (const auto& s : kSeries)+ series_combo_->addItem(s.label + " (" + s.unit + ")", s.command);+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(260);++ thl->addWidget(lbl);+ thl->addWidget(series_combo_);+}++void BcbPanel::on_fetch() {+ const int idx = series_combo_->currentIndex();+ const auto& series = kSeries[idx];++ show_loading("Fetching BCB: " + series.label + "…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, series.command, {},+ "bcb_" + series.command);+}++void BcbPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("bcb_")) return;+ if (!result.success) { show_error(result.error); return; }++ // Find series descriptor from command suffix+ const QString cmd = request_id.mid(4); // strip "bcb_"+ const BcbSeries* series_ptr = nullptr;+ for (const auto& s : kSeries)+ if (s.command == cmd) { series_ptr = &s; break; }++ // Extract data array — may be under "data" key directly or wrapped by service+ QJsonArray raw = result.data["data"].toArray();++ if (raw.isEmpty()) {+ show_error("No data returned for this series");+ return;+ }++ // Normalise: rename value_key -> "value", convert date format+ QJsonArray rows;+ for (const auto& rv : raw) {+ const QJsonObject r = rv.toObject();+ QJsonObject row;+ row["date"] = bcb_date_to_iso(r["date"].toString());+ // value may be under the specific key or already normalised+ if (series_ptr && r.contains(series_ptr->value_key)) {+ row["value"] = r[series_ptr->value_key];+ } else {+ // Pick first numeric field that isn't "date"+ for (auto it = r.constBegin(); it != r.constEnd(); ++it) {+ if (it.key() != "date" && it.value().isDouble()) {+ row["value"] = it.value();+ break;+ }+ }+ }+ rows.append(row);+ }++ const int idx = series_combo_->currentIndex();+ const QString unit = (idx >= 0 && idx < kSeries.size())+ ? " (" + kSeries[idx].unit + ")" : "";+ const QString title = "BCB: " + (series_ptr ? series_ptr->label : cmd) + unit;++ display(rows, title);+ LOG_INFO("BcbPanel", QString("Displayed %1 records: %2").arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/BcbPanel.h b/fincept-qt/src/screens/economics/panels/BcbPanel.hnew file mode 100644index 000000000..4789e7829--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/BcbPanel.h@@ -0,0 +1,28 @@+// src/screens/economics/panels/BcbPanel.h+// Brazil Central Bank (BCB / Banco Central do Brasil) — no API key required.+// Script: bcb_data.py+// Working commands: selic, ipca, gdp, unemployment, credit, reserves+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class BcbPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit BcbPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* series_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/BlsPanel.cpp b/fincept-qt/src/screens/economics/panels/BlsPanel.cppnew file mode 100644index 000000000..5dbdfac35--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/BlsPanel.cpp@@ -0,0 +1,204 @@+// src/screens/economics/panels/BlsPanel.cpp+// BLS data panel. Requires BLS_API_KEY environment variable.+//+// Response shape (series overview commands):+// { series: [{series_id, title, data:[{year,period,value,...}]}] }+// or for overview commands:+// { series_data: [...] } / { data: [...] }+//+// Error shape when no key:+// { error: true, message: "BLS API key required...", endpoint, status_code, timestamp }+#include "screens/economics/panels/BlsPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "bls_data.py";+static constexpr const char* kSourceId = "bls";+static constexpr const char* kColor = "#DC2626"; // BLS red++struct BlsPreset {+ QString label;+ QString command;+ QString series_id; // non-empty -> use get_series command+};++static const QList<BlsPreset> kPresets = {+ { "-- Select a series --", "", "" },+ { "Total Nonfarm Employment", "get_series", "CES0000000001"},+ { "Unemployment Rate (U-3)", "get_series", "LNS14000000" },+ { "CPI All Urban Consumers", "get_series", "CUUR0000SA0" },+ { "CPI Less Food & Energy (Core)", "get_series", "CUUR0000SA0L1E"},+ { "PPI Final Demand", "get_series", "WPUFD4" },+ { "Average Hourly Earnings", "get_series", "CES0500000003"},+ { "Labor Force Participation Rate", "get_series", "LNS11300000" },+ { "Job Openings (JOLTS)", "get_series", "JTS000000000000000JOL"},+ { "Labor Market Overview", "get_labor_overview", "" },+ { "Inflation Overview", "get_inflation_overview",""},+ { "Employment Cost Index", "get_employment_cost_index",""},+ { "Productivity & Costs", "get_productivity_costs",""},+};++BlsPanel::BlsPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &BlsPanel::on_result);+}++void BlsPanel::activate() {+ show_empty("Set BLS_API_KEY environment variable, then select a series and click FETCH\n"+ "Get a free key at: data.bls.gov/registrationEngine/");+}++void BlsPanel::build_controls(QHBoxLayout* thl) {+ auto lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ preset_combo_ = new QComboBox;+ for (const auto& p : kPresets)+ preset_combo_->addItem(p.label, p.command + "|" + p.series_id);+ preset_combo_->setFixedHeight(26);+ preset_combo_->setMinimumWidth(240);++ connect(preset_combo_, &QComboBox::currentIndexChanged, this,+ [this](int idx) {+ if (idx > 0 && idx < kPresets.size()) {+ const auto& p = kPresets[idx];+ if (!p.series_id.isEmpty())+ series_input_->setText(p.series_id);+ }+ });++ auto* lbl2 = new QLabel("SERIES ID");+ lbl2->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ series_input_ = new QLineEdit;+ series_input_->setPlaceholderText("e.g. CES0000000001");+ series_input_->setFixedHeight(26);+ series_input_->setFixedWidth(140);++ thl->addWidget(lbl("PRESET"));+ thl->addWidget(preset_combo_);+ thl->addWidget(lbl2);+ thl->addWidget(series_input_);+}++void BlsPanel::on_fetch() {+ const int idx = preset_combo_->currentIndex();+ if (idx <= 0) {+ // Check manual series ID+ const QString sid = series_input_->text().trimmed().toUpper();+ if (sid.isEmpty()) { show_empty("Select a preset or enter a series ID"); return; }+ show_loading("Fetching BLS series " + sid + "…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, "get_series", {sid}, "bls_series_" + sid);+ return;+ }++ const auto& preset = kPresets[idx];+ show_loading("Fetching BLS: " + preset.label + "…");++ if (preset.command == "get_series") {+ const QString sid = series_input_->text().trimmed().toUpper();+ const QString use_sid = sid.isEmpty() ? preset.series_id : sid;+ services::EconomicsService::instance().execute(+ kSourceId, kScript, "get_series", {use_sid},+ "bls_series_" + use_sid);+ } else {+ services::EconomicsService::instance().execute(+ kSourceId, kScript, preset.command, {},+ "bls_" + preset.command);+ }+}++// Normalize various BLS response shapes into a flat QJsonArray for display().+static QJsonArray extract_bls_rows(const QJsonObject& data) {+ // Shape 1: {series:[{series_id, title, data:[{year,period,value}]}]}+ const QJsonArray series_arr = data["series"].toArray();+ if (!series_arr.isEmpty()) {+ QJsonArray rows;+ for (const auto& sv : series_arr) {+ const QJsonObject s = sv.toObject();+ const QString title = s["title"].toString(s["series_id"].toString());+ for (const auto& dv : s["data"].toArray()) {+ QJsonObject row = dv.toObject();+ row["series"] = title;+ // Combine year+period into a date string+ const QString year = row["year"].toString();+ const QString period = row["period"].toString(); // e.g. "M01"+ if (!year.isEmpty() && !period.isEmpty() && period != "M13") {+ const QString month = period.mid(1).rightJustified(2, '0');+ row["date"] = year + "-" + month;+ }+ rows.append(row);+ }+ }+ return rows;+ }++ // Shape 2: {series_data:[...]} or {data:[...]}+ QJsonArray fallback = data["series_data"].toArray();+ if (fallback.isEmpty()) fallback = data["data"].toArray();+ return fallback;+}++void BlsPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("bls_")) return;++ if (!result.success) {+ const QString msg = result.error;+ if (msg.contains("API key") || msg.contains("api_key") ||+ msg.contains("BLS_API_KEY")) {+ show_error("BLS API key not configured.\n"+ "Set BLS_API_KEY environment variable.\n"+ "Free key at: data.bls.gov/registrationEngine/");+ } else {+ show_error(msg);+ }+ return;+ }++ // Also check for error object inside successful result+ if (result.data["error"].toBool()) {+ const QString msg = result.data["message"].toString(result.data["error"].toString());+ if (msg.contains("API key") || msg.contains("BLS_API_KEY")) {+ show_error("BLS API key not configured.\n"+ "Set BLS_API_KEY environment variable.\n"+ "Free key at: data.bls.gov/registrationEngine/");+ } else {+ show_error(msg);+ }+ return;+ }++ const QJsonArray rows = extract_bls_rows(result.data);+ if (rows.isEmpty()) {+ show_error("No data returned");+ return;+ }++ const int idx = preset_combo_->currentIndex();+ const QString title = (idx > 0 && idx < kPresets.size())+ ? "BLS: " + kPresets[idx].label+ : "BLS: " + series_input_->text().trimmed().toUpper();+ display(rows, title);+ LOG_INFO("BlsPanel", QString("Displayed %1 rows").arg(rows.size()));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/BlsPanel.h b/fincept-qt/src/screens/economics/panels/BlsPanel.hnew file mode 100644index 000000000..4bb69b7a5--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/BlsPanel.h@@ -0,0 +1,31 @@+// src/screens/economics/panels/BlsPanel.h+// US Bureau of Labor Statistics — requires BLS_API_KEY env var.+// Script: bls_data.py+// Commands: get_popular, get_labor_overview, get_inflation_overview,+// get_employment_cost_index, get_productivity_costs, get_series+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>+#include <QLineEdit>++namespace fincept::screens {++class BlsPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit BlsPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* preset_combo_ = nullptr;+ QLineEdit* series_input_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/CensusPanel.cpp b/fincept-qt/src/screens/economics/panels/CensusPanel.cppnew file mode 100644index 000000000..6aae5134d--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/CensusPanel.cpp@@ -0,0 +1,133 @@+// src/screens/economics/panels/CensusPanel.cpp+// US Census Bureau data panel.+//+// Response shape: { headers: ["NAME","B01003_001E","state"], data: [{...}, ...], count: N }+// Flatten: each data row is already a dict — pass directly to display().+// Headers are Census variable codes; we rename known ones for readability.+#include "screens/economics/panels/CensusPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "census_data.py";+static constexpr const char* kSourceId = "census";+static constexpr const char* kColor = "#7C3AED"; // purple++struct CensusDataset {+ QString label;+ QString command;+ QString description;+};++static const QList<CensusDataset> kDatasets = {+ { "Population by State (ACS)", "acs", "Total population estimate by US state" },+ { "Housing by State (ACS)", "housing", "Housing units, occupancy & tenure by state" },+};++// Rename Census variable codes to human-readable labels+static const QMap<QString, QString> kVarNames = {+ { "NAME", "State" },+ { "B01003_001E", "Total Population"},+ { "state", "State FIPS" },+ { "B25001_001E", "Total Housing Units" },+ { "B25002_002E", "Occupied Units" },+ { "B25002_003E", "Vacant Units" },+ { "B25003_002E", "Owner Occupied" },+ { "B25003_003E", "Renter Occupied" },+};++QJsonArray CensusPanel::flatten_census(const QJsonObject& response) {+ const QJsonArray headers = response["headers"].toArray();+ const QJsonArray data = response["data"].toArray();++ if (headers.isEmpty() || data.isEmpty())+ return {};++ // Each data row is already a flat object — rename keys to friendly labels+ QJsonArray rows;+ for (const auto& rv : data) {+ const QJsonObject orig = rv.toObject();+ QJsonObject renamed;+ for (auto it = orig.constBegin(); it != orig.constEnd(); ++it) {+ const QString friendly = kVarNames.value(it.key(), it.key());+ renamed[friendly] = it.value();+ }+ rows.append(renamed);+ }+ return rows;+}++CensusPanel::CensusPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &CensusPanel::on_result);+}++void CensusPanel::activate() {+ show_empty("Select a dataset and click FETCH\n"+ "Source: US Census Bureau — American Community Survey (ACS 5-year)");+}++void CensusPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("DATASET");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ dataset_combo_ = new QComboBox;+ for (const auto& d : kDatasets)+ dataset_combo_->addItem(d.label, d.command);+ dataset_combo_->setFixedHeight(26);+ dataset_combo_->setMinimumWidth(220);+ dataset_combo_->setToolTip("ACS 5-year estimates, state level");++ thl->addWidget(lbl);+ thl->addWidget(dataset_combo_);+}++void CensusPanel::on_fetch() {+ const int idx = dataset_combo_->currentIndex();+ const auto& dataset = kDatasets[idx];++ show_loading("Fetching Census: " + dataset.label + "…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, dataset.command, {},+ "census_" + dataset.command);+}++void CensusPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("census_")) return;+ if (!result.success) { show_error(result.error); return; }++ // Try Census-specific flatten first+ QJsonArray rows = flatten_census(result.data);++ // Fallback: service normalised to {data:[...]}+ if (rows.isEmpty())+ rows = result.data["data"].toArray();++ if (rows.isEmpty()) {+ const QString err = result.data["error"].toString();+ show_error(err.isEmpty() ? "No data returned" : err);+ return;+ }++ const int idx = dataset_combo_->currentIndex();+ const QString title = "Census: " + (idx >= 0 && idx < kDatasets.size()+ ? kDatasets[idx].label+ : request_id.mid(7));+ display(rows, title);+ LOG_INFO("CensusPanel", QString("Displayed %1 rows for %2").arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/CensusPanel.h b/fincept-qt/src/screens/economics/panels/CensusPanel.hnew file mode 100644index 000000000..301500159--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/CensusPanel.h@@ -0,0 +1,31 @@+// src/screens/economics/panels/CensusPanel.h+// US Census Bureau — ACS demographic and housing data by state.+// Script: census_data.py+// Working commands: acs (population), housing+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class CensusPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit CensusPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ /// Flatten Census {headers, data} shape into [{col1, col2, ...}] for display().+ static QJsonArray flatten_census(const QJsonObject& response);++ QComboBox* dataset_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EcbPanel.cpp b/fincept-qt/src/screens/economics/panels/EcbPanel.cppnew file mode 100644index 000000000..d981d9cfc--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EcbPanel.cpp@@ -0,0 +1,129 @@+// src/screens/economics/panels/EcbPanel.cpp+// ECB SDMX data panel.+// Response shape: {<key>: [{dimensions:{...}, observations:[{period,value}], obs_count}], ...}+// Working commands: exchange_rates, inflation, money_supply+#include "screens/economics/panels/EcbPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "ecb_sdmx_data.py";+static constexpr const char* kSourceId = "ecb";+static constexpr const char* kColor = "#2563EB"; // ECB blue++// Series: display name -> {command, arg (optional currency)}+struct EcbSeries {+ QString label;+ QString command;+ QString arg; // currency for exchange_rates, empty otherwise+ QString result_key; // top-level JSON key in response+};++static const QList<EcbSeries> kSeries = {+ { "EUR/USD Exchange Rate", "exchange_rates", "USD", "exchange_rates" },+ { "EUR/GBP Exchange Rate", "exchange_rates", "GBP", "exchange_rates" },+ { "EUR/JPY Exchange Rate", "exchange_rates", "JPY", "exchange_rates" },+ { "EUR/CHF Exchange Rate", "exchange_rates", "CHF", "exchange_rates" },+ { "EUR/CNY Exchange Rate", "exchange_rates", "CNY", "exchange_rates" },+ { "Eurozone HICP Inflation", "inflation", "", "inflation" },+ { "M3 Money Supply", "money_supply", "", "money_supply" },+};++EcbPanel::EcbPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &EcbPanel::on_result);+}++void EcbPanel::activate() {+ show_empty("Select a series and click FETCH\n"+ "Source: European Central Bank SDMX 2.1 API");+}++void EcbPanel::build_controls(QHBoxLayout* thl) {+ auto lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ series_combo_ = new QComboBox;+ for (const auto& s : kSeries)+ series_combo_->addItem(s.label, s.command + "|" + s.arg);+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(220);++ thl->addWidget(lbl("SERIES"));+ thl->addWidget(series_combo_);+}++void EcbPanel::on_fetch() {+ const QString data = series_combo_->currentData().toString();+ const int idx = series_combo_->currentIndex();+ const auto& series = kSeries[idx];++ show_loading("Fetching ECB data: " + series.label + "…");++ QStringList args = { series.command };+ if (!series.arg.isEmpty()) args << series.arg;++ const QString req_id = "ecb_" + series.command+ + (series.arg.isEmpty() ? "" : "_" + series.arg);++ services::EconomicsService::instance().execute(+ kSourceId, kScript, series.command, args, req_id);+}++// ECB response: {<result_key>: [{dimensions:{}, observations:[{period,value}], obs_count}], ...}+// Flatten the first series' observations into a plain [{period, value}] array for display().+void EcbPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!result.success) { show_error(result.error); return; }+ if (!request_id.startsWith("ecb_")) return;++ // Find which series was fetched+ const int idx = series_combo_->currentIndex();+ if (idx < 0 || idx >= kSeries.size()) return;+ const auto& series = kSeries[idx];++ // Extract observations from first element of the result array+ const QJsonValue top = result.data[series.result_key];+ QJsonArray obs;++ if (top.isArray()) {+ const QJsonArray arr = top.toArray();+ if (!arr.isEmpty()) {+ obs = arr[0].toObject()["observations"].toArray();+ }+ } else if (top.isObject()) {+ // Fallback: result wrapped as object+ obs = top.toObject()["observations"].toArray();+ }++ // Also accept flat data array from service normalisation+ if (obs.isEmpty()) {+ obs = result.data["data"].toArray();+ }++ if (obs.isEmpty()) {+ show_error("No observations returned for " + series.label);+ return;+ }++ display(obs, "ECB: " + series.label);+ LOG_INFO("EcbPanel", QString("Displayed %1 observations for %2")+ .arg(obs.size()).arg(series.label));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EcbPanel.h b/fincept-qt/src/screens/economics/panels/EcbPanel.hnew file mode 100644index 000000000..0915712c2--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EcbPanel.h@@ -0,0 +1,29 @@+// src/screens/economics/panels/EcbPanel.h+// European Central Bank — exchange rates, inflation, money supply.+// Script: ecb_sdmx_data.py+// Working commands: exchange_rates, inflation, money_supply+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class EcbPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit EcbPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* series_combo_ = nullptr;+ QComboBox* country_combo_ = nullptr; // for exchange_rates currency+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EconDbPanel.cpp b/fincept-qt/src/screens/economics/panels/EconDbPanel.cppnew file mode 100644index 000000000..c717b3e4a--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EconDbPanel.cpp@@ -0,0 +1,187 @@+// src/screens/economics/panels/EconDbPanel.cpp+// EconDB macroeconomic indicators panel. No API key required.+//+// Response shape:+// { indicator, country, transform, observation_count,+// metadata: { description, frequency, country, ticker, dataset },+// observations: [ {date:"YYYY-MM-DD", value:float}, ... ] }+#include "screens/economics/panels/EconDbPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "econdb_data.py";+static constexpr const char* kSourceId = "econdb";+static constexpr const char* kColor = "#059669"; // green++static const QList<QPair<QString,QString>> kIndicators = {+ { "GDP (Nominal)", "gdp" },+ { "Real GDP", "rgdp" },+ { "CPI Inflation", "cpi" },+ { "PPI Inflation", "ppi" },+ { "Core Inflation", "core" },+ { "Unemployment Rate", "urate" },+ { "Employment", "emp" },+ { "Industrial Production", "ip" },+ { "Retail Sales", "reta" },+ { "Consumer Confidence", "conf" },+ { "Policy Interest Rate", "polir" },+ { "10-Year Yield", "y10yd" },+ { "3-Month Yield", "m3yd" },+ { "Government Debt (% GDP)", "gdebt" },+ { "Current Account (% GDP)", "ca" },+ { "Trade Balance", "tb" },+ { "Population", "pop" },+ { "Consumer Prices", "prc" },+ { "Gross Fixed Capital Fmn", "gfcf" },+ { "Exports", "exp" },+ { "Imports", "imp" },+};++// 49 countries available in EconDB (ISO2 codes)+static const QList<QPair<QString,QString>> kCountries = {+ { "United States", "US" },+ { "China", "CN" },+ { "Germany", "DE" },+ { "Japan", "JP" },+ { "United Kingdom", "GB" },+ { "France", "FR" },+ { "India", "IN" },+ { "Brazil", "BR" },+ { "Canada", "CA" },+ { "South Korea", "KR" },+ { "Australia", "AU" },+ { "Russia", "RU" },+ { "Mexico", "MX" },+ { "Spain", "ES" },+ { "Italy", "IT" },+ { "Netherlands", "NL" },+ { "Switzerland", "CH" },+ { "Turkey", "TR" },+ { "Poland", "PL" },+ { "Sweden", "SE" },+ { "Belgium", "BE" },+ { "Argentina", "AR" },+ { "Austria", "AT" },+ { "Bangladesh", "BD" },+ { "Chile", "CL" },+ { "Colombia", "CO" },+ { "Czech Republic", "CZ" },+ { "Denmark", "DK" },+ { "Egypt", "EG" },+ { "Finland", "FI" },+ { "Greece", "GR" },+ { "Hong Kong", "HK" },+ { "Hungary", "HU" },+ { "Indonesia", "ID" },+ { "Israel", "IL" },+ { "Malaysia", "MY" },+ { "Nigeria", "NG" },+ { "Norway", "NO" },+ { "Pakistan", "PK" },+ { "Peru", "PE" },+ { "Philippines", "PH" },+ { "Portugal", "PT" },+ { "Romania", "RO" },+ { "Saudi Arabia", "SA" },+ { "Singapore", "SG" },+ { "South Africa", "ZA" },+ { "Taiwan", "TW" },+ { "Thailand", "TH" },+ { "Ukraine", "UA" },+ { "Vietnam", "VN" },+};++EconDbPanel::EconDbPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &EconDbPanel::on_result);+}++void EconDbPanel::activate() {+ show_empty("Select an indicator and country, then click FETCH\n"+ "Source: EconDB — macroeconomic data, no API key required");+}++void EconDbPanel::build_controls(QHBoxLayout* thl) {+ auto lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ indicator_combo_ = new QComboBox;+ for (const auto& p : kIndicators)+ indicator_combo_->addItem(p.first, p.second);+ indicator_combo_->setFixedHeight(26);+ indicator_combo_->setMinimumWidth(180);++ country_combo_ = new QComboBox;+ for (const auto& c : kCountries)+ country_combo_->addItem(c.first, c.second);+ country_combo_->setFixedHeight(26);+ country_combo_->setMinimumWidth(130);++ thl->addWidget(lbl("INDICATOR"));+ thl->addWidget(indicator_combo_);+ thl->addWidget(lbl("COUNTRY"));+ thl->addWidget(country_combo_);+}++void EconDbPanel::on_fetch() {+ const QString indicator = indicator_combo_->currentData().toString();+ const QString country = country_combo_->currentData().toString();++ show_loading("Fetching EconDB: " + indicator_combo_->currentText()+ + " — " + country_combo_->currentText() + "…");++ services::EconomicsService::instance().execute(+ kSourceId, kScript, "indicator",+ { indicator, country },+ "econdb_" + indicator + "_" + country);+}++void EconDbPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("econdb_")) return;+ if (!result.success) { show_error(result.error); return; }++ // Primary shape: {observations:[{date,value}], metadata:{description,...}}+ QJsonArray obs = result.data["observations"].toArray();++ // Fallback: service may wrap as {data:[...]}+ if (obs.isEmpty())+ obs = result.data["data"].toArray();++ if (obs.isEmpty()) {+ show_error("No observations returned");+ return;+ }++ // Build descriptive title from metadata+ const QJsonObject meta = result.data["metadata"].toObject();+ const QString desc = meta["description"].toString();+ const QString freq = meta["frequency"].toString();+ const QString title = desc.isEmpty()+ ? "EconDB: " + indicator_combo_->currentText()+ + " — " + country_combo_->currentText()+ : "EconDB: " + desc+ + (freq.isEmpty() ? "" : " (" + freq + ")");++ display(obs, title);+ LOG_INFO("EconDbPanel", QString("Displayed %1 observations: %2")+ .arg(obs.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EconDbPanel.h b/fincept-qt/src/screens/economics/panels/EconDbPanel.hnew file mode 100644index 000000000..15ca26dca--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EconDbPanel.h@@ -0,0 +1,29 @@+// src/screens/economics/panels/EconDbPanel.h+// EconDB — macroeconomic indicators for 49 countries, no API key required.+// Script: econdb_data.py+// Command: indicator <code> <country_iso2>+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class EconDbPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit EconDbPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* indicator_combo_ = nullptr;+ QComboBox* country_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp b/fincept-qt/src/screens/economics/panels/EconPanelBase.cppnew file mode 100644index 000000000..e8860cade--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp@@ -0,0 +1,346 @@+// src/screens/economics/panels/EconPanelBase.cpp+#include "screens/economics/panels/EconPanelBase.h"++#include <QColor>+#include <QFile>+#include <QFileDialog>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QTextStream>+#include <QVBoxLayout>++namespace fincept::screens {++// ── Stylesheet ────────────────────────────────────────────────────────────────++QString EconPanelBase::panel_style() const {+ int r = QColor(color_).red();+ int g = QColor(color_).green();+ int b = QColor(color_).blue();+ return QString(+ "#econToolbar { background:#111111; border-bottom:1px solid #1a1a1a; }"+ "#econFetchBtn { background:%1; color:#080808; border:none;"+ " font-size:10px; font-weight:700; padding:4px 14px; }"+ "#econFetchBtn:hover { background:rgba(%2,%3,%4,0.75); }"+ "#econFetchBtn:disabled { background:#1a1a1a; color:#404040; }"+ "#econCsvBtn { background:transparent; color:#808080; border:1px solid #1a1a1a;"+ " font-size:10px; font-weight:700; padding:4px 10px; }"+ "#econCsvBtn:hover { color:#e5e5e5; background:#161616; }"+ "QComboBox, QSpinBox, QDateEdit, QLineEdit {"+ " background:#080808; color:#e5e5e5; border:1px solid #1a1a1a;"+ " font-size:11px; padding:2px 6px; }"+ "QComboBox::drop-down, QDateEdit::drop-down { border:none; }"+ "QComboBox QAbstractItemView { background:#111111; color:#e5e5e5;"+ " border:1px solid #1a1a1a; }"+ "QTableWidget { background:#080808; color:#e5e5e5; border:none;"+ " gridline-color:#1a1a1a; font-size:11px; alternate-background-color:#0a0a0a; }"+ "QTableWidget::item { padding:5px 8px; border-bottom:1px solid #1a1a1a; }"+ "QTableWidget::item:selected { background:rgba(%2,%3,%4,0.1); color:%1; }"+ "QHeaderView::section { background:#111111; color:#808080; border:none;"+ " border-bottom:2px solid #1a1a1a; border-right:1px solid #1a1a1a;"+ " padding:5px 8px; font-size:10px; font-weight:700; letter-spacing:0.5px; }"+ "#econStatCard { background:#0a0a0a; border:1px solid #1a1a1a; }"+ "#econStatCard:hover { border-color:#333333; }"+ "#econStatLabel { color:#808080; font-size:8px; font-weight:700;"+ " letter-spacing:1px; background:transparent; }"+ "#econStatVal { color:%1; font-size:15px; font-weight:700; background:transparent; }"+ "#econStatSub { color:#525252; font-size:9px; background:transparent; }"+ "#econEmptyPage { background:#080808; }"+ "#econEmptyMsg { color:#808080; font-size:13px; background:transparent; }"+ "#econErrMsg { color:#dc2626; font-size:12px; background:transparent; }"+ "#econTitleLbl { color:#e5e5e5; font-size:11px; font-weight:700;"+ " background:transparent; }"+ "#econRowCount { color:#525252; font-size:9px; background:transparent; }"+ "QScrollBar:vertical { background:#080808; width:5px; }"+ "QScrollBar::handle:vertical { background:#1a1a1a; min-height:20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }"+ "QScrollBar:horizontal { background:#080808; height:5px; }"+ "QScrollBar::handle:horizontal { background:#1a1a1a; min-width:20px; }"+ "QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal { width:0; }"+ ).arg(color_).arg(r).arg(g).arg(b);+}++// ── Constructor ───────────────────────────────────────────────────────────────++EconPanelBase::EconPanelBase(const QString& source_id,+ const QString& color,+ QWidget* parent)+ : QWidget(parent), source_id_(source_id), color_(color) {}++// ── Build ─────────────────────────────────────────────────────────────────────++void EconPanelBase::build_base_ui(QWidget* container) {+ container->setStyleSheet(panel_style());++ auto* root = new QVBoxLayout(container);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // Toolbar+ auto* toolbar = new QWidget;+ toolbar->setObjectName("econToolbar");+ toolbar->setFixedHeight(40);+ auto* thl = new QHBoxLayout(toolbar);+ thl->setContentsMargins(10, 0, 10, 0);+ thl->setSpacing(6);+ build_controls(thl);+ thl->addStretch(1);++ fetch_btn_ = new QPushButton("FETCH");+ fetch_btn_->setObjectName("econFetchBtn");+ fetch_btn_->setCursor(Qt::PointingHandCursor);+ connect(fetch_btn_, &QPushButton::clicked, this, &EconPanelBase::on_fetch);++ export_btn_ = new QPushButton("CSV");+ export_btn_->setObjectName("econCsvBtn");+ export_btn_->setCursor(Qt::PointingHandCursor);+ connect(export_btn_, &QPushButton::clicked, this, &EconPanelBase::export_csv);++ thl->addWidget(fetch_btn_);+ thl->addWidget(export_btn_);+ root->addWidget(toolbar);++ // Stat cards row+ auto* cards_row = new QWidget;+ cards_row->setStyleSheet("background:#080808; border-bottom:1px solid #1a1a1a;");+ auto* crhl = new QHBoxLayout(cards_row);+ crhl->setContentsMargins(10, 6, 10, 6);+ crhl->setSpacing(6);++ auto make_card = [&](const QString& label, QLabel*& out) {+ auto* card = new QWidget;+ card->setObjectName("econStatCard");+ card->setMinimumWidth(90);+ auto* vl = new QVBoxLayout(card);+ vl->setContentsMargins(10, 6, 10, 6);+ vl->setSpacing(1);+ auto* lbl = new QLabel(label);+ lbl->setObjectName("econStatLabel");+ out = new QLabel("—");+ out->setObjectName("econStatVal");+ vl->addWidget(lbl);+ vl->addWidget(out);+ crhl->addWidget(card);+ };+ make_card("LATEST", stat_latest_);+ make_card("CHANGE", stat_change_);+ make_card("MIN", stat_min_);+ make_card("MAX", stat_max_);+ make_card("AVG", stat_avg_);+ make_card("POINTS", stat_count_);+ crhl->addStretch(1);+ root->addWidget(cards_row);++ // Title bar+ auto* title_bar = new QWidget;+ title_bar->setStyleSheet("background:#0a0a0a; border-bottom:1px solid #1a1a1a;");+ auto* tbhl = new QHBoxLayout(title_bar);+ tbhl->setContentsMargins(12, 4, 12, 4);+ title_lbl_ = new QLabel;+ title_lbl_->setObjectName("econTitleLbl");+ row_count_ = new QLabel;+ row_count_->setObjectName("econRowCount");+ tbhl->addWidget(title_lbl_);+ tbhl->addStretch(1);+ tbhl->addWidget(row_count_);+ root->addWidget(title_bar);++ // Content stack+ stack_ = new QStackedWidget;++ auto* empty_pg = new QWidget;+ empty_pg->setObjectName("econEmptyPage");+ auto* evl = new QVBoxLayout(empty_pg);+ evl->setAlignment(Qt::AlignCenter);+ empty_lbl_ = new QLabel("Select parameters and click FETCH");+ empty_lbl_->setObjectName("econEmptyMsg");+ empty_lbl_->setAlignment(Qt::AlignCenter);+ empty_lbl_->setWordWrap(true);+ evl->addWidget(empty_lbl_);+ stack_->addWidget(empty_pg); // index 0++ table_ = new QTableWidget;+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->verticalHeader()->setVisible(false);+ table_->setAlternatingRowColors(true);+ table_->setShowGrid(true);+ stack_->addWidget(table_); // index 1++ root->addWidget(stack_, 1);+}++// ── State ─────────────────────────────────────────────────────────────────────++void EconPanelBase::show_loading(const QString& msg) {+ if (!empty_lbl_) return;+ empty_lbl_->setStyleSheet(+ QString("color:%1; font-size:13px; background:transparent;").arg(color_));+ empty_lbl_->setText(msg);+ stack_->setCurrentIndex(0);+ if (fetch_btn_) fetch_btn_->setEnabled(false);+}++void EconPanelBase::show_error(const QString& msg) {+ if (!empty_lbl_) return;+ empty_lbl_->setStyleSheet("color:#dc2626; font-size:12px; background:transparent;");+ empty_lbl_->setText("Error: " + msg);+ stack_->setCurrentIndex(0);+ if (fetch_btn_) fetch_btn_->setEnabled(true);+}++void EconPanelBase::show_empty(const QString& msg) {+ if (!empty_lbl_) return;+ empty_lbl_->setStyleSheet("color:#808080; font-size:13px; background:transparent;");+ empty_lbl_->setText(msg);+ stack_->setCurrentIndex(0);+ if (fetch_btn_) fetch_btn_->setEnabled(true);+}++void EconPanelBase::show_table() {+ stack_->setCurrentIndex(1);+ if (fetch_btn_) fetch_btn_->setEnabled(true);+}++// ── Display ───────────────────────────────────────────────────────────────────++void EconPanelBase::display(const QJsonArray& rows, const QString& title) {+ if (rows.isEmpty()) { show_empty("No data returned for this selection"); return; }++ // Collect all keys, prioritise date then value+ QStringList cols;+ for (const auto& v : rows) {+ for (const auto& k : v.toObject().keys())+ if (!cols.contains(k)) cols << k;+ }+ static const QStringList kDateKeys = {+ "date","period","year","time","Date","Period","TIME_PERIOD","record_date","ref_date"};+ for (const auto& dk : kDateKeys) {+ int idx = cols.indexOf(dk);+ if (idx > 0) { cols.move(idx, 0); break; }+ }+ static const QStringList kValKeys = {+ "value","Value","val","OBS_VALUE","obs_value","amount","rate"};+ for (const auto& vk : kValKeys) {+ int idx = cols.indexOf(vk);+ if (idx > 1) { cols.move(idx, 1); break; }+ }++ table_->setColumnCount(cols.size());+ table_->setHorizontalHeaderLabels(cols);+ table_->setRowCount(rows.size());++ for (int r = 0; r < rows.size(); ++r) {+ const auto obj = rows[r].toObject();+ for (int c = 0; c < cols.size(); ++c) {+ const auto jv = obj[cols[c]];+ QString text;+ if (jv.isDouble())+ text = QString::number(jv.toDouble(), 'g', 8);+ else+ text = jv.toString();+ auto* item = new QTableWidgetItem(text);+ if (c == 0) item->setForeground(QColor(color_));+ table_->setItem(r, c, item);+ }+ }++ table_->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);+ if (cols.size() > 1)+ table_->horizontalHeader()->setSectionResizeMode(+ cols.size() - 1, QHeaderView::Stretch);++ if (title_lbl_) title_lbl_->setText(title);+ if (row_count_) row_count_->setText(QString::number(rows.size()) + " records");++ update_stats(rows);+ show_table();+}++void EconPanelBase::update_stats(const QJsonArray& rows) {+ QVector<double> vals;+ for (const auto& v : rows) {+ const auto obj = v.toObject();+ QJsonValue jv = obj["value"];+ if (jv.isUndefined()) jv = obj["Value"];+ if (jv.isUndefined()) jv = obj["OBS_VALUE"];+ if (jv.isUndefined()) jv = obj["obs_value"];+ if (jv.isUndefined()) jv = obj["amount"];+ if (jv.isUndefined()) jv = obj["rate"];+ if (jv.isUndefined()) {+ auto keys = obj.keys();+ if (keys.size() > 1) jv = obj[keys[1]];+ }+ bool ok = false;+ double d = jv.toString().toDouble(&ok);+ if (!ok && jv.isDouble()) { d = jv.toDouble(); ok = true; }+ if (ok) vals << d;+ }++ if (vals.isEmpty()) {+ for (auto* l : {stat_latest_, stat_change_, stat_min_,+ stat_max_, stat_avg_, stat_count_})+ if (l) l->setText("—");+ if (stat_count_) stat_count_->setText(QString::number(rows.size()));+ return;+ }++ double latest = vals.last();+ double prev = vals.size() > 1 ? vals[vals.size() - 2] : latest;+ double change = (prev != 0.0) ? ((latest - prev) / qAbs(prev)) * 100.0 : 0.0;+ double mn = *std::min_element(vals.begin(), vals.end());+ double mx = *std::max_element(vals.begin(), vals.end());+ double sum = 0.0;+ for (double x : vals) sum += x;+ double avg = sum / vals.size();++ auto fmt = [](double v) { return QString::number(v, 'g', 6); };++ if (stat_latest_) stat_latest_->setText(fmt(latest));+ if (stat_change_) {+ stat_change_->setText((change >= 0 ? "+" : "") ++ QString::number(change, 'f', 2) + "%");+ stat_change_->setStyleSheet(+ QString("color:%1; font-size:15px; font-weight:700; background:transparent;")+ .arg(change >= 0 ? "#16a34a" : "#dc2626"));+ }+ if (stat_min_) stat_min_->setText(fmt(mn));+ if (stat_max_) stat_max_->setText(fmt(mx));+ if (stat_avg_) stat_avg_->setText(fmt(avg));+ if (stat_count_) stat_count_->setText(QString::number(rows.size()));+}++// ── CSV ───────────────────────────────────────────────────────────────────────++void EconPanelBase::export_csv() {+ if (!table_ || table_->rowCount() == 0) return;++ QString path = QFileDialog::getSaveFileName(+ this, "Export CSV", source_id_ + "_data.csv", "CSV Files (*.csv)");+ if (path.isEmpty()) return;++ QFile file(path);+ if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return;+ QTextStream out(&file);++ QStringList hdrs;+ for (int c = 0; c < table_->columnCount(); ++c) {+ auto* h = table_->horizontalHeaderItem(c);+ hdrs << (h ? h->text() : "");+ }+ out << hdrs.join(",") << "\n";++ for (int r = 0; r < table_->rowCount(); ++r) {+ QStringList row;+ for (int c = 0; c < table_->columnCount(); ++c) {+ auto* item = table_->item(r, c);+ QString val = item ? item->text() : "";+ if (val.contains(',') || val.contains('"'))+ val = "\"" + val.replace("\"", "\"\"") + "\"";+ row << val;+ }+ out << row.join(",") << "\n";+ }+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EconPanelBase.h b/fincept-qt/src/screens/economics/panels/EconPanelBase.hnew file mode 100644index 000000000..0caeaa5ab--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EconPanelBase.h@@ -0,0 +1,80 @@+// src/screens/economics/panels/EconPanelBase.h+// Base class for all economics source panels.+// Provides: stat cards + empty/loading/error state + data table + CSV export.+// Subclasses call build_base_ui() from their constructor.+// For panels with a left selector sidebar, pass the right-side container+// to build_base_ui(container) instead.+#pragma once++#include "services/economics/EconomicsService.h"++#include <QDate>+#include <QJsonArray>+#include <QLabel>+#include <QPushButton>+#include <QStackedWidget>+#include <QTableWidget>+#include <QWidget>++namespace fincept::screens {++class EconPanelBase : public QWidget {+ Q_OBJECT+ public:+ explicit EconPanelBase(const QString& source_id,+ const QString& color,+ QWidget* parent = nullptr);++ /// Called by EconomicsScreen when user switches to this panel.+ virtual void activate() = 0;++ protected:+ // ── Subclass API ──────────────────────────────────────────────────────────+ /// Add source-specific controls into the toolbar layout.+ virtual void build_controls(QHBoxLayout* toolbar_layout) = 0;+ virtual void on_fetch() = 0;+ virtual void on_result(const QString& request_id,+ const services::EconomicsResult& result) = 0;++ // ── UI construction ───────────────────────────────────────────────────────+ /// Build toolbar + stat cards + table stack into the given container widget.+ /// Call this from the subclass constructor (pass 'this' or a right-side pane).+ void build_base_ui(QWidget* container);++ // ── State helpers ─────────────────────────────────────────────────────────+ void show_loading(const QString& msg = "Fetching data…");+ void show_error(const QString& msg);+ void show_empty(const QString& msg = "Select parameters and click FETCH");+ void show_table();++ /// Populate the shared table + update stat cards.+ void display(const QJsonArray& rows, const QString& title = {});+ void export_csv();++ /// Per-provider accent color stylesheet.+ QString panel_style() const;++ // ── Shared widgets (accessible to subclasses) ─────────────────────────────+ QLabel* stat_latest_ = nullptr;+ QLabel* stat_change_ = nullptr;+ QLabel* stat_min_ = nullptr;+ QLabel* stat_max_ = nullptr;+ QLabel* stat_avg_ = nullptr;+ QLabel* stat_count_ = nullptr;+ QPushButton* fetch_btn_ = nullptr;+ QPushButton* export_btn_ = nullptr;++ QString source_id_;+ QString color_;++ private:+ void update_stats(const QJsonArray& rows);++ QStackedWidget* stack_ = nullptr; // 0=empty/status 1=table+ QLabel* empty_lbl_ = nullptr;+ QTableWidget* table_ = nullptr;+ QLabel* title_lbl_ = nullptr;+ QLabel* row_count_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EconomicCalendarPanel.cpp b/fincept-qt/src/screens/economics/panels/EconomicCalendarPanel.cppnew file mode 100644index 000000000..aff72a58b--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EconomicCalendarPanel.cpp@@ -0,0 +1,137 @@+// src/screens/economics/panels/EconomicCalendarPanel.cpp+// Forex Factory economic calendar scraper — no API key required.+//+// Script: economic_calendar.py <mmmDD.YYYY> (e.g. "mar28.2026")+// Response: { date, url, events_count, events: [+// { time, currency, impact:int(1-3), event, actual, forecast, previous }+// ]}+// Impact levels: 1=low, 2=medium, 3=high+#include "screens/economics/panels/EconomicCalendarPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QDate>+#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "economic_calendar.py";+static constexpr const char* kSourceId = "econ_calendar";+static constexpr const char* kColor = "#D97706"; // amber++// Convert QDate to Forex Factory date string: "mar28.2026"+static QString to_ff_date(const QDate& d) {+ static const char* months[] = {+ "", "jan","feb","mar","apr","may","jun",+ "jul","aug","sep","oct","nov","dec"+ };+ return QString("%1%2.%3")+ .arg(months[d.month()])+ .arg(d.day())+ .arg(d.year());+}++EconomicCalendarPanel::EconomicCalendarPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &EconomicCalendarPanel::on_result);+}++void EconomicCalendarPanel::activate() {+ // Default to today on first activation+ if (date_edit_) {+ date_edit_->setDate(QDate::currentDate());+ }+ show_empty("Select a date and click FETCH to load economic events\n"+ "Source: Forex Factory — global economic calendar (no API key required)");+}++void EconomicCalendarPanel::build_controls(QHBoxLayout* thl) {+ auto lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ date_edit_ = new QDateEdit(QDate::currentDate());+ date_edit_->setDisplayFormat("MMM dd yyyy");+ date_edit_->setCalendarPopup(true);+ date_edit_->setFixedHeight(26);+ date_edit_->setFixedWidth(120);++ filter_combo_ = new QComboBox;+ filter_combo_->addItem("All Events", 0);+ filter_combo_->addItem("Medium + High", 2);+ filter_combo_->addItem("High Only", 3);+ filter_combo_->setFixedHeight(26);+ filter_combo_->setFixedWidth(110);++ thl->addWidget(lbl("DATE"));+ thl->addWidget(date_edit_);+ thl->addWidget(lbl("IMPACT"));+ thl->addWidget(filter_combo_);+}++void EconomicCalendarPanel::on_fetch() {+ const QDate date = date_edit_->date();+ const QString ff_date = to_ff_date(date);++ show_loading("Fetching economic calendar for " + date.toString("MMM d, yyyy") + "…");++ services::EconomicsService::instance().execute(+ kSourceId, kScript, ff_date, {},+ "calendar_" + ff_date);+}++void EconomicCalendarPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("calendar_")) return;+ if (!result.success) { show_error(result.error); return; }++ QJsonArray events = result.data["events"].toArray();++ // Fallback: service normalised shape+ if (events.isEmpty())+ events = result.data["data"].toArray();++ if (events.isEmpty()) {+ show_empty("No events found for this date");+ return;+ }++ // Apply impact filter+ const int min_impact = filter_combo_->currentData().toInt();+ if (min_impact > 0) {+ QJsonArray filtered;+ for (const auto& ev : events) {+ if (ev.toObject()["impact"].toInt() >= min_impact)+ filtered.append(ev);+ }+ events = filtered;+ }++ if (events.isEmpty()) {+ show_empty("No events match the selected impact filter");+ return;+ }++ const QString date_str = date_edit_->date().toString("MMM d, yyyy");+ const int total = result.data["events_count"].toInt(events.size());+ const QString title = QString("Economic Calendar — %1 (%2 events)")+ .arg(date_str)+ .arg(total);++ display(events, title);+ LOG_INFO("EconomicCalendarPanel", QString("Displayed %1 events for %2")+ .arg(events.size()).arg(date_str));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EconomicCalendarPanel.h b/fincept-qt/src/screens/economics/panels/EconomicCalendarPanel.hnew file mode 100644index 000000000..e2e062249--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EconomicCalendarPanel.h@@ -0,0 +1,30 @@+// src/screens/economics/panels/EconomicCalendarPanel.h+// Forex Factory economic calendar scraper — no API key required.+// Script: economic_calendar.py <mmmDD.YYYY>+// Returns: {date, url, events_count, events:[{time,currency,impact,event,actual,forecast,previous}]}+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>+#include <QDateEdit>++namespace fincept::screens {++class EconomicCalendarPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit EconomicCalendarPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QDateEdit* date_edit_ = nullptr;+ QComboBox* filter_combo_ = nullptr; // filter by impact level+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EurostatPanel.cpp b/fincept-qt/src/screens/economics/panels/EurostatPanel.cppnew file mode 100644index 000000000..2e4c4022a--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EurostatPanel.cpp@@ -0,0 +1,205 @@+// src/screens/economics/panels/EurostatPanel.cpp+// Eurostat extra data panel.+//+// Response shape (Eurostat SDMX-JSON v2.0):+// { version, class, label, source, updated,+// value: {"0": 78.9, "1": 78.0, ...}, <- flat indexed values+// id: ["freq","indic_bt",...,"geo","time"],+// size: [1, 1, ..., 1, N], <- last dim is time+// dimension: {+// time: { category: { index: {"1953-01":0, ...}, label: {"1953-01":"1953-01",...} } }+// ...+// }+// }+// Flatten: value index i -> time position = i % time_size -> period string via index map.+#include "screens/economics/panels/EurostatPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>+#include <QMap>++namespace fincept::screens {++static constexpr const char* kScript = "eurostat_extra_data.py";+static constexpr const char* kSourceId = "eurostat";+static constexpr const char* kColor = "#0369A1"; // EU blue++struct EurostatDataset {+ QString label;+ QString command;+ bool has_country; // whether this command takes a country arg+};++static const QList<EurostatDataset> kDatasets = {+ { "Industrial Production", "industrial", true },+ { "Retail Trade", "retail", true },+ { "Energy Balance", "energy", true },+ { "Trade in Goods", "trade", true },+ { "Construction Output", "construction", true },+ { "Tourism Statistics", "tourism", true },+};++static const QList<QPair<QString,QString>> kCountries = {+ { "Germany", "DE" },+ { "France", "FR" },+ { "Italy", "IT" },+ { "Spain", "ES" },+ { "Netherlands", "NL" },+ { "Poland", "PL" },+ { "Belgium", "BE" },+ { "Sweden", "SE" },+ { "Austria", "AT" },+ { "Denmark", "DK" },+ { "Finland", "FI" },+ { "Portugal", "PT" },+ { "Czech Republic", "CZ" },+ { "Romania", "RO" },+ { "Hungary", "HU" },+ { "EU27", "EU27_2020" },+ { "Euro Area", "EA20" },+};++// ── SDMX-JSON flattener ───────────────────────────────────────────────────────++QJsonArray EurostatPanel::flatten_sdmx(const QJsonObject& response) {+ // Check for error+ if (response.contains("error"))+ return {};++ const QJsonArray id_arr = response["id"].toArray();+ const QJsonArray size_arr = response["size"].toArray();+ const QJsonObject dims = response["dimension"].toObject();+ const QJsonObject vals = response["value"].toObject();++ if (id_arr.isEmpty() || size_arr.isEmpty() || vals.isEmpty())+ return {};++ // Time is always the last dimension+ const int time_size = size_arr.last().toInt(1);++ // Build reverse map: int_position -> period_string from time dimension index+ // dimension.time.category.index = {"1953-01": 0, "1953-02": 1, ...}+ const QJsonObject time_cat = dims["time"].toObject()["category"].toObject();+ const QJsonObject time_index = time_cat["index"].toObject();++ QMap<int, QString> pos_to_period;+ for (auto it = time_index.constBegin(); it != time_index.constEnd(); ++it)+ pos_to_period[it.value().toInt()] = it.key();++ // Flatten: for each value entry, derive time position and look up period+ QJsonArray rows;+ for (auto it = vals.constBegin(); it != vals.constEnd(); ++it) {+ const int flat_idx = it.key().toInt();+ const int time_pos = flat_idx % time_size;+ const QString period = pos_to_period.value(time_pos, QString::number(time_pos));+ QJsonObject row;+ row["period"] = period;+ row["value"] = it.value().toDouble();+ rows.append(row);+ }++ // Sort by period string — copy to QList to avoid QJsonValueRef swap issue on MSVC+ QList<QJsonValue> sorted(rows.begin(), rows.end());+ std::sort(sorted.begin(), sorted.end(), [](const QJsonValue& a, const QJsonValue& b) {+ return a.toObject()["period"].toString() < b.toObject()["period"].toString();+ });+ rows = QJsonArray();+ for (const auto& v : sorted) rows.append(v);++ return rows;+}++// ── Panel ─────────────────────────────────────────────────────────────────────++EurostatPanel::EurostatPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &EurostatPanel::on_result);+}++void EurostatPanel::activate() {+ show_empty("Select a dataset and country, then click FETCH\n"+ "Source: Eurostat — EU statistical office");+}++void EurostatPanel::build_controls(QHBoxLayout* thl) {+ auto lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ dataset_combo_ = new QComboBox;+ for (const auto& d : kDatasets)+ dataset_combo_->addItem(d.label, d.command);+ dataset_combo_->setFixedHeight(26);+ dataset_combo_->setMinimumWidth(180);++ country_combo_ = new QComboBox;+ for (const auto& c : kCountries)+ country_combo_->addItem(c.first, c.second);+ country_combo_->setFixedHeight(26);++ thl->addWidget(lbl("DATASET"));+ thl->addWidget(dataset_combo_);+ thl->addWidget(lbl("COUNTRY"));+ thl->addWidget(country_combo_);+}++void EurostatPanel::on_fetch() {+ const int ds_idx = dataset_combo_->currentIndex();+ const auto& dataset = kDatasets[ds_idx];+ const QString country = country_combo_->currentData().toString();++ show_loading("Fetching Eurostat: " + dataset.label + " — "+ + country_combo_->currentText() + "…");++ QStringList args = { dataset.command };+ if (dataset.has_country) args << country;++ const QString req_id = "eurostat_" + dataset.command + "_" + country;++ services::EconomicsService::instance().execute(+ kSourceId, kScript, dataset.command, args, req_id);+}++void EurostatPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("eurostat_")) return;+ if (!result.success) { show_error(result.error); return; }++ const int ds_idx = dataset_combo_->currentIndex();+ if (ds_idx < 0 || ds_idx >= kDatasets.size()) return;+ const auto& dataset = kDatasets[ds_idx];++ // Try SDMX flatten first (raw Eurostat format)+ QJsonArray rows = flatten_sdmx(result.data);++ // Fallback: service may have wrapped as {data:[...]}+ if (rows.isEmpty())+ rows = result.data["data"].toArray();++ if (rows.isEmpty()) {+ // Check for explicit error in data+ const QString err = result.data["error"].toString();+ show_error(err.isEmpty() ? "No data returned for this selection" : err);+ return;+ }++ const QString title = "Eurostat: " + dataset.label + " — "+ + country_combo_->currentText();+ display(rows, title);+ LOG_INFO("EurostatPanel", QString("Displayed %1 rows for %2")+ .arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/EurostatPanel.h b/fincept-qt/src/screens/economics/panels/EurostatPanel.hnew file mode 100644index 000000000..dc0f94ea4--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/EurostatPanel.h@@ -0,0 +1,32 @@+// src/screens/economics/panels/EurostatPanel.h+// Eurostat — EU statistical data (industrial, retail, energy, trade, etc.)+// Script: eurostat_extra_data.py+// Response: Eurostat SDMX-JSON with indexed value dict + dimension/time labels+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class EurostatPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit EurostatPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ /// Flatten Eurostat SDMX-JSON indexed response into [{period, value}] rows.+ static QJsonArray flatten_sdmx(const QJsonObject& response);++ QComboBox* dataset_combo_ = nullptr;+ QComboBox* country_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/FederalReservePanel.cpp b/fincept-qt/src/screens/economics/panels/FederalReservePanel.cppnew file mode 100644index 000000000..55e9961ef--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/FederalReservePanel.cpp@@ -0,0 +1,122 @@+// src/screens/economics/panels/FederalReservePanel.cpp+// US Federal Reserve data — Fed Funds Rate, SOFR, Treasury Rates, Yield Curve, Money Supply.+// Script: federal_reserve_data.py | No API key required.+//+// Response shape: { success, endpoint, data:[{date, rate|...}] }+#include "screens/economics/panels/FederalReservePanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "federal_reserve_data.py";+static constexpr const char* kSourceId = "federal_reserve";+static constexpr const char* kColor = "#DC2626"; // Fed red++struct FedSeries {+ QString label;+ QString command;+ QStringList args;+};++static const QList<FedSeries> kSeries = {+ { "Federal Funds Rate", "federal_funds_rate", {} },+ { "SOFR Overnight Rate", "sofr_rate", {} },+ { "Treasury Rates (Yield Curve)","treasury_rates", {} },+ { "Yield Curve (single date)", "yield_curve", {} },+ { "Money Supply (M1/M2)", "money_measures", {} },+ { "Central Bank Holdings", "central_bank_holdings", {} },+};++FederalReservePanel::FederalReservePanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &FederalReservePanel::on_result);+}++void FederalReservePanel::activate() {+ show_empty("Select a series and click FETCH\n"+ "Source: Federal Reserve Economic Data — federal_reserve_data.py\n"+ "No API key required");+}++void FederalReservePanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("SERIES");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ series_combo_ = new QComboBox;+ for (const auto& s : kSeries)+ series_combo_->addItem(s.label, s.command);+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(240);++ thl->addWidget(lbl);+ thl->addWidget(series_combo_);+}++void FederalReservePanel::on_fetch() {+ const int idx = series_combo_->currentIndex();+ const auto& series = kSeries[idx];++ show_loading("Fetching Federal Reserve: " + series.label + "…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, series.command, series.args,+ "fed_" + series.command);+}++void FederalReservePanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("fed_")) return;+ if (!result.success) { show_error(result.error); return; }++ const QString inline_err = result.data["error"].toString();+ if (!inline_err.isEmpty()) { show_error(inline_err); return; }++ // Response: { success, endpoint, data:[{date, <value cols>}] }+ QJsonArray rows = result.data["data"].toArray();++ // Some endpoints nest differently — handle yield_curve which may use "rates" key+ if (rows.isEmpty())+ rows = result.data["rates"].toArray();++ // Filter: keep rows that have at least one non-empty numeric-ish value beyond "date"+ QJsonArray clean;+ for (const auto& rv : rows) {+ const QJsonObject r = rv.toObject();+ bool has_val = false;+ for (auto it = r.begin(); it != r.end(); ++it) {+ if (it.key() == "date") continue;+ if (it.value().isDouble() || !it.value().toString().isEmpty()) {+ has_val = true;+ break;+ }+ }+ if (has_val) clean.append(r);+ }++ if (clean.isEmpty()) {+ show_error("No data returned");+ return;+ }++ const int idx = series_combo_->currentIndex();+ const QString title = "Federal Reserve: "+ + (idx >= 0 && idx < kSeries.size() ? kSeries[idx].label+ : request_id.mid(4));++ display(clean, title);+ LOG_INFO("FederalReservePanel",+ QString("Displayed %1 rows: %2").arg(clean.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/FederalReservePanel.h b/fincept-qt/src/screens/economics/panels/FederalReservePanel.hnew file mode 100644index 000000000..082785cd1--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/FederalReservePanel.h@@ -0,0 +1,27 @@+// src/screens/economics/panels/FederalReservePanel.h+// US Federal Reserve data panel.+// Script: federal_reserve_data.py | No API key required.+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class FederalReservePanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit FederalReservePanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* series_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/FiscalDataPanel.cpp b/fincept-qt/src/screens/economics/panels/FiscalDataPanel.cppnew file mode 100644index 000000000..1bd0363da--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/FiscalDataPanel.cpp@@ -0,0 +1,106 @@+// src/screens/economics/panels/FiscalDataPanel.cpp+// US Treasury FiscalData — debt to penny, interest rates, interest expense, exchange rates.+// Script: fiscal_data.py | No API key required.+//+// Response shape: { data:[{record_date, <value cols>}] }+#include "screens/economics/panels/FiscalDataPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "fiscal_data.py";+static constexpr const char* kSourceId = "fiscal_data";+static constexpr const char* kColor = "#0EA5E9"; // Treasury blue++struct FiscalSeries {+ QString label;+ QString command;+ QStringList args;+};++static const QList<FiscalSeries> kSeries = {+ { "Debt to the Penny", "debt-to-penny", {"--all"} },+ { "Avg Interest Rates", "avg-interest-rates", {"--all"} },+ { "Interest Expense", "interest-expense", {"--all"} },+ { "US Treasury Exchange Rates", "exchange-rates", {} },+ { "Record-Setting Auction Debt", "record-debt", {} },+};++FiscalDataPanel::FiscalDataPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &FiscalDataPanel::on_result);+}++void FiscalDataPanel::activate() {+ show_empty("Select a dataset and click FETCH\n"+ "Source: US Treasury FiscalData API (fiscaldata.treasury.gov)\n"+ "No API key required");+}++void FiscalDataPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("DATASET");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ series_combo_ = new QComboBox;+ for (const auto& s : kSeries)+ series_combo_->addItem(s.label, s.command);+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(240);++ thl->addWidget(lbl);+ thl->addWidget(series_combo_);+}++void FiscalDataPanel::on_fetch() {+ const int idx = series_combo_->currentIndex();+ const auto& series = kSeries[idx];++ show_loading("Fetching FiscalData: " + series.label + "…");++ QStringList args = {series.command};+ args << series.args;++ services::EconomicsService::instance().execute(+ kSourceId, kScript, series.command, series.args,+ "fiscal_" + QString(series.command).replace('-', '_'));+}++void FiscalDataPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("fiscal_")) return;+ if (!result.success) { show_error(result.error); return; }++ const QString inline_err = result.data["error"].toString();+ if (!inline_err.isEmpty()) { show_error(inline_err); return; }++ // Response: { data:[{record_date, ...}] }+ QJsonArray rows = result.data["data"].toArray();++ if (rows.isEmpty()) {+ show_error("No data returned");+ return;+ }++ const int idx = series_combo_->currentIndex();+ const QString title = "FiscalData: "+ + (idx >= 0 && idx < kSeries.size() ? kSeries[idx].label+ : request_id.mid(7));++ display(rows, title);+ LOG_INFO("FiscalDataPanel",+ QString("Displayed %1 rows: %2").arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/FiscalDataPanel.h b/fincept-qt/src/screens/economics/panels/FiscalDataPanel.hnew file mode 100644index 000000000..1eb40c2e8--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/FiscalDataPanel.h@@ -0,0 +1,27 @@+// src/screens/economics/panels/FiscalDataPanel.h+// US Treasury FiscalData panel — debt, interest rates, exchange rates.+// Script: fiscal_data.py | No API key required.+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class FiscalDataPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit FiscalDataPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* series_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.cpp b/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.cppnew file mode 100644index 000000000..2ce5b301b--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.cpp@@ -0,0 +1,158 @@+// src/screens/economics/panels/FredAnalyticsPanel.cpp+// FRED Analytics panel — composite dataset views built from multiple FRED series.+// Requires FRED_API_KEY (same key as FredPanel).+//+// Response shapes vary per command:+// yield_curve: { curve:[{maturity, yield, date}], spread_2_10 }+// money_supply: { observations:[{date,value}], measure, ... }+// credit: { observations:[{date,value}], series_id }+// stress: { observations:[{date,value}] }+// sentiment: { observations:[{date,value}] }+// pce: { observations:[{date,value}] }+#include "screens/economics/panels/FredAnalyticsPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "fred_economic_data.py";+static constexpr const char* kSourceId = "fred_analytics";+static constexpr const char* kColor = "#F97316"; // orange (distinct from FredPanel red)++struct FredAnalDataset {+ QString label;+ QString command;+ QStringList args;+};++static const QList<FredAnalDataset> kDatasets = {+ { "Yield Curve (Treasury Rates)", "yield_curve", {} },+ { "M1 Money Supply", "money_supply", {"m1"} },+ { "M2 Money Supply", "money_supply", {"m2"} },+ { "M3 Money Supply", "money_supply", {"m3"} },+ { "Fed Funds Rate (Credit)", "credit", {"fed_funds_rate"} },+ { "Prime Rate (Credit)", "credit", {"prime_rate"} },+ { "Financial Stress Index", "stress", {} },+ { "Consumer Sentiment", "sentiment", {} },+ { "PCE Price Index", "pce", {} },+};++FredAnalyticsPanel::FredAnalyticsPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &FredAnalyticsPanel::on_result);+}++void FredAnalyticsPanel::activate() {+ show_empty("Set FRED_API_KEY environment variable, then select a dataset and click FETCH\n"+ "Uses the same key as the FRED panel — fred.stlouisfed.org/docs/api/api_key.html");+}++void FredAnalyticsPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("DATASET");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ dataset_combo_ = new QComboBox;+ for (const auto& d : kDatasets)+ dataset_combo_->addItem(d.label, d.command);+ dataset_combo_->setFixedHeight(26);+ dataset_combo_->setMinimumWidth(240);++ thl->addWidget(lbl);+ thl->addWidget(dataset_combo_);+}++void FredAnalyticsPanel::on_fetch() {+ const int idx = dataset_combo_->currentIndex();+ const auto& dataset = kDatasets[idx];++ show_loading("Fetching FRED Analytics: " + dataset.label + "…");++ QStringList args = { dataset.command };+ args << dataset.args;++ const QString arg_suffix = dataset.args.isEmpty() ? "" : "_" + dataset.args.join("_");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, dataset.command, args,+ "fredan_" + dataset.command + arg_suffix);+}++// Extract rows from various FRED Analytics response shapes.+static QJsonArray extract_fred_analytics_rows(const QJsonObject& data) {+ // Standard observations array+ QJsonArray obs = data["observations"].toArray();+ if (!obs.isEmpty()) return obs;++ // Yield curve: {curve:[{maturity, yield, date}]}+ obs = data["curve"].toArray();+ if (!obs.isEmpty()) return obs;++ // Fallback service normalisation+ obs = data["data"].toArray();+ return obs;+}++void FredAnalyticsPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("fredan_")) return;++ if (!result.success) {+ const QString msg = result.error;+ if (msg.contains("FRED_API_KEY") || msg.contains("api_key") || msg.contains("API key")) {+ show_error("FRED API key not configured.\n"+ "Set FRED_API_KEY environment variable.\n"+ "Free key at: fred.stlouisfed.org/docs/api/api_key.html");+ } else {+ show_error(msg);+ }+ return;+ }++ // Check inline error+ const QString inline_err = result.data["error"].toString();+ if (!inline_err.isEmpty()) {+ if (inline_err.contains("FRED_API_KEY") || inline_err.contains("not set")) {+ show_error("FRED API key not configured.\n"+ "Set FRED_API_KEY environment variable.\n"+ "Free key at: fred.stlouisfed.org/docs/api/api_key.html");+ } else {+ show_error(inline_err);+ }+ return;+ }++ // Filter string sentinel values (FRED uses "." for missing)+ QJsonArray raw = extract_fred_analytics_rows(result.data);+ QJsonArray rows;+ for (const auto& rv : raw) {+ const QJsonObject r = rv.toObject();+ const QString val_str = r["value"].toString();+ if (val_str == "." || (val_str.isEmpty() && !r["value"].isDouble())) continue;+ rows.append(r);+ }++ if (rows.isEmpty()) {+ show_error("No data returned — check FRED_API_KEY is set");+ return;+ }++ const int idx = dataset_combo_->currentIndex();+ const QString title = "FRED Analytics: "+ + (idx >= 0 && idx < kDatasets.size() ? kDatasets[idx].label : request_id.mid(7));++ display(rows, title);+ LOG_INFO("FredAnalyticsPanel", QString("Displayed %1 rows: %2")+ .arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.h b/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.hnew file mode 100644index 000000000..6826c9496--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.h@@ -0,0 +1,28 @@+// src/screens/economics/panels/FredAnalyticsPanel.h+// FRED Analytics — yield curve, money supply, credit, stress, sentiment, PCE.+// Script: fred_economic_data.py+// Requires FRED_API_KEY environment variable (same key as FredPanel).+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class FredAnalyticsPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit FredAnalyticsPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* dataset_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/FredPanel.cpp b/fincept-qt/src/screens/economics/panels/FredPanel.cppnew file mode 100644index 000000000..56796f1c2--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/FredPanel.cpp@@ -0,0 +1,134 @@+// src/screens/economics/panels/FredPanel.cpp+#include "screens/economics/panels/FredPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>+#include <QVBoxLayout>++namespace fincept::screens {++static constexpr const char* kScript = "fred_data.py";+static constexpr const char* kSourceId = "fred";+static constexpr const char* kColor = "#EF4444"; // red++static const QList<QPair<QString,QString>> kPresets = {+ {"-- Custom series ID --", ""},+ {"Real GDP (GDPC1)", "GDPC1"},+ {"Nominal GDP (GDP)", "GDP"},+ {"CPI All Items (CPIAUCSL)", "CPIAUCSL"},+ {"Core CPI (CPILFESL)", "CPILFESL"},+ {"Unemployment Rate (UNRATE)", "UNRATE"},+ {"Federal Funds Rate (FEDFUNDS)", "FEDFUNDS"},+ {"10-Year Treasury Yield (DGS10)", "DGS10"},+ {"2-Year Treasury Yield (DGS2)", "DGS2"},+ {"30-Year Mortgage Rate (MORTGAGE30US)", "MORTGAGE30US"},+ {"M2 Money Supply (M2SL)", "M2SL"},+ {"Personal Savings Rate (PSAVERT)", "PSAVERT"},+ {"Industrial Production (INDPRO)", "INDPRO"},+ {"Retail Sales (RSXFS)", "RSXFS"},+ {"Housing Starts (HOUST)", "HOUST"},+ {"Trade Balance (BOPGSTB)", "BOPGSTB"},+ {"VIX Volatility Index (VIXCLS)", "VIXCLS"},+ {"S&P 500 (SP500)", "SP500"},+};++FredPanel::FredPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &FredPanel::on_result);+}++void FredPanel::activate() {+ show_empty("Set FRED_API_KEY environment variable, then select a series and click FETCH\n"+ "Get a free key at: fred.stlouisfed.org/docs/api/api_key.html");+}++void FredPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl1 = new QLabel("PRESET");+ lbl1->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ preset_combo_ = new QComboBox;+ for (const auto& p : kPresets) preset_combo_->addItem(p.first, p.second);+ preset_combo_->setFixedHeight(26);+ preset_combo_->setMinimumWidth(200);+ connect(preset_combo_, &QComboBox::currentIndexChanged, this,+ [this](int idx) {+ const QString code = preset_combo_->itemData(idx).toString();+ if (!code.isEmpty()) series_input_->setText(code);+ });++ auto* lbl2 = new QLabel("SERIES ID");+ lbl2->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ series_input_ = new QLineEdit;+ series_input_->setPlaceholderText("e.g. GDPC1");+ series_input_->setFixedHeight(26);+ series_input_->setFixedWidth(100);++ thl->addWidget(lbl1);+ thl->addWidget(preset_combo_);+ thl->addWidget(lbl2);+ thl->addWidget(series_input_);+}++void FredPanel::on_fetch() {+ QString series = series_input_->text().trimmed().toUpper();+ if (series.isEmpty()) {+ const QString code = preset_combo_->currentData().toString();+ if (code.isEmpty()) { show_empty("Enter a FRED series ID"); return; }+ series = code;+ }+ show_loading("Fetching FRED series " + series + "…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, "series", {series},+ "fred_" + series);+}++void FredPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!result.success) {+ // Check for API key error specifically+ if (result.error.contains("API key") || result.error.contains("api_key")) {+ show_error("FRED API key not configured.\n"+ "Set FRED_API_KEY environment variable.\n"+ "Free key at: fred.stlouisfed.org/docs/api/api_key.html");+ } else {+ show_error(result.error);+ }+ return;+ }++ if (request_id.startsWith("fred_")) {+ // FRED returns: {observations: [{date, value}]}+ QJsonArray obs = result.data["observations"].toArray();+ if (obs.isEmpty()) obs = result.data["data"].toArray();++ // Convert string values to numbers where possible+ QJsonArray clean;+ for (const auto& v : obs) {+ auto obj = v.toObject();+ const QString val_str = obj["value"].toString();+ if (val_str == "." || val_str.isEmpty()) continue;+ bool ok = false;+ double d = val_str.toDouble(&ok);+ if (ok) obj["value"] = d;+ clean.append(obj);+ }++ const QString series = request_id.mid(5); // strip "fred_"+ display(clean, "FRED: " + series);+ LOG_INFO("FredPanel", QString("Displayed %1 observations").arg(clean.size()));+ }+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/FredPanel.h b/fincept-qt/src/screens/economics/panels/FredPanel.hnew file mode 100644index 000000000..c28280703--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/FredPanel.h@@ -0,0 +1,29 @@+// src/screens/economics/panels/FredPanel.h+// FRED (Federal Reserve Economic Data) — requires FRED_API_KEY env var.+// Script: fred_data.py+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>+#include <QLineEdit>++namespace fincept::screens {++class FredPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit FredPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QLineEdit* series_input_ = nullptr;+ QComboBox* preset_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.cpp b/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.cppnew file mode 100644index 000000000..026da596c--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.cpp@@ -0,0 +1,238 @@+// src/screens/economics/panels/GlobalCentralBanksPanel.cpp+// Global Central Banks — BOE, RBA, Bank of Canada, Riksbank, SNB, Norges Bank.+// No API key required for any source.+//+// Response shapes (all use {success, data:[{date, <value_col>}]} or similar):+// BOE: { success, data:[{date:"02 Jan 1975", <CDID>:value}] }+// RBA: { success, table, data:[{date:"04-Jan-2011", <col>:value}] }+// BOC: { success, series, data:[{date:"2026-02-01", <series_id>:value}] }+// Riksbank:{ success, series_id, data:[{date:"2025-03-28", value:2.25}] }+// SNB: { success, cube, data:[{date:"2026-03-16", <col>:value}] }+// Norges: { success, flow, data:[{date:"2026-03-17", <col>:value}] }+#include "screens/economics/panels/GlobalCentralBanksPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kSourceId = "global_cb";+static constexpr const char* kColor = "#6366F1"; // indigo++// ── Per-bank descriptor ──────────────────────────────────────────────────────++struct CbSeries {+ QString label;+ QString command;+};++struct CbBank {+ QString label; // display name+ QString script; // python script filename+ QString req_prefix; // request_id prefix+ QList<CbSeries> series;+};++static const QList<CbBank> kBanks = {+ {+ "BOE — Bank of England", "boe_data.py", "boe",+ {+ { "Bank Rate", "bank_rate" },+ { "SONIA Overnight Rate", "sonia" },+ { "Exchange Rates (GBP)", "exchange_rates" },+ { "Monetary Aggregates (M0/M4)","monetary_aggregates"},+ { "Quoted Interest Rates", "quoted_rates" },+ }+ },+ {+ "RBA — Reserve Bank of Australia", "rba_data.py", "rba",+ {+ { "Cash Rate (F1)", "cash_rate" },+ { "Bond Yields (F2)", "bond_yields" },+ { "Exchange Rates (F11)", "exchange_rates"},+ { "Inflation / CPI", "inflation" },+ { "Lending Rates", "lending_rates"},+ { "Monetary Aggregates", "monetary" },+ }+ },+ {+ "BOC — Bank of Canada", "boc_data.py", "boc",+ {+ { "Overnight Policy Rate", "policy_rate" },+ { "CORRA", "corra" },+ { "Prime Rate", "prime" },+ { "USD/CAD", "usd" },+ { "EUR/CAD", "eur" },+ }+ },+ {+ "Riksbank — Sweden", "riksbank_data.py", "riksbank",+ {+ { "Policy Rate", "policy_rate" },+ { "Policy + Deposit + Lending", "policy_all" },+ { "T-Bills (1M-6M)", "tbills" },+ { "Mortgage Bond Yields", "mortgage" },+ }+ },+ {+ "SNB — Swiss National Bank", "snb_data.py", "snb",+ {+ { "Policy Rate + SARON", "policy_rate" },+ { "Bond Yields (Monthly)", "bond_yields" },+ { "Bond Yields (Daily)", "bond_yields_d" },+ { "CHF Exchange Rates", "exchange_rates" },+ }+ },+ {+ "Norges Bank — Norway", "norges_bank_data.py", "norges",+ {+ { "Policy Rate Announcements", "policy_rate" },+ { "Exchange Rates (NOK)", "exchange_rates" },+ { "NIBOR / Interest Rates", "interest_rates" },+ }+ },+};++// ── Flatten helpers ──────────────────────────────────────────────────────────++// All bank response shapes have a "data" array of objects with a "date" key+// and one or more numeric value columns. We keep all columns as-is.+static QJsonArray extract_cb_rows(const QJsonObject& data) {+ return data["data"].toArray();+}++// ── Panel ────────────────────────────────────────────────────────────────────++GlobalCentralBanksPanel::GlobalCentralBanksPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &GlobalCentralBanksPanel::on_result);+}++void GlobalCentralBanksPanel::activate() {+ show_empty("Select a central bank and series, then click FETCH\n"+ "Sources: BOE, RBA, Bank of Canada, Riksbank, SNB, Norges Bank\n"+ "No API key required for any source");+}++void GlobalCentralBanksPanel::build_controls(QHBoxLayout* thl) {+ auto* blbl = new QLabel("BANK");+ blbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ bank_combo_ = new QComboBox;+ for (const auto& b : kBanks)+ bank_combo_->addItem(b.label);+ bank_combo_->setFixedHeight(26);+ bank_combo_->setMinimumWidth(230);++ auto* slbl = new QLabel("SERIES");+ slbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ series_combo_ = new QComboBox;+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(200);++ // Populate series for the initial bank+ update_series_for_bank(0);++ connect(bank_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &GlobalCentralBanksPanel::update_series_for_bank);++ thl->addWidget(blbl);+ thl->addWidget(bank_combo_);+ thl->addSpacing(8);+ thl->addWidget(slbl);+ thl->addWidget(series_combo_);+}++void GlobalCentralBanksPanel::update_series_for_bank(int bank_idx) {+ if (bank_idx < 0 || bank_idx >= kBanks.size()) return;+ series_combo_->clear();+ for (const auto& s : kBanks[bank_idx].series)+ series_combo_->addItem(s.label, s.command);+}++void GlobalCentralBanksPanel::on_fetch() {+ const int bi = bank_combo_->currentIndex();+ const int si = series_combo_->currentIndex();+ if (bi < 0 || bi >= kBanks.size()) return;+ if (si < 0 || si >= kBanks[bi].series.size()) return;++ const auto& bank = kBanks[bi];+ const auto& series = bank.series[si];++ show_loading("Fetching " + bank.label + ": " + series.label + "…");+ services::EconomicsService::instance().execute(+ kSourceId, bank.script, series.command, {},+ bank.req_prefix + "_" + series.command);+}++void GlobalCentralBanksPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;++ // Check this result belongs to one of our banks+ bool matched = false;+ int matched_bank = -1;+ int matched_series = -1;+ for (int bi = 0; bi < kBanks.size(); ++bi) {+ const auto& bank = kBanks[bi];+ if (!request_id.startsWith(bank.req_prefix + "_")) continue;+ matched = true;+ matched_bank = bi;+ const QString cmd = request_id.mid(bank.req_prefix.size() + 1);+ for (int si = 0; si < bank.series.size(); ++si) {+ if (bank.series[si].command == cmd) {+ matched_series = si;+ break;+ }+ }+ break;+ }+ if (!matched) return;++ if (!result.success) { show_error(result.error); return; }++ const QString inline_err = result.data["error"].toString();+ if (!inline_err.isEmpty()) { show_error(inline_err); return; }++ QJsonArray raw = extract_cb_rows(result.data);++ // Filter rows: keep only those with at least one numeric value+ QJsonArray rows;+ for (const auto& rv : raw) {+ const QJsonObject r = rv.toObject();+ bool has_value = false;+ for (const auto& key : r.keys()) {+ if (key == "date") continue;+ if (r[key].isDouble()) { has_value = true; break; }+ }+ if (has_value) rows.append(r);+ }++ if (rows.isEmpty()) {+ show_error("No data returned");+ return;+ }++ const QString bank_name = matched_bank >= 0 ? kBanks[matched_bank].label : "";+ const QString series_name = (matched_bank >= 0 && matched_series >= 0)+ ? kBanks[matched_bank].series[matched_series].label+ : request_id;+ const QString title = bank_name + ": " + series_name;++ display(rows, title);+ LOG_INFO("GlobalCentralBanksPanel",+ QString("Displayed %1 rows: %2").arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.h b/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.hnew file mode 100644index 000000000..206f9c8b9--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.h@@ -0,0 +1,30 @@+// src/screens/economics/panels/GlobalCentralBanksPanel.h+// Global Central Banks panel — BOE, RBA, BOC, Riksbank, SNB, Norges Bank.+// No API key required for any source.+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class GlobalCentralBanksPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit GlobalCentralBanksPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* bank_combo_ = nullptr;+ QComboBox* series_combo_ = nullptr;++ void update_series_for_bank(int bank_idx);+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/IlostatPanel.cpp b/fincept-qt/src/screens/economics/panels/IlostatPanel.cppnew file mode 100644index 000000000..a5583f3ed--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/IlostatPanel.cpp@@ -0,0 +1,142 @@+// src/screens/economics/panels/IlostatPanel.cpp+// ILO ILOSTAT — unemployment rate, labour force participation, employment-to-population.+// Script: ilostat_data.py | No API key required.+//+// Response shape: { success, indicator, dataflow, key, data:[{TIME_PERIOD, OBS_VALUE, REF_AREA, ...}] }+#include "screens/economics/panels/IlostatPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "ilostat_data.py";+static constexpr const char* kSourceId = "ilostat";+static constexpr const char* kColor = "#3B82F6"; // ILO blue++struct IloSeries {+ QString label;+ QString command;+ QString description;+};++static const QList<IloSeries> kSeries = {+ { "Unemployment Rate", "unemployment", "UNE_DEAP_SEX_AGE_RT — annual, total, 15+" },+ { "Labour Force Participation Rate", "lfpr", "EAP_DWAP_SEX_AGE_RT — annual, total, 15+" },+ { "Employment-to-Population Ratio", "emp_to_pop", "EMP_DWAP_SEX_AGE_RT — annual, total, 15+" },+};++IlostatPanel::IlostatPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &IlostatPanel::on_result);+}++void IlostatPanel::activate() {+ show_empty("Select a series, enter a country code, then click FETCH\n"+ "Source: ILO ILOSTAT SDMX REST API (sdmx.ilo.org) — no API key required\n"+ "Country codes: USA, GBR, DEU, FRA, IND, CHN, JPN, BRA, ZAF, G7=CAN+USA+GBR+DEU+FRA+ITA+JPN");+}++void IlostatPanel::build_controls(QHBoxLayout* thl) {+ auto mk_lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet("color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ series_combo_ = new QComboBox;+ for (const auto& s : kSeries)+ series_combo_->addItem(s.label, s.command);+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(220);++ for (int i = 0; i < kSeries.size(); ++i)+ series_combo_->setItemData(i, kSeries[i].description, Qt::ToolTipRole);++ country_edit_ = new QLineEdit("USA");+ country_edit_->setFixedHeight(26);+ country_edit_->setFixedWidth(120);+ country_edit_->setPlaceholderText("ISO-2 code…");+ country_edit_->setToolTip("ISO-2 country code, e.g. USA, GBR, DEU\n"+ "Multiple: CAN+USA+GBR\n"+ "All countries: ALL");++ start_edit_ = new QLineEdit("2010");+ start_edit_->setFixedHeight(26);+ start_edit_->setFixedWidth(52);++ end_edit_ = new QLineEdit("2023");+ end_edit_->setFixedHeight(26);+ end_edit_->setFixedWidth(52);++ thl->addWidget(mk_lbl("SERIES"));+ thl->addWidget(series_combo_);+ thl->addSpacing(6);+ thl->addWidget(mk_lbl("COUNTRY"));+ thl->addWidget(country_edit_);+ thl->addSpacing(6);+ thl->addWidget(mk_lbl("FROM"));+ thl->addWidget(start_edit_);+ thl->addWidget(mk_lbl("TO"));+ thl->addWidget(end_edit_);+}++void IlostatPanel::on_fetch() {+ const int idx = series_combo_->currentIndex();+ const auto& series = kSeries[idx];++ const QString country = country_edit_->text().trimmed().toUpper();+ const QString start = start_edit_->text().trimmed();+ const QString end = end_edit_->text().trimmed();++ if (country.isEmpty()) { show_error("Please enter a country code (e.g. USA)"); return; }++ show_loading("Fetching ILO: " + series.label + " — " + country + "…");++ services::EconomicsService::instance().execute(+ kSourceId, kScript, series.command,+ { country, "A", "SEX_T", "AGE_YTHADULT_YGE15", start, end },+ "ilostat_" + series.command);+}++void IlostatPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("ilostat_")) return;+ if (!result.success) { show_error(result.error); return; }++ const QString inline_err = result.data["error"].toString();+ if (!inline_err.isEmpty()) { show_error(inline_err); return; }++ // Response: { success, indicator, dataflow, key, data:[{TIME_PERIOD, OBS_VALUE, REF_AREA, ...}] }+ QJsonArray rows = result.data["data"].toArray();++ if (rows.isEmpty()) {+ show_error("No data returned — try a different country code or year range");+ return;+ }++ // Build title+ const QString cmd = request_id.mid(8); // strip "ilostat_"+ QString label;+ for (const auto& s : kSeries) {+ if (s.command == cmd) { label = s.label; break; }+ }+ const QString country = country_edit_->text().trimmed().toUpper();+ const QString title = "ILO: " + (label.isEmpty() ? cmd : label)+ + (country.isEmpty() ? "" : " — " + country);++ display(rows, title);+ LOG_INFO("IlostatPanel",+ QString("Displayed %1 rows: %2").arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/IlostatPanel.h b/fincept-qt/src/screens/economics/panels/IlostatPanel.hnew file mode 100644index 000000000..65d02704d--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/IlostatPanel.h@@ -0,0 +1,31 @@+// src/screens/economics/panels/IlostatPanel.h+// ILO ILOSTAT — unemployment, labour force participation, employment-to-population.+// Script: ilostat_data.py | No API key required.+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>+#include <QLineEdit>++namespace fincept::screens {++class IlostatPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit IlostatPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* series_combo_ = nullptr;+ QLineEdit* country_edit_ = nullptr;+ QLineEdit* start_edit_ = nullptr;+ QLineEdit* end_edit_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/ImfPanel.cpp b/fincept-qt/src/screens/economics/panels/ImfPanel.cppnew file mode 100644index 000000000..63ce4f8d6--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/ImfPanel.cpp@@ -0,0 +1,246 @@+// src/screens/economics/panels/ImfPanel.cpp+// IMF DataMapper panel — nested pivot {values.INDICATOR.COUNTRY.YEAR}+#include "screens/economics/panels/ImfPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>+#include <QVBoxLayout>++namespace fincept::screens {++static constexpr const char* kScript = "imf_datamapper_data.py";+static constexpr const char* kSourceId = "imf";+static constexpr const char* kColor = "#3B82F6"; // blue++// Curated indicator list: display name → IMF DataMapper code+static const QList<QPair<QString,QString>> kIndicators = {+ {"Real GDP Growth (%)", "NGDP_RPCH"},+ {"Nominal GDP (USD billions)", "NGDPD"},+ {"GDP per capita (USD)", "NGDPDPC"},+ {"Inflation, End of Period (%)", "PCPIE"},+ {"Inflation, Average (%)", "PCPIPCH"},+ {"Unemployment Rate (%)", "LUR"},+ {"Current Account Balance (% GDP)", "BCA_NGDPD"},+ {"General Gov. Gross Debt (% GDP)", "GGXWDG_NGDP"},+ {"General Gov. Net Lending (% GDP)", "GGXCNL_NGDP"},+ {"General Gov. Revenue (% GDP)", "GGR_NGDP"},+ {"Total Investment (% GDP)", "NID_NGDP"},+ {"Gross National Savings (% GDP)", "NGSD_NGDP"},+ {"Volume of Imports of Goods (% change)", "TM_RPCH"},+ {"Volume of Exports of Goods (% change)", "TX_RPCH"},+ {"Commodity Terms of Trade", "TT"},+ {"Population (millions)", "LP"},+};++// Curated country list+static const QList<QPair<QString,QString>> kCountries = {+ {"All Countries", ""},+ {"United States", "USA"},+ {"China", "CHN"},+ {"Japan", "JPN"},+ {"Germany", "DEU"},+ {"United Kingdom", "GBR"},+ {"France", "FRA"},+ {"India", "IND"},+ {"Brazil", "BRA"},+ {"Canada", "CAN"},+ {"South Korea", "KOR"},+ {"Australia", "AUS"},+ {"Russia", "RUS"},+ {"Mexico", "MEX"},+ {"Indonesia", "IDN"},+ {"Saudi Arabia", "SAU"},+ {"Turkey", "TUR"},+ {"Netherlands", "NLD"},+ {"Switzerland", "CHE"},+ {"Argentina", "ARG"},+};++// ── Constructor ───────────────────────────────────────────────────────────────++ImfPanel::ImfPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {++ auto* main = new QHBoxLayout(this);+ main->setContentsMargins(0, 0, 0, 0);+ main->setSpacing(0);++ // Left: indicator list+ auto* left = new QWidget;+ left->setFixedWidth(240);+ left->setStyleSheet("background:#0a0a0a; border-right:1px solid #1a1a1a;");+ auto* lvl = new QVBoxLayout(left);+ lvl->setContentsMargins(0, 0, 0, 0);+ lvl->setSpacing(0);++ auto* hdr = new QLabel("IMF INDICATOR");+ hdr->setStyleSheet("color:#525252; font-size:8px; font-weight:700;"+ " letter-spacing:1px; background:#111111;"+ " padding:4px 10px; border-bottom:1px solid #1a1a1a;");+ lvl->addWidget(hdr);++ indicator_search_ = new QLineEdit;+ indicator_search_->setPlaceholderText("Filter indicators…");+ indicator_search_->setStyleSheet(+ "background:#080808; color:#e5e5e5; border:none;"+ " border-bottom:1px solid #1a1a1a; padding:4px 10px; font-size:11px;");+ connect(indicator_search_, &QLineEdit::textChanged,+ this, &ImfPanel::on_indicator_filter);+ lvl->addWidget(indicator_search_);++ indicator_list_ = new QListWidget;+ indicator_list_->setStyleSheet(+ QString(+ "QListWidget { background:transparent; border:none; outline:none; }"+ "QListWidget::item { color:#808080; padding:5px 10px;"+ " border-bottom:1px solid #111111; font-size:11px; }"+ "QListWidget::item:hover { color:#e5e5e5; background:#161616; }"+ "QListWidget::item:selected { color:%1; background:rgba(0,0,0,0.3);"+ " border-left:2px solid %1; font-weight:700; }").arg(kColor));+ for (const auto& pair : kIndicators) {+ auto* item = new QListWidgetItem(pair.first, indicator_list_);+ item->setData(Qt::UserRole, pair.second);+ }+ indicator_list_->setCurrentRow(0);+ lvl->addWidget(indicator_list_, 1);++ main->addWidget(left);++ auto* right = new QWidget;+ main->addWidget(right, 1);+ build_base_ui(right);++ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &ImfPanel::on_result);+}++// ── Activate ──────────────────────────────────────────────────────────────────++void ImfPanel::activate() {+ show_empty("Select an indicator and country, then click FETCH");+}++// ── Controls ──────────────────────────────────────────────────────────────────++void ImfPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("COUNTRY");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ country_combo_ = new QComboBox;+ for (const auto& pair : kCountries)+ country_combo_->addItem(pair.first, pair.second);+ country_combo_->setFixedHeight(26);+ country_combo_->setMinimumWidth(140);+ thl->addWidget(lbl);+ thl->addWidget(country_combo_);+}++// ── Fetch ─────────────────────────────────────────────────────────────────────++void ImfPanel::on_fetch() {+ auto* ind_item = indicator_list_->currentItem();+ if (!ind_item) { show_empty("Select an indicator"); return; }++ const QString code = ind_item->data(Qt::UserRole).toString();+ const QString country = country_combo_->currentData().toString();++ show_loading("Fetching IMF DataMapper data…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, "data",+ {code},+ "imf_data_" + code + "_" + country);+}++// ── Result ────────────────────────────────────────────────────────────────────++void ImfPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!result.success) { show_error(result.error); return; }++ if (request_id.startsWith("imf_data_")) {+ // Response: {values: {CODE: {COUNTRY: {YEAR: value}}}}+ const QJsonObject values = result.data["values"].toObject();+ if (values.isEmpty()) { show_error("No data in response"); return; }++ auto* ind_item = indicator_list_->currentItem();+ const QString code = ind_item ? ind_item->data(Qt::UserRole).toString()+ : values.keys().first();+ const QString country = country_combo_->currentData().toString();++ const QJsonArray rows = flatten_pivot(values, code, country);+ const QString title = (ind_item ? ind_item->text() : code) ++ (country.isEmpty() ? " — All Countries"+ : " — " + country_combo_->currentText());+ display(rows, title);+ LOG_INFO("ImfPanel", QString("Displayed %1 rows").arg(rows.size()));+ }+}++QJsonArray ImfPanel::flatten_pivot(const QJsonObject& values,+ const QString& indicator_code,+ const QString& country_filter) const {+ const QJsonObject by_country = values[indicator_code].toObject();+ QJsonArray rows;++ // Collect all years across all countries for sorting+ // If country_filter is set, only include that country+ const QStringList countries = country_filter.isEmpty()+ ? by_country.keys()+ : QStringList{country_filter};++ // Collect all years+ QSet<QString> year_set;+ for (const auto& c : countries) {+ for (const auto& y : by_country[c].toObject().keys())+ year_set.insert(y);+ }+ QStringList years = year_set.values();+ std::sort(years.begin(), years.end());++ if (country_filter.isEmpty()) {+ // Wide format: one row per country, columns = years (last 10)+ const QStringList recent_years = years.mid(qMax(0, years.size() - 10));+ for (const auto& c : countries) {+ const QJsonObject y_map = by_country[c].toObject();+ QJsonObject row;+ row["country"] = c;+ for (const auto& y : recent_years) {+ const QJsonValue v = y_map[y];+ row[y] = v.isNull() ? QJsonValue() : v;+ }+ rows.append(row);+ }+ } else {+ // Long format: one row per year for selected country+ const QJsonObject y_map = by_country[country_filter].toObject();+ for (const auto& y : years) {+ const QJsonValue v = y_map[y];+ if (v.isNull() || v.isUndefined()) continue;+ QJsonObject row;+ row["year"] = y;+ row["value"] = v;+ rows.append(row);+ }+ }+ return rows;+}++void ImfPanel::on_indicator_filter(const QString& text) {+ for (int i = 0; i < indicator_list_->count(); ++i) {+ auto* item = indicator_list_->item(i);+ item->setHidden(!item->text().contains(text, Qt::CaseInsensitive));+ }+}++void ImfPanel::load_indicators() {+ indicators_loaded_ = true;+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/ImfPanel.h b/fincept-qt/src/screens/economics/panels/ImfPanel.hnew file mode 100644index 000000000..0211b4000--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/ImfPanel.h@@ -0,0 +1,41 @@+// src/screens/economics/panels/ImfPanel.h+// IMF DataMapper — 133 macro indicators, all countries, pivot data.+// Script: imf_datamapper_data.py (no API key required)+#pragma once++#include "screens/economics/panels/EconPanelBase.h"++#include <QComboBox>+#include <QLineEdit>+#include <QListWidget>++namespace fincept::screens {++class ImfPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit ImfPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ void load_indicators();+ void on_indicator_filter(const QString& text);+ // Flatten nested pivot: values.INDICATOR.COUNTRY.YEAR -> rows+ QJsonArray flatten_pivot(const QJsonObject& values,+ const QString& indicator_code,+ const QString& country_filter) const;++ QLineEdit* indicator_search_ = nullptr;+ QListWidget* indicator_list_ = nullptr;+ QComboBox* country_combo_ = nullptr;++ bool indicators_loaded_ = false;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/OecdPanel.cpp b/fincept-qt/src/screens/economics/panels/OecdPanel.cppnew file mode 100644index 000000000..534cd1d31--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/OecdPanel.cpp@@ -0,0 +1,110 @@+// src/screens/economics/panels/OecdPanel.cpp+#include "screens/economics/panels/OecdPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>+#include <QVBoxLayout>++namespace fincept::screens {++static constexpr const char* kScript = "oecd_data.py";+static constexpr const char* kSourceId = "oecd";+static constexpr const char* kColor = "#F59E0B"; // amber++static const QList<QPair<QString,QString>> kDatasets = {+ {"GDP (Real)", "gdp_real"},+ {"CPI / Inflation", "cpi"},+ {"GDP Forecast", "gdp_forecast"},+ {"Unemployment", "unemployment"},+ {"Interest Rates", "interest_rates"},+ {"Trade Balance", "trade_balance"},+};++static const QList<QPair<QString,QString>> kCountries = {+ {"United States", "US"},+ {"Germany", "DE"},+ {"Japan", "JP"},+ {"France", "FR"},+ {"United Kingdom","GB"},+ {"Canada", "CA"},+ {"Australia", "AU"},+ {"South Korea", "KR"},+ {"Italy", "IT"},+ {"Spain", "ES"},+ {"G7", "G-7"},+ {"OECD Total", "OECD"},+};++OecdPanel::OecdPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &OecdPanel::on_result);+}++void OecdPanel::activate() {+ show_empty("Select a dataset and country, then click FETCH");+}++void OecdPanel::build_controls(QHBoxLayout* thl) {+ auto lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ dataset_combo_ = new QComboBox;+ for (const auto& p : kDatasets) dataset_combo_->addItem(p.first, p.second);+ dataset_combo_->setFixedHeight(26);++ country_combo_ = new QComboBox;+ for (const auto& p : kCountries) country_combo_->addItem(p.first, p.second);+ country_combo_->setFixedHeight(26);++ frequency_combo_ = new QComboBox;+ frequency_combo_->addItem("Annual", "A");+ frequency_combo_->addItem("Quarterly", "Q");+ frequency_combo_->addItem("Monthly", "M");+ frequency_combo_->setFixedHeight(26);++ thl->addWidget(lbl("DATASET"));+ thl->addWidget(dataset_combo_);+ thl->addWidget(lbl("COUNTRY"));+ thl->addWidget(country_combo_);+ thl->addWidget(lbl("FREQ"));+ thl->addWidget(frequency_combo_);+}++void OecdPanel::on_fetch() {+ const QString cmd = dataset_combo_->currentData().toString();+ const QString country = country_combo_->currentData().toString();+ const QString freq = frequency_combo_->currentData().toString();++ show_loading("Fetching OECD data…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, cmd,+ {country, freq},+ "oecd_" + cmd + "_" + country);+}++void OecdPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!result.success) { show_error(result.error); return; }+ if (request_id.startsWith("oecd_")) {+ const QJsonArray arr = result.data["data"].toArray();+ const QString title = dataset_combo_->currentText() ++ " — " + country_combo_->currentText();+ display(arr, title);+ LOG_INFO("OecdPanel", QString("Displayed %1 rows").arg(arr.size()));+ }+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/OecdPanel.h b/fincept-qt/src/screens/economics/panels/OecdPanel.hnew file mode 100644index 000000000..39b79f5aa--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/OecdPanel.h@@ -0,0 +1,29 @@+// src/screens/economics/panels/OecdPanel.h+// OECD Statistics — GDP, CPI, unemployment, trade, interest rates.+// Script: oecd_data.py (no API key, SDMX endpoints)+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class OecdPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit OecdPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* dataset_combo_ = nullptr;+ QComboBox* country_combo_ = nullptr;+ QComboBox* frequency_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/OnsPanel.cpp b/fincept-qt/src/screens/economics/panels/OnsPanel.cppnew file mode 100644index 000000000..35de271af--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/OnsPanel.cpp@@ -0,0 +1,110 @@+// src/screens/economics/panels/OnsPanel.cpp+// UK Office for National Statistics — GDP, CPI, unemployment, trade, housing.+// Script: ons_data.py | No API key required.+//+// Response shape: { success, series, label, unit, count, data:[{date, value}] }+#include "screens/economics/panels/OnsPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "ons_data.py";+static constexpr const char* kSourceId = "ons";+static constexpr const char* kColor = "#005EB8"; // ONS blue++struct OnsSeries {+ QString label;+ QString command;+};++static const QList<OnsSeries> kSeries = {+ { "GDP (Chained Volume, SA)", "gdp" },+ { "CPI All Items", "cpi" },+ { "CPIH (incl. Housing Costs)", "cpih" },+ { "RPI", "rpi" },+ { "Unemployment Rate", "unemployment" },+ { "Employment Rate", "employment" },+ { "Trade Balance (BoP)", "trade_balance" },+ { "House Prices (HPI)", "house_prices" },+ { "Average Earnings", "avg_earnings" },+ { "Public Sector Net Debt", "public_debt" },+};++OnsPanel::OnsPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &OnsPanel::on_result);+}++void OnsPanel::activate() {+ show_empty("Select a series and click FETCH\n"+ "Source: UK Office for National Statistics (no API key required)\n"+ "Data via api.beta.ons.gov.uk — GDP, CPI, labour market, housing");+}++void OnsPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("SERIES");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ series_combo_ = new QComboBox;+ for (const auto& s : kSeries)+ series_combo_->addItem(s.label, s.command);+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(240);++ thl->addWidget(lbl);+ thl->addWidget(series_combo_);+}++void OnsPanel::on_fetch() {+ const int idx = series_combo_->currentIndex();+ const auto& series = kSeries[idx];++ show_loading("Fetching ONS: " + series.label + "…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, series.command, {},+ "ons_" + series.command);+}++void OnsPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("ons_")) return;+ if (!result.success) { show_error(result.error); return; }++ // Check inline error+ const QString inline_err = result.data["error"].toString();+ if (!inline_err.isEmpty()) { show_error(inline_err); return; }++ // Response: { success, series, label, unit, count, data:[{date, value}] }+ QJsonArray rows = result.data["data"].toArray();++ if (rows.isEmpty()) {+ show_error("No data returned");+ return;+ }++ const QString label = result.data["label"].toString();+ const QString unit = result.data["unit"].toString();+ const QString title = "ONS: " + (label.isEmpty()+ ? (series_combo_->currentIndex() >= 0+ ? kSeries[series_combo_->currentIndex()].label+ : request_id.mid(4))+ : label)+ + (unit.isEmpty() ? "" : " (" + unit + ")");++ display(rows, title);+ LOG_INFO("OnsPanel", QString("Displayed %1 rows: %2").arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/OnsPanel.h b/fincept-qt/src/screens/economics/panels/OnsPanel.hnew file mode 100644index 000000000..6a0499e6c--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/OnsPanel.h@@ -0,0 +1,27 @@+// src/screens/economics/panels/OnsPanel.h+// UK Office for National Statistics panel.+// Script: ons_data.py | No API key required.+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class OnsPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit OnsPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* series_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/OwIdPanel.cpp b/fincept-qt/src/screens/economics/panels/OwIdPanel.cppnew file mode 100644index 000000000..e47560f12--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/OwIdPanel.cpp@@ -0,0 +1,143 @@+// src/screens/economics/panels/OwIdPanel.cpp+// Our World in Data — CO2, energy, life expectancy, poverty, GDP per capita.+// Script: owid_data.py | No API key required.+//+// Response shape: { success, title, country, count, data:[{country, year, <metric cols>}] }+#include "screens/economics/panels/OwIdPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "owid_data.py";+static constexpr const char* kSourceId = "owid";+static constexpr const char* kColor = "#10B981"; // OWID green++struct OwIdSeries {+ QString label;+ QString command;+ QString default_country;+};++static const QList<OwIdSeries> kSeries = {+ { "CO2 Emissions", "co2", "United States" },+ { "CO2 Per Capita", "co2_per_capita", "United States" },+ { "Energy Consumption", "energy", "China" },+ { "Life Expectancy", "life_expectancy", "Japan" },+ { "Poverty Headcount", "poverty", "World" },+ { "GDP Per Capita", "gdp_per_capita", "Germany" },+};++OwIdPanel::OwIdPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &OwIdPanel::on_result);+}++void OwIdPanel::activate() {+ show_empty("Select a series, enter a country and year range, then click FETCH\n"+ "Source: Our World in Data (ourworldindata.org) — no API key required\n"+ "Country examples: United States, China, Germany, India, Japan, World");+}++void OwIdPanel::build_controls(QHBoxLayout* thl) {+ auto mk_lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet("color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ series_combo_ = new QComboBox;+ for (const auto& s : kSeries)+ series_combo_->addItem(s.label, s.command);+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(180);++ country_edit_ = new QLineEdit("United States");+ country_edit_->setFixedHeight(26);+ country_edit_->setFixedWidth(130);+ country_edit_->setPlaceholderText("Country…");++ start_edit_ = new QLineEdit("2000");+ start_edit_->setFixedHeight(26);+ start_edit_->setFixedWidth(52);++ end_edit_ = new QLineEdit("2023");+ end_edit_->setFixedHeight(26);+ end_edit_->setFixedWidth(52);++ // Update default country when series changes+ connect(series_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, [this](int idx) {+ if (idx >= 0 && idx < kSeries.size())+ country_edit_->setText(kSeries[idx].default_country);+ });++ thl->addWidget(mk_lbl("SERIES"));+ thl->addWidget(series_combo_);+ thl->addSpacing(6);+ thl->addWidget(mk_lbl("COUNTRY"));+ thl->addWidget(country_edit_);+ thl->addSpacing(6);+ thl->addWidget(mk_lbl("FROM"));+ thl->addWidget(start_edit_);+ thl->addWidget(mk_lbl("TO"));+ thl->addWidget(end_edit_);+}++void OwIdPanel::on_fetch() {+ const int idx = series_combo_->currentIndex();+ const auto& series = kSeries[idx];++ const QString country = country_edit_->text().trimmed();+ const QString start = start_edit_->text().trimmed();+ const QString end = end_edit_->text().trimmed();++ if (country.isEmpty()) { show_error("Please enter a country name"); return; }++ show_loading("Fetching OWID: " + series.label + " — " + country + "…");++ services::EconomicsService::instance().execute(+ kSourceId, kScript, series.command,+ { country, start, end },+ "owid_" + series.command);+}++void OwIdPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("owid_")) return;+ if (!result.success) { show_error(result.error); return; }++ const QString inline_err = result.data["error"].toString();+ if (!inline_err.isEmpty()) { show_error(inline_err); return; }++ // Response: { success, title, country, count, data:[{country, year, <cols>}] }+ QJsonArray rows = result.data["data"].toArray();++ if (rows.isEmpty()) {+ show_error("No data returned — try a different country or year range");+ return;+ }++ const QString title = result.data["title"].toString();+ const QString country = result.data["country"].toString();+ const QString display_title = title.isEmpty()+ ? ("OWID: " + (series_combo_->currentIndex() >= 0+ ? kSeries[series_combo_->currentIndex()].label : request_id.mid(5)))+ : (title + (country.isEmpty() || country == "All" ? "" : " — " + country));++ display(rows, display_title);+ LOG_INFO("OwIdPanel",+ QString("Displayed %1 rows: %2").arg(rows.size()).arg(display_title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/OwIdPanel.h b/fincept-qt/src/screens/economics/panels/OwIdPanel.hnew file mode 100644index 000000000..3ab6c380a--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/OwIdPanel.h@@ -0,0 +1,31 @@+// src/screens/economics/panels/OwIdPanel.h+// Our World in Data panel — CO2, energy, life expectancy, poverty, GDP.+// Script: owid_data.py | No API key required.+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>+#include <QLineEdit>++namespace fincept::screens {++class OwIdPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit OwIdPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* series_combo_ = nullptr;+ QLineEdit* country_edit_ = nullptr;+ QLineEdit* start_edit_ = nullptr;+ QLineEdit* end_edit_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/StatCanPanel.cpp b/fincept-qt/src/screens/economics/panels/StatCanPanel.cppnew file mode 100644index 000000000..a1736b9db--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/StatCanPanel.cpp@@ -0,0 +1,113 @@+// src/screens/economics/panels/StatCanPanel.cpp+// Statistics Canada — GDP, CPI, unemployment, employment, population, housing starts.+// Script: statcan_data.py | No API key required.+//+// Response shape: { success, vector_id, product_id, label, count, data:[{date, value}], series }+#include "screens/economics/panels/StatCanPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "statcan_data.py";+static constexpr const char* kSourceId = "statcan";+static constexpr const char* kColor = "#EF4444"; // Canada red++struct StatCanSeries {+ QString label;+ QString command;+ QString description;+};++static const QList<StatCanSeries> kSeries = {+ { "Real GDP (Chained 2017 $, SA)", "gdp", "Table 36-10-0104-01, v65201210, quarterly" },+ { "CPI All-Items, Canada", "cpi", "Table 18-10-0004-01, v41690973, monthly" },+ { "Unemployment Rate", "unemployment", "Table 14-10-0287-01, v2062815, monthly" },+ { "Employment Rate", "employment", "Table 14-10-0287-01, v2062817, monthly" },+ { "Population Estimate (Canada)", "population", "Table 17-10-0005-01, v466668, quarterly" },+ { "Housing Starts (SA, SAAR)", "housing", "Table 34-10-0158-01, v52300157, monthly" },+};++StatCanPanel::StatCanPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &StatCanPanel::on_result);+}++void StatCanPanel::activate() {+ show_empty("Select a series and click FETCH\n"+ "Source: Statistics Canada WDS API (www150.statcan.gc.ca)\n"+ "No API key required — data via vector IDs for reliability");+}++void StatCanPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("SERIES");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");++ series_combo_ = new QComboBox;+ for (const auto& s : kSeries)+ series_combo_->addItem(s.label, s.command);+ series_combo_->setFixedHeight(26);+ series_combo_->setMinimumWidth(240);++ // Show description as tooltip+ for (int i = 0; i < kSeries.size(); ++i)+ series_combo_->setItemData(i, kSeries[i].description, Qt::ToolTipRole);++ thl->addWidget(lbl);+ thl->addWidget(series_combo_);+}++void StatCanPanel::on_fetch() {+ const int idx = series_combo_->currentIndex();+ const auto& series = kSeries[idx];++ show_loading("Fetching StatCan: " + series.label + "…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, series.command, {},+ "statcan_" + series.command);+}++void StatCanPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("statcan_")) return;+ if (!result.success) { show_error(result.error); return; }++ const QString inline_err = result.data["error"].toString();+ if (!inline_err.isEmpty()) { show_error(inline_err); return; }++ // Response: { success, vector_id, label, count, data:[{date, value}], series }+ QJsonArray rows = result.data["data"].toArray();++ if (rows.isEmpty()) {+ show_error("No data returned");+ return;+ }++ // Build title from label or series name+ QString label = result.data["label"].toString().trimmed();+ const QString series_key = result.data["series"].toString();+ if (label.isEmpty()) {+ // Find display label from kSeries+ for (const auto& s : kSeries) {+ if (s.command == series_key) { label = s.label; break; }+ }+ }+ const QString title = "StatCan: " + (label.isEmpty() ? request_id.mid(8) : label);++ display(rows, title);+ LOG_INFO("StatCanPanel",+ QString("Displayed %1 rows: %2").arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/StatCanPanel.h b/fincept-qt/src/screens/economics/panels/StatCanPanel.hnew file mode 100644index 000000000..a810b2ca0--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/StatCanPanel.h@@ -0,0 +1,27 @@+// src/screens/economics/panels/StatCanPanel.h+// Statistics Canada panel — GDP, CPI, unemployment, employment, population, housing.+// Script: statcan_data.py | No API key required.+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class StatCanPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit StatCanPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* series_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.cpp b/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.cppnew file mode 100644index 000000000..4df6075a7--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.cpp@@ -0,0 +1,180 @@+// src/screens/economics/panels/TradingEconomicsPanel.cpp+// Trading Economics panel. Requires TRADING_ECONOMICS_API_KEY env var.+//+// Working commands (with key): ratings, ratings_by_agency, bonds,+// us_treasuries, european_bonds, yield_curve, country_data, calendar+// Response shape varies per command — normalised via extract_te_rows().+#include "screens/economics/panels/TradingEconomicsPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "trading_economics_data.py";+static constexpr const char* kSourceId = "trading_economics";+static constexpr const char* kColor = "#F59E0B"; // amber++struct TeDataset {+ QString label;+ QString command;+ QString country_arg; // "required", "optional", or ""+};++static const QList<TeDataset> kDatasets = {+ { "Credit Ratings (All)", "ratings", "" },+ { "Credit Ratings by Agency", "ratings_by_agency", "" },+ { "US Treasuries", "us_treasuries", "" },+ { "European Bonds", "european_bonds", "" },+ { "Bond Yield Curve", "yield_curve", "required" },+ { "Country Economic Data", "country_data", "required" },+ { "Economic Calendar", "calendar", "" },+};++static const QList<QPair<QString,QString>> kCountries = {+ { "United States", "US" }, { "Germany", "DE" }, { "Japan", "JP" },+ { "United Kingdom","GB" }, { "France", "FR" }, { "Italy", "IT" },+ { "China", "CN" }, { "Brazil", "BR" }, { "India", "IN" },+ { "Australia", "AU" }, { "Canada", "CA" }, { "Spain", "ES" },+};++TradingEconomicsPanel::TradingEconomicsPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &TradingEconomicsPanel::on_result);+}++void TradingEconomicsPanel::activate() {+ show_empty("Set TRADING_ECONOMICS_API_KEY environment variable, then select a dataset and click FETCH\n"+ "Get a key at: tradingeconomics.com/api");+}++void TradingEconomicsPanel::build_controls(QHBoxLayout* thl) {+ auto lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ dataset_combo_ = new QComboBox;+ for (const auto& d : kDatasets)+ dataset_combo_->addItem(d.label, d.command);+ dataset_combo_->setFixedHeight(26);+ dataset_combo_->setMinimumWidth(200);++ country_combo_ = new QComboBox;+ for (const auto& c : kCountries)+ country_combo_->addItem(c.first, c.second);+ country_combo_->setFixedHeight(26);+ country_combo_->setMinimumWidth(130);+ country_combo_->setToolTip("Required for yield_curve and country_data");++ thl->addWidget(lbl("DATASET"));+ thl->addWidget(dataset_combo_);+ thl->addWidget(lbl("COUNTRY"));+ thl->addWidget(country_combo_);+}++void TradingEconomicsPanel::on_fetch() {+ const int idx = dataset_combo_->currentIndex();+ const auto& dataset = kDatasets[idx];+ const QString country = country_combo_->currentData().toString();++ show_loading("Fetching Trading Economics: " + dataset.label + "…");++ QStringList args = { dataset.command };+ if (dataset.country_arg == "required" || dataset.country_arg == "optional")+ args << country;++ services::EconomicsService::instance().execute(+ kSourceId, kScript, dataset.command, args,+ "te_" + dataset.command + (args.size() > 1 ? "_" + country : ""));+}++// Normalise various Trading Economics response shapes into displayable rows.+static QJsonArray extract_te_rows(const QJsonObject& data) {+ // Shape 1: direct array in "data" key+ QJsonArray arr = data["data"].toArray();+ if (!arr.isEmpty()) return arr;++ // Shape 2: ratings array+ arr = data["ratings"].toArray();+ if (!arr.isEmpty()) return arr;++ // Shape 3: bonds / treasuries / yield_curve+ arr = data["bonds"].toArray();+ if (!arr.isEmpty()) return arr;++ arr = data["treasuries"].toArray();+ if (!arr.isEmpty()) return arr;++ arr = data["yield_curve"].toArray();+ if (!arr.isEmpty()) return arr;++ // Shape 4: events / calendar+ arr = data["events"].toArray();+ if (!arr.isEmpty()) return arr;++ // Shape 5: single object with country data fields — wrap in array+ if (data.contains("country") || data.contains("gdp") || data.contains("inflation")) {+ return QJsonArray{ data };+ }++ return {};+}++void TradingEconomicsPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("te_")) return;++ if (!result.success) {+ const QString msg = result.error;+ if (msg.contains("API key") || msg.contains("TRADING_ECONOMICS_API_KEY")) {+ show_error("Trading Economics API key not configured.\n"+ "Set TRADING_ECONOMICS_API_KEY environment variable.\n"+ "Get a key at: tradingeconomics.com/api");+ } else {+ show_error(msg);+ }+ return;+ }++ // Also check for inline error field+ if (result.data.contains("error") && !result.data["error"].toBool(false)) {+ const QString err = result.data["error"].toString();+ if (!err.isEmpty() && err != "false") {+ if (err.contains("API key") || err.contains("TRADING_ECONOMICS")) {+ show_error("Trading Economics API key not configured.\n"+ "Set TRADING_ECONOMICS_API_KEY environment variable.\n"+ "Get a key at: tradingeconomics.com/api");+ } else {+ show_error(err);+ }+ return;+ }+ }++ const QJsonArray rows = extract_te_rows(result.data);+ if (rows.isEmpty()) {+ show_error("No data returned — API key may be required");+ return;+ }++ const int idx = dataset_combo_->currentIndex();+ const QString title = "Trading Economics: "+ + (idx >= 0 && idx < kDatasets.size() ? kDatasets[idx].label : request_id.mid(3));+ display(rows, title);+ LOG_INFO("TradingEconomicsPanel", QString("Displayed %1 rows: %2")+ .arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.h b/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.hnew file mode 100644index 000000000..2fb595220--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.h@@ -0,0 +1,29 @@+// src/screens/economics/panels/TradingEconomicsPanel.h+// Trading Economics — bonds, yield curves, country data.+// Script: trading_economics_data.py+// Requires TRADING_ECONOMICS_API_KEY environment variable.+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class TradingEconomicsPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit TradingEconomicsPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* dataset_combo_ = nullptr;+ QComboBox* country_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/UnComtradePanel.cpp b/fincept-qt/src/screens/economics/panels/UnComtradePanel.cppnew file mode 100644index 000000000..001766dd9--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/UnComtradePanel.cpp@@ -0,0 +1,117 @@+// src/screens/economics/panels/UnComtradePanel.cpp+#include "screens/economics/panels/UnComtradePanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QDate>+#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>+#include <QVBoxLayout>++namespace fincept::screens {++static constexpr const char* kScript = "un_comtrade_data.py";+static constexpr const char* kSourceId = "un_comtrade";+static constexpr const char* kColor = "#0891B2"; // cyan++// ISO numeric reporter codes for major economies+static const QList<QPair<QString,QString>> kReporters = {+ {"United States", "842"},+ {"China", "156"},+ {"Germany", "276"},+ {"Japan", "392"},+ {"United Kingdom", "826"},+ {"France", "251"},+ {"India", "699"},+ {"Brazil", "76"},+ {"Canada", "124"},+ {"South Korea", "410"},+ {"Australia", "36"},+ {"Russia", "643"},+ {"Mexico", "484"},+ {"World", "0"},+};++UnComtradePanel::UnComtradePanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &UnComtradePanel::on_result);+}++void UnComtradePanel::activate() {+ show_empty("Select reporter, flow, and period, then click FETCH\n"+ "(Free tier: up to 250 records per request)");+}++void UnComtradePanel::build_controls(QHBoxLayout* thl) {+ auto lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ reporter_combo_ = new QComboBox;+ for (const auto& p : kReporters) reporter_combo_->addItem(p.first, p.second);+ reporter_combo_->setFixedHeight(26);++ flow_combo_ = new QComboBox;+ flow_combo_->addItem("Exports", "X");+ flow_combo_->addItem("Imports", "M");+ flow_combo_->addItem("Re-exports", "RX");+ flow_combo_->addItem("Re-imports", "RM");+ flow_combo_->setFixedHeight(26);++ // Last 5 years+ period_combo_ = new QComboBox;+ int cur_year = QDate::currentDate().year();+ for (int y = cur_year; y >= cur_year - 5; --y)+ period_combo_->addItem(QString::number(y), QString::number(y));+ period_combo_->setFixedHeight(26);++ cmd_combo_ = new QComboBox;+ cmd_combo_->addItem("All Commodities", "AG2");+ cmd_combo_->addItem("Total (all)", "TOTAL");+ cmd_combo_->setFixedHeight(26);++ thl->addWidget(lbl("REPORTER"));+ thl->addWidget(reporter_combo_);+ thl->addWidget(lbl("FLOW"));+ thl->addWidget(flow_combo_);+ thl->addWidget(lbl("YEAR"));+ thl->addWidget(period_combo_);+}++void UnComtradePanel::on_fetch() {+ const QString reporter = reporter_combo_->currentData().toString();+ const QString period = period_combo_->currentData().toString();+ const QString flow = flow_combo_->currentData().toString();++ show_loading("Fetching UN Comtrade data…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, "trade_balance",+ {reporter, period},+ "comtrade_" + reporter + "_" + period + "_" + flow);+}++void UnComtradePanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!result.success) { show_error(result.error); return; }++ if (request_id.startsWith("comtrade_")) {+ const QJsonArray arr = result.data["data"].toArray();+ const QString title = reporter_combo_->currentText() + " — " ++ flow_combo_->currentText() + " " ++ period_combo_->currentText();+ display(arr, title);+ LOG_INFO("UnComtradePanel", QString("Displayed %1 rows").arg(arr.size()));+ }+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/UnComtradePanel.h b/fincept-qt/src/screens/economics/panels/UnComtradePanel.hnew file mode 100644index 000000000..750dc5fa1--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/UnComtradePanel.h@@ -0,0 +1,31 @@+// src/screens/economics/panels/UnComtradePanel.h+// UN Comtrade — international trade statistics (free tier).+// Script: un_comtrade_data.py+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>+#include <QLineEdit>++namespace fincept::screens {++class UnComtradePanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit UnComtradePanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ QComboBox* reporter_combo_ = nullptr;+ QComboBox* flow_combo_ = nullptr;+ QComboBox* period_combo_ = nullptr;+ QComboBox* cmd_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.cpp b/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.cppnew file mode 100644index 000000000..24f206cf2--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.cpp@@ -0,0 +1,159 @@+// src/screens/economics/panels/WorldBankHealthPanel.cpp+// World Bank health & development indicators panel.+//+// Response shape:+// { indicator, country, total, records: [+// { date:"2023", value:78.3, indicator:{id,value}, country:{id,value},+// countryiso3code, unit, obs_status, decimal }+// ]}+// Flatten: filter null values, extract date+value, sort oldest→newest.+#include "screens/economics/panels/WorldBankHealthPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>++namespace fincept::screens {++static constexpr const char* kScript = "worldbank_health_data.py";+static constexpr const char* kSourceId = "wb_health";+static constexpr const char* kColor = "#16A34A"; // green++struct WbHealthIndicator {+ QString label;+ QString command;+ QString unit;+};++static const QList<WbHealthIndicator> kIndicators = {+ { "Life Expectancy", "life_expectancy", "years" },+ { "Infant Mortality Rate", "infant_mortality", "per 1,000" },+ { "Literacy Rate (Adult)", "literacy", "%" },+ { "Gini Index (Inequality)", "gini", "index" },+ { "Human Development Index", "hdi", "index" },+ { "Poverty Rate ($2.15/day)", "poverty", "%" },+};++static const QList<QPair<QString,QString>> kCountries = {+ { "United States", "US" }, { "China", "CN" }, { "Germany", "DE" },+ { "Japan", "JP" }, { "United Kingdom", "GB" }, { "France", "FR" },+ { "India", "IN" }, { "Brazil", "BR" }, { "Canada", "CA" },+ { "South Korea", "KR" }, { "Australia", "AU" }, { "Russia", "RU" },+ { "Mexico", "MX" }, { "Indonesia", "ID" }, { "Spain", "ES" },+ { "Italy", "IT" }, { "Netherlands", "NL" }, { "Turkey", "TR" },+ { "Saudi Arabia", "SA" }, { "South Africa", "ZA" }, { "Nigeria", "NG" },+ { "World", "WLD"},+};++QJsonArray WorldBankHealthPanel::flatten_wb(const QJsonObject& response) {+ const QJsonArray records = response["records"].toArray();+ if (records.isEmpty()) return {};++ QJsonArray rows;+ for (const auto& rv : records) {+ const QJsonObject r = rv.toObject();+ if (r["value"].isNull() || r["value"].isUndefined()) continue;+ const double val = r["value"].toDouble();+ // Skip placeholder zeros for HDI/similar where 0 is not meaningful+ QJsonObject row;+ row["date"] = r["date"].toString();+ row["value"] = val;+ rows.append(row);+ }++ // Sort oldest→newest — copy to QList to avoid QJsonValueRef swap issue on MSVC+ QList<QJsonValue> sorted(rows.begin(), rows.end());+ std::sort(sorted.begin(), sorted.end(), [](const QJsonValue& a, const QJsonValue& b) {+ return a.toObject()["date"].toString() < b.toObject()["date"].toString();+ });+ rows = QJsonArray();+ for (const auto& v : sorted) rows.append(v);++ return rows;+}++WorldBankHealthPanel::WorldBankHealthPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {+ build_base_ui(this);+ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &WorldBankHealthPanel::on_result);+}++void WorldBankHealthPanel::activate() {+ show_empty("Select an indicator and country, then click FETCH\n"+ "Source: World Bank — Health & Development indicators");+}++void WorldBankHealthPanel::build_controls(QHBoxLayout* thl) {+ auto lbl = [](const QString& t) {+ auto* l = new QLabel(t);+ l->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ return l;+ };++ indicator_combo_ = new QComboBox;+ for (const auto& ind : kIndicators)+ indicator_combo_->addItem(ind.label, ind.command);+ indicator_combo_->setFixedHeight(26);+ indicator_combo_->setMinimumWidth(200);++ country_combo_ = new QComboBox;+ for (const auto& c : kCountries)+ country_combo_->addItem(c.first, c.second);+ country_combo_->setFixedHeight(26);+ country_combo_->setMinimumWidth(130);++ thl->addWidget(lbl("INDICATOR"));+ thl->addWidget(indicator_combo_);+ thl->addWidget(lbl("COUNTRY"));+ thl->addWidget(country_combo_);+}++void WorldBankHealthPanel::on_fetch() {+ const QString command = indicator_combo_->currentData().toString();+ const QString country = country_combo_->currentData().toString();++ show_loading("Fetching WB Health: " + indicator_combo_->currentText()+ + " — " + country_combo_->currentText() + "…");++ services::EconomicsService::instance().execute(+ kSourceId, kScript, command,+ { country },+ "wbhealth_" + command + "_" + country);+}++void WorldBankHealthPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!request_id.startsWith("wbhealth_")) return;+ if (!result.success) { show_error(result.error); return; }++ QJsonArray rows = flatten_wb(result.data);++ if (rows.isEmpty())+ rows = result.data["data"].toArray();++ if (rows.isEmpty()) {+ show_error("No data available for this selection");+ return;+ }++ const int idx = indicator_combo_->currentIndex();+ const QString unit = (idx >= 0 && idx < kIndicators.size())+ ? " (" + kIndicators[idx].unit + ")"+ : "";+ const QString title = "WB Health: " + indicator_combo_->currentText()+ + unit + " — " + country_combo_->currentText();++ display(rows, title);+ LOG_INFO("WorldBankHealthPanel", QString("Displayed %1 records: %2")+ .arg(rows.size()).arg(title));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.h b/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.hnew file mode 100644index 000000000..57ac993ae--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.h@@ -0,0 +1,33 @@+// src/screens/economics/panels/WorldBankHealthPanel.h+// World Bank Health & Development indicators.+// Script: worldbank_health_data.py+// Commands: life_expectancy, infant_mortality, literacy, gini, hdi, poverty+#pragma once++#include "screens/economics/panels/EconPanelBase.h"+#include <QComboBox>++namespace fincept::screens {++class WorldBankHealthPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit WorldBankHealthPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ /// Flatten WB records [{date, value, indicator:{value}, country:{value}}]+ /// into [{date, value}], filtering null values, sorted oldest→newest.+ static QJsonArray flatten_wb(const QJsonObject& response);++ QComboBox* indicator_combo_ = nullptr;+ QComboBox* country_combo_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/WorldBankPanel.cpp b/fincept-qt/src/screens/economics/panels/WorldBankPanel.cppnew file mode 100644index 000000000..63c5a8aff--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/WorldBankPanel.cpp@@ -0,0 +1,252 @@+// src/screens/economics/panels/WorldBankPanel.cpp+#include "screens/economics/panels/WorldBankPanel.h"++#include "core/logging/Logger.h"+#include "services/economics/EconomicsService.h"++#include <QDate>+#include <QHBoxLayout>+#include <QJsonArray>+#include <QJsonObject>+#include <QLabel>+#include <QSplitter>+#include <QVBoxLayout>++namespace fincept::screens {++static constexpr const char* kScript = "worldbank_data.py";+static constexpr const char* kSourceId = "worldbank";+static constexpr const char* kColor = "#22C55E";++static const QList<QPair<QString,QString>> kIndicators = {+ {"GDP (current US$)", "NY.GDP.MKTP.CD"},+ {"GDP per capita (current US$)", "NY.GDP.PCAP.CD"},+ {"GDP growth (annual %)", "NY.GDP.MKTP.KD.ZG"},+ {"GNI per capita (current US$)", "NY.GNP.PCAP.CD"},+ {"Inflation, CPI (annual %)", "FP.CPI.TOTL.ZG"},+ {"Unemployment (% labor force)", "SL.UEM.TOTL.ZS"},+ {"Population, total", "SP.POP.TOTL"},+ {"Population growth (annual %)", "SP.POP.GROW"},+ {"Life expectancy at birth", "SP.DYN.LE00.IN"},+ {"Exports of goods & services (% GDP)", "NE.EXP.GNFS.ZS"},+ {"Imports of goods & services (% GDP)", "NE.IMP.GNFS.ZS"},+ {"Current account balance (% GDP)", "BN.CAB.XOKA.GD.ZS"},+ {"Government debt (% GDP)", "GC.DOD.TOTL.GD.ZS"},+ {"FDI net inflows (% GDP)", "BX.KLT.DINV.WD.GD.ZS"},+ {"Electric power consumption (kWh/cap)", "EG.USE.ELEC.KH.PC"},+ {"CO2 emissions (metric tons per cap)", "EN.ATM.CO2E.PC"},+ {"Internet users (% population)", "IT.NET.USER.ZS"},+ {"Mobile subscriptions (per 100)", "IT.CEL.SETS.P2"},+ {"Forest area (% land area)", "AG.LND.FRST.ZS"},+ {"Access to electricity (% pop)", "EG.ELC.ACCS.ZS"},+};++// ── Constructor ───────────────────────────────────────────────────────────────++WorldBankPanel::WorldBankPanel(QWidget* parent)+ : EconPanelBase(kSourceId, kColor, parent) {++ // Outer layout: left selector | right content (base UI)+ auto* main = new QHBoxLayout(this);+ main->setContentsMargins(0, 0, 0, 0);+ main->setSpacing(0);++ // ── Left: country + indicator selectors ──────────────────────────────────+ auto* left = new QWidget;+ left->setFixedWidth(220);+ left->setStyleSheet("background:#0a0a0a; border-right:1px solid #1a1a1a;");+ auto* lvl = new QVBoxLayout(left);+ lvl->setContentsMargins(0, 0, 0, 0);+ lvl->setSpacing(0);++ auto section_header = [](const QString& text) {+ auto* lbl = new QLabel(text);+ lbl->setStyleSheet("color:#525252; font-size:8px; font-weight:700;"+ " letter-spacing:1px; background:#111111;"+ " padding:4px 10px; border-bottom:1px solid #1a1a1a;");+ return lbl;+ };++ auto list_style = [](const QString& col) {+ return QString(+ "QListWidget { background:transparent; border:none; outline:none; }"+ "QListWidget::item { color:#808080; padding:5px 10px;"+ " border-bottom:1px solid #111111; font-size:11px; }"+ "QListWidget::item:hover { color:#e5e5e5; background:#161616; }"+ "QListWidget::item:selected { color:%1; background:rgba(0,0,0,0.3);"+ " border-left:2px solid %1; font-weight:700; }").arg(col);+ };++ auto search_style = []() {+ return QString("background:#080808; color:#e5e5e5; border:none;"+ " border-bottom:1px solid #1a1a1a; padding:4px 10px;"+ " font-size:11px;");+ };++ // Country+ lvl->addWidget(section_header("COUNTRY"));+ country_search_ = new QLineEdit;+ country_search_->setPlaceholderText("Filter countries…");+ country_search_->setStyleSheet(search_style());+ connect(country_search_, &QLineEdit::textChanged,+ this, &WorldBankPanel::on_country_filter);+ lvl->addWidget(country_search_);++ country_list_ = new QListWidget;+ country_list_->setStyleSheet(list_style(kColor));+ connect(country_list_, &QListWidget::currentItemChanged, this,+ [this](QListWidgetItem* item) {+ if (item) selected_country_ = item->data(Qt::UserRole).toString();+ });+ lvl->addWidget(country_list_, 2);++ // Indicator+ lvl->addWidget(section_header("INDICATOR"));+ indicator_search_ = new QLineEdit;+ indicator_search_->setPlaceholderText("Filter indicators…");+ indicator_search_->setStyleSheet(search_style());+ connect(indicator_search_, &QLineEdit::textChanged,+ this, &WorldBankPanel::on_indicator_filter);+ lvl->addWidget(indicator_search_);++ indicator_list_ = new QListWidget;+ indicator_list_->setStyleSheet(list_style(kColor));+ for (const auto& pair : kIndicators) {+ auto* item = new QListWidgetItem(pair.first, indicator_list_);+ item->setData(Qt::UserRole, pair.second);+ }+ indicator_list_->setCurrentRow(0);+ selected_indicator_ = kIndicators[0].second;+ lvl->addWidget(indicator_list_, 3);++ main->addWidget(left);++ // ── Right: base UI (toolbar + stat cards + table) ─────────────────────────+ auto* right = new QWidget;+ main->addWidget(right, 1);+ build_base_ui(right);++ connect(&services::EconomicsService::instance(),+ &services::EconomicsService::result_ready,+ this, &WorldBankPanel::on_result);+}++// ── Activate ──────────────────────────────────────────────────────────────────++void WorldBankPanel::activate() {+ if (!countries_loaded_) load_countries();+}++void WorldBankPanel::load_countries() {+ countries_loaded_ = true;+ show_loading("Loading countries…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, "countries", {}, "wb_countries");+}++// ── Controls ──────────────────────────────────────────────────────────────────++void WorldBankPanel::build_controls(QHBoxLayout* thl) {+ auto* lbl = new QLabel("YEARS");+ lbl->setStyleSheet(+ "color:#525252; font-size:9px; font-weight:700; background:transparent;");+ date_preset_ = new QComboBox;+ date_preset_->addItem("5 Years", 5);+ date_preset_->addItem("10 Years", 10);+ date_preset_->addItem("20 Years", 20);+ date_preset_->addItem("50 Years", 50);+ date_preset_->setCurrentIndex(1);+ date_preset_->setFixedHeight(26);+ thl->addWidget(lbl);+ thl->addWidget(date_preset_);+}++// ── Fetch ─────────────────────────────────────────────────────────────────────++void WorldBankPanel::on_fetch() {+ if (selected_country_.isEmpty()) {+ show_empty("Select a country from the left panel");+ return;+ }+ auto* ind_item = indicator_list_->currentItem();+ if (!ind_item) {+ show_empty("Select an indicator from the left panel");+ return;+ }+ selected_indicator_ = ind_item->data(Qt::UserRole).toString();+ int years = date_preset_->currentData().toInt();+ int end_year = QDate::currentDate().year();+ QString range = QString::number(end_year - years) + ":" ++ QString::number(end_year);++ show_loading("Fetching World Bank data…");+ services::EconomicsService::instance().execute(+ kSourceId, kScript, "indicators",+ {selected_country_, selected_indicator_, range},+ "wb_data_" + selected_country_ + "_" + selected_indicator_);+}++// ── Result ────────────────────────────────────────────────────────────────────++void WorldBankPanel::on_result(const QString& request_id,+ const services::EconomicsResult& result) {+ if (result.source_id != kSourceId) return;+ if (!result.success) { show_error(result.error); return; }++ if (request_id == "wb_countries") {+ const QJsonArray arr = result.data["data"].toArray();+ country_list_->clear();+ for (const auto& v : arr) {+ const auto obj = v.toObject();+ const QString n = obj["name"].toString();+ const QString id= obj["iso2Code"].toString();+ if (n.isEmpty() || id.isEmpty()) continue;+ if (obj["region"].toString().contains("Aggregates")) continue;+ auto* item = new QListWidgetItem(n, country_list_);+ item->setData(Qt::UserRole, id);+ }+ // Default select United States+ const auto hits = country_list_->findItems("United States", Qt::MatchExactly);+ if (!hits.isEmpty()) {+ country_list_->setCurrentItem(hits.first());+ selected_country_ = "US";+ }+ show_empty("Select a country and indicator, then click FETCH");+ LOG_INFO("WorldBankPanel", QString("Loaded %1 countries").arg(arr.size()));+ return;+ }++ if (request_id.startsWith("wb_data_")) {+ // Reverse to chronological order, skip null values+ QJsonArray clean;+ const QJsonArray raw = result.data["data"].toArray();+ for (int i = raw.size() - 1; i >= 0; --i) {+ const auto obj = raw[i].toObject();+ if (!obj["value"].isNull()) clean.append(obj);+ }+ auto* ind = indicator_list_->currentItem();+ display(clean,+ (ind ? ind->text() : selected_indicator_) ++ " — " + selected_country_);+ LOG_INFO("WorldBankPanel",+ QString("Displayed %1 data points").arg(clean.size()));+ }+}++// ── Filters ───────────────────────────────────────────────────────────────────++void WorldBankPanel::on_country_filter(const QString& text) {+ for (int i = 0; i < country_list_->count(); ++i) {+ auto* item = country_list_->item(i);+ item->setHidden(!item->text().contains(text, Qt::CaseInsensitive));+ }+}++void WorldBankPanel::on_indicator_filter(const QString& text) {+ for (int i = 0; i < indicator_list_->count(); ++i) {+ auto* item = indicator_list_->item(i);+ item->setHidden(!item->text().contains(text, Qt::CaseInsensitive));+ }+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/economics/panels/WorldBankPanel.h b/fincept-qt/src/screens/economics/panels/WorldBankPanel.hnew file mode 100644index 000000000..da9663366--- /dev/null+++ b/fincept-qt/src/screens/economics/panels/WorldBankPanel.h@@ -0,0 +1,42 @@+// src/screens/economics/panels/WorldBankPanel.h+// World Bank Open Data — 296 countries, 70+ sources, 1000s of indicators.+// Script: worldbank_data.py (no API key required)+#pragma once++#include "screens/economics/panels/EconPanelBase.h"++#include <QComboBox>+#include <QLineEdit>+#include <QListWidget>++namespace fincept::screens {++class WorldBankPanel : public EconPanelBase {+ Q_OBJECT+ public:+ explicit WorldBankPanel(QWidget* parent = nullptr);+ void activate() override;++ protected:+ void build_controls(QHBoxLayout* thl) override;+ void on_fetch() override;+ void on_result(const QString& request_id,+ const services::EconomicsResult& result) override;++ private:+ void load_countries();+ void on_country_filter(const QString& text);+ void on_indicator_filter(const QString& text);++ QLineEdit* country_search_ = nullptr;+ QListWidget* country_list_ = nullptr;+ QLineEdit* indicator_search_ = nullptr;+ QListWidget* indicator_list_ = nullptr;+ QComboBox* date_preset_ = nullptr;++ QString selected_country_ = "US";+ QString selected_indicator_;+ bool countries_loaded_ = false;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/forum/ForumFeedPanel.cpp b/fincept-qt/src/screens/forum/ForumFeedPanel.cppindex b7dc1e85b..67310fc55 100644--- a/fincept-qt/src/screens/forum/ForumFeedPanel.cpp+++ b/fincept-qt/src/screens/forum/ForumFeedPanel.cpp@@ -29,12 +29,12 @@ static QString rel_time(const QString& iso) {if (sec < 0)sec = 0;if (sec < 60)- return QString("%1s").arg(sec);+ return QString("%1s ago").arg(sec);if (sec < 3600)- return QString("%1m").arg(sec / 60);+ return QString("%1m ago").arg(sec / 60);if (sec < 86400)- return QString("%1h").arg(sec / 3600);- return QString("%1d").arg(sec / 86400);+ return QString("%1h ago").arg(sec / 3600);+ return QString("%1d ago").arg(sec / 86400);}static QString det_color(const QString& s) {@@ -51,116 +51,47 @@ static QString fmt_n(int n) {return QString::number(n);}-// ── Section header helper ─────────────────────────────────────────────────────-static QWidget* make_section_hdr(const QString& title, const QString& accent = "#d97706") {- auto* w = new QWidget;- w->setFixedHeight(24);- w->setStyleSheet("background:#060606;border-bottom:1px solid #0e0e0e;");- auto* hl = new QHBoxLayout(w);- hl->setContentsMargins(16, 0, 16, 0);- hl->setSpacing(6);- auto* dot = new QLabel("■");- dot->setStyleSheet(QString("color:%1;font-size:6px;background:transparent;").arg(accent));- auto* lbl = new QLabel(title);- lbl->setStyleSheet(QString("color:#707070;font-size:9px;font-weight:700;letter-spacing:1.5px;"- "background:transparent;%1")- .arg(M(9)));- hl->addWidget(dot);- hl->addWidget(lbl);- hl->addStretch();- return w;-}--static QFrame* thin_line() {- auto* f = new QFrame;- f->setFixedHeight(1);- f->setStyleSheet("background:#0e0e0e;border:none;");- return f;-}-ForumFeedPanel::ForumFeedPanel(QWidget* parent) : QWidget(parent) {build_ui();}void ForumFeedPanel::build_ui() {- setStyleSheet("background:#080808;");+ setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* root = new QVBoxLayout(this);root->setContentsMargins(0, 0, 0, 0);root->setSpacing(0);+ build_toolbar();+ root->addWidget(toolbar_);++ // ── Scrollable content ────────────────────────────────────────────────────scroll_ = new QScrollArea;scroll_->setWidgetResizable(true);scroll_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);- scroll_->setStyleSheet("QScrollArea{border:none;background:#080808;}"- "QScrollBar:vertical{width:4px;background:transparent;margin:0;}"- "QScrollBar::handle:vertical{background:#151515;min-height:30px;}"- "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}");+ scroll_->setStyleSheet(+ QString("QScrollArea{border:none;background:%1;}"+ "QScrollBar:vertical{width:6px;background:transparent;margin:0;}"+ "QScrollBar::handle:vertical{background:%2;min-height:40px;"+ "border-radius:3px;}"+ "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical"+ "{height:0;}")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));content_w_ = new QWidget;- content_w_->setStyleSheet("background:#080808;");+ content_w_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));content_vl_ = new QVBoxLayout(content_w_);content_vl_->setContentsMargins(0, 0, 0, 0);content_vl_->setSpacing(0);- // ── 1. Stats bar (rebuilt by set_stats) ───────────────────────────────────- stats_section_ = new QWidget;- stats_section_->setFixedHeight(0);- content_vl_->addWidget(stats_section_);-- // ── 2. Two-column: profile + contributors ─────────────────────────────────- auto* mid_row = new QWidget;- mid_row->setStyleSheet("background:#080808;");- auto* mid_hl = new QHBoxLayout(mid_row);- mid_hl->setContentsMargins(0, 0, 0, 0);- mid_hl->setSpacing(0);-- profile_section_ = new QWidget;- profile_section_->setStyleSheet("background:#080808;border-right:1px solid #0e0e0e;");- mid_hl->addWidget(profile_section_, 1);-- contrib_section_ = new QWidget;- contrib_section_->setStyleSheet("background:#080808;");- mid_hl->addWidget(contrib_section_, 1);- content_vl_->addWidget(mid_row);-- // ── 3. Category cards ─────────────────────────────────────────────────────- cats_section_ = new QWidget;- cats_section_->setFixedHeight(0);- content_vl_->addWidget(cats_section_);-- // ── 4. Posts header ───────────────────────────────────────────────────────- auto* posts_hdr = new QWidget;- posts_hdr->setFixedHeight(28);- posts_hdr->setStyleSheet("background:#060606;border-bottom:1px solid #0e0e0e;"- "border-top:1px solid #0e0e0e;");- auto* ph_hl = new QHBoxLayout(posts_hdr);- ph_hl->setContentsMargins(16, 0, 16, 0);- ph_hl->setSpacing(8);-- auto* ph_dot = new QLabel("■");- ph_dot->setStyleSheet("color:#d97706;font-size:6px;background:transparent;");- posts_header_lbl_ = new QLabel("LATEST POSTS");- posts_header_lbl_->setStyleSheet(QString("color:#707070;font-size:9px;font-weight:700;letter-spacing:1.5px;"- "background:transparent;%1")- .arg(M(9)));- posts_count_lbl_ = new QLabel;- posts_count_lbl_->setStyleSheet(QString("color:#555555;font-size:9px;background:transparent;%1").arg(M(9)));-- ph_hl->addWidget(ph_dot);- ph_hl->addWidget(posts_header_lbl_);- ph_hl->addStretch();- ph_hl->addWidget(posts_count_lbl_);- content_vl_->addWidget(posts_hdr);-- // ── 5. Posts container ────────────────────────────────────────────────────+ // Posts containerposts_container_ = new QWidget;- posts_container_->setStyleSheet("background:#080808;");+ posts_container_->setStyleSheet("background:transparent;");posts_vl_ = new QVBoxLayout(posts_container_);posts_vl_->setContentsMargins(0, 0, 0, 0);posts_vl_->setSpacing(0);content_vl_->addWidget(posts_container_);-content_vl_->addStretch();+scroll_->setWidget(content_w_);root->addWidget(scroll_, 1);@@ -170,338 +101,109 @@ void ForumFeedPanel::build_ui() {}// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-// Dashboard data setters+// Toolbar: header + category chips + new post button// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+void ForumFeedPanel::build_toolbar() {+ toolbar_ = new QWidget;+ toolbar_->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));++ auto* tb_vl = new QVBoxLayout(toolbar_);+ tb_vl->setContentsMargins(0, 0, 0, 0);+ tb_vl->setSpacing(0);++ // ── Top row: header + stats + new post ────────────────────────────────────+ auto* top_row = new QWidget;+ top_row->setFixedHeight(48);+ top_row->setStyleSheet("background:transparent;");+ auto* top_hl = new QHBoxLayout(top_row);+ top_hl->setContentsMargins(20, 0, 16, 0);+ top_hl->setSpacing(12);++ // Channel icon + name+ auto* hash = new QLabel("#");+ hash->setStyleSheet(+ QString("color:%1;font-size:22px;font-weight:700;background:transparent;%2")+ .arg(ui::colors::AMBER, M(22)));++ header_lbl_ = new QLabel("DISCUSSIONS");+ header_lbl_->setStyleSheet(+ QString("color:%1;font-size:15px;font-weight:700;letter-spacing:1px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(15)));++ header_count_lbl_ = new QLabel;+ header_count_lbl_->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));++ // New post button+ auto* new_btn = new QPushButton("+ NEW POST");+ new_btn->setFixedHeight(30);+ new_btn->setCursor(Qt::PointingHandCursor);+ new_btn->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.1);color:%1;"+ "border:1px solid rgba(217,119,6,0.25);padding:0 16px;"+ "font-size:11px;font-weight:700;letter-spacing:0.5px;%2}"+ "QPushButton:hover{background:rgba(217,119,6,0.2);color:%3;"+ "border-color:rgba(217,119,6,0.5);}")+ .arg(ui::colors::TEXT_SECONDARY, M(11), ui::colors::AMBER));+ connect(new_btn, &QPushButton::clicked, this,+ [this]() { emit new_post_clicked(); });++ top_hl->addWidget(hash);+ top_hl->addWidget(header_lbl_);+ top_hl->addWidget(header_count_lbl_);+ top_hl->addStretch();+ top_hl->addWidget(new_btn);+ tb_vl->addWidget(top_row);++ // ── Bottom row: scrollable category chips ─────────────────────────────────+ auto* chips_scroll = new QScrollArea;+ chips_scroll->setFixedHeight(36);+ chips_scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);+ chips_scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);+ chips_scroll->setStyleSheet(+ QString("QScrollArea{border:none;background:transparent;"+ "border-top:1px solid %1;}")+ .arg(ui::colors::BORDER_DIM));+ chips_scroll->setWidgetResizable(false);++ chips_container_ = new QWidget;+ chips_container_->setFixedHeight(36);+ chips_container_->setStyleSheet("background:transparent;");+ chips_layout_ = new QHBoxLayout(chips_container_);+ chips_layout_->setContentsMargins(16, 0, 16, 0);+ chips_layout_->setSpacing(6);+ chips_layout_->addStretch();++ chips_container_->adjustSize();+ chips_scroll->setWidget(chips_container_);+ tb_vl->addWidget(chips_scroll);+}+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+// Data setters+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━void ForumFeedPanel::set_stats(const services::ForumStats& stats) {stats_ = stats;stats_loaded_ = true;- rebuild_stats();- rebuild_contributors();}void ForumFeedPanel::set_profile(const services::ForumProfile& profile) {profile_ = profile;- profile_loaded_ = true;- rebuild_profile();}-void ForumFeedPanel::set_categories(const QVector<services::ForumCategory>& cats, int active_id) {+void ForumFeedPanel::set_categories(const QVector<services::ForumCategory>& cats,+ int active_id) {categories_ = cats;active_cat_id_ = active_id;- cats_loaded_ = true;- rebuild_categories();-}--// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-// Stats bar — 5 metric cells in a row-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-void ForumFeedPanel::rebuild_stats() {- // Clear old- delete stats_section_->layout();- auto children = stats_section_->findChildren<QWidget*>(QString(), Qt::FindDirectChildrenOnly);- for (auto* c : children)- c->deleteLater();- stats_section_->setFixedHeight(QWIDGETSIZE_MAX);-- auto* vl = new QVBoxLayout(stats_section_);- vl->setContentsMargins(0, 0, 0, 0);- vl->setSpacing(0);-- vl->addWidget(make_section_hdr("COMMUNITY OVERVIEW", "#d97706"));-- auto* row = new QWidget;- row->setStyleSheet("background:#0a0a0a;border-bottom:1px solid #0e0e0e;");- auto* hl = new QHBoxLayout(row);- hl->setContentsMargins(0, 0, 0, 0);- hl->setSpacing(0);-- struct StatDef {- QString label;- QString value;- QString color;- };- StatDef defs[] = {- {"CATEGORIES", fmt_n(stats_.total_categories), "#555555"}, {"POSTS", fmt_n(stats_.total_posts), "#e5e5e5"},- {"COMMENTS", fmt_n(stats_.total_comments), "#06b6d4"}, {"VOTES", fmt_n(stats_.total_votes), "#10b981"},- {"24H ACTIVE", fmt_n(stats_.recent_posts_24h), "#d97706"},- };-- for (int i = 0; i < 5; ++i) {- auto* cell = new QWidget;- cell->setStyleSheet(i < 4 ? "background:transparent;border-right:1px solid #0e0e0e;"- : "background:transparent;");- auto* cvl = new QVBoxLayout(cell);- cvl->setContentsMargins(16, 10, 16, 10);- cvl->setSpacing(2);- auto* val_lbl = new QLabel(defs[i].value);- val_lbl->setStyleSheet(- QString("color:%1;font-size:16px;font-weight:700;background:transparent;%2").arg(defs[i].color, M(16)));- auto* lbl = new QLabel(defs[i].label);- lbl->setStyleSheet(- QString("color:#606060;font-size:8px;letter-spacing:1px;background:transparent;%1").arg(M(8)));- cvl->addWidget(val_lbl);- cvl->addWidget(lbl);- hl->addWidget(cell, 1);- }- vl->addWidget(row);+ rebuild_category_chips();}-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-// Profile card-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-void ForumFeedPanel::rebuild_profile() {- delete profile_section_->layout();- auto children = profile_section_->findChildren<QWidget*>(QString(), Qt::FindDirectChildrenOnly);- for (auto* c : children)- c->deleteLater();-- auto* vl = new QVBoxLayout(profile_section_);- vl->setContentsMargins(0, 0, 0, 0);- vl->setSpacing(0);-- vl->addWidget(make_section_hdr("MY PROFILE", "#06b6d4"));-- auto* card = new QWidget;- card->setStyleSheet("background:#0a0a0a;border-bottom:1px solid #0e0e0e;");- auto* card_vl = new QVBoxLayout(card);- card_vl->setContentsMargins(16, 10, 16, 10);- card_vl->setSpacing(6);-- // Avatar + name row- auto* top = new QWidget;- top->setStyleSheet("background:transparent;");- auto* top_hl = new QHBoxLayout(top);- top_hl->setContentsMargins(0, 0, 0, 0);- top_hl->setSpacing(10);-- QString av_col = profile_.avatar_color.isEmpty() ? "#d97706" : profile_.avatar_color;- auto* avatar = new QLabel(profile_.display_name.left(2).toUpper());- avatar->setFixedSize(32, 32);- avatar->setAlignment(Qt::AlignCenter);- avatar->setStyleSheet(QString("color:#080808;font-size:12px;font-weight:700;background:%1;%2").arg(av_col, M(12)));-- auto* name_col = new QVBoxLayout;- name_col->setSpacing(1);- name_col->setContentsMargins(0, 0, 0, 0);- auto* name_lbl = new QLabel(profile_.display_name.toUpper());- name_lbl->setStyleSheet(- QString("color:%1;font-size:12px;font-weight:700;background:transparent;%2").arg(av_col, M(12)));- auto* handle = new QLabel("@" + profile_.username);- handle->setStyleSheet(QString("color:#666666;font-size:10px;background:transparent;%1").arg(M(10)));- name_col->addWidget(name_lbl);- name_col->addWidget(handle);-- top_hl->addWidget(avatar);- top_hl->addLayout(name_col, 1);- card_vl->addWidget(top);-- // Bio- if (!profile_.bio.isEmpty()) {- auto* bio = new QLabel(profile_.bio);- bio->setWordWrap(true);- bio->setStyleSheet(QString("color:#444444;font-size:11px;font-style:italic;"- "background:transparent;%1")- .arg(M(11)));- card_vl->addWidget(bio);- }-- // Stats row- auto* stat_row = new QWidget;- stat_row->setStyleSheet("background:transparent;");- auto* sr_hl = new QHBoxLayout(stat_row);- sr_hl->setContentsMargins(0, 4, 0, 0);- sr_hl->setSpacing(14);-- auto mk_ps = [&](const QString& lbl, int val, const QString& col) {- auto* w = new QWidget;- w->setStyleSheet("background:transparent;");- auto* hl = new QHBoxLayout(w);- hl->setContentsMargins(0, 0, 0, 0);- hl->setSpacing(4);- auto* v = new QLabel(QString::number(val));- v->setStyleSheet(QString("color:%1;font-size:11px;font-weight:700;background:transparent;%2").arg(col, M(11)));- auto* l = new QLabel(lbl);- l->setStyleSheet(QString("color:#666666;font-size:10px;background:transparent;%1").arg(M(10)));- hl->addWidget(v);- hl->addWidget(l);- return w;- };-- sr_hl->addWidget(mk_ps("REP", profile_.reputation, "#d97706"));- sr_hl->addWidget(mk_ps("posts", profile_.posts_count, "#888888"));- sr_hl->addWidget(mk_ps("comments", profile_.comments_count, "#888888"));- sr_hl->addWidget(mk_ps("likes", profile_.likes_given, "#10b981"));- sr_hl->addStretch();- card_vl->addWidget(stat_row);-- // Signature- if (!profile_.signature.isEmpty()) {- auto* sig = new QLabel("\"" + profile_.signature + "\"");- sig->setStyleSheet(QString("color:#666666;font-size:10px;background:transparent;%1").arg(M(10)));- card_vl->addWidget(sig);- }-- vl->addWidget(card);-}--// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-// Top contributors-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-void ForumFeedPanel::rebuild_contributors() {- delete contrib_section_->layout();- auto children = contrib_section_->findChildren<QWidget*>(QString(), Qt::FindDirectChildrenOnly);- for (auto* c : children)- c->deleteLater();-- auto* vl = new QVBoxLayout(contrib_section_);- vl->setContentsMargins(0, 0, 0, 0);- vl->setSpacing(0);-- vl->addWidget(make_section_hdr("TOP CONTRIBUTORS", "#10b981"));-- static const char* rank_col[] = {"#d97706", "#aaaaaa", "#cd7f32", "#555555", "#555555"};-- for (int i = 0; i < std::min(5, (int)stats_.top_contributors.size()); ++i) {- const auto& c = stats_.top_contributors[i];- auto* row = new QWidget;- row->setFixedHeight(28);- row->setStyleSheet(i % 2 == 0 ? "background:#0a0a0a;border-bottom:1px solid #0d0d0d;"- : "background:#090909;border-bottom:1px solid #0d0d0d;");- auto* hl = new QHBoxLayout(row);- hl->setContentsMargins(16, 0, 16, 0);- hl->setSpacing(8);-- // Rank- auto* rank_lbl = new QLabel(QString("#%1").arg(i + 1));- rank_lbl->setFixedWidth(22);- rank_lbl->setStyleSheet(- QString("color:%1;font-size:10px;font-weight:700;background:transparent;%2").arg(rank_col[i], M(10)));-- // Avatar- auto* av = new QLabel(c.display_name.left(2).toUpper());- av->setFixedSize(18, 18);- av->setAlignment(Qt::AlignCenter);- av->setStyleSheet(QString("color:#080808;font-size:8px;font-weight:700;background:%1;%2")- .arg(det_color(c.display_name), M(8)));-- // Name- auto* name = new QLabel(c.display_name.left(16));- name->setStyleSheet(QString("color:#666666;font-size:11px;background:transparent;%1").arg(M(11)));-- // Rep + posts- auto* rep = new QLabel(QString("▲ %1").arg(c.reputation));- rep->setStyleSheet(QString("color:%1;font-size:10px;background:transparent;%2").arg(rank_col[i], M(10)));-- auto* posts = new QLabel(QString("%1 posts").arg(c.posts_count));- posts->setStyleSheet(QString("color:#666666;font-size:10px;background:transparent;%1").arg(M(10)));-- hl->addWidget(rank_lbl);- hl->addWidget(av);- hl->addWidget(name, 1);- hl->addWidget(posts);- hl->addSpacing(6);- hl->addWidget(rep);- vl->addWidget(row);- }-- if (stats_.top_contributors.isEmpty()) {- auto* empty = new QLabel(" No contributors yet");- empty->setFixedHeight(28);- empty->setStyleSheet(QString("color:#1a1a1a;font-size:10px;background:#0a0a0a;%1").arg(M(10)));- vl->addWidget(empty);- }-- vl->addStretch();-}--// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-// Category cards — horizontal row-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-void ForumFeedPanel::rebuild_categories() {- delete cats_section_->layout();- auto children = cats_section_->findChildren<QWidget*>(QString(), Qt::FindDirectChildrenOnly);- for (auto* c : children)- c->deleteLater();- cats_section_->setFixedHeight(QWIDGETSIZE_MAX);-- auto* vl = new QVBoxLayout(cats_section_);- vl->setContentsMargins(0, 0, 0, 0);- vl->setSpacing(0);-- vl->addWidget(make_section_hdr("CHANNELS", "#8b5cf6"));-- auto* row = new QWidget;- row->setStyleSheet("background:#080808;border-bottom:1px solid #0e0e0e;");- auto* hl = new QHBoxLayout(row);- hl->setContentsMargins(12, 8, 12, 8);- hl->setSpacing(6);-- for (const auto& cat : categories_) {- const bool active = (cat.id == active_cat_id_);- QString cc = cat.color.isEmpty() ? "#d97706" : cat.color;-- auto* card = new QWidget;- card->setCursor(Qt::PointingHandCursor);- card->setStyleSheet(active ? QString("background:#111111;border:none;border-bottom:2px solid %1;").arg(cc)- : "background:#0a0a0a;border:none;border-bottom:2px solid transparent;");- auto* cvl = new QVBoxLayout(card);- cvl->setContentsMargins(12, 8, 12, 8);- cvl->setSpacing(3);-- // Name + count- auto* name_row = new QWidget;- name_row->setStyleSheet("background:transparent;");- auto* nr_hl = new QHBoxLayout(name_row);- nr_hl->setContentsMargins(0, 0, 0, 0);- nr_hl->setSpacing(6);-- auto* dot = new QLabel("●");- dot->setStyleSheet(QString("color:%1;font-size:8px;background:transparent;").arg(cc));- auto* nm = new QLabel(cat.name.toUpper());- nm->setStyleSheet(- active ? QString("color:#e5e5e5;font-size:11px;font-weight:700;background:transparent;%1").arg(M(11))- : QString("color:#888888;font-size:11px;font-weight:600;background:transparent;%1").arg(M(11)));- auto* cnt = new QLabel(QString::number(cat.post_count));- cnt->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;background:transparent;%2").arg(cc, M(10)));-- nr_hl->addWidget(dot);- nr_hl->addWidget(nm);- nr_hl->addStretch();- nr_hl->addWidget(cnt);- cvl->addWidget(name_row);-- // Description- if (!cat.description.isEmpty()) {- auto* desc = new QLabel(cat.description);- desc->setWordWrap(true);- desc->setStyleSheet(QString("color:#666666;font-size:10px;background:transparent;%1").arg(M(10)));- desc->setMaximumHeight(28);- cvl->addWidget(desc);- }-- // Click handler- auto* click = new QPushButton(card);- click->setGeometry(0, 0, 4000, 200);- click->setFlat(true);- click->setStyleSheet("QPushButton{background:transparent;border:none;}");- click->raise();- auto cat_copy = cat;- connect(click, &QPushButton::clicked, this,- [this, cat_copy]() { emit category_clicked(cat_copy.id, cat_copy.name, cat_copy.color); });-- hl->addWidget(card, 1);- }-- vl->addWidget(row);-}--// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-// Posts-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-void ForumFeedPanel::set_header(const QString& text) {- posts_header_lbl_->setText(text.toUpper());+ header_lbl_->setText(text.toUpper());}void ForumFeedPanel::set_loading(bool on) {@@ -516,75 +218,16 @@ void ForumFeedPanel::set_loading(bool on) {}}-void ForumFeedPanel::show_skeleton() {- if (skeleton_w_) {- skeleton_w_->deleteLater();- skeleton_w_ = nullptr;- }- skeleton_w_ = new QWidget(posts_container_);- auto* vl = new QVBoxLayout(skeleton_w_);- vl->setContentsMargins(12, 6, 12, 6);- vl->setSpacing(6);- for (int i = 0; i < 5; ++i) {- auto* card = new QWidget;- card->setFixedHeight(90);- card->setStyleSheet("background:#0a0a0a;border:1px solid #0d0d0d;");- auto* cvl = new QVBoxLayout(card);- cvl->setContentsMargins(16, 12, 16, 12);- cvl->setSpacing(8);- for (int j = 0; j < 3; ++j) {- auto* bar = new QWidget;- int w[] = {130, 300 + i * 25, 160};- bar->setFixedHeight(j == 1 ? 11 : 7);- bar->setMaximumWidth(w[j]);- bar->setStyleSheet(QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"- "stop:0 #0e0e0e,stop:%1 #181818,stop:1 #0e0e0e);")- .arg(0.3 + (i % 4) * 0.15));- cvl->addWidget(bar);- }- cvl->addStretch();- vl->addWidget(card);- }- posts_vl_->insertWidget(0, skeleton_w_);- skeleton_timer_->start();-}--void ForumFeedPanel::pulse_skeleton() {- if (!skeleton_w_)- return;- static int off = 0;- off = (off + 12) % 100;- double s = off / 100.0, e = std::min(1.0, s + 0.28);- QString bg = QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"- "stop:0 #090909,stop:%1 #1d1d1d,stop:%2 #090909);")- .arg(s, 0, 'f', 2)- .arg(e, 0, 'f', 2);- auto* vl = qobject_cast<QVBoxLayout*>(skeleton_w_->layout());- if (!vl)- return;- for (int i = 0; i < vl->count(); ++i) {- auto* ci = vl->itemAt(i);- if (!ci || !ci->widget())- continue;- auto* cvl = qobject_cast<QVBoxLayout*>(ci->widget()->layout());- if (!cvl)- continue;- for (int j = 0; j < cvl->count(); ++j) {- auto* bi = cvl->itemAt(j);- if (bi && bi->widget() && bi->widget()->height() <= 14)- bi->widget()->setStyleSheet(bg);- }- }-}-void ForumFeedPanel::clear_active() {active_uuid_.clear();}+void ForumFeedPanel::set_active_post(const QString& uuid) {active_uuid_ = uuid;}-void ForumFeedPanel::set_posts(const services::ForumPostsPage& pg, const QString& cc) {+void ForumFeedPanel::set_posts(const services::ForumPostsPage& pg,+ const QString& cc) {page_ = pg;cat_color_ = cc;skeleton_timer_->stop();@@ -595,6 +238,54 @@ void ForumFeedPanel::set_posts(const services::ForumPostsPage& pg, const QStringrebuild_posts();}+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+// Category chips+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+void ForumFeedPanel::rebuild_category_chips() {+ while (chips_layout_->count() > 0) {+ auto* item = chips_layout_->takeAt(0);+ if (item->widget())+ item->widget()->deleteLater();+ delete item;+ }++ for (const auto& cat : categories_) {+ const bool active = (cat.id == active_cat_id_);+ QString cc = cat.color.isEmpty() ? ui::colors::AMBER : cat.color;++ auto* chip = new QPushButton(cat.name.toUpper());+ chip->setFixedHeight(24);+ chip->setCursor(Qt::PointingHandCursor);+ chip->setStyleSheet(+ active+ ? QString("QPushButton{background:%1;color:%2;"+ "border:none;padding:0 14px;"+ "font-size:10px;font-weight:700;letter-spacing:0.5px;"+ "border-radius:12px;%3}")+ .arg(cc, ui::colors::BG_BASE, M(10))+ : QString("QPushButton{background:transparent;color:%1;"+ "border:1px solid %2;padding:0 14px;"+ "font-size:10px;letter-spacing:0.3px;"+ "border-radius:12px;%3}"+ "QPushButton:hover{color:%4;border-color:%5;"+ "background:rgba(255,255,255,0.02);}")+ .arg(ui::colors::TEXT_SECONDARY, ui::colors::BORDER_DIM,+ M(10), ui::colors::TEXT_PRIMARY,+ ui::colors::BORDER_MED));+ connect(chip, &QPushButton::clicked, this,+ [this, cat]() {+ emit category_clicked(cat.id, cat.name, cat.color);+ });+ chips_layout_->addWidget(chip);+ }++ chips_layout_->addStretch();+ chips_container_->adjustSize();+}++// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+// Posts+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━void ForumFeedPanel::rebuild_posts() {posts_container_->setUpdatesEnabled(false);while (posts_vl_->count() > 0) {@@ -604,159 +295,241 @@ void ForumFeedPanel::rebuild_posts() {delete item;}- posts_count_lbl_->setText(- QString("%1 posts · page %2/%3").arg(page_.total).arg(page_.page).arg(std::max(1, page_.pages)));+ header_count_lbl_->setText(+ page_.total > 0 ? QString("%1 posts").arg(page_.total) : "");if (page_.posts.isEmpty()) {auto* empty = new QWidget;- empty->setMinimumHeight(100);+ empty->setMinimumHeight(200);empty->setStyleSheet("background:transparent;");auto* evl = new QVBoxLayout(empty);- auto* lbl = new QLabel("No posts in this category yet. Be the first!");- lbl->setAlignment(Qt::AlignCenter);- lbl->setStyleSheet(QString("color:#555555;font-size:12px;background:transparent;%1").arg(M(12)));- evl->addStretch();- evl->addWidget(lbl);- evl->addStretch();+ evl->setAlignment(Qt::AlignCenter);+ evl->setSpacing(8);++ auto* icon = new QLabel("◇");+ icon->setAlignment(Qt::AlignCenter);+ icon->setStyleSheet(+ QString("color:%1;font-size:32px;background:transparent;")+ .arg(ui::colors::BORDER_DIM));++ auto* msg = new QLabel("NO DISCUSSIONS YET");+ msg->setAlignment(Qt::AlignCenter);+ msg->setStyleSheet(+ QString("color:%1;font-size:14px;font-weight:700;letter-spacing:1.5px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(14)));++ auto* sub = new QLabel("Be the first to start a conversation");+ sub->setAlignment(Qt::AlignCenter);+ sub->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(11)));++ evl->addWidget(icon);+ evl->addWidget(msg);+ evl->addWidget(sub);posts_vl_->addWidget(empty);posts_container_->setUpdatesEnabled(true);return;}- // Grid: 12px padding on sides+ // ── Post cards with modern design ─────────────────────────────────────────auto* grid = new QWidget;grid->setStyleSheet("background:transparent;");auto* gvl = new QVBoxLayout(grid);- gvl->setContentsMargins(12, 6, 12, 6);- gvl->setSpacing(6);+ gvl->setContentsMargins(16, 10, 16, 10);+ gvl->setSpacing(8);for (int i = 0; i < page_.posts.size(); ++i) {const auto& p = page_.posts[i];const bool active = (p.post_uuid == active_uuid_);- QString cc = p.category_color.isEmpty() ? det_color(p.category_name) : p.category_color;+ QString cc = p.category_color.isEmpty() ? det_color(p.category_name)+ : p.category_color;bool voted_up = (p.user_vote == "up");auto* card = new QWidget;card->setCursor(Qt::PointingHandCursor);- card->setStyleSheet(active ? QString("background:#0c0c0c;border:1px solid #181818;"- "border-left:3px solid %1;")- .arg(cc)- : "background:#0a0a0a;border:1px solid #0e0e0e;"- "border-left:3px solid #0e0e0e;");+ card->setStyleSheet(+ active+ ? QString("background:rgba(217,119,6,0.04);"+ "border:1px solid rgba(217,119,6,0.2);"+ "border-left:3px solid %1;border-radius:4px;")+ .arg(cc)+ : QString("background:%1;"+ "border:1px solid %2;"+ "border-left:3px solid transparent;"+ "border-radius:4px;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));auto* cl = new QVBoxLayout(card);- cl->setContentsMargins(14, 10, 14, 8);- cl->setSpacing(5);+ cl->setContentsMargins(16, 12, 16, 10);+ cl->setSpacing(6);- // ── Row 1: avatar · author · category · time ─────────────────────────+ // ── Row 1: avatar + author + category + time ──────────────────────────auto* r1 = new QWidget;r1->setStyleSheet("background:transparent;");auto* r1h = new QHBoxLayout(r1);r1h->setContentsMargins(0, 0, 0, 0);- r1h->setSpacing(7);+ r1h->setSpacing(8);+ // Circular avatarauto* av = new QLabel(p.author_display_name.left(2).toUpper());- av->setFixedSize(22, 22);+ av->setFixedSize(28, 28);av->setAlignment(Qt::AlignCenter);- av->setStyleSheet(QString("color:#080808;font-size:9px;font-weight:700;background:%1;%2")- .arg(det_color(p.author_display_name), M(9)));-- auto* au = new QLabel(p.author_display_name.left(20));- au->setStyleSheet(QString("color:#555555;font-size:11px;font-weight:600;background:transparent;%1").arg(M(11)));-- auto* chip = new QLabel(p.category_name.toUpper().left(14));- chip->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;background:transparent;"- "border:1px solid %1;padding:0px 5px;letter-spacing:0.3px;%2")- .arg(cc, M(9)));+ QString avc = det_color(p.author_display_name);+ av->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;background:%2;"+ "border-radius:14px;%3")+ .arg(ui::colors::BG_BASE, avc, M(10)));++ // Author + time column+ auto* author_col = new QVBoxLayout;+ author_col->setSpacing(0);+ author_col->setContentsMargins(0, 0, 0, 0);++ auto* au = new QLabel(p.author_display_name);+ au->setStyleSheet(+ QString("color:%1;font-size:12px;font-weight:600;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(12)));auto* tm = new QLabel(rel_time(p.created_at));- tm->setStyleSheet(QString("color:#666666;font-size:10px;background:transparent;%1").arg(M(10)));+ tm->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(10)));++ author_col->addWidget(au);+ author_col->addWidget(tm);++ // Category chip (pill style)+ auto* chip = new QLabel(p.category_name.toUpper());+ chip->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;background:transparent;"+ "border:1px solid %1;padding:2px 8px;letter-spacing:0.5px;"+ "border-radius:10px;%2")+ .arg(cc, M(9)));+ chip->setFixedHeight(18);r1h->addWidget(av);- r1h->addWidget(au);- r1h->addSpacing(4);+ r1h->addLayout(author_col, 1);r1h->addWidget(chip);- r1h->addStretch();- r1h->addWidget(tm);cl->addWidget(r1);- // ── Row 2: title ─────────────────────────────────────────────────────+ // ── Row 2: title ──────────────────────────────────────────────────────auto* title = new QLabel(p.title);title->setWordWrap(true);- title->setStyleSheet(active ? QString("color:#f0f0f0;font-size:14px;font-weight:700;"- "background:transparent;%1")- .arg(M(14))- : QString("color:#c0c0c0;font-size:14px;font-weight:600;"- "background:transparent;%1")- .arg(M(14)));+ title->setStyleSheet(+ active+ ? QString("color:%1;font-size:15px;font-weight:700;"+ "background:transparent;line-height:1.3;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(15))+ : QString("color:#c8c8c8;font-size:15px;font-weight:600;"+ "background:transparent;line-height:1.3;%1")+ .arg(M(15)));cl->addWidget(title);- // ── Row 3: body preview ──────────────────────────────────────────────+ // ── Row 3: body preview ───────────────────────────────────────────────if (!p.content.isEmpty()) {- QString preview = p.content.left(160).replace('\n', ' ');- if (p.content.length() > 160)+ QString preview = p.content.left(180).replace('\n', ' ');+ if (p.content.length() > 180)preview += "...";- auto* body_lbl = new QLabel(preview);- body_lbl->setWordWrap(true);- body_lbl->setMaximumHeight(36);- body_lbl->setStyleSheet(QString("color:#777777;font-size:12px;background:transparent;"- "line-height:1.4;%1")- .arg(M(12)));- cl->addWidget(body_lbl);+ auto* body = new QLabel(preview);+ body->setWordWrap(true);+ body->setMaximumHeight(40);+ body->setStyleSheet(+ QString("color:%1;font-size:12px;background:transparent;"+ "line-height:1.5;%2")+ .arg(ui::colors::TEXT_SECONDARY, M(12)));+ cl->addWidget(body);}- // ── Row 4: engagement ────────────────────────────────────────────────+ // ── Row 4: engagement bar ─────────────────────────────────────────────auto* eng = new QWidget;eng->setStyleSheet("background:transparent;");auto* eng_hl = new QHBoxLayout(eng);- eng_hl->setContentsMargins(0, 2, 0, 0);- eng_hl->setSpacing(14);-- auto mk_eng = [&](const QString& icon, const QString& val, const QString& col) {- auto* w = new QWidget;- w->setStyleSheet("background:transparent;");- auto* hl = new QHBoxLayout(w);- hl->setContentsMargins(0, 0, 0, 0);- hl->setSpacing(3);- auto* ic = new QLabel(icon);- ic->setStyleSheet(QString("color:%1;font-size:10px;background:transparent;%2").arg(col, M(10)));- auto* v = new QLabel(val);- v->setStyleSheet(QString("color:#666666;font-size:10px;background:transparent;%1").arg(M(10)));- hl->addWidget(ic);- hl->addWidget(v);- return w;+ eng_hl->setContentsMargins(0, 4, 0, 0);+ eng_hl->setSpacing(16);++ // Upvote button (clickable, not just a label)+ auto* up_btn = new QPushButton(+ QString("▲ %1").arg(fmt_n(p.likes)));+ up_btn->setFixedHeight(22);+ up_btn->setCursor(Qt::PointingHandCursor);+ QString like_col = voted_up || p.likes > 0 ? ui::colors::AMBER : ui::colors::TEXT_DIM;+ up_btn->setStyleSheet(+ voted_up+ ? QString("QPushButton{background:rgba(217,119,6,0.12);"+ "color:%1;border:1px solid rgba(217,119,6,0.3);"+ "font-size:10px;font-weight:700;padding:0 8px;"+ "border-radius:11px;%2}"+ "QPushButton:hover{background:rgba(217,119,6,0.2);}")+ .arg(ui::colors::AMBER, M(10))+ : QString("QPushButton{background:transparent;"+ "color:%1;border:1px solid transparent;"+ "font-size:10px;padding:0 8px;"+ "border-radius:11px;%2}"+ "QPushButton:hover{color:%3;"+ "background:rgba(217,119,6,0.06);"+ "border-color:rgba(217,119,6,0.2);}")+ .arg(like_col, M(10), ui::colors::AMBER));+ auto post_uuid = p.post_uuid;+ connect(up_btn, &QPushButton::clicked, this,+ [this, post_uuid]() {+ emit vote_post_requested(post_uuid, "up");+ });++ auto mk_eng = [&](const QString& icon, const QString& val,+ const QString& col) {+ auto* lbl = new QLabel(icon + " " + val);+ lbl->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(col, M(10)));+ return lbl;};- QString like_col = voted_up ? "#d97706" : (p.likes > 0 ? "#d97706" : "#1e1e1e");- eng_hl->addWidget(mk_eng("▲", fmt_n(p.likes), like_col));- eng_hl->addWidget(- mk_eng("◆", QString("%1 replies").arg(p.reply_count), p.reply_count > 0 ? "#06b6d4" : "#1e1e1e"));+ QString rep_col = p.reply_count > 0 ? ui::colors::CYAN : "#1e1e1e";++ eng_hl->addWidget(up_btn);+ eng_hl->addWidget(mk_eng("◆", QString("%1 replies").arg(p.reply_count), rep_col));eng_hl->addWidget(mk_eng("◉", fmt_n(p.views) + " views", "#1e1e1e"));eng_hl->addStretch();+ // Badgesif (voted_up) {- auto* voted_badge = new QLabel("✓ VOTED");- voted_badge->setStyleSheet(QString("color:#d97706;font-size:9px;font-weight:700;"- "background:transparent;%1")- .arg(M(9)));- eng_hl->addWidget(voted_badge);+ auto* voted = new QLabel("✓ VOTED");+ voted->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;"+ "background:rgba(217,119,6,0.08);padding:2px 6px;"+ "border-radius:8px;%2")+ .arg(ui::colors::AMBER, M(9)));+ eng_hl->addWidget(voted);}- if (p.reply_count > 3) {- auto* hot = new QLabel("● ACTIVE");- hot->setStyleSheet(QString("color:#ef4444;font-size:9px;font-weight:700;"- "background:transparent;letter-spacing:0.5px;%1")- .arg(M(9)));+ if (p.reply_count > 5) {+ auto* hot = new QLabel("● HOT");+ hot->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;"+ "background:rgba(220,38,38,0.08);padding:2px 6px;"+ "border-radius:8px;%2")+ .arg(ui::colors::NEGATIVE, M(9)));eng_hl->addWidget(hot);+ } else if (p.reply_count > 2) {+ auto* active_badge = new QLabel("● ACTIVE");+ active_badge->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;"+ "background:rgba(16,185,129,0.08);padding:2px 6px;"+ "border-radius:8px;%2")+ .arg(ui::colors::POSITIVE, M(9)));+ eng_hl->addWidget(active_badge);}cl->addWidget(eng);- // Click overlay+ // ── Click overlay — lower behind engagement buttons ───────────────────auto* click_btn = new QPushButton(card);click_btn->setGeometry(0, 0, 5000, 400);click_btn->setFlat(true);click_btn->setStyleSheet("QPushButton{background:transparent;border:none;}");- click_btn->raise();+ click_btn->lower(); // lower so upvote button stays clickable on topauto cp = p;connect(click_btn, &QPushButton::clicked, this, [this, cp]() {active_uuid_ = cp.post_uuid;@@ -768,21 +541,133 @@ void ForumFeedPanel::rebuild_posts() {posts_vl_->addWidget(grid);- // Load more+ // ── Load more button ──────────────────────────────────────────────────────if (page_.page < page_.pages) {- auto* more = new QPushButton(QString("↓ LOAD MORE · %1 remaining").arg(page_.total - page_.posts.size()));- more->setFixedHeight(34);+ int remaining = page_.total - page_.posts.size();+ auto* more = new QPushButton(+ QString("Load %1 more posts").arg(remaining));+ more->setFixedHeight(36);more->setCursor(Qt::PointingHandCursor);- more->setStyleSheet(QString("QPushButton{background:#0a0a0a;color:#252525;border:1px solid #0e0e0e;"- "font-size:11px;font-weight:700;letter-spacing:0.5px;margin:0 12px;%1}"- "QPushButton:hover{color:#d97706;border-color:#1a1a1a;}")- .arg(M(11)));+ more->setStyleSheet(+ QString("QPushButton{background:%1;color:%2;"+ "border:1px solid %3;font-size:12px;font-weight:600;"+ "margin:8px 16px;border-radius:4px;%4}"+ "QPushButton:hover{color:%5;border-color:%6;"+ "background:rgba(217,119,6,0.05);}")+ .arg(ui::colors::BG_SURFACE, ui::colors::TEXT_TERTIARY,+ ui::colors::BORDER_DIM, M(12),+ ui::colors::AMBER, ui::colors::BORDER_MED));int np = page_.page + 1;- connect(more, &QPushButton::clicked, this, [this, np]() { emit load_more_requested(np); });+ connect(more, &QPushButton::clicked, this,+ [this, np]() { emit load_more_requested(np); });posts_vl_->addWidget(more);}posts_container_->setUpdatesEnabled(true);}+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+// Skeleton loading+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+void ForumFeedPanel::show_skeleton() {+ if (skeleton_w_) {+ skeleton_w_->deleteLater();+ skeleton_w_ = nullptr;+ }+ skeleton_w_ = new QWidget(posts_container_);+ auto* vl = new QVBoxLayout(skeleton_w_);+ vl->setContentsMargins(16, 10, 16, 10);+ vl->setSpacing(8);++ for (int i = 0; i < 6; ++i) {+ auto* card = new QWidget;+ card->setStyleSheet(+ QString("background:%1;border:1px solid %2;border-radius:4px;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));+ auto* cvl = new QVBoxLayout(card);+ cvl->setContentsMargins(16, 14, 16, 12);+ cvl->setSpacing(10);++ // Avatar + name row+ auto* r1 = new QWidget;+ r1->setStyleSheet("background:transparent;");+ auto* r1h = new QHBoxLayout(r1);+ r1h->setContentsMargins(0, 0, 0, 0);+ r1h->setSpacing(10);+ auto* av_skel = new QWidget;+ av_skel->setFixedSize(28, 28);+ av_skel->setStyleSheet(+ QString("background:%1;border-radius:14px;")+ .arg(ui::colors::BORDER_DIM));+ auto* name_skel = new QWidget;+ name_skel->setFixedSize(100 + i * 15, 10);+ name_skel->setStyleSheet(+ QString("background:%1;border-radius:5px;")+ .arg(ui::colors::BORDER_DIM));+ r1h->addWidget(av_skel);+ r1h->addWidget(name_skel);+ r1h->addStretch();+ cvl->addWidget(r1);++ // Title bar+ auto* title_skel = new QWidget;+ title_skel->setFixedHeight(12);+ title_skel->setMaximumWidth(300 + i * 30);+ title_skel->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:%2 %3,stop:1 %1);border-radius:6px;")+ .arg(ui::colors::BORDER_DIM)+ .arg(0.3 + (i % 4) * 0.15)+ .arg(ui::colors::BORDER_MED));+ cvl->addWidget(title_skel);++ // Body bar+ auto* body_skel = new QWidget;+ body_skel->setFixedHeight(8);+ body_skel->setMaximumWidth(200 + i * 20);+ body_skel->setStyleSheet(+ QString("background:%1;border-radius:4px;")+ .arg(ui::colors::BORDER_DIM));+ cvl->addWidget(body_skel);++ vl->addWidget(card);+ }++ posts_vl_->insertWidget(0, skeleton_w_);+ skeleton_timer_->start();+}++void ForumFeedPanel::pulse_skeleton() {+ if (!skeleton_w_)+ return;+ static int off = 0;+ off = (off + 12) % 100;+ double s = off / 100.0, e = std::min(1.0, s + 0.3);++ QString bg = QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:%2 %3,stop:%4 %1);border-radius:6px;")+ .arg(ui::colors::BORDER_DIM)+ .arg(s, 0, 'f', 2)+ .arg(ui::colors::BORDER_MED)+ .arg(e, 0, 'f', 2);++ auto* vl = qobject_cast<QVBoxLayout*>(skeleton_w_->layout());+ if (!vl)+ return;+ for (int i = 0; i < vl->count(); ++i) {+ auto* ci = vl->itemAt(i);+ if (!ci || !ci->widget())+ continue;+ auto* cvl = qobject_cast<QVBoxLayout*>(ci->widget()->layout());+ if (!cvl)+ continue;+ for (int j = 0; j < cvl->count(); ++j) {+ auto* bi = cvl->itemAt(j);+ if (bi && bi->widget() && bi->widget()->maximumWidth() < 2000 &&+ bi->widget()->height() >= 8 && bi->widget()->height() <= 14)+ bi->widget()->setStyleSheet(bg);+ }+ }+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/forum/ForumFeedPanel.h b/fincept-qt/src/screens/forum/ForumFeedPanel.hindex 2ee1b51d4..acdc0528e 100644--- a/fincept-qt/src/screens/forum/ForumFeedPanel.h+++ b/fincept-qt/src/screens/forum/ForumFeedPanel.h@@ -2,6 +2,7 @@#pragma once#include "services/forum/ForumModels.h"+#include <QHBoxLayout>#include <QLabel>#include <QScrollArea>#include <QTimer>@@ -31,30 +32,28 @@ class ForumFeedPanel : public QWidget {void load_more_requested(int page);void category_clicked(int id, const QString& name, const QString& color);void profile_edit_requested();+ void new_post_clicked();+ void vote_post_requested(const QString& post_uuid, const QString& vote_type);private:void build_ui();+ void build_toolbar();void rebuild_posts();- void rebuild_stats();- void rebuild_profile();- void rebuild_categories();- void rebuild_contributors();+ void rebuild_category_chips();void show_skeleton();void pulse_skeleton();+ // Toolbar+ QWidget* toolbar_ = nullptr;+ QLabel* header_lbl_ = nullptr;+ QLabel* header_count_lbl_ = nullptr;+ QWidget* chips_container_ = nullptr;+ QHBoxLayout* chips_layout_ = nullptr;++ // Scroll + postsQScrollArea* scroll_ = nullptr;QWidget* content_w_ = nullptr;QVBoxLayout* content_vl_ = nullptr;-- // Dashboard sections- QWidget* stats_section_ = nullptr;- QWidget* profile_section_ = nullptr;- QWidget* cats_section_ = nullptr;- QWidget* contrib_section_ = nullptr;-- // Posts section- QLabel* posts_header_lbl_ = nullptr;- QLabel* posts_count_lbl_ = nullptr;QWidget* posts_container_ = nullptr;QVBoxLayout* posts_vl_ = nullptr;@@ -71,8 +70,6 @@ class ForumFeedPanel : public QWidget {QString active_uuid_;QString cat_color_;bool stats_loaded_ = false;- bool profile_loaded_ = false;- bool cats_loaded_ = false;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/forum/ForumPostListPanel.cpp b/fincept-qt/src/screens/forum/ForumPostListPanel.cppindex 31c131e07..7bbd0901c 100644--- a/fincept-qt/src/screens/forum/ForumPostListPanel.cpp+++ b/fincept-qt/src/screens/forum/ForumPostListPanel.cpp@@ -13,7 +13,7 @@namespace fincept::screens {-static QString mono(int sz = 12) {+static QString M(int sz = 12) {return QString("font-family:'Consolas','Courier New',monospace;font-size:%1px;").arg(sz);}@@ -29,27 +29,26 @@ static QString rel_time(const QString& iso) {if (sec < 0)sec = 0;if (sec < 60)- return QString("%1s").arg(sec);+ return QString("%1s ago").arg(sec);if (sec < 3600)- return QString("%1m").arg(sec / 60);+ return QString("%1m ago").arg(sec / 60);if (sec < 86400)- return QString("%1h").arg(sec / 3600);- return QString("%1d").arg(sec / 86400);+ return QString("%1h ago").arg(sec / 3600);+ return QString("%1d ago").arg(sec / 86400);}-// Compact number formatterstatic QString fmt_num(int n) {+ if (n >= 10000)+ return QString("%1K").arg(n / 1000);if (n >= 1000)- return QString("%1k").arg(n / 1000);+ return QString("%1.%2K").arg(n / 1000).arg((n % 1000) / 100);return QString::number(n);}-// Deterministic color from string-static QString str_color(const QString& s) {- static const QString palette[] = {"#d97706", "#06b6d4", "#10b981", "#8b5cf6", "#ef4444",- "#f97316", "#3b82f6", "#84cc16", "#ec4899", "#14b8a6"};- uint h = qHash(s);- return palette[h % 10];+static QString det_color(const QString& s) {+ static const char* pal[] = {"#d97706", "#06b6d4", "#10b981", "#8b5cf6", "#f97316",+ "#3b82f6", "#ec4899", "#14b8a6", "#84cc16", "#ef4444"};+ return pal[qHash(s) % 10];}ForumPostListPanel::ForumPostListPanel(QWidget* parent) : QWidget(parent) {@@ -57,47 +56,57 @@ ForumPostListPanel::ForumPostListPanel(QWidget* parent) : QWidget(parent) {}void ForumPostListPanel::build_ui() {- setStyleSheet("background:#080808;");+ setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* root = new QVBoxLayout(this);root->setContentsMargins(0, 0, 0, 0);root->setSpacing(0);// ── Channel header ────────────────────────────────────────────────────────auto* hdr = new QWidget;- hdr->setFixedHeight(38);- hdr->setStyleSheet("background:#0a0a0a;border-bottom:1px solid #111111;");+ hdr->setFixedHeight(44);+ hdr->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));auto* hdr_hl = new QHBoxLayout(hdr);- hdr_hl->setContentsMargins(12, 0, 12, 0);- hdr_hl->setSpacing(8);+ hdr_hl->setContentsMargins(16, 0, 16, 0);+ hdr_hl->setSpacing(10);auto* hash = new QLabel("#");hash->setStyleSheet(- QString("color:#333333;font-size:18px;font-weight:700;background:transparent;%1").arg(mono(18)));- hash->setFixedWidth(16);+ QString("color:%1;font-size:20px;font-weight:700;background:transparent;%2")+ .arg(ui::colors::AMBER, M(20)));+ hash->setFixedWidth(18);channel_label_ = new QLabel("all-posts");channel_label_->setStyleSheet(- QString("color:#888888;font-size:13px;font-weight:700;background:transparent;%1").arg(mono(13)));+ QString("color:%1;font-size:14px;font-weight:700;background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(14)));count_label_ = new QLabel;- count_label_->setStyleSheet(QString("color:#2a2a2a;font-size:11px;background:transparent;%1").arg(mono(11)));+ count_label_->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));hdr_hl->addWidget(hash);hdr_hl->addWidget(channel_label_, 1);hdr_hl->addWidget(count_label_);root->addWidget(hdr);- // ── Scrollable card feed ───────────────────────────────────────────────────+ // ── Scrollable card feed ──────────────────────────────────────────────────scroll_ = new QScrollArea;scroll_->setWidgetResizable(true);scroll_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);- scroll_->setStyleSheet("QScrollArea{border:none;background:#080808;}"- "QScrollBar:vertical{width:3px;background:transparent;margin:0;}"- "QScrollBar::handle:vertical{background:#1a1a1a;min-height:20px;}"- "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}");+ scroll_->setStyleSheet(+ QString("QScrollArea{border:none;background:%1;}"+ "QScrollBar:vertical{width:6px;background:transparent;margin:0;}"+ "QScrollBar::handle:vertical{background:%2;min-height:40px;"+ "border-radius:3px;}"+ "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical"+ "{height:0;}")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));feed_container_ = new QWidget;- feed_container_->setStyleSheet("background:#080808;");+ feed_container_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));feed_layout_ = new QVBoxLayout(feed_container_);feed_layout_->setContentsMargins(0, 0, 0, 0);feed_layout_->setSpacing(0);@@ -106,10 +115,10 @@ void ForumPostListPanel::build_ui() {scroll_->setWidget(feed_container_);root->addWidget(scroll_, 1);- // Skeleton timerskeleton_timer_ = new QTimer(this);skeleton_timer_->setInterval(400);- connect(skeleton_timer_, &QTimer::timeout, this, &ForumPostListPanel::pulse_skeleton);+ connect(skeleton_timer_, &QTimer::timeout, this,+ &ForumPostListPanel::pulse_skeleton);}void ForumPostListPanel::set_header(const QString& title, const QString& color) {@@ -137,29 +146,34 @@ void ForumPostListPanel::show_skeleton() {skeleton_widget_ = new QWidget(feed_container_);auto* sk_vl = new QVBoxLayout(skeleton_widget_);- sk_vl->setContentsMargins(0, 0, 0, 0);- sk_vl->setSpacing(1);+ sk_vl->setContentsMargins(12, 8, 12, 8);+ sk_vl->setSpacing(6);for (int i = 0; i < 8; ++i) {auto* card = new QWidget;- card->setFixedHeight(72);- card->setStyleSheet("background:#0a0a0a;border-bottom:1px solid #0d0d0d;");+ card->setFixedHeight(68);+ card->setStyleSheet(+ QString("background:%1;border:1px solid %2;border-radius:4px;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));auto* cvl = new QVBoxLayout(card);- cvl->setContentsMargins(12, 10, 12, 10);- cvl->setSpacing(6);+ cvl->setContentsMargins(14, 10, 14, 10);+ cvl->setSpacing(8);- // Title shimmer barauto* bar1 = new QWidget;bar1->setFixedHeight(10);- bar1->setStyleSheet(QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"- "stop:0 #111111,stop:%1 #1a1a1a,stop:1 #111111);")- .arg(0.3 + (i % 4) * 0.15));+ bar1->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:%2 %3,stop:1 %1);border-radius:5px;")+ .arg(ui::colors::BORDER_DIM)+ .arg(0.3 + (i % 4) * 0.15)+ .arg(ui::colors::BORDER_MED));bar1->setMaximumWidth(200 + i * 20);- // Meta shimmer barauto* bar2 = new QWidget;- bar2->setFixedHeight(8);- bar2->setStyleSheet("background:#0d0d0d;");+ bar2->setFixedHeight(7);+ bar2->setStyleSheet(+ QString("background:%1;border-radius:3px;")+ .arg(ui::colors::BORDER_DIM));bar2->setMaximumWidth(120);cvl->addWidget(bar1);@@ -181,8 +195,10 @@ void ForumPostListPanel::pulse_skeleton() {double s = off / 100.0;double e = std::min(1.0, s + 0.3);QString bg = QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"- "stop:0 #090909,stop:%1 #1c1c1c,stop:%2 #090909);")+ "stop:0 %1,stop:%2 %3,stop:%4 %1);border-radius:5px;")+ .arg(ui::colors::BORDER_DIM).arg(s, 0, 'f', 2)+ .arg(ui::colors::BORDER_MED).arg(e, 0, 'f', 2);auto* lay = qobject_cast<QVBoxLayout*>(skeleton_widget_->layout());@@ -198,7 +214,8 @@ void ForumPostListPanel::pulse_skeleton() {continue;for (int j = 0; j < cvl->count(); ++j) {auto* ci = cvl->itemAt(j);- if (ci && ci->widget() && ci->widget()->height() >= 8 && ci->widget()->height() <= 12)+ if (ci && ci->widget() && ci->widget()->height() >= 7 &&+ ci->widget()->height() <= 12)ci->widget()->setStyleSheet(bg);}}@@ -220,7 +237,8 @@ void ForumPostListPanel::set_active_post(const QString& uuid) {active_uuid_ = uuid;}-void ForumPostListPanel::set_posts(const services::ForumPostsPage& page, const QString& category_color) {+void ForumPostListPanel::set_posts(const services::ForumPostsPage& page,+ const QString& category_color) {current_page_ = page;category_color_ = category_color;skeleton_timer_->stop();@@ -233,25 +251,39 @@ void ForumPostListPanel::set_posts(const services::ForumPostsPage& page, const Qvoid ForumPostListPanel::rebuild_feed() {clear();- count_label_->setText(QString("%1 posts").arg(current_page_.total));+ count_label_->setText(+ current_page_.total > 0 ? QString("%1 posts").arg(current_page_.total) : "");if (current_page_.posts.isEmpty()) {auto* empty = new QWidget;- empty->setFixedHeight(80);+ empty->setMinimumHeight(120);empty->setStyleSheet("background:transparent;");auto* el = new QVBoxLayout(empty);+ el->setAlignment(Qt::AlignCenter);+ el->setSpacing(6);++ auto* icon = new QLabel("◇");+ icon->setAlignment(Qt::AlignCenter);+ icon->setStyleSheet(+ QString("color:%1;font-size:24px;background:transparent;")+ .arg(ui::colors::BORDER_DIM));+auto* lbl = new QLabel("NO POSTS YET");lbl->setAlignment(Qt::AlignCenter);- lbl->setStyleSheet(QString("color:#222222;font-size:13px;font-weight:700;letter-spacing:1px;"- "background:transparent;%1")- .arg(mono(13)));+ lbl->setStyleSheet(+ QString("color:%1;font-size:13px;font-weight:700;letter-spacing:1.5px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(13)));+auto* sub = new QLabel("Be the first to start a discussion");sub->setAlignment(Qt::AlignCenter);- sub->setStyleSheet(QString("color:#1a1a1a;font-size:11px;background:transparent;%1").arg(mono(11)));- el->addStretch();+ sub->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(11)));++ el->addWidget(icon);el->addWidget(lbl);el->addWidget(sub);- el->addStretch();feed_layout_->addWidget(empty);feed_layout_->addStretch();return;@@ -262,21 +294,25 @@ void ForumPostListPanel::rebuild_feed() {for (int i = 0; i < current_page_.posts.size(); ++i) {const auto& post = current_page_.posts[i];const bool active = (post.post_uuid == active_uuid_);+ QString cat_color = post.category_color.isEmpty()+ ? det_color(post.category_name)+ : post.category_color;- // ── Post card ─────────────────────────────────────────────────────────auto* card = new QWidget;card->setCursor(Qt::PointingHandCursor);-- QString cat_color = post.category_color.isEmpty() ? str_color(post.category_name) : post.category_color;-- card->setStyleSheet(active ? QString("background:#0d0d0d;border-bottom:1px solid #111111;"- "border-left:3px solid %1;")- .arg(cat_color)- : "background:#080808;border-bottom:1px solid #0d0d0d;"- "border-left:3px solid transparent;");+ card->setStyleSheet(+ active+ ? QString("background:rgba(217,119,6,0.04);"+ "border-bottom:1px solid %1;"+ "border-left:3px solid %2;")+ .arg(ui::colors::BORDER_DIM, cat_color)+ : QString("background:%1;"+ "border-bottom:1px solid %2;"+ "border-left:3px solid transparent;")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));auto* card_vl = new QVBoxLayout(card);- card_vl->setContentsMargins(12, 8, 12, 6);+ card_vl->setContentsMargins(14, 10, 14, 8);card_vl->setSpacing(4);// ── Top row: avatar + name + category chip + time ─────────────────────@@ -284,32 +320,37 @@ void ForumPostListPanel::rebuild_feed() {top_row->setStyleSheet("background:transparent;");auto* top_hl = new QHBoxLayout(top_row);top_hl->setContentsMargins(0, 0, 0, 0);- top_hl->setSpacing(6);+ top_hl->setSpacing(8);- // Avatar square with initials- auto* avatar = new QLabel;- avatar->setFixedSize(22, 22);+ auto* avatar = new QLabel(+ post.author_display_name.isEmpty()+ ? "?"+ : post.author_display_name.left(2).toUpper());+ avatar->setFixedSize(24, 24);avatar->setAlignment(Qt::AlignCenter);- QString av_color = str_color(post.author_display_name);- QString initials = post.author_display_name.isEmpty() ? "?" : post.author_display_name.left(2).toUpper();- avatar->setText(initials);avatar->setStyleSheet(- QString("color:#080808;font-size:9px;font-weight:700;background:%1;%2").arg(av_color, mono(9)));+ QString("color:%1;font-size:9px;font-weight:700;background:%2;"+ "border-radius:12px;%3")+ .arg(ui::colors::BG_BASE, det_color(post.author_display_name),+ M(9)));- // Author nameauto* author = new QLabel(post.author_display_name.left(16));author->setStyleSheet(- QString("color:#888888;font-size:11px;font-weight:600;background:transparent;%1").arg(mono(11)));+ QString("color:%1;font-size:11px;font-weight:600;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(11)));- // Category chipauto* cat_chip = new QLabel(post.category_name.toUpper().left(12));- cat_chip->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;background:rgba(0,0,0,0);"- "border:1px solid %1;padding:0 4px;letter-spacing:0.5px;%2")- .arg(cat_color, mono(9)));+ cat_chip->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;background:transparent;"+ "border:1px solid %1;padding:1px 6px;letter-spacing:0.5px;"+ "border-radius:8px;%2")+ .arg(cat_color, M(9)));- // Timeauto* time_lbl = new QLabel(rel_time(post.created_at));- time_lbl->setStyleSheet(QString("color:#2a2a2a;font-size:10px;background:transparent;%1").arg(mono(10)));+ time_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(10)));top_hl->addWidget(avatar);top_hl->addWidget(author);@@ -324,52 +365,51 @@ void ForumPostListPanel::rebuild_feed() {title_lbl->setWordWrap(false);title_lbl->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);title_lbl->setStyleSheet(- active ? QString("color:#e5e5e5;font-size:13px;font-weight:700;background:transparent;%1").arg(mono(13))- : QString("color:#cccccc;font-size:13px;background:transparent;%1").arg(mono(13)));+ active+ ? QString("color:%1;font-size:13px;font-weight:700;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(13))+ : QString("color:#c0c0c0;font-size:13px;font-weight:600;"+ "background:transparent;%1")+ .arg(M(13)));card_vl->addWidget(title_lbl);- // ── Engagement bar ────────────────────────────────────────────────────+ // ── Engagement ────────────────────────────────────────────────────────auto* eng_row = new QWidget;eng_row->setStyleSheet("background:transparent;");auto* eng_hl = new QHBoxLayout(eng_row);- eng_hl->setContentsMargins(0, 0, 0, 0);- eng_hl->setSpacing(12);-- auto make_eng = [&](const QString& icon, const QString& val, const QString& color) {- auto* w = new QWidget;- w->setStyleSheet("background:transparent;");- auto* hl = new QHBoxLayout(w);- hl->setContentsMargins(0, 0, 0, 0);- hl->setSpacing(3);- auto* ic = new QLabel(icon);- ic->setStyleSheet(QString("color:%1;font-size:10px;background:transparent;%2").arg(color, mono(10)));- auto* vl = new QLabel(val);- vl->setStyleSheet(QString("color:#444444;font-size:10px;background:transparent;%1").arg(mono(10)));- hl->addWidget(ic);- hl->addWidget(vl);- return w;+ eng_hl->setContentsMargins(0, 2, 0, 0);+ eng_hl->setSpacing(14);++ auto mk_eng = [&](const QString& icon, const QString& val,+ const QString& color) {+ auto* lbl = new QLabel(icon + " " + val);+ lbl->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(color, M(10)));+ return lbl;};- QString like_color = post.likes > 0 ? "#d97706" : "#2a2a2a";- QString rep_color = post.reply_count > 0 ? "#06b6d4" : "#2a2a2a";+ QString like_color = post.likes > 0 ? ui::colors::AMBER : "#1e1e1e";+ QString rep_color = post.reply_count > 0 ? ui::colors::CYAN : "#1e1e1e";- eng_hl->addWidget(make_eng("▲", fmt_num(post.likes), like_color));- eng_hl->addWidget(make_eng("◆", fmt_num(post.reply_count), rep_color));- eng_hl->addWidget(make_eng("◉", fmt_num(post.views), "#2a2a2a"));+ eng_hl->addWidget(mk_eng("▲", fmt_num(post.likes), like_color));+ eng_hl->addWidget(mk_eng("◆", fmt_num(post.reply_count), rep_color));+ eng_hl->addWidget(mk_eng("◉", fmt_num(post.views), "#1e1e1e"));eng_hl->addStretch();- // Hot indicator if replies > 5if (post.reply_count > 5) {- auto* hot = new QLabel("HOT");- hot->setStyleSheet(QString("color:#ef4444;font-size:9px;font-weight:700;letter-spacing:0.8px;"- "background:transparent;%1")- .arg(mono(9)));+ auto* hot = new QLabel("● HOT");+ hot->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;"+ "background:rgba(220,38,38,0.08);padding:1px 6px;"+ "border-radius:6px;%2")+ .arg(ui::colors::NEGATIVE, M(9)));eng_hl->addWidget(hot);}-card_vl->addWidget(eng_row);- // ── Click handler ────────────────────────────────────────────────────+ // ── Click handler ─────────────────────────────────────────────────────auto* click_btn = new QPushButton(card);click_btn->setGeometry(0, 0, 3000, 200);click_btn->setFlat(true);@@ -389,16 +429,20 @@ void ForumPostListPanel::rebuild_feed() {// ── Load more ─────────────────────────────────────────────────────────────if (current_page_.page < current_page_.pages) {int remaining = current_page_.total - current_page_.posts.size();- auto* more_btn = new QPushButton(QString("↓ LOAD %1 MORE POSTS").arg(remaining));- more_btn->setFixedHeight(32);+ auto* more_btn = new QPushButton(+ QString("Load %1 more posts").arg(remaining));+ more_btn->setFixedHeight(34);more_btn->setCursor(Qt::PointingHandCursor);- more_btn->setStyleSheet(QString("QPushButton{background:#0a0a0a;color:#333333;border:none;"- "border-top:1px solid #111111;font-size:11px;font-weight:700;"- "letter-spacing:0.5px;%1}"- "QPushButton:hover{background:#0d0d0d;color:%2;}")- .arg(mono(11), ui::colors::AMBER));+ more_btn->setStyleSheet(+ QString("QPushButton{background:%1;color:%2;border:none;"+ "border-top:1px solid %3;font-size:12px;font-weight:600;%4}"+ "QPushButton:hover{color:%5;"+ "background:rgba(217,119,6,0.04);}")+ .arg(ui::colors::BG_SURFACE, ui::colors::TEXT_TERTIARY,+ ui::colors::BORDER_DIM, M(12), ui::colors::AMBER));int next = current_page_.page + 1;- connect(more_btn, &QPushButton::clicked, this, [this, next]() { emit load_more_requested(next); });+ connect(more_btn, &QPushButton::clicked, this,+ [this, next]() { emit load_more_requested(next); });feed_layout_->addWidget(more_btn);}diff --git a/fincept-qt/src/screens/forum/ForumPostReaderPanel.cpp b/fincept-qt/src/screens/forum/ForumPostReaderPanel.cppindex 8d3f2cd3e..32eb77b53 100644--- a/fincept-qt/src/screens/forum/ForumPostReaderPanel.cpp+++ b/fincept-qt/src/screens/forum/ForumPostReaderPanel.cpp@@ -12,7 +12,7 @@namespace fincept::screens {-static QString mono(int sz = 12) {+static QString M(int sz = 12) {return QString("font-family:'Consolas','Courier New',monospace;font-size:%1px;").arg(sz);}@@ -36,11 +36,10 @@ static QString rel_time(const QString& iso) {return QString("%1d ago").arg(sec / 86400);}-static QString str_color(const QString& s) {- static const QString palette[] = {"#d97706", "#06b6d4", "#10b981", "#8b5cf6", "#ef4444",- "#f97316", "#3b82f6", "#84cc16", "#ec4899", "#14b8a6"};- uint h = qHash(s);- return palette[h % 10];+static QString det_color(const QString& s) {+ static const char* pal[] = {"#d97706", "#06b6d4", "#10b981", "#8b5cf6", "#f97316",+ "#3b82f6", "#ec4899", "#14b8a6", "#84cc16", "#ef4444"};+ return pal[qHash(s) % 10];}ForumPostReaderPanel::ForumPostReaderPanel(QWidget* parent) : QWidget(parent) {@@ -48,7 +47,7 @@ ForumPostReaderPanel::ForumPostReaderPanel(QWidget* parent) : QWidget(parent) {}void ForumPostReaderPanel::build_ui() {- setStyleSheet("background:#080808;");+ setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* root = new QVBoxLayout(this);root->setContentsMargins(0, 0, 0, 0);root->setSpacing(0);@@ -57,41 +56,60 @@ void ForumPostReaderPanel::build_ui() {// ── Page 0: empty placeholder ─────────────────────────────────────────────auto* empty_page = new QWidget;- empty_page->setStyleSheet("background:#080808;");+ empty_page->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));{auto* vl = new QVBoxLayout(empty_page);+ vl->setAlignment(Qt::AlignCenter);+ vl->setSpacing(10);+auto* icon = new QLabel("◈");icon->setAlignment(Qt::AlignCenter);- icon->setStyleSheet(QString("color:#111111;font-size:36px;background:transparent;"));+ icon->setStyleSheet(+ QString("color:%1;font-size:40px;background:transparent;")+ .arg(ui::colors::BORDER_DIM));+auto* lbl = new QLabel("SELECT A POST");lbl->setAlignment(Qt::AlignCenter);- lbl->setStyleSheet(QString("color:#1a1a1a;font-size:13px;font-weight:700;letter-spacing:1.5px;"- "background:transparent;%1")- .arg(mono(13)));- auto* sub = new QLabel("Click any post from the feed");+ lbl->setStyleSheet(+ QString("color:%1;font-size:14px;font-weight:700;letter-spacing:2px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(14)));++ auto* sub = new QLabel("Click any post from the feed to read it");sub->setAlignment(Qt::AlignCenter);- sub->setStyleSheet(QString("color:#151515;font-size:11px;background:transparent;%1").arg(mono(11)));- vl->addStretch();+ sub->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(11)));+vl->addWidget(icon);- vl->addSpacing(8);+ vl->addSpacing(4);vl->addWidget(lbl);vl->addWidget(sub);- vl->addStretch();}stack_->addWidget(empty_page); // 0// ── Page 1: loading ───────────────────────────────────────────────────────auto* load_page = new QWidget;- load_page->setStyleSheet("background:#080808;");+ load_page->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));{auto* vl = new QVBoxLayout(load_page);+ vl->setAlignment(Qt::AlignCenter);+ vl->setSpacing(10);+spin_label_ = new QLabel("⣾");spin_label_->setAlignment(Qt::AlignCenter);spin_label_->setStyleSheet(- QString("color:%1;font-size:20px;background:transparent;%2").arg(ui::colors::AMBER, mono(20)));- vl->addStretch();+ QString("color:%1;font-size:24px;background:transparent;%2")+ .arg(ui::colors::AMBER, M(24)));++ auto* lt = new QLabel("Loading...");+ lt->setAlignment(Qt::AlignCenter);+ lt->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));+vl->addWidget(spin_label_);- vl->addStretch();+ vl->addWidget(lt);}stack_->addWidget(load_page); // 1@@ -104,17 +122,21 @@ void ForumPostReaderPanel::build_ui() {// ── Page 2: content ───────────────────────────────────────────────────────content_page_ = new QWidget;- content_page_->setStyleSheet("background:#080808;");+ content_page_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* content_root = new QVBoxLayout(content_page_);content_root->setContentsMargins(0, 0, 0, 0);content_root->setSpacing(0);- // ── Post header zone ──────────────────────────────────────────────────────+ // ── Post header with gradient background ──────────────────────────────────auto* post_hdr = new QWidget;- post_hdr->setStyleSheet("background:#0a0a0a;border-bottom:1px solid #111111;");+ post_hdr->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:0,y2:1,"+ "stop:0 #0e0e0e,stop:1 %1);"+ "border-bottom:1px solid %2;")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));auto* hdr_vl = new QVBoxLayout(post_hdr);- hdr_vl->setContentsMargins(16, 12, 16, 10);- hdr_vl->setSpacing(6);+ hdr_vl->setContentsMargins(20, 16, 20, 14);+ hdr_vl->setSpacing(8);// Category chip + time rowauto* chip_row = new QWidget;@@ -124,13 +146,17 @@ void ForumPostReaderPanel::build_ui() {chip_hl->setSpacing(8);category_chip_ = new QLabel;- category_chip_->setStyleSheet(QString("color:#d97706;font-size:9px;font-weight:700;letter-spacing:0.8px;"- "background:rgba(217,119,6,0.08);border:1px solid rgba(217,119,6,0.3);"- "padding:1px 6px;%1")- .arg(mono(9)));+ category_chip_->setFixedHeight(18);+ category_chip_->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;letter-spacing:0.8px;"+ "background:transparent;border:1px solid %1;"+ "padding:1px 8px;border-radius:9px;%2")+ .arg(ui::colors::AMBER, M(9)));meta_label_ = new QLabel;- meta_label_->setStyleSheet(QString("color:#2a2a2a;font-size:10px;background:transparent;%1").arg(mono(10)));+ meta_label_->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(10)));chip_hl->addWidget(category_chip_);chip_hl->addStretch();@@ -140,9 +166,10 @@ void ForumPostReaderPanel::build_ui() {// Titletitle_label_ = new QLabel;title_label_->setWordWrap(true);- title_label_->setStyleSheet(QString("color:#e5e5e5;font-size:15px;font-weight:700;line-height:1.4;"- "background:transparent;%1")- .arg(mono(15)));+ title_label_->setStyleSheet(+ QString("color:%1;font-size:16px;font-weight:700;line-height:1.4;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(16)));hdr_vl->addWidget(title_label_);// Author row@@ -150,25 +177,41 @@ void ForumPostReaderPanel::build_ui() {author_label_->setTextFormat(Qt::RichText);author_label_->setTextInteractionFlags(Qt::TextBrowserInteraction);author_label_->setOpenExternalLinks(false);- author_label_->setStyleSheet(QString("color:#555555;font-size:11px;background:transparent;%1").arg(mono(11)));- connect(author_label_, &QLabel::linkActivated, this, [this](const QString& link) {- if (link.startsWith("author:"))- emit author_clicked(link.mid(7));- });+ author_label_->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));+ connect(author_label_, &QLabel::linkActivated, this,+ [this](const QString& link) {+ if (link.startsWith("author:"))+ emit author_clicked(link.mid(7));+ });hdr_vl->addWidget(author_label_);++ // Gradient separator+ auto* hdr_sep = new QWidget;+ hdr_sep->setFixedHeight(2);+ hdr_sep->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:0.3 %2,stop:1 transparent);")+ .arg(ui::colors::AMBER, ui::colors::BORDER_DIM));+ hdr_vl->addWidget(hdr_sep);content_root->addWidget(post_hdr);// ── Scrollable area ───────────────────────────────────────────────────────auto* scroll = new QScrollArea;scroll->setWidgetResizable(true);scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);- scroll->setStyleSheet("QScrollArea{border:none;background:#080808;}"- "QScrollBar:vertical{width:3px;background:transparent;margin:0;}"- "QScrollBar::handle:vertical{background:#1a1a1a;min-height:20px;}"- "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}");+ scroll->setStyleSheet(+ QString("QScrollArea{border:none;background:%1;}"+ "QScrollBar:vertical{width:6px;background:transparent;margin:0;}"+ "QScrollBar::handle:vertical{background:%2;min-height:30px;"+ "border-radius:3px;}"+ "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical"+ "{height:0;}")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));auto* scroll_w = new QWidget;- scroll_w->setStyleSheet("background:#080808;");+ scroll_w->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* scroll_vl = new QVBoxLayout(scroll_w);scroll_vl->setContentsMargins(0, 0, 0, 0);scroll_vl->setSpacing(0);@@ -178,42 +221,52 @@ void ForumPostReaderPanel::build_ui() {body_label_->setWordWrap(true);body_label_->setTextFormat(Qt::PlainText);body_label_->setAlignment(Qt::AlignTop | Qt::AlignLeft);- body_label_->setStyleSheet(QString("color:#888888;font-size:13px;line-height:1.7;background:transparent;"- "padding:16px;border-bottom:1px solid #0d0d0d;%1")- .arg(mono(13)));+ body_label_->setStyleSheet(+ QString("color:%1;font-size:13px;line-height:1.7;background:transparent;"+ "padding:16px 20px;border-bottom:1px solid %2;%3")+ .arg(ui::colors::TEXT_SECONDARY, ui::colors::BORDER_DIM, M(13)));scroll_vl->addWidget(body_label_);// ── Engagement bar ────────────────────────────────────────────────────────auto* eng_bar = new QWidget;- eng_bar->setFixedHeight(36);- eng_bar->setStyleSheet("background:#0a0a0a;border-bottom:1px solid #111111;");+ eng_bar->setFixedHeight(40);+ eng_bar->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));auto* eng_hl = new QHBoxLayout(eng_bar);- eng_hl->setContentsMargins(16, 0, 16, 0);- eng_hl->setSpacing(16);+ eng_hl->setContentsMargins(20, 0, 20, 0);+ eng_hl->setSpacing(14);- // Upvote button- auto* up_btn = new QPushButton("▲ UPVOTE");- up_btn->setFixedHeight(24);- up_btn->setFixedWidth(90);+ auto* up_btn = new QPushButton("▲ Upvote");+ up_btn->setFixedHeight(26);up_btn->setCursor(Qt::PointingHandCursor);- up_btn->setStyleSheet(QString("QPushButton{background:transparent;color:#333333;border:1px solid #1a1a1a;"- "font-size:10px;font-weight:700;padding:0 8px;%1}"- "QPushButton:hover{background:rgba(217,119,6,0.1);color:#d97706;"- "border-color:rgba(217,119,6,0.4);}")- .arg(mono(10)));+ up_btn->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.06);"+ "color:%1;border:1px solid rgba(217,119,6,0.2);"+ "font-size:10px;font-weight:700;padding:0 12px;"+ "border-radius:13px;%2}"+ "QPushButton:hover{background:rgba(217,119,6,0.12);"+ "color:%3;border-color:rgba(217,119,6,0.5);}")+ .arg(ui::colors::TEXT_SECONDARY, M(10), ui::colors::AMBER));connect(up_btn, &QPushButton::clicked, this, [this]() {if (!current_detail_.post.post_uuid.isEmpty())emit vote_post(current_detail_.post.post_uuid, "up");});likes_label_ = new QLabel("▲ 0");- likes_label_->setStyleSheet(QString("color:#444444;font-size:11px;background:transparent;%1").arg(mono(11)));+ likes_label_->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));replies_label_ = new QLabel("◆ 0 replies");- replies_label_->setStyleSheet(QString("color:#333333;font-size:11px;background:transparent;%1").arg(mono(11)));+ replies_label_->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));views_label_ = new QLabel("◉ 0 views");- views_label_->setStyleSheet(QString("color:#222222;font-size:11px;background:transparent;%1").arg(mono(11)));+ views_label_->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(11)));eng_hl->addWidget(up_btn);eng_hl->addWidget(likes_label_);@@ -224,20 +277,31 @@ void ForumPostReaderPanel::build_ui() {// ── Comments header ───────────────────────────────────────────────────────auto* com_hdr = new QWidget;- com_hdr->setFixedHeight(26);- com_hdr->setStyleSheet("background:#090909;border-bottom:1px solid #111111;");+ com_hdr->setFixedHeight(28);+ com_hdr->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));auto* com_hdr_hl = new QHBoxLayout(com_hdr);- com_hdr_hl->setContentsMargins(16, 0, 16, 0);+ com_hdr_hl->setContentsMargins(20, 0, 20, 0);+ com_hdr_hl->setSpacing(6);+ auto* com_dot = new QLabel("◆");+ com_dot->setStyleSheet(+ QString("color:%1;font-size:7px;background:transparent;")+ .arg(ui::colors::CYAN));auto* com_hdr_lbl = new QLabel("REPLIES");- com_hdr_lbl->setStyleSheet(QString("color:#222222;font-size:10px;font-weight:700;letter-spacing:1px;"- "background:transparent;%1")- .arg(mono(10)));+ com_hdr_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;letter-spacing:1.5px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(10)));+ com_hdr_hl->addWidget(com_dot);com_hdr_hl->addWidget(com_hdr_lbl);+ com_hdr_hl->addStretch();scroll_vl->addWidget(com_hdr);// Comments areacomments_area_ = new QWidget;- comments_area_->setStyleSheet("background:#080808;");+ comments_area_->setStyleSheet(+ QString("background:%1;").arg(ui::colors::BG_BASE));comments_layout_ = new QVBoxLayout(comments_area_);comments_layout_->setContentsMargins(0, 0, 0, 0);comments_layout_->setSpacing(0);@@ -249,45 +313,48 @@ void ForumPostReaderPanel::build_ui() {// ── Reply compose bar ─────────────────────────────────────────────────────auto* compose = new QWidget;- compose->setFixedHeight(42);- compose->setStyleSheet("background:#0a0a0a;border-top:1px solid #111111;");+ compose->setFixedHeight(48);+ compose->setStyleSheet(+ QString("background:%1;border-top:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));auto* compose_hl = new QHBoxLayout(compose);- compose_hl->setContentsMargins(12, 6, 12, 6);+ compose_hl->setContentsMargins(16, 8, 16, 8);compose_hl->setSpacing(8);- auto* compose_icon = new QLabel("◉");- compose_icon->setStyleSheet("color:#222222;font-size:14px;background:transparent;");- compose_icon->setFixedWidth(18);-reply_input_ = new QLineEdit;- reply_input_->setPlaceholderText("write a reply...");- reply_input_->setStyleSheet(QString("QLineEdit{background:#0d0d0d;color:#888888;border:1px solid #1a1a1a;"- "padding:4px 10px;font-size:12px;%1}"- "QLineEdit:focus{border-color:#333333;color:#e5e5e5;}"- "QLineEdit::placeholder{color:#2a2a2a;}")- .arg(mono(12)));-- auto* send_btn = new QPushButton("SEND ↵");- send_btn->setFixedSize(72, 28);+ reply_input_->setPlaceholderText("Write a reply...");+ reply_input_->setFixedHeight(32);+ reply_input_->setStyleSheet(+ QString("QLineEdit{background:rgba(255,255,255,0.03);color:%1;"+ "border:1px solid %2;padding:4px 12px;font-size:12px;"+ "border-radius:4px;%3}"+ "QLineEdit:focus{border-color:%4;color:%5;}"+ "QLineEdit::placeholder{color:%6;}")+ .arg(ui::colors::TEXT_SECONDARY, ui::colors::BORDER_DIM,+ M(12), ui::colors::BORDER_BRIGHT,+ ui::colors::TEXT_PRIMARY, ui::colors::TEXT_DIM));++ auto* send_btn = new QPushButton("Reply");+ send_btn->setFixedSize(72, 32);send_btn->setCursor(Qt::PointingHandCursor);- send_btn->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.12);color:#555555;"- "border:1px solid #1a1a1a;font-size:10px;font-weight:700;%1}"- "QPushButton:hover{background:rgba(217,119,6,0.25);color:#d97706;"- "border-color:rgba(217,119,6,0.4);}")- .arg(mono(10)));-- auto submit = [this, send_btn]() {+ send_btn->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.1);color:%1;"+ "border:1px solid rgba(217,119,6,0.25);font-size:11px;"+ "font-weight:700;border-radius:4px;%2}"+ "QPushButton:hover{background:rgba(217,119,6,0.2);"+ "color:%3;border-color:rgba(217,119,6,0.5);}")+ .arg(ui::colors::TEXT_SECONDARY, M(11), ui::colors::AMBER));++ auto submit = [this]() {QString text = reply_input_->text().trimmed();if (text.isEmpty() || current_detail_.post.post_uuid.isEmpty())return;emit comment_submitted(current_detail_.post.post_uuid, text);reply_input_->clear();- Q_UNUSED(send_btn)};connect(send_btn, &QPushButton::clicked, this, submit);connect(reply_input_, &QLineEdit::returnPressed, this, submit);- compose_hl->addWidget(compose_icon);compose_hl->addWidget(reply_input_, 1);compose_hl->addWidget(send_btn);content_root->addWidget(compose);@@ -317,45 +384,53 @@ void ForumPostReaderPanel::show_post(const services::ForumPostDetail& detail) {spin_timer_->stop();current_detail_ = detail;- // Category chip- QString cat_color =- detail.post.category_color.isEmpty() ? str_color(detail.post.category_name) : detail.post.category_color;+ QString cat_color = detail.post.category_color.isEmpty()+ ? det_color(detail.post.category_name)+ : detail.post.category_color;+category_chip_->setText(detail.post.category_name.toUpper());- category_chip_->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;letter-spacing:0.8px;"- "background:transparent;border:1px solid %1;"- "padding:1px 6px;%2")- .arg(cat_color, mono(9)));+ category_chip_->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;letter-spacing:0.8px;"+ "background:transparent;border:1px solid %1;"+ "padding:1px 8px;border-radius:9px;%2")+ .arg(cat_color, M(9)));- // Timemeta_label_->setText(rel_time(detail.post.created_at));-- // Titletitle_label_->setText(detail.post.title);// Author- QString av_color = str_color(detail.post.author_display_name);- QString initials =- detail.post.author_display_name.isEmpty() ? "?" : detail.post.author_display_name.left(2).toUpper();- QString author_link =- QString("<span style='background:%1;color:#080808;font-size:9px;"- "font-family:Consolas;padding:1px 4px;'>%2</span>"+ QString av_color = det_color(detail.post.author_display_name);+ QString initials = detail.post.author_display_name.isEmpty()+ ? "?"+ : detail.post.author_display_name.left(2).toUpper();+ author_label_->setText(+ QString("<span style='background:%1;color:%2;font-size:9px;"+ "font-family:Consolas;padding:2px 5px;font-weight:700;"+ "border-radius:10px;'>%3</span>"" "- "<a href='author:%3' style='color:%4;text-decoration:none;"- "font-family:Consolas;font-size:11px;'>%5</a>")- .arg(av_color, initials, detail.post.author_name, "#555555", detail.post.author_display_name.toUpper());- author_label_->setText(author_link);+ "<a href='author:%4' style='color:%5;text-decoration:none;"+ "font-family:Consolas;font-size:11px;font-weight:600;'>%6</a>")+ .arg(av_color, ui::colors::BG_BASE, initials,+ detail.post.author_name, ui::colors::TEXT_SECONDARY,+ detail.post.author_display_name));- // Bodybody_label_->setText(detail.post.content);// Engagement- likes_label_->setText(detail.post.likes > 0- ? QString("<span style='color:#d97706;'>▲ %1</span>").arg(detail.post.likes)- : QString("▲ 0"));- likes_label_->setTextFormat(Qt::RichText);+ bool voted = (detail.post.user_vote == "up");+ QString lc = voted || detail.post.likes > 0+ ? ui::colors::AMBER+ : ui::colors::TEXT_DIM;+ likes_label_->setText(QString("▲ %1").arg(detail.post.likes));+ likes_label_->setStyleSheet(+ QString("color:%1;font-size:11px;font-weight:600;"+ "background:transparent;%2")+ .arg(lc, M(11)));replies_label_->setText(- QString("◆ %1 %2").arg(detail.total_comments).arg(detail.total_comments == 1 ? "reply" : "replies"));+ QString("◆ %1 %2")+ .arg(detail.total_comments)+ .arg(detail.total_comments == 1 ? "reply" : "replies"));views_label_->setText(QString("◉ %1 views").arg(detail.post.views));@@ -373,113 +448,136 @@ void ForumPostReaderPanel::rebuild_comments() {if (current_detail_.comments.isEmpty()) {auto* no_com = new QWidget;- no_com->setFixedHeight(52);+ no_com->setMinimumHeight(60);no_com->setStyleSheet("background:transparent;");auto* vl = new QVBoxLayout(no_com);+ vl->setAlignment(Qt::AlignCenter);+ vl->setSpacing(4);++ auto* icon = new QLabel("◇");+ icon->setAlignment(Qt::AlignCenter);+ icon->setStyleSheet(+ QString("color:%1;font-size:18px;background:transparent;")+ .arg(ui::colors::BORDER_DIM));+auto* lbl = new QLabel("NO REPLIES YET");lbl->setAlignment(Qt::AlignCenter);- lbl->setStyleSheet(QString("color:#1a1a1a;font-size:11px;font-weight:700;letter-spacing:1px;"- "background:transparent;%1")- .arg(mono(11)));- auto* sub = new QLabel("Be the first to reply");- sub->setAlignment(Qt::AlignCenter);- sub->setStyleSheet(QString("color:#141414;font-size:10px;background:transparent;%1").arg(mono(10)));+ lbl->setStyleSheet(+ QString("color:%1;font-size:11px;font-weight:700;letter-spacing:1px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));++ vl->addWidget(icon);vl->addWidget(lbl);- vl->addWidget(sub);comments_layout_->addWidget(no_com);return;}for (int i = 0; i < current_detail_.comments.size(); ++i) {const auto& c = current_detail_.comments[i];+ QString avc = det_color(c.author_display_name);auto* row = new QWidget;- row->setStyleSheet(i % 2 == 0 ? "background:#080808;border-bottom:1px solid #0d0d0d;"- : "background:#090909;border-bottom:1px solid #0d0d0d;");+ row->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(i % 2 == 0 ? ui::colors::BG_BASE : ui::colors::BG_SURFACE,+ ui::colors::BORDER_DIM));auto* row_vl = new QVBoxLayout(row);- row_vl->setContentsMargins(16, 8, 16, 6);- row_vl->setSpacing(4);+ row_vl->setContentsMargins(20, 10, 20, 8);+ row_vl->setSpacing(5);- // ── Comment header ─────────────────────────────────────────────────────+ // ── Comment header ────────────────────────────────────────────────────auto* com_top = new QWidget;com_top->setStyleSheet("background:transparent;");auto* com_hl = new QHBoxLayout(com_top);com_hl->setContentsMargins(0, 0, 0, 0);- com_hl->setSpacing(6);+ com_hl->setSpacing(8);- // Thread line + avatarauto* thread_line = new QWidget;- thread_line->setFixedWidth(2);- thread_line->setStyleSheet(QString("background:%1;").arg(str_color(c.author_display_name)));+ thread_line->setFixedSize(3, 20);+ thread_line->setStyleSheet(+ QString("background:%1;border-radius:1px;").arg(avc));- // Avatarauto* av = new QLabel(c.author_display_name.left(2).toUpper());- av->setFixedSize(20, 20);+ av->setFixedSize(22, 22);av->setAlignment(Qt::AlignCenter);- av->setStyleSheet(QString("color:#080808;font-size:9px;font-weight:700;background:%1;%2")- .arg(str_color(c.author_display_name), mono(9)));+ av->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;background:%2;"+ "border-radius:11px;%3")+ .arg(ui::colors::BG_BASE, avc, M(9)));- // Author name- auto* author_lbl = new QLabel(c.author_display_name.toUpper().left(18));+ auto* author_lbl = new QLabel(c.author_display_name);author_lbl->setStyleSheet(- QString("color:#666666;font-size:11px;font-weight:600;background:transparent;%1").arg(mono(11)));+ QString("color:%1;font-size:11px;font-weight:600;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(11)));- // Timeauto* time_lbl = new QLabel(rel_time(c.created_at));- time_lbl->setStyleSheet(QString("color:#252525;font-size:10px;background:transparent;%1").arg(mono(10)));+ time_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(10)));- // Likesbool voted = (c.user_vote == "up");- QString like_col = (voted || c.likes > 0) ? "#d97706" : "#252525";auto* likes_lbl = new QLabel(QString("▲ %1").arg(c.likes));- likes_lbl->setStyleSheet(QString("color:%1;font-size:10px;background:transparent;%2").arg(like_col, mono(10)));+ likes_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:600;"+ "background:transparent;%2")+ .arg(voted || c.likes > 0 ? ui::colors::AMBER+ : ui::colors::TEXT_DIM,+ M(10)));com_hl->addWidget(thread_line);- com_hl->addSpacing(6);com_hl->addWidget(av);com_hl->addWidget(author_lbl);com_hl->addStretch();com_hl->addWidget(time_lbl);- com_hl->addSpacing(8);+ com_hl->addSpacing(6);com_hl->addWidget(likes_lbl);row_vl->addWidget(com_top);- // ── Comment body ───────────────────────────────────────────────────────+ // ── Comment body ──────────────────────────────────────────────────────auto* body = new QLabel(c.content);body->setWordWrap(true);body->setTextFormat(Qt::PlainText);body->setAlignment(Qt::AlignTop | Qt::AlignLeft);- body->setStyleSheet(QString("color:#666666;font-size:12px;line-height:1.5;"- "background:transparent;padding-left:20px;%1")- .arg(mono(12)));+ body->setStyleSheet(+ QString("color:%1;font-size:12px;line-height:1.5;"+ "background:transparent;padding-left:28px;%2")+ .arg(ui::colors::TEXT_SECONDARY, M(12)));row_vl->addWidget(body);- // ── Action row ─────────────────────────────────────────────────────────+ // ── Action row ────────────────────────────────────────────────────────auto* act_row = new QWidget;act_row->setStyleSheet("background:transparent;");auto* act_hl = new QHBoxLayout(act_row);- act_hl->setContentsMargins(20, 0, 0, 0);- act_hl->setSpacing(8);+ act_hl->setContentsMargins(28, 0, 0, 0);+ act_hl->setSpacing(12);- auto make_act = [&](const QString& label, const QString& color, const QString& vtype) {+ auto make_act = [&](const QString& label, const QString& color,+ const QString& vtype) {auto* btn = new QPushButton(label);- btn->setFixedHeight(16);+ btn->setFixedHeight(18);btn->setCursor(Qt::PointingHandCursor);bool active = (c.user_vote == vtype);- btn->setStyleSheet(active ? QString("QPushButton{background:transparent;color:%1;border:none;"- "font-size:10px;font-weight:700;padding:0;%2}")- .arg(color, mono(10))- : QString("QPushButton{background:transparent;color:#252525;border:none;"- "font-size:10px;padding:0;%1}"- "QPushButton:hover{color:%2;}")- .arg(mono(10), color));+ btn->setStyleSheet(+ active+ ? QString("QPushButton{background:transparent;color:%1;"+ "border:none;font-size:10px;font-weight:700;"+ "padding:0;%2}")+ .arg(color, M(10))+ : QString("QPushButton{background:transparent;color:%1;"+ "border:none;font-size:10px;padding:0;%2}"+ "QPushButton:hover{color:%3;}")+ .arg(ui::colors::TEXT_DIM, M(10), color));auto uuid = c.comment_uuid;- connect(btn, &QPushButton::clicked, this, [this, uuid, vtype]() { emit vote_comment(uuid, vtype); });+ connect(btn, &QPushButton::clicked, this,+ [this, uuid, vtype]() { emit vote_comment(uuid, vtype); });return btn;};- act_hl->addWidget(make_act("▲ upvote", "#d97706", "up"));- act_hl->addWidget(make_act("▼ downvote", "#555555", "down"));+ act_hl->addWidget(make_act("▲ upvote", ui::colors::AMBER, "up"));+ act_hl->addWidget(+ make_act("▼ downvote", ui::colors::TEXT_TERTIARY, "down"));act_hl->addStretch();row_vl->addWidget(act_row);diff --git a/fincept-qt/src/screens/forum/ForumScreen.cpp b/fincept-qt/src/screens/forum/ForumScreen.cppindex 2ace0b756..51cbeeee0 100644--- a/fincept-qt/src/screens/forum/ForumScreen.cpp+++ b/fincept-qt/src/screens/forum/ForumScreen.cpp@@ -3,6 +3,7 @@#include "core/logging/Logger.h"#include "screens/forum/ForumFeedPanel.h"+#include "screens/forum/ForumSidebarPanel.h"#include "screens/forum/ForumThreadPanel.h"#include "services/forum/ForumService.h"#include "ui/theme/Theme.h"@@ -16,6 +17,7 @@#include <QPushButton>#include <QScrollArea>#include <QShowEvent>+#include <QSplitter>#include <QTextEdit>#include <QVBoxLayout>@@ -30,18 +32,26 @@ ForumScreen::ForumScreen(QWidget* parent) : QWidget(parent) {}// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-// build_ui — single stacked widget, NO splitter, NO columns+// build_ui — 3-column: sidebar | feed | thread (via splitter)// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━void ForumScreen::build_ui() {- setStyleSheet("background:#080808;");+ setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* root = new QVBoxLayout(this);root->setContentsMargins(0, 0, 0, 0);root->setSpacing(0);- build_toolbar();- root->addWidget(toolbar_);+ // ── Splitter: sidebar | main content ──────────────────────────────────────+ splitter_ = new QSplitter(Qt::Horizontal);+ splitter_->setHandleWidth(1);+ splitter_->setStyleSheet(+ QString("QSplitter{background:%1;}"+ "QSplitter::handle{background:%2;}")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));- // ── Main content: stacked feed / thread ───────────────────────────────────+ // ── Left: Sidebar ─────────────────────────────────────────────────────────+ sidebar_ = new ForumSidebarPanel;++ // ── Center+Right: Stacked feed/thread ─────────────────────────────────────main_stack_ = new QStackedWidget;feed_ = new ForumFeedPanel;thread_ = new ForumThreadPanel;@@ -49,263 +59,260 @@ void ForumScreen::build_ui() {main_stack_->addWidget(thread_); // 1main_stack_->setCurrentIndex(0);- root->addWidget(main_stack_, 1);+ splitter_->addWidget(sidebar_);+ splitter_->addWidget(main_stack_);+ splitter_->setStretchFactor(0, 0); // sidebar fixed+ splitter_->setStretchFactor(1, 1); // feed stretches+ splitter_->setSizes({240, 800});++ root->addWidget(splitter_, 1);++ // ── Wire sidebar signals ──────────────────────────────────────────────────+ connect(sidebar_, &ForumSidebarPanel::category_selected,+ this, &ForumScreen::on_category_selected);++ connect(sidebar_, &ForumSidebarPanel::trending_clicked,+ this, &ForumScreen::on_trending);++ connect(sidebar_, &ForumSidebarPanel::search_requested,+ this, &ForumScreen::on_search);++ connect(sidebar_, &ForumSidebarPanel::new_post_requested,+ this, [this](int cat_id) { show_new_post_dialog(cat_id); });- // ── Wire signals ──────────────────────────────────────────────────────────- connect(feed_, &ForumFeedPanel::post_selected, this, &ForumScreen::on_post_selected);+ // ── Wire feed signals ─────────────────────────────────────────────────────+ connect(feed_, &ForumFeedPanel::post_selected,+ this, &ForumScreen::on_post_selected);- connect(feed_, &ForumFeedPanel::category_clicked, this, &ForumScreen::on_category_selected);+ connect(feed_, &ForumFeedPanel::category_clicked,+ this, &ForumScreen::on_category_selected);connect(feed_, &ForumFeedPanel::load_more_requested, this, [this](int page) {if (active_category_id_ > 0) {feed_->set_loading(true);- services::ForumService::instance().fetch_posts(active_category_id_, page, "latest",- [this](bool ok, services::ForumPostsPage p) {- if (ok)- feed_->set_posts(p, active_category_color_);- else- feed_->set_loading(false);- });- }- });-- // Thread panel back button → return to feed- connect(thread_, &ForumThreadPanel::back_requested, this, &ForumScreen::navigate_back_to_feed);-- connect(thread_, &ForumThreadPanel::comment_submitted, this, [this](const QString& uuid, const QString& content) {- services::ForumService::instance().create_comment(uuid, content, [this, uuid](bool ok, const QString&) {- if (ok) {- thread_->set_loading(true);- services::ForumService::instance().fetch_post(uuid, [this](bool ok2, services::ForumPostDetail d) {- if (ok2)- thread_->show_post(d);+ services::ForumService::instance().fetch_posts(+ active_category_id_, page, "latest",+ [this](bool ok, services::ForumPostsPage p) {+ if (ok)+ feed_->set_posts(p, active_category_color_);else- thread_->set_loading(false);+ feed_->set_loading(false);});- }- });+ }});- connect(thread_, &ForumThreadPanel::vote_post, this, [this](const QString& uuid, const QString& vtype) {- services::ForumService::instance().vote_post(uuid, vtype, [this, uuid](bool ok, const QString&) {- if (ok) {- services::ForumService::instance().fetch_post(uuid, [this](bool ok2, services::ForumPostDetail d) {- if (ok2)- thread_->show_post(d);- });- }- });- });+ connect(feed_, &ForumFeedPanel::new_post_clicked,+ this, [this]() { on_new_post_requested(); });++ connect(feed_, &ForumFeedPanel::vote_post_requested,+ this, [this](const QString& uuid, const QString& vtype) {+ LOG_INFO("ForumScreen", "Feed vote: " + uuid + " type=" + vtype);+ services::ForumService::instance().vote_post(+ uuid, vtype, [this](bool ok, const QString&) {+ LOG_INFO("ForumScreen", QString("Feed vote result: ok=%1").arg(ok));+ if (ok && active_category_id_ > 0) {+ // Refresh current feed to show updated vote+ services::ForumService::instance().fetch_posts(+ active_category_id_, 1, "latest",+ [this](bool ok2, services::ForumPostsPage p) {+ if (ok2)+ feed_->set_posts(p, active_category_color_);+ });+ }+ });+ });- connect(thread_, &ForumThreadPanel::vote_comment, this, [this](const QString& uuid, const QString& vtype) {- services::ForumService::instance().vote_comment(uuid, vtype, [this](bool, const QString&) {- if (!current_detail_uuid_.isEmpty()) {- services::ForumService::instance().fetch_post(current_detail_uuid_,- [this](bool ok, services::ForumPostDetail d) {- if (ok)- thread_->show_post(d);- });- }- });- });+ // ── Wire thread signals ───────────────────────────────────────────────────+ connect(thread_, &ForumThreadPanel::back_requested,+ this, &ForumScreen::navigate_back_to_feed);++ connect(thread_, &ForumThreadPanel::comment_submitted,+ this, [this](const QString& uuid, const QString& content) {+ services::ForumService::instance().create_comment(+ uuid, content, [this, uuid](bool ok, const QString&) {+ if (ok) {+ thread_->set_loading(true);+ services::ForumService::instance().fetch_post(+ uuid, [this](bool ok2, services::ForumPostDetail d) {+ if (ok2)+ thread_->show_post(d);+ else+ thread_->set_loading(false);+ });+ }+ });+ });- connect(thread_, &ForumThreadPanel::author_clicked, this, [this](const QString& username) {- services::ForumService::instance().fetch_profile(username, [this](bool ok, services::ForumProfile profile) {- if (!ok)- return;- // Profile popup dialog- auto* dlg = new QDialog(this);- dlg->setWindowTitle("USER PROFILE");- dlg->setFixedSize(340, 280);- dlg->setStyleSheet("QDialog{background:#0a0a0a;border:1px solid #1a1a1a;}"- "QLabel{background:transparent;"- "font-family:'Consolas','Courier New',monospace;}");- auto* vl = new QVBoxLayout(dlg);- vl->setContentsMargins(20, 16, 20, 14);- vl->setSpacing(8);-- auto* name_lbl = new QLabel(profile.display_name.toUpper());- name_lbl->setStyleSheet(QString("color:%1;font-size:16px;font-weight:700;%2")- .arg(profile.avatar_color.isEmpty() ? "#d97706" : profile.avatar_color, M(16)));- vl->addWidget(name_lbl);-- if (!profile.bio.isEmpty()) {- auto* bio = new QLabel(profile.bio);- bio->setWordWrap(true);- bio->setStyleSheet(QString("color:#444444;font-size:12px;font-style:italic;%1").arg(M(12)));- vl->addWidget(bio);- }+ connect(thread_, &ForumThreadPanel::vote_post,+ this, [this](const QString& uuid, const QString& vtype) {+ LOG_INFO("ForumScreen", "Vote post: " + uuid + " type=" + vtype);+ services::ForumService::instance().vote_post(+ uuid, vtype, [this, uuid](bool ok, const QString& msg) {+ LOG_INFO("ForumScreen", QString("Vote result: ok=%1 msg=%2").arg(ok).arg(msg));+ if (ok) {+ services::ForumService::instance().fetch_post(+ uuid, [this](bool ok2, services::ForumPostDetail d) {+ if (ok2)+ thread_->show_post(d);+ });+ }+ });+ });- auto* sep = new QFrame;- sep->setFixedHeight(1);- sep->setStyleSheet("background:#151515;border:none;");- vl->addWidget(sep);-- auto mk_row = [&](const QString& l, const QString& v, const QString& vc) {- auto* w = new QWidget;- w->setStyleSheet("background:transparent;");- auto* hl = new QHBoxLayout(w);- hl->setContentsMargins(0, 0, 0, 0);- auto* ll = new QLabel(l);- ll->setStyleSheet(QString("color:#252525;font-size:11px;%1").arg(M(11)));- auto* vl2 = new QLabel(v);- vl2->setStyleSheet(QString("color:%1;font-size:11px;font-weight:700;%2").arg(vc, M(11)));- hl->addWidget(ll);- hl->addStretch();- hl->addWidget(vl2);- return w;- };- vl->addWidget(mk_row("REPUTATION", QString::number(profile.reputation), "#d97706"));- vl->addWidget(mk_row("POSTS", QString::number(profile.posts_count), "#888888"));- vl->addWidget(mk_row("COMMENTS", QString::number(profile.comments_count), "#888888"));- vl->addWidget(mk_row("LIKES GIVEN", QString::number(profile.likes_given), "#16a34a"));-- if (profile.is_own_profile) {- auto* edit_btn = new QPushButton("EDIT MY PROFILE");- edit_btn->setFixedHeight(28);- edit_btn->setCursor(Qt::PointingHandCursor);- edit_btn->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.1);"- "color:#444444;border:1px solid #1e1e1e;"- "font-size:11px;font-weight:700;%1}"- "QPushButton:hover{color:#d97706;"- "border-color:rgba(217,119,6,0.4);}")- .arg(M(11)));- connect(edit_btn, &QPushButton::clicked, this, [this, dlg, profile]() {- dlg->accept();- show_edit_profile_dialog(profile);- });- vl->addStretch();- vl->addWidget(edit_btn);- } else {- vl->addStretch();- }- dlg->exec();- });- });-}+ connect(thread_, &ForumThreadPanel::vote_comment,+ this, [this](const QString& uuid, const QString& vtype) {+ services::ForumService::instance().vote_comment(+ uuid, vtype, [this](bool, const QString&) {+ if (!current_detail_uuid_.isEmpty()) {+ services::ForumService::instance().fetch_post(+ current_detail_uuid_,+ [this](bool ok, services::ForumPostDetail d) {+ if (ok)+ thread_->show_post(d);+ });+ }+ });+ });-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-// Toolbar: brand | scrollable category chips | live stats | search | compose btn-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-void ForumScreen::build_toolbar() {- toolbar_ = new QWidget;- toolbar_->setFixedHeight(44);- toolbar_->setStyleSheet("background:#050505;border-bottom:1px solid #111111;");- auto* tb = new QHBoxLayout(toolbar_);- tb->setContentsMargins(0, 0, 0, 0);- tb->setSpacing(0);-- // ── Brand block ───────────────────────────────────────────────────────────- auto* brand = new QWidget;- brand->setFixedWidth(120);- brand->setStyleSheet("background:transparent;border-right:1px solid #111111;");- auto* brand_hl = new QHBoxLayout(brand);- brand_hl->setContentsMargins(14, 0, 14, 0);- brand_hl->setSpacing(8);-- auto* diamond = new QLabel("◈");- diamond->setStyleSheet("color:#d97706;font-size:16px;background:transparent;");- auto* forum_lbl = new QLabel("FORUM");- forum_lbl->setStyleSheet(QString("color:#e5e5e5;font-size:12px;font-weight:700;letter-spacing:0.8px;"- "background:transparent;%1")- .arg(M(12)));- brand_hl->addWidget(diamond);- brand_hl->addWidget(forum_lbl);- tb->addWidget(brand);-- // ── Category chips (horizontal scrollable) ────────────────────────────────- auto* chips_scroll = new QScrollArea;- chips_scroll->setFixedHeight(44);- chips_scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);- chips_scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);- chips_scroll->setStyleSheet("QScrollArea{border:none;background:transparent;border-right:1px solid #111111;}");- chips_scroll->setWidgetResizable(false);-- chips_container_ = new QWidget;- chips_container_->setFixedHeight(44);- chips_container_->setStyleSheet("background:transparent;");- chips_layout_ = new QHBoxLayout(chips_container_);- chips_layout_->setContentsMargins(8, 0, 8, 0);- chips_layout_->setSpacing(4);-- // Trending chip — always present- auto* trend_chip = new QPushButton("▲ TRENDING");- trend_chip->setFixedHeight(26);- trend_chip->setCursor(Qt::PointingHandCursor);- trend_chip->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.08);color:#d97706;"- "border:1px solid rgba(217,119,6,0.25);padding:0 12px;"- "font-size:10px;font-weight:700;letter-spacing:0.5px;%1}"- "QPushButton:hover{background:rgba(217,119,6,0.15);"- "border-color:rgba(217,119,6,0.5);}")- .arg(M(10)));- connect(trend_chip, &QPushButton::clicked, this, &ForumScreen::on_trending);- chips_layout_->addWidget(trend_chip);-- chips_layout_->addStretch();- chips_container_->adjustSize();- chips_scroll->setWidget(chips_container_);- tb->addWidget(chips_scroll, 1);-- // ── Live stats chips ──────────────────────────────────────────────────────- auto* stats_w = new QWidget;- stats_w->setFixedWidth(160);- stats_w->setStyleSheet("background:transparent;border-right:1px solid #111111;");- auto* stats_hl = new QHBoxLayout(stats_w);- stats_hl->setContentsMargins(10, 0, 10, 0);- stats_hl->setSpacing(10);-- stat_posts_lbl_ = new QLabel("—");- stat_posts_lbl_->setStyleSheet(QString("color:#666666;font-size:11px;background:transparent;%1").arg(M(11)));- stat_active_lbl_ = new QLabel("—");- stat_active_lbl_->setStyleSheet(- QString("color:#d97706;font-size:11px;font-weight:700;background:transparent;%1").arg(M(11)));-- stats_hl->addWidget(stat_posts_lbl_);- stats_hl->addStretch();- stats_hl->addWidget(stat_active_lbl_);- tb->addWidget(stats_w);-- // ── Search + profile avatar + compose ─────────────────────────────────────- auto* right_w = new QWidget;- right_w->setFixedWidth(300);- right_w->setStyleSheet("background:transparent;");- auto* right_hl = new QHBoxLayout(right_w);- right_hl->setContentsMargins(8, 7, 10, 7);- right_hl->setSpacing(6);-- search_input_ = new QLineEdit;- search_input_->setPlaceholderText("search posts...");- search_input_->setStyleSheet(QString("QLineEdit{background:#0a0a0a;color:#888888;border:1px solid #141414;"- "padding:3px 10px;font-size:11px;%1}"- "QLineEdit:focus{border-color:#252525;color:#e5e5e5;}"- "QLineEdit::placeholder{color:#555555;}")- .arg(M(11)));- connect(search_input_, &QLineEdit::returnPressed, this, [this]() { on_search(search_input_->text().trimmed()); });-- // Profile avatar- profile_avatar_ = new QLabel("?");- profile_avatar_->setFixedSize(28, 28);- profile_avatar_->setAlignment(Qt::AlignCenter);- profile_avatar_->setStyleSheet(QString("color:#080808;font-size:11px;font-weight:700;"- "background:#d97706;%1")- .arg(M(11)));-- // New post button- auto* new_btn = new QPushButton("+ NEW POST");- new_btn->setFixedHeight(28);- new_btn->setCursor(Qt::PointingHandCursor);- new_btn->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.1);color:#555555;"- "border:1px solid #1a1a1a;padding:0 12px;"- "font-size:10px;font-weight:700;%1}"- "QPushButton:hover{color:#d97706;border-color:rgba(217,119,6,0.4);"- "background:rgba(217,119,6,0.18);}")- .arg(M(10)));- connect(new_btn, &QPushButton::clicked, this, [this]() { on_new_post_requested(); });-- right_hl->addWidget(search_input_, 1);- right_hl->addWidget(profile_avatar_);- right_hl->addWidget(new_btn);- tb->addWidget(right_w);+ connect(thread_, &ForumThreadPanel::author_clicked,+ this, [this](const QString& username) {+ services::ForumService::instance().fetch_profile(+ username, [this](bool ok, services::ForumProfile profile) {+ if (!ok)+ return;+ // Profile popup+ auto* dlg = new QDialog(this);+ dlg->setWindowTitle("USER PROFILE");+ dlg->setFixedSize(380, 340);+ dlg->setStyleSheet(+ QString("QDialog{background:%1;border:1px solid %2;}"+ "QLabel{background:transparent;"+ "font-family:'Consolas','Courier New',monospace;}")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));+ auto* vl = new QVBoxLayout(dlg);+ vl->setContentsMargins(24, 20, 24, 18);+ vl->setSpacing(10);++ // Profile header with gradient accent+ auto* hdr = new QWidget;+ hdr->setFixedHeight(4);+ QString avc = profile.avatar_color.isEmpty() ? ui::colors::AMBER : profile.avatar_color;+ hdr->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:0.5 %2,stop:1 transparent);")+ .arg(avc, ui::colors::AMBER));+ vl->addWidget(hdr);++ // Avatar + name+ auto* top = new QWidget;+ top->setStyleSheet("background:transparent;");+ auto* th = new QHBoxLayout(top);+ th->setContentsMargins(0, 0, 0, 0);+ th->setSpacing(14);++ auto* av = new QLabel(profile.display_name.left(2).toUpper());+ av->setFixedSize(48, 48);+ av->setAlignment(Qt::AlignCenter);+ av->setStyleSheet(+ QString("color:%1;font-size:16px;font-weight:700;"+ "background:%2;border-radius:24px;%3")+ .arg(ui::colors::BG_BASE, avc, M(16)));++ auto* info = new QVBoxLayout;+ info->setSpacing(2);+ auto* nm = new QLabel(profile.display_name.toUpper());+ nm->setStyleSheet(+ QString("color:%1;font-size:16px;font-weight:700;%2")+ .arg(avc, M(16)));+ auto* un = new QLabel("@" + profile.username);+ un->setStyleSheet(+ QString("color:%1;font-size:11px;%2")+ .arg(ui::colors::TEXT_SECONDARY, M(11)));+ info->addWidget(nm);+ info->addWidget(un);+ th->addWidget(av);+ th->addLayout(info, 1);+ vl->addWidget(top);++ if (!profile.bio.isEmpty()) {+ auto* bio = new QLabel(profile.bio);+ bio->setWordWrap(true);+ bio->setStyleSheet(+ QString("color:%1;font-size:12px;font-style:italic;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(12)));+ vl->addWidget(bio);+ }++ auto* sep = new QFrame;+ sep->setFixedHeight(1);+ sep->setStyleSheet(+ QString("background:%1;border:none;")+ .arg(ui::colors::BORDER_DIM));+ vl->addWidget(sep);++ // Stats grid+ auto* grid = new QWidget;+ grid->setStyleSheet("background:transparent;");+ auto* gh = new QHBoxLayout(grid);+ gh->setContentsMargins(0, 0, 0, 0);+ gh->setSpacing(0);++ auto mk_stat = [&](const QString& val, const QString& lbl,+ const QString& col) {+ auto* cell = new QWidget;+ cell->setStyleSheet("background:transparent;");+ auto* cv = new QVBoxLayout(cell);+ cv->setContentsMargins(0, 8, 0, 8);+ cv->setSpacing(2);+ cv->setAlignment(Qt::AlignCenter);+ auto* v = new QLabel(val);+ v->setAlignment(Qt::AlignCenter);+ v->setStyleSheet(+ QString("color:%1;font-size:18px;font-weight:700;%2")+ .arg(col, M(18)));+ auto* l = new QLabel(lbl);+ l->setAlignment(Qt::AlignCenter);+ l->setStyleSheet(+ QString("color:%1;font-size:9px;letter-spacing:1px;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(9)));+ cv->addWidget(v);+ cv->addWidget(l);+ return cell;+ };++ gh->addWidget(mk_stat(QString::number(profile.reputation), "REP", ui::colors::AMBER));+ gh->addWidget(mk_stat(QString::number(profile.posts_count), "POSTS", ui::colors::TEXT_PRIMARY));+ gh->addWidget(mk_stat(QString::number(profile.comments_count), "REPLIES", ui::colors::CYAN));+ gh->addWidget(mk_stat(QString::number(profile.likes_received), "LIKES", ui::colors::POSITIVE));+ vl->addWidget(grid);++ if (profile.is_own_profile) {+ auto* edit_btn = new QPushButton("EDIT MY PROFILE");+ edit_btn->setFixedHeight(32);+ edit_btn->setCursor(Qt::PointingHandCursor);+ edit_btn->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.08);"+ "color:%1;border:1px solid %2;"+ "font-size:11px;font-weight:700;%3}"+ "QPushButton:hover{color:%4;"+ "border-color:rgba(217,119,6,0.5);"+ "background:rgba(217,119,6,0.15);}")+ .arg(ui::colors::TEXT_TERTIARY,+ ui::colors::BORDER_DIM,+ M(11), ui::colors::AMBER));+ connect(edit_btn, &QPushButton::clicked, this,+ [this, dlg, profile]() {+ dlg->accept();+ show_edit_profile_dialog(profile);+ });+ vl->addStretch();+ vl->addWidget(edit_btn);+ } else {+ vl->addStretch();+ }+ dlg->exec();+ });+ });}// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━@@ -325,37 +332,34 @@ void ForumScreen::load_initial_data() {initial_load_done_ = true;feed_->set_loading(true);- // Stats → toolbar + feed dashboard- services::ForumService::instance().fetch_stats([this](bool ok, services::ForumStats s) {- if (!ok)- return;- stat_posts_lbl_->setText(QString("%1 posts").arg(s.total_posts));- stat_active_lbl_->setText(QString("%1 today").arg(s.recent_posts_24h));- feed_->set_stats(s);- });+ // Stats+ services::ForumService::instance().fetch_stats(+ [this](bool ok, services::ForumStats s) {+ if (!ok)+ return;+ sidebar_->set_stats(s);+ feed_->set_stats(s);+ });- // My profile → toolbar avatar + feed dashboard- services::ForumService::instance().fetch_my_profile([this](bool ok, services::ForumProfile p) {- if (!ok)- return;- QString col = p.avatar_color.isEmpty() ? "#d97706" : p.avatar_color;- QString ini = p.display_name.isEmpty() ? "?" : p.display_name.left(2).toUpper();- profile_avatar_->setText(ini);- profile_avatar_->setStyleSheet(QString("color:#080808;font-size:11px;font-weight:700;"- "background:%1;%2")- .arg(col, M(11)));- feed_->set_profile(p);- });+ // My profile+ services::ForumService::instance().fetch_my_profile(+ [this](bool ok, services::ForumProfile p) {+ if (!ok)+ return;+ sidebar_->set_my_profile(p);+ feed_->set_profile(p);+ });- // Categories → toolbar chips + feed dashboard cards+ // Categoriesservices::ForumService::instance().fetch_categories(- [this](bool ok, QVector<services::ForumCategory> cats, services::ForumPermissions) {+ [this](bool ok, QVector<services::ForumCategory> cats,+ services::ForumPermissions) {if (!ok || cats.isEmpty())return;categories_ = cats;- rebuild_category_chips();+ sidebar_->set_categories(cats);- // Auto-select first category with posts, else just first+ // Auto-select first category with postsint sel_idx = 0;for (int i = 0; i < cats.size(); ++i) {if (cats[i].post_count > 0) {@@ -367,56 +371,21 @@ void ForumScreen::load_initial_data() {active_category_id_ = first.id;active_category_name_ = first.name;active_category_color_ = first.color;+ sidebar_->set_active_category(first.id);feed_->set_header(first.name);feed_->set_categories(cats, first.id);- services::ForumService::instance().fetch_posts(first.id, 1, "latest",- [this, first](bool ok2, services::ForumPostsPage p) {- if (ok2)- feed_->set_posts(p, first.color);- else- feed_->set_loading(false);- });+ services::ForumService::instance().fetch_posts(+ first.id, 1, "latest",+ [this, first](bool ok2, services::ForumPostsPage p) {+ if (ok2)+ feed_->set_posts(p, first.color);+ else+ feed_->set_loading(false);+ });});}-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-// Category chip bar-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-void ForumScreen::rebuild_category_chips() {- // Remove everything except trending chip (index 0) and stretch- while (chips_layout_->count() > 1) {- auto* item = chips_layout_->takeAt(1);- if (item->widget())- item->widget()->deleteLater();- delete item;- }-- for (const auto& cat : categories_) {- const bool active = (cat.id == active_category_id_);- QString cc = cat.color.isEmpty() ? "#d97706" : cat.color;-- auto* chip = new QPushButton(cat.name.toUpper());- chip->setFixedHeight(26);- chip->setCursor(Qt::PointingHandCursor);- chip->setStyleSheet(active ? QString("QPushButton{background:%1;color:#080808;"- "border:1px solid %1;padding:0 12px;"- "font-size:10px;font-weight:700;letter-spacing:0.3px;%2}")- .arg(cc, M(10))- : QString("QPushButton{background:transparent;color:#777777;"- "border:1px solid #1a1a1a;padding:0 12px;"- "font-size:10px;letter-spacing:0.3px;%1}"- "QPushButton:hover{color:#888888;border-color:#2a2a2a;}")- .arg(M(10)));- connect(chip, &QPushButton::clicked, this,- [this, cat]() { on_category_selected(cat.id, cat.name, cat.color); });- chips_layout_->addWidget(chip);- }-- chips_layout_->addStretch();- chips_container_->adjustSize();-}-// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━// Navigation// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━@@ -424,7 +393,8 @@ void ForumScreen::navigate_back_to_feed() {main_stack_->setCurrentIndex(0);}-void ForumScreen::on_category_selected(int id, const QString& name, const QString& color) {+void ForumScreen::on_category_selected(int id, const QString& name,+ const QString& color) {active_category_id_ = id;active_category_name_ = name;active_category_color_ = color;@@ -432,65 +402,67 @@ void ForumScreen::on_category_selected(int id, const QString& name, const QStrinfeed_->set_loading(true);feed_->clear_active();feed_->set_categories(categories_, id);- main_stack_->setCurrentIndex(0); // Go back to feed if in thread- rebuild_category_chips();-- services::ForumService::instance().fetch_posts(id, 1, "latest", [this, color](bool ok, services::ForumPostsPage p) {- if (ok)- feed_->set_posts(p, color);- else- feed_->set_loading(false);- });+ sidebar_->set_active_category(id);+ main_stack_->setCurrentIndex(0);++ services::ForumService::instance().fetch_posts(+ id, 1, "latest", [this, color](bool ok, services::ForumPostsPage p) {+ if (ok)+ feed_->set_posts(p, color);+ else+ feed_->set_loading(false);+ });}void ForumScreen::on_post_selected(const services::ForumPost& post) {current_detail_uuid_ = post.post_uuid;feed_->set_active_post(post.post_uuid);thread_->set_loading(true);- main_stack_->setCurrentIndex(1); // Switch to thread view — FULL SCREEN-- services::ForumService::instance().fetch_post(post.post_uuid, [this](bool ok, services::ForumPostDetail d) {- if (ok)- thread_->show_post(d);- else- thread_->set_loading(false);- });+ main_stack_->setCurrentIndex(1);++ services::ForumService::instance().fetch_post(+ post.post_uuid, [this](bool ok, services::ForumPostDetail d) {+ if (ok)+ thread_->show_post(d);+ else+ thread_->set_loading(false);+ });}void ForumScreen::on_search(const QString& query) {if (query.isEmpty())return;active_category_id_ = 0;- active_category_color_ = "#06b6d4";+ active_category_color_ = ui::colors::CYAN;feed_->set_header("SEARCH: " + query);feed_->set_loading(true);feed_->clear_active();main_stack_->setCurrentIndex(0);- rebuild_category_chips();- services::ForumService::instance().search(query, 1, [this](bool ok, services::ForumPostsPage p) {- if (ok)- feed_->set_posts(p, "#06b6d4");- else- feed_->set_loading(false);- });+ services::ForumService::instance().search(+ query, 1, [this](bool ok, services::ForumPostsPage p) {+ if (ok)+ feed_->set_posts(p, ui::colors::CYAN);+ else+ feed_->set_loading(false);+ });}void ForumScreen::on_trending() {active_category_id_ = 0;- active_category_color_ = "#d97706";+ active_category_color_ = ui::colors::AMBER;feed_->set_header("TRENDING");feed_->set_loading(true);feed_->clear_active();main_stack_->setCurrentIndex(0);- rebuild_category_chips();- services::ForumService::instance().fetch_trending([this](bool ok, services::ForumPostsPage p) {- if (ok)- feed_->set_posts(p, "#d97706");- else- feed_->set_loading(false);- });+ services::ForumService::instance().fetch_trending(+ [this](bool ok, services::ForumPostsPage p) {+ if (ok)+ feed_->set_posts(p, ui::colors::AMBER);+ else+ feed_->set_loading(false);+ });}void ForumScreen::on_new_post_requested() {@@ -503,76 +475,112 @@ void ForumScreen::on_new_post_requested() {void ForumScreen::show_new_post_dialog(int category_id) {auto* dlg = new QDialog(this);dlg->setWindowTitle("NEW POST");- dlg->setMinimumSize(520, 340);- dlg->setStyleSheet("QDialog{background:#0a0a0a;border:1px solid #1a1a1a;}"- "QLabel{color:#888888;font-size:11px;background:transparent;"- "font-family:'Consolas','Courier New',monospace;}"- "QLineEdit,QTextEdit{background:#080808;color:#e5e5e5;"- "border:1px solid #1a1a1a;font-size:12px;"- "font-family:'Consolas','Courier New',monospace;padding:4px 10px;}"- "QLineEdit:focus,QTextEdit:focus{border-color:#2a2a2a;}");+ dlg->setMinimumSize(560, 400);+ dlg->setStyleSheet(+ QString("QDialog{background:%1;border:1px solid %2;}"+ "QLabel{color:%3;font-size:11px;background:transparent;"+ "font-family:'Consolas','Courier New',monospace;}"+ "QLineEdit,QTextEdit{background:%4;color:%5;"+ "border:1px solid %2;font-size:13px;"+ "font-family:'Consolas','Courier New',monospace;padding:8px 12px;}"+ "QLineEdit:focus,QTextEdit:focus{border-color:%6;}")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM,+ ui::colors::TEXT_SECONDARY, ui::colors::BG_BASE,+ ui::colors::TEXT_PRIMARY, ui::colors::BORDER_BRIGHT));auto* vl = new QVBoxLayout(dlg);- vl->setContentsMargins(18, 16, 18, 14);- vl->setSpacing(10);-- auto* hdr = new QLabel("NEW POST");- hdr->setStyleSheet(QString("color:#d97706;font-size:14px;font-weight:700;letter-spacing:1px;%1").arg(M(14)));+ vl->setContentsMargins(24, 20, 24, 18);+ vl->setSpacing(12);++ // Gradient accent bar+ auto* accent = new QWidget;+ accent->setFixedHeight(3);+ accent->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:0.6 %2,stop:1 transparent);")+ .arg(ui::colors::AMBER, ui::colors::ORANGE));+ vl->addWidget(accent);++ auto* hdr = new QLabel("CREATE NEW POST");+ hdr->setStyleSheet(+ QString("color:%1;font-size:15px;font-weight:700;letter-spacing:1.5px;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(15)));vl->addWidget(hdr);- auto* sep = new QFrame;- sep->setFixedHeight(1);- sep->setStyleSheet("background:#111111;border:none;");- vl->addWidget(sep);+ auto* sub = new QLabel("Share your insights with the community");+ sub->setStyleSheet(+ QString("color:%1;font-size:11px;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));+ vl->addWidget(sub);+ vl->addSpacing(4);++ auto* title_lbl = new QLabel("TITLE");+ title_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;letter-spacing:1px;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(10)));auto* title_edit = new QLineEdit;- title_edit->setPlaceholderText("Post title...");- title_edit->setFixedHeight(32);+ title_edit->setPlaceholderText("Give your post a descriptive title...");+ title_edit->setFixedHeight(36);++ auto* content_lbl = new QLabel("CONTENT");+ content_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;letter-spacing:1px;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(10)));auto* body_edit = new QTextEdit;- body_edit->setPlaceholderText("Write your post content...");+ body_edit->setPlaceholderText("Write your thoughts...");- vl->addWidget(new QLabel("TITLE"));+ vl->addWidget(title_lbl);vl->addWidget(title_edit);- vl->addWidget(new QLabel("CONTENT"));+ vl->addWidget(content_lbl);vl->addWidget(body_edit, 1);auto* btn_row = new QWidget;btn_row->setStyleSheet("background:transparent;");auto* btn_hl = new QHBoxLayout(btn_row);- btn_hl->setContentsMargins(0, 0, 0, 0);- btn_hl->setSpacing(8);+ btn_hl->setContentsMargins(0, 4, 0, 0);+ btn_hl->setSpacing(10);auto* cancel = new QPushButton("CANCEL");- cancel->setFixedHeight(28);- cancel->setStyleSheet(QString("QPushButton{background:transparent;color:#333333;"- "border:1px solid #1a1a1a;font-size:11px;font-weight:700;"- "padding:0 16px;%1}"- "QPushButton:hover{color:#888888;}")- .arg(M(11)));+ cancel->setFixedHeight(32);+ cancel->setCursor(Qt::PointingHandCursor);+ cancel->setStyleSheet(+ QString("QPushButton{background:transparent;color:%1;"+ "border:1px solid %2;font-size:11px;font-weight:700;"+ "padding:0 20px;%3}"+ "QPushButton:hover{color:%4;border-color:%5;}")+ .arg(ui::colors::TEXT_TERTIARY, ui::colors::BORDER_DIM,+ M(11), ui::colors::TEXT_SECONDARY, ui::colors::BORDER_MED));connect(cancel, &QPushButton::clicked, dlg, &QDialog::reject);- auto* submit = new QPushButton("SUBMIT POST");- submit->setFixedHeight(28);+ auto* submit = new QPushButton("PUBLISH POST");+ submit->setFixedHeight(32);submit->setCursor(Qt::PointingHandCursor);- submit->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.12);color:#555555;"- "border:1px solid #1e1e1e;font-size:11px;font-weight:700;"- "padding:0 16px;%1}"- "QPushButton:hover{color:#d97706;"- "border-color:rgba(217,119,6,0.4);}")- .arg(M(11)));- connect(submit, &QPushButton::clicked, this, [this, dlg, title_edit, body_edit, category_id]() {- QString title = title_edit->text().trimmed();- QString content = body_edit->toPlainText().trimmed();- if (title.isEmpty() || content.isEmpty())- return;- dlg->accept();- services::ForumService::instance().create_post(- category_id, title, content, [this](bool ok, const QString& msg) {- if (ok)- on_category_selected(active_category_id_, active_category_name_, active_category_color_);- else- LOG_WARN("ForumScreen", "Create post failed: " + msg);+ submit->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.12);color:%1;"+ "border:1px solid rgba(217,119,6,0.3);font-size:11px;"+ "font-weight:700;padding:0 20px;%2}"+ "QPushButton:hover{color:%3;"+ "border-color:rgba(217,119,6,0.6);"+ "background:rgba(217,119,6,0.2);}")+ .arg(ui::colors::TEXT_SECONDARY, M(11), ui::colors::AMBER));+ connect(submit, &QPushButton::clicked, this,+ [this, dlg, title_edit, body_edit, category_id]() {+ QString title = title_edit->text().trimmed();+ QString content = body_edit->toPlainText().trimmed();+ if (title.isEmpty() || content.isEmpty())+ return;+ dlg->accept();+ services::ForumService::instance().create_post(+ category_id, title, content,+ [this](bool ok, const QString& msg) {+ if (ok)+ on_category_selected(active_category_id_,+ active_category_name_,+ active_category_color_);+ else+ LOG_WARN("ForumScreen", "Create post failed: " + msg);+ });});- });btn_hl->addStretch();btn_hl->addWidget(cancel);@@ -584,83 +592,99 @@ void ForumScreen::show_new_post_dialog(int category_id) {void ForumScreen::show_edit_profile_dialog(const services::ForumProfile& profile) {auto* dlg = new QDialog(this);dlg->setWindowTitle("EDIT PROFILE");- dlg->setMinimumSize(400, 280);- dlg->setStyleSheet("QDialog{background:#0a0a0a;border:1px solid #1a1a1a;}"- "QLabel{color:#888888;font-size:11px;background:transparent;"- "font-family:'Consolas','Courier New',monospace;}"- "QLineEdit{background:#080808;color:#e5e5e5;border:1px solid #1a1a1a;"- "font-size:12px;font-family:'Consolas','Courier New',monospace;"- "padding:3px 10px;}"- "QLineEdit:focus{border-color:#2a2a2a;}");+ dlg->setMinimumSize(440, 320);+ dlg->setStyleSheet(+ QString("QDialog{background:%1;border:1px solid %2;}"+ "QLabel{color:%3;font-size:11px;background:transparent;"+ "font-family:'Consolas','Courier New',monospace;}"+ "QLineEdit{background:%4;color:%5;border:1px solid %2;"+ "font-size:12px;font-family:'Consolas','Courier New',monospace;"+ "padding:6px 12px;}"+ "QLineEdit:focus{border-color:%6;}")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM,+ ui::colors::TEXT_SECONDARY, ui::colors::BG_BASE,+ ui::colors::TEXT_PRIMARY, ui::colors::BORDER_BRIGHT));auto* vl = new QVBoxLayout(dlg);- vl->setContentsMargins(18, 16, 18, 14);- vl->setSpacing(8);+ vl->setContentsMargins(24, 20, 24, 18);+ vl->setSpacing(10);++ // Gradient accent+ auto* accent = new QWidget;+ accent->setFixedHeight(3);+ accent->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:0.6 %2,stop:1 transparent);")+ .arg(ui::colors::CYAN, ui::colors::AMBER));+ vl->addWidget(accent);auto* hdr = new QLabel("EDIT PROFILE");- hdr->setStyleSheet(QString("color:#d97706;font-size:14px;font-weight:700;letter-spacing:1px;%1").arg(M(14)));+ hdr->setStyleSheet(+ QString("color:%1;font-size:15px;font-weight:700;letter-spacing:1.5px;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(15)));vl->addWidget(hdr);-- auto* sep = new QFrame;- sep->setFixedHeight(1);- sep->setStyleSheet("background:#111111;border:none;");- vl->addWidget(sep);+ vl->addSpacing(4);auto mk = [&](const QString& lbl, const QString& val) -> QLineEdit* {- vl->addWidget(new QLabel(lbl));+ auto* l = new QLabel(lbl);+ l->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;letter-spacing:1px;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(10)));+ vl->addWidget(l);auto* e = new QLineEdit(val);- e->setFixedHeight(28);+ e->setFixedHeight(30);vl->addWidget(e);return e;};auto* name_e = mk("DISPLAY NAME", profile.display_name);auto* bio_e = mk("BIO", profile.bio);auto* sig_e = mk("SIGNATURE", profile.signature);- auto* col_e = mk("AVATAR COLOR", profile.avatar_color);+ auto* col_e = mk("AVATAR COLOR (HEX)", profile.avatar_color);auto* btn_row = new QWidget;btn_row->setStyleSheet("background:transparent;");auto* bh = new QHBoxLayout(btn_row);- bh->setContentsMargins(0, 0, 0, 0);- bh->setSpacing(8);+ bh->setContentsMargins(0, 4, 0, 0);+ bh->setSpacing(10);auto* cc = new QPushButton("CANCEL");- cc->setFixedHeight(28);- cc->setStyleSheet(QString("QPushButton{background:transparent;color:#333333;"- "border:1px solid #1a1a1a;font-size:11px;font-weight:700;"- "padding:0 16px;%1}"- "QPushButton:hover{color:#888888;}")- .arg(M(11)));+ cc->setFixedHeight(32);+ cc->setStyleSheet(+ QString("QPushButton{background:transparent;color:%1;"+ "border:1px solid %2;font-size:11px;font-weight:700;"+ "padding:0 20px;%3}"+ "QPushButton:hover{color:%4;}")+ .arg(ui::colors::TEXT_TERTIARY, ui::colors::BORDER_DIM,+ M(11), ui::colors::TEXT_SECONDARY));connect(cc, &QPushButton::clicked, dlg, &QDialog::reject);- auto* sc = new QPushButton("SAVE");- sc->setFixedHeight(28);+ auto* sc = new QPushButton("SAVE CHANGES");+ sc->setFixedHeight(32);sc->setCursor(Qt::PointingHandCursor);- sc->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.12);color:#555555;"- "border:1px solid #1e1e1e;font-size:11px;font-weight:700;"- "padding:0 16px;%1}"- "QPushButton:hover{color:#d97706;"- "border-color:rgba(217,119,6,0.4);}")- .arg(M(11)));- connect(sc, &QPushButton::clicked, this, [this, dlg, name_e, bio_e, sig_e, col_e]() {- dlg->accept();- services::ForumService::instance().update_profile(- name_e->text().trimmed(), bio_e->text().trimmed(), sig_e->text().trimmed(), col_e->text().trimmed(),- [this](bool ok, const QString&) {- if (ok) {- // Refresh avatar- services::ForumService::instance().fetch_my_profile([this](bool ok2, services::ForumProfile p) {- if (!ok2)- return;- QString col = p.avatar_color.isEmpty() ? "#d97706" : p.avatar_color;- QString ini = p.display_name.isEmpty() ? "?" : p.display_name.left(2).toUpper();- profile_avatar_->setText(ini);- profile_avatar_->setStyleSheet(QString("color:#080808;font-size:11px;"- "font-weight:700;background:%1;%2")- .arg(col, M(11)));+ sc->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.12);color:%1;"+ "border:1px solid rgba(217,119,6,0.3);font-size:11px;"+ "font-weight:700;padding:0 20px;%2}"+ "QPushButton:hover{color:%3;"+ "border-color:rgba(217,119,6,0.6);"+ "background:rgba(217,119,6,0.2);}")+ .arg(ui::colors::TEXT_SECONDARY, M(11), ui::colors::AMBER));+ connect(sc, &QPushButton::clicked, this,+ [this, dlg, name_e, bio_e, sig_e, col_e]() {+ dlg->accept();+ services::ForumService::instance().update_profile(+ name_e->text().trimmed(), bio_e->text().trimmed(),+ sig_e->text().trimmed(), col_e->text().trimmed(),+ [this](bool ok, const QString&) {+ if (ok) {+ services::ForumService::instance().fetch_my_profile(+ [this](bool ok2, services::ForumProfile p) {+ if (!ok2)+ return;+ sidebar_->set_my_profile(p);+ });+ }});- }});- });bh->addStretch();bh->addWidget(cc);diff --git a/fincept-qt/src/screens/forum/ForumScreen.h b/fincept-qt/src/screens/forum/ForumScreen.hindex 7dd53190f..96e21ce71 100644--- a/fincept-qt/src/screens/forum/ForumScreen.h+++ b/fincept-qt/src/screens/forum/ForumScreen.h@@ -5,6 +5,7 @@#include <QHBoxLayout>#include <QLabel>#include <QLineEdit>+#include <QSplitter>#include <QStackedWidget>#include <QWidget>@@ -12,6 +13,7 @@ namespace fincept::screens {class ForumFeedPanel;class ForumThreadPanel;+class ForumSidebarPanel;class ForumScreen : public QWidget {Q_OBJECT@@ -32,22 +34,15 @@ class ForumScreen : public QWidget {private:void build_ui();- void build_toolbar();void load_initial_data();- void rebuild_category_chips();void show_new_post_dialog(int category_id);void show_edit_profile_dialog(const services::ForumProfile& profile);- // Toolbar- QWidget* toolbar_ = nullptr;- QWidget* chips_container_ = nullptr;- QHBoxLayout* chips_layout_ = nullptr;- QLineEdit* search_input_ = nullptr;- QLabel* stat_posts_lbl_ = nullptr;- QLabel* stat_active_lbl_ = nullptr;- QLabel* profile_avatar_ = nullptr;+ // Layout+ QSplitter* splitter_ = nullptr;+ ForumSidebarPanel* sidebar_ = nullptr;- // Main stacked view: 0=feed, 1=thread+ // Main content: stacked feed / threadQStackedWidget* main_stack_ = nullptr;ForumFeedPanel* feed_ = nullptr;ForumThreadPanel* thread_ = nullptr;diff --git a/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp b/fincept-qt/src/screens/forum/ForumSidebarPanel.cppindex 340a18517..d5f6cbbf3 100644--- a/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp+++ b/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp@@ -12,41 +12,14 @@namespace fincept::screens {-static QString mono(int sz = 12) {+static QString M(int sz = 12) {return QString("font-family:'Consolas','Courier New',monospace;font-size:%1px;").arg(sz);}-// ── Section header factory ─────────────────────────────────────────────────-static QWidget* make_section_hdr(const QString& title, const QString& accent = {}) {- auto* w = new QWidget;- w->setFixedHeight(22);- w->setStyleSheet(QString("background:#0d0d0d;border-top:1px solid #1a1a1a;"- "border-bottom:1px solid #1a1a1a;"));- auto* hl = new QHBoxLayout(w);- hl->setContentsMargins(10, 0, 10, 0);- hl->setSpacing(6);-- if (!accent.isEmpty()) {- auto* dot = new QLabel("■");- dot->setStyleSheet(QString("color:%1;font-size:7px;background:transparent;").arg(accent));- hl->addWidget(dot);- }-- auto* lbl = new QLabel(title);- lbl->setStyleSheet(QString("color:#555555;font-size:9px;font-weight:700;letter-spacing:1.2px;"- "background:transparent;%1")- .arg(mono(9)));- hl->addWidget(lbl);- hl->addStretch();- return w;-}--// ── Thin divider ──────────────────────────────────────────────────────────-static QFrame* make_divider() {- auto* f = new QFrame;- f->setFixedHeight(1);- f->setStyleSheet("background:#111111;border:none;");- return f;+static QString det_color(const QString& s) {+ static const char* pal[] = {"#d97706", "#06b6d4", "#10b981", "#8b5cf6", "#f97316",+ "#3b82f6", "#ec4899", "#14b8a6", "#84cc16", "#ef4444"};+ return pal[qHash(s) % 10];}ForumSidebarPanel::ForumSidebarPanel(QWidget* parent) : QWidget(parent) {@@ -54,183 +27,258 @@ ForumSidebarPanel::ForumSidebarPanel(QWidget* parent) : QWidget(parent) {}void ForumSidebarPanel::build_ui() {- setFixedWidth(210);- setStyleSheet("background:#080808;border-right:1px solid #111111;");+ setFixedWidth(240);+ setStyleSheet(QString("background:%1;border-right:1px solid %2;")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));auto* root = new QVBoxLayout(this);root->setContentsMargins(0, 0, 0, 0);root->setSpacing(0);- // ── Brand header ──────────────────────────────────────────────────────+ // ── Brand header with gradient accent ─────────────────────────────────────auto* brand = new QWidget;- brand->setFixedHeight(38);- brand->setStyleSheet("background:#0a0a0a;border-bottom:1px solid #111111;");- auto* brand_hl = new QHBoxLayout(brand);- brand_hl->setContentsMargins(10, 0, 10, 0);- brand_hl->setSpacing(8);+ brand->setFixedHeight(56);+ brand->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:0,y2:1,"+ "stop:0 #0f0f0f,stop:1 %1);"+ "border-bottom:1px solid %2;")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));+ auto* brand_vl = new QVBoxLayout(brand);+ brand_vl->setContentsMargins(16, 10, 16, 0);+ brand_vl->setSpacing(2);++ auto* brand_row = new QWidget;+ brand_row->setStyleSheet("background:transparent;");+ auto* brand_hl = new QHBoxLayout(brand_row);+ brand_hl->setContentsMargins(0, 0, 0, 0);+ brand_hl->setSpacing(10);auto* brand_icon = new QLabel("◈");- brand_icon->setStyleSheet(QString("color:%1;font-size:16px;background:transparent;").arg(ui::colors::AMBER));- auto* brand_vl = new QVBoxLayout;- brand_vl->setSpacing(0);- brand_vl->setContentsMargins(0, 0, 0, 0);- auto* brand_title = new QLabel("FINCEPT FORUM");- brand_title->setStyleSheet(QString("color:#e5e5e5;font-size:11px;font-weight:700;letter-spacing:0.5px;"- "background:transparent;%1")- .arg(mono(11)));- auto* brand_sub = new QLabel("COMMUNITY · LIVE");- brand_sub->setStyleSheet(QString("color:#333333;font-size:9px;letter-spacing:0.8px;"- "background:transparent;%1")- .arg(mono(9)));- brand_vl->addWidget(brand_title);- brand_vl->addWidget(brand_sub);+ brand_icon->setStyleSheet(+ QString("color:%1;font-size:20px;background:transparent;")+ .arg(ui::colors::AMBER));++ auto* brand_title = new QLabel("COMMUNITY");+ brand_title->setStyleSheet(+ QString("color:%1;font-size:13px;font-weight:700;letter-spacing:2px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(13)));brand_hl->addWidget(brand_icon);- brand_hl->addLayout(brand_vl, 1);+ brand_hl->addWidget(brand_title, 1);+ brand_vl->addWidget(brand_row);++ // Gradient accent line+ brand_accent_ = new QWidget;+ brand_accent_->setFixedHeight(2);+ brand_accent_->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:0.4 %2,stop:0.7 %3,stop:1 transparent);")+ .arg(ui::colors::AMBER, ui::colors::ORANGE, ui::colors::CYAN));+ brand_vl->addWidget(brand_accent_);+root->addWidget(brand);- // ── Search ────────────────────────────────────────────────────────────+ // ── My Profile card ───────────────────────────────────────────────────────+ auto* profile_card = new QWidget;+ profile_card->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));+ auto* pc_hl = new QHBoxLayout(profile_card);+ pc_hl->setContentsMargins(14, 12, 14, 12);+ pc_hl->setSpacing(12);++ avatar_lbl_ = new QLabel("?");+ avatar_lbl_->setFixedSize(36, 36);+ avatar_lbl_->setAlignment(Qt::AlignCenter);+ avatar_lbl_->setStyleSheet(+ QString("color:%1;font-size:14px;font-weight:700;background:%2;"+ "border-radius:18px;%3")+ .arg(ui::colors::BG_BASE, ui::colors::AMBER, M(14)));++ auto* profile_info = new QVBoxLayout;+ profile_info->setSpacing(1);+ profile_info->setContentsMargins(0, 0, 0, 0);++ profile_name_lbl_ = new QLabel("Loading...");+ profile_name_lbl_->setStyleSheet(+ QString("color:%1;font-size:12px;font-weight:700;background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(12)));++ profile_sub_lbl_ = new QLabel("...");+ profile_sub_lbl_->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(10)));++ profile_rep_lbl_ = new QLabel;+ profile_rep_lbl_->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;background:transparent;%2")+ .arg(ui::colors::AMBER, M(10)));++ profile_info->addWidget(profile_name_lbl_);+ profile_info->addWidget(profile_sub_lbl_);++ pc_hl->addWidget(avatar_lbl_);+ pc_hl->addLayout(profile_info, 1);+ pc_hl->addWidget(profile_rep_lbl_);+ root->addWidget(profile_card);++ // ── Search bar ────────────────────────────────────────────────────────────auto* search_wrap = new QWidget;- search_wrap->setFixedHeight(34);- search_wrap->setStyleSheet("background:#080808;border-bottom:1px solid #111111;");+ search_wrap->setFixedHeight(40);+ search_wrap->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));auto* search_hl = new QHBoxLayout(search_wrap);- search_hl->setContentsMargins(8, 5, 8, 5);- search_hl->setSpacing(4);+ search_hl->setContentsMargins(12, 6, 12, 6);+ search_hl->setSpacing(6);auto* search_icon = new QLabel("⌕");- search_icon->setStyleSheet("color:#333333;font-size:13px;background:transparent;");+ search_icon->setStyleSheet(+ QString("color:%1;font-size:14px;background:transparent;")+ .arg(ui::colors::TEXT_TERTIARY));search_icon->setFixedWidth(16);- auto* search_input = new QLineEdit;- search_input->setPlaceholderText("search posts...");- search_input->setStyleSheet(QString("QLineEdit{background:transparent;color:#888888;border:none;"- "font-size:11px;%1}"- "QLineEdit:focus{color:#e5e5e5;}"- "QLineEdit::placeholder{color:#2a2a2a;}")- .arg(mono(11)));-- auto* go_btn = new QPushButton("↵");- go_btn->setFixedSize(22, 22);- go_btn->setCursor(Qt::PointingHandCursor);- go_btn->setStyleSheet(QString("QPushButton{background:#111111;color:#555555;border:1px solid #1a1a1a;"- "font-size:12px;font-weight:700;%1}"- "QPushButton:hover{background:%2;color:#080808;border-color:%2;}")- .arg(mono(12), ui::colors::AMBER));-- connect(go_btn, &QPushButton::clicked, this,- [this, search_input]() { emit search_requested(search_input->text().trimmed()); });- connect(search_input, &QLineEdit::returnPressed, this,- [this, search_input]() { emit search_requested(search_input->text().trimmed()); });+ search_input_ = new QLineEdit;+ search_input_->setPlaceholderText("Search discussions...");+ search_input_->setStyleSheet(+ QString("QLineEdit{background:rgba(255,255,255,0.03);color:%1;"+ "border:1px solid %2;padding:3px 10px;"+ "font-size:11px;border-radius:3px;%3}"+ "QLineEdit:focus{border-color:%4;color:%5;"+ "background:rgba(255,255,255,0.05);}"+ "QLineEdit::placeholder{color:%6;}")+ .arg(ui::colors::TEXT_SECONDARY, ui::colors::BORDER_DIM,+ M(11), ui::colors::BORDER_BRIGHT,+ ui::colors::TEXT_PRIMARY, ui::colors::TEXT_DIM));++ connect(search_input_, &QLineEdit::returnPressed, this,+ [this]() { emit search_requested(search_input_->text().trimmed()); });search_hl->addWidget(search_icon);- search_hl->addWidget(search_input, 1);- search_hl->addWidget(go_btn);+ search_hl->addWidget(search_input_, 1);root->addWidget(search_wrap);- // ── Scrollable body ───────────────────────────────────────────────────+ // ── Scrollable body ───────────────────────────────────────────────────────auto* scroll = new QScrollArea;scroll->setWidgetResizable(true);scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);- scroll->setStyleSheet("QScrollArea{border:none;background:#080808;}"- "QScrollBar:vertical{width:0px;}");+ scroll->setStyleSheet(+ QString("QScrollArea{border:none;background:%1;}"+ "QScrollBar:vertical{width:0px;}")+ .arg(ui::colors::BG_BASE));auto* body = new QWidget;- body->setStyleSheet("background:#080808;");+ body->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* body_vl = new QVBoxLayout(body);body_vl->setContentsMargins(0, 0, 0, 0);body_vl->setSpacing(0);- // ── My profile card ───────────────────────────────────────────────────- body_vl->addWidget(make_section_hdr("MY PROFILE", ui::colors::CYAN));-- auto* profile_card = new QWidget;- profile_card->setFixedHeight(52);- profile_card->setStyleSheet("background:#0a0a0a;border-bottom:1px solid #111111;");- auto* pc_hl = new QHBoxLayout(profile_card);- pc_hl->setContentsMargins(10, 6, 10, 6);- pc_hl->setSpacing(10);-- // Avatar circle- avatar_lbl_ = new QLabel;- avatar_lbl_->setFixedSize(32, 32);- avatar_lbl_->setAlignment(Qt::AlignCenter);- avatar_lbl_->setStyleSheet(QString("color:#080808;font-size:13px;font-weight:700;background:%1;"- "border-radius:0px;%2")- .arg(ui::colors::AMBER, mono(13)));- avatar_lbl_->setText("?");-- auto* profile_right = new QVBoxLayout;- profile_right->setSpacing(2);- profile_right->setContentsMargins(0, 0, 0, 0);-- profile_name_lbl_ = new QLabel("—");- profile_name_lbl_->setStyleSheet(- QString("color:#e5e5e5;font-size:12px;font-weight:700;background:transparent;%1").arg(mono(12)));-- profile_sub_lbl_ = new QLabel("REP 0 · 0 POSTS");- profile_sub_lbl_->setStyleSheet(QString("color:#333333;font-size:10px;background:transparent;%1").arg(mono(10)));-- profile_right->addWidget(profile_name_lbl_);- profile_right->addWidget(profile_sub_lbl_);-- pc_hl->addWidget(avatar_lbl_);- pc_hl->addLayout(profile_right, 1);- body_vl->addWidget(profile_card);-- // ── Community stats ───────────────────────────────────────────────────- body_vl->addWidget(make_section_hdr("COMMUNITY STATS", ui::colors::AMBER));-- // Stats grid — 2x2- auto* stats_grid = new QWidget;- stats_grid->setStyleSheet("background:#0a0a0a;border-bottom:1px solid #111111;");- auto* sg_grid = new QHBoxLayout(stats_grid);- sg_grid->setContentsMargins(0, 0, 0, 0);- sg_grid->setSpacing(0);-- auto make_stat_cell = [&](const QString& label, QLabel*& val_out) -> QWidget* {+ // ── Quick stats row ───────────────────────────────────────────────────────+ auto* stats_hdr = new QWidget;+ stats_hdr->setFixedHeight(22);+ stats_hdr->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));+ auto* sh_hl = new QHBoxLayout(stats_hdr);+ sh_hl->setContentsMargins(14, 0, 14, 0);+ auto* sh_lbl = new QLabel("ACTIVITY");+ sh_lbl->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;letter-spacing:1.5px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(9)));+ sh_hl->addWidget(sh_lbl);+ sh_hl->addStretch();+ body_vl->addWidget(stats_hdr);++ auto* stats_row = new QWidget;+ stats_row->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));+ auto* sr_hl = new QHBoxLayout(stats_row);+ sr_hl->setContentsMargins(0, 0, 0, 0);+ sr_hl->setSpacing(0);++ auto mk_mini_stat = [&](const QString& label, const QString& color,+ QLabel*& out) -> QWidget* {auto* cell = new QWidget;- cell->setStyleSheet("background:transparent;border-right:1px solid #111111;");- auto* vl = new QVBoxLayout(cell);- vl->setContentsMargins(10, 8, 10, 8);- vl->setSpacing(2);- val_out = new QLabel("—");- val_out->setStyleSheet(- QString("color:#e5e5e5;font-size:14px;font-weight:700;background:transparent;%1").arg(mono(14)));- auto* lbl = new QLabel(label);- lbl->setStyleSheet(- QString("color:#333333;font-size:9px;letter-spacing:0.5px;background:transparent;%1").arg(mono(9)));- vl->addWidget(val_out);- vl->addWidget(lbl);+ cell->setStyleSheet("background:transparent;");+ auto* cvl = new QVBoxLayout(cell);+ cvl->setContentsMargins(14, 8, 14, 8);+ cvl->setSpacing(1);+ out = new QLabel("--");+ out->setStyleSheet(+ QString("color:%1;font-size:16px;font-weight:700;background:transparent;%2")+ .arg(color, M(16)));+ auto* l = new QLabel(label);+ l->setStyleSheet(+ QString("color:%1;font-size:8px;letter-spacing:0.8px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(8)));+ cvl->addWidget(out);+ cvl->addWidget(l);return cell;};- sg_grid->addWidget(make_stat_cell("POSTS", stat_posts_val_));- sg_grid->addWidget(make_stat_cell("COMMENTS", stat_comments_val_));- sg_grid->addWidget(make_stat_cell("VOTES", stat_votes_val_));- auto* last_cell = make_stat_cell("24H", stat_24h_val_);- last_cell->setStyleSheet("background:transparent;");- sg_grid->addWidget(last_cell);- body_vl->addWidget(stats_grid);+ sr_hl->addWidget(mk_mini_stat("POSTS", ui::colors::TEXT_PRIMARY, stat_posts_val_));+ sr_hl->addWidget(mk_mini_stat("REPLIES", ui::colors::CYAN, stat_comments_val_));+ sr_hl->addWidget(mk_mini_stat("TODAY", ui::colors::AMBER, stat_active_val_));+ body_vl->addWidget(stats_row);- // ── Navigation ────────────────────────────────────────────────────────- body_vl->addWidget(make_section_hdr("NAVIGATE", "#555555"));-- // Trending button+ // ── Trending button ───────────────────────────────────────────────────────auto* trending_btn = new QPushButton;- trending_btn->setFixedHeight(30);+ trending_btn->setFixedHeight(34);trending_btn->setCursor(Qt::PointingHandCursor);- trending_btn->setStyleSheet(QString("QPushButton{background:transparent;color:#888888;border:none;"- "border-bottom:1px solid #111111;text-align:left;padding:0 10px;"- "font-size:11px;%1}"- "QPushButton:hover{background:#0d0d0d;color:#e5e5e5;}")- .arg(mono(11)));- trending_btn->setText(" ▲ TRENDING");- connect(trending_btn, &QPushButton::clicked, this, &ForumSidebarPanel::trending_clicked);+ trending_btn->setText(" ▲ TRENDING POSTS");+ trending_btn->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.04);color:%1;border:none;"+ "border-bottom:1px solid %2;text-align:left;padding:0 14px;"+ "font-size:11px;font-weight:600;%3}"+ "QPushButton:hover{background:rgba(217,119,6,0.1);color:%4;}")+ .arg(ui::colors::TEXT_SECONDARY, ui::colors::BORDER_DIM,+ M(11), ui::colors::AMBER));+ connect(trending_btn, &QPushButton::clicked, this,+ &ForumSidebarPanel::trending_clicked);body_vl->addWidget(trending_btn);- // ── Categories ────────────────────────────────────────────────────────- body_vl->addWidget(make_section_hdr("CHANNELS", ui::colors::ORANGE));+ // ── Channels section ──────────────────────────────────────────────────────+ auto* chan_hdr = new QWidget;+ chan_hdr->setFixedHeight(26);+ chan_hdr->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));+ auto* ch_hl = new QHBoxLayout(chan_hdr);+ ch_hl->setContentsMargins(14, 0, 14, 0);+ ch_hl->setSpacing(6);+ auto* ch_dot = new QLabel("●");+ ch_dot->setStyleSheet(+ QString("color:%1;font-size:6px;background:transparent;")+ .arg(ui::colors::AMBER));+ auto* ch_lbl = new QLabel("CHANNELS");+ ch_lbl->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;letter-spacing:1.5px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(9)));++ auto* new_post_btn = new QPushButton("+");+ new_post_btn->setFixedSize(18, 18);+ new_post_btn->setCursor(Qt::PointingHandCursor);+ new_post_btn->setToolTip("New post");+ new_post_btn->setStyleSheet(+ QString("QPushButton{background:transparent;color:%1;border:none;"+ "font-size:14px;font-weight:700;%2}"+ "QPushButton:hover{color:%3;}")+ .arg(ui::colors::TEXT_DIM, M(14), ui::colors::AMBER));+ connect(new_post_btn, &QPushButton::clicked, this, [this]() {+ int cat_id = active_category_id_ > 0 ? active_category_id_ : 1;+ emit new_post_requested(cat_id);+ });++ ch_hl->addWidget(ch_dot);+ ch_hl->addWidget(ch_lbl);+ ch_hl->addStretch();+ ch_hl->addWidget(new_post_btn);+ body_vl->addWidget(chan_hdr);cat_container_ = new QWidget;cat_container_->setStyleSheet("background:transparent;");@@ -239,8 +287,29 @@ void ForumSidebarPanel::build_ui() {cat_layout_->setSpacing(0);body_vl->addWidget(cat_container_);- // ── Top contributors ─────────────────────────────────────────────────- body_vl->addWidget(make_section_hdr("TOP CONTRIBUTORS", ui::colors::CYAN));+ // ── Leaderboard section ───────────────────────────────────────────────────+ auto* lb_hdr = new QWidget;+ lb_hdr->setFixedHeight(26);+ lb_hdr->setStyleSheet(+ QString("background:%1;border-top:1px solid %2;"+ "border-bottom:1px solid %2;")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));+ auto* lb_hl = new QHBoxLayout(lb_hdr);+ lb_hl->setContentsMargins(14, 0, 14, 0);+ lb_hl->setSpacing(6);+ auto* lb_dot = new QLabel("★");+ lb_dot->setStyleSheet(+ QString("color:%1;font-size:8px;background:transparent;")+ .arg(ui::colors::AMBER));+ auto* lb_lbl = new QLabel("LEADERBOARD");+ lb_lbl->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;letter-spacing:1.5px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(9)));+ lb_hl->addWidget(lb_dot);+ lb_hl->addWidget(lb_lbl);+ lb_hl->addStretch();+ body_vl->addWidget(lb_hdr);contrib_container_ = new QWidget;contrib_container_->setStyleSheet("background:transparent;");@@ -248,10 +317,11 @@ void ForumSidebarPanel::build_ui() {contrib_layout_->setContentsMargins(0, 0, 0, 0);contrib_layout_->setSpacing(0);- // Placeholder rowauto* ph = new QLabel(" loading...");- ph->setFixedHeight(26);- ph->setStyleSheet(QString("color:#222222;font-size:10px;background:transparent;%1").arg(mono(10)));+ ph->setFixedHeight(28);+ ph->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(10)));contrib_layout_->addWidget(ph);body_vl->addWidget(contrib_container_);@@ -260,99 +330,50 @@ void ForumSidebarPanel::build_ui() {root->addWidget(scroll, 1);}+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+// Data setters+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━void ForumSidebarPanel::set_my_profile(const services::ForumProfile& profile) {- if (profile_name_lbl_)- profile_name_lbl_->setText(profile.display_name.toUpper().left(14));- if (profile_sub_lbl_)- profile_sub_lbl_->setText(QString("REP %1 · %2 POSTS").arg(profile.reputation).arg(profile.posts_count));-- if (avatar_lbl_) {- QString color = profile.avatar_color.isEmpty() ? ui::colors::AMBER : profile.avatar_color;- QString initials = profile.display_name.isEmpty() ? "?" : profile.display_name.left(2).toUpper();- avatar_lbl_->setText(initials);- avatar_lbl_->setStyleSheet(QString("color:#080808;font-size:11px;font-weight:700;background:%1;"- "border-radius:0px;%2")- .arg(color, mono(11)));- }+ QString color = profile.avatar_color.isEmpty() ? ui::colors::AMBER+ : profile.avatar_color;+ QString initials = profile.display_name.isEmpty()+ ? "?"+ : profile.display_name.left(2).toUpper();+ avatar_lbl_->setText(initials);+ avatar_lbl_->setStyleSheet(+ QString("color:%1;font-size:14px;font-weight:700;background:%2;"+ "border-radius:18px;%3")+ .arg(ui::colors::BG_BASE, color, M(14)));++ profile_name_lbl_->setText(profile.display_name);+ profile_sub_lbl_->setText("@" + profile.username);+ profile_rep_lbl_->setText(QString("★ %1").arg(profile.reputation));}void ForumSidebarPanel::set_stats(const services::ForumStats& stats) {cached_stats_ = stats;- auto set_val = [](QLabel* lbl, const QString& v) {- if (lbl)- lbl->setText(v);- };-- // Format large numbersauto fmt = [](int n) -> QString {- if (n >= 1000)+ if (n >= 10000)return QString("%1K").arg(n / 1000);+ if (n >= 1000)+ return QString("%1.%2K").arg(n / 1000).arg((n % 1000) / 100);return QString::number(n);};- set_val(stat_posts_val_, fmt(stats.total_posts));- set_val(stat_comments_val_, fmt(stats.total_comments));- set_val(stat_votes_val_, fmt(stats.total_votes));- set_val(stat_24h_val_, QString::number(stats.recent_posts_24h));+ if (stat_posts_val_)+ stat_posts_val_->setText(fmt(stats.total_posts));+ if (stat_comments_val_)+ stat_comments_val_->setText(fmt(stats.total_comments));+ if (stat_active_val_)+ stat_active_val_->setText(QString::number(stats.recent_posts_24h));- // Rebuild contributorscontributors_ = stats.top_contributors;rebuild_contributors();}-void ForumSidebarPanel::rebuild_contributors() {- // Clear- while (contrib_layout_->count() > 0) {- auto* item = contrib_layout_->takeAt(0);- if (item->widget())- item->widget()->deleteLater();- delete item;- }-- if (contributors_.isEmpty()) {- auto* ph = new QLabel(" —");- ph->setFixedHeight(26);- ph->setStyleSheet(QString("color:#222222;font-size:10px;background:transparent;%1").arg(mono(10)));- contrib_layout_->addWidget(ph);- return;- }-- static const QString rank_colors[] = {ui::colors::AMBER, "#aaaaaa", "#cd7f32", "#555555", "#555555"};-- for (int i = 0; i < std::min(5, (int)contributors_.size()); ++i) {- const auto& c = contributors_[i];- auto* row = new QWidget;- row->setFixedHeight(26);- row->setStyleSheet("background:#080808;border-bottom:1px solid #0d0d0d;");- auto* hl = new QHBoxLayout(row);- hl->setContentsMargins(10, 0, 10, 0);- hl->setSpacing(6);-- // Rank badge- auto* rank = new QLabel(QString::number(i + 1));- rank->setFixedWidth(14);- rank->setAlignment(Qt::AlignCenter);- rank->setStyleSheet(- QString("color:%1;font-size:9px;font-weight:700;background:transparent;%2").arg(rank_colors[i], mono(9)));-- // Name- auto* name = new QLabel(c.display_name.left(14));- name->setStyleSheet(QString("color:#888888;font-size:11px;background:transparent;%1").arg(mono(11)));-- // Rep chip- auto* rep = new QLabel(QString("▲%1").arg(c.reputation));- rep->setStyleSheet(QString("color:%1;font-size:10px;background:transparent;%2").arg(rank_colors[i], mono(10)));- rep->setAlignment(Qt::AlignRight | Qt::AlignVCenter);-- hl->addWidget(rank);- hl->addWidget(name, 1);- hl->addWidget(rep);- contrib_layout_->addWidget(row);- }-}--void ForumSidebarPanel::set_categories(const QVector<services::ForumCategory>& cats) {+void ForumSidebarPanel::set_categories(+ const QVector<services::ForumCategory>& cats) {categories_ = cats;rebuild_categories();}@@ -366,6 +387,9 @@ void ForumSidebarPanel::set_loading(bool on) {Q_UNUSED(on)}+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+// Categories+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━void ForumSidebarPanel::rebuild_categories() {while (cat_layout_->count() > 0) {auto* item = cat_layout_->takeAt(0);@@ -376,67 +400,155 @@ void ForumSidebarPanel::rebuild_categories() {for (const auto& cat : categories_) {const bool active = (cat.id == active_category_id_);- QString color = cat.color.isEmpty() ? ui::colors::ORANGE : cat.color;+ QString color = cat.color.isEmpty() ? ui::colors::AMBER : cat.color;auto* row = new QWidget;- row->setFixedHeight(30);+ row->setFixedHeight(34);row->setCursor(Qt::PointingHandCursor);row->setStyleSheet(- active ? QString("background:#0d0d0d;border-bottom:1px solid #111111;"- "border-left:2px solid %1;")- .arg(color)- : "background:transparent;border-bottom:1px solid #0d0d0d;border-left:2px solid transparent;");+ active+ ? QString("background:rgba(255,255,255,0.03);"+ "border-bottom:1px solid %1;"+ "border-left:2px solid %2;")+ .arg(ui::colors::BORDER_DIM, color)+ : QString("background:transparent;"+ "border-bottom:1px solid %1;"+ "border-left:2px solid transparent;")+ .arg(ui::colors::BORDER_DIM));auto* hl = new QHBoxLayout(row);- hl->setContentsMargins(8, 0, 6, 0);- hl->setSpacing(6);+ hl->setContentsMargins(10, 0, 10, 0);+ hl->setSpacing(8);- // Color chip- auto* chip = new QLabel("●");- chip->setFixedWidth(10);- chip->setStyleSheet(QString("color:%1;font-size:8px;background:transparent;").arg(color));+ // Hash icon+ auto* hash = new QLabel("#");+ hash->setFixedWidth(14);+ hash->setStyleSheet(+ QString("color:%1;font-size:13px;font-weight:600;background:transparent;%2")+ .arg(active ? ui::colors::TEXT_SECONDARY : ui::colors::TEXT_DIM,+ M(13)));// Name- auto* name_lbl = new QLabel(cat.name.toUpper());+ auto* name_lbl = new QLabel(cat.name.toLower().replace(' ', '-'));name_lbl->setStyleSheet(- active ? QString("color:#e5e5e5;font-size:11px;font-weight:700;background:transparent;%1").arg(mono(11))- : QString("color:#555555;font-size:11px;background:transparent;%1").arg(mono(11)));-- // Post count- auto* count_lbl = new QLabel(QString::number(cat.post_count));- count_lbl->setStyleSheet(QString("color:#333333;font-size:10px;background:transparent;%1").arg(mono(10)));- count_lbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);- count_lbl->setFixedWidth(28);-- // "+" new post — appears on hover (always visible but dim)- auto* new_btn = new QPushButton("+");- new_btn->setFixedSize(20, 20);- new_btn->setCursor(Qt::PointingHandCursor);- new_btn->setToolTip("New post in " + cat.name);- new_btn->setStyleSheet(QString("QPushButton{background:transparent;color:#2a2a2a;border:none;"- "font-size:13px;font-weight:700;%1}"- "QPushButton:hover{color:%2;background:rgba(217,119,6,0.1);}")- .arg(mono(13), ui::colors::AMBER));- connect(new_btn, &QPushButton::clicked, this, [this, cat]() { emit new_post_requested(cat.id); });-- // Click entire row to select+ active+ ? QString("color:%1;font-size:12px;font-weight:600;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(12))+ : QString("color:%1;font-size:12px;background:transparent;%2")+ .arg(ui::colors::TEXT_SECONDARY, M(12)));++ // Post count badge+ auto* count_lbl = new QLabel;+ if (cat.post_count > 0) {+ count_lbl->setText(QString::number(cat.post_count));+ count_lbl->setFixedHeight(18);+ count_lbl->setMinimumWidth(24);+ count_lbl->setAlignment(Qt::AlignCenter);+ count_lbl->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;"+ "background:rgba(255,255,255,0.04);"+ "border-radius:9px;padding:0 6px;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(9)));+ }++ // Click handlerauto* click_btn = new QPushButton(row);- click_btn->setGeometry(0, 0, 2000, 30);+ click_btn->setGeometry(0, 0, 2000, 34);click_btn->setFlat(true);click_btn->setStyleSheet("QPushButton{background:transparent;border:none;}");click_btn->lower();connect(click_btn, &QPushButton::clicked, this, [this, cat]() {- active_cat_for_post_ = cat.id;set_active_category(cat.id);emit category_selected(cat.id, cat.name, cat.color);});- hl->addWidget(chip);+ hl->addWidget(hash);hl->addWidget(name_lbl, 1);- hl->addWidget(count_lbl);- hl->addWidget(new_btn);+ if (cat.post_count > 0)+ hl->addWidget(count_lbl);cat_layout_->addWidget(row);}}+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+// Leaderboard+// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+void ForumSidebarPanel::rebuild_contributors() {+ while (contrib_layout_->count() > 0) {+ auto* item = contrib_layout_->takeAt(0);+ if (item->widget())+ item->widget()->deleteLater();+ delete item;+ }++ if (contributors_.isEmpty()) {+ auto* ph = new QLabel(" No contributors yet");+ ph->setFixedHeight(28);+ ph->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(10)));+ contrib_layout_->addWidget(ph);+ return;+ }++ // Medal icons for top 3+ static const char* medals[] = {"🥇", "🥈", "🥉", " 4", " 5"};+ static const char* rank_colors[] = {"#d97706", "#94a3b8", "#cd7f32",+ "#525252", "#525252"};++ for (int i = 0; i < std::min(5, (int)contributors_.size()); ++i) {+ const auto& c = contributors_[i];+ auto* row = new QWidget;+ row->setFixedHeight(32);+ row->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(i % 2 == 0 ? ui::colors::BG_BASE : ui::colors::BG_SURFACE,+ ui::colors::BORDER_DIM));+ auto* hl = new QHBoxLayout(row);+ hl->setContentsMargins(14, 0, 14, 0);+ hl->setSpacing(8);++ // Rank+ auto* rank = new QLabel(i < 3 ? medals[i] : QString::number(i + 1));+ rank->setFixedWidth(18);+ rank->setAlignment(Qt::AlignCenter);+ rank->setStyleSheet(+ QString("color:%1;font-size:%2px;font-weight:700;"+ "background:transparent;%3")+ .arg(rank_colors[i])+ .arg(i < 3 ? 12 : 10)+ .arg(M(i < 3 ? 12 : 10)));++ // Avatar+ auto* av = new QLabel(c.display_name.left(1).toUpper());+ av->setFixedSize(22, 22);+ av->setAlignment(Qt::AlignCenter);+ av->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;background:%2;"+ "border-radius:11px;%3")+ .arg(ui::colors::BG_BASE, det_color(c.display_name), M(10)));++ // Name+ auto* name = new QLabel(c.display_name.left(12));+ name->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_SECONDARY, M(11)));++ // Rep+ auto* rep = new QLabel(QString("★%1").arg(c.reputation));+ rep->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:600;"+ "background:transparent;%2")+ .arg(rank_colors[i], M(10)));+ rep->setAlignment(Qt::AlignRight | Qt::AlignVCenter);++ hl->addWidget(rank);+ hl->addWidget(av);+ hl->addWidget(name, 1);+ hl->addWidget(rep);+ contrib_layout_->addWidget(row);+ }+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/forum/ForumSidebarPanel.h b/fincept-qt/src/screens/forum/ForumSidebarPanel.hindex edf613894..42563d83e 100644--- a/fincept-qt/src/screens/forum/ForumSidebarPanel.h+++ b/fincept-qt/src/screens/forum/ForumSidebarPanel.h@@ -3,6 +3,7 @@#include "services/forum/ForumModels.h"#include <QLabel>+#include <QLineEdit>#include <QVBoxLayout>#include <QVector>#include <QWidget>@@ -30,20 +31,23 @@ class ForumSidebarPanel : public QWidget {void build_ui();void rebuild_categories();void rebuild_contributors();- void update_activity_bars();++ // Brand+ QWidget* brand_accent_ = nullptr;// Profile cardQLabel* avatar_lbl_ = nullptr;QLabel* profile_name_lbl_ = nullptr;QLabel* profile_sub_lbl_ = nullptr;+ QLabel* profile_rep_lbl_ = nullptr;++ // Search+ QLineEdit* search_input_ = nullptr;- // Stats gauges+ // StatsQLabel* stat_posts_val_ = nullptr;QLabel* stat_comments_val_ = nullptr;- QLabel* stat_votes_val_ = nullptr;- QLabel* stat_24h_val_ = nullptr;- QWidget* stat_posts_bar_ = nullptr;- QWidget* stat_activity_bar_ = nullptr;+ QLabel* stat_active_val_ = nullptr;// CategoriesQVBoxLayout* cat_layout_ = nullptr;@@ -57,7 +61,6 @@ class ForumSidebarPanel : public QWidget {QVector<services::ForumContributor> contributors_;services::ForumStats cached_stats_;int active_category_id_ = -1;- int active_cat_for_post_ = 0;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/forum/ForumThreadPanel.cpp b/fincept-qt/src/screens/forum/ForumThreadPanel.cppindex b4ca861e5..e422b9b62 100644--- a/fincept-qt/src/screens/forum/ForumThreadPanel.cpp+++ b/fincept-qt/src/screens/forum/ForumThreadPanel.cpp@@ -1,6 +1,7 @@// src/screens/forum/ForumThreadPanel.cpp#include "screens/forum/ForumThreadPanel.h"+#include "core/logging/Logger.h"#include "ui/theme/Theme.h"#include <QDateTime>@@ -46,7 +47,7 @@ ForumThreadPanel::ForumThreadPanel(QWidget* parent) : QWidget(parent) {}void ForumThreadPanel::build_ui() {- setStyleSheet("background:#080808;");+ setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* root = new QVBoxLayout(this);root->setContentsMargins(0, 0, 0, 0);root->setSpacing(0);@@ -55,14 +56,27 @@ void ForumThreadPanel::build_ui() {// ── Page 0: Loading ───────────────────────────────────────────────────────auto* load_page = new QWidget;- load_page->setStyleSheet("background:#080808;");+ load_page->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));{auto* vl = new QVBoxLayout(load_page);+ vl->setAlignment(Qt::AlignCenter);+ vl->setSpacing(12);+spin_lbl_ = new QLabel("⣾");spin_lbl_->setAlignment(Qt::AlignCenter);- spin_lbl_->setStyleSheet(QString("color:#d97706;font-size:24px;background:transparent;%1").arg(M(24)));+ spin_lbl_->setStyleSheet(+ QString("color:%1;font-size:28px;background:transparent;%2")+ .arg(ui::colors::AMBER, M(28)));++ auto* loading_text = new QLabel("Loading thread...");+ loading_text->setAlignment(Qt::AlignCenter);+ loading_text->setStyleSheet(+ QString("color:%1;font-size:11px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));+vl->addStretch();vl->addWidget(spin_lbl_);+ vl->addWidget(loading_text);vl->addStretch();}stack_->addWidget(load_page); // 0@@ -76,27 +90,35 @@ void ForumThreadPanel::build_ui() {// ── Page 1: Thread view ───────────────────────────────────────────────────thread_page_ = new QWidget;- thread_page_->setStyleSheet("background:#080808;");+ thread_page_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* tp = new QVBoxLayout(thread_page_);tp->setContentsMargins(0, 0, 0, 0);tp->setSpacing(0);- // ── Back bar ──────────────────────────────────────────────────────────────+ // ── Back bar with gradient accent ─────────────────────────────────────────auto* back_bar = new QWidget;- back_bar->setFixedHeight(32);- back_bar->setStyleSheet("background:#060606;border-bottom:1px solid #0f0f0f;");+ back_bar->setFixedHeight(38);+ back_bar->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));auto* bb_hl = new QHBoxLayout(back_bar);bb_hl->setContentsMargins(16, 0, 16, 0);- bb_hl->setSpacing(8);+ bb_hl->setSpacing(10);- auto* back_btn = new QPushButton("← BACK TO FEED");+ auto* back_btn = new QPushButton("← Back to Feed");back_btn->setCursor(Qt::PointingHandCursor);- back_btn->setFixedHeight(32);- back_btn->setStyleSheet(QString("QPushButton{background:transparent;color:#333333;border:none;"- "font-size:11px;font-weight:700;letter-spacing:0.5px;padding:0 4px;%1}"- "QPushButton:hover{color:#888888;}")- .arg(M(11)));- connect(back_btn, &QPushButton::clicked, this, [this]() { emit back_requested(); });+ back_btn->setFixedHeight(28);+ back_btn->setStyleSheet(+ QString("QPushButton{background:rgba(255,255,255,0.03);"+ "color:%1;border:1px solid %2;"+ "font-size:11px;font-weight:600;padding:0 14px;"+ "border-radius:4px;%3}"+ "QPushButton:hover{color:%4;border-color:%5;"+ "background:rgba(255,255,255,0.06);}")+ .arg(ui::colors::TEXT_SECONDARY, ui::colors::BORDER_DIM,+ M(11), ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED));+ connect(back_btn, &QPushButton::clicked, this,+ [this]() { emit back_requested(); });bb_hl->addWidget(back_btn);bb_hl->addStretch();@@ -106,80 +128,103 @@ void ForumThreadPanel::build_ui() {auto* scroll = new QScrollArea;scroll->setWidgetResizable(true);scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);- scroll->setStyleSheet("QScrollArea{border:none;background:#080808;}"- "QScrollBar:vertical{width:4px;background:transparent;margin:0;}"- "QScrollBar::handle:vertical{background:#151515;min-height:30px;}"- "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}");+ scroll->setStyleSheet(+ QString("QScrollArea{border:none;background:%1;}"+ "QScrollBar:vertical{width:6px;background:transparent;margin:0;}"+ "QScrollBar::handle:vertical{background:%2;min-height:40px;"+ "border-radius:3px;}"+ "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical"+ "{height:0;}")+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_DIM));auto* sw = new QWidget;- sw->setStyleSheet("background:#080808;");+ sw->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* svl = new QVBoxLayout(sw);svl->setContentsMargins(0, 0, 0, 0);svl->setSpacing(0);- // ── Post header — centered, wide ──────────────────────────────────────────+ // ── Post hero header — centered, max 860px ────────────────────────────────auto* hdr_outer = new QWidget;- hdr_outer->setStyleSheet("background:#080808;");+ hdr_outer->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:0,y2:1,"+ "stop:0 #0e0e0e,stop:1 %1);")+ .arg(ui::colors::BG_BASE));auto* hdr_outer_hl = new QHBoxLayout(hdr_outer);hdr_outer_hl->setContentsMargins(0, 0, 0, 0);- hdr_outer_hl->setSpacing(0);auto* hdr_w = new QWidget;- hdr_w->setMaximumWidth(800);- hdr_w->setStyleSheet("background:#080808;border-bottom:1px solid #0f0f0f;");+ hdr_w->setMaximumWidth(860);+ hdr_w->setStyleSheet("background:transparent;");auto* hdr_vl = new QVBoxLayout(hdr_w);- hdr_vl->setContentsMargins(32, 20, 32, 16);- hdr_vl->setSpacing(10);+ hdr_vl->setContentsMargins(32, 24, 32, 20);+ hdr_vl->setSpacing(12);// Category chip + time rowauto* chip_row = new QWidget;chip_row->setStyleSheet("background:transparent;");auto* chip_hl = new QHBoxLayout(chip_row);chip_hl->setContentsMargins(0, 0, 0, 0);- chip_hl->setSpacing(10);+ chip_hl->setSpacing(12);t_cat_chip_ = new QLabel;- t_cat_chip_->setStyleSheet(QString("color:#d97706;font-size:9px;font-weight:700;letter-spacing:0.8px;"- "background:transparent;border:1px solid rgba(217,119,6,0.4);"- "padding:2px 8px;%1")- .arg(M(9)));+ t_cat_chip_->setFixedHeight(20);+ t_cat_chip_->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;letter-spacing:1px;"+ "background:transparent;border:1px solid %1;"+ "padding:2px 10px;border-radius:10px;%2")+ .arg(ui::colors::AMBER, M(9)));t_meta_lbl_ = new QLabel;- t_meta_lbl_->setStyleSheet(QString("color:#666666;font-size:10px;background:transparent;%1").arg(M(10)));+ t_meta_lbl_->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(10)));chip_hl->addWidget(t_cat_chip_);chip_hl->addStretch();chip_hl->addWidget(t_meta_lbl_);hdr_vl->addWidget(chip_row);- // Title — large+ // Title — hero sizet_title_lbl_ = new QLabel;t_title_lbl_->setWordWrap(true);- t_title_lbl_->setStyleSheet(QString("color:#e5e5e5;font-size:18px;font-weight:700;line-height:1.3;"- "background:transparent;%1")- .arg(M(18)));+ t_title_lbl_->setStyleSheet(+ QString("color:%1;font-size:22px;font-weight:700;line-height:1.3;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(22)));hdr_vl->addWidget(t_title_lbl_);- // Author row with avatar+ // Author row with circular avatart_author_lbl_ = new QLabel;t_author_lbl_->setTextFormat(Qt::RichText);t_author_lbl_->setTextInteractionFlags(Qt::TextBrowserInteraction);t_author_lbl_->setOpenExternalLinks(false);- t_author_lbl_->setStyleSheet(QString("color:#444444;font-size:11px;background:transparent;%1").arg(M(11)));- connect(t_author_lbl_, &QLabel::linkActivated, this, [this](const QString& link) {- if (link.startsWith("author:"))- emit author_clicked(link.mid(7));- });+ t_author_lbl_->setStyleSheet(+ QString("color:%1;font-size:12px;background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(12)));+ connect(t_author_lbl_, &QLabel::linkActivated, this,+ [this](const QString& link) {+ if (link.startsWith("author:"))+ emit author_clicked(link.mid(7));+ });hdr_vl->addWidget(t_author_lbl_);+ // Gradient separator+ auto* hdr_sep = new QWidget;+ hdr_sep->setFixedHeight(2);+ hdr_sep->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:0.4 %2,stop:1 transparent);")+ .arg(ui::colors::AMBER, ui::colors::BORDER_DIM));+ hdr_vl->addWidget(hdr_sep);+hdr_outer_hl->addStretch();hdr_outer_hl->addWidget(hdr_w, 1);hdr_outer_hl->addStretch();svl->addWidget(hdr_outer);- // ── Post body — centered column ──────────────────────────────────────────+ // ── Post body — centered, max 860px ───────────────────────────────────────auto* body_outer = new QWidget;- body_outer->setStyleSheet("background:#080808;");+ body_outer->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* body_outer_hl = new QHBoxLayout(body_outer);body_outer_hl->setContentsMargins(0, 0, 0, 0);@@ -187,52 +232,71 @@ void ForumThreadPanel::build_ui() {t_body_lbl_->setWordWrap(true);t_body_lbl_->setTextFormat(Qt::PlainText);t_body_lbl_->setAlignment(Qt::AlignTop | Qt::AlignLeft);- t_body_lbl_->setMaximumWidth(800);- t_body_lbl_->setStyleSheet(QString("color:#777777;font-size:13px;line-height:1.8;background:transparent;"- "padding:24px 32px;%1")- .arg(M(13)));+ t_body_lbl_->setMaximumWidth(860);+ t_body_lbl_->setStyleSheet(+ QString("color:%1;font-size:13px;line-height:1.8;background:transparent;"+ "padding:20px 32px;%2")+ .arg(ui::colors::TEXT_SECONDARY, M(13)));body_outer_hl->addStretch();body_outer_hl->addWidget(t_body_lbl_, 1);body_outer_hl->addStretch();svl->addWidget(body_outer);- // ── Engagement bar — centered ─────────────────────────────────────────────+ // ── Engagement bar — centered, modern pill buttons ────────────────────────auto* eng_outer = new QWidget;- eng_outer->setStyleSheet("background:#060606;border-top:1px solid #0f0f0f;"- "border-bottom:1px solid #0f0f0f;");- eng_outer->setFixedHeight(38);+ eng_outer->setFixedHeight(48);+ eng_outer->setStyleSheet(+ QString("background:%1;border-top:1px solid %2;"+ "border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));auto* eng_outer_hl = new QHBoxLayout(eng_outer);eng_outer_hl->setContentsMargins(0, 0, 0, 0);auto* eng_w = new QWidget;- eng_w->setMaximumWidth(800);+ eng_w->setMaximumWidth(860);eng_w->setStyleSheet("background:transparent;");auto* eng_hl = new QHBoxLayout(eng_w);eng_hl->setContentsMargins(32, 0, 32, 0);- eng_hl->setSpacing(0);+ eng_hl->setSpacing(12);- auto* up_btn = new QPushButton("▲ UPVOTE");- up_btn->setFixedSize(90, 26);+ auto* up_btn = new QPushButton("▲ Upvote");+ up_btn->setFixedHeight(30);up_btn->setCursor(Qt::PointingHandCursor);- up_btn->setStyleSheet(QString("QPushButton{background:transparent;color:#666666;"- "border:1px solid #161616;font-size:10px;font-weight:700;%1}"- "QPushButton:hover{color:#d97706;border-color:rgba(217,119,6,0.4);"- "background:rgba(217,119,6,0.06);}")- .arg(M(10)));+ up_btn->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.06);"+ "color:%1;border:1px solid rgba(217,119,6,0.2);"+ "font-size:11px;font-weight:700;padding:0 16px;"+ "border-radius:15px;%2}"+ "QPushButton:hover{color:%3;"+ "border-color:rgba(217,119,6,0.5);"+ "background:rgba(217,119,6,0.12);}"+ "QPushButton:pressed{color:%3;"+ "border-color:%3;"+ "background:rgba(217,119,6,0.25);}")+ .arg(ui::colors::TEXT_SECONDARY, M(11), ui::colors::AMBER));connect(up_btn, &QPushButton::clicked, this, [this]() {+ LOG_INFO("ForumThread", "Upvote clicked, uuid=" + current_.post.post_uuid);if (!current_.post.post_uuid.isEmpty())emit vote_post(current_.post.post_uuid, "up");});t_likes_lbl_ = new QLabel("▲ 0");t_likes_lbl_->setStyleSheet(- QString("color:#666666;font-size:11px;background:transparent;padding:0 16px;%1").arg(M(11)));+ QString("color:%1;font-size:12px;font-weight:600;"+ "background:transparent;padding:0 8px;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(12)));+t_replies_lbl_ = new QLabel("◆ 0 replies");t_replies_lbl_->setStyleSheet(- QString("color:#606060;font-size:11px;background:transparent;padding:0 8px;%1").arg(M(11)));+ QString("color:%1;font-size:12px;background:transparent;"+ "padding:0 8px;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(12)));+t_views_lbl_ = new QLabel("◉ 0 views");- t_views_lbl_->setStyleSheet(QString("color:#1c1c1c;font-size:11px;background:transparent;%1").arg(M(11)));+ t_views_lbl_->setStyleSheet(+ QString("color:%1;font-size:12px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(12)));eng_hl->addWidget(up_btn);eng_hl->addWidget(t_likes_lbl_);@@ -247,21 +311,32 @@ void ForumThreadPanel::build_ui() {// ── Comments section header ───────────────────────────────────────────────auto* com_hdr_outer = new QWidget;- com_hdr_outer->setFixedHeight(28);- com_hdr_outer->setStyleSheet("background:#060606;border-bottom:1px solid #0d0d0d;");+ com_hdr_outer->setFixedHeight(32);+ com_hdr_outer->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));auto* com_hdr_hl = new QHBoxLayout(com_hdr_outer);com_hdr_hl->setContentsMargins(0, 0, 0, 0);auto* com_hdr_inner = new QWidget;- com_hdr_inner->setMaximumWidth(800);+ com_hdr_inner->setMaximumWidth(860);com_hdr_inner->setStyleSheet("background:transparent;");auto* chi = new QHBoxLayout(com_hdr_inner);chi->setContentsMargins(32, 0, 32, 0);+ chi->setSpacing(8);++ auto* com_dot = new QLabel("◆");+ com_dot->setStyleSheet(+ QString("color:%1;font-size:8px;background:transparent;")+ .arg(ui::colors::CYAN));auto* ch_lbl = new QLabel("REPLIES");- ch_lbl->setStyleSheet(QString("color:#555555;font-size:9px;font-weight:700;letter-spacing:1.5px;"- "background:transparent;%1")- .arg(M(9)));+ ch_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;letter-spacing:1.5px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(10)));+ chi->addWidget(com_dot);chi->addWidget(ch_lbl);+ chi->addStretch();com_hdr_hl->addStretch();com_hdr_hl->addWidget(com_hdr_inner, 1);@@ -270,13 +345,14 @@ void ForumThreadPanel::build_ui() {// ── Comments container — centered ─────────────────────────────────────────auto* com_outer = new QWidget;- com_outer->setStyleSheet("background:#080808;");+ com_outer->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));auto* com_outer_hl = new QHBoxLayout(com_outer);com_outer_hl->setContentsMargins(0, 0, 0, 0);t_comments_w_ = new QWidget;- t_comments_w_->setMaximumWidth(800);- t_comments_w_->setStyleSheet("background:#080808;");+ t_comments_w_->setMaximumWidth(860);+ t_comments_w_->setStyleSheet(+ QString("background:%1;").arg(ui::colors::BG_BASE));t_comments_vl_ = new QVBoxLayout(t_comments_w_);t_comments_vl_->setContentsMargins(0, 0, 0, 0);t_comments_vl_->setSpacing(0);@@ -290,36 +366,59 @@ void ForumThreadPanel::build_ui() {scroll->setWidget(sw);tp->addWidget(scroll, 1);- // ── Compose bar ───────────────────────────────────────────────────────────+ // ── Compose bar — modern with gradient accent ─────────────────────────────auto* compose = new QWidget;- compose->setFixedHeight(46);- compose->setStyleSheet("background:#060606;border-top:1px solid #111111;");- auto* comp_outer_hl = new QHBoxLayout(compose);+ compose->setFixedHeight(54);+ compose->setStyleSheet(+ QString("background:%1;border-top:1px solid %2;")+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));+ auto* comp_vl = new QVBoxLayout(compose);+ comp_vl->setContentsMargins(0, 0, 0, 0);+ comp_vl->setSpacing(0);++ // Thin gradient accent+ auto* comp_accent = new QWidget;+ comp_accent->setFixedHeight(1);+ comp_accent->setStyleSheet(+ QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"+ "stop:0 %1,stop:0.3 %2,stop:1 transparent);")+ .arg(ui::colors::AMBER, ui::colors::CYAN));+ comp_vl->addWidget(comp_accent);++ auto* comp_outer_hl = new QHBoxLayout;comp_outer_hl->setContentsMargins(0, 0, 0, 0);auto* comp_inner = new QWidget;- comp_inner->setMaximumWidth(800);+ comp_inner->setMaximumWidth(860);comp_inner->setStyleSheet("background:transparent;");auto* comp_hl = new QHBoxLayout(comp_inner);comp_hl->setContentsMargins(32, 8, 32, 8);- comp_hl->setSpacing(8);+ comp_hl->setSpacing(10);t_reply_input_ = new QLineEdit;- t_reply_input_->setPlaceholderText("write a reply...");- t_reply_input_->setStyleSheet(QString("QLineEdit{background:#0a0a0a;color:#888888;border:1px solid #161616;"- "padding:5px 12px;font-size:12px;%1}"- "QLineEdit:focus{border-color:#666666;color:#e5e5e5;}"- "QLineEdit::placeholder{color:#555555;}")- .arg(M(12)));-- auto* send_btn = new QPushButton("REPLY ↵");- send_btn->setFixedSize(80, 30);+ t_reply_input_->setPlaceholderText("Write a reply...");+ t_reply_input_->setFixedHeight(34);+ t_reply_input_->setStyleSheet(+ QString("QLineEdit{background:rgba(255,255,255,0.03);color:%1;"+ "border:1px solid %2;padding:6px 14px;font-size:12px;"+ "border-radius:4px;%3}"+ "QLineEdit:focus{border-color:%4;color:%5;"+ "background:rgba(255,255,255,0.05);}"+ "QLineEdit::placeholder{color:%6;}")+ .arg(ui::colors::TEXT_SECONDARY, ui::colors::BORDER_DIM,+ M(12), ui::colors::BORDER_BRIGHT,+ ui::colors::TEXT_PRIMARY, ui::colors::TEXT_DIM));++ auto* send_btn = new QPushButton("Reply");+ send_btn->setFixedSize(80, 34);send_btn->setCursor(Qt::PointingHandCursor);- send_btn->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.1);color:#444444;"- "border:1px solid #1a1a1a;font-size:10px;font-weight:700;%1}"- "QPushButton:hover{background:rgba(217,119,6,0.2);color:#d97706;"- "border-color:rgba(217,119,6,0.5);}")- .arg(M(10)));+ send_btn->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.1);color:%1;"+ "border:1px solid rgba(217,119,6,0.25);font-size:12px;"+ "font-weight:700;border-radius:4px;%2}"+ "QPushButton:hover{background:rgba(217,119,6,0.2);color:%3;"+ "border-color:rgba(217,119,6,0.5);}")+ .arg(ui::colors::TEXT_SECONDARY, M(12), ui::colors::AMBER));auto submit = [this]() {QString txt = t_reply_input_->text().trimmed();@@ -337,6 +436,7 @@ void ForumThreadPanel::build_ui() {comp_outer_hl->addStretch();comp_outer_hl->addWidget(comp_inner, 1);comp_outer_hl->addStretch();+ comp_vl->addLayout(comp_outer_hl, 1);tp->addWidget(compose);stack_->addWidget(thread_page_); // 1@@ -363,40 +463,51 @@ void ForumThreadPanel::show_post(const services::ForumPostDetail& detail) {spin_timer_->stop();current_ = detail;- QString cc =- detail.post.category_color.isEmpty() ? det_color(detail.post.category_name) : detail.post.category_color;+ QString cc = detail.post.category_color.isEmpty()+ ? det_color(detail.post.category_name)+ : detail.post.category_color;t_cat_chip_->setText(detail.post.category_name.toUpper());- t_cat_chip_->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;letter-spacing:0.8px;"- "background:transparent;border:1px solid %1;"- "padding:2px 8px;%2")- .arg(cc, M(9)));+ t_cat_chip_->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;letter-spacing:1px;"+ "background:transparent;border:1px solid %1;"+ "padding:2px 10px;border-radius:10px;%2")+ .arg(cc, M(9)));t_meta_lbl_->setText(rel_time(detail.post.created_at));t_title_lbl_->setText(detail.post.title);- // Author+ // Author with circular avatarQString avc = det_color(detail.post.author_display_name);- QString ini = detail.post.author_display_name.isEmpty() ? "?" : detail.post.author_display_name.left(2).toUpper();- t_author_lbl_->setText(QString("<span style='background:%1;color:#080808;font-size:10px;"- "font-family:Consolas;padding:2px 5px;font-weight:700;'>%2</span>"- " "- "<a href='author:%3' style='color:#555555;text-decoration:none;"- "font-family:Consolas;font-size:12px;'>%4</a>")- .arg(avc, ini, detail.post.author_name, detail.post.author_display_name));+ QString ini = detail.post.author_display_name.isEmpty()+ ? "?"+ : detail.post.author_display_name.left(2).toUpper();+ t_author_lbl_->setText(+ QString("<span style='background:%1;color:%2;font-size:10px;"+ "font-family:Consolas;padding:3px 6px;font-weight:700;"+ "border-radius:12px;'>%3</span>"+ " "+ "<a href='author:%4' style='color:%5;text-decoration:none;"+ "font-family:Consolas;font-size:12px;font-weight:600;'>%6</a>")+ .arg(avc, ui::colors::BG_BASE, ini, detail.post.author_name,+ ui::colors::TEXT_SECONDARY, detail.post.author_display_name));t_body_lbl_->setText(detail.post.content);// Engagement- QString lc = detail.post.likes > 0 ? "#d97706" : "#2a2a2a";- t_likes_lbl_->setText(QString("<span style='color:%1;font-family:Consolas;font-size:11px;'>"- "▲ %2</span>")- .arg(lc)- .arg(detail.post.likes));- t_likes_lbl_->setTextFormat(Qt::RichText);+ bool voted = (detail.post.user_vote == "up");+ QString lc = voted || detail.post.likes > 0 ? ui::colors::AMBER+ : ui::colors::TEXT_DIM;+ t_likes_lbl_->setText(QString("▲ %1").arg(detail.post.likes));+ t_likes_lbl_->setStyleSheet(+ QString("color:%1;font-size:12px;font-weight:600;"+ "background:transparent;padding:0 8px;%2")+ .arg(lc, M(12)));t_replies_lbl_->setText(- QString("◆ %1 %2").arg(detail.total_comments).arg(detail.total_comments == 1 ? "reply" : "replies"));+ QString("◆ %1 %2")+ .arg(detail.total_comments)+ .arg(detail.total_comments == 1 ? "reply" : "replies"));t_views_lbl_->setText(QString("◉ %1 views").arg(detail.post.views));rebuild_comments();@@ -413,113 +524,149 @@ void ForumThreadPanel::rebuild_comments() {if (current_.comments.isEmpty()) {auto* noc = new QWidget;- noc->setFixedHeight(60);+ noc->setMinimumHeight(80);noc->setStyleSheet("background:transparent;");auto* nvl = new QVBoxLayout(noc);+ nvl->setAlignment(Qt::AlignCenter);+ nvl->setSpacing(6);+auto* icon = new QLabel("◇");icon->setAlignment(Qt::AlignCenter);- icon->setStyleSheet("color:#111111;font-size:18px;background:transparent;");+ icon->setStyleSheet(+ QString("color:%1;font-size:24px;background:transparent;")+ .arg(ui::colors::BORDER_DIM));+auto* nl = new QLabel("NO REPLIES YET");nl->setAlignment(Qt::AlignCenter);- nl->setStyleSheet(QString("color:#555555;font-size:10px;font-weight:700;letter-spacing:1.5px;"- "background:transparent;%1")- .arg(M(10)));+ nl->setStyleSheet(+ QString("color:%1;font-size:11px;font-weight:700;letter-spacing:1.5px;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_TERTIARY, M(11)));++ auto* sub = new QLabel("Be the first to share your thoughts");+ sub->setAlignment(Qt::AlignCenter);+ sub->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(10)));+nvl->addWidget(icon);nvl->addWidget(nl);+ nvl->addWidget(sub);t_comments_vl_->addWidget(noc);return;}for (int i = 0; i < current_.comments.size(); ++i) {const auto& c = current_.comments[i];+ QString avc = det_color(c.author_display_name);- auto* row = new QWidget;- row->setStyleSheet(i % 2 == 0 ? "background:#080808;border-bottom:1px solid #0d0d0d;"- : "background:#090909;border-bottom:1px solid #0d0d0d;");- auto* rvl = new QVBoxLayout(row);- rvl->setContentsMargins(32, 10, 32, 8);- rvl->setSpacing(5);+ auto* card = new QWidget;+ card->setStyleSheet(+ QString("background:%1;border-bottom:1px solid %2;")+ .arg(i % 2 == 0 ? ui::colors::BG_BASE : ui::colors::BG_SURFACE,+ ui::colors::BORDER_DIM));+ auto* cvl = new QVBoxLayout(card);+ cvl->setContentsMargins(32, 12, 32, 10);+ cvl->setSpacing(6);// ── Comment header ────────────────────────────────────────────────────auto* hr = new QWidget;hr->setStyleSheet("background:transparent;");auto* hrh = new QHBoxLayout(hr);hrh->setContentsMargins(0, 0, 0, 0);- hrh->setSpacing(8);+ hrh->setSpacing(10);- // Thread accent+ // Thread accent lineauto* tline = new QWidget;- tline->setFixedSize(2, 18);- tline->setStyleSheet(QString("background:%1;").arg(det_color(c.author_display_name)));+ tline->setFixedSize(3, 22);+ tline->setStyleSheet(+ QString("background:%1;border-radius:1px;").arg(avc));- // Avatar+ // Circular avatarauto* cav = new QLabel(c.author_display_name.left(2).toUpper());- cav->setFixedSize(20, 20);+ cav->setFixedSize(24, 24);cav->setAlignment(Qt::AlignCenter);- cav->setStyleSheet(QString("color:#080808;font-size:9px;font-weight:700;background:%1;%2")- .arg(det_color(c.author_display_name), M(9)));+ cav->setStyleSheet(+ QString("color:%1;font-size:9px;font-weight:700;background:%2;"+ "border-radius:12px;%3")+ .arg(ui::colors::BG_BASE, avc, M(9)));- auto* cname = new QLabel(c.author_display_name.left(20));+ // Author name+ auto* cname = new QLabel(c.author_display_name);cname->setStyleSheet(- QString("color:#555555;font-size:11px;font-weight:600;background:transparent;%1").arg(M(11)));+ QString("color:%1;font-size:12px;font-weight:600;"+ "background:transparent;%2")+ .arg(ui::colors::TEXT_PRIMARY, M(12)));+ // Timeauto* ctime = new QLabel(rel_time(c.created_at));- ctime->setStyleSheet(QString("color:#555555;font-size:10px;background:transparent;%1").arg(M(10)));+ ctime->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;%2")+ .arg(ui::colors::TEXT_DIM, M(10)));+ // Likesbool voted = (c.user_vote == "up");auto* clikes = new QLabel(QString("▲ %1").arg(c.likes));- clikes->setStyleSheet(QString("color:%1;font-size:10px;background:transparent;%2")- .arg(voted || c.likes > 0 ? "#d97706" : "#1e1e1e", M(10)));+ clikes->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:600;"+ "background:transparent;%2")+ .arg(voted || c.likes > 0 ? ui::colors::AMBER+ : ui::colors::TEXT_DIM,+ M(10)));hrh->addWidget(tline);- hrh->addSpacing(2);hrh->addWidget(cav);hrh->addWidget(cname);hrh->addStretch();hrh->addWidget(ctime);- hrh->addSpacing(10);+ hrh->addSpacing(8);hrh->addWidget(clikes);- rvl->addWidget(hr);+ cvl->addWidget(hr);// Bodyauto* cbody = new QLabel(c.content);cbody->setWordWrap(true);cbody->setTextFormat(Qt::PlainText);cbody->setAlignment(Qt::AlignTop | Qt::AlignLeft);- cbody->setStyleSheet(QString("color:#666666;font-size:12px;line-height:1.5;background:transparent;"- "padding-left:28px;%1")- .arg(M(12)));- rvl->addWidget(cbody);+ cbody->setStyleSheet(+ QString("color:%1;font-size:12px;line-height:1.6;"+ "background:transparent;padding-left:38px;%2")+ .arg(ui::colors::TEXT_SECONDARY, M(12)));+ cvl->addWidget(cbody);// Actionsauto* ar = new QWidget;ar->setStyleSheet("background:transparent;");auto* arh = new QHBoxLayout(ar);- arh->setContentsMargins(28, 0, 0, 0);- arh->setSpacing(12);+ arh->setContentsMargins(38, 0, 0, 0);+ arh->setSpacing(14);- auto mk_act = [&](const QString& lbl, const QString& col, const QString& vt) {+ auto mk_act = [&](const QString& lbl, const QString& col,+ const QString& vt) {auto* b = new QPushButton(lbl);- b->setFixedHeight(16);+ b->setFixedHeight(18);b->setCursor(Qt::PointingHandCursor);bool a = (c.user_vote == vt);- b->setStyleSheet(a ? QString("QPushButton{background:transparent;color:%1;border:none;"- "font-size:10px;font-weight:700;padding:0;%2}")- .arg(col, M(10))- : QString("QPushButton{background:transparent;color:#555555;border:none;"- "font-size:10px;padding:0;%1}"- "QPushButton:hover{color:%2;}")- .arg(M(10), col));+ b->setStyleSheet(+ a ? QString("QPushButton{background:transparent;color:%1;"+ "border:none;font-size:10px;font-weight:700;"+ "padding:0;%2}")+ .arg(col, M(10))+ : QString("QPushButton{background:transparent;color:%1;"+ "border:none;font-size:10px;padding:0;%2}"+ "QPushButton:hover{color:%3;}")+ .arg(ui::colors::TEXT_DIM, M(10), col));auto uuid = c.comment_uuid;- connect(b, &QPushButton::clicked, this, [this, uuid, vt]() { emit vote_comment(uuid, vt); });+ connect(b, &QPushButton::clicked, this,+ [this, uuid, vt]() { emit vote_comment(uuid, vt); });return b;};- arh->addWidget(mk_act("▲ upvote", "#d97706", "up"));- arh->addWidget(mk_act("▼ downvote", "#555555", "down"));+ arh->addWidget(mk_act("▲ upvote", ui::colors::AMBER, "up"));+ arh->addWidget(mk_act("▼ downvote", ui::colors::TEXT_TERTIARY, "down"));arh->addStretch();- rvl->addWidget(ar);+ cvl->addWidget(ar);- t_comments_vl_->addWidget(row);+ t_comments_vl_->addWidget(card);}}diff --git a/fincept-qt/src/services/agents/AgentService.cpp b/fincept-qt/src/services/agents/AgentService.cppindex 6b6530403..3e7e13854 100644--- a/fincept-qt/src/services/agents/AgentService.cpp+++ b/fincept-qt/src/services/agents/AgentService.cpp@@ -14,6 +14,7 @@#include <QJsonDocument>#include <QPointer>#include <QProcess>+#include <QUuid>namespace fincept::services {@@ -335,22 +336,23 @@ void AgentService::discover_agents() {// ── Agent execution ──────────────────────────────────────────────────────────-void AgentService::run_agent(const QString& query, const QJsonObject& config) {- LOG_INFO("AgentService", QString("Running agent query: %1").arg(query.left(80)));+QString AgentService::run_agent(const QString& query, const QJsonObject& config) {+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);+ LOG_INFO("AgentService", QString("Running agent query [%1]: %2").arg(req_id.left(8), query.left(80)));QJsonObject params;params["query"] = query;QPointer<AgentService> self = this;- run_python_stdin("run", params, config, [self](bool ok, QJsonObject result) {+ run_python_stdin("run", params, config, [self, req_id](bool ok, QJsonObject result) {if (!self)return;AgentExecutionResult r;+ r.request_id = req_id;r.success = ok && result["success"].toBool(ok);r.execution_time_ms = result["execution_time_ms"].toInt();if (r.success) {- // Extract response text from various formatsif (result.contains("response"))r.response = result["response"].toString();else if (result.contains("result"))@@ -365,20 +367,23 @@ void AgentService::run_agent(const QString& query, const QJsonObject& config) {emit self->agent_result(r);});+ return req_id;}// ── Streaming agent execution ─────────────────────────────────────────────────-void AgentService::run_agent_streaming(const QString& query, const QJsonObject& config) {- LOG_INFO("AgentService", QString("Streaming agent query: %1").arg(query.left(80)));+QString AgentService::run_agent_streaming(const QString& query, const QJsonObject& config) {+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);+ LOG_INFO("AgentService", QString("Streaming agent query [%1]: %2").arg(req_id.left(8), query.left(80)));auto& py = python::PythonRunner::instance();if (!py.is_available()) {AgentExecutionResult r;+ r.request_id = req_id;r.success = false;r.error = "Python not available";emit agent_stream_done(r);- return;+ return req_id;}QJsonObject params;@@ -399,7 +404,7 @@ void AgentService::run_agent_streaming(const QString& query, const QJsonObject&QString* accumulated = new QString;// Read stdout line by line as process writes- connect(proc, &QProcess::readyReadStandardOutput, this, [self, proc, accumulated]() {+ connect(proc, &QProcess::readyReadStandardOutput, this, [self, proc, accumulated, req_id]() {if (!self) return;while (proc->canReadLine()) {QString line = QString::fromUtf8(proc->readLine()).trimmed();@@ -408,13 +413,14 @@ void AgentService::run_agent_streaming(const QString& query, const QJsonObject&if (line.startsWith("TOKEN: ")) {QString token = line.mid(7);*accumulated += token + " ";- emit self->agent_stream_token(token);+ emit self->agent_stream_token(req_id, token);} else if (line.startsWith("THINKING: ")) {- emit self->agent_stream_thinking(line.mid(10));+ emit self->agent_stream_thinking(req_id, line.mid(10));} else if (line.startsWith("TOOL: ")) {- emit self->agent_stream_thinking("Tool: " + line.mid(6));+ emit self->agent_stream_thinking(req_id, "Tool: " + line.mid(6));} else if (line.startsWith("ERROR: ")) {AgentExecutionResult r;+ r.request_id = req_id;r.success = false;r.error = line.mid(7);emit self->agent_stream_done(r);@@ -424,7 +430,7 @@ void AgentService::run_agent_streaming(const QString& query, const QJsonObject&});connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,- [self, proc, accumulated, timer](int exit_code, QProcess::ExitStatus) {+ [self, proc, accumulated, timer, req_id](int exit_code, QProcess::ExitStatus) {int elapsed = timer->elapsed();delete timer;@@ -443,16 +449,15 @@ void AgentService::run_agent_streaming(const QString& query, const QJsonObject&}AgentExecutionResult r;+ r.request_id = req_id;r.execution_time_ms = elapsed;QJsonDocument doc = QJsonDocument::fromJson(final_json.toUtf8());if (!doc.isNull() && doc.object()["success"].toBool()) {- // Prefer full response from JSON if available, else use accumulated tokensQString json_response = doc.object()["response"].toString();r.success = true;r.response = json_response.isEmpty() ? accumulated->trimmed() : json_response;} else if (!accumulated->trimmed().isEmpty()) {- // Tokens arrived but no final JSON — use accumulatedr.success = true;r.response = accumulated->trimmed();} else {@@ -465,13 +470,14 @@ void AgentService::run_agent_streaming(const QString& query, const QJsonObject&emit self->agent_stream_done(r);});- connect(proc, &QProcess::errorOccurred, this, [self, proc, accumulated, timer](QProcess::ProcessError) {+ connect(proc, &QProcess::errorOccurred, this, [self, proc, accumulated, timer, req_id](QProcess::ProcessError) {delete timer;QString err = proc->errorString();proc->deleteLater();delete accumulated;if (!self) return;AgentExecutionResult r;+ r.request_id = req_id;r.success = false;r.error = "Process error: " + err;emit self->agent_stream_done(r);@@ -481,21 +487,24 @@ void AgentService::run_agent_streaming(const QString& query, const QJsonObject&proc->start(python_path, {script_path, "--stdin", "--stream"});proc->write(payload_bytes);proc->closeWriteChannel();+ return req_id;}// ── Query routing ────────────────────────────────────────────────────────────-void AgentService::route_query(const QString& query) {+QString AgentService::route_query(const QString& query) {LOG_INFO("AgentService", QString("Routing query: %1").arg(query.left(80)));QJsonObject params;params["query"] = query;+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);QPointer<AgentService> self = this;- run_python_stdin("route_query", params, {}, [self](bool ok, QJsonObject result) {+ run_python_stdin("route_query", params, {}, [self, req_id](bool ok, QJsonObject result) {if (!self)return;RoutingResult r;+ r.request_id = req_id;r.success = ok && result["success"].toBool(ok);r.agent_id = result["agent_id"].toString();r.intent = result["intent"].toString();@@ -508,11 +517,12 @@ void AgentService::route_query(const QString& query) {emit self->routing_result(r);});+ return req_id;}// ── Team execution ───────────────────────────────────────────────────────────-void AgentService::run_team(const QString& query, const QJsonObject& team_config) {+QString AgentService::run_team(const QString& query, const QJsonObject& team_config) {LOG_INFO("AgentService", QString("Running team query: %1").arg(query.left(80)));QJsonObject params;@@ -525,11 +535,13 @@ void AgentService::run_team(const QString& query, const QJsonObject& team_configif (team_config.contains("model"))coord_as_config["model"] = team_config["model"];+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);QPointer<AgentService> self = this;- run_python_stdin("run_team", params, coord_as_config, [self](bool ok, QJsonObject result) {+ run_python_stdin("run_team", params, coord_as_config, [self, req_id](bool ok, QJsonObject result) {if (!self)return;AgentExecutionResult r;+ r.request_id = req_id;r.success = ok && result["success"].toBool(ok);r.execution_time_ms = result["execution_time_ms"].toInt();r.response = result.contains("response") ? result["response"].toString()@@ -537,21 +549,24 @@ void AgentService::run_team(const QString& query, const QJsonObject& team_configr.error = result["error"].toString();emit self->agent_result(r);});+ return req_id;}// ── Workflow execution ───────────────────────────────────────────────────────-void AgentService::run_workflow(const QString& workflow_type, const QJsonObject& params) {- LOG_INFO("AgentService", QString("Running workflow: %1").arg(workflow_type));+QString AgentService::run_workflow(const QString& workflow_type, const QJsonObject& params) {+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);+ LOG_INFO("AgentService", QString("Running workflow [%1]: %2").arg(req_id.left(8), workflow_type));QJsonObject p = params;p["workflow_type"] = workflow_type;QPointer<AgentService> self = this;- run_python_stdin(workflow_type, p, {}, [self](bool ok, QJsonObject result) {+ run_python_stdin(workflow_type, p, {}, [self, req_id](bool ok, QJsonObject result) {if (!self)return;AgentExecutionResult r;+ r.request_id = req_id;r.success = ok && result["success"].toBool(ok);r.execution_time_ms = result["execution_time_ms"].toInt();r.response = result.contains("response") ? result["response"].toString()@@ -559,18 +574,23 @@ void AgentService::run_workflow(const QString& workflow_type, const QJsonObject&r.error = result["error"].toString();emit self->agent_result(r);});+ return req_id;}// ── Planner ──────────────────────────────────────────────────────────────────-void AgentService::create_plan(const QString& query) {+QString AgentService::create_plan(const QString& query, const QJsonObject& config) {LOG_INFO("AgentService", QString("Creating plan for: %1").arg(query.left(80)));+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);QJsonObject params;params["query"] = query;+ if (!config.isEmpty())+ for (auto it = config.begin(); it != config.end(); ++it)+ params[it.key()] = it.value();QPointer<AgentService> self = this;- run_python_stdin("generate_dynamic_plan", params, {}, [self](bool ok, QJsonObject result) {+ run_python_stdin("generate_dynamic_plan", params, {}, [self, req_id](bool ok, QJsonObject result) {if (!self)return;if (!ok) {@@ -579,6 +599,7 @@ void AgentService::create_plan(const QString& query) {}ExecutionPlan plan;+ plan.request_id = req_id;plan.id = result["id"].toString();plan.name = result["name"].toString();plan.description = result["description"].toString();@@ -602,16 +623,21 @@ void AgentService::create_plan(const QString& query) {emit self->plan_created(plan);});+ return req_id;}-void AgentService::execute_plan(const QJsonObject& plan) {+QString AgentService::execute_plan(const QJsonObject& plan, const QJsonObject& config) {LOG_INFO("AgentService", "Executing plan");+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);QJsonObject params;params["plan"] = plan;+ if (!config.isEmpty())+ for (auto it = config.begin(); it != config.end(); ++it)+ params[it.key()] = it.value();QPointer<AgentService> self = this;- run_python_stdin("execute_plan", params, {}, [self](bool ok, QJsonObject result) {+ run_python_stdin("execute_plan", params, {}, [self, req_id](bool ok, QJsonObject result) {if (!self)return;if (!ok) {@@ -620,6 +646,7 @@ void AgentService::execute_plan(const QJsonObject& plan) {}ExecutionPlan plan;+ plan.request_id = req_id;plan.id = result["id"].toString();plan.status = result["status"].toString();plan.is_complete = result["is_complete"].toBool();@@ -639,6 +666,7 @@ void AgentService::execute_plan(const QJsonObject& plan) {emit self->plan_executed(plan);});+ return req_id;}// ── System info ──────────────────────────────────────────────────────────────@@ -793,17 +821,19 @@ void AgentService::set_active_config(const QString& id) {// ── Structured output ────────────────────────────────────────────────────────-void AgentService::run_agent_structured(const QString& query, const QJsonObject& config, const QString& output_model) {- LOG_INFO("AgentService", QString("Running structured agent (%1): %2").arg(output_model, query.left(60)));+QString AgentService::run_agent_structured(const QString& query, const QJsonObject& config, const QString& output_model) {+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);+ LOG_INFO("AgentService", QString("Running structured agent [%1] (%2): %3").arg(req_id.left(8), output_model, query.left(60)));QJsonObject params;params["query"] = query;params["output_model"] = output_model;QPointer<AgentService> self = this;- run_python_stdin("run_structured", params, config, [self](bool ok, QJsonObject result) {+ run_python_stdin("run_structured", params, config, [self, req_id](bool ok, QJsonObject result) {if (!self)return;AgentExecutionResult r;+ r.request_id = req_id;r.success = ok && result["success"].toBool(ok);r.execution_time_ms = result["execution_time_ms"].toInt();r.response = result.contains("response") ? result["response"].toString()@@ -811,6 +841,7 @@ void AgentService::run_agent_structured(const QString& query, const QJsonObject&r.error = result["error"].toString();emit self->agent_result(r);});+ return req_id;}// ── Routed query execution ───────────────────────────────────────────────────@@ -939,13 +970,14 @@ void AgentService::run_portfolio_analysis(const QString& analysis_type, const QJ// ── Plan variants ────────────────────────────────────────────────────────────-void AgentService::create_stock_analysis_plan(const QString& symbol) {+QString AgentService::create_stock_analysis_plan(const QString& symbol, const QJsonObject& config) {LOG_INFO("AgentService", QString("Stock analysis plan: %1").arg(symbol));+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);QJsonObject params;params["symbol"] = symbol;QPointer<AgentService> self = this;- run_python_stdin("create_stock_plan", params, {}, [self](bool ok, QJsonObject result) {+ run_python_stdin("create_stock_plan", params, {}, [self, req_id](bool ok, QJsonObject result) {if (!self)return;if (!ok) {@@ -953,6 +985,7 @@ void AgentService::create_stock_analysis_plan(const QString& symbol) {return;}ExecutionPlan plan;+ plan.request_id = req_id;plan.id = result["id"].toString();plan.name = result["name"].toString();plan.status = result["status"].toString("pending");@@ -969,16 +1002,18 @@ void AgentService::create_stock_analysis_plan(const QString& symbol) {}emit self->plan_created(plan);});+ return req_id;}-void AgentService::create_portfolio_plan(const QJsonObject& goals) {+QString AgentService::create_portfolio_plan(const QJsonObject& goals, const QJsonObject& config) {LOG_INFO("AgentService", "Portfolio plan");+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);QJsonObject params;if (!goals.isEmpty())params["goals"] = goals;QPointer<AgentService> self = this;- run_python_stdin("create_portfolio_plan", params, {}, [self](bool ok, QJsonObject result) {+ run_python_stdin("create_portfolio_plan", params, {}, [self, req_id](bool ok, QJsonObject result) {if (!self)return;if (!ok) {@@ -986,6 +1021,7 @@ void AgentService::create_portfolio_plan(const QJsonObject& goals) {return;}ExecutionPlan plan;+ plan.request_id = req_id;plan.id = result["id"].toString();plan.name = result["name"].toString();plan.status = result["status"].toString("pending");@@ -1002,6 +1038,7 @@ void AgentService::create_portfolio_plan(const QJsonObject& goals) {}emit self->plan_created(plan);});+ return req_id;}// ── Memory & Knowledge ───────────────────────────────────────────────────────diff --git a/fincept-qt/src/services/agents/AgentService.h b/fincept-qt/src/services/agents/AgentService.hindex bd7abf7f1..2c1ae2ea2 100644--- a/fincept-qt/src/services/agents/AgentService.h+++ b/fincept-qt/src/services/agents/AgentService.h@@ -26,10 +26,12 @@ class AgentService : public QObject {void get_system_info();// ── Core agent execution ─────────────────────────────────────────────────- void run_agent(const QString& query, const QJsonObject& config);- void run_agent_streaming(const QString& query, const QJsonObject& config);- void run_agent_structured(const QString& query, const QJsonObject& config, const QString& output_model);- void route_query(const QString& query);+ // Returns a request_id that will be echoed in the emitted result signals,+ // so callers can guard on their own request and ignore results from other panels.+ QString run_agent(const QString& query, const QJsonObject& config);+ QString run_agent_streaming(const QString& query, const QJsonObject& config);+ QString run_agent_structured(const QString& query, const QJsonObject& config, const QString& output_model);+ QString route_query(const QString& query);void execute_routed_query(const QString& query, const QJsonObject& config = {}, const QString& session_id = {});// ── Multi-query & parallel ───────────────────────────────────────────────@@ -42,16 +44,16 @@ class AgentService : public QObject {void run_portfolio_analysis(const QString& analysis_type, const QJsonObject& portfolio_summary = {});// ── Team execution ───────────────────────────────────────────────────────- void run_team(const QString& query, const QJsonObject& team_config);+ QString run_team(const QString& query, const QJsonObject& team_config);// ── Workflow execution ───────────────────────────────────────────────────- void run_workflow(const QString& workflow_type, const QJsonObject& params = {});+ QString run_workflow(const QString& workflow_type, const QJsonObject& params = {});// ── Planner ──────────────────────────────────────────────────────────────- void create_plan(const QString& query);- void create_stock_analysis_plan(const QString& symbol);- void create_portfolio_plan(const QJsonObject& goals = {});- void execute_plan(const QJsonObject& plan);+ QString create_plan(const QString& query, const QJsonObject& config = {});+ QString create_stock_analysis_plan(const QString& symbol, const QJsonObject& config = {});+ QString create_portfolio_plan(const QJsonObject& goals = {}, const QJsonObject& config = {});+ QString execute_plan(const QJsonObject& plan, const QJsonObject& config = {});// ── Memory & Knowledge ───────────────────────────────────────────────────void store_memory(const QString& content, const QString& memory_type = "general", const QJsonObject& metadata = {});@@ -90,9 +92,9 @@ class AgentService : public QObject {signals:void agents_discovered(QVector<AgentInfo> agents, QVector<AgentCategory> categories);void agent_result(AgentExecutionResult result);- void agent_stream_token(const QString& token); // emitted per TOKEN chunk- void agent_stream_thinking(const QString& status); // emitted per THINKING chunk- void agent_stream_done(AgentExecutionResult result); // emitted when stream ends+ void agent_stream_token(const QString& request_id, const QString& token);+ void agent_stream_thinking(const QString& request_id, const QString& status);+ void agent_stream_done(AgentExecutionResult result);void routing_result(RoutingResult result);void tools_loaded(AgentToolsInfo info);void models_loaded(AgentModelsInfo info);diff --git a/fincept-qt/src/services/agents/AgentTypes.h b/fincept-qt/src/services/agents/AgentTypes.hindex 36d110e08..8d693f81b 100644--- a/fincept-qt/src/services/agents/AgentTypes.h+++ b/fincept-qt/src/services/agents/AgentTypes.h@@ -36,6 +36,7 @@ struct AgentExecutionResult {QString response;QString error;int execution_time_ms = 0;+ QString request_id; // set by AgentService; panels guard on this to avoid cross-contamination};// ── Routing ─────────────────────────────────────────────────────────────────@@ -47,6 +48,7 @@ struct RoutingResult {double confidence = 0.0;QStringList matched_keywords;QJsonObject config;+ QString request_id; // matches the run_agent call that triggered this routing};// ── System info ─────────────────────────────────────────────────────────────@@ -112,8 +114,9 @@ struct ExecutionPlan {QString description;QVector<PlanStep> steps;QString status;- bool is_complete = false;- bool has_failed = false;+ bool is_complete = false;+ bool has_failed = false;+ QString request_id;};} // namespace fincept::servicesdiff --git a/fincept-qt/src/services/backtesting/BacktestingService.cpp b/fincept-qt/src/services/backtesting/BacktestingService.cppindex fabed4f38..c208c21d2 100644--- a/fincept-qt/src/services/backtesting/BacktestingService.cpp+++ b/fincept-qt/src/services/backtesting/BacktestingService.cpp@@ -45,6 +45,41 @@ void BacktestingService::execute(const QString& provider, const QString& command});}+void BacktestingService::load_strategies(const QString& provider) {+ auto script = QString("Analytics/backtesting/%1/%1_provider.py").arg(provider);+ QPointer<BacktestingService> self = this;+ python::PythonRunner::instance().run(+ script, {"get_strategies", "{}"}, [self, provider](python::PythonResult result) {+ if (!self) return;+ if (!result.success) {+ emit self->error_occurred("load_strategies/" + provider, result.error);+ return;+ }+ auto doc = QJsonDocument::fromJson(python::extract_json(result.output).toUtf8());+ if (!doc.isNull())+ emit self->result_ready(provider, "get_strategies", doc.object());+ });+}++void BacktestingService::load_command_options(const QString& provider) {+ auto script = QString("Analytics/backtesting/%1/%1_provider.py").arg(provider);+ QPointer<BacktestingService> self = this;+ python::PythonRunner::instance().run(+ script, {"get_command_options", "{}"}, [self, provider](python::PythonResult result) {+ if (!self) return;+ if (!result.success) {+ LOG_WARN("Backtesting", QString("get_command_options failed for %1 — using defaults").arg(provider));+ return;+ }+ auto doc = QJsonDocument::fromJson(python::extract_json(result.output).toUtf8());+ if (doc.isNull()) return;+ auto obj = doc.object();+ // Unwrap "data" wrapper if present+ auto data = obj.contains("data") ? obj.value("data").toObject() : obj;+ emit self->command_options_loaded(provider, data);+ });+}+void BacktestingService::list_strategies() {QPointer<BacktestingService> self = this;python::PythonRunner::instance().run(diff --git a/fincept-qt/src/services/backtesting/BacktestingService.h b/fincept-qt/src/services/backtesting/BacktestingService.hindex 137db0f8b..017efc474 100644--- a/fincept-qt/src/services/backtesting/BacktestingService.h+++ b/fincept-qt/src/services/backtesting/BacktestingService.h@@ -15,12 +15,19 @@ class BacktestingService : public QObject {/// Execute a backtesting command on a specific providervoid execute(const QString& provider, const QString& command, const QJsonObject& args);- /// List available strategies from Fincept provider (dynamic)+ /// Load strategies dynamically from any provider+ void load_strategies(const QString& provider);++ /// Load command option lists (label_types, splitter_types, etc.) for a provider+ void load_command_options(const QString& provider);++ /// Legacy: load strategies from fincept provider onlyvoid list_strategies();signals:void result_ready(QString provider, QString command, QJsonObject data);void strategies_loaded(QJsonObject strategies);+ void command_options_loaded(QString provider, QJsonObject options);void error_occurred(QString context, QString message);private:diff --git a/fincept-qt/src/services/backtesting/BacktestingTypes.h b/fincept-qt/src/services/backtesting/BacktestingTypes.hindex 2977fa77a..e712c591d 100644--- a/fincept-qt/src/services/backtesting/BacktestingTypes.h+++ b/fincept-qt/src/services/backtesting/BacktestingTypes.h@@ -1,6 +1,7 @@// src/services/backtesting/BacktestingTypes.h#pragma once#include <QColor>+#include <QJsonArray>#include <QJsonObject>#include <QString>#include <QStringList>@@ -77,237 +78,81 @@ struct Strategy {QVector<StrategyParam> params;};+/// Returns empty — Python is the source of truth. Strategies are loaded dynamically+/// via BacktestingService::load_strategies() → result_ready("get_strategies").inline QVector<Strategy> default_strategies() {- return {- // ── Trend Following ─────────────────────────────────────────────- {"sma_crossover",- "SMA Crossover",- "trend",- {- {"fastPeriod", "Fast Period", 10, 2, 100, 1},- {"slowPeriod", "Slow Period", 20, 5, 200, 1},- }},- {"ema_crossover",- "EMA Crossover",- "trend",- {- {"fastPeriod", "Fast Period", 12, 2, 100, 1},- {"slowPeriod", "Slow Period", 26, 5, 200, 1},- }},- {"macd",- "MACD",- "trend",- {- {"fast", "Fast Period", 12, 2, 50, 1},- {"slow", "Slow Period", 26, 5, 100, 1},- {"signal", "Signal Period", 9, 2, 50, 1},- }},- {"adx_trend",- "ADX Trend",- "trend",- {- {"period", "Period", 14, 5, 50, 1},- {"threshold", "Threshold", 25, 10, 50, 1},- }},- {"triple_ma",- "Triple MA",- "trend",- {- {"fast", "Fast Period", 5, 2, 50, 1},- {"medium", "Medium Period", 20, 5, 100, 1},- {"slow", "Slow Period", 50, 10, 200, 1},- }},- {"keltner",- "Keltner Channel",- "trend",- {- {"period", "Period", 20, 5, 50, 1},- {"multiplier", "Multiplier", 2.0, 0.5, 5.0, 0.1},- }},- {"williams_r",- "Williams %R",- "trend",- {- {"period", "Period", 14, 5, 50, 1},- {"overbought", "Overbought", -20, -50, -5, 1},- {"oversold", "Oversold", -80, -95, -50, 1},- }},- {"cci_trend",- "CCI Trend",- "trend",- {- {"period", "Period", 20, 5, 50, 1},- {"threshold", "Threshold", 100, 50, 200, 10},- }},- {"obv_trend",- "OBV Trend",- "trend",- {- {"maPeriod", "MA Period", 20, 5, 50, 1},- }},-- // ── Mean Reversion ──────────────────────────────────────────────- {"zscore",- "Z-Score",- "mean_reversion",- {- {"period", "Period", 20, 5, 100, 1},- {"entry_z", "Entry Z", 2.0, 0.5, 4.0, 0.1},- {"exit_z", "Exit Z", 0.5, 0.0, 2.0, 0.1},- }},- {"bollinger",- "Bollinger Bands",- "mean_reversion",- {- {"period", "Period", 20, 5, 50, 1},- {"std_dev", "Std Dev", 2.0, 0.5, 4.0, 0.1},- }},- {"rsi",- "RSI",- "mean_reversion",- {- {"period", "Period", 14, 2, 50, 1},- {"oversold", "Oversold", 30, 10, 40, 1},- {"overbought", "Overbought", 70, 60, 90, 1},- }},- {"stochastic",- "Stochastic",- "mean_reversion",- {- {"k_period", "K Period", 14, 5, 50, 1},- {"d_period", "D Period", 3, 2, 20, 1},- }},- {"mfi",- "Money Flow Index",- "mean_reversion",- {- {"period", "Period", 14, 5, 50, 1},- {"oversold", "Oversold", 20, 10, 40, 1},- {"overbought", "Overbought", 80, 60, 90, 1},- }},-- // ── Momentum ────────────────────────────────────────────────────- {"momentum",- "Momentum (ROC)",- "momentum",- {- {"period", "Period", 14, 2, 50, 1},- }},- {"dual_momentum",- "Dual Momentum",- "momentum",- {- {"period", "Period", 12, 2, 50, 1},- {"lookback", "Lookback", 6, 1, 24, 1},- }},- {"macd_zero_cross",- "MACD Zero Cross",- "momentum",- {- {"fast", "Fast Period", 12, 2, 50, 1},- {"slow", "Slow Period", 26, 5, 100, 1},- {"signal", "Signal Period", 9, 2, 50, 1},- }},-- // ── Breakout ────────────────────────────────────────────────────- {"donchian",- "Donchian Breakout",- "breakout",- {- {"period", "Period", 20, 5, 100, 1},- }},- {"volatility_bo",- "Volatility Breakout",- "breakout",- {- {"period", "Period", 20, 5, 50, 1},- {"multiplier", "Multiplier", 2.0, 0.5, 5.0, 0.1},- }},- {"atr_trailing",- "ATR Trailing Stop",- "breakout",- {- {"period", "Period", 14, 5, 50, 1},- {"multiplier", "Multiplier", 3.0, 1.0, 6.0, 0.5},- }},- {"keltner_breakout",- "Keltner Breakout",- "breakout",- {- {"period", "Period", 20, 5, 50, 1},- {"multiplier", "Multiplier", 1.5, 0.5, 4.0, 0.1},- }},-- // ── Multi-Indicator ─────────────────────────────────────────────- {"rsi_macd",- "RSI + MACD",- "multi",- {- {"rsi_period", "RSI Period", 14, 5, 50, 1},- {"macd_fast", "MACD Fast", 12, 2, 50, 1},- {"macd_slow", "MACD Slow", 26, 5, 100, 1},- }},- {"macd_adx",- "MACD + ADX",- "multi",- {- {"macd_fast", "MACD Fast", 12, 2, 50, 1},- {"adx_period", "ADX Period", 14, 5, 50, 1},- }},- {"bollinger_rsi",- "Bollinger + RSI",- "multi",- {- {"bb_period", "BB Period", 20, 5, 50, 1},- {"rsi_period", "RSI Period", 14, 5, 50, 1},- }},- {"trend_momentum",- "Trend + Momentum",- "multi",- {- {"ma_period", "MA Period", 50, 10, 200, 5},- {"rsi_period", "RSI Period", 14, 5, 50, 1},- {"adx_period", "ADX Period", 14, 5, 50, 1},- }},-- // ── Portfolio Allocation (BT provider) ──────────────────────────- {"equal_weight", "Equal Weight", "portfolio", {}},- {"inverse_vol",- "Inverse Volatility",- "portfolio",- {- {"lookback", "Lookback Days", 60, 20, 252, 5},- }},- {"mean_variance",- "Mean-Variance",- "portfolio",- {- {"lookback", "Lookback Days", 252, 60, 504, 20},- }},- {"risk_parity",- "Risk Parity",- "portfolio",- {- {"lookback", "Lookback Days", 60, 20, 252, 5},- }},- {"target_vol",- "Target Volatility",- "portfolio",- {- {"targetVol", "Target Vol %", 15, 5, 30, 1},- {"lookback", "Lookback Days", 60, 20, 252, 5},- }},- {"min_variance",- "Min Variance",- "portfolio",- {- {"lookback", "Lookback Days", 252, 60, 504, 20},- }},- };-}--inline QStringList strategy_categories() {- return {"trend", "mean_reversion", "momentum", "breakout", "multi", "portfolio", "custom"};+ return {};+}++/// Derive categories from a loaded strategy list (no hardcoded list needed).+inline QStringList categories_from_strategies(const QVector<Strategy>& strategies) {+ QStringList cats;+ for (const auto& s : strategies)+ if (!cats.contains(s.category))+ cats.append(s.category);+ return cats;+}++/// Parse a single strategy parameter from JSON.+/// Handles both BT shape {name, label, default, min, max, step}+/// and VectorBT shape {id, name, default, min, max, step}.+inline StrategyParam param_from_json(const QJsonObject& p) {+ StrategyParam sp;+ sp.name = p.contains("name") ? p.value("name").toString() : p.value("id").toString();+ sp.label = p.contains("label") ? p.value("label").toString() : p.value("name").toString(sp.name);+ sp.default_val = p.value("default").toDouble(14);+ sp.min_val = p.value("min").toDouble(1);+ sp.max_val = p.value("max").toDouble(200);+ sp.step = p.value("step").toDouble(1);+ return sp;+}++/// Parse strategies from a Python get_strategies JSON response.+///+/// Handles two shapes:+/// BT/backtestingpy: {"success":true,"data":{"strategies":{"category":[{id,name,params:[]}]}}}+/// VectorBT: {"success":true,"data":[{"type","category","parameters":[{id,name,...}]}]}+inline QVector<Strategy> strategies_from_json(const QJsonObject& root) {+ QVector<Strategy> out;+ auto data_val = root.value("data");++ // VectorBT shape: data is an array+ if (data_val.isArray()) {+ for (const auto& item : data_val.toArray()) {+ auto obj = item.toObject();+ Strategy s;+ s.id = obj.value("type").toString();+ s.name = obj.value("name").toString(s.id);+ s.category = obj.value("category").toString("other");+ for (const auto& pv : obj.value("parameters").toArray())+ s.params.append(param_from_json(pv.toObject()));+ if (!s.id.isEmpty())+ out.append(s);+ }+ return out;+ }++ // BT/backtestingpy shape: data.strategies is an object keyed by category+ auto data_obj = data_val.isObject() ? data_val.toObject() : root;+ auto strategies_val = data_obj.value("strategies");+ if (!strategies_val.isObject())+ return out;++ auto cats_obj = strategies_val.toObject();+ for (const auto& cat : cats_obj.keys()) {+ for (const auto& sv : cats_obj.value(cat).toArray()) {+ auto obj = sv.toObject();+ Strategy s;+ s.id = obj.value("id").toString();+ s.name = obj.value("name").toString(s.id);+ s.category = cat;+ for (const auto& pv : obj.value("params").toArray())+ s.params.append(param_from_json(pv.toObject()));+ if (!s.id.isEmpty())+ out.append(s);+ }+ }+ return out;}// ── Indicator definitions ───────────────────────────────────────────────────@@ -318,91 +163,47 @@ struct Indicator {QVector<StrategyParam> params;};+/// Returns empty — Python is the source of truth. Indicators are loaded dynamically+/// via BacktestingService::execute(provider, "get_indicators", {}) → result_ready.inline QVector<Indicator> all_indicators() {- return {- {"ma", "Moving Average (SMA)", {{"period", "Period", 20, 2, 200, 1}}},- {"ema", "Moving Average (EMA)", {{"period", "Period", 20, 2, 200, 1}}},- {"rsi", "RSI", {{"period", "Period", 14, 2, 50, 1}}},- {"macd",- "MACD",- {- {"fast", "Fast", 12, 2, 50, 1},- {"slow", "Slow", 26, 5, 100, 1},- {"signal", "Signal", 9, 2, 50, 1},- }},- {"stoch",- "Stochastic",- {- {"k_period", "K Period", 14, 5, 50, 1},- {"d_period", "D Period", 3, 2, 20, 1},- }},- {"cci", "CCI", {{"period", "Period", 20, 5, 50, 1}}},- {"williams", "Williams %R", {{"period", "Period", 14, 5, 50, 1}}},- {"adx", "ADX", {{"period", "Period", 14, 5, 50, 1}}},- {"momentum", "Momentum", {{"period", "Period", 14, 2, 50, 1}}},- {"atr", "ATR", {{"period", "Period", 14, 5, 50, 1}}},- {"bbands",- "Bollinger Bands",- {- {"period", "Period", 20, 5, 50, 1},- {"std_dev", "Std Dev", 2.0, 0.5, 4.0, 0.1},- }},- {"obv", "On Balance Volume", {}},- {"vwap", "VWAP", {}},- {"ichimoku",- "Ichimoku Cloud",- {- {"tenkan", "Tenkan", 9, 5, 20, 1},- {"kijun", "Kijun", 26, 10, 52, 1},- {"senkou", "Senkou", 52, 20, 120, 1},- }},- };+ return {};}-// ── Position sizing ─────────────────────────────────────────────────────────+// ── Command options ─────────────────────────────────────────────────────────+// These are compile-time fallbacks used ONLY when a provider does not support+// the "get_command_options" command (e.g. FastTrade, Zipline).+// Real providers (bt, vectorbt, backtestingpy, fincept) override these at+// runtime via BacktestingService::execute(provider, "get_command_options", {})+// → result_ready → BacktestingScreen::on_command_options_loaded().inline QStringList position_sizing_methods() {return {"percent", "fixed", "kelly", "vol_target", "risk"};}-// ── Optimize objectives ─────────────────────────────────────────────────────-inline QStringList optimize_objectives() {return {"sharpe", "sortino", "calmar", "return"};}-// ── Optimize methods ────────────────────────────────────────────────────────-inline QStringList optimize_methods() {return {"grid", "random"};}-// ── ML Label types ──────────────────────────────────────────────────────────-inline QStringList label_types() {return {"FIXLB", "MEANLB", "LEXLB", "TRENDLB", "BOLB"};}-// ── Splitter types ──────────────────────────────────────────────────────────-inline QStringList splitter_types() {return {"RollingSplitter", "ExpandingSplitter", "PurgedKFold"};}-// ── Signal generators ───────────────────────────────────────────────────────-inline QStringList signal_generators() {return {"RAND", "RANDX", "RANDNX", "RPROB", "RPROBX"};}-// ── Indicator signal modes ──────────────────────────────────────────────────-inline QStringList indicator_signal_modes() {return {"crossover", "threshold", "breakout", "mean_reversion", "filter"};}-// ── Returns analysis types ──────────────────────────────────────────────────-inline QStringList returns_analysis_types() {return {"cumulative", "rolling", "drawdown", "distribution", "benchmark_comparison"};}diff --git a/fincept-qt/src/services/economics/EconomicsService.cpp b/fincept-qt/src/services/economics/EconomicsService.cppnew file mode 100644index 000000000..7a6cc3850--- /dev/null+++ b/fincept-qt/src/services/economics/EconomicsService.cpp@@ -0,0 +1,123 @@+// src/services/economics/EconomicsService.cpp+#include "services/economics/EconomicsService.h"++#include "core/logging/Logger.h"+#include "python/PythonRunner.h"++#include <QDateTime>+#include <QJsonDocument>+#include <QJsonParseError>++namespace fincept::services {++EconomicsService& EconomicsService::instance() {+ static EconomicsService inst;+ return inst;+}++EconomicsService::EconomicsService(QObject* parent) : QObject(parent) {}++// ── Cache ─────────────────────────────────────────────────────────────────────++QString EconomicsService::cache_key(const QString& script,+ const QString& command,+ const QStringList& args) const {+ return script + ":" + command + ":" + args.join(",");+}++bool EconomicsService::is_cache_fresh(const QString& key) const {+ if (!cache_.contains(key)) return false;+ return (QDateTime::currentMSecsSinceEpoch() - cache_[key].fetched_at) < kCacheTtlMs;+}++void EconomicsService::invalidate(const QString& request_id) {+ cache_.remove(request_id);+}++// ── Execute ───────────────────────────────────────────────────────────────────++void EconomicsService::execute(const QString& source_id,+ const QString& script,+ const QString& command,+ const QStringList& args,+ const QString& request_id) {+ const QString key = cache_key(script, command, args);++ if (is_cache_fresh(key)) {+ LOG_DEBUG("EconomicsService", "Cache hit: " + key);+ EconomicsResult res;+ res.success = true;+ res.data = cache_[key].data;+ res.source_id = source_id;+ emit result_ready(request_id, res);+ return;+ }++ QStringList full_args;+ full_args << command << args;++ LOG_INFO("EconomicsService",+ QString("Run %1 %2 [%3]").arg(script, command, args.join(", ")));++ QPointer<EconomicsService> self = this;+ python::PythonRunner::instance().run(+ script, full_args,+ [self, source_id, request_id, key](python::PythonResult py) {+ if (!self) return;++ EconomicsResult res;+ res.source_id = source_id;++ if (!py.success) {+ res.success = false;+ res.error = py.error.isEmpty()+ ? QString("Script exited with code %1").arg(py.exit_code)+ : py.error;+ LOG_ERROR("EconomicsService", "Script failed: " + res.error);+ emit self->result_ready(request_id, res);+ return;+ }++ QString json_str = python::extract_json(py.output);+ if (json_str.isEmpty()) {+ res.success = false;+ res.error = "No JSON output from script";+ LOG_ERROR("EconomicsService", res.error);+ emit self->result_ready(request_id, res);+ return;+ }++ QJsonParseError err;+ QJsonDocument doc = QJsonDocument::fromJson(json_str.toUtf8(), &err);+ if (doc.isNull()) {+ res.success = false;+ res.error = "JSON parse error: " + err.errorString();+ LOG_ERROR("EconomicsService", res.error);+ emit self->result_ready(request_id, res);+ return;+ }++ // If the root is an array, wrap it+ if (doc.isArray())+ res.data = QJsonObject{{"data", doc.array()}};+ else+ res.data = doc.object();++ // Treat script-level error field as failure+ if (res.data.contains("error") && !res.data["error"].isNull()+ && !res.data["error"].toString().isEmpty()+ && !res.data.contains("data")) {+ res.success = false;+ res.error = res.data["error"].toString();+ emit self->result_ready(request_id, res);+ return;+ }++ res.success = true;+ self->cache_[key] = {res.data, QDateTime::currentMSecsSinceEpoch()};+ LOG_INFO("EconomicsService", "Result ready: " + request_id);+ emit self->result_ready(request_id, res);+ });+}++} // namespace fincept::servicesdiff --git a/fincept-qt/src/services/economics/EconomicsService.h b/fincept-qt/src/services/economics/EconomicsService.hnew file mode 100644index 000000000..8b5bb8f3e--- /dev/null+++ b/fincept-qt/src/services/economics/EconomicsService.h@@ -0,0 +1,61 @@+// src/services/economics/EconomicsService.h+// Singleton service for all economics data sources.+// Wraps PythonRunner, caches results, emits result_ready.+#pragma once++#include <QJsonObject>+#include <QMap>+#include <QObject>+#include <QString>+#include <QStringList>++namespace fincept::services {++struct EconomicsResult {+ bool success = false;+ QJsonObject data;+ QString error;+ QString source_id; // which provider produced this+};++class EconomicsService : public QObject {+ Q_OBJECT+ public:+ static EconomicsService& instance();++ /// Run a script command asynchronously.+ /// @param source_id caller tag echoed back in result_ready+ /// @param script python script filename+ /// @param command first CLI argument+ /// @param args additional arguments+ /// @param request_id unique id to correlate response+ void execute(const QString& source_id,+ const QString& script,+ const QString& command,+ const QStringList& args,+ const QString& request_id);++ /// Invalidate cache for a given request key (force re-fetch).+ void invalidate(const QString& request_id);++ signals:+ void result_ready(const QString& request_id, const fincept::services::EconomicsResult& result);++ private:+ explicit EconomicsService(QObject* parent = nullptr);+ Q_DISABLE_COPY(EconomicsService)++ struct CacheEntry {+ QJsonObject data;+ qint64 fetched_at = 0;+ };+ QMap<QString, CacheEntry> cache_;+ static constexpr int kCacheTtlMs = 10 * 60 * 1000; // 10 min++ QString cache_key(const QString& script,+ const QString& command,+ const QStringList& args) const;+ bool is_cache_fresh(const QString& key) const;+};++} // namespace fincept::servicesdiff --git a/fincept-qt/src/ui/widgets/PhoneCodeComboBox.cpp b/fincept-qt/src/ui/widgets/PhoneCodeComboBox.cppnew file mode 100644index 000000000..f63d2959a--- /dev/null+++ b/fincept-qt/src/ui/widgets/PhoneCodeComboBox.cpp@@ -0,0 +1,236 @@+#include "ui/widgets/PhoneCodeComboBox.h"++#include <QAbstractItemView>+#include <QCompleter>+#include <QLabel>+#include <QLineEdit>+#include <QResizeEvent>+#include <QScrollBar>+#include <QStandardItem>++namespace fincept::ui {++static const struct { const char* flag; const char* name; const char* code; } k_countries[] = {+ {"🇦🇫","Afghanistan","+93"},{"🇦🇱","Albania","+355"},{"🇩🇿","Algeria","+213"},+ {"🇦🇩","Andorra","+376"},{"🇦🇴","Angola","+244"},{"🇦🇬","Antigua & Barbuda","+1-268"},+ {"🇦🇷","Argentina","+54"},{"🇦🇲","Armenia","+374"},{"🇦🇺","Australia","+61"},+ {"🇦🇹","Austria","+43"},{"🇦🇿","Azerbaijan","+994"},{"🇧🇸","Bahamas","+1-242"},+ {"🇧🇭","Bahrain","+973"},{"🇧🇩","Bangladesh","+880"},{"🇧🇧","Barbados","+1-246"},+ {"🇧🇾","Belarus","+375"},{"🇧🇪","Belgium","+32"},{"🇧🇿","Belize","+501"},+ {"🇧🇯","Benin","+229"},{"🇧🇹","Bhutan","+975"},{"🇧🇴","Bolivia","+591"},+ {"🇧🇦","Bosnia & Herzegovina","+387"},{"🇧🇼","Botswana","+267"},{"🇧🇷","Brazil","+55"},+ {"🇧🇳","Brunei","+673"},{"🇧🇬","Bulgaria","+359"},{"🇧🇫","Burkina Faso","+226"},+ {"🇧🇮","Burundi","+257"},{"🇨🇻","Cabo Verde","+238"},{"🇰🇭","Cambodia","+855"},+ {"🇨🇲","Cameroon","+237"},{"🇨🇦","Canada","+1"},{"🇨🇫","Central African Republic","+236"},+ {"🇹🇩","Chad","+235"},{"🇨🇱","Chile","+56"},{"🇨🇳","China","+86"},+ {"🇨🇴","Colombia","+57"},{"🇰🇲","Comoros","+269"},{"🇨🇩","Congo (DRC)","+243"},+ {"🇨🇬","Congo (Republic)","+242"},{"🇨🇷","Costa Rica","+506"},{"🇭🇷","Croatia","+385"},+ {"🇨🇺","Cuba","+53"},{"🇨🇾","Cyprus","+357"},{"🇨🇿","Czech Republic","+420"},+ {"🇩🇰","Denmark","+45"},{"🇩🇯","Djibouti","+253"},{"🇩🇲","Dominica","+1-767"},+ {"🇩🇴","Dominican Republic","+1-809"},{"🇪🇨","Ecuador","+593"},{"🇪🇬","Egypt","+20"},+ {"🇸🇻","El Salvador","+503"},{"🇬🇶","Equatorial Guinea","+240"},{"🇪🇷","Eritrea","+291"},+ {"🇪🇪","Estonia","+372"},{"🇸🇿","Eswatini","+268"},{"🇪🇹","Ethiopia","+251"},+ {"🇫🇯","Fiji","+679"},{"🇫🇮","Finland","+358"},{"🇫🇷","France","+33"},+ {"🇬🇦","Gabon","+241"},{"🇬🇲","Gambia","+220"},{"🇬🇪","Georgia","+995"},+ {"🇩🇪","Germany","+49"},{"🇬🇭","Ghana","+233"},{"🇬🇷","Greece","+30"},+ {"🇬🇩","Grenada","+1-473"},{"🇬🇹","Guatemala","+502"},{"🇬🇳","Guinea","+224"},+ {"🇬🇼","Guinea-Bissau","+245"},{"🇬🇾","Guyana","+592"},{"🇭🇹","Haiti","+509"},+ {"🇭🇳","Honduras","+504"},{"🇭🇺","Hungary","+36"},{"🇮🇸","Iceland","+354"},+ {"🇮🇳","India","+91"},{"🇮🇩","Indonesia","+62"},{"🇮🇷","Iran","+98"},+ {"🇮🇶","Iraq","+964"},{"🇮🇪","Ireland","+353"},{"🇮🇱","Israel","+972"},+ {"🇮🇹","Italy","+39"},{"🇯🇲","Jamaica","+1-876"},{"🇯🇵","Japan","+81"},+ {"🇯🇴","Jordan","+962"},{"🇰🇿","Kazakhstan","+7"},{"🇰🇪","Kenya","+254"},+ {"🇰🇮","Kiribati","+686"},{"🇽🇰","Kosovo","+383"},{"🇰🇼","Kuwait","+965"},+ {"🇰🇬","Kyrgyzstan","+996"},{"🇱🇦","Laos","+856"},{"🇱🇻","Latvia","+371"},+ {"🇱🇧","Lebanon","+961"},{"🇱🇸","Lesotho","+266"},{"🇱🇷","Liberia","+231"},+ {"🇱🇾","Libya","+218"},{"🇱🇮","Liechtenstein","+423"},{"🇱🇹","Lithuania","+370"},+ {"🇱🇺","Luxembourg","+352"},{"🇲🇬","Madagascar","+261"},{"🇲🇼","Malawi","+265"},+ {"🇲🇾","Malaysia","+60"},{"🇲🇻","Maldives","+960"},{"🇲🇱","Mali","+223"},+ {"🇲🇹","Malta","+356"},{"🇲🇭","Marshall Islands","+692"},{"🇲🇷","Mauritania","+222"},+ {"🇲🇺","Mauritius","+230"},{"🇲🇽","Mexico","+52"},{"🇫🇲","Micronesia","+691"},+ {"🇲🇩","Moldova","+373"},{"🇲🇨","Monaco","+377"},{"🇲🇳","Mongolia","+976"},+ {"🇲🇪","Montenegro","+382"},{"🇲🇦","Morocco","+212"},{"🇲🇿","Mozambique","+258"},+ {"🇲🇲","Myanmar","+95"},{"🇳🇦","Namibia","+264"},{"🇳🇷","Nauru","+674"},+ {"🇳🇵","Nepal","+977"},{"🇳🇱","Netherlands","+31"},{"🇳🇿","New Zealand","+64"},+ {"🇳🇮","Nicaragua","+505"},{"🇳🇪","Niger","+227"},{"🇳🇬","Nigeria","+234"},+ {"🇲🇰","North Macedonia","+389"},{"🇳🇴","Norway","+47"},{"🇴🇲","Oman","+968"},+ {"🇵🇰","Pakistan","+92"},{"🇵🇼","Palau","+680"},{"🇵🇦","Panama","+507"},+ {"🇵🇬","Papua New Guinea","+675"},{"🇵🇾","Paraguay","+595"},{"🇵🇪","Peru","+51"},+ {"🇵🇭","Philippines","+63"},{"🇵🇱","Poland","+48"},{"🇵🇹","Portugal","+351"},+ {"🇶🇦","Qatar","+974"},{"🇷🇴","Romania","+40"},{"🇷🇺","Russia","+7"},+ {"🇷🇼","Rwanda","+250"},{"🇰🇳","Saint Kitts & Nevis","+1-869"},{"🇱🇨","Saint Lucia","+1-758"},+ {"🇻🇨","Saint Vincent & Grenadines","+1-784"},{"🇼🇸","Samoa","+685"},+ {"🇸🇲","San Marino","+378"},{"🇸🇹","São Tomé & Príncipe","+239"},+ {"🇸🇦","Saudi Arabia","+966"},{"🇸🇳","Senegal","+221"},{"🇷🇸","Serbia","+381"},+ {"🇸🇨","Seychelles","+248"},{"🇸🇱","Sierra Leone","+232"},{"🇸🇬","Singapore","+65"},+ {"🇸🇰","Slovakia","+421"},{"🇸🇮","Slovenia","+386"},{"🇸🇧","Solomon Islands","+677"},+ {"🇸🇴","Somalia","+252"},{"🇿🇦","South Africa","+27"},{"🇸🇸","South Sudan","+211"},+ {"🇪🇸","Spain","+34"},{"🇱🇰","Sri Lanka","+94"},{"🇸🇩","Sudan","+249"},+ {"🇸🇷","Suriname","+597"},{"🇸🇪","Sweden","+46"},{"🇨🇭","Switzerland","+41"},+ {"🇸🇾","Syria","+963"},{"🇹🇼","Taiwan","+886"},{"🇹🇯","Tajikistan","+992"},+ {"🇹🇿","Tanzania","+255"},{"🇹🇭","Thailand","+66"},{"🇹🇱","Timor-Leste","+670"},+ {"🇹🇬","Togo","+228"},{"🇹🇴","Tonga","+676"},{"🇹🇹","Trinidad & Tobago","+1-868"},+ {"🇹🇳","Tunisia","+216"},{"🇹🇷","Turkey","+90"},{"🇹🇲","Turkmenistan","+993"},+ {"🇹🇻","Tuvalu","+688"},{"🇺🇬","Uganda","+256"},{"🇺🇦","Ukraine","+380"},+ {"🇦🇪","United Arab Emirates","+971"},{"🇬🇧","United Kingdom","+44"},+ {"🇺🇸","United States","+1"},{"🇺🇾","Uruguay","+598"},{"🇺🇿","Uzbekistan","+998"},+ {"🇻🇺","Vanuatu","+678"},{"🇻🇦","Vatican City","+379"},{"🇻🇪","Venezuela","+58"},+ {"🇻🇳","Vietnam","+84"},{"🇾🇪","Yemen","+967"},{"🇿🇲","Zambia","+260"},+ {"🇿🇼","Zimbabwe","+263"},+};++static const char* k_scrollbar_style =+ "QScrollBar:vertical { background:#0a0a0a; width:5px; border:none; }"+ "QScrollBar::handle:vertical { background:#2a2a2a; border-radius:2px; min-height:20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }";++static const char* k_popup_style =+ "QAbstractItemView {"+ " background:#111111; color:#e5e5e5; border:1px solid #2a2a2a;"+ " selection-background-color:#1c1400; selection-color:#d97706;"+ " font-size:13px; font-family:'Consolas',monospace; outline:none; padding:2px; }"+ "QAbstractItemView::item { padding:5px 12px; min-height:28px; border:none; }"+ "QScrollBar:vertical { background:#0a0a0a; width:5px; border:none; }"+ "QScrollBar::handle:vertical { background:#2a2a2a; border-radius:2px; min-height:20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }";++PhoneCodeComboBox::PhoneCodeComboBox(QWidget* parent) : QComboBox(parent) {+ model_ = new QStandardItemModel(this);++ setEditable(true);+ setInsertPolicy(QComboBox::NoInsert);+ setMaxVisibleItems(12);++ populate();+ setModel(model_);++ // Wide enough to show full country names without clipping+ view()->setMinimumWidth(320);+ view()->setStyleSheet(k_popup_style);+ view()->verticalScrollBar()->setStyleSheet(k_scrollbar_style);++ // Completer: MatchContains so typing any part of name/code filters the list+ auto* comp = new QCompleter(model_, this);+ comp->setCaseSensitivity(Qt::CaseInsensitive);+ comp->setFilterMode(Qt::MatchContains);+ comp->setCompletionMode(QCompleter::PopupCompletion);+ comp->setCompletionColumn(0);+ if (auto* popup = comp->popup()) {+ popup->setMinimumWidth(320);+ popup->setStyleSheet(k_popup_style);+ popup->verticalScrollBar()->setStyleSheet(k_scrollbar_style);+ }+ setCompleter(comp);++ // When completer picks a match, sync the index and display+ connect(comp, QOverload<const QModelIndex&>::of(&QCompleter::activated),+ this, [this](const QModelIndex& idx) {+ int row = idx.row();+ setCurrentIndex(row);+ sync_display(row);+ });++ setStyleSheet(+ "QComboBox {"+ " background:#0a0a0a; color:#e5e5e5; border:1px solid #1a1a1a;"+ " padding:4px 8px; font-size:14px;"+ " font-family:'Consolas','Courier New',monospace; }"+ "QComboBox:focus { border:1px solid #333333; }"+ // Reserve space on the right for the custom drop-down button+ "QComboBox::drop-down {"+ " subcontrol-origin: padding; subcontrol-position: right center;"+ " width: 28px; border-left: 1px solid #1a1a1a; background: #111111;"+ " border-radius: 0 2px 2px 0; }"+ // Use the unicode chevron as the arrow via a UTF-8 string trick+ "QComboBox::down-arrow {"+ " image: none; width:0; height:0; }"+ "QComboBox QAbstractItemView {"+ " background:#111111; color:#e5e5e5; border:1px solid #2a2a2a;"+ " selection-background-color:#1c1400; selection-color:#d97706;"+ " font-size:13px; font-family:'Consolas',monospace; outline:none; padding:2px; }"+ "QComboBox QAbstractItemView::item { padding:5px 12px; min-height:28px; border:none; }"+ "QComboBox QAbstractItemView QScrollBar:vertical { background:#0a0a0a; width:5px; border:none; }"+ "QComboBox QAbstractItemView QScrollBar::handle:vertical { background:#2a2a2a; border-radius:2px; }"+ "QComboBox QAbstractItemView QScrollBar::add-line:vertical,"+ "QComboBox QAbstractItemView QScrollBar::sub-line:vertical { height:0; }");++ // Draw a proper chevron "⌄" in the drop-down button area via a QLabel overlay+ arrow_lbl_ = new QLabel("⌄", this);+ arrow_lbl_->setAlignment(Qt::AlignCenter);+ arrow_lbl_->setStyleSheet(+ "color:#707070; font-size:16px; background:transparent;"+ "font-family:'Consolas',monospace;");+ arrow_lbl_->setAttribute(Qt::WA_TransparentForMouseEvents);+ arrow_lbl_->setGeometry(width() - 28, 0, 28, height());++ if (auto* le = lineEdit()) {+ le->setStyleSheet(+ "QLineEdit { background:transparent; color:#e5e5e5; border:none;"+ " font-size:14px; font-family:'Consolas','Courier New',monospace; padding:0; }");+ le->setPlaceholderText("Search country…");++ // When user manually edits the field, try to match and update dial code+ connect(le, &QLineEdit::textEdited, this, [this](const QString& text) {+ // Try to find an exact code match first (e.g. user typed "+91")+ for (int i = 0; i < model_->rowCount(); i++) {+ if (model_->item(i)->data(Qt::UserRole).toString().compare(+ text.trimmed(), Qt::CaseInsensitive) == 0) {+ setCurrentIndex(i);+ return;+ }+ }+ });+ }++ // Default to United States+ set_dial_code("+1");++ // On selection from native dropdown: show compact flag + code+ connect(this, &QComboBox::activated, this, &PhoneCodeComboBox::sync_display);+}++void PhoneCodeComboBox::populate() {+ for (const auto& c : k_countries) {+ auto* item = new QStandardItem;+ QString flag = QString::fromUtf8(c.flag);+ QString name = QString::fromUtf8(c.name);+ QString code = QString::fromUtf8(c.code);+ item->setText(QString("%1 %2 %3").arg(flag, name, code));+ item->setData(code, Qt::UserRole);+ item->setData(flag, Qt::UserRole + 1);+ model_->appendRow(item);+ }+}++void PhoneCodeComboBox::sync_display(int index) {+ if (index < 0 || index >= model_->rowCount()) return;+ QString flag = model_->item(index)->data(Qt::UserRole + 1).toString();+ QString code = model_->item(index)->data(Qt::UserRole).toString();+ if (auto* le = lineEdit())+ le->setText(QString("%1 %2").arg(flag, code));+}++QString PhoneCodeComboBox::dial_code() const {+ int idx = currentIndex();+ if (idx >= 0 && idx < model_->rowCount())+ return model_->item(idx)->data(Qt::UserRole).toString();+ return {};+}++void PhoneCodeComboBox::resizeEvent(QResizeEvent* e) {+ QComboBox::resizeEvent(e);+ if (arrow_lbl_)+ arrow_lbl_->setGeometry(width() - 28, 0, 28, height());+}++void PhoneCodeComboBox::set_dial_code(const QString& code) {+ for (int i = 0; i < model_->rowCount(); i++) {+ if (model_->item(i)->data(Qt::UserRole).toString() == code) {+ setCurrentIndex(i);+ sync_display(i);+ return;+ }+ }+}++} // namespace fincept::uidiff --git a/fincept-qt/src/ui/widgets/PhoneCodeComboBox.h b/fincept-qt/src/ui/widgets/PhoneCodeComboBox.hnew file mode 100644index 000000000..992574e74--- /dev/null+++ b/fincept-qt/src/ui/widgets/PhoneCodeComboBox.h@@ -0,0 +1,32 @@+#pragma once+#include <QComboBox>+#include <QLabel>+#include <QResizeEvent>+#include <QStandardItemModel>+#include <QString>++namespace fincept::ui {++/// Searchable country dial-code selector using QStandardItemModel.+/// Dropdown shows: flag + country name + dial code (searchable by any field).+/// Closed field shows compact: flag + dial code only (e.g. "🇺🇸 +1").+/// Use dial_code() to retrieve the E.164 prefix (e.g. "+1").+class PhoneCodeComboBox : public QComboBox {+ Q_OBJECT+ public:+ explicit PhoneCodeComboBox(QWidget* parent = nullptr);++ QString dial_code() const;+ void set_dial_code(const QString& code);++ protected:+ void resizeEvent(QResizeEvent* e) override;++ private:+ QStandardItemModel* model_ = nullptr;+ QLabel* arrow_lbl_ = nullptr;+ void populate();+ void sync_display(int index);+};++} // namespace fincept::ui