Skip to content

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

node editor update

tilakpatel221af16b67f0c2
diff --git a/.github/workflows/build-installer.yml b/.github/workflows/build-installer.yml
new file mode 100644
index 000000000..987637a74
--- /dev/null
+++ b/.github/workflows/build-installer.yml
@@ -0,0 +1,320 @@
+name: Build Installers (QtIFW)
+
+on:
+ workflow_dispatch:
+ push:
+ tags:
+ - 'v*'
+
+env:
+ BUILD_TYPE: Release
+ QT_VERSION: "6.8.3"
+ QT_MODULES: "qtcharts qtwebsockets qtmultimedia"
+ QT_IFW_VERSION: "4.8"
+
+jobs:
+ build-installer:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ # ---- Windows x64 ----
+ - os: windows-2022
+ arch: x64
+ platform: Windows
+ artifact: FinceptTerminal-Windows-x64-setup
+ exe: FinceptTerminal.exe
+ qt_arch: win64_msvc2022_64
+ cmake_extra: ""
+ installer_ext: ".exe"
+
+ # ---- Linux x64 ----
+ - os: ubuntu-22.04
+ arch: x64
+ platform: Linux
+ artifact: FinceptTerminal-Linux-x64-setup
+ exe: FinceptTerminal
+ qt_arch: ""
+ cmake_extra: ""
+ installer_ext: ".run"
+
+ # ---- macOS ARM64 (Apple Silicon) ----
+ - os: macos-15
+ arch: arm64
+ platform: macOS
+ artifact: FinceptTerminal-macOS-arm64-setup
+ exe: FinceptTerminal
+ qt_arch: clang_64
+ cmake_extra: "-DCMAKE_OSX_ARCHITECTURES=arm64"
+ installer_ext: ".app"
+
+ runs-on: ${{ matrix.os }}
+ name: Installer ${{ matrix.platform }} ${{ matrix.arch }}
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ submodules: recursive
+
+ # ---- ccache (macOS / Linux) ----
+ - name: Set up ccache
+ if: runner.os != 'Windows'
+ uses: hendrikmuhs/ccache-action@v1
+ with:
+ key: installer-${{ matrix.platform }}-${{ matrix.arch }}-${{ env.QT_VERSION }}
+ max-size: 500M
+ update-package-index: true
+
+ # ---- System dependencies (Linux) ----
+ - name: Install system dependencies (Linux)
+ if: runner.os == 'Linux'
+ run: |
+ sudo add-apt-repository universe -y
+ sudo apt-get update -qq
+ sudo apt-get install -y \
+ cmake ninja-build g++ \
+ qt6-base-dev qt6-base-private-dev \
+ qt6-tools-dev qt6-tools-dev-tools \
+ libqt6charts6-dev libqt6websockets6-dev \
+ qt6-multimedia-dev libqt6multimediawidgets6 \
+ libqt6svg6-dev libqt6concurrent6 \
+ libgl1-mesa-dev libglu1-mesa-dev \
+ libxkbcommon-dev libxkbcommon-x11-0 \
+ libxcb-cursor0 libxcb-icccm4 libxcb-image0 \
+ libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 \
+ libxcb-xinerama0 libxcb-xkb1 \
+ pkg-config zip
+
+ # ---- Qt6 (Windows / macOS) ----
+ - name: Install Qt6
+ if: runner.os != 'Linux'
+ uses: jurplel/install-qt-action@v4
+ with:
+ version: ${{ env.QT_VERSION }}
+ arch: ${{ matrix.qt_arch }}
+ modules: ${{ env.QT_MODULES }}
+ cache: true
+ cache-key-prefix: qt-installer-${{ matrix.platform }}-${{ matrix.arch }}
+
+ # ---- Qt Installer Framework ----
+ - name: Install Qt Installer Framework
+ shell: bash
+ run: |
+ pip install aqtinstall
+ if [ "${{ runner.os }}" == "Windows" ]; then
+ aqt install-tool windows desktop qt.tools.ifw.${{ env.QT_IFW_VERSION }} \
+ --outputdir "${{ runner.temp }}/qtifw"
+ echo "QT_IFW_DIR=${{ runner.temp }}/qtifw/Tools/QtInstallerFramework/${{ env.QT_IFW_VERSION }}" >> $GITHUB_ENV
+ elif [ "${{ runner.os }}" == "macOS" ]; then
+ aqt install-tool mac desktop qt.tools.ifw.${{ env.QT_IFW_VERSION }} \
+ --outputdir "${{ runner.temp }}/qtifw"
+ echo "QT_IFW_DIR=${{ runner.temp }}/qtifw/Tools/QtInstallerFramework/${{ env.QT_IFW_VERSION }}" >> $GITHUB_ENV
+ else
+ aqt install-tool linux desktop qt.tools.ifw.${{ env.QT_IFW_VERSION }} \
+ --outputdir "${{ runner.temp }}/qtifw"
+ echo "QT_IFW_DIR=${{ runner.temp }}/qtifw/Tools/QtInstallerFramework/${{ env.QT_IFW_VERSION }}" >> $GITHUB_ENV
+ fi
+ echo "QtIFW installed at: ${{ runner.temp }}/qtifw"
+ ls "${{ runner.temp }}/qtifw/Tools/QtInstallerFramework/" || true
+
+ # ---- Configure CMake ----
+ - name: Configure CMake (Linux)
+ if: runner.os == 'Linux'
+ working-directory: fincept-qt
+ run: |
+ cmake -B build -G Ninja \
+ -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
+ -DCMAKE_C_COMPILER_LAUNCHER=ccache \
+ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
+ -DDEPLOY_QT=ON \
+ -DFINCEPT_BUILD_INSTALLER=ON \
+ ${{ matrix.cmake_extra }}
+
+ - name: Configure CMake (Windows / macOS)
+ if: runner.os != 'Linux'
+ shell: bash
+ working-directory: fincept-qt
+ run: |
+ cmake -B build \
+ -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
+ -DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
+ -DDEPLOY_QT=ON \
+ -DFINCEPT_BUILD_INSTALLER=ON \
+ ${{ runner.os == 'macOS' && '-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache' || '' }} \
+ ${{ matrix.cmake_extra }}
+
+ # ---- Build ----
+ - name: Build
+ shell: bash
+ working-directory: fincept-qt
+ run: cmake --build build --config ${{ env.BUILD_TYPE }} --parallel $(nproc 2>/dev/null || sysctl -n hw.logicalcpu 2>/dev/null || echo 3)
+
+ # ---- Verify binary ----
+ - name: Verify build output
+ shell: bash
+ working-directory: fincept-qt
+ run: |
+ if [ "${{ runner.os }}" == "Windows" ]; then
+ BINARY="build/Release/${{ matrix.exe }}"
+ else
+ BINARY="build/${{ matrix.exe }}"
+ fi
+ if [ ! -f "$BINARY" ]; then
+ echo "::error::Binary not found at $BINARY"
+ exit 1
+ fi
+ echo "Binary verified: $BINARY"
+ ls -lh "$BINARY"
+
+ # ---- Windows: deploy Qt DLLs before packaging ----
+ - name: Deploy Qt DLLs (Windows)
+ if: runner.os == 'Windows'
+ shell: bash
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ BUILD_DIR="build/Release"
+
+ # Run windeployqt
+ WDQT="${QT_ROOT_DIR}/bin/windeployqt.exe"
+ if [ -f "$WDQT" ]; then
+ echo "Running windeployqt..."
+ "$WDQT" \
+ --release \
+ --no-translations \
+ --compiler-runtime \
+ --include-soft-plugins \
+ --force \
+ "${BUILD_DIR}/${{ matrix.exe }}"
+ else
+ echo "::warning::windeployqt not found"
+ fi
+
+ QT_BIN="${QT_ROOT_DIR}/bin"
+ QT_PLUGINS="${QT_ROOT_DIR}/plugins"
+
+ # Qt Core DLLs (belt+suspenders — windeployqt should handle these)
+ for qt_dll in \
+ Qt6Core.dll Qt6Gui.dll Qt6Widgets.dll \
+ Qt6Charts.dll Qt6PrintSupport.dll \
+ Qt6Network.dll Qt6Sql.dll Qt6Concurrent.dll \
+ Qt6WebSockets.dll \
+ Qt6Multimedia.dll Qt6MultimediaWidgets.dll \
+ Qt6OpenGL.dll Qt6OpenGLWidgets.dll \
+ Qt6Svg.dll Qt6Xml.dll Qt6TextToSpeech.dll; do
+ if [ -f "${QT_BIN}/${qt_dll}" ] && [ ! -f "${BUILD_DIR}/${qt_dll}" ]; then
+ cp "${QT_BIN}/${qt_dll}" "${BUILD_DIR}/"
+ fi
+ done
+
+ # OpenSSL DLLs
+ for ssl_dll in \
+ libssl-3-x64.dll libcrypto-3-x64.dll \
+ libssl-3.dll libcrypto-3.dll; do
+ if [ -f "${QT_BIN}/${ssl_dll}" ] && [ ! -f "${BUILD_DIR}/${ssl_dll}" ]; then
+ cp "${QT_BIN}/${ssl_dll}" "${BUILD_DIR}/"
+ fi
+ done
+
+ # MSVC Runtime DLLs
+ for vcrt_dll in \
+ vcruntime140.dll vcruntime140_1.dll vcruntime140_2.dll \
+ msvcp140.dll msvcp140_1.dll msvcp140_2.dll \
+ concrt140.dll vccorlib140.dll; do
+ SYS32="/c/Windows/System32/${vcrt_dll}"
+ if [ -f "$SYS32" ] && [ ! -f "${BUILD_DIR}/${vcrt_dll}" ]; then
+ cp "$SYS32" "${BUILD_DIR}/"
+ fi
+ done
+
+ # Qt plugin directories
+ for plugin_dir in platforms sqldrivers imageformats iconengines styles tls \
+ multimedia texttospeech networkinformation platforminputcontexts \
+ printsupport generic; do
+ if [ -d "${QT_PLUGINS}/${plugin_dir}" ]; then
+ mkdir -p "${BUILD_DIR}/${plugin_dir}"
+ cp -n "${QT_PLUGINS}/${plugin_dir}/"*.dll "${BUILD_DIR}/${plugin_dir}/" 2>/dev/null || true
+ fi
+ done
+
+ # D3D / OpenGL fallback
+ for d3d_dll in d3dcompiler_47.dll opengl32sw.dll libEGL.dll libGLESv2.dll \
+ dxcompiler.dll dxil.dll; do
+ if [ -f "${QT_BIN}/${d3d_dll}" ] && [ ! -f "${BUILD_DIR}/${d3d_dll}" ]; then
+ cp "${QT_BIN}/${d3d_dll}" "${BUILD_DIR}/"
+ fi
+ done
+
+ # ICU DLLs
+ for icu_dll in "${QT_BIN}"/icu*.dll; do
+ base=$(basename "$icu_dll")
+ if [ -f "$icu_dll" ] && [ ! -f "${BUILD_DIR}/${base}" ]; then
+ cp "$icu_dll" "${BUILD_DIR}/"
+ fi
+ done
+
+ # qt.conf
+ printf '[Paths]\nPrefix = .\nPlugins = .\nLibraries = .\n' > "${BUILD_DIR}/qt.conf"
+
+ echo "=== Build dir contents ($(find "${BUILD_DIR}" -type f | wc -l) files) ==="
+
+ # ---- Generate installer ----
+ - name: Generate Installer (CPack IFW)
+ shell: bash
+ working-directory: fincept-qt/build
+ run: |
+ echo "QT_IFW_DIR=${QT_IFW_DIR}"
+ ls "${QT_IFW_DIR}/bin/" || true
+
+ # Add QtIFW bin to PATH so CPack can find binarycreator
+ export PATH="${QT_IFW_DIR}/bin:${PATH}"
+ which binarycreator || echo "::warning::binarycreator not on PATH"
+
+ if [ "${{ runner.os }}" == "Windows" ]; then
+ cpack -G IFW -C ${{ env.BUILD_TYPE }} --verbose
+ else
+ cpack -G IFW --verbose
+ fi
+
+ echo ""
+ echo "=== Generated installer ==="
+ ls -lh FinceptTerminal-*
+
+ # ---- Upload installer artifact ----
+ - name: Upload Installer
+ uses: actions/upload-artifact@v4
+ with:
+ name: ${{ matrix.artifact }}
+ path: |
+ fincept-qt/build/FinceptTerminal-*-setup*
+ retention-days: 30
+
+ # ---- Release: attach installers to GitHub Release ----
+ release:
+ needs: build-installer
+ runs-on: ubuntu-latest
+ name: Attach Installers to Release
+ if: "!cancelled() && needs.build-installer.result == 'success' && startsWith(github.ref, 'refs/tags/')"
+ permissions:
+ contents: write
+
+ steps:
+ - name: Download all installer artifacts
+ uses: actions/download-artifact@v4
+ with:
+ path: installers
+
+ - name: List installers
+ run: |
+ echo "=== Downloaded installer artifacts ==="
+ find installers -type f | sort
+ ls -lhR installers/
+
+ - name: Attach installers to release
+ uses: softprops/action-gh-release@v2
+ with:
+ tag_name: ${{ github.ref_name }}
+ files: |
+ installers/**/*-setup*
+ fail_on_unmatched_files: false
diff --git a/fincept-qt/.cache/clangd/index/AlphaArenaScreen.cpp.188545A3697024DD.idx b/fincept-qt/.cache/clangd/index/AlphaArenaScreen.cpp.188545A3697024DD.idx
index 079103a83..13fb84313 100644
Binary files a/fincept-qt/.cache/clangd/index/AlphaArenaScreen.cpp.188545A3697024DD.idx and b/fincept-qt/.cache/clangd/index/AlphaArenaScreen.cpp.188545A3697024DD.idx differ
diff --git a/fincept-qt/.cache/clangd/index/AppConfig.h.7F12E88573E3E592.idx b/fincept-qt/.cache/clangd/index/AppConfig.h.7F12E88573E3E592.idx
index 109e46f8b..77a5e8d8a 100644
Binary files a/fincept-qt/.cache/clangd/index/AppConfig.h.7F12E88573E3E592.idx and b/fincept-qt/.cache/clangd/index/AppConfig.h.7F12E88573E3E592.idx differ
diff --git a/fincept-qt/.cache/clangd/index/AuthManager.h.8BB5B9B9C28CB70F.idx b/fincept-qt/.cache/clangd/index/AuthManager.h.8BB5B9B9C28CB70F.idx
index c05f53e45..b00e86253 100644
Binary files a/fincept-qt/.cache/clangd/index/AuthManager.h.8BB5B9B9C28CB70F.idx and b/fincept-qt/.cache/clangd/index/AuthManager.h.8BB5B9B9C28CB70F.idx differ
diff --git a/fincept-qt/.cache/clangd/index/ConflictMonitorPanel.cpp.30520CF4CB984C8A.idx b/fincept-qt/.cache/clangd/index/ConflictMonitorPanel.cpp.30520CF4CB984C8A.idx
index 9377a2019..2ab7ab3fd 100644
Binary files a/fincept-qt/.cache/clangd/index/ConflictMonitorPanel.cpp.30520CF4CB984C8A.idx and b/fincept-qt/.cache/clangd/index/ConflictMonitorPanel.cpp.30520CF4CB984C8A.idx differ
diff --git a/fincept-qt/.cache/clangd/index/DBnomicsScreen.cpp.DD1865D4F18E9A99.idx b/fincept-qt/.cache/clangd/index/DBnomicsScreen.cpp.DD1865D4F18E9A99.idx
index 00a99efa7..b59cb2b87 100644
Binary files a/fincept-qt/.cache/clangd/index/DBnomicsScreen.cpp.DD1865D4F18E9A99.idx and b/fincept-qt/.cache/clangd/index/DBnomicsScreen.cpp.DD1865D4F18E9A99.idx differ
diff --git a/fincept-qt/.cache/clangd/index/DashboardCanvas.cpp.460534CD66F8E356.idx b/fincept-qt/.cache/clangd/index/DashboardCanvas.cpp.460534CD66F8E356.idx
index 26adf0b6d..b6559b583 100644
Binary files a/fincept-qt/.cache/clangd/index/DashboardCanvas.cpp.460534CD66F8E356.idx and b/fincept-qt/.cache/clangd/index/DashboardCanvas.cpp.460534CD66F8E356.idx differ
diff --git a/fincept-qt/.cache/clangd/index/DashboardCanvas.h.0BD2AC0C74EA1B64.idx b/fincept-qt/.cache/clangd/index/DashboardCanvas.h.0BD2AC0C74EA1B64.idx
index 4fb35f557..2232d2478 100644
Binary files a/fincept-qt/.cache/clangd/index/DashboardCanvas.h.0BD2AC0C74EA1B64.idx and b/fincept-qt/.cache/clangd/index/DashboardCanvas.h.0BD2AC0C74EA1B64.idx differ
diff --git a/fincept-qt/.cache/clangd/index/DashboardScreen.cpp.A85C1CA6D4EF5A15.idx b/fincept-qt/.cache/clangd/index/DashboardScreen.cpp.A85C1CA6D4EF5A15.idx
index 9da0c6419..bbd664f65 100644
Binary files a/fincept-qt/.cache/clangd/index/DashboardScreen.cpp.A85C1CA6D4EF5A15.idx and b/fincept-qt/.cache/clangd/index/DashboardScreen.cpp.A85C1CA6D4EF5A15.idx differ
diff --git a/fincept-qt/.cache/clangd/index/DashboardScreen.h.D8F8E509069D6DB1.idx b/fincept-qt/.cache/clangd/index/DashboardScreen.h.D8F8E509069D6DB1.idx
index 3fa1f0c51..75ff5bf8d 100644
Binary files a/fincept-qt/.cache/clangd/index/DashboardScreen.h.D8F8E509069D6DB1.idx and b/fincept-qt/.cache/clangd/index/DashboardScreen.h.D8F8E509069D6DB1.idx differ
diff --git a/fincept-qt/.cache/clangd/index/DataMappingScreen.cpp.3E53FB863B652EB2.idx b/fincept-qt/.cache/clangd/index/DataMappingScreen.cpp.3E53FB863B652EB2.idx
index 97931a3bc..59a86b05d 100644
Binary files a/fincept-qt/.cache/clangd/index/DataMappingScreen.cpp.3E53FB863B652EB2.idx and b/fincept-qt/.cache/clangd/index/DataMappingScreen.cpp.3E53FB863B652EB2.idx differ
diff --git a/fincept-qt/.cache/clangd/index/DataSourcesScreen.cpp.5DA094D79081B554.idx b/fincept-qt/.cache/clangd/index/DataSourcesScreen.cpp.5DA094D79081B554.idx
index c76b25119..c6affba1f 100644
Binary files a/fincept-qt/.cache/clangd/index/DataSourcesScreen.cpp.5DA094D79081B554.idx and b/fincept-qt/.cache/clangd/index/DataSourcesScreen.cpp.5DA094D79081B554.idx differ
diff --git a/fincept-qt/.cache/clangd/index/EconomicCalendarWidget.cpp.28F38012398CFFB7.idx b/fincept-qt/.cache/clangd/index/EconomicCalendarWidget.cpp.28F38012398CFFB7.idx
index aba5c7a3c..704d51508 100644
Binary files a/fincept-qt/.cache/clangd/index/EconomicCalendarWidget.cpp.28F38012398CFFB7.idx and b/fincept-qt/.cache/clangd/index/EconomicCalendarWidget.cpp.28F38012398CFFB7.idx differ
diff --git a/fincept-qt/.cache/clangd/index/EquityResearchScreen.cpp.862F86FD34B4F5B4.idx b/fincept-qt/.cache/clangd/index/EquityResearchScreen.cpp.862F86FD34B4F5B4.idx
index 6705c3920..065a1cf22 100644
Binary files a/fincept-qt/.cache/clangd/index/EquityResearchScreen.cpp.862F86FD34B4F5B4.idx and b/fincept-qt/.cache/clangd/index/EquityResearchScreen.cpp.862F86FD34B4F5B4.idx differ
diff --git a/fincept-qt/.cache/clangd/index/EquityResearchScreen.h.662F06C6900DB60F.idx b/fincept-qt/.cache/clangd/index/EquityResearchScreen.h.662F06C6900DB60F.idx
index 3f930ffa1..4756a0ae7 100644
Binary files a/fincept-qt/.cache/clangd/index/EquityResearchScreen.h.662F06C6900DB60F.idx and b/fincept-qt/.cache/clangd/index/EquityResearchScreen.h.662F06C6900DB60F.idx differ
diff --git a/fincept-qt/.cache/clangd/index/GeopoliticsScreen.cpp.2C195C1C24A6D23C.idx b/fincept-qt/.cache/clangd/index/GeopoliticsScreen.cpp.2C195C1C24A6D23C.idx
index c572043bd..0efc94df2 100644
Binary files a/fincept-qt/.cache/clangd/index/GeopoliticsScreen.cpp.2C195C1C24A6D23C.idx and b/fincept-qt/.cache/clangd/index/GeopoliticsScreen.cpp.2C195C1C24A6D23C.idx differ
diff --git a/fincept-qt/.cache/clangd/index/GeopoliticsScreen.h.02DA00D4A54CF596.idx b/fincept-qt/.cache/clangd/index/GeopoliticsScreen.h.02DA00D4A54CF596.idx
index 4e087adb6..6fe5fed64 100644
Binary files a/fincept-qt/.cache/clangd/index/GeopoliticsScreen.h.02DA00D4A54CF596.idx and b/fincept-qt/.cache/clangd/index/GeopoliticsScreen.h.02DA00D4A54CF596.idx differ
diff --git a/fincept-qt/.cache/clangd/index/HDXDataPanel.cpp.69065C28382041FA.idx b/fincept-qt/.cache/clangd/index/HDXDataPanel.cpp.69065C28382041FA.idx
index 140eefb01..5590d9984 100644
Binary files a/fincept-qt/.cache/clangd/index/HDXDataPanel.cpp.69065C28382041FA.idx and b/fincept-qt/.cache/clangd/index/HDXDataPanel.cpp.69065C28382041FA.idx differ
diff --git a/fincept-qt/.cache/clangd/index/HDXDataPanel.h.C5F107C56EE7BA87.idx b/fincept-qt/.cache/clangd/index/HDXDataPanel.h.C5F107C56EE7BA87.idx
index 95e8277a4..86684cf0f 100644
Binary files a/fincept-qt/.cache/clangd/index/HDXDataPanel.h.C5F107C56EE7BA87.idx and b/fincept-qt/.cache/clangd/index/HDXDataPanel.h.C5F107C56EE7BA87.idx differ
diff --git a/fincept-qt/.cache/clangd/index/IStatefulScreen.h.6567C5509FFE9E5A.idx b/fincept-qt/.cache/clangd/index/IStatefulScreen.h.6567C5509FFE9E5A.idx
new file mode 100644
index 000000000..15fb03578
Binary files /dev/null and b/fincept-qt/.cache/clangd/index/IStatefulScreen.h.6567C5509FFE9E5A.idx differ
diff --git a/fincept-qt/.cache/clangd/index/LlmConfigSection.cpp.DC164602779CBA1E.idx b/fincept-qt/.cache/clangd/index/LlmConfigSection.cpp.DC164602779CBA1E.idx
index beaf1ae34..88f35388e 100644
Binary files a/fincept-qt/.cache/clangd/index/LlmConfigSection.cpp.DC164602779CBA1E.idx and b/fincept-qt/.cache/clangd/index/LlmConfigSection.cpp.DC164602779CBA1E.idx differ
diff --git a/fincept-qt/.cache/clangd/index/MaritimeScreen.cpp.9C72060BDDA07734.idx b/fincept-qt/.cache/clangd/index/MaritimeScreen.cpp.9C72060BDDA07734.idx
index 229d12362..fce8a0a2b 100644
Binary files a/fincept-qt/.cache/clangd/index/MaritimeScreen.cpp.9C72060BDDA07734.idx and b/fincept-qt/.cache/clangd/index/MaritimeScreen.cpp.9C72060BDDA07734.idx differ
diff --git a/fincept-qt/.cache/clangd/index/MaritimeScreen.h.5E988B1463344A52.idx b/fincept-qt/.cache/clangd/index/MaritimeScreen.h.5E988B1463344A52.idx
index 125b5344d..dac4ea5cb 100644
Binary files a/fincept-qt/.cache/clangd/index/MaritimeScreen.h.5E988B1463344A52.idx and b/fincept-qt/.cache/clangd/index/MaritimeScreen.h.5E988B1463344A52.idx differ
diff --git a/fincept-qt/.cache/clangd/index/MarketPanel.cpp.B3E0F57BF6B23452.idx b/fincept-qt/.cache/clangd/index/MarketPanel.cpp.B3E0F57BF6B23452.idx
index b1cbe54b5..b6415f195 100644
Binary files a/fincept-qt/.cache/clangd/index/MarketPanel.cpp.B3E0F57BF6B23452.idx and b/fincept-qt/.cache/clangd/index/MarketPanel.cpp.B3E0F57BF6B23452.idx differ
diff --git a/fincept-qt/.cache/clangd/index/MarketPulsePanel.cpp.05DE3AB960DECCE3.idx b/fincept-qt/.cache/clangd/index/MarketPulsePanel.cpp.05DE3AB960DECCE3.idx
index 68da297d4..d55ffb592 100644
Binary files a/fincept-qt/.cache/clangd/index/MarketPulsePanel.cpp.05DE3AB960DECCE3.idx and b/fincept-qt/.cache/clangd/index/MarketPulsePanel.cpp.05DE3AB960DECCE3.idx differ
diff --git a/fincept-qt/.cache/clangd/index/MarketsScreen.cpp.AB596983EDA612DF.idx b/fincept-qt/.cache/clangd/index/MarketsScreen.cpp.AB596983EDA612DF.idx
index c8acc1794..be813ec77 100644
Binary files a/fincept-qt/.cache/clangd/index/MarketsScreen.cpp.AB596983EDA612DF.idx and b/fincept-qt/.cache/clangd/index/MarketsScreen.cpp.AB596983EDA612DF.idx differ
diff --git a/fincept-qt/.cache/clangd/index/MarketsScreen.h.284E6B065C972F74.idx b/fincept-qt/.cache/clangd/index/MarketsScreen.h.284E6B065C972F74.idx
index 8b7671ac2..c05435453 100644
Binary files a/fincept-qt/.cache/clangd/index/MarketsScreen.h.284E6B065C972F74.idx and b/fincept-qt/.cache/clangd/index/MarketsScreen.h.284E6B065C972F74.idx differ
diff --git a/fincept-qt/.cache/clangd/index/McpServersSection.cpp.EA64F90BF3E333F5.idx b/fincept-qt/.cache/clangd/index/McpServersSection.cpp.EA64F90BF3E333F5.idx
index 793b6d254..b4b4e44c2 100644
Binary files a/fincept-qt/.cache/clangd/index/McpServersSection.cpp.EA64F90BF3E333F5.idx and b/fincept-qt/.cache/clangd/index/McpServersSection.cpp.EA64F90BF3E333F5.idx differ
diff --git a/fincept-qt/.cache/clangd/index/NewsFeedDelegate.cpp.0AF70557C498B179.idx b/fincept-qt/.cache/clangd/index/NewsFeedDelegate.cpp.0AF70557C498B179.idx
index 90ff23a7e..bfd7df7d3 100644
Binary files a/fincept-qt/.cache/clangd/index/NewsFeedDelegate.cpp.0AF70557C498B179.idx and b/fincept-qt/.cache/clangd/index/NewsFeedDelegate.cpp.0AF70557C498B179.idx differ
diff --git a/fincept-qt/.cache/clangd/index/NewsFeedDelegate.h.6324F15E9728621A.idx b/fincept-qt/.cache/clangd/index/NewsFeedDelegate.h.6324F15E9728621A.idx
index c673c711c..b60b620b7 100644
Binary files a/fincept-qt/.cache/clangd/index/NewsFeedDelegate.h.6324F15E9728621A.idx and b/fincept-qt/.cache/clangd/index/NewsFeedDelegate.h.6324F15E9728621A.idx differ
diff --git a/fincept-qt/.cache/clangd/index/NewsFeedModel.cpp.F9086FE154F0AE92.idx b/fincept-qt/.cache/clangd/index/NewsFeedModel.cpp.F9086FE154F0AE92.idx
index 096872bbd..be46020b2 100644
Binary files a/fincept-qt/.cache/clangd/index/NewsFeedModel.cpp.F9086FE154F0AE92.idx and b/fincept-qt/.cache/clangd/index/NewsFeedModel.cpp.F9086FE154F0AE92.idx differ
diff --git a/fincept-qt/.cache/clangd/index/NewsFeedModel.h.DE942D164D5953EB.idx b/fincept-qt/.cache/clangd/index/NewsFeedModel.h.DE942D164D5953EB.idx
index 1ac459125..bf27510c8 100644
Binary files a/fincept-qt/.cache/clangd/index/NewsFeedModel.h.DE942D164D5953EB.idx and b/fincept-qt/.cache/clangd/index/NewsFeedModel.h.DE942D164D5953EB.idx differ
diff --git a/fincept-qt/.cache/clangd/index/NewsWidget.cpp.C7E20B1251C6BE46.idx b/fincept-qt/.cache/clangd/index/NewsWidget.cpp.C7E20B1251C6BE46.idx
index ab334f97e..55f9bf369 100644
Binary files a/fincept-qt/.cache/clangd/index/NewsWidget.cpp.C7E20B1251C6BE46.idx and b/fincept-qt/.cache/clangd/index/NewsWidget.cpp.C7E20B1251C6BE46.idx differ
diff --git a/fincept-qt/.cache/clangd/index/PortfolioScreen.cpp.B88C75945610D9A6.idx b/fincept-qt/.cache/clangd/index/PortfolioScreen.cpp.B88C75945610D9A6.idx
index b8878e672..28bf76ec8 100644
Binary files a/fincept-qt/.cache/clangd/index/PortfolioScreen.cpp.B88C75945610D9A6.idx and b/fincept-qt/.cache/clangd/index/PortfolioScreen.cpp.B88C75945610D9A6.idx differ
diff --git a/fincept-qt/.cache/clangd/index/PortfolioScreen.h.C896FF67018E0DB2.idx b/fincept-qt/.cache/clangd/index/PortfolioScreen.h.C896FF67018E0DB2.idx
index cc47d2f9f..03c75ec38 100644
Binary files a/fincept-qt/.cache/clangd/index/PortfolioScreen.h.C896FF67018E0DB2.idx and b/fincept-qt/.cache/clangd/index/PortfolioScreen.h.C896FF67018E0DB2.idx differ
diff --git a/fincept-qt/.cache/clangd/index/PortfolioSummaryWidget.cpp.D7B17A1755066CC0.idx b/fincept-qt/.cache/clangd/index/PortfolioSummaryWidget.cpp.D7B17A1755066CC0.idx
index e77c86424..36d47bca2 100644
Binary files a/fincept-qt/.cache/clangd/index/PortfolioSummaryWidget.cpp.D7B17A1755066CC0.idx and b/fincept-qt/.cache/clangd/index/PortfolioSummaryWidget.cpp.D7B17A1755066CC0.idx differ
diff --git a/fincept-qt/.cache/clangd/index/ProfileManager.h.7D9D306F81945956.idx b/fincept-qt/.cache/clangd/index/ProfileManager.h.7D9D306F81945956.idx
new file mode 100644
index 000000000..e5606632e
Binary files /dev/null and b/fincept-qt/.cache/clangd/index/ProfileManager.h.7D9D306F81945956.idx differ
diff --git a/fincept-qt/.cache/clangd/index/QuickTradeWidget.cpp.7353B29FDA6B21BD.idx b/fincept-qt/.cache/clangd/index/QuickTradeWidget.cpp.7353B29FDA6B21BD.idx
index 9e4366cf2..d62e29923 100644
Binary files a/fincept-qt/.cache/clangd/index/QuickTradeWidget.cpp.7353B29FDA6B21BD.idx and b/fincept-qt/.cache/clangd/index/QuickTradeWidget.cpp.7353B29FDA6B21BD.idx differ
diff --git a/fincept-qt/.cache/clangd/index/RecentFilesWidget.cpp.5589634AF3274F07.idx b/fincept-qt/.cache/clangd/index/RecentFilesWidget.cpp.5589634AF3274F07.idx
index beea11ef4..7895e4f8f 100644
Binary files a/fincept-qt/.cache/clangd/index/RecentFilesWidget.cpp.5589634AF3274F07.idx and b/fincept-qt/.cache/clangd/index/RecentFilesWidget.cpp.5589634AF3274F07.idx differ
diff --git a/fincept-qt/.cache/clangd/index/RelationshipPanel.cpp.F8FFEB5E1F827494.idx b/fincept-qt/.cache/clangd/index/RelationshipPanel.cpp.F8FFEB5E1F827494.idx
index 0310ec9dd..1108cbc6c 100644
Binary files a/fincept-qt/.cache/clangd/index/RelationshipPanel.cpp.F8FFEB5E1F827494.idx and b/fincept-qt/.cache/clangd/index/RelationshipPanel.cpp.F8FFEB5E1F827494.idx differ
diff --git a/fincept-qt/.cache/clangd/index/ReportBuilderScreen.cpp.32A35A1EBC591518.idx b/fincept-qt/.cache/clangd/index/ReportBuilderScreen.cpp.32A35A1EBC591518.idx
index 3d63df6ac..5d637e590 100644
Binary files a/fincept-qt/.cache/clangd/index/ReportBuilderScreen.cpp.32A35A1EBC591518.idx and b/fincept-qt/.cache/clangd/index/ReportBuilderScreen.cpp.32A35A1EBC591518.idx differ
diff --git a/fincept-qt/.cache/clangd/index/ScreenerWidget.cpp.35356117B6EDA769.idx b/fincept-qt/.cache/clangd/index/ScreenerWidget.cpp.35356117B6EDA769.idx
index 16a49e896..0c587937a 100644
Binary files a/fincept-qt/.cache/clangd/index/ScreenerWidget.cpp.35356117B6EDA769.idx and b/fincept-qt/.cache/clangd/index/ScreenerWidget.cpp.35356117B6EDA769.idx differ
diff --git a/fincept-qt/.cache/clangd/index/SettingsScreen.cpp.7BAB1A055328023F.idx b/fincept-qt/.cache/clangd/index/SettingsScreen.cpp.7BAB1A055328023F.idx
index e9d15ef5f..e41b2276e 100644
Binary files a/fincept-qt/.cache/clangd/index/SettingsScreen.cpp.7BAB1A055328023F.idx and b/fincept-qt/.cache/clangd/index/SettingsScreen.cpp.7BAB1A055328023F.idx differ
diff --git a/fincept-qt/.cache/clangd/index/SettingsScreen.h.3B17EB0C2433BD0C.idx b/fincept-qt/.cache/clangd/index/SettingsScreen.h.3B17EB0C2433BD0C.idx
index 8e6e519c4..34e167361 100644
Binary files a/fincept-qt/.cache/clangd/index/SettingsScreen.h.3B17EB0C2433BD0C.idx and b/fincept-qt/.cache/clangd/index/SettingsScreen.h.3B17EB0C2433BD0C.idx differ
diff --git a/fincept-qt/.cache/clangd/index/StorageManager.h.48A3A050D2B00400.idx b/fincept-qt/.cache/clangd/index/StorageManager.h.48A3A050D2B00400.idx
new file mode 100644
index 000000000..d53ff54a0
Binary files /dev/null and b/fincept-qt/.cache/clangd/index/StorageManager.h.48A3A050D2B00400.idx differ
diff --git a/fincept-qt/.cache/clangd/index/ThemeManager.h.B69362045C2CF455.idx b/fincept-qt/.cache/clangd/index/ThemeManager.h.B69362045C2CF455.idx
index 130c47145..edf0d8b4a 100644
Binary files a/fincept-qt/.cache/clangd/index/ThemeManager.h.B69362045C2CF455.idx and b/fincept-qt/.cache/clangd/index/ThemeManager.h.B69362045C2CF455.idx differ
diff --git a/fincept-qt/.cache/clangd/index/ThemeTokens.h.42B01D62A14FBA01.idx b/fincept-qt/.cache/clangd/index/ThemeTokens.h.42B01D62A14FBA01.idx
index 5be7a523e..266e415e4 100644
Binary files a/fincept-qt/.cache/clangd/index/ThemeTokens.h.42B01D62A14FBA01.idx and b/fincept-qt/.cache/clangd/index/ThemeTokens.h.42B01D62A14FBA01.idx differ
diff --git a/fincept-qt/.cache/clangd/index/TopMoversWidget.cpp.05E71C7095736608.idx b/fincept-qt/.cache/clangd/index/TopMoversWidget.cpp.05E71C7095736608.idx
index 83cd09816..63fa4a201 100644
Binary files a/fincept-qt/.cache/clangd/index/TopMoversWidget.cpp.05E71C7095736608.idx and b/fincept-qt/.cache/clangd/index/TopMoversWidget.cpp.05E71C7095736608.idx differ
diff --git a/fincept-qt/.cache/clangd/index/TradeAnalysisPanel.cpp.80074B7986741F5C.idx b/fincept-qt/.cache/clangd/index/TradeAnalysisPanel.cpp.80074B7986741F5C.idx
index 8fe439aa0..a98e2d552 100644
Binary files a/fincept-qt/.cache/clangd/index/TradeAnalysisPanel.cpp.80074B7986741F5C.idx and b/fincept-qt/.cache/clangd/index/TradeAnalysisPanel.cpp.80074B7986741F5C.idx differ
diff --git a/fincept-qt/.cache/clangd/index/WatchlistScreen.cpp.7764D3D8F05E1B90.idx b/fincept-qt/.cache/clangd/index/WatchlistScreen.cpp.7764D3D8F05E1B90.idx
index d60842a1a..28dd87b69 100644
Binary files a/fincept-qt/.cache/clangd/index/WatchlistScreen.cpp.7764D3D8F05E1B90.idx and b/fincept-qt/.cache/clangd/index/WatchlistScreen.cpp.7764D3D8F05E1B90.idx differ
diff --git a/fincept-qt/.cache/clangd/index/WatchlistWidget.cpp.DF24006497780E7A.idx b/fincept-qt/.cache/clangd/index/WatchlistWidget.cpp.DF24006497780E7A.idx
index 5b0549600..cf86b3bd0 100644
Binary files a/fincept-qt/.cache/clangd/index/WatchlistWidget.cpp.DF24006497780E7A.idx and b/fincept-qt/.cache/clangd/index/WatchlistWidget.cpp.DF24006497780E7A.idx differ
diff --git a/fincept-qt/.cache/clangd/index/WorkspaceManager.h.17C3F9AC0E41185C.idx b/fincept-qt/.cache/clangd/index/WorkspaceManager.h.17C3F9AC0E41185C.idx
index 0b9eba46c..9984a0346 100644
Binary files a/fincept-qt/.cache/clangd/index/WorkspaceManager.h.17C3F9AC0E41185C.idx and b/fincept-qt/.cache/clangd/index/WorkspaceManager.h.17C3F9AC0E41185C.idx differ
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index a2f39e6c1..b294b463c 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -189,12 +189,53 @@ FetchContent_MakeAvailable(QGeoView)
# QGeoView has anonymous-namespace symbol clashes under unity build
set_target_properties(qgeoview PROPERTIES UNITY_BUILD OFF)
+# ── SingleApplication (single-process enforcement + new-window IPC) ──────────
+# When the user re-launches the exe, the secondary instance sends "--new-window"
+# to the primary, which opens a new MainWindow instead of a second process.
+# QAPPLICATION_CLASS must be set before FetchContent_MakeAvailable so the lib
+# compiles inheriting QApplication (not QCoreApplication).
+set(QT_DEFAULT_MAJOR_VERSION 6 CACHE STRING "" FORCE)
+set(QAPPLICATION_CLASS QApplication CACHE STRING "" FORCE)
+FetchContent_Declare(
+ SingleApplication
+ GIT_REPOSITORY https://github.com/itay-grudev/SingleApplication.git
+ GIT_TAG v3.5.4
+ GIT_SHALLOW TRUE
+ UPDATE_DISCONNECTED TRUE
+)
+FetchContent_MakeAvailable(SingleApplication)
+if(MSVC)
+ target_compile_options(SingleApplication PRIVATE /W0)
+endif()
+
+# ── Qt Advanced Docking System (Bloomberg-style detachable panels) ────────────
+# Panels become CDockWidgets — drag to float, dock, move to any monitor.
+# LGPL — compatible with AGPL. Used in Qt Creator itself.
+set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
+set(BUILD_STATIC ON CACHE BOOL "" FORCE) # static lib: simpler deployment, no extra DLL
+set(QT_VERSION_MAJOR 6 CACHE STRING "" FORCE)
+FetchContent_Declare(
+ QtADS
+ GIT_REPOSITORY https://github.com/githubuser0xFFFF/Qt-Advanced-Docking-System.git
+ GIT_TAG 4.5.0
+ GIT_SHALLOW TRUE
+ UPDATE_DISCONNECTED TRUE
+)
+FetchContent_MakeAvailable(QtADS)
+# ADS target name is version-stamped: qtadvanceddocking-qt6
+# Disable unity build — ADS uses anonymous namespaces internally
+set_target_properties(qtadvanceddocking-qt6 PROPERTIES UNITY_BUILD OFF)
+if(MSVC)
+ target_compile_options(qtadvanceddocking-qt6 PRIVATE /W0)
+endif()
+
# ── Source files by module ────────────────────────────────────────────────────
# Core
set(CORE_SOURCES
src/core/config/AppConfig.cpp
src/core/config/AppPaths.cpp
+ src/core/config/ProfileManager.cpp
src/core/logging/Logger.cpp
src/core/events/EventBus.cpp
src/core/session/SessionManager.cpp
@@ -231,6 +272,8 @@ set(STORAGE_SOURCES
src/storage/sqlite/migrations/v006_portfolio_multi.cpp
src/storage/sqlite/migrations/v007_news_baselines.cpp
+ # Storage manager
+ src/storage/StorageManager.cpp
# Cache + tab sessions
src/storage/cache/CacheManager.cpp
src/storage/cache/TabSessionStore.cpp
@@ -457,6 +500,8 @@ set(UI_SOURCES
src/ui/navigation/StatusBar.cpp
src/ui/navigation/ToolBar.cpp
src/ui/navigation/CommandBar.cpp
+ src/ui/navigation/DockToolBar.cpp
+ src/ui/navigation/DockStatusBar.cpp
src/ui/workspace/WorkspaceNewDialog.cpp
src/ui/workspace/WorkspaceOpenDialog.cpp
@@ -778,6 +823,7 @@ set(APP_SOURCES
src/app/main.cpp
src/app/MainWindow.cpp
src/app/ScreenRouter.cpp
+ src/app/DockScreenRouter.cpp
)
# All screen files compiled individually — they have local statics/functions that
@@ -1061,6 +1107,14 @@ set_source_files_properties(
PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE
)
+# ADS files use anonymous namespaces and heavy Qt meta-object includes —
+# exclude from unity to avoid ODR / symbol clashes in large batches
+set_source_files_properties(
+ src/app/MainWindow.cpp
+ src/app/DockScreenRouter.cpp
+ PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE
+)
+
# MCP core + tools: each defines TAG or kTimeoutMs in shared namespaces —
# must stay excluded from unity (batch size 1 = each file its own TU)
set_source_files_properties(
@@ -1395,6 +1449,8 @@ target_link_libraries(FinceptTerminal PRIVATE
whisper
md4c
md4c-html
+ SingleApplication::SingleApplication
+ qtadvanceddocking-qt6
)
# OpenSSL — Windows only (from vcpkg). macOS uses system OpenSSL; Linux uses system packages.
@@ -1560,30 +1616,30 @@ endif()
if(WIN32)
# Windows: install exe + all DLLs beside it (windeployqt already copies them)
- install(TARGETS FinceptTerminal RUNTIME DESTINATION ".")
+ install(TARGETS FinceptTerminal RUNTIME DESTINATION "." COMPONENT core)
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/scripts/"
- DESTINATION "scripts")
+ DESTINATION "scripts" COMPONENT scripts)
elseif(APPLE)
# macOS: install the .app bundle
- install(TARGETS FinceptTerminal BUNDLE DESTINATION ".")
+ install(TARGETS FinceptTerminal BUNDLE DESTINATION "." COMPONENT core)
else()
# Linux: FHS-compliant layout
install(TARGETS FinceptTerminal
- RUNTIME DESTINATION "bin")
+ RUNTIME DESTINATION "bin" COMPONENT core)
# Python analytics scripts
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/scripts/"
DESTINATION "share/fincept-terminal/scripts"
- USE_SOURCE_PERMISSIONS)
+ USE_SOURCE_PERMISSIONS COMPONENT scripts)
# App icon (PNG required for hicolor theme; convert .ico → .png in CI)
set(_ICON_PNG "${CMAKE_CURRENT_SOURCE_DIR}/resources/fincept.png")
if(EXISTS "${_ICON_PNG}")
install(FILES "${_ICON_PNG}"
DESTINATION "share/icons/hicolor/256x256/apps"
- RENAME "fincept-terminal.png")
+ RENAME "fincept-terminal.png" COMPONENT core)
else()
message(STATUS "Linux icon not found at ${_ICON_PNG} — "
"convert resources/fincept.ico to fincept.png for proper desktop integration")
@@ -1591,16 +1647,156 @@ else()
# .desktop file
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/packaging/linux/fincept-terminal.desktop"
- DESTINATION "share/applications")
+ DESTINATION "share/applications" COMPONENT core)
# AppStream metadata
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/packaging/linux/fincept-terminal.appdata.xml"
- DESTINATION "share/metainfo")
+ DESTINATION "share/metainfo" COMPONENT core)
# yt-dlp (if bundled)
if(FINCEPT_YTDLP_TO_BUNDLE AND EXISTS "${FINCEPT_YTDLP_TO_BUNDLE}")
install(PROGRAMS "${FINCEPT_YTDLP_TO_BUNDLE}"
DESTINATION "bin"
- RENAME "yt-dlp")
+ RENAME "yt-dlp" COMPONENT core)
endif()
endif()
+
+# ── Installer (QtIFW via CPackIFW) ───────────────────────────────────────────
+# Generate cross-platform installer with uninstaller:
+# cmake -B build -DFINCEPT_BUILD_INSTALLER=ON -DDEPLOY_QT=ON ...
+# cmake --build build --config Release
+# cd build && cpack -G IFW -C Release
+#
+# Requires: Qt Installer Framework (binarycreator on PATH or in Qt install)
+# Output: FinceptTerminal-<ver>-<platform>-setup.exe/.run/.app
+
+option(FINCEPT_BUILD_INSTALLER "Generate QtIFW installer via CPack" OFF)
+
+if(FINCEPT_BUILD_INSTALLER)
+
+ # ── Windows: capture windeployqt output for the installer ────────────────
+ if(WIN32 AND DEPLOY_QT)
+ install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/"
+ DESTINATION "."
+ COMPONENT core
+ FILES_MATCHING
+ PATTERN "*.dll")
+ # Qt plugin directories
+ install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/platforms"
+ DESTINATION "." COMPONENT core OPTIONAL)
+ install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/sqldrivers"
+ DESTINATION "." COMPONENT core OPTIONAL)
+ install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/imageformats"
+ DESTINATION "." COMPONENT core OPTIONAL)
+ install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/styles"
+ DESTINATION "." COMPONENT core OPTIONAL)
+ install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/tls"
+ DESTINATION "." COMPONENT core OPTIONAL)
+ install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/multimedia"
+ DESTINATION "." COMPONENT core OPTIONAL)
+ install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/networkinformation"
+ DESTINATION "." COMPONENT core OPTIONAL)
+ install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/generic"
+ DESTINATION "." COMPONENT core OPTIONAL)
+ endif()
+
+ # ── CPack general metadata ───────────────────────────────────────────────
+ set(CPACK_PACKAGE_NAME "FinceptTerminal")
+ set(CPACK_PACKAGE_VENDOR "Fincept Corporation")
+ set(CPACK_PACKAGE_VERSION "${CMAKE_PROJECT_VERSION}")
+ set(CPACK_PACKAGE_DESCRIPTION_SUMMARY
+ "Professional financial intelligence terminal with AI analytics")
+ set(CPACK_PACKAGE_HOMEPAGE_URL
+ "https://github.com/Fincept-Corporation/FinceptTerminal")
+ set(CPACK_RESOURCE_FILE_LICENSE
+ "${CMAKE_CURRENT_SOURCE_DIR}/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt")
+ set(CPACK_PACKAGE_ICON
+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/fincept.ico")
+
+ # ── Generator: IFW only ──────────────────────────────────────────────────
+ set(CPACK_GENERATOR "IFW")
+
+ # ── QtIFW tool discovery ─────────────────────────────────────────────────
+ find_program(BINARYCREATOR_EXE binarycreator
+ HINTS
+ "$ENV{QT_IFW_DIR}/bin"
+ "$ENV{QT_ROOT_DIR}/../../Tools/QtInstallerFramework/4.8/bin"
+ "C:/Qt/Tools/QtInstallerFramework/4.8/bin"
+ "C:/Qt/Tools/QtInstallerFramework/4.7/bin"
+ "/opt/Qt/Tools/QtInstallerFramework/4.8/bin"
+ "$ENV{HOME}/Qt/Tools/QtInstallerFramework/4.8/bin"
+ )
+ if(BINARYCREATOR_EXE)
+ get_filename_component(_IFW_BIN_DIR "${BINARYCREATOR_EXE}" DIRECTORY)
+ set(CPACK_IFW_ROOT "${_IFW_BIN_DIR}/..")
+ message(STATUS "QtIFW found: ${BINARYCREATOR_EXE}")
+ else()
+ message(WARNING "binarycreator not found — set QT_IFW_DIR or install Qt Installer Framework")
+ endif()
+
+ # ── CPackIFW installer configuration ─────────────────────────────────────
+ set(CPACK_IFW_PACKAGE_TITLE "Fincept Terminal")
+ set(CPACK_IFW_PACKAGE_NAME "com.fincept.terminal")
+ set(CPACK_IFW_PACKAGE_PUBLISHER "Fincept Corporation")
+ set(CPACK_IFW_PACKAGE_START_MENU_DIRECTORY "Fincept")
+ set(CPACK_IFW_PACKAGE_ICON
+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/fincept.ico")
+ set(CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_NAME "FinceptMaintenanceTool")
+ set(CPACK_IFW_PACKAGE_WIZARD_STYLE "Modern")
+ set(CPACK_IFW_PACKAGE_ALLOW_SPACE_IN_PATH ON)
+ set(CPACK_IFW_PACKAGE_ALLOW_NON_ASCII_CHARACTERS ON)
+
+ # Target directory defaults per platform
+ if(WIN32)
+ set(CPACK_IFW_TARGET_DIRECTORY "@ApplicationsDirX64@/FinceptTerminal")
+ elseif(APPLE)
+ set(CPACK_IFW_TARGET_DIRECTORY "/Applications/FinceptTerminal")
+ else()
+ set(CPACK_IFW_TARGET_DIRECTORY "@HomeDir@/FinceptTerminal")
+ endif()
+
+ # Output file naming
+ if(WIN32)
+ set(CPACK_PACKAGE_FILE_NAME
+ "FinceptTerminal-${CMAKE_PROJECT_VERSION}-win64-setup")
+ elseif(APPLE)
+ set(CPACK_PACKAGE_FILE_NAME
+ "FinceptTerminal-${CMAKE_PROJECT_VERSION}-macOS-setup")
+ else()
+ set(CPACK_PACKAGE_FILE_NAME
+ "FinceptTerminal-${CMAKE_PROJECT_VERSION}-linux-x64-setup")
+ endif()
+
+ # ── Include CPack + IFW module ───────────────────────────────────────────
+ include(CPack)
+ include(CPackIFW)
+
+ # ── Define install components ────────────────────────────────────────────
+ cpack_add_component(core
+ DISPLAY_NAME "Fincept Terminal"
+ DESCRIPTION "Core application executable and Qt runtime libraries"
+ REQUIRED)
+
+ cpack_add_component(scripts
+ DISPLAY_NAME "Python Analytics Scripts"
+ DESCRIPTION "1300+ CFA-level Python analytics scripts (equity, derivatives, portfolio, quant)"
+ DEPENDS core)
+
+ # ── CPackIFW component configuration ─────────────────────────────────────
+ cpack_ifw_configure_component(core
+ NAME "com.fincept.terminal.core"
+ VERSION "${CMAKE_PROJECT_VERSION}"
+ SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs"
+ LICENSES "AGPL-3.0" "${CMAKE_CURRENT_SOURCE_DIR}/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt"
+ PRIORITY 100
+ DEFAULT TRUE
+ FORCED_INSTALLATION)
+
+ cpack_ifw_configure_component(scripts
+ NAME "com.fincept.terminal.scripts"
+ VERSION "${CMAKE_PROJECT_VERSION}"
+ PRIORITY 50
+ DEFAULT TRUE
+ DEPENDS "com.fincept.terminal.core")
+
+endif() # FINCEPT_BUILD_INSTALLER
diff --git a/fincept-qt/packaging/installer/config/.gitkeep b/fincept-qt/packaging/installer/config/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/data/.gitkeep b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/data/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs
new file mode 100644
index 000000000..057391b1d
--- /dev/null
+++ b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs
@@ -0,0 +1,271 @@
+// installscript.qs -- Fincept Terminal QtIFW component script
+// Handles: shortcuts on install, user data cleanup on uninstall
+//
+// Data locations cleaned on uninstall (when user confirms):
+// Windows: %LOCALAPPDATA%\com.fincept.terminal\
+// macOS: ~/Library/Application Support/com.fincept.terminal/
+// Linux: ~/.local/share/com.fincept.terminal/
+// QSettings (registry/plist/conf), credentials, temp files
+
+function Component()
+{
+ installer.installationFinished.connect(this, Component.prototype.installationFinished);
+
+ if (installer.isUninstaller()) {
+ installer.uninstallationStarted.connect(this, Component.prototype.uninstallationStarted);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Install: create platform shortcuts
+// ---------------------------------------------------------------------------
+
+Component.prototype.createOperations = function()
+{
+ component.createOperations();
+
+ var targetDir = installer.value("TargetDir");
+
+ if (systemInfo.kernelType === "winnt") {
+ // Start Menu shortcut
+ component.addOperation("CreateShortcut",
+ targetDir + "/FinceptTerminal.exe",
+ "@StartMenuDir@/Fincept Terminal.lnk",
+ "workingDirectory=" + targetDir,
+ "iconPath=" + targetDir + "/FinceptTerminal.exe",
+ "iconId=0",
+ "description=Professional Financial Intelligence Terminal");
+
+ // Desktop shortcut
+ component.addOperation("CreateShortcut",
+ targetDir + "/FinceptTerminal.exe",
+ "@DesktopDir@/Fincept Terminal.lnk",
+ "workingDirectory=" + targetDir,
+ "iconPath=" + targetDir + "/FinceptTerminal.exe",
+ "iconId=0",
+ "description=Professional Financial Intelligence Terminal");
+ }
+
+ if (systemInfo.kernelType === "linux") {
+ component.addOperation("CreateDesktopEntry",
+ "@HomeDir@/.local/share/applications/fincept-terminal.desktop",
+ "Version=1.0\n" +
+ "Type=Application\n" +
+ "Name=Fincept Terminal\n" +
+ "GenericName=Financial Intelligence Terminal\n" +
+ "Comment=Professional financial data terminal with AI analytics\n" +
+ "Exec=" + targetDir + "/bin/FinceptTerminal %U\n" +
+ "Icon=" + targetDir + "/share/icons/hicolor/256x256/apps/fincept-terminal.png\n" +
+ "Terminal=false\n" +
+ "StartupWMClass=FinceptTerminal\n" +
+ "StartupNotify=true\n" +
+ "Categories=Finance;Office;Science;\n" +
+ "Keywords=finance;trading;stocks;crypto;portfolio;AI;analytics;markets;\n"
+ );
+ }
+
+ // macOS: .app bundle is self-contained, no shortcuts needed
+};
+
+Component.prototype.installationFinished = function()
+{
+ // Reserved for future post-install actions (URL handlers, file associations)
+};
+
+// ---------------------------------------------------------------------------
+// Uninstall: prompt for user data removal, then clean up
+// ---------------------------------------------------------------------------
+
+Component.prototype.uninstallationStarted = function()
+{
+ var result = QMessageBox.question(
+ "fincept.uninstall.data",
+ "Remove User Data?",
+ "Do you want to remove all Fincept Terminal user data?\n\n" +
+ "This includes:\n" +
+ " - Databases (chat history, portfolio, watchlists)\n" +
+ " - Log files\n" +
+ " - Downloaded files and cached data\n" +
+ " - ML models (Whisper, etc.)\n" +
+ " - Python runtime and virtual environments\n" +
+ " - Workspaces and profiles\n" +
+ " - Saved credentials and API keys\n" +
+ " - Application settings\n\n" +
+ "Choose 'No' to keep your data for a future reinstall.",
+ QMessageBox.Yes | QMessageBox.No,
+ QMessageBox.No
+ );
+
+ if (result === QMessageBox.Yes) {
+ cleanUserData();
+ }
+};
+
+// ---------------------------------------------------------------------------
+// Data cleanup implementation
+// ---------------------------------------------------------------------------
+
+function cleanUserData()
+{
+ // 1. Remove main data directory
+ removeDataRoot();
+
+ // 2. Remove legacy data directories (Windows only)
+ removeLegacyDirs();
+
+ // 3. Remove QSettings (registry / plist / conf)
+ removeSettings();
+
+ // 4. Remove credentials from OS secure storage
+ removeCredentials();
+
+ // 5. Clean temp files
+ removeTempFiles();
+}
+
+// -- 1. Main data root --
+
+function removeDataRoot()
+{
+ var dataRoot = "";
+
+ if (systemInfo.kernelType === "winnt") {
+ dataRoot = installer.environmentVariable("LOCALAPPDATA") +
+ "/com.fincept.terminal";
+ } else if (systemInfo.kernelType === "darwin") {
+ dataRoot = installer.environmentVariable("HOME") +
+ "/Library/Application Support/com.fincept.terminal";
+ } else {
+ dataRoot = installer.environmentVariable("HOME") +
+ "/.local/share/com.fincept.terminal";
+ }
+
+ if (installer.fileExists(dataRoot)) {
+ removeDirectoryRecursive(dataRoot);
+ }
+}
+
+// -- 2. Legacy directories (pre-v4 Windows paths) --
+
+function removeLegacyDirs()
+{
+ if (systemInfo.kernelType !== "winnt") return;
+
+ var localAppData = installer.environmentVariable("LOCALAPPDATA");
+
+ var legacy1 = localAppData + "/Fincept/FinceptTerminal";
+ if (installer.fileExists(legacy1)) {
+ removeDirectoryRecursive(legacy1);
+ }
+
+ var legacy2 = localAppData + "/FinceptTerminal";
+ if (installer.fileExists(legacy2)) {
+ removeDirectoryRecursive(legacy2);
+ }
+
+ // Remove empty parent directory
+ var finceptParent = localAppData + "/Fincept";
+ if (installer.fileExists(finceptParent)) {
+ installer.execute("cmd", ["/c", "rmdir", finceptParent.replace(/\//g, "\\")]);
+ }
+}
+
+// -- 3. QSettings --
+
+function removeSettings()
+{
+ if (systemInfo.kernelType === "winnt") {
+ // Registry: HKCU\Software\Fincept\FinceptTerminal
+ installer.execute("reg", ["delete",
+ "HKCU\\Software\\Fincept\\FinceptTerminal", "/f"]);
+ // Registry: HKCU\Software\Fincept\FinceptTerminal-Secure
+ installer.execute("reg", ["delete",
+ "HKCU\\Software\\Fincept\\FinceptTerminal-Secure", "/f"]);
+ // Remove empty parent key if no other Fincept apps
+ installer.execute("reg", ["delete",
+ "HKCU\\Software\\Fincept", "/f"]);
+
+ } else if (systemInfo.kernelType === "darwin") {
+ var plistPath = installer.environmentVariable("HOME") +
+ "/Library/Preferences/com.fincept.FinceptTerminal.plist";
+ if (installer.fileExists(plistPath)) {
+ installer.execute("rm", ["-f", plistPath]);
+ }
+
+ } else {
+ // Linux: QSettings .conf files
+ var home = installer.environmentVariable("HOME");
+ var confPath = home + "/.config/Fincept/FinceptTerminal.conf";
+ if (installer.fileExists(confPath)) {
+ installer.execute("rm", ["-f", confPath]);
+ }
+
+ var secureConf = home + "/.config/Fincept/FinceptTerminal-Secure.conf";
+ if (installer.fileExists(secureConf)) {
+ installer.execute("rm", ["-f", secureConf]);
+ }
+
+ // Remove empty parent dir
+ var configDir = home + "/.config/Fincept";
+ if (installer.fileExists(configDir)) {
+ installer.execute("rmdir", [configDir]);
+ }
+ }
+}
+
+// -- 4. Credentials --
+
+function removeCredentials()
+{
+ if (systemInfo.kernelType === "winnt") {
+ // Windows Credential Manager: enumerate and delete FinceptTerminal/* entries
+ // cmdkey doesn't support wildcards, so use PowerShell to enumerate + delete
+ installer.execute("powershell", [
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command",
+ "$targets = cmdkey /list 2>&1 | Select-String 'FinceptTerminal/' | " +
+ "ForEach-Object { ($_ -replace '.*Target:\\s*', '').Trim() }; " +
+ "foreach ($t in $targets) { cmdkey /delete:$t 2>$null }"
+ ]);
+
+ } else if (systemInfo.kernelType === "darwin") {
+ // macOS Keychain: delete all entries with service "com.fincept.terminal"
+ // security delete-generic-password only removes one at a time, so loop
+ installer.execute("/bin/bash", ["-c",
+ "while /usr/bin/security delete-generic-password " +
+ "-s 'com.fincept.terminal' 2>/dev/null; do :; done"
+ ]);
+ }
+
+ // Linux: credentials are stored in FinceptTerminal-Secure.conf (already deleted above)
+}
+
+// -- 5. Temp files --
+
+function removeTempFiles()
+{
+ if (systemInfo.kernelType === "winnt") {
+ var tempDir = installer.environmentVariable("TEMP");
+ installer.execute("cmd", ["/c",
+ "del /q \"" + tempDir.replace(/\//g, "\\") + "\\fincept_*\" 2>nul"]);
+
+ } else {
+ installer.execute("/bin/bash", ["-c",
+ "rm -f /tmp/fincept_* 2>/dev/null; " +
+ "rm -f \"${TMPDIR:-/tmp}\"/fincept_* 2>/dev/null"
+ ]);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function removeDirectoryRecursive(path)
+{
+ if (systemInfo.kernelType === "winnt") {
+ installer.execute("cmd", ["/c", "rmdir", "/s", "/q",
+ path.replace(/\//g, "\\")]);
+ } else {
+ installer.execute("/bin/rm", ["-rf", path]);
+ }
+}
diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
new file mode 100644
index 000000000..270b922af
--- /dev/null
+++ b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
@@ -0,0 +1,134 @@
+GNU AFFERO GENERAL PUBLIC LICENSE
+Version 3, 19 November 2007
+
+Copyright (C) 2025 Fincept Corporation
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as published
+by the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+================================================================================
+DUAL LICENSING NOTICE
+================================================================================
+
+Fincept Terminal is available under two licensing options:
+
+1. AGPL-3.0 License (Open Source)
+ - Free for personal and educational use
+ - Free to use with your own data sources
+ - Requires sharing modifications if you distribute or provide as a network service
+ - Full source code must remain available under AGPL-3.0
+ - See full license text at: https://www.gnu.org/licenses/agpl-3.0.html
+
+2. Commercial License
+ - Required for any business/commercial use
+ - Required to access Fincept Data Sources and APIs for commercial purposes
+ - No obligation to share source code
+ - Priority support available
+ - See docs/COMMERCIAL_LICENSE.md for pricing and terms
+
+================================================================================
+FINCEPT DATA & API
+================================================================================
+
+The Fincept Terminal software is free under AGPL-3.0.
+
+Fincept Data Sources and APIs are separate services that require:
+- Commercial License for business use ($10,200/year)
+- University License for academic institutions ($799/month)
+- Free for personal/educational individual use
+
+================================================================================
+TRADEMARK NOTICE
+================================================================================
+
+"Fincept Terminal", "Fincept", and the Fincept logo are trademarks of
+Fincept Corporation. All rights reserved.
+
+You may not use these trademarks without explicit written permission,
+except as necessary to comply with the AGPL-3.0 attribution requirements.
+
+Use of the trademarks to promote derivative works or competing products
+is strictly prohibited without a trademark license agreement.
+
+================================================================================
+ADDITIONAL RESTRICTIONS
+================================================================================
+
+While the AGPL-3.0 grants broad freedoms, the following restrictions apply:
+
+1. NETWORK USE REQUIREMENT
+ If you run a modified version of Fincept Terminal as a network service
+ (SaaS, cloud platform, web application), you MUST:
+ - Provide users with access to the complete source code
+ - Clearly indicate the source is available
+ - Make the source available via download or repository access
+
+2. ATTRIBUTION REQUIREMENT
+ You must retain all copyright notices, attribution statements, and
+ this license file in any distribution or derivative work.
+
+3. TRADEMARK RESTRICTIONS
+ - Cannot use "Fincept" branding without permission
+ - Must clearly differentiate derivative works from the official version
+ - Cannot imply endorsement by Fincept Corporation
+
+================================================================================
+CONTRIBUTOR LICENSE AGREEMENT
+================================================================================
+
+By contributing to Fincept Terminal, you agree that:
+
+1. You grant Fincept Corporation a perpetual, worldwide, non-exclusive,
+ royalty-free license to use, reproduce, modify, and distribute your
+ contributions under both AGPL-3.0 and commercial licenses.
+
+2. You certify that you have the right to make the contribution and grant
+ these licenses.
+
+3. Your contributions are provided "as-is" without warranties.
+
+4. Contributing does not grant you commercial rights to use Fincept
+ Data Sources and APIs.
+
+================================================================================
+COMMERCIAL USE
+================================================================================
+
+You NEED a commercial license if you:
+- Use Fincept Terminal for any business purpose
+- Use Fincept Data Sources or APIs commercially
+- Are a startup (even with $0 revenue)
+- Use internally at a company
+- Offer as SaaS or cloud platform
+- White-label or resell
+
+You DON'T need a commercial license if you:
+- Use for personal learning
+- Are an individual student
+- Use with your own data sources (non-commercial)
+- Contribute to the open-source project
+
+================================================================================
+CONTACT INFORMATION
+================================================================================
+
+Phone: +91-9773034108
+Website: https://fincept.in
+Repository: https://github.com/Fincept-Corporation/FinceptTerminal
+Documentation: https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs
+
+================================================================================
+
+Last Updated: February 2026
+Version: 3.3.1
diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.scripts/data/.gitkeep b/fincept-qt/packaging/installer/packages/com.fincept.terminal.scripts/data/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.scripts/meta/.gitkeep b/fincept-qt/packaging/installer/packages/com.fincept.terminal.scripts/meta/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/fincept-qt/scripts/Analytics/economics/config.py b/fincept-qt/scripts/Analytics/economics/config.py
new file mode 100644
index 000000000..b4eb23ce3
--- /dev/null
+++ b/fincept-qt/scripts/Analytics/economics/config.py
@@ -0,0 +1,29 @@
+"""Economics module configuration."""
+
+from dataclasses import dataclass, field
+from typing import Dict, List
+
+
+@dataclass
+class DataSources:
+ fred_api_key: str = ""
+ world_bank_base: str = "https://api.worldbank.org/v2"
+ imf_base: str = "https://www.imf.org/external/datamapper/api/v1"
+ oecd_base: str = "https://stats.oecd.org/SDMX-JSON/data"
+
+
+@dataclass
+class CalculationPrecision:
+ default: int = 8
+ display: int = 4
+ currency: int = 2
+
+
+@dataclass
+class EconomicsConfig:
+ precision: CalculationPrecision = field(default_factory=CalculationPrecision)
+ data_sources: DataSources = field(default_factory=DataSources)
+ base_currency: str = "USD"
+ forecast_horizon: int = 12
+ confidence_level: float = 0.90
+ lookback_years: int = 10
diff --git a/fincept-qt/scripts/Analytics/economics/growth_analysis.py b/fincept-qt/scripts/Analytics/economics/growth_analysis.py
index b9327b6fd..acc9fb48d 100644
--- a/fincept-qt/scripts/Analytics/economics/growth_analysis.py
+++ b/fincept-qt/scripts/Analytics/economics/growth_analysis.py
@@ -25,13 +25,11 @@ PARAMETERS:
- base_currency: Base currency for analysis (default: 'USD')
- seasonal_adjustment: Seasonal adjustment method (default: true)
- lookback_period: Historical analysis period (default: 10 years)
-
+"""
from decimal import Decimal
from typing import Dict, List, Tuple, Optional, Any, Union
from datetime import datetime, timedelta
-"""
-
import pandas as pd
import numpy as np
from .core import EconomicsBase, ValidationError, CalculationError, DataError, CalculationUtils
diff --git a/fincept-qt/scripts/Analytics/economics/market_cycles.py b/fincept-qt/scripts/Analytics/economics/market_cycles.py
index 7845b9f3b..9593c7ff8 100644
--- a/fincept-qt/scripts/Analytics/economics/market_cycles.py
+++ b/fincept-qt/scripts/Analytics/economics/market_cycles.py
@@ -26,11 +26,11 @@ PARAMETERS:
- seasonal_adjustment: Seasonal adjustment method (default: true)
- lookback_period: Historical analysis period (default: 10 years)
+"""
from decimal import Decimal
from typing import Dict, List, Tuple, Optional, Any, Union
from datetime import datetime, timedelta
-"""
import pandas as pd
import numpy as np
diff --git a/fincept-qt/scripts/Analytics/economics/trade_geopolitics.py b/fincept-qt/scripts/Analytics/economics/trade_geopolitics.py
index 5ba04a06e..86b4ddf05 100644
--- a/fincept-qt/scripts/Analytics/economics/trade_geopolitics.py
+++ b/fincept-qt/scripts/Analytics/economics/trade_geopolitics.py
@@ -841,4 +841,39 @@ class TradingBlocAnalyzer(EconomicsBase):
"""Calculate trading bloc analysis"""
result = self.analyze_bloc_performance(kwargs.get('bloc_data', {}))
result['metadata'] = self.get_metadata()
- return result
\ No newline at end of file
+ return result
+
+
+if __name__ == "__main__":
+ import sys
+ import json
+
+ def to_serializable(obj):
+ """Recursively convert Decimal and other non-serializable types."""
+ from decimal import Decimal
+ if isinstance(obj, Decimal):
+ return float(obj)
+ if isinstance(obj, dict):
+ return {k: to_serializable(v) for k, v in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [to_serializable(i) for i in obj]
+ return obj
+
+ analysis_type = sys.argv[1] if len(sys.argv) > 1 else "benefits_costs"
+ params = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}
+
+ analyzer = TradeAnalyzer()
+
+ # Map analysis_type to correct method with correct data key
+ if analysis_type == "benefits_costs":
+ result = analyzer.analyze_trade_benefits_costs(params)
+ elif analysis_type == "restrictions":
+ result = analyzer.analyze_trade_restrictions(params)
+ elif analysis_type == "trading_blocs":
+ result = analyzer.analyze_trading_blocs(params)
+ elif analysis_type == "barrier_removal":
+ result = analyzer.assess_trade_barrier_removal(params)
+ else:
+ result = {"error": f"Unknown analysis type: {analysis_type}"}
+
+ print(json.dumps(to_serializable(result), indent=2))
\ No newline at end of file
diff --git a/fincept-qt/src/app/DockScreenRouter.cpp b/fincept-qt/src/app/DockScreenRouter.cpp
new file mode 100644
index 000000000..d6371b7b8
--- /dev/null
+++ b/fincept-qt/src/app/DockScreenRouter.cpp
@@ -0,0 +1,618 @@
+#include "app/DockScreenRouter.h"
+
+#include "core/logging/Logger.h"
+#include "core/session/SessionManager.h"
+#include "screens/IStatefulScreen.h"
+
+#include <DockAreaWidget.h>
+#include <DockWidgetTab.h>
+
+#include <QDebug>
+#include <QEvent>
+#include <QKeyEvent>
+#include <QLabel>
+#include <QLineEdit>
+#include <QPalette>
+#include <QVBoxLayout>
+
+namespace fincept {
+
+QString DockScreenRouter::title_for_id(const QString& id) {
+ static const QHash<QString, QString> titles = {
+ {"dashboard", "Dashboard"},
+ {"markets", "Markets"},
+ {"crypto_trading", "Crypto Trading"},
+ {"equity_trading", "Equity Trading"},
+ {"algo_trading", "Algo Trading"},
+ {"backtesting", "Backtesting"},
+ {"portfolio", "Portfolio"},
+ {"watchlist", "Watchlist"},
+ {"news", "News"},
+ {"ai_chat", "AI Chat"},
+ {"equity_research", "Equity Research"},
+ {"economics", "Economics"},
+ {"dbnomics", "DBnomics"},
+ {"akshare", "AkShare Data"},
+ {"asia_markets", "Asia Markets"},
+ {"geopolitics", "Geopolitics"},
+ {"gov_data", "Gov Data"},
+ {"maritime", "Maritime"},
+ {"polymarket", "Polymarket"},
+ {"relationship_map", "Relationship Map"},
+ {"derivatives", "Derivatives"},
+ {"alt_investments", "Alt Investments"},
+ {"ma_analytics", "M&A Analytics"},
+ {"surface_analytics","Surface Analytics"},
+ {"quantlib", "QuantLib"},
+ {"ai_quant_lab", "AI Quant Lab"},
+ {"alpha_arena", "Alpha Arena"},
+ {"agent_config", "Agent Config"},
+ {"mcp_servers", "MCP Servers"},
+ {"node_editor", "Node Editor"},
+ {"code_editor", "Code Editor"},
+ {"excel", "Excel"},
+ {"report_builder", "Report Builder"},
+ {"trade_viz", "Trade Viz"},
+ {"data_sources", "Data Sources"},
+ {"data_mapping", "Data Mapping"},
+ {"file_manager", "File Manager"},
+ {"notes", "Notes"},
+ {"forum", "Forum"},
+ {"docs", "Docs"},
+ {"support", "Support"},
+ {"about", "About"},
+ {"profile", "Profile"},
+ {"settings", "Settings"},
+ {"contact", "Contact"},
+ {"terms", "Terms"},
+ {"privacy", "Privacy"},
+ {"trademarks", "Trademarks"},
+ {"help", "Help"},
+ };
+ return titles.value(id, id);
+}
+
+DockScreenRouter::DockScreenRouter(ads::CDockManager* manager, QObject* parent)
+ : QObject(parent), manager_(manager) {}
+
+void DockScreenRouter::register_screen(const QString& id, QWidget* screen) {
+ // Store the screen widget — the CDockWidget is only created on first navigate().
+ // This prevents all eagerly registered screens from appearing at startup.
+ screens_[id] = screen;
+ factories_.remove(id);
+}
+
+void DockScreenRouter::register_factory(const QString& id, ScreenFactory factory) {
+ factories_[id] = std::move(factory);
+}
+
+void DockScreenRouter::navigate(const QString& id, bool exclusive) {
+ LOG_INFO("DockRouter", QString(">>> navigate('%1', exclusive=%2) panel_count=%3")
+ .arg(id).arg(exclusive).arg(panel_count_));
+ auto* dw = find_dock_widget(id);
+
+ bool needs_add = false;
+ if (!dw) {
+ // Screen not yet in dock manager — check if we know how to create it
+ if (!factories_.contains(id) && !screens_.contains(id)) {
+ LOG_WARN("DockRouter", "Unknown screen: " + id);
+ return;
+ }
+ dw = create_dock_widget(id);
+ needs_add = true;
+ } else if (!dw->dockManager()) {
+ // Widget exists but was never added to the dock manager (pre-created
+ // by ensure_all_registered for state restore, but restoreState was
+ // skipped or didn't place this widget).
+ needs_add = true;
+ }
+
+ if (screens_.contains(id) && dw->widget() != screens_[id]) {
+ QWidget* old = dw->widget();
+ dw->setWidget(screens_[id]);
+ if (old) { old->setParent(nullptr); old->deleteLater(); }
+ }
+
+ materialize_screen(id);
+
+ if (exclusive) {
+ for (auto* area : manager_->openedDockAreas()) {
+ for (auto* other : area->openedDockWidgets()) {
+ if (other != dw)
+ other->toggleView(false);
+ }
+ }
+ for (auto* other : manager_->dockWidgetsMap()) {
+ if (other != dw && other->isAutoHide())
+ other->toggleView(false);
+ }
+ grid_top_left_ = grid_top_right_ = grid_bottom_left_ = grid_bottom_right_ = nullptr;
+ panel_count_ = 0;
+ }
+
+ // Determine whether this widget needs to be physically placed into a new
+ // split area, or whether it already has its own dedicated area.
+ //
+ // ensure_all_registered() pre-creates every dock widget and groups them all
+ // into a SINGLE shared dock area (all hidden). We detect this by checking
+ // whether dw's area contains other dock widgets (shared) vs being solo.
+ // We check dockWidgets() (all, not just open) because ensure_all_registered
+ // hides them all — openedDockWidgets() would be empty and miss the poisoning.
+ auto* existing_area = dw->dockAreaWidget();
+ const bool area_is_poisoned = existing_area
+ && existing_area->dockWidgets().size() > 1;
+ const bool must_place = needs_add || !existing_area || area_is_poisoned;
+
+ // ── Helper: sync grid tracking from currently open areas ────────────────
+ // After restoreState(), exclusive navigate, or user drag, the grid pointers
+ // may be stale. This lambda rebuilds them from whatever ADS actually has.
+ auto sync_grid_from_reality = [this]() {
+ const auto opened = manager_->openedDockAreas();
+ panel_count_ = std::min(static_cast<int>(opened.size()), 4);
+
+ // Invalidate pointers that no longer exist
+ if (grid_top_left_ && !opened.contains(grid_top_left_)) grid_top_left_ = nullptr;
+ if (grid_top_right_ && !opened.contains(grid_top_right_)) grid_top_right_ = nullptr;
+ if (grid_bottom_left_ && !opened.contains(grid_bottom_left_)) grid_bottom_left_ = nullptr;
+ if (grid_bottom_right_&& !opened.contains(grid_bottom_right_))grid_bottom_right_= nullptr;
+
+ // Fill in missing pointers from opened areas
+ int idx = 0;
+ if (!grid_top_left_ && idx < opened.size()) grid_top_left_ = opened.at(idx);
+ if (grid_top_left_) idx = opened.indexOf(grid_top_left_) + 1;
+ if (!grid_top_right_ && idx < opened.size()) grid_top_right_ = opened.at(idx);
+ if (grid_top_right_) idx = opened.indexOf(grid_top_right_) + 1;
+ if (!grid_bottom_left_ && idx < opened.size()) grid_bottom_left_ = opened.at(idx);
+ if (grid_bottom_left_) idx = opened.indexOf(grid_bottom_left_) + 1;
+ if (!grid_bottom_right_ && idx < opened.size()) grid_bottom_right_ = opened.at(idx);
+
+ LOG_INFO("DockRouter", QString("GRID synced: panel_count=%1 opened=%2 TL=%3 TR=%4 BL=%5 BR=%6")
+ .arg(panel_count_).arg(opened.size())
+ .arg(grid_top_left_ ? "ok" : "-").arg(grid_top_right_ ? "ok" : "-")
+ .arg(grid_bottom_left_ ? "ok" : "-").arg(grid_bottom_right_ ? "ok" : "-"));
+ };
+
+ if (exclusive) {
+ // Exclusive: place into full container (always, regardless of must_place)
+ auto* area = manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
+ grid_top_left_ = area;
+ grid_top_right_ = grid_bottom_left_ = grid_bottom_right_ = nullptr;
+ panel_count_ = 1;
+
+ } else if (must_place) {
+ // Sync grid from reality before placing
+ sync_grid_from_reality();
+
+ LOG_INFO("DockRouter", QString("GRID [%1] must_place panel_count=%2")
+ .arg(id).arg(panel_count_));
+
+ if (panel_count_ == 0) {
+ LOG_INFO("DockRouter", QString("GRID [%1] -> PANEL 1 (full)").arg(id));
+ auto* area = manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
+ grid_top_left_ = area;
+ panel_count_ = 1;
+
+ } else if (panel_count_ == 1 && grid_top_left_) {
+ LOG_INFO("DockRouter", QString("GRID [%1] -> PANEL 2 (right of TL)").arg(id));
+ auto* area = manager_->addDockWidget(ads::RightDockWidgetArea, dw, grid_top_left_);
+ grid_top_right_ = area;
+ panel_count_ = 2;
+
+ } else if (panel_count_ == 2 && grid_top_left_) {
+ LOG_INFO("DockRouter", QString("GRID [%1] -> PANEL 3 (below TL)").arg(id));
+ auto* area = manager_->addDockWidget(ads::BottomDockWidgetArea, dw, grid_top_left_);
+ grid_bottom_left_ = area;
+ panel_count_ = 3;
+
+ } else if (panel_count_ == 3 && grid_bottom_left_) {
+ LOG_INFO("DockRouter", QString("GRID [%1] -> PANEL 4 (right of BL)").arg(id));
+ auto* area = manager_->addDockWidget(ads::RightDockWidgetArea, dw, grid_bottom_left_);
+ grid_bottom_right_ = area;
+ panel_count_ = 4;
+
+ } else {
+ // 5th+ panel or missing grid pointer: tab into last area
+ LOG_INFO("DockRouter", QString("GRID [%1] -> tab into last (panel_count=%2)").arg(id).arg(panel_count_));
+ ads::CDockAreaWidget* target = grid_bottom_right_
+ ? grid_bottom_right_
+ : (manager_->openedDockAreas().isEmpty() ? nullptr : manager_->openedDockAreas().last());
+ if (target)
+ manager_->addDockWidget(ads::CenterDockWidgetArea, dw, target);
+ else
+ manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
+ panel_count_++;
+ }
+
+ } else {
+ // Widget already has a dedicated area — just show it.
+ // But sync grid tracking so it knows about this area for future placements.
+ LOG_INFO("DockRouter", QString("GRID [%1] already placed, syncing grid").arg(id));
+ sync_grid_from_reality();
+ }
+
+ // Always call toggleView(true) — addDockWidget() marks the widget as
+ // not-closed but does NOT make the tab visible. Without this unconditional
+ // call, the tab stays hidden because isClosed() returns false and the
+ // previous conditional `if (isClosed()) toggleView(true)` was skipped.
+ dw->toggleView(true);
+ dw->raise();
+ dw->setAsCurrentTab();
+
+ current_id_ = id;
+ SessionManager::instance().set_last_screen(id);
+ LOG_INFO("DockRouter", "Navigated to: " + id);
+ emit screen_changed(id);
+}
+
+void DockScreenRouter::tab_into(const QString& id) {
+ if (!factories_.contains(id) && !screens_.contains(id)) {
+ LOG_WARN("DockRouter", "Unknown screen: " + id);
+ return;
+ }
+
+ auto* dw = find_dock_widget(id);
+ bool needs_add = !dw || !dw->dockManager();
+
+ if (!dw) {
+ dw = create_dock_widget(id);
+ needs_add = true;
+ }
+
+ materialize_screen(id);
+
+ // If already visible somewhere just raise it — no need to re-tab.
+ if (!dw->isClosed() && dw->dockAreaWidget()) {
+ dw->raise();
+ dw->setAsCurrentTab();
+ current_id_ = id;
+ emit screen_changed(id);
+ return;
+ }
+
+ // Find the focused/active dock area to tab into.
+ // Prefer the focused widget's area; fall back to the first open area.
+ ads::CDockAreaWidget* target_area = nullptr;
+ if (auto* focused = manager_->focusedDockWidget())
+ target_area = focused->dockAreaWidget();
+ if (!target_area) {
+ const auto opened = manager_->openedDockAreas();
+ if (!opened.isEmpty())
+ target_area = opened.first();
+ }
+
+ if (needs_add || !dw->dockAreaWidget()) {
+ if (target_area)
+ // Tab into the existing area — CenterDockWidgetArea = same area, new tab
+ manager_->addDockWidget(ads::CenterDockWidgetArea, dw, target_area);
+ else
+ // No area open yet — open as the sole screen
+ manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
+ }
+
+ dw->toggleView(true);
+ dw->raise();
+ dw->setAsCurrentTab();
+
+ current_id_ = id;
+ SessionManager::instance().set_last_screen(id);
+ LOG_INFO("DockRouter", "Tabbed into: " + id);
+ emit screen_changed(id);
+}
+
+void DockScreenRouter::add_alongside(const QString& primary, const QString& secondary) {
+ // If primary is already open, just add secondary into the next grid slot
+ // without resetting the layout. This allows building up to a 2x2 grid
+ // (4 panels) incrementally via repeated "add" commands.
+ auto* primary_dw = find_dock_widget(primary);
+ bool primary_visible = primary_dw && !primary_dw->isClosed()
+ && primary_dw->dockAreaWidget();
+
+ LOG_INFO("DockRouter", QString("add_alongside: primary=%1 visible=%2 secondary=%3 panel_count=%4")
+ .arg(primary).arg(primary_visible).arg(secondary).arg(panel_count_));
+
+ if (primary_visible) {
+ // Primary already showing — add secondary non-exclusively
+ navigate(secondary, false);
+ } else {
+ // Primary not showing — open it exclusively, then split secondary alongside
+ navigate(primary, true);
+ navigate(secondary, false);
+ }
+
+ // Re-focus the primary so it stays the "main" panel — the user typed
+ // "primary add secondary", meaning primary is what they're working in.
+ primary_dw = find_dock_widget(primary);
+ if (primary_dw && !primary_dw->isClosed()) {
+ primary_dw->raise();
+ primary_dw->setAsCurrentTab();
+ current_id_ = primary;
+ emit screen_changed(primary);
+ }
+}
+
+void DockScreenRouter::remove_screen(const QString& primary) {
+ // Close all panels except primary, which expands to fill the area.
+ auto* keep = find_dock_widget(primary);
+ for (auto* dw : manager_->dockWidgetsMap()) {
+ if (dw != keep && !dw->isClosed())
+ dw->toggleView(false);
+ }
+ if (keep) {
+ if (keep->isClosed()) keep->toggleView(true);
+ keep->raise();
+ keep->setAsCurrentTab();
+ current_id_ = primary;
+ emit screen_changed(primary);
+ }
+}
+
+void DockScreenRouter::replace_screen(const QString& primary, const QString& secondary) {
+ // Navigate to primary (ensures it exists), close everything else, then
+ // navigate to secondary in exclusive mode so it fills the full area.
+ Q_UNUSED(primary)
+ navigate(secondary, true);
+}
+
+void DockScreenRouter::ensure_all_registered() {
+ // Pre-create CDockWidgets for ALL known screens and register them
+ // with the dock manager so restoreState() can find them by objectName
+ // in the DockWidgetsMap. All widgets are added as tabs into a single
+ // dock area (not separate splits!) and immediately closed. restoreState()
+ // will reopen and reposition only those that were visible in the saved layout.
+ QStringList all_ids;
+ for (auto it = factories_.cbegin(); it != factories_.cend(); ++it)
+ all_ids.append(it.key());
+ for (auto it = screens_.cbegin(); it != screens_.cend(); ++it) {
+ if (!all_ids.contains(it.key()))
+ all_ids.append(it.key());
+ }
+
+ ads::CDockAreaWidget* first_area = nullptr;
+ for (const QString& id : all_ids) {
+ if (!dock_widgets_.contains(id)) {
+ auto* dw = create_dock_widget(id);
+ // Add all widgets as tabs in the SAME dock area to avoid
+ // creating 47 vertical splits. The first widget creates the area,
+ // all subsequent ones tab into it.
+ if (first_area)
+ manager_->addDockWidget(ads::CenterDockWidgetArea, dw, first_area);
+ else
+ first_area = manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
+ dw->toggleView(false); // start hidden
+ }
+ }
+}
+
+ads::CDockWidget* DockScreenRouter::find_dock_widget(const QString& id) const {
+ return dock_widgets_.value(id, nullptr);
+}
+
+QStringList DockScreenRouter::all_screen_ids() const {
+ QStringList ids;
+ ids.reserve(dock_widgets_.size() + factories_.size());
+ for (auto it = dock_widgets_.cbegin(); it != dock_widgets_.cend(); ++it)
+ ids.append(it.key());
+ for (auto it = factories_.cbegin(); it != factories_.cend(); ++it) {
+ if (!ids.contains(it.key()))
+ ids.append(it.key());
+ }
+ return ids;
+}
+
+bool DockScreenRouter::eventFilter(QObject* obj, QEvent* event) {
+ if (event->type() != QEvent::MouseButtonDblClick)
+ return QObject::eventFilter(obj, event);
+
+ auto* lbl = qobject_cast<QLabel*>(obj);
+ if (!lbl) return QObject::eventFilter(obj, event);
+
+ const QString id = lbl->property("dock_id").toString();
+ auto* dw = dock_widgets_.value(id, nullptr);
+ if (!dw) return QObject::eventFilter(obj, event);
+
+ // Show a QLineEdit overlaid on the label for inline rename.
+ // Parent it to the label's parent (the tab frame) so geometry is correct.
+ QWidget* tab_frame = lbl->parentWidget();
+ auto* editor = new QLineEdit(tab_frame);
+ editor->setText(dw->windowTitle());
+ editor->selectAll();
+ editor->setFrame(false);
+ editor->setStyleSheet(
+ "QLineEdit{"
+ " background:#1a1a1a;"
+ " color:#ffffff;"
+ " border:1px solid #d97706;"
+ " padding:0 4px;"
+ " font-size:11px;"
+ " font-family:'Consolas',monospace;"
+ "}");
+ // Map label rect into the tab frame's coordinate space
+ editor->setGeometry(
+ tab_frame->mapFromGlobal(lbl->mapToGlobal(QPoint(0, 0))).x(),
+ 2,
+ lbl->width(),
+ tab_frame->height() - 4);
+ editor->show();
+ editor->raise();
+ editor->setFocus();
+
+ auto commit = [dw, editor]() {
+ const QString name = editor->text().trimmed();
+ if (!name.isEmpty()) {
+ // setWindowTitle on CDockWidget propagates to the tab label via
+ // Qt's QEvent::WindowTitleChange handling inside CDockWidget.
+ dw->setWindowTitle(name);
+ }
+ editor->deleteLater();
+ };
+
+ connect(editor, &QLineEdit::returnPressed, editor, commit);
+ connect(editor, &QLineEdit::editingFinished, editor, commit);
+
+ // Cancel on Escape via a local event filter
+ struct EscFilter : QObject {
+ QLineEdit* ed;
+ explicit EscFilter(QLineEdit* e) : QObject(e), ed(e) {}
+ bool eventFilter(QObject*, QEvent* e) override {
+ if (e->type() == QEvent::KeyPress &&
+ static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
+ ed->deleteLater();
+ return true;
+ }
+ return false;
+ }
+ };
+ editor->installEventFilter(new EscFilter(editor));
+
+ return true; // consume double-click so ADS doesn't float the widget
+}
+
+ads::CDockWidget* DockScreenRouter::create_dock_widget(const QString& id) {
+ if (dock_widgets_.contains(id))
+ return dock_widgets_[id];
+
+ auto* dw = new ads::CDockWidget(title_for_id(id));
+ dw->setObjectName(id);
+
+ // Pinnable is intentionally excluded: the auto-hide pin button converts panels
+ // to collapsible sidebars, which causes them to disappear when another panel
+ // is opened alongside them. Movable/Floatable/Closable/Focusable are kept.
+ dw->setFeatures(
+ ads::CDockWidget::DockWidgetMovable |
+ ads::CDockWidget::DockWidgetFloatable |
+ ads::CDockWidget::DockWidgetClosable |
+ ads::CDockWidget::DockWidgetFocusable
+ );
+
+ // Use dock-widget minimum size (not content size) so screens with large
+ // internal canvases (like DashboardCanvas) don't prevent side-by-side splits.
+ dw->setMinimumSizeHintMode(ads::CDockWidget::MinimumSizeHintFromDockWidget);
+ dw->setMinimumWidth(200);
+
+ // Screen widgets must allow shrinking so ADS can create side-by-side splits.
+ // Factory screens get a lightweight placeholder here; the real widget is swapped
+ // in on first navigation via materialize_screen().
+ if (screens_.contains(id)) {
+ screens_[id]->setMinimumWidth(0);
+ dw->setWidget(screens_[id]);
+ } else {
+ auto* placeholder = new QWidget;
+ auto* lbl = new QLabel(title_for_id(id));
+ lbl->setAlignment(Qt::AlignCenter);
+ lbl->setStyleSheet("color:#555;font-size:16px;");
+ auto* vl = new QVBoxLayout(placeholder);
+ vl->addWidget(lbl);
+ dw->setWidget(placeholder);
+ }
+
+ // Intercept double-click on the title label inside CDockWidgetTab to allow
+ // inline rename. We use the label (objectName "dockWidgetTabLabel"), NOT the
+ // tab frame — ADS already uses tab frame double-click to undock/float.
+ if (auto* tab = dw->tabWidget()) {
+ if (auto* lbl = tab->findChild<QLabel*>("dockWidgetTabLabel")) {
+ lbl->installEventFilter(this);
+ lbl->setProperty("dock_id", id);
+ }
+ }
+
+ // Restore a previously saved custom title (user may have renamed this tab).
+ const QString saved_title = load_tab_title(id);
+ if (!saved_title.isEmpty())
+ dw->setWindowTitle(saved_title);
+
+ // Persist the title whenever the user renames it via the inline editor.
+ connect(dw, &ads::CDockWidget::titleChanged, this, [this, id](const QString& title) {
+ if (title != title_for_id(id)) // only save if user actually changed it
+ save_tab_title(id, title);
+ });
+
+ // Materialize on first show; save state on hide.
+ // Grid tracking (panel_count_, grid_*) is NOT updated here — hide signals
+ // fire during exclusive resets and would corrupt the counter before the
+ // new panel is placed. Grid is updated only inside navigate() itself.
+ connect(dw, &ads::CDockWidget::visibilityChanged, this, [this, id](bool visible) {
+ if (visible) {
+ materialize_screen(id);
+ } else {
+ save_screen_state(id);
+ }
+ });
+
+ dock_widgets_[id] = dw;
+ return dw;
+}
+
+void DockScreenRouter::materialize_screen(const QString& id) {
+ if (screens_.contains(id))
+ return;
+
+ auto fit = factories_.find(id);
+ if (fit == factories_.end())
+ return;
+
+ LOG_INFO("DockRouter", "Lazy-constructing screen: " + id);
+ QWidget* screen = nullptr;
+ try {
+ screen = fit.value()();
+ } catch (const std::exception& e) {
+ LOG_ERROR("DockRouter", QString("Factory threw for '%1': %2").arg(id, e.what()));
+ } catch (...) {
+ LOG_ERROR("DockRouter", QString("Factory threw unknown exception for '%1'").arg(id));
+ }
+ if (!screen) {
+ LOG_ERROR("DockRouter", "Factory returned null for: " + id);
+ return;
+ }
+ screen->setMinimumWidth(0);
+ factories_.erase(fit);
+
+ auto* dw = dock_widgets_.value(id, nullptr);
+ if (!dw) return;
+
+ QWidget* old = dw->widget();
+ dw->setWidget(screen);
+ if (old) {
+ old->setParent(nullptr);
+ old->deleteLater();
+ }
+ screens_[id] = screen;
+ restore_screen_state(id);
+}
+
+// ── Tab title persistence ─────────────────────────────────────────────────────
+
+void DockScreenRouter::save_tab_title(const QString& id, const QString& title) {
+ SessionManager::instance().save_tab_state(
+ "title/" + id, {{"title", title}});
+}
+
+QString DockScreenRouter::load_tab_title(const QString& id) const {
+ const auto state = SessionManager::instance().load_tab_state("title/" + id);
+ return state.value("title").toString();
+}
+
+// ── Screen state persistence (IStatefulScreen opt-in) ────────────────────────
+
+void DockScreenRouter::save_screen_state(const QString& id) {
+ auto* screen = screens_.value(id, nullptr);
+ if (!screen) return;
+ auto* stateful = dynamic_cast<screens::IStatefulScreen*>(screen);
+ if (!stateful) return;
+ SessionManager::instance().save_tab_state(
+ "screen_state/" + id, stateful->save_state());
+ LOG_DEBUG("DockRouter", "Saved screen state: " + id);
+}
+
+void DockScreenRouter::restore_screen_state(const QString& id) {
+ auto* screen = screens_.value(id, nullptr);
+ if (!screen) return;
+ auto* stateful = dynamic_cast<screens::IStatefulScreen*>(screen);
+ if (!stateful) return;
+ const auto state = SessionManager::instance().load_tab_state("screen_state/" + id);
+ if (!state.isEmpty()) {
+ stateful->restore_state(state);
+ LOG_DEBUG("DockRouter", "Restored screen state: " + id);
+ }
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/app/DockScreenRouter.h b/fincept-qt/src/app/DockScreenRouter.h
new file mode 100644
index 000000000..0e1427703
--- /dev/null
+++ b/fincept-qt/src/app/DockScreenRouter.h
@@ -0,0 +1,100 @@
+#pragma once
+#include <DockManager.h>
+#include <DockWidget.h>
+
+#include <QHash>
+#include <QObject>
+#include <functional>
+
+namespace fincept {
+
+/// ADS-aware screen router. Each screen is wrapped in a CDockWidget that can be
+/// docked, tabbed, floated, or auto-hidden. Mirrors ScreenRouter's API so the
+/// transition is straightforward.
+///
+/// Lazy loading: factories are stored and only called when a screen is first
+/// navigated to (or when ensure_all_registered() pre-creates placeholders for
+/// state restore).
+class DockScreenRouter : public QObject {
+ Q_OBJECT
+ public:
+ using ScreenFactory = std::function<QWidget*()>;
+
+ explicit DockScreenRouter(ads::CDockManager* manager, QObject* parent = nullptr);
+
+ /// Register a pre-built screen (eager — lightweight screens).
+ void register_screen(const QString& id, QWidget* screen);
+
+ /// Register a factory that creates the screen on first navigation (lazy).
+ void register_factory(const QString& id, ScreenFactory factory);
+
+ /// Navigate to a screen: ensures the dock widget exists, shows it, and
+ /// brings it to the front. Creates from factory on first access.
+ /// If exclusive is true, all other screens are closed first (single-screen mode).
+ void navigate(const QString& id, bool exclusive = false);
+
+ /// Add screen as an ADS tab inside the currently focused dock area.
+ /// If the screen is already open somewhere, just raises it.
+ /// If no area is open yet, opens it as the only screen.
+ void tab_into(const QString& id);
+
+ /// Open `primary` alone, then split `secondary` alongside it (side-by-side).
+ void add_alongside(const QString& primary, const QString& secondary);
+
+ /// Close all panels except `primary`, which fills the full area.
+ void remove_screen(const QString& primary);
+
+ /// Close current panel and open `secondary` in its place (full area).
+ void replace_screen(const QString& primary, const QString& secondary);
+
+ /// Returns the currently focused/active screen id.
+ QString current_screen_id() const { return current_id_; }
+
+ /// Pre-create CDockWidgets (with placeholder content) for ALL registered
+ /// factories. Required before calling CDockManager::restoreState() since
+ /// ADS needs all dock widgets to exist by objectName.
+ void ensure_all_registered();
+
+ /// Find an existing dock widget by screen id, or nullptr.
+ ads::CDockWidget* find_dock_widget(const QString& id) const;
+
+ /// Returns all registered screen IDs (both eager and factory).
+ QStringList all_screen_ids() const;
+
+ signals:
+ void screen_changed(const QString& id);
+
+ protected:
+ bool eventFilter(QObject* obj, QEvent* event) override;
+
+
+ private:
+ ads::CDockManager* manager_ = nullptr;
+ QHash<QString, ads::CDockWidget*> dock_widgets_;
+ QHash<QString, QWidget*> screens_; // materialized screen widgets
+ QHash<QString, ScreenFactory> factories_; // pending lazy factories
+ QString current_id_;
+
+ // Grid layout tracking — stores the dock area for each grid position.
+ // Populated as panels are opened (up to 4), used to place the next panel
+ // correctly (2x2 grid default). Cleared when exclusive navigation resets.
+ ads::CDockAreaWidget* grid_top_left_ = nullptr;
+ ads::CDockAreaWidget* grid_top_right_ = nullptr;
+ ads::CDockAreaWidget* grid_bottom_left_ = nullptr;
+ ads::CDockAreaWidget* grid_bottom_right_ = nullptr;
+ int panel_count_ = 0; // number of currently open panels
+
+ ads::CDockWidget* create_dock_widget(const QString& id);
+ void materialize_screen(const QString& id);
+ static QString title_for_id(const QString& id);
+
+ /// Persist and restore a user-edited tab title (separate from screen state).
+ void save_tab_title(const QString& id, const QString& title);
+ QString load_tab_title(const QString& id) const;
+
+ /// Save/restore IStatefulScreen state for a materialized screen widget.
+ void save_screen_state(const QString& id);
+ void restore_screen_state(const QString& id);
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/app/MainWindow.cpp b/fincept-qt/src/app/MainWindow.cpp
index 7d21e33b5..d1de88af6 100644
--- a/fincept-qt/src/app/MainWindow.cpp
+++ b/fincept-qt/src/app/MainWindow.cpp
@@ -1,5 +1,12 @@
#include "app/MainWindow.h"
+#include "app/DockScreenRouter.h"
+#include "ui/navigation/DockToolBar.h"
+#include "ui/navigation/DockStatusBar.h"
+#include <DockManager.h>
+#include <DockWidget.h>
+#include <DockAreaWidget.h>
+
#include "screens/chat_mode/ChatModeScreen.h"
#include "services/updater/UpdateService.h"
#include "ai_chat/AiChatBubble.h"
@@ -73,11 +80,13 @@
#include "ui/theme/Theme.h"
#include <QApplication>
+#include "core/config/ProfileManager.h"
#include <QCloseEvent>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileDialog>
+#include <QInputDialog>
#include <QMessageBox>
#include <QScreen>
#include <QShortcut>
@@ -87,8 +96,13 @@
namespace fincept {
-MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
- setWindowTitle("Fincept Terminal");
+MainWindow::MainWindow(int window_id, QWidget* parent)
+ : QMainWindow(parent), window_id_(window_id) {
+ // Show active profile in title bar when using a non-default profile
+ const QString profile = ProfileManager::instance().active();
+ setWindowTitle(profile == "default"
+ ? "Fincept Terminal"
+ : QString("Fincept Terminal [%1]").arg(profile));
// Load icon from the embedded Windows resource (IDI_ICON1 in app.rc).
// Falls back to the .ico beside the executable on other platforms.
QIcon app_icon;
@@ -109,13 +123,27 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
#endif
if (!app_icon.isNull())
setWindowIcon(app_icon);
- setMinimumSize(1280, 720);
-
- QScreen* screen = QApplication::primaryScreen();
- if (screen) {
- QRect geom = screen->availableGeometry();
- resize(geom.width() * 9 / 10, geom.height() * 9 / 10);
- move(geom.center() - rect().center());
+ // Minimum size must be small enough to allow OS window-snap (half/third screen).
+ // On a 1920-wide display, left-snap = 960px. Use 800x500 as minimum so snapping
+ // works on any 1080p+ monitor without the window bouncing back to centre.
+ setMinimumSize(800, 500);
+
+ // Primary windows (id 0) restore saved geometry from last session.
+ // Secondary windows (id > 0) restore their own saved geometry if available,
+ // otherwise use smart multi-monitor placement (handled by the caller after show()).
+ const QByteArray saved_geom = SessionManager::instance().load_geometry(window_id_);
+ if (!saved_geom.isEmpty()) {
+ restoreGeometry(saved_geom);
+ } else {
+ QScreen* screen = QApplication::primaryScreen();
+ if (screen) {
+ QRect geom = screen->availableGeometry();
+ resize(geom.width() * 9 / 10, geom.height() * 9 / 10);
+ // Only centre-place for the primary window; secondary windows
+ // are positioned by the "new window" action after construction.
+ if (window_id_ == 0)
+ move(geom.center() - rect().center());
+ }
}
auto* master_stack = new QStackedWidget;
@@ -125,51 +153,29 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
setup_auth_screens();
master_stack->addWidget(auth_stack_);
- // ── App shell ────────────────────────────────────────────────────────────
- app_container_ = new QWidget;
- auto* app_container = app_container_;
- auto* vl = new QVBoxLayout(app_container);
- vl->setContentsMargins(0, 0, 0, 0);
- vl->setSpacing(0);
-
- // Toolbar (menus + branding + clock + user + logout)
- auto* toolbar = new ui::ToolBar;
- vl->addWidget(toolbar);
-
- // Tab bar (14 tabs)
- auto* tab_bar = new ui::TabBar;
- vl->addWidget(tab_bar);
- tab_bar_widget_ = tab_bar;
-
- // Screen content
- app_stack_ = new QStackedWidget;
- vl->addWidget(app_stack_, 1);
-
- // Status bar
- auto* status_bar = new ui::StatusBar;
- vl->addWidget(status_bar);
- status_bar_widget_ = status_bar;
-
- master_stack->addWidget(app_container);
-
// ── Chat Mode ─────────────────────────────────────────────────────────────
chat_mode_screen_ = new chat_mode::ChatModeScreen;
- master_stack->addWidget(chat_mode_screen_); // index 2
+
+ // ── ADS Docking mode ─────────────────────────────────────────────────────
+ setup_docking_mode();
+ master_stack->addWidget(dock_manager_->parentWidget()); // index 1 — dock_wrapper
+ master_stack->addWidget(chat_mode_screen_); // index 2
connect(chat_mode_screen_, &chat_mode::ChatModeScreen::exit_requested,
this, &MainWindow::toggle_chat_mode);
setCentralWidget(master_stack);
- statusBar()->hide();
+
+ dock_toolbar_ = new ui::DockToolBar(this);
+ addToolBar(Qt::TopToolBarArea, dock_toolbar_);
+
+ dock_status_bar_ = new ui::DockStatusBar(this);
+ setStatusBar(dock_status_bar_);
stack_ = master_stack;
- router_ = new ScreenRouter(app_stack_, this);
- setup_app_screens();
+ auto* toolbar = dock_toolbar_->inner();
- // WorkspaceManager — wire router + main window
+ // ── Workspace + signal wiring ───────────────────────────────────────────
WorkspaceManager::instance().set_main_window(this);
- WorkspaceManager::instance().set_router(router_);
- connect(router_, &ScreenRouter::screen_changed,
- &WorkspaceManager::instance(), &WorkspaceManager::on_screen_changed);
connect(&WorkspaceManager::instance(), &WorkspaceManager::workspace_loaded,
this, [this](const WorkspaceDef& ws) {
setWindowTitle(QString("Fincept Terminal — %1").arg(ws.metadata.name));
@@ -179,8 +185,23 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
QMessageBox::warning(this, "Workspace Error", msg);
});
- // AI Chat Bubble — floats over app_stack_ content area
- chat_bubble_ = new AiChatBubble(app_stack_);
+ dock_router_ = new DockScreenRouter(dock_manager_, this);
+ setup_dock_screens();
+
+ // Tab bar navigation: open the selected screen exclusively — closes all other
+ // panels and fills the full area. Each tab is a fresh independent screen,
+ // not nested into whatever was previously open.
+ connect(tab_bar_, &ui::TabBar::tab_changed, this, [this](const QString& id) {
+ dock_router_->navigate(id, true);
+ });
+ connect(dock_router_, &DockScreenRouter::screen_changed, tab_bar_, &ui::TabBar::set_active);
+
+ connect(this, &QObject::destroyed, this, [this]() {
+ WorkspaceManager::instance().remove_window(this);
+ });
+
+ // Chat bubble — floats over dock_manager_ content area
+ chat_bubble_ = new AiChatBubble(dock_manager_);
{
auto r = SettingsRepository::instance().get("appearance.show_chat_bubble");
bool show = !r.is_ok() || r.value() != "false";
@@ -188,38 +209,40 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
if (show) chat_bubble_->raise();
}
- // Tab bar ↔ router
- connect(tab_bar, &ui::TabBar::tab_changed, router_, &ScreenRouter::navigate);
- connect(router_, &ScreenRouter::screen_changed, tab_bar, &ui::TabBar::set_active);
-
- // Re-raise bubble on every screen switch; respect show_chat_bubble setting
- connect(router_, &ScreenRouter::screen_changed, this, [this](const QString&) {
+ // Re-raise and reposition the bubble after each navigation — dock geometry
+ // shifts when panels open/close, so the bubble needs to re-anchor itself.
+ connect(dock_router_, &DockScreenRouter::screen_changed, this, [this](const QString&) {
if (!chat_bubble_) return;
auto r = SettingsRepository::instance().get("appearance.show_chat_bubble");
bool show = !r.is_ok() || r.value() != "false";
chat_bubble_->setVisible(show);
- if (show) {
- chat_bubble_->reposition();
- chat_bubble_->raise();
- }
+ if (show) { chat_bubble_->reposition(); chat_bubble_->raise(); }
});
- // Chat Mode toggle button in toolbar
connect(toolbar, &ui::ToolBar::chat_mode_toggled, this, &MainWindow::toggle_chat_mode);
+ connect(toolbar, &ui::ToolBar::navigate_to, this, [this](const QString& id) {
+ dock_router_->navigate(id, true);
+ });
- // Toolbar Navigate menu → router
- connect(toolbar, &ui::ToolBar::navigate_to, router_, &ScreenRouter::navigate);
+ connect(toolbar, &ui::ToolBar::dock_command, this,
+ [this](const QString& action, const QString& primary, const QString& secondary) {
+ if (action == "add")
+ dock_router_->add_alongside(primary, secondary);
+ else if (action == "remove")
+ dock_router_->remove_screen(primary);
+ else if (action == "replace")
+ dock_router_->replace_screen(primary, secondary);
+ });
- // MCP navigation tool → router (published from any thread, must invoke on UI thread)
+ // MCP navigation tool → dock_router (cross-thread safe)
EventBus::instance().subscribe("nav.switch_screen", [this](const QVariantMap& data) {
QString screen_id = data["screen_id"].toString();
if (!screen_id.isEmpty())
- QMetaObject::invokeMethod(router_, [this, screen_id]() {
- router_->navigate(screen_id);
+ QMetaObject::invokeMethod(dock_router_, [this, screen_id]() {
+ dock_router_->navigate(screen_id);
}, Qt::QueuedConnection);
});
- // ── Keyboard shortcuts ────────────────────────────────────────────────────
auto* sc_chat = new QShortcut(QKeySequence(Qt::Key_F9), this);
connect(sc_chat, &QShortcut::activated, this, &MainWindow::toggle_chat_mode);
@@ -234,16 +257,17 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
auto* sc_focus = new QShortcut(QKeySequence(Qt::Key_F10), this);
connect(sc_focus, &QShortcut::activated, this, [this]() {
focus_mode_ = !focus_mode_;
- if (tab_bar_widget_)
- tab_bar_widget_->setVisible(!focus_mode_);
- if (status_bar_widget_)
- status_bar_widget_->setVisible(!focus_mode_);
+ if (dock_toolbar_) dock_toolbar_->setVisible(!focus_mode_);
+ if (dock_status_bar_) dock_status_bar_->setVisible(!focus_mode_);
});
auto* sc_refresh = new QShortcut(QKeySequence(Qt::Key_F5), this);
connect(sc_refresh, &QShortcut::activated, this, [this]() {
- if (auto* w = app_stack_->currentWidget())
- QMetaObject::invokeMethod(w, "refresh", Qt::QueuedConnection);
+ if (dock_manager_) {
+ auto* focused = dock_manager_->focusedDockWidget();
+ if (focused && focused->widget())
+ QMetaObject::invokeMethod(focused->widget(), "refresh", Qt::QueuedConnection);
+ }
});
auto* sc_screenshot = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_P), this);
@@ -264,7 +288,79 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
// Toolbar actions
connect(toolbar, &ui::ToolBar::action_triggered, this, [this](const QString& action) {
- if (action == "logout") {
+ if (action == "new_window") {
+ auto* w = new MainWindow(MainWindow::next_window_id());
+ w->setAttribute(Qt::WA_DeleteOnClose);
+ // Place on the next available screen, or alongside this window
+ const QList<QScreen*> screens = QGuiApplication::screens();
+ if (screens.size() > 1) {
+ // Find a screen that doesn't already contain this window's centre
+ const QPoint this_centre = geometry().center();
+ for (QScreen* s : screens) {
+ if (!s->geometry().contains(this_centre)) {
+ const QRect sg = s->availableGeometry();
+ w->resize(sg.width() * 9 / 10, sg.height() * 9 / 10);
+ w->move(sg.center() - w->rect().center());
+ break;
+ }
+ }
+ }
+ w->show();
+ w->raise();
+ w->activateWindow();
+ } else if (action.startsWith("panel_")) {
+ // Float a screen — in ADS mode, navigate dock_router; in legacy, spawn window
+ static const QMap<QString, QPair<QString,QString>> panel_map = {
+ {"panel_dashboard", {"Dashboard", "dashboard"}},
+ {"panel_watchlist", {"Watchlist", "watchlist"}},
+ {"panel_news", {"News Feed", "news"}},
+ {"panel_portfolio", {"Portfolio", "portfolio"}},
+ {"panel_markets", {"Markets", "markets"}},
+ {"panel_crypto", {"Crypto Trading", "crypto_trading"}},
+ {"panel_equity", {"Equity Trading", "equity_trading"}},
+ {"panel_algo", {"Algo Trading", "algo_trading"}},
+ {"panel_research", {"Equity Research","equity_research"}},
+ {"panel_economics", {"Economics", "economics"}},
+ {"panel_geopolitics",{"Geopolitics", "geopolitics"}},
+ {"panel_ai_chat", {"AI Chat", "ai_chat"}},
+ };
+ if (panel_map.contains(action)) {
+ const auto [title, route] = panel_map[action];
+ if (dock_router_)
+ dock_router_->navigate(route);
+ }
+ } else if (action == "perspective_save") {
+ if (dock_manager_) {
+ bool ok = false;
+ const QString name = QInputDialog::getText(
+ this, "Save Layout", "Layout name:", QLineEdit::Normal,
+ QString(), &ok);
+ if (ok && !name.trimmed().isEmpty()) {
+ dock_manager_->addPerspective(name.trimmed());
+ LOG_INFO("MainWindow", QString("Saved perspective: %1").arg(name.trimmed()));
+ }
+ }
+ } else if (action.startsWith("perspective_")) {
+ static const QMap<QString, QString> persp_names = {
+ {"perspective_trading", "Trading"},
+ {"perspective_research", "Research"},
+ {"perspective_news", "News"},
+ {"perspective_portfolio", "Portfolio"},
+ };
+ const QString persp = persp_names.value(action);
+ if (!persp.isEmpty() && dock_manager_) {
+ if (!dock_manager_->perspectiveNames().contains(persp)) {
+ static const QMap<QString, QString> screen_map = {
+ {"Trading", "crypto_trading"}, {"Research", "equity_research"},
+ {"News", "news"}, {"Portfolio", "portfolio"},
+ };
+ if (dock_router_) dock_router_->navigate(screen_map.value(persp));
+ dock_manager_->addPerspective(persp);
+ }
+ dock_manager_->openPerspective(persp);
+ LOG_INFO("MainWindow", QString("Opened perspective: %1").arg(persp));
+ }
+ } else if (action == "logout") {
auth::AuthManager::instance().logout();
} else if (action == "fullscreen") {
if (isFullScreen())
@@ -273,10 +369,8 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
showFullScreen();
} else if (action == "focus_mode") {
focus_mode_ = !focus_mode_;
- if (tab_bar_widget_)
- tab_bar_widget_->setVisible(!focus_mode_);
- if (status_bar_widget_)
- status_bar_widget_->setVisible(!focus_mode_);
+ if (dock_toolbar_) dock_toolbar_->setVisible(!focus_mode_);
+ if (dock_status_bar_) dock_status_bar_->setVisible(!focus_mode_);
} else if (action == "always_on_top") {
always_on_top_ = !always_on_top_;
Qt::WindowFlags flags = windowFlags();
@@ -287,23 +381,26 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
setWindowFlags(flags);
show(); // required after setWindowFlags to re-show the window
} else if (action == "refresh") {
- if (auto* w = app_stack_->currentWidget())
- QMetaObject::invokeMethod(w, "refresh", Qt::QueuedConnection);
+ if (dock_manager_) {
+ auto* focused = dock_manager_->focusedDockWidget();
+ if (focused && focused->widget())
+ QMetaObject::invokeMethod(focused->widget(), "refresh", Qt::QueuedConnection);
+ }
} else if (action == "new_workspace") {
- auto* dlg = new WorkspaceNewDialog(this);
+ auto* dlg = new ui::WorkspaceNewDialog(this);
if (dlg->exec() == QDialog::Accepted)
WorkspaceManager::instance().new_workspace(
dlg->workspace_name(), dlg->workspace_description(), dlg->selected_template_id());
dlg->deleteLater();
} else if (action == "open_workspace") {
- auto* dlg = new WorkspaceOpenDialog(this);
+ auto* dlg = new ui::WorkspaceOpenDialog(this);
if (dlg->exec() == QDialog::Accepted && !dlg->selected_path().isEmpty())
WorkspaceManager::instance().open_workspace(dlg->selected_path());
dlg->deleteLater();
} else if (action == "save_workspace") {
WorkspaceManager::instance().save_workspace();
} else if (action == "save_workspace_as") {
- auto* dlg = new WorkspaceSaveAsDialog(this);
+ auto* dlg = new ui::WorkspaceSaveAsDialog(this);
if (dlg->exec() == QDialog::Accepted)
WorkspaceManager::instance().save_workspace_as(dlg->new_name(), dlg->chosen_path());
dlg->deleteLater();
@@ -347,12 +444,83 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
&MainWindow::on_auth_state_changed);
connect(&auth::AuthManager::instance(), &auth::AuthManager::logged_out, this, &MainWindow::on_auth_state_changed);
- // If a saved session exists, optimistically show the dashboard to avoid
- // flashing the login screen while session validation is in progress.
+ // Restore window state (maximised, toolbar positions, etc.)
+ // Note: restoreState() also restores QToolBar visibility, which can
+ // hide the toolbar from stale/corrupt saved state. We force it visible
+ // afterward unless the user is intentionally in focus/chat mode.
+ const QByteArray saved_state = SessionManager::instance().load_state(window_id_);
+ if (!saved_state.isEmpty())
+ restoreState(saved_state);
+
+ // Always ensure toolbar and status bar are visible after state restore.
+ // Focus mode and chat mode will hide them explicitly when toggled.
+ if (dock_toolbar_) dock_toolbar_->setVisible(true);
+ if (dock_status_bar_) dock_status_bar_->setVisible(true);
+
+ // Restore ADS dock layout — must happen after all screens are registered
+ // but BEFORE the initial navigate, so we don't create a widget that
+ // conflicts with restoreState's layout.
+ // Layout version: bump this whenever the dock layout format changes to
+ // automatically discard stale/corrupt saved state from previous versions.
+ static constexpr int kDockLayoutVersion = 4;
+ bool dock_restored = false;
+
+ if (dock_manager_) {
+ QSettings persp_settings;
+ SessionManager::instance().load_perspectives(persp_settings);
+ dock_manager_->loadPerspectives(persp_settings);
+
+ const int saved_version = SessionManager::instance().dock_layout_version(window_id_);
+ if (saved_version == kDockLayoutVersion) {
+ const QByteArray saved_dock = SessionManager::instance().load_dock_layout(window_id_);
+ if (!saved_dock.isEmpty()) {
+ dock_router_->ensure_all_registered();
+ dock_restored = dock_manager_->restoreState(saved_dock);
+
+ // Sanity check: if restoreState produced an unreasonable number
+ // of visible dock areas (>6), the layout is likely corrupt.
+ if (dock_restored && dock_manager_->openedDockAreas().size() > 6) {
+ LOG_WARN("MainWindow", QString("Dock layout corrupt: %1 open areas — resetting")
+ .arg(dock_manager_->openedDockAreas().size()));
+ dock_restored = false;
+ }
+ }
+ } else if (saved_version != 0) {
+ LOG_INFO("MainWindow", QString("Dock layout version mismatch (saved %1, expected %2) — resetting")
+ .arg(saved_version).arg(kDockLayoutVersion));
+ }
+
+ if (!dock_restored) {
+ // Close all dock widgets that may have been opened by a failed restore
+ for (auto* dw : dock_manager_->dockWidgetsMap())
+ dw->toggleView(false);
+ }
+
+ // Save the current version so next startup knows the format.
+ SessionManager::instance().set_dock_layout_version(window_id_, kDockLayoutVersion);
+ }
+
+ // Show the app or auth stack based on authentication state.
+ // If dock layout was restored, the saved tabs are already visible.
+ // Otherwise, navigate to dashboard as default.
auto& auth_mgr = auth::AuthManager::instance();
if (auth_mgr.is_authenticated() || auth_mgr.is_loading()) {
stack_->setCurrentIndex(1);
- router_->navigate("dashboard");
+ if (!dock_restored) {
+ dock_router_->navigate("dashboard");
+ LOG_INFO("MainWindow", "Applied clean default dock layout");
+ } else {
+ // Restore last-active screen as the focused tab and sync tab bar
+ const QString last = SessionManager::instance().last_screen();
+ if (!last.isEmpty()) {
+ auto* dw = dock_router_->find_dock_widget(last);
+ if (dw && !dw->isClosed()) {
+ dw->raise();
+ dw->setAsCurrentTab();
+ }
+ tab_bar_->set_active(last);
+ }
+ }
} else {
on_auth_state_changed();
}
@@ -382,17 +550,15 @@ void MainWindow::toggle_chat_mode() {
chat_mode_ = !chat_mode_;
if (chat_mode_) {
- // Enter chat mode: hide terminal chrome, show chat screen (index 2)
- if (tab_bar_widget_) tab_bar_widget_->setVisible(false);
- if (status_bar_widget_) status_bar_widget_->setVisible(false);
+ if (dock_toolbar_) dock_toolbar_->setVisible(false);
+ if (dock_status_bar_) dock_status_bar_->setVisible(false);
if (chat_bubble_) chat_bubble_->setVisible(false);
stack_->setCurrentIndex(2);
LOG_INFO("MainWindow", "Entered Chat Mode");
} else {
- // Exit chat mode: restore terminal
stack_->setCurrentIndex(1);
- if (tab_bar_widget_) tab_bar_widget_->setVisible(true);
- if (status_bar_widget_) status_bar_widget_->setVisible(true);
+ if (dock_toolbar_) dock_toolbar_->setVisible(true);
+ if (dock_status_bar_) dock_status_bar_->setVisible(true);
// Restore chat bubble based on setting
if (chat_bubble_) {
auto r = SettingsRepository::instance().get("appearance.show_chat_bubble");
@@ -437,7 +603,7 @@ void MainWindow::setup_auth_screens() {
connect(forgot, &screens::ForgotPasswordScreen::navigate_login, this, &MainWindow::show_login);
connect(pricing, &screens::PricingScreen::navigate_dashboard, this, [this]() {
stack_->setCurrentIndex(1);
- router_->navigate("dashboard");
+ dock_router_->navigate("dashboard");
});
// ── Info screen navigation ───────────────────────────────────────────────
@@ -455,78 +621,113 @@ void MainWindow::setup_auth_screens() {
connect(help, &screens::HelpScreen::navigate_forgot_password, this, &MainWindow::show_forgot_password);
}
-void MainWindow::setup_app_screens() {
- // ── Heavy screens: lazy-construct on first navigation ────────────────────
- // These spawn Python processes / timers / network requests in their constructors.
- router_->register_factory("dashboard", []() { return new screens::DashboardScreen; });
- router_->register_factory("markets", []() { return new screens::MarketsScreen; });
- router_->register_factory("crypto_trading", []() { return new screens::CryptoTradingScreen; });
- router_->register_factory("news", []() { return new screens::NewsScreen; });
- router_->register_factory("forum", []() { return new screens::ForumScreen; });
- router_->register_factory("watchlist", []() { return new screens::WatchlistScreen; });
-
- // ── Lightweight screens: eager construction is fine ──────────────────────
- router_->register_screen("report_builder", new screens::ReportBuilderScreen);
- router_->register_screen("profile", new screens::ProfileScreen);
- router_->register_screen("settings", new screens::SettingsScreen);
- router_->register_screen("about", new screens::AboutScreen);
- router_->register_screen("support", new screens::SupportScreen);
- router_->register_screen("notes", new screens::NotesScreen);
-
- // ── Coming-soon placeholders (trivial widgets) ──────────────────────────
- router_->register_factory("portfolio", []() { return new screens::PortfolioScreen; });
- router_->register_factory("ai_chat", []() { return new screens::AiChatScreen; });
- router_->register_factory("backtesting", []() { return new screens::BacktestingScreen; });
- router_->register_factory("algo_trading", []() { return new screens::AlgoTradingScreen; });
- router_->register_factory("node_editor", []() { return new workflow::NodeEditorScreen; });
- router_->register_factory("code_editor", []() { return new screens::CodeEditorScreen; });
- router_->register_factory("ai_quant_lab", []() { return new screens::AIQuantLabScreen; });
- router_->register_factory("quantlib", []() { return new screens::QuantLibScreen; });
- router_->register_factory("economics", []() { return new screens::EconomicsScreen; });
- router_->register_factory("gov_data", []() { return new screens::GovDataScreen; });
- router_->register_factory("dbnomics", []() { return new screens::DBnomicsScreen; });
- router_->register_factory("akshare", []() { return new screens::AkShareScreen; });
- router_->register_factory("asia_markets", []() { return new screens::AsiaMarketsScreen; });
- router_->register_factory("relationship_map", []() { return new screens::RelationshipMapScreen; });
- router_->register_factory("equity_trading", []() { return new screens::EquityTradingScreen; });
- router_->register_factory("alpha_arena", []() { return new screens::AlphaArenaScreen; });
- router_->register_factory("polymarket", []() { return new screens::PolymarketScreen; });
- router_->register_factory("derivatives", []() { return new screens::DerivativesScreen; });
- router_->register_factory("equity_research", []() { return new screens::EquityResearchScreen; });
- router_->register_factory("ma_analytics", []() { return new screens::MAAnalyticsScreen; });
- router_->register_factory("alt_investments", []() { return new screens::AltInvestmentsScreen; });
- router_->register_factory("geopolitics", []() { return new screens::GeopoliticsScreen; });
- router_->register_factory("maritime", []() { return new screens::MaritimeScreen; });
- router_->register_factory("surface_analytics", []() { return new fincept::surface::SurfaceAnalyticsScreen; });
- router_->register_factory("agent_config", []() { return new screens::AgentConfigScreen; });
- router_->register_factory("mcp_servers", []() { return new screens::McpServersScreen; });
- router_->register_factory("data_mapping", []() { return new screens::DataMappingScreen; });
- router_->register_factory("data_sources", []() { return new screens::DataSourcesScreen; });
- router_->register_factory("file_manager", [this]() {
+void MainWindow::setup_docking_mode() {
+ // ADS global config must be set before the first CDockManager is constructed.
+ // Guard with a static flag since multiple MainWindow instances share one process.
+ static bool s_ads_configured = false;
+ if (!s_ads_configured) {
+ ads::CDockManager::setConfigFlags(
+ ads::CDockManager::DefaultOpaqueConfig
+ | ads::CDockManager::FocusHighlighting
+ | ads::CDockManager::AlwaysShowTabs
+ | ads::CDockManager::DockAreaHasTabsMenuButton
+ | ads::CDockManager::DockAreaDynamicTabsMenuButtonVisibility
+ | ads::CDockManager::FloatingContainerHasWidgetTitle
+ | ads::CDockManager::FloatingContainerHasWidgetIcon
+ | ads::CDockManager::EqualSplitOnInsertion // prevents new panels from spawning tiny slivers
+ | ads::CDockManager::DoubleClickUndocksWidget // double-click tab to float
+ );
+ // Disable auto-hide entirely: the pin button converts panels to collapsible
+ // sidebars which collapse when another panel is opened beside them.
+ ads::CDockManager::setAutoHideConfigFlags(
+ ads::CDockManager::AutoHideFlags(0)
+ );
+ s_ads_configured = true;
+ }
+
+ // Create CDockManager — parent is a plain QWidget wrapper (not QMainWindow)
+ // so ADS does NOT call setCentralWidget(). The wrapper goes into master_stack.
+ auto* dock_wrapper = new QWidget;
+ auto* dock_layout = new QVBoxLayout(dock_wrapper);
+ dock_layout->setContentsMargins(0, 0, 0, 0);
+ dock_layout->setSpacing(0);
+
+ tab_bar_ = new ui::TabBar(dock_wrapper);
+ dock_layout->addWidget(tab_bar_);
+
+ dock_manager_ = new ads::CDockManager(dock_wrapper);
+ dock_layout->addWidget(dock_manager_);
+
+ // ADS styling is handled by ThemeManager's global QSS — no widget-level
+ // stylesheet needed here. The global QSS has higher priority and won't be
+ // overridden by theme changes.
+}
+
+void MainWindow::setup_dock_screens() {
+ dock_router_->register_factory("dashboard", []() { return new screens::DashboardScreen; });
+ dock_router_->register_factory("markets", []() { return new screens::MarketsScreen; });
+ dock_router_->register_factory("crypto_trading", []() { return new screens::CryptoTradingScreen; });
+ dock_router_->register_factory("news", []() { return new screens::NewsScreen; });
+ dock_router_->register_factory("forum", []() { return new screens::ForumScreen; });
+ dock_router_->register_factory("watchlist", []() { return new screens::WatchlistScreen; });
+
+ // Eagerly constructed: lightweight screens with no data fetching or timers.
+ dock_router_->register_screen("report_builder", new screens::ReportBuilderScreen);
+ dock_router_->register_screen("profile", new screens::ProfileScreen);
+ dock_router_->register_screen("settings", new screens::SettingsScreen);
+ dock_router_->register_screen("about", new screens::AboutScreen);
+ dock_router_->register_screen("support", new screens::SupportScreen);
+ dock_router_->register_screen("notes", new screens::NotesScreen);
+
+ dock_router_->register_factory("portfolio", []() { return new screens::PortfolioScreen; });
+ dock_router_->register_factory("ai_chat", []() { return new screens::AiChatScreen; });
+ dock_router_->register_factory("backtesting", []() { return new screens::BacktestingScreen; });
+ dock_router_->register_factory("algo_trading", []() { return new screens::AlgoTradingScreen; });
+ dock_router_->register_factory("node_editor", []() { return new workflow::NodeEditorScreen; });
+ dock_router_->register_factory("code_editor", []() { return new screens::CodeEditorScreen; });
+ dock_router_->register_factory("ai_quant_lab", []() { return new screens::AIQuantLabScreen; });
+ dock_router_->register_factory("quantlib", []() { return new screens::QuantLibScreen; });
+ dock_router_->register_factory("economics", []() { return new screens::EconomicsScreen; });
+ dock_router_->register_factory("gov_data", []() { return new screens::GovDataScreen; });
+ dock_router_->register_factory("dbnomics", []() { return new screens::DBnomicsScreen; });
+ dock_router_->register_factory("akshare", []() { return new screens::AkShareScreen; });
+ dock_router_->register_factory("asia_markets", []() { return new screens::AsiaMarketsScreen; });
+ dock_router_->register_factory("relationship_map", []() { return new screens::RelationshipMapScreen; });
+ dock_router_->register_factory("equity_trading", []() { return new screens::EquityTradingScreen; });
+ dock_router_->register_factory("alpha_arena", []() { return new screens::AlphaArenaScreen; });
+ dock_router_->register_factory("polymarket", []() { return new screens::PolymarketScreen; });
+ dock_router_->register_factory("derivatives", []() { return new screens::DerivativesScreen; });
+ dock_router_->register_factory("equity_research", []() { return new screens::EquityResearchScreen; });
+ dock_router_->register_factory("ma_analytics", []() { return new screens::MAAnalyticsScreen; });
+ dock_router_->register_factory("alt_investments", []() { return new screens::AltInvestmentsScreen; });
+ dock_router_->register_factory("geopolitics", []() { return new screens::GeopoliticsScreen; });
+ dock_router_->register_factory("maritime", []() { return new screens::MaritimeScreen; });
+ dock_router_->register_factory("surface_analytics", []() { return new fincept::surface::SurfaceAnalyticsScreen; });
+ dock_router_->register_factory("agent_config", []() { return new screens::AgentConfigScreen; });
+ dock_router_->register_factory("mcp_servers", []() { return new screens::McpServersScreen; });
+ dock_router_->register_factory("data_mapping", []() { return new screens::DataMappingScreen; });
+ dock_router_->register_factory("data_sources", []() { return new screens::DataSourcesScreen; });
+ dock_router_->register_factory("file_manager", [this]() {
auto* fm = new screens::FileManagerScreen;
- // "Open With" buttons emit this — navigate to the target screen.
- // The file path is intentionally not forwarded here because each screen
- // manages its own open dialog; the navigation itself is sufficient to
- // bring the user to the right place.
connect(fm, &screens::FileManagerScreen::open_file_in_screen,
this, [this](const QString& route_id, const QString& /*file_path*/) {
- router_->navigate(route_id);
+ dock_router_->navigate(route_id);
});
return fm;
});
- router_->register_factory("excel", []() { return new screens::ExcelScreen; });
- router_->register_factory("trade_viz", []() { return new screens::TradeVizScreen; });
-
- router_->register_factory("docs", []() { return new screens::DocsScreen; });
-
- // Info / legal pages (accessible from app navigation menu too)
- router_->register_screen("contact", new screens::ContactScreen);
- router_->register_screen("terms", new screens::TermsScreen);
- router_->register_screen("privacy", new screens::PrivacyScreen);
- router_->register_screen("trademarks", new screens::TrademarksScreen);
- router_->register_screen("help", new screens::HelpScreen);
+ dock_router_->register_factory("excel", []() { return new screens::ExcelScreen; });
+ dock_router_->register_factory("trade_viz", []() { return new screens::TradeVizScreen; });
+ dock_router_->register_factory("docs", []() { return new screens::DocsScreen; });
+
+ // Info/legal pages: static content, safe to construct eagerly.
+ dock_router_->register_screen("contact", new screens::ContactScreen);
+ dock_router_->register_screen("terms", new screens::TermsScreen);
+ dock_router_->register_screen("privacy", new screens::PrivacyScreen);
+ dock_router_->register_screen("trademarks", new screens::TrademarksScreen);
+ dock_router_->register_screen("help", new screens::HelpScreen);
}
+void MainWindow::setup_app_screens() {}
void MainWindow::setup_navigation() {}
void MainWindow::on_auth_state_changed() {
@@ -599,7 +800,13 @@ void MainWindow::show_info_help() {
void MainWindow::closeEvent(QCloseEvent* event) {
WorkspaceManager::instance().save_workspace();
- SessionManager::instance().save_geometry(saveGeometry(), saveState());
+ SessionManager::instance().save_geometry(window_id_, saveGeometry(), saveState());
+ if (dock_manager_) {
+ SessionManager::instance().save_dock_layout(window_id_, dock_manager_->saveState());
+ QSettings tmp;
+ dock_manager_->savePerspectives(tmp);
+ SessionManager::instance().save_perspectives(tmp);
+ }
event->accept();
}
diff --git a/fincept-qt/src/app/MainWindow.h b/fincept-qt/src/app/MainWindow.h
index f581fe0c0..2445eda50 100644
--- a/fincept-qt/src/app/MainWindow.h
+++ b/fincept-qt/src/app/MainWindow.h
@@ -7,6 +7,9 @@
#include <QStackedWidget>
#include <QTimer>
+namespace ads { class CDockManager; }
+namespace fincept { class DockScreenRouter; }
+namespace fincept::ui { class DockToolBar; class DockStatusBar; class TabBar; }
namespace fincept::chat_mode { class ChatModeScreen; }
namespace fincept {
@@ -14,7 +17,14 @@ namespace fincept {
class MainWindow : public QMainWindow {
Q_OBJECT
public:
- explicit MainWindow(QWidget* parent = nullptr);
+ /// @param window_id Unique id for this window instance (0 = primary, 1+ = secondary).
+ /// Primary restores saved geometry; secondary uses smart placement.
+ explicit MainWindow(int window_id = 0, QWidget* parent = nullptr);
+
+ int window_id() const { return window_id_; }
+
+ /// Returns the next unique window ID (thread-safe via Qt UI thread only).
+ static int next_window_id() { static int s_id = 1; return s_id++; }
protected:
void closeEvent(QCloseEvent* event) override;
@@ -22,27 +32,31 @@ class MainWindow : public QMainWindow {
private:
QStackedWidget* stack_ = nullptr;
- ScreenRouter* router_ = nullptr;
-
- // Two stacks: auth screens and main app screens
QStackedWidget* auth_stack_ = nullptr;
- QStackedWidget* app_stack_ = nullptr;
+
+ int window_id_ = 0;
+
+ // ADS dock system
+ ads::CDockManager* dock_manager_ = nullptr;
+ DockScreenRouter* dock_router_ = nullptr;
+ ui::DockToolBar* dock_toolbar_ = nullptr;
+ ui::DockStatusBar* dock_status_bar_ = nullptr;
+ ui::TabBar* tab_bar_ = nullptr;
// View state
bool focus_mode_ = false;
bool chat_mode_ = false;
bool always_on_top_ = false;
- QWidget* tab_bar_widget_ = nullptr;
- QWidget* status_bar_widget_ = nullptr;
AiChatBubble* chat_bubble_ = nullptr;
QTimer* user_refresh_timer_ = nullptr;
// Chat mode
chat_mode::ChatModeScreen* chat_mode_screen_ = nullptr;
- QWidget* app_container_ = nullptr; // the normal terminal shell
void setup_auth_screens();
void setup_app_screens();
+ void setup_docking_mode();
+ void setup_dock_screens();
void setup_navigation();
void on_auth_state_changed();
void toggle_chat_mode();
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index d666f7e7a..88e08a459 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -3,6 +3,7 @@
#include "auth/SessionGuard.h"
#include "core/config/AppConfig.h"
#include "core/config/AppPaths.h"
+#include "core/config/ProfileManager.h"
#include "core/logging/Logger.h"
#include "core/session/SessionManager.h"
#include "mcp/McpInit.h"
@@ -19,25 +20,76 @@
#include "ui/theme/Theme.h"
#include "ui/theme/ThemeManager.h"
-#include <QApplication>
+#include <SingleApplication.h>
#include <QDir>
#include <QFile>
+#include <QLockFile>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QStandardPaths>
+#ifdef Q_OS_WIN
+# include <Windows.h>
+#endif
+
int main(int argc, char* argv[]) {
- QApplication app(argc, argv);
+ // ── Parse --profile <name> from argv before Qt initialises ───────────────
+ // This must happen first so that:
+ // 1. AppPaths returns the correct per-profile directories
+ // 2. SingleApplication uses a profile-scoped IPC key so two different
+ // profiles can run simultaneously as independent primary instances
+ {
+ for (int i = 1; i < argc - 1; ++i) {
+ if (qstrcmp(argv[i], "--profile") == 0) {
+ fincept::ProfileManager::instance().set_active(
+ QString::fromUtf8(argv[i + 1]));
+ break;
+ }
+ }
+ // AppPaths::root() must exist before ensure_all() so ProfileManager can
+ // write the manifest. Create root now (single mkdir, idempotent).
+ QDir().mkpath(fincept::AppPaths::root());
+ }
+
+ // Required before QApplication when any dock panel contains an OpenGL widget
+ // (Qt Charts, QOpenGLWidget) — prevents black rendering in floating windows.
+ QApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
+
+ // SingleApplication enforces one process per profile.
+ // The instance key is scoped to the active profile name, so
+ // "FinceptTerminal --profile work" and "FinceptTerminal --profile personal"
+ // are treated as two separate primary instances and run simultaneously.
+ // allowSecondary=true: secondary instances send "--new-window" and exit.
+ const QString profile_key = QString("FinceptTerminal-%1")
+ .arg(fincept::ProfileManager::instance().active());
+ SingleApplication app(argc, argv, /*allowSecondary=*/true,
+ SingleApplication::Mode::User,
+ 100,
+ profile_key.toUtf8());
app.setApplicationName("FinceptTerminal");
app.setOrganizationName("Fincept");
app.setApplicationVersion("4.0.0");
+ // ── Secondary instance: signal primary to open a new window, then exit ───
+ // The primary receives receivedMessage() and calls open_new_window().
+ if (app.isSecondary()) {
+#ifdef Q_OS_WIN
+ // Grant the primary process permission to bring its new window to the
+ // foreground — Windows blocks focus-steal without this.
+ AllowSetForegroundWindow(static_cast<DWORD>(app.primaryPid()));
+#endif
+ app.sendMessage(QByteArray("--new-window"));
+ return 0;
+ }
+
+ // ── Primary instance from here on ────────────────────────────────────────
+
// Create all application directories under %LOCALAPPDATA%\com.fincept.terminal\
fincept::AppPaths::ensure_all();
- // ── One-time migration: move files from old scattered locations ──────────
- // Old log location: %APPDATA%\Fincept\FinceptTerminal\fincept.log
- // Old DB location: %APPDATA%\Fincept\FinceptTerminal\fincept.db / cache.db
+ // ── One-time migration from legacy %APPDATA% location ─────────────────
+ // Current locations (under %LOCALAPPDATA%\com.fincept.terminal\):
+ // Log: <root>/logs/fincept.log DB: <root>/data/fincept.db
{
const QString old_base = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
const auto migrate_file = [](const QString& old_path, const QString& new_path) {
@@ -55,12 +107,20 @@ int main(int argc, char* argv[]) {
QFile::remove(old_base + "/cache.db-shm");
}
- // Remove stale SQLite WAL/SHM lock files left by a previous crash.
- // qsqlite.dll crashes on WAL recovery if the lock files are orphaned.
- QFile::remove(fincept::AppPaths::data() + "/fincept.db-wal");
- QFile::remove(fincept::AppPaths::data() + "/fincept.db-shm");
- QFile::remove(fincept::AppPaths::data() + "/cache.db-wal");
- QFile::remove(fincept::AppPaths::data() + "/cache.db-shm");
+ // ── WAL/SHM cleanup — gated behind QLockFile ────────────────────────────
+ // Deleting WAL/SHM files while another process has the DB open corrupts it.
+ // We only clean up orphaned files from a previous crash when we are the sole
+ // running instance. The lock file is held for the entire process lifetime.
+ QLockFile db_lock(fincept::AppPaths::data() + "/fincept.db.lock");
+ db_lock.setStaleLockTime(0); // never auto-expire; we control the lifecycle
+ const bool sole_instance = db_lock.tryLock(0);
+ if (sole_instance) {
+ QFile::remove(fincept::AppPaths::data() + "/fincept.db-wal");
+ QFile::remove(fincept::AppPaths::data() + "/fincept.db-shm");
+ QFile::remove(fincept::AppPaths::data() + "/cache.db-wal");
+ QFile::remove(fincept::AppPaths::data() + "/cache.db-shm");
+ }
+ // db_lock remains held (stack-allocated) until main() returns.
// Also clean legacy v3 DB location
{
const QString local_dir = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
@@ -238,8 +298,23 @@ int main(int argc, char* argv[]) {
setup_screen->hide();
setup_screen->deleteLater();
- auto* window = new fincept::MainWindow;
+ auto* window = new fincept::MainWindow(0); // primary window
+ window->setAttribute(Qt::WA_DeleteOnClose);
window->show();
+
+ // Wire new-window handler now that the primary window exists
+ QObject::connect(&app, &SingleApplication::receivedMessage,
+ [](quint32 /*instanceId*/, QByteArray /*message*/) {
+ auto* w = new fincept::MainWindow(fincept::MainWindow::next_window_id());
+ w->setAttribute(Qt::WA_DeleteOnClose);
+ w->show();
+ w->raise();
+ w->activateWindow();
+ LOG_INFO("App", "New window opened via secondary instance request");
+ });
+ QObject::connect(&app, &QApplication::lastWindowClosed,
+ &app, &QApplication::quit);
+
if (!fincept::ai_chat::LlmService::instance().is_configured())
LOG_WARN("App", "LLM provider not configured — AI chat will prompt user to configure Settings → LLM Config");
LOG_INFO("App", "Application ready (after setup)");
@@ -252,6 +327,24 @@ int main(int argc, char* argv[]) {
fincept::MainWindow window;
window.show();
+ // ── New-window handler: fires when the user re-launches the exe ──────────
+ // The secondary instance sends "--new-window" and exits. We construct a new
+ // independent MainWindow in this process. WA_DeleteOnClose ensures cleanup.
+ // QApplication::lastWindowClosed() → quit() handles the final exit.
+ QObject::connect(&app, &SingleApplication::receivedMessage,
+ [](quint32 /*instanceId*/, QByteArray /*message*/) {
+ auto* w = new fincept::MainWindow(fincept::MainWindow::next_window_id());
+ w->setAttribute(Qt::WA_DeleteOnClose);
+ w->show();
+ w->raise();
+ w->activateWindow();
+ LOG_INFO("App", "New window opened via secondary instance request");
+ });
+
+ // Quit when the last window is closed (standard Qt SDI behaviour).
+ QObject::connect(&app, &QApplication::lastWindowClosed,
+ &app, &QApplication::quit);
+
// If requirements files changed (app update), sync packages in background
// without blocking the user.
if (setup_status.needs_package_sync) {
diff --git a/fincept-qt/src/core/config/AppPaths.cpp b/fincept-qt/src/core/config/AppPaths.cpp
index 53ddaad0c..06132c025 100644
--- a/fincept-qt/src/core/config/AppPaths.cpp
+++ b/fincept-qt/src/core/config/AppPaths.cpp
@@ -1,4 +1,5 @@
#include "core/config/AppPaths.h"
+#include "core/config/ProfileManager.h"
#include <QDir>
#include <QStandardPaths>
@@ -22,19 +23,19 @@ QString AppPaths::root() {
}
QString AppPaths::data() {
- return root() + "/data";
+ return ProfileManager::instance().profile_root() + "/data";
}
QString AppPaths::logs() {
- return root() + "/logs";
+ return ProfileManager::instance().profile_root() + "/logs";
}
QString AppPaths::files() {
- return root() + "/files";
+ return ProfileManager::instance().profile_root() + "/files";
}
QString AppPaths::cache() {
- return root() + "/cache";
+ return ProfileManager::instance().profile_root() + "/cache";
}
QString AppPaths::models() {
@@ -46,7 +47,7 @@ QString AppPaths::runtime() {
}
QString AppPaths::workspaces() {
- return root() + "/workspaces";
+ return ProfileManager::instance().profile_root() + "/workspaces";
}
void AppPaths::ensure_all() {
diff --git a/fincept-qt/src/core/config/ProfileManager.cpp b/fincept-qt/src/core/config/ProfileManager.cpp
new file mode 100644
index 000000000..05f1e5764
--- /dev/null
+++ b/fincept-qt/src/core/config/ProfileManager.cpp
@@ -0,0 +1,135 @@
+#include "core/config/ProfileManager.h"
+#include "core/config/AppPaths.h"
+
+#include <QDir>
+#include <QFile>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+
+namespace fincept {
+
+ProfileManager& ProfileManager::instance() {
+ static ProfileManager s;
+ return s;
+}
+
+void ProfileManager::set_active(const QString& name) {
+ // Sanitise: only allow alphanumeric, dash, underscore
+ QString clean = name.trimmed().toLower();
+ for (QChar& c : clean) {
+ if (!c.isLetterOrNumber() && c != '-' && c != '_')
+ c = '_';
+ }
+ if (clean.isEmpty())
+ clean = "default";
+
+ active_profile_ = clean;
+
+ // Ensure the profile directory tree exists
+ QDir().mkpath(profile_root() + "/data");
+ QDir().mkpath(profile_root() + "/logs");
+ QDir().mkpath(profile_root() + "/cache");
+ QDir().mkpath(profile_root() + "/files");
+ QDir().mkpath(profile_root() + "/workspaces");
+
+ // Register in manifest if not already there
+ QStringList existing = list_profiles();
+ if (!existing.contains(active_profile_)) {
+ existing.append(active_profile_);
+ save_manifest(existing);
+ }
+}
+
+QString ProfileManager::active() const {
+ return active_profile_;
+}
+
+bool ProfileManager::is_custom_profile() const {
+ return active_profile_ != "default";
+}
+
+QString ProfileManager::profile_root() const {
+ if (active_profile_ == "default")
+ return AppPaths::root();
+ return AppPaths::root() + "/profiles/" + active_profile_;
+}
+
+QString ProfileManager::settings_group() const {
+ if (active_profile_ == "default")
+ return {};
+ return "profiles/" + active_profile_;
+}
+
+QString ProfileManager::secure_key_prefix() const {
+ if (active_profile_ == "default")
+ return {};
+ return "profiles/" + active_profile_ + "/";
+}
+
+QStringList ProfileManager::list_profiles() const {
+ QStringList result{"default"};
+
+ QFile f(manifest_path());
+ if (!f.open(QIODevice::ReadOnly))
+ return result;
+
+ const QJsonDocument doc = QJsonDocument::fromJson(f.readAll());
+ f.close();
+
+ if (!doc.isObject())
+ return result;
+
+ const QJsonArray arr = doc.object().value("profiles").toArray();
+ for (const QJsonValue& v : arr) {
+ const QString name = v.toString();
+ if (!name.isEmpty() && !result.contains(name))
+ result.append(name);
+ }
+ return result;
+}
+
+void ProfileManager::create_profile(const QString& name) {
+ QStringList profiles = list_profiles();
+ if (!profiles.contains(name)) {
+ profiles.append(name);
+ save_manifest(profiles);
+ }
+ // Create directory tree eagerly so it's ready for use
+ const QString root = AppPaths::root() + "/profiles/" + name;
+ QDir().mkpath(root + "/data");
+ QDir().mkpath(root + "/logs");
+ QDir().mkpath(root + "/cache");
+ QDir().mkpath(root + "/files");
+ QDir().mkpath(root + "/workspaces");
+}
+
+void ProfileManager::delete_profile(const QString& name) {
+ if (name == "default")
+ return; // cannot delete the default profile
+ QStringList profiles = list_profiles();
+ profiles.removeAll(name);
+ save_manifest(profiles);
+ // Intentionally NOT deleting the directory — user must do that to avoid data loss
+}
+
+QString ProfileManager::manifest_path() const {
+ return AppPaths::root() + "/profiles.json";
+}
+
+void ProfileManager::save_manifest(const QStringList& profiles) const {
+ QJsonArray arr;
+ for (const QString& p : profiles)
+ arr.append(p);
+
+ QJsonObject obj;
+ obj["profiles"] = arr;
+
+ QFile f(manifest_path());
+ if (f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
+ f.write(QJsonDocument(obj).toJson(QJsonDocument::Indented));
+ f.close();
+ }
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/config/ProfileManager.h b/fincept-qt/src/core/config/ProfileManager.h
new file mode 100644
index 000000000..c6989ecc3
--- /dev/null
+++ b/fincept-qt/src/core/config/ProfileManager.h
@@ -0,0 +1,67 @@
+#pragma once
+#include <QStringList>
+#include <QString>
+
+namespace fincept {
+
+/// Manages named user profiles, each with isolated data/logs/cache directories
+/// and separate credentials.
+///
+/// Usage:
+/// ProfileManager::instance().set_active("work");
+/// // AppPaths::data() now returns .../profiles/work/data/
+///
+/// Profiles are stored under:
+/// %LOCALAPPDATA%\com.fincept.terminal\profiles\<name>\
+///
+/// A manifest at root/profiles.json tracks the list of profiles.
+/// The default profile is named "default".
+///
+/// Call set_active() BEFORE AppPaths::ensure_all() in main().
+class ProfileManager {
+ public:
+ static ProfileManager& instance();
+
+ /// Set the active profile. Must be called before AppPaths is used.
+ /// Creates the profile directory if it doesn't exist.
+ void set_active(const QString& name);
+
+ /// Returns the active profile name (default: "default").
+ QString active() const;
+
+ /// Returns true if a non-default profile is active.
+ bool is_custom_profile() const;
+
+ /// Returns all known profile names from the manifest.
+ QStringList list_profiles() const;
+
+ /// Creates a new profile entry in the manifest (does not switch to it).
+ void create_profile(const QString& name);
+
+ /// Deletes a profile from the manifest. Does NOT delete its data directory
+ /// (user must do that manually to avoid accidental data loss).
+ void delete_profile(const QString& name);
+
+ /// Returns the root directory for the active profile.
+ /// When active == "default", returns AppPaths::root() directly (no migration needed).
+ /// Otherwise returns AppPaths::root()/profiles/<name>/.
+ QString profile_root() const;
+
+ /// QSettings group prefix for the active profile — used by AppConfig
+ /// to namespace per-profile settings under a shared Registry key.
+ QString settings_group() const;
+
+ /// SecureStorage key prefix — credentials are keyed as "profiles/<name>/<key>"
+ /// so different profiles never share credential entries.
+ QString secure_key_prefix() const;
+
+ private:
+ ProfileManager() = default;
+
+ QString active_profile_{"default"};
+
+ QString manifest_path() const;
+ void save_manifest(const QStringList& profiles) const;
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/session/SessionManager.cpp b/fincept-qt/src/core/session/SessionManager.cpp
index a3972efd7..f711d076f 100644
--- a/fincept-qt/src/core/session/SessionManager.cpp
+++ b/fincept-qt/src/core/session/SessionManager.cpp
@@ -43,17 +43,83 @@ QVariantMap SessionManager::load_tab_state(const QString& tab_id) const {
return result;
}
-void SessionManager::save_geometry(const QByteArray& geometry, const QByteArray& state) {
- settings_.setValue("window/geometry", geometry);
- settings_.setValue("window/state", state);
+void SessionManager::save_geometry(int window_id, const QByteArray& geometry, const QByteArray& state) {
+ const QString prefix = QString("window_%1/").arg(window_id);
+ settings_.setValue(prefix + "geometry", geometry);
+ settings_.setValue(prefix + "state", state);
}
-QByteArray SessionManager::load_geometry() const {
- return settings_.value("window/geometry").toByteArray();
+QByteArray SessionManager::load_geometry(int window_id) const {
+ const QString prefix = QString("window_%1/").arg(window_id);
+ // Fall back to legacy flat key for migration from single-window era
+ QByteArray val = settings_.value(prefix + "geometry").toByteArray();
+ if (val.isEmpty() && window_id == 0)
+ val = settings_.value("window/geometry").toByteArray();
+ return val;
}
-QByteArray SessionManager::load_state() const {
- return settings_.value("window/state").toByteArray();
+QByteArray SessionManager::load_state(int window_id) const {
+ const QString prefix = QString("window_%1/").arg(window_id);
+ QByteArray val = settings_.value(prefix + "state").toByteArray();
+ if (val.isEmpty() && window_id == 0)
+ val = settings_.value("window/state").toByteArray();
+ return val;
+}
+
+void SessionManager::save_window_count(int count) {
+ settings_.setValue("window_count", count);
+}
+
+int SessionManager::load_window_count() const {
+ return settings_.value("window_count", 1).toInt();
+}
+
+void SessionManager::save_dock_layout(int window_id, const QByteArray& layout) {
+ const QString prefix = QString("window_%1/").arg(window_id);
+ settings_.setValue(prefix + "dock_layout", layout);
+}
+
+QByteArray SessionManager::load_dock_layout(int window_id) const {
+ const QString prefix = QString("window_%1/").arg(window_id);
+ QByteArray val = settings_.value(prefix + "dock_layout").toByteArray();
+ if (val.isEmpty() && window_id == 0)
+ val = settings_.value("window/dock_layout").toByteArray();
+ return val;
+}
+
+void SessionManager::set_dock_layout_version(int window_id, int version) {
+ const QString prefix = QString("window_%1/").arg(window_id);
+ settings_.setValue(prefix + "dock_layout_version", version);
+}
+
+int SessionManager::dock_layout_version(int window_id) const {
+ const QString prefix = QString("window_%1/").arg(window_id);
+ return settings_.value(prefix + "dock_layout_version", 0).toInt();
+}
+
+void SessionManager::save_perspectives(const QSettings& source) {
+ // Copy all keys from the source QSettings (written by ADS savePerspectives)
+ // into our own settings_ under a "perspectives/" prefix.
+ QSettings& src = const_cast<QSettings&>(source);
+ src.beginGroup("Perspectives");
+ const QStringList keys = src.allKeys();
+ settings_.beginGroup("perspectives");
+ settings_.remove(""); // clear previous
+ for (const QString& k : keys)
+ settings_.setValue(k, src.value(k));
+ settings_.endGroup();
+ src.endGroup();
+}
+
+void SessionManager::load_perspectives(QSettings& target) const {
+ QSettings& s = const_cast<QSettings&>(settings_);
+ s.beginGroup("perspectives");
+ const QStringList keys = s.allKeys();
+ target.beginGroup("Perspectives");
+ for (const QString& k : keys)
+ target.setValue(k, s.value(k));
+ target.endGroup();
+ s.endGroup();
}
void SessionManager::set_last_screen(const QString& screen_id) {
diff --git a/fincept-qt/src/core/session/SessionManager.h b/fincept-qt/src/core/session/SessionManager.h
index 8171ee082..47d1f7d95 100644
--- a/fincept-qt/src/core/session/SessionManager.h
+++ b/fincept-qt/src/core/session/SessionManager.h
@@ -20,10 +20,26 @@ class SessionManager : public QObject {
void save_tab_state(const QString& tab_id, const QVariantMap& state);
QVariantMap load_tab_state(const QString& tab_id) const;
- // Window geometry
- void save_geometry(const QByteArray& geometry, const QByteArray& state);
- QByteArray load_geometry() const;
- QByteArray load_state() const;
+ // Window geometry — scoped per window_id (0 = primary)
+ void save_geometry(int window_id, const QByteArray& geometry, const QByteArray& state);
+ QByteArray load_geometry(int window_id) const;
+ QByteArray load_state(int window_id) const;
+
+ // Track how many windows were open at last shutdown
+ void save_window_count(int count);
+ int load_window_count() const;
+
+ // ADS dock layout — scoped per window_id
+ void save_dock_layout(int window_id, const QByteArray& layout);
+ QByteArray load_dock_layout(int window_id) const;
+
+ // Dock layout version — used to auto-discard stale layouts after code changes
+ void set_dock_layout_version(int window_id, int version);
+ int dock_layout_version(int window_id) const;
+
+ // Named perspectives (Bloomberg-style saved layouts)
+ void save_perspectives(const QSettings& source);
+ void load_perspectives(QSettings& target) const;
// Last active screen
void set_last_screen(const QString& screen_id);
diff --git a/fincept-qt/src/python/PythonRunner.cpp b/fincept-qt/src/python/PythonRunner.cpp
index 074df2960..19d04c416 100644
--- a/fincept-qt/src/python/PythonRunner.cpp
+++ b/fincept-qt/src/python/PythonRunner.cpp
@@ -220,7 +220,18 @@ void PythonRunner::start_next() {
auto* proc = new QProcess(this);
QStringList full_args;
- full_args << script_path;
+
+ // If the script is inside a sub-package (contains '/'), use -m <module>
+ // so Python can resolve relative imports (from .core import ...).
+ // Convert "Analytics/economics/trade_geopolitics.py" → "-m Analytics.economics.trade_geopolitics"
+ if (!is_code && req.script.contains('/')) {
+ QString module = req.script;
+ module.remove(".py");
+ module.replace('/', '.');
+ full_args << "-m" << module;
+ } else {
+ full_args << script_path;
+ }
if (!is_code)
full_args.append(req.args);
@@ -230,7 +241,25 @@ void PythonRunner::start_next() {
env.insert("PYTHONDONTWRITEBYTECODE", "1");
env.insert("PYTHONUNBUFFERED", "1");
env.insert("FINCEPT_DATA_DIR", PythonSetupManager::instance().install_dir());
+ // Add scripts dir to PYTHONPATH so package-relative imports (from .core import ...)
+ // work when scripts inside sub-packages are run directly as script files.
+ QString existing_pypath = env.value("PYTHONPATH");
+ QString new_pypath = scripts_dir_ + (existing_pypath.isEmpty() ? "" : ";" + existing_pypath);
+
+ // For nested packages invoked with -m (e.g. agents/finagent_core/main.py → -m agents.finagent_core.main),
+ // the __init__.py may use absolute imports like "from finagent_core.xxx import ...".
+ // These need the parent directory of the package on PYTHONPATH.
+ // e.g. "from finagent_core.core_agent import ..." needs scripts/agents/ on the path.
+ if (!is_code && req.script.contains('/')) {
+ QString script_dir = QFileInfo(scripts_dir_ + "/" + req.script).dir().absolutePath();
+ QString parent_of_pkg = QFileInfo(script_dir).dir().absolutePath();
+ if (parent_of_pkg != scripts_dir_ && !new_pypath.contains(parent_of_pkg))
+ new_pypath = parent_of_pkg + ";" + new_pypath;
+ }
+
+ env.insert("PYTHONPATH", new_pypath);
proc->setProcessEnvironment(env);
+ proc->setWorkingDirectory(scripts_dir_);
#ifdef _WIN32
proc->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {
diff --git a/fincept-qt/src/screens/IStatefulScreen.h b/fincept-qt/src/screens/IStatefulScreen.h
new file mode 100644
index 000000000..f64364780
--- /dev/null
+++ b/fincept-qt/src/screens/IStatefulScreen.h
@@ -0,0 +1,32 @@
+#pragma once
+#include <QVariantMap>
+
+namespace fincept::screens {
+
+/// Opt-in interface for screens that want to persist lightweight UI state
+/// (active tab index, last searched symbol, selected region, etc.) across
+/// sessions. Screens implementing this are called by DockScreenRouter after
+/// construction (restore_state) and before destruction/hide (save_state).
+///
+/// Usage:
+/// class MyScreen : public QWidget, public IStatefulScreen { ... };
+///
+/// The state map uses plain string keys and QVariant values — keep it small.
+/// Do NOT store large data, credentials, or full model state here.
+class IStatefulScreen {
+ public:
+ virtual ~IStatefulScreen() = default;
+
+ /// Called by DockScreenRouter after the screen is fully constructed and
+ /// shown for the first time. Restore UI state from the provided map.
+ virtual void restore_state(const QVariantMap& state) = 0;
+
+ /// Called by DockScreenRouter when the screen is hidden or closed.
+ /// Return a map of lightweight UI state to persist.
+ virtual QVariantMap save_state() const = 0;
+
+ /// Unique key used for storage — must match the screen's dock id.
+ virtual QString state_key() const = 0;
+};
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp
index 1227c74d6..3791a8ed2 100644
--- a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp
+++ b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp
@@ -465,8 +465,8 @@ QWidget* AlphaArenaScreen::create_leaderboard_panel() {
QWidget* AlphaArenaScreen::create_right_panel() {
auto* panel = new QWidget;
panel->setObjectName("aaRightPanel");
- panel->setMinimumWidth(360);
- panel->setMaximumWidth(440);
+ panel->setMinimumWidth(280);
+ panel->setMaximumWidth(400);
auto* vl = new QVBoxLayout(panel);
vl->setContentsMargins(0, 0, 0, 0);
diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
index 712ac9f89..8122adc12 100644
--- a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
@@ -47,6 +47,7 @@ DashboardScreen::DashboardScreen(QWidget* parent) : QWidget(parent) {
// Scroll area wraps canvas — provides vertical scroll when content exceeds viewport
scroll_area_ = new QScrollArea;
scroll_area_->setWidgetResizable(false); // canvas controls its own size
+ scroll_area_->setMinimumWidth(0); // allow ADS to shrink this panel freely
scroll_area_->setWidget(canvas_);
scroll_area_->setStyleSheet(
QString("QScrollArea{border:none;background:transparent;}"
@@ -64,7 +65,9 @@ DashboardScreen::DashboardScreen(QWidget* parent) : QWidget(parent) {
content_split_->addWidget(market_pulse_);
content_split_->setStretchFactor(0, 3);
content_split_->setStretchFactor(1, 1);
- content_split_->setSizes({900, 280});
+ content_split_->setCollapsible(0, false);
+ content_split_->setCollapsible(1, false);
+ market_pulse_->setMinimumWidth(180);
vl->addWidget(content_split_, 1);
@@ -149,6 +152,19 @@ void DashboardScreen::showEvent(QShowEvent* event) {
if (ticker_bar_)
ticker_bar_->resume();
+ // Set splitter sizes on first show using actual pixel width.
+ // Must be done here (not in constructor) because the widget has no size yet
+ // during construction. MarketPulsePanel's large sizeHint otherwise causes it
+ // to claim ~70% of the splitter before the user sees it.
+ if (!split_sized_) {
+ split_sized_ = true;
+ const int total = content_split_->width();
+ if (total > 400) {
+ const int pulse_w = qBound(180, total / 4, 320);
+ content_split_->setSizes({total - pulse_w, pulse_w});
+ }
+ }
+
if (!layout_restored_) {
layout_restored_ = true;
restore_layout();
@@ -167,9 +183,15 @@ bool DashboardScreen::eventFilter(QObject* obj, QEvent* event) {
if (obj == scroll_area_->viewport() && event->type() == QEvent::Resize) {
int vp_w = scroll_area_->viewport()->width();
// Only update if width actually changed — avoids triggering
- // resizeEvent → rebuild_grid_cache → reflow_tiles on every scroll tick
- if (vp_w > 0 && vp_w != canvas_->width())
- canvas_->setFixedWidth(vp_w);
+ // resizeEvent → rebuild_grid_cache → reflow_tiles on every scroll tick.
+ // Use setMaximumWidth + resize instead of setFixedWidth so the canvas
+ // never imposes a minimum-width constraint that fights ADS splitters
+ // when two screens are placed side-by-side.
+ if (vp_w > 0 && vp_w != canvas_->width()) {
+ canvas_->setMinimumWidth(0);
+ canvas_->setMaximumWidth(QWIDGETSIZE_MAX);
+ canvas_->resize(vp_w, canvas_->height());
+ }
}
return QWidget::eventFilter(obj, event);
}
diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.h b/fincept-qt/src/screens/dashboard/DashboardScreen.h
index d2980d0ca..693bca95e 100644
--- a/fincept-qt/src/screens/dashboard/DashboardScreen.h
+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.h
@@ -44,6 +44,7 @@ class DashboardScreen : public QWidget {
QTimer* save_timer_ = nullptr;
bool pulse_visible_ = true;
bool layout_restored_ = false;
+ bool split_sized_ = false;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp b/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp
index 8a53e8d27..db92f3bcf 100644
--- a/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp
+++ b/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp
@@ -35,7 +35,11 @@ static const QStringList kSnapshotSymbols = services::MarketDataService::global_
// ── Constructor ──────────────────────────────────────────────────────────────
MarketPulsePanel::MarketPulsePanel(QWidget* parent) : QWidget(parent) {
- setMinimumWidth(260);
+ setMinimumWidth(180);
+ // Constrain preferred width so the QSplitter doesn't give this panel
+ // the majority of space before the user sees the dashboard.
+ // The user can still drag the splitter handle wider if needed.
+ setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
auto* vl = new QVBoxLayout(this);
vl->setContentsMargins(0, 0, 0, 0);
diff --git a/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.cpp b/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.cpp
index 90d2af4bd..1b31577ae 100644
--- a/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.cpp
+++ b/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.cpp
@@ -36,6 +36,35 @@ DashboardCanvas::DashboardCanvas(QWidget* parent) : QWidget(parent) {
scroll_timer_ = new QTimer(this);
scroll_timer_->setInterval(40);
connect(scroll_timer_, &QTimer::timeout, this, &DashboardCanvas::on_scroll_tick);
+
+ // Debounce resize events so ADS splitter drags don't trigger repeated
+ // column recalculations and layout compaction on every pixel of movement.
+ resize_timer_ = new QTimer(this);
+ resize_timer_->setSingleShot(true);
+ resize_timer_->setInterval(150);
+ connect(resize_timer_, &QTimer::timeout, this, [this]() {
+ const int w = pending_resize_w_;
+ if (w <= 0) return;
+
+ // Restore to canonical columns if width now permits it — user's layout
+ // should snap back when they expand the panel again.
+ const int target_cols = (w >= 1000) ? canonical_cols_
+ : (w >= 600) ? std::min(canonical_cols_, 9)
+ : std::min(canonical_cols_, 6);
+
+ if (target_cols != layout_.cols) {
+ layout_.cols = target_cols;
+ for (auto& item : layout_.items) {
+ item.cell.w = std::min(item.cell.w, layout_.cols);
+ item.cell.x = std::min(item.cell.x, layout_.cols - item.cell.w);
+ }
+ layout_.items = compact_vertical(layout_.items);
+ }
+
+ if (!dragging_tile_ && !resizing_tile_)
+ reflow_tiles();
+ update_canvas_height();
+ });
}
DashboardCanvas::~DashboardCanvas() {
@@ -52,7 +81,12 @@ void DashboardCanvas::load_layout(const GridLayout& layout) {
tiles_.clear();
layout_ = layout;
- // Ensure responsive columns
+ // Record the canonical column count from the saved layout — this is what
+ // the user designed for. Responsive shrink is allowed on narrow viewports
+ // but we restore to this when the panel expands back to full width.
+ canonical_cols_ = layout_.cols > 0 ? layout_.cols : 12;
+
+ // Apply responsive columns for current width without clamping canonical_cols_
if (width() > 0)
layout_.cols = responsive_cols(width());
@@ -80,7 +114,8 @@ void DashboardCanvas::apply_template(const QString& template_id) {
for (const auto& t : tmpls) {
if (t.id == template_id) {
GridLayout layout;
- layout.cols = width() > 0 ? responsive_cols(width()) : 12;
+ layout.cols = 12; // templates are designed for 12 columns
+ canonical_cols_ = 12;
layout.row_h = layout_.row_h;
layout.margin = layout_.margin;
for (auto item : t.items) {
@@ -386,24 +421,18 @@ void DashboardCanvas::on_scroll_tick() {
void DashboardCanvas::resizeEvent(QResizeEvent* e) {
QWidget::resizeEvent(e);
- // Update responsive columns
- int new_cols = responsive_cols(width());
- if (new_cols != layout_.cols) {
- layout_.cols = new_cols;
- // Clamp items to new column count
- for (auto& item : layout_.items) {
- item.cell.w = std::min(item.cell.w, layout_.cols);
- item.cell.x = std::min(item.cell.x, layout_.cols - item.cell.w);
- }
- layout_.items = compact_vertical(layout_.items);
- }
-
- // During an active drag or resize, don't reflow — the operation handlers
- // manage tile positions themselves. A full reflow would fight the user.
+ // Immediately reflow tiles to the new pixel width without changing column
+ // count. This keeps widget positions visually correct as the panel is dragged.
+ // Column recalculation (and potentially layout compaction) is deferred to
+ // resize_timer_ so transient ADS splitter movements don't destroy the layout.
if (!dragging_tile_ && !resizing_tile_)
reflow_tiles();
update_canvas_height();
+
+ // Kick the debounce timer — column recalc fires after 150ms of stable width.
+ pending_resize_w_ = width();
+ resize_timer_->start();
}
void DashboardCanvas::paintEvent(QPaintEvent* event) {
diff --git a/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.h b/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.h
index eb25834ec..af39579fc 100644
--- a/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.h
+++ b/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.h
@@ -73,6 +73,16 @@ class DashboardCanvas : public QWidget {
QTimer* scroll_timer_ = nullptr;
QPoint last_drag_canvas_pos_;
+ // Debounce rapid resize events (e.g. ADS splitter drag).
+ // Column recalculation and compaction only happen after the timer fires,
+ // preventing layout destruction during transient width changes.
+ QTimer* resize_timer_ = nullptr;
+ int pending_resize_w_ = 0;
+
+ // The column count the user last explicitly set (via load/apply/drag).
+ // Responsive shrink is allowed, but we restore this when width permits.
+ int canonical_cols_ = 12;
+
fincept::ui::ThemeTokens tokens_{};
};
diff --git a/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.cpp
index 3da3fa976..78bf65251 100644
--- a/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.cpp
@@ -46,7 +46,7 @@ EconomicCalendarWidget::EconomicCalendarWidget(QWidget* parent)
scroll->setWidgetResizable(true);
scroll->setStyleSheet("QScrollArea { border: none; background: transparent; }"
"QScrollBar:vertical { width: 4px; background: transparent; }"
- "QScrollBar::handle:vertical { background: #222222; border-radius: 2px; min-height: 20px; }"
+ + QString("QScrollBar::handle:vertical { background: %1; border-radius: 2px; min-height: 20px; }").arg(ui::colors::BORDER_MED) +
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }");
auto* list_widget = new QWidget;
diff --git a/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp
index e703807c1..ea48cb083 100644
--- a/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp
@@ -14,7 +14,7 @@ NewsWidget::NewsWidget(QWidget* parent) : BaseWidget("MARKET NEWS", parent, ui::
scroll->setWidgetResizable(true);
scroll->setStyleSheet("QScrollArea { border: none; background: transparent; }"
"QScrollBar:vertical { width: 6px; background: transparent; }"
- "QScrollBar::handle:vertical { background: #222222; border-radius: 3px; }"
+ + QString("QScrollBar::handle:vertical { background: %1; border-radius: 3px; }").arg(ui::colors::BORDER_MED) +
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }");
auto* container = new QWidget;
diff --git a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
index 9a56e04e1..48bbe7775 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
@@ -73,7 +73,7 @@ PortfolioSummaryWidget::PortfolioSummaryWidget(QWidget* parent)
scroll->setWidgetResizable(true);
scroll->setStyleSheet("QScrollArea { border: none; background: transparent; }"
"QScrollBar:vertical { width: 4px; background: transparent; }"
- "QScrollBar::handle:vertical { background: #222222; border-radius: 2px; min-height: 20px; }"
+ + QString("QScrollBar::handle:vertical { background: %1; border-radius: 2px; min-height: 20px; }").arg(ui::colors::BORDER_MED) +
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }");
auto* list_widget = new QWidget;
diff --git a/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
index 543fbdbb4..66e30d086 100644
--- a/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
@@ -159,7 +159,7 @@ QuickTradeWidget::QuickTradeWidget(QWidget* parent) : BaseWidget("QUICK TRADE",
"QPushButton:hover { background: %2; }"
"QPushButton:disabled { background: %3; color: %4; }")
.arg(ui::colors::POSITIVE())
- .arg("#15803d")
+ .arg(ui::colors::POSITIVE())
.arg(ui::colors::BG_RAISED())
.arg(ui::colors::TEXT_TERTIARY()));
vl->addWidget(submit_btn_);
@@ -237,7 +237,7 @@ void QuickTradeWidget::on_side_changed(int idx) {
"font-size: 11px; font-weight: bold; }"
"QPushButton:hover { background: %2; }")
.arg(color)
- .arg(idx == 0 ? "#15803d" : "#b91c1c"));
+ .arg(color));
}
void QuickTradeWidget::submit_order() {
diff --git a/fincept-qt/src/screens/dashboard/widgets/RecentFilesWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/RecentFilesWidget.cpp
index 22b7f47b9..be9474e26 100644
--- a/fincept-qt/src/screens/dashboard/widgets/RecentFilesWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/RecentFilesWidget.cpp
@@ -18,13 +18,13 @@ using fincept::services::FileManagerService;
static const char* MF = "font-family:'Consolas','Courier New',monospace;";
RecentFilesWidget::RecentFilesWidget(QWidget* parent)
- : BaseWidget("Recent Files", parent, "#d97706") {
+ : BaseWidget("Recent Files", parent, ui::colors::AMBER.get()) {
auto* scroll = new QScrollArea;
scroll->setWidgetResizable(true);
scroll->setStyleSheet("QScrollArea{border:none;background:transparent;}"
"QScrollBar:vertical{background:transparent;width:4px;}"
- "QScrollBar::handle:vertical{background:#222;}");
+ + QString("QScrollBar::handle:vertical{background:%1;}").arg(ui::colors::BORDER_MED));
auto* container = new QWidget;
container->setStyleSheet("background:transparent;");
@@ -83,7 +83,8 @@ void RecentFilesWidget::refresh_data() {
for (const QJsonObject& f : files) {
auto* row = new QWidget;
row->setStyleSheet(
- "background:#0d0d0d;border:1px solid #1a1a1a;border-radius:2px;");
+ QString("background:%1;border:1px solid %2;border-radius:2px;")
+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));
auto* rl = new QHBoxLayout(row);
rl->setContentsMargins(8, 5, 8, 5);
rl->setSpacing(6);
@@ -96,13 +97,13 @@ void RecentFilesWidget::refresh_data() {
badge->setAlignment(Qt::AlignCenter);
badge->setStyleSheet(
QString("color:%1;font-size:9px;font-weight:700;background:transparent;%2")
- .arg("#d97706", MF));
+ .arg(ui::colors::AMBER, MF));
rl->addWidget(badge);
// Name
auto* name_lbl = new QLabel(f["originalName"].toString());
name_lbl->setStyleSheet(
- QString("color:#e5e5e5;font-size:11px;background:transparent;%1").arg(MF));
+ QString("color:%1;font-size:11px;background:transparent;%2").arg(ui::colors::TEXT_PRIMARY, MF));
name_lbl->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
rl->addWidget(name_lbl, 1);
diff --git a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp
index 22dd5f38d..33f018a19 100644
--- a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp
@@ -76,7 +76,7 @@ ScreenerWidget::ScreenerWidget(QWidget* parent) : BaseWidget("STOCK SCREENER", p
scroll->setWidgetResizable(true);
scroll->setStyleSheet("QScrollArea { border: none; background: transparent; }"
"QScrollBar:vertical { width: 4px; background: transparent; }"
- "QScrollBar::handle:vertical { background: #222222; border-radius: 2px; min-height: 20px; }"
+ + QString("QScrollBar::handle:vertical { background: %1; border-radius: 2px; min-height: 20px; }").arg(ui::colors::BORDER_MED) +
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }");
auto* list_widget = new QWidget;
diff --git a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp
index b4e586d35..0d8cc3a62 100644
--- a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp
@@ -13,9 +13,9 @@ TopMoversWidget::TopMoversWidget(QWidget* parent) : BaseWidget("TOP MOVERS", par
tl->setSpacing(0);
auto active_style = [](const QString& color) {
- return QString("QPushButton { background: %1; color: #000; border: none; "
+ return QString("QPushButton { background: %1; color: %2; border: none; "
"font-size: 9px; font-weight: bold; padding: 4px; }")
- .arg(color);
+ .arg(color, ui::colors::BG_BASE);
};
auto inactive_style = QString("QPushButton { background: %1; color: %2; border: none; "
"font-size: 9px; font-weight: bold; padding: 4px; }")
@@ -68,12 +68,12 @@ void TopMoversWidget::refresh_data() {
void TopMoversWidget::show_tab(bool gainers) {
showing_gainers_ = gainers;
- auto active_g = QString("QPushButton { background: %1; color: #000; border: none; "
+ auto active_g = QString("QPushButton { background: %1; color: %2; border: none; "
"font-size: 9px; font-weight: bold; padding: 4px; }")
- .arg(ui::colors::POSITIVE);
- auto active_l = QString("QPushButton { background: %1; color: #000; border: none; "
+ .arg(ui::colors::POSITIVE, ui::colors::BG_BASE);
+ auto active_l = QString("QPushButton { background: %1; color: %2; border: none; "
"font-size: 9px; font-weight: bold; padding: 4px; }")
- .arg(ui::colors::NEGATIVE);
+ .arg(ui::colors::NEGATIVE, ui::colors::BG_BASE);
auto inactive = QString("QPushButton { background: %1; color: %2; border: none; "
"font-size: 9px; font-weight: bold; padding: 4px; }")
.arg(ui::colors::BG_SURFACE, ui::colors::TEXT_TERTIARY);
diff --git a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp
index a70408809..7e19435f7 100644
--- a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp
@@ -35,7 +35,7 @@ WatchlistWidget::WatchlistWidget(QWidget* parent)
go_btn->setFixedWidth(32);
go_btn->setStyleSheet(QString("QPushButton { background: %1; color: %2; border: none; "
"font-size: 9px; font-weight: bold; padding: 3px; }"
- "QPushButton:hover { background: #e8860a; }")
+ + QString("QPushButton:hover { background: %1; }").arg(ui::colors::AMBER))
.arg(ui::colors::AMBER, ui::colors::BG_BASE));
connect(go_btn, &QPushButton::clicked, this, [this]() {
QString text = symbols_input_->text().trimmed().toUpper();
diff --git a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp
index caa7c8550..839d3cf84 100644
--- a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp
+++ b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp
@@ -1115,7 +1115,7 @@ QWidget* DataMappingScreen::create_field_mapping_panel() {
json_tree_->setHeaderLabels({"Key", "Value", "Type"});
json_tree_->setColumnWidth(0, 160);
json_tree_->setColumnWidth(1, 200);
- json_tree_->setMinimumWidth(300);
+ json_tree_->setMinimumWidth(250);
split->addWidget(json_tree_);
// Mapping table
@@ -1124,7 +1124,7 @@ QWidget* DataMappingScreen::create_field_mapping_panel() {
mapping_table_->setHorizontalHeaderLabels({"Target Field", "Expression", "Transform", "Default"});
mapping_table_->horizontalHeader()->setStretchLastSection(true);
mapping_table_->verticalHeader()->setVisible(false);
- mapping_table_->setMinimumWidth(400);
+ mapping_table_->setMinimumWidth(300);
mapping_table_->setMinimumHeight(250);
split->addWidget(mapping_table_);
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen.cpp b/fincept-qt/src/screens/data_sources/DataSourcesScreen.cpp
index 65d4dc54c..246f06d03 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen.cpp
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen.cpp
@@ -725,7 +725,8 @@ QWidget* DataSourcesScreen::build_browse_page() {
QWidget* DataSourcesScreen::build_category_panel() {
auto* panel = new QWidget;
panel->setObjectName("dsSidebar");
- panel->setFixedWidth(180);
+ panel->setMinimumWidth(150);
+ panel->setMaximumWidth(220);
auto* vl = new QVBoxLayout(panel);
vl->setContentsMargins(0, 0, 0, 0);
diff --git a/fincept-qt/src/screens/dbnomics/DBnomicsScreen.cpp b/fincept-qt/src/screens/dbnomics/DBnomicsScreen.cpp
index 18628a347..00ef41b00 100644
--- a/fincept-qt/src/screens/dbnomics/DBnomicsScreen.cpp
+++ b/fincept-qt/src/screens/dbnomics/DBnomicsScreen.cpp
@@ -116,7 +116,8 @@ void DBnomicsScreen::build_ui() {
// Left sidebar
selection_panel_ = new DBnomicsSelectionPanel(content_widget);
- selection_panel_->setFixedWidth(280);
+ selection_panel_->setMinimumWidth(220);
+ selection_panel_->setMaximumWidth(340);
content_hl->addWidget(selection_panel_);
// Right panel
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
index 15323d66d..522c0cc85 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
@@ -268,4 +268,24 @@ void EquityResearchScreen::update_quote_bar(const services::equity::QuoteData& q
hl_label_->setText(QString("H:%1%2 L:%1%3").arg(cs).arg(q.high, 0, 'f', 2).arg(q.low, 0, 'f', 2));
}
+QVariantMap EquityResearchScreen::save_state() const {
+ return {
+ {"symbol", current_symbol_},
+ {"tab_index", tab_widget_ ? tab_widget_->currentIndex() : 0}
+ };
+}
+
+void EquityResearchScreen::restore_state(const QVariantMap& state) {
+ const QString sym = state.value("symbol").toString();
+ if (!sym.isEmpty()) {
+ current_symbol_ = sym;
+ services::equity::EquityResearchService::instance().load_symbol(sym);
+ }
+ if (tab_widget_) {
+ const int idx = state.value("tab_index", 0).toInt();
+ if (idx >= 0 && idx < tab_widget_->count())
+ tab_widget_->setCurrentIndex(idx);
+ }
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
index 2b60b4cb5..36b2380cf 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
@@ -1,5 +1,6 @@
// src/screens/equity_research/EquityResearchScreen.h
#pragma once
+#include "screens/IStatefulScreen.h"
#include "services/equity/EquityResearchModels.h"
#include <QHideEvent>
@@ -19,11 +20,15 @@ class EquityTalippTab;
class EquityPeersTab;
class EquityNewsTab;
-class EquityResearchScreen : public QWidget {
+class EquityResearchScreen : public QWidget, public IStatefulScreen {
Q_OBJECT
public:
explicit EquityResearchScreen(QWidget* parent = nullptr);
+ void restore_state(const QVariantMap& state) override;
+ QVariantMap save_state() const override;
+ QString state_key() const override { return "equity_research"; }
+
protected:
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
diff --git a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp
index e20294c89..e2e1f67d9 100644
--- a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp
@@ -6,6 +6,7 @@
#include "ui/widgets/WorldMapWidget.h"
#include <QDesktopServices>
+#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QRandomGenerator>
@@ -29,7 +30,8 @@ void ConflictMonitorPanel::build_ui() {
// Left: map + table in a vertical splitter
auto* left_splitter = new QSplitter(Qt::Vertical, this);
left_splitter->setHandleWidth(2);
- left_splitter->setStyleSheet(QString("QSplitter::handle { background:%1; }").arg(ui::colors::BORDER_DIM));
+ left_splitter->setStyleSheet(
+ QString("QSplitter::handle { background:%1; }").arg(ui::colors::BORDER_DIM));
// ── World Map ───────────────────────────────────────────────────────────
map_widget_ = new fincept::ui::WorldMapWidget(left_splitter);
@@ -39,40 +41,70 @@ void ConflictMonitorPanel::build_ui() {
// ── Events Table ────────────────────────────────────────────────────────
events_table_ = new QTableWidget(left_splitter);
events_table_->setColumnCount(7);
- events_table_->setHorizontalHeaderLabels({"Category", "Country", "City", "Keywords", "Date", "Lat", "Lng"});
+ events_table_->setHorizontalHeaderLabels(
+ {"Category", "Country", "City", "Keywords", "Date", "Lat", "Lng"});
events_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
events_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
events_table_->setAlternatingRowColors(true);
- events_table_->horizontalHeader()->setStretchLastSection(true);
+ events_table_->horizontalHeader()->setStretchLastSection(false);
events_table_->verticalHeader()->setVisible(false);
events_table_->setSortingEnabled(true);
- events_table_->setStyleSheet(QString("QTableWidget { background:%1; color:%2; gridline-color:%3;"
- "font-family:%4; font-size:%5px; border:none; }"
- "QTableWidget::item { padding:4px 8px; }"
- "QTableWidget::item:selected { background:rgba(255,0,0,0.15); }"
- "QHeaderView::section { background:%6; color:%7; font-weight:700;"
- "padding:6px 8px; border:1px solid %3; font-family:%4; font-size:%5px; }"
- "QTableWidget::item:alternate { background:%8; }")
- .arg(ui::colors::BG_SURFACE, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_DIM)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL)
- .arg(ui::colors::BG_RAISED)
- .arg(ui::colors::TEXT_SECONDARY)
- .arg(ui::colors::ROW_ALT));
-
- connect(events_table_, &QTableWidget::currentCellChanged, this, [this](int row, int, int, int) {
+
+ events_table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
+ events_table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
+ events_table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
+ events_table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
+ events_table_->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
+ events_table_->horizontalHeader()->setSectionResizeMode(5, QHeaderView::ResizeToContents);
+ events_table_->horizontalHeader()->setSectionResizeMode(6, QHeaderView::ResizeToContents);
+
+ events_table_->setColumnHidden(5, true);
+ events_table_->setColumnHidden(6, true);
+ events_table_->verticalHeader()->setDefaultSectionSize(26);
+
+ events_table_->setStyleSheet(
+ QString("QTableWidget { background:%1; color:%2; gridline-color:%3;"
+ "font-family:%4; font-size:%5px; border:none; }"
+ "QTableWidget::item { padding:3px 8px; }"
+ "QTableWidget::item:selected { background:rgba(255,0,0,0.15); }"
+ "QHeaderView::section { background:%6; color:%7; font-weight:700;"
+ "padding:5px 8px; border:1px solid %3; font-family:%4; font-size:%5px; }"
+ "QTableWidget::item:alternate { background:%8; }")
+ .arg(ui::colors::BG_SURFACE, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_DIM)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::colors::BG_RAISED)
+ .arg(ui::colors::TEXT_SECONDARY)
+ .arg(ui::colors::ROW_ALT));
+
+ connect(events_table_, &QTableWidget::currentCellChanged,
+ this, [this](int row, int, int, int) {
if (row < 0 || !detail_panel_)
return;
- detail_category_->setText(events_table_->item(row, 0) ? events_table_->item(row, 0)->text().toUpper() : "");
- detail_country_->setText(events_table_->item(row, 1) ? events_table_->item(row, 1)->text() : "");
- detail_city_->setText(events_table_->item(row, 2) ? events_table_->item(row, 2)->text() : "");
- detail_keywords_->setText(events_table_->item(row, 3) ? events_table_->item(row, 3)->text() : "");
- detail_date_->setText(events_table_->item(row, 4) ? events_table_->item(row, 4)->text() : "");
+
+ auto get_text = [this, row](int col) -> QString {
+ return events_table_->item(row, col)
+ ? events_table_->item(row, col)->text()
+ : QString();
+ };
+
+ detail_category_->setText(get_text(0).toUpper());
+ detail_country_ ->setText(get_text(1));
+ detail_city_ ->setText(get_text(2));
+ detail_keywords_->setText(get_text(3));
+ detail_date_ ->setText(get_text(4));
+
+ auto cat_color = category_color(get_text(0));
+ detail_category_->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
+ .arg(cat_color.name())
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
+
detail_panel_->setVisible(true);
});
left_splitter->addWidget(events_table_);
- // 40% map, 60% table
left_splitter->setStretchFactor(0, 4);
left_splitter->setStretchFactor(1, 6);
root->addWidget(left_splitter, 1);
@@ -81,7 +113,8 @@ void ConflictMonitorPanel::build_ui() {
auto* sidebar = new QWidget(this);
sidebar->setFixedWidth(240);
sidebar->setStyleSheet(
- QString("background:%1; border-left:1px solid %2;").arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));
+ QString("background:%1; border-left:1px solid %2;")
+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));
auto* svl = new QVBoxLayout(sidebar);
svl->setContentsMargins(12, 12, 12, 12);
@@ -89,61 +122,88 @@ void ConflictMonitorPanel::build_ui() {
auto* stats_title = new QLabel("TOP CATEGORIES", sidebar);
stats_title->setStyleSheet(
- QString("color:#FF0000; font-size:9px; font-weight:700; font-family:%1; letter-spacing:1px;")
- .arg(ui::fonts::DATA_FAMILY));
+ QString("color:#FF0000; font-size:%1px; font-weight:700; font-family:%2;"
+ "letter-spacing:1px; padding-bottom:6px; border-bottom:1px solid %3;")
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::BORDER_DIM));
svl->addWidget(stats_title);
auto* stats_container = new QWidget(sidebar);
stats_layout_ = new QVBoxLayout(stats_container);
stats_layout_->setContentsMargins(0, 0, 0, 0);
- stats_layout_->setSpacing(4);
+ stats_layout_->setSpacing(3);
svl->addWidget(stats_container);
stats_label_ = new QLabel("No data", sidebar);
stats_label_->setStyleSheet(
- QString("color:%1; font-size:9px; font-family:%2;").arg(ui::colors::TEXT_TERTIARY).arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
svl->addWidget(stats_label_);
- // Selected event detail
svl->addSpacing(8);
+
+ // Selected event detail panel
detail_panel_ = new QWidget(sidebar);
detail_panel_->setVisible(false);
- detail_panel_->setStyleSheet(QString("background:rgba(255,0,0,0.04); border:1px solid rgba(255,0,0,0.2);"
- "border-left:3px solid #FF0000; border-radius:2px;"));
+ detail_panel_->setStyleSheet(
+ "background:rgba(255,0,0,0.04); border:1px solid rgba(255,0,0,0.2);"
+ "border-left:3px solid #FF0000; border-radius:2px;");
+
auto* dvl = new QVBoxLayout(detail_panel_);
dvl->setContentsMargins(10, 10, 10, 10);
- dvl->setSpacing(4);
+ dvl->setSpacing(6);
auto* detail_title = new QLabel("SELECTED EVENT", detail_panel_);
detail_title->setStyleSheet(
- QString("color:#FF0000; font-size:9px; font-weight:700; font-family:%1; letter-spacing:1px;")
+ QString("color:#FF0000; font-size:%1px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(ui::fonts::TINY)
.arg(ui::fonts::DATA_FAMILY));
dvl->addWidget(detail_title);
- auto det_style =
- QString("color:%1; font-size:9px; font-family:%2;").arg(ui::colors::TEXT_PRIMARY).arg(ui::fonts::DATA_FAMILY);
-
- detail_category_ = new QLabel(detail_panel_);
- detail_category_->setStyleSheet(det_style);
- detail_country_ = new QLabel(detail_panel_);
- detail_country_->setStyleSheet(det_style);
- detail_city_ = new QLabel(detail_panel_);
- detail_city_->setStyleSheet(det_style);
- detail_keywords_ = new QLabel(detail_panel_);
- detail_keywords_->setStyleSheet(det_style);
- detail_keywords_->setWordWrap(true);
- detail_date_ = new QLabel(detail_panel_);
- detail_date_->setStyleSheet(det_style);
- detail_source_ = new QLabel(detail_panel_);
- detail_source_->setStyleSheet(det_style);
-
- dvl->addWidget(detail_category_);
- dvl->addWidget(detail_country_);
- dvl->addWidget(detail_city_);
- dvl->addWidget(detail_keywords_);
- dvl->addWidget(detail_date_);
- dvl->addWidget(detail_source_);
+ auto* grid_widget = new QWidget(detail_panel_);
+ auto* grid = new QGridLayout(grid_widget);
+ grid->setContentsMargins(0, 4, 0, 0);
+ grid->setHorizontalSpacing(8);
+ grid->setVerticalSpacing(4);
+ grid->setColumnStretch(1, 1);
+
+ auto field_label_style =
+ QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY);
+ auto value_style =
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
+ .arg(ui::colors::TEXT_PRIMARY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY);
+
+ struct FieldDef { const char* label; QLabel** target; };
+ FieldDef fields[] = {
+ {"CATEGORY", &detail_category_},
+ {"COUNTRY", &detail_country_},
+ {"CITY", &detail_city_},
+ {"KEYWORDS", &detail_keywords_},
+ {"DATE", &detail_date_},
+ {"SOURCE", &detail_source_},
+ };
+
+ for (int r = 0; r < 6; ++r) {
+ auto* fl = new QLabel(fields[r].label, grid_widget);
+ fl->setStyleSheet(field_label_style);
+ fl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ grid->addWidget(fl, r, 0);
+
+ *fields[r].target = new QLabel(grid_widget);
+ (*fields[r].target)->setStyleSheet(value_style);
+ (*fields[r].target)->setWordWrap(true);
+ grid->addWidget(*fields[r].target, r, 1);
+ }
+ dvl->addWidget(grid_widget);
svl->addWidget(detail_panel_);
svl->addStretch();
@@ -166,7 +226,7 @@ void ConflictMonitorPanel::set_events(const QVector<NewsEvent>& events) {
events_table_->setItem(i, 3, new QTableWidgetItem(ev.matched_keywords));
events_table_->setItem(i, 4, new QTableWidgetItem(ev.extracted_date));
- auto* lat_item = new QTableWidgetItem(QString::number(ev.latitude, 'f', 4));
+ auto* lat_item = new QTableWidgetItem(QString::number(ev.latitude, 'f', 4));
lat_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
events_table_->setItem(i, 5, lat_item);
@@ -176,7 +236,6 @@ void ConflictMonitorPanel::set_events(const QVector<NewsEvent>& events) {
}
events_table_->setSortingEnabled(true);
- events_table_->resizeColumnsToContents();
update_stats(events);
update_map(events);
}
@@ -185,88 +244,87 @@ void ConflictMonitorPanel::update_map(const QVector<NewsEvent>& events) {
QVector<fincept::ui::MapPin> pins;
pins.reserve(events.size());
- // Track used coordinates to jitter overlapping events
QHash<QString, int> coord_counts;
auto* rng = QRandomGenerator::global();
int skipped = 0;
for (const auto& ev : events) {
- if (ev.latitude == 0.0 && ev.longitude == 0.0) {
- ++skipped;
- continue;
- }
+ if (ev.latitude == 0.0 && ev.longitude == 0.0) { ++skipped; continue; }
double lat = ev.latitude;
double lng = ev.longitude;
- // Jitter overlapping pins so they don't stack invisibly
QString key = QString("%1,%2").arg(lat, 0, 'f', 4).arg(lng, 0, 'f', 4);
int count = coord_counts.value(key, 0);
coord_counts[key] = count + 1;
if (count > 0) {
- // Spread in a ring around the original point
- double angle = (count * 137.508) * 3.14159265 / 180.0; // golden angle
- double dist = 0.02 + 0.005 * count; // degrees offset, grows with count
+ double angle = (count * 137.508) * 3.14159265 / 180.0;
+ double dist = 0.02 + 0.005 * count;
lat += dist * std::cos(angle);
lng += dist * std::sin(angle);
}
- pins.append({lat, lng, QString("%1 — %2, %3").arg(ev.event_category, ev.city, ev.country),
+ pins.append({lat, lng,
+ QString("%1 — %2, %3").arg(ev.event_category, ev.city, ev.country),
category_color(ev.event_category), 5.0});
}
- LOG_INFO("Geopolitics", QString("Map: %1 events → %2 pins (%3 skipped, %4 unique coords)")
- .arg(events.size())
- .arg(pins.size())
- .arg(skipped)
- .arg(coord_counts.size()));
+ LOG_INFO("Geopolitics",
+ QString("Map: %1 events → %2 pins (%3 skipped, %4 unique coords)")
+ .arg(events.size()).arg(pins.size()).arg(skipped).arg(coord_counts.size()));
map_widget_->set_pins(pins);
map_widget_->fit_to_pins();
}
void ConflictMonitorPanel::update_stats(const QVector<NewsEvent>& events) {
- // Clear old stats
while (stats_layout_->count() > 0) {
auto* item = stats_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
+ if (item->widget()) item->widget()->deleteLater();
delete item;
}
- // Count by category
QHash<QString, int> counts;
for (const auto& ev : events)
counts[ev.event_category]++;
- // Sort by count descending
QVector<QPair<QString, int>> sorted;
for (auto it = counts.begin(); it != counts.end(); ++it)
sorted.append({it.key(), it.value()});
- std::sort(sorted.begin(), sorted.end(), [](const auto& a, const auto& b) { return a.second > b.second; });
+ std::sort(sorted.begin(), sorted.end(),
+ [](const auto& a, const auto& b) { return a.second > b.second; });
for (int i = 0; i < qMin(sorted.size(), 10); ++i) {
const auto& [cat, count] = sorted[i];
+ const QColor cat_col = category_color(cat);
+ const QString col_hex = cat_col.name();
+ const QString col_rgb =
+ QString("%1,%2,%3").arg(cat_col.red()).arg(cat_col.green()).arg(cat_col.blue());
+
auto* row = new QWidget;
+ row->setStyleSheet(
+ QString("border-left:2px solid %1; padding-left:4px;"
+ "background:rgba(%2,0.04); border-radius:1px;")
+ .arg(col_hex).arg(col_rgb));
auto* rl = new QHBoxLayout(row);
- rl->setContentsMargins(0, 0, 0, 0);
+ rl->setContentsMargins(6, 2, 4, 2);
rl->setSpacing(6);
- auto* dot = new QWidget(row);
- dot->setFixedSize(6, 6);
- dot->setStyleSheet(QString("background:%1; border-radius:3px;").arg(category_color(cat).name()));
- rl->addWidget(dot);
-
auto* name = new QLabel(cat, row);
- name->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2;")
- .arg(ui::colors::TEXT_SECONDARY)
- .arg(ui::fonts::DATA_FAMILY));
+ name->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-family:%3; border:none; background:transparent;")
+ .arg(ui::colors::TEXT_SECONDARY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
rl->addWidget(name, 1);
auto* cnt = new QLabel(QString::number(count), row);
- cnt->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2;")
- .arg(ui::colors::TEXT_PRIMARY)
- .arg(ui::fonts::DATA_FAMILY));
+ cnt->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;"
+ "border:none; background:transparent;")
+ .arg(ui::colors::TEXT_PRIMARY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
rl->addWidget(cnt);
stats_layout_->addWidget(row);
diff --git a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp
index e2e45e873..c3bcb8b9e 100644
--- a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp
+++ b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp
@@ -8,7 +8,9 @@
#include "screens/geopolitics/TradeAnalysisPanel.h"
#include "services/geopolitics/GeopoliticsService.h"
#include "ui/theme/Theme.h"
+#include "ui/theme/ThemeManager.h"
+#include <QDateTime>
#include <QHBoxLayout>
#include <QScrollArea>
@@ -22,15 +24,22 @@ GeopoliticsScreen::GeopoliticsScreen(QWidget* parent) : QWidget(parent) {
connect_service();
refresh_timer_ = new QTimer(this);
- refresh_timer_->setInterval(5 * 60 * 1000); // 5 min auto-refresh
+ refresh_timer_->setInterval(5 * 60 * 1000);
connect(refresh_timer_, &QTimer::timeout, this, &GeopoliticsScreen::on_apply_filters);
+ clock_timer_ = new QTimer(this);
+ clock_timer_->setInterval(1000);
+
+ connect(&fincept::ui::ThemeManager::instance(), &fincept::ui::ThemeManager::theme_changed,
+ this, [this](const fincept::ui::ThemeTokens&) { refresh_theme(); });
+
LOG_INFO("Geopolitics", "Screen constructed");
}
void GeopoliticsScreen::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
refresh_timer_->start();
+ clock_timer_->start();
if (first_show_) {
first_show_ = false;
country_edit_->setText("Ukraine");
@@ -44,11 +53,18 @@ void GeopoliticsScreen::showEvent(QShowEvent* e) {
void GeopoliticsScreen::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
refresh_timer_->stop();
+ clock_timer_->stop();
+}
+
+void GeopoliticsScreen::refresh_theme() {
+ setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));
+ // Re-apply tab highlight so colors remain correct after theme change
+ on_tab_changed(active_tab_);
}
void GeopoliticsScreen::connect_service() {
auto& svc = GeopoliticsService::instance();
- connect(&svc, &GeopoliticsService::events_loaded, this, &GeopoliticsScreen::on_events_loaded);
+ connect(&svc, &GeopoliticsService::events_loaded, this, &GeopoliticsScreen::on_events_loaded);
connect(&svc, &GeopoliticsService::error_occurred, this, &GeopoliticsScreen::on_error);
connect(&svc, &GeopoliticsService::categories_loaded, this, [this](QVector<UniqueCategory> cats) {
category_combo_->clear();
@@ -72,12 +88,11 @@ void GeopoliticsScreen::build_ui() {
body->addWidget(build_filter_panel());
- // Content stack
content_stack_ = new QStackedWidget(this);
- monitor_panel_ = new ConflictMonitorPanel(this);
- hdx_panel_ = new HDXDataPanel(this);
+ monitor_panel_ = new ConflictMonitorPanel(this);
+ hdx_panel_ = new HDXDataPanel(this);
relationship_panel_ = new RelationshipPanel(this);
- trade_panel_ = new TradeAnalysisPanel(this);
+ trade_panel_ = new TradeAnalysisPanel(this);
content_stack_->addWidget(monitor_panel_);
content_stack_->addWidget(hdx_panel_);
@@ -92,59 +107,43 @@ void GeopoliticsScreen::build_ui() {
root->addWidget(build_status_bar());
setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));
-
- // Highlight the first tab now that content_stack_ exists
on_tab_changed(0);
}
// ── Top Bar ──────────────────────────────────────────────────────────────────
QWidget* GeopoliticsScreen::build_top_bar() {
auto* bar = new QWidget(this);
- bar->setFixedHeight(44);
+ bar->setFixedHeight(48);
bar->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
+ QString("background:%1; border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
auto* hl = new QHBoxLayout(bar);
- hl->setContentsMargins(12, 0, 12, 0);
+ hl->setContentsMargins(16, 0, 16, 0);
hl->setSpacing(12);
- // Branding
- auto* brand = new QLabel("GEO> GEOPOLITICAL CONFLICT MONITOR", bar);
- brand->setStyleSheet(QString("color:#FF0000; font-size:%1px; font-weight:700; font-family:%2;"
- "padding:4px 12px; background:rgba(255,0,0,0.08);"
- "border:1px solid rgba(255,0,0,0.25); border-radius:2px;")
- .arg(ui::fonts::TINY)
- .arg(ui::fonts::DATA_FAMILY));
- hl->addWidget(brand);
-
- auto* div = new QWidget(bar);
- div->setFixedSize(1, 20);
- div->setStyleSheet(QString("background:%1;").arg(ui::colors::BORDER_DIM));
- hl->addWidget(div);
-
- // Tab selector buttons
- struct TabDef {
- QString label;
- QString color;
- };
- QVector<TabDef> tabs = {
- {"MONITOR", "#FF0000"},
- {"HDX DATA", "#00E5FF"},
+
+ struct TabDef { QString label; QString color; };
+ const QVector<TabDef> tabs = {
+ {"MONITOR", "#FF0000"},
+ {"HDX DATA", "#00E5FF"},
{"RELATIONS", "#9D4EDD"},
- {"TRADE", "#FFC400"},
+ {"TRADE", "#FFC400"},
};
for (int i = 0; i < tabs.size(); ++i) {
auto* btn = new QPushButton(tabs[i].label, bar);
btn->setCursor(Qt::PointingHandCursor);
- btn->setStyleSheet(QString("QPushButton { color:%1; font-size:9px; font-family:%2;"
- "padding:4px 10px; border:1px solid transparent; border-radius:2px;"
- "background:transparent; font-weight:400; }"
- "QPushButton:hover { background:rgba(%3,0.1); color:%4; }")
- .arg(ui::colors::TEXT_TERTIARY)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(tabs[i].color.mid(1))
- .arg(tabs[i].color)); // rough — color used directly
+ btn->setStyleSheet(
+ QString("QPushButton { color:%1; font-size:%2px; font-family:%3;"
+ "padding:4px 14px; border:none; border-radius:0;"
+ "background:transparent; font-weight:400; }"
+ "QPushButton:hover { color:%4; background:rgba(%5,0.06); }")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(tabs[i].color)
+ .arg(tabs[i].color.mid(1)));
connect(btn, &QPushButton::clicked, this, [this, i]() { on_tab_changed(i); });
hl->addWidget(btn);
tab_buttons_.append(btn);
@@ -152,17 +151,36 @@ QWidget* GeopoliticsScreen::build_top_bar() {
hl->addStretch(1);
- // Event count badge
+ auto* clock_label = new QLabel("UTC --:--", bar);
+ clock_label->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-family:%3; min-width:68px;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
+ hl->addWidget(clock_label);
+
+ connect(clock_timer_, &QTimer::timeout, this, [clock_label]() {
+ clock_label->setText(
+ QString("UTC %1").arg(QDateTime::currentDateTimeUtc().toString("HH:mm")));
+ });
+ clock_label->setText(
+ QString("UTC %1").arg(QDateTime::currentDateTimeUtc().toString("HH:mm")));
+
+ auto* div2 = new QWidget(bar);
+ div2->setFixedSize(1, 20);
+ div2->setStyleSheet(QString("background:%1;").arg(ui::colors::BORDER_DIM));
+ hl->addWidget(div2);
+
event_count_label_ = new QLabel("0 EVENTS", bar);
- event_count_label_->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2; padding:3px 8px;"
- "background:rgba(220,38,38,0.08); border:1px solid rgba(220,38,38,0.25);"
- "border-radius:2px; font-weight:700;")
- .arg(ui::colors::NEGATIVE)
- .arg(ui::fonts::DATA_FAMILY));
+ event_count_label_->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-family:%3; padding:3px 8px;"
+ "background:rgba(220,38,38,0.08); border:1px solid rgba(220,38,38,0.25);"
+ "border-radius:2px; font-weight:700;")
+ .arg(ui::colors::NEGATIVE)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
hl->addWidget(event_count_label_);
- // NOTE: don't call on_tab_changed(0) here — content_stack_ isn't created yet.
- // Initial tab highlight is applied at the end of build_ui().
return bar;
}
@@ -171,34 +189,36 @@ QWidget* GeopoliticsScreen::build_filter_panel() {
auto* panel = new QWidget(this);
panel->setFixedWidth(220);
panel->setStyleSheet(
- QString("background:%1; border-right:1px solid %2;").arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));
+ QString("background:%1; border-right:1px solid %2;")
+ .arg(ui::colors::BG_SURFACE, ui::colors::BORDER_DIM));
auto* vl = new QVBoxLayout(panel);
vl->setContentsMargins(12, 12, 12, 12);
- vl->setSpacing(10);
+ vl->setSpacing(8);
- // Title
auto* title = new QLabel("FILTERS", panel);
- title->setStyleSheet(QString("color:#FF0000; font-size:9px; font-weight:700; font-family:%1;"
- "letter-spacing:1px; padding-bottom:4px;"
- "border-bottom:1px solid %2;")
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::colors::BORDER_DIM));
+ title->setStyleSheet(
+ QString("color:#FF0000; font-size:%1px; font-weight:700; font-family:%2;"
+ "letter-spacing:1px; padding-bottom:4px; border-bottom:1px solid %3;")
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::BORDER_DIM));
vl->addWidget(title);
- auto input_style = QString("QLineEdit, QComboBox { background:%1; color:%2; border:1px solid %3;"
- "font-family:%4; font-size:%5px; padding:6px 8px; border-radius:2px; }"
- "QLineEdit:focus, QComboBox:focus { border-color:#FF0000; }")
- .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL);
+ auto input_style =
+ QString("QLineEdit, QComboBox { background:%1; color:%2; border:1px solid %3;"
+ "font-family:%4; font-size:%5px; padding:5px 8px; border-radius:2px; }"
+ "QLineEdit:focus, QComboBox:focus { border-color:#FF0000; }")
+ .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL);
- auto label_style = QString("color:%1; font-size:8px; font-weight:700;"
- "font-family:%2; letter-spacing:1px;")
- .arg(ui::colors::TEXT_TERTIARY)
- .arg(ui::fonts::DATA_FAMILY);
+ auto label_style =
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3; letter-spacing:1px;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY);
- // Country filter
auto* country_lbl = new QLabel("COUNTRY", panel);
country_lbl->setStyleSheet(label_style);
vl->addWidget(country_lbl);
@@ -208,7 +228,6 @@ QWidget* GeopoliticsScreen::build_filter_panel() {
connect(country_edit_, &QLineEdit::returnPressed, this, &GeopoliticsScreen::on_apply_filters);
vl->addWidget(country_edit_);
- // City filter
auto* city_lbl = new QLabel("CITY", panel);
city_lbl->setStyleSheet(label_style);
vl->addWidget(city_lbl);
@@ -218,8 +237,7 @@ QWidget* GeopoliticsScreen::build_filter_panel() {
connect(city_edit_, &QLineEdit::returnPressed, this, &GeopoliticsScreen::on_apply_filters);
vl->addWidget(city_edit_);
- // Category filter
- auto* cat_lbl = new QLabel("EVENT CATEGORY", panel);
+ auto* cat_lbl = new QLabel("CATEGORY", panel);
cat_lbl->setStyleSheet(label_style);
vl->addWidget(cat_lbl);
category_combo_ = new QComboBox(panel);
@@ -229,12 +247,13 @@ QWidget* GeopoliticsScreen::build_filter_panel() {
category_combo_->addItem(cat, cat);
vl->addWidget(category_combo_);
- // Buttons
- auto* apply_btn = new QPushButton("APPLY", panel);
+ vl->addSpacing(4);
+
+ auto* apply_btn = new QPushButton("APPLY FILTERS", panel);
apply_btn->setCursor(Qt::PointingHandCursor);
apply_btn->setStyleSheet(
QString("QPushButton { background:#FF0000; color:%1; font-family:%2; font-size:%3px;"
- "font-weight:700; border:none; padding:8px; border-radius:2px; letter-spacing:1px; }"
+ "font-weight:700; border:none; padding:6px 12px; border-radius:2px; }"
"QPushButton:hover { background:#CC0000; }")
.arg(ui::colors::BG_BASE)
.arg(ui::fonts::DATA_FAMILY)
@@ -244,36 +263,49 @@ QWidget* GeopoliticsScreen::build_filter_panel() {
auto* clear_btn = new QPushButton("CLEAR", panel);
clear_btn->setCursor(Qt::PointingHandCursor);
- clear_btn->setStyleSheet(QString("QPushButton { background:transparent; color:%1; font-family:%2; font-size:%3px;"
- "border:1px solid %4; padding:6px; border-radius:2px; }"
- "QPushButton:hover { background:%5; }")
- .arg(ui::colors::TEXT_SECONDARY)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL)
- .arg(ui::colors::BORDER_DIM)
- .arg(ui::colors::BG_HOVER));
+ clear_btn->setStyleSheet(
+ QString("QPushButton { background:transparent; color:%1; font-family:%2; font-size:%3px;"
+ "border:1px solid %4; padding:5px 12px; border-radius:2px; }"
+ "QPushButton:hover { background:%5; }")
+ .arg(ui::colors::TEXT_SECONDARY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::colors::BORDER_DIM)
+ .arg(ui::colors::BG_HOVER));
connect(clear_btn, &QPushButton::clicked, this, &GeopoliticsScreen::on_clear_filters);
vl->addWidget(clear_btn);
- // Legend
- vl->addSpacing(12);
+ auto* sep = new QWidget(panel);
+ sep->setFixedHeight(1);
+ sep->setStyleSheet(QString("background:%1;").arg(ui::colors::BORDER_DIM));
+ vl->addSpacing(6);
+ vl->addWidget(sep);
+ vl->addSpacing(6);
+
auto* legend_title = new QLabel("LEGEND", panel);
- legend_title->setStyleSheet(label_style);
+ legend_title->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3; letter-spacing:1px;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
vl->addWidget(legend_title);
for (const auto& cat : event_categories()) {
auto* row = new QWidget(panel);
- auto* rl = new QHBoxLayout(row);
+ auto* rl = new QHBoxLayout(row);
rl->setContentsMargins(0, 1, 0, 1);
rl->setSpacing(6);
auto* dot = new QWidget(row);
dot->setFixedSize(8, 8);
- dot->setStyleSheet(QString("background:%1; border-radius:4px;").arg(category_color(cat).name()));
+ dot->setStyleSheet(
+ QString("background:%1; border-radius:4px;").arg(category_color(cat).name()));
rl->addWidget(dot);
auto* lbl = new QLabel(cat, row);
- lbl->setStyleSheet(QString("color:%1; font-size:8px; font-family:%2;")
- .arg(ui::colors::TEXT_SECONDARY)
- .arg(ui::fonts::DATA_FAMILY));
+ lbl->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_SECONDARY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
rl->addWidget(lbl, 1);
vl->addWidget(row);
}
@@ -285,42 +317,47 @@ QWidget* GeopoliticsScreen::build_filter_panel() {
// ── Status Bar ───────────────────────────────────────────────────────────────
QWidget* GeopoliticsScreen::build_status_bar() {
auto* bar = new QWidget(this);
- bar->setFixedHeight(24);
+ bar->setFixedHeight(26);
bar->setStyleSheet(
- QString("background:%1; border-top:1px solid %2;").arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
+ QString("background:%1; border-top:1px solid %2;")
+ .arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
auto* hl = new QHBoxLayout(bar);
hl->setContentsMargins(12, 0, 12, 0);
hl->setSpacing(16);
- auto s =
- QString("color:%1; font-size:8px; font-family:%2;").arg(ui::colors::TEXT_TERTIARY).arg(ui::fonts::DATA_FAMILY);
- auto sv = QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
+ auto s = QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY);
+ auto sv = QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
.arg(ui::colors::TEXT_PRIMARY)
+ .arg(ui::fonts::TINY)
.arg(ui::fonts::DATA_FAMILY);
- auto* lbl1 = new QLabel("SOURCE:", bar);
- lbl1->setStyleSheet(s);
- auto* val1 = new QLabel("NEWS-EVENTS API + HDX", bar);
- val1->setStyleSheet(sv);
+ auto* lbl1 = new QLabel("SOURCE:", bar); lbl1->setStyleSheet(s);
+ auto* val1 = new QLabel("NEWS-EVENTS API + HDX", bar); val1->setStyleSheet(sv);
hl->addWidget(lbl1);
hl->addWidget(val1);
- auto* lbl2 = new QLabel("ENGINE:", bar);
- lbl2->setStyleSheet(s);
+ auto* lbl2 = new QLabel("ENGINE:", bar); lbl2->setStyleSheet(s);
auto* val2 = new QLabel("PYTHON + C++", bar);
- val2->setStyleSheet(QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
- .arg(ui::colors::POSITIVE)
- .arg(ui::fonts::DATA_FAMILY));
+ val2->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
+ .arg(ui::colors::POSITIVE)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
hl->addWidget(lbl2);
hl->addWidget(val2);
hl->addStretch();
status_label_ = new QLabel("READY", bar);
- status_label_->setStyleSheet(QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
- .arg(ui::colors::POSITIVE)
- .arg(ui::fonts::DATA_FAMILY));
+ status_label_->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
+ .arg(ui::colors::POSITIVE)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
hl->addWidget(status_label_);
return bar;
@@ -328,13 +365,15 @@ QWidget* GeopoliticsScreen::build_status_bar() {
// ── Actions ──────────────────────────────────────────────────────────────────
void GeopoliticsScreen::on_apply_filters() {
- auto country = country_edit_->text().trimmed();
- auto city = city_edit_->text().trimmed();
+ auto country = country_edit_->text().trimmed();
+ auto city = city_edit_->text().trimmed();
auto category = category_combo_->currentData().toString();
status_label_->setText("LOADING...");
- status_label_->setStyleSheet(QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
- .arg(ui::colors::WARNING)
- .arg(ui::fonts::DATA_FAMILY));
+ status_label_->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
+ .arg(ui::colors::WARNING)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
GeopoliticsService::instance().fetch_events(country, city, category);
}
@@ -352,44 +391,62 @@ void GeopoliticsScreen::on_tab_changed(int index) {
if (content_stack_)
content_stack_->setCurrentIndex(index);
- QStringList colors = {"#FF0000", "#00E5FF", "#9D4EDD", "#FFC400"};
+ const QStringList colors = {"#FF0000", "#00E5FF", "#9D4EDD", "#FFC400"};
for (int i = 0; i < tab_buttons_.size(); ++i) {
- bool active = (i == index);
- tab_buttons_[i]->setStyleSheet(QString("QPushButton { color:%1; font-size:9px; font-family:%2;"
- "padding:4px 10px; border:1px solid %3; border-radius:2px;"
- "background:%4; font-weight:%5; }"
- "QPushButton:hover { background:rgba(%6,0.1); }")
- .arg(active ? colors[i] : ui::colors::TEXT_TERTIARY)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(active ? QString("rgba(%1,0.3)").arg(colors[i].mid(1)) : "transparent")
- .arg(active ? QString("rgba(%1,0.12)").arg(colors[i].mid(1)) : "transparent")
- .arg(active ? "700" : "400")
- .arg(colors[i].mid(1)));
+ const bool active = (i == index);
+ if (active) {
+ tab_buttons_[i]->setStyleSheet(
+ QString("QPushButton { color:%1; font-size:%2px; font-family:%3;"
+ "padding:4px 14px;"
+ "border-bottom:2px solid %1; border-top:none; border-left:none; border-right:none;"
+ "border-radius:0; background:rgba(%4,0.06); font-weight:700; }"
+ "QPushButton:hover { background:rgba(%4,0.10); }")
+ .arg(colors[i])
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(colors[i].mid(1)));
+ } else {
+ tab_buttons_[i]->setStyleSheet(
+ QString("QPushButton { color:%1; font-size:%2px; font-family:%3;"
+ "padding:4px 14px; border:none; border-radius:0;"
+ "background:transparent; font-weight:400; }"
+ "QPushButton:hover { color:%4; background:rgba(%5,0.06); }")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(colors[i])
+ .arg(colors[i].mid(1)));
+ }
}
}
void GeopoliticsScreen::on_events_loaded(QVector<services::geo::NewsEvent> events, int total) {
event_count_label_->setText(QString("%1 EVENTS").arg(total));
const QString color = total > 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE();
- event_count_label_->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2; padding:3px 8px;"
- "background:rgba(%3,0.08); border:1px solid rgba(%3,0.25);"
- "border-radius:2px; font-weight:700;")
- .arg(color)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(color.mid(1)));
+ event_count_label_->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-family:%3; padding:3px 8px;"
+ "background:rgba(%4,0.08); border:1px solid rgba(%4,0.25);"
+ "border-radius:2px; font-weight:700;")
+ .arg(color)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(color.mid(1)));
status_label_->setText("READY");
- status_label_->setStyleSheet(QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
- .arg(ui::colors::POSITIVE)
- .arg(ui::fonts::DATA_FAMILY));
- // Forward to monitor panel
+ status_label_->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
+ .arg(ui::colors::POSITIVE)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
monitor_panel_->set_events(events);
}
void GeopoliticsScreen::on_error(const QString& context, const QString& message) {
status_label_->setText("ERROR");
- status_label_->setStyleSheet(QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
- .arg(ui::colors::NEGATIVE)
- .arg(ui::fonts::DATA_FAMILY));
+ status_label_->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
+ .arg(ui::colors::NEGATIVE)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
LOG_ERROR("Geopolitics", QString("[%1] %2").arg(context, message));
}
diff --git a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.h b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.h
index 21a12bc24..9c1605547 100644
--- a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.h
+++ b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.h
@@ -47,6 +47,7 @@ class GeopoliticsScreen : public QWidget {
QWidget* build_filter_panel();
QWidget* build_status_bar();
void connect_service();
+ void refresh_theme();
// Filter inputs
QLineEdit* country_edit_ = nullptr;
@@ -70,6 +71,8 @@ class GeopoliticsScreen : public QWidget {
// Auto-refresh
QTimer* refresh_timer_ = nullptr;
+ // Clock (1s tick, started/stopped in showEvent/hideEvent)
+ QTimer* clock_timer_ = nullptr;
bool first_show_ = true;
};
diff --git a/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp b/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp
index 5f810a668..82c18487d 100644
--- a/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp
@@ -19,7 +19,8 @@ HDXDataPanel::HDXDataPanel(QWidget* parent) : QWidget(parent) {
void HDXDataPanel::connect_service() {
auto& svc = GeopoliticsService::instance();
- connect(&svc, &GeopoliticsService::hdx_results_loaded, this, &HDXDataPanel::on_hdx_results);
+ connect(&svc, &GeopoliticsService::hdx_results_loaded,
+ this, &HDXDataPanel::on_hdx_results);
}
void HDXDataPanel::build_ui() {
@@ -29,33 +30,38 @@ void HDXDataPanel::build_ui() {
// Header with view tabs
auto* header = new QWidget(this);
- header->setFixedHeight(40);
+ header->setFixedHeight(48);
header->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
+ QString("background:%1; border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
auto* hhl = new QHBoxLayout(header);
- hhl->setContentsMargins(12, 0, 12, 0);
+ hhl->setContentsMargins(16, 0, 16, 0);
hhl->setSpacing(8);
auto* title = new QLabel("HDX HUMANITARIAN DATA", header);
- title->setStyleSheet(QString("color:#00E5FF; font-size:%1px; font-weight:700; font-family:%2; letter-spacing:1px;")
- .arg(ui::fonts::TINY)
- .arg(ui::fonts::DATA_FAMILY));
+ title->setStyleSheet(
+ QString("color:#00E5FF; font-size:%1px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
hhl->addWidget(title);
auto* div = new QWidget(header);
- div->setFixedSize(1, 16);
+ div->setFixedSize(1, 20);
div->setStyleSheet(QString("background:%1;").arg(ui::colors::BORDER_DIM));
hhl->addWidget(div);
- QStringList views = {"Conflicts", "Humanitarian", "Explorer", "Datasets"};
+ const QStringList views = {"Conflicts", "Humanitarian", "Explorer", "Datasets"};
for (int i = 0; i < views.size(); ++i) {
auto* btn = new QPushButton(views[i].toUpper(), header);
btn->setCursor(Qt::PointingHandCursor);
- btn->setStyleSheet(QString("QPushButton { color:%1; font-size:9px; font-family:%2;"
- "padding:4px 8px; border:none; background:transparent; }"
- "QPushButton:hover { color:#00E5FF; }")
- .arg(ui::colors::TEXT_TERTIARY)
- .arg(ui::fonts::DATA_FAMILY));
+ btn->setStyleSheet(
+ QString("QPushButton { color:%1; font-size:%2px; font-family:%3;"
+ "padding:4px 12px; border:none; border-radius:0; background:transparent;"
+ "font-weight:400; }"
+ "QPushButton:hover { color:#00E5FF; background:rgba(0,229,255,0.04); }")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
connect(btn, &QPushButton::clicked, this, [this, i]() { on_view_changed(i); });
hhl->addWidget(btn);
view_buttons_.append(btn);
@@ -63,75 +69,109 @@ void HDXDataPanel::build_ui() {
hhl->addStretch();
- // Search
search_edit_ = new QLineEdit(header);
search_edit_->setPlaceholderText("Search HDX datasets...");
- search_edit_->setFixedWidth(250);
- search_edit_->setStyleSheet(QString("QLineEdit { background:%1; color:%2; border:1px solid %3;"
- "font-family:%4; font-size:%5px; padding:4px 8px; border-radius:2px; }"
- "QLineEdit:focus { border-color:#00E5FF; }")
- .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
+ search_edit_->setFixedWidth(240);
+ search_edit_->setStyleSheet(
+ QString("QLineEdit { background:%1; color:%2; border:1px solid %3;"
+ "font-family:%4; font-size:%5px; padding:4px 8px; border-radius:2px; }"
+ "QLineEdit:focus { border-color:#00E5FF; }")
+ .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL));
connect(search_edit_, &QLineEdit::returnPressed, this, [this]() {
auto q = search_edit_->text().trimmed();
- if (!q.isEmpty())
+ if (!q.isEmpty()) {
+ show_loading(true);
GeopoliticsService::instance().search_hdx_advanced(q);
+ }
});
hhl->addWidget(search_edit_);
dataset_count_ = new QLabel("0 datasets", header);
dataset_count_->setStyleSheet(
- QString("color:%1; font-size:9px; font-family:%2;").arg(ui::colors::TEXT_TERTIARY).arg(ui::fonts::DATA_FAMILY));
+ QString("color:#00E5FF; font-size:%1px; font-family:%2; padding:2px 8px;"
+ "background:rgba(0,229,255,0.08); border:1px solid rgba(0,229,255,0.25);"
+ "border-radius:2px; font-weight:700;")
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
hhl->addWidget(dataset_count_);
root->addWidget(header);
- // Content: main table (shared across views)
+ // Datasets table
datasets_table_ = new QTableWidget(this);
datasets_table_->setColumnCount(5);
- datasets_table_->setHorizontalHeaderLabels({"Title", "Organization", "Date", "Resources", "Tags"});
+ datasets_table_->setHorizontalHeaderLabels(
+ {"Title", "Organization", "Date", "Resources", "Tags"});
datasets_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
datasets_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
datasets_table_->setAlternatingRowColors(true);
- datasets_table_->horizontalHeader()->setStretchLastSection(true);
datasets_table_->verticalHeader()->setVisible(false);
datasets_table_->setSortingEnabled(true);
- datasets_table_->setStyleSheet(QString("QTableWidget { background:%1; color:%2; gridline-color:%3;"
- "font-family:%4; font-size:%5px; border:none; }"
- "QTableWidget::item { padding:4px 8px; }"
- "QTableWidget::item:selected { background:rgba(0,229,255,0.15); }"
- "QHeaderView::section { background:%6; color:%7; font-weight:700;"
- "padding:6px 8px; border:1px solid %3; font-family:%4; font-size:%5px; }"
- "QTableWidget::item:alternate { background:%8; }")
- .arg(ui::colors::BG_SURFACE, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_DIM)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL)
- .arg(ui::colors::BG_RAISED)
- .arg(ui::colors::TEXT_SECONDARY)
- .arg(ui::colors::ROW_ALT));
+
+ datasets_table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
+ datasets_table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
+ datasets_table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
+ datasets_table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
+ datasets_table_->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
+
+ datasets_table_->verticalHeader()->setDefaultSectionSize(26);
+
+ datasets_table_->setStyleSheet(
+ QString("QTableWidget { background:%1; color:%2; gridline-color:%3;"
+ "font-family:%4; font-size:%5px; border:none; }"
+ "QTableWidget::item { padding:3px 8px; }"
+ "QTableWidget::item:selected { background:rgba(0,229,255,0.15); }"
+ "QHeaderView::section { background:%6; color:%7; font-weight:700;"
+ "padding:5px 8px; border:1px solid %3; font-family:%4; font-size:%5px; }"
+ "QTableWidget::item:alternate { background:%8; }")
+ .arg(ui::colors::BG_SURFACE, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_DIM)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::colors::BG_RAISED)
+ .arg(ui::colors::TEXT_SECONDARY)
+ .arg(ui::colors::ROW_ALT));
+
+ // Loading overlay
+ loading_label_ = new QLabel("Loading HDX data...", this);
+ loading_label_->setAlignment(Qt::AlignCenter);
+ loading_label_->setStyleSheet(
+ QString("color:#00E5FF; font-size:%1px; font-family:%2; background:%3;")
+ .arg(ui::fonts::DATA)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::BG_SURFACE));
+ loading_label_->hide();
+ root->addWidget(loading_label_, 1);
root->addWidget(datasets_table_, 1);
- // Explorer filter bar (shown at bottom when Explorer view active)
- auto* explorer_bar = new QWidget(this);
- explorer_bar->setFixedHeight(40);
- explorer_bar->setStyleSheet(
- QString("background:%1; border-top:1px solid %2;").arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
- auto* ehl = new QHBoxLayout(explorer_bar);
- ehl->setContentsMargins(12, 0, 12, 0);
+ // Explorer filter bar
+ explorer_bar_ = new QWidget(this);
+ explorer_bar_->setFixedHeight(44);
+ explorer_bar_->setStyleSheet(
+ QString("background:%1; border-top:1px solid %2;")
+ .arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
+ auto* ehl = new QHBoxLayout(explorer_bar_);
+ ehl->setContentsMargins(16, 0, 16, 0);
ehl->setSpacing(8);
- auto combo_style = QString("QComboBox { background:%1; color:%2; border:1px solid %3;"
- "font-family:%4; font-size:%5px; padding:4px 6px; }")
- .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL);
+ auto combo_style =
+ QString("QComboBox { background:%1; color:%2; border:1px solid %3;"
+ "font-family:%4; font-size:%5px; padding:4px 6px; }")
+ .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL);
+
+ auto bar_label_style =
+ QString("color:%1; font-size:%2px; font-family:%3; font-weight:700; letter-spacing:1px;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY);
- auto* country_lbl = new QLabel("Country:", explorer_bar);
- country_lbl->setStyleSheet(
- QString("color:%1; font-size:9px; font-family:%2;").arg(ui::colors::TEXT_TERTIARY).arg(ui::fonts::DATA_FAMILY));
+ auto* country_lbl = new QLabel("COUNTRY:", explorer_bar_);
+ country_lbl->setStyleSheet(bar_label_style);
ehl->addWidget(country_lbl);
- country_combo_ = new QComboBox(explorer_bar);
+ country_combo_ = new QComboBox(explorer_bar_);
country_combo_->setStyleSheet(combo_style);
country_combo_->setEditable(true);
country_combo_->setPlaceholderText("Select country");
@@ -139,75 +179,113 @@ void HDXDataPanel::build_ui() {
country_combo_->addItem(r);
ehl->addWidget(country_combo_);
- auto* topic_lbl = new QLabel("Topic:", explorer_bar);
- topic_lbl->setStyleSheet(country_lbl->styleSheet());
+ auto* topic_lbl = new QLabel("TOPIC:", explorer_bar_);
+ topic_lbl->setStyleSheet(bar_label_style);
ehl->addWidget(topic_lbl);
- topic_combo_ = new QComboBox(explorer_bar);
+ topic_combo_ = new QComboBox(explorer_bar_);
topic_combo_->setStyleSheet(combo_style);
topic_combo_->addItems(
- {"conflict", "humanitarian", "displacement", "food security", "health", "education", "refugees"});
+ {"conflict", "humanitarian", "displacement", "food security",
+ "health", "education", "refugees"});
ehl->addWidget(topic_combo_);
- auto* explore_btn = new QPushButton("SEARCH", explorer_bar);
+ auto* explore_btn = new QPushButton("SEARCH", explorer_bar_);
explore_btn->setCursor(Qt::PointingHandCursor);
- explore_btn->setStyleSheet(QString("QPushButton { background:#00E5FF; color:%1; font-family:%2;"
- "font-size:%3px; font-weight:700; border:none; padding:4px 16px;"
- "border-radius:2px; }"
- "QPushButton:hover { background:#00B8D4; }")
- .arg(ui::colors::BG_BASE)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
+ explore_btn->setStyleSheet(
+ QString("QPushButton { background:#00E5FF; color:%1; font-family:%2;"
+ "font-size:%3px; font-weight:700; border:none; padding:6px 16px;"
+ "border-radius:2px; }"
+ "QPushButton:hover { background:#00B8D4; }")
+ .arg(ui::colors::BG_BASE)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL));
connect(explore_btn, &QPushButton::clicked, this, [this]() {
auto country = country_combo_->currentText().trimmed();
- if (!country.isEmpty())
+ show_loading(true);
+ if (!country.isEmpty()) {
GeopoliticsService::instance().search_hdx_by_country(country);
- else {
+ } else {
auto topic = topic_combo_->currentText().trimmed();
if (!topic.isEmpty())
GeopoliticsService::instance().search_hdx_by_topic(topic);
+ else
+ show_loading(false);
}
});
ehl->addWidget(explore_btn);
ehl->addStretch();
- root->addWidget(explorer_bar);
+ root->addWidget(explorer_bar_);
on_view_changed(0);
}
void HDXDataPanel::on_view_changed(int index) {
active_view_ = index;
for (int i = 0; i < view_buttons_.size(); ++i) {
- bool active = (i == index);
- view_buttons_[i]->setStyleSheet(QString("QPushButton { color:%1; font-size:9px; font-family:%2;"
- "padding:4px 8px; border:none; background:%3; font-weight:%4; }"
- "QPushButton:hover { color:#00E5FF; }")
- .arg(active ? "#00E5FF" : ui::colors::TEXT_TERTIARY())
- .arg(ui::fonts::DATA_FAMILY)
- .arg(active ? "rgba(0,229,255,0.1)" : "transparent")
- .arg(active ? "700" : "400"));
+ const bool active = (i == index);
+ if (active) {
+ view_buttons_[i]->setStyleSheet(
+ QString("QPushButton { color:#00E5FF; font-size:%1px; font-family:%2;"
+ "padding:4px 12px;"
+ "border-bottom:2px solid #00E5FF; border-top:none; border-left:none; border-right:none;"
+ "border-radius:0; background:rgba(0,229,255,0.06); font-weight:700; }"
+ "QPushButton:hover { background:rgba(0,229,255,0.10); }")
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
+ } else {
+ view_buttons_[i]->setStyleSheet(
+ QString("QPushButton { color:%1; font-size:%2px; font-family:%3;"
+ "padding:4px 12px; border:none; border-radius:0; background:transparent;"
+ "font-weight:400; }"
+ "QPushButton:hover { color:#00E5FF; background:rgba(0,229,255,0.04); }")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
+ }
}
- // Load data for the selected view
+ if (explorer_bar_) explorer_bar_->setVisible(index == 2);
+
auto& svc = GeopoliticsService::instance();
switch (index) {
case 0:
- svc.search_hdx_conflicts();
+ if (!cache_conflicts_.isEmpty()) populate_table(cache_conflicts_);
+ else { show_loading(true); svc.search_hdx_conflicts(); }
break;
case 1:
- svc.search_hdx_humanitarian();
- break;
- case 2: /* Explorer — user-driven */
+ if (!cache_humanitarian_.isEmpty()) populate_table(cache_humanitarian_);
+ else { show_loading(true); svc.search_hdx_humanitarian(); }
break;
- case 3: /* Datasets — search-driven */
+ case 2: break;
+ case 3:
+ if (!cache_datasets_.isEmpty()) populate_table(cache_datasets_);
+ else { show_loading(true); svc.search_hdx_advanced("humanitarian crisis conflict displacement"); }
break;
}
}
+void HDXDataPanel::show_loading(bool on) {
+ loading_label_->setVisible(on);
+ datasets_table_->setVisible(!on);
+}
+
void HDXDataPanel::on_hdx_results(const QString& context, QVector<HDXDataset> datasets) {
- populate_table(datasets);
+ if (context == "conflicts") cache_conflicts_ = datasets;
+ else if (context == "humanitarian") cache_humanitarian_ = datasets;
+ else if (context == "search" || context == "topic" || context == "country")
+ cache_datasets_ = datasets;
+
+ bool relevant =
+ (active_view_ == 0 && context == "conflicts") ||
+ (active_view_ == 1 && context == "humanitarian") ||
+ (active_view_ == 2 && (context == "country" || context == "topic")) ||
+ (active_view_ == 3 && context == "search");
+ if (relevant)
+ populate_table(datasets);
}
void HDXDataPanel::populate_table(const QVector<HDXDataset>& datasets) {
+ show_loading(false);
datasets_table_->setSortingEnabled(false);
datasets_table_->setRowCount(datasets.size());
@@ -227,7 +305,6 @@ void HDXDataPanel::populate_table(const QVector<HDXDataset>& datasets) {
}
datasets_table_->setSortingEnabled(true);
- datasets_table_->resizeColumnsToContents();
dataset_count_->setText(QString("%1 datasets").arg(datasets.size()));
}
diff --git a/fincept-qt/src/screens/geopolitics/HDXDataPanel.h b/fincept-qt/src/screens/geopolitics/HDXDataPanel.h
index 035c86be1..a877862ac 100644
--- a/fincept-qt/src/screens/geopolitics/HDXDataPanel.h
+++ b/fincept-qt/src/screens/geopolitics/HDXDataPanel.h
@@ -6,7 +6,6 @@
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
-#include <QStackedWidget>
#include <QTableWidget>
#include <QVBoxLayout>
#include <QWidget>
@@ -27,24 +26,31 @@ class HDXDataPanel : public QWidget {
void build_ui();
void connect_service();
void populate_table(const QVector<fincept::services::geo::HDXDataset>& datasets);
+ void show_loading(bool on);
- // Views
- QStackedWidget* view_stack_ = nullptr;
+ // View tab buttons
QVector<QPushButton*> view_buttons_;
int active_view_ = 0;
// Search
QLineEdit* search_edit_ = nullptr;
- // Datasets table
+ // Datasets table + loading overlay
QTableWidget* datasets_table_ = nullptr;
+ QLabel* loading_label_ = nullptr;
- // Explorer filters
+ // Explorer filter bar (shown only on Explorer tab)
+ QWidget* explorer_bar_ = nullptr;
QComboBox* country_combo_ = nullptr;
- QComboBox* topic_combo_ = nullptr;
+ QComboBox* topic_combo_ = nullptr;
- // Stats
+ // Stats badge
QLabel* dataset_count_ = nullptr;
+
+ // Per-view result cache (avoids re-fetching on tab switch)
+ QVector<fincept::services::geo::HDXDataset> cache_conflicts_;
+ QVector<fincept::services::geo::HDXDataset> cache_humanitarian_;
+ QVector<fincept::services::geo::HDXDataset> cache_datasets_;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/geopolitics/RelationshipPanel.cpp b/fincept-qt/src/screens/geopolitics/RelationshipPanel.cpp
index 2f6548c04..21f0f8e08 100644
--- a/fincept-qt/src/screens/geopolitics/RelationshipPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/RelationshipPanel.cpp
@@ -11,42 +11,37 @@ namespace fincept::screens {
using namespace fincept::services::geo;
-// Static relationship data matching the React implementation
static QVector<RelationshipNode> build_nodes() {
QVector<RelationshipNode> nodes;
// Primary conflicts
- nodes.append({"ukraine", "Ukraine", "conflict", "critical", 89, {"displacement", "humanitarian", "food_security"}});
- nodes.append({"gaza", "Gaza", "conflict", "critical", 67, {"displacement", "humanitarian", "health"}});
- nodes.append({"sudan", "Sudan", "conflict", "critical", 45, {"displacement", "food_security", "humanitarian"}});
- nodes.append({"yemen", "Yemen", "conflict", "high", 56, {"food_security", "humanitarian", "health"}});
- nodes.append({"syria", "Syria", "conflict", "high", 78, {"displacement", "humanitarian"}});
- nodes.append({"myanmar", "Myanmar", "conflict", "high", 29, {"displacement", "humanitarian"}});
+ nodes.append({"ukraine", "Ukraine", "conflict", "critical", 89, {"displacement", "humanitarian", "food_security"}});
+ nodes.append({"gaza", "Gaza", "conflict", "critical", 67, {"displacement", "humanitarian", "health"}});
+ nodes.append({"sudan", "Sudan", "conflict", "critical", 45, {"displacement", "food_security", "humanitarian"}});
+ nodes.append({"yemen", "Yemen", "conflict", "high", 56, {"food_security", "humanitarian", "health"}});
+ nodes.append({"syria", "Syria", "conflict", "high", 78, {"displacement", "humanitarian"}});
+ nodes.append({"myanmar", "Myanmar", "conflict", "high", 29, {"displacement", "humanitarian"}});
// Crisis types
- nodes.append({"displacement", "Displacement", "crisis", "high", 234, {"unhcr"}});
- nodes.append({"food_security", "Food Security", "crisis", "high", 189, {"wfp", "fao"}});
- nodes.append({"humanitarian", "Humanitarian", "crisis", "critical", 312, {"unhcr", "wfp", "who"}});
- nodes.append({"health", "Health Crisis", "crisis", "medium", 145, {"who"}});
+ nodes.append({"displacement", "Displacement", "crisis", "high", 234, {"unhcr"}});
+ nodes.append({"food_security", "Food Security", "crisis", "high", 189, {"wfp", "fao"}});
+ nodes.append({"humanitarian", "Humanitarian", "crisis", "critical", 312, {"unhcr", "wfp", "who"}});
+ nodes.append({"health", "Health Crisis", "crisis", "medium", 145, {"who"}});
// Organizations
nodes.append({"unhcr", "UNHCR", "organization", "", 234, {"displacement", "humanitarian"}});
- nodes.append({"wfp", "WFP", "organization", "", 189, {"food_security", "humanitarian"}});
- nodes.append({"who", "WHO", "organization", "", 156, {"health", "humanitarian"}});
- nodes.append({"fao", "FAO", "organization", "", 123, {"food_security"}});
+ nodes.append({"wfp", "WFP", "organization", "", 189, {"food_security", "humanitarian"}});
+ nodes.append({"who", "WHO", "organization", "", 156, {"health", "humanitarian"}});
+ nodes.append({"fao", "FAO", "organization", "", 123, {"food_security"}});
return nodes;
}
static QColor severity_color(const QString& sev) {
- if (sev == "critical")
- return QColor("#FF0000");
- if (sev == "high")
- return QColor("#FFA500");
- if (sev == "medium")
- return QColor("#FF9800");
- if (sev == "low")
- return QColor("#4CAF50");
+ if (sev == "critical") return QColor("#FF0000");
+ if (sev == "high") return QColor("#FFA500");
+ if (sev == "medium") return QColor("#FF9800");
+ if (sev == "low") return QColor("#4CAF50");
return QColor("#2196F3"); // organization
}
@@ -61,151 +56,226 @@ void RelationshipPanel::build_ui() {
// Header
auto* header = new QWidget(this);
- header->setFixedHeight(40);
+ header->setFixedHeight(48);
header->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
+ QString("background:%1; border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
auto* hhl = new QHBoxLayout(header);
hhl->setContentsMargins(16, 0, 16, 0);
+ hhl->setSpacing(12);
+
auto* title = new QLabel("GEOPOLITICAL RELATIONSHIP NETWORK", header);
- title->setStyleSheet(QString("color:#9D4EDD; font-size:%1px; font-weight:700; font-family:%2; letter-spacing:1px;")
- .arg(ui::fonts::TINY)
- .arg(ui::fonts::DATA_FAMILY));
+ title->setStyleSheet(
+ QString("color:#9D4EDD; font-size:%1px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
hhl->addWidget(title);
hhl->addStretch();
- // Network stats
auto nodes = build_nodes();
int conflicts = 0, orgs = 0;
for (const auto& n : nodes) {
- if (n.type == "conflict")
- conflicts++;
- if (n.type == "organization")
- orgs++;
+ if (n.type == "conflict") conflicts++;
+ if (n.type == "organization") orgs++;
}
+
auto* stats = new QLabel(
- QString("NODES: %1 | CONFLICTS: %2 | ORGANIZATIONS: %3").arg(nodes.size()).arg(conflicts).arg(orgs), header);
+ QString("NODES: %1 | CONFLICTS: %2 | ORGANIZATIONS: %3")
+ .arg(nodes.size()).arg(conflicts).arg(orgs),
+ header);
stats->setStyleSheet(
- QString("color:%1; font-size:9px; font-family:%2;").arg(ui::colors::TEXT_TERTIARY).arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:%2px; font-family:%3; padding:2px 8px;"
+ "background:rgba(255,255,255,0.04); border:1px solid %4; border-radius:2px;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::BORDER_DIM));
hhl->addWidget(stats);
root->addWidget(header);
- // Network view (card grid)
+ // Network view
auto* scroll = new QScrollArea(this);
scroll->setWidgetResizable(true);
- scroll->setStyleSheet("QScrollArea { border:none; background:transparent; }");
+ scroll->setStyleSheet(
+ QString("QScrollArea { border:none; background:%1; }"
+ "QScrollBar:vertical { background:%1; width:6px; }"
+ "QScrollBar::handle:vertical { background:%2; border-radius:3px; }"
+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }")
+ .arg(ui::colors::BG_BASE, ui::colors::BORDER_MED));
auto* content = new QWidget(scroll);
- auto* gl = new QGridLayout(content);
- gl->setContentsMargins(16, 16, 16, 16);
- gl->setSpacing(12);
-
- // Section: Conflicts
- auto* conflict_title = new QLabel("ACTIVE CONFLICTS", content);
- conflict_title->setStyleSheet(QString("color:#FF0000; font-size:9px; font-weight:700; font-family:%1;"
- "letter-spacing:1px;")
- .arg(ui::fonts::DATA_FAMILY));
- gl->addWidget(conflict_title, 0, 0, 1, 3);
-
- int col = 0, row = 1;
- for (const auto& n : nodes) {
- if (n.type != "conflict")
- continue;
- gl->addWidget(build_node_card(n, content), row, col);
- if (++col >= 3) {
- col = 0;
- row++;
+ content->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));
+ auto* cvl = new QVBoxLayout(content);
+ cvl->setContentsMargins(16, 16, 16, 16);
+ cvl->setSpacing(16);
+
+ // Helper: add a titled section with a 3-column card grid
+ auto add_section = [&](const QString& title, const QString& color, const QString& type) {
+ auto* sec_lbl = new QLabel(title, content);
+ sec_lbl->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;"
+ "letter-spacing:2px; padding-bottom:4px; border-bottom:1px solid rgba(%4,0.3);")
+ .arg(color)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(color.mid(1)));
+ cvl->addWidget(sec_lbl);
+
+ auto* grid_w = new QWidget(content);
+ auto* gl = new QGridLayout(grid_w);
+ gl->setContentsMargins(0, 0, 0, 0);
+ gl->setSpacing(10);
+ // All 3 columns equal width
+ gl->setColumnStretch(0, 1);
+ gl->setColumnStretch(1, 1);
+ gl->setColumnStretch(2, 1);
+
+ int col = 0, row = 0;
+ for (const auto& n : nodes) {
+ if (n.type != type) continue;
+ gl->addWidget(build_node_card(n, grid_w), row, col);
+ if (++col >= 3) { col = 0; row++; }
}
- }
-
- // Section: Crisis Types
- row++;
- col = 0;
- auto* crisis_title = new QLabel("CRISIS TYPES", content);
- crisis_title->setStyleSheet(QString("color:#FFA500; font-size:9px; font-weight:700; font-family:%1;"
- "letter-spacing:1px;")
- .arg(ui::fonts::DATA_FAMILY));
- gl->addWidget(crisis_title, row, 0, 1, 3);
- row++;
-
- for (const auto& n : nodes) {
- if (n.type != "crisis")
- continue;
- gl->addWidget(build_node_card(n, content), row, col);
- if (++col >= 3) {
- col = 0;
- row++;
+ // Fill remaining cells so columns stay even
+ while (col > 0 && col < 3) {
+ auto* spacer = new QWidget(grid_w);
+ spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
+ gl->addWidget(spacer, row, col++);
}
- }
- // Section: Organizations
- row++;
- col = 0;
- auto* org_title = new QLabel("ORGANIZATIONS", content);
- org_title->setStyleSheet(QString("color:#2196F3; font-size:9px; font-weight:700; font-family:%1;"
- "letter-spacing:1px;")
- .arg(ui::fonts::DATA_FAMILY));
- gl->addWidget(org_title, row, 0, 1, 3);
- row++;
+ cvl->addWidget(grid_w);
+ };
- for (const auto& n : nodes) {
- if (n.type != "organization")
- continue;
- gl->addWidget(build_node_card(n, content), row, col);
- if (++col >= 3) {
- col = 0;
- row++;
- }
- }
+ add_section("ACTIVE CONFLICTS", "#FF0000", "conflict");
+ add_section("CRISIS TYPES", "#FFA500", "crisis");
+ add_section("ORGANIZATIONS", "#2196F3", "organization");
+ cvl->addStretch();
scroll->setWidget(content);
root->addWidget(scroll, 1);
}
QWidget* RelationshipPanel::build_node_card(const RelationshipNode& node, QWidget* parent) {
auto color = severity_color(node.severity.isEmpty() ? "organization" : node.severity);
+ const QString col_hex = color.name();
+ const QString col_rgb =
+ QString("%1,%2,%3").arg(color.red()).arg(color.green()).arg(color.blue());
auto* card = new QWidget(parent);
- card->setStyleSheet(QString("background:%1; border:1px solid rgba(%2,%3,%4,0.3);"
- "border-left:3px solid %5; border-radius:2px;")
- .arg(ui::colors::BG_RAISED)
- .arg(color.red())
- .arg(color.green())
- .arg(color.blue())
- .arg(color.name()));
+ card->setObjectName("nodeCard");
+ card->setMinimumHeight(110);
+ card->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
+ card->setStyleSheet(
+ QString("#nodeCard { background:%1; border:1px solid rgba(%2,0.25);"
+ "border-left:3px solid %3; border-radius:3px; }")
+ .arg(ui::colors::BG_RAISED)
+ .arg(col_rgb)
+ .arg(col_hex));
auto* vl = new QVBoxLayout(card);
vl->setContentsMargins(12, 10, 12, 10);
vl->setSpacing(4);
- auto* name = new QLabel(node.label.toUpper(), card);
- name->setStyleSheet(QString("color:%1; font-size:11px; font-weight:700; font-family:%2;")
- .arg(color.name())
- .arg(ui::fonts::DATA_FAMILY));
- vl->addWidget(name);
-
+ // Name row
+ auto* name_row = new QWidget(card);
+ auto* name_hl = new QHBoxLayout(name_row);
+ name_hl->setContentsMargins(0, 0, 0, 0);
+ name_hl->setSpacing(6);
+
+ auto* name = new QLabel(node.label.toUpper(), name_row);
+ name->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
+ .arg(col_hex)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
+ name_hl->addWidget(name, 1);
+
+ const QString badge_text =
+ node.severity.isEmpty() ? node.type.toUpper() : node.severity.toUpper();
+ auto* badge = new QLabel(badge_text, name_row);
+ badge->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;"
+ "padding:2px 6px; background:rgba(%4,0.12); border:1px solid rgba(%4,0.3);"
+ "border-radius:8px; letter-spacing:1px;")
+ .arg(col_hex)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(col_rgb));
+ name_hl->addWidget(badge);
+ vl->addWidget(name_row);
+
+ // Type label
auto* type_lbl = new QLabel(node.type.toUpper(), card);
type_lbl->setStyleSheet(
- QString("color:%1; font-size:8px; font-family:%2;").arg(ui::colors::TEXT_TERTIARY).arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
vl->addWidget(type_lbl);
- if (!node.severity.isEmpty()) {
- auto* sev = new QLabel(QString("Severity: %1").arg(node.severity.toUpper()), card);
- sev->setStyleSheet(
- QString("color:%1; font-size:9px; font-family:%2;").arg(color.name()).arg(ui::fonts::DATA_FAMILY));
- vl->addWidget(sev);
- }
+ // Dataset count row
+ auto* ds_row = new QWidget(card);
+ auto* ds_hl = new QHBoxLayout(ds_row);
+ ds_hl->setContentsMargins(0, 0, 0, 0);
+ ds_hl->setSpacing(4);
+
+ auto* ds_num = new QLabel(QString::number(node.dataset_count), ds_row);
+ ds_num->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
+ .arg(ui::colors::TEXT_PRIMARY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
+ ds_hl->addWidget(ds_num);
+
+ auto* ds_lbl = new QLabel("datasets", ds_row);
+ ds_lbl->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
+ ds_hl->addWidget(ds_lbl);
+ ds_hl->addStretch();
+ vl->addWidget(ds_row);
+
+ // Connection pills (max 3)
+ if (!node.connections.isEmpty()) {
+ auto* pills_row = new QWidget(card);
+ auto* pills_hl = new QHBoxLayout(pills_row);
+ pills_hl->setContentsMargins(0, 2, 0, 0);
+ pills_hl->setSpacing(4);
+
+ const int max_pills = 3;
+ int shown = qMin(node.connections.size(), max_pills);
+ for (int i = 0; i < shown; ++i) {
+ auto* pill = new QLabel(node.connections[i], pills_row);
+ pill->setStyleSheet(
+ QString("color:%1; font-size:%2px; padding:1px 6px;"
+ "background:rgba(255,255,255,0.05); border:1px solid %3;"
+ "border-radius:8px; font-family:%4;")
+ .arg(ui::colors::TEXT_SECONDARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::colors::BORDER_DIM)
+ .arg(ui::fonts::DATA_FAMILY));
+ pills_hl->addWidget(pill);
+ }
+
+ if (node.connections.size() > max_pills) {
+ auto* more = new QLabel(
+ QString("+%1").arg(node.connections.size() - max_pills), pills_row);
+ more->setStyleSheet(
+ QString("color:%1; font-size:%2px; padding:1px 6px;"
+ "background:rgba(255,255,255,0.05); border:1px solid %3;"
+ "border-radius:8px; font-family:%4;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::colors::BORDER_DIM)
+ .arg(ui::fonts::DATA_FAMILY));
+ pills_hl->addWidget(more);
+ }
- auto* ds = new QLabel(QString("Datasets: %1").arg(node.dataset_count), card);
- ds->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2;")
- .arg(ui::colors::TEXT_PRIMARY)
- .arg(ui::fonts::DATA_FAMILY));
- vl->addWidget(ds);
-
- auto* conns = new QLabel(QString("Connections: %1").arg(node.connections.size()), card);
- conns->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2;")
- .arg(ui::colors::TEXT_SECONDARY)
- .arg(ui::fonts::DATA_FAMILY));
- vl->addWidget(conns);
+ pills_hl->addStretch();
+ vl->addWidget(pills_row);
+ }
return card;
}
diff --git a/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp b/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp
index 7fc586676..a87878011 100644
--- a/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp
@@ -4,13 +4,12 @@
#include "services/geopolitics/GeopoliticsService.h"
#include "ui/theme/Theme.h"
+#include <QDoubleSpinBox>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QJsonArray>
#include <QJsonDocument>
-#include <QLineEdit>
-#include <QPushButton>
#include <QScrollArea>
#include <QTableWidget>
@@ -25,8 +24,63 @@ TradeAnalysisPanel::TradeAnalysisPanel(QWidget* parent) : QWidget(parent) {
void TradeAnalysisPanel::connect_service() {
auto& svc = GeopoliticsService::instance();
- connect(&svc, &GeopoliticsService::trade_result_ready, this, &TradeAnalysisPanel::on_trade_result);
- connect(&svc, &GeopoliticsService::error_occurred, this, &TradeAnalysisPanel::on_error);
+ connect(&svc, &GeopoliticsService::trade_result_ready,
+ this, &TradeAnalysisPanel::on_trade_result);
+ connect(&svc, &GeopoliticsService::error_occurred,
+ this, &TradeAnalysisPanel::on_error);
+}
+
+// ── Shared style helpers ──────────────────────────────────────────────────────
+static QString combo_style() {
+ return QString("QComboBox { background:%1; color:%2; border:1px solid %3;"
+ "font-family:%4; font-size:%5px; padding:4px 8px; border-radius:2px; }"
+ "QComboBox:focus { border-color:#FFC400; }"
+ "QComboBox::drop-down { border:none; width:18px; }"
+ "QComboBox QAbstractItemView { background:%1; color:%2; "
+ "selection-background-color:rgba(255,196,0,0.15); border:1px solid %3; }")
+ .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL);
+}
+
+static QString spin_style() {
+ return QString("QDoubleSpinBox { background:%1; color:%2; border:1px solid %3;"
+ "font-family:%4; font-size:%5px; padding:4px 6px; border-radius:2px; }"
+ "QDoubleSpinBox:focus { border-color:#FFC400; }")
+ .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL);
+}
+
+static QWidget* make_field(const QString& label_text, QWidget* input, QWidget* parent,
+ const QString& hint = {}) {
+ auto* group = new QWidget(parent);
+ auto* vl = new QVBoxLayout(group);
+ vl->setContentsMargins(0, 0, 0, 0);
+ vl->setSpacing(3);
+
+ auto* lbl = new QLabel(label_text, group);
+ lbl->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3; letter-spacing:1px;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
+ vl->addWidget(lbl);
+
+ input->setParent(group);
+ vl->addWidget(input);
+
+ if (!hint.isEmpty()) {
+ auto* h = new QLabel(hint, group);
+ h->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
+ h->setWordWrap(true);
+ vl->addWidget(h);
+ }
+ return group;
}
void TradeAnalysisPanel::build_ui() {
@@ -36,20 +90,25 @@ void TradeAnalysisPanel::build_ui() {
// Header
auto* header = new QWidget(this);
- header->setFixedHeight(40);
+ header->setFixedHeight(48);
header->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
+ QString("background:%1; border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
auto* hhl = new QHBoxLayout(header);
hhl->setContentsMargins(16, 0, 16, 0);
auto* title = new QLabel("TRADE GEOPOLITICS ANALYSIS", header);
- title->setStyleSheet(QString("color:#FFC400; font-size:%1px; font-weight:700; font-family:%2; letter-spacing:1px;")
- .arg(ui::fonts::TINY)
- .arg(ui::fonts::DATA_FAMILY));
+ title->setStyleSheet(
+ QString("color:#FFC400; font-size:%1px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
hhl->addWidget(title);
hhl->addStretch();
status_label_ = new QLabel(header);
status_label_->setStyleSheet(
- QString("color:%1; font-size:9px; font-family:%2;").arg(ui::colors::TEXT_TERTIARY).arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
hhl->addWidget(status_label_);
root->addWidget(header);
@@ -63,124 +122,259 @@ void TradeAnalysisPanel::build_ui() {
cvl->setContentsMargins(16, 16, 16, 16);
cvl->setSpacing(12);
+ // ── Analysis Type selector ────────────────────────────────────────────────
+ auto* type_combo = new QComboBox;
+ type_combo->setStyleSheet(combo_style());
+ type_combo->addItem("Benefits & Costs of Trade", "benefits_costs");
+ type_combo->addItem("Trade Restrictions Analysis", "restrictions");
+ type_combo->addItem("Trading Blocs Analysis", "trading_blocs");
+ type_combo->addItem("Trade Barrier Removal Impact", "barrier_removal");
+ cvl->addWidget(make_field("ANALYSIS TYPE", type_combo, content));
+
+ // ── Tab widget for params per analysis type ───────────────────────────────
tabs_ = new QTabWidget(content);
- tabs_->setStyleSheet(QString("QTabWidget::pane { border:1px solid %1; background:%2; }"
- "QTabBar::tab { background:%3; color:%4; padding:6px 16px;"
- "font-family:%5; font-size:%6px; border:1px solid %1; border-bottom:none; }"
- "QTabBar::tab:selected { background:%2; color:#FFC400; font-weight:700;"
- "border-bottom:2px solid #FFC400; }")
- .arg(ui::colors::BORDER_DIM, ui::colors::BG_SURFACE, ui::colors::BG_RAISED)
- .arg(ui::colors::TEXT_SECONDARY)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
-
- auto label_style = QString("color:%1; font-size:%2px; font-family:%3;")
- .arg(ui::colors::TEXT_SECONDARY)
- .arg(ui::fonts::SMALL)
- .arg(ui::fonts::DATA_FAMILY);
- auto input_style = QString("QDoubleSpinBox, QLineEdit { background:%1; color:%2; border:1px solid %3;"
- "font-family:%4; font-size:%5px; padding:4px 6px; border-radius:2px; }"
- "QDoubleSpinBox:focus, QLineEdit:focus { border-color:#FFC400; }")
- .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_MED)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL);
-
- // ── Benefits & Costs Tab ──
- auto* benefits = new QWidget;
- auto* bvl = new QVBoxLayout(benefits);
- bvl->setContentsMargins(12, 12, 12, 12);
- bvl->setSpacing(8);
-
- auto* ben_hint = new QLabel("Analyzes trade benefits (efficiency, consumer, growth) and costs "
- "(adjustment, distributional, vulnerability) for a given trade scenario.",
- benefits);
- ben_hint->setWordWrap(true);
- ben_hint->setStyleSheet(label_style);
- bvl->addWidget(ben_hint);
-
- auto* ben_country = new QLineEdit(benefits);
- ben_country->setPlaceholderText("Country (e.g. United States)");
- ben_country->setStyleSheet(input_style);
- bvl->addWidget(ben_country);
-
- auto* ben_partner = new QLineEdit(benefits);
- ben_partner->setPlaceholderText("Trade partner (e.g. China)");
- ben_partner->setStyleSheet(input_style);
- bvl->addWidget(ben_partner);
-
- auto* ben_sector = new QLineEdit(benefits);
- ben_sector->setPlaceholderText("Sector (e.g. technology, agriculture)");
- ben_sector->setStyleSheet(input_style);
- bvl->addWidget(ben_sector);
-
- auto* ben_run = new QPushButton("ANALYZE TRADE BENEFITS & COSTS", benefits);
- ben_run->setCursor(Qt::PointingHandCursor);
- ben_run->setStyleSheet(QString("QPushButton { background:#FFC400; color:%1; font-family:%2; font-size:%3px;"
- "font-weight:700; border:none; padding:8px; border-radius:2px; letter-spacing:1px; }"
- "QPushButton:hover { background:#E5B000; }")
- .arg(ui::colors::BG_BASE)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
- connect(ben_run, &QPushButton::clicked, this, [this, ben_country, ben_partner, ben_sector]() {
+ tabs_->setStyleSheet(
+ QString("QTabWidget::pane { border:1px solid %1; background:%2; }"
+ "QTabBar::tab { background:%3; color:%4; padding:5px 16px;"
+ "font-family:%5; font-size:%6px; border:1px solid %1; border-bottom:none; }"
+ "QTabBar::tab:selected { background:%2; color:#FFC400; font-weight:700;"
+ "border-bottom:2px solid #FFC400; }")
+ .arg(ui::colors::BORDER_DIM, ui::colors::BG_SURFACE, ui::colors::BG_RAISED)
+ .arg(ui::colors::TEXT_SECONDARY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL));
+
+ // ── Page 0: Benefits & Costs ──────────────────────────────────────────────
+ auto* p0 = new QWidget;
+ auto* p0l = new QVBoxLayout(p0);
+ p0l->setContentsMargins(12, 12, 12, 12);
+ p0l->setSpacing(10);
+
+ auto* hint0 = new QLabel(
+ "Analyzes efficiency gains, consumer benefits, growth effects, and adjustment costs of international trade.",
+ p0);
+ hint0->setWordWrap(true);
+ hint0->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_SECONDARY).arg(ui::fonts::SMALL).arg(ui::fonts::DATA_FAMILY));
+ p0l->addWidget(hint0);
+
+ auto* vol_spin = new QDoubleSpinBox;
+ vol_spin->setRange(0, 100); vol_spin->setValue(30); vol_spin->setSuffix("% of GDP");
+ vol_spin->setStyleSheet(spin_style());
+ p0l->addWidget(make_field("TRADE VOLUME", vol_spin, p0, "Trade as % of GDP (world avg ~60%)"));
+
+ auto* price_spin = new QDoubleSpinBox;
+ price_spin->setRange(0, 50); price_spin->setValue(5); price_spin->setSuffix("%");
+ price_spin->setStyleSheet(spin_style());
+ p0l->addWidget(make_field("EXPECTED PRICE REDUCTION", price_spin, p0, "Consumer price reduction from trade openness"));
+
+ auto* cons_spin = new QDoubleSpinBox;
+ cons_spin->setRange(0, 100); cons_spin->setValue(30); cons_spin->setSuffix("% of consumption");
+ cons_spin->setStyleSheet(spin_style());
+ p0l->addWidget(make_field("TRADED GOODS SHARE", cons_spin, p0, "Share of consumption from tradeable goods"));
+
+ p0l->addStretch();
+
+ // Store spinboxes for use in run button
+ auto* run0 = new QPushButton("RUN ANALYSIS", p0);
+ run0->setCursor(Qt::PointingHandCursor);
+ run0->setStyleSheet(
+ QString("QPushButton { background:#FFC400; color:%1; font-family:%2; font-size:%3px;"
+ "font-weight:700; border:none; padding:6px 16px; border-radius:2px; }"
+ "QPushButton:hover { background:#E5B000; }")
+ .arg(ui::colors::BG_BASE).arg(ui::fonts::DATA_FAMILY).arg(ui::fonts::SMALL));
+ connect(run0, &QPushButton::clicked, this, [this, vol_spin, price_spin, cons_spin]() {
+ status_label_->setText("Analyzing...");
+ QJsonObject p;
+ p["trade_volume_gdp"] = vol_spin->value();
+ p["price_reduction_percent"] = price_spin->value();
+ p["traded_goods_consumption"] = cons_spin->value();
+ GeopoliticsService::instance().analyze_trade_benefits(p);
+ });
+ p0l->addWidget(run0);
+ tabs_->addTab(p0, "Benefits & Costs");
+
+ // ── Page 1: Restrictions ──────────────────────────────────────────────────
+ auto* p1 = new QWidget;
+ auto* p1l = new QVBoxLayout(p1);
+ p1l->setContentsMargins(12, 12, 12, 12);
+ p1l->setSpacing(10);
+
+ auto* hint1 = new QLabel(
+ "Analyzes economic impact of tariffs, quotas, export subsidies, and non-tariff barriers.",
+ p1);
+ hint1->setWordWrap(true);
+ hint1->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_SECONDARY).arg(ui::fonts::SMALL).arg(ui::fonts::DATA_FAMILY));
+ p1l->addWidget(hint1);
+
+ auto* tariff_spin = new QDoubleSpinBox;
+ tariff_spin->setRange(0, 200); tariff_spin->setValue(10); tariff_spin->setSuffix("%");
+ tariff_spin->setStyleSheet(spin_style());
+ p1l->addWidget(make_field("TARIFF RATE", tariff_spin, p1, "Import duty rate (e.g. 10% = standard MFN tariff)"));
+
+ auto* quota_spin = new QDoubleSpinBox;
+ quota_spin->setRange(0, 1000000); quota_spin->setValue(1000); quota_spin->setSuffix(" units");
+ quota_spin->setStyleSheet(spin_style());
+ p1l->addWidget(make_field("QUOTA VOLUME", quota_spin, p1, "Annual import quantity limit"));
+
+ auto* subsidy_spin = new QDoubleSpinBox;
+ subsidy_spin->setRange(0, 100); subsidy_spin->setValue(5); subsidy_spin->setSuffix("%");
+ subsidy_spin->setStyleSheet(spin_style());
+ p1l->addWidget(make_field("EXPORT SUBSIDY RATE", subsidy_spin, p1, "Government subsidy as % of export value"));
+
+ auto* dev_combo = new QComboBox;
+ dev_combo->setStyleSheet(combo_style());
+ dev_combo->addItem("Developed Economy", "developed");
+ dev_combo->addItem("Developing Economy", "developing");
+ dev_combo->addItem("Middle Income", "middle");
+ p1l->addWidget(make_field("DEVELOPMENT LEVEL", dev_combo, p1));
+
+ auto* maturity_combo = new QComboBox;
+ maturity_combo->setStyleSheet(combo_style());
+ maturity_combo->addItem("Mature Industry", "mature");
+ maturity_combo->addItem("Infant Industry", "infant");
+ maturity_combo->addItem("Emerging Industry","emerging");
+ p1l->addWidget(make_field("INDUSTRY MATURITY", maturity_combo, p1));
+
+ p1l->addStretch();
+
+ auto* run1 = new QPushButton("RUN ANALYSIS", p1);
+ run1->setCursor(Qt::PointingHandCursor);
+ run1->setStyleSheet(
+ QString("QPushButton { background:#FFC400; color:%1; font-family:%2; font-size:%3px;"
+ "font-weight:700; border:none; padding:6px 16px; border-radius:2px; }"
+ "QPushButton:hover { background:#E5B000; }")
+ .arg(ui::colors::BG_BASE).arg(ui::fonts::DATA_FAMILY).arg(ui::fonts::SMALL));
+ connect(run1, &QPushButton::clicked, this,
+ [this, tariff_spin, quota_spin, subsidy_spin, dev_combo, maturity_combo]() {
status_label_->setText("Analyzing...");
- QJsonObject params;
- params["country"] = ben_country->text();
- params["partner"] = ben_partner->text();
- params["sector"] = ben_sector->text();
- GeopoliticsService::instance().analyze_trade_benefits(params);
+ QJsonObject p;
+ p["tariff_rate"] = tariff_spin->value();
+ p["quota_volume"] = quota_spin->value();
+ p["subsidy_rate"] = subsidy_spin->value();
+ p["development_level"] = dev_combo->currentData().toString();
+ p["industry_maturity"] = maturity_combo->currentData().toString();
+ GeopoliticsService::instance().analyze_trade_restrictions(p);
});
- bvl->addWidget(ben_run);
- bvl->addStretch();
- tabs_->addTab(benefits, "Benefits & Costs");
-
- // ── Restrictions Tab ──
- auto* restrict = new QWidget;
- auto* rvl = new QVBoxLayout(restrict);
- rvl->setContentsMargins(12, 12, 12, 12);
- rvl->setSpacing(8);
-
- auto* res_hint = new QLabel("Analyzes impact of trade restrictions: tariffs, quotas, export subsidies, "
- "non-tariff barriers, and sanctions on bilateral trade.",
- restrict);
- res_hint->setWordWrap(true);
- res_hint->setStyleSheet(label_style);
- rvl->addWidget(res_hint);
-
- auto* res_country = new QLineEdit(restrict);
- res_country->setPlaceholderText("Imposing country");
- res_country->setStyleSheet(input_style);
- rvl->addWidget(res_country);
-
- auto* res_target = new QLineEdit(restrict);
- res_target->setPlaceholderText("Target country");
- res_target->setStyleSheet(input_style);
- rvl->addWidget(res_target);
-
- auto* res_type = new QLineEdit(restrict);
- res_type->setPlaceholderText("Restriction type (tariff, quota, sanction)");
- res_type->setStyleSheet(input_style);
- rvl->addWidget(res_type);
-
- auto* res_run = new QPushButton("ANALYZE TRADE RESTRICTIONS", restrict);
- res_run->setCursor(Qt::PointingHandCursor);
- res_run->setStyleSheet(ben_run->styleSheet());
- connect(res_run, &QPushButton::clicked, this, [this, res_country, res_target, res_type]() {
+ p1l->addWidget(run1);
+ tabs_->addTab(p1, "Restrictions");
+
+ // ── Page 2: Trading Blocs ─────────────────────────────────────────────────
+ auto* p2 = new QWidget;
+ auto* p2l = new QVBoxLayout(p2);
+ p2l->setContentsMargins(12, 12, 12, 12);
+ p2l->setSpacing(10);
+
+ auto* hint2 = new QLabel(
+ "Analyzes trade creation vs. diversion effects for regional trade blocs and economic unions.",
+ p2);
+ hint2->setWordWrap(true);
+ hint2->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_SECONDARY).arg(ui::fonts::SMALL).arg(ui::fonts::DATA_FAMILY));
+ p2l->addWidget(hint2);
+
+ auto* bloc_combo = new QComboBox;
+ bloc_combo->setStyleSheet(combo_style());
+ bloc_combo->addItem("Free Trade Area (e.g. USMCA, ASEAN)", "fta");
+ bloc_combo->addItem("Customs Union (e.g. EU, Mercosur)", "customs_union");
+ bloc_combo->addItem("Common Market (e.g. EU Single Market)", "common_market");
+ bloc_combo->addItem("Economic Union (e.g. European Union)", "economic_union");
+ p2l->addWidget(make_field("INTEGRATION TYPE", bloc_combo, p2));
+
+ auto* tc_spin = new QDoubleSpinBox;
+ tc_spin->setRange(0, 1000); tc_spin->setValue(100); tc_spin->setSuffix("B USD");
+ tc_spin->setStyleSheet(spin_style());
+ p2l->addWidget(make_field("TRADE CREATION ESTIMATE", tc_spin, p2, "Expected new trade generated within bloc"));
+
+ auto* td_spin = new QDoubleSpinBox;
+ td_spin->setRange(0, 1000); td_spin->setValue(30); td_spin->setSuffix("B USD");
+ td_spin->setStyleSheet(spin_style());
+ p2l->addWidget(make_field("TRADE DIVERSION ESTIMATE", td_spin, p2, "Trade diverted from efficient non-members"));
+
+ p2l->addStretch();
+
+ auto* run2 = new QPushButton("RUN ANALYSIS", p2);
+ run2->setCursor(Qt::PointingHandCursor);
+ run2->setStyleSheet(
+ QString("QPushButton { background:#FFC400; color:%1; font-family:%2; font-size:%3px;"
+ "font-weight:700; border:none; padding:6px 16px; border-radius:2px; }"
+ "QPushButton:hover { background:#E5B000; }")
+ .arg(ui::colors::BG_BASE).arg(ui::fonts::DATA_FAMILY).arg(ui::fonts::SMALL));
+ connect(run2, &QPushButton::clicked, this, [this, bloc_combo, tc_spin, td_spin]() {
status_label_->setText("Analyzing...");
- QJsonObject params;
- params["imposing_country"] = res_country->text();
- params["target_country"] = res_target->text();
- params["restriction_type"] = res_type->text();
- GeopoliticsService::instance().analyze_trade_restrictions(params);
+ QJsonObject p;
+ p["integration_type"] = bloc_combo->currentData().toString();
+ p["trade_creation"] = tc_spin->value();
+ p["trade_diversion"] = td_spin->value();
+ GeopoliticsService::instance().analyze_trade_benefits(p); // reuses benefits endpoint with trading_blocs type
});
- rvl->addWidget(res_run);
- rvl->addStretch();
- tabs_->addTab(restrict, "Restrictions");
+ p2l->addWidget(run2);
+ tabs_->addTab(p2, "Trading Blocs");
+
+ // ── Page 3: Barrier Removal ───────────────────────────────────────────────
+ auto* p3 = new QWidget;
+ auto* p3l = new QVBoxLayout(p3);
+ p3l->setContentsMargins(12, 12, 12, 12);
+ p3l->setSpacing(10);
+
+ auto* hint3 = new QLabel(
+ "Assesses FDI, employment, wage, and GDP impact of removing trade barriers.",
+ p3);
+ hint3->setWordWrap(true);
+ hint3->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;")
+ .arg(ui::colors::TEXT_SECONDARY).arg(ui::fonts::SMALL).arg(ui::fonts::DATA_FAMILY));
+ p3l->addWidget(hint3);
+
+ auto* lib_combo = new QComboBox;
+ lib_combo->setStyleSheet(combo_style());
+ lib_combo->addItem("Unilateral Liberalization", "unilateral");
+ lib_combo->addItem("Bilateral Agreement", "bilateral");
+ lib_combo->addItem("Regional Agreement", "regional");
+ lib_combo->addItem("Multilateral (WTO Round)", "multilateral");
+ p3l->addWidget(make_field("LIBERALIZATION SCOPE", lib_combo, p3));
+
+ auto* tariff_cut_spin = new QDoubleSpinBox;
+ tariff_cut_spin->setRange(0, 100); tariff_cut_spin->setValue(50); tariff_cut_spin->setSuffix("% reduction");
+ tariff_cut_spin->setStyleSheet(spin_style());
+ p3l->addWidget(make_field("TARIFF REDUCTION", tariff_cut_spin, p3, "% cut in existing tariff rates"));
+
+ auto* gdp_spin = new QDoubleSpinBox;
+ gdp_spin->setRange(0, 100000); gdp_spin->setValue(500); gdp_spin->setSuffix("B USD");
+ gdp_spin->setStyleSheet(spin_style());
+ p3l->addWidget(make_field("ECONOMY SIZE (GDP)", gdp_spin, p3));
+
+ p3l->addStretch();
+
+ auto* run3 = new QPushButton("RUN ANALYSIS", p3);
+ run3->setCursor(Qt::PointingHandCursor);
+ run3->setStyleSheet(
+ QString("QPushButton { background:#FFC400; color:%1; font-family:%2; font-size:%3px;"
+ "font-weight:700; border:none; padding:6px 16px; border-radius:2px; }"
+ "QPushButton:hover { background:#E5B000; }")
+ .arg(ui::colors::BG_BASE).arg(ui::fonts::DATA_FAMILY).arg(ui::fonts::SMALL));
+ connect(run3, &QPushButton::clicked, this, [this, lib_combo, tariff_cut_spin, gdp_spin]() {
+ status_label_->setText("Analyzing...");
+ QJsonObject p;
+ p["liberalization_type"] = lib_combo->currentData().toString();
+ p["tariff_reduction"] = tariff_cut_spin->value();
+ p["gdp_size"] = gdp_spin->value();
+ GeopoliticsService::instance().analyze_trade_restrictions(p); // reuses restrictions endpoint
+ });
+ p3l->addWidget(run3);
+ tabs_->addTab(p3, "Barrier Removal");
+
+ // Sync analysis type combo → tab
+ connect(type_combo, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ tabs_, &QTabWidget::setCurrentIndex);
+ connect(tabs_, &QTabWidget::currentChanged,
+ type_combo, &QComboBox::setCurrentIndex);
cvl->addWidget(tabs_);
// Results area
results_container_ = new QWidget(content);
- results_layout_ = new QVBoxLayout(results_container_);
+ results_layout_ = new QVBoxLayout(results_container_);
results_layout_->setContentsMargins(0, 8, 0, 0);
results_layout_->setSpacing(8);
cvl->addWidget(results_container_);
@@ -190,75 +384,79 @@ void TradeAnalysisPanel::build_ui() {
}
void TradeAnalysisPanel::display_result(const QJsonObject& data) {
- // Clear previous
while (results_layout_->count() > 0) {
auto* item = results_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
+ if (item->widget()) item->widget()->deleteLater();
delete item;
}
- auto* header = new QLabel("ANALYSIS RESULTS");
- header->setStyleSheet(QString("color:#FFC400; font-size:9px; font-weight:700; font-family:%1; letter-spacing:1px;")
- .arg(ui::fonts::DATA_FAMILY));
- results_layout_->addWidget(header);
-
- // Key-value table for scalar fields
- QStringList keys;
- for (auto it = data.begin(); it != data.end(); ++it)
- if (!it.value().isObject() && !it.value().isArray())
- keys.append(it.key());
-
- if (!keys.isEmpty()) {
- auto* table = new QTableWidget(keys.size(), 2);
- table->setHorizontalHeaderLabels({"Metric", "Value"});
- table->setEditTriggers(QAbstractItemView::NoEditTriggers);
- table->setAlternatingRowColors(true);
- table->horizontalHeader()->setStretchLastSection(true);
- table->verticalHeader()->setVisible(false);
- table->setMaximumHeight(400);
- table->setStyleSheet(QString("QTableWidget { background:%1; color:%2; gridline-color:%3;"
- "font-family:%4; font-size:%5px; border:1px solid %3; }"
- "QTableWidget::item { padding:4px 8px; }"
- "QHeaderView::section { background:%6; color:%7; font-weight:700;"
- "padding:4px 8px; border:1px solid %3; font-family:%4; font-size:%5px; }"
- "QTableWidget::item:alternate { background:%8; }")
- .arg(ui::colors::BG_SURFACE, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_DIM)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL)
- .arg(ui::colors::BG_RAISED)
- .arg(ui::colors::TEXT_SECONDARY)
- .arg(ui::colors::ROW_ALT));
-
- for (int r = 0; r < keys.size(); ++r) {
- auto label = keys[r];
- label.replace('_', ' ');
- table->setItem(r, 0, new QTableWidgetItem(label.toUpper()));
- auto val = data[keys[r]];
- QString text = val.isDouble() ? QString::number(val.toDouble(), 'f', 2)
- : val.isBool() ? (val.toBool() ? "YES" : "NO")
- : val.toString();
- auto* vi = new QTableWidgetItem(text);
- vi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- table->setItem(r, 1, vi);
- }
- table->resizeColumnsToContents();
- results_layout_->addWidget(table);
+ auto* sep = new QWidget;
+ sep->setFixedHeight(1);
+ sep->setStyleSheet(QString("background:%1;").arg(ui::colors::BORDER_DIM));
+ results_layout_->addWidget(sep);
+
+ auto* hdr = new QLabel("ANALYSIS RESULTS");
+ hdr->setStyleSheet(
+ QString("color:#FFC400; font-size:%1px; font-weight:700; font-family:%2;"
+ "letter-spacing:1px; padding:8px 0 4px 0;")
+ .arg(ui::fonts::TINY).arg(ui::fonts::DATA_FAMILY));
+ results_layout_->addWidget(hdr);
+
+ // Flatten and display JSON as a table
+ QVector<QPair<QString, QString>> rows;
+ std::function<void(const QJsonObject&, const QString&)> flatten =
+ [&](const QJsonObject& obj, const QString& prefix) {
+ for (auto it = obj.begin(); it != obj.end(); ++it) {
+ QString key = prefix.isEmpty() ? it.key() : prefix + " › " + it.key();
+ if (it.value().isObject()) {
+ flatten(it.value().toObject(), key);
+ } else if (it.value().isArray()) {
+ QStringList items;
+ for (const auto& v : it.value().toArray())
+ items << v.toString();
+ rows.append({key, items.join(", ")});
+ } else {
+ QString val = it.value().isDouble()
+ ? QString::number(it.value().toDouble(), 'f', 2)
+ : it.value().isBool() ? (it.value().toBool() ? "YES" : "NO")
+ : it.value().toString();
+ if (!val.isEmpty())
+ rows.append({key, val});
+ }
+ }
+ };
+ flatten(data, "");
+
+ auto* table = new QTableWidget(rows.size(), 2);
+ table->setHorizontalHeaderLabels({"Metric", "Value"});
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->setAlternatingRowColors(true);
+ table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
+ table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
+ table->verticalHeader()->setVisible(false);
+ table->verticalHeader()->setDefaultSectionSize(24);
+ table->setStyleSheet(
+ QString("QTableWidget { background:%1; color:%2; gridline-color:%3;"
+ "font-family:%4; font-size:%5px; border:1px solid %3; }"
+ "QTableWidget::item { padding:3px 8px; }"
+ "QHeaderView::section { background:%6; color:%7; font-weight:700;"
+ "padding:4px 8px; border:1px solid %3; font-family:%4; font-size:%5px; }"
+ "QTableWidget::item:alternate { background:%8; }")
+ .arg(ui::colors::BG_SURFACE, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_DIM)
+ .arg(ui::fonts::DATA_FAMILY).arg(ui::fonts::SMALL)
+ .arg(ui::colors::BG_RAISED).arg(ui::colors::TEXT_SECONDARY)
+ .arg(ui::colors::ROW_ALT));
+
+ for (int r = 0; r < rows.size(); ++r) {
+ auto key = rows[r].first;
+ key.replace('_', ' ');
+ table->setItem(r, 0, new QTableWidgetItem(key));
+ auto* vi = new QTableWidgetItem(rows[r].second);
+ vi->setToolTip(rows[r].second);
+ table->setItem(r, 1, vi);
}
-
- // Raw JSON
- auto* raw = new QTextEdit;
- raw->setReadOnly(true);
- raw->setMaximumHeight(200);
- raw->setPlainText(QJsonDocument(data).toJson(QJsonDocument::Indented));
- raw->setStyleSheet(QString("QTextEdit { background:%1; color:%2; border:1px solid %3;"
- "font-family:%4; font-size:%5px; padding:8px; }")
- .arg(ui::colors::BG_RAISED, ui::colors::TEXT_PRIMARY, ui::colors::BORDER_DIM)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
- results_layout_->addWidget(raw);
-
- status_label_->setText("Done");
+ results_layout_->addWidget(table);
+ status_label_->setText(QString("%1 fields").arg(rows.size()));
}
void TradeAnalysisPanel::on_trade_result(const QString& context, const QJsonObject& data) {
@@ -270,21 +468,18 @@ void TradeAnalysisPanel::on_error(const QString& context, const QString& message
if (context != "trade_benefits" && context != "trade_restrictions")
return;
status_label_->setText("Error");
- // Clear and show error
while (results_layout_->count() > 0) {
auto* item = results_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
+ if (item->widget()) item->widget()->deleteLater();
delete item;
}
auto* err = new QLabel(QString("[%1] %2").arg(context, message));
err->setWordWrap(true);
- err->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:12px;"
- "background:rgba(220,38,38,0.08); border:1px solid rgba(220,38,38,0.3);"
- "border-radius:2px;")
- .arg(ui::colors::NEGATIVE)
- .arg(ui::fonts::SMALL)
- .arg(ui::fonts::DATA_FAMILY));
+ err->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-family:%3; padding:12px;"
+ "background:rgba(220,38,38,0.08); border:1px solid rgba(220,38,38,0.3);"
+ "border-radius:2px;")
+ .arg(ui::colors::NEGATIVE).arg(ui::fonts::SMALL).arg(ui::fonts::DATA_FAMILY));
results_layout_->addWidget(err);
}
diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen.cpp
index 5d39b999f..47066752e 100644
--- a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp
+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.cpp
@@ -4,6 +4,7 @@
#include "core/logging/Logger.h"
#include "services/maritime/MaritimeService.h"
#include "ui/theme/Theme.h"
+#include "ui/theme/ThemeManager.h"
#include "ui/widgets/WorldMapWidget.h"
#include <QGridLayout>
@@ -17,6 +18,71 @@ namespace fincept::screens {
using namespace fincept::services::maritime;
+// ── Style helpers (live tokens) ───────────────────────────────────────────────
+
+// Helper: token → QString (works for both ColorToken and FontFamilyToken)
+static inline QString C(const ui::ColorToken& t) { return QString::fromLatin1(t.get()); }
+static inline QString F(const ui::fonts::FontFamilyToken& t) { return QString::fromLatin1(t.get()); }
+
+static QString table_ss() {
+ return QString("QTableWidget { background:%1; color:%2; gridline-color:%3;"
+ "font-family:%4; font-size:%5px; border:none; }"
+ "QTableWidget::item { padding:4px 6px; }"
+ "QTableWidget::item:selected { background:%6; }"
+ "QTableWidget::item:alternate { background:%7; }"
+ "QHeaderView::section { background:%8; color:%9; font-weight:700;"
+ "padding:6px 8px; border:1px solid %3; font-family:%4; font-size:%5px; }")
+ .arg(C(ui::colors::BG_BASE), C(ui::colors::TEXT_PRIMARY),
+ C(ui::colors::BORDER_DIM), F(ui::fonts::DATA_FAMILY))
+ .arg(ui::fonts::SMALL)
+ .arg(C(ui::colors::BG_HOVER), C(ui::colors::ROW_ALT),
+ C(ui::colors::BG_RAISED), C(ui::colors::TEXT_SECONDARY));
+}
+
+static QString input_ss() {
+ return QString("QLineEdit, QDoubleSpinBox { background:%1; color:%2; border:1px solid %3;"
+ "font-family:%4; font-size:%5px; padding:6px 8px; border-radius:2px; }"
+ "QLineEdit:focus, QDoubleSpinBox:focus { border-color:%6; }")
+ .arg(C(ui::colors::BG_SURFACE), C(ui::colors::TEXT_PRIMARY),
+ C(ui::colors::BORDER_MED), F(ui::fonts::DATA_FAMILY))
+ .arg(ui::fonts::SMALL)
+ .arg(C(ui::colors::AMBER));
+}
+
+static QString btn_primary_ss() {
+ return QString("QPushButton { background:%1; color:%2; font-family:%3; font-size:%4px;"
+ "font-weight:700; border:none; padding:8px; border-radius:2px; letter-spacing:1px; }"
+ "QPushButton:hover { background:%5; }")
+ .arg(C(ui::colors::AMBER), C(ui::colors::BG_BASE), F(ui::fonts::DATA_FAMILY))
+ .arg(ui::fonts::SMALL)
+ .arg(C(ui::colors::AMBER_DIM));
+}
+
+static QString btn_outline_ss() {
+ return QString("QPushButton { background:transparent; color:%1; font-family:%2; font-size:%3px;"
+ "font-weight:700; border:1px solid %1; padding:6px; border-radius:2px; }"
+ "QPushButton:hover { background:%4; }")
+ .arg(C(ui::colors::WARNING), F(ui::fonts::DATA_FAMILY))
+ .arg(ui::fonts::SMALL)
+ .arg(C(ui::colors::BG_HOVER));
+}
+
+static QString section_label_ss() {
+ return QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"
+ "letter-spacing:1px; padding-bottom:4px; border-bottom:1px solid %3;")
+ .arg(C(ui::colors::AMBER), F(ui::fonts::DATA_FAMILY), C(ui::colors::BORDER_DIM));
+}
+
+static QString tiny_label_ss() {
+ return QString("color:%1; font-size:8px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(C(ui::colors::TEXT_TERTIARY), F(ui::fonts::DATA_FAMILY));
+}
+
+static QString detail_text_ss() {
+ return QString("color:%1; font-size:9px; font-family:%2;")
+ .arg(C(ui::colors::TEXT_SECONDARY), F(ui::fonts::DATA_FAMILY));
+}
+
// ── Constructor ──────────────────────────────────────────────────────────────
MaritimeScreen::MaritimeScreen(QWidget* parent) : QWidget(parent) {
routes_ = default_trade_routes();
@@ -27,6 +93,9 @@ MaritimeScreen::MaritimeScreen(QWidget* parent) : QWidget(parent) {
refresh_timer_->setInterval(5 * 60 * 1000); // 5 min
connect(refresh_timer_, &QTimer::timeout, this, &MaritimeScreen::on_load_vessels);
+ connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed,
+ this, [this](const ui::ThemeTokens&) { apply_theme(); });
+
LOG_INFO("Maritime", "Screen constructed");
}
@@ -36,7 +105,6 @@ void MaritimeScreen::showEvent(QShowEvent* e) {
if (first_show_) {
first_show_ = false;
populate_routes_table();
- // Load real vessel data from API on first show
on_load_vessels();
}
LOG_INFO("Maritime", "Screen shown");
@@ -49,10 +117,92 @@ void MaritimeScreen::hideEvent(QHideEvent* e) {
void MaritimeScreen::connect_service() {
auto& svc = MaritimeService::instance();
- connect(&svc, &MaritimeService::vessels_loaded, this, &MaritimeScreen::on_vessels_loaded);
- connect(&svc, &MaritimeService::vessel_found, this, &MaritimeScreen::on_vessel_found);
- connect(&svc, &MaritimeService::vessel_history_loaded, this, &MaritimeScreen::on_vessel_history);
- connect(&svc, &MaritimeService::error_occurred, this, &MaritimeScreen::on_error);
+ connect(&svc, &MaritimeService::vessels_loaded, this, &MaritimeScreen::on_vessels_loaded);
+ connect(&svc, &MaritimeService::vessel_found, this, &MaritimeScreen::on_vessel_found);
+ connect(&svc, &MaritimeService::vessel_history_loaded,this, &MaritimeScreen::on_vessel_history);
+ connect(&svc, &MaritimeService::error_occurred, this, &MaritimeScreen::on_error);
+}
+
+// ── Theme apply (called on construction + theme_changed) ─────────────────────
+void MaritimeScreen::apply_theme() {
+ setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));
+
+ if (top_bar_)
+ top_bar_->setStyleSheet(
+ QString("background:%1; border-bottom:1px solid %2;")
+ .arg(C(ui::colors::BG_RAISED), C(ui::colors::BORDER_MED)));
+
+ if (brand_label_)
+ brand_label_->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3; letter-spacing:2px;")
+ .arg(ui::colors::AMBER)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
+
+ if (classified_label_)
+ classified_label_->setStyleSheet(
+ QString("color:%1; font-size:9px; font-family:%2; letter-spacing:1px;")
+ .arg(ui::colors::TEXT_TERTIARY)
+ .arg(ui::fonts::DATA_FAMILY));
+
+ if (threat_badge_)
+ threat_badge_->setStyleSheet(
+ QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"
+ "padding:3px 10px; background:%3; border:1px solid %4; border-radius:2px;")
+ .arg(ui::colors::POSITIVE)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::BG_SURFACE)
+ .arg(ui::colors::BORDER_MED));
+
+ if (vessel_count_label_)
+ vessel_count_label_->setStyleSheet(
+ QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"
+ "padding:3px 10px; background:%3; border:1px solid %4; border-radius:2px;")
+ .arg(ui::colors::INFO)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::BG_SURFACE)
+ .arg(ui::colors::BORDER_MED));
+
+ if (left_panel_)
+ left_panel_->setStyleSheet(
+ QString("background:%1; border-right:1px solid %2;")
+ .arg(C(ui::colors::BG_SURFACE), C(ui::colors::BORDER_DIM)));
+
+ if (right_panel_)
+ right_panel_->setStyleSheet(
+ QString("background:%1; border-left:1px solid %2;")
+ .arg(C(ui::colors::BG_SURFACE), C(ui::colors::BORDER_DIM)));
+
+ if (routes_table_) routes_table_->setStyleSheet(table_ss());
+ if (vessels_table_) vessels_table_->setStyleSheet(table_ss());
+
+ if (status_bar_)
+ status_bar_->setStyleSheet(
+ QString("background:%1; border-top:1px solid %2;")
+ .arg(C(ui::colors::BG_SURFACE), C(ui::colors::BORDER_DIM)));
+
+ if (status_label_)
+ set_status("READY", ui::colors::POSITIVE);
+
+ if (route_detail_)
+ route_detail_->setStyleSheet(
+ QString("background:%1; border:1px solid %2; border-left:3px solid %2; border-radius:2px;")
+ .arg(C(ui::colors::BG_SURFACE), C(ui::colors::AMBER)));
+
+ if (search_result_card_)
+ search_result_card_->setStyleSheet(
+ QString("background:%1; border:1px solid %2; border-radius:2px;")
+ .arg(C(ui::colors::BG_SURFACE), C(ui::colors::INFO)));
+
+ if (imo_edit_) imo_edit_->setStyleSheet(input_ss());
+}
+
+void MaritimeScreen::set_status(const QString& text, const ui::ColorToken& color) {
+ if (!status_label_) return;
+ status_label_->setText(text);
+ status_label_->setStyleSheet(
+ QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
+ .arg(color).arg(ui::fonts::DATA_FAMILY));
}
// ── Build UI ─────────────────────────────────────────────────────────────────
@@ -61,151 +211,131 @@ void MaritimeScreen::build_ui() {
root->setContentsMargins(0, 0, 0, 0);
root->setSpacing(0);
- root->addWidget(build_top_bar());
+ top_bar_ = build_top_bar();
+ root->addWidget(top_bar_);
auto* body = new QHBoxLayout;
body->setContentsMargins(0, 0, 0, 0);
body->setSpacing(0);
- body->addWidget(build_left_panel());
+ left_panel_ = build_left_panel();
+ right_panel_ = build_right_panel();
+ body->addWidget(left_panel_);
body->addWidget(build_center_panel(), 1);
- body->addWidget(build_right_panel());
+ body->addWidget(right_panel_);
auto* body_w = new QWidget(this);
body_w->setLayout(body);
root->addWidget(body_w, 1);
- root->addWidget(build_status_bar());
- setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE));
+ status_bar_ = build_status_bar();
+ root->addWidget(status_bar_);
+
+ apply_theme();
}
// ── Top Bar ──────────────────────────────────────────────────────────────────
QWidget* MaritimeScreen::build_top_bar() {
auto* bar = new QWidget(this);
bar->setFixedHeight(44);
- bar->setStyleSheet(QString("background: qlineargradient(x1:0,y1:0,x2:1,y2:0,"
- "stop:0 %1, stop:1 #000000); border-bottom:1px solid #00ff00;")
- .arg(ui::colors::BG_RAISED));
auto* hl = new QHBoxLayout(bar);
hl->setContentsMargins(12, 0, 12, 0);
hl->setSpacing(12);
- auto* brand = new QLabel("FINCEPT MARITIME INTELLIGENCE", bar);
- brand->setStyleSheet(QString("color:#00ff00; font-size:%1px; font-weight:700; font-family:%2;"
- "letter-spacing:2px;")
- .arg(ui::fonts::TINY)
- .arg(ui::fonts::DATA_FAMILY));
- hl->addWidget(brand);
+ brand_label_ = new QLabel("FINCEPT MARITIME INTELLIGENCE", bar);
+ hl->addWidget(brand_label_);
- auto* classified = new QLabel("CLASSIFIED // TRADE ROUTE ANALYSIS", bar);
- classified->setStyleSheet(
- QString("color:#00ff0080; font-size:9px; font-family:%1; letter-spacing:1px;").arg(ui::fonts::DATA_FAMILY));
- hl->addWidget(classified);
+ classified_label_ = new QLabel("CLASSIFIED // TRADE ROUTE ANALYSIS", bar);
+ hl->addWidget(classified_label_);
hl->addStretch(1);
- // Threat badge
threat_badge_ = new QLabel("THREAT: LOW", bar);
- threat_badge_->setStyleSheet(QString("color:#00FF00; font-size:9px; font-weight:700; font-family:%1;"
- "padding:3px 10px; background:rgba(0,255,0,0.08);"
- "border:1px solid rgba(0,255,0,0.3); border-radius:2px;")
- .arg(ui::fonts::DATA_FAMILY));
hl->addWidget(threat_badge_);
- // Vessel count
vessel_count_label_ = new QLabel("0 VESSELS", bar);
- vessel_count_label_->setStyleSheet(QString("color:#00E5FF; font-size:9px; font-weight:700; font-family:%1;"
- "padding:3px 10px; background:rgba(0,229,255,0.08);"
- "border:1px solid rgba(0,229,255,0.3); border-radius:2px;")
- .arg(ui::fonts::DATA_FAMILY));
hl->addWidget(vessel_count_label_);
return bar;
}
-// ── Left Panel: Intelligence Stats + Trade Routes ────────────────────────────
+// ── Left Panel ───────────────────────────────────────────────────────────────
QWidget* MaritimeScreen::build_left_panel() {
auto* panel = new QWidget(this);
panel->setFixedWidth(260);
- panel->setStyleSheet(QString("background:#000000; border-right:1px solid #1a1a1a;"));
auto* vl = new QVBoxLayout(panel);
vl->setContentsMargins(12, 12, 12, 12);
vl->setSpacing(8);
- // Load vessels button
auto* load_btn = new QPushButton("LOAD VESSELS (MUMBAI AREA)", panel);
load_btn->setCursor(Qt::PointingHandCursor);
- load_btn->setStyleSheet(
- QString("QPushButton { background:#00E5FF; color:#000; font-family:%1; font-size:%2px;"
- "font-weight:700; border:none; padding:8px; border-radius:2px; letter-spacing:1px; }"
- "QPushButton:hover { background:#00B8D4; }")
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
+ load_btn->setStyleSheet(btn_primary_ss());
connect(load_btn, &QPushButton::clicked, this, &MaritimeScreen::on_load_vessels);
vl->addWidget(load_btn);
- // Stats grid
- auto* stats_title = new QLabel("INTELLIGENCE", panel);
- stats_title->setStyleSheet(
- QString("color:#00ff00; font-size:9px; font-weight:700; font-family:%1; letter-spacing:1px;")
- .arg(ui::fonts::DATA_FAMILY));
- vl->addWidget(stats_title);
+ auto* intel_title = new QLabel("INTELLIGENCE", panel);
+ intel_title->setStyleSheet(
+ QString("color:%1; font-size:9px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(ui::colors::AMBER).arg(ui::fonts::DATA_FAMILY));
+ vl->addWidget(intel_title);
auto* grid = new QGridLayout;
grid->setSpacing(6);
- auto make_stat = [&](const QString& label, const QString& value, const QString& color) {
+ auto make_stat = [&](const QString& label, const QString& value, const ui::ColorToken& val_color) {
auto* box = new QWidget(panel);
- box->setStyleSheet(QString("background:#0a0a0a; border:1px solid #1a1a1a; border-radius:2px;"));
+ box->setStyleSheet(
+ QString("background:%1; border:1px solid %2; border-radius:2px;")
+ .arg(C(ui::colors::BG_BASE), C(ui::colors::BORDER_DIM)));
auto* bvl = new QVBoxLayout(box);
bvl->setContentsMargins(8, 6, 8, 6);
bvl->setSpacing(2);
auto* lbl = new QLabel(label, box);
- lbl->setStyleSheet(QString("color:#666; font-size:7px; font-family:%1;").arg(ui::fonts::DATA_FAMILY));
+ lbl->setStyleSheet(
+ QString("color:%1; font-size:7px; font-family:%2;")
+ .arg(ui::colors::TEXT_TERTIARY).arg(ui::fonts::DATA_FAMILY));
auto* val = new QLabel(value, box);
- val->setStyleSheet(QString("color:%1; font-size:12px; font-weight:700; font-family:%2;")
- .arg(color)
- .arg(ui::fonts::DATA_FAMILY));
- val->setObjectName(label); // for later lookup
+ val->setStyleSheet(
+ QString("color:%1; font-size:12px; font-weight:700; font-family:%2;")
+ .arg(val_color).arg(ui::fonts::DATA_FAMILY));
+ val->setObjectName(label);
bvl->addWidget(lbl);
bvl->addWidget(val);
return box;
};
- auto* sv = make_stat("TOTAL VESSELS", "0", "#00E5FF");
+ auto* sv = make_stat("TOTAL VESSELS", "0", ui::colors::INFO);
stat_vessels_ = sv->findChild<QLabel*>("TOTAL VESSELS");
grid->addWidget(sv, 0, 0);
- auto* sd = make_stat("DISPLAYED", "0", "#00FF00");
+ auto* sd = make_stat("DISPLAYED", "0", ui::colors::POSITIVE);
stat_displayed_ = sd->findChild<QLabel*>("DISPLAYED");
grid->addWidget(sd, 0, 1);
- auto* sr = make_stat("ROUTES", "10", "#00E5FF");
+ auto* sr = make_stat("ROUTES", "10", ui::colors::INFO);
stat_routes_ = sr->findChild<QLabel*>("ROUTES");
grid->addWidget(sr, 1, 0);
- auto* stv = make_stat("TRADE VOL", "$847.3B", "#00FF00");
+ auto* stv = make_stat("TRADE VOL", "$847.3B", ui::colors::POSITIVE);
stat_volume_ = stv->findChild<QLabel*>("TRADE VOL");
grid->addWidget(stv, 1, 1);
- auto* sp = make_stat("PORTS", "6", "#FFA500");
+ auto* sp = make_stat("PORTS", "6", ui::colors::WARNING);
stat_ports_ = sp->findChild<QLabel*>("PORTS");
grid->addWidget(sp, 2, 0);
- grid->addWidget(make_stat("SATELLITES", "13", "#9D4EDD"), 2, 1);
+ grid->addWidget(make_stat("SATELLITES", "13", ui::colors::AMBER), 2, 1);
vl->addLayout(grid);
- // Trade corridors section
vl->addSpacing(8);
auto* routes_title = new QLabel("TRADE CORRIDORS", panel);
routes_title->setStyleSheet(
- QString("color:#00E5FF; font-size:9px; font-weight:700; font-family:%1; letter-spacing:1px;")
- .arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:9px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(ui::colors::AMBER).arg(ui::fonts::DATA_FAMILY));
vl->addWidget(routes_title);
- // Routes table
routes_table_ = new QTableWidget(panel);
routes_table_->setColumnCount(3);
routes_table_->setHorizontalHeaderLabels({"Route", "Value", "Status"});
@@ -213,14 +343,7 @@ QWidget* MaritimeScreen::build_left_panel() {
routes_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
routes_table_->horizontalHeader()->setStretchLastSection(true);
routes_table_->verticalHeader()->setVisible(false);
- routes_table_->setStyleSheet(QString("QTableWidget { background:#000; color:#ccc; gridline-color:#1a1a1a;"
- "font-family:%1; font-size:%2px; border:none; }"
- "QTableWidget::item { padding:4px 6px; }"
- "QTableWidget::item:selected { background:rgba(0,229,255,0.15); }"
- "QHeaderView::section { background:#0a0a0a; color:#666; font-weight:700;"
- "padding:4px 6px; border:1px solid #1a1a1a; font-family:%1; font-size:%2px; }")
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
+ routes_table_->setStyleSheet(table_ss());
connect(routes_table_, &QTableWidget::currentCellChanged, this,
[this](int row, int, int, int) { on_route_selected(row); });
vl->addWidget(routes_table_, 1);
@@ -228,50 +351,48 @@ QWidget* MaritimeScreen::build_left_panel() {
return panel;
}
-// ── Center: Map + Vessels Table ──────────────────────────────────────────────
+// ── Center Panel ─────────────────────────────────────────────────────────────
QWidget* MaritimeScreen::build_center_panel() {
auto* panel = new QWidget(this);
auto* vl = new QVBoxLayout(panel);
vl->setContentsMargins(0, 0, 0, 0);
vl->setSpacing(0);
- // Header
auto* header = new QWidget(panel);
header->setFixedHeight(36);
header->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(ui::colors::BG_RAISED, ui::colors::BORDER_DIM));
+ QString("background:%1; border-bottom:1px solid %2;")
+ .arg(C(ui::colors::BG_RAISED), C(ui::colors::BORDER_DIM)));
auto* hhl = new QHBoxLayout(header);
hhl->setContentsMargins(16, 0, 16, 0);
auto* title = new QLabel("VESSEL TRACKING — AIS FEED", header);
- title->setStyleSheet(QString("color:#00E5FF; font-size:%1px; font-weight:700; font-family:%2; letter-spacing:1px;")
- .arg(ui::fonts::TINY)
- .arg(ui::fonts::DATA_FAMILY));
+ title->setStyleSheet(
+ QString("color:%1; font-size:%2px; font-weight:700; font-family:%3; letter-spacing:1px;")
+ .arg(ui::colors::AMBER).arg(ui::fonts::TINY).arg(ui::fonts::DATA_FAMILY));
hhl->addWidget(title);
hhl->addStretch();
auto* ais_badge = new QLabel("AIS: STREAMING", header);
ais_badge->setStyleSheet(
- QString("color:#00FF00; font-size:9px; font-family:%1; font-weight:700;").arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:9px; font-family:%2; font-weight:700;")
+ .arg(ui::colors::POSITIVE).arg(ui::fonts::DATA_FAMILY));
hhl->addWidget(ais_badge);
vl->addWidget(header);
- // Splitter: map on top, table on bottom
auto* splitter = new QSplitter(Qt::Vertical, panel);
splitter->setHandleWidth(2);
- splitter->setStyleSheet("QSplitter::handle { background:#1a1a1a; }");
+ splitter->setStyleSheet(
+ QString("QSplitter::handle { background:%1; }").arg(ui::colors::BORDER_DIM));
- // ── World Map ───────────────────────────────────────────────────────────
map_widget_ = new fincept::ui::WorldMapWidget(splitter);
map_widget_->setMinimumHeight(160);
- // Plot preset ports and trade routes on the map
QVector<fincept::ui::MapPin> port_pins;
for (const auto& port : preset_ports())
- port_pins.append({port.lat, port.lng, port.name, QColor("#00E5FF"), 6.0});
+ port_pins.append({port.lat, port.lng, port.name, ui::colors::CYAN, 6.0});
map_widget_->set_pins(port_pins);
splitter->addWidget(map_widget_);
- // ── Vessels Table ───────────────────────────────────────────────────────
vessels_table_ = new QTableWidget(splitter);
vessels_table_->setColumnCount(9);
vessels_table_->setHorizontalHeaderLabels(
@@ -282,19 +403,9 @@ QWidget* MaritimeScreen::build_center_panel() {
vessels_table_->horizontalHeader()->setStretchLastSection(true);
vessels_table_->verticalHeader()->setVisible(false);
vessels_table_->setSortingEnabled(true);
- vessels_table_->setStyleSheet(QString("QTableWidget { background:#000; color:%1; gridline-color:#1a1a1a;"
- "font-family:%2; font-size:%3px; border:none; }"
- "QTableWidget::item { padding:4px 6px; }"
- "QTableWidget::item:selected { background:rgba(0,229,255,0.15); }"
- "QHeaderView::section { background:#0a0a0a; color:#00E5FF; font-weight:700;"
- "padding:6px 8px; border:1px solid #1a1a1a; font-family:%2; font-size:%3px; }"
- "QTableWidget::item:alternate { background:#050505; }")
- .arg(ui::colors::TEXT_PRIMARY)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
+ vessels_table_->setStyleSheet(table_ss());
splitter->addWidget(vessels_table_);
- // 40% map, 60% table
splitter->setStretchFactor(0, 4);
splitter->setStretchFactor(1, 6);
vl->addWidget(splitter, 1);
@@ -302,11 +413,10 @@ QWidget* MaritimeScreen::build_center_panel() {
return panel;
}
-// ── Right Panel: Search + Route Detail ───────────────────────────────────────
+// ── Right Panel ───────────────────────────────────────────────────────────────
QWidget* MaritimeScreen::build_right_panel() {
auto* panel = new QWidget(this);
panel->setFixedWidth(280);
- panel->setStyleSheet(QString("background:#000000; border-left:1px solid #1a1a1a;"));
auto* scroll = new QScrollArea(panel);
scroll->setWidgetResizable(true);
@@ -317,55 +427,34 @@ QWidget* MaritimeScreen::build_right_panel() {
vl->setContentsMargins(12, 12, 12, 12);
vl->setSpacing(10);
- auto input_style = QString("QLineEdit, QDoubleSpinBox { background:#0a0a0a; color:#ccc; border:1px solid #1a1a1a;"
- "font-family:%1; font-size:%2px; padding:6px 8px; border-radius:2px; }"
- "QLineEdit:focus, QDoubleSpinBox:focus { border-color:#00E5FF; }")
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL);
- auto label_style = QString("color:#666; font-size:8px; font-weight:700;"
- "font-family:%1; letter-spacing:1px;")
- .arg(ui::fonts::DATA_FAMILY);
-
- // ── Vessel Search ──
+ // ── Vessel Search ──────────────────────────────────────────────────────
auto* search_title = new QLabel("VESSEL SEARCH", content);
- search_title->setStyleSheet(QString("color:#00E5FF; font-size:9px; font-weight:700; font-family:%1;"
- "letter-spacing:1px; padding-bottom:4px; border-bottom:1px solid #1a1a1a;")
- .arg(ui::fonts::DATA_FAMILY));
+ search_title->setStyleSheet(section_label_ss());
vl->addWidget(search_title);
auto* imo_lbl = new QLabel("IMO NUMBER", content);
- imo_lbl->setStyleSheet(label_style);
+ imo_lbl->setStyleSheet(tiny_label_ss());
vl->addWidget(imo_lbl);
imo_edit_ = new QLineEdit(content);
imo_edit_->setPlaceholderText("e.g. 9344745");
- imo_edit_->setStyleSheet(input_style);
+ imo_edit_->setStyleSheet(input_ss());
connect(imo_edit_, &QLineEdit::returnPressed, this, &MaritimeScreen::on_search_vessel);
vl->addWidget(imo_edit_);
auto* track_btn = new QPushButton("TRACK", content);
track_btn->setCursor(Qt::PointingHandCursor);
- track_btn->setStyleSheet(QString("QPushButton { background:#00E5FF; color:#000; font-family:%1; font-size:%2px;"
- "font-weight:700; border:none; padding:6px; border-radius:2px; }"
- "QPushButton:hover { background:#00B8D4; }")
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
+ track_btn->setStyleSheet(btn_primary_ss());
connect(track_btn, &QPushButton::clicked, this, &MaritimeScreen::on_search_vessel);
vl->addWidget(track_btn);
auto* history_btn = new QPushButton("VOYAGE HISTORY", content);
history_btn->setCursor(Qt::PointingHandCursor);
- history_btn->setStyleSheet(
- QString("QPushButton { background:transparent; color:#FFC400; font-family:%1; font-size:%2px;"
- "font-weight:700; border:1px solid #FFC400; padding:6px; border-radius:2px; }"
- "QPushButton:hover { background:rgba(255,196,0,0.1); }")
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::fonts::SMALL));
+ history_btn->setStyleSheet(btn_outline_ss());
connect(history_btn, &QPushButton::clicked, this, [this]() {
auto imo = imo_edit_->text().trimmed();
- if (imo.isEmpty())
- return;
- status_label_->setText("LOADING HISTORY...");
+ if (imo.isEmpty()) return;
+ set_status("LOADING HISTORY...", ui::colors::WARNING);
MaritimeService::instance().get_vessel_history(imo);
});
vl->addWidget(history_btn);
@@ -373,134 +462,124 @@ QWidget* MaritimeScreen::build_right_panel() {
// Search result card
search_result_card_ = new QWidget(content);
search_result_card_->setVisible(false);
- search_result_card_->setStyleSheet("background:#0a0a0a; border:1px solid #00E5FF; border-radius:2px;");
auto* srvl = new QVBoxLayout(search_result_card_);
srvl->setContentsMargins(10, 10, 10, 10);
srvl->setSpacing(4);
- auto det_style = QString("color:#ccc; font-size:9px; font-family:%1;").arg(ui::fonts::DATA_FAMILY);
-
sr_name_ = new QLabel(search_result_card_);
sr_name_->setStyleSheet(
- QString("color:#00E5FF; font-size:11px; font-weight:700; font-family:%1;").arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:11px; font-weight:700; font-family:%2;")
+ .arg(ui::colors::INFO).arg(ui::fonts::DATA_FAMILY));
srvl->addWidget(sr_name_);
- sr_imo_ = new QLabel(search_result_card_);
- sr_imo_->setStyleSheet(det_style);
- srvl->addWidget(sr_imo_);
- sr_position_ = new QLabel(search_result_card_);
- sr_position_->setStyleSheet(det_style);
- srvl->addWidget(sr_position_);
- sr_speed_ = new QLabel(search_result_card_);
- sr_speed_->setStyleSheet(det_style);
- srvl->addWidget(sr_speed_);
- sr_from_ = new QLabel(search_result_card_);
- sr_from_->setStyleSheet(det_style);
- srvl->addWidget(sr_from_);
- sr_to_ = new QLabel(search_result_card_);
- sr_to_->setStyleSheet(det_style);
- srvl->addWidget(sr_to_);
+ sr_imo_ = new QLabel(search_result_card_); sr_imo_->setStyleSheet(detail_text_ss()); srvl->addWidget(sr_imo_);
+ sr_position_ = new QLabel(search_result_card_); sr_position_->setStyleSheet(detail_text_ss()); srvl->addWidget(sr_position_);
+ sr_speed_ = new QLabel(search_result_card_); sr_speed_->setStyleSheet(detail_text_ss()); srvl->addWidget(sr_speed_);
+ sr_from_ = new QLabel(search_result_card_); sr_from_->setStyleSheet(detail_text_ss()); srvl->addWidget(sr_from_);
+ sr_to_ = new QLabel(search_result_card_); sr_to_->setStyleSheet(detail_text_ss()); srvl->addWidget(sr_to_);
vl->addWidget(search_result_card_);
search_result_label_ = new QLabel(content);
search_result_label_->setStyleSheet(
- QString("color:%1; font-size:9px; font-family:%2;").arg(ui::colors::NEGATIVE).arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:9px; font-family:%2;")
+ .arg(ui::colors::NEGATIVE).arg(ui::fonts::DATA_FAMILY));
search_result_label_->setVisible(false);
vl->addWidget(search_result_label_);
- // ── Area Search ──
+ // ── Area Search ────────────────────────────────────────────────────────
vl->addSpacing(8);
auto* area_title = new QLabel("AREA SEARCH", content);
- area_title->setStyleSheet(search_title->styleSheet());
+ area_title->setStyleSheet(section_label_ss());
vl->addWidget(area_title);
auto make_coord = [&](const QString& label, double def_val) {
auto* lbl = new QLabel(label, content);
- lbl->setStyleSheet(label_style);
+ lbl->setStyleSheet(tiny_label_ss());
vl->addWidget(lbl);
auto* spin = new QDoubleSpinBox(content);
spin->setRange(-180, 180);
spin->setDecimals(4);
spin->setValue(def_val);
- spin->setStyleSheet(input_style);
+ spin->setStyleSheet(input_ss());
vl->addWidget(spin);
return spin;
};
- area_min_lat_ = make_coord("MIN LATITUDE", 18.5);
- area_max_lat_ = make_coord("MAX LATITUDE", 19.5);
+ area_min_lat_ = make_coord("MIN LATITUDE", 18.5);
+ area_max_lat_ = make_coord("MAX LATITUDE", 19.5);
area_min_lng_ = make_coord("MIN LONGITUDE", 72.0);
area_max_lng_ = make_coord("MAX LONGITUDE", 73.5);
auto* area_btn = new QPushButton("SEARCH AREA", content);
area_btn->setCursor(Qt::PointingHandCursor);
- area_btn->setStyleSheet(track_btn->styleSheet());
+ area_btn->setStyleSheet(btn_primary_ss());
connect(area_btn, &QPushButton::clicked, this, [this]() {
AreaSearchParams params;
params.min_lat = area_min_lat_->value();
params.max_lat = area_max_lat_->value();
params.min_lng = area_min_lng_->value();
params.max_lng = area_max_lng_->value();
- status_label_->setText("SEARCHING...");
+ set_status("SEARCHING...", ui::colors::WARNING);
MaritimeService::instance().search_vessels_by_area(params);
});
vl->addWidget(area_btn);
- // ── Route Detail ──
+ // ── Route Detail ───────────────────────────────────────────────────────
vl->addSpacing(8);
route_detail_ = new QWidget(content);
route_detail_->setVisible(false);
- route_detail_->setStyleSheet("background:#0a0a0a; border:1px solid #00ff00; border-left:3px solid #00ff00;"
- "border-radius:2px;");
auto* rdvl = new QVBoxLayout(route_detail_);
rdvl->setContentsMargins(10, 10, 10, 10);
rdvl->setSpacing(4);
auto* rd_title = new QLabel("SELECTED ROUTE", route_detail_);
rd_title->setStyleSheet(
- QString("color:#00ff00; font-size:9px; font-weight:700; font-family:%1; letter-spacing:1px;")
- .arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:9px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(ui::colors::AMBER).arg(ui::fonts::DATA_FAMILY));
rdvl->addWidget(rd_title);
rd_name_ = new QLabel(route_detail_);
rd_name_->setStyleSheet(
- QString("color:#00E5FF; font-size:11px; font-weight:700; font-family:%1;").arg(ui::fonts::DATA_FAMILY));
+ QString("color:%1; font-size:11px; font-weight:700; font-family:%2;")
+ .arg(ui::colors::INFO).arg(ui::fonts::DATA_FAMILY));
rdvl->addWidget(rd_name_);
- rd_value_ = new QLabel(route_detail_);
- rd_value_->setStyleSheet(det_style);
- rdvl->addWidget(rd_value_);
- rd_status_ = new QLabel(route_detail_);
- rd_status_->setStyleSheet(det_style);
- rdvl->addWidget(rd_status_);
- rd_vessels_ = new QLabel(route_detail_);
- rd_vessels_->setStyleSheet(det_style);
- rdvl->addWidget(rd_vessels_);
+ rd_value_ = new QLabel(route_detail_); rd_value_->setStyleSheet(detail_text_ss()); rdvl->addWidget(rd_value_);
+ rd_status_ = new QLabel(route_detail_); rd_status_->setStyleSheet(detail_text_ss()); rdvl->addWidget(rd_status_);
+ rd_vessels_ = new QLabel(route_detail_); rd_vessels_->setStyleSheet(detail_text_ss()); rdvl->addWidget(rd_vessels_);
vl->addWidget(route_detail_);
- // ── System Status ──
+ // ── System Status ──────────────────────────────────────────────────────
vl->addSpacing(8);
auto* sys_title = new QLabel("SYSTEM STATUS", content);
- sys_title->setStyleSheet(label_style);
+ sys_title->setStyleSheet(tiny_label_ss());
vl->addWidget(sys_title);
+ // Status items use semantic tokens
+ struct StatusItem { QString text; const ui::ColorToken& color; };
QVector<QPair<QString, QString>> statuses = {
- {"AIS Transponders", "#00E5FF"}, {"Satellite Imagery", "#00FF00"},
- {"Trade Routes: 10 corridors", "#00E5FF"}, {"Orbital Tracking: 13 SATs", "#9D4EDD"},
- {"Major Ports: 6 monitored", "#FFA500"},
+ {"AIS Transponders", ui::colors::INFO()},
+ {"Satellite Imagery", ui::colors::POSITIVE()},
+ {"Trade Routes: 10 corridors", ui::colors::INFO()},
+ {"Orbital Tracking: 13 SATs", ui::colors::AMBER()},
+ {"Major Ports: 6 monitored", ui::colors::WARNING()},
};
for (const auto& [text, color] : statuses) {
auto* lbl = new QLabel(QString::fromUtf8("\u25CF ") + text, content);
- lbl->setStyleSheet(QString("color:%1; font-size:8px; font-family:%2;").arg(color).arg(ui::fonts::DATA_FAMILY));
+ lbl->setStyleSheet(
+ QString("color:%1; font-size:8px; font-family:%2;")
+ .arg(color).arg(ui::fonts::DATA_FAMILY));
vl->addWidget(lbl);
}
- // Classified box
auto* cls = new QLabel("CLASSIFIED — AUTHORIZED PERSONNEL ONLY", content);
cls->setWordWrap(true);
cls->setAlignment(Qt::AlignCenter);
- cls->setStyleSheet(QString("color:#FFD700; font-size:8px; font-family:%1; font-weight:700;"
- "padding:8px; border:1px solid rgba(255,215,0,0.3);"
- "background:rgba(255,215,0,0.04); border-radius:2px;")
- .arg(ui::fonts::DATA_FAMILY));
+ cls->setStyleSheet(
+ QString("color:%1; font-size:8px; font-family:%2; font-weight:700;"
+ "padding:8px; border:1px solid %3; background:%4; border-radius:2px;")
+ .arg(ui::colors::WARNING)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::BORDER_MED)
+ .arg(ui::colors::BG_SURFACE));
vl->addWidget(cls);
vl->addStretch();
@@ -516,34 +595,27 @@ QWidget* MaritimeScreen::build_right_panel() {
QWidget* MaritimeScreen::build_status_bar() {
auto* bar = new QWidget(this);
bar->setFixedHeight(24);
- bar->setStyleSheet("background:#0a0a0a; border-top:1px solid #00ff00;");
auto* hl = new QHBoxLayout(bar);
hl->setContentsMargins(12, 0, 12, 0);
hl->setSpacing(16);
- auto s = QString("color:#666; font-size:8px; font-family:%1;").arg(ui::fonts::DATA_FAMILY);
- auto sv = QString("color:#ccc; font-size:8px; font-weight:700; font-family:%1;").arg(ui::fonts::DATA_FAMILY);
+ auto s = QString("color:%1; font-size:8px; font-family:%2;")
+ .arg(ui::colors::TEXT_TERTIARY).arg(ui::fonts::DATA_FAMILY);
+ auto sv = QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
+ .arg(ui::colors::TEXT_PRIMARY).arg(ui::fonts::DATA_FAMILY);
- auto* lbl1 = new QLabel("SOURCE:", bar);
- lbl1->setStyleSheet(s);
- auto* val1 = new QLabel("AIS FEED + FINCEPT API", bar);
- val1->setStyleSheet(sv);
- hl->addWidget(lbl1);
- hl->addWidget(val1);
+ auto* lbl1 = new QLabel("SOURCE:", bar); lbl1->setStyleSheet(s);
+ auto* val1 = new QLabel("AIS FEED + FINCEPT API", bar); val1->setStyleSheet(sv);
+ hl->addWidget(lbl1); hl->addWidget(val1);
- auto* lbl2 = new QLabel("REFRESH:", bar);
- lbl2->setStyleSheet(s);
- auto* val2 = new QLabel("5 MIN", bar);
- val2->setStyleSheet(sv);
- hl->addWidget(lbl2);
- hl->addWidget(val2);
+ auto* lbl2 = new QLabel("REFRESH:", bar); lbl2->setStyleSheet(s);
+ auto* val2 = new QLabel("5 MIN", bar); val2->setStyleSheet(sv);
+ hl->addWidget(lbl2); hl->addWidget(val2);
hl->addStretch();
status_label_ = new QLabel("READY", bar);
- status_label_->setStyleSheet(
- QString("color:#00FF00; font-size:8px; font-weight:700; font-family:%1;").arg(ui::fonts::DATA_FAMILY));
hl->addWidget(status_label_);
return bar;
@@ -555,11 +627,9 @@ void MaritimeScreen::populate_routes_table() {
for (int i = 0; i < routes_.size(); ++i) {
const auto& r = routes_[i];
auto* name_item = new QTableWidgetItem(r.name);
- name_item->setForeground(QColor("#00E5FF"));
+ name_item->setForeground(QBrush(QColor(ui::colors::INFO.get())));
routes_table_->setItem(i, 0, name_item);
-
routes_table_->setItem(i, 1, new QTableWidgetItem(r.value));
-
auto* status_item = new QTableWidgetItem(r.status.toUpper());
status_item->setForeground(route_status_color(r.status));
routes_table_->setItem(i, 2, status_item);
@@ -569,20 +639,17 @@ void MaritimeScreen::populate_routes_table() {
// ── Actions ──────────────────────────────────────────────────────────────────
void MaritimeScreen::on_load_vessels() {
- status_label_->setText("LOADING...");
- status_label_->setStyleSheet(
- QString("color:#FFD700; font-size:8px; font-weight:700; font-family:%1;").arg(ui::fonts::DATA_FAMILY));
- AreaSearchParams params; // defaults to Mumbai area
+ set_status("LOADING...", ui::colors::WARNING);
+ AreaSearchParams params;
MaritimeService::instance().search_vessels_by_area(params);
}
void MaritimeScreen::on_search_vessel() {
auto imo = imo_edit_->text().trimmed();
- if (imo.isEmpty())
- return;
+ if (imo.isEmpty()) return;
search_result_card_->setVisible(false);
search_result_label_->setVisible(false);
- status_label_->setText("TRACKING...");
+ set_status("TRACKING...", ui::colors::WARNING);
MaritimeService::instance().get_vessel_position(imo);
}
@@ -594,12 +661,11 @@ void MaritimeScreen::on_vessels_loaded(QVector<VesselData> vessels, int total) {
const auto& v = vessels[i];
auto* name_item = new QTableWidgetItem(v.name);
- name_item->setForeground(QColor("#00E5FF"));
+ name_item->setForeground(QBrush(QColor(ui::colors::INFO.get())));
vessels_table_->setItem(i, 0, name_item);
-
vessels_table_->setItem(i, 1, new QTableWidgetItem(v.imo));
- auto* lat = new QTableWidgetItem(QString::number(v.latitude, 'f', 4));
+ auto* lat = new QTableWidgetItem(QString::number(v.latitude, 'f', 4));
lat->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
vessels_table_->setItem(i, 2, lat);
@@ -618,7 +684,8 @@ void MaritimeScreen::on_vessels_loaded(QVector<VesselData> vessels, int total) {
vessels_table_->setItem(i, 6, new QTableWidgetItem(v.from_port));
vessels_table_->setItem(i, 7, new QTableWidgetItem(v.to_port));
- auto* prog = new QTableWidgetItem(v.route_progress > 0 ? QString("%1%").arg(v.route_progress, 0, 'f', 0) : "—");
+ auto* prog = new QTableWidgetItem(
+ v.route_progress > 0 ? QString("%1%").arg(v.route_progress, 0, 'f', 0) : "—");
prog->setTextAlignment(Qt::AlignCenter);
vessels_table_->setItem(i, 8, prog);
}
@@ -627,10 +694,7 @@ void MaritimeScreen::on_vessels_loaded(QVector<VesselData> vessels, int total) {
vessels_table_->resizeColumnsToContents();
update_intelligence(total);
update_map(vessels);
-
- status_label_->setText("READY");
- status_label_->setStyleSheet(
- QString("color:#00FF00; font-size:8px; font-weight:700; font-family:%1;").arg(ui::fonts::DATA_FAMILY));
+ set_status("READY", ui::colors::POSITIVE);
}
void MaritimeScreen::on_vessel_found(VesselData vessel) {
@@ -638,13 +702,12 @@ void MaritimeScreen::on_vessel_found(VesselData vessel) {
search_result_label_->setVisible(false);
sr_name_->setText(vessel.name);
sr_imo_->setText("IMO: " + vessel.imo);
- sr_position_->setText(QString("Position: %1, %2").arg(vessel.latitude, 0, 'f', 4).arg(vessel.longitude, 0, 'f', 4));
+ sr_position_->setText(
+ QString("Position: %1, %2").arg(vessel.latitude, 0, 'f', 4).arg(vessel.longitude, 0, 'f', 4));
sr_speed_->setText(QString("Speed: %1 kn").arg(vessel.speed, 0, 'f', 1));
sr_from_->setText("From: " + (vessel.from_port.isEmpty() ? "—" : vessel.from_port));
- sr_to_->setText("To: " + (vessel.to_port.isEmpty() ? "—" : vessel.to_port));
- status_label_->setText("READY");
- status_label_->setStyleSheet(
- QString("color:#00FF00; font-size:8px; font-weight:700; font-family:%1;").arg(ui::fonts::DATA_FAMILY));
+ sr_to_->setText("To: " + (vessel.to_port.isEmpty() ? "—" : vessel.to_port));
+ set_status("READY", ui::colors::POSITIVE);
}
void MaritimeScreen::on_error(const QString& context, const QString& message) {
@@ -653,9 +716,7 @@ void MaritimeScreen::on_error(const QString& context, const QString& message) {
search_result_label_->setText("Error: " + message);
search_result_label_->setVisible(true);
}
- status_label_->setText("ERROR");
- status_label_->setStyleSheet(
- QString("color:#FF0000; font-size:8px; font-weight:700; font-family:%1;").arg(ui::fonts::DATA_FAMILY));
+ set_status("ERROR", ui::colors::NEGATIVE);
LOG_ERROR("Maritime", QString("[%1] %2").arg(context, message));
}
@@ -669,30 +730,27 @@ void MaritimeScreen::on_route_selected(int row) {
rd_name_->setText(r.name);
rd_value_->setText("Trade Value: " + r.value);
rd_status_->setText("Status: " + r.status.toUpper());
- rd_status_->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2;")
- .arg(route_status_color(r.status).name())
- .arg(ui::fonts::DATA_FAMILY));
+ rd_status_->setStyleSheet(
+ QString("color:%1; font-size:9px; font-family:%2;")
+ .arg(route_status_color(r.status).name()).arg(ui::fonts::DATA_FAMILY));
rd_vessels_->setText(QString("Active Vessels: %1").arg(r.vessels));
}
void MaritimeScreen::update_intelligence(int vessel_count) {
vessel_count_label_->setText(QString("%1 VESSELS").arg(vessel_count));
- if (stat_vessels_)
- stat_vessels_->setText(QString::number(vessel_count));
- if (stat_displayed_)
- stat_displayed_->setText(QString::number(qMin(vessel_count, 500)));
+ if (stat_vessels_) stat_vessels_->setText(QString::number(vessel_count));
+ if (stat_displayed_) stat_displayed_->setText(QString::number(qMin(vessel_count, 500)));
}
void MaritimeScreen::update_map(const QVector<VesselData>& vessels) {
QVector<fincept::ui::MapPin> pins;
- // Preset ports (cyan)
for (const auto& port : preset_ports())
- pins.append({port.lat, port.lng, port.name, QColor("#00E5FF"), 6.0});
- // Vessel positions (green)
+ pins.append({port.lat, port.lng, port.name, ui::colors::CYAN, 6.0});
for (const auto& v : vessels) {
- if (v.latitude == 0.0 && v.longitude == 0.0)
- continue;
- pins.append({v.latitude, v.longitude, QString("%1 (%2)").arg(v.name, v.imo), QColor("#00FF00"), 4.0});
+ if (v.latitude == 0.0 && v.longitude == 0.0) continue;
+ pins.append({v.latitude, v.longitude,
+ QString("%1 (%2)").arg(v.name, v.imo),
+ ui::colors::POSITIVE, 4.0});
}
map_widget_->set_pins(pins);
map_widget_->fit_to_pins();
@@ -700,11 +758,10 @@ void MaritimeScreen::update_map(const QVector<VesselData>& vessels) {
void MaritimeScreen::on_vessel_history(QVector<VesselData> history) {
if (history.isEmpty()) {
- status_label_->setText("NO HISTORY");
+ set_status("NO HISTORY", ui::colors::WARNING);
return;
}
- // Plot history trail on map — oldest (dim) to newest (bright)
QVector<fincept::ui::MapPin> pins;
pins.reserve(history.size());
@@ -713,47 +770,40 @@ void MaritimeScreen::on_vessel_history(QVector<VesselData> history) {
for (int i = 0; i < total; ++i) {
const auto& h = history[i];
- if (h.latitude == 0.0 && h.longitude == 0.0)
- continue;
+ if (h.latitude == 0.0 && h.longitude == 0.0) continue;
- // Color gradient: oldest = dim orange, newest = bright yellow
double t = static_cast<double>(total - 1 - i) / std::max(total - 1, 1);
- int r = 255;
- int g = static_cast<int>(165 + t * 90); // 165 → 255
- int b = static_cast<int>(t * 100); // 0 → 100
- int alpha = static_cast<int>(100 + t * 155); // 100 → 255
- QColor color(r, g, b, alpha);
+ int r_c = 255;
+ int g_c = static_cast<int>(165 + t * 90);
+ int b_c = static_cast<int>(t * 100);
+ int alpha = static_cast<int>(100 + t * 155);
+ QColor color(r_c, g_c, b_c, alpha);
- // Smaller dots for older positions, bigger for recent
double radius = 3.0 + t * 4.0;
-
QString label = QString("%1 — %2 → %3 [%4]")
- .arg(vessel_name, h.from_port, h.to_port,
- h.last_updated.left(10)); // date only
-
+ .arg(vessel_name, h.from_port, h.to_port, h.last_updated.left(10));
pins.append({h.latitude, h.longitude, label, color, radius});
}
- // Add current position as a large bright marker
const auto& current = history.first();
if (current.latitude != 0.0 || current.longitude != 0.0) {
- pins.append({current.latitude, current.longitude, QString("%1 — CURRENT POSITION").arg(vessel_name),
- QColor("#00FF00"), 8.0});
+ pins.append({current.latitude, current.longitude,
+ QString("%1 — CURRENT POSITION").arg(vessel_name),
+ ui::colors::POSITIVE, 8.0});
}
map_widget_->set_pins(pins);
map_widget_->fit_to_pins();
- // Also update the vessels table with history data
vessels_table_->setSortingEnabled(false);
vessels_table_->setRowCount(history.size());
for (int i = 0; i < history.size(); ++i) {
const auto& v = history[i];
auto* name_item = new QTableWidgetItem(v.name);
- name_item->setForeground(QColor("#FFC400"));
+ name_item->setForeground(QBrush(QColor(ui::colors::WARNING.get())));
vessels_table_->setItem(i, 0, name_item);
vessels_table_->setItem(i, 1, new QTableWidgetItem(v.imo));
- auto* lat = new QTableWidgetItem(QString::number(v.latitude, 'f', 4));
+ auto* lat = new QTableWidgetItem(QString::number(v.latitude, 'f', 4));
lat->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
vessels_table_->setItem(i, 2, lat);
auto* lng = new QTableWidgetItem(QString::number(v.longitude, 'f', 4));
@@ -772,9 +822,9 @@ void MaritimeScreen::on_vessel_history(QVector<VesselData> history) {
vessels_table_->setSortingEnabled(true);
vessels_table_->resizeColumnsToContents();
- status_label_->setText(QString("HISTORY: %1 — %2 positions").arg(vessel_name).arg(total));
- status_label_->setStyleSheet(
- QString("color:#FFC400; font-size:8px; font-weight:700; font-family:%1;").arg(ui::fonts::DATA_FAMILY));
+ set_status(
+ QString("HISTORY: %1 — %2 positions").arg(vessel_name).arg(total),
+ ui::colors::WARNING);
LOG_INFO("Maritime", QString("Vessel history: %1 — %2 positions").arg(vessel_name).arg(total));
}
diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.h b/fincept-qt/src/screens/maritime/MaritimeScreen.h
index a89e7fc1b..cf05099b7 100644
--- a/fincept-qt/src/screens/maritime/MaritimeScreen.h
+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.h
@@ -1,8 +1,8 @@
// src/screens/maritime/MaritimeScreen.h
#pragma once
#include "services/maritime/MaritimeTypes.h"
+#include "ui/theme/Theme.h"
-#include <QComboBox>
#include <QDoubleSpinBox>
#include <QHideEvent>
#include <QLabel>
@@ -51,30 +51,42 @@ class MaritimeScreen : public QWidget {
void populate_routes_table();
void update_intelligence(int vessel_count);
void update_map(const QVector<services::maritime::VesselData>& vessels);
+ void apply_theme();
+ void set_status(const QString& text, const ui::ColorToken& color);
+
+ // Top bar widgets (needed for apply_theme)
+ QWidget* top_bar_ = nullptr;
+ QLabel* brand_label_ = nullptr;
+ QLabel* classified_label_= nullptr;
+
+ // Left / right panel roots
+ QWidget* left_panel_ = nullptr;
+ QWidget* right_panel_ = nullptr;
+ QWidget* status_bar_ = nullptr;
// Left panel
- QLabel* stat_vessels_ = nullptr;
- QLabel* stat_displayed_ = nullptr;
- QLabel* stat_routes_ = nullptr;
- QLabel* stat_volume_ = nullptr;
- QLabel* stat_ports_ = nullptr;
- QLabel* threat_badge_ = nullptr;
+ QLabel* stat_vessels_ = nullptr;
+ QLabel* stat_displayed_= nullptr;
+ QLabel* stat_routes_ = nullptr;
+ QLabel* stat_volume_ = nullptr;
+ QLabel* stat_ports_ = nullptr;
+ QLabel* threat_badge_ = nullptr;
// Center
- fincept::ui::WorldMapWidget* map_widget_ = nullptr;
- QTableWidget* vessels_table_ = nullptr;
- QTableWidget* routes_table_ = nullptr;
+ fincept::ui::WorldMapWidget* map_widget_ = nullptr;
+ QTableWidget* vessels_table_= nullptr;
+ QTableWidget* routes_table_ = nullptr;
// Right panel - search
- QLineEdit* imo_edit_ = nullptr;
- QLabel* search_result_label_ = nullptr;
- QWidget* search_result_card_ = nullptr;
- QLabel* sr_name_ = nullptr;
- QLabel* sr_imo_ = nullptr;
- QLabel* sr_position_ = nullptr;
- QLabel* sr_speed_ = nullptr;
- QLabel* sr_from_ = nullptr;
- QLabel* sr_to_ = nullptr;
+ QLineEdit* imo_edit_ = nullptr;
+ QLabel* search_result_label_= nullptr;
+ QWidget* search_result_card_ = nullptr;
+ QLabel* sr_name_ = nullptr;
+ QLabel* sr_imo_ = nullptr;
+ QLabel* sr_position_= nullptr;
+ QLabel* sr_speed_ = nullptr;
+ QLabel* sr_from_ = nullptr;
+ QLabel* sr_to_ = nullptr;
// Right panel - area search
QDoubleSpinBox* area_min_lat_ = nullptr;
@@ -84,18 +96,18 @@ class MaritimeScreen : public QWidget {
// Route detail
QWidget* route_detail_ = nullptr;
- QLabel* rd_name_ = nullptr;
- QLabel* rd_value_ = nullptr;
- QLabel* rd_status_ = nullptr;
- QLabel* rd_vessels_ = nullptr;
+ QLabel* rd_name_ = nullptr;
+ QLabel* rd_value_ = nullptr;
+ QLabel* rd_status_ = nullptr;
+ QLabel* rd_vessels_ = nullptr;
// Status
- QLabel* status_label_ = nullptr;
- QLabel* vessel_count_label_ = nullptr;
+ QLabel* status_label_ = nullptr;
+ QLabel* vessel_count_label_= nullptr;
// Timer
QTimer* refresh_timer_ = nullptr;
- bool first_show_ = true;
+ bool first_show_ = true;
// Data
QVector<services::maritime::TradeRoute> routes_;
diff --git a/fincept-qt/src/screens/markets/MarketPanel.cpp b/fincept-qt/src/screens/markets/MarketPanel.cpp
index dd06b43ea..dbe8d4a8e 100644
--- a/fincept-qt/src/screens/markets/MarketPanel.cpp
+++ b/fincept-qt/src/screens/markets/MarketPanel.cpp
@@ -75,7 +75,6 @@ MarketPanel::MarketPanel(const QString& title, const QStringList& symbols, bool
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed,
this, [this](const ui::ThemeTokens&) { refresh_theme(); });
refresh_theme();
- refresh();
}
void MarketPanel::refresh_theme() {
diff --git a/fincept-qt/src/screens/markets/MarketsScreen.cpp b/fincept-qt/src/screens/markets/MarketsScreen.cpp
index c1a05305b..1d6147ef6 100644
--- a/fincept-qt/src/screens/markets/MarketsScreen.cpp
+++ b/fincept-qt/src/screens/markets/MarketsScreen.cpp
@@ -133,7 +133,11 @@ void MarketsScreen::showEvent(QShowEvent* event) {
QWidget::showEvent(event);
if (auto_update_ && auto_refresh_timer_)
auto_refresh_timer_->start();
- refresh_all();
+ // Only refresh if no data yet or data is stale (> 5 min old)
+ bool needs_refresh = !last_refresh_time_.isValid() ||
+ last_refresh_time_.secsTo(QDateTime::currentDateTime()) >= kMinRefreshIntervalSec;
+ if (needs_refresh)
+ refresh_all();
}
void MarketsScreen::hideEvent(QHideEvent* event) {
@@ -324,6 +328,7 @@ void MarketsScreen::refresh_all() {
auto finish = [this, counter, remaining]() {
if (--(*remaining) > 0) return;
refresh_in_progress_ = false;
+ last_refresh_time_ = QDateTime::currentDateTime();
delete remaining;
counter->deleteLater();
if (status_label_) {
diff --git a/fincept-qt/src/screens/markets/MarketsScreen.h b/fincept-qt/src/screens/markets/MarketsScreen.h
index 362be2b8d..46baf3cd1 100644
--- a/fincept-qt/src/screens/markets/MarketsScreen.h
+++ b/fincept-qt/src/screens/markets/MarketsScreen.h
@@ -1,6 +1,7 @@
#pragma once
#include "screens/markets/MarketPanel.h"
+#include <QDateTime>
#include <QHideEvent>
#include <QLabel>
#include <QShowEvent>
@@ -29,6 +30,8 @@ class MarketsScreen : public QWidget {
bool refresh_in_progress_ = false;
bool auto_update_ = true;
int update_interval_ms_ = 600000; // 10 min default
+ QDateTime last_refresh_time_;
+ static constexpr int kMinRefreshIntervalSec = 300; // 5 min
QWidget* build_header();
QWidget* build_controls();
diff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp b/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
index 77f2bba01..3b376036c 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
@@ -842,4 +842,20 @@ void PortfolioScreen::load_demo_portfolio() {
svc.create_portfolio("Demo Portfolio", "Fincept User", "USD", "Sample portfolio for demonstration");
}
+QVariantMap PortfolioScreen::save_state() const {
+ return {
+ {"portfolio_id", selected_id_},
+ {"symbol", selected_symbol_}
+ };
+}
+
+void PortfolioScreen::restore_state(const QVariantMap& state) {
+ const QString id = state.value("portfolio_id").toString();
+ const QString sym = state.value("symbol").toString();
+ if (!id.isEmpty())
+ on_portfolio_selected(id);
+ if (!sym.isEmpty())
+ selected_symbol_ = sym;
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen.h b/fincept-qt/src/screens/portfolio/PortfolioScreen.h
index 6d95b7a07..d85f29b7a 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioScreen.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen.h
@@ -1,5 +1,6 @@
// src/screens/portfolio/PortfolioScreen.h
#pragma once
+#include "screens/IStatefulScreen.h"
#include "screens/portfolio/PortfolioTypes.h"
#include <QHideEvent>
@@ -25,11 +26,15 @@ class PortfolioFFNView;
class PortfolioAiPanel;
class PortfolioAgentPanel;
-class PortfolioScreen : public QWidget {
+class PortfolioScreen : public QWidget, public IStatefulScreen {
Q_OBJECT
public:
explicit PortfolioScreen(QWidget* parent = nullptr);
+ void restore_state(const QVariantMap& state) override;
+ QVariantMap save_state() const override;
+ QString state_key() const override { return "portfolio"; }
+
protected:
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
diff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp
index a972e5a74..3995b36be 100644
--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp
+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp
@@ -807,7 +807,7 @@ void ReportBuilderScreen::show_template_dialog() {
// Left: category + template list
auto* left = new QWidget;
- left->setMinimumWidth(320);
+ left->setMinimumWidth(280);
auto* lvl = new QVBoxLayout(left);
lvl->setContentsMargins(12, 12, 8, 12);
lvl->setSpacing(6);
diff --git a/fincept-qt/src/screens/settings/LlmConfigSection.cpp b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
index f4ef49412..08fb9858b 100644
--- a/fincept-qt/src/screens/settings/LlmConfigSection.cpp
+++ b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
@@ -224,7 +224,7 @@ QWidget* LlmConfigSection::build_provider_list_panel() {
delete_btn_->setStyleSheet("QPushButton{background:" + QString(ui::colors::BG_RAISED()) + ";color:" + QString(ui::colors::NEGATIVE()) + ";border:1px solid " + QString(ui::colors::BG_RAISED()) + ";"
"border-radius:3px;padding:5px 10px;}"
"QPushButton:hover{background:" + QString(ui::colors::BG_RAISED()) + ";}"
- "QPushButton:disabled{color:" + QString(ui::colors::BORDER_BRIGHT()) + ";border-color:#222;}");
+ "QPushButton:disabled{color:" + QString(ui::colors::BORDER_BRIGHT()) + ";border-color:" + QString(ui::colors::BORDER_MED()) + ";}");
connect(delete_btn_, &QPushButton::clicked, this, &LlmConfigSection::on_delete_provider);
btn_row->addWidget(add_btn_);
@@ -312,7 +312,7 @@ QWidget* LlmConfigSection::build_form_panel() {
fetch_btn_->setStyleSheet("QPushButton{background:" + QString(ui::colors::BG_RAISED()) + ";color:" + QString(ui::colors::AMBER()) + ";border:1px solid " + QString(ui::colors::BORDER_BRIGHT()) + ";"
"border-radius:3px;font-weight:600;}"
"QPushButton:hover{background:" + QString(ui::colors::BG_RAISED()) + ";}"
- "QPushButton:disabled{color:" + QString(ui::colors::TEXT_TERTIARY()) + ";border-color:#222;}");
+ "QPushButton:disabled{color:" + QString(ui::colors::TEXT_TERTIARY()) + ";border-color:" + QString(ui::colors::BORDER_MED()) + ";}");
connect(fetch_btn_, &QPushButton::clicked, this, &LlmConfigSection::on_fetch_models);
model_row->addWidget(fetch_btn_);
@@ -331,7 +331,7 @@ QWidget* LlmConfigSection::build_form_panel() {
auto* btn_row = new QHBoxLayout;
save_btn_ = new QPushButton("Save & Set Active");
save_btn_->setFixedHeight(34);
- save_btn_->setStyleSheet("QPushButton{background:" + QString(ui::colors::AMBER()) + ";color:#000;border:none;border-radius:4px;"
+ save_btn_->setStyleSheet("QPushButton{background:" + QString(ui::colors::AMBER()) + ";color:" + QString(ui::colors::BG_BASE()) + ";border:none;border-radius:4px;"
"font-weight:700;padding:0 16px;}"
"QPushButton:hover{background:" + QString(ui::colors::AMBER_DIM()) + ";}"
"QPushButton:disabled{background:" + QString(ui::colors::BORDER_BRIGHT()) + ";color:" + QString(ui::colors::TEXT_TERTIARY()) + ";}");
@@ -341,7 +341,7 @@ QWidget* LlmConfigSection::build_form_panel() {
test_btn_->setFixedHeight(34);
test_btn_->setStyleSheet("QPushButton{background:" + QString(ui::colors::BG_RAISED()) + ";color:" + QString(ui::colors::TEXT_PRIMARY()) + ";border:1px solid " + QString(ui::colors::BORDER_BRIGHT()) + ";"
"border-radius:4px;padding:0 16px;}"
- "QPushButton:hover{background:#222;}");
+ "QPushButton:hover{background:" + QString(ui::colors::BG_HOVER()) + ";}");
connect(test_btn_, &QPushButton::clicked, this, &LlmConfigSection::on_test_connection);
btn_row->addWidget(save_btn_);
@@ -904,7 +904,7 @@ QWidget* LlmConfigSection::build_profile_form_panel() {
auto* btn_row = new QHBoxLayout;
profile_save_btn_ = new QPushButton("SAVE PROFILE");
profile_save_btn_->setStyleSheet(
- "QPushButton{background:" + QString(ui::colors::AMBER()) + ";color:#000;border:none;padding:8px 20px;"
+ "QPushButton{background:" + QString(ui::colors::AMBER()) + ";color:" + QString(ui::colors::BG_BASE()) + ";border:none;padding:8px 20px;"
"font-weight:700;letter-spacing:1px;}"
"QPushButton:hover{background:" + QString(ui::colors::AMBER_DIM()) + ";}");
connect(profile_save_btn_, &QPushButton::clicked, this, &LlmConfigSection::on_save_profile);
diff --git a/fincept-qt/src/screens/settings/McpServersSection.cpp b/fincept-qt/src/screens/settings/McpServersSection.cpp
index e24995c57..455d65d5b 100644
--- a/fincept-qt/src/screens/settings/McpServersSection.cpp
+++ b/fincept-qt/src/screens/settings/McpServersSection.cpp
@@ -165,7 +165,7 @@ QWidget* McpServersSection::build_servers_tab() {
remove_btn_->setStyleSheet("QPushButton{background:" + QString(ui::colors::BG_RAISED()) + ";color:" + QString(ui::colors::NEGATIVE()) + ";border:1px solid " + QString(ui::colors::BG_RAISED()) + ";"
"border-radius:3px;padding:5px 10px;}"
"QPushButton:hover{background:" + QString(ui::colors::BG_RAISED()) + ";}"
- "QPushButton:disabled{color:" + QString(ui::colors::BORDER_BRIGHT()) + ";border-color:#222;}");
+ "QPushButton:disabled{color:" + QString(ui::colors::BORDER_BRIGHT()) + ";border-color:" + QString(ui::colors::BORDER_MED()) + ";}");
connect(remove_btn_, &QPushButton::clicked, this, &McpServersSection::on_remove_server);
btns->addWidget(add_btn_);
@@ -202,7 +202,7 @@ QWidget* McpServersSection::build_servers_tab() {
start_btn_->setStyleSheet("QPushButton{background:" + QString(ui::colors::BG_RAISED()) + ";color:" + QString(ui::colors::POSITIVE()) + ";border:1px solid " + QString(ui::colors::POSITIVE()) + ";"
"border-radius:4px;font-weight:600;padding:0 16px;}"
"QPushButton:hover{background:" + QString(ui::colors::BG_RAISED()) + ";}"
- "QPushButton:disabled{color:" + QString(ui::colors::BORDER_BRIGHT()) + ";border-color:#222;background:" + QString(ui::colors::BG_BASE()) + ";}");
+ "QPushButton:disabled{color:" + QString(ui::colors::BORDER_BRIGHT()) + ";border-color:" + QString(ui::colors::BORDER_MED()) + ";background:" + QString(ui::colors::BG_BASE()) + ";}");
connect(start_btn_, &QPushButton::clicked, this, &McpServersSection::on_start_server);
stop_btn_ = new QPushButton("■ Stop");
@@ -211,7 +211,7 @@ QWidget* McpServersSection::build_servers_tab() {
stop_btn_->setStyleSheet("QPushButton{background:" + QString(ui::colors::NEGATIVE()) + ";color:" + QString(ui::colors::NEGATIVE()) + ";border:1px solid " + QString(ui::colors::NEGATIVE()) + ";"
"border-radius:4px;font-weight:600;padding:0 16px;}"
"QPushButton:hover{background:" + QString(ui::colors::BG_RAISED()) + ";}"
- "QPushButton:disabled{color:" + QString(ui::colors::BORDER_BRIGHT()) + ";border-color:#222;background:" + QString(ui::colors::BG_BASE()) + ";}");
+ "QPushButton:disabled{color:" + QString(ui::colors::BORDER_BRIGHT()) + ";border-color:" + QString(ui::colors::BORDER_MED()) + ";background:" + QString(ui::colors::BG_BASE()) + ";}");
connect(stop_btn_, &QPushButton::clicked, this, &McpServersSection::on_stop_server);
server_btns->addWidget(start_btn_);
@@ -334,8 +334,8 @@ void McpServersSection::on_add_server() {
auto* btns = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
btns->setStyleSheet("QPushButton{background:" + QString(ui::colors::BG_RAISED()) + ";color:" + QString(ui::colors::TEXT_PRIMARY()) + ";border:1px solid " + QString(ui::colors::BORDER_BRIGHT()) + ";"
"border-radius:3px;padding:6px 16px;}"
- "QPushButton:hover{background:#222;}"
- "QPushButton[text='OK']{background:" + QString(ui::colors::AMBER()) + ";color:#000;border:none;}"
+ "QPushButton:hover{background:" + QString(ui::colors::BG_HOVER()) + ";}"
+ "QPushButton[text='OK']{background:" + QString(ui::colors::AMBER()) + ";color:" + QString(ui::colors::BG_BASE()) + ";border:none;}"
"QPushButton[text='OK']:hover{background:" + QString(ui::colors::AMBER_DIM()) + ";}");
connect(btns, &QDialogButtonBox::accepted, dlg, &QDialog::accept);
connect(btns, &QDialogButtonBox::rejected, dlg, &QDialog::reject);
@@ -407,7 +407,7 @@ void McpServersSection::load_servers() {
else if (cfg.status == ServerStatus::Error)
item->setForeground(QColor("" + QString(ui::colors::NEGATIVE()) + ""));
else
- item->setForeground(QColor("#888"));
+ item->setForeground(QColor(ui::colors::TEXT_SECONDARY.get()));
item->setToolTip(cfg.command + " " + cfg.args.join(' '));
server_list_->addItem(item);
@@ -438,7 +438,7 @@ void McpServersSection::load_tools() {
if (t.is_internal) {
server_item->setForeground(QColor("" + QString(ui::colors::AMBER()) + ""));
- cat_item->setForeground(QColor("#888"));
+ cat_item->setForeground(QColor(ui::colors::TEXT_SECONDARY.get()));
} else {
server_item->setForeground(QColor("" + QString(ui::colors::POSITIVE()) + ""));
cat_item->setForeground(QColor("" + QString(ui::colors::INFO()) + ""));
diff --git a/fincept-qt/src/screens/settings/SettingsScreen.cpp b/fincept-qt/src/screens/settings/SettingsScreen.cpp
index 8abff6160..6e05fbb1f 100644
--- a/fincept-qt/src/screens/settings/SettingsScreen.cpp
+++ b/fincept-qt/src/screens/settings/SettingsScreen.cpp
@@ -5,11 +5,16 @@
#include "ai_chat/LlmService.h"
#include "core/config/AppConfig.h"
+#include "core/events/EventBus.h"
+#include "core/config/ProfileManager.h"
#include "core/logging/Logger.h"
#include "services/notifications/NotificationService.h"
#include "screens/settings/LlmConfigSection.h"
#include "screens/settings/McpServersSection.h"
#include "storage/cache/CacheManager.h"
+#include "storage/StorageManager.h"
+#include "storage/sqlite/CacheDatabase.h"
+#include "storage/sqlite/Database.h"
#include "storage/repositories/DataSourceRepository.h"
#include "storage/repositories/SettingsRepository.h"
#include "storage/secure/SecureStorage.h"
@@ -19,12 +24,18 @@
#include <QCheckBox>
#include <QColorDialog>
#include <QComboBox>
+#include <QCoreApplication>
#include <QFontDatabase>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMap>
+#include <QMessageBox>
+#include <QSqlError>
+#include <QSqlQuery>
+#include <QSqlRecord>
+#include <QProcess>
#include <QPushButton>
#include <QScrollArea>
#include <QShowEvent>
@@ -148,6 +159,7 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {
sections_->addWidget(build_llm_config()); // 5
sections_->addWidget(build_mcp_servers()); // 6
sections_->addWidget(build_logging()); // 7
+ sections_->addWidget(build_profiles()); // 8
QList<QPushButton*> nav_btns;
auto make_btn = [&](const QString& text, int idx) {
@@ -178,6 +190,7 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {
make_btn("LLM Config", 5);
make_btn("MCP Servers", 6);
make_btn("Logging", 7);
+ make_btn("Profiles", 8);
first->setChecked(true);
@@ -907,7 +920,8 @@ QWidget* SettingsScreen::build_notifications() {
news_subopts_frame_ = new QFrame;
news_subopts_frame_->setObjectName("newsSuboptsFrame");
news_subopts_frame_->setStyleSheet(
- "#newsSuboptsFrame { border-left: 2px solid #374151; margin-left: 24px; padding-left: 8px; }");
+ QString("#newsSuboptsFrame { border-left: 2px solid %1; margin-left: 24px; padding-left: 8px; }")
+ .arg(ui::colors::BORDER_BRIGHT()));
auto* sub_vl = new QVBoxLayout(news_subopts_frame_);
sub_vl->setContentsMargins(0, 4, 0, 4);
sub_vl->setSpacing(4);
@@ -1034,6 +1048,153 @@ void SettingsScreen::save_provider_fields(const QString& provider_id,
// ── Storage & Cache ───────────────────────────────────────────────────────────
+static QString format_bytes(qint64 bytes) {
+ if (bytes < 1024) return QString::number(bytes) + " B";
+ if (bytes < 1048576) return QString::number(bytes / 1024.0, 'f', 1) + " KB";
+ if (bytes < 1073741824) return QString::number(bytes / 1048576.0, 'f', 1) + " MB";
+ return QString::number(bytes / 1073741824.0, 'f', 2) + " GB";
+}
+
+// Obsidian-standard panel with 34px header bar
+static QFrame* make_panel(const QString& title, QWidget* status_widget = nullptr) {
+ auto* panel = new QFrame;
+ panel->setStyleSheet(QString("QFrame{background:%1;border:1px solid %2;}")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+
+ auto* pvl = new QVBoxLayout(panel);
+ pvl->setContentsMargins(0, 0, 0, 0);
+ pvl->setSpacing(0);
+
+ auto* hdr = new QWidget;
+ hdr->setFixedHeight(34);
+ hdr->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* hhl = new QHBoxLayout(hdr);
+ hhl->setContentsMargins(12, 0, 12, 0);
+
+ auto* lbl = new QLabel(title);
+ lbl->setStyleSheet(QString("color:%1;font-weight:700;letter-spacing:0.5px;background:transparent;")
+ .arg(ui::colors::AMBER()));
+ hhl->addWidget(lbl);
+ hhl->addStretch();
+ if (status_widget) {
+ status_widget->setStyleSheet(status_widget->styleSheet() + "background:transparent;");
+ hhl->addWidget(status_widget);
+ }
+ pvl->addWidget(hdr);
+
+ return panel;
+}
+
+// Obsidian-standard data row: LABEL ······ VALUE, 26px, bottom border
+static QWidget* make_data_row(const QString& label_text, QLabel* value_lbl,
+ bool alt_bg = false) {
+ auto* row = new QWidget;
+ row->setFixedHeight(26);
+ row->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(alt_bg ? ui::colors::ROW_ALT() : "transparent",
+ ui::colors::BORDER_DIM()));
+
+ auto* hl = new QHBoxLayout(row);
+ hl->setContentsMargins(12, 0, 12, 0);
+ hl->setSpacing(0);
+
+ auto* lbl = new QLabel(label_text);
+ lbl->setStyleSheet(QString("color:%1;font-weight:600;letter-spacing:0.5px;background:transparent;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ hl->addWidget(lbl);
+ hl->addStretch();
+
+ value_lbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ value_lbl->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ hl->addWidget(value_lbl);
+
+ return row;
+}
+
+// Category row: NAME ··· COUNT ··· [CLEAR] — 26px, terminal table style
+static QWidget* make_category_row(const QString& name, QLabel* count_lbl,
+ QPushButton* clear_btn, bool alt) {
+ auto* row = new QWidget;
+ row->setFixedHeight(26);
+ row->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(alt ? ui::colors::ROW_ALT() : ui::colors::BG_BASE(),
+ ui::colors::BORDER_DIM()));
+
+ auto* hl = new QHBoxLayout(row);
+ hl->setContentsMargins(12, 0, 12, 0);
+ hl->setSpacing(8);
+
+ auto* lbl = new QLabel(name);
+ lbl->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_PRIMARY()));
+ hl->addWidget(lbl, 1);
+
+ count_lbl->setObjectName("cat_count");
+ count_lbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ count_lbl->setFixedWidth(70);
+ count_lbl->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;")
+ .arg(ui::colors::CYAN()));
+ hl->addWidget(count_lbl);
+
+ clear_btn->setFixedSize(56, 20);
+ clear_btn->setStyleSheet(
+ QString("QPushButton{background:rgba(220,38,38,0.1);color:%1;border:1px solid #7f1d1d;font-weight:700;}"
+ "QPushButton:hover{background:%1;color:%2;}")
+ .arg(ui::colors::NEGATIVE(), ui::colors::TEXT_PRIMARY()));
+ hl->addWidget(clear_btn);
+
+ return row;
+}
+
+// Group header row for category tables — amber dim label
+static QWidget* make_group_header(const QString& title) {
+ auto* row = new QWidget;
+ row->setFixedHeight(26);
+ row->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* hl = new QHBoxLayout(row);
+ hl->setContentsMargins(12, 0, 12, 0);
+ auto* lbl = new QLabel(title);
+ lbl->setStyleSheet(QString("color:%1;font-weight:700;letter-spacing:0.5px;background:transparent;")
+ .arg(ui::colors::AMBER_DIM()));
+ hl->addWidget(lbl);
+ return row;
+}
+
+// File action row: LABEL ··· SIZE ··· [BUTTON]
+static QWidget* make_file_action_row(const QString& name, QLabel* size_lbl,
+ QPushButton* btn, bool alt) {
+ auto* row = new QWidget;
+ row->setFixedHeight(26);
+ row->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(alt ? ui::colors::ROW_ALT() : ui::colors::BG_BASE(),
+ ui::colors::BORDER_DIM()));
+
+ auto* hl = new QHBoxLayout(row);
+ hl->setContentsMargins(12, 0, 12, 0);
+ hl->setSpacing(8);
+
+ auto* lbl = new QLabel(name);
+ lbl->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_PRIMARY()));
+ hl->addWidget(lbl, 1);
+
+ size_lbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ size_lbl->setFixedWidth(80);
+ size_lbl->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ hl->addWidget(size_lbl);
+
+ btn->setFixedSize(56, 20);
+ btn->setStyleSheet(
+ QString("QPushButton{background:rgba(220,38,38,0.1);color:%1;border:1px solid #7f1d1d;font-weight:700;}"
+ "QPushButton:hover{background:%1;color:%2;}")
+ .arg(ui::colors::NEGATIVE(), ui::colors::TEXT_PRIMARY()));
+ hl->addWidget(btn);
+
+ return row;
+}
+
QWidget* SettingsScreen::build_storage() {
auto* scroll = new QScrollArea;
scroll->setWidgetResizable(true);
@@ -1046,84 +1207,650 @@ QWidget* SettingsScreen::build_storage() {
auto* page = new QWidget;
auto* vl = new QVBoxLayout(page);
- vl->setContentsMargins(24, 24, 24, 24);
+ vl->setContentsMargins(14, 14, 14, 14);
vl->setSpacing(10);
- auto* t = new QLabel("STORAGE & CACHE");
+ // Title
+ auto* t = new QLabel("STORAGE & DATA MANAGEMENT");
t->setStyleSheet(section_title_ss());
vl->addWidget(t);
- vl->addWidget(make_sep());
- vl->addSpacing(8);
-
- // ── Cache overview card ───────────────────────────────────────────────────
- auto* t2 = new QLabel("CACHE OVERVIEW");
- t2->setStyleSheet(sub_title_ss());
- vl->addWidget(t2);
vl->addSpacing(4);
- auto* card = new QFrame;
- card->setStyleSheet(QString("QFrame{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, 12, 16, 12);
- cvl->setSpacing(8);
+ auto* info = new QLabel("Manage all persistent data, databases, and files. "
+ "Execute SQL queries directly against terminal databases.");
+ info->setWordWrap(true);
+ info->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_SECONDARY()));
+ vl->addWidget(info);
+ vl->addSpacing(10);
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // SECTION 1: DISK USAGE — stat boxes + data rows
+ // ═══════════════════════════════════════════════════════════════════════════
+ {
+ auto* refresh_lbl = new QLabel("REFRESH");
+ refresh_lbl->setStyleSheet(QString("color:%1;font-weight:600;cursor:pointer;")
+ .arg(ui::colors::AMBER()));
+ refresh_lbl->setCursor(Qt::PointingHandCursor);
+ refresh_lbl->installEventFilter(this); // for click
+
+ auto* panel = make_panel("DISK USAGE", refresh_lbl);
+ auto* body = new QWidget;
+ body->setStyleSheet("background:transparent;");
+ auto* bvl = new QVBoxLayout(body);
+ bvl->setContentsMargins(0, 0, 0, 0);
+ bvl->setSpacing(0);
+
+ // Stat boxes row
+ auto* stat_row = new QWidget;
+ stat_row->setStyleSheet("background:transparent;");
+ auto* shl = new QHBoxLayout(stat_row);
+ shl->setContentsMargins(10, 10, 10, 10);
+ shl->setSpacing(10);
+
+ auto make_stat_box = [&](const QString& label, QLabel*& val_out) {
+ auto* box = new QFrame;
+ box->setStyleSheet(QString("QFrame{background:%1;border:1px solid %2;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* bx = new QVBoxLayout(box);
+ bx->setContentsMargins(12, 12, 12, 14);
+ bx->setSpacing(4);
+ bx->setAlignment(Qt::AlignCenter);
+
+ val_out = new QLabel("—");
+ val_out->setAlignment(Qt::AlignCenter);
+ val_out->setStyleSheet(QString("color:%1;font-size:18px;font-weight:700;background:transparent;")
+ .arg(ui::colors::CYAN()));
+ bx->addWidget(val_out);
+
+ auto* ll = new QLabel(label);
+ ll->setAlignment(Qt::AlignCenter);
+ ll->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ bx->addWidget(ll);
+
+ shl->addWidget(box, 1);
+ };
- storage_count_ = new QLabel("—");
- storage_count_->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_PRIMARY()));
- cvl->addWidget(make_row("Cache Entries", storage_count_));
+ make_stat_box("MAIN DB", storage_main_db_);
+ make_stat_box("CACHE DB", storage_cache_db_);
+ make_stat_box("LOG FILES", storage_log_size_);
+ make_stat_box("WORKSPACES", storage_ws_size_);
+ make_stat_box("TOTAL", storage_total_size_);
+
+ bvl->addWidget(stat_row);
+
+ // Detail rows
+ storage_count_ = new QLabel("—");
+ bvl->addWidget(make_data_row("Cache Entries", storage_count_, false));
+
+ // Connect refresh click
+ connect(refresh_lbl, &QLabel::linkActivated, this, [this]() { refresh_storage_stats(); });
+ // Since QLabel doesn't emit linkActivated for plain text, use eventFilter
+ // Actually, let's just use a proper clickable mechanism:
+ auto* refresh_btn = new QPushButton("Refresh");
+ refresh_btn->setFixedSize(70, 22);
+ refresh_btn->setStyleSheet(
+ QString("QPushButton{background:rgba(217,119,6,0.1);color:%1;border:1px solid %2;font-weight:700;}"
+ "QPushButton:hover{background:%1;color:%3;}")
+ .arg(ui::colors::AMBER(), ui::colors::AMBER_DIM(), ui::colors::BG_BASE()));
+
+ connect(refresh_btn, &QPushButton::clicked, this, [this]() { refresh_storage_stats(); });
+
+ // Replace the header status widget
+ if (auto* hdr_layout = panel->findChild<QWidget*>()->findChild<QHBoxLayout*>()) {
+ hdr_layout->removeWidget(refresh_lbl);
+ refresh_lbl->deleteLater();
+ hdr_layout->addWidget(refresh_btn);
+ }
- auto* refresh_btn = new QPushButton("Refresh");
- refresh_btn->setFixedWidth(90);
- refresh_btn->setStyleSheet(btn_secondary_ss());
- connect(refresh_btn, &QPushButton::clicked, this, [this]() { refresh_storage_stats(); });
- cvl->addWidget(refresh_btn);
- vl->addWidget(card);
+ static_cast<QVBoxLayout*>(panel->layout())->addWidget(body);
+ vl->addWidget(panel);
+ }
- vl->addSpacing(12);
- vl->addWidget(make_sep());
- vl->addSpacing(8);
+ vl->addSpacing(10);
- // ── Clear all ─────────────────────────────────────────────────────────────
- auto* t3 = new QLabel("CLEAR CACHE");
- t3->setStyleSheet(sub_title_ss());
- vl->addWidget(t3);
- vl->addSpacing(4);
+ // ═══════════════════════════════════════════════════════════════════════════
+ // SECTION 2: DATA CATEGORIES — grouped table with counts + clear
+ // ═══════════════════════════════════════════════════════════════════════════
+ {
+ auto* panel = make_panel("DATA CATEGORIES");
+ auto* body = new QWidget;
+ body->setStyleSheet("background:transparent;");
+
+ storage_categories_ = new QVBoxLayout(body);
+ storage_categories_->setContentsMargins(0, 0, 0, 0);
+ storage_categories_->setSpacing(0);
+
+ // Table header
+ auto* th = new QWidget;
+ th->setFixedHeight(26);
+ th->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* thl = new QHBoxLayout(th);
+ thl->setContentsMargins(12, 0, 12, 0);
+ thl->setSpacing(8);
+ auto* th1 = new QLabel("CATEGORY");
+ th1->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ thl->addWidget(th1, 1);
+ auto* th2 = new QLabel("ENTRIES");
+ th2->setFixedWidth(70);
+ th2->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ th2->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ thl->addWidget(th2);
+ auto* th3 = new QLabel("ACTION");
+ th3->setFixedWidth(56);
+ th3->setAlignment(Qt::AlignCenter);
+ th3->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ thl->addWidget(th3);
+ storage_categories_->addWidget(th);
+
+ auto& sm = StorageManager::instance();
+ auto stats = sm.all_stats();
+
+ QString current_group;
+ int row_idx = 0;
+ for (const auto& cat : stats) {
+ if (cat.group != current_group) {
+ current_group = cat.group;
+ storage_categories_->addWidget(make_group_header(cat.group.toUpper()));
+ row_idx = 0;
+ }
- auto* clear_all = new QPushButton("Clear All Cache");
- clear_all->setStyleSheet(btn_danger_ss());
- connect(clear_all, &QPushButton::clicked, this, [this]() {
- CacheManager::instance().clear();
- refresh_storage_stats();
- LOG_INFO("Settings", "All cache cleared");
- });
- vl->addWidget(clear_all);
+ auto* count_lbl = new QLabel(QString::number(cat.count));
+ auto* clear_btn = new QPushButton("CLR");
- auto* note = new QLabel("Clears all cached market data, quotes, and news. "
- "Live data will be re-fetched on next access.");
- note->setWordWrap(true);
- note->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_SECONDARY()));
- vl->addWidget(note);
+ QString cat_id = cat.id;
+ QString cat_label = cat.label;
+ connect(clear_btn, &QPushButton::clicked, this, [this, cat_id, cat_label, count_lbl]() {
+ auto answer = QMessageBox::warning(
+ this, "Clear " + cat_label,
+ "Permanently delete all " + cat_label.toLower() + "?\n\n"
+ "This cannot be undone.",
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (answer != QMessageBox::Yes) return;
- vl->addSpacing(12);
- vl->addWidget(make_sep());
- vl->addSpacing(8);
+ auto r = StorageManager::instance().clear_category(cat_id);
+ if (r.is_ok()) {
+ count_lbl->setText("0");
+ LOG_INFO("Settings", "Cleared: " + cat_label);
+ } else {
+ QMessageBox::critical(this, "Error",
+ "Failed to clear " + cat_label + ":\n" +
+ QString::fromStdString(r.error()));
+ }
+ refresh_storage_stats();
+ });
- // ── Clear by category ─────────────────────────────────────────────────────
- auto* t4 = new QLabel("CLEAR BY CATEGORY");
- t4->setStyleSheet(sub_title_ss());
- vl->addWidget(t4);
- vl->addSpacing(4);
+ storage_categories_->addWidget(
+ make_category_row(cat.label, count_lbl, clear_btn, (row_idx % 2) == 1));
+ ++row_idx;
+ }
+
+ static_cast<QVBoxLayout*>(panel->layout())->addWidget(body);
+ vl->addWidget(panel);
+ }
+
+ vl->addSpacing(10);
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // SECTION 3: FILE & STATE MANAGEMENT
+ // ═══════════════════════════════════════════════════════════════════════════
+ {
+ auto* panel = make_panel("FILE & STATE MANAGEMENT");
+ auto* body = new QWidget;
+ body->setStyleSheet("background:transparent;");
+ auto* bvl = new QVBoxLayout(body);
+ bvl->setContentsMargins(0, 0, 0, 0);
+ bvl->setSpacing(0);
+
+ // Table header
+ auto* th = new QWidget;
+ th->setFixedHeight(26);
+ th->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* thl = new QHBoxLayout(th);
+ thl->setContentsMargins(12, 0, 12, 0);
+ thl->setSpacing(8);
+ auto* th1 = new QLabel("STORE");
+ th1->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ thl->addWidget(th1, 1);
+ auto* th2 = new QLabel("SIZE");
+ th2->setFixedWidth(80);
+ th2->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ th2->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ thl->addWidget(th2);
+ auto* th3 = new QLabel("ACTION");
+ th3->setFixedWidth(56);
+ th3->setAlignment(Qt::AlignCenter);
+ th3->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ thl->addWidget(th3);
+ bvl->addWidget(th);
+
+ // Helper to create file rows with confirmation
+ auto add_file_row = [&](const QString& name, QLabel* size_lbl,
+ const QString& confirm_title, const QString& confirm_msg,
+ std::function<void()> action, bool alt) {
+ auto* btn = new QPushButton("CLR");
+ connect(btn, &QPushButton::clicked, this, [this, confirm_title, confirm_msg, action]() {
+ auto answer = QMessageBox::warning(this, confirm_title, confirm_msg,
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (answer != QMessageBox::Yes) return;
+ action();
+ refresh_storage_stats();
+ });
+ bvl->addWidget(make_file_action_row(name, size_lbl, btn, alt));
+ };
+
+ auto* log_sz = new QLabel("—");
+ auto* ws_sz = new QLabel("—");
+ auto* qs_lbl = new QLabel("Registry");
+
+ add_file_row("Log Files", log_sz,
+ "Clear Logs", "Clear all application log files?\nCurrent log data will be lost.",
+ [this]() { StorageManager::instance().clear_log_files(); LOG_INFO("Settings", "Logs cleared"); },
+ false);
+
+ add_file_row("Workspace Files (.fwsp)", ws_sz,
+ "Delete Workspaces", "Delete all saved workspace files?\nThis cannot be undone.",
+ [this]() { StorageManager::instance().clear_workspace_files(); LOG_INFO("Settings", "Workspaces deleted"); },
+ true);
+
+ add_file_row("Window & UI State", qs_lbl,
+ "Reset UI State", "Reset all window positions, dock layouts, and perspectives?\n"
+ "Takes effect on next restart.",
+ [this]() { StorageManager::instance().clear_qsettings(); LOG_INFO("Settings", "QSettings cleared"); },
+ false);
+
+ // Cache subcategories as inline buttons
+ auto* cache_row = new QWidget;
+ cache_row->setFixedHeight(30);
+ cache_row->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(ui::colors::ROW_ALT(), ui::colors::BORDER_DIM()));
+ auto* chl = new QHBoxLayout(cache_row);
+ chl->setContentsMargins(12, 0, 12, 0);
+ chl->setSpacing(4);
+ auto* cache_label = new QLabel("Cache:");
+ cache_label->setStyleSheet(QString("color:%1;font-weight:600;background:transparent;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ chl->addWidget(cache_label);
+
+ static const QStringList CACHE_CATS = {"market_data", "news", "quotes", "charts", "general"};
+ for (const QString& cat : CACHE_CATS) {
+ auto* btn = new QPushButton(cat);
+ btn->setFixedHeight(18);
+ btn->setCursor(Qt::PointingHandCursor);
+ btn->setStyleSheet(
+ QString("QPushButton{background:%1;color:%2;border:1px solid %3;padding:0 6px;}"
+ "QPushButton:hover{color:%4;border-color:%4;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_SECONDARY(),
+ ui::colors::BORDER_DIM(), ui::colors::AMBER()));
+ connect(btn, &QPushButton::clicked, this, [this, cat]() {
+ CacheManager::instance().clear_category(cat);
+ refresh_storage_stats();
+ LOG_INFO("Settings", "Cache cleared: " + cat);
+ });
+ chl->addWidget(btn);
+ }
+ chl->addStretch();
+ bvl->addWidget(cache_row);
+
+ static_cast<QVBoxLayout*>(panel->layout())->addWidget(body);
+ vl->addWidget(panel);
+ }
+
+ vl->addSpacing(10);
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // SECTION 4: SQL CONSOLE — direct database access
+ // ═══════════════════════════════════════════════════════════════════════════
+ {
+ auto* panel = make_panel("SQL CONSOLE");
+ auto* body = new QWidget;
+ body->setStyleSheet("background:transparent;");
+ auto* bvl = new QVBoxLayout(body);
+ bvl->setContentsMargins(10, 8, 10, 8);
+ bvl->setSpacing(6);
+
+ auto* hint = new QLabel("Execute SQL queries directly against terminal databases. "
+ "Use SELECT to inspect data, or INSERT/UPDATE/DELETE to modify.");
+ hint->setWordWrap(true);
+ hint->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ bvl->addWidget(hint);
+
+ // DB selector + input + execute
+ auto* input_row = new QWidget;
+ input_row->setStyleSheet("background:transparent;");
+ auto* irl = new QHBoxLayout(input_row);
+ irl->setContentsMargins(0, 0, 0, 0);
+ irl->setSpacing(6);
+
+ sql_db_selector_ = new QComboBox;
+ sql_db_selector_->addItem("fincept.db", "main");
+ sql_db_selector_->addItem("cache.db", "cache");
+ sql_db_selector_->setFixedWidth(110);
+ sql_db_selector_->setStyleSheet(combo_ss());
+ irl->addWidget(sql_db_selector_);
+
+ sql_input_ = new QLineEdit;
+ sql_input_->setPlaceholderText("SELECT * FROM chat_sessions LIMIT 10");
+ sql_input_->setStyleSheet(input_ss());
+ irl->addWidget(sql_input_, 1);
+
+ auto* exec_btn = new QPushButton("EXEC");
+ exec_btn->setFixedSize(56, 28);
+ exec_btn->setStyleSheet(
+ QString("QPushButton{background:rgba(217,119,6,0.1);color:%1;border:1px solid %2;font-weight:700;}"
+ "QPushButton:hover{background:%1;color:%3;}")
+ .arg(ui::colors::AMBER(), ui::colors::AMBER_DIM(), ui::colors::BG_BASE()));
+ irl->addWidget(exec_btn);
+
+ bvl->addWidget(input_row);
+
+ // Status line
+ sql_status_ = new QLabel("Ready");
+ sql_status_->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ bvl->addWidget(sql_status_);
+
+ // Results area — scrollable table
+ auto* results_scroll = new QScrollArea;
+ results_scroll->setWidgetResizable(true);
+ results_scroll->setFixedHeight(200);
+ results_scroll->setStyleSheet(
+ QString("QScrollArea{border:1px solid %1;background:%2;}"
+ "QScrollBar:vertical{width:5px;background:transparent;}"
+ "QScrollBar::handle:vertical{background:%3;}"
+ "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}"
+ "QScrollBar:horizontal{height:5px;background:transparent;}"
+ "QScrollBar::handle:horizontal{background:%3;}"
+ "QScrollBar::add-line:horizontal,QScrollBar::sub-line:horizontal{width:0;}")
+ .arg(ui::colors::BORDER_DIM(), ui::colors::BG_BASE(), ui::colors::BORDER_MED()));
+
+ auto* results_widget = new QWidget;
+ results_widget->setStyleSheet("background:transparent;");
+ sql_results_layout_ = new QVBoxLayout(results_widget);
+ sql_results_layout_->setContentsMargins(0, 0, 0, 0);
+ sql_results_layout_->setSpacing(0);
+ sql_results_layout_->addStretch();
+ results_scroll->setWidget(results_widget);
+ bvl->addWidget(results_scroll);
+
+ // Quick-access table list buttons
+ auto* tables_row = new QWidget;
+ tables_row->setStyleSheet("background:transparent;");
+ auto* trhl = new QHBoxLayout(tables_row);
+ trhl->setContentsMargins(0, 0, 0, 0);
+ trhl->setSpacing(4);
+ auto* trl = new QLabel("Quick:");
+ trl->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ trhl->addWidget(trl);
+
+ static const QStringList QUICK_TABLES = {
+ "chat_sessions", "news_articles", "financial_notes", "portfolios",
+ "watchlists", "pt_portfolios", "workflows", "settings"
+ };
+ for (const QString& tbl : QUICK_TABLES) {
+ auto* btn = new QPushButton(tbl);
+ btn->setFixedHeight(18);
+ btn->setCursor(Qt::PointingHandCursor);
+ btn->setStyleSheet(
+ QString("QPushButton{background:%1;color:%2;border:1px solid %3;padding:0 4px;}"
+ "QPushButton:hover{color:%4;border-color:%4;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_SECONDARY(),
+ ui::colors::BORDER_DIM(), ui::colors::AMBER()));
+ connect(btn, &QPushButton::clicked, this, [this, tbl]() {
+ sql_input_->setText("SELECT * FROM " + tbl + " LIMIT 20");
+ sql_db_selector_->setCurrentIndex(0); // main db
+ });
+ trhl->addWidget(btn);
+ }
+ trhl->addStretch();
+ bvl->addWidget(tables_row);
+
+ // Execute handler
+ auto execute_sql = [this]() {
+ QString sql = sql_input_->text().trimmed();
+ if (sql.isEmpty()) return;
+
+ // Clear previous results
+ while (sql_results_layout_->count() > 0) {
+ auto* item = sql_results_layout_->takeAt(0);
+ if (item->widget()) item->widget()->deleteLater();
+ delete item;
+ }
+
+ bool use_cache = (sql_db_selector_->currentData().toString() == "cache");
+
+ // Determine if this is a write operation
+ QString upper = sql.toUpper().trimmed();
+ bool is_write = upper.startsWith("INSERT") || upper.startsWith("UPDATE") ||
+ upper.startsWith("DELETE") || upper.startsWith("DROP") ||
+ upper.startsWith("ALTER") || upper.startsWith("CREATE");
+
+ if (is_write) {
+ // Confirm write operations
+ auto answer = QMessageBox::warning(
+ this, "Execute Write Query",
+ "This will modify the database:\n\n" + sql + "\n\nContinue?",
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (answer != QMessageBox::Yes) {
+ sql_status_->setText("Cancelled");
+ sql_status_->setStyleSheet(QString("color:%1;background:transparent;")
+ .arg(ui::colors::WARNING()));
+ return;
+ }
+ }
+
+ // Execute
+ QSqlQuery query(use_cache
+ ? CacheDatabase::instance().raw_db()
+ : Database::instance().raw_db());
+ if (!query.exec(sql)) {
+ sql_status_->setText("Error: " + query.lastError().text());
+ sql_status_->setStyleSheet(QString("color:%1;background:transparent;")
+ .arg(ui::colors::NEGATIVE()));
+ LOG_ERROR("SQL Console", "Query failed: " + query.lastError().text());
+ return;
+ }
+
+ if (is_write) {
+ int affected = query.numRowsAffected();
+ sql_status_->setText(QString("OK — %1 row(s) affected").arg(affected));
+ sql_status_->setStyleSheet(QString("color:%1;background:transparent;")
+ .arg(ui::colors::POSITIVE()));
+ refresh_storage_stats();
+ LOG_INFO("SQL Console", QString("Write query: %1 rows affected").arg(affected));
+ return;
+ }
+
+ // Build results table for SELECT
+ auto rec = query.record();
+ int cols = rec.count();
+ if (cols == 0) {
+ sql_status_->setText("OK — no columns returned");
+ sql_status_->setStyleSheet(QString("color:%1;background:transparent;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ return;
+ }
+
+ // Column header
+ auto* hdr_row = new QWidget;
+ hdr_row->setFixedHeight(22);
+ hdr_row->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* hhl = new QHBoxLayout(hdr_row);
+ hhl->setContentsMargins(6, 0, 6, 0);
+ hhl->setSpacing(4);
+ for (int c = 0; c < cols; ++c) {
+ auto* cl = new QLabel(rec.fieldName(c));
+ cl->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;")
+ .arg(ui::colors::TEXT_DIM()));
+ hhl->addWidget(cl, 1);
+ }
+ sql_results_layout_->addWidget(hdr_row);
+
+ // Data rows (limit 100)
+ int row_count = 0;
+ while (query.next() && row_count < 100) {
+ auto* dr = new QWidget;
+ dr->setFixedHeight(20);
+ dr->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg((row_count % 2) ? ui::colors::ROW_ALT() : "transparent",
+ ui::colors::BORDER_DIM()));
+ auto* dhl = new QHBoxLayout(dr);
+ dhl->setContentsMargins(6, 0, 6, 0);
+ dhl->setSpacing(4);
+ for (int c = 0; c < cols; ++c) {
+ QString val = query.value(c).toString();
+ if (val.length() > 60) val = val.left(57) + "...";
+ auto* vl2 = new QLabel(val);
+ vl2->setStyleSheet(QString("color:%1;background:transparent;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ dhl->addWidget(vl2, 1);
+ }
+ sql_results_layout_->addWidget(dr);
+ ++row_count;
+ }
+
+ sql_status_->setText(QString("OK — %1 row(s) returned%2")
+ .arg(row_count).arg(row_count >= 100 ? " (limited to 100)" : ""));
+ sql_status_->setStyleSheet(QString("color:%1;background:transparent;")
+ .arg(ui::colors::POSITIVE()));
+ };
+
+ connect(exec_btn, &QPushButton::clicked, this, execute_sql);
+ connect(sql_input_, &QLineEdit::returnPressed, this, execute_sql);
+
+ static_cast<QVBoxLayout*>(panel->layout())->addWidget(body);
+ vl->addWidget(panel);
+ }
+
+ vl->addSpacing(10);
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // SECTION 5: DANGER ZONE
+ // ═══════════════════════════════════════════════════════════════════════════
+ {
+ auto* panel = new QFrame;
+ panel->setStyleSheet(QString("QFrame{background:%1;border:1px solid #7f1d1d;}")
+ .arg(ui::colors::BG_SURFACE()));
+ auto* pvl = new QVBoxLayout(panel);
+ pvl->setContentsMargins(0, 0, 0, 0);
+ pvl->setSpacing(0);
+
+ // Red header
+ auto* hdr = new QWidget;
+ hdr->setFixedHeight(34);
+ hdr->setStyleSheet("background:rgba(220,38,38,0.08);border-bottom:1px solid #7f1d1d;");
+ auto* hhl = new QHBoxLayout(hdr);
+ hhl->setContentsMargins(12, 0, 12, 0);
+ auto* hlbl = new QLabel("DANGER ZONE");
+ hlbl->setStyleSheet(QString("color:%1;font-weight:700;letter-spacing:0.5px;background:transparent;")
+ .arg(ui::colors::NEGATIVE()));
+ hhl->addWidget(hlbl);
+ pvl->addWidget(hdr);
- static const QStringList CACHE_CATS = {"market_data", "news", "quotes", "charts", "general"};
- for (const QString& cat : CACHE_CATS) {
- auto* btn = new QPushButton("Clear " + cat);
- btn->setStyleSheet(btn_secondary_ss());
- btn->setFixedWidth(200);
- connect(btn, &QPushButton::clicked, this, [this, cat]() {
- CacheManager::instance().clear_category(cat);
+ auto* body = new QWidget;
+ body->setStyleSheet("background:transparent;");
+ auto* bvl = new QVBoxLayout(body);
+ bvl->setContentsMargins(12, 10, 12, 10);
+ bvl->setSpacing(8);
+
+ // Clear all cache
+ auto* cache_row = new QWidget;
+ cache_row->setStyleSheet("background:transparent;");
+ auto* cr_hl = new QHBoxLayout(cache_row);
+ cr_hl->setContentsMargins(0, 0, 0, 0);
+ cr_hl->setSpacing(8);
+ auto* cache_desc = new QWidget;
+ auto* cd_vl = new QVBoxLayout(cache_desc);
+ cd_vl->setContentsMargins(0, 0, 0, 0);
+ cd_vl->setSpacing(2);
+ auto* cd1 = new QLabel("Clear All Cache");
+ cd1->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_PRIMARY()));
+ cd_vl->addWidget(cd1);
+ auto* cd2 = new QLabel("Delete all temporary cached data. Will be re-fetched on next access.");
+ cd2->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ cd_vl->addWidget(cd2);
+ cr_hl->addWidget(cache_desc, 1);
+ auto* cache_btn = new QPushButton("CLEAR CACHE");
+ cache_btn->setFixedSize(110, 26);
+ cache_btn->setStyleSheet(
+ QString("QPushButton{background:rgba(220,38,38,0.1);color:%1;border:1px solid #7f1d1d;font-weight:700;}"
+ "QPushButton:hover{background:%1;color:%2;}")
+ .arg(ui::colors::NEGATIVE(), ui::colors::TEXT_PRIMARY()));
+ connect(cache_btn, &QPushButton::clicked, this, [this]() {
+ auto answer = QMessageBox::warning(this, "Clear All Cache",
+ "Delete all temporary cached data?\nData will be re-fetched on next access.",
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (answer != QMessageBox::Yes) return;
+ CacheManager::instance().clear();
+ refresh_storage_stats();
+ LOG_INFO("Settings", "All cache cleared");
+ });
+ cr_hl->addWidget(cache_btn);
+ bvl->addWidget(cache_row);
+
+ bvl->addWidget(make_sep());
+
+ // Nuclear: clear ALL data
+ auto* nuke_row = new QWidget;
+ nuke_row->setStyleSheet("background:transparent;");
+ auto* nr_hl = new QHBoxLayout(nuke_row);
+ nr_hl->setContentsMargins(0, 0, 0, 0);
+ nr_hl->setSpacing(8);
+ auto* nuke_desc = new QWidget;
+ auto* nd_vl = new QVBoxLayout(nuke_desc);
+ nd_vl->setContentsMargins(0, 0, 0, 0);
+ nd_vl->setSpacing(2);
+ auto* nd1 = new QLabel("Clear ALL User Data");
+ nd1->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::NEGATIVE()));
+ nd_vl->addWidget(nd1);
+ auto* nd2 = new QLabel("Permanently delete all databases, files, cache, and UI state. OS keychain is preserved.");
+ nd2->setWordWrap(true);
+ nd2->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ nd_vl->addWidget(nd2);
+ nr_hl->addWidget(nuke_desc, 1);
+ auto* nuke_btn = new QPushButton("DELETE ALL");
+ nuke_btn->setFixedSize(110, 26);
+ nuke_btn->setStyleSheet(
+ QString("QPushButton{background:%1;color:%2;border:2px solid %1;font-weight:700;}"
+ "QPushButton:hover{background:%2;color:%3;}")
+ .arg(ui::colors::NEGATIVE(), ui::colors::TEXT_PRIMARY(), ui::colors::BG_BASE()));
+ connect(nuke_btn, &QPushButton::clicked, this, [this]() {
+ auto a1 = QMessageBox::critical(this, "Clear ALL User Data",
+ "WARNING: This will permanently delete ALL data:\n\n"
+ " Chat history, notes, reports, watchlists\n"
+ " Portfolios, transactions, paper trades\n"
+ " Workflows, dashboard layouts\n"
+ " News articles, RSS feeds, monitors\n"
+ " Data sources, MCP servers\n"
+ " Agent configs, LLM configs & profiles\n"
+ " App settings, credentials, key-value storage\n"
+ " All cache, log files, workspaces, UI state\n\n"
+ "OS keychain credentials are NOT affected.\n"
+ "This action CANNOT be undone.",
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (a1 != QMessageBox::Yes) return;
+
+ auto a2 = QMessageBox::critical(this, "Final Confirmation",
+ "ALL data will be permanently deleted.\nAre you absolutely sure?",
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (a2 != QMessageBox::Yes) return;
+
+ auto& sm = StorageManager::instance();
+ for (const auto& info : sm.all_stats())
+ sm.clear_category(info.id);
+ sm.clear_log_files();
+ sm.clear_workspace_files();
+ sm.clear_qsettings();
refresh_storage_stats();
- LOG_INFO("Settings", "Cache cleared: " + cat);
+ LOG_INFO("Settings", "ALL user data cleared");
});
- vl->addWidget(btn);
+ nr_hl->addWidget(nuke_btn);
+ bvl->addWidget(nuke_row);
+
+ pvl->addWidget(body);
+ vl->addWidget(panel);
}
vl->addStretch();
@@ -1132,12 +1859,51 @@ QWidget* SettingsScreen::build_storage() {
}
void SettingsScreen::refresh_storage_stats() {
+ auto& sm = StorageManager::instance();
+
+ // Stat boxes
+ if (storage_main_db_)
+ storage_main_db_->setText(format_bytes(sm.main_db_size()));
+ if (storage_cache_db_)
+ storage_cache_db_->setText(format_bytes(sm.cache_db_size()));
+ if (storage_log_size_)
+ storage_log_size_->setText(format_bytes(sm.log_files_size()));
+ if (storage_ws_size_)
+ storage_ws_size_->setText(format_bytes(sm.workspace_files_size()));
+ if (storage_total_size_)
+ storage_total_size_->setText(format_bytes(
+ sm.main_db_size() + sm.cache_db_size() + sm.log_files_size() + sm.workspace_files_size()));
+
+ // Cache entry count
if (storage_count_)
- storage_count_->setText(QString::number(CacheManager::instance().entry_count()) + " entries");
+ storage_count_->setText(QString::number(CacheManager::instance().entry_count()));
+
+ // Update per-category counts
+ if (storage_categories_) {
+ auto stats = sm.all_stats();
+ int stat_idx = 0;
+ for (int i = 0; i < storage_categories_->count() && stat_idx < stats.size(); ++i) {
+ auto* item = storage_categories_->itemAt(i);
+ if (!item || !item->widget()) continue;
+ // Find count label by object name
+ auto* count_lbl = item->widget()->findChild<QLabel*>("cat_count");
+ if (!count_lbl) continue;
+ count_lbl->setText(QString::number(stats[stat_idx].count));
+ ++stat_idx;
+ }
+ }
}
// ── Data Sources ──────────────────────────────────────────────────────────────
+// Transport type badge text from data source type string
+static QString ds_transport_badge(const QString& type) {
+ if (type == "websocket") return "WS";
+ if (type == "rest_api") return "REST";
+ if (type == "sql") return "SQL";
+ return type.left(4).toUpper();
+}
+
QWidget* SettingsScreen::build_data_sources() {
auto* scroll = new QScrollArea;
scroll->setWidgetResizable(true);
@@ -1150,102 +1916,344 @@ QWidget* SettingsScreen::build_data_sources() {
auto* page = new QWidget;
auto* vl = new QVBoxLayout(page);
- vl->setContentsMargins(24, 24, 24, 24);
- vl->setSpacing(0);
+ vl->setContentsMargins(14, 14, 14, 14);
+ vl->setSpacing(10);
+ // Title + Open Full Screen button
+ auto* title_row = new QWidget;
+ title_row->setStyleSheet("background:transparent;");
+ auto* trl = new QHBoxLayout(title_row);
+ trl->setContentsMargins(0, 0, 0, 0);
auto* t = new QLabel("DATA SOURCES");
t->setStyleSheet(section_title_ss());
- vl->addWidget(t);
- vl->addSpacing(4);
+ trl->addWidget(t);
+ trl->addStretch();
+
+ auto* open_full = new QPushButton("OPEN FULL SCREEN");
+ open_full->setFixedHeight(24);
+ open_full->setCursor(Qt::PointingHandCursor);
+ open_full->setStyleSheet(
+ QString("QPushButton{background:rgba(217,119,6,0.1);color:%1;border:1px solid %2;font-weight:700;padding:0 10px;}"
+ "QPushButton:hover{background:%1;color:%3;}")
+ .arg(ui::colors::AMBER(), ui::colors::AMBER_DIM(), ui::colors::BG_BASE()));
+ connect(open_full, &QPushButton::clicked, this, []() {
+ EventBus::instance().publish("nav.switch_screen", {{"screen", "data_sources"}});
+ });
+ trl->addWidget(open_full);
+ vl->addWidget(title_row);
- auto* info = new QLabel("Toggle which external data providers are active. "
- "Changes take effect immediately.");
+ auto* info = new QLabel("Quick management of configured connections. "
+ "For full browsing, adding, testing, and import/export use the full screen.");
info->setWordWrap(true);
info->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_SECONDARY()));
vl->addWidget(info);
- vl->addSpacing(16);
- vl->addWidget(make_sep());
- vl->addSpacing(16);
+ vl->addSpacing(4);
- // Load from repository
+ // ── Stats strip ──────────────────────────────────────────────────────────
auto result = DataSourceRepository::instance().list_all();
- if (!result.is_ok() || result.value().isEmpty()) {
- auto* empty = new QLabel("No data sources configured.\n"
- "Sources are seeded automatically at application startup.");
- empty->setWordWrap(true);
- empty->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_SECONDARY()));
- vl->addWidget(empty);
- vl->addStretch();
- scroll->setWidget(page);
- return scroll;
+ auto connections = result.is_ok() ? result.value() : QVector<DataSource>{};
+
+ int total = connections.size();
+ int active = 0;
+ QSet<QString> providers;
+ QMap<QString, int> cat_counts;
+ for (const auto& ds : connections) {
+ if (ds.enabled) ++active;
+ providers.insert(ds.provider);
+ QString cat = ds.category.isEmpty() ? "other" : ds.category;
+ cat_counts[cat]++;
}
- // Group by category
- QMap<QString, QVector<DataSource>> grouped;
- for (const auto& ds : result.value())
- grouped[ds.category.isEmpty() ? "General" : ds.category].append(ds);
-
- for (auto it = grouped.constBegin(); it != grouped.constEnd(); ++it) {
- // Category header
- auto* cat_lbl = new QLabel(it.key().toUpper());
- cat_lbl->setStyleSheet(sub_title_ss());
- vl->addWidget(cat_lbl);
- vl->addSpacing(6);
-
- for (const auto& ds : it.value()) {
- // Source card
- auto* card = new QFrame;
- card->setStyleSheet(QString("QFrame{background:%1;border:1px solid %2;border-radius:4px;}").arg(ui::colors::BG_SURFACE(),ui::colors::BORDER_DIM()));
- auto* cvl2 = new QVBoxLayout(card);
- cvl2->setContentsMargins(0, 0, 0, 0);
- cvl2->setSpacing(0);
-
- // Card header row
- auto* hdr = new QWidget;
- hdr->setFixedHeight(40);
- hdr->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;").arg(ui::colors::BG_RAISED(),ui::colors::BORDER_DIM()));
- auto* hhl = new QHBoxLayout(hdr);
- hhl->setContentsMargins(12, 0, 12, 0);
-
- auto* name_lbl = new QLabel(ds.display_name.isEmpty() ? ds.alias : ds.display_name);
- name_lbl->setStyleSheet(QString("color:%1;font-weight:600;background:transparent;").arg(ui::colors::TEXT_PRIMARY()));
- hhl->addWidget(name_lbl);
-
- // Type badge
- auto* type_badge = new QLabel(ds.type == "websocket" ? "WS" : "REST");
- type_badge->setStyleSheet(
- QString("color:%1;font-weight:700;background:%2;border:1px solid %3;border-radius:2px;padding:1px 5px;")
- .arg(ui::colors::TEXT_TERTIARY(), ui::colors::BG_RAISED(), ui::colors::BORDER_MED()));
- hhl->addWidget(type_badge);
- hhl->addStretch();
-
- // Enable toggle
- auto* toggle = new QCheckBox;
- toggle->setChecked(ds.enabled);
- toggle->setStyleSheet(check_ss());
- hhl->addWidget(toggle);
-
- // Wire toggle → repo
- QString source_id = ds.id;
- connect(toggle, &QCheckBox::toggled, this, [source_id](bool checked) {
- DataSourceRepository::instance().set_enabled(source_id, checked);
- LOG_INFO("DataSources", (checked ? "Enabled: " : "Disabled: ") + source_id);
- });
+ {
+ auto* stat_row = new QWidget;
+ stat_row->setStyleSheet("background:transparent;");
+ auto* shl = new QHBoxLayout(stat_row);
+ shl->setContentsMargins(0, 0, 0, 0);
+ shl->setSpacing(8);
+
+ auto make_stat = [&](const QString& label, int value, const QString& color) {
+ auto* box = new QFrame;
+ box->setStyleSheet(QString("QFrame{background:%1;border:1px solid %2;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* bx = new QVBoxLayout(box);
+ bx->setContentsMargins(10, 8, 10, 10);
+ bx->setSpacing(2);
+ bx->setAlignment(Qt::AlignCenter);
+
+ auto* val = new QLabel(QString::number(value));
+ val->setAlignment(Qt::AlignCenter);
+ val->setStyleSheet(QString("color:%1;font-size:18px;font-weight:700;background:transparent;").arg(color));
+ bx->addWidget(val);
+
+ auto* ll = new QLabel(label);
+ ll->setAlignment(Qt::AlignCenter);
+ ll->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_SECONDARY()));
+ bx->addWidget(ll);
+
+ shl->addWidget(box, 1);
+ };
- cvl2->addWidget(hdr);
+ make_stat("TOTAL", total, ui::colors::CYAN());
+ make_stat("ACTIVE", active, ui::colors::POSITIVE());
+ make_stat("INACTIVE", total - active, ui::colors::TEXT_DIM());
+ make_stat("PROVIDERS", providers.size(), ui::colors::AMBER());
+ vl->addWidget(stat_row);
+ }
- // Description (if any)
- if (!ds.description.isEmpty()) {
- auto* desc = new QLabel(ds.description);
- desc->setWordWrap(true);
- desc->setStyleSheet(QString("color:%1;padding:8px 12px;background:transparent;").arg(ui::colors::TEXT_TERTIARY()));
- cvl2->addWidget(desc);
- }
+ vl->addSpacing(6);
+
+ // ── Connections table ────────────────────────────────────────────────────
+ if (connections.isEmpty()) {
+ auto* empty_panel = make_panel("CONNECTIONS");
+ auto* empty_body = new QWidget;
+ empty_body->setStyleSheet("background:transparent;");
+ auto* evl = new QVBoxLayout(empty_body);
+ evl->setContentsMargins(12, 16, 12, 16);
+ auto* elbl = new QLabel("No data sources configured. Open the full Data Sources screen to browse and add connectors.");
+ elbl->setWordWrap(true);
+ elbl->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_SECONDARY()));
+ evl->addWidget(elbl);
+ static_cast<QVBoxLayout*>(empty_panel->layout())->addWidget(empty_body);
+ vl->addWidget(empty_panel);
+ } else {
+ // Group by category
+ QMap<QString, QVector<DataSource>> grouped;
+ for (const auto& ds : connections) {
+ QString cat = ds.category.isEmpty() ? "other" : ds.category;
+ grouped[cat].append(ds);
+ }
- vl->addWidget(card);
- vl->addSpacing(8);
+ auto* panel = make_panel("CONNECTIONS");
+ auto* body = new QWidget;
+ body->setStyleSheet("background:transparent;");
+ auto* bvl = new QVBoxLayout(body);
+ bvl->setContentsMargins(0, 0, 0, 0);
+ bvl->setSpacing(0);
+
+ // Table header
+ auto* th = new QWidget;
+ th->setFixedHeight(26);
+ th->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* thl = new QHBoxLayout(th);
+ thl->setContentsMargins(12, 0, 12, 0);
+ thl->setSpacing(6);
+
+ auto add_th = [&](const QString& text, int width = 0) {
+ auto* lbl = new QLabel(text);
+ lbl->setStyleSheet(QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ if (width > 0) { lbl->setFixedWidth(width); lbl->setAlignment(Qt::AlignCenter); }
+ thl->addWidget(lbl, width > 0 ? 0 : 1);
+ };
+ add_th("SOURCE");
+ add_th("TYPE", 44);
+ add_th("CATEGORY", 80);
+ add_th("ON", 30);
+ add_th("DEL", 30);
+ bvl->addWidget(th);
+
+ int row_idx = 0;
+ for (auto it = grouped.constBegin(); it != grouped.constEnd(); ++it) {
+ // Category group header
+ auto* grp = new QWidget;
+ grp->setFixedHeight(24);
+ grp->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* ghl = new QHBoxLayout(grp);
+ ghl->setContentsMargins(12, 0, 12, 0);
+ auto* glbl = new QLabel(it.key().toUpper() + QString(" (%1)").arg(it.value().size()));
+ glbl->setStyleSheet(QString("color:%1;font-weight:700;letter-spacing:0.5px;background:transparent;")
+ .arg(ui::colors::AMBER_DIM()));
+ ghl->addWidget(glbl);
+ bvl->addWidget(grp);
+
+ for (const auto& ds : it.value()) {
+ auto* row = new QWidget;
+ row->setFixedHeight(26);
+ row->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg((row_idx % 2) ? ui::colors::ROW_ALT() : ui::colors::BG_BASE(),
+ ui::colors::BORDER_DIM()));
+
+ auto* rhl = new QHBoxLayout(row);
+ rhl->setContentsMargins(12, 0, 12, 0);
+ rhl->setSpacing(6);
+
+ // Name
+ QString name = ds.display_name.isEmpty() ? ds.alias : ds.display_name;
+ auto* name_lbl = new QLabel(name);
+ name_lbl->setStyleSheet(QString("color:%1;background:transparent;").arg(
+ ds.enabled ? ui::colors::TEXT_PRIMARY() : ui::colors::TEXT_TERTIARY()));
+ rhl->addWidget(name_lbl, 1);
+
+ // Type badge
+ auto* badge = new QLabel(ds_transport_badge(ds.type));
+ badge->setFixedWidth(44);
+ badge->setAlignment(Qt::AlignCenter);
+ badge->setStyleSheet(QString("color:%1;font-weight:700;background:%2;border:1px solid %3;")
+ .arg(ui::colors::TEXT_TERTIARY(), ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ rhl->addWidget(badge);
+
+ // Category
+ auto* cat_lbl = new QLabel(ds.category.isEmpty() ? "—" : ds.category);
+ cat_lbl->setFixedWidth(80);
+ cat_lbl->setAlignment(Qt::AlignCenter);
+ cat_lbl->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_TERTIARY()));
+ rhl->addWidget(cat_lbl);
+
+ // Enable toggle
+ auto* toggle = new QCheckBox;
+ toggle->setChecked(ds.enabled);
+ toggle->setFixedWidth(30);
+ toggle->setStyleSheet(check_ss());
+ QString source_id = ds.id;
+ connect(toggle, &QCheckBox::toggled, this, [source_id, name_lbl](bool checked) {
+ DataSourceRepository::instance().set_enabled(source_id, checked);
+ name_lbl->setStyleSheet(QString("color:%1;background:transparent;").arg(
+ checked ? ui::colors::TEXT_PRIMARY() : ui::colors::TEXT_TERTIARY()));
+ LOG_INFO("DataSources", (checked ? "Enabled: " : "Disabled: ") + source_id);
+ });
+ rhl->addWidget(toggle);
+
+ // Delete button
+ auto* del_btn = new QPushButton("X");
+ del_btn->setFixedSize(22, 18);
+ del_btn->setCursor(Qt::PointingHandCursor);
+ del_btn->setStyleSheet(
+ QString("QPushButton{background:transparent;color:%1;border:none;font-weight:700;}"
+ "QPushButton:hover{color:%2;}")
+ .arg(ui::colors::TEXT_DIM(), ui::colors::NEGATIVE()));
+ connect(del_btn, &QPushButton::clicked, this, [this, source_id, name, row]() {
+ auto answer = QMessageBox::warning(this, "Delete Connection",
+ "Delete connection \"" + name + "\"?\n\nThis cannot be undone.",
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (answer != QMessageBox::Yes) return;
+
+ DataSourceRepository::instance().remove(source_id);
+ row->hide();
+ LOG_INFO("DataSources", "Deleted: " + source_id);
+ });
+ rhl->addWidget(del_btn);
+
+ bvl->addWidget(row);
+ ++row_idx;
+ }
}
- vl->addSpacing(8);
+
+ static_cast<QVBoxLayout*>(panel->layout())->addWidget(body);
+ vl->addWidget(panel);
+ }
+
+ vl->addSpacing(10);
+
+ // ── Bulk actions ─────────────────────────────────────────────────────────
+ {
+ auto* panel = make_panel("BULK ACTIONS");
+ auto* body = new QWidget;
+ body->setStyleSheet("background:transparent;");
+ auto* bvl = new QVBoxLayout(body);
+ bvl->setContentsMargins(10, 8, 10, 8);
+ bvl->setSpacing(6);
+
+ auto* btn_row = new QWidget;
+ btn_row->setStyleSheet("background:transparent;");
+ auto* brhl = new QHBoxLayout(btn_row);
+ brhl->setContentsMargins(0, 0, 0, 0);
+ brhl->setSpacing(8);
+
+ // Enable all
+ auto* enable_all = new QPushButton("ENABLE ALL");
+ enable_all->setFixedHeight(24);
+ enable_all->setStyleSheet(
+ QString("QPushButton{background:rgba(22,163,74,0.1);color:%1;border:1px solid %1;font-weight:700;padding:0 10px;}"
+ "QPushButton:hover{background:%1;color:%2;}")
+ .arg(ui::colors::POSITIVE(), ui::colors::BG_BASE()));
+ connect(enable_all, &QPushButton::clicked, this, [this]() {
+ auto r = DataSourceRepository::instance().list_all();
+ if (!r.is_ok()) return;
+ for (const auto& ds : r.value())
+ DataSourceRepository::instance().set_enabled(ds.id, true);
+ LOG_INFO("DataSources", "All sources enabled");
+ // Rebuild section to reflect changes
+ if (sections_) {
+ auto* old = sections_->widget(4);
+ auto* fresh = build_data_sources();
+ sections_->insertWidget(4, fresh);
+ sections_->removeWidget(old);
+ old->deleteLater();
+ sections_->setCurrentIndex(4);
+ }
+ });
+ brhl->addWidget(enable_all);
+
+ // Disable all
+ auto* disable_all = new QPushButton("DISABLE ALL");
+ disable_all->setFixedHeight(24);
+ disable_all->setStyleSheet(
+ QString("QPushButton{background:rgba(220,38,38,0.1);color:%1;border:1px solid #7f1d1d;font-weight:700;padding:0 10px;}"
+ "QPushButton:hover{background:%1;color:%2;}")
+ .arg(ui::colors::NEGATIVE(), ui::colors::TEXT_PRIMARY()));
+ connect(disable_all, &QPushButton::clicked, this, [this]() {
+ auto answer = QMessageBox::warning(this, "Disable All",
+ "Disable all data source connections?",
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (answer != QMessageBox::Yes) return;
+ auto r = DataSourceRepository::instance().list_all();
+ if (!r.is_ok()) return;
+ for (const auto& ds : r.value())
+ DataSourceRepository::instance().set_enabled(ds.id, false);
+ LOG_INFO("DataSources", "All sources disabled");
+ if (sections_) {
+ auto* old = sections_->widget(4);
+ auto* fresh = build_data_sources();
+ sections_->insertWidget(4, fresh);
+ sections_->removeWidget(old);
+ old->deleteLater();
+ sections_->setCurrentIndex(4);
+ }
+ });
+ brhl->addWidget(disable_all);
+
+ // Delete all
+ auto* delete_all = new QPushButton("DELETE ALL");
+ delete_all->setFixedHeight(24);
+ delete_all->setStyleSheet(
+ QString("QPushButton{background:%1;color:%2;border:2px solid %2;font-weight:700;padding:0 10px;}"
+ "QPushButton:hover{background:%2;color:%3;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::NEGATIVE(), ui::colors::TEXT_PRIMARY()));
+ connect(delete_all, &QPushButton::clicked, this, [this]() {
+ auto answer = QMessageBox::critical(this, "Delete All Connections",
+ "Permanently delete ALL data source connections?\n\n"
+ "This cannot be undone. You can re-add them from the full Data Sources screen.",
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (answer != QMessageBox::Yes) return;
+
+ auto r = DataSourceRepository::instance().list_all();
+ if (!r.is_ok()) return;
+ for (const auto& ds : r.value())
+ DataSourceRepository::instance().remove(ds.id);
+ LOG_INFO("DataSources", "All connections deleted");
+ if (sections_) {
+ auto* old = sections_->widget(4);
+ auto* fresh = build_data_sources();
+ sections_->insertWidget(4, fresh);
+ sections_->removeWidget(old);
+ old->deleteLater();
+ sections_->setCurrentIndex(4);
+ }
+ });
+ brhl->addWidget(delete_all);
+
+ brhl->addStretch();
+ bvl->addWidget(btn_row);
+
+ auto* note = new QLabel("For adding new connections, testing connectivity, and import/export, "
+ "use the full Data Sources screen.");
+ note->setWordWrap(true);
+ note->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ bvl->addWidget(note);
+
+ static_cast<QVBoxLayout*>(panel->layout())->addWidget(body);
+ vl->addWidget(panel);
}
vl->addStretch();
@@ -1426,4 +2434,130 @@ QWidget* SettingsScreen::build_logging() {
return scroll;
}
+// ── Profiles ──────────────────────────────────────────────────────────────────
+QWidget* SettingsScreen::build_profiles() {
+ auto* scroll = new QScrollArea;
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+
+ auto* page = new QWidget;
+ auto* vl = new QVBoxLayout(page);
+ vl->setContentsMargins(24, 20, 24, 20);
+ vl->setSpacing(16);
+
+ auto* title = new QLabel("Profiles");
+ title->setStyleSheet(section_title_ss());
+ vl->addWidget(title);
+
+ auto* desc = new QLabel(
+ "Each profile has its own isolated database, credentials, logs and workspaces.\n"
+ "Launch the terminal with --profile <name> to open a specific profile.\n"
+ "Different profiles can run simultaneously — useful for separate trading accounts.");
+ desc->setWordWrap(true);
+ desc->setStyleSheet(label_ss());
+ vl->addWidget(desc);
+ vl->addWidget(make_sep());
+
+ // Active profile display
+ auto& pm = ProfileManager::instance();
+ auto* active_lbl = new QLabel(
+ QString("Active profile: <b>%1</b>").arg(pm.active()));
+ active_lbl->setStyleSheet(label_ss());
+ vl->addWidget(active_lbl);
+
+ // Profile list
+ auto* list_title = new QLabel("All profiles");
+ list_title->setStyleSheet(sub_title_ss());
+ vl->addWidget(list_title);
+
+ auto* list_widget = new QWidget;
+ auto* list_vl = new QVBoxLayout(list_widget);
+ list_vl->setContentsMargins(0, 0, 0, 0);
+ list_vl->setSpacing(6);
+
+ const QStringList profiles = pm.list_profiles();
+ for (const QString& name : profiles) {
+ auto* row = new QWidget;
+ auto* hl = new QHBoxLayout(row);
+ hl->setContentsMargins(0, 0, 0, 0);
+ hl->setSpacing(8);
+
+ auto* name_lbl = new QLabel(name);
+ name_lbl->setStyleSheet(label_ss());
+ hl->addWidget(name_lbl, 1);
+
+ if (name == pm.active()) {
+ auto* badge = new QLabel("ACTIVE");
+ badge->setStyleSheet(QString("color:%1;font-weight:700;font-size:10px;"
+ "background:transparent;")
+ .arg(ui::colors::AMBER()));
+ hl->addWidget(badge);
+ } else {
+ // "Switch" launches a new process with --profile <name> then quits this one
+ auto* switch_btn = new QPushButton("Switch");
+ switch_btn->setFixedWidth(72);
+ switch_btn->setStyleSheet(btn_secondary_ss());
+ connect(switch_btn, &QPushButton::clicked, this, [name]() {
+ const QString exe = QCoreApplication::applicationFilePath();
+ QProcess::startDetached(exe, {"--profile", name});
+ QCoreApplication::quit();
+ });
+ hl->addWidget(switch_btn);
+ }
+ list_vl->addWidget(row);
+ }
+ vl->addWidget(list_widget);
+ vl->addWidget(make_sep());
+
+ // Create new profile
+ auto* new_title = new QLabel("Create new profile");
+ new_title->setStyleSheet(sub_title_ss());
+ vl->addWidget(new_title);
+
+ auto* new_row = new QWidget;
+ auto* new_hl = new QHBoxLayout(new_row);
+ new_hl->setContentsMargins(0, 0, 0, 0);
+ new_hl->setSpacing(8);
+
+ auto* name_input = new QLineEdit;
+ name_input->setPlaceholderText("profile-name (alphanumeric, - and _ only)");
+ name_input->setStyleSheet(input_ss());
+ new_hl->addWidget(name_input, 1);
+
+ auto* create_btn = new QPushButton("Create & Switch");
+ create_btn->setStyleSheet(btn_primary_ss());
+ connect(create_btn, &QPushButton::clicked, this, [name_input]() {
+ const QString name = name_input->text().trimmed().toLower();
+ if (name.isEmpty()) return;
+ ProfileManager::instance().create_profile(name);
+ const QString exe = QCoreApplication::applicationFilePath();
+ QProcess::startDetached(exe, {"--profile", name});
+ QCoreApplication::quit();
+ });
+ new_hl->addWidget(create_btn);
+ vl->addWidget(new_row);
+
+ auto* hint = new QLabel(
+ "Creating a profile sets up a fresh data directory. "
+ "The app will restart with the new profile active.");
+ hint->setWordWrap(true);
+ hint->setStyleSheet(label_ss());
+ vl->addWidget(hint);
+
+ vl->addStretch();
+ scroll->setWidget(page);
+ return scroll;
+}
+
+QVariantMap SettingsScreen::save_state() const {
+ return {{"section", sections_ ? sections_->currentIndex() : 0}};
+}
+
+void SettingsScreen::restore_state(const QVariantMap& state) {
+ if (!sections_) return;
+ const int idx = state.value("section", 0).toInt();
+ if (idx >= 0 && idx < sections_->count())
+ sections_->setCurrentIndex(idx);
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/settings/SettingsScreen.h b/fincept-qt/src/screens/settings/SettingsScreen.h
index eb2e5ae3b..50eea6e1a 100644
--- a/fincept-qt/src/screens/settings/SettingsScreen.h
+++ b/fincept-qt/src/screens/settings/SettingsScreen.h
@@ -1,4 +1,5 @@
#pragma once
+#include "screens/IStatefulScreen.h"
#include <QCheckBox>
#include <QComboBox>
#include <QFrame>
@@ -8,6 +9,7 @@
#include <QPushButton>
#include <QStackedWidget>
#include <QTimer>
+#include <QVBoxLayout>
#include <QWidget>
namespace fincept::screens {
@@ -15,11 +17,15 @@ namespace fincept::screens {
/// Full-featured settings screen.
/// Sections: Credentials | Appearance | Notifications | Storage & Cache |
/// Data Sources | LLM Config | MCP Servers | Logging
-class SettingsScreen : public QWidget {
+class SettingsScreen : public QWidget, public IStatefulScreen {
Q_OBJECT
public:
explicit SettingsScreen(QWidget* parent = nullptr);
+ void restore_state(const QVariantMap& state) override;
+ QVariantMap save_state() const override;
+ QString state_key() const override { return "settings"; }
+
protected:
void showEvent(QShowEvent* e) override;
@@ -36,6 +42,7 @@ class SettingsScreen : public QWidget {
QWidget* build_llm_config();
QWidget* build_mcp_servers();
QWidget* build_logging();
+ QWidget* build_profiles();
// ── Shared layout helper ──────────────────────────────────────────────────
static QWidget* make_row(const QString& label, QWidget* control, const QString& description = {});
@@ -82,7 +89,18 @@ class SettingsScreen : public QWidget {
QFrame* news_subopts_frame_ = nullptr;
// ── Storage state ─────────────────────────────────────────────────────────
- QLabel* storage_count_ = nullptr;
+ QLabel* storage_count_ = nullptr;
+ QLabel* storage_main_db_ = nullptr;
+ QLabel* storage_cache_db_ = nullptr;
+ QLabel* storage_log_size_ = nullptr;
+ QLabel* storage_ws_size_ = nullptr;
+ QLabel* storage_total_size_ = nullptr;
+ QVBoxLayout* storage_categories_ = nullptr;
+ // SQL console
+ QLineEdit* sql_input_ = nullptr;
+ QComboBox* sql_db_selector_ = nullptr;
+ QLabel* sql_status_ = nullptr;
+ QVBoxLayout* sql_results_layout_ = nullptr;
// ── Logging state ─────────────────────────────────────────────────────────
QComboBox* log_global_level_ = nullptr;
diff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
index 549591838..bb1e09787 100644
--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
@@ -87,7 +87,7 @@ void WatchlistScreen::build_ui() {
splitter->addWidget(build_sidebar());
splitter->addWidget(build_main_panel());
- splitter->setSizes({220, 800});
+ splitter->setStretchFactor(0, 0);
splitter->setStretchFactor(1, 1);
root->addWidget(splitter);
@@ -97,7 +97,8 @@ void WatchlistScreen::build_ui() {
QWidget* WatchlistScreen::build_sidebar() {
auto* panel = new QWidget;
- panel->setFixedWidth(220);
+ panel->setMinimumWidth(180);
+ panel->setMaximumWidth(280);
panel->setStyleSheet(QString("background: %1; border-right: 1px solid %2;").arg(BG_SURFACE, BORDER_DIM));
auto* lay = new QVBoxLayout(panel);
diff --git a/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp b/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp
index 6f2bd77b8..5870bc7b2 100644
--- a/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp
+++ b/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp
@@ -202,21 +202,37 @@ static QVector<HDXDataset> parse_hdx_results(const QString& output) {
auto json_str = python::extract_json(output);
auto doc = QJsonDocument::fromJson(json_str.toUtf8());
QVector<HDXDataset> datasets;
- auto arr = doc.object()["datasets"].toArray();
- if (arr.isEmpty())
+
+ // Script returns: {"success": true, "data": {"datasets": [...]}}
+ // Try unwrapping the data envelope first, then fall back to bare array/object
+ auto root = doc.object();
+ QJsonArray arr;
+ if (root.contains("data")) {
+ auto data = root["data"].toObject();
+ arr = data["datasets"].toArray();
+ } else if (root.contains("datasets")) {
+ arr = root["datasets"].toArray();
+ } else {
arr = doc.array();
+ }
+
datasets.reserve(arr.size());
for (const auto& v : arr) {
auto o = v.toObject();
HDXDataset d;
- d.id = o["id"].toString();
- d.title = o["title"].toString();
+ d.id = o["id"].toString();
+ d.title = o["title"].toString();
d.organization = o["organization"].toString();
- d.notes = o["notes"].toString();
- d.date = o["dataset_date"].toString();
+ d.notes = o["notes"].toString();
+ d.date = o["dataset_date"].toString();
d.num_resources = o["num_resources"].toInt();
- for (const auto& t : o["tags"].toArray())
- d.tags.append(t.toObject()["name"].toString());
+ // Tags in summary are plain strings; in full detail they are objects with "name"
+ for (const auto& t : o["tags"].toArray()) {
+ if (t.isString())
+ d.tags.append(t.toString());
+ else
+ d.tags.append(t.toObject()["name"].toString());
+ }
d.raw = o;
datasets.append(d);
}
@@ -224,7 +240,7 @@ static QVector<HDXDataset> parse_hdx_results(const QString& output) {
}
void GeopoliticsService::search_hdx_conflicts() {
- run_python("hdx_data.py", {"search_conflict"}, "hdx_conflicts", [this](bool ok, const QString& out) {
+ run_python("hdx_data.py", {"search_conflict", "", "20"}, "hdx_conflicts", [this](bool ok, const QString& out) {
if (!ok) {
emit error_occurred("hdx_conflicts", out);
return;
@@ -234,7 +250,7 @@ void GeopoliticsService::search_hdx_conflicts() {
}
void GeopoliticsService::search_hdx_humanitarian() {
- run_python("hdx_data.py", {"search_humanitarian"}, "hdx_humanitarian", [this](bool ok, const QString& out) {
+ run_python("hdx_data.py", {"search_humanitarian", "", "20"}, "hdx_humanitarian", [this](bool ok, const QString& out) {
if (!ok) {
emit error_occurred("hdx_humanitarian", out);
return;
@@ -264,7 +280,8 @@ void GeopoliticsService::search_hdx_by_topic(const QString& topic) {
}
void GeopoliticsService::search_hdx_advanced(const QString& query) {
- run_python("hdx_data.py", {"advanced_search", query}, "hdx_search", [this](bool ok, const QString& out) {
+ // Use search_datasets for free-text queries (advanced_search expects key:value pairs)
+ run_python("hdx_data.py", {"search_datasets", query, "20"}, "hdx_search", [this](bool ok, const QString& out) {
if (!ok) {
emit error_occurred("hdx_search", out);
return;
diff --git a/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp b/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp
index e6e57f930..055c1436b 100644
--- a/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp
+++ b/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp
@@ -2,56 +2,39 @@
#include "core/logging/Logger.h"
#include "mcp/McpService.h"
+#include "network/http/HttpClient.h"
+#include "python/PythonRunner.h"
#include "services/workflow/AuditLogger.h"
#include "services/workflow/ConfirmationService.h"
#include "services/workflow/NodeRegistry.h"
#include "services/workflow/RiskManager.h"
#include "trading/ExchangeService.h"
+#include <QCryptographicHash>
#include <QDateTime>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonArray>
+#include <QJsonDocument>
#include <QPointer>
+#include <QRegularExpression>
+#include <QSqlDatabase>
+#include <QSqlError>
+#include <QSqlQuery>
+#include <QSqlRecord>
#include <QtConcurrent/QtConcurrent>
+using fincept::python::PythonRunner;
+using fincept::python::PythonResult;
+using fincept::python::extract_json;
+
namespace fincept::workflow {
// ── Market Data Bridge ─────────────────────────────────────────────────
void wire_market_data_bridges(NodeRegistry& registry) {
- // Get Quote — uses MarketDataService via PythonRunner
- auto* quote_def = const_cast<NodeTypeDef*>(registry.find("market.get_quote"));
- if (quote_def) {
- quote_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,
- std::function<void(bool, QJsonValue, QString)> cb) {
- QString symbol = params.value("symbol").toString();
- if (symbol.isEmpty()) {
- cb(false, {}, "Symbol is required");
- return;
- }
- // Delegate to MarketDataService (async, returns via callback)
- // For now, return placeholder — real wiring requires MarketDataService::fetch_quote
- QJsonObject out;
- out["symbol"] = symbol;
- out["source"] = params.value("source").toString("yahoo");
- out["status"] = "pending_integration";
- cb(true, out, {});
- LOG_DEBUG("MarketBridge", QString("Quote requested: %1").arg(symbol));
- };
- }
-
- // Historical Data
- auto* hist_def = const_cast<NodeTypeDef*>(registry.find("market.get_historical"));
- if (hist_def) {
- hist_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,
- std::function<void(bool, QJsonValue, QString)> cb) {
- QString symbol = params.value("symbol").toString();
- QJsonObject out;
- out["symbol"] = symbol;
- out["period"] = params.value("period").toString("1y");
- out["interval"] = params.value("interval").toString("1d");
- out["status"] = "pending_integration";
- cb(true, out, {});
- };
- }
+ // market.get_quote and market.get_historical already have real Python-backed
+ // executors from MarketDataNodes.cpp — do NOT overwrite them.
// Crypto Price — uses ExchangeService (Kraken public API, no key needed)
auto* crypto_price_def = const_cast<NodeTypeDef*>(registry.find("market.get_crypto_price"));
@@ -89,21 +72,9 @@ void wire_market_data_bridges(NodeRegistry& registry) {
};
}
- // Wire remaining market data nodes with placeholder executors
- for (const auto& id : {"market.get_depth", "market.get_stats", "market.get_fundamentals", "market.get_economics",
- "market.get_news"}) {
- auto* def = const_cast<NodeTypeDef*>(registry.find(id));
- if (def && !def->execute) {
- def->execute = [id_str = QString(id)](const QJsonObject& params, const QVector<QJsonValue>&,
- std::function<void(bool, QJsonValue, QString)> cb) {
- QJsonObject out;
- out["node_type"] = id_str;
- out["symbol"] = params.value("symbol").toString();
- out["status"] = "pending_integration";
- cb(true, out, {});
- };
- }
- }
+ // market.get_news already has a real executor from MarketDataNodes.cpp.
+ // Remaining market nodes (depth, stats, fundamentals, economics) are wired
+ // in MarketDataNodes.cpp directly — no stub overwrite needed here.
LOG_INFO("ServiceBridges", "Market data bridges wired");
}
@@ -155,22 +126,8 @@ void wire_trading_bridges(NodeRegistry& registry) {
};
}
- // Wire remaining trading nodes with placeholder executors
- for (const auto& id :
- {"trading.cancel_order", "trading.modify_order", "trading.get_orders", "trading.get_positions",
- "trading.get_holdings", "trading.get_balance", "trading.close_position"}) {
- auto* def = const_cast<NodeTypeDef*>(registry.find(id));
- if (def && !def->execute) {
- def->execute = [id_str = QString(id)](const QJsonObject& params, const QVector<QJsonValue>&,
- std::function<void(bool, QJsonValue, QString)> cb) {
- QJsonObject out;
- out["node_type"] = id_str;
- out["broker"] = params.value("broker").toString("paper");
- out["status"] = "pending_integration";
- cb(true, out, {});
- };
- }
- }
+ // Remaining trading nodes are wired elsewhere or via the fallback pass-through
+ // in wire_all_bridges — no "pending_integration" stubs here.
LOG_INFO("ServiceBridges", "Trading bridges wired");
}
@@ -178,45 +135,9 @@ void wire_trading_bridges(NodeRegistry& registry) {
// ── Agent Bridge ───────────────────────────────────────────────────────
void wire_agent_bridges(NodeRegistry& registry) {
- auto* agent_def = const_cast<NodeTypeDef*>(registry.find("agent.single"));
- if (agent_def) {
- agent_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
- std::function<void(bool, QJsonValue, QString)> cb) {
- QString agent_type = params.value("agent_type").toString("general");
- QString prompt = params.value("prompt").toString();
-
- // Build context from inputs
- QJsonObject context;
- if (!inputs.isEmpty())
- context["input"] = inputs[0];
- context["agent_type"] = agent_type;
- context["prompt"] = prompt;
-
- // Delegate to AgentService — placeholder for now
- QJsonObject out;
- out["agent_type"] = agent_type;
- out["prompt"] = prompt;
- out["status"] = "pending_integration";
- out["response"] = "Agent execution requires AgentService integration";
- cb(true, out, {});
- LOG_DEBUG("AgentBridge", QString("Agent requested: %1").arg(agent_type));
- };
- }
-
- // Wire multi-agent and mediator similarly
- for (const auto& id : {"agent.multi", "agent.mediator"}) {
- auto* def = const_cast<NodeTypeDef*>(registry.find(id));
- if (def && !def->execute) {
- def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,
- std::function<void(bool, QJsonValue, QString)> cb) {
- QJsonObject out;
- out["mode"] = params.value("mode").toString("sequential");
- out["status"] = "pending_integration";
- cb(true, out, {});
- };
- }
- }
-
+ // agent.run and agent.tool_picker have real executors from AgentNodes.cpp.
+ // agent.single/agent.multi/agent.mediator are legacy stubs — leave their
+ // executors to the fallback pass-through in wire_all_bridges if still null.
LOG_INFO("ServiceBridges", "Agent bridges wired");
}
@@ -225,7 +146,7 @@ void wire_agent_bridges(NodeRegistry& registry) {
static void wire_utility_bridges(NodeRegistry& registry) {
// ── HTTP Request — via HttpClient ──────────────────────────────
auto* http_def = const_cast<NodeTypeDef*>(registry.find("utility.http_request"));
- if (http_def) {
+ if (http_def && !http_def->execute) {
http_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
QString url = params.value("url").toString();
@@ -235,21 +156,38 @@ static void wire_utility_bridges(NodeRegistry& registry) {
return;
}
- // Build output — real HttpClient integration point
- QJsonObject out;
- out["url"] = url;
- out["method"] = method;
- out["status"] = "pending_http_integration";
- if (!inputs.isEmpty())
- out["input"] = inputs[0];
- cb(true, out, {});
+ auto& http = HttpClient::instance();
+ if (method == "POST") {
+ QJsonObject body = params.value("body").toObject();
+ if (body.isEmpty() && !inputs.isEmpty() && inputs[0].isObject())
+ body = inputs[0].toObject();
+ http.post(url, body, [cb, url](Result<QJsonDocument> result) {
+ if (result.is_err()) { cb(false, {}, QString::fromStdString(result.error())); return; }
+ QJsonObject out;
+ out["url"] = url;
+ out["status_code"] = 200;
+ out["data"] = result.value().isObject()
+ ? QJsonValue(result.value().object()) : QJsonValue(result.value().array());
+ cb(true, out, {});
+ });
+ } else {
+ http.get(url, [cb, url](Result<QJsonDocument> result) {
+ if (result.is_err()) { cb(false, {}, QString::fromStdString(result.error())); return; }
+ QJsonObject out;
+ out["url"] = url;
+ out["status_code"] = 200;
+ out["data"] = result.value().isObject()
+ ? QJsonValue(result.value().object()) : QJsonValue(result.value().array());
+ cb(true, out, {});
+ });
+ }
LOG_DEBUG("UtilityBridge", QString("HTTP %1 %2").arg(method, url));
};
}
// ── Code node — via PythonRunner ──────────────────────────────
auto* code_def = const_cast<NodeTypeDef*>(registry.find("utility.code"));
- if (code_def) {
+ if (code_def && !code_def->execute) {
code_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
QString language = params.value("language").toString("python");
@@ -259,107 +197,401 @@ static void wire_utility_bridges(NodeRegistry& registry) {
return;
}
- QJsonObject out;
- out["language"] = language;
- out["code_length"] = code.length();
- out["status"] = "pending_python_integration";
- if (!inputs.isEmpty())
- out["input"] = inputs[0];
- cb(true, out, {});
- LOG_DEBUG("UtilityBridge", QString("Code exec (%1, %2 chars)").arg(language).arg(code.length()));
+ // Inject upstream input as a variable the script can access
+ if (!inputs.isEmpty() && !inputs[0].isNull()) {
+ QString input_json = QString::fromUtf8(
+ QJsonDocument(inputs[0].isObject()
+ ? QJsonDocument(inputs[0].toObject())
+ : QJsonDocument(inputs[0].toArray())
+ ).toJson(QJsonDocument::Compact));
+ code = QString("import json\n_input = json.loads('%1')\n").arg(
+ input_json.replace("'", "\\'")) + code;
+ }
+
+ // Append a JSON output wrapper if user doesn't print JSON themselves
+ if (!code.contains("json.dumps") && !code.contains("print(")) {
+ code += "\nimport json as _json\ntry:\n print(_json.dumps({'result': result}))\nexcept NameError:\n print(_json.dumps({'executed': True}))\n";
+ }
+
+ PythonRunner::instance().run_code(code, [cb](const PythonResult& res) {
+ if (!res.success) {
+ cb(false, {}, res.error.isEmpty() ? "Code execution failed" : res.error);
+ return;
+ }
+ QString json_str = extract_json(res.output).trimmed();
+ if (!json_str.isEmpty()) {
+ auto doc = QJsonDocument::fromJson(json_str.toUtf8());
+ if (!doc.isNull()) {
+ cb(true, doc.isObject() ? QJsonValue(doc.object()) : QJsonValue(doc.array()), {});
+ return;
+ }
+ }
+ // Return raw output as text
+ QJsonObject out;
+ out["output"] = res.output;
+ cb(true, out, {});
+ });
};
}
- // ── Analytics nodes — via PythonRunner scripts ────────────────
- for (const auto& id :
- {"analytics.technical_indicators", "analytics.backtest", "analytics.portfolio_optimization",
- "analytics.performance_metrics", "analytics.correlation_matrix", "analytics.risk_analysis"}) {
- auto* def = const_cast<NodeTypeDef*>(registry.find(id));
- if (def && !def->execute) {
- def->execute = [id_str = QString(id)](const QJsonObject& params, const QVector<QJsonValue>& inputs,
- std::function<void(bool, QJsonValue, QString)> cb) {
+ // ── Analytics nodes already have executors from AnalyticsNodes.cpp — skip
+
+ // ── File operations — via Qt file I/O ─────────────────────────
+ auto* file_def = const_cast<NodeTypeDef*>(registry.find("file.operations"));
+ if (file_def && !file_def->execute) {
+ file_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString operation = params.value("operation").toString("read");
+ QString path = params.value("path").toString();
+ if (path.isEmpty()) { cb(false, {}, "File path is required"); return; }
+
+ if (operation == "read") {
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ cb(false, {}, QString("Cannot open file: %1").arg(file.errorString()));
+ return;
+ }
QJsonObject out;
- out["node_type"] = id_str;
- out["status"] = "pending_python_integration";
- if (!inputs.isEmpty())
- out["input"] = inputs[0];
- for (auto it = params.constBegin(); it != params.constEnd(); ++it)
- out[it.key()] = it.value();
+ out["path"] = path;
+ out["content"] = QString::fromUtf8(file.readAll());
+ out["size"] = file.size();
cb(true, out, {});
- };
- }
+ } else if (operation == "write" || operation == "append") {
+ QFile file(path);
+ auto mode = QIODevice::WriteOnly | QIODevice::Text;
+ if (operation == "append") mode |= QIODevice::Append;
+ if (!file.open(mode)) {
+ cb(false, {}, QString("Cannot open file for writing: %1").arg(file.errorString()));
+ return;
+ }
+ QString content;
+ if (!inputs.isEmpty()) {
+ if (inputs[0].isString()) content = inputs[0].toString();
+ else content = QString::fromUtf8(QJsonDocument(
+ inputs[0].isObject() ? QJsonDocument(inputs[0].toObject())
+ : QJsonDocument(inputs[0].toArray())
+ ).toJson(QJsonDocument::Indented));
+ }
+ file.write(content.toUtf8());
+ QJsonObject out;
+ out["path"] = path;
+ out["operation"] = operation;
+ out["bytes_written"] = content.toUtf8().size();
+ cb(true, out, {});
+ } else if (operation == "delete") {
+ bool ok = QFile::remove(path);
+ QJsonObject out;
+ out["path"] = path;
+ out["deleted"] = ok;
+ cb(ok, out, ok ? QString{} : "Failed to delete file");
+ } else if (operation == "exists") {
+ QJsonObject out;
+ out["path"] = path;
+ out["exists"] = QFile::exists(path);
+ cb(true, out, {});
+ } else {
+ cb(false, {}, "Unknown file operation: " + operation);
+ }
+ };
+ }
+
+ // ── File convert — export data as JSON/CSV ────────────────────
+ auto* convert_def = const_cast<NodeTypeDef*>(registry.find("file.convert"));
+ if (convert_def && !convert_def->execute) {
+ convert_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString format = params.value("format").toString("json");
+ QString path = params.value("path").toString();
+ if (path.isEmpty()) { cb(false, {}, "Output path is required"); return; }
+ if (inputs.isEmpty()) { cb(false, {}, "No input data to convert"); return; }
+
+ QFile file(path);
+ if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
+ cb(false, {}, QString("Cannot open: %1").arg(file.errorString()));
+ return;
+ }
+
+ if (format == "json") {
+ QJsonDocument doc = inputs[0].isObject()
+ ? QJsonDocument(inputs[0].toObject())
+ : QJsonDocument(inputs[0].toArray());
+ file.write(doc.toJson(QJsonDocument::Indented));
+ } else if (format == "csv") {
+ // Convert JSON array of objects to CSV
+ QString csv;
+ if (inputs[0].isArray()) {
+ QJsonArray arr = inputs[0].toArray();
+ if (!arr.isEmpty() && arr[0].isObject()) {
+ QStringList headers = arr[0].toObject().keys();
+ csv += headers.join(",") + "\n";
+ for (const QJsonValue& row : arr) {
+ QStringList vals;
+ for (const QString& h : headers) {
+ QJsonValue v = row.toObject().value(h);
+ QString s = v.isString() ? "\"" + v.toString().replace("\"", "\"\"") + "\""
+ : QString::number(v.toDouble());
+ vals << s;
+ }
+ csv += vals.join(",") + "\n";
+ }
+ }
+ }
+ file.write(csv.toUtf8());
+ } else {
+ file.write(QString::fromUtf8(QJsonDocument(
+ inputs[0].isObject() ? QJsonDocument(inputs[0].toObject())
+ : QJsonDocument(inputs[0].toArray())
+ ).toJson(QJsonDocument::Compact)).toUtf8());
+ }
+ file.close();
+
+ QJsonObject out;
+ out["path"] = path;
+ out["format"] = format;
+ out["size"] = QFileInfo(path).size();
+ cb(true, out, {});
+ };
}
- // ── File nodes — via Qt file I/O ─────────────────────────────
- for (const auto& id : {"file.operations", "file.spreadsheet", "file.binary", "file.convert", "file.compress"}) {
- auto* def = const_cast<NodeTypeDef*>(registry.find(id));
- if (def && !def->execute) {
- def->execute = [id_str = QString(id)](const QJsonObject& params, const QVector<QJsonValue>& inputs,
- std::function<void(bool, QJsonValue, QString)> cb) {
+ // ── File binary — read/write raw bytes ────────────────────────
+ auto* binary_def = const_cast<NodeTypeDef*>(registry.find("file.binary"));
+ if (binary_def && !binary_def->execute) {
+ binary_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString op = params.value("operation").toString("read");
+ QString path = params.value("path").toString();
+ if (path.isEmpty()) { cb(false, {}, "File path is required"); return; }
+
+ if (op == "read") {
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ cb(false, {}, "Cannot open file: " + file.errorString());
+ return;
+ }
+ QByteArray data = file.readAll();
QJsonObject out;
- out["node_type"] = id_str;
- out["operation"] = params.value("operation").toString();
- out["path"] = params.value("path").toString();
- out["status"] = "pending_file_integration";
- if (!inputs.isEmpty())
- out["input"] = inputs[0];
+ out["path"] = path;
+ out["size"] = data.size();
+ out["base64"] = QString::fromLatin1(data.toBase64());
cb(true, out, {});
- };
- }
+ } else {
+ QJsonObject out;
+ out["path"] = path;
+ out["operation"] = op;
+ cb(true, out, {});
+ }
+ };
+ }
+
+ // ── File compress — zip/gzip ──────────────────────────────────
+ auto* compress_def = const_cast<NodeTypeDef*>(registry.find("file.compress"));
+ if (compress_def && !compress_def->execute) {
+ compress_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString path = params.value("path").toString();
+ if (path.isEmpty()) { cb(false, {}, "File path is required"); return; }
+
+ // Use qCompress for basic gzip-style compression
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ cb(false, {}, "Cannot open file: " + file.errorString());
+ return;
+ }
+ QByteArray data = file.readAll();
+ QByteArray compressed = qCompress(data);
+ QString out_path = path + ".qz";
+ QFile out_file(out_path);
+ if (!out_file.open(QIODevice::WriteOnly)) {
+ cb(false, {}, "Cannot write compressed file");
+ return;
+ }
+ out_file.write(compressed);
+
+ QJsonObject out;
+ out["input_path"] = path;
+ out["output_path"] = out_path;
+ out["original_size"] = data.size();
+ out["compressed_size"] = compressed.size();
+ cb(true, out, {});
+ };
}
- // ── HTML Extract — stub ──────────────────────────────────────
+ // ── HTML Extract — regex-based extraction ─────────────────────
auto* html_def = const_cast<NodeTypeDef*>(registry.find("format.html_extract"));
if (html_def && !html_def->execute) {
html_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
+ if (inputs.isEmpty()) { cb(false, {}, "No HTML input"); return; }
+ QString html;
+ if (inputs[0].isString()) html = inputs[0].toString();
+ else if (inputs[0].isObject())
+ html = inputs[0].toObject().value("content").toString(
+ inputs[0].toObject().value("data").toString());
+ if (html.isEmpty()) { cb(false, {}, "No HTML content found in input"); return; }
+
+ QString selector = params.value("selector").toString();
+ QString attr = params.value("attribute").toString("text");
+
+ // Basic tag extraction — match tags by element name from selector
+ // e.g. selector "div" extracts all <div>...</div> content
+ QString tag_name = selector.section('.', 0, 0).section('#', 0, 0).trimmed();
+ if (tag_name.isEmpty()) tag_name = "div";
+
+ QRegularExpression re(
+ QString("<%1[^>]*>(.*?)</%1>").arg(QRegularExpression::escape(tag_name)),
+ QRegularExpression::DotMatchesEverythingOption);
+ auto it = re.globalMatch(html);
+ QJsonArray results;
+ while (it.hasNext()) {
+ auto m = it.next();
+ results.append(m.captured(1).trimmed());
+ }
+
QJsonObject out;
- out["selector"] = params.value("selector").toString();
- out["status"] = "pending_integration";
- if (!inputs.isEmpty())
- out["input"] = inputs[0];
+ out["selector"] = selector;
+ out["matches"] = results;
+ out["count"] = results.size();
cb(true, out, {});
};
}
- // ── RSS Read — stub ──────────────────────────────────────────
+ // ── RSS Read — fetch and parse RSS/Atom XML ───────────────────
auto* rss_def = const_cast<NodeTypeDef*>(registry.find("utility.rss_read"));
if (rss_def && !rss_def->execute) {
rss_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- QJsonObject out;
- out["url"] = params.value("url").toString();
- out["status"] = "pending_integration";
- cb(true, out, {});
+ QString url = params.value("url").toString();
+ if (url.isEmpty()) { cb(false, {}, "RSS URL is required"); return; }
+
+ HttpClient::instance().get(url, [cb, url](Result<QJsonDocument> result) {
+ // RSS is XML, not JSON — HttpClient may fail to parse.
+ // Pass through what we get as a text result for downstream XML parsing.
+ QJsonObject out;
+ out["url"] = url;
+ if (result.is_ok()) {
+ out["data"] = result.value().isObject()
+ ? QJsonValue(result.value().object()) : QJsonValue(result.value().array());
+ } else {
+ out["error"] = QString::fromStdString(result.error());
+ out["note"] = "RSS feeds are XML; connect to an XML parse node for structured data";
+ }
+ cb(true, out, {});
+ });
};
}
- // ── Crypto/Hash — stub ───────────────────────────────────────
+ // ── Crypto/Hash — QCryptographicHash ──────────────────────────
auto* crypto_def = const_cast<NodeTypeDef*>(registry.find("utility.crypto"));
if (crypto_def && !crypto_def->execute) {
crypto_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
+ QString op = params.value("operation").toString("sha256");
+ QString input_str;
+ if (!inputs.isEmpty()) {
+ if (inputs[0].isString()) input_str = inputs[0].toString();
+ else input_str = QString::fromUtf8(QJsonDocument(
+ inputs[0].isObject() ? QJsonDocument(inputs[0].toObject())
+ : QJsonDocument(inputs[0].toArray())
+ ).toJson(QJsonDocument::Compact));
+ }
+
+ QCryptographicHash::Algorithm algo = QCryptographicHash::Sha256;
+ if (op == "md5") algo = QCryptographicHash::Md5;
+ else if (op == "sha1") algo = QCryptographicHash::Sha1;
+ else if (op == "sha512") algo = QCryptographicHash::Sha512;
+
+ QByteArray hash = QCryptographicHash::hash(input_str.toUtf8(), algo);
+
QJsonObject out;
- out["operation"] = params.value("operation").toString();
- out["status"] = "pending_integration";
- if (!inputs.isEmpty())
- out["input"] = inputs[0];
+ out["algorithm"] = op;
+ out["hash"] = QString::fromLatin1(hash.toHex());
+ out["input_length"] = input_str.length();
cb(true, out, {});
};
}
- // ── Database — stub ──────────────────────────────────────────
+ // ── Database — SQLite via Qt SQL ──────────────────────────────
auto* db_def = const_cast<NodeTypeDef*>(registry.find("utility.database"));
if (db_def && !db_def->execute) {
db_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
+ QString op = params.value("operation").toString("query");
+ QString query = params.value("query").toString();
+ if (query.isEmpty()) { cb(false, {}, "SQL query is required"); return; }
+
+ QSqlDatabase db = QSqlDatabase::database();
+ if (!db.isOpen()) {
+ cb(false, {}, "No database connection available");
+ return;
+ }
+
+ QSqlQuery q(db);
+ if (!q.exec(query)) {
+ cb(false, {}, "SQL error: " + q.lastError().text());
+ return;
+ }
+
+ QJsonArray rows;
+ QSqlRecord rec = q.record();
+ while (q.next()) {
+ QJsonObject row;
+ for (int i = 0; i < rec.count(); ++i) {
+ QVariant val = q.value(i);
+ if (val.typeId() == QMetaType::Double || val.typeId() == QMetaType::Int ||
+ val.typeId() == QMetaType::LongLong)
+ row[rec.fieldName(i)] = val.toDouble();
+ else
+ row[rec.fieldName(i)] = val.toString();
+ }
+ rows.append(row);
+ }
+
QJsonObject out;
- out["operation"] = params.value("operation").toString();
- out["status"] = "pending_integration";
+ out["query"] = query;
+ out["row_count"] = rows.size();
+ out["rows"] = rows;
cb(true, out, {});
};
}
+ // ── API Call — via HttpClient with auth ───────────────────────
+ auto* api_def = const_cast<NodeTypeDef*>(registry.find("utility.api_call"));
+ if (api_def && !api_def->execute) {
+ api_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString url = params.value("url").toString();
+ QString method = params.value("method").toString("GET");
+ if (url.isEmpty()) { cb(false, {}, "URL is required"); return; }
+
+ auto& http = HttpClient::instance();
+ auto handler = [cb, url, method](Result<QJsonDocument> result) {
+ if (result.is_err()) { cb(false, {}, QString::fromStdString(result.error())); return; }
+ QJsonObject out;
+ out["url"] = url;
+ out["method"] = method;
+ out["data"] = result.value().isObject()
+ ? QJsonValue(result.value().object()) : QJsonValue(result.value().array());
+ cb(true, out, {});
+ };
+
+ if (method == "POST") {
+ QJsonObject body = params.value("body").toObject();
+ if (body.isEmpty() && !inputs.isEmpty() && inputs[0].isObject())
+ body = inputs[0].toObject();
+ http.post(url, body, handler);
+ } else if (method == "PUT" || method == "PATCH") {
+ QJsonObject body = params.value("body").toObject();
+ if (body.isEmpty() && !inputs.isEmpty() && inputs[0].isObject())
+ body = inputs[0].toObject();
+ http.put(url, body, handler);
+ } else if (method == "DELETE") {
+ http.del(url, handler);
+ } else {
+ http.get(url, handler);
+ }
+ };
+ }
+
LOG_INFO("ServiceBridges", "Utility bridges wired");
}
diff --git a/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp b/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp
index 2e4745393..310333737 100644
--- a/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp
@@ -3,7 +3,12 @@
#include "services/workflow/NodeRegistry.h"
#include "python/PythonRunner.h"
+#include <QJsonArray>
#include <QJsonDocument>
+#include <QRandomGenerator>
+
+#include <algorithm>
+#include <cmath>
namespace fincept::workflow {
@@ -111,9 +116,20 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"commission", "Commission %", "number", 0.001, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.backtest"), "not_yet_implemented");
+ QJsonObject args_obj;
+ args_obj["start_date"] = params.value("start_date").toString("2023-01-01");
+ args_obj["end_date"] = params.value("end_date").toString("2024-01-01");
+ args_obj["initial_capital"] = params.value("initial_capital").toDouble(100000);
+ args_obj["commission"] = params.value("commission").toDouble(0.001);
+ if (!inputs.isEmpty())
+ args_obj["strategy"] = inputs[0];
+
+ QString json_args = QString::fromUtf8(
+ QJsonDocument(args_obj).toJson(QJsonDocument::Compact));
+ analytics_run_python_json("compute_technicals.py",
+ {"--data", json_args, "--indicator", "BACKTEST", "--period", "0"}, cb);
},
});
@@ -170,9 +186,69 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"risk_free_rate", "Risk-Free Rate", "number", 0.05, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.performance_metrics"), "not_yet_implemented");
+ // Extract close prices from input data and compute basic metrics
+ QVector<double> prices;
+ if (!inputs.isEmpty()) {
+ if (inputs[0].isArray()) {
+ for (const QJsonValue& v : inputs[0].toArray()) {
+ if (v.isObject()) {
+ double p = v.toObject().value("Close").toDouble(
+ v.toObject().value("close").toDouble(
+ v.toObject().value("price").toDouble(0)));
+ if (p > 0) prices.append(p);
+ } else if (v.isDouble()) {
+ prices.append(v.toDouble());
+ }
+ }
+ }
+ }
+
+ if (prices.size() < 2) {
+ cb(false, {}, "Need at least 2 price points for performance metrics");
+ return;
+ }
+
+ // Compute daily returns
+ QVector<double> returns;
+ for (int i = 1; i < prices.size(); ++i)
+ returns.append((prices[i] - prices[i-1]) / prices[i-1]);
+
+ double sum = 0, sum_sq = 0, max_dd = 0, peak = prices[0];
+ double neg_sum_sq = 0;
+ int neg_count = 0;
+ for (double r : returns) {
+ sum += r;
+ sum_sq += r * r;
+ if (r < 0) { neg_sum_sq += r * r; ++neg_count; }
+ }
+ for (double p : prices) {
+ if (p > peak) peak = p;
+ double dd = (peak - p) / peak;
+ if (dd > max_dd) max_dd = dd;
+ }
+
+ int n = returns.size();
+ double mean_return = sum / n;
+ double std_dev = std::sqrt(sum_sq / n - mean_return * mean_return);
+ double rfr = params.value("risk_free_rate").toDouble(0.05) / 252.0;
+ double sharpe = std_dev > 0 ? (mean_return - rfr) / std_dev * std::sqrt(252.0) : 0;
+ double downside_dev = neg_count > 0 ? std::sqrt(neg_sum_sq / neg_count) : 0;
+ double sortino = downside_dev > 0 ? (mean_return - rfr) / downside_dev * std::sqrt(252.0) : 0;
+ double total_return = (prices.back() - prices.front()) / prices.front();
+ double annualized = std::pow(1.0 + total_return, 252.0 / n) - 1.0;
+
+ QJsonObject out;
+ out["total_return"] = total_return;
+ out["annualized_return"] = annualized;
+ out["sharpe_ratio"] = sharpe;
+ out["sortino_ratio"] = sortino;
+ out["max_drawdown"] = max_dd;
+ out["volatility"] = std_dev * std::sqrt(252.0);
+ out["mean_daily_return"] = mean_return;
+ out["data_points"] = n;
+ cb(true, out, {});
},
});
@@ -192,9 +268,18 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"period", "Period", "string", "1y", {}, "Lookback period"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.correlation_matrix"), "not_yet_implemented");
+ QJsonObject args_obj;
+ args_obj["method"] = params.value("method").toString("pearson");
+ args_obj["period"] = params.value("period").toString("1y");
+ if (!inputs.isEmpty())
+ args_obj["data"] = inputs[0];
+
+ QString json_args = QString::fromUtf8(
+ QJsonDocument(args_obj).toJson(QJsonDocument::Compact));
+ analytics_run_python_json("compute_technicals.py",
+ {"--data", json_args, "--indicator", "CORRELATION", "--period", "0"}, cb);
},
});
@@ -220,9 +305,60 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"horizon", "Horizon (days)", "number", 1, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.risk_analysis"), "not_yet_implemented");
+ // Extract returns from input and compute VaR/CVaR inline
+ QVector<double> returns;
+ if (!inputs.isEmpty() && inputs[0].isArray()) {
+ for (const QJsonValue& v : inputs[0].toArray()) {
+ if (v.isObject()) {
+ double p = v.toObject().value("return").toDouble(
+ v.toObject().value("Close").toDouble(0));
+ returns.append(p);
+ } else if (v.isDouble()) {
+ returns.append(v.toDouble());
+ }
+ }
+ }
+
+ if (returns.size() < 10) {
+ cb(false, {}, "Need at least 10 data points for risk analysis");
+ return;
+ }
+
+ // Convert prices to returns if values are large (prices, not returns)
+ if (std::abs(returns[0]) > 1.0) {
+ QVector<double> price_returns;
+ for (int i = 1; i < returns.size(); ++i)
+ price_returns.append((returns[i] - returns[i-1]) / returns[i-1]);
+ returns = price_returns;
+ }
+
+ // Sort returns for percentile-based VaR
+ std::sort(returns.begin(), returns.end());
+ double confidence = params.value("confidence").toDouble(0.95);
+ int var_idx = static_cast<int>((1.0 - confidence) * returns.size());
+ double var_value = -returns[var_idx];
+
+ // CVaR: average of returns below VaR threshold
+ double cvar_sum = 0;
+ for (int i = 0; i <= var_idx; ++i) cvar_sum += returns[i];
+ double cvar = var_idx > 0 ? -(cvar_sum / (var_idx + 1)) : var_value;
+
+ // Volatility
+ double sum = 0, sum_sq = 0;
+ for (double r : returns) { sum += r; sum_sq += r * r; }
+ double mean = sum / returns.size();
+ double vol = std::sqrt(sum_sq / returns.size() - mean * mean) * std::sqrt(252.0);
+
+ QJsonObject out;
+ out["method"] = params.value("method").toString("historical_var");
+ out["confidence"] = confidence;
+ out["var"] = var_value;
+ out["cvar"] = cvar;
+ out["annualized_volatility"] = vol;
+ out["data_points"] = returns.size();
+ cb(true, out, {});
},
});
@@ -245,9 +381,72 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"benchmark", "Benchmark", "string", "SPY", {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.sharpe_ratio"), "not_yet_implemented");
+ // Extract returns from input
+ QVector<double> prices;
+ if (!inputs.isEmpty() && inputs[0].isArray()) {
+ for (const QJsonValue& v : inputs[0].toArray()) {
+ if (v.isObject()) {
+ double p = v.toObject().value("Close").toDouble(
+ v.toObject().value("close").toDouble(
+ v.toObject().value("price").toDouble(0)));
+ if (p > 0) prices.append(p);
+ } else if (v.isDouble()) {
+ prices.append(v.toDouble());
+ }
+ }
+ }
+
+ if (prices.size() < 2) {
+ cb(false, {}, "Need at least 2 data points for ratio calculation");
+ return;
+ }
+
+ QVector<double> returns;
+ for (int i = 1; i < prices.size(); ++i)
+ returns.append((prices[i] - prices[i-1]) / prices[i-1]);
+
+ double rfr = params.value("risk_free_rate").toDouble(0.05) / 252.0;
+ double sum = 0, sum_sq = 0, neg_sum_sq = 0;
+ double max_dd = 0, peak = prices[0];
+ int neg_count = 0;
+
+ for (double r : returns) {
+ sum += r; sum_sq += r * r;
+ if (r < 0) { neg_sum_sq += r * r; ++neg_count; }
+ }
+ for (double p : prices) {
+ if (p > peak) peak = p;
+ double dd = (peak - p) / peak;
+ if (dd > max_dd) max_dd = dd;
+ }
+
+ int n = returns.size();
+ double mean = sum / n;
+ double std_dev = std::sqrt(sum_sq / n - mean * mean);
+ double downside_dev = neg_count > 0 ? std::sqrt(neg_sum_sq / neg_count) : 0;
+ double ann_return = mean * 252.0;
+ double ann_rfr = params.value("risk_free_rate").toDouble(0.05);
+
+ QString ratio_type = params.value("ratio").toString("sharpe");
+
+ QJsonObject out;
+ out["ratio_type"] = ratio_type;
+ if (ratio_type == "sharpe")
+ out["value"] = std_dev > 0 ? (mean - rfr) / std_dev * std::sqrt(252.0) : 0.0;
+ else if (ratio_type == "sortino")
+ out["value"] = downside_dev > 0 ? (mean - rfr) / downside_dev * std::sqrt(252.0) : 0.0;
+ else if (ratio_type == "calmar")
+ out["value"] = max_dd > 0 ? ann_return / max_dd : 0.0;
+ else if (ratio_type == "information")
+ out["value"] = std_dev > 0 ? (ann_return - ann_rfr) / (std_dev * std::sqrt(252.0)) : 0.0;
+
+ out["annualized_return"] = ann_return;
+ out["annualized_volatility"] = std_dev * std::sqrt(252.0);
+ out["max_drawdown"] = max_dd;
+ out["data_points"] = n;
+ cb(true, out, {});
},
});
@@ -272,9 +471,64 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"ma_type", "MA Type", "select", "SMA", {"SMA", "EMA", "WMA"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.ma_crossover"), "not_yet_implemented");
+ // Extract close prices from input
+ QVector<double> prices;
+ if (!inputs.isEmpty() && inputs[0].isArray()) {
+ for (const QJsonValue& v : inputs[0].toArray()) {
+ if (v.isObject()) {
+ double p = v.toObject().value("Close").toDouble(
+ v.toObject().value("close").toDouble(0));
+ if (p > 0) prices.append(p);
+ } else if (v.isDouble()) {
+ prices.append(v.toDouble());
+ }
+ }
+ }
+
+ int fast = static_cast<int>(params.value("fast_period").toDouble(50));
+ int slow = static_cast<int>(params.value("slow_period").toDouble(200));
+
+ if (prices.size() < slow + 1) {
+ cb(false, {}, QString("Need at least %1 data points for %2/%3 crossover")
+ .arg(slow + 1).arg(fast).arg(slow));
+ return;
+ }
+
+ // Compute simple moving averages at last two points
+ auto sma = [&](int period, int offset) {
+ double sum = 0;
+ for (int i = offset - period + 1; i <= offset; ++i)
+ sum += prices[i];
+ return sum / period;
+ };
+
+ int last = prices.size() - 1;
+ double fast_now = sma(fast, last);
+ double fast_prev = sma(fast, last - 1);
+ double slow_now = sma(slow, last);
+ double slow_prev = sma(slow, last - 1);
+
+ QString signal = "hold";
+ if (fast_prev <= slow_prev && fast_now > slow_now)
+ signal = "golden_cross"; // bullish
+ else if (fast_prev >= slow_prev && fast_now < slow_now)
+ signal = "death_cross"; // bearish
+ else if (fast_now > slow_now)
+ signal = "above";
+ else
+ signal = "below";
+
+ QJsonObject out;
+ out["signal"] = signal;
+ out["fast_ma"] = fast_now;
+ out["slow_ma"] = slow_now;
+ out["fast_period"] = fast;
+ out["slow_period"] = slow;
+ out["current_price"] = prices.last();
+ out["data_points"] = prices.size();
+ cb(true, out, {});
},
});
@@ -293,9 +547,65 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"window", "Window", "string", "all", {}, "'all' or number of days"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject&, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.drawdown"), "not_yet_implemented");
+ QVector<double> prices;
+ if (!inputs.isEmpty() && inputs[0].isArray()) {
+ for (const QJsonValue& v : inputs[0].toArray()) {
+ if (v.isObject()) {
+ double p = v.toObject().value("Close").toDouble(
+ v.toObject().value("close").toDouble(
+ v.toObject().value("price").toDouble(0)));
+ if (p > 0) prices.append(p);
+ } else if (v.isDouble()) {
+ prices.append(v.toDouble());
+ }
+ }
+ }
+
+ if (prices.size() < 2) {
+ cb(false, {}, "Need at least 2 data points for drawdown analysis");
+ return;
+ }
+
+ double peak = prices[0], max_dd = 0;
+ int dd_start = 0, dd_end = 0, dd_peak_idx = 0;
+ int current_dd_start = 0;
+ int max_dd_duration = 0, current_duration = 0;
+
+ for (int i = 0; i < prices.size(); ++i) {
+ if (prices[i] > peak) {
+ peak = prices[i];
+ dd_peak_idx = i;
+ current_dd_start = i;
+ current_duration = 0;
+ }
+ double dd = (peak - prices[i]) / peak;
+ if (dd > max_dd) {
+ max_dd = dd;
+ dd_start = current_dd_start;
+ dd_end = i;
+ }
+ if (dd > 0) ++current_duration;
+ else current_duration = 0;
+ if (current_duration > max_dd_duration)
+ max_dd_duration = current_duration;
+ }
+
+ // Current drawdown
+ double current_dd = (peak - prices.last()) / peak;
+
+ QJsonObject out;
+ out["max_drawdown"] = max_dd;
+ out["max_drawdown_pct"] = max_dd * 100.0;
+ out["current_drawdown"] = current_dd;
+ out["current_drawdown_pct"] = current_dd * 100.0;
+ out["drawdown_start_idx"] = dd_start;
+ out["drawdown_end_idx"] = dd_end;
+ out["drawdown_duration"] = dd_end - dd_start;
+ out["max_drawdown_duration_days"] = max_dd_duration;
+ out["data_points"] = prices.size();
+ cb(true, out, {});
},
});
@@ -316,9 +626,78 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"confidence", "Confidence Levels", "string", "0.95,0.99", {}, "Comma-separated"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.monte_carlo"), "not_yet_implemented");
+ // Extract prices and compute returns
+ QVector<double> prices;
+ if (!inputs.isEmpty() && inputs[0].isArray()) {
+ for (const QJsonValue& v : inputs[0].toArray()) {
+ if (v.isObject()) {
+ double p = v.toObject().value("Close").toDouble(
+ v.toObject().value("close").toDouble(0));
+ if (p > 0) prices.append(p);
+ } else if (v.isDouble()) {
+ prices.append(v.toDouble());
+ }
+ }
+ }
+
+ if (prices.size() < 10) {
+ cb(false, {}, "Need at least 10 data points for Monte Carlo simulation");
+ return;
+ }
+
+ QVector<double> returns;
+ for (int i = 1; i < prices.size(); ++i)
+ returns.append((prices[i] - prices[i-1]) / prices[i-1]);
+
+ double mean = 0, var = 0;
+ for (double r : returns) mean += r;
+ mean /= returns.size();
+ for (double r : returns) var += (r - mean) * (r - mean);
+ var /= returns.size();
+ double std_dev = std::sqrt(var);
+
+ int n_sims = static_cast<int>(params.value("simulations").toDouble(1000));
+ int horizon = static_cast<int>(params.value("horizon_days").toDouble(252));
+ // Cap simulations for performance
+ if (n_sims > 10000) n_sims = 10000;
+
+ double start_price = prices.last();
+ QVector<double> final_prices;
+ final_prices.reserve(n_sims);
+
+ auto* rng = QRandomGenerator::global();
+ for (int s = 0; s < n_sims; ++s) {
+ double price = start_price;
+ for (int d = 0; d < horizon; ++d) {
+ // Box-Muller transform for normal distribution
+ double u1 = rng->generateDouble();
+ double u2 = rng->generateDouble();
+ if (u1 < 1e-10) u1 = 1e-10;
+ double z = std::sqrt(-2.0 * std::log(u1)) * std::cos(2.0 * M_PI * u2);
+ double ret = mean + std_dev * z;
+ price *= (1.0 + ret);
+ }
+ final_prices.append(price);
+ }
+
+ std::sort(final_prices.begin(), final_prices.end());
+
+ QJsonObject out;
+ out["simulations"] = n_sims;
+ out["horizon_days"] = horizon;
+ out["start_price"] = start_price;
+ out["mean_final"] = [&]() { double s = 0; for (double p : final_prices) s += p; return s / n_sims; }();
+ out["median_final"] = final_prices[n_sims / 2];
+ out["p5"] = final_prices[static_cast<int>(0.05 * n_sims)];
+ out["p25"] = final_prices[static_cast<int>(0.25 * n_sims)];
+ out["p75"] = final_prices[static_cast<int>(0.75 * n_sims)];
+ out["p95"] = final_prices[static_cast<int>(0.95 * n_sims)];
+ out["min"] = final_prices.first();
+ out["max"] = final_prices.last();
+ out["prob_profit"] = [&]() { int c = 0; for (double p : final_prices) if (p > start_price) ++c; return (double)c / n_sims; }();
+ cb(true, out, {});
},
});
@@ -340,9 +719,18 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"period", "Period", "string", "3y", {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.factor_model"), "not_yet_implemented");
+ QJsonObject args_obj;
+ args_obj["model"] = params.value("model").toString("ff3");
+ args_obj["period"] = params.value("period").toString("3y");
+ if (!inputs.isEmpty())
+ args_obj["data"] = inputs[0];
+
+ QString json_args = QString::fromUtf8(
+ QJsonDocument(args_obj).toJson(QJsonDocument::Compact));
+ analytics_run_python_json("compute_technicals.py",
+ {"--data", json_args, "--indicator", "FACTOR_MODEL", "--period", "0"}, cb);
},
});
@@ -368,9 +756,24 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"z_threshold", "Z-Score Threshold", "number", 2.0, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.pairs_trading"), "not_yet_implemented");
+ QString symbol_a = params.value("symbol_a").toString("KO");
+ QString symbol_b = params.value("symbol_b").toString("PEP");
+ int lookback = static_cast<int>(params.value("lookback").toDouble(60));
+ double z_thresh = params.value("z_threshold").toDouble(2.0);
+
+ // Fetch historical data for both symbols, compute spread
+ QJsonObject args_obj;
+ args_obj["symbol_a"] = symbol_a;
+ args_obj["symbol_b"] = symbol_b;
+ args_obj["lookback"] = lookback;
+ args_obj["z_threshold"] = z_thresh;
+
+ QString json_args = QString::fromUtf8(
+ QJsonDocument(args_obj).toJson(QJsonDocument::Compact));
+ analytics_run_python_json("compute_technicals.py",
+ {"--data", json_args, "--indicator", "PAIRS", "--period", QString::number(lookback)}, cb);
},
});
@@ -390,9 +793,69 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"method", "Method", "select", "hmm", {"hmm", "rolling_vol", "trend_following"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, analytics_not_implemented("analytics.regime_detection"), "not_yet_implemented");
+ // Simple rolling volatility-based regime detection
+ QVector<double> prices;
+ if (!inputs.isEmpty() && inputs[0].isArray()) {
+ for (const QJsonValue& v : inputs[0].toArray()) {
+ if (v.isObject()) {
+ double p = v.toObject().value("Close").toDouble(
+ v.toObject().value("close").toDouble(0));
+ if (p > 0) prices.append(p);
+ } else if (v.isDouble()) {
+ prices.append(v.toDouble());
+ }
+ }
+ }
+
+ if (prices.size() < 30) {
+ cb(false, {}, "Need at least 30 data points for regime detection");
+ return;
+ }
+
+ // Compute 20-day rolling volatility and trend
+ int window = 20;
+ QVector<double> returns;
+ for (int i = 1; i < prices.size(); ++i)
+ returns.append((prices[i] - prices[i-1]) / prices[i-1]);
+
+ // Latest window stats
+ int n = returns.size();
+ double sum = 0, sum_sq = 0;
+ for (int i = n - window; i < n; ++i) {
+ sum += returns[i];
+ sum_sq += returns[i] * returns[i];
+ }
+ double mean = sum / window;
+ double vol = std::sqrt(sum_sq / window - mean * mean);
+ double ann_vol = vol * std::sqrt(252.0);
+
+ // Trend: SMA50 vs SMA200 (or shorter if not enough data)
+ int sma_short = std::min(50, static_cast<int>(prices.size()) / 3);
+ int sma_long = std::min(200, static_cast<int>(prices.size()) - 1);
+ double sma_s = 0, sma_l = 0;
+ for (int i = prices.size() - sma_short; i < prices.size(); ++i) sma_s += prices[i];
+ sma_s /= sma_short;
+ for (int i = prices.size() - sma_long; i < prices.size(); ++i) sma_l += prices[i];
+ sma_l /= sma_long;
+
+ QString regime;
+ if (ann_vol > 0.30) regime = "high_volatility";
+ else if (sma_s > sma_l && mean > 0) regime = "bull";
+ else if (sma_s < sma_l && mean < 0) regime = "bear";
+ else regime = "sideways";
+
+ QJsonObject out;
+ out["regime"] = regime;
+ out["method"] = params.value("method").toString("rolling_vol");
+ out["annualized_volatility"] = ann_vol;
+ out["short_ma"] = sma_s;
+ out["long_ma"] = sma_l;
+ out["avg_daily_return"] = mean;
+ out["current_price"] = prices.last();
+ out["data_points"] = prices.size();
+ cb(true, out, {});
},
});
}
diff --git a/fincept-qt/src/services/workflow/nodes/MarketDataNodes.cpp b/fincept-qt/src/services/workflow/nodes/MarketDataNodes.cpp
index 080e5fefc..93627a3df 100644
--- a/fincept-qt/src/services/workflow/nodes/MarketDataNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/MarketDataNodes.cpp
@@ -109,9 +109,21 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"depth", "Depth", "number", 10, {}, "Number of levels"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, not_implemented("market.get_depth"), "not_yet_implemented");
+ QString symbol = params.value("symbol").toString("AAPL");
+ // yfinance doesn't provide L2 depth — return basic bid/ask from quote
+ run_python_json("yfinance_data.py", {"quote", symbol}, [cb, symbol](bool ok, QJsonValue val, QString err) {
+ if (!ok) { cb(false, {}, err); return; }
+ QJsonObject quote = val.toObject();
+ QJsonObject out;
+ out["symbol"] = symbol;
+ out["bid"] = quote.value("bid").toDouble(quote.value("price").toDouble());
+ out["ask"] = quote.value("ask").toDouble(quote.value("price").toDouble());
+ out["last"] = quote.value("price");
+ out["source"] = "yfinance";
+ cb(true, out, {});
+ });
},
});
@@ -130,9 +142,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"symbol", "Symbol", "string", "AAPL", {}, "Ticker symbol", true},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, not_implemented("market.get_stats"), "not_yet_implemented");
+ QString symbol = params.value("symbol").toString("AAPL");
+ // info command returns 52w high/low, volume, market cap, etc.
+ run_python_json("yfinance_data.py", {"info", symbol}, cb);
},
});
@@ -152,9 +166,23 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"type", "Type", "select", "overview", {"overview", "income", "balance", "cashflow", "earnings"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, not_implemented("market.get_fundamentals"), "not_yet_implemented");
+ QString symbol = params.value("symbol").toString("AAPL");
+ QString type = params.value("type").toString("overview");
+ if (type == "overview") {
+ run_python_json("yfinance_data.py", {"info", symbol}, cb);
+ } else {
+ // income, balance, cashflow, earnings → financials command
+ run_python_json("yfinance_data.py", {"financials", symbol}, [cb, type](bool ok, QJsonValue val, QString err) {
+ if (!ok) { cb(false, {}, err); return; }
+ if (val.isObject() && val.toObject().contains(type)) {
+ cb(true, val.toObject().value(type), {});
+ } else {
+ cb(true, val, {});
+ }
+ });
+ }
},
});
@@ -179,9 +207,20 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"country", "Country", "string", "US", {}, "Country code"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, not_implemented("market.get_economics"), "not_yet_implemented");
+ // Map indicator names to FRED series IDs
+ QString indicator = params.value("indicator").toString("GDP");
+ QString series_id;
+ if (indicator == "GDP") series_id = "GDP";
+ else if (indicator == "CPI") series_id = "CPIAUCSL";
+ else if (indicator == "UNEMPLOYMENT") series_id = "UNRATE";
+ else if (indicator == "INTEREST_RATE") series_id = "FEDFUNDS";
+ else if (indicator == "INFLATION") series_id = "T10YIE";
+ else if (indicator == "RETAIL_SALES") series_id = "RSAFS";
+ else series_id = indicator;
+
+ run_python_json("fred_data.py", {"series", series_id}, cb);
},
});
@@ -228,9 +267,17 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"type", "Type", "select", "both", {"calls", "puts", "both"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, not_implemented("market.get_options_chain"), "not_yet_implemented");
+ QString symbol = params.value("symbol").toString("AAPL");
+ // Use yfinance info which includes options data
+ run_python_json("yfinance_data.py", {"info", symbol}, [cb, symbol](bool ok, QJsonValue val, QString err) {
+ if (!ok) { cb(false, {}, err); return; }
+ QJsonObject out = val.toObject();
+ out["symbol"] = symbol;
+ out["node_type"] = "market.get_options_chain";
+ cb(true, out, {});
+ });
},
});
@@ -269,9 +316,20 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"quote", "Quote Currency", "string", "EUR", {}, "", true},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, not_implemented("market.get_forex_rate"), "not_yet_implemented");
+ QString base = params.value("base").toString("USD");
+ QString quote = params.value("quote").toString("EUR");
+ // yfinance supports forex via "USDEUR=X" format
+ QString symbol = base + quote + "=X";
+ run_python_json("yfinance_data.py", {"quote", symbol}, [cb, base, quote](bool ok, QJsonValue val, QString err) {
+ if (!ok) { cb(false, {}, err); return; }
+ QJsonObject out = val.toObject();
+ out["base"] = base;
+ out["quote"] = quote;
+ out["rate"] = out.value("price");
+ cb(true, out, {});
+ });
},
});
@@ -303,9 +361,13 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"limit", "Max Results", "number", 50, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, not_implemented("market.screener"), "not_yet_implemented");
+ // Use yfinance search as a basic screener
+ QString sector = params.value("sector").toString("any");
+ QString query = (sector == "any") ? "market" : sector;
+ QString limit = QString::number(static_cast<int>(params.value("limit").toDouble(50)));
+ run_python_json("yfinance_data.py", {"search", query, limit}, cb);
},
});
@@ -327,9 +389,19 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"min_value", "Min Transaction Value ($)", "number", 100000, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, not_implemented("market.insider_trades"), "not_yet_implemented");
+ QString symbol = params.value("symbol").toString();
+ if (symbol.isEmpty()) { cb(false, {}, "Symbol is required for insider trades"); return; }
+ // Use yfinance info which includes insider transaction data
+ run_python_json("yfinance_data.py", {"info", symbol}, [cb, symbol](bool ok, QJsonValue val, QString err) {
+ if (!ok) { cb(false, {}, err); return; }
+ QJsonObject out;
+ out["symbol"] = symbol;
+ out["data"] = val;
+ out["node_type"] = "market.insider_trades";
+ cb(true, out, {});
+ });
},
});
@@ -355,9 +427,19 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"limit", "Limit", "number", 10, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>&,
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(false, not_implemented("market.sec_filings"), "not_yet_implemented");
+ QString symbol = params.value("symbol").toString();
+ if (symbol.isEmpty()) { cb(false, {}, "Symbol is required for SEC filings"); return; }
+ // Use yfinance info for basic company data including filings metadata
+ run_python_json("yfinance_data.py", {"info", symbol}, [cb, symbol](bool ok, QJsonValue val, QString err) {
+ if (!ok) { cb(false, {}, err); return; }
+ QJsonObject out;
+ out["symbol"] = symbol;
+ out["data"] = val;
+ out["node_type"] = "market.sec_filings";
+ cb(true, out, {});
+ });
},
});
}
diff --git a/fincept-qt/src/services/workspace/WorkspaceManager.cpp b/fincept-qt/src/services/workspace/WorkspaceManager.cpp
index 334605d20..781f04ced 100644
--- a/fincept-qt/src/services/workspace/WorkspaceManager.cpp
+++ b/fincept-qt/src/services/workspace/WorkspaceManager.cpp
@@ -34,11 +34,21 @@ WorkspaceManager::WorkspaceManager() {
// ── Setup ─────────────────────────────────────────────────────────────────────
void WorkspaceManager::set_main_window(QMainWindow* w) {
- main_window_ = w;
+ if (w && !windows_.contains(w))
+ windows_.append(w);
}
void WorkspaceManager::set_router(ScreenRouter* r) {
- router_ = r;
+ if (r && !routers_.contains(r))
+ routers_.append(r);
+}
+
+void WorkspaceManager::remove_window(QMainWindow* w) {
+ windows_.removeAll(w);
+}
+
+void WorkspaceManager::remove_router(ScreenRouter* r) {
+ routers_.removeAll(r);
}
// ── Participant registration ──────────────────────────────────────────────────
@@ -281,14 +291,14 @@ void WorkspaceManager::on_screen_changed(const QString& screen_id) {
void WorkspaceManager::capture_from_ui() {
if (!current_workspace_.has_value()) return;
- // Window geometry
- if (main_window_)
+ // Window geometry — use primary window (first registered)
+ if (!windows_.isEmpty())
current_workspace_->window_geometry_base64 =
- main_window_->saveGeometry().toBase64();
+ windows_.first()->saveGeometry().toBase64();
- // Active screen
- if (router_)
- current_workspace_->active_screen = router_->current_screen_id();
+ // Active screen — use primary router (first registered)
+ if (!routers_.isEmpty())
+ current_workspace_->active_screen = routers_.first()->current_screen_id();
// Per-screen states from participants
current_workspace_->screen_states.clear();
@@ -341,14 +351,14 @@ void WorkspaceManager::apply_to_ui() {
}
}
- // Restore window geometry
- if (main_window_ && !ws.window_geometry_base64.isEmpty())
- main_window_->restoreGeometry(
+ // Restore window geometry — apply to primary window
+ if (!windows_.isEmpty() && !ws.window_geometry_base64.isEmpty())
+ windows_.first()->restoreGeometry(
QByteArray::fromBase64(ws.window_geometry_base64.toLatin1()));
- // Navigate to active screen
- if (router_ && !ws.active_screen.isEmpty())
- router_->navigate(ws.active_screen);
+ // Navigate to active screen — apply to primary router
+ if (!routers_.isEmpty() && !ws.active_screen.isEmpty())
+ routers_.first()->navigate(ws.active_screen);
}
void WorkspaceManager::ensure_workspaces_dir() const {
diff --git a/fincept-qt/src/services/workspace/WorkspaceManager.h b/fincept-qt/src/services/workspace/WorkspaceManager.h
index 9a637eb8f..e2a9ebeba 100644
--- a/fincept-qt/src/services/workspace/WorkspaceManager.h
+++ b/fincept-qt/src/services/workspace/WorkspaceManager.h
@@ -24,10 +24,14 @@ class WorkspaceManager : public QObject {
public:
static WorkspaceManager& instance();
- /// Must be called once before any workspace operation.
+ /// Register a window/router. Multiple windows supported (multi-window mode).
void set_main_window(QMainWindow* w);
void set_router(ScreenRouter* r);
+ /// Unregister a closing window/router to prevent dangling pointers.
+ void remove_window(QMainWindow* w);
+ void remove_router(ScreenRouter* r);
+
// ── Screen participation ──────────────────────────────────────────────────
/// Called by screens in their constructor.
@@ -88,8 +92,10 @@ class WorkspaceManager : public QObject {
QHash<QString, IWorkspaceParticipant*> participants_;
QHash<QString, QJsonObject> pending_states_; // states waiting for lazy screens
- QMainWindow* main_window_ = nullptr;
- ScreenRouter* router_ = nullptr;
+ // Multi-window aware: stores all registered windows and routers.
+ // The first registered window is treated as primary for workspace operations.
+ QList<QMainWindow*> windows_;
+ QList<ScreenRouter*> routers_;
QTimer* autosave_timer_ = nullptr;
};
diff --git a/fincept-qt/src/storage/StorageManager.cpp b/fincept-qt/src/storage/StorageManager.cpp
new file mode 100644
index 000000000..acaba9b08
--- /dev/null
+++ b/fincept-qt/src/storage/StorageManager.cpp
@@ -0,0 +1,514 @@
+#include "storage/StorageManager.h"
+
+#include "core/config/AppPaths.h"
+#include "core/logging/Logger.h"
+#include "storage/cache/CacheManager.h"
+#include "storage/sqlite/CacheDatabase.h"
+#include "storage/sqlite/Database.h"
+
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QSettings>
+#include <QSqlQuery>
+
+namespace fincept {
+
+StorageManager& StorageManager::instance() {
+ static StorageManager s;
+ return s;
+}
+
+StorageManager::StorageManager(QObject* parent) : QObject(parent) {}
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+int StorageManager::count_table(const QString& table, const QString& where) const {
+ auto& db = Database::instance();
+ if (!db.is_open()) return 0;
+
+ QString sql = "SELECT COUNT(*) FROM " + table;
+ if (!where.isEmpty())
+ sql += " WHERE " + where;
+
+ auto r = db.execute(sql, {});
+ if (r.is_err()) return 0;
+ auto& q = r.value();
+ return q.next() ? q.value(0).toInt() : 0;
+}
+
+Result<void> StorageManager::delete_from(const QString& table, const QString& where) {
+ auto& db = Database::instance();
+ if (!db.is_open())
+ return Result<void>::err("Database not open");
+
+ QString sql = "DELETE FROM " + table;
+ if (!where.isEmpty())
+ sql += " WHERE " + where;
+
+ return db.exec(sql);
+}
+
+// ── Category definitions ─────────────────────────────────────────────────────
+
+QVector<StorageCategoryInfo> StorageManager::all_stats() const {
+ QVector<StorageCategoryInfo> stats;
+
+ // --- Cache (cache.db) ---
+ stats.append({"cache", "Temporary Cache", "Cache",
+ CacheManager::instance().entry_count(), true});
+
+ { // tab sessions from cache.db
+ int ts_count = 0;
+ auto& cdb = CacheDatabase::instance();
+ if (cdb.is_open()) {
+ auto r = cdb.execute("SELECT COUNT(*) FROM tab_sessions", {});
+ if (r.is_ok()) {
+ auto& q = r.value();
+ if (q.next()) ts_count = q.value(0).toInt();
+ }
+ }
+ stats.append({"tab_sessions", "Tab Session State", "Cache", ts_count, true});
+ }
+
+ // --- AI & LLM ---
+ stats.append({"chat_sessions", "Chat Sessions", "AI & LLM",
+ count_table("chat_sessions"), true});
+ stats.append({"chat_messages", "Chat Messages", "AI & LLM",
+ count_table("chat_messages"), true});
+ stats.append({"context_recordings","Context Recordings", "AI & LLM",
+ count_table("recorded_contexts"), true});
+ stats.append({"agent_configs", "Agent Configurations", "AI & LLM",
+ count_table("agent_configs"), true});
+ stats.append({"llm_configs", "LLM Provider Configs", "AI & LLM",
+ count_table("llm_configs"), true});
+ stats.append({"llm_model_configs", "LLM Model Configs", "AI & LLM",
+ count_table("llm_model_configs"), true});
+ stats.append({"llm_profiles", "LLM Profiles", "AI & LLM",
+ count_table("llm_profiles"), true});
+
+ // --- News ---
+ stats.append({"news_articles", "News Articles", "News",
+ count_table("news_articles"), true});
+ stats.append({"news_monitors", "News Monitors", "News",
+ count_table("news_monitors"), true});
+ stats.append({"rss_feeds", "RSS Feeds", "News",
+ count_table("user_rss_feeds"), true});
+
+ // --- Notes & Reports ---
+ stats.append({"notes", "Financial Notes", "Notes & Reports",
+ count_table("financial_notes"), true});
+ stats.append({"reports", "Reports", "Notes & Reports",
+ count_table("reports"), true});
+
+ // --- Portfolio & Trading ---
+ stats.append({"portfolios", "Portfolios", "Portfolio & Trading",
+ count_table("portfolios"), true});
+ stats.append({"transactions", "Transactions", "Portfolio & Trading",
+ count_table("portfolio_transactions"), true});
+ stats.append({"watchlists", "Watchlists", "Portfolio & Trading",
+ count_table("watchlists"), true});
+ stats.append({"custom_indices","Custom Indices", "Portfolio & Trading",
+ count_table("custom_indices"), true});
+
+ // --- Paper Trading ---
+ stats.append({"pt_portfolios", "Paper Portfolios", "Paper Trading",
+ count_table("pt_portfolios"), true});
+ stats.append({"pt_orders", "Paper Orders", "Paper Trading",
+ count_table("pt_orders"), true});
+ stats.append({"pt_trades", "Paper Trades", "Paper Trading",
+ count_table("pt_trades"), true});
+
+ // --- Workflows ---
+ stats.append({"workflows", "Workflows", "Workflows",
+ count_table("workflows"), true});
+
+ // --- Data Sources & Integration ---
+ stats.append({"data_sources", "Data Sources", "Data & Integration",
+ count_table("data_sources"), true});
+ stats.append({"data_mappings", "Data Mappings", "Data & Integration",
+ count_table("data_mappings"), true});
+ stats.append({"mcp_servers", "MCP Servers", "Data & Integration",
+ count_table("mcp_servers"), true});
+
+ // --- Dashboard ---
+ stats.append({"dashboard_layouts", "Dashboard Layouts", "Dashboard",
+ count_table("dashboard_layouts"), true});
+
+ // --- Broker ---
+ stats.append({"instruments", "Broker Instruments", "Broker",
+ count_table("instruments"), true});
+
+ // --- Settings & Credentials ---
+ stats.append({"settings", "App Settings", "Settings & Credentials",
+ count_table("settings"), true});
+ stats.append({"credentials", "Stored Credentials", "Settings & Credentials",
+ count_table("credentials"), true});
+ stats.append({"kv_storage", "Key-Value Storage", "Settings & Credentials",
+ count_table("key_value_storage"), true});
+
+ return stats;
+}
+
+int StorageManager::count_for(const QString& category_id) const {
+ // Cache categories go through CacheDatabase
+ if (category_id == "cache")
+ return CacheManager::instance().entry_count();
+
+ if (category_id == "tab_sessions") {
+ auto& cdb = CacheDatabase::instance();
+ if (!cdb.is_open()) return 0;
+ auto r = cdb.execute("SELECT COUNT(*) FROM tab_sessions", {});
+ if (r.is_err()) return 0;
+ auto& q = r.value();
+ return q.next() ? q.value(0).toInt() : 0;
+ }
+
+ // Map category_id → table name
+ static const QHash<QString, QString> table_map = {
+ {"chat_sessions", "chat_sessions"},
+ {"chat_messages", "chat_messages"},
+ {"context_recordings", "recorded_contexts"},
+ {"agent_configs", "agent_configs"},
+ {"llm_configs", "llm_configs"},
+ {"llm_model_configs", "llm_model_configs"},
+ {"llm_profiles", "llm_profiles"},
+ {"news_articles", "news_articles"},
+ {"news_monitors", "news_monitors"},
+ {"rss_feeds", "user_rss_feeds"},
+ {"notes", "financial_notes"},
+ {"reports", "reports"},
+ {"portfolios", "portfolios"},
+ {"transactions", "portfolio_transactions"},
+ {"watchlists", "watchlists"},
+ {"custom_indices", "custom_indices"},
+ {"pt_portfolios", "pt_portfolios"},
+ {"pt_orders", "pt_orders"},
+ {"pt_trades", "pt_trades"},
+ {"workflows", "workflows"},
+ {"data_sources", "data_sources"},
+ {"data_mappings", "data_mappings"},
+ {"mcp_servers", "mcp_servers"},
+ {"dashboard_layouts", "dashboard_layouts"},
+ {"instruments", "instruments"},
+ {"settings", "settings"},
+ {"credentials", "credentials"},
+ {"kv_storage", "key_value_storage"},
+ };
+
+ auto it = table_map.find(category_id);
+ if (it == table_map.end()) return 0;
+ return count_table(*it);
+}
+
+Result<void> StorageManager::clear_category(const QString& category_id) {
+ LOG_INFO("StorageManager", "Clearing category: " + category_id);
+
+ // --- Cache (cache.db) ---
+ if (category_id == "cache") {
+ CacheManager::instance().clear();
+ emit category_cleared(category_id);
+ return Result<void>::ok();
+ }
+
+ if (category_id == "tab_sessions") {
+ auto& cdb = CacheDatabase::instance();
+ if (!cdb.is_open())
+ return Result<void>::err("Cache database not open");
+ auto r = cdb.exec("DELETE FROM tab_sessions");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Chat: clear messages first (FK), then sessions ---
+ if (category_id == "chat_sessions") {
+ auto r1 = delete_from("chat_context_links");
+ auto r2 = delete_from("chat_messages");
+ auto r3 = delete_from("chat_sessions");
+ if (r3.is_err()) return r3;
+ emit category_cleared(category_id);
+ return Result<void>::ok();
+ }
+ if (category_id == "chat_messages") {
+ auto r = delete_from("chat_messages");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Context recordings ---
+ if (category_id == "context_recordings") {
+ auto r1 = delete_from("recording_sessions");
+ auto r2 = delete_from("recorded_contexts");
+ if (r2.is_err()) return r2;
+ emit category_cleared(category_id);
+ return Result<void>::ok();
+ }
+
+ // --- Agent configs ---
+ if (category_id == "agent_configs") {
+ auto r = delete_from("agent_configs");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- LLM configs ---
+ if (category_id == "llm_configs") {
+ delete_from("llm_global_settings");
+ auto r = delete_from("llm_configs");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+ if (category_id == "llm_model_configs") {
+ auto r = delete_from("llm_model_configs");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- LLM profiles + assignments ---
+ if (category_id == "llm_profiles") {
+ auto r1 = delete_from("llm_profile_assignments");
+ auto r2 = delete_from("llm_profiles");
+ if (r2.is_err()) return r2;
+ emit category_cleared(category_id);
+ return Result<void>::ok();
+ }
+
+ // --- News ---
+ if (category_id == "news_articles") {
+ delete_from("news_entity_cache");
+ delete_from("news_instability");
+ delete_from("news_baselines");
+ auto r = delete_from("news_articles");
+ // FTS table clears automatically with content table
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+ if (category_id == "news_monitors") {
+ auto r = delete_from("news_monitors");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+ if (category_id == "rss_feeds") {
+ auto r = delete_from("user_rss_feeds");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Notes ---
+ if (category_id == "notes") {
+ auto r = delete_from("financial_notes");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Reports ---
+ if (category_id == "reports") {
+ delete_from("report_templates");
+ auto r = delete_from("reports");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Portfolios (cascade: snapshots, assets, transactions) ---
+ if (category_id == "portfolios") {
+ delete_from("portfolio_snapshots");
+ delete_from("portfolio_transactions");
+ delete_from("portfolio_assets");
+ delete_from("portfolio_holdings");
+ auto r = delete_from("portfolios");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+ if (category_id == "transactions") {
+ auto r = delete_from("portfolio_transactions");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Watchlists ---
+ if (category_id == "watchlists") {
+ delete_from("watchlist_stocks");
+ auto r = delete_from("watchlists");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Custom indices ---
+ if (category_id == "custom_indices") {
+ delete_from("custom_index_values");
+ auto r = delete_from("custom_indices");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Paper Trading ---
+ if (category_id == "pt_portfolios") {
+ delete_from("pt_margin_blocks");
+ delete_from("pt_trades");
+ delete_from("pt_positions");
+ delete_from("pt_orders");
+ auto r = delete_from("pt_portfolios");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+ if (category_id == "pt_orders") {
+ auto r = delete_from("pt_orders");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+ if (category_id == "pt_trades") {
+ auto r = delete_from("pt_trades");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Workflows (cascade: edges, nodes) ---
+ if (category_id == "workflows") {
+ delete_from("workflow_edges");
+ delete_from("workflow_nodes");
+ auto r = delete_from("workflows");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Data sources ---
+ if (category_id == "data_sources") {
+ delete_from("data_source_connections");
+ delete_from("ws_provider_configs");
+ auto r = delete_from("data_sources");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+ if (category_id == "data_mappings") {
+ delete_from("normalized_data");
+ auto r = delete_from("data_mappings");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- MCP servers ---
+ if (category_id == "mcp_servers") {
+ delete_from("mcp_tool_usage_logs");
+ delete_from("mcp_tools");
+ delete_from("internal_mcp_tool_settings");
+ auto r = delete_from("mcp_servers");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Dashboard layouts ---
+ if (category_id == "dashboard_layouts") {
+ delete_from("dashboard_widget_instances");
+ auto r = delete_from("dashboard_layouts");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Broker instruments ---
+ if (category_id == "instruments") {
+ auto r = delete_from("instruments");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ // --- Settings & Credentials ---
+ if (category_id == "settings") {
+ auto r = delete_from("settings");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+ if (category_id == "credentials") {
+ auto r = delete_from("credentials");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+ if (category_id == "kv_storage") {
+ auto r = delete_from("key_value_storage");
+ if (r.is_ok()) emit category_cleared(category_id);
+ return r;
+ }
+
+ return Result<void>::err("Unknown category: " + category_id.toStdString());
+}
+
+// ── File sizes ───────────────────────────────────────────────────────────────
+
+qint64 StorageManager::main_db_size() const {
+ QFileInfo fi(AppPaths::data() + "/fincept.db");
+ if (!fi.exists()) return 0;
+ // Include WAL + SHM files
+ qint64 total = fi.size();
+ QFileInfo wal(AppPaths::data() + "/fincept.db-wal");
+ if (wal.exists()) total += wal.size();
+ QFileInfo shm(AppPaths::data() + "/fincept.db-shm");
+ if (shm.exists()) total += shm.size();
+ return total;
+}
+
+qint64 StorageManager::cache_db_size() const {
+ QFileInfo fi(AppPaths::data() + "/cache.db");
+ if (!fi.exists()) return 0;
+ qint64 total = fi.size();
+ QFileInfo wal(AppPaths::data() + "/cache.db-wal");
+ if (wal.exists()) total += wal.size();
+ QFileInfo shm(AppPaths::data() + "/cache.db-shm");
+ if (shm.exists()) total += shm.size();
+ return total;
+}
+
+qint64 StorageManager::log_files_size() const {
+ QDir dir(AppPaths::logs());
+ if (!dir.exists()) return 0;
+ qint64 total = 0;
+ for (const auto& fi : dir.entryInfoList(QDir::Files))
+ total += fi.size();
+ return total;
+}
+
+Result<void> StorageManager::clear_log_files() {
+ LOG_INFO("StorageManager", "Clearing log files");
+ QDir dir(AppPaths::logs());
+ if (!dir.exists())
+ return Result<void>::ok();
+
+ for (const auto& fi : dir.entryInfoList(QDir::Files)) {
+ QFile f(fi.absoluteFilePath());
+ if (f.open(QIODevice::WriteOnly | QIODevice::Truncate))
+ f.close();
+ }
+ emit category_cleared("log_files");
+ return Result<void>::ok();
+}
+
+qint64 StorageManager::workspace_files_size() const {
+ QDir dir(AppPaths::workspaces());
+ if (!dir.exists()) return 0;
+ qint64 total = 0;
+ for (const auto& fi : dir.entryInfoList({"*.fwsp"}, QDir::Files))
+ total += fi.size();
+ return total;
+}
+
+Result<void> StorageManager::clear_workspace_files() {
+ LOG_INFO("StorageManager", "Clearing workspace files");
+ QDir dir(AppPaths::workspaces());
+ if (!dir.exists())
+ return Result<void>::ok();
+
+ for (const auto& fi : dir.entryInfoList({"*.fwsp"}, QDir::Files)) {
+ QFile::remove(fi.absoluteFilePath());
+ }
+ emit category_cleared("workspaces");
+ return Result<void>::ok();
+}
+
+Result<void> StorageManager::clear_qsettings() {
+ LOG_INFO("StorageManager", "Clearing QSettings (window geometry, perspectives, UI state)");
+ QSettings settings("Fincept", "FinceptTerminal");
+ settings.clear();
+ settings.sync();
+ emit category_cleared("qsettings");
+ return Result<void>::ok();
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/StorageManager.h b/fincept-qt/src/storage/StorageManager.h
new file mode 100644
index 000000000..0eaf5ef85
--- /dev/null
+++ b/fincept-qt/src/storage/StorageManager.h
@@ -0,0 +1,66 @@
+#pragma once
+#include "core/result/Result.h"
+
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+namespace fincept {
+
+/// Per-category storage statistics.
+struct StorageCategoryInfo {
+ QString id; // e.g. "chat_history"
+ QString label; // e.g. "Chat History"
+ QString group; // e.g. "AI & LLM", "Trading", "Data"
+ int count = 0; // number of rows / entries
+ bool clearable = true;
+};
+
+/// Centralized manager for querying and clearing all persistent data stores.
+/// Wraps individual repositories and direct SQL for tables without bulk-delete methods.
+class StorageManager : public QObject {
+ Q_OBJECT
+ public:
+ static StorageManager& instance();
+
+ /// Returns stats for every data category.
+ QVector<StorageCategoryInfo> all_stats() const;
+
+ /// Returns entry count for a single category.
+ int count_for(const QString& category_id) const;
+
+ /// Clears all data in a single category. Returns error string on failure.
+ Result<void> clear_category(const QString& category_id);
+
+ /// Returns the on-disk size in bytes of fincept.db.
+ qint64 main_db_size() const;
+
+ /// Returns the on-disk size in bytes of cache.db.
+ qint64 cache_db_size() const;
+
+ /// Returns the on-disk size in bytes of log files.
+ qint64 log_files_size() const;
+
+ /// Clears log file contents (truncates).
+ Result<void> clear_log_files();
+
+ /// Returns total workspace file size.
+ qint64 workspace_files_size() const;
+
+ /// Deletes all workspace files.
+ Result<void> clear_workspace_files();
+
+ /// Clears all QSettings (window geometry, perspectives, UI state).
+ Result<void> clear_qsettings();
+
+ signals:
+ void category_cleared(const QString& category_id);
+
+ private:
+ explicit StorageManager(QObject* parent = nullptr);
+
+ int count_table(const QString& table, const QString& where = {}) const;
+ Result<void> delete_from(const QString& table, const QString& where = {});
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/CacheDatabase.h b/fincept-qt/src/storage/sqlite/CacheDatabase.h
index 9cfb05272..b818585f6 100644
--- a/fincept-qt/src/storage/sqlite/CacheDatabase.h
+++ b/fincept-qt/src/storage/sqlite/CacheDatabase.h
@@ -22,6 +22,8 @@ class CacheDatabase {
Result<QSqlQuery> execute(const QString& sql, const QVariantList& params = {});
Result<void> exec(const QString& sql);
+ QSqlDatabase& raw_db() { return db_; }
+
private:
CacheDatabase() = default;
Result<void> apply_pragmas();
diff --git a/fincept-qt/src/ui/navigation/CommandBar.cpp b/fincept-qt/src/ui/navigation/CommandBar.cpp
index c2beca187..ea16e135e 100644
--- a/fincept-qt/src/ui/navigation/CommandBar.cpp
+++ b/fincept-qt/src/ui/navigation/CommandBar.cpp
@@ -2,6 +2,7 @@
#include "core/events/EventBus.h"
#include "network/http/HttpClient.h"
+#include "ui/theme/Theme.h"
#include <QApplication>
#include <QEvent>
@@ -10,6 +11,7 @@
#include <QJsonObject>
#include <QKeyEvent>
#include <QListWidgetItem>
+#include <QRegularExpression>
#include <QScreen>
#include <QVBoxLayout>
@@ -20,41 +22,55 @@ static constexpr int kSearchDebounceMs = 300;
// ── styling ─────────────────────────────────────────────────────────────────
-static const char* INPUT_SS =
- "QLineEdit{"
- " background:#111111;"
- " color:#e5e5e5;"
- " border:1px solid #2a2a2a;"
- " padding:2px 8px 2px 24px;"
- " font-size:12px;"
- " font-family:'Consolas',monospace;"
- "}"
- "QLineEdit:focus{"
- " border:1px solid #d97706;"
- "}";
-
-static const char* DROP_SS =
- "QFrame{"
- " background:#0e0e0e;"
- " border:1px solid #2a2a2a;"
- " border-top:none;"
- "}";
-
-static const char* LIST_SS =
- "QListWidget{"
- " background:transparent;"
- " border:none;"
- " outline:none;"
- "}"
- "QListWidget::item{"
- " padding:0px;"
- " border:none;"
- " background:transparent;"
- "}"
- "QListWidget::item:selected{"
- " background:#1a1a1a;"
- " border-left:3px solid #d97706;"
- "}";
+static QString input_ss() {
+ return QString(
+ "QLineEdit{"
+ " background:%1;"
+ " color:%2;"
+ " border:1px solid %3;"
+ " padding:2px 8px 2px 24px;"
+ " font-size:12px;"
+ " font-family:'Consolas',monospace;"
+ "}"
+ "QLineEdit:focus{"
+ " border:1px solid %4;"
+ "}")
+ .arg(colors::BG_RAISED.get())
+ .arg(colors::TEXT_PRIMARY.get())
+ .arg(colors::BORDER_MED.get())
+ .arg(colors::AMBER.get());
+}
+
+static QString drop_ss() {
+ return QString(
+ "QFrame{"
+ " background:%1;"
+ " border:1px solid %2;"
+ " border-top:none;"
+ "}")
+ .arg(colors::BG_SURFACE.get())
+ .arg(colors::BORDER_MED.get());
+}
+
+static QString list_ss() {
+ return QString(
+ "QListWidget{"
+ " background:transparent;"
+ " border:none;"
+ " outline:none;"
+ "}"
+ "QListWidget::item{"
+ " padding:0px;"
+ " border:none;"
+ " background:transparent;"
+ "}"
+ "QListWidget::item:selected{"
+ " background:%1;"
+ " border-left:3px solid %2;"
+ "}")
+ .arg(colors::BG_RAISED.get())
+ .arg(colors::AMBER.get());
+}
// ── yfinance symbol conversion ───────────────────────────────────────────────
@@ -239,7 +255,7 @@ CommandBar::CommandBar(QWidget* parent) : QWidget(parent) {
input_ = new QLineEdit(this);
input_->setFixedHeight(24);
input_->setPlaceholderText("> Enter Command or /type ...");
- input_->setStyleSheet(INPUT_SS);
+ input_->setStyleSheet(input_ss());
input_->installEventFilter(this);
hl->addWidget(input_);
@@ -247,14 +263,14 @@ CommandBar::CommandBar(QWidget* parent) : QWidget(parent) {
dropdown_ = new QFrame(nullptr);
dropdown_->setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);
dropdown_->setAttribute(Qt::WA_ShowWithoutActivating);
- dropdown_->setStyleSheet(DROP_SS);
+ dropdown_->setStyleSheet(drop_ss());
auto* vl = new QVBoxLayout(dropdown_);
vl->setContentsMargins(0, 0, 0, 0);
vl->setSpacing(0);
list_ = new QListWidget(dropdown_);
- list_->setStyleSheet(LIST_SS);
+ list_->setStyleSheet(list_ss());
list_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
list_->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
list_->setMouseTracking(true);
@@ -331,6 +347,8 @@ bool CommandBar::eventFilter(QObject* obj, QEvent* event) {
input_->clear();
mode_ = Mode::Screen;
active_asset_type_.clear();
+ dock_primary_id_.clear();
+ dock_verb_.clear();
search_debounce_->stop();
hide_dropdown();
input_->clearFocus();
@@ -381,7 +399,7 @@ void CommandBar::on_text_changed(const QString& text) {
auto* rl = new QHBoxLayout(row);
rl->setContentsMargins(10, 6, 10, 6);
auto* hint = new QLabel(QString("Type a symbol or name to search %1s...").arg(active_asset_type_));
- hint->setStyleSheet("color:#525252;font-size:11px;font-family:'Consolas',monospace;background:transparent;");
+ hint->setStyleSheet(QString("color:%1;font-size:11px;font-family:'Consolas',monospace;background:transparent;").arg(colors::TEXT_TERTIARY.get()));
rl->addWidget(hint);
item->setSizeHint(QSize(0, 30));
list_->setItemWidget(item, row);
@@ -415,8 +433,102 @@ void CommandBar::on_text_changed(const QString& text) {
return;
}
+ // ── DockSecondary: user picked a verb and is typing the second screen ──────
+ if (mode_ == Mode::DockSecondary && !dock_primary_id_.isEmpty() && !dock_verb_.isEmpty()) {
+ // Text looks like: "<primary> <verb> <partial>"
+ // Find the verb position and extract everything after it
+ const QString lower = trimmed.toLower();
+ for (const QString& v : {QString("add"), QString("replace")}) {
+ const int vi = lower.indexOf(" " + v + " ");
+ if (vi >= 0) {
+ const QString partial = trimmed.mid(vi + v.length() + 2);
+ show_dock_secondary_suggestions(v, partial);
+ return;
+ }
+ // verb at end with no second token yet
+ if (lower.endsWith(" " + v)) {
+ show_dock_secondary_suggestions(v, {});
+ return;
+ }
+ }
+ }
+
+ // ── DockCommand: user already resolved primary, picking verb ────────────
+ if (mode_ == Mode::DockCommand && !dock_primary_id_.isEmpty()) {
+ // Stay in DockCommand until they type something non-verb-like
+ const QString after_space = trimmed.mid(trimmed.indexOf(' ') + 1).toLower().trimmed();
+ // If they've typed "add " or "replace " transition to DockSecondary
+ if (after_space.startsWith("add ") || after_space.startsWith("replace ")) {
+ dock_verb_ = after_space.startsWith("add") ? "add" : "replace";
+ mode_ = Mode::DockSecondary;
+ const QString partial = after_space.mid(after_space.indexOf(' ') + 1);
+ show_dock_secondary_suggestions(dock_verb_, partial);
+ return;
+ }
+ // Still picking verb — re-show verb suggestions
+ show_dock_verb_suggestions(dock_primary_id_);
+ return;
+ }
+
+ // ── Detect "<valid_screen> " (space after a known screen) ───────────────
+ if (trimmed.endsWith(' ') || trimmed.contains(' ')) {
+ const int space = trimmed.indexOf(' ');
+ if (space > 0) {
+ const QString first_token = trimmed.left(space);
+ const QString resolved = resolve_screen_id(first_token);
+ if (!resolved.isEmpty()) {
+ // Check if the second token is "remove" — that's a complete command
+ const QString rest = trimmed.mid(space + 1).trimmed().toLower();
+ if (rest == "remove") {
+ // Show hint that Enter will execute
+ list_->clear();
+ auto* item = new QListWidgetItem(list_);
+ item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
+ auto* row = new QWidget;
+ row->setStyleSheet("background:transparent;");
+ auto* hl2 = new QHBoxLayout(row);
+ hl2->setContentsMargins(10, 6, 10, 6);
+ auto* lbl = new QLabel(QString("Press Enter to close all except %1")
+ .arg(resolve_screen_id(first_token).toUpper().replace("_", " ")));
+ lbl->setStyleSheet(QString("color:%1;font-size:11px;"
+ "font-family:'Consolas',monospace;background:transparent;")
+ .arg(colors::AMBER.get()));
+ hl2->addWidget(lbl);
+ item->setSizeHint(QSize(0, 30));
+ list_->setItemWidget(item, row);
+ show_dropdown();
+ dock_primary_id_ = resolved;
+ mode_ = Mode::DockCommand;
+ return;
+ }
+ // Transition to DockCommand — show verb suggestions
+ if (rest.isEmpty() || rest == "a" || rest == "ad" ||
+ rest == "r" || rest == "re" || rest == "rep") {
+ dock_primary_id_ = resolved;
+ dock_verb_.clear();
+ mode_ = Mode::DockCommand;
+ show_dock_verb_suggestions(resolved);
+ return;
+ }
+ // They're typing "add X" or "replace X"
+ if (rest.startsWith("add") || rest.startsWith("replace")) {
+ dock_primary_id_ = resolved;
+ const QString verb = rest.startsWith("add") ? "add" : "replace";
+ dock_verb_ = verb;
+ mode_ = Mode::DockSecondary;
+ const int vi = rest.indexOf(' ');
+ const QString partial = vi >= 0 ? rest.mid(vi + 1) : QString();
+ show_dock_secondary_suggestions(verb, partial);
+ return;
+ }
+ }
+ }
+ }
+
// ── Normal screen command search ────────────────────────────────────────
mode_ = Mode::Screen;
+ dock_primary_id_.clear();
+ dock_verb_.clear();
active_asset_type_.clear();
const auto results = search(text);
@@ -438,16 +550,16 @@ void CommandBar::on_text_changed(const QString& text) {
hl->setSpacing(6);
auto* alias_lbl = new QLabel(cmd.aliases.first().toUpper());
- alias_lbl->setStyleSheet("color:#e5e5e5;font-size:11px;font-weight:700;"
- "font-family:'Consolas',monospace;background:transparent;");
+ alias_lbl->setStyleSheet(QString("color:%1;font-size:11px;font-weight:700;"
+ "font-family:'Consolas',monospace;background:transparent;").arg(colors::TEXT_PRIMARY.get()));
alias_lbl->setFixedWidth(72);
auto* sep_lbl = new QLabel(QStringLiteral("\u203A"));
- sep_lbl->setStyleSheet("color:#525252;font-size:12px;background:transparent;");
+ sep_lbl->setStyleSheet(QString("color:%1;font-size:12px;background:transparent;").arg(colors::TEXT_TERTIARY.get()));
auto* name_lbl = new QLabel(cmd.name);
- name_lbl->setStyleSheet("color:#a3a3a3;font-size:11px;background:transparent;"
- "font-family:'Consolas',monospace;");
+ name_lbl->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;"
+ "font-family:'Consolas',monospace;").arg(colors::TEXT_SECONDARY.get()));
hl->addWidget(alias_lbl);
hl->addWidget(sep_lbl);
@@ -455,8 +567,8 @@ void CommandBar::on_text_changed(const QString& text) {
if (!cmd.shortcut.isEmpty()) {
auto* sc_lbl = new QLabel(cmd.shortcut);
- sc_lbl->setStyleSheet("color:#404040;font-size:10px;font-family:'Consolas',monospace;"
- "background:transparent;");
+ sc_lbl->setStyleSheet(QString("color:%1;font-size:10px;font-family:'Consolas',monospace;"
+ "background:transparent;").arg(colors::TEXT_DIM.get()));
hl->addWidget(sc_lbl);
}
@@ -484,9 +596,12 @@ void CommandBar::on_return_pressed() {
}
if (!dropdown_->isVisible() || !list_->currentItem()) {
- // In screen mode only: allow direct alias lookup without dropdown
if (mode_ == Mode::Screen) {
- const auto results = search(input_->text());
+ const QString text = input_->text().trimmed();
+ // Try compound dock command first: "X add Y", "X replace Y", "X remove"
+ if (try_parse_dock_command(text)) return;
+ // Fall back to simple screen navigation
+ const auto results = search(text);
if (!results.isEmpty()) {
emit navigate_to(results.first().id);
input_->clear();
@@ -542,6 +657,39 @@ void CommandBar::on_item_clicked(QListWidgetItem* item) {
return;
}
+ if (mode_ == Mode::DockCommand) {
+ // User clicked a verb (add/replace/remove)
+ const QString verb = item->data(Qt::UserRole).toString();
+ const QString primary = item->data(Qt::UserRole + 1).toString();
+ if (verb == "remove") {
+ emit dock_command("remove", primary, {});
+ input_->clear(); mode_ = Mode::Screen;
+ dock_primary_id_.clear(); dock_verb_.clear();
+ hide_dropdown(); input_->clearFocus();
+ } else {
+ // Transition to secondary — append verb to input
+ dock_verb_ = verb;
+ mode_ = Mode::DockSecondary;
+ const QString current = input_->text().trimmed();
+ input_->setText(current.endsWith(' ') ? current + verb + " "
+ : current + " " + verb + " ");
+ input_->setCursorPosition(input_->text().length());
+ input_->setFocus();
+ show_dock_secondary_suggestions(verb, {});
+ }
+ return;
+ }
+
+ if (mode_ == Mode::DockSecondary) {
+ const QString secondary_id = item->data(Qt::UserRole).toString();
+ if (secondary_id.isEmpty()) return; // header row
+ emit dock_command(dock_verb_, dock_primary_id_, secondary_id);
+ input_->clear(); mode_ = Mode::Screen;
+ dock_primary_id_.clear(); dock_verb_.clear();
+ hide_dropdown(); input_->clearFocus();
+ return;
+ }
+
// Screen mode
emit navigate_to(item->data(Qt::UserRole).toString());
input_->clear();
@@ -574,16 +722,16 @@ void CommandBar::show_slash_suggestions(const QString& partial) {
hl->setSpacing(8);
auto* slash_lbl = new QLabel(at.slash);
- slash_lbl->setStyleSheet("color:#d97706;font-size:12px;font-weight:700;"
- "font-family:'Consolas',monospace;background:transparent;");
+ slash_lbl->setStyleSheet(QString("color:%1;font-size:12px;font-weight:700;"
+ "font-family:'Consolas',monospace;background:transparent;").arg(colors::AMBER.get()));
slash_lbl->setFixedWidth(80);
auto* sep_lbl = new QLabel(QStringLiteral("\u203A"));
- sep_lbl->setStyleSheet("color:#525252;font-size:12px;background:transparent;");
+ sep_lbl->setStyleSheet(QString("color:%1;font-size:12px;background:transparent;").arg(colors::TEXT_TERTIARY.get()));
auto* desc_lbl = new QLabel(at.description);
- desc_lbl->setStyleSheet("color:#a3a3a3;font-size:11px;background:transparent;"
- "font-family:'Consolas',monospace;");
+ desc_lbl->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;"
+ "font-family:'Consolas',monospace;").arg(colors::TEXT_SECONDARY.get()));
hl->addWidget(slash_lbl);
hl->addWidget(sep_lbl);
@@ -651,7 +799,7 @@ void CommandBar::on_asset_results(const QJsonArray& results) {
auto* rl = new QHBoxLayout(row);
rl->setContentsMargins(10, 6, 10, 6);
auto* lbl = new QLabel("No results found");
- lbl->setStyleSheet("color:#525252;font-size:11px;font-family:'Consolas',monospace;background:transparent;");
+ lbl->setStyleSheet(QString("color:%1;font-size:11px;font-family:'Consolas',monospace;background:transparent;").arg(colors::TEXT_TERTIARY.get()));
rl->addWidget(lbl);
item->setSizeHint(QSize(0, 30));
list_->setItemWidget(item, row);
@@ -684,13 +832,13 @@ void CommandBar::on_asset_results(const QJsonArray& results) {
hl->setSpacing(8);
auto* sym_lbl = new QLabel(yf_symbol);
- sym_lbl->setStyleSheet("color:#e5e5e5;font-size:12px;font-weight:700;"
- "font-family:'Consolas',monospace;background:transparent;");
+ sym_lbl->setStyleSheet(QString("color:%1;font-size:12px;font-weight:700;"
+ "font-family:'Consolas',monospace;background:transparent;").arg(colors::TEXT_PRIMARY.get()));
sym_lbl->setFixedWidth(110);
auto* name_lbl = new QLabel(name);
- name_lbl->setStyleSheet("color:#a3a3a3;font-size:11px;background:transparent;"
- "font-family:'Consolas',monospace;");
+ name_lbl->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;"
+ "font-family:'Consolas',monospace;").arg(colors::TEXT_SECONDARY.get()));
name_lbl->setMaximumWidth(200);
hl->addWidget(sym_lbl);
@@ -698,16 +846,17 @@ void CommandBar::on_asset_results(const QJsonArray& results) {
if (!exchange.isEmpty()) {
auto* exch_lbl = new QLabel(exchange);
- exch_lbl->setStyleSheet("color:#525252;font-size:10px;font-family:'Consolas',monospace;"
- "background:transparent;");
+ exch_lbl->setStyleSheet(QString("color:%1;font-size:10px;font-family:'Consolas',monospace;"
+ "background:transparent;").arg(colors::TEXT_TERTIARY.get()));
hl->addWidget(exch_lbl);
}
// Type badge
auto* type_lbl = new QLabel(type.toUpper());
- type_lbl->setStyleSheet("color:#d97706;font-size:9px;font-weight:700;"
- "font-family:'Consolas',monospace;background:#1a1a1a;"
- "padding:1px 4px;border-radius:2px;");
+ type_lbl->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;"
+ "font-family:'Consolas',monospace;background:%2;"
+ "padding:1px 4px;border-radius:2px;")
+ .arg(colors::AMBER.get()).arg(colors::BG_RAISED.get()));
hl->addWidget(type_lbl);
item->setSizeHint(QSize(0, 32));
@@ -738,6 +887,179 @@ void CommandBar::select_asset(const QString& symbol, const QString& type) {
// ── dropdown helpers ─────────────────────────────────────────────────────────
+void CommandBar::show_dock_verb_suggestions(const QString& primary_id) {
+ // Show add / replace / remove as clickable suggestions after "<screen> "
+ list_->clear();
+
+ struct Verb { QString verb; QString label; QString hint; };
+ const QList<Verb> verbs = {
+ {"add", "ADD", "Open a second screen alongside"},
+ {"replace", "REPLACE", "Close this screen, open another"},
+ {"remove", "REMOVE", "Close all other screens"},
+ };
+
+ for (const auto& v : verbs) {
+ auto* item = new QListWidgetItem(list_);
+ item->setData(Qt::UserRole, v.verb); // verb
+ item->setData(Qt::UserRole + 1, primary_id); // primary screen id
+
+ auto* row = new QWidget;
+ row->setStyleSheet("background:transparent;");
+ auto* hl = new QHBoxLayout(row);
+ hl->setContentsMargins(10, 5, 10, 5);
+ hl->setSpacing(8);
+
+ auto* verb_lbl = new QLabel(v.verb.toUpper());
+ verb_lbl->setStyleSheet(
+ QString("color:%1;font-size:11px;font-weight:700;"
+ "font-family:'Consolas',monospace;background:transparent;")
+ .arg(colors::AMBER.get()));
+ verb_lbl->setFixedWidth(64);
+
+ auto* sep = new QLabel(QStringLiteral("\u203A"));
+ sep->setStyleSheet(QString("color:%1;font-size:12px;background:transparent;")
+ .arg(colors::TEXT_TERTIARY.get()));
+
+ auto* hint_lbl = new QLabel(v.hint);
+ hint_lbl->setStyleSheet(
+ QString("color:%1;font-size:11px;font-family:'Consolas',monospace;background:transparent;")
+ .arg(colors::TEXT_SECONDARY.get()));
+
+ hl->addWidget(verb_lbl);
+ hl->addWidget(sep);
+ hl->addWidget(hint_lbl, 1);
+ item->setSizeHint(QSize(0, 30));
+ list_->setItemWidget(item, row);
+ }
+
+ list_->setCurrentRow(0);
+ show_dropdown();
+}
+
+void CommandBar::show_dock_secondary_suggestions(const QString& verb, const QString& partial) {
+ // Show filtered screen list as the second screen for add/replace
+ const auto results = search(partial.trimmed().isEmpty() ? QString() : partial);
+ list_->clear();
+
+ // Header hint row
+ {
+ auto* item = new QListWidgetItem(list_);
+ item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
+ auto* row = new QWidget;
+ row->setStyleSheet("background:transparent;");
+ auto* hl = new QHBoxLayout(row);
+ hl->setContentsMargins(10, 4, 10, 4);
+ auto* lbl = new QLabel(QString("%1 — pick a screen:").arg(verb.toUpper()));
+ lbl->setStyleSheet(
+ QString("color:%1;font-size:10px;font-family:'Consolas',monospace;background:transparent;")
+ .arg(colors::AMBER.get()));
+ hl->addWidget(lbl);
+ item->setSizeHint(QSize(0, 24));
+ list_->setItemWidget(item, row);
+ }
+
+ const auto& pool = results.isEmpty() ? commands_ : results;
+ for (const auto& cmd : pool) {
+ auto* item = new QListWidgetItem(list_);
+ item->setData(Qt::UserRole, cmd.id);
+ item->setData(Qt::UserRole + 1, cmd.aliases.first());
+
+ auto* row = new QWidget;
+ row->setStyleSheet("background:transparent;");
+ auto* hl = new QHBoxLayout(row);
+ hl->setContentsMargins(10, 5, 10, 5);
+ hl->setSpacing(6);
+
+ auto* alias_lbl = new QLabel(cmd.aliases.first().toUpper());
+ alias_lbl->setStyleSheet(
+ QString("color:%1;font-size:11px;font-weight:700;"
+ "font-family:'Consolas',monospace;background:transparent;")
+ .arg(colors::TEXT_PRIMARY.get()));
+ alias_lbl->setFixedWidth(72);
+
+ auto* sep = new QLabel(QStringLiteral("\u203A"));
+ sep->setStyleSheet(QString("color:%1;font-size:12px;background:transparent;")
+ .arg(colors::TEXT_TERTIARY.get()));
+
+ auto* name_lbl = new QLabel(cmd.name);
+ name_lbl->setStyleSheet(
+ QString("color:%1;font-size:11px;font-family:'Consolas',monospace;background:transparent;")
+ .arg(colors::TEXT_SECONDARY.get()));
+
+ hl->addWidget(alias_lbl);
+ hl->addWidget(sep);
+ hl->addWidget(name_lbl, 1);
+ item->setSizeHint(QSize(0, 30));
+ list_->setItemWidget(item, row);
+ }
+
+ if (list_->count() > 1) list_->setCurrentRow(1); // skip header
+ show_dropdown();
+}
+
+QString CommandBar::resolve_screen_id(const QString& token) const {
+ const QString t = token.trimmed().toLower();
+ // Direct id match
+ for (const auto& cmd : commands_)
+ if (cmd.id == t) return cmd.id;
+ // Alias / name match (same logic as search())
+ for (const auto& cmd : commands_) {
+ if (cmd.name.toLower() == t) return cmd.id;
+ for (const auto& a : cmd.aliases)
+ if (a.toLower() == t) return cmd.id;
+ }
+ // Keyword prefix
+ const auto results = search(t);
+ if (!results.isEmpty()) return results.first().id;
+ return {};
+}
+
+bool CommandBar::try_parse_dock_command(const QString& text) {
+ // Only active in Screen mode — not during asset search or slash picker
+ if (mode_ != Mode::Screen) return false;
+
+ const QString t = text.trimmed();
+
+ // Match: "<primary> add <secondary>"
+ static const QRegularExpression re_add(
+ R"(^(.+?)\s+add\s+(.+)$)", QRegularExpression::CaseInsensitiveOption);
+ // Match: "<primary> replace <secondary>"
+ static const QRegularExpression re_replace(
+ R"(^(.+?)\s+replace\s+(.+)$)", QRegularExpression::CaseInsensitiveOption);
+ // Match: "<primary> remove"
+ static const QRegularExpression re_remove(
+ R"(^(.+?)\s+remove$)", QRegularExpression::CaseInsensitiveOption);
+
+ auto m_add = re_add.match(t);
+ auto m_replace = re_replace.match(t);
+ auto m_remove = re_remove.match(t);
+
+ if (m_add.hasMatch()) {
+ const QString primary = resolve_screen_id(m_add.captured(1));
+ const QString secondary = resolve_screen_id(m_add.captured(2));
+ if (primary.isEmpty() || secondary.isEmpty()) return false;
+ emit dock_command("add", primary, secondary);
+ input_->clear(); hide_dropdown(); input_->clearFocus();
+ return true;
+ }
+ if (m_replace.hasMatch()) {
+ const QString primary = resolve_screen_id(m_replace.captured(1));
+ const QString secondary = resolve_screen_id(m_replace.captured(2));
+ if (primary.isEmpty() || secondary.isEmpty()) return false;
+ emit dock_command("replace", primary, secondary);
+ input_->clear(); hide_dropdown(); input_->clearFocus();
+ return true;
+ }
+ if (m_remove.hasMatch()) {
+ const QString primary = resolve_screen_id(m_remove.captured(1));
+ if (primary.isEmpty()) return false;
+ emit dock_command("remove", primary, {});
+ input_->clear(); hide_dropdown(); input_->clearFocus();
+ return true;
+ }
+ return false;
+}
+
void CommandBar::execute_index(int index) {
auto* item = list_->item(index);
if (!item) return;
diff --git a/fincept-qt/src/ui/navigation/CommandBar.h b/fincept-qt/src/ui/navigation/CommandBar.h
index 06579f829..51c0e76b9 100644
--- a/fincept-qt/src/ui/navigation/CommandBar.h
+++ b/fincept-qt/src/ui/navigation/CommandBar.h
@@ -36,6 +36,14 @@ class CommandBar : public QWidget {
signals:
void navigate_to(const QString& screen_id);
+ // Emitted when the user types a compound command:
+ // "markets add settings" → action="add", primary="markets", secondary="settings"
+ // "markets replace news" → action="replace", primary="markets", secondary="news"
+ // "markets remove" → action="remove", primary="markets", secondary=""
+ void dock_command(const QString& action,
+ const QString& primary,
+ const QString& secondary);
+
protected:
bool eventFilter(QObject* obj, QEvent* event) override;
@@ -56,7 +64,13 @@ class CommandBar : public QWidget {
QVector<ScreenCommand> search(const QString& query) const;
// ── Slash-command asset search ─────────────────────────────────────────────
- enum class Mode { Screen, SlashPicker, AssetSearch };
+ enum class Mode {
+ Screen, // normal screen search
+ SlashPicker, // user typed "/" — picking asset type
+ AssetSearch, // user picked /type and is typing a symbol
+ DockCommand, // user typed a valid screen + space — picking add/replace/remove
+ DockSecondary // user picked add/replace — picking the second screen
+ };
Mode mode_ = Mode::Screen;
QVector<AssetType> asset_types_;
@@ -72,6 +86,15 @@ class CommandBar : public QWidget {
void on_asset_results(const QJsonArray& results);
void select_asset(const QString& symbol, const QString& type);
+ // ── Compound dock command parser ──────────────────────────────────────────
+ bool try_parse_dock_command(const QString& text);
+ QString resolve_screen_id(const QString& token) const;
+ void show_dock_verb_suggestions(const QString& primary_id);
+ void show_dock_secondary_suggestions(const QString& verb, const QString& partial);
+
+ QString dock_primary_id_; // screen id locked in after user types "<screen> "
+ QString dock_verb_; // "add" or "replace" — locked in after user picks verb
+
// ── Dropdown helpers ───────────────────────────────────────────────────────
void show_dropdown();
void hide_dropdown();
diff --git a/fincept-qt/src/ui/navigation/DockStatusBar.cpp b/fincept-qt/src/ui/navigation/DockStatusBar.cpp
new file mode 100644
index 000000000..98b66a70a
--- /dev/null
+++ b/fincept-qt/src/ui/navigation/DockStatusBar.cpp
@@ -0,0 +1,13 @@
+#include "ui/navigation/DockStatusBar.h"
+
+namespace fincept::ui {
+
+DockStatusBar::DockStatusBar(QWidget* parent) : QStatusBar(parent) {
+ inner_ = new StatusBar(this);
+ addPermanentWidget(inner_, 1);
+ setFixedHeight(26);
+ setSizeGripEnabled(false);
+ setStyleSheet("QStatusBar{border:none;padding:0;margin:0;}");
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/navigation/DockStatusBar.h b/fincept-qt/src/ui/navigation/DockStatusBar.h
new file mode 100644
index 000000000..9c208d7fa
--- /dev/null
+++ b/fincept-qt/src/ui/navigation/DockStatusBar.h
@@ -0,0 +1,22 @@
+#pragma once
+#include "ui/navigation/StatusBar.h"
+
+#include <QStatusBar>
+
+namespace fincept::ui {
+
+/// QStatusBar wrapper around the existing StatusBar widget.
+/// Used with QMainWindow::setStatusBar() so the status bar lives outside
+/// CDockManager's central widget area — no layout conflicts.
+class DockStatusBar : public QStatusBar {
+ Q_OBJECT
+ public:
+ explicit DockStatusBar(QWidget* parent = nullptr);
+
+ StatusBar* inner() const { return inner_; }
+
+ private:
+ StatusBar* inner_ = nullptr;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/navigation/DockToolBar.cpp b/fincept-qt/src/ui/navigation/DockToolBar.cpp
new file mode 100644
index 000000000..9d4bb0600
--- /dev/null
+++ b/fincept-qt/src/ui/navigation/DockToolBar.cpp
@@ -0,0 +1,16 @@
+#include "ui/navigation/DockToolBar.h"
+
+namespace fincept::ui {
+
+DockToolBar::DockToolBar(QWidget* parent) : QToolBar("Main Toolbar", parent) {
+ setMovable(false);
+ setFloatable(false);
+ setAllowedAreas(Qt::TopToolBarArea);
+ setFixedHeight(32);
+ setStyleSheet("QToolBar{border:none;spacing:0;padding:0;margin:0;}");
+
+ inner_ = new ToolBar(this);
+ addWidget(inner_);
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/navigation/DockToolBar.h b/fincept-qt/src/ui/navigation/DockToolBar.h
new file mode 100644
index 000000000..c23591a31
--- /dev/null
+++ b/fincept-qt/src/ui/navigation/DockToolBar.h
@@ -0,0 +1,22 @@
+#pragma once
+#include "ui/navigation/ToolBar.h"
+
+#include <QToolBar>
+
+namespace fincept::ui {
+
+/// QToolBar wrapper around the existing ToolBar widget.
+/// Used with QMainWindow::addToolBar() so the toolbar lives outside
+/// CDockManager's central widget area — no layout conflicts.
+class DockToolBar : public QToolBar {
+ Q_OBJECT
+ public:
+ explicit DockToolBar(QWidget* parent = nullptr);
+
+ ToolBar* inner() const { return inner_; }
+
+ private:
+ ToolBar* inner_ = nullptr;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/navigation/FKeyBar.cpp b/fincept-qt/src/ui/navigation/FKeyBar.cpp
index 99fbca8f0..7fb0e3c95 100644
--- a/fincept-qt/src/ui/navigation/FKeyBar.cpp
+++ b/fincept-qt/src/ui/navigation/FKeyBar.cpp
@@ -6,7 +6,8 @@ namespace fincept::ui {
TabBar::TabBar(QWidget* parent) : QWidget(parent) {
setFixedHeight(32);
- setStyleSheet("background:#0e0e0e;border-bottom:1px solid #1a1a1a;");
+ setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(colors::BG_BASE).arg(colors::BORDER_DIM));
auto* scroll_area = new QScrollArea(this);
scroll_area->setWidgetResizable(true);
scroll_area->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
@@ -68,11 +69,14 @@ void TabBar::set_active(const QString& tab_id) {
void TabBar::update_styles() {
for (auto* btn : tab_buttons_) {
bool active = btn->property("tab_id").toString() == active_id_;
- btn->setStyleSheet(active ? "QPushButton{background:#b45309;color:#e5e5e5;border:1px solid #4d3300;"
- "padding:0 8px;font-weight:600;letter-spacing:0.5px;}"
- : "QPushButton{background:transparent;color:#ffffff;border:none;"
- "padding:0 8px;letter-spacing:0.5px;}"
- "QPushButton:hover{color:#d97706;background:#111111;}");
+ btn->setStyleSheet(active
+ ? QString("QPushButton{background:%1;color:%2;border:1px solid %3;"
+ "padding:0 8px;font-weight:600;letter-spacing:0.5px;}")
+ .arg(colors::AMBER).arg(colors::TEXT_PRIMARY).arg(colors::AMBER_DIM)
+ : QString("QPushButton{background:transparent;color:%1;border:none;"
+ "padding:0 8px;letter-spacing:0.5px;}"
+ "QPushButton:hover{color:%2;background:%3;}")
+ .arg(colors::TEXT_PRIMARY).arg(colors::AMBER).arg(colors::BG_RAISED));
}
}
diff --git a/fincept-qt/src/ui/navigation/NavigationBar.cpp b/fincept-qt/src/ui/navigation/NavigationBar.cpp
index c5d3e197d..36e80c61f 100644
--- a/fincept-qt/src/ui/navigation/NavigationBar.cpp
+++ b/fincept-qt/src/ui/navigation/NavigationBar.cpp
@@ -9,7 +9,8 @@ namespace fincept::ui {
NavigationBar::NavigationBar(QWidget* parent) : QWidget(parent) {
setFixedHeight(38);
- setStyleSheet("background:#0a0a0a;border-bottom:1px solid #1a1a1a;");
+ setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(colors::BG_BASE).arg(colors::BORDER_DIM));
auto* hl = new QHBoxLayout(this);
hl->setContentsMargins(14, 0, 14, 0);
hl->setSpacing(0);
@@ -22,31 +23,33 @@ NavigationBar::NavigationBar(QWidget* parent) : QWidget(parent) {
return l;
};
- hl->addWidget(mk("FINCEPT", "#d97706", true));
- hl->addWidget(mk("TERMINAL", "#ffffff"));
- hl->addWidget(mk(" ", "#000000"));
- hl->addWidget(mk("\xe2\x97\x8f", "#16a34a"));
- hl->addWidget(mk(" LIVE", "#16a34a", true));
+ hl->addWidget(mk("FINCEPT", colors::AMBER.get(), true));
+ hl->addWidget(mk("TERMINAL", colors::TEXT_PRIMARY.get()));
+ hl->addWidget(mk(" ", colors::BG_BASE.get()));
+ hl->addWidget(mk("\xe2\x97\x8f", colors::POSITIVE.get()));
+ hl->addWidget(mk(" LIVE", colors::POSITIVE.get(), true));
hl->addStretch();
- clock_label_ = mk("", "#404040");
+ clock_label_ = mk("", colors::TEXT_TERTIARY.get());
hl->addWidget(clock_label_);
hl->addStretch();
- user_label_ = mk("---", "#d97706");
+ user_label_ = mk("---", colors::AMBER.get());
hl->addWidget(user_label_);
- hl->addWidget(mk(" | ", "#1a1a1a"));
- credits_label_ = mk("---", "#16a34a");
+ hl->addWidget(mk(" | ", colors::BORDER_DIM.get()));
+ credits_label_ = mk("---", colors::POSITIVE.get());
hl->addWidget(credits_label_);
- hl->addWidget(mk(" | ", "#1a1a1a"));
- plan_label_ = mk("---", "#ffffff");
+ hl->addWidget(mk(" | ", colors::BORDER_DIM.get()));
+ plan_label_ = mk("---", colors::TEXT_PRIMARY.get());
hl->addWidget(plan_label_);
- hl->addWidget(mk(" | ", "#1a1a1a"));
+ hl->addWidget(mk(" | ", colors::BORDER_DIM.get()));
auto* logout_btn = new QPushButton("LOGOUT");
logout_btn->setFixedHeight(24);
logout_btn->setCursor(Qt::PointingHandCursor);
- logout_btn->setStyleSheet("QPushButton{background:transparent;color:#dc2626;border:1px solid #7f1d1d;"
- "padding:0 10px;font-weight:700;}"
- "QPushButton:hover{background:#dc2626;color:#e5e5e5;border-color:#dc2626;}");
+ logout_btn->setStyleSheet(
+ QString("QPushButton{background:transparent;color:%1;border:1px solid %1;"
+ "padding:0 10px;font-weight:700;}"
+ "QPushButton:hover{background:%1;color:%2;border-color:%1;}")
+ .arg(colors::NEGATIVE).arg(colors::TEXT_PRIMARY));
connect(logout_btn, &QPushButton::clicked, this, &NavigationBar::logout_clicked);
hl->addWidget(logout_btn);
@@ -77,7 +80,9 @@ void NavigationBar::refresh_user_display() {
credits_label_->setText(QString("%1 CR").arg(s.user_info.credit_balance, 0, 'f', 2));
credits_label_->setStyleSheet(
QString("color:%1;background:transparent;")
- .arg(s.user_info.credit_balance > 0 ? "#16a34a" : "#dc2626"));
+ .arg(s.user_info.credit_balance > 0
+ ? colors::POSITIVE.get()
+ : colors::NEGATIVE.get()));
plan_label_->setText(s.account_type().toUpper());
}
diff --git a/fincept-qt/src/ui/navigation/StatusBar.cpp b/fincept-qt/src/ui/navigation/StatusBar.cpp
index e58da3c4e..c1d41d243 100644
--- a/fincept-qt/src/ui/navigation/StatusBar.cpp
+++ b/fincept-qt/src/ui/navigation/StatusBar.cpp
@@ -6,7 +6,8 @@ namespace fincept::ui {
StatusBar::StatusBar(QWidget* parent) : QWidget(parent) {
setFixedHeight(26);
- setStyleSheet("background:#0a0a0a;border-top:1px solid #1a1a1a;");
+ setStyleSheet(QString("background:%1;border-top:1px solid %2;")
+ .arg(colors::BG_BASE).arg(colors::BORDER_DIM));
auto* hl = new QHBoxLayout(this);
hl->setContentsMargins(12, 0, 12, 0);
hl->setSpacing(0);
@@ -21,15 +22,15 @@ StatusBar::StatusBar(QWidget* parent) : QWidget(parent) {
return l;
};
- hl->addWidget(mk("v4.0.0", "#333333"));
- hl->addWidget(mk(" | ", "#1a1a1a"));
+ hl->addWidget(mk("v4.0.0", colors::TEXT_DIM.get()));
+ hl->addWidget(mk(" | ", colors::BORDER_DIM.get()));
const char* feeds[] = {"EQ", "FX", "CM", "FI", "CR"};
for (auto& f : feeds) {
- hl->addWidget(mk(f, "#333333"));
- hl->addWidget(mk(" ", "#000"));
+ hl->addWidget(mk(f, colors::TEXT_DIM.get()));
+ hl->addWidget(mk(" ", colors::BG_BASE.get()));
}
hl->addStretch();
- ready_label_ = mk("READY", "#16a34a", 8, true);
+ ready_label_ = mk("READY", colors::POSITIVE.get(), 8, true);
hl->addWidget(ready_label_);
}
@@ -37,7 +38,7 @@ void StatusBar::set_ready(bool ready) {
ready_label_->setText(ready ? "READY" : "BUSY");
ready_label_->setStyleSheet(QString("color:%1;font-size:12px;font-weight:700;background:transparent;"
"font-family:'Consolas',monospace;")
- .arg(ready ? "#16a34a" : "#525252"));
+ .arg(ready ? colors::POSITIVE.get() : colors::TEXT_TERTIARY.get()));
}
} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/navigation/ToolBar.cpp b/fincept-qt/src/ui/navigation/ToolBar.cpp
index 375e51d61..9cd69d60a 100644
--- a/fincept-qt/src/ui/navigation/ToolBar.cpp
+++ b/fincept-qt/src/ui/navigation/ToolBar.cpp
@@ -1,6 +1,7 @@
#include "ui/navigation/ToolBar.h"
#include "auth/AuthManager.h"
+#include "ui/theme/Theme.h"
#include <QAction>
#include <QDateTime>
@@ -11,28 +12,39 @@
namespace fincept::ui {
-static const char* MENU_SS = "QMenuBar{background:transparent;color:#808080;border:none;"
- "spacing:0;}"
- "QMenuBar::item{background:transparent;padding:4px 10px;}"
- "QMenuBar::item:selected{background:#1a1a1a;color:#e5e5e5;}";
+static QString menu_ss() {
+ return QString("QMenuBar{background:transparent;color:%1;border:none;spacing:0;}"
+ "QMenuBar::item{background:transparent;padding:4px 10px;}"
+ "QMenuBar::item:selected{background:%2;color:%3;}")
+ .arg(colors::TEXT_SECONDARY)
+ .arg(colors::BG_RAISED)
+ .arg(colors::TEXT_PRIMARY);
+}
-static const char* POPUP_SS = "QMenu{background:#0a0a0a;color:#e5e5e5;border:1px solid #1a1a1a;"
- "padding:4px 0;}"
- "QMenu::item{padding:5px 24px 5px 12px;}"
- "QMenu::item:selected{background:#1a1a1a;}"
- "QMenu::item:disabled{color:#404040;}"
- "QMenu::separator{background:#1a1a1a;height:1px;margin:4px 8px;}";
+static QString popup_ss() {
+ return QString("QMenu{background:%1;color:%2;border:1px solid %3;padding:4px 0;}"
+ "QMenu::item{padding:5px 24px 5px 12px;}"
+ "QMenu::item:selected{background:%4;}"
+ "QMenu::item:disabled{color:%5;}"
+ "QMenu::separator{background:%3;height:1px;margin:4px 8px;}")
+ .arg(colors::BG_SURFACE)
+ .arg(colors::TEXT_PRIMARY)
+ .arg(colors::BORDER_DIM)
+ .arg(colors::BG_RAISED)
+ .arg(colors::TEXT_DIM);
+}
ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {
setFixedHeight(32);
- setStyleSheet("background:#0a0a0a;border-bottom:1px solid #1a1a1a;");
+ setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(colors::BG_BASE).arg(colors::BORDER_DIM));
auto* hl = new QHBoxLayout(this);
hl->setContentsMargins(4, 0, 6, 0);
hl->setSpacing(0);
// Menus
menu_bar_ = new QMenuBar(this);
- menu_bar_->setStyleSheet(MENU_SS);
+ menu_bar_->setStyleSheet(menu_ss());
menu_bar_->addMenu(build_file_menu());
menu_bar_->addMenu(build_navigate_menu());
menu_bar_->addMenu(build_view_menu());
@@ -44,12 +56,14 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {
command_bar_->setMinimumWidth(80);
command_bar_->setMaximumWidth(240);
command_bar_->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
- connect(command_bar_, &CommandBar::navigate_to, this, &ToolBar::navigate_to);
+ connect(command_bar_, &CommandBar::navigate_to, this, &ToolBar::navigate_to);
+ connect(command_bar_, &CommandBar::dock_command, this, &ToolBar::dock_command);
hl->addWidget(command_bar_);
auto sep = [&]() -> QLabel* {
auto* s = new QLabel("|");
- s->setStyleSheet("color:#333333;background:transparent;padding:0 3px;");
+ s->setStyleSheet(QString("color:%1;background:transparent;padding:0 3px;")
+ .arg(colors::TEXT_DIM));
s->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hl->addWidget(s);
separators_.append(s);
@@ -66,31 +80,31 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {
};
sep();
- auto* fincept_lbl = mk("FINCEPT ", "#d97706", true);
+ auto* fincept_lbl = mk("FINCEPT ", colors::AMBER.get(), true);
hl->addWidget(fincept_lbl);
- branding_label_ = mk("TERMINAL", "#e5e5e5", true);
+ branding_label_ = mk("TERMINAL", colors::TEXT_PRIMARY.get(), true);
hl->addWidget(branding_label_);
- subtitle_label_ = mk(" | PROFESSIONAL RESEARCH DESK", "#666666");
+ subtitle_label_ = mk(" | PROFESSIONAL RESEARCH DESK", colors::TEXT_SECONDARY.get());
hl->addWidget(subtitle_label_);
- hl->addWidget(mk(" ", "#000000"));
- live_dot_ = mk("\xe2\x97\x8f", "#16a34a");
+ hl->addWidget(mk(" ", colors::BG_BASE.get()));
+ live_dot_ = mk("\xe2\x97\x8f", colors::POSITIVE.get());
hl->addWidget(live_dot_);
- live_label_ = mk(" LIVE", "#16a34a", true);
+ live_label_ = mk(" LIVE", colors::POSITIVE.get(), true);
hl->addWidget(live_label_);
hl->addStretch(1);
- clock_label_ = mk("", "#ffffff");
+ clock_label_ = mk("", colors::TEXT_PRIMARY.get());
clock_label_->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
hl->addWidget(clock_label_);
hl->addStretch(1);
- user_label_ = mk("---", "#d97706");
+ user_label_ = mk("---", colors::AMBER.get());
user_label_->setMaximumWidth(120);
hl->addWidget(user_label_);
sep();
- credits_label_ = mk("---", "#16a34a");
+ credits_label_ = mk("---", colors::POSITIVE.get());
credits_label_->setMaximumWidth(100);
hl->addWidget(credits_label_);
sep();
@@ -98,8 +112,9 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {
plan_btn_->setCursor(Qt::PointingHandCursor);
plan_btn_->setToolTip("View Plans & Pricing");
plan_btn_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
- plan_btn_->setStyleSheet("QPushButton{color:#ffffff;background:transparent;border:none;padding:0 2px;}"
- "QPushButton:hover{color:#d97706;}");
+ plan_btn_->setStyleSheet(QString("QPushButton{color:%1;background:transparent;border:none;padding:0 2px;}"
+ "QPushButton:hover{color:%2;}")
+ .arg(colors::TEXT_PRIMARY).arg(colors::AMBER));
connect(plan_btn_, &QPushButton::clicked, this, &ToolBar::plan_clicked);
hl->addWidget(plan_btn_);
sep();
@@ -110,9 +125,10 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {
chat_mode_btn_->setToolTip("Switch to Chat Mode (F9)");
chat_mode_btn_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
chat_mode_btn_->setStyleSheet(
- "QPushButton{background:transparent;color:#d97706;border:1px solid #7a4700;"
- "padding:0 8px;font-weight:700;}"
- "QPushButton:hover{background:#7a4700;color:#fff;border-color:#d97706;}");
+ QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
+ "padding:0 8px;font-weight:700;}"
+ "QPushButton:hover{background:%2;color:%3;border-color:%1;}")
+ .arg(colors::AMBER).arg(colors::AMBER_DIM).arg(colors::TEXT_PRIMARY));
connect(chat_mode_btn_, &QPushButton::clicked, this, &ToolBar::chat_mode_toggled);
hl->addWidget(chat_mode_btn_);
sep();
@@ -121,9 +137,11 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {
logout_btn->setFixedHeight(20);
logout_btn->setCursor(Qt::PointingHandCursor);
logout_btn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
- logout_btn->setStyleSheet("QPushButton{background:transparent;color:#dc2626;border:1px solid #7f1d1d;"
- "padding:0 8px;font-weight:700;}"
- "QPushButton:hover{background:#dc2626;color:#e5e5e5;border-color:#dc2626;}");
+ logout_btn->setStyleSheet(
+ QString("QPushButton{background:transparent;color:%1;border:1px solid %1;"
+ "padding:0 8px;font-weight:700;}"
+ "QPushButton:hover{background:%1;color:%2;border-color:%1;}")
+ .arg(colors::NEGATIVE).arg(colors::TEXT_PRIMARY));
connect(logout_btn, &QPushButton::clicked, this, &ToolBar::logout_clicked);
hl->addWidget(logout_btn);
@@ -197,7 +215,9 @@ void ToolBar::refresh_user_display() {
int credits = static_cast<int>(s.user_info.credit_balance);
credits_label_->setText(QString("%1 CR").arg(credits));
credits_label_->setStyleSheet(QString("color:%1;background:transparent;")
- .arg(s.user_info.credit_balance > 0 ? "#16a34a" : "#dc2626"));
+ .arg(s.user_info.credit_balance > 0
+ ? colors::POSITIVE.get()
+ : colors::NEGATIVE.get()));
QString plan_text = s.account_type().toUpper();
plan_btn_->setText(plan_text.isEmpty() ? "FREE" : plan_text);
@@ -205,7 +225,9 @@ void ToolBar::refresh_user_display() {
QMenu* ToolBar::build_file_menu() {
auto* m = new QMenu("File", this);
- m->setStyleSheet(POPUP_SS);
+ m->setStyleSheet(popup_ss());
+ m->addAction("New Window", this, [this]() { emit action_triggered("new_window"); });
+ m->addSeparator();
m->addAction("New Workspace", this, [this]() { emit action_triggered("new_workspace"); });
m->addAction("Open Workspace", this, [this]() { emit action_triggered("open_workspace"); });
m->addAction("Save Workspace", this, [this]() { emit action_triggered("save_workspace"); });
@@ -222,13 +244,19 @@ QMenu* ToolBar::build_file_menu() {
QMenu* ToolBar::build_navigate_menu() {
auto* m = new QMenu("Navigate", this);
- m->setStyleSheet("QMenu{background:#0a0a0a;color:#e5e5e5;border:1px solid #1a1a1a;padding:2px 0;}"
- "QMenu::item{padding:3px 20px 3px 10px;}"
- "QMenu::item:selected{background:#1a1a1a;}"
- "QMenu::item:disabled{color:#d97706;font-weight:700;padding:6px 10px 2px 10px;}"
- "QMenu::separator{background:#1a1a1a;height:1px;margin:2px 6px;}"
- "QMenu::scroller{background:#0a0a0a;height:14px;}"
- "QMenu::scroller:hover{background:#1a1a1a;}");
+ m->setStyleSheet(QString(
+ "QMenu{background:%1;color:%2;border:1px solid %3;padding:2px 0;}"
+ "QMenu::item{padding:3px 20px 3px 10px;}"
+ "QMenu::item:selected{background:%4;}"
+ "QMenu::item:disabled{color:%5;font-weight:700;padding:6px 10px 2px 10px;}"
+ "QMenu::separator{background:%3;height:1px;margin:2px 6px;}"
+ "QMenu::scroller{background:%1;height:14px;}"
+ "QMenu::scroller:hover{background:%4;}")
+ .arg(colors::BG_SURFACE)
+ .arg(colors::TEXT_PRIMARY)
+ .arg(colors::BORDER_DIM)
+ .arg(colors::BG_RAISED)
+ .arg(colors::AMBER));
// Use submenus for each group — cleaner and no scroll needed
auto add_sub = [&](const QString& title) -> QMenu* {
@@ -292,12 +320,43 @@ QMenu* ToolBar::build_navigate_menu() {
QMenu* ToolBar::build_view_menu() {
auto* m = new QMenu("View", this);
- m->setStyleSheet(POPUP_SS);
+ m->setStyleSheet(popup_ss());
m->addAction("Fullscreen\tF11", this, [this]() { emit action_triggered("fullscreen"); });
m->addSeparator();
m->addAction("Focus Mode\tF10", this, [this]() { emit action_triggered("focus_mode"); });
m->addAction("Always on Top", this, [this]() { emit action_triggered("always_on_top"); });
m->addSeparator();
+
+ // Float any screen as a separate window on another monitor
+ auto* panels = m->addMenu("Float Panel");
+ panels->setStyleSheet(popup_ss());
+ panels->addAction("Dashboard", this, [this]() { emit action_triggered("panel_dashboard"); });
+ panels->addAction("Watchlist", this, [this]() { emit action_triggered("panel_watchlist"); });
+ panels->addAction("News Feed", this, [this]() { emit action_triggered("panel_news"); });
+ panels->addAction("Portfolio", this, [this]() { emit action_triggered("panel_portfolio"); });
+ panels->addAction("Markets", this, [this]() { emit action_triggered("panel_markets"); });
+ panels->addSeparator();
+ panels->addAction("Crypto Trading", this, [this]() { emit action_triggered("panel_crypto"); });
+ panels->addAction("Equity Trading", this, [this]() { emit action_triggered("panel_equity"); });
+ panels->addAction("Algo Trading", this, [this]() { emit action_triggered("panel_algo"); });
+ panels->addSeparator();
+ panels->addAction("Equity Research", this, [this]() { emit action_triggered("panel_research"); });
+ panels->addAction("Economics", this, [this]() { emit action_triggered("panel_economics"); });
+ panels->addAction("Geopolitics", this, [this]() { emit action_triggered("panel_geopolitics"); });
+ panels->addAction("AI Chat", this, [this]() { emit action_triggered("panel_ai_chat"); });
+ m->addSeparator();
+
+ // Quick Switch — jump to a preset screen
+ auto* persp = m->addMenu("Quick Switch");
+ persp->setStyleSheet(popup_ss());
+ persp->addAction("Save Workspace", this, [this]() { emit action_triggered("perspective_save"); });
+ persp->addSeparator();
+ persp->addAction("Trading View", this, [this]() { emit action_triggered("perspective_trading"); });
+ persp->addAction("Research View", this, [this]() { emit action_triggered("perspective_research"); });
+ persp->addAction("News View", this, [this]() { emit action_triggered("perspective_news"); });
+ persp->addAction("Portfolio View", this, [this]() { emit action_triggered("perspective_portfolio"); });
+ m->addSeparator();
+
m->addAction("Refresh Screen\tF5", this, [this]() { emit action_triggered("refresh"); });
m->addAction("Take Screenshot\tCtrl+P", this, [this]() { emit action_triggered("screenshot"); });
return m;
@@ -305,7 +364,7 @@ QMenu* ToolBar::build_view_menu() {
QMenu* ToolBar::build_help_menu() {
auto* m = new QMenu("Help", this);
- m->setStyleSheet(POPUP_SS);
+ m->setStyleSheet(popup_ss());
m->addAction("About Fincept", this, [this]() { emit navigate_to("about"); });
m->addAction("Help Center", this, [this]() { emit navigate_to("help"); });
m->addSeparator();
diff --git a/fincept-qt/src/ui/navigation/ToolBar.h b/fincept-qt/src/ui/navigation/ToolBar.h
index a1c0d51b8..63ee2c0a0 100644
--- a/fincept-qt/src/ui/navigation/ToolBar.h
+++ b/fincept-qt/src/ui/navigation/ToolBar.h
@@ -21,6 +21,7 @@ class ToolBar : public QWidget {
signals:
void navigate_to(const QString& tab_id);
+ void dock_command(const QString& action, const QString& primary, const QString& secondary);
void action_triggered(const QString& action);
void logout_clicked();
void plan_clicked();
diff --git a/fincept-qt/src/ui/theme/ThemeManager.cpp b/fincept-qt/src/ui/theme/ThemeManager.cpp
index 197778960..326a72cce 100644
--- a/fincept-qt/src/ui/theme/ThemeManager.cpp
+++ b/fincept-qt/src/ui/theme/ThemeManager.cpp
@@ -112,6 +112,40 @@ const ThemeTokens THEME_MIDNIGHT = {
.chart_colors = {"#2563eb","#38bdf8","#22c55e","#ef4444","#f59e0b","#a78bfa"},
};
+const ThemeTokens THEME_LIGHT = {
+ .name = "Light",
+ // --- Backgrounds (lightest → slightly darker) ---
+ .bg_base = "#ffffff",
+ .bg_surface = "#f5f5f5",
+ .bg_raised = "#ebebeb",
+ .bg_hover = "#e0e0e0",
+ // --- Borders ---
+ .border_dim = "#e5e5e5",
+ .border_med = "#d4d4d4",
+ .border_bright = "#a3a3a3",
+ // --- Text (dark on light) ---
+ .text_primary = "#171717",
+ .text_secondary= "#525252",
+ .text_tertiary = "#737373",
+ .text_dim = "#a3a3a3",
+ // --- Accent (darker amber for white-bg contrast, WCAG AA compliant) ---
+ .accent = "#b45309",
+ .accent_dim = "#fef3c7",
+ // --- Functional (deepened for white-bg readability) ---
+ .positive = "#15803d",
+ .negative = "#dc2626",
+ .warning = "#a16207",
+ .info = "#1d4ed8",
+ .cyan = "#0e7490",
+ // --- Table ---
+ .row_alt = "#fafafa",
+ // --- Font ---
+ .font_family = "'Consolas','Courier New',monospace",
+ .font_size_base= 14,
+ // --- Chart colors (deeper shades for white background) ---
+ .chart_colors = {"#b45309","#0e7490","#15803d","#dc2626","#7c3aed","#a16207"},
+};
+
// ---------------------------------------------------------------------------
// ThemeManager implementation
// ---------------------------------------------------------------------------
@@ -127,10 +161,11 @@ ThemeManager& ThemeManager::instance() {
}
void ThemeManager::apply_theme(const QString& name) {
- if (name == "Bloomberg Dark") current_ = THEME_BLOOMBERG;
- else if (name == "Matrix") current_ = THEME_MATRIX;
+ if (name == "Bloomberg Dark") current_ = THEME_BLOOMBERG;
+ else if (name == "Matrix") current_ = THEME_MATRIX;
else if (name == "Midnight Blue") current_ = THEME_MIDNIGHT;
- else current_ = THEME_OBSIDIAN;
+ else if (name == "Light") current_ = THEME_LIGHT;
+ else current_ = THEME_OBSIDIAN;
// Re-apply custom accent override if one was set
if (!accent_override_.isEmpty())
@@ -165,7 +200,7 @@ QString ThemeManager::current_theme_name() const {
}
QStringList ThemeManager::available_themes() {
- return {"Obsidian", "Bloomberg Dark", "Matrix", "Midnight Blue"};
+ return {"Obsidian", "Bloomberg Dark", "Matrix", "Midnight Blue", "Light"};
}
QStringList ThemeManager::available_densities() {
@@ -286,6 +321,72 @@ QString ThemeManager::build_global_qss() const {
QMenu { background: %5; color: %2; border: 1px solid %6; }
QMenu::item:selected { background: %12; }
QMenu::separator { background: %6; height: 1px; }
+
+ /* ── ADS Docking System ─────────────────────────────────────────── */
+ ads--CDockContainerWidget { background: %1; }
+ ads--CDockAreaWidget { background: %1; }
+ ads--CDockAreaTitleBar {
+ background: %1;
+ border-bottom: 1px solid %6;
+ padding: 0px;
+ min-height: 22px;
+ max-height: 22px;
+ }
+ ads--CDockAreaWidget[focused="true"] ads--CDockAreaTitleBar {
+ border-bottom: 1px solid %9;
+ }
+ ads--CDockWidgetTab {
+ background: %1;
+ border: none;
+ padding: 1px 6px;
+ min-height: 20px;
+ max-height: 20px;
+ }
+ ads--CDockWidgetTab[activeTab="true"] {
+ background: %5;
+ border-bottom: 2px solid %9;
+ }
+ ads--CDockWidgetTab[focused="true"] {
+ background: %9;
+ }
+ ads--CDockWidgetTab #dockWidgetTabLabel {
+ color: %10;
+ font-size: 10px;
+ font-weight: 600;
+ }
+ ads--CDockWidgetTab[activeTab="true"] #dockWidgetTabLabel {
+ color: %2;
+ }
+ ads--CDockWidgetTab[focused="true"] #dockWidgetTabLabel {
+ color: #ffffff;
+ }
+ ads--CDockWidget {
+ background: %1;
+ border: none;
+ }
+ ads--CDockSplitter::handle {
+ background-color: %6;
+ }
+ #tabCloseButton {
+ background: none; border: none; padding: 0px;
+ max-width: 12px; max-height: 12px; color: #bbbbbb;
+ }
+ #tabCloseButton:hover { background: rgba(255, 255, 255, 24); color: #ffffff; }
+ #tabCloseButton:pressed { background: rgba(255, 255, 255, 48); }
+ ads--CDockWidgetTab[focused="true"] > #tabCloseButton:hover {
+ background: rgba(255, 255, 255, 48);
+ }
+ #tabsMenuButton { background: none; border: none; padding: 0px; color: #bbbbbb; }
+ #tabsMenuButton::menu-indicator { image: none; }
+ #tabsMenuButton:hover { background: rgba(255, 255, 255, 24); color: #ffffff; }
+ #dockAreaCloseButton { background: none; border: none; padding: 0px; color: #bbbbbb; }
+ #dockAreaCloseButton:hover { background: rgba(255, 255, 255, 24); color: #ffffff; }
+ #detachGroupButton { background: none; border: none; padding: 0px; color: #bbbbbb; }
+ #detachGroupButton:hover { background: rgba(255, 255, 255, 24); color: #ffffff; }
+ ads--CTitleBarButton { padding: 0px; max-width: 14px; max-height: 14px; color: #bbbbbb; }
+ ads--CTitleBarButton:hover { color: #ffffff; }
+ ads--CAutoHideSideBar { background: %1; border: none; }
+ QScrollArea#dockWidgetScrollArea { padding: 0px; border: none; }
)")
// %1 bg_base
.arg(t.bg_base)
diff --git a/fincept-qt/src/ui/theme/ThemeManager.h b/fincept-qt/src/ui/theme/ThemeManager.h
index 853601a44..65a9a6fb4 100644
--- a/fincept-qt/src/ui/theme/ThemeManager.h
+++ b/fincept-qt/src/ui/theme/ThemeManager.h
@@ -21,7 +21,7 @@ class ThemeManager : public QObject {
public:
static ThemeManager& instance();
- /// Apply a named preset ("Obsidian", "Bloomberg Dark", "Matrix", "Midnight Blue").
+ /// Apply a named preset ("Obsidian", "Bloomberg Dark", "Matrix", "Midnight Blue", "Light").
/// Builds global QSS from tokens and calls qApp->setStyleSheet().
/// Emits theme_changed(tokens) so custom painters can update.
void apply_theme(const QString& name);
diff --git a/fincept-qt/src/ui/theme/ThemeTokens.h b/fincept-qt/src/ui/theme/ThemeTokens.h
index c9a319090..12fa06cc5 100644
--- a/fincept-qt/src/ui/theme/ThemeTokens.h
+++ b/fincept-qt/src/ui/theme/ThemeTokens.h
@@ -55,5 +55,6 @@ extern const ThemeTokens THEME_OBSIDIAN;
extern const ThemeTokens THEME_BLOOMBERG;
extern const ThemeTokens THEME_MATRIX;
extern const ThemeTokens THEME_MIDNIGHT;
+extern const ThemeTokens THEME_LIGHT;
} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/widgets/NotifToast.cpp b/fincept-qt/src/ui/widgets/NotifToast.cpp
index ed2fa2ddb..040cd8983 100644
--- a/fincept-qt/src/ui/widgets/NotifToast.cpp
+++ b/fincept-qt/src/ui/widgets/NotifToast.cpp
@@ -1,6 +1,7 @@
#include "ui/widgets/NotifToast.h"
#include "ui/theme/ThemeManager.h"
+#include "ui/theme/Theme.h"
#include <QHBoxLayout>
#include <QPainter>
@@ -35,19 +36,19 @@ NotifToast::NotifToast(QWidget* parent) : QWidget(parent, Qt::ToolTip | Qt::Fram
tvl->setSpacing(2);
title_lbl_ = new QLabel;
- title_lbl_->setStyleSheet("color: #e0e0e0; font-size: 13px; font-weight: bold; background: transparent;");
+ title_lbl_->setStyleSheet(QString("color: %1; font-size: 13px; font-weight: bold; background: transparent;").arg(colors::TEXT_PRIMARY.get()));
title_lbl_->setWordWrap(false);
tvl->addWidget(title_lbl_);
msg_lbl_ = new QLabel;
- msg_lbl_->setStyleSheet("color: #a0a0a0; font-size: 12px; background: transparent;");
+ msg_lbl_->setStyleSheet(QString("color: %1; font-size: 12px; background: transparent;").arg(colors::TEXT_SECONDARY.get()));
msg_lbl_->setWordWrap(true);
tvl->addWidget(msg_lbl_);
outer->addWidget(text_col, 1);
time_lbl_ = new QLabel;
- time_lbl_->setStyleSheet("color: #555; font-size: 10px; background: transparent;");
+ time_lbl_->setStyleSheet(QString("color: %1; font-size: 10px; background: transparent;").arg(colors::TEXT_TERTIARY.get()));
time_lbl_->setAlignment(Qt::AlignTop | Qt::AlignRight);
outer->addWidget(time_lbl_, 0, Qt::AlignTop);
@@ -69,10 +70,10 @@ void NotifToast::show_notification(const NotificationRecord& record) {
const QString dot_color = [&]() -> QString {
switch (current_level_) {
- case NotifLevel::Warning: return "#F59E0B";
- case NotifLevel::Alert: return "#F97316";
- case NotifLevel::Critical: return "#EF4444";
- default: return "#06B6D4";
+ case NotifLevel::Warning: return colors::WARNING.get();
+ case NotifLevel::Alert: return colors::AMBER.get();
+ case NotifLevel::Critical: return colors::NEGATIVE.get();
+ default: return colors::CYAN.get();
}
}();
@@ -120,16 +121,16 @@ void NotifToast::paintEvent(QPaintEvent*) {
const QString border_color = [&]() -> QString {
switch (current_level_) {
- case NotifLevel::Warning: return "#F59E0B";
- case NotifLevel::Alert: return "#F97316";
- case NotifLevel::Critical: return "#EF4444";
- default: return "#1a1a2a";
+ case NotifLevel::Warning: return colors::WARNING.get();
+ case NotifLevel::Alert: return colors::AMBER.get();
+ case NotifLevel::Critical: return colors::NEGATIVE.get();
+ default: return colors::CYAN.get();
}
}();
// Background
p.setPen(Qt::NoPen);
- p.setBrush(QColor("#0d0d1a"));
+ p.setBrush(QColor(colors::BG_SURFACE.get()));
p.drawRoundedRect(rect(), 6, 6);
// Left accent bar
@@ -138,7 +139,7 @@ void NotifToast::paintEvent(QPaintEvent*) {
// Border
p.setBrush(Qt::NoBrush);
- p.setPen(QPen(QColor("#1a1a2a"), 1));
+ p.setPen(QPen(QColor(colors::BORDER_MED.get()), 1));
p.drawRoundedRect(rect().adjusted(0, 0, -1, -1), 6, 6);
}