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.

18.9 KB
Raw Blame
#include "screens/news/NewsFeedPanel.h"

#include "core/events/EventBus.h"
#include "core/logging/Logger.h"
#include "storage/repositories/WatchlistRepository.h"

#include <QApplication>
#include <QClipboard>
#include <QCursor>
#include <QDateTime>
#include <QDesktopServices>
#include <QMenu>
#include <QPointer>
#include <QPushButton>
#include <QScrollBar>
#include <QToolTip>
#include <QUrl>

#if defined(Q_OS_WIN)
#    include <windows.h>
#endif

namespace fincept::screens {

NewsFeedPanel::NewsFeedPanel(QWidget* parent) : QWidget(parent) {
    setObjectName("newsFeedPanel");

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

    // Breaking banner (hidden by default)
    build_breaking_banner();
    root->addWidget(banner_widget_);

    // Use a QStackedWidget so skeleton and list can swap cleanly
    auto* stack = new QStackedWidget(this);

    // QListView with model/delegate
    model_ = new NewsFeedModel(this);
    delegate_ = new NewsFeedDelegate(this);

    list_view_ = new QListView(stack);
    list_view_->setObjectName("newsFeedList");
    list_view_->setModel(model_);
    list_view_->setItemDelegate(delegate_);
    list_view_->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    list_view_->setSelectionMode(QAbstractItemView::NoSelection);
    list_view_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    list_view_->setMouseTracking(true);
    list_view_->setFrameShape(QFrame::NoFrame);
    list_view_->setUniformItemSizes(true); // WIRE mode: all 26px — big perf win

    // Skeleton loading widget
    build_skeleton();

    // Empty-state widget — shown when fetch yields zero articles
    empty_state_ = new QWidget(stack);
    empty_state_->setObjectName("newsEmptyState");
    {
        auto* layout = new QVBoxLayout(empty_state_);
        layout->setContentsMargins(24, 24, 24, 24);
        layout->setSpacing(8);
        layout->addStretch();
        empty_state_title_ = new QLabel(tr("No articles available"), empty_state_);
        empty_state_title_->setObjectName("newsEmptyStateTitle");
        empty_state_title_->setAlignment(Qt::AlignCenter);
        empty_state_hint_ = new QLabel(tr("Check your network connection and click Refresh to retry."), empty_state_);
        empty_state_hint_->setObjectName("newsEmptyStateHint");
        empty_state_hint_->setAlignment(Qt::AlignCenter);
        empty_state_hint_->setWordWrap(true);
        layout->addWidget(empty_state_title_);
        layout->addWidget(empty_state_hint_);
        layout->addStretch();
    }

    stack->addWidget(list_view_);        // index 0 = feed
    stack->addWidget(skeleton_overlay_); // index 1 = skeleton
    stack->addWidget(empty_state_);      // index 2 = empty state
    stack->setCurrentIndex(0);
    stack_ = stack;

    root->addWidget(stack, 1);

    // Accessibility — a news reader is exactly the surface a screen reader
    // user needs named, and the list must be reachable by keyboard.
    list_view_->setAccessibleName(tr("News feed"));
    list_view_->setAccessibleDescription(
        tr("Article list. Use the arrow keys to move, Enter to open the article in a browser."));
    list_view_->setFocusPolicy(Qt::StrongFocus);
    empty_state_->setAccessibleName(tr("Empty news feed"));
    banner_widget_->setAccessibleName(tr("Breaking news banner"));

    // Right-click: open the story / open or filter by one of its tickers.
    list_view_->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(list_view_, &QWidget::customContextMenuRequested, this, &NewsFeedPanel::show_context_menu);

    // Connect clicks
    connect(list_view_, &QListView::clicked, this, &NewsFeedPanel::on_item_clicked);
    // Keyboard: Enter/Return on the highlighted row opens it, same as a click.
    connect(list_view_, &QListView::activated, this, &NewsFeedPanel::on_item_clicked);

    // Preserve the reading position across model resets (see the header note).
    connect(model_, &QAbstractItemModel::modelAboutToBeReset, this, &NewsFeedPanel::capture_scroll_anchor);
    connect(model_, &QAbstractItemModel::modelReset, this, &NewsFeedPanel::restore_scroll_anchor);

    // Scroll-to-bottom detection for lazy loading
    connect(list_view_->verticalScrollBar(), &QScrollBar::valueChanged, this, &NewsFeedPanel::check_scroll_position);

    // Banner dismiss timer
    banner_dismiss_timer_ = new QTimer(this);
    banner_dismiss_timer_->setSingleShot(true);
    connect(banner_dismiss_timer_, &QTimer::timeout, this, &NewsFeedPanel::clear_breaking);
}

void NewsFeedPanel::build_breaking_banner() {
    banner_widget_ = new QWidget(this);
    banner_widget_->setObjectName("newsBreakingBanner");
    banner_widget_->setFixedHeight(28);
    banner_widget_->hide();

    auto* layout = new QHBoxLayout(banner_widget_);
    layout->setContentsMargins(8, 0, 8, 0);
    layout->setSpacing(8);

    banner_tag_ = new QLabel(tr("FLASH"), banner_widget_);
    banner_tag_->setObjectName("newsBreakingTag");
    banner_tag_->setFixedWidth(48);
    banner_tag_->setAlignment(Qt::AlignCenter);

    // Headline and source come straight from the feed: pin them to plain text so
    // a headline that looks like markup can't be rendered as rich text.
    banner_headline_ = new QLabel(banner_widget_);
    banner_headline_->setObjectName("newsBreakingHeadline");
    banner_headline_->setTextFormat(Qt::PlainText);

    banner_source_ = new QLabel(banner_widget_);
    banner_source_->setObjectName("newsBreakingSource");
    banner_source_->setTextFormat(Qt::PlainText);
    banner_source_->setFixedWidth(80);
    banner_source_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    auto* dismiss_btn = new QPushButton("x", banner_widget_);
    dismiss_btn->setObjectName("newsBreakingDismiss");
    dismiss_btn->setFixedSize(20, 20);
    connect(dismiss_btn, &QPushButton::clicked, this, &NewsFeedPanel::clear_breaking);

    layout->addWidget(banner_tag_);
    layout->addWidget(banner_headline_, 1);
    layout->addWidget(banner_source_);
    layout->addWidget(dismiss_btn);
}

void NewsFeedPanel::show_breaking(const QVector<services::NewsCluster>& breaking_clusters) {
    if (breaking_clusters.isEmpty())
        return;

    const auto& cluster = breaking_clusters.first();
    const auto& lead = cluster.lead_article;
    int64_t now = QDateTime::currentSecsSinceEpoch();

    // Global cooldown
    if (now < global_cooldown_until_)
        return;

    // Per-event deduplication
    QString key = lead.headline.left(50).toLower();
    if (is_banner_duplicate(key))
        return;

    // Show banner
    QString tag = lead.priority == services::Priority::FLASH ? tr("FLASH") : tr("BREAKING");
    banner_tag_->setText(tag);
    banner_headline_->setText(lead.headline);
    banner_source_->setText(lead.source.toUpper());
    banner_widget_->show();

    // Record for dedup
    recent_banners_.append({key, now});
    global_cooldown_until_ = now + BANNER_GLOBAL_COOLDOWN_SEC;

    // Cleanup old entries
    QVector<BreakingEntry> fresh;
    for (const auto& entry : recent_banners_) {
        if (now - entry.shown_at < BANNER_DEDUP_WINDOW_SEC)
            fresh.append(entry);
    }
    recent_banners_ = fresh;

    // Auto-dismiss: 60s for FLASH, 30s for BREAKING
    int dismiss_ms = (lead.priority == services::Priority::FLASH) ? 60000 : 30000;
    banner_dismiss_timer_->start(dismiss_ms);

    // Sound notification with 5-min cooldown
    if (now - last_sound_at_ >= SOUND_COOLDOWN_SEC) {
        last_sound_at_ = now;
#if defined(Q_OS_WIN)
        MessageBeep(MB_ICONEXCLAMATION);
#else
        QApplication::beep();
#endif
    }

    LOG_INFO("NewsFeedPanel", QString("Breaking banner: %1").arg(lead.headline.left(60)));
}

void NewsFeedPanel::clear_breaking() {
    banner_widget_->hide();
    banner_dismiss_timer_->stop();
}

bool NewsFeedPanel::is_banner_duplicate(const QString& headline) const {
    int64_t now = QDateTime::currentSecsSinceEpoch();
    for (const auto& entry : recent_banners_) {
        if (now - entry.shown_at < BANNER_DEDUP_WINDOW_SEC && entry.headline_key == headline)
            return true;
    }
    return false;
}

void NewsFeedPanel::build_skeleton() {
    skeleton_overlay_ = new QWidget(this);
    skeleton_overlay_->setObjectName("newsSkeletonOverlay");
    // No hide() — managed by QStackedWidget

    auto* skel_layout = new QVBoxLayout(skeleton_overlay_);
    skel_layout->setContentsMargins(0, 0, 0, 0);
    skel_layout->setSpacing(1);

    for (int i = 0; i < 20; ++i) {
        auto* row = new QWidget(skeleton_overlay_);
        row->setFixedHeight(26);
        row->setObjectName("newsSkeletonRow");
        skel_layout->addWidget(row);
    }
    skel_layout->addStretch();

    skeleton_anim_timer_ = new QTimer(this);
    skeleton_anim_timer_->setInterval(500);
    connect(skeleton_anim_timer_, &QTimer::timeout, this, [this]() {
        skeleton_phase_ = (skeleton_phase_ + 1) % 2;
        if (skeleton_overlay_->isVisible()) {
            // Toggle between two opacity levels via property
            QString opacity = skeleton_phase_ == 0 ? "0.04" : "0.08";
            skeleton_overlay_->setStyleSheet(
                QString("QWidget#newsSkeletonRow { background: rgba(255,255,255,%1); }").arg(opacity));
        }
    });
}

void NewsFeedPanel::remove_skeleton() {
    stack_->setCurrentWidget(list_view_);
    skeleton_anim_timer_->stop();
}

void NewsFeedPanel::set_loading(bool loading) {
    is_loading_ = loading;
    if (loading) {
        stack_->setCurrentWidget(skeleton_overlay_);
        skeleton_anim_timer_->start();
    } else {
        remove_skeleton();
    }
}

void NewsFeedPanel::set_empty_state(bool empty) {
    if (is_loading_)
        return; // skeleton wins until loading completes
    if (empty) {
        stack_->setCurrentWidget(empty_state_);
    } else if (stack_->currentWidget() == empty_state_) {
        stack_->setCurrentWidget(list_view_);
    }
}

void NewsFeedPanel::capture_scroll_anchor() {
    anchor_article_id_.clear();
    current_article_id_.clear();
    anchor_was_at_top_ = true;
    if (!list_view_ || !model_)
        return;
    auto* sb = list_view_->verticalScrollBar();
    anchor_was_at_top_ = !sb || sb->value() <= 0;

    // Anchor on whatever row is currently at the top of the viewport. Doing
    // this by article id (not pixel offset) keeps the anchor correct even when
    // rows are inserted above it by the refresh.
    const QModelIndex top = list_view_->indexAt(QPoint(4, 4));
    if (top.isValid())
        anchor_article_id_ = model_->article_at(top.row()).id;

    const QModelIndex cur = list_view_->currentIndex();
    if (cur.isValid())
        current_article_id_ = model_->article_at(cur.row()).id;
}

void NewsFeedPanel::restore_scroll_anchor() {
    if (!list_view_ || !model_)
        return;
    // Restore the keyboard cursor first — setCurrentIndex() ensure-visible
    // scrolls, so doing it after the anchor scroll would undo it.
    if (!current_article_id_.isEmpty()) {
        const auto cur = model_->index_for_article(current_article_id_);
        if (cur.isValid())
            list_view_->setCurrentIndex(cur);
    }
    // At the very top the user wants to see the newest items — leave it there.
    if (anchor_was_at_top_ || anchor_article_id_.isEmpty())
        return;
    const auto anchor = model_->index_for_article(anchor_article_id_);
    if (anchor.isValid())
        list_view_->scrollTo(anchor, QAbstractItemView::PositionAtTop);
}

void NewsFeedPanel::scroll_to(const QString& article_id) {
    auto idx = model_->index_for_article(article_id);
    if (idx.isValid())
        list_view_->scrollTo(idx, QAbstractItemView::EnsureVisible);
}

void NewsFeedPanel::set_selected(const QString& article_id) {
    model_->set_selected_id(article_id);
    scroll_to(article_id);
}

void NewsFeedPanel::select_next() {
    auto current = list_view_->currentIndex();
    int next_row = current.isValid() ? current.row() + 1 : 0;
    if (next_row < model_->rowCount()) {
        auto next = model_->index(next_row, 0);
        list_view_->setCurrentIndex(next);
        list_view_->scrollTo(next);
        on_item_clicked(next);
    }
}

void NewsFeedPanel::select_previous() {
    auto current = list_view_->currentIndex();
    int prev_row = current.isValid() ? current.row() - 1 : 0;
    if (prev_row >= 0) {
        auto prev = model_->index(prev_row, 0);
        list_view_->setCurrentIndex(prev);
        list_view_->scrollTo(prev);
        on_item_clicked(prev);
    }
}

void NewsFeedPanel::on_item_clicked(const QModelIndex& index) {
    if (!index.isValid())
        return;

    auto article = model_->article_at(index.row());
    model_->set_selected_id(article.id);
    model_->mark_seen(article.id);

    emit article_clicked(article);

    if (model_->view_mode() == "CLUSTERS") {
        auto cluster = model_->cluster_at(index.row());
        emit cluster_clicked(cluster);
    }
}

void NewsFeedPanel::show_context_menu(const QPoint& pos) {
    const QModelIndex index = list_view_->indexAt(pos);
    if (!index.isValid())
        return;
    const auto article = model_->article_at(index.row());
    if (article.id.isEmpty())
        return;

    // Feed links are untrusted (cached/DB rows may predate link validation):
    // only offer web URLs.
    const QUrl url(article.link);
    const bool has_link =
        url.isValid() && (url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("https"));

    QMenu menu(this);
    auto* open_act = menu.addAction(tr("Open article in browser"));
    open_act->setEnabled(has_link);
    connect(open_act, &QAction::triggered, this, [url]() { QDesktopServices::openUrl(url); });
    auto* copy_act = menu.addAction(tr("Copy link"));
    copy_act->setEnabled(has_link);
    connect(copy_act, &QAction::triggered, this, [link = article.link]() { QApplication::clipboard()->setText(link); });

    if (!article.tickers.isEmpty()) {
        menu.addSeparator();
        QPointer<NewsFeedPanel> self = this;
        auto filter_cb = [self](const QString& t) {
            if (self)
                emit self->ticker_filter_requested(t);
        };
        if (article.tickers.size() == 1) {
            add_ticker_actions(&menu, article.tickers.first(), this, filter_cb);
        } else {
            // One submenu per ticker keeps a multi-ticker story's menu short.
            for (const QString& ticker : article.tickers)
                add_ticker_actions(menu.addMenu(QStringLiteral("$") + ticker), ticker, this, filter_cb);
        }
    }
    menu.exec(list_view_->viewport()->mapToGlobal(pos));
}

void NewsFeedPanel::add_ticker_actions(QMenu* menu, const QString& ticker, QWidget* host,
                                       const std::function<void(const QString&)>& filter_cb) {
    if (!menu || ticker.isEmpty())
        return;
    const QString shown = QStringLiteral("$") + ticker;
    // nav.open_symbol navigates first (constructing the target screen when needed)
    // and then hands it the ticker through IGroupLinked.
    auto open_in = [ticker](const QString& screen_id) {
        EventBus::instance().publish("nav.open_symbol", QVariantMap{{"screen_id", screen_id}, {"symbol", ticker}});
    };
    QObject::connect(menu->addAction(tr("Open %1 in Equity Research").arg(shown)), &QAction::triggered, host,
                     [open_in]() { open_in(QStringLiteral("equity_research")); });
    QObject::connect(menu->addAction(tr("Open %1 chart / order ticket (Equity Trading)").arg(shown)),
                     &QAction::triggered, host, [open_in]() { open_in(QStringLiteral("equity_trading")); });
    QObject::connect(menu->addAction(tr("Backtest %1").arg(shown)), &QAction::triggered, host,
                     [open_in]() { open_in(QStringLiteral("backtesting")); });

    // One entry per watchlist (same pattern as the Screener / Markets menus).
    QMenu* wl_menu = menu->addMenu(tr("Add %1 to Watchlist").arg(shown));
    const auto lists = fincept::WatchlistRepository::instance().list_all();
    if (!lists.is_ok() || lists.value().isEmpty()) {
        wl_menu->addAction(tr("No watchlists yet — create one on the Watchlist screen"))->setEnabled(false);
    } else {
        for (const auto& wl : lists.value()) {
            QObject::connect(wl_menu->addAction(wl.name), &QAction::triggered, host,
                             [host, ticker, list_id = wl.id, list_name = wl.name]() {
                                 auto& repo = fincept::WatchlistRepository::instance();
                                 if (const auto stocks = repo.get_stocks(list_id); stocks.is_ok()) {
                                     for (const auto& st : stocks.value()) {
                                         if (st.symbol.compare(ticker, Qt::CaseInsensitive) == 0) {
                                             QToolTip::showText(QCursor::pos(),
                                                                tr("%1 is already in %2").arg(ticker, list_name), host);
                                             return;
                                         }
                                     }
                                 }
                                 const auto r = repo.add_stock(list_id, ticker);
                                 QToolTip::showText(QCursor::pos(),
                                                    r.is_ok() ? tr("Added %1 to %2").arg(ticker, list_name)
                                                              : tr("Could not add %1 to %2").arg(ticker, list_name),
                                                    host);
                                 if (r.is_ok()) // an open Watchlist screen picks the change up
                                     EventBus::instance().publish(
                                         "watchlist.updated", QVariantMap{{"action", QStringLiteral("add")},
                                                                          {"symbol", ticker}});
                             });
        }
    }

    menu->addSeparator();
    if (filter_cb)
        QObject::connect(menu->addAction(tr("Filter feed by %1").arg(shown)), &QAction::triggered, host,
                         [filter_cb, ticker]() { filter_cb(ticker); });
    QObject::connect(menu->addAction(tr("Copy %1").arg(ticker)), &QAction::triggered, host,
                     [ticker]() { QApplication::clipboard()->setText(ticker); });
}

void NewsFeedPanel::check_scroll_position() {
    auto* sb = list_view_->verticalScrollBar();
    if (!sb)
        return;
    int remaining = sb->maximum() - sb->value();
    if (remaining < 200 && sb->maximum() > 0)
        emit near_bottom();
}

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

void NewsFeedPanel::retranslateUi() {
    if (empty_state_title_)
        empty_state_title_->setText(tr("No articles available"));
    if (empty_state_hint_)
        empty_state_hint_->setText(tr("Check your network connection and click Refresh to retry."));
    // banner_tag_ reflects the live FLASH/BREAKING priority of the current
    // banner and refreshes on the next show_breaking() — not forced here.
}

} // namespace fincept::screens