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.

51.1 KB
Raw Blame
// src/screens/excel/ExcelScreen.cpp
#include "screens/excel/ExcelScreen.h"

#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
#include "screens/excel/SpreadsheetWidget.h"
#include "services/file_manager/FileManagerService.h"
#include "ui/theme/Theme.h"

#include <QColor>
#include <QDateTime>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QLocale>
#include <QLabel>
#include <QMessageBox>
#include <QPushButton>
#include <QShortcut>
#include <QTabBar>
#include <QTextStream>
#include <QVBoxLayout>

#include <algorithm>
#include <cmath>

#ifdef FINCEPT_HAS_QXLSX
#    include <xlsxcell.h>
#    include <xlsxcellformula.h>
#    include <xlsxdocument.h>
#    include <xlsxformat.h>
#    include <xlsxrichstring.h>
#    include <xlsxworksheet.h>
#endif

#include <QFutureWatcher>
#include <QPointer>
#include <QSet>
#include <QTimer>
#include <QtConcurrent/QtConcurrent>

#include <utility>

namespace fincept::screens {

using namespace fincept::ui;

static QString kAccent() {
    return QString("#ea580c");
} // Orange accent

// A workbook parsed on a worker thread and handed back to the UI thread. Plain
// values only — no widgets are created or touched off-thread.
struct ExcelImportedSheet {
    QString name;
    QVector<QVector<QString>> cells;
    QHash<qint64, QString> cached; // formula cells: the value the file stored (SpreadsheetWidget::cache_key)
};
struct ExcelImportResult {
    QVector<ExcelImportedSheet> sheets;
    bool truncated = false;
};

// Live screen + parked path for ExcelScreen::open_when_ready() (File Manager
// "EXCEL" button, which can fire before this lazily-built screen exists).
static QPointer<ExcelScreen> g_excel_live_screen;
static QString g_excel_pending_path;

// ─────────────────────────────────────────────────────────────────────────────
// Constructor
// ─────────────────────────────────────────────────────────────────────────────

ExcelScreen::ExcelScreen(QWidget* parent) : QWidget(parent) {
    build_ui();
    g_excel_live_screen = this;
}

void ExcelScreen::open_when_ready(const QString& path) {
    if (path.isEmpty())
        return;
    if (g_excel_live_screen) {
        g_excel_live_screen->open_file_path(path);
        return;
    }
    g_excel_pending_path = path;
}

bool ExcelScreen::open_file_path(const QString& path) {
    if (busy_)
        return false;
    if (!QFileInfo(path).isFile()) {
        QMessageBox::warning(this, tr("Open failed"), tr("The file no longer exists:\n%1").arg(path));
        return false;
    }
    if (!confirm_discard(tr("Opening another file")))
        return false;
    import_path(path);
    return true;
}

// ─────────────────────────────────────────────────────────────────────────────
// Show / Hide
// ─────────────────────────────────────────────────────────────────────────────

void ExcelScreen::showEvent(QShowEvent* event) {
    QWidget::showEvent(event);
    LOG_INFO("ExcelScreen", "Screen shown");

    // A file handed over by the File Manager before this screen existed.
    if (!g_excel_pending_path.isEmpty()) {
        const QString pending = std::exchange(g_excel_pending_path, QString());
        QTimer::singleShot(0, this, [this, pending]() { open_file_path(pending); });
    }
}

void ExcelScreen::hideEvent(QHideEvent* event) {
    QWidget::hideEvent(event);
    LOG_INFO("ExcelScreen", "Screen hidden");
}

// ─────────────────────────────────────────────────────────────────────────────
// Build UI
// ─────────────────────────────────────────────────────────────────────────────

void ExcelScreen::build_ui() {
    setStyleSheet(QString("QWidget { background:%1; color:%2; }").arg(colors::BG_BASE(), colors::TEXT_PRIMARY()));

    auto* root = new QVBoxLayout(this);
    root->setContentsMargins(0, 0, 0, 0);
    root->setSpacing(0);

    // Toolbar
    root->addWidget(build_toolbar());

    // Tab widget for sheets
    sheet_tabs_ = new QTabWidget(this);
    sheet_tabs_->setTabPosition(QTabWidget::South);
    sheet_tabs_->setMovable(true);
    sheet_tabs_->setTabsClosable(false); // We handle close via button
    sheet_tabs_->setStyleSheet(QString("QTabWidget::pane { border:none; background:%3; }"
                                       "QTabBar { background:%4; }"
                                       "QTabBar::tab { background:%5; color:%6; border:1px solid %7;"
                                       "  padding:4px 14px; font-family:%1; font-size:10px; margin-right:2px; }"
                                       "QTabBar::tab:selected { background:%2; color:%8; border-color:%2; }"
                                       "QTabBar::tab:hover { background:%7; }")
                                   .arg(fonts::DATA_FAMILY, kAccent(), colors::BG_HOVER(), colors::BORDER_MED(),
                                        colors::TEXT_DIM(), colors::TEXT_SECONDARY(), colors::TEXT_TERTIARY(),
                                        colors::TEXT_PRIMARY()));

    // Add initial sheet
    auto* sheet1 = new SpreadsheetWidget("Sheet1", 100, 26, sheet_tabs_);
    sheet_tabs_->addTab(sheet1, "Sheet1");
    watch_sheet(sheet1);

    connect(sheet_tabs_, &QTabWidget::currentChanged, this, &ExcelScreen::on_tab_changed);

    // Ctrl+S saves back to the current file path (or prompts on first save) —
    // previously the only way to persist work was the EXPORT button, which
    // always re-asked for a filename.
    auto* save_sc = new QShortcut(QKeySequence::Save, this);
    save_sc->setContext(Qt::WidgetWithChildrenShortcut);
    connect(save_sc, &QShortcut::activated, this, &ExcelScreen::on_save);

    root->addWidget(sheet_tabs_, 1);

    // Status bar
    auto* status_bar = new QWidget(this);
    status_bar->setFixedHeight(24);
    status_bar->setStyleSheet(
        QString("background:%1; border-top:1px solid %2;").arg(colors::BG_HOVER(), colors::BORDER_MED()));

    auto* status_hl = new QHBoxLayout(status_bar);
    status_hl->setContentsMargins(12, 0, 12, 0);
    status_hl->setSpacing(12);

    status_label_ = new QLabel(this);
    status_label_->setStyleSheet(
        QString("color:%1; font-family:%2; font-size:9px;").arg(colors::TEXT_SECONDARY(), fonts::DATA_FAMILY));
    status_hl->addWidget(status_label_);
    status_hl->addStretch();

    root->addWidget(status_bar);

    update_status();
}

QWidget* ExcelScreen::build_toolbar() {
    auto* bar = new QWidget(this);
    bar->setFixedHeight(40);
    bar->setStyleSheet(
        QString("background:%1; border-bottom:1px solid %2;").arg(colors::BORDER_MED(), colors::TEXT_DIM()));

    auto* hl = new QHBoxLayout(bar);
    hl->setContentsMargins(12, 0, 12, 0);
    hl->setSpacing(4);

    // Title
    toolbar_title_ = new QLabel(tr("EXCEL SPREADSHEET"), bar);
    toolbar_title_->setStyleSheet(
        QString("color:%1; font-family:%2; font-size:11px; font-weight:700; margin-right:12px;")
            .arg(kAccent(), fonts::DATA_FAMILY));
    hl->addWidget(toolbar_title_);

    // Button factory
    auto make_btn = [&](const QString& text, const QString& tooltip = {}) -> QPushButton* {
        auto* btn = new QPushButton(text, bar);
        btn->setToolTip(tooltip);
        btn->setStyleSheet(QString("QPushButton { background:%3; color:%4; border:none;"
                                   " font-family:%1; font-size:10px; font-weight:600; padding:6px 12px; }"
                                   "QPushButton:hover { background:%5; }"
                                   "QPushButton:pressed { background:%2; }")
                               .arg(fonts::DATA_FAMILY, kAccent(), colors::TEXT_DIM(), colors::TEXT_PRIMARY(),
                                    colors::TEXT_TERTIARY()));
        return btn;
    };

    import_btn_ = make_btn(tr("IMPORT"), tr("Import XLSX/CSV file"));
    connect(import_btn_, &QPushButton::clicked, this, &ExcelScreen::on_import);
    hl->addWidget(import_btn_);

    export_btn_ = make_btn(tr("EXPORT"), tr("Export as XLSX"));
    connect(export_btn_, &QPushButton::clicked, this, &ExcelScreen::on_export);
    hl->addWidget(export_btn_);

    export_csv_btn_ = make_btn(tr("CSV"), tr("Export active sheet as CSV"));
    connect(export_csv_btn_, &QPushButton::clicked, this, &ExcelScreen::on_export_csv);
    hl->addWidget(export_csv_btn_);

    // Separator
    auto* sep1 = new QWidget(bar);
    sep1->setFixedSize(1, 20);
    sep1->setStyleSheet(QString("background:%1;").arg(colors::TEXT_TERTIARY()));
    hl->addWidget(sep1);

    add_sheet_btn_ = make_btn(tr("+ SHEET"), tr("Add new sheet"));
    connect(add_sheet_btn_, &QPushButton::clicked, this, &ExcelScreen::on_add_sheet);
    hl->addWidget(add_sheet_btn_);

    rename_btn_ = make_btn(tr("RENAME"), tr("Rename current sheet"));
    connect(rename_btn_, &QPushButton::clicked, this, &ExcelScreen::on_rename_sheet);
    hl->addWidget(rename_btn_);

    delete_btn_ = make_btn(tr("DELETE"), tr("Delete current sheet"));
    delete_btn_->setStyleSheet(
        QString("QPushButton { background:%2; color:%3; border:none;"
                " font-family:%1; font-size:10px; font-weight:600; padding:6px 12px; }"
                "QPushButton:hover { background:%4; }")
            .arg(fonts::DATA_FAMILY, colors::TEXT_DIM(), colors::TEXT_PRIMARY(), colors::NEGATIVE()));
    connect(delete_btn_, &QPushButton::clicked, this, &ExcelScreen::on_delete_sheet);
    hl->addWidget(delete_btn_);

    hl->addStretch();

    // File name label
    auto* fname_label = new QLabel(file_name_, bar);
    fname_label->setObjectName("excelFileName");
    fname_label->setStyleSheet(
        QString("color:%1; font-family:%2; font-size:10px;").arg(colors::TEXT_SECONDARY(), fonts::DATA_FAMILY));
    hl->addWidget(fname_label);

    return bar;
}

// ─────────────────────────────────────────────────────────────────────────────
// Import (XLSX via QXlsx)
// ─────────────────────────────────────────────────────────────────────────────

// Split one CSV line honouring RFC-4180 quoting (""-escaped quotes inside a
// quoted field). Kept local — the watchlist screen has its own copy but lives
// in a different slice.
static QStringList split_csv_line(const QString& line, QChar delim = QLatin1Char(',')) {
    QStringList fields;
    QString cur;
    bool in_quotes = false;
    for (int i = 0; i < line.length(); ++i) {
        const QChar c = line[i];
        if (c == '"') {
            if (in_quotes && i + 1 < line.length() && line[i + 1] == '"') {
                cur += '"';
                ++i;
            } else {
                in_quotes = !in_quotes;
            }
        } else if (c == delim && !in_quotes) {
            fields.append(cur);
            cur.clear();
        } else {
            cur += c;
        }
    }
    fields.append(cur);
    return fields;
}

bool ExcelScreen::import_csv(const QString& path) {
    QFile f(path);
    if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("Import failed"), tr("Could not open file for reading:\n%1").arg(path));
        return false;
    }
    QTextStream in(&f);
    in.setEncoding(QStringConverter::Utf8);

    QVector<QVector<QString>> cells;
    // Hard cap so a pathological file can't allocate millions of table items
    // and freeze the UI thread.
    constexpr int kMaxRows = 20000;
    // Delimiter: comma, or the semicolon / tab that European-locale Excel and
    // TSV exports use — picked from whichever splits the first record most.
    QChar delim = QLatin1Char(',');
    bool delim_known = false;
    while (!in.atEnd() && cells.size() < kMaxRows) {
        // A quoted field may contain line breaks (RFC 4180). readLine() cuts there, which used to split one
        // record into several broken rows: keep appending lines until the quotes balance ("" escapes count as
        // two quote characters, so parity is unaffected).
        QString record = in.readLine();
        while (record.count(QLatin1Char('"')) % 2 == 1 && !in.atEnd())
            record += QLatin1Char('\n') + in.readLine();
        if (!delim_known) {
            qsizetype best = 0;
            for (const QChar cand : {QLatin1Char(','), QLatin1Char(';'), QLatin1Char('\t')}) {
                const qsizetype n = split_csv_line(record, cand).size();
                if (n > best) {
                    best = n;
                    delim = cand;
                }
            }
            delim_known = true;
        }
        const QStringList fields = split_csv_line(record, delim);
        QVector<QString> row;
        row.reserve(fields.size());
        // CSV is data: a field that starts with '=' stays text (CSV formula
        // injection — it would otherwise become a live formula, and a live
        // Excel formula once exported to .xlsx).
        for (const auto& v : fields)
            row.append(v.startsWith(QLatin1Char('=')) ? QLatin1Char('\'') + v : v);
        cells.append(row);
    }
    const bool truncated = !in.atEnd();

    const QString name = QFileInfo(path).completeBaseName();
    auto* sheet = new SpreadsheetWidget(name, std::max<int>(100, static_cast<int>(cells.size())), 26, sheet_tabs_);
    sheet->set_data(cells);

    // Replace the current sheet set with the imported file (matches the XLSX path).
    while (sheet_tabs_->count() > 0) {
        auto* w = sheet_tabs_->widget(0);
        sheet_tabs_->removeTab(0);
        w->deleteLater();
    }
    sheet_tabs_->addTab(sheet, name);
    watch_sheet(sheet);

    file_name_ = QFileInfo(path).fileName();
    file_path_ = path;
    if (auto* fname = findChild<QLabel*>("excelFileName"))
        fname->setText(file_name_);
    dirty_ = false;
    update_status();
    LOG_INFO("ExcelScreen", QString("Imported %1 CSV rows from %2").arg(cells.size()).arg(file_name_));
    services::FileManagerService::instance().import_file(path, "excel");

    if (truncated)
        QMessageBox::information(this, tr("Import truncated"),
                                 tr("Only the first %1 rows were imported.").arg(kMaxRows));
    return true;
}

void ExcelScreen::on_import() {
    if (busy_)
        return;
    if (!confirm_discard(tr("Import a different file")))
        return;

    QString path = QFileDialog::getOpenFileName(this, tr("Import Spreadsheet"), {},
                                                tr("Spreadsheet Files (*.xlsx *.xls *.csv);;All Files (*)"));
    if (path.isEmpty())
        return;
    import_path(path);
}

void ExcelScreen::import_path(const QString& path) {
    // CSV is advertised in the file filter (and in the no-QXlsx message) but was
    // never actually handled — QXlsx::Document on a .csv just reported "no
    // sheets" to the log and the screen silently did nothing.
    if (QFileInfo(path).suffix().compare(QLatin1String("csv"), Qt::CaseInsensitive) == 0) {
        import_csv(path);
        return;
    }
    import_xlsx(path);
}

// The import window bounds BOTH the xlsx.read() calls and the grid we build
// from them, so it has to stay something a grid can plausibly show. The old
// 20 000 × 512 window was 10.2M cells — a cap that itself caused the hang it
// was meant to prevent. 64 columns is already past "BL" in Excel lettering;
// anything wider is a data dump, not a spreadsheet.
[[maybe_unused]] static constexpr int kExcelMaxImportRows = 20000;
[[maybe_unused]] static constexpr int kExcelMaxImportCols = 64;

#ifdef FINCEPT_HAS_QXLSX
// Text for a stored number, following the cell's number format closely enough
// that the round trip keeps it: percentages stay "12.5%", grouped/currency
// figures stay "1,234.50" / "$1,234.50", accounting negatives "(1,234.50)".
// The formula engine reads all of these back as numbers.
static QString xlsx_number_text(double v, const QXlsx::Format& fmt) {
    QString code = fmt.numberFormat();
    if (code.isEmpty()) {
        switch (fmt.numberFormatIndex()) { // built-in formats carry no code string
            case 3: code = QStringLiteral("#,##0"); break;
            case 4: code = QStringLiteral("#,##0.00"); break;
            case 9: code = QStringLiteral("0%"); break;
            case 10: code = QStringLiteral("0.00%"); break;
            case 37: case 38: code = QStringLiteral("#,##0;(#,##0)"); break;
            case 39: case 40: code = QStringLiteral("#,##0.00;(#,##0.00)"); break;
            default: break;
        }
    }
    const QString positive = code.section(QLatin1Char(';'), 0, 0);
    auto decimals = [&positive]() {
        const int dot = static_cast<int>(positive.indexOf(QLatin1Char('.')));
        if (dot < 0)
            return 0;
        int n = 0;
        for (int i = dot + 1; i < positive.size() && (positive[i] == QLatin1Char('0') || positive[i] == QLatin1Char('#')); ++i)
            ++n;
        return n;
    };
    if (positive.contains(QLatin1Char('%')))
        return QString::number(v * 100.0, 'f', decimals()) + QLatin1Char('%');
    if (positive.contains(QLatin1String("#,##"))) {
        QString s = QLocale::c().toString(std::fabs(v), 'f', decimals());
        if (positive.contains(QLatin1Char('$')))
            s.prepend(QLatin1Char('$'));
        if (v < 0)
            s = code.section(QLatin1Char(';'), 1, 1).contains(QLatin1Char('(')) ? QLatin1Char('(') + s + QLatin1Char(')')
                                                                                  : QLatin1Char('-') + s;
        return s;
    }
    return formula::export_text(formula::Value::num(v));
}

static QString xlsx_date_text(const QVariant& dt) {
    if (dt.userType() == QMetaType::QDate)
        return dt.toDate().toString(Qt::ISODate);
    if (dt.userType() == QMetaType::QTime)
        return dt.toTime().toString(QStringLiteral("HH:mm:ss"));
    const QDateTime d = dt.toDateTime();
    if (d.time() == QTime(0, 0))
        return d.date().toString(Qt::ISODate);
    return d.toString(QStringLiteral("yyyy-MM-dd HH:mm:ss"));
}

// Plain-value text of a non-formula cell. Text that would otherwise READ as a
// number, boolean, error or formula ("00123", "TRUE", "=x") keeps a leading
// apostrophe so it stays text, as it was in the file.
static QString xlsx_value_text(QXlsx::Cell* cell) {
    if (cell->isDateTime())
        return xlsx_date_text(cell->dateTime());
    const QVariant v = cell->value();
    switch (cell->cellType()) {
        case QXlsx::Cell::NumberType:
        case QXlsx::Cell::CustomType:
            if (v.canConvert<double>() && v.userType() != QMetaType::QString)
                return xlsx_number_text(v.toDouble(), cell->format());
            break;
        case QXlsx::Cell::BooleanType:
            return v.toBool() ? QStringLiteral("TRUE") : QStringLiteral("FALSE");
        case QXlsx::Cell::ErrorType:
            return v.toString();
        default:
            break;
    }
    QString s = v.userType() == qMetaTypeId<QXlsx::RichString>() ? v.value<QXlsx::RichString>().toPlainString()
                                                                 : v.toString();
    const formula::Value lit = formula::literal_value(s);
    if (!s.isEmpty() && (!lit.is_text() || s.startsWith(QLatin1Char('=')) || s.startsWith(QLatin1Char('\''))))
        s.prepend(QLatin1Char('\''));
    return s;
}

// Runs on a worker thread: QXlsx::Document is created, used and destroyed
// entirely inside this call and the result is plain values.
static ExcelImportResult read_xlsx_workbook(const QString& path) {
    ExcelImportResult result;
    QXlsx::Document xlsx(path);
    const QStringList sheet_names = xlsx.sheetNames();

    for (const auto& name : sheet_names) {
        xlsx.selectSheet(name);
        QXlsx::Worksheet* ws = xlsx.currentWorksheet();
        if (!ws)
            continue; // chart sheets have no cells

        // Read the sheet's USED range only; SpreadsheetWidget pads the visible
        // grid to its minimum itself, without touching the file.
        const auto dim = ws->dimension();
        const int data_rows = std::clamp(dim.lastRow(), 0, kExcelMaxImportRows);
        const int data_cols = std::clamp(dim.lastColumn(), 0, kExcelMaxImportCols);
        if (dim.lastRow() > kExcelMaxImportRows || dim.lastColumn() > kExcelMaxImportCols)
            result.truncated = true;

        ExcelImportedSheet sheet;
        sheet.name = name;
        sheet.cells.resize(data_rows);
        for (int r = 0; r < data_rows; ++r) {
            sheet.cells[r].resize(data_cols);
            for (int c = 0; c < data_cols; ++c) {
                QXlsx::Cell* cell = ws->cellAt(r + 1, c + 1); // QXlsx is 1-based
                if (!cell)
                    continue;
                if (cell->hasFormula()) {
                    // read() resolves shared formulas to this cell's own text.
                    sheet.cells[r][c] = ws->read(r + 1, c + 1).toString();
                    // The value Excel stored: shown (marked) if the engine can't
                    // evaluate the formula itself (functions it doesn't implement).
                    const QVariant cv = cell->value();
                    if (cv.isValid() && !cv.toString().isEmpty())
                        sheet.cached.insert(SpreadsheetWidget::cache_key(r, c),
                                            cv.userType() == QMetaType::QString ? cv.toString()
                                                                                : xlsx_number_text(cv.toDouble(), cell->format()));
                } else {
                    sheet.cells[r][c] = xlsx_value_text(cell);
                }
            }
        }
        result.sheets.append(std::move(sheet));
    }
    return result;
}
#endif // FINCEPT_HAS_QXLSX

void ExcelScreen::import_xlsx(const QString& path) {
#ifdef FINCEPT_HAS_QXLSX
    if (busy_)
        return;
    // A big workbook is up to 20 000 × 64 xlsx.read() calls — seconds of work that
    // froze the whole terminal when run on the UI thread (P1). Read on a worker,
    // lock the screen meanwhile, and build the widgets back here.
    set_busy(true, tr("Importing %1...").arg(QFileInfo(path).fileName()));
    auto* watcher = new QFutureWatcher<ExcelImportResult>(this);
    connect(watcher, &QFutureWatcher<ExcelImportResult>::finished, this, [this, watcher, path]() {
        const ExcelImportResult result = watcher->result();
        watcher->deleteLater();
        finish_xlsx_import(path, result);
    });
    watcher->setFuture(QtConcurrent::run([path]() { return read_xlsx_workbook(path); }));
#else
    Q_UNUSED(path);
    QMessageBox::information(this, tr("Excel Import"),
                             tr("Excel (.xlsx) import requires Qt6 private headers.\n"
                                "This build was compiled without QXlsx support.\n\n"
                                "CSV files can still be imported via the toolbar."));
#endif
}

void ExcelScreen::finish_xlsx_import(const QString& path, const ExcelImportResult& result) {
    set_busy(false);

    if (result.sheets.isEmpty()) {
        LOG_ERROR("ExcelScreen", "No sheets found in file");
        QMessageBox::warning(this, tr("Import failed"),
                             tr("No sheets could be read from:\n%1\n\nThe file may be corrupt or "
                                "in an unsupported format.")
                                 .arg(path));
        return;
    }

    // Remove existing tabs
    while (sheet_tabs_->count() > 0) {
        auto* w = sheet_tabs_->widget(0);
        sheet_tabs_->removeTab(0);
        w->deleteLater();
    }

    for (const ExcelImportedSheet& imported : result.sheets) {
        const int rows = static_cast<int>(imported.cells.size());
        const int cols = rows > 0 ? static_cast<int>(imported.cells.first().size()) : 0;
        auto* sheet = new SpreadsheetWidget(imported.name, std::max(rows, 100), std::max(cols, 26), sheet_tabs_);
        sheet->set_data(imported.cells, imported.cached);
        sheet_tabs_->addTab(sheet, imported.name);
        watch_sheet(sheet);
    }

    // Update file info
    file_name_ = QFileInfo(path).fileName();
    file_path_ = path;
    auto* fname = findChild<QLabel*>("excelFileName");
    if (fname)
        fname->setText(file_name_);

    dirty_ = false;
    update_status();
    LOG_INFO("ExcelScreen", QString("Imported %1 sheets from %2").arg(result.sheets.size()).arg(file_name_));

    // Register with File Manager so it appears in the Files tab
    services::FileManagerService::instance().import_file(path, "excel");

    if (result.truncated)
        QMessageBox::information(this, tr("Import truncated"),
                                 tr("This workbook is larger than the %1 × %2 import window; "
                                    "only that region was loaded.")
                                     .arg(kExcelMaxImportRows)
                                     .arg(kExcelMaxImportCols));
}

void ExcelScreen::set_busy(bool busy, const QString& message) {
    busy_ = busy;
    for (QPushButton* btn : {import_btn_, export_btn_, export_csv_btn_, add_sheet_btn_, rename_btn_, delete_btn_}) {
        if (btn)
            btn->setEnabled(!busy);
    }
    if (sheet_tabs_)
        sheet_tabs_->setEnabled(!busy);
    if (busy && status_label_)
        status_label_->setText(message);
    else
        update_status();
}

// ─────────────────────────────────────────────────────────────────────────────
// Export (XLSX via QXlsx)
// ─────────────────────────────────────────────────────────────────────────────

// ── XLSX writing ────────────────────────────────────────────────────────────
// Data is snapshotted out of the widgets before any dialog opens (see
// on_export), so this works on plain values and touches no UI state.

struct ExcelSheetSnapshot {
    QString name;
    QVector<QVector<QString>> cells; // used range, raw text (formulas included)
    QHash<qint64, double> results;   // numeric results of formula cells (SpreadsheetWidget::cache_key)
};

static ExcelSheetSnapshot excel_snapshot(const SpreadsheetWidget* sheet) {
    ExcelSheetSnapshot snap{sheet->sheet_name(), sheet->get_used_data(), {}};
    for (int r = 0; r < snap.cells.size(); ++r)
        for (int c = 0; c < snap.cells[r].size(); ++c)
            if (snap.cells[r][c].startsWith(QLatin1Char('='))) {
                const formula::Value v = sheet->value_at(r, c);
                if (v.is_number())
                    snap.results.insert(SpreadsheetWidget::cache_key(r, c), v.number);
            }
    return snap;
}

#ifdef FINCEPT_HAS_QXLSX

// Excel sheet-name rules: 1-31 chars, none of []:*?/\, and unique per workbook.
// A name that violates these makes addSheet/renameSheet fail, after which the
// writes land on whatever sheet happened to be current.
static QString excel_safe_sheet_name(QString name, QSet<QString>& taken) {
    static const QString kIllegal = QStringLiteral("[]:*?/\\");
    for (const QChar& ch : kIllegal)
        name.replace(ch, QLatin1Char('_'));
    name = name.trimmed().left(31);
    if (name.isEmpty())
        name = QStringLiteral("Sheet");

    QString candidate = name;
    int n = 2;
    while (taken.contains(candidate.toLower())) {
        const QString suffix = QStringLiteral("_") + QString::number(n++);
        candidate = name.left(31 - suffix.size()) + suffix;
    }
    taken.insert(candidate.toLower());
    return candidate;
}

// Number format that reproduces how a value was TYPED: "12.5%" -> 0.0%,
// "$1,234.50" -> $#,##0.00, "(1,200)" -> #,##0;(#,##0), "1,234" -> #,##0.
// Plain numbers stay General. (Formats used to be guessed from the row label:
// a "Price" row got "$" even for rupee prices, and a "Growth" row typed as 5
// meaning 5% exported as 500%.)
static QString excel_format_for_typed(const QString& raw) {
    const QString t = raw.trimmed();
    const int dot = static_cast<int>(t.indexOf(QLatin1Char('.')));
    int decimals = 0;
    if (dot >= 0)
        for (int i = dot + 1; i < t.size() && t[i].isDigit(); ++i)
            ++decimals;
    const QString frac = decimals > 0 ? QLatin1Char('.') + QString(decimals, QLatin1Char('0')) : QString();
    if (t.endsWith(QLatin1Char('%')))
        return QStringLiteral("0") + frac + QLatin1Char('%');
    const bool grouped = t.contains(QLatin1Char(','));
    const bool parens = t.startsWith(QLatin1Char('(')) && t.endsWith(QLatin1Char(')'));
    QString currency;
    for (const QChar ch : t) {
        if (ch == QLatin1Char('$')) {
            currency = QStringLiteral("$");
            break;
        }
        if (ch == QChar(0x20AC) || ch == QChar(0x00A3) || ch == QChar(0x00A5) || ch == QChar(0x20B9)) {
            currency = QStringLiteral("\"") + ch + QStringLiteral("\"");
            break;
        }
    }
    if (!grouped && !parens && currency.isEmpty())
        return {};
    const QString body = currency + QStringLiteral("#,##0") + frac;
    return parens ? body + QStringLiteral(";(") + body + QLatin1Char(')') : body;
}

static bool write_snapshots_to_xlsx(QXlsx::Document& xlsx, const QVector<ExcelSheetSnapshot>& snapshots) {
    using QXlsx::Format;

    // Header row: bold, dark text on the terminal's amber accent. Numbers in it
    // stay numbers (years used to be exported as text).
    Format header_fmt;
    header_fmt.setFontBold(true);
    header_fmt.setFontColor(QColor(Qt::black));
    header_fmt.setPatternBackgroundColor(QColor(QStringLiteral("#d97706")));
    header_fmt.setHorizontalAlignment(Format::AlignHCenter);
    header_fmt.setBorderStyle(Format::BorderThin);

    Format label_fmt;
    label_fmt.setFontBold(true);

    Format date_fmt;
    date_fmt.setNumberFormat(QStringLiteral("yyyy-mm-dd"));
    Format datetime_fmt;
    datetime_fmt.setNumberFormat(QStringLiteral("yyyy-mm-dd hh:mm:ss"));

    QHash<QString, Format> number_formats;
    auto number_format = [&number_formats](const QString& code) -> Format {
        if (code.isEmpty())
            return Format();
        auto it = number_formats.find(code);
        if (it == number_formats.end()) {
            Format f;
            f.setNumberFormat(code);
            it = number_formats.insert(code, f);
        }
        return it.value();
    };

    QSet<QString> taken_names;
    bool wrote_any = false;

    for (int s = 0; s < snapshots.size(); ++s) {
        const ExcelSheetSnapshot& snap = snapshots[s];
        const QString name = excel_safe_sheet_name(snap.name, taken_names);
        if (s == 0) {
            const QStringList names = xlsx.sheetNames();
            if (names.isEmpty()) {
                if (!xlsx.addSheet(name))
                    continue;
            } else {
                xlsx.selectSheet(names.first());
                if (names.first() != name)
                    xlsx.renameSheet(names.first(), name);
            }
        } else if (!xlsx.addSheet(name)) {
            LOG_WARN("ExcelScreen", "Export: could not add sheet " + name + " - skipped");
            continue;
        }
        QXlsx::Worksheet* ws = xlsx.currentWorksheet();
        if (!ws)
            continue;
        wrote_any = true;

        const int rows = static_cast<int>(snap.cells.size());
        int cols = 0;
        for (const auto& row : snap.cells)
            cols = std::max(cols, static_cast<int>(row.size()));
        if (rows == 0)
            continue;

        // Header = first row with content, when its first value is text.
        int header_row = -1;
        for (int r = 0; r < rows && header_row == -1; ++r) {
            for (const QString& v : snap.cells[r]) {
                if (v.trimmed().isEmpty())
                    continue;
                header_row = (formula::literal_value(v).is_text() && !v.startsWith(QLatin1Char('='))) ? r : -2;
                break;
            }
        }

        QVector<int> col_width(cols, 10);
        for (int r = 0; r < rows; ++r) {
            for (int c = 0; c < snap.cells[r].size(); ++c) {
                const QString& raw = snap.cells[r][c];
                if (raw.isEmpty())
                    continue;
                const bool header = r == header_row;
                const int xr = r + 1;
                const int xc = c + 1;
                const bool is_formula = raw.startsWith(QLatin1Char('='));
                col_width[c] = std::max(col_width[c], is_formula ? 12 : static_cast<int>(raw.size()) + 2);

                if (is_formula) {
                    // A formula that doesn't parse would make Excel "repair" the
                    // file and drop it - write it as text instead.
                    if (!formula::compile(raw).program) {
                        ws->writeString(xr, xc, raw, header ? header_fmt : Format());
                        continue;
                    }
                    // Store our result as the cached value so readers that do not
                    // recalculate (pandas, previewers) see the number, not 0.
                    const double result = snap.results.value(SpreadsheetWidget::cache_key(r, c), 0.0);
                    ws->writeFormula(xr, xc, QXlsx::CellFormula(formula::to_excel(raw)), header ? header_fmt : Format(),
                                     result);
                    continue;
                }

                const formula::Value v = formula::literal_value(raw);
                if (v.is_number()) {
                    const QString code = excel_format_for_typed(raw);
                    Format f = number_format(code);
                    if (header) {
                        f = header_fmt;
                        if (!code.isEmpty())
                            f.setNumberFormat(code);
                    }
                    ws->writeNumeric(xr, xc, v.number, f);
                } else if (v.is_bool()) {
                    ws->writeBool(xr, xc, v.boolean, header ? header_fmt : Format());
                } else {
                    const bool forced_text = raw.startsWith(QLatin1Char('\''));
                    const QString text = forced_text ? raw.mid(1) : raw;
                    // ISO dates round-trip as real dates.
                    const QDate d = QDate::fromString(text.trimmed(), Qt::ISODate);
                    const QDateTime dt = QDateTime::fromString(text.trimmed(), QStringLiteral("yyyy-MM-dd HH:mm:ss"));
                    if (!forced_text && d.isValid())
                        ws->writeDate(xr, xc, d, header ? header_fmt : date_fmt);
                    else if (!forced_text && dt.isValid())
                        ws->writeDateTime(xr, xc, dt, header ? header_fmt : datetime_fmt);
                    else
                        ws->writeString(xr, xc, text, header ? header_fmt : (c == 0 ? label_fmt : Format()));
                }
            }
        }
        for (int c = 0; c < cols; ++c)
            xlsx.setColumnWidth(c + 1, std::min(col_width[c], 52));
    }
    return wrote_any;
}

#endif // FINCEPT_HAS_QXLSX

void ExcelScreen::on_export() {
#ifdef FINCEPT_HAS_QXLSX
    if (busy_)
        return; // Ctrl+S while a read/write is still running on the worker
    // ── Snapshot BEFORE the file dialog ───────────────────────────────────
    // getSaveFileName runs a nested event loop. Anything queued on the UI
    // thread runs inside it — including MCP tool bodies, which can call
    // navigate() and tear down or rebuild the Excel dock. The old code read
    // sheet_tabs_ and every SpreadsheetWidget* AFTER the dialog returned, so a
    // dock rebuild mid-dialog left it walking freed widgets: the observed crash
    // was a read of address 0x8 (a null QObject's d_ptr) inside Qt6Core during
    // export. Copying the data out first means the dialog can't invalidate
    // anything we still need.
    QVector<ExcelSheetSnapshot> snapshots;
    if (sheet_tabs_) {
        for (int i = 0; i < sheet_tabs_->count(); ++i) {
            auto* sheet = qobject_cast<SpreadsheetWidget*>(sheet_tabs_->widget(i));
            if (!sheet)
                continue;
            snapshots.append(excel_snapshot(sheet));
        }
    }
    if (snapshots.isEmpty()) {
        QMessageBox::warning(this, tr("Export failed"), tr("There is nothing to export."));
        return;
    }

    // `this` can still be destroyed while the modal dialog is open; every
    // member touched after it returns is guarded on the QPointer.
    QPointer<ExcelScreen> self = this;
    QString path;
    const bool quick = std::exchange(quick_save_, false);
    if (quick && file_path_.endsWith(QLatin1String(".xlsx"), Qt::CaseInsensitive) && QFileInfo(file_path_).isFile())
        path = file_path_; // Ctrl+S on an open workbook: save in place
    else
        path = QFileDialog::getSaveFileName(this, tr("Export as XLSX"), file_name_, tr("Excel Files (*.xlsx)"));
    if (!self || path.isEmpty())
        return;
    // QFileDialog on Linux/macOS does not always append the filter suffix.
    if (!path.endsWith(QLatin1String(".xlsx"), Qt::CaseInsensitive))
        path += QLatin1String(".xlsx");

    // Building and zipping a large workbook is seconds of work — do it on a worker
    // from the snapshot taken above (P1). The screen is locked until it returns.
    set_busy(true, tr("Exporting %1...").arg(QFileInfo(path).fileName()));
    auto* watcher = new QFutureWatcher<int>(this);
    connect(watcher, &QFutureWatcher<int>::finished, this, [this, watcher, path]() {
        const int outcome = watcher->result();
        watcher->deleteLater();
        finish_xlsx_export(path, outcome);
    });
    watcher->setFuture(QtConcurrent::run([snapshots, path]() -> int {
        QXlsx::Document xlsx;
        if (!write_snapshots_to_xlsx(xlsx, snapshots))
            return 1;
        return xlsx.saveAs(path) ? 0 : 2;
    }));
#else
    QMessageBox::information(this, tr("Excel Export"),
                             tr("Excel (.xlsx) export requires Qt6 private headers.\n"
                                "This build was compiled without QXlsx support.\n\n"
                                "CSV export is still available via the toolbar."));
#endif
}

void ExcelScreen::on_save() {
    quick_save_ = true;
    on_export();
    quick_save_ = false;
}

void ExcelScreen::finish_xlsx_export(const QString& path, int outcome) {
    set_busy(false);

    if (outcome == 0) {
        file_name_ = QFileInfo(path).fileName();
        file_path_ = path;
        auto* fname = findChild<QLabel*>("excelFileName");
        if (fname)
            fname->setText(file_name_);
        dirty_ = false;
        update_status();
        LOG_INFO("ExcelScreen", QString("Exported to %1").arg(path));

        // Register with File Manager so it appears in the Files tab
        services::FileManagerService::instance().import_file(path, "excel");
    } else if (outcome == 1) {
        QMessageBox::warning(this, tr("Export failed"), tr("Could not build the workbook contents."));
    } else {
        LOG_ERROR("ExcelScreen", "Failed to save XLSX file");
        // Silently logging a failed save is the worst possible outcome — the
        // user believes their workbook is on disk when it isn't.
        QMessageBox::warning(this, tr("Export failed"),
                             tr("Could not write the workbook to:\n%1\n\nCheck that the file is not "
                                "open in another application and that you have write permission.")
                                 .arg(path));
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Export CSV (active sheet)
// ─────────────────────────────────────────────────────────────────────────────

void ExcelScreen::on_export_csv() {
    if (busy_)
        return;
    auto* sheet = current_sheet();
    if (!sheet)
        return;

    // Snapshot before the dialog — same re-entrancy hazard as on_export: the
    // modal loop can run queued work that rebuilds the Excel dock and frees
    // `sheet`. Reading it afterwards is a use-after-free.
    const QString sheet_name = sheet->sheet_name();
    // CSV carries VALUES, as Excel's "Save as CSV" does: formula cells export
    // their computed result (full precision), not "=SUM(...)" text that no
    // CSV reader can evaluate.
    QVector<QVector<QString>> cells = sheet->get_used_data();
    for (int r = 0; r < cells.size(); ++r)
        for (int c = 0; c < cells[r].size(); ++c) {
            QString& v = cells[r][c];
            if (v.startsWith(QLatin1Char('=')))
                v = formula::export_text(sheet->value_at(r, c));
            else if (v.startsWith(QLatin1Char('\'')))
                v = v.mid(1);
        }

    QPointer<ExcelScreen> self = this;
    QString path = QFileDialog::getSaveFileName(this, tr("Export CSV"), sheet_name + ".csv", tr("CSV Files (*.csv)"));
    if (!self || path.isEmpty())
        return;
    if (!path.endsWith(QLatin1String(".csv"), Qt::CaseInsensitive))
        path += QLatin1String(".csv");

    // Find the last row/col with data to avoid huge trailing empty rows
    int last_row = -1;
    int last_col = -1;
    for (int r = 0; r < cells.size(); ++r) {
        for (int c = 0; c < cells[r].size(); ++c) {
            if (!cells[r][c].trimmed().isEmpty()) {
                last_row = std::max(last_row, r);
                last_col = std::max(last_col, c);
            }
        }
    }

    // Scoped so the stream flushes and the file closes BEFORE File Manager
    // copies it. Previously both were destroyed at end of function — i.e. after
    // import_file — so the Files tab could receive a truncated copy.
    {
        QFile file(path);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QMessageBox::warning(this, tr("Export failed"), tr("Could not open file for writing:\n%1").arg(path));
            return;
        }
        QTextStream out(&file);
        out.setEncoding(QStringConverter::Utf8);

        for (int r = 0; r <= last_row; ++r) {
            QStringList row;
            for (int c = 0; c <= last_col; ++c) {
                QString val = (r < cells.size() && c < cells[r].size()) ? cells[r][c] : QString();
                if (val.contains(',') || val.contains('"') || val.contains('\n'))
                    val = "\"" + val.replace("\"", "\"\"") + "\"";
                row << val;
            }
            out << row.join(",") << "\n";
        }
        out.flush();
        file.close();
    }

    LOG_INFO("ExcelScreen", QString("Exported CSV to %1").arg(path));

    // Register with File Manager so it appears in the Files tab
    services::FileManagerService::instance().import_file(path, "excel");
}

// ─────────────────────────────────────────────────────────────────────────────
// Sheet management
// ─────────────────────────────────────────────────────────────────────────────

void ExcelScreen::on_add_sheet() {
    QString name = generate_sheet_name();
    auto* sheet = new SpreadsheetWidget(name, 100, 26, sheet_tabs_);
    sheet_tabs_->addTab(sheet, name);
    watch_sheet(sheet);
    sheet_tabs_->setCurrentIndex(sheet_tabs_->count() - 1);
    mark_dirty();
    update_status();
}

// ── Dirty tracking ───────────────────────────────────────────────────────────

void ExcelScreen::watch_sheet(SpreadsheetWidget* sheet) {
    if (!sheet)
        return;
    connect(sheet, &SpreadsheetWidget::data_changed, this, &ExcelScreen::mark_dirty);
    // Excel-style SUM / AVG / COUNT of the selection in the status bar.
    connect(sheet, &SpreadsheetWidget::selection_changed, this, &ExcelScreen::update_status);
}

void ExcelScreen::mark_dirty() {
    if (dirty_)
        return;
    dirty_ = true;
    update_status();
}

bool ExcelScreen::confirm_discard(const QString& action) {
    if (!dirty_)
        return true;
    const auto reply =
        QMessageBox::warning(this, tr("Unsaved changes"),
                             tr("\"%1\" has unsaved changes.\n\n%2 will discard them.").arg(file_name_, action),
                             QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
    return reply == QMessageBox::Discard;
}

void ExcelScreen::on_delete_sheet() {
    if (sheet_tabs_->count() <= 1) {
        QMessageBox::warning(this, tr("Cannot Delete"), tr("Cannot delete the last sheet."));
        return;
    }

    int idx = sheet_tabs_->currentIndex();
    QString name = sheet_tabs_->tabText(idx);

    auto reply = QMessageBox::question(this, tr("Delete Sheet"), tr("Delete \"%1\"? This cannot be undone.").arg(name),
                                       QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        auto* w = sheet_tabs_->widget(idx);
        sheet_tabs_->removeTab(idx);
        w->deleteLater();
        mark_dirty();
        update_status();
    }
}

void ExcelScreen::on_rename_sheet() {
    int idx = sheet_tabs_->currentIndex();
    if (idx < 0)
        return;

    bool ok = false;
    QString current = sheet_tabs_->tabText(idx);
    QString name = QInputDialog::getText(this, tr("Rename Sheet"), tr("New name:"), QLineEdit::Normal, current, &ok);

    if (!ok || name.trimmed().isEmpty())
        return;
    name = name.trimmed();

    // Sheet names must be unique — QXlsx::addSheet() fails on a duplicate, which
    // used to silently drop a sheet on export.
    for (int i = 0; i < sheet_tabs_->count(); ++i) {
        if (i != idx && sheet_tabs_->tabText(i).compare(name, Qt::CaseInsensitive) == 0) {
            QMessageBox::warning(this, tr("Rename Sheet"), tr("A sheet named \"%1\" already exists.").arg(name));
            return;
        }
    }

    sheet_tabs_->setTabText(idx, name);
    if (auto* sheet = qobject_cast<SpreadsheetWidget*>(sheet_tabs_->widget(idx)))
        sheet->set_sheet_name(name);
    mark_dirty();
    update_status();
}

void ExcelScreen::on_tab_changed(int index) {
    Q_UNUSED(index);
    update_status();
    ScreenStateManager::instance().notify_changed(this);
}

// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────

SpreadsheetWidget* ExcelScreen::current_sheet() const {
    return qobject_cast<SpreadsheetWidget*>(sheet_tabs_->currentWidget());
}

QString ExcelScreen::generate_sheet_name() const {
    // Compare against the TAB TEXT. The old loop asked findChild<QWidget*>(name)
    // — sheets never have an objectName, so it always returned nullptr and the
    // uniqueness check was a no-op: deleting "Sheet2" from Sheet1/2/3 and adding
    // a sheet produced a duplicate "Sheet3".
    auto taken = [this](const QString& n) {
        for (int i = 0; i < sheet_tabs_->count(); ++i)
            if (sheet_tabs_->tabText(i).compare(n, Qt::CaseInsensitive) == 0)
                return true;
        return false;
    };
    for (int n = sheet_tabs_->count() + 1; n <= 999; ++n) {
        const QString name = QString("Sheet%1").arg(n);
        if (!taken(name))
            return name;
    }
    return QString("Sheet%1").arg(QDateTime::currentMSecsSinceEpoch());
}

void ExcelScreen::update_status() {
    auto* sheet = current_sheet();
    QString info = tr("File: %1%2  |  Sheets: %3")
                       .arg(file_name_, dirty_ ? QStringLiteral(" *") : QString())
                       .arg(sheet_tabs_->count());
    if (sheet) {
        info += tr("  |  Active: %1  |  %2 rows x %3 cols")
                    .arg(sheet->sheet_name())
                    .arg(sheet->row_count())
                    .arg(sheet->col_count());
        const QString summary = sheet->selection_summary();
        if (!summary.isEmpty())
            info += QStringLiteral("  |  ") + summary;
    }
    if (status_label_)
        status_label_->setText(info);
}

// ── Live language switch ─────────────────────────────────────────────────────

void ExcelScreen::changeEvent(QEvent* event) {
    if (event->type() == QEvent::LanguageChange)
        retranslateUi();
    QWidget::changeEvent(event);
}

void ExcelScreen::retranslateUi() {
    if (toolbar_title_)
        toolbar_title_->setText(tr("EXCEL SPREADSHEET"));
    if (import_btn_) {
        import_btn_->setText(tr("IMPORT"));
        import_btn_->setToolTip(tr("Import XLSX/CSV file"));
    }
    if (export_btn_) {
        export_btn_->setText(tr("EXPORT"));
        export_btn_->setToolTip(tr("Export as XLSX"));
    }
    if (export_csv_btn_) {
        export_csv_btn_->setText(tr("CSV"));
        export_csv_btn_->setToolTip(tr("Export active sheet as CSV"));
    }
    if (add_sheet_btn_) {
        add_sheet_btn_->setText(tr("+ SHEET"));
        add_sheet_btn_->setToolTip(tr("Add new sheet"));
    }
    if (rename_btn_) {
        rename_btn_->setText(tr("RENAME"));
        rename_btn_->setToolTip(tr("Rename current sheet"));
    }
    if (delete_btn_) {
        delete_btn_->setText(tr("DELETE"));
        delete_btn_->setToolTip(tr("Delete current sheet"));
    }
    update_status(); // re-render the status bar summary in the new language
}

// ── IStatefulScreen ───────────────────────────────────────────────────────────

QVariantMap ExcelScreen::save_state() const {
    return {{"tab_index", sheet_tabs_ ? sheet_tabs_->currentIndex() : 0}};
}

void ExcelScreen::restore_state(const QVariantMap& state) {
    const int idx = state.value("tab_index", 0).toInt();
    if (sheet_tabs_ && idx < sheet_tabs_->count())
        sheet_tabs_->setCurrentIndex(idx);
}

} // namespace fincept::screens