diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 740215a43..d2d8ed542 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,5 +1,7 @@ set(mmapper_SRCS main.cpp + adventure/AdventureLogModel.cpp + adventure/AdventureLogModel.h adventure/adventuresession.cpp adventure/adventuresession.h adventure/adventuretracker.cpp @@ -10,8 +12,6 @@ set(mmapper_SRCS adventure/lineparsers.h adventure/xpstatuswidget.cpp adventure/xpstatuswidget.h - display/AudioHintWidget.cpp - display/AudioHintWidget.h media/AudioManager.cpp media/AudioManager.h media/DescriptionWidget.cpp @@ -22,26 +22,32 @@ set(mmapper_SRCS media/MusicManager.h media/SfxManager.cpp media/SfxManager.h + media/StackBlur.cpp + media/StackBlur.h client/ClientTelnet.cpp client/ClientTelnet.h client/ClientWidget.cpp client/ClientWidget.h - client/PaletteManager.cpp - client/PaletteManager.h - client/displaywidget.cpp - client/displaywidget.h - client/inputwidget.cpp - client/inputwidget.h - client/stackedinputwidget.cpp - client/stackedinputwidget.h + client/InputHistory.cpp + client/InputHistory.h client/Hotkey.cpp client/Hotkey.h client/HotkeyManager.cpp client/HotkeyManager.h + client/displaywidget.cpp + client/displaywidget.h + client/PaletteManager.cpp + client/PaletteManager.h client/PasswordDialog.cpp client/PasswordDialog.h client/PreviewWidget.cpp client/PreviewWidget.h + client/inputwidget.cpp + client/inputwidget.h + client/stackedinputwidget.cpp + client/stackedinputwidget.h + clock/ClockStrings.cpp + clock/ClockStrings.h clock/mumeclock.cpp clock/mumeclock.h clock/mumeclockwidget.cpp @@ -77,6 +83,9 @@ set(mmapper_SRCS display/MapCanvasData.h display/MapCanvasRoomDrawer.cpp display/MapCanvasRoomDrawer.h + display/MapCanvasWindow.cpp + display/MapCanvasWindow.h + display/MapCanvasWindow_gl.cpp display/FrameManager.cpp display/FrameManager.h display/ProjectionUtils.cpp @@ -91,10 +100,14 @@ set(mmapper_SRCS display/mapcanvas.cpp display/mapcanvas.h display/mapcanvas_gl.cpp + display/MapScroller.cpp + display/MapScroller.h display/mapwindow.cpp display/mapwindow.h display/prespammedpath.cpp display/prespammedpath.h + global/AnsiHtml.cpp + global/AnsiHtml.h global/AnsiOstream.cpp global/AnsiOstream.h global/AnsiTextUtils.cpp @@ -237,42 +250,48 @@ set(mmapper_SRCS group/ColorGenerator.h group/GroupManagerApi.cpp group/GroupManagerApi.h - group/enums.cpp - group/enums.h + group/GroupModel.cpp + group/GroupModel.h group/groupwidget.cpp group/groupwidget.h + group/enums.cpp + group/enums.h group/mmapper2character.cpp group/mmapper2character.h group/mmapper2group.cpp group/mmapper2group.h logger/autologger.cpp logger/autologger.h + mainwindow/aboutdialog.cpp + mainwindow/aboutdialog.h mainwindow/AsyncTypes.h mainwindow/AudioVolumeSlider.cpp mainwindow/AudioVolumeSlider.h + mainwindow/CompactLayout.h mainwindow/MapZoomSlider.cpp mainwindow/MapZoomSlider.h mainwindow/TasksPanel.cpp mainwindow/TasksPanel.h mainwindow/ThemeManager.cpp mainwindow/ThemeManager.h + mainwindow/UpdateChecker.cpp + mainwindow/UpdateChecker.h mainwindow/UpdateDialog.cpp mainwindow/UpdateDialog.h - mainwindow/aboutdialog.cpp - mainwindow/aboutdialog.h mainwindow/findroomsdlg.cpp mainwindow/findroomsdlg.h mainwindow/infomarkseditdlg.cpp mainwindow/infomarkseditdlg.h + mainwindow/roomeditattrdlg.cpp + mainwindow/roomeditattrdlg.h mainwindow/mainwindow-async.cpp mainwindow/mainwindow-async.h + mainwindow/mainwindow-compact.cpp mainwindow/mainwindow-saveslots.cpp mainwindow/mainwindow.cpp mainwindow/mainwindow.h mainwindow/metatypes.cpp mainwindow/metatypes.h - mainwindow/roomeditattrdlg.cpp - mainwindow/roomeditattrdlg.h mainwindow/utils.cpp mainwindow/utils.h map/AbstractChangeVisitor.cpp @@ -385,6 +404,8 @@ set(mmapper_SRCS mapfrontend/mapfrontend.h mapstorage/MapDestination.cpp mapstorage/MapDestination.h + mapstorage/MapLoadHelper.cpp + mapstorage/MapLoadHelper.h mapstorage/MapSource.cpp mapstorage/MapSource.h mapstorage/MmpMapStorage.cpp @@ -409,6 +430,10 @@ set(mmapper_SRCS mpi/remoteedit.h mpi/remoteeditsession.cpp mpi/remoteeditsession.h + mpi/RemoteEditDocumentOps.cpp + mpi/RemoteEditDocumentOps.h + mpi/RemoteEditHighlighter.cpp + mpi/RemoteEditHighlighter.h mpi/remoteeditwidget.cpp mpi/remoteeditwidget.h mpi/gotowidget.cpp @@ -516,6 +541,8 @@ set(mmapper_SRCS preferences/AdvancedGraphics.h preferences/audiopage.cpp preferences/audiopage.h + preferences/AnsiColorTables.cpp + preferences/AnsiColorTables.h preferences/AnsiColorDialog.cpp preferences/AnsiColorDialog.h preferences/ansicombo.cpp @@ -524,22 +551,22 @@ set(mmapper_SRCS preferences/autologpage.h preferences/clientpage.cpp preferences/clientpage.h - preferences/configdialog.cpp - preferences/configdialog.h preferences/generalpage.cpp preferences/generalpage.h preferences/graphicspage.cpp preferences/graphicspage.h preferences/grouppage.cpp preferences/grouppage.h - preferences/mumeprotocolpage.cpp - preferences/mumeprotocolpage.h preferences/ManagePasswordDialog.cpp preferences/ManagePasswordDialog.h + preferences/mumeprotocolpage.cpp + preferences/mumeprotocolpage.h preferences/parserpage.cpp preferences/parserpage.h preferences/pathmachinepage.cpp preferences/pathmachinepage.h + preferences/configdialog.cpp + preferences/configdialog.h proxy/AbstractSocket.h proxy/AbstractTelnet.cpp proxy/AbstractTelnet.h @@ -565,6 +592,8 @@ set(mmapper_SRCS proxy/connectionlistener.h proxy/mumesocket.cpp proxy/mumesocket.h + proxy/ProxyHost.cpp + proxy/ProxyHost.h proxy/proxy.cpp proxy/proxy.h proxy/telnetfilter.cpp @@ -575,6 +604,8 @@ set(mmapper_SRCS roompanel/RoomMob.h roompanel/RoomMobs.cpp roompanel/RoomMobs.h + roompanel/RoomModel.cpp + roompanel/RoomModel.h roompanel/RoomWidget.cpp roompanel/RoomWidget.h syntax/Accept.cpp @@ -602,9 +633,9 @@ set(mmapper_SRCS timers/CTimers.cpp timers/CTimers.h timers/TimerDelegate.cpp + timers/TimerDelegate.h timers/TimerModel.cpp timers/TimerModel.h - timers/TimerDelegate.h timers/TimerWidget.cpp timers/TimerWidget.h viewers/AnsiViewWindow.cpp diff --git a/src/adventure/AdventureLogModel.cpp b/src/adventure/AdventureLogModel.cpp new file mode 100644 index 000000000..c47f807a1 --- /dev/null +++ b/src/adventure/AdventureLogModel.cpp @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "AdventureLogModel.h" + +#include "../global/Consts.h" +#include "adventuresession.h" + +AdventureLogModel::AdventureLogModel(AdventureTracker &tracker, QObject *const parent) + : QAbstractListModel(parent) +{ + addDefaultContent(); + + connect(&tracker, + &AdventureTracker::sig_accomplishedTask, + this, + &AdventureLogModel::slot_onAccomplishedTask); + + connect(&tracker, + &AdventureTracker::sig_achievedSomething, + this, + &AdventureLogModel::slot_onAchievedSomething); + + connect(&tracker, &AdventureTracker::sig_diedInGame, this, &AdventureLogModel::slot_onDied); + + connect(&tracker, + &AdventureTracker::sig_gainedLevel, + this, + &AdventureLogModel::slot_onGainedLevel); + + connect(&tracker, &AdventureTracker::sig_killedMob, this, &AdventureLogModel::slot_onKilledMob); + + connect(&tracker, + &AdventureTracker::sig_receivedHint, + this, + &AdventureLogModel::slot_onReceivedHint); +} + +int AdventureLogModel::rowCount(const QModelIndex &parent) const +{ + if (parent.isValid()) + return 0; + return static_cast(m_lines.size()); +} + +QVariant AdventureLogModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || index.row() < 0 + || static_cast(index.row()) >= m_lines.size()) { + return QVariant(); + } + + if (role == Qt::DisplayRole) { + return m_lines.at(index.row()); + } + + return QVariant(); +} + +QHash AdventureLogModel::roleNames() const +{ + QHash roles; + roles[Qt::DisplayRole] = "display"; + return roles; +} + +void AdventureLogModel::clear() +{ + if (!m_lines.isEmpty()) { + beginRemoveRows(QModelIndex(), 0, static_cast(m_lines.size()) - 1); + m_lines.clear(); + endRemoveRows(); + } + addDefaultContent(); +} + +void AdventureLogModel::addDefaultContent() +{ + addAdventureUpdate(DEFAULT_MSG); +} + +void AdventureLogModel::addAdventureUpdate(const QString &msg) +{ + QString line = msg; + while (line.endsWith(char_consts::C_NEWLINE)) { + line.chop(1); + } + + const int row = static_cast(m_lines.size()); + beginInsertRows(QModelIndex(), row, row); + m_lines.append(line); + endInsertRows(); + + // If more than MAX_LINES, preserve by deleting from the start + const int over = static_cast(m_lines.size()) - MAX_LINES; + if (over > 0) { + beginRemoveRows(QModelIndex(), 0, over - 1); + m_lines.erase(m_lines.begin(), m_lines.begin() + over); + endRemoveRows(); + } +} + +void AdventureLogModel::slot_onAccomplishedTask(double xpGained) +{ + // Only record accomplishedTask if it actually has associated xp to avoid + // spam, since sometimes it co-triggers with achievement and can be redundant. + if (xpGained > 0.0) { + auto msg = QString(ACCOMPLISH_MSG).arg(AdventureSession::formatPoints(xpGained)); + addAdventureUpdate(msg); + } +} + +void AdventureLogModel::slot_onAchievedSomething(const QString &achievement, double xpGained) +{ + QString msg; + + if (xpGained > 0.0) { + msg = QString(ACHIEVE_MSG_XP).arg(achievement, AdventureSession::formatPoints(xpGained)); + } else { + msg = QString(ACHIEVE_MSG).arg(achievement); + } + + addAdventureUpdate(msg); +} + +void AdventureLogModel::slot_onDied(double xpLost) +{ + // Ignore Died messages that don't have an accompanying XP loss (to avoid whois spam, etc.) + if (xpLost < 0.0) { + auto msg = QString(DIED_MSG).arg(AdventureSession::formatPoints(xpLost)); + addAdventureUpdate(msg); + } +} + +void AdventureLogModel::slot_onGainedLevel() +{ + addAdventureUpdate(QString(GAINED_LEVEL_MSG)); +} + +void AdventureLogModel::slot_onKilledMob(const QString &mobName, double xpGained) +{ + // When player gets XP from multiple kills on the same heartbeat, as + // frequently happens with quake xp, then the first mob gets all the XP + // attributed and the others are zero. No way to solve this given + // current MUME "protocol". + auto xpf = (xpGained > 0.0) ? AdventureSession::formatPoints(xpGained) : "?"; + auto msg = QString(KILL_TROPHY_MSG).arg(mobName, xpf); + + addAdventureUpdate(msg); +} + +void AdventureLogModel::slot_onReceivedHint(const QString &hint) +{ + auto msg = QString(HINT_MSG).arg(hint); + + addAdventureUpdate(msg); +} diff --git a/src/adventure/AdventureLogModel.h b/src/adventure/AdventureLogModel.h new file mode 100644 index 000000000..aded7f8ea --- /dev/null +++ b/src/adventure/AdventureLogModel.h @@ -0,0 +1,52 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "../global/macros.h" +#include "adventuretracker.h" + +#include +#include + +class NODISCARD_QOBJECT AdventureLogModel final : public QAbstractListModel +{ + Q_OBJECT + +private: + QStringList m_lines; + +public: + static constexpr const int MAX_LINES = 1024; + static constexpr const auto DEFAULT_MSG + = "Your adventures in Middle Earth will be tracked here!\n"; + + static constexpr const auto ACCOMPLISH_MSG = "Task accomplished! (%1 xp)\n"; + static constexpr const auto ACHIEVE_MSG = "Achievement: %1\n"; + static constexpr const auto ACHIEVE_MSG_XP = "Achievement: %1 (%2 xp)\n"; + static constexpr const auto DIED_MSG = "You are dead! Sorry... (%1 xp)\n"; + static constexpr const auto GAINED_LEVEL_MSG = "You gain a level! Congrats!\n"; + static constexpr const auto HINT_MSG = "Hint: %1\n"; + static constexpr const auto KILL_TROPHY_MSG = "Trophy: %1 (%2 xp)\n"; + + explicit AdventureLogModel(AdventureTracker &tracker, QObject *parent = nullptr); + + NODISCARD int rowCount(const QModelIndex &parent = QModelIndex()) const override; + NODISCARD QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + NODISCARD QHash roleNames() const override; + +public slots: + // Drops every line and re-adds the default welcome line. + void clear(); + +private: + void addDefaultContent(); + void addAdventureUpdate(const QString &msg); + +private slots: + void slot_onAccomplishedTask(double xpGained); + void slot_onAchievedSomething(const QString &achievement, double xpGained); + void slot_onDied(double xpLost); + void slot_onGainedLevel(); + void slot_onKilledMob(const QString &mobName, double xpGained); + void slot_onReceivedHint(const QString &hint); +}; diff --git a/src/adventure/adventurewidget.cpp b/src/adventure/adventurewidget.cpp index a7fcf10fd..a84015017 100644 --- a/src/adventure/adventurewidget.cpp +++ b/src/adventure/adventurewidget.cpp @@ -5,8 +5,8 @@ #include "adventurewidget.h" #include "../configuration/configuration.h" +#include "../global/Consts.h" #include "../global/window_utils.h" -#include "adventuresession.h" #include @@ -15,13 +15,11 @@ AdventureWidget::AdventureWidget(AdventureTracker &at, QWidget *const parent) : QWidget{parent} - , m_adventureTracker{at} { - m_textEdit = new QTextEdit(this); - m_textCursor = std::make_unique(m_textEdit->document()); + m_model = new AdventureLogModel(at, this); + m_textEdit = new QTextEdit(this); m_textEdit->setReadOnly(true); - m_textEdit->setOverwriteMode(true); m_textEdit->setUndoRedoEnabled(false); m_textEdit->setDocumentTitle("Adventure Panel Text"); m_textEdit->setTextInteractionFlags(Qt::TextSelectableByMouse); @@ -29,32 +27,28 @@ AdventureWidget::AdventureWidget(AdventureTracker &at, QWidget *const parent) const auto &settings = getConfig().integratedClient; - QTextFrameFormat frameFormat = m_textEdit->document()->rootFrame()->frameFormat(); + auto *const document = m_textEdit->document(); + QTextFrameFormat frameFormat = document->rootFrame()->frameFormat(); frameFormat.setBackground(settings.backgroundColor); - m_textEdit->document()->rootFrame()->setFrameFormat(frameFormat); + document->rootFrame()->setFrameFormat(frameFormat); - QTextCharFormat blockCharFormat = m_textCursor->blockCharFormat(); + QTextCharFormat blockCharFormat = QTextCursor(document).blockCharFormat(); blockCharFormat.setForeground(settings.foregroundColor); { QFont font; font.fromString(settings.font); // need fromString() to extract PointSize blockCharFormat.setFont(font); } - m_textCursor->setBlockCharFormat(blockCharFormat); + QTextCursor(document).setBlockCharFormat(blockCharFormat); - auto layout = new QVBoxLayout(this); + auto *const layout = new QVBoxLayout(this); layout->setAlignment(Qt::AlignTop); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(m_textEdit); - addDefaultContent(); - m_clearContentAction = new QAction("Clear Content", this); - connect(m_clearContentAction, - &QAction::triggered, - this, - &AdventureWidget::slot_actionClearContent); + connect(m_clearContentAction, &QAction::triggered, m_model, &AdventureLogModel::clear); m_textEdit->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_textEdit, @@ -62,91 +56,58 @@ AdventureWidget::AdventureWidget(AdventureTracker &at, QWidget *const parent) this, &AdventureWidget::slot_contextMenuRequested); - connect(&m_adventureTracker, - &AdventureTracker::sig_accomplishedTask, - this, - &AdventureWidget::slot_onAccomplishedTask); - - connect(&m_adventureTracker, - &AdventureTracker::sig_achievedSomething, - this, - &AdventureWidget::slot_onAchievedSomething); - - connect(&m_adventureTracker, - &AdventureTracker::sig_diedInGame, - this, - &AdventureWidget::slot_onDied); - - connect(&m_adventureTracker, - &AdventureTracker::sig_gainedLevel, - this, - &AdventureWidget::slot_onGainedLevel); + connect(m_model, &QAbstractItemModel::rowsInserted, this, &AdventureWidget::slot_rowsInserted); + connect(m_model, &QAbstractItemModel::rowsRemoved, this, &AdventureWidget::slot_rowsRemoved); - connect(&m_adventureTracker, - &AdventureTracker::sig_killedMob, - this, - &AdventureWidget::slot_onKilledMob); - - connect(&m_adventureTracker, - &AdventureTracker::sig_receivedHint, - this, - &AdventureWidget::slot_onReceivedHint); -} - -void AdventureWidget::slot_onAccomplishedTask(double xpGained) -{ - // Only record accomplishedTask if it actually has associated xp to avoid - // spam, since sometimes it co-triggers with achievement and can be redundant. - if (xpGained > 0.0) { - auto msg = QString(ACCOMPLISH_MSG).arg(AdventureSession::formatPoints(xpGained)); - addAdventureUpdate(msg); + // The model already holds its default welcome line. + if (const int rows = m_model->rowCount(); rows > 0) { + appendRows(0, rows - 1); } } -void AdventureWidget::slot_onAchievedSomething(const QString &achievement, double xpGained) +void AdventureWidget::slot_rowsInserted(const QModelIndex &parent, const int first, const int last) { - QString msg; - - if (xpGained > 0.0) { - msg = QString(ACHIEVE_MSG_XP).arg(achievement, AdventureSession::formatPoints(xpGained)); - } else { - msg = QString(ACHIEVE_MSG).arg(achievement); + if (parent.isValid()) { + return; } - - addAdventureUpdate(msg); + appendRows(first, last); } -void AdventureWidget::slot_onDied(double xpLost) +void AdventureWidget::slot_rowsRemoved(const QModelIndex &parent, const int first, const int last) { - // Ignore Died messages that don't have an accompanying XP loss (to avoid whois spam, etc.) - if (xpLost < 0.0) { - auto msg = QString(DIED_MSG).arg(AdventureSession::formatPoints(xpLost)); - addAdventureUpdate(msg); + if (parent.isValid()) { + return; } + removeRows(first, last); } -void AdventureWidget::slot_onGainedLevel() +void AdventureWidget::appendRows(const int first, const int last) { - addAdventureUpdate(QString(GAINED_LEVEL_MSG)); -} + // Rows are only ever appended (see AdventureLogModel::addAdventureUpdate()), + // so the new blocks go at the end of the document. + assert(first == m_textEdit->document()->blockCount() - 1); + + QTextCursor cursor(m_textEdit->document()); + cursor.movePosition(QTextCursor::End); + for (int row = first; row <= last; ++row) { + cursor.insertText(m_model->data(m_model->index(row)).toString()); + cursor.insertText(QString(char_consts::C_NEWLINE)); + } -void AdventureWidget::slot_onKilledMob(const QString &mobName, double xpGained) -{ - // When player gets XP from multiple kills on the same heartbeat, as - // frequently happens with quake xp, then the first mob gets all the XP - // attributed and the others are zero. No way to solve this given - // current MUME "protocol". - auto xpf = (xpGained > 0.0) ? AdventureSession::formatPoints(xpGained) : "?"; - auto msg = QString(KILL_TROPHY_MSG).arg(mobName, xpf); - - addAdventureUpdate(msg); + auto *const scrollBar = m_textEdit->verticalScrollBar(); + scrollBar->setValue(scrollBar->maximum()); } -void AdventureWidget::slot_onReceivedHint(const QString &hint) +void AdventureWidget::removeRows(const int first, const int last) { - auto msg = QString(HINT_MSG).arg(hint); - - addAdventureUpdate(msg); + // One document block per model row (plus the trailing empty block after + // the final newline), so removing rows [first, last] is removing the + // same range of blocks. + QTextCursor cursor(m_textEdit->document()); + cursor.movePosition(QTextCursor::Start); + cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor, first); + cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, last - first + 1); + cursor.removeSelectedText(); } void AdventureWidget::slot_contextMenuRequested(const QPoint &pos) @@ -156,36 +117,3 @@ void AdventureWidget::slot_contextMenuRequested(const QPoint &pos) contextMenu->addAction(m_clearContentAction); mmqt::popupMenu(std::move(contextMenu), m_textEdit->mapToGlobal(pos)); } - -void AdventureWidget::slot_actionClearContent([[maybe_unused]] bool checked) -{ - // REVISIT should use m_textCursor->document()->clear() instead? - m_textCursor->movePosition(QTextCursor::Start); - m_textCursor->movePosition(QTextCursor::Down, QTextCursor::KeepAnchor, QTextCursor::End); - m_textCursor->removeSelectedText(); - addDefaultContent(); -} - -void AdventureWidget::addDefaultContent() -{ - addAdventureUpdate(DEFAULT_MSG); -} - -void AdventureWidget::addAdventureUpdate(const QString &msg) -{ - m_textCursor->movePosition(QTextCursor::End); - m_textCursor->insertText(msg); - - // If more than MAX_LINES, preserve by deleting from the start - auto lines_over = m_textEdit->document()->lineCount() - AdventureWidget::MAX_LINES; - if (lines_over > 0) { - m_textCursor->movePosition(QTextCursor::Start); - m_textCursor->movePosition(QTextCursor::Down, QTextCursor::KeepAnchor, lines_over); - m_textCursor->removeSelectedText(); - m_textCursor->movePosition(QTextCursor::End); - } - - // force scroll to bottom upon new message - auto scrollBar = m_textEdit->verticalScrollBar(); - scrollBar->setValue(scrollBar->maximum()); -} diff --git a/src/adventure/adventurewidget.h b/src/adventure/adventurewidget.h index 13726b36c..d6fdf20ac 100644 --- a/src/adventure/adventurewidget.h +++ b/src/adventure/adventurewidget.h @@ -4,54 +4,35 @@ // Author: Mike Repass (Taryn) #include "../global/macros.h" +#include "AdventureLogModel.h" #include "adventuretracker.h" -#include - #include #include #include #include -class NODISCARD_QOBJECT AdventureWidget : public QWidget +// Read-only text view of an AdventureLogModel: one document block per model +// row, kept in sync through the model's rowsInserted()/rowsRemoved() +// signals. The model owns the line cap and the AdventureTracker wiring. +class NODISCARD_QOBJECT AdventureWidget final : public QWidget { Q_OBJECT private: - AdventureTracker &m_adventureTracker; - + AdventureLogModel *m_model = nullptr; QTextEdit *m_textEdit = nullptr; - std::unique_ptr m_textCursor; QAction *m_clearContentAction = nullptr; public: - static constexpr const int MAX_LINES = 1024; - static constexpr const auto DEFAULT_MSG - = "Your adventures in Middle Earth will be tracked here!\n"; - - static constexpr const auto ACCOMPLISH_MSG = "Task accomplished! (%1 xp)\n"; - static constexpr const auto ACHIEVE_MSG = "Achievement: %1\n"; - static constexpr const auto ACHIEVE_MSG_XP = "Achievement: %1 (%2 xp)\n"; - static constexpr const auto DIED_MSG = "You are dead! Sorry... (%1 xp)\n"; - static constexpr const auto GAINED_LEVEL_MSG = "You gain a level! Congrats!\n"; - static constexpr const auto HINT_MSG = "Hint: %1\n"; - static constexpr const auto KILL_TROPHY_MSG = "Trophy: %1 (%2 xp)\n"; - explicit AdventureWidget(AdventureTracker &at, QWidget *parent); private: - void addDefaultContent(); - void addAdventureUpdate(const QString &msg); - -public slots: - void slot_onAccomplishedTask(double xpGained); - void slot_onAchievedSomething(const QString &achievement, double xpGained); - void slot_onDied(double xpLost); - void slot_onGainedLevel(); - void slot_onKilledMob(const QString &mobName, double xpGained); - void slot_onReceivedHint(const QString &hint); + void appendRows(int first, int last); + void removeRows(int first, int last); private slots: + void slot_rowsInserted(const QModelIndex &parent, int first, int last); + void slot_rowsRemoved(const QModelIndex &parent, int first, int last); void slot_contextMenuRequested(const QPoint &pos); - void slot_actionClearContent(bool checked = false); }; diff --git a/src/client/ClientWidget.cpp b/src/client/ClientWidget.cpp index ec66a506f..e35b1be42 100644 --- a/src/client/ClientWidget.cpp +++ b/src/client/ClientWidget.cpp @@ -12,16 +12,21 @@ #include "HotkeyManager.h" #include "PreviewWidget.h" #include "displaywidget.h" +#include "inputwidget.h" #include "stackedinputwidget.h" #include "ui_ClientWidget.h" +#include #include #include #include +#include #include +#include #include #include +#include ClientWidget::ClientWidget(ConnectionListener &listener, HotkeyManager &hotkeyManager, @@ -35,24 +40,79 @@ ClientWidget::ClientWidget(ConnectionListener &listener, initPipeline(); auto &ui = getUi(); - - // Port - ui.port->setText(QString("%1").arg(getConfig().connection.localPort)); - - ui.playButton->setFocus(); - QObject::connect(ui.playButton, &QAbstractButton::clicked, this, [this]() { - getUi().parent->setCurrentIndex(1); - getTelnet().connectToHost(m_listener); - }); + initWelcomePage(); ui.input->installEventFilter(this); ui.display->setFocusPolicy(Qt::TabFocus); - if constexpr (CURRENT_PLATFORM == PlatformEnum::Wasm) { - ui.playButton->click(); + // The card asks how to play; the preference can answer instead, and + // the web build has only the built-in client. + switch (getConfig().general.gameClient) { + case GameClientEnum::BUILT_IN: + play(); + break; + case GameClientEnum::EXTERNAL: + ui.parent->setCurrentWidget(ui.externalPage); + break; + case GameClientEnum::ASK: + ui.parent->setCurrentWidget(ui.welcomePage); + ui.playButton->setFocus(); + break; } } +void ClientWidget::initWelcomePage() +{ + auto &ui = getUi(); + const auto &audio = getConfig().audio; + const QString port = QString::number(getConfig().connection.localPort); + ui.portLabel->setText(tr("Point it at localhost, port %1").arg(port)); + ui.waitingLabel->setText(tr("Waiting for your MUD client on localhost, port %1").arg(port)); + ui.soundCheckBox->setChecked(audio.getMusicVolume() > 0 || audio.getSoundVolume() > 0); + + // What the card decided: sound, and (if asked not to ask again) how to + // play from now on. Either remembered choice is undone in Preferences. + const auto applyChoices = [this](const GameClientEnum client) { + auto &ui2 = getUi(); + // The box is a coarse switch over both channels (the sliders in + // Preferences > Audio set levels): on brings a channel at 0 up to + // the default level and unlocks; off is both at 0. + auto &settings = setConfig().audio; + using AudioSettings = Configuration::AudioSettings; + if (ui2.soundCheckBox->isChecked()) { + if (settings.getMusicVolume() == 0) { + settings.setMusicVolume(AudioSettings::DEFAULT_VOLUME); + } + if (settings.getSoundVolume() == 0) { + settings.setSoundVolume(AudioSettings::DEFAULT_VOLUME); + } + settings.setUnlocked(); + } else { + settings.setMusicVolume(0); + settings.setSoundVolume(0); + } + if (ui2.dontAskCheckBox->isChecked()) { + setConfig().general.gameClient = client; + } + }; + connect(ui.playButton, &QAbstractButton::clicked, this, [this, applyChoices]() { + applyChoices(GameClientEnum::BUILT_IN); + play(); + }); + connect(ui.externalButton, &QAbstractButton::clicked, this, [this, applyChoices]() { + applyChoices(GameClientEnum::EXTERNAL); + getUi().parent->setCurrentWidget(getUi().externalPage); + }); + connect(ui.playInsteadButton, &QAbstractButton::clicked, this, [this]() { play(); }); +} + +void ClientWidget::play() +{ + auto &ui = getUi(); + ui.parent->setCurrentWidget(ui.clientPage); + getTelnet().connectToHost(m_listener); +} + ClientWidget::~ClientWidget() = default; ClientWidget::Pipeline::~Pipeline() @@ -61,8 +121,10 @@ ClientWidget::Pipeline::~Pipeline() objs.ui.reset(); } -QSize ClientWidget::minimumSizeHint() const +QSize ClientWidget::sizeHint() const { + // Preferred size is the configured terminal columns/rows; the minimum is + // left to the layout so the dock can shrink on small screens. return m_pipeline.objs.ui->display->sizeHint(); } @@ -72,6 +134,7 @@ void ClientWidget::initPipeline() getUi().setupUi(this); // creates stacked input and display initStackedInputWidget(); + initTouchInputStrip(); initDisplayWidget(); initClientTelnet(); @@ -140,6 +203,64 @@ void ClientWidget::initStackedInputWidget() getInput().init(deref(out)); } +void ClientWidget::initTouchInputStrip() +{ + // On-screen keyboards have no Up/Down/Tab, so the compact layout shows a + // row of buttons beside the input that drives command history and + // completion (see setCompactLayout()). The input keeps its + // place in the client page's splitter; this wraps it in a row. + auto &ui = getUi(); + QSplitter &splitter = deref(ui.clientPage); + const int inputIndex = splitter.indexOf(ui.input); + + auto *const row = new QWidget(this); + auto *const layout = new QHBoxLayout(row); + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(0); + layout->addWidget(ui.input, 1); + + auto *const strip = new QWidget(row); + auto *const stripLayout = new QHBoxLayout(strip); + stripLayout->setContentsMargins(0, 0, 0, 0); + stripLayout->setSpacing(0); + + InputWidget &inputWidget = getInput().getInputWidget(); + static constexpr int TOUCH_BUTTON_SIZE = 44; // logical px; the usual finger target + const auto addButton = [&](const QString &text, const QString &toolTip, auto &&onClicked) { + auto *const button = new QToolButton(strip); + button->setText(text); + button->setToolTip(toolTip); + button->setAutoRaise(true); + button->setFocusPolicy(Qt::NoFocus); // never take focus from the input + button->setFixedSize(TOUCH_BUTTON_SIZE, TOUCH_BUTTON_SIZE); + connect(button, + &QToolButton::clicked, + &inputWidget, + std::forward(onClicked)); + stripLayout->addWidget(button); + }; + addButton(QStringLiteral("\u2191"), tr("Previous command"), &InputWidget::backwardHistory); + addButton(QStringLiteral("\u2193"), tr("Next command"), &InputWidget::forwardHistory); + addButton(QStringLiteral("\u21e5"), tr("Complete word"), &InputWidget::tabComplete); + strip->hide(); + layout->addWidget(strip, 0, Qt::AlignBottom); + + splitter.insertWidget(inputIndex, row); + splitter.setCollapsible(splitter.indexOf(row), false); + m_touchInputStrip = strip; +} + +void ClientWidget::setCompactLayout(const bool compact) +{ + if (m_touchInputStrip != nullptr) { + m_touchInputStrip->setVisible(compact); + } + m_previewEnabled = !compact; + if (!m_previewEnabled) { + getPreview().hide(); + } +} + void ClientWidget::initDisplayWidget() { class NODISCARD LocalDisplayWidgetOutputs final : public DisplayWidgetOutputs @@ -166,7 +287,10 @@ void ClientWidget::initDisplayWidget() getTelnet().onWindowSizeChanged(width, height); } void virt_returnFocusToInput() final { getSelf().getInput().setFocus(); } - void virt_showPreview(bool visible) final { getSelf().getPreview().setVisible(visible); } + void virt_showPreview(bool visible) final + { + getSelf().getPreview().setVisible(visible && getSelf().m_previewEnabled); + } }; auto &out = m_pipeline.outputs.displayWidgetOutputs; out = std::make_unique(*this); @@ -272,7 +396,8 @@ void ClientWidget::slot_onVisibilityChanged(const bool /*visible*/) bool ClientWidget::isUsingClient() const { - return getUi().parent->currentIndex() != 0; + const auto &ui = getUi(); + return ui.parent->currentWidget() == ui.clientPage; } void ClientWidget::displayReconnectHint() diff --git a/src/client/ClientWidget.h b/src/client/ClientWidget.h index fd9c55ba8..69ef8fad8 100644 --- a/src/client/ClientWidget.h +++ b/src/client/ClientWidget.h @@ -56,6 +56,8 @@ class NODISCARD_QOBJECT ClientWidget final : public QWidget }; Pipeline m_pipeline; + QWidget *m_touchInputStrip = nullptr; + bool m_previewEnabled = true; ConnectionListener &m_listener; HotkeyManager &m_hotkeyManager; @@ -67,7 +69,19 @@ class NODISCARD_QOBJECT ClientWidget final : public QWidget private: void initPipeline(); + void initWelcomePage(); void initStackedInputWidget(); + void initTouchInputStrip(); + +public: + // The Up/Down/Tab buttons beside the input, for on-screen keyboards; + // MainWindow shows them in its compact layout. + // Compact layout: the touch input strip shows and the peek preview + // pane (a second copy of the newest lines while scrolled back) is not + // used, since it would take a phone's whole terminal. + void setCompactLayout(bool compact); + +private: void initDisplayWidget(); void initClientTelnet(); @@ -85,13 +99,15 @@ class NODISCARD_QOBJECT ClientWidget final : public QWidget public: NODISCARD HotkeyManager &getHotkeys(); NODISCARD bool isUsingClient() const; + // Connects the built-in client (the Play button; also Tools > Play MUME). + void play(); void displayReconnectHint(); private: void relayMessage(const QString &msg) { emit sig_relayMessage(msg); } protected: - NODISCARD QSize minimumSizeHint() const override; + NODISCARD QSize sizeHint() const override; NODISCARD bool focusNextPrevChild(bool next) override; signals: diff --git a/src/client/ClientWidget.ui b/src/client/ClientWidget.ui index d51c11953..43ff9a7cb 100644 --- a/src/client/ClientWidget.ui +++ b/src/client/ClientWidget.ui @@ -32,13 +32,7 @@ 0 - - - 343 - 0 - - - + 0 @@ -59,220 +53,153 @@ QFrame::NoFrame - - 0 - - - Qt::ScrollBarAlwaysOff - - - QAbstractScrollArea::AdjustToContentsOnFirstShow - true - - - 0 - 0 - 343 - 504 - - - + - 12 + 24 - 9 + 24 - 0 + 24 - 9 + 24 - 0 + 24 - - - - QFrame::NoFrame + + + + + 420 + 16777215 + - - QFrame::Raised + + QFrame::StyledPanel - + + + 16 + - 0 + 20 - 0 + 20 - 0 + 20 - 0 + 20 - + + + + 18 + true + + - Play MUME by launching the integrated mud client + Play MUME - - true + + + + + + MUME has area music and sound effects; you can change your mind in Preferences + + + Play music and sound effects + + + + :/icons/audiocfg.png:/icons/audiocfg.png + + + 0 + 44 + + true - Play MUME using the integrated mud client + Play MUME right here in MMapper - Play MUME + Play in MMapper :/icons/terminal.png:/icons/terminal.png - - - 48 - 48 - + + true - - - - - - - QFrame::NoFrame - - - 0 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - or - - - Qt::AlignCenter + + + + Keep MMapper as the mapper and play in another MUD client - - - - - - Qt::Horizontal + + I use my own MUD client - - - - - - Qt::Horizontal + + true - - - - - - - Connect to MMapper using your favorite mud client for a better experience - - - true - - - - - - - QFrame::NoFrame - - - 0 - - - - 0 - - - 0 - - - 0 - - - 0 - - + + + false + - hostname: + Point it at localhost, port 4242 - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + Qt::AlignCenter - - - localhost + + + Next time, do what you choose now without asking - - true + + Don't ask again - + - port: + New to MUME? <a href="https://docs.mume.org/newcomers">Read the newcomer's guide</a> - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - 4242 + Qt::AlignCenter - + true @@ -303,7 +230,7 @@ 0 0 - + @@ -312,6 +239,64 @@ + + + + 12 + + + 24 + + + 24 + + + 24 + + + 24 + + + + + Waiting for your MUD client on localhost, port 4242 + + + Qt::AlignCenter + + + true + + + + + + + Play MUME right here in MMapper + + + Play here instead + + + true + + + + + + + Qt::Vertical + + + + 0 + 0 + + + + + + diff --git a/src/client/InputHistory.cpp b/src/client/InputHistory.cpp new file mode 100644 index 000000000..83453e746 --- /dev/null +++ b/src/client/InputHistory.cpp @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "InputHistory.h" + +#include "../configuration/configuration.h" + +#include + +static constexpr const int MIN_WORD_LENGTH = 3; + +static const QRegularExpression g_whitespaceRx(R"(\s+)"); + +void InputHistory::addInputLine(const QString &string) +{ + if (!string.isEmpty() && (empty() || back() != string)) { + // Add to line history if it is a new entry + push_front(string); + } + + // Trim line history + if (static_cast(size()) > getConfig().integratedClient.linesOfInputHistory) { + pop_back(); + } + + // Reset the iterator + m_iterator = begin(); +} + +void TabHistory::addInputLine(const QString &string) +{ + QStringList list = string.split(g_whitespaceRx, Qt::SplitBehaviorFlags::SkipEmptyParts); + for (const QString &word : list) { + if (word.length() > MIN_WORD_LENGTH) { + // Adding this word to the dictionary + push_front(word); + + // Trim dictionary + if (static_cast(size()) + > getConfig().integratedClient.tabCompletionDictionarySize) { + pop_back(); + } + } + } + + // Reset the iterator + m_iterator = begin(); +} + +std::optional TabHistory::nextMatch(const QString &fragment) +{ + while (!atEnd()) { + const QString word = value(); + forward(); + if (!word.startsWith(fragment)) { + continue; + } + if (atEnd()) { + // The match found was the last entry in the dictionary: mirrors + // InputWidget::tabComplete()'s original two-step + // apply-then-immediately-revert behavior for this case (the + // completion it would have applied gets undone by the very next + // "reached end" check), so the net effect is the same as no + // match having been found at all. + reset(); + return std::nullopt; + } + return word; + } + reset(); + return std::nullopt; +} diff --git a/src/client/InputHistory.h b/src/client/InputHistory.h new file mode 100644 index 000000000..f2edd6243 --- /dev/null +++ b/src/client/InputHistory.h @@ -0,0 +1,67 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "../global/macros.h" + +#include +#include +#include + +#include + +// Command history used by InputWidget; has no QWidget dependency so it can be +// unit tested on its own. +class NODISCARD InputHistory final : private std::list +{ +private: + std::list::iterator m_iterator; + +public: + InputHistory() { m_iterator = begin(); } + +public: + void addInputLine(const QString &); + +public: + void forward() { std::advance(m_iterator, 1); } + void backward() { std::advance(m_iterator, -1); } + +public: + NODISCARD const QString &value() const { return *m_iterator; } + +public: + NODISCARD bool atFront() const { return m_iterator == begin(); } + NODISCARD bool atEnd() const { return m_iterator == end(); } +}; + +class NODISCARD TabHistory final : private std::list +{ + using base = std::list; + +private: + std::list::iterator m_iterator; + +public: + TabHistory() { m_iterator = begin(); } + +public: + void addInputLine(const QString &); + +public: + void forward() { std::advance(m_iterator, 1); } + void reset() { m_iterator = begin(); } + +public: + NODISCARD const QString &value() const { return *m_iterator; } + +public: + NODISCARD bool empty() { return base::empty(); } + NODISCARD bool atEnd() const { return m_iterator == end(); } + +public: + // Iterates from the current iterator; returns the next word starting with + // fragment and advances past it; nullopt + reset() on wraparound (mirrors + // InputWidget::tabComplete's end-of-dictionary behavior). + NODISCARD std::optional nextMatch(const QString &fragment); +}; diff --git a/src/client/PasswordDialog.cpp b/src/client/PasswordDialog.cpp index a172b233b..0ba408d7d 100644 --- a/src/client/PasswordDialog.cpp +++ b/src/client/PasswordDialog.cpp @@ -17,6 +17,8 @@ PasswordDialog::PasswordDialog(InputWidgetOutputs &outputs, QWidget *const paren m_passwordLineEdit = new QLineEdit(this); m_passwordLineEdit->setEchoMode(QLineEdit::Password); + m_passwordLineEdit->setInputMethodHints(Qt::ImhSensitiveData | Qt::ImhNoAutoUppercase + | Qt::ImhNoPredictiveText); m_passwordLineEdit->setPlaceholderText("Password"); m_passwordLineEdit->setObjectName("passwordLineEdit"); diff --git a/src/client/PreviewWidget.cpp b/src/client/PreviewWidget.cpp index 642e859fa..70816a30e 100644 --- a/src/client/PreviewWidget.cpp +++ b/src/client/PreviewWidget.cpp @@ -29,7 +29,7 @@ PreviewWidget::PreviewWidget(QWidget *parent) // Set maximum height based on configured lines and font metrics int lineCount = qMax(1, settings.linesOfPeekPreview); - QFontMetrics fontMetrics(helper.format.font()); + QFontMetrics fontMetrics(helper.core.format.font()); int lineHeight = fontMetrics.height(); setMaximumHeight(lineHeight * lineCount); } diff --git a/src/client/displaywidget.cpp b/src/client/displaywidget.cpp index 8b538e76b..265ad1e0f 100644 --- a/src/client/displaywidget.cpp +++ b/src/client/displaywidget.cpp @@ -6,22 +6,26 @@ #include "../configuration/configuration.h" #include "../global/AnsiTextUtils.h" +#include "../global/window_utils.h" + +#include #include #include #include #include +#include #include #include #include #include #include #include +#include namespace { // anonymous const constexpr int TAB_WIDTH_SPACES = 8; -const volatile bool ignore_non_default_underline_colors = false; void foreach_char(const QChar qchar, const QStringView text, @@ -43,13 +47,6 @@ void foreach_char(const QChar qchar, } } -void foreach_backspace(const QStringView text, - const std::function &callback_backspace, - const std::function &callback_between) -{ - foreach_char(char_consts::C_BACKSPACE, text, callback_backspace, callback_between); -} - } // namespace FontDefaults::FontDefaults() @@ -66,17 +63,17 @@ FontDefaults::FontDefaults() void AnsiTextHelper::init() { - QTextFrameFormat frameFormat = textEdit.document()->rootFrame()->frameFormat(); - frameFormat.setBackground(defaults.defaultBg); - frameFormat.setForeground(defaults.defaultFg); - textEdit.document()->rootFrame()->setFrameFormat(frameFormat); - - format = cursor.charFormat(); - setDefaultFormat(format, defaults); - cursor.setCharFormat(format); + // core.init() sets the frame and character format's background/foreground colors from + // defaults; the font family is a widget-only concern, so it's applied here afterward. + core.init(); + core.format.setFont(defaults.serverOutputFont); + core.cursor.setCharFormat(core.format); } DisplayWidgetOutputs::~DisplayWidgetOutputs() = default; +// Touch long-press duration; see mousePressEvent(). +static constexpr int LONG_PRESS_MS = 600; + DisplayWidget::DisplayWidget(QWidget *const parent) : QTextBrowser(parent) , m_ansiTextHelper{static_cast(*this)} @@ -92,6 +89,18 @@ DisplayWidget::DisplayWidget(QWidget *const parent) frameFormat.setBackground(getConfig().integratedClient.backgroundColor); document()->rootFrame()->setFrameFormat(frameFormat); }); + m_longPressTimer.setSingleShot(true); + m_longPressTimer.setInterval(LONG_PRESS_MS); + connect(&m_longPressTimer, &QTimer::timeout, this, [this]() { + if (!m_longPressPos) { + return; + } + const QPoint pos = *m_longPressPos; + m_longPressPos.reset(); + mmqt::popupMenu(std::unique_ptr{createStandardContextMenu(pos)}, + viewport()->mapToGlobal(pos)); + }); + setDocumentTitle("MMapper Mud Client"); setTextInteractionFlags(Qt::TextBrowserInteraction); setOpenExternalLinks(true); @@ -146,6 +155,69 @@ QSize DisplayWidget::sizeHint() const return QSize(x, y); } +void DisplayWidget::mousePressEvent(QMouseEvent *const event) +{ + m_longPressTimer.stop(); + m_longPressPos.reset(); + m_touchPressPos.reset(); + m_touchScrolling = false; + + // A single finger (delivered as a synthesized left press) scrolls the + // output rather than selecting text, and a held finger opens the + // context menu, since touch never synthesizes a right-click. The press + // is not passed on, so no selection starts; the mouse is unaffected. + if (event->button() == Qt::LeftButton && event->source() != Qt::MouseEventNotSynthesized) { + const QPoint pos = event->position().toPoint(); + m_longPressPos = pos; + m_longPressTimer.start(); + m_touchPressPos = pos; + QScroller::scroller(viewport()) + ->handleInput(QScroller::InputPress, + event->position(), + static_cast(event->timestamp())); + event->accept(); + return; + } + QTextBrowser::mousePressEvent(event); +} + +void DisplayWidget::mouseMoveEvent(QMouseEvent *const event) +{ + if (m_touchPressPos) { + if (!m_touchScrolling + && (event->position().toPoint() - *m_touchPressPos).manhattanLength() + > QApplication::startDragDistance()) { + m_touchScrolling = true; + m_longPressTimer.stop(); + m_longPressPos.reset(); + } + QScroller::scroller(viewport()) + ->handleInput(QScroller::InputMove, + event->position(), + static_cast(event->timestamp())); + event->accept(); + return; + } + QTextBrowser::mouseMoveEvent(event); +} + +void DisplayWidget::mouseReleaseEvent(QMouseEvent *const event) +{ + m_longPressTimer.stop(); + m_longPressPos.reset(); + if (m_touchPressPos) { + m_touchPressPos.reset(); + m_touchScrolling = false; + QScroller::scroller(viewport()) + ->handleInput(QScroller::InputRelease, + event->position(), + static_cast(event->timestamp())); + event->accept(); + return; + } + QTextBrowser::mouseReleaseEvent(event); +} + void DisplayWidget::resizeEvent(QResizeEvent *const event) { const auto &margins = contentsMargins(); @@ -220,156 +292,6 @@ void DisplayWidget::keyPressEvent(QKeyEvent *event) } } -void setDefaultFormat(QTextCharFormat &format, const FontDefaults &defaults) -{ - format.setFont(defaults.serverOutputFont); - format.setBackground(defaults.defaultBg); - format.setForeground(defaults.defaultFg); - format.setFontWeight(QFont::Normal); - format.setFontUnderline(false); - format.setFontItalic(false); - format.setFontStrikeOut(false); -} - -void AnsiTextHelper::displayText(const QStringView input_str) -{ - // ANSI codes are formatted as the following: - // escape + [ + n1 (+ n2) + m - static const QRegularExpression ansi_regex{R"regex(\x1B[^A-Za-z\x1B]*[A-Za-z]?)regex"}; - static const QRegularExpression url_regex{ - R"regex(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))regex"}; - - // REVISIT: should we even bother supporting backspaces? - // - // QTextEdit is not a terminal, so it doesn't really have the concept of a mutable text buffer - // where you can backspace and then later overwrite the previous letter with something else. - // - // (Yes, technically we could abuse the cursor this to achieve a similar result, but the - // cursor is used in multiple functions, so that might be too fragile.) - // - // Current solution: simulate the backspace operation by adding a backspace character to the - // buffer, and then later remove the backspace and previous character. - // - // MUME could send a telnet event that signals that the player is waiting, - // and then we could display the waiting state some other way. - // - // Or we could just ignore the backspaces and display "\|/-" instead of the animation. - // - // It might also be worth considering using an emoji or an icon instead of C_BACKSPACE. - static const volatile bool allow_backspaces = true; - - // note: debug_backspaces effectively implies allow_backspaces == false, - // because writes "(Backspace)" instead of a backspace character, and then it leaves both - // "(Backspace)" and the letter that would have been removed by the backspace operation. - static const volatile bool debug_backspaces = false; - - auto try_remove_backspace = [this]() { - if (!allow_backspaces) { - return; - } - - const auto block = cursor.block(); - if (!block.isValid() || cursor.block().length() == 0) { - return; - } - - const auto text = block.text(); - if (text.isNull() || text.isEmpty() || text.back() != char_consts::C_BACKSPACE) { - return; - } - - cursor.deletePreviousChar(); - if (block.length() > 0) { - cursor.deletePreviousChar(); - } - }; - - auto add_raw = [this, &try_remove_backspace](const QStringView text, - const QTextCharFormat &withFmt) { - try_remove_backspace(); - cursor.insertText(text.toString(), withFmt); - }; - - auto try_add_backspace = [this, &add_raw]() { - if (debug_backspaces) { - add_raw(u"(BACKSPACE)", {}); - return; - } - - if (!allow_backspaces || cursor.position() < 1) { - return; - } - - const auto block = cursor.block(); - if (!block.isValid() && block.length() < 1) { - return; - } - - const auto text = block.text(); - if (text.isNull() || text.isEmpty()) { - return; - } - - add_raw(mmqt::QS_BACKSPACE, {}); - }; - - auto add_formatted = [this, &add_raw, &try_remove_backspace](const QStringView text) { - mmqt::foreach_regex( - url_regex, - text, - [this, &try_remove_backspace](const QStringView url) { - const auto s = url.toString(); - // TODO: override the document's CSS for URLs - const auto link - = QString( - R"(%2)") - .arg(QString::fromUtf8(QUrl::fromUserInput(s).toEncoded()), - s.toHtmlEscaped()); - - try_remove_backspace(); - cursor.insertHtml(link); - }, - [this, &add_raw](const QStringView non_url) { add_raw(non_url, format); }); - }; - - // Display text using a cursor - mmqt::foreach_regex( - ansi_regex, - input_str, - [this, &add_raw](const QStringView ansiStr) { - assert(!ansiStr.isEmpty() && ansiStr.front() == char_consts::C_ESC); - if (mmqt::isAnsiColor(ansiStr)) { - if (auto optNewColor = mmqt::parseAnsiColor(currentAnsi, ansiStr)) { - currentAnsi = updateFormat(format, defaults, currentAnsi, *optNewColor); - } - } else if (mmqt::isAnsiEraseLine(ansiStr)) { - cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 1); - cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); - cursor.removeSelectedText(); - } else { - add_raw(u"", {}); - if (ansiStr.length() > 1) { - add_raw(ansiStr.mid(1), format); - } - } - }, - [&try_add_backspace, &add_formatted](const QStringView textStr) { - foreach_backspace(textStr, try_add_backspace, add_formatted); - }); -} - -void AnsiTextHelper::limitScrollback(int lineLimit) -{ - const int lineCount = textEdit.document()->lineCount(); - if (lineCount > lineLimit) { - const int trimLines = lineCount - lineLimit; - cursor.movePosition(QTextCursor::Start); - cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor, trimLines); - cursor.removeSelectedText(); - cursor.movePosition(QTextCursor::End); - } -} - void DisplayWidget::slot_displayText(const QStringView str) { const int lineLimit = getConfig().integratedClient.linesOfScrollback; @@ -417,139 +339,6 @@ void DisplayWidget::slot_displayText(const QStringView str) } } -NODISCARD static QColor decodeColor(const AnsiColorRGB var) -{ - return QColor::fromRgb(var.r, var.g, var.b); -} - -NODISCARD static QColor decodeColor(AnsiColor256 var, const bool intense) -{ - if (var.color < 8 && intense) { - var.color += 8; - } - - return mmqt::ansi256toRgb(var.color); -} - -NODISCARD static QColor decodeColor(const AnsiColorVariant var, - const QColor defaultColor, - const bool intense) -{ - if (var.hasRGB()) { - return decodeColor(var.getRGB()); - } - - if (var.has256()) { - return decodeColor(var.get256(), intense); - } - - return defaultColor; -} - -static void reverseInPlace(QColor &color) -{ - color.setRed(255 - color.red()); - color.setGreen(255 - color.green()); - color.setBlue(255 - color.blue()); -} - -RawAnsi updateFormat(QTextCharFormat &format, - const FontDefaults &defaults, - const RawAnsi &before, - RawAnsi updated) -{ - if (ignore_non_default_underline_colors && !updated.ul.hasDefaultColor()) { - // Ignore underline color. - updated.ul = AnsiColorVariant{}; - } - - if (before == updated) { - return updated; - } - - if (updated == RawAnsi{}) { - setDefaultFormat(format, defaults); - return updated; - } - - // auto removed = before.flags & ~updated.flags; - // auto added = updated.flags & ~before.flags; - const auto diff = before.getFlags() ^ updated.getFlags(); - - for (const AnsiStyleFlagEnum flag : diff) { - switch (flag) { - case AnsiStyleFlagEnum::Italic: - format.setFontItalic(updated.hasItalic()); - break; - case AnsiStyleFlagEnum::Underline: { - // QTextCharFormat doesn't support other underline styles. - format.setFontUnderline(updated.hasUnderline()); - using ULS = QTextCharFormat::UnderlineStyle; - const auto style = std::invoke([&updated]() -> QTextCharFormat::UnderlineStyle { - switch (updated.getUnderlineStyle()) { - case AnsiUnderlineStyleEnum::Dotted: - return ULS::DotLine; - case AnsiUnderlineStyleEnum::Curly: - return ULS::WaveUnderline; - case AnsiUnderlineStyleEnum::Dashed: - return ULS::DashUnderline; - case AnsiUnderlineStyleEnum::None: - case AnsiUnderlineStyleEnum::Normal: - case AnsiUnderlineStyleEnum::Double: // not supported by Qt - default: - return ULS::SingleUnderline; - } - }); - format.setUnderlineStyle(style); - break; - } - case AnsiStyleFlagEnum::Strikeout: - format.setFontStrikeOut(updated.hasStrikeout()); - break; - case AnsiStyleFlagEnum::Bold: - case AnsiStyleFlagEnum::Faint: - if (updated.hasBold()) { - format.setFontWeight(QFont::Bold); - } else if (updated.hasFaint()) { - format.setFontWeight(QFont::Light); - } else { - format.setFontWeight(QFont::Normal); - } - break; - case AnsiStyleFlagEnum::Blink: // ignored - case AnsiStyleFlagEnum::Reverse: // handled below - case AnsiStyleFlagEnum::Conceal: // handled below - break; - } - } - - const bool conceal = updated.hasConceal(); - const bool reverse = updated.hasReverse(); - const bool intense = updated.hasBold(); - - auto bg = decodeColor(updated.bg, defaults.defaultBg, false); - auto fg = decodeColor(updated.fg, defaults.defaultFg, intense); - auto ul = decodeColor(updated.ul, defaults.getDefaultUl(), intense); - - if (reverse) { - // was swap(fg, bg) before we supported underline color - ::reverseInPlace(fg); - ::reverseInPlace(bg); - ::reverseInPlace(ul); - } - - // Create a config setting and use it here if you really want to miss text that others will see! - bool userExplicitlyOptedInForConceal = false; - if (conceal && userExplicitlyOptedInForConceal) { - ul = fg = bg; - } - - format.setBackground(bg); - format.setForeground(fg); - format.setUnderlineColor(ul); - return updated; -} - void setAnsiText(QTextEdit *const pEdit, const std::string_view text) { QTextEdit &edit = deref(pEdit); diff --git a/src/client/displaywidget.h b/src/client/displaywidget.h index 9b37d7f12..d87fdcb79 100644 --- a/src/client/displaywidget.h +++ b/src/client/displaywidget.h @@ -3,8 +3,10 @@ // Copyright (C) 2019 The MMapper Authors // Author: Nils Schimmelmann (Jahara) +#include "../global/AnsiHtml.h" #include "../global/AnsiTextUtils.h" #include "../global/macros.h" +#include "../global/utils.h" #include @@ -34,28 +36,24 @@ struct NODISCARD FontDefaults final explicit FontDefaults(); NODISCARD QColor getDefaultUl() const { return defaultUl.value_or(defaultFg); } + NODISCARD mmqt::AnsiHtmlDefaults toAnsiHtmlDefaults() const + { + return mmqt::AnsiHtmlDefaults{defaultBg, defaultFg, defaultUl}; + } }; -extern void setDefaultFormat(QTextCharFormat &format, const FontDefaults &defaults); - -NODISCARD extern RawAnsi updateFormat(QTextCharFormat &format, - const FontDefaults &defaults, - const RawAnsi &before, - RawAnsi updated); - +// AnsiTextHelper is a thin QTextEdit-flavored wrapper around mmqt::AnsiTextToDocument +// (see global/AnsiHtml.h), which does the widget-free rendering work. struct NODISCARD AnsiTextHelper final { QTextEdit &textEdit; - QTextCursor cursor; - QTextCharFormat format; const FontDefaults defaults; - RawAnsi currentAnsi; + mmqt::AnsiTextToDocument core; explicit AnsiTextHelper(QTextEdit &input_textEdit, FontDefaults def) : textEdit{input_textEdit} - , cursor{textEdit.document()->rootFrame()->firstCursorPosition()} - , format{cursor.charFormat()} , defaults{std::move(def)} + , core{deref(textEdit.document()), defaults.toAnsiHtmlDefaults()} {} explicit AnsiTextHelper(QTextEdit &input_textEdit) @@ -63,8 +61,8 @@ struct NODISCARD AnsiTextHelper final {} void init(); - void displayText(const QStringView str); - void limitScrollback(int lineLimit); + void displayText(const QStringView str) { core.displayText(str); } + void limitScrollback(const int lineLimit) { core.limitScrollback(lineLimit); } }; extern void setAnsiText(QTextEdit *pEdit, std::string_view text); @@ -104,6 +102,15 @@ class NODISCARD_QOBJECT DisplayWidget final : public QTextBrowser AnsiTextHelper m_ansiTextHelper; QTimer *m_timer = nullptr; bool m_canCopy = false; + // Touch long-press -> the standard context menu (copy, select all, ...), + // which touch cannot otherwise reach; see mousePressEvent(). + QTimer m_longPressTimer; + std::optional m_longPressPos; + // A finger on the output scrolls it (fed to the viewport's QScroller by + // hand, see mousePressEvent()); it never selects text, and a held + // finger opens the context menu. + std::optional m_touchPressPos; + bool m_touchScrolling = false; public: explicit DisplayWidget(QWidget *parent); @@ -135,6 +142,9 @@ class NODISCARD_QOBJECT DisplayWidget final : public QTextBrowser protected: void resizeEvent(QResizeEvent *event) override; void keyPressEvent(QKeyEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; public slots: void slot_displayText(const QStringView str); diff --git a/src/client/inputwidget.cpp b/src/client/inputwidget.cpp index 348f7f246..6f50e048a 100644 --- a/src/client/inputwidget.cpp +++ b/src/client/inputwidget.cpp @@ -17,10 +17,6 @@ #include #include -static constexpr const int MIN_WORD_LENGTH = 3; - -static const QRegularExpression g_whitespaceRx(R"(\s+)"); - InputWidgetOutputs::~InputWidgetOutputs() = default; InputWidget::InputWidget(QWidget *const parent, InputWidgetOutputs &outputs) @@ -47,6 +43,9 @@ InputWidget::InputWidget(QWidget *const parent, InputWidgetOutputs &outputs) // Line Wrapping setLineWrapMode(QPlainTextEdit::NoWrap); + // On-screen keyboards: MUD commands are lowercase and not prose. + setInputMethodHints(Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText); + // Remember native palletes m_paletteManager.init(*this, std::nullopt, Qt::lightGray); } @@ -258,42 +257,6 @@ void InputWidget::gotInput() m_tabHistory.addInputLine(input); } -void InputHistory::addInputLine(const QString &string) -{ - if (!string.isEmpty() && (empty() || back() != string)) { - // Add to line history if it is a new entry - push_front(string); - } - - // Trim line history - if (static_cast(size()) > getConfig().integratedClient.linesOfInputHistory) { - pop_back(); - } - - // Reset the iterator - m_iterator = begin(); -} - -void TabHistory::addInputLine(const QString &string) -{ - QStringList list = string.split(g_whitespaceRx, Qt::SplitBehaviorFlags::SkipEmptyParts); - for (const QString &word : list) { - if (word.length() > MIN_WORD_LENGTH) { - // Adding this word to the dictionary - push_front(word); - - // Trim dictionary - if (static_cast(size()) - > getConfig().integratedClient.tabCompletionDictionarySize) { - pop_back(); - } - } - } - - // Reset the iterator - m_iterator = begin(); -} - void InputWidget::forwardHistory() { clear(); @@ -346,32 +309,19 @@ void InputWidget::tabComplete() m_tabbing = true; } - // Iterate through all previous words - while (!m_tabHistory.atEnd()) { - const auto &word = m_tabHistory.value(); - if (!word.startsWith(m_tabFragment)) { - // Try the next word - m_tabHistory.forward(); - continue; - } - - // Found a previous word to complete to + // Find the next previous word that completes the fragment, cycling back + // to reverting the completion (see TabHistory::nextMatch()) once the + // dictionary is exhausted. + if (const std::optional word = m_tabHistory.nextMatch(m_tabFragment)) { current.removeSelectedText(); current.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor); - current.insertText(word); - auto length = static_cast(word.length() - m_tabFragment.length()); + current.insertText(*word); + auto length = static_cast(word->length() - m_tabFragment.length()); current.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, length); current.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, length); setTextCursor(current); - - m_tabHistory.forward(); - break; - } - - // If we reach the end then loop back to the beginning and clear the selected text again - if (m_tabHistory.atEnd()) { + } else { textCursor().removeSelectedText(); - m_tabHistory.reset(); } } diff --git a/src/client/inputwidget.h b/src/client/inputwidget.h index 3db19bbb8..b940dad7d 100644 --- a/src/client/inputwidget.h +++ b/src/client/inputwidget.h @@ -6,11 +6,9 @@ #include "../global/RuleOf5.h" #include "../global/macros.h" #include "Hotkey.h" +#include "InputHistory.h" #include "PaletteManager.h" -#include -#include - #include #include #include @@ -23,54 +21,6 @@ class QKeyEvent; class QObject; class QWidget; -class NODISCARD InputHistory final : private std::list -{ -private: - std::list::iterator m_iterator; - -public: - InputHistory() { m_iterator = begin(); } - -public: - void addInputLine(const QString &); - -public: - void forward() { std::advance(m_iterator, 1); } - void backward() { std::advance(m_iterator, -1); } - -public: - NODISCARD const QString &value() const { return *m_iterator; } - -public: - NODISCARD bool atFront() const { return m_iterator == begin(); } - NODISCARD bool atEnd() const { return m_iterator == end(); } -}; - -class NODISCARD TabHistory final : private std::list -{ - using base = std::list; - -private: - std::list::iterator m_iterator; - -public: - TabHistory() { m_iterator = begin(); } - -public: - void addInputLine(const QString &); - -public: - void forward() { std::advance(m_iterator, 1); } - void reset() { m_iterator = begin(); } - -public: - NODISCARD const QString &value() const { return *m_iterator; } - -public: - NODISCARD bool empty() { return base::empty(); } - NODISCARD bool atEnd() const { return m_iterator == end(); } -}; - struct NODISCARD InputWidgetOutputs { public: @@ -128,10 +78,10 @@ class NODISCARD_QOBJECT InputWidget final : public QPlainTextEdit NODISCARD bool handleTerminalShortcut(int key); NODISCARD bool handleBasicKey(int key); -private: +public: + // The Tab / Up / Down key actions; also driven by the touch input strip + // (see ClientWidget::initTouchInputStrip()). void tabComplete(); - -private: void forwardHistory(); void backwardHistory(); diff --git a/src/client/stackedinputwidget.h b/src/client/stackedinputwidget.h index c4abc4753..2ab48bbf3 100644 --- a/src/client/stackedinputwidget.h +++ b/src/client/stackedinputwidget.h @@ -109,8 +109,10 @@ class NODISCARD_QOBJECT StackedInputWidget final : public QStackedWidget // if this fails, it means you forgot to call init NODISCARD StackedInputWidgetOutputs &getOutput() { return deref(m_output); } -private: +public: NODISCARD InputWidget &getInputWidget(); + +private: NODISCARD PasswordDialog &getPasswordDialog(); public: diff --git a/src/clock/ClockStrings.cpp b/src/clock/ClockStrings.cpp new file mode 100644 index 000000000..71d953474 --- /dev/null +++ b/src/clock/ClockStrings.cpp @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "ClockStrings.h" + +namespace clockstrings { + +QString moonPhaseEmoji(const MumeMoonPhaseEnum phase) +{ + switch (phase) { + case MumeMoonPhaseEnum::WAXING_CRESCENT: + return QString::fromUtf8("\xF0\x9F\x8C\x92"); + case MumeMoonPhaseEnum::FIRST_QUARTER: + return QString::fromUtf8("\xF0\x9F\x8C\x93"); + case MumeMoonPhaseEnum::WAXING_GIBBOUS: + return QString::fromUtf8("\xF0\x9F\x8C\x94"); + case MumeMoonPhaseEnum::FULL_MOON: + return QString::fromUtf8("\xF0\x9F\x8C\x95"); + case MumeMoonPhaseEnum::WANING_GIBBOUS: + return QString::fromUtf8("\xF0\x9F\x8C\x96"); + case MumeMoonPhaseEnum::THIRD_QUARTER: + return QString::fromUtf8("\xF0\x9F\x8C\x97"); + case MumeMoonPhaseEnum::WANING_CRESCENT: + return QString::fromUtf8("\xF0\x9F\x8C\x98"); + case MumeMoonPhaseEnum::NEW_MOON: + return QString::fromUtf8("\xF0\x9F\x8C\x91"); + case MumeMoonPhaseEnum::UNKNOWN: + default: + return QString(); + } +} + +QString seasonText(const MumeSeasonEnum season) +{ + switch (season) { + case MumeSeasonEnum::WINTER: + return QStringLiteral("Winter"); + case MumeSeasonEnum::SPRING: + return QStringLiteral("Spring"); + case MumeSeasonEnum::SUMMER: + return QStringLiteral("Summer"); + case MumeSeasonEnum::AUTUMN: + return QStringLiteral("Autumn"); + case MumeSeasonEnum::UNKNOWN: + default: + return QString(); + } +} + +QString weatherEmoji(const PromptWeatherEnum weather) +{ + switch (weather) { + case PromptWeatherEnum::CLOUDS: + return QString::fromUtf8("\xE2\x98\x81"); + case PromptWeatherEnum::RAIN: + return QString::fromUtf8("\xF0\x9F\x8C\xA7"); + case PromptWeatherEnum::HEAVY_RAIN: + return QString::fromUtf8("\xE2\x9B\x88"); + case PromptWeatherEnum::SNOW: + return QString::fromUtf8("\xE2\x9D\x84"); + case PromptWeatherEnum::NICE: + default: + return QString(); + } +} + +QString weatherTooltip(const PromptWeatherEnum weather) +{ + switch (weather) { + case PromptWeatherEnum::CLOUDS: + return QStringLiteral("Cloudy"); + case PromptWeatherEnum::RAIN: + return QStringLiteral("Rainy"); + case PromptWeatherEnum::HEAVY_RAIN: + return QStringLiteral("Heavy Rain"); + case PromptWeatherEnum::SNOW: + return QStringLiteral("Snowy"); + case PromptWeatherEnum::NICE: + default: + return QString(); + } +} + +QString fogEmoji(const PromptFogEnum fog) +{ + switch (fog) { + case PromptFogEnum::LIGHT_FOG: + return QString::fromUtf8("\xF0\x9F\x8C\xAB"); + case PromptFogEnum::HEAVY_FOG: + return QString::fromUtf8("\xF0\x9F\x8C\xAB\xF0\x9F\x8C\xAB"); + case PromptFogEnum::NO_FOG: + default: + return QString(); + } +} + +QString fogTooltip(const PromptFogEnum fog) +{ + switch (fog) { + case PromptFogEnum::LIGHT_FOG: + return QStringLiteral("Light Fog"); + case PromptFogEnum::HEAVY_FOG: + return QStringLiteral("Heavy Fog"); + case PromptFogEnum::NO_FOG: + default: + return QString(); + } +} + +} // namespace clockstrings diff --git a/src/clock/ClockStrings.h b/src/clock/ClockStrings.h new file mode 100644 index 000000000..75648cbcc --- /dev/null +++ b/src/clock/ClockStrings.h @@ -0,0 +1,31 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "../global/macros.h" +#include "../map/PromptFlags.h" +#include "mumemoment.h" + +#include + +// Pure enum -> user-facing string mappings used by MumeClockWidget (the +// QWidget-based clock). Kept free of any Qt widget dependency. +namespace clockstrings { + +// Emoji glyph for the moon phase, or an empty string for UNKNOWN. +NODISCARD QString moonPhaseEmoji(MumeMoonPhaseEnum phase); + +// Display text for the season, or an empty string for UNKNOWN. +NODISCARD QString seasonText(MumeSeasonEnum season); + +// Emoji glyph for the weather, or an empty string for NICE (nothing to show). +NODISCARD QString weatherEmoji(PromptWeatherEnum weather); +// Human-readable tooltip/status-tip text for the weather, or an empty string for NICE. +NODISCARD QString weatherTooltip(PromptWeatherEnum weather); + +// Emoji glyph(s) for the fog, or an empty string for NO_FOG. +NODISCARD QString fogEmoji(PromptFogEnum fog); +// Human-readable tooltip/status-tip text for the fog, or an empty string for NO_FOG. +NODISCARD QString fogTooltip(PromptFogEnum fog); + +} // namespace clockstrings diff --git a/src/clock/mumeclockwidget.cpp b/src/clock/mumeclockwidget.cpp index c4a1ad4b3..10636d7ec 100644 --- a/src/clock/mumeclockwidget.cpp +++ b/src/clock/mumeclockwidget.cpp @@ -5,6 +5,7 @@ #include "mumeclockwidget.h" #include "../configuration/configuration.h" +#include "ClockStrings.h" #include "mumeclock.h" #include "mumemoment.h" @@ -97,35 +98,7 @@ void MumeClockWidget::updateTime(MumeTimeEnum time) void MumeClockWidget::updateMoonPhase(MumeMoonPhaseEnum phase) { - switch (phase) { - case MumeMoonPhaseEnum::WAXING_CRESCENT: - moonPhaseLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\x92")); - break; - case MumeMoonPhaseEnum::FIRST_QUARTER: - moonPhaseLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\x93")); - break; - case MumeMoonPhaseEnum::WAXING_GIBBOUS: - moonPhaseLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\x94")); - break; - case MumeMoonPhaseEnum::FULL_MOON: - moonPhaseLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\x95")); - break; - case MumeMoonPhaseEnum::WANING_GIBBOUS: - moonPhaseLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\x96")); - break; - case MumeMoonPhaseEnum::THIRD_QUARTER: - moonPhaseLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\x97")); - break; - case MumeMoonPhaseEnum::WANING_CRESCENT: - moonPhaseLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\x98")); - break; - case MumeMoonPhaseEnum::NEW_MOON: - moonPhaseLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\x91")); - break; - case MumeMoonPhaseEnum::UNKNOWN: - moonPhaseLabel->setText(""); - break; - } + moonPhaseLabel->setText(clockstrings::moonPhaseEmoji(phase)); } void MumeClockWidget::updateMoonVisibility(MumeMoonVisibilityEnum visibility) @@ -142,84 +115,41 @@ void MumeClockWidget::updateMoonVisibility(MumeMoonVisibilityEnum visibility) void MumeClockWidget::updateSeason(MumeSeasonEnum season) { QString styleSheet = "color:black"; - QString text = ""; switch (season) { case MumeSeasonEnum::WINTER: styleSheet = "color:black;background:white"; - text = "Winter"; break; case MumeSeasonEnum::SPRING: styleSheet = "color:white;background:teal"; - text = "Spring"; break; case MumeSeasonEnum::SUMMER: styleSheet = "color:white;background:green"; - text = "Summer"; break; case MumeSeasonEnum::AUTUMN: styleSheet = "color:black;background:orange"; - text = "Autumn"; break; case MumeSeasonEnum::UNKNOWN: default: break; } seasonLabel->setStyleSheet(styleSheet); - seasonLabel->setText(text); + seasonLabel->setText(clockstrings::seasonText(season)); } void MumeClockWidget::updateWeather(PromptWeatherEnum weather) { - switch (weather) { - case PromptWeatherEnum::CLOUDS: - weatherLabel->setText(QString::fromUtf8("\xE2\x98\x81")); - weatherLabel->setStatusTip("Cloudy"); - weatherLabel->setVisible(true); - break; - case PromptWeatherEnum::RAIN: - weatherLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\xA7")); - weatherLabel->setStatusTip("Rainy"); - weatherLabel->setVisible(true); - break; - case PromptWeatherEnum::HEAVY_RAIN: - weatherLabel->setText(QString::fromUtf8("\xE2\x9B\x88")); - weatherLabel->setStatusTip("Heavy Rain"); - weatherLabel->setVisible(true); - break; - case PromptWeatherEnum::SNOW: - weatherLabel->setText(QString::fromUtf8("\xE2\x9D\x84")); - weatherLabel->setStatusTip("Snowy"); - weatherLabel->setVisible(true); - break; - case PromptWeatherEnum::NICE: - default: - weatherLabel->setText(""); - weatherLabel->setStatusTip(""); - weatherLabel->setVisible(false); - break; - } + const QString text = clockstrings::weatherEmoji(weather); + weatherLabel->setText(text); + weatherLabel->setStatusTip(clockstrings::weatherTooltip(weather)); + weatherLabel->setVisible(!text.isEmpty()); } void MumeClockWidget::updateFog(PromptFogEnum fog) { - switch (fog) { - case PromptFogEnum::LIGHT_FOG: - fogLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\xAB")); - fogLabel->setStatusTip("Light Fog"); - fogLabel->setVisible(true); - break; - case PromptFogEnum::HEAVY_FOG: - fogLabel->setText(QString::fromUtf8("\xF0\x9F\x8C\xAB\xF0\x9F\x8C\xAB")); - fogLabel->setStatusTip("Heavy Fog"); - fogLabel->setVisible(true); - break; - case PromptFogEnum::NO_FOG: - default: - fogLabel->setText(""); - fogLabel->setStatusTip(""); - fogLabel->setVisible(false); - break; - } + const QString text = clockstrings::fogEmoji(fog); + fogLabel->setText(text); + fogLabel->setStatusTip(clockstrings::fogTooltip(fog)); + fogLabel->setVisible(!text.isEmpty()); } void MumeClockWidget::updateCountdown(const MumeMoment &moment) diff --git a/src/configuration/configuration.cpp b/src/configuration/configuration.cpp index fb5e0d99b..4ebe6032d 100644 --- a/src/configuration/configuration.cpp +++ b/src/configuration/configuration.cpp @@ -224,6 +224,7 @@ ConstString KEY_AUTO_RESIZE_TERMINAL = "Auto resize terminal"; ConstString KEY_BACKGROUND_COLOR = "Background color"; ConstString KEY_CHARACTER_ENCODING = "Character encoding"; ConstString KEY_CHECK_FOR_UPDATE = "Check for update"; +ConstString KEY_UI_FONT_SCALE = "UI Font Scale"; ConstString KEY_CLEAR_INPUT_ON_ENTER = "Clear input on enter"; ConstString KEY_COLUMNS = "Columns"; ConstString KEY_COMMAND_PREFIX_CHAR = "Command prefix character"; @@ -267,6 +268,7 @@ ConstString KEY_LINES_OF_PEEK_PREVIEW = "Lines of peek preview"; ConstString KEY_LINES_OF_SCROLLBACK = "Lines of scrollback"; ConstString KEY_PROXY_LOCAL_PORT = "Local port number"; ConstString KEY_MAP_MODE = "Map Mode"; +ConstString KEY_GAME_CLIENT = "Game Client"; ConstString KEY_MUSIC_VOLUME = "Music volume"; ConstString KEY_SOUND_VOLUME = "Sound volume"; ConstString KEY_AUDIO_OUTPUT_DEVICE = "Audio output device"; @@ -275,6 +277,7 @@ ConstString KEY_MAXIMUM_NUMBER_OF_PATHS = "maximum number of paths"; ConstString KEY_MULTIPLE_CONNECTIONS_PENALTY = "multiple connections penalty"; ConstString KEY_MUME_START_EPOCH = "Mume start epoch"; ConstString KEY_NUMBER_OF_ANTI_ALIASING_SAMPLES = "Number of anti-aliasing samples"; +ConstString KEY_RENDER_SCALE = "Render scale percentage"; ConstString KEY_PROXY_CONNECTION_STATUS = "Proxy connection status"; ConstString KEY_PROXY_LISTENS_ON_ANY_INTERFACE = "Proxy listens on any interface"; ConstString KEY_RELATIVE_PATH_ACCEPTANCE = "relative path acceptance"; @@ -304,6 +307,7 @@ ConstString KEY_WEATHER_PRECIPITATION_INTENSITY = "weather.precipitationIntensit ConstString KEY_WEATHER_TIME_OF_DAY_INTENSITY = "weather.todIntensity"; ConstString KEY_WINDOW_GEOMETRY = "Window Geometry"; ConstString KEY_WINDOW_STATE = "Window State"; +ConstString KEY_WINDOW_STATE_COMPACT = "Window State Compact"; ConstString KEY_BELL_AUDIBLE = "Bell audible"; ConstString KEY_BELL_VISUAL = "Bell visual"; ConstString KEY_USE_COMMAND_SEPARATOR = "Use command separator"; @@ -422,6 +426,28 @@ NODISCARD static MapModeEnum sanitizeMapMode(const uint32_t input) return MapModeEnum::PLAY; } +NODISCARD static bool isValidGameClient(const GameClientEnum client) +{ + switch (client) { + case GameClientEnum::ASK: + case GameClientEnum::BUILT_IN: + case GameClientEnum::EXTERNAL: + return true; + } + return false; +} + +NODISCARD static GameClientEnum sanitizeGameClient(const uint32_t input) +{ + const auto client = static_cast(input); + if (isValidGameClient(client)) { + return client; + } + + qWarning() << "invalid GameClient:" << input; + return GameClientEnum::ASK; +} + NODISCARD static ThemeEnum sanitizeTheme(const uint32_t input) { const auto theme = static_cast(input); @@ -596,13 +622,20 @@ void Configuration::GeneralSettings::read(const QSettings &conf) */ windowGeometry = conf.value(KEY_WINDOW_GEOMETRY).toByteArray(); windowState = conf.value(KEY_WINDOW_STATE).toByteArray(); + windowStateCompact = conf.value(KEY_WINDOW_STATE_COMPACT).toByteArray(); alwaysOnTop = conf.value(KEY_ALWAYS_ON_TOP, false).toBool(); showStatusBar = conf.value(KEY_SHOW_STATUS_BAR, true).toBool(); showScrollBars = conf.value(KEY_SHOW_SCROLL_BARS, true).toBool(); showMenuBar = conf.value(KEY_SHOW_MENU_BAR, true).toBool(); mapMode = sanitizeMapMode( conf.value(KEY_MAP_MODE, static_cast(MapModeEnum::PLAY)).toUInt()); + gameClient = (CURRENT_PLATFORM == PlatformEnum::Wasm) + ? GameClientEnum::BUILT_IN + : sanitizeGameClient( + conf.value(KEY_GAME_CLIENT, static_cast(GameClientEnum::ASK)) + .toUInt()); checkForUpdate = conf.value(KEY_CHECK_FOR_UPDATE, true).toBool(); + uiFontScale = std::clamp(conf.value(KEY_UI_FONT_SCALE, 1.0).toDouble(), 0.5, 3.0); characterEncoding = sanitizeCharacterEncoding( conf.value(KEY_CHARACTER_ENCODING, static_cast(CharacterEncodingEnum::LATIN1)) .toUInt()); @@ -663,6 +696,7 @@ void Configuration::CanvasSettings::read(const QSettings &conf) roomDarkColor = lookupColor(KEY_ROOM_DARK_COLOR, DEFAULT_DARK_COLOR); roomDarkLitColor = lookupColor(KEY_ROOM_DARK_LIT_COLOR, DEFAULT_NO_SUNDEATH_COLOR); antialiasingSamples.set(conf.value(KEY_NUMBER_OF_ANTI_ALIASING_SAMPLES, 0).toInt()); + renderScale.set(std::clamp(conf.value(KEY_RENDER_SCALE, 100).toInt(), 25, 100)); trilinearFiltering.set(conf.value(KEY_USE_TRILINEAR_FILTERING, true).toBool()); advanced.use3D.set(conf.value(KEY_3D_CANVAS, false).toBool()); advanced.autoTilt.set(conf.value(KEY_3D_AUTO_TILT, true).toBool()); @@ -782,8 +816,8 @@ void Configuration::AudioSettings::read(const QSettings &conf) m_unlocked = (CURRENT_PLATFORM == PlatformEnum::Wasm) ? false : conf.value(KEY_AUDIO_UNLOCKED, false).toBool(); - m_musicVolume = std::clamp(conf.value(KEY_MUSIC_VOLUME, 50).toInt(), 0, 100); - m_soundVolume = std::clamp(conf.value(KEY_SOUND_VOLUME, 50).toInt(), 0, 100); + m_musicVolume = std::clamp(conf.value(KEY_MUSIC_VOLUME, 0).toInt(), 0, 100); + m_soundVolume = std::clamp(conf.value(KEY_SOUND_VOLUME, 0).toInt(), 0, 100); m_outputDeviceId = conf.value(KEY_AUDIO_OUTPUT_DEVICE).toByteArray(); } @@ -832,12 +866,15 @@ void Configuration::GeneralSettings::write(QSettings &conf) const conf.setValue(KEY_RUN_FIRST_TIME, false); conf.setValue(KEY_WINDOW_GEOMETRY, windowGeometry); conf.setValue(KEY_WINDOW_STATE, windowState); + conf.setValue(KEY_WINDOW_STATE_COMPACT, windowStateCompact); conf.setValue(KEY_ALWAYS_ON_TOP, alwaysOnTop); conf.setValue(KEY_SHOW_STATUS_BAR, showStatusBar); conf.setValue(KEY_SHOW_SCROLL_BARS, showScrollBars); conf.setValue(KEY_SHOW_MENU_BAR, showMenuBar); conf.setValue(KEY_MAP_MODE, static_cast(mapMode)); + conf.setValue(KEY_GAME_CLIENT, static_cast(gameClient)); conf.setValue(KEY_CHECK_FOR_UPDATE, checkForUpdate); + conf.setValue(KEY_UI_FONT_SCALE, uiFontScale); conf.setValue(KEY_CHARACTER_ENCODING, static_cast(characterEncoding)); conf.setValue(KEY_THEME, static_cast(m_theme)); } @@ -870,6 +907,7 @@ void Configuration::CanvasSettings::write(QSettings &conf) const conf.setValue(KEY_ROOM_DARK_LIT_COLOR, getQColorName(roomDarkLitColor)); conf.setValue(KEY_CONNECTION_NORMAL_COLOR, getQColorName(connectionNormalColor)); conf.setValue(KEY_NUMBER_OF_ANTI_ALIASING_SAMPLES, antialiasingSamples.get()); + conf.setValue(KEY_RENDER_SCALE, renderScale.get()); conf.setValue(KEY_USE_TRILINEAR_FILTERING, trilinearFiltering.get()); conf.setValue(KEY_3D_CANVAS, advanced.use3D.get()); conf.setValue(KEY_3D_AUTO_TILT, advanced.autoTilt.get()); diff --git a/src/configuration/configuration.h b/src/configuration/configuration.h index 6f174fd0a..e2fa18c8a 100644 --- a/src/configuration/configuration.h +++ b/src/configuration/configuration.h @@ -76,12 +76,20 @@ class NODISCARD Configuration final bool firstRun = false; QByteArray windowGeometry; QByteArray windowState; + // Dock/toolbar state used while the window is in the compact layout + // (see MainWindow::setCompactLayout()); kept apart from + // windowState so the two layouts never overwrite each other. + QByteArray windowStateCompact; bool alwaysOnTop = false; bool showStatusBar = true; bool showScrollBars = true; bool showMenuBar = true; MapModeEnum mapMode = MapModeEnum::PLAY; + GameClientEnum gameClient = GameClientEnum::ASK; bool checkForUpdate = true; + // Global multiplier applied to the application's default font point + // size at startup; 1.0 = unchanged (byte-for-byte no-op). + double uiFontScale = 1.0; CharacterEncodingEnum characterEncoding = CharacterEncodingEnum::LATIN1; private: @@ -166,6 +174,10 @@ class NODISCARD Configuration final struct NODISCARD CanvasSettings final : public CanvasNamedColorOptions { NamedConfig antialiasingSamples{"ANTIALIASING_SAMPLES", 0}; + // Percentage of the display resolution the map is rendered at; below + // 100 the offscreen framebuffer shrinks accordingly (see + // Legacy::Functions::setRenderScale()). + NamedConfig renderScale{"RENDER_SCALE", 100}; NamedConfig trilinearFiltering{"TRILINEAR_FILTERING", true}; NamedConfig showMissingMapId{"SHOW_MISSING_MAPID", false}; NamedConfig showUnsavedChanges{"SHOW_UNSAVED_CHANGES", false}; @@ -351,10 +363,14 @@ class NODISCARD Configuration final struct NODISCARD AudioSettings final { + public: + // The level a channel gets when it is turned on from 0. + static constexpr int DEFAULT_VOLUME = 50; + private: ChangeMonitor m_changeMonitor; - int m_musicVolume = 50; - int m_soundVolume = 50; + int m_musicVolume = 0; + int m_soundVolume = 0; QByteArray m_outputDeviceId; bool m_unlocked = false; diff --git a/src/display/AudioHintWidget.cpp b/src/display/AudioHintWidget.cpp deleted file mode 100644 index ef848c22b..000000000 --- a/src/display/AudioHintWidget.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -// Copyright (C) 2026 The MMapper Authors - -#include "AudioHintWidget.h" - -#include "../configuration/configuration.h" - -#include -#include -#include -#include -#include -#include - -AudioHintWidget::AudioHintWidget(QWidget *const parent) - : QWidget(parent) -{ - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - - QHBoxLayout *layout = new QHBoxLayout(this); - layout->setContentsMargins(10, 4, 10, 4); - layout->setSpacing(8); - - m_iconLabel = new QLabel(this); - m_iconLabel->setPixmap(QIcon(":/icons/audiocfg.png").pixmap(16, 16)); - layout->addWidget(m_iconLabel); - - m_textLabel = new QLabel(tr("Enable game audio?"), this); - layout->addWidget(m_textLabel); - - m_yesButton = new QPushButton(tr("Yes"), this); - - m_noButton = new QPushButton(tr("No"), this); - - layout->addWidget(m_yesButton); - layout->addWidget(m_noButton); - layout->addStretch(); - - connect(m_yesButton, &QPushButton::clicked, this, [this]() { - setConfig().audio.setUnlocked(); - hide(); - }); - - connect(m_noButton, &QPushButton::clicked, this, [this]() { - // Set volumes to 0 if they choose "No" - auto &settings = setConfig().audio; - settings.setMusicVolume(0); - settings.setSoundVolume(0); - hide(); - }); - - auto updateAudioHint = [this]() { - auto &cfg = getConfig().audio; - setVisible(!NO_AUDIO && !cfg.isUnlocked() - && (cfg.getMusicVolume() > 0 || cfg.getSoundVolume() > 0)); - }; - - updateAudioHint(); - setConfig().audio.registerChangeCallback(m_lifetime, updateAudioHint); -} - -AudioHintWidget::~AudioHintWidget() = default; diff --git a/src/display/AudioHintWidget.h b/src/display/AudioHintWidget.h deleted file mode 100644 index 97a9d5d08..000000000 --- a/src/display/AudioHintWidget.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -// SPDX-License-Identifier: GPL-2.0-or-later -// Copyright (C) 2026 The MMapper Authors - -#include "../global/Signal2.h" -#include "../global/macros.h" - -#include -#include - -class QPushButton; -class QLabel; - -class NODISCARD_QOBJECT AudioHintWidget final : public QWidget -{ - Q_OBJECT - -public: - explicit AudioHintWidget(QWidget *parent = nullptr); - ~AudioHintWidget() override; - -private: - QLabel *m_iconLabel; - QLabel *m_textLabel; - QPushButton *m_yesButton; - QPushButton *m_noButton; - Signal2Lifetime m_lifetime; -}; diff --git a/src/display/Filenames.cpp b/src/display/Filenames.cpp index 30bab7d72..ff75913e3 100644 --- a/src/display/Filenames.cpp +++ b/src/display/Filenames.cpp @@ -122,6 +122,26 @@ QString getAssetsPath() } } + // Dev-tree fallback: in developer builds the binary lives under + // /src/ (or, on macOS, inside a .app bundle within /src/) + // while the sideloaded assets directory sits at the build root + // (/assets). None of the packaged-layout checks above find it, + // so walk up a few parent directories looking for a real assets + // layout (not just an empty "assets" folder, which could false-positive). + { + QDir devDir(appDir); + for (int i = 0; i < 5; ++i) { + if (devDir.exists(assetsDirName + "/areas") + || devDir.exists(assetsDirName + "/rooms") + || devDir.exists(assetsDirName + "/sounds")) { + return devDir.absoluteFilePath(assetsDirName) + "/"; + } + if (!devDir.cdUp()) { + break; + } + } + } + // Fallback: check next to the binary if (appDir.exists(assetsDirName)) { return appDir.absoluteFilePath(assetsDirName) + "/"; diff --git a/src/display/FrameManager.cpp b/src/display/FrameManager.cpp index 7c1733b3c..1b4582e26 100644 --- a/src/display/FrameManager.cpp +++ b/src/display/FrameManager.cpp @@ -6,12 +6,13 @@ #include "../configuration/configuration.h" #include +#include -#include - -FrameManager::FrameManager(QOpenGLWindow &window, Legacy::UboManager &uboManager, QObject *parent) +FrameManager::FrameManager(RequestUpdateCallback requestUpdate, + Legacy::UboManager &uboManager, + QObject *parent) : QObject(parent) - , m_window(window) + , m_requestUpdate(std::move(requestUpdate)) , m_uboManager(uboManager) { m_uboManager.registerRebuildFunction(Legacy::SharedVboEnum::TimeBlock, @@ -152,7 +153,7 @@ void FrameManager::onHeartbeat() return; } - m_window.update(); + m_requestUpdate(); if (needsHeartbeat()) { requestFrame(); @@ -189,7 +190,7 @@ void FrameManager::requestFrame() if (m_heartbeatTimer.isActive()) { m_heartbeatTimer.stop(); } - m_window.update(); + m_requestUpdate(); // Start a fallback timer in case window update is ignored. if (needsHeartbeat()) { const int delayMs = static_cast( diff --git a/src/display/FrameManager.h b/src/display/FrameManager.h index b318db3f8..f95776dc7 100644 --- a/src/display/FrameManager.h +++ b/src/display/FrameManager.h @@ -16,8 +16,6 @@ #include #include -class QOpenGLWindow; - /** * @brief Manages the application's frame-rate and animation lifecycle. * @@ -47,6 +45,12 @@ class FrameManager final : public QObject */ using AnimationCallback = std::function; + /** + * @brief Callback invoked whenever the manager wants the host to schedule + * a repaint (e.g. QOpenGLWindow::update()). + */ + using RequestUpdateCallback = std::function; + private: struct Entry { @@ -59,7 +63,7 @@ class FrameManager final : public QObject std::chrono::nanoseconds m_minFrameTime{0}; Signal2Lifetime m_configLifetime; QTimer m_heartbeatTimer; - QOpenGLWindow &m_window; + RequestUpdateCallback m_requestUpdate; bool m_dirty = true; float m_elapsedTime = 0.0f; Legacy::UboManager &m_uboManager; @@ -87,7 +91,7 @@ class FrameManager final : public QObject }; public: - explicit FrameManager(QOpenGLWindow &window, + explicit FrameManager(RequestUpdateCallback requestUpdate, Legacy::UboManager &uboManager, QObject *parent = nullptr); ~FrameManager() override; diff --git a/src/display/MapCanvasConfig.h b/src/display/MapCanvasConfig.h index 2973a630c..1a9530e68 100644 --- a/src/display/MapCanvasConfig.h +++ b/src/display/MapCanvasConfig.h @@ -6,6 +6,9 @@ namespace MapCanvasConfig { +// Scroll-bar units per world unit; shared by MapCanvas and MapScroller. +static constexpr const int SCROLL_SCALE = 64; + void registerChangeCallback(const ChangeMonitor::Lifetime &lifetime, ChangeMonitor::Function callback); diff --git a/src/display/MapCanvasData.h b/src/display/MapCanvasData.h index 9eeeec8ba..d8a19a919 100644 --- a/src/display/MapCanvasData.h +++ b/src/display/MapCanvasData.h @@ -25,7 +25,6 @@ #include #include -#include #include #include #include @@ -92,7 +91,12 @@ struct NODISCARD ScaleFactor final struct NODISCARD MapCanvasViewport { private: - QWindow &m_window; + // Cached geometry pushed in by the host (e.g. QOpenGLWindow). Never + // queried from a live window, so this type has no dependency on any + // particular host widget/window type. + int m_viewportWidth = 0; + int m_viewportHeight = 0; + qreal m_dpr = 1.0; protected: mutable int m_lastWidth = 0; @@ -117,9 +121,7 @@ struct NODISCARD MapCanvasViewport ViewportConfig m_viewportConfig; public: - explicit MapCanvasViewport(QWindow &window) - : m_window{window} - {} + explicit MapCanvasViewport() = default; virtual ~MapCanvasViewport(); @@ -127,8 +129,20 @@ struct NODISCARD MapCanvasViewport virtual void onViewProjDirty() const {} public: - NODISCARD auto width() const { return m_window.width(); } - NODISCARD auto height() const { return m_window.height(); } + // Called by the host whenever its size and/or device pixel ratio changes + // (e.g. resizeGL()/screenChanged() on a QOpenGLWindow host), and also + // refreshed once per paint so the cached values never go stale. + void setViewportSize(const int width, const int height, const qreal dpr) + { + m_viewportWidth = width; + m_viewportHeight = height; + m_dpr = dpr; + } + +public: + NODISCARD int width() const { return m_viewportWidth; } + NODISCARD int height() const { return m_viewportHeight; } + NODISCARD qreal getDevicePixelRatio() const { return m_dpr; } public: NODISCARD glm::vec2 getScroll() const { return m_scroll; } @@ -176,7 +190,7 @@ struct NODISCARD MapCanvasViewport NODISCARD const glm::mat4 &getViewProj() const; NODISCARD Viewport getViewport() const { - return Viewport{glm::ivec2{0, 0}, glm::ivec2{m_window.width(), m_window.height()}}; + return Viewport{glm::ivec2{0, 0}, glm::ivec2{m_viewportWidth, m_viewportHeight}}; } NODISCARD float getTotalScaleFactor() const { return m_scaleFactor.getTotal(); } @@ -239,6 +253,9 @@ struct NODISCARD PinchState { float initialDistance = 0.f; float lastFactor = 1.f; + // Midpoint of the two touch points at the previous update, in the + // {x, height()-y} space getMouseCoords() uses; drives two-finger panning. + std::optional lastCentroid; }; struct NODISCARD MagnificationState diff --git a/src/display/MapCanvasWindow.cpp b/src/display/MapCanvasWindow.cpp new file mode 100644 index 000000000..0db65b85b --- /dev/null +++ b/src/display/MapCanvasWindow.cpp @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Ulf Hermann (Alve) +// Author: Marek Krejza (Caligor) +// Author: Nils Schimmelmann (Jahara) + +#include "MapCanvasWindow.h" + +#include "../global/ConfigConsts-Computed.h" +#include "../global/utils.h" +#include "../global/window_utils.h" +#include "InfomarkSelection.h" +#include "connectionselection.h" + +#include +#include +#include +#include + +using NonOwningPointer = MapCanvasWindow *; +NODISCARD static NonOwningPointer &primaryMapCanvas() +{ + static NonOwningPointer primary = nullptr; + return primary; +} + +MapCanvasWindow::MapCanvasWindow(MapData &mapData, + GameObserver &observer, + PrespammedPath &prespammedPath, + Mmapper2Group &groupManager, + QWindow *const parent) + : QOpenGLWindow{NoPartialUpdate, parent} + , m_core{mapData, observer, prespammedPath, groupManager, static_cast(*this)} +{ + // Forward the core's public signal surface as our own, so that callers + // (MainWindow, MapWindow, ...) can connect to `MapCanvasWindow::sig_*` + // without knowing MapCanvas exists. + connect(&m_core, &MapCanvas::sig_onCenter, this, &MapCanvasWindow::sig_onCenter); + connect(&m_core, &MapCanvas::sig_mapMove, this, &MapCanvasWindow::sig_mapMove); + connect(&m_core, &MapCanvas::sig_setScrollBars, this, &MapCanvasWindow::sig_setScrollBars); + connect(&m_core, &MapCanvas::sig_continuousScroll, this, &MapCanvasWindow::sig_continuousScroll); + connect(&m_core, &MapCanvas::sig_log, this, &MapCanvasWindow::sig_log); + connect(&m_core, &MapCanvas::sig_selectionChanged, this, &MapCanvasWindow::sig_selectionChanged); + connect(&m_core, &MapCanvas::sig_newRoomSelection, this, &MapCanvasWindow::sig_newRoomSelection); + connect(&m_core, + &MapCanvas::sig_newConnectionSelection, + this, + &MapCanvasWindow::sig_newConnectionSelection); + connect(&m_core, + &MapCanvas::sig_newInfomarkSelection, + this, + &MapCanvasWindow::sig_newInfomarkSelection); + connect(&m_core, &MapCanvas::sig_setCurrentRoom, this, &MapCanvasWindow::sig_setCurrentRoom); + connect(&m_core, &MapCanvas::sig_zoomChanged, this, &MapCanvasWindow::sig_zoomChanged); + connect(&m_core, &MapCanvas::sig_showTooltip, this, &MapCanvasWindow::sig_showTooltip); + connect(&m_core, + &MapCanvas::sig_customContextMenuRequested, + this, + &MapCanvasWindow::sig_customContextMenuRequested); + connect(&m_core, + &MapCanvas::sig_dismissContextMenu, + this, + &MapCanvasWindow::sig_dismissContextMenu); + + // The core stays QtWidgets-free; these two connections are where the + // widget-specific UX (message boxes, hiding the window, aborting) lives. + connect(&m_core, + &MapCanvas::sig_glInitFailed, + this, + &MapCanvasWindow::handleGlInitFailed, + Qt::DirectConnection); + connect(&m_core, + &MapCanvas::sig_glFatalError, + this, + &MapCanvasWindow::handleGlFatalError, + Qt::DirectConnection); + + NonOwningPointer &pmc = primaryMapCanvas(); + if (pmc == nullptr) { + pmc = this; + } +} + +MapCanvasWindow::~MapCanvasWindow() +{ + NonOwningPointer &pmc = primaryMapCanvas(); + if (pmc == this) { + pmc = nullptr; + } +} + +MapCanvasWindow *MapCanvasWindow::getPrimary() +{ + return primaryMapCanvas(); +} + +void MapCanvasWindow::handleGlInitFailed(const QString &reason) +{ + qWarning() << "OpenGL initialization failed:" << reason; + hide(); + doneCurrent(); + mmqt::showCritical(QApplication::activeWindow(), + "Unable to initialize OpenGL", + "Upgrade your video card drivers"); + if constexpr (CURRENT_PLATFORM == PlatformEnum::Windows) { + // Link to Microsoft OpenGL Compatibility Pack + QDesktopServices::openUrl( + QUrl(QStringLiteral("ms-windows-store://pdp/?productid=9nqpsl29bfff"))); + } +} + +void MapCanvasWindow::handleGlFatalError(const QString &message) +{ + QMessageBox box; + box.setWindowTitle("Fatal OpenGL error"); + box.setText(message); + box.exec(); + + std::abort(); +} diff --git a/src/display/MapCanvasWindow.h b/src/display/MapCanvasWindow.h new file mode 100644 index 000000000..9f21681e7 --- /dev/null +++ b/src/display/MapCanvasWindow.h @@ -0,0 +1,187 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Ulf Hermann (Alve) +// Author: Marek Krejza (Caligor) +// Author: Nils Schimmelmann (Jahara) + +// MapCanvasWindow is a thin QOpenGLWindow shell around MapCanvas, which holds +// all of the GL/paint/input/signal machinery. MapCanvas itself has no +// dependency on QOpenGLWindow or QtWidgets. +// +// MapCanvasWindow re-exposes MapCanvas's public signal/slot surface by +// forwarding (rather than by exposing a getCore() accessor) so that callers +// (MainWindow, MapWindow, ...) can connect directly to +// `MapCanvasWindow::sig_*`/`MapCanvasWindow::slot_*`. + +#include "../global/Signal2.h" +#include "../map/PromptFlags.h" +#include "../mapdata/roomselection.h" +#include "CanvasMouseModeEnum.h" +#include "mapcanvas.h" + +#include + +#include +#include +#include + +class ConnectionSelection; +class Coordinate; +class GameObserver; +class InfomarkSelection; +class MapData; +class Mmapper2Group; +class PrespammedPath; +class QMouseEvent; +class QNativeGestureEvent; +class QTouchEvent; +class QWheelEvent; + +class NODISCARD_QOBJECT MapCanvasWindow final : public QOpenGLWindow, private MapCanvasHost +{ + Q_OBJECT + +public: + static constexpr const int SCROLL_SCALE = MapCanvas::SCROLL_SCALE; + +private: + MapCanvas m_core; + +public: + explicit MapCanvasWindow(MapData &mapData, + GameObserver &observer, + PrespammedPath &prespammedPath, + Mmapper2Group &groupManager, + QWindow *parent = nullptr); + ~MapCanvasWindow() final; + +public: + NODISCARD static MapCanvasWindow *getPrimary(); + +private: + // MapCanvasHost + void virt_requestCanvasUpdate() final { update(); } + NODISCARD qreal virt_hostDevicePixelRatio() const final { return devicePixelRatioF(); } + NODISCARD QSize virt_hostSize() const final + { + return QSize(QOpenGLWindow::width(), QOpenGLWindow::height()); + } + void virt_setHostCursor(const Qt::CursorShape shape) final { QOpenGLWindow::setCursor(shape); } + +private: + void cleanupOpenGL(); + +private slots: + // Widget-facing reactions to MapCanvas's Qt-widgets-free failure + // signals; see the comments on sig_glInitFailed/sig_glFatalError in + // mapcanvas.h. + void handleGlInitFailed(const QString &reason); + void handleGlFatalError(const QString &message); + +public: + void shuttingDown(); + +public: + void setZoom(float zoom) { m_core.setZoom(zoom); } + NODISCARD float getRawZoom() const { return m_core.getRawZoom(); } + NODISCARD float getTotalScaleFactor() const { return m_core.getTotalScaleFactor(); } + + // Exposes the Qt-widgets-free core directly: ConnectionListener/Proxy + // (see ../proxy/connectionlistener.h/proxy.h) only ever call methods + // MapCanvas already implements natively (slot_mapChanged()/ + // graphicsSettingsChanged()/slot_setRoomSelection()), so they take a + // MapCanvas& instead of a MapCanvasWindow&. + NODISCARD MapCanvas &getCore() { return m_core; } + +public: + NODISCARD auto width() const { return QOpenGLWindow::width(); } + NODISCARD auto height() const { return QOpenGLWindow::height(); } + NODISCARD QRect rect() const { return QRect(0, 0, width(), height()); } + +protected: + void initializeGL() override; + void paintGL() override { m_core.hostPaintGL(); } + void resizeGL(int width, int height) override + { + m_core.hostResize(width, height, devicePixelRatioF()); + } + void mousePressEvent(QMouseEvent *event) override { m_core.handleMousePress(event); } + void mouseReleaseEvent(QMouseEvent *event) override { m_core.handleMouseRelease(event); } + void mouseMoveEvent(QMouseEvent *event) override { m_core.handleMouseMove(event); } + void wheelEvent(QWheelEvent *event) override { m_core.handleWheel(event); } + void touchEvent(QTouchEvent *event) override { m_core.handleTouch(event); } + bool event(QEvent *e) override + { + if (m_core.handleGenericEvent(e)) { + return true; + } + return QOpenGLWindow::event(e); + } + +public: + void userPressedEscape(bool pressed) { m_core.userPressedEscape(pressed); } + void screenChanged() { m_core.screenChanged(); } + void graphicsSettingsChanged() { m_core.graphicsSettingsChanged(); } + +signals: + void sig_onCenter(glm::vec2 worldCoord); + void sig_mapMove(int dx, int dy); + void sig_setScrollBars(Coordinate min, Coordinate max); + void sig_continuousScroll(int, int); + + void sig_log(const QString &, const QString &); + + void sig_selectionChanged(); + void sig_newRoomSelection(const SigRoomSelection &); + void sig_newConnectionSelection(ConnectionSelection *); + void sig_newInfomarkSelection(InfomarkSelection *); + + void sig_setCurrentRoom(RoomId id, bool update); + void sig_zoomChanged(float); + + void sig_showTooltip(const QString &text, const QPoint &pos); + void sig_customContextMenuRequested(const QPoint &pos); + void sig_dismissContextMenu(); + +public slots: + void slot_onForcedPositionChange() { m_core.slot_onForcedPositionChange(); } + void slot_createRoom() { m_core.slot_createRoom(); } + + void slot_setCanvasMouseMode(CanvasMouseModeEnum mode) { m_core.slot_setCanvasMouseMode(mode); } + + void slot_setScroll(const glm::vec2 worldPos) { m_core.slot_setScroll(worldPos); } + void slot_setHorizontalScroll(float worldX) { m_core.slot_setHorizontalScroll(worldX); } + void slot_setVerticalScroll(float worldY) { m_core.slot_setVerticalScroll(worldY); } + + void slot_zoomIn() { m_core.slot_zoomIn(); } + void slot_zoomOut() { m_core.slot_zoomOut(); } + void slot_zoomReset() { m_core.slot_zoomReset(); } + void slot_centerOnPlayer() { m_core.slot_centerOnPlayer(); } + + void slot_layerUp() { m_core.slot_layerUp(); } + void slot_layerDown() { m_core.slot_layerDown(); } + void slot_layerReset() { m_core.slot_layerReset(); } + + void slot_setRoomSelection(const SigRoomSelection &sel) { m_core.slot_setRoomSelection(sel); } + void slot_setConnectionSelection(const std::shared_ptr &sel) + { + m_core.slot_setConnectionSelection(sel); + } + void slot_setInfomarkSelection(const std::shared_ptr &sel) + { + m_core.slot_setInfomarkSelection(sel); + } + + void slot_clearRoomSelection() { m_core.slot_clearRoomSelection(); } + void slot_clearConnectionSelection() { m_core.slot_clearConnectionSelection(); } + void slot_clearInfomarkSelection() { m_core.slot_clearInfomarkSelection(); } + void slot_clearAllSelections() { m_core.slot_clearAllSelections(); } + + void slot_dataLoaded() { m_core.slot_dataLoaded(); } + void slot_moveMarker(RoomId id) { m_core.slot_moveMarker(id); } + + void slot_rebuildMeshes() { m_core.slot_rebuildMeshes(); } + void slot_mapChanged() { m_core.slot_mapChanged(); } + void slot_requestUpdate() { m_core.slot_requestUpdate(); } +}; diff --git a/src/display/MapCanvasWindow_gl.cpp b/src/display/MapCanvasWindow_gl.cpp new file mode 100644 index 000000000..020ee2746 --- /dev/null +++ b/src/display/MapCanvasWindow_gl.cpp @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors + +#include "../global/RuleOf5.h" +#include "../global/logging.h" +#include "MapCanvasWindow.h" + +#include + +class NODISCARD MakeCurrentRaii final +{ +private: + QOpenGLWindow &m_glWindow; + +public: + explicit MakeCurrentRaii(QOpenGLWindow &window) + : m_glWindow{window} + { + m_glWindow.makeCurrent(); + } + ~MakeCurrentRaii() { m_glWindow.doneCurrent(); } + + DELETE_CTORS_AND_ASSIGN_OPS(MakeCurrentRaii); +}; + +void MapCanvasWindow::shuttingDown() +{ + qInfo() << MM_SOURCE_LOCATION().function_name(); + if (!m_core.isCleanedUp()) { + cleanupOpenGL(); + } +} + +void MapCanvasWindow::cleanupOpenGL() +{ + // Make sure the context is current and then explicitly destroy all + // underlying OpenGL resources. hostCleanupGL() requires a current + // context; only the host (us) knows how to make one current. + MakeCurrentRaii makeCurrentRaii{*this}; + m_core.hostCleanupGL(); +} + +void MapCanvasWindow::initializeGL() +{ + if (!m_core.hostInitializeGL()) { + // Failure was already handled synchronously by handleGlInitFailed() + // (connected to MapCanvas::sig_glInitFailed with a direct + // connection in the constructor). + return; + } + + // Clean up GL resources while the context is still current. + // The destructor is too late — Qt destroys the context before ~MapCanvasWindow() runs. + connect(context(), + &QOpenGLContext::aboutToBeDestroyed, + this, + &MapCanvasWindow::cleanupOpenGL, + Qt::DirectConnection); +} diff --git a/src/display/MapScroller.cpp b/src/display/MapScroller.cpp new file mode 100644 index 000000000..1931bc185 --- /dev/null +++ b/src/display/MapScroller.cpp @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "MapScroller.h" + +#include + +#include + +MapScroller::MapScroller(QObject *const parent) + : QObject(parent) +{ + m_scrollTimer = new QTimer(this); + connect(m_scrollTimer, &QTimer::timeout, this, &MapScroller::slot_scrollTimerTimeout); +} + +MapScroller::~MapScroller() = default; + +void MapScroller::slot_setScrollBars(const Coordinate min, const Coordinate max) +{ + m_knownMapSize.min = min.to_ivec3(); + m_knownMapSize.max = max.to_ivec3(); + + const auto dims = m_knownMapSize.size() * MapCanvasConfig::SCROLL_SCALE; + m_horizontalScrollMax = dims.x; + m_verticalScrollMax = dims.y; +} + +// REVISIT: This looks more like "delayed jump" than "continuous scroll." +void MapScroller::slot_continuousScroll(const int hStep, const int input_vStep) +{ + const auto fitsInInt8 = [](int n) -> bool { + // alternate: test against std::numeric_limits::min and max. + return static_cast(static_cast(n)) == n; + }; + + // hStep/vStep must fit in an int8_t range. + assert(fitsInInt8(hStep)); + assert(fitsInInt8(input_vStep)); + + // Y is negated because delta is in world space + const int vStep = -input_vStep; + + m_horizontalScrollStep = hStep; + m_verticalScrollStep = vStep; + + auto &scrollTimer = *m_scrollTimer; + // stop + if (hStep == 0 && vStep == 0) { + if (scrollTimer.isActive()) { + scrollTimer.stop(); + } + } else { + // start + if (!scrollTimer.isActive()) { + scrollTimer.start(100); + } + } +} + +void MapScroller::slot_scrollTimerTimeout() +{ + emit sig_continuousScrollStep(m_horizontalScrollStep, m_verticalScrollStep); +} + +glm::vec2 MapScroller::KnownMapSize::scrollToWorld(const glm::ivec2 scrollPos) const +{ + auto worldPos = glm::vec2{scrollPos} / static_cast(MapCanvasConfig::SCROLL_SCALE); + worldPos.y = static_cast(size().y) - worldPos.y; // negate Y + worldPos += glm::vec2{min}; + return worldPos; +} + +glm::ivec2 MapScroller::KnownMapSize::worldToScroll(const glm::vec2 worldPos_in) const +{ + auto worldPos = worldPos_in; + worldPos -= glm::vec2{min}; + worldPos.y = static_cast(size().y) - worldPos.y; // negate Y + const glm::ivec2 scrollPos{worldPos * static_cast(MapCanvasConfig::SCROLL_SCALE)}; + return scrollPos; +} diff --git a/src/display/MapScroller.h b/src/display/MapScroller.h new file mode 100644 index 000000000..12aaf2d64 --- /dev/null +++ b/src/display/MapScroller.h @@ -0,0 +1,80 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +// MapScroller holds the map view's scroll math (world<->scroll-unit +// conversion, driven by the known map bounds) and its continuous-scroll +// timer. It owns no widgets, so it belongs in the unconditional display +// sources. +// +// MapWindow (see mapwindow.cpp) uses this for the math/timer, and keeps +// owning its QScrollBar widgets and the "read bar value, compute delta, +// write bar value" glue, since that part is inherently QWidget-specific. +#include "../global/macros.h" +#include "../map/coordinate.h" +#include "MapCanvasConfig.h" + +#include + +#include +#include + +class QTimer; + +class NODISCARD_QOBJECT MapScroller final : public QObject +{ + Q_OBJECT + +private: + // World<->scroll-unit conversion, driven by the known map bounds. + struct NODISCARD KnownMapSize final + { + glm::ivec3 min{0}; + glm::ivec3 max{0}; + + NODISCARD glm::ivec2 size() const { return glm::ivec2{max - min}; } + + NODISCARD glm::vec2 scrollToWorld(glm::ivec2 scrollPos) const; + NODISCARD glm::ivec2 worldToScroll(glm::vec2 worldPos) const; + } m_knownMapSize; + + QPointer m_scrollTimer; + int m_horizontalScrollStep = 0; + int m_verticalScrollStep = 0; + int m_horizontalScrollMax = 0; + int m_verticalScrollMax = 0; + +public: + explicit MapScroller(QObject *parent = nullptr); + ~MapScroller() final; + +public: + NODISCARD glm::vec2 scrollToWorld(glm::ivec2 scrollPos) const + { + return m_knownMapSize.scrollToWorld(scrollPos); + } + NODISCARD glm::ivec2 worldToScroll(glm::vec2 worldPos) const + { + return m_knownMapSize.worldToScroll(worldPos); + } + + NODISCARD int getHorizontalScrollMax() const { return m_horizontalScrollMax; } + NODISCARD int getVerticalScrollMax() const { return m_verticalScrollMax; } + +public slots: + // Stores the known map bounds and recomputes the scrollbar ranges (min + // is always 0). + void slot_setScrollBars(Coordinate min, Coordinate max); + + // Starts/stops a 100ms-interval timer while a non-zero step is active, + // and emits sig_continuousScrollStep() on every tick. + void slot_continuousScroll(int hStep, int vStep); + +signals: + // Emitted every 100ms while a continuous scroll is active (see + // slot_continuousScroll()). + void sig_continuousScrollStep(int hStep, int vStep); + +private slots: + void slot_scrollTimerTimeout(); +}; diff --git a/src/display/mapcanvas.cpp b/src/display/mapcanvas.cpp index e1b4ca3f5..34fdfe499 100644 --- a/src/display/mapcanvas.cpp +++ b/src/display/mapcanvas.cpp @@ -50,20 +50,28 @@ constexpr float GESTURE_EPSILON = 1e-6f; constexpr float PINCH_DISTANCE_THRESHOLD = 1e-3f; } // namespace -using NonOwningPointer = MapCanvas *; -NODISCARD static NonOwningPointer &primaryMapCanvas() -{ - static NonOwningPointer primary = nullptr; - return primary; -} +MapCanvasHost::~MapCanvasHost() = default; + +// Touch long-press duration; see handleMousePress(). +static constexpr int LONG_PRESS_MS = 600; + +// Touch flick (see handleMouseRelease()/onFlickTick()): samples older than +// this are ignored when measuring the release velocity; the view keeps +// moving at that velocity, scaled by FLICK_DECAY every tick, until it drops +// below FLICK_MIN_SPEED (world units per second). +static constexpr qint64 FLICK_SAMPLE_WINDOW_MS = 100; +static constexpr int FLICK_TICK_MS = 16; +static constexpr float FLICK_DECAY = 0.92f; +static constexpr float FLICK_MIN_SPEED = 0.5f; +static constexpr size_t FLICK_MAX_SAMPLES = 5; MapCanvas::MapCanvas(MapData &mapData, GameObserver &observer, PrespammedPath &prespammedPath, Mmapper2Group &groupManager, - QWindow *const parent) - : QOpenGLWindow{NoPartialUpdate, parent} - , MapCanvasViewport{static_cast(*this)} + MapCanvasHost &host) + : QObject{nullptr} + , MapCanvasViewport{} , MapCanvasInputState{prespammedPath} , m_mapScreen{static_cast(*this)} , m_observer{observer} @@ -71,35 +79,28 @@ MapCanvas::MapCanvas(MapData &mapData, , m_glFont{m_opengl} , m_data{mapData} , m_groupManager{groupManager} - , m_frameManager{static_cast(*this), m_opengl.getUboManager()} + , m_host{host} + , m_frameManager{[this]() { m_host.requestCanvasUpdate(); }, m_opengl.getUboManager()} , m_weather{m_opengl, m_data, m_textures, observer, m_frameManager} { syncViewportConfig(); + m_longPressTimer.setSingleShot(true); + m_longPressTimer.setInterval(LONG_PRESS_MS); + connect(&m_longPressTimer, &QTimer::timeout, this, &MapCanvas::onLongPress); + + m_flickTimer.setInterval(FLICK_TICK_MS); + connect(&m_flickTimer, &QTimer::timeout, this, &MapCanvas::onFlickTick); + m_frameManager.registerCallback(m_lifetime, [this]() { return m_batches.remeshCookie.isPending() ? FrameManager::AnimationStatusEnum::Continue : FrameManager::AnimationStatusEnum::Stop; }); - NonOwningPointer &pmc = primaryMapCanvas(); - if (pmc == nullptr) { - pmc = this; - } - - setCursor(Qt::OpenHandCursor); -} -MapCanvas::~MapCanvas() -{ - NonOwningPointer &pmc = primaryMapCanvas(); - if (pmc == this) { - pmc = nullptr; - } + applyCursor(Qt::OpenHandCursor); } -MapCanvas *MapCanvas::getPrimary() -{ - return primaryMapCanvas(); -} +MapCanvas::~MapCanvas() = default; void MapCanvas::slot_layerUp() { @@ -133,7 +134,7 @@ void MapCanvas::slot_setCanvasMouseMode(const CanvasMouseModeEnum mode) switch (mode) { case CanvasMouseModeEnum::MOVE: - setCursor(Qt::OpenHandCursor); + applyCursor(Qt::OpenHandCursor); break; default: @@ -141,7 +142,7 @@ void MapCanvas::slot_setCanvasMouseMode(const CanvasMouseModeEnum mode) case CanvasMouseModeEnum::RAYPICK_ROOMS: case CanvasMouseModeEnum::SELECT_CONNECTIONS: case CanvasMouseModeEnum::CREATE_INFOMARKS: - setCursor(Qt::CrossCursor); + applyCursor(Qt::CrossCursor); break; case CanvasMouseModeEnum::SELECT_ROOMS: @@ -149,7 +150,7 @@ void MapCanvas::slot_setCanvasMouseMode(const CanvasMouseModeEnum mode) case CanvasMouseModeEnum::CREATE_CONNECTIONS: case CanvasMouseModeEnum::CREATE_ONEWAY_CONNECTIONS: case CanvasMouseModeEnum::SELECT_INFOMARKS: - setCursor(Qt::ArrowCursor); + applyCursor(Qt::ArrowCursor); break; } @@ -213,8 +214,9 @@ NODISCARD static uint32_t operator&(const Qt::KeyboardModifiers left, const Qt:: return static_cast(left) & static_cast(right); } -void MapCanvas::wheelEvent(QWheelEvent *const event) +void MapCanvas::handleWheel(QWheelEvent *const event) { + stopFlick(); const bool hasCtrl = (event->modifiers() & Qt::CTRL) != 0u; switch (m_canvasMouseMode) { @@ -259,9 +261,10 @@ void MapCanvas::slot_onForcedPositionChange() slot_requestUpdate(); } -void MapCanvas::touchEvent(QTouchEvent *const event) +void MapCanvas::handleTouch(QTouchEvent *const event) { if (event->type() == QEvent::TouchBegin) { + stopFlick(); emit sig_dismissContextMenu(); } @@ -291,6 +294,28 @@ void MapCanvas::touchEvent(QTouchEvent *const event) updatePinch(currentPinchFactor); } + // Two-finger pan: move the view by however far the fingers' midpoint + // travelled since the last update (after the zoom above, so the map + // stays under the fingers). Same {x, height()-y} space as + // getMouseCoords(). + if (m_pinchState) { + const QPointF mid = (p1.position() + p2.position()) / 2.0; + const glm::vec2 centroid{static_cast(mid.x()), + static_cast(height() - mid.y())}; + if (m_pinchState->lastCentroid) { + const glm::vec2 prevWorld{unproject_clamped(*m_pinchState->lastCentroid)}; + const glm::vec2 currWorld{unproject_clamped(centroid)}; + const glm::vec2 delta = currWorld - prevWorld; + if (glm::length(delta) > GESTURE_EPSILON) { + const glm::vec2 newScroll = getScroll() - delta; + setScroll(newScroll); + emit sig_onCenter(newScroll); + m_frameManager.requestUpdate(); + } + } + m_pinchState->lastCentroid = centroid; + } + if (event->type() == QEvent::TouchEnd || p1.state() == QEventPoint::Released || p2.state() == QEventPoint::Released) { endPinch(); @@ -299,11 +324,13 @@ void MapCanvas::touchEvent(QTouchEvent *const event) } else { if (points.size() > 2) { // Explicitly ignore more than 2 touch points for pinch zoom. - qDebug() << "MapCanvas::touchEvent: ignoring" << points.size() << "touch points"; + qDebug() << "MapCanvas::handleTouch: ignoring" << points.size() << "touch points"; } endPinch(); - QOpenGLWindow::touchEvent(event); + // Mirrors QWindow::touchEvent()'s default behavior of leaving the + // event unhandled/ignored. + event->ignore(); } } @@ -316,39 +343,44 @@ void MapCanvas::handleZoomAtEvent(const QInputEvent *const event, const float de } } -bool MapCanvas::event(QEvent *const event) +bool MapCanvas::handleGenericEvent(QEvent *const event) { if (event->type() == QEvent::NativeGesture) { auto *const nativeEvent = static_cast(event); if (nativeEvent->gestureType() == Qt::ZoomNativeGesture) { - const auto value = static_cast(nativeEvent->value()); - float deltaFactor = 1.f; - if constexpr (CURRENT_PLATFORM == PlatformEnum::Mac) { - // On macOS, event->value() for ZoomNativeGesture is the magnification delta - // since the last event. - deltaFactor += value; - } else { - // On other platforms, it's typically the cumulative scale factor (1.0 at start). - if (nativeEvent->isBeginEvent() || !m_magnificationState) { - beginMagnification(); - } - - if (std::abs(m_magnificationState->lastValue) > GESTURE_EPSILON) { - deltaFactor = value / m_magnificationState->lastValue; - } - updateMagnification(value); - - if (nativeEvent->isEndEvent()) { - endMagnification(); - } - } - handleZoomAtEvent(nativeEvent, deltaFactor); - event->accept(); + handleNativeGesture(nativeEvent); return true; } } - return QOpenGLWindow::event(event); + return false; +} + +void MapCanvas::handleNativeGesture(QNativeGestureEvent *const nativeEvent) +{ + const auto value = static_cast(nativeEvent->value()); + float deltaFactor = 1.f; + if constexpr (CURRENT_PLATFORM == PlatformEnum::Mac) { + // On macOS, event->value() for ZoomNativeGesture is the magnification delta + // since the last event. + deltaFactor += value; + } else { + // On other platforms, it's typically the cumulative scale factor (1.0 at start). + if (nativeEvent->isBeginEvent() || !m_magnificationState) { + beginMagnification(); + } + + if (std::abs(m_magnificationState->lastValue) > GESTURE_EPSILON) { + deltaFactor = value / m_magnificationState->lastValue; + } + updateMagnification(value); + + if (nativeEvent->isEndEvent()) { + endMagnification(); + } + } + handleZoomAtEvent(nativeEvent, deltaFactor); + nativeEvent->accept(); } void MapCanvas::slot_createRoom() @@ -423,20 +455,143 @@ std::shared_ptr MapCanvas::getInfomarkSelection(const MouseSe return InfomarkSelection::alloc(m_data, lo, hi); } -void MapCanvas::mousePressEvent(QMouseEvent *const event) +void MapCanvas::requestContextMenuAt(const QPointF &pos) +{ + // getMouseCoords() derives its glm coordinate from a QMouseEvent as + // {x, height()-y} (see MapCanvasData.cpp); a touch long-press reaches + // here with no QMouseEvent, so reproduce that transform directly. This is + // the same selection + emit that the right-mouse-button branch of + // handleMousePress() performs. + const glm::vec2 xy{static_cast(pos.x()), static_cast(height() - pos.y())}; + if (m_canvasMouseMode == CanvasMouseModeEnum::MOVE) { + const auto worldPos = unproject_clamped(xy); + m_sel1 = m_sel2 = MouseSel{Coordinate2f{worldPos.x, worldPos.y}, getCurrentLayer()}; + } else { + m_sel1 = m_sel2 = getUnprojectedMouseSel(xy); + } + + if (m_canvasMouseMode == CanvasMouseModeEnum::MOVE && hasSel1()) { + // Select the room under the cursor + m_roomSelection = RoomSelection::createSelection( + m_data.findAllRooms(getSel1().getCoordinate())); + slot_setRoomSelection(SigRoomSelection{m_roomSelection}); + + // Select infomarks under the cursor. + slot_setInfomarkSelection(getInfomarkSelection(getSel1())); + + selectionChanged(); + } + emit sig_customContextMenuRequested(pos.toPoint()); +} + +void MapCanvas::cancelLongPress() +{ + m_longPressTimer.stop(); + m_longPressPos.reset(); +} + +void MapCanvas::onLongPress() +{ + if (!m_longPressPos) { + return; + } + const QPointF pos = *m_longPressPos; + m_longPressPos.reset(); + m_longPressFired = true; + + // Abandon whatever the synthesized left press started (a map drag, a + // rubber-band selection, ...): the menu takes the eventual release. + m_mouseLeftPressed = false; + endInteraction(); + emit sig_continuousScroll(0, 0); + if (m_canvasMouseMode == CanvasMouseModeEnum::MOVE) { + applyCursor(Qt::OpenHandCursor); + } + + requestContextMenuAt(pos); +} + +void MapCanvas::recordScrollSample(const qint64 msecs) +{ + m_scrollSamples.push_back(ScrollSample{msecs, getScroll()}); + while (m_scrollSamples.size() > FLICK_MAX_SAMPLES) { + m_scrollSamples.pop_front(); + } +} + +void MapCanvas::startFlick() +{ + if (m_scrollSamples.size() < 2) { + return; + } + const ScrollSample &last = m_scrollSamples.back(); + // Oldest sample still inside the window; the velocity is measured + // across it so a pause before lifting the finger yields no flick. + const ScrollSample *first = nullptr; + for (const ScrollSample &sample : m_scrollSamples) { + if (last.msecs - sample.msecs <= FLICK_SAMPLE_WINDOW_MS) { + first = &sample; + break; + } + } + if (first == nullptr || first == &last || last.msecs <= first->msecs) { + return; + } + const float seconds = static_cast(last.msecs - first->msecs) / 1000.f; + m_flickVelocity = (last.scroll - first->scroll) / seconds; + if (glm::length(m_flickVelocity) < FLICK_MIN_SPEED) { + m_flickVelocity = glm::vec2{0.f}; + return; + } + m_flickTimer.start(); +} + +void MapCanvas::stopFlick() +{ + m_flickTimer.stop(); + m_flickVelocity = glm::vec2{0.f}; +} + +void MapCanvas::onFlickTick() +{ + const float seconds = static_cast(FLICK_TICK_MS) / 1000.f; + const glm::vec2 newScroll = getScroll() + m_flickVelocity * seconds; + setScroll(newScroll); + emit sig_onCenter(newScroll); + m_frameManager.requestUpdate(); + + m_flickVelocity *= FLICK_DECAY; + if (glm::length(m_flickVelocity) < FLICK_MIN_SPEED) { + stopFlick(); + } +} + +void MapCanvas::handleMousePress(QMouseEvent *const event) { if (event->button() != Qt::RightButton) { emit sig_dismissContextMenu(); } + // Touch never synthesizes a right-click, so a held single-finger press + // (which Qt delivers here as a synthesized left press) opens the context + // menu instead; see onLongPress(). + cancelLongPress(); + m_longPressFired = false; + stopFlick(); + m_scrollSamples.clear(); + if (event->button() == Qt::LeftButton && event->source() != Qt::MouseEventNotSynthesized) { + m_longPressPos = event->position(); + m_longPressTimer.start(); + } + const bool hasLeftButton = (event->buttons() & Qt::LeftButton) != 0u; const bool hasRightButton = (event->buttons() & Qt::RightButton) != 0u; const bool hasCtrl = (event->modifiers() & Qt::CTRL) != 0u; MAYBE_UNUSED const bool hasAlt = (event->modifiers() & Qt::ALT) != 0u; if (hasLeftButton && hasAlt) { - beginAltDrag(event->position().toPoint(), cursor()); - setCursor(Qt::ClosedHandCursor); + beginAltDrag(event->position().toPoint(), currentCursor()); + applyCursor(Qt::ClosedHandCursor); event->accept(); return; } @@ -463,18 +618,7 @@ void MapCanvas::mousePressEvent(QMouseEvent *const event) slot_layerDown(); return event->accept(); } else if (!m_mouseLeftPressed && m_mouseRightPressed) { - if (m_canvasMouseMode == CanvasMouseModeEnum::MOVE && hasSel1()) { - // Select the room under the cursor - m_roomSelection = RoomSelection::createSelection( - m_data.findAllRooms(getSel1().getCoordinate())); - slot_setRoomSelection(SigRoomSelection{m_roomSelection}); - - // Select infomarks under the cursor. - slot_setInfomarkSelection(getInfomarkSelection(getSel1())); - - selectionChanged(); - } - emit sig_customContextMenuRequested(event->position().toPoint()); + requestContextMenuAt(event->position()); m_mouseRightPressed = false; event->accept(); return; @@ -499,7 +643,7 @@ void MapCanvas::mousePressEvent(QMouseEvent *const event) break; case CanvasMouseModeEnum::MOVE: if (hasLeftButton && hasSel1()) { - setCursor(Qt::ClosedHandCursor); + applyCursor(Qt::ClosedHandCursor); startMoving(m_sel1.value()); } break; @@ -553,10 +697,17 @@ void MapCanvas::mousePressEvent(QMouseEvent *const event) } // Select rooms if (hasLeftButton && hasSel1()) { - if (!hasCtrl) { - const auto pRoom = m_data.findRoomHandle(getSel1().getCoordinate()); - if (pRoom.exists() && m_roomSelection != nullptr - && m_roomSelection->contains(pRoom.getId())) { + const auto pRoom = m_data.findRoomHandle(getSel1().getCoordinate()); + const bool onSelectedRoom = pRoom.exists() && m_roomSelection != nullptr + && m_roomSelection->contains(pRoom.getId()); + // Touch has no Ctrl, so a tap on a room that is not yet selected + // adds it (and a drag from there rubber-bands additively), like + // Ctrl+click; a selected room still moves, and empty space still + // clears. Mouse input is unchanged. + const bool touch = event->source() != Qt::MouseEventNotSynthesized; + const bool additive = hasCtrl || (touch && pRoom.exists() && !onSelectedRoom); + if (!additive) { + if (onSelectedRoom) { beginRoomMove(); } else { endInteraction(); @@ -618,18 +769,18 @@ void MapCanvas::mousePressEvent(QMouseEvent *const event) } } -void MapCanvas::mouseMoveEvent(QMouseEvent *const event) +void MapCanvas::handleMouseMove(QMouseEvent *const event) { - const auto optXy = getMouseCoords(event); - if (!optXy) { - return; + if (m_longPressPos + && (event->position() - *m_longPressPos).manhattanLength() + > QGuiApplication::styleHints()->startDragDistance()) { + cancelLongPress(); } - const auto xy = *optXy; if (auto *const altDragState = getInteraction()) { // The user released the Alt key mid-drag. if (!((event->modifiers() & Qt::ALT) != 0u)) { - setCursor(altDragState->originalCursor); + applyCursor(altDragState->originalCursor.shape()); endInteraction(); // Don't accept the event; let the underlying widgets handle it. return; @@ -672,7 +823,24 @@ void MapCanvas::mouseMoveEvent(QMouseEvent *const event) return; } - const bool hasLeftButton = (event->buttons() & Qt::LeftButton) != 0u; + const auto optXy = getMouseCoords(event); + if (!optXy) { + return; + } + handlePointerMove(*optXy, event->modifiers(), event->buttons()); + + // Touch drag in MOVE mode: remember where the view is over time so the + // release can turn the finger's speed into a flick. + if (event->source() != Qt::MouseEventNotSynthesized && getInteraction() != nullptr) { + recordScrollSample(static_cast(event->timestamp())); + } +} + +void MapCanvas::handlePointerMove(const glm::vec2 xy, + MAYBE_UNUSED const Qt::KeyboardModifiers modifiers, + const Qt::MouseButtons buttons) +{ + const bool hasLeftButton = (buttons & Qt::LeftButton) != 0u; if (m_canvasMouseMode != CanvasMouseModeEnum::MOVE) { // NOTE: Y is opposite of what you might expect here. @@ -711,7 +879,7 @@ void MapCanvas::mouseMoveEvent(QMouseEvent *const event) if (hasLeftButton && hasSel1() && hasSel2()) { if (auto *const move = getInteraction()) { move->pos = getSel2().pos - getSel1().pos; - setCursor(Qt::ClosedHandCursor); + applyCursor(Qt::ClosedHandCursor); } else { beginAreaSelection(); @@ -759,7 +927,7 @@ void MapCanvas::mouseMoveEvent(QMouseEvent *const event) move->pos = diff; move->wrongPlace = wrongPlace; - setCursor(wrongPlace ? Qt::ForbiddenCursor : Qt::ClosedHandCursor); + applyCursor(wrongPlace ? Qt::ForbiddenCursor : Qt::ClosedHandCursor); } else { beginAreaSelection(); } @@ -805,8 +973,24 @@ void MapCanvas::mouseMoveEvent(QMouseEvent *const event) } } -void MapCanvas::mouseReleaseEvent(QMouseEvent *const event) +void MapCanvas::handleMouseRelease(QMouseEvent *const event) { + cancelLongPress(); + if (std::exchange(m_longPressFired, false) && event->button() == Qt::LeftButton) { + // onLongPress() already abandoned the press and opened the context + // menu; treating this release as a tap would also raise the room + // tooltip over the open menu. + m_scrollSamples.clear(); + event->accept(); + return; + } + if (event->button() == Qt::LeftButton && event->source() != Qt::MouseEventNotSynthesized + && m_canvasMouseMode == CanvasMouseModeEnum::MOVE + && getInteraction() != nullptr) { + recordScrollSample(static_cast(event->timestamp())); + startFlick(); + } + m_scrollSamples.clear(); const auto optXy = getMouseCoords(event); if (!optXy) { return; @@ -814,7 +998,7 @@ void MapCanvas::mouseReleaseEvent(QMouseEvent *const event) const auto xy = *optXy; if (auto *const altDragState = getInteraction()) { - setCursor(altDragState->originalCursor); + applyCursor(altDragState->originalCursor.shape()); endInteraction(); event->accept(); return; @@ -829,7 +1013,7 @@ void MapCanvas::mouseReleaseEvent(QMouseEvent *const event) switch (m_canvasMouseMode) { case CanvasMouseModeEnum::SELECT_INFOMARKS: - setCursor(Qt::ArrowCursor); + applyCursor(Qt::ArrowCursor); if (m_mouseLeftPressed) { m_mouseLeftPressed = false; if (auto *const move = getInteraction()) { @@ -881,13 +1065,15 @@ void MapCanvas::mouseReleaseEvent(QMouseEvent *const event) case CanvasMouseModeEnum::MOVE: stopMoving(); - setCursor(Qt::OpenHandCursor); + applyCursor(Qt::OpenHandCursor); if (m_mouseLeftPressed) { m_mouseLeftPressed = false; } - // Display a room info tooltip if there was no mouse movement - if (event->button() == Qt::LeftButton && hasSel1() && hasSel2() - && getSel1().to_vec3() == getSel2().to_vec3()) { + // Display a room info tooltip if there was no mouse movement. + // Not for touch: a tooltip is a hover affordance, and a tapped one + // would sit over the map until the next tap. + if (event->button() == Qt::LeftButton && event->source() == Qt::MouseEventNotSynthesized + && hasSel1() && hasSel2() && getSel1().to_vec3() == getSel2().to_vec3()) { if (const auto room = m_data.findRoomHandle(getSel1().getCoordinate())) { // Tooltip doesn't support ANSI, and there's no way to add formatted text. auto message = mmqt::previewRoom(room, @@ -904,7 +1090,7 @@ void MapCanvas::mouseReleaseEvent(QMouseEvent *const event) break; case CanvasMouseModeEnum::SELECT_ROOMS: - setCursor(Qt::ArrowCursor); + applyCursor(Qt::ArrowCursor); // This seems very unusual. if (m_ctrlPressed && m_altPressed) { @@ -1145,6 +1331,7 @@ void MapCanvas::slot_zoomReset() void MapCanvas::onMovement() { + stopFlick(); const Coordinate pos = m_data.tryGetPosition().value_or(Coordinate{}); setCurrentLayer(pos.z); getOpenGL().getUboManager().invalidate(Legacy::SharedVboEnum::CameraBlock); @@ -1160,10 +1347,7 @@ void MapCanvas::onMovement() void MapCanvas::slot_dataLoaded() { onMovement(); - - // REVISIT: is the makeCurrent necessary for calling update()? - // MakeCurrentRaii makeCurrentRaii{*this}; - forceUpdateMeshes(); + requestForceUpdateMeshes(); } void MapCanvas::slot_moveMarker(const RoomId id) @@ -1192,6 +1376,25 @@ void MapCanvas::forceUpdateMeshes() m_frameManager.requestUpdate(); } +void MapCanvas::requestForceUpdateMeshes() +{ + // Deferred: dropping the cached meshes destroys GL objects (VBOs/VAOs), + // which requires a current GL context. Callers of this function (UI + // actions, config-change callbacks, data-loaded notifications) may run + // with no GL context current, so we just flag the work and let the next + // hostPaintGL() perform it, mirroring finishPendingMapBatches()'s pattern. + m_pendingForceUpdateMeshes = true; + m_frameManager.requestUpdate(); +} + +void MapCanvas::requestUpdateTextures() +{ + // Deferred for the same reason as requestForceUpdateMeshes(): updateTextures() + // touches real GL texture objects and may be requested from outside paint. + m_pendingUpdateTextures = true; + m_frameManager.requestUpdate(); +} + void MapCanvas::slot_mapChanged() { // REVISIT: Ideally we'd want to only update the layers/chunks @@ -1214,8 +1417,8 @@ void MapCanvas::screenChanged() return; } - const auto newDpi = static_cast(QPaintDevice::devicePixelRatioF()); - const auto oldDpi = gl.getDevicePixelRatio(); + const auto newDpi = static_cast(currentDpr()); + const auto oldDpi = gl.getHostDevicePixelRatio(); if (!utils::isSameFloat(newDpi, oldDpi)) { log(QString("Display: %1 DPI").arg(static_cast(newDpi))); @@ -1225,10 +1428,11 @@ void MapCanvas::screenChanged() // without having to compute it again, right? m_batches.resetExistingMeshesButKeepPendingRemesh(); - gl.setDevicePixelRatio(newDpi); - auto &font = getGLFont(); - font.cleanup(); - font.init(); + // Deferred: applying the new DPR touches the GL font (cleanup+init, + // real GL texture calls), so it's applied at the top of the next + // hostPaintGL() instead of immediately (screenChanged() can be called + // outside of paint, e.g. from QWindow::screenChanged()). + m_pendingDpr = newDpi; m_frameManager.requestUpdate(); } diff --git a/src/display/mapcanvas.h b/src/display/mapcanvas.h index 43ab73316..3eae2e918 100644 --- a/src/display/mapcanvas.h +++ b/src/display/mapcanvas.h @@ -16,6 +16,7 @@ #include "../opengl/Weather.h" #include "FrameManager.h" #include "Infomarks.h" +#include "MapCanvasConfig.h" #include "MapCanvasData.h" #include "MapCanvasRoomDrawer.h" #include "Textures.h" @@ -24,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -37,7 +39,7 @@ #include #include #include -#include +#include #include class CharacterBatch; @@ -49,20 +51,60 @@ class MapData; class Mmapper2Group; class PrespammedPath; class QMouseEvent; +class QNativeGestureEvent; class QOpenGLDebugLogger; class QOpenGLDebugMessage; +class QTouchEvent; class QWheelEvent; -class QWidget; class RoomSelFakeGL; -class NODISCARD_QOBJECT MapCanvas final : public QOpenGLWindow, +// Minimal interface a MapCanvas uses to talk back to whatever widget/item +// is actually hosting it on screen. MapCanvas talks only to this +// interface, so it doesn't know or care which concrete host implements it. +class NODISCARD MapCanvasHost +{ +public: + virtual ~MapCanvasHost(); + +public: + // Schedule a repaint (e.g. QOpenGLWindow::update()). + void requestCanvasUpdate() { virt_requestCanvasUpdate(); } + + // The host's current device pixel ratio. + NODISCARD qreal hostDevicePixelRatio() const { return virt_hostDevicePixelRatio(); } + + // The host's current size in logical pixels. + NODISCARD QSize hostSize() const { return virt_hostSize(); } + + // Set the shape of the cursor shown while hovering the host. + void setHostCursor(const Qt::CursorShape shape) { virt_setHostCursor(shape); } + + // Called with the GL context current, immediately before the core + // composites its internal FBO into the currently bound framebuffer + // (blitFboToDefault()). By this point the paint has left the viewport + // at (0, 0, w, h) -- the right presentation rect for a host that owns + // its whole framebuffer (e.g. QOpenGLWindow), hence the no-op default. + // A host that presents into a SUB-RECT of a framebuffer it shares with + // other content must re-apply its own viewport here, or the blit lands + // at the framebuffer's bottom-left corner instead of the host's rect. + void applyPresentViewport() { virt_applyPresentViewport(); } + +private: + virtual void virt_requestCanvasUpdate() = 0; + NODISCARD virtual qreal virt_hostDevicePixelRatio() const = 0; + NODISCARD virtual QSize virt_hostSize() const = 0; + virtual void virt_setHostCursor(Qt::CursorShape shape) = 0; + virtual void virt_applyPresentViewport() {} +}; + +class NODISCARD_QOBJECT MapCanvas final : public QObject, private MapCanvasViewport, private MapCanvasInputState { Q_OBJECT public: - static constexpr const int SCROLL_SCALE = 64; + static constexpr const int SCROLL_SCALE = MapCanvasConfig::SCROLL_SCALE; private: struct NODISCARD Diff final @@ -143,33 +185,86 @@ class NODISCARD_QOBJECT MapCanvas final : public QOpenGLWindow, MapData &m_data; Mmapper2Group &m_groupManager; Diff m_diff; + + // Declared before m_frameManager, whose constructor already invokes the + // repaint callback that uses it. + MapCanvasHost &m_host; + Qt::CursorShape m_currentCursor = Qt::ArrowCursor; + FrameManager m_frameManager; std::unique_ptr m_logger; Signal2Lifetime m_lifetime; GLWeather m_weather; bool m_cleanedUp = false; + // Deferred (defer-to-next-render) state for GL work that historically ran + // outside of paintGL(), relying on the implicit assumption that the host's + // GL context happened to still be current. See hostPaintGL()/actuallyPaintGL(). + bool m_pendingForceUpdateMeshes = false; + bool m_pendingUpdateTextures = false; + std::optional m_pendingDpr; + std::optional m_pendingRenderScale; + + // Touch long-press -> context menu. A left press synthesized from touch + // arms the timer; moving past the drag threshold or releasing disarms it + // (see handleMousePress()/handleMouseMove()/handleMouseRelease()). + QTimer m_longPressTimer; + std::optional m_longPressPos; + // Set when the timer fired: the finger's eventual release is then + // swallowed, since the context menu was the response to that gesture. + bool m_longPressFired = false; + + // Touch flick: recent scroll samples of a touch drag in MOVE mode, and + // the velocity (world units per second) the view keeps after release + // until it decays (see handleMouseRelease()/onFlickTick()). + struct NODISCARD ScrollSample final + { + qint64 msecs = 0; + glm::vec2 scroll{0.f}; + }; + std::deque m_scrollSamples; + QTimer m_flickTimer; + glm::vec2 m_flickVelocity{0.f}; + public: explicit MapCanvas(MapData &mapData, GameObserver &observer, PrespammedPath &prespammedPath, Mmapper2Group &groupManager, - QWindow *parent = nullptr); - ~MapCanvas() final; + MapCanvasHost &host); + ~MapCanvas() override; -public: - NODISCARD static MapCanvas *getPrimary(); +private: + NODISCARD qreal currentDpr() const { return m_host.hostDevicePixelRatio(); } + // Configuration::canvas.renderScale (a percentage) as the factor the + // offscreen FBO is rendered at; see Legacy::Functions::setRenderScale(). + NODISCARD static float configuredRenderScale(); + NODISCARD QSize currentHostSize() const { return m_host.hostSize(); } + void applyCursor(Qt::CursorShape shape) + { + m_currentCursor = shape; + m_host.setHostCursor(shape); + } + NODISCARD QCursor currentCursor() const { return QCursor(m_currentCursor); } private: NODISCARD inline auto &getOpenGL() { return m_opengl; } NODISCARD inline auto &getGLFont() { return m_glFont; } - void cleanupOpenGL(); public: - void shuttingDown(); + // Called by the host with a current GL context. Idempotent: cleanup state + // is reset the next time a host attaches and re-initializes. + NODISCARD bool hostInitializeGL(); + void hostPaintGL(); + void hostResize(int width, int height, qreal dpr); + // Must be called with a current GL context (the host is responsible for that). + void hostCleanupGL(); + NODISCARD bool isCleanedUp() const { return m_cleanedUp; } public: using MapCanvasViewport::getTotalScaleFactor; + using MapCanvasViewport::height; + using MapCanvasViewport::width; void setZoom(float zoom) { ScaleFactor sf = getScaleFactor(); @@ -179,11 +274,6 @@ class NODISCARD_QOBJECT MapCanvas final : public QOpenGLWindow, } NODISCARD float getRawZoom() const { return getScaleFactor().getRaw(); } -public: - NODISCARD auto width() const { return QOpenGLWindow::width(); } - NODISCARD auto height() const { return QOpenGLWindow::height(); } - NODISCARD QRect rect() const { return QRect(0, 0, width(), height()); } - private: void onMovement(); void startMoving(const MouseSel &startPos); @@ -196,24 +286,28 @@ class NODISCARD_QOBJECT MapCanvas final : public QOpenGLWindow, protected: void onViewProjDirty() const override; -protected: - void initializeGL() override; - void paintGL() override; +public: + // Bodies of the QOpenGLWindow event overrides on the facade, exposed as + // plain QEvent-taking entry points so any host can forward into the same + // logic. handleMouseMove() further delegates the position+modifiers core + // to handlePointerMove(), which a hover-event path with no button/press + // semantics can call directly. + void handleMousePress(QMouseEvent *event); + void handleMouseRelease(QMouseEvent *event); + void handleMouseMove(QMouseEvent *event); + void handlePointerMove(glm::vec2 pos, Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons); + void handleWheel(QWheelEvent *event); + void handleTouch(QTouchEvent *event); + void handleNativeGesture(QNativeGestureEvent *event); + // Returns true if the event was handled (i.e. it was a recognized native + // zoom gesture); mirrors the facade's bool event(QEvent*) override. + NODISCARD bool handleGenericEvent(QEvent *event); +private: void drawGroupCharacters(CharacterBatch &characterBatch, ServerRoomId yourServerId); - void resizeGL(int width, int height) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; - void mouseMoveEvent(QMouseEvent *event) override; - void wheelEvent(QWheelEvent *event) override; - void touchEvent(QTouchEvent *event) override; - bool event(QEvent *e) override; - -private: void initLogger(); - void resizeGL() { resizeGL(width(), height()); } void initTextures(); void updateTextures(); void updateMultisampling(); @@ -222,7 +316,7 @@ class NODISCARD_QOBJECT MapCanvas final : public QOpenGLWindow, public: void setMvp(const glm::mat4 &viewProj); - void setViewportAndMvp(int width, int height); + void setViewportAndMvp(int width, int height, qreal dpr); void zoomAt(float factor, glm::vec2 mousePos); void handleZoomAtEvent(const QInputEvent *event, float deltaFactor); @@ -238,6 +332,7 @@ class NODISCARD_QOBJECT MapCanvas final : public QOpenGLWindow, void updateMapBatches(); void updateInfomarkBatches(); + void applyPendingGLWork(); void actuallyPaintGL(); void paintMap(); void renderMapBatches(); @@ -252,10 +347,16 @@ class NODISCARD_QOBJECT MapCanvas final : public QOpenGLWindow, void paintSelectedInfomarks(); void paintCharacters(); void paintDifferences(); + + // Immediately drops all cached meshes (must run with a current GL context). void forceUpdateMeshes(); + // Defers forceUpdateMeshes() to the start of the next hostPaintGL(). + void requestForceUpdateMeshes(); + // Defers updateTextures() to the start of the next hostPaintGL(). + void requestUpdateTextures(); public: - void slot_rebuildMeshes() { forceUpdateMeshes(); } + void slot_rebuildMeshes() { requestForceUpdateMeshes(); } void infomarksChanged(); void layerChanged(); void slot_mapChanged(); @@ -267,8 +368,24 @@ class NODISCARD_QOBJECT MapCanvas final : public QOpenGLWindow, void syncViewportConfig(); public: + // Forwarded by MapWindow::keyPressEvent()/keyReleaseEvent(); the bool + // parameter is otherwise unused (see the .cpp). void userPressedEscape(bool); +private: + // Selects the room and infomarks under a canvas-local, top-left-origin + // point and emits sig_customContextMenuRequested; shared by the + // right-mouse-button press and the touch long-press (see + // handleMousePress()). + void requestContextMenuAt(const QPointF &pos); + void cancelLongPress(); + void onLongPress(); + void recordScrollSample(qint64 msecs); + void startFlick(); + void stopFlick(); + void onFlickTick(); + +public: private: void log(const QString &msg) { emit sig_log("MapCanvas", msg); } @@ -292,6 +409,17 @@ class NODISCARD_QOBJECT MapCanvas final : public QOpenGLWindow, void sig_customContextMenuRequested(const QPoint &pos); void sig_dismissContextMenu(); + // Emitted from hostInitializeGL() when OpenGL initialization fails (e.g. + // an unsupported/blacklisted driver). The core stays QtWidgets-free, so + // it's up to whoever connects to this signal (the widget facade) to show + // a QMessageBox and/or hide the host window. + void sig_glInitFailed(const QString &reason); + + // Emitted from the (direct) GL debug message handler for fatal errors. + // The core stays QtWidgets-free, so the widget facade is responsible for + // showing a blocking dialog and aborting. + void sig_glFatalError(const QString &message); + public slots: void slot_onForcedPositionChange(); void slot_createRoom(); @@ -306,6 +434,7 @@ public slots: void slot_zoomIn(); void slot_zoomOut(); void slot_zoomReset(); + void slot_centerOnPlayer() { onMovement(); } void slot_layerUp(); void slot_layerDown(); @@ -329,5 +458,6 @@ public slots: void slot_dataLoaded(); void slot_moveMarker(RoomId id); +private slots: void slot_onMessageLoggedDirect(const QOpenGLDebugMessage &message); }; diff --git a/src/display/mapcanvas_gl.cpp b/src/display/mapcanvas_gl.cpp index 7e459158d..0b26c2a64 100644 --- a/src/display/mapcanvas_gl.cpp +++ b/src/display/mapcanvas_gl.cpp @@ -11,7 +11,6 @@ #include "../global/logging.h" #include "../global/progresscounter.h" #include "../global/utils.h" -#include "../global/window_utils.h" #include "../map/coordinate.h" #include "../mapdata/mapdata.h" #include "../opengl/Font.h" @@ -54,10 +53,12 @@ #include #include -#include -#include +#ifdef Q_OS_WASM +#include +#endif + #include -#include +#include #include #include #include @@ -112,32 +113,10 @@ void setShowPerfStats(const bool show) } // namespace MapCanvasConfig -class NODISCARD MakeCurrentRaii final -{ -private: - QOpenGLWindow &m_glWindow; - -public: - explicit MakeCurrentRaii(QOpenGLWindow &window) - : m_glWindow{window} - { - m_glWindow.makeCurrent(); - } - ~MakeCurrentRaii() { m_glWindow.doneCurrent(); } - - DELETE_CTORS_AND_ASSIGN_OPS(MakeCurrentRaii); -}; - -void MapCanvas::shuttingDown() -{ - qInfo() << MM_SOURCE_LOCATION().function_name(); - if (!m_cleanedUp) { - cleanupOpenGL(); - } -} - -void MapCanvas::cleanupOpenGL() +void MapCanvas::hostCleanupGL() { + // NOTE: The caller (the host facade) is responsible for making sure a GL + // context is current before calling this function. const auto fname = MM_SOURCE_LOCATION().function_name(); qInfo() << fname << "Entered."; @@ -147,20 +126,16 @@ void MapCanvas::cleanupOpenGL() } qInfo() << fname << "Cleaning up..."; - { - // Make sure the context is current and then explicitly - // destroy all underlying OpenGL resources. - MakeCurrentRaii makeCurrentRaii{*this}; - - // note: m_batchedMeshes co-owns textures created by MapCanvasData, - // and it also owns the lifetime of some OpenGL objects (e.g. VBOs). - m_batches.resetExistingMeshesAndIgnorePendingRemesh(); - m_weather.cleanup(); - m_textures.destroyAll(); - getGLFont().cleanup(); - getOpenGL().cleanup(); - m_logger.reset(); - } + + // note: m_batchedMeshes co-owns textures created by MapCanvasData, + // and it also owns the lifetime of some OpenGL objects (e.g. VBOs). + m_batches.resetExistingMeshesAndIgnorePendingRemesh(); + m_weather.cleanup(); + m_textures.destroyAll(); + getGLFont().cleanup(); + getOpenGL().cleanup(); + m_logger.reset(); + qInfo() << fname << "Done."; } @@ -241,25 +216,33 @@ void MapCanvas::reportGLVersion() } #endif - const auto version = std::invoke([this]() -> std::string { - const QSurfaceFormat &format = context()->format(); + // NOTE: hostInitializeGL() runs with a current GL context (the host + // guarantees this, same as the old QOpenGLWindow::initializeGL()), so + // querying the thread's current context here is equivalent to the old + // QOpenGLWindow::context() call, without depending on any particular host. + const auto version = std::invoke([]() -> std::string { std::ostringstream oss; - switch (format.renderableType()) { - case QSurfaceFormat::OpenGL: - oss << "GL"; - break; - case QSurfaceFormat::OpenGLES: - oss << "ES"; - break; - case QSurfaceFormat::OpenVG: - oss << "VG"; - break; - case QSurfaceFormat::DefaultRenderableType: - default: - oss << "UN"; - break; + if (auto *const ctxt = QOpenGLContext::currentContext()) { + const QSurfaceFormat &format = ctxt->format(); + switch (format.renderableType()) { + case QSurfaceFormat::OpenGL: + oss << "GL"; + break; + case QSurfaceFormat::OpenGLES: + oss << "ES"; + break; + case QSurfaceFormat::OpenVG: + oss << "VG"; + break; + case QSurfaceFormat::DefaultRenderableType: + default: + oss << "UN"; + break; + } + oss << format.majorVersion() << "." << format.minorVersion(); + } else { + oss << "UNKNOWN"; } - oss << format.majorVersion() << "." << format.minorVersion(); return std::move(oss).str(); }); @@ -267,7 +250,10 @@ void MapCanvas::reportGLVersion() QString("%1 (%2)") .arg(version.c_str()) // FIXME: This is a bit late to report an invalid context. - .arg(context()->isValid() ? "valid" : "invalid") + .arg((QOpenGLContext::currentContext() != nullptr + && QOpenGLContext::currentContext()->isValid()) + ? "valid" + : "invalid") .toUtf8()); if constexpr (!NO_OPENGL) { logMsg("Highest OpenGL:", mmqt::toQByteArrayUtf8(OpenGLConfig::getGLVersionString())); @@ -276,7 +262,11 @@ void MapCanvas::reportGLVersion() logMsg("Highest GLES:", mmqt::toQByteArrayUtf8(OpenGLConfig::getESVersionString())); } - logMsg("Display:", QString("%1 DPI").arg(QPaintDevice::devicePixelRatioF()).toUtf8()); + logMsg("Display:", + QString("%1 DPI, render scale %2%") + .arg(currentDpr()) + .arg(getConfig().canvas.renderScale.get()) + .toUtf8()); } bool MapCanvas::isBlacklistedDriver() @@ -297,7 +287,7 @@ bool MapCanvas::isBlacklistedDriver() return false; } -void MapCanvas::initializeGL() +bool MapCanvas::hostInitializeGL() { OpenGL &gl = getOpenGL(); try { @@ -307,18 +297,12 @@ void MapCanvas::initializeGL() if (isBlacklistedDriver()) { throw std::runtime_error("unsupported driver"); } - } catch (const std::exception &) { - hide(); - doneCurrent(); - mmqt::showCritical(QApplication::activeWindow(), - "Unable to initialize OpenGL", - "Upgrade your video card drivers"); - if constexpr (CURRENT_PLATFORM == PlatformEnum::Windows) { - // Link to Microsoft OpenGL Compatibility Pack - QDesktopServices::openUrl( - QUrl(QStringLiteral("ms-windows-store://pdp/?productid=9nqpsl29bfff"))); - } - return; + } catch (const std::exception &ex) { + // The core stays QtWidgets-free, so it can't show the message box or + // hide the host window itself; the host facade does that in response + // to this signal. + emit sig_glInitFailed(QString::fromUtf8(ex.what())); + return false; } reportGLVersion(); @@ -328,7 +312,8 @@ void MapCanvas::initializeGL() // because the logger purposely calls std::abort() when it receives an error. initLogger(); - gl.initializeRenderer(static_cast(QPaintDevice::devicePixelRatioF())); + gl.initializeRenderer(static_cast(currentDpr())); + gl.setRenderScale(configuredRenderScale()); gl.getUboManager() .registerRebuildFunction(Legacy::SharedVboEnum::NamedColorsBlock, @@ -370,19 +355,19 @@ void MapCanvas::initializeGL() setConfig().canvas.showUnsavedChanges.registerChangeCallback(m_lifetime, [this]() { if (getConfig().canvas.showUnsavedChanges.get() && m_diff.highlight.has_value() && m_diff.highlight->highlights.empty()) { - this->forceUpdateMeshes(); + this->requestForceUpdateMeshes(); } }); setConfig().canvas.showMissingMapId.registerChangeCallback(m_lifetime, [this]() { if (getConfig().canvas.showMissingMapId.get() && m_diff.highlight.has_value() && m_diff.highlight->highlights.empty()) { - this->forceUpdateMeshes(); + this->requestForceUpdateMeshes(); } }); setConfig().canvas.showUnmappedExits.registerChangeCallback(m_lifetime, [this]() { - this->forceUpdateMeshes(); + this->requestForceUpdateMeshes(); }); setConfig().canvas.antialiasingSamples.registerChangeCallback(m_lifetime, [this]() { @@ -390,18 +375,21 @@ void MapCanvas::initializeGL() m_frameManager.requestUpdate(); }); - setConfig().canvas.trilinearFiltering.registerChangeCallback(m_lifetime, [this]() { - this->updateTextures(); + setConfig().canvas.renderScale.registerChangeCallback(m_lifetime, [this]() { + // Deferred like m_pendingDpr: the FBO is reconfigured at the top of + // the next paint, where the GL context is current. + m_pendingRenderScale = configuredRenderScale(); m_frameManager.requestUpdate(); }); - // Clean up GL resources while the context is still current. - // The destructor is too late — Qt destroys the context before ~MapCanvas() runs. - connect(context(), - &QOpenGLContext::aboutToBeDestroyed, - this, - &MapCanvas::cleanupOpenGL, - Qt::DirectConnection); + setConfig().canvas.trilinearFiltering.registerChangeCallback(m_lifetime, [this]() { + this->requestUpdateTextures(); + }); + + // NOTE: The host facade is responsible for connecting to + // QOpenGLContext::aboutToBeDestroyed (see MapCanvas::initializeGL()); the + // core has no notion of a QOpenGLContext or its lifetime. + return true; } /* Direct means it is always called from the emitter's thread */ @@ -427,12 +415,11 @@ void MapCanvas::slot_onMessageLoggedDirect(const QOpenGLDebugMessage &message) qCritical() << message; - QMessageBox box; - box.setWindowTitle("Fatal OpenGL error"); - box.setText(message.message()); - box.exec(); - - std::abort(); + // The core stays QtWidgets-free, so it can't show the blocking message + // box itself; the host facade does that (and calls std::abort()) in + // response to this signal, using a direct connection so the abort still + // happens synchronously from here. + emit sig_glFatalError(message.message()); } void MapCanvas::initLogger() @@ -467,8 +454,14 @@ void MapCanvas::setMvp(const glm::mat4 &viewProj) gl.setProjectionMatrix(viewProj); } -void MapCanvas::setViewportAndMvp(int width, int height) +void MapCanvas::setViewportAndMvp(const int width, const int height, const qreal dpr) { + // Refresh the cached viewport geometry (and DPR) every time; this is called + // once per paint (from actuallyPaintGL()) as well as from hostResize(), so it + // also acts as the "first frame" safety net, since nothing else queries + // the live host size on every access. + setViewportSize(width, height, dpr); + if (width != m_lastWidth || height != m_lastHeight) { m_lastWidth = width; m_lastHeight = height; @@ -490,14 +483,14 @@ void MapCanvas::onViewProjDirty() const m_opengl.getUboManager().invalidate(Legacy::SharedVboEnum::CameraBlock); } -void MapCanvas::resizeGL(int width, int height) +void MapCanvas::hostResize(const int width, const int height, const qreal dpr) { if (m_textures.room_highlight == nullptr) { - // resizeGL called but initializeGL was not called yet + // hostResize called but hostInitializeGL was not called yet return; } - setViewportAndMvp(width, height); + setViewportAndMvp(width, height, dpr); markMultisamplingDirty(); m_frameManager.requestUpdate(); } @@ -604,10 +597,50 @@ void MapCanvas::finishPendingMapBatches() #undef LOG } +void MapCanvas::applyPendingGLWork() +{ + // Deferred (defer-to-next-render) GL work relies on the host's GL context + // being current, so it is applied at the top of the paint, before the + // batches are (re)built: a forced remesh must not discard the remesh + // that updateBatches() just started, and glyph meshes must use the + // font metrics of the new DPI / render scale. + if (m_pendingDpr.has_value()) { + const float newDpi = *m_pendingDpr; + m_pendingDpr.reset(); + getOpenGL().setDevicePixelRatio(newDpi); + auto &font = getGLFont(); + font.cleanup(); + font.init(); + } + if (m_pendingRenderScale.has_value()) { + const float newScale = *m_pendingRenderScale; + m_pendingRenderScale.reset(); + if (!utils::isSameFloat(newScale, getOpenGL().getRenderScale())) { + log(QString("Render scale: %1%").arg(static_cast(newScale) * 100.0)); + getOpenGL().setRenderScale(newScale); + // Glyphs are rasterized for the render target's pixel density, + // and the FBO is sized from it. + auto &font = getGLFont(); + font.cleanup(); + font.init(); + m_batches.resetExistingMeshesButKeepPendingRemesh(); + markMultisamplingDirty(); + } + } + if (std::exchange(m_pendingUpdateTextures, false)) { + updateTextures(); + } + if (std::exchange(m_pendingForceUpdateMeshes, false)) { + forceUpdateMeshes(); + } +} + void MapCanvas::actuallyPaintGL() { // DECL_TIMER(t, __FUNCTION__); - setViewportAndMvp(width(), height()); + + const QSize hostSizeNow = currentHostSize(); + setViewportAndMvp(hostSizeNow.width(), hostSizeNow.height(), currentDpr()); if (takeMultisamplingDirty()) { updateMultisampling(); } @@ -666,6 +699,7 @@ void MapCanvas::actuallyPaintGL() } if (paintSucceeded) { + m_host.applyPresentViewport(); gl.blitFboToDefault(); } } @@ -831,11 +865,12 @@ void MapCanvas::paintSelections() paintSelectedInfomarks(); } -void MapCanvas::paintGL() +void MapCanvas::hostPaintGL() { auto frame = m_frameManager.beginFrame(); if (!frame) { // Blit the existing FBO on resize or expose + m_host.applyPresentViewport(); getOpenGL().blitFboToDefault(); return; } @@ -853,6 +888,7 @@ void MapCanvas::paintGL() } { + applyPendingGLWork(); if (showPerfStats) { optAfterTextures = Clock::now(); } @@ -881,14 +917,13 @@ void MapCanvas::paintGL() const auto &afterTextures = optAfterTextures.value(); const auto &afterBatches = optAfterBatches.value(); const auto afterPaint = Clock::now(); - const bool calledFinish = std::invoke([this]() -> bool { - if (auto *const ctxt = QOpenGLWindow::context()) { - if (auto *const func = ctxt->functions()) { - func->glFinish(); - return true; - } + auto &gl = getOpenGL(); + const bool calledFinish = std::invoke([&gl]() -> bool { + if (!gl.isRendererInitialized()) { + return false; } - return false; + gl.glFinish(); + return true; }); const auto end = Clock::now(); @@ -940,6 +975,29 @@ void MapCanvas::paintGL() longestBatchMs = std::max(batchTime, longestBatchMs); print(QString::asprintf("Worst updateBatches: %.1f ms", longestBatchMs)); +#ifdef Q_OS_WASM + { + // Browser memory is what limits the map on tablets; show the wasm + // heap and the offscreen framebuffer's footprint next to the timings. + const size_t heapSize = emscripten_get_heap_size(); + const size_t heapMax = emscripten_get_heap_max(); + const Viewport fbo = getOpenGL().getPhysicalViewport(); + const int samples = std::max(1, getConfig().canvas.antialiasingSamples.get()); + const double fboMegabytes = static_cast(fbo.size.x) + * static_cast(fbo.size.y) + * 8.0 /* RGBA8 color + 32-bit depth */ + * static_cast(samples) / (1024.0 * 1024.0); + print(QString::asprintf("WASM heap: %zu MB of %zu MB", + heapSize / (1024 * 1024), + heapMax / (1024 * 1024))); + print(QString::asprintf("FBO: %dx%d at %d%% (~%.1f MB)", + fbo.size.x, + fbo.size.y, + getConfig().canvas.renderScale.get(), + fboMegabytes)); + } +#endif + const auto &advanced = getConfig().canvas.advanced; const float zoom = getTotalScaleFactor(); const bool is3d = advanced.use3D.get(); @@ -1036,10 +1094,19 @@ void MapCanvas::paintSelectionArea() void MapCanvas::updateMultisampling() { - const int wantMultisampling = getConfig().canvas.antialiasingSamples.get(); + // MSAA multiplies the FBO's memory, which a reduced render scale exists + // to save, so the two are exclusive (the Graphics page enforces the same). + const int wantMultisampling = (getConfig().canvas.renderScale.get() < 100) + ? 0 + : getConfig().canvas.antialiasingSamples.get(); getOpenGL().configureFbo(wantMultisampling); } +float MapCanvas::configuredRenderScale() +{ + return std::clamp(static_cast(getConfig().canvas.renderScale.get()) / 100.f, 0.25f, 1.f); +} + void MapCanvas::renderMapBatches() { std::optional &mapBatches = m_batches.mapBatches; diff --git a/src/display/mapwindow.cpp b/src/display/mapwindow.cpp index 30408d637..44509ac27 100644 --- a/src/display/mapwindow.cpp +++ b/src/display/mapwindow.cpp @@ -12,8 +12,7 @@ #include "../global/SignalBlocker.h" #include "../global/Version.h" #include "../global/utils.h" -#include "AudioHintWidget.h" -#include "mapcanvas.h" +#include "MapCanvasWindow.h" #include #include @@ -104,6 +103,8 @@ MapWindow::MapWindow(MapData &mapData, QWidget *const parent) : QWidget(parent) { + m_scroller = new MapScroller(this); + m_gridLayout = mmqt::makeQPointer(this); m_gridLayout->setSpacing(0); m_gridLayout->setContentsMargins(0, 0, 0, 0); @@ -114,7 +115,7 @@ MapWindow::MapWindow(MapData &mapData, m_verticalScrollBar->setOrientation(Qt::Vertical); m_verticalScrollBar->setRange(0, 0); m_verticalScrollBar->hide(); - m_verticalScrollBar->setSingleStep(MapCanvas::SCROLL_SCALE); + m_verticalScrollBar->setSingleStep(MapCanvasWindow::SCROLL_SCALE); m_gridLayout->addWidget(m_verticalScrollBar, 0, 1, 1, 1); @@ -122,11 +123,11 @@ MapWindow::MapWindow(MapData &mapData, m_horizontalScrollBar->setOrientation(Qt::Horizontal); m_horizontalScrollBar->setRange(0, 0); m_horizontalScrollBar->hide(); - m_horizontalScrollBar->setSingleStep(MapCanvas::SCROLL_SCALE); + m_horizontalScrollBar->setSingleStep(MapCanvasWindow::SCROLL_SCALE); m_gridLayout->addWidget(m_horizontalScrollBar, 1, 0, 1, 1); - m_canvas = new MapCanvas(mapData, observer, pp, gm); + m_canvas = new MapCanvasWindow(mapData, observer, pp, gm); m_canvas->setMinimumSize(QSize(1280 / 4, 720 / 4)); m_canvas->resize(QSize(1280, 720)); @@ -136,9 +137,6 @@ MapWindow::MapWindow(MapData &mapData, m_gridLayout->addWidget(m_canvasContainer, 0, 0, 1, 1); - m_audioHint = new AudioHintWidget(this); - m_gridLayout->addWidget(m_audioHint, 2, 0, 1, 2); - setMinimumSize(m_canvas->minimumSize()); m_splashWidget = mmqt::makeQPointer(this); @@ -152,7 +150,7 @@ MapWindow::MapWindow(MapData &mapData, &QScrollBar::valueChanged, m_canvas, [this](const int x) -> void { - const float val = m_knownMapSize.scrollToWorld(glm::ivec2{x, 0}).x; + const float val = m_scroller->scrollToWorld(glm::ivec2{x, 0}).x; m_canvas->slot_setHorizontalScroll(val); }); @@ -160,25 +158,30 @@ MapWindow::MapWindow(MapData &mapData, &QScrollBar::valueChanged, m_canvas, [this](const int y) -> void { - const float value = m_knownMapSize.scrollToWorld(glm::ivec2{0, y}).y; + const float value = m_scroller->scrollToWorld(glm::ivec2{0, y}).y; m_canvas->slot_setVerticalScroll(value); }); - connect(this, &MapWindow::sig_setScroll, m_canvas, &MapCanvas::slot_setScroll); + connect(this, &MapWindow::sig_setScroll, m_canvas, &MapCanvasWindow::slot_setScroll); } // from canvas to map window { - connect(m_canvas, &MapCanvas::sig_onCenter, this, &MapWindow::slot_centerOnWorldPos); - connect(m_canvas, &MapCanvas::sig_setScrollBars, this, &MapWindow::slot_setScrollBars); - connect(m_canvas, &MapCanvas::sig_continuousScroll, this, &MapWindow::slot_continuousScroll); - connect(m_canvas, &MapCanvas::sig_mapMove, this, &MapWindow::slot_mapMove); - connect(m_canvas, &MapCanvas::sig_zoomChanged, this, &MapWindow::slot_zoomChanged); - connect(m_canvas, &MapCanvas::sig_showTooltip, this, &MapWindow::slot_showTooltip); + connect(m_canvas, &MapCanvasWindow::sig_onCenter, this, &MapWindow::slot_centerOnWorldPos); + connect(m_canvas, &MapCanvasWindow::sig_setScrollBars, this, &MapWindow::slot_setScrollBars); + connect(m_canvas, + &MapCanvasWindow::sig_continuousScroll, + this, + &MapWindow::slot_continuousScroll); + connect(m_canvas, &MapCanvasWindow::sig_mapMove, this, &MapWindow::slot_mapMove); + connect(m_canvas, &MapCanvasWindow::sig_zoomChanged, this, &MapWindow::slot_zoomChanged); + connect(m_canvas, &MapCanvasWindow::sig_showTooltip, this, &MapWindow::slot_showTooltip); } - m_scrollTimer = mmqt::makeQPointer(this); - connect(m_scrollTimer, &QTimer::timeout, this, &MapWindow::slot_scrollTimerTimeout); + connect(m_scroller, + &MapScroller::sig_continuousScrollStep, + this, + &MapWindow::slot_applyScrollStep); } void MapWindow::hideSplashImage() @@ -226,47 +229,20 @@ void MapWindow::slot_mapMove(const int dx, const int input_dy) centerOnScrollPos(scrollPos); } -// REVISIT: This looks more like "delayed jump" than "continuous scroll." -void MapWindow::slot_continuousScroll(const int hStep, const int input_vStep) +void MapWindow::slot_continuousScroll(const int hStep, const int vStep) { - const auto fitsInInt8 = [](int n) -> bool { - // alternate: test against std::numeric_limits::min and max. - return static_cast(static_cast(n)) == n; - }; - - // code originally used int8_t - assert(fitsInInt8(hStep)); - assert(fitsInInt8(input_vStep)); - - // Y is negated because delta is in world space - const int vStep = -input_vStep; - - m_horizontalScrollStep = hStep; - m_verticalScrollStep = vStep; - - auto &scrollTimer = deref(m_scrollTimer); - // stop - if (hStep == 0 && vStep == 0) { - if (scrollTimer.isActive()) { - scrollTimer.stop(); - } - } else { - // start - if (!scrollTimer.isActive()) { - scrollTimer.start(100); - } - } + m_scroller->slot_continuousScroll(hStep, vStep); } -void MapWindow::slot_scrollTimerTimeout() +void MapWindow::slot_applyScrollStep(const int hStep, const int vStep) { auto &horz = deref(m_horizontalScrollBar); auto &vert = deref(m_verticalScrollBar); const SignalBlocker block_horz{horz}; const SignalBlocker block_vert{vert}; - const int vValue = vert.value() + m_verticalScrollStep; - const int hValue = horz.value() + m_horizontalScrollStep; + const int vValue = vert.value() + vStep; + const int hValue = horz.value() + hStep; const glm::ivec2 scrollPos{hValue, vValue}; centerOnScrollPos(scrollPos); @@ -284,7 +260,7 @@ void MapWindow::slot_centerOnWorldPos(const glm::vec2 worldPos) const SignalBlocker block_horz{horz}; const SignalBlocker block_vert{vert}; - const auto scrollPos = m_knownMapSize.worldToScroll(worldPos); + const auto scrollPos = m_scroller->worldToScroll(worldPos); horz.setValue(scrollPos.x); vert.setValue(scrollPos.y); @@ -296,7 +272,7 @@ void MapWindow::centerOnScrollPos(const glm::ivec2 scrollPos) deref(m_horizontalScrollBar).setValue(scrollPos.x); deref(m_verticalScrollBar).setValue(scrollPos.y); - const auto worldPos = m_knownMapSize.scrollToWorld(scrollPos); + const auto worldPos = m_scroller->scrollToWorld(scrollPos); emit sig_setScroll(worldPos); } @@ -307,34 +283,40 @@ void MapWindow::resizeEvent(QResizeEvent * /*event*/) void MapWindow::slot_setScrollBars(const Coordinate min, const Coordinate max) { - m_knownMapSize.min = min.to_ivec3(); - m_knownMapSize.max = max.to_ivec3(); + m_scroller->slot_setScrollBars(min, max); + updateScrollBars(); +} + +void MapWindow::setScrollBarsSuppressed(const bool suppressed) +{ + m_scrollBarsSuppressed = suppressed; updateScrollBars(); } void MapWindow::updateScrollBars() { - const auto dims = m_knownMapSize.size() * MapCanvas::SCROLL_SCALE; - const auto showScrollBars = getConfig().general.showScrollBars; + const bool showScrollBars = getConfig().general.showScrollBars && !m_scrollBarsSuppressed; auto &horz = deref(m_horizontalScrollBar); - horz.setRange(0, dims.x); - if (dims.x > 0 && showScrollBars) { + const int hMax = m_scroller->getHorizontalScrollMax(); + horz.setRange(0, hMax); + if (hMax > 0 && showScrollBars) { horz.show(); } else { horz.hide(); } auto &vert = deref(m_verticalScrollBar); - vert.setRange(0, dims.y); - if (dims.y > 0 && showScrollBars) { + const int vMax = m_scroller->getVerticalScrollMax(); + vert.setRange(0, vMax); + if (vMax > 0 && showScrollBars) { vert.show(); } else { vert.hide(); } } -MapCanvas *MapWindow::getCanvas() const +MapCanvasWindow *MapWindow::getCanvas() const { return m_canvas; } @@ -359,20 +341,3 @@ void MapWindow::setCanvasEnabled(bool enabled) { deref(m_canvasContainer).setEnabled(enabled); } - -glm::vec2 MapWindow::KnownMapSize::scrollToWorld(const glm::ivec2 scrollPos) const -{ - auto worldPos = glm::vec2{scrollPos} / static_cast(MapCanvas::SCROLL_SCALE); - worldPos.y = static_cast(size().y) - worldPos.y; // negate Y - worldPos += glm::vec2{min}; - return worldPos; -} - -glm::ivec2 MapWindow::KnownMapSize::worldToScroll(const glm::vec2 worldPos_in) const -{ - auto worldPos = worldPos_in; - worldPos -= glm::vec2{min}; - worldPos.y = static_cast(size().y) - worldPos.y; // negate Y - const glm::ivec2 scrollPos{worldPos * static_cast(MapCanvas::SCROLL_SCALE)}; - return scrollPos; -} diff --git a/src/display/mapwindow.h b/src/display/mapwindow.h index 91a255980..30fb545d5 100644 --- a/src/display/mapwindow.h +++ b/src/display/mapwindow.h @@ -6,7 +6,8 @@ // Author: Nils Schimmelmann (Jahara) #include "../map/coordinate.h" -#include "mapcanvas.h" +#include "MapCanvasWindow.h" +#include "MapScroller.h" #include #include @@ -18,9 +19,8 @@ #include #include -class AudioHintWidget; class GameObserver; -class MapCanvas; +class MapCanvasWindow; class MapData; class Mmapper2Group; class PrespammedPath; @@ -30,7 +30,6 @@ class QMouseEvent; class QObject; class QResizeEvent; class QScrollBar; -class QTimer; class NODISCARD_QOBJECT MapWindow final : public QWidget { @@ -40,26 +39,18 @@ class NODISCARD_QOBJECT MapWindow final : public QWidget QPointer m_gridLayout; QPointer m_horizontalScrollBar; QPointer m_verticalScrollBar; - QPointer m_canvas; + QPointer m_canvas; QPointer m_canvasContainer; QPointer m_splashWidget; - QPointer m_audioHint; - QPointer m_scrollTimer; - int m_verticalScrollStep = 0; - int m_horizontalScrollStep = 0; private: - struct NODISCARD KnownMapSize final - { - glm::ivec3 min{0}; - glm::ivec3 max{0}; - - NODISCARD glm::ivec2 size() const { return glm::ivec2{max - min}; } - - NODISCARD glm::vec2 scrollToWorld(glm::ivec2 scrollPos) const; - NODISCARD glm::ivec2 worldToScroll(glm::vec2 worldPos) const; - - } m_knownMapSize; + // Scroll math (world<->scroll-unit conversion) and the continuous-scroll + // timer live in MapScroller (see MapScroller.h/.cpp). MapWindow owns + // the QScrollBar widgets themselves and the glue that reads/writes their + // values. + MapScroller *m_scroller = nullptr; + // Compact layout: drag-to-pan makes the bars dead weight on a phone. + bool m_scrollBarsSuppressed = false; public: explicit MapWindow(MapData &mapData, @@ -74,10 +65,11 @@ class NODISCARD_QOBJECT MapWindow final : public QWidget void keyReleaseEvent(QKeyEvent *event) override; void resizeEvent(QResizeEvent *event) override; - NODISCARD MapCanvas *getCanvas() const; + NODISCARD MapCanvasWindow *getCanvas() const; public: void updateScrollBars(); + void setScrollBarsSuppressed(bool suppressed); void setZoom(float zoom); NODISCARD float getZoom() const; void hideSplashImage(); @@ -94,10 +86,14 @@ public slots: void slot_centerOnWorldPos(glm::vec2 worldPos); void slot_mapMove(int dx, int dy); void slot_continuousScroll(int dx, int dy); - void slot_scrollTimerTimeout(); void slot_graphicsSettingsChanged(); void slot_zoomChanged(const float zoom) { emit sig_zoomChanged(zoom); } void slot_showTooltip(const QString &text, const QPoint &pos); void setCanvasEnabled(bool enabled); + +private slots: + // Connected to MapScroller::sig_continuousScrollStep(); applies one + // 100ms continuous-scroll tick to the scrollbars. + void slot_applyScrollStep(int hStep, int vStep); }; diff --git a/src/display/prespammedpath.h b/src/display/prespammedpath.h index 8b8c12324..b22edf1cc 100644 --- a/src/display/prespammedpath.h +++ b/src/display/prespammedpath.h @@ -10,7 +10,7 @@ #include #include -class MapCanvas; +class MapCanvasWindow; class MapData; class NODISCARD_QOBJECT PrespammedPath final : public QObject diff --git a/src/global/AnsiHtml.cpp b/src/global/AnsiHtml.cpp new file mode 100644 index 000000000..868aae4db --- /dev/null +++ b/src/global/AnsiHtml.cpp @@ -0,0 +1,320 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "AnsiHtml.h" + +#include "Consts.h" +#include "TextUtils.h" +#include "utils.h" + +#include +#include + +#include +#include +#include +#include +#include + +namespace { // anonymous + +void foreach_char(const QChar qchar, + const QStringView text, + const std::function &callback_qchar, + const std::function &callback_between) +{ + qsizetype pos = 0; + const qsizetype end = text.length(); + while (pos != end) { + const qsizetype qcharIndex = text.indexOf(qchar, pos); + if (qcharIndex < 0) { + callback_between(text.mid(pos)); + break; + } + + callback_between(text.mid(pos, qcharIndex - pos)); + callback_qchar(); + pos = qcharIndex + 1; + } +} + +void foreach_backspace(const QStringView text, + const std::function &callback_backspace, + const std::function &callback_between) +{ + foreach_char(char_consts::C_BACKSPACE, text, callback_backspace, callback_between); +} + +} // namespace + +namespace mmqt { + +void setAnsiDefaultFormat(QTextCharFormat &format, const AnsiHtmlDefaults &defaults) +{ + format.setBackground(defaults.defaultBg); + format.setForeground(defaults.defaultFg); + format.setFontWeight(QFont::Normal); + format.setFontUnderline(false); + format.setFontItalic(false); + format.setFontStrikeOut(false); +} + +RawAnsi updateAnsiFormat(QTextCharFormat &format, + const AnsiHtmlDefaults &defaults, + const RawAnsi &before, + RawAnsi updated) +{ + if (before == updated) { + return updated; + } + + if (updated == RawAnsi{}) { + setAnsiDefaultFormat(format, defaults); + return updated; + } + + const auto diff = before.getFlags() ^ updated.getFlags(); + + for (const AnsiStyleFlagEnum flag : diff) { + switch (flag) { + case AnsiStyleFlagEnum::Italic: + format.setFontItalic(updated.hasItalic()); + break; + case AnsiStyleFlagEnum::Underline: { + // QTextCharFormat doesn't support other underline styles. + format.setFontUnderline(updated.hasUnderline()); + using ULS = QTextCharFormat::UnderlineStyle; + const auto style = std::invoke([&updated]() -> QTextCharFormat::UnderlineStyle { + switch (updated.getUnderlineStyle()) { + case AnsiUnderlineStyleEnum::Dotted: + return ULS::DotLine; + case AnsiUnderlineStyleEnum::Curly: + return ULS::WaveUnderline; + case AnsiUnderlineStyleEnum::Dashed: + return ULS::DashUnderline; + case AnsiUnderlineStyleEnum::None: + case AnsiUnderlineStyleEnum::Normal: + case AnsiUnderlineStyleEnum::Double: // not supported by Qt + default: + return ULS::SingleUnderline; + } + }); + format.setUnderlineStyle(style); + break; + } + case AnsiStyleFlagEnum::Strikeout: + format.setFontStrikeOut(updated.hasStrikeout()); + break; + case AnsiStyleFlagEnum::Bold: + case AnsiStyleFlagEnum::Faint: + if (updated.hasBold()) { + format.setFontWeight(QFont::Bold); + } else if (updated.hasFaint()) { + format.setFontWeight(QFont::Light); + } else { + format.setFontWeight(QFont::Normal); + } + break; + case AnsiStyleFlagEnum::Blink: // ignored + case AnsiStyleFlagEnum::Reverse: // handled below + case AnsiStyleFlagEnum::Conceal: // handled below + break; + } + } + + const bool conceal = updated.hasConceal(); + const bool reverse = updated.hasReverse(); + const bool intense = updated.hasBold(); + + auto bg = mmqt::decodeColor(updated.bg, defaults.defaultBg, false); + auto fg = mmqt::decodeColor(updated.fg, defaults.defaultFg, intense); + auto ul = mmqt::decodeColor(updated.ul, defaults.getDefaultUl(), intense); + + if (reverse) { + // was swap(fg, bg) before we supported underline color + mmqt::reverseInPlace(fg); + mmqt::reverseInPlace(bg); + mmqt::reverseInPlace(ul); + } + + // Create a config setting and use it here if you really want to miss text that others will see! + bool userExplicitlyOptedInForConceal = false; + if (conceal && userExplicitlyOptedInForConceal) { + ul = fg = bg; + } + + format.setBackground(bg); + format.setForeground(fg); + format.setUnderlineColor(ul); + return updated; +} + +AnsiTextToDocument::AnsiTextToDocument(QTextDocument &document, + AnsiHtmlDefaults def, + const bool input_linkify) + : cursor{document.rootFrame()->firstCursorPosition()} + , format{cursor.charFormat()} + , defaults{std::move(def)} + , linkify{input_linkify} +{} + +void AnsiTextToDocument::init() +{ + QTextDocument &document = deref(cursor.document()); + QTextFrameFormat frameFormat = document.rootFrame()->frameFormat(); + frameFormat.setBackground(defaults.defaultBg); + frameFormat.setForeground(defaults.defaultFg); + document.rootFrame()->setFrameFormat(frameFormat); + + format = cursor.charFormat(); + setAnsiDefaultFormat(format, defaults); + cursor.setCharFormat(format); +} + +void AnsiTextToDocument::displayText(const QStringView input_str) +{ + // ANSI codes are formatted as the following: + // escape + [ + n1 (+ n2) + m + static const QRegularExpression ansi_regex{R"regex(\x1B[^A-Za-z\x1B]*[A-Za-z]?)regex"}; + static const QRegularExpression url_regex{ + R"regex(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))regex"}; + + // REVISIT: should we even bother supporting backspaces? + // + // QTextEdit is not a terminal, so it doesn't really have the concept of a mutable text buffer + // where you can backspace and then later overwrite the previous letter with something else. + // + // (Yes, technically we could abuse the cursor this to achieve a similar result, but the + // cursor is used in multiple functions, so that might be too fragile.) + // + // Current solution: simulate the backspace operation by adding a backspace character to the + // buffer, and then later remove the backspace and previous character. + // + // MUME could send a telnet event that signals that the player is waiting, + // and then we could display the waiting state some other way. + // + // Or we could just ignore the backspaces and display "\|/-" instead of the animation. + // + // It might also be worth considering using an emoji or an icon instead of C_BACKSPACE. + static const volatile bool allow_backspaces = true; + + // note: debug_backspaces effectively implies allow_backspaces == false, + // because writes "(Backspace)" instead of a backspace character, and then it leaves both + // "(Backspace)" and the letter that would have been removed by the backspace operation. + static const volatile bool debug_backspaces = false; + + auto try_remove_backspace = [this]() { + if (!allow_backspaces) { + return; + } + + const auto block = cursor.block(); + if (!block.isValid() || cursor.block().length() == 0) { + return; + } + + const auto text = block.text(); + if (text.isNull() || text.isEmpty() || text.back() != char_consts::C_BACKSPACE) { + return; + } + + cursor.deletePreviousChar(); + if (block.length() > 0) { + cursor.deletePreviousChar(); + } + }; + + auto add_raw = [this, &try_remove_backspace](const QStringView text, + const QTextCharFormat &withFmt) { + try_remove_backspace(); + cursor.insertText(text.toString(), withFmt); + }; + + auto try_add_backspace = [this, &add_raw]() { + if (debug_backspaces) { + add_raw(u"(BACKSPACE)", {}); + return; + } + + if (!allow_backspaces || cursor.position() < 1) { + return; + } + + const auto block = cursor.block(); + if (!block.isValid() && block.length() < 1) { + return; + } + + const auto text = block.text(); + if (text.isNull() || text.isEmpty()) { + return; + } + + add_raw(mmqt::QS_BACKSPACE, {}); + }; + + auto add_formatted = [this, &add_raw, &try_remove_backspace](const QStringView text) { + if (!linkify) { + add_raw(text, format); + return; + } + + mmqt::foreach_regex( + url_regex, + text, + [this, &try_remove_backspace](const QStringView url) { + const auto s = url.toString(); + // TODO: override the document's CSS for URLs + const auto link + = QString( + R"(%2)") + .arg(QString::fromUtf8(QUrl::fromUserInput(s).toEncoded()), + s.toHtmlEscaped()); + + try_remove_backspace(); + cursor.insertHtml(link); + }, + [this, &add_raw](const QStringView non_url) { add_raw(non_url, format); }); + }; + + // Display text using a cursor + mmqt::foreach_regex( + ansi_regex, + input_str, + [this, &add_raw](const QStringView ansiStr) { + assert(!ansiStr.isEmpty() && ansiStr.front() == char_consts::C_ESC); + if (mmqt::isAnsiColor(ansiStr)) { + if (auto optNewColor = mmqt::parseAnsiColor(currentAnsi, ansiStr)) { + currentAnsi = updateAnsiFormat(format, defaults, currentAnsi, *optNewColor); + } + } else if (mmqt::isAnsiEraseLine(ansiStr)) { + cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 1); + cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); + cursor.removeSelectedText(); + } else { + add_raw(u"", {}); + if (ansiStr.length() > 1) { + add_raw(ansiStr.mid(1), format); + } + } + }, + [&try_add_backspace, &add_formatted](const QStringView textStr) { + foreach_backspace(textStr, try_add_backspace, add_formatted); + }); +} + +void AnsiTextToDocument::limitScrollback(const int lineLimit) +{ + QTextDocument &document = deref(cursor.document()); + const int lineCount = document.lineCount(); + if (lineCount > lineLimit) { + const int trimLines = lineCount - lineLimit; + cursor.movePosition(QTextCursor::Start); + cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor, trimLines); + cursor.removeSelectedText(); + cursor.movePosition(QTextCursor::End); + } +} + +} // namespace mmqt diff --git a/src/global/AnsiHtml.h b/src/global/AnsiHtml.h new file mode 100644 index 000000000..c68d4b7a7 --- /dev/null +++ b/src/global/AnsiHtml.h @@ -0,0 +1,58 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "AnsiTextUtils.h" +#include "macros.h" + +#include + +#include +#include +#include +#include +#include + +class QTextDocument; + +namespace mmqt { + +// Widget-free equivalent of client/displaywidget.h's FontDefaults, containing only the +// colors needed to render ANSI text; no QFont, and no dependency on getConfig(). +struct NODISCARD AnsiHtmlDefaults final +{ + QColor defaultBg = Qt::black; + QColor defaultFg = Qt::lightGray; + std::optional defaultUl; + + NODISCARD QColor getDefaultUl() const { return defaultUl.value_or(defaultFg); } +}; + +void setAnsiDefaultFormat(QTextCharFormat &format, const AnsiHtmlDefaults &defaults); + +NODISCARD RawAnsi updateAnsiFormat(QTextCharFormat &format, + const AnsiHtmlDefaults &defaults, + const RawAnsi &before, + RawAnsi updated); + +// Renders ANSI SGR text into a QTextDocument via a cursor positioned at the document's end. +// This is the widget-free core that client/displaywidget.h's AnsiTextHelper delegates to. +struct NODISCARD AnsiTextToDocument final +{ + QTextCursor cursor; + QTextCharFormat format; + AnsiHtmlDefaults defaults; + RawAnsi currentAnsi; + bool linkify = true; + + explicit AnsiTextToDocument(QTextDocument &document, + AnsiHtmlDefaults def, + bool input_linkify = true); + + void init(); + void displayText(QStringView str); + void limitScrollback(int lineLimit); +}; + +} // namespace mmqt diff --git a/src/global/AnsiTextUtils.cpp b/src/global/AnsiTextUtils.cpp index 0283ecb0b..c443abb22 100644 --- a/src/global/AnsiTextUtils.cpp +++ b/src/global/AnsiTextUtils.cpp @@ -1076,6 +1076,40 @@ QColor mmqt::ansi256toRgb(const int ansi) return QColor{c.r, c.g, c.b}; } +QColor mmqt::decodeColor(const AnsiColorRGB var) +{ + return QColor::fromRgb(var.r, var.g, var.b); +} + +QColor mmqt::decodeColor(AnsiColor256 var, const bool intense) +{ + if (var.color < 8 && intense) { + var.color += 8; + } + + return mmqt::ansi256toRgb(var.color); +} + +QColor mmqt::decodeColor(const AnsiColorVariant var, const QColor defaultColor, const bool intense) +{ + if (var.hasRGB()) { + return mmqt::decodeColor(var.getRGB()); + } + + if (var.has256()) { + return mmqt::decodeColor(var.get256(), intense); + } + + return defaultColor; +} + +void mmqt::reverseInPlace(QColor &color) +{ + color.setRed(255 - color.red()); + color.setGreen(255 - color.green()); + color.setBlue(255 - color.blue()); +} + int rgbToAnsi256(int r, int g, int b) { // REVISIT: check for exact match to color table? diff --git a/src/global/AnsiTextUtils.h b/src/global/AnsiTextUtils.h index c6a3eba2e..ff95fbb35 100644 --- a/src/global/AnsiTextUtils.h +++ b/src/global/AnsiTextUtils.h @@ -1130,6 +1130,18 @@ NODISCARD TextBuffer normalizeAnsi(AnsiSupportFlags supportFlags, const QString NODISCARD QColor toQColor(AnsiColor16Enum ansi); NODISCARD QColor ansi256toRgb(int ansi); NODISCARD QString rgbToAnsi256String(const QColor &rgb, AnsiColor16LocationEnum type); + +// Decode a single ANSI RGB triple to a QColor. +NODISCARD QColor decodeColor(AnsiColorRGB var); +// Decode an ANSI 256-color index to a QColor; if intense and the index is one of the +// low 8 colors (0..7), it's promoted to the corresponding high-intensity color (8..15). +NODISCARD QColor decodeColor(AnsiColor256 var, bool intense); +// Decode an AnsiColorVariant (default/256/RGB) to a QColor, falling back to defaultColor +// when the variant has no explicit color. +NODISCARD QColor decodeColor(AnsiColorVariant var, QColor defaultColor, bool intense); + +// Invert a color in-place (used to implement ANSI "reverse video"). +void reverseInPlace(QColor &color); } // namespace mmqt NODISCARD bool containsAnsi(std::string_view sv); diff --git a/src/global/ConfigEnums.h b/src/global/ConfigEnums.h index 1abfa034e..ba39c5b7f 100644 --- a/src/global/ConfigEnums.h +++ b/src/global/ConfigEnums.h @@ -8,6 +8,10 @@ enum class NODISCARD AutoLoggerEnum { KeepForever, DeleteDays, DeleteSize }; enum class NODISCARD CharacterEncodingEnum { LATIN1, UTF8, ASCII }; enum class NODISCARD EnvironmentEnum { Unknown, Env32Bit, Env64Bit }; enum class NODISCARD MapModeEnum { PLAY, MAP, OFFLINE }; +// How the game is played: the Client Panel asks each time, connects its +// built-in client right away, or waits for an external client on the proxy +// port. The web build has only the built-in client. +enum class NODISCARD GameClientEnum { ASK, BUILT_IN, EXTERNAL }; enum class NODISCARD ThemeEnum { System, Dark, Light }; enum class NODISCARD PackageEnum { Source, Deb, Dmg, Nsis, AppImage, AppX, Flatpak, Snap, Wasm }; enum class NODISCARD PlatformEnum { Unknown, Windows, Mac, Linux, Wasm }; diff --git a/src/global/window_utils.cpp b/src/global/window_utils.cpp index b4ab2cd65..b46dcf221 100644 --- a/src/global/window_utils.cpp +++ b/src/global/window_utils.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -45,6 +46,20 @@ void mmqt::setWindowTitle2(QWidget &widget, const QString &program, const QStrin } } +void mmqt::showFittedToScreen(QWidget &widget) +{ + const QScreen *const screen = widget.screen(); + if (screen != nullptr) { + const QSize available = screen->availableGeometry().size(); + const QSize wanted = widget.sizeHint(); + if (wanted.width() > available.width() || wanted.height() > available.height()) { + widget.showMaximized(); + return; + } + } + widget.show(); +} + namespace { QMessageBox &showMessageBox(QWidget *const parent, const QMessageBox::Icon icon, diff --git a/src/global/window_utils.h b/src/global/window_utils.h index 0da309dda..2073e1770 100644 --- a/src/global/window_utils.h +++ b/src/global/window_utils.h @@ -15,6 +15,9 @@ namespace mmqt { // recursively disconnect all children extern void rdisconnect(QObject *obj); extern void setWindowTitle2(QWidget &widget, const QString &program, const QString &title); +// Shows a window maximized when its preferred size would not fit the +// screen it is on (phone-sized screens), and normally otherwise. +extern void showFittedToScreen(QWidget &widget); // Non-blocking replacements for the QMessageBox::information/warning/critical // statics: the box is window-modal, deletes itself when closed, and never // runs a nested event loop (which is unavailable on wasm without Asyncify). diff --git a/src/group/GroupModel.cpp b/src/group/GroupModel.cpp new file mode 100644 index 000000000..382a4f2a8 --- /dev/null +++ b/src/group/GroupModel.cpp @@ -0,0 +1,722 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "GroupModel.h" + +#include "../configuration/configuration.h" +#include "../global/Color.h" +#include "../global/Timer.h" +#include "../global/utils.h" +#include "../map/roomid.h" +#include "CGroupChar.h" +#include "enums.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +static constexpr const char *GROUP_MIME_TYPE = "application/vnd.mm_groupchar.row"; + +namespace { // anonymous + +NODISCARD static const char *getColumnFriendlyName(const ColumnTypeEnum column) +{ +#define X_DECL_COLUMNTYPE(UPPER_CASE, lower_case, CamelCase, friendly) \ + case ColumnTypeEnum::UPPER_CASE: \ + return friendly; + + switch (column) { + XFOREACH_COLUMNTYPE(X_DECL_COLUMNTYPE) + default: + qWarning() << "Unsupported column type" << static_cast(column); + return ""; + } +#undef X_DECL_COLUMNTYPE +} + +// Same "lower_case" token used by Filenames.cpp's getFilenameSuffix(); see the +// image://groupicons/... URL scheme documented in GroupModel.h. +NODISCARD static QString getPositionToken(const CharacterPositionEnum position) +{ +#define X_CASE(UPPER_CASE, lower_case, CamelCase, friendly) \ + case CharacterPositionEnum::UPPER_CASE: \ + return QStringLiteral(#lower_case); + switch (position) { + XFOREACH_CHARACTER_POSITION(X_CASE) + } + return QString(); +#undef X_CASE +} +NODISCARD static QString getAffectToken(const CharacterAffectEnum affect) +{ +#define X_CASE(UPPER_CASE, lower_case, CamelCase, friendly) \ + case CharacterAffectEnum::UPPER_CASE: \ + return QStringLiteral(#lower_case); + switch (affect) { + XFOREACH_CHARACTER_AFFECT(X_CASE) + } + return QString(); +#undef X_CASE +} + +NODISCARD static double computeRatio(const int cur, const int max) +{ + if (max <= 0) { + return 0.0; + } + return std::clamp(static_cast(cur) / static_cast(max), 0.0, 1.0); +} + +NODISCARD static QStringList buildStateIcons(const CGroupChar &character) +{ + QStringList icons; + // Mirrors GroupImageCache's invert condition in groupwidget.cpp. + const bool invert = mmqt::textColor(character.getColor()) == Qt::white; + const QString variant = invert ? QStringLiteral("inv") : QStringLiteral("std"); + + const CharacterPositionEnum position = character.getPosition(); + if (position != CharacterPositionEnum::UNDEFINED) { + icons << QString("image://groupicons/%1/position/%2") + .arg(variant, getPositionToken(position)); + } + for (const CharacterAffectEnum affect : ALL_CHARACTER_AFFECTS) { + if (character.getAffects().contains(affect)) { + icons << QString("image://groupicons/%1/affect/%2").arg(variant, getAffectToken(affect)); + } + } + return icons; +} +} // namespace + +GroupProxyModel::GroupProxyModel(QObject *const parent) + : QSortFilterProxyModel(parent) +{} + +GroupProxyModel::~GroupProxyModel() = default; + +void GroupProxyModel::refresh() +{ + // Triggers re-filter and re-sort + invalidate(); +} + +SharedGroupChar GroupProxyModel::getCharacterFromSource(const QModelIndex &source_index) const +{ + const GroupModel *srcModel = qobject_cast(sourceModel()); + if (!srcModel || !source_index.isValid()) { + return nullptr; + } + + return srcModel->getCharacter(source_index.row()); +} + +bool GroupProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +{ + if (!getConfig().groupManager.npcHide) { + return true; + } + + QModelIndex sourceIndex = sourceModel()->index(source_row, 0, source_parent); + SharedGroupChar character = getCharacterFromSource(sourceIndex); + if (character && character->isNpc()) { + return false; + } + + return true; +} + +GroupStateData::GroupStateData(const QColor &color, + const CharacterPositionEnum position, + const CharacterAffectFlags affects) + : m_color(color) + , m_position(position) + , m_affects(affects) +{ + if (position != CharacterPositionEnum::UNDEFINED) { + ++m_count; + } + // Increment imageCount for each active affect + for (const CharacterAffectEnum affect : ALL_CHARACTER_AFFECTS) { + if (affects.contains(affect)) { + ++m_count; + } + } + // Users spam search/reveal/flush so pad an extra position to reduce eye strain + if (!affects.contains(CharacterAffectEnum::WAITING)) { + ++m_count; + } +} + +GroupModel::GroupModel(QObject *const parent) + : QAbstractTableModel(parent) +{} + +void GroupModel::setCharacters(const GroupVector &newGameChars) +{ + DECL_TIMER(t, __FUNCTION__); + + std::unordered_set newGameCharIds; + newGameCharIds.reserve(newGameChars.size()); + for (const auto &pGameChar : newGameChars) { + const auto &gameChar = deref(pGameChar); + newGameCharIds.insert(gameChar.getId()); + } + + GroupVector resultingCharacterList; + resultingCharacterList.reserve(m_characters.size() + newGameChars.size()); + + // Temporary vectors to hold truly new players, NPCs, and all truly new characters + GroupVector trulyNewPlayers; + trulyNewPlayers.reserve(newGameChars.size()); + GroupVector trulyNewNpcs; + trulyNewNpcs.reserve(newGameChars.size()); + GroupVector allTrulyNewCharsInOriginalOrder; + allTrulyNewCharsInOriginalOrder.reserve(newGameChars.size()); + + // Preserve existing characters + std::unordered_set existingIds; + existingIds.reserve(m_characters.size()); + for (const auto &pExistingChar : m_characters) { + const auto &existingChar = deref(pExistingChar); + existingIds.insert(existingChar.getId()); + if (newGameCharIds.count(existingChar.getId())) { + resultingCharacterList.push_back(pExistingChar); + } + } + + // Identify truly new characters and categorize them as NPC or player + for (const auto &pGameChar : newGameChars) { + const auto &gameChar = deref(pGameChar); + if (existingIds.find(gameChar.getId()) == existingIds.end()) { + allTrulyNewCharsInOriginalOrder.push_back(pGameChar); + if (gameChar.isNpc()) { + trulyNewNpcs.push_back(pGameChar); + } else { + trulyNewPlayers.push_back(pGameChar); + } + } + } + + // Insert the newly identified characters into the resulting list based on configuration. + if (getConfig().groupManager.npcSortBottom) { + // Find the insertion point for new players: before the first NPC in the preserved list. + auto itPlayerInsertPos = resultingCharacterList.begin(); + while (itPlayerInsertPos != resultingCharacterList.end()) { + if (*itPlayerInsertPos && (*itPlayerInsertPos)->isNpc()) { + break; + } + ++itPlayerInsertPos; + } + + // Insert truly new players at the determined position. + if (!trulyNewPlayers.empty()) { + resultingCharacterList.insert(itPlayerInsertPos, + trulyNewPlayers.begin(), + trulyNewPlayers.end()); + } + // Insert truly new NPCs at the end of the list. + if (!trulyNewNpcs.empty()) { + resultingCharacterList.insert(resultingCharacterList.end(), + trulyNewNpcs.begin(), + trulyNewNpcs.end()); + } + } else { + // If no special NPC sorting, just append all truly new characters in their original order. + if (!allTrulyNewCharsInOriginalOrder.empty()) { + resultingCharacterList.insert(resultingCharacterList.end(), + allTrulyNewCharsInOriginalOrder.begin(), + allTrulyNewCharsInOriginalOrder.end()); + } + } + + beginResetModel(); + m_characters = std::move(resultingCharacterList); + endResetModel(); + + updateAnyMana(); +} + +int GroupModel::findIndexById(const GroupId charId) const +{ + if (charId == INVALID_GROUPID) { + return -1; + } + auto it = std::find_if(m_characters.begin(), + m_characters.end(), + [charId](const SharedGroupChar &c) { return c && c->getId() == charId; }); + if (it != m_characters.end()) { + return static_cast(std::distance(m_characters.begin(), it)); + } + return -1; +} + +void GroupModel::insertCharacter(const SharedGroupChar &newCharacter) +{ + assert(newCharacter); + if (newCharacter->getId() == INVALID_GROUPID) { + return; + } + + auto calculateInsertIndex = [this, &newCharacter]() -> int { + if (getConfig().groupManager.npcSortBottom && !newCharacter->isNpc()) { + auto it = std::find_if(m_characters.begin(), + m_characters.end(), + [](const SharedGroupChar &c) { return c && c->isNpc(); }); + return static_cast(std::distance(m_characters.begin(), it)); + } + return static_cast(m_characters.size()); + }; + + const int newIndex = calculateInsertIndex(); + assert(newIndex >= 0 && newIndex <= static_cast(m_characters.size())); + + beginInsertRows(QModelIndex(), newIndex, newIndex); + m_characters.insert(m_characters.begin() + newIndex, newCharacter); + endInsertRows(); + + updateAnyMana(); +} + +void GroupModel::removeCharacterById(const GroupId charId) +{ + const int index = findIndexById(charId); + if (index == -1) { + return; + } + + beginRemoveRows(QModelIndex(), index, index); + m_characters.erase(m_characters.begin() + index); + endRemoveRows(); + + updateAnyMana(); +} + +void GroupModel::updateCharacter(const SharedGroupChar &updatedCharacter) +{ + assert(updatedCharacter); + const GroupId charId = updatedCharacter->getId(); + const int index = findIndexById(charId); + if (index == -1) { + insertCharacter(updatedCharacter); + return; + } + + SharedGroupChar &existingChar = m_characters[static_cast(index)]; + existingChar = updatedCharacter; + + // Empty role list: refresh every role, since consumers bind to + // individual roles rather than only the fixed set GroupWidget's + // QTableView columns use. + emit dataChanged(this->index(index, 0), this->index(index, columnCount(QModelIndex()) - 1), {}); + + updateAnyMana(); +} + +void GroupModel::updateAnyMana() +{ + bool any = false; + for (const auto &character : m_characters) { + if (character && (character->getMana() > 0 || character->getMaxMana() > 0)) { + any = true; + break; + } + } + if (any != m_anyMana) { + m_anyMana = any; + emit sig_anyManaChanged(); + } +} + +SharedGroupChar GroupModel::getCharacter(int row) const +{ + if (row >= 0 && row < static_cast(m_characters.size())) { + return m_characters.at(static_cast(row)); + } + return nullptr; +} + +void GroupModel::resetModel() +{ + beginResetModel(); + endResetModel(); +} + +int GroupModel::rowCount(const QModelIndex & /* parent */) const +{ + return static_cast(m_characters.size()); +} + +int GroupModel::columnCount(const QModelIndex & /* parent */) const +{ + return GROUP_COLUMN_COUNT; +} + +NODISCARD static QString getPrettyName(const CharacterPositionEnum position) +{ +#define X_CASE(UPPER_CASE, lower_case, CamelCase, friendly) \ + do { \ + case CharacterPositionEnum::UPPER_CASE: \ + return QStringLiteral(friendly); \ + } while (false); + switch (position) { + XFOREACH_CHARACTER_POSITION(X_CASE) + } + return QString::asprintf("(CharacterPositionEnum)%d", static_cast(position)); +#undef X_CASE +} +NODISCARD static QString getPrettyName(const CharacterAffectEnum affect) +{ +#define X_CASE(UPPER_CASE, lower_case, CamelCase, friendly) \ + do { \ + case CharacterAffectEnum::UPPER_CASE: \ + return QStringLiteral(friendly); \ + } while (false); + switch (affect) { + XFOREACH_CHARACTER_AFFECT(X_CASE) + } + return QString::asprintf("(CharacterAffectEnum)%d", static_cast(affect)); +#undef X_CASE +} + +QVariant GroupModel::dataForCharacter(const SharedGroupChar &pCharacter, + const ColumnTypeEnum column, + const int role) const +{ + const CGroupChar &character = deref(pCharacter); + + const auto formatStat = [&character](int numerator, int denomenator) -> QString { + if (numerator == 0 && denomenator == 0) { + return QLatin1String(""); + } + + if (character.getType() == CharacterTypeEnum::NPC) { + const double pct = denomenator > 0 ? static_cast(numerator) / denomenator : 0.0; + return QString("%1%").arg(static_cast(std::round(pct * 100.0))); + } + + return QString("%1 / %2").arg(numerator).arg(denomenator); + }; + + // Map column to data + switch (role) { + case Qt::DisplayRole: + switch (column) { + case ColumnTypeEnum::NAME: + if (character.getLabel().isEmpty() + || character.getName().getStdStringViewUtf8() + == character.getLabel().getStdStringViewUtf8()) { + return character.getName().toQString(); + } else { + return QString("%1 (%2)").arg(character.getName().toQString(), + character.getLabel().toQString()); + } + case ColumnTypeEnum::HP: + return formatStat(character.getHits(), character.getMaxHits()); + case ColumnTypeEnum::MANA: + return formatStat(character.getMana(), character.getMaxMana()); + case ColumnTypeEnum::MOVES: + return formatStat(character.getMoves(), character.getMaxMoves()); + case ColumnTypeEnum::STATE: + return QVariant::fromValue(GroupStateData(character.getColor(), + character.getPosition(), + character.getAffects())); + case ColumnTypeEnum::ROOM_NAME: + if (character.getRoomName().isEmpty()) { + return QStringLiteral("Somewhere"); + } else { + return character.getRoomName().toQString(); + } + default: + qWarning() << "Unsupported column" << static_cast(column); + break; + } + break; + + case Qt::BackgroundRole: + return QVariant(); + + case Qt::ForegroundRole: + return QVariant(); + + case Qt::TextAlignmentRole: + if (column != ColumnTypeEnum::NAME && column != ColumnTypeEnum::ROOM_NAME) { + // NOTE: There's no QVariant(AlignmentFlag) constructor. + return static_cast(Qt::AlignCenter); + } + break; + + case Qt::ToolTipRole: { + switch (column) { + case ColumnTypeEnum::HP: + case ColumnTypeEnum::MANA: + case ColumnTypeEnum::MOVES: { + const int cur = (column == ColumnTypeEnum::HP) ? character.getHits() + : (column == ColumnTypeEnum::MANA) ? character.getMana() + : character.getMoves(); + const int max = (column == ColumnTypeEnum::HP) ? character.getMaxHits() + : (column == ColumnTypeEnum::MANA) ? character.getMaxMana() + : character.getMaxMoves(); + if (max > 0) { + const double pct = static_cast(cur) / max; + return QString("%1%").arg(static_cast(std::round(pct * 100.0))); + } + return QVariant(); + } + case ColumnTypeEnum::STATE: { + QString prettyName; + prettyName += getPrettyName(character.getPosition()); + for (const CharacterAffectEnum affect : ALL_CHARACTER_AFFECTS) { + if (character.getAffects().contains(affect)) { + prettyName.append(QStringLiteral(", ")).append(getPrettyName(affect)); + } + } + return prettyName; + } + case ColumnTypeEnum::NAME: + break; + case ColumnTypeEnum::ROOM_NAME: + if (character.getServerId() != INVALID_SERVER_ROOMID) { + return QString("%1").arg(character.getServerId().asUint32()); + } + break; + } + break; + } + + default: + break; + } + + return QVariant(); +} + +QVariant GroupModel::roleDataForCharacter(const SharedGroupChar &pCharacter, const int role) const +{ + const CGroupChar &character = deref(pCharacter); + + switch (role) { + case NameRole: + return dataForCharacter(pCharacter, ColumnTypeEnum::NAME, Qt::DisplayRole); + case CharColorRole: + return character.getColor(); + case TextColorRole: + return mmqt::textColor(character.getColor()); + case HpTextRole: + return dataForCharacter(pCharacter, ColumnTypeEnum::HP, Qt::DisplayRole); + case ManaTextRole: + // Mirrors GroupDelegate::paint()'s MANA "Hidden State" branch, which + // always draws "--" once maxmana <= 0 (regardless of the formatted text). + if (character.getMaxMana() <= 0) { + return QStringLiteral("--"); + } + return dataForCharacter(pCharacter, ColumnTypeEnum::MANA, Qt::DisplayRole); + case MovesTextRole: + return dataForCharacter(pCharacter, ColumnTypeEnum::MOVES, Qt::DisplayRole); + case HpRatioRole: + return computeRatio(character.getHits(), character.getMaxHits()); + case ManaRatioRole: + return computeRatio(character.getMana(), character.getMaxMana()); + case MovesRatioRole: + return computeRatio(character.getMoves(), character.getMaxMoves()); + case HpLowRole: + // Threshold matches GroupDelegate::paint()'s HP pulse/red-bar cutoff (pct < 0.3). + // Like the delegate's pulse decision, an unknown max (max <= 0) is NOT low. + return character.getMaxHits() > 0 + && computeRatio(character.getHits(), character.getMaxHits()) < 0.30; + case MovesLowRole: + // Threshold matches GroupDelegate::paint()'s Moves pulse cutoff (pct < 0.15). + // Like the delegate's pulse decision, an unknown max (max <= 0) is NOT low. + return character.getMaxMoves() > 0 + && computeRatio(character.getMoves(), character.getMaxMoves()) < 0.15; + case ManaHiddenRole: + return character.getMaxMana() <= 0; + case StateIconsRole: + return buildStateIcons(character); + case StateTipRole: + return dataForCharacter(pCharacter, ColumnTypeEnum::STATE, Qt::ToolTipRole); + case HpTipRole: + return dataForCharacter(pCharacter, ColumnTypeEnum::HP, Qt::ToolTipRole); + case ManaTipRole: + return dataForCharacter(pCharacter, ColumnTypeEnum::MANA, Qt::ToolTipRole); + case MovesTipRole: + return dataForCharacter(pCharacter, ColumnTypeEnum::MOVES, Qt::ToolTipRole); + case RoomNameRole: + return dataForCharacter(pCharacter, ColumnTypeEnum::ROOM_NAME, Qt::DisplayRole); + case IsYouRole: + return character.isYou(); + case IsNpcRole: + return character.isNpc(); + case CanCenterRole: + return character.isYou() || character.getServerId() != INVALID_SERVER_ROOMID; + default: + return QVariant(); + } +} + +QVariant GroupModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) { + return QVariant(); + } + + if (index.row() >= 0 && index.row() < static_cast(m_characters.size())) { + const SharedGroupChar &character = m_characters.at(static_cast(index.row())); + // Custom roles are read from column 0, so those roles are answered + // independently of index.column(); the standard Qt roles keep the + // per-column behavior the QTableView-based GroupWidget relies on. + if (role >= Qt::UserRole + 1) { + return roleDataForCharacter(character, role); + } + return dataForCharacter(character, static_cast(index.column()), role); + } + + return QVariant(); +} + +QVariant GroupModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + switch (role) { + case Qt::DisplayRole: + if (orientation == Qt::Orientation::Horizontal) { + return getColumnFriendlyName(static_cast(section)); + } + break; + } + return QVariant(); +} + +QHash GroupModel::roleNames() const +{ + QHash roles = QAbstractTableModel::roleNames(); + roles[Qt::DisplayRole] = "display"; + roles[Qt::ToolTipRole] = "toolTip"; + roles[NameRole] = "name"; + roles[CharColorRole] = "charColor"; + roles[TextColorRole] = "textColor"; + roles[HpTextRole] = "hpText"; + roles[ManaTextRole] = "manaText"; + roles[MovesTextRole] = "movesText"; + roles[HpRatioRole] = "hpRatio"; + roles[ManaRatioRole] = "manaRatio"; + roles[MovesRatioRole] = "movesRatio"; + roles[HpLowRole] = "hpLow"; + roles[MovesLowRole] = "movesLow"; + roles[ManaHiddenRole] = "manaHidden"; + roles[StateIconsRole] = "stateIcons"; + roles[StateTipRole] = "stateTip"; + roles[HpTipRole] = "hpTip"; + roles[ManaTipRole] = "manaTip"; + roles[MovesTipRole] = "movesTip"; + roles[RoomNameRole] = "roomName"; + roles[IsYouRole] = "isYou"; + roles[IsNpcRole] = "isNpc"; + roles[CanCenterRole] = "canCenter"; + return roles; +} + +Qt::ItemFlags GroupModel::flags(const QModelIndex &index) const +{ + if (!index.isValid()) { + return Qt::NoItemFlags; + } + return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; +} + +Qt::DropActions GroupModel::supportedDropActions() const +{ + return Qt::MoveAction; +} + +QStringList GroupModel::mimeTypes() const +{ + QStringList types; + types << GROUP_MIME_TYPE; + return types; +} + +QMimeData *GroupModel::mimeData(const QModelIndexList &indexes) const +{ + QMimeData *mimeDataObj = new QMimeData(); + QByteArray encodedData; + QDataStream stream(&encodedData, QIODevice::WriteOnly); + if (!indexes.isEmpty() && indexes.first().isValid()) { + stream << indexes.first().row(); + } + mimeDataObj->setData(GROUP_MIME_TYPE, encodedData); + return mimeDataObj; +} + +bool GroupModel::dropMimeData( + const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) +{ + if (action == Qt::IgnoreAction) { + return true; + } + if (!data->hasFormat(GROUP_MIME_TYPE) || column > 0) { + return false; + } + + QByteArray encodedData = data->data(GROUP_MIME_TYPE); + QDataStream stream(&encodedData, QIODevice::ReadOnly); + if (stream.atEnd()) { + return false; + } + int sourceRow; + stream >> sourceRow; + + int targetInsertionIndex; + if (parent.isValid()) { + targetInsertionIndex = parent.row(); + } else if (row != -1) { + targetInsertionIndex = row; + } else { + targetInsertionIndex = static_cast(m_characters.size()); + } + + return moveRow(sourceRow, targetInsertionIndex); +} + +bool GroupModel::moveRow(const int from, int to) +{ + const int size = static_cast(m_characters.size()); + if (from < 0 || from >= size) { + return false; + } + if (to < 0 || to > size) { + return false; + } + + // No-op: dropping onto the same position, or immediately after itself. + if (from == to || to == from + 1) { + return false; + } + + if (!beginMoveRows(QModelIndex(), from, from, QModelIndex(), to)) { + return false; + } + + SharedGroupChar movedChar = m_characters[static_cast(from)]; + m_characters.erase(m_characters.begin() + from); + + // beginMoveRows()'s destinationChild is expressed in terms of the row indices + // *before* removal; once the source row is erased, every index after it shifts + // down by one, so the insertion point needs the same +1 adjustment. + int actualInsertionIdx = to; + if (from < to) { + actualInsertionIdx--; + } + actualInsertionIdx = std::clamp(actualInsertionIdx, 0, static_cast(m_characters.size())); + + m_characters.insert(m_characters.begin() + actualInsertionIdx, movedChar); + + endMoveRows(); + return true; +} diff --git a/src/group/GroupModel.h b/src/group/GroupModel.h new file mode 100644 index 000000000..40f7c4222 --- /dev/null +++ b/src/group/GroupModel.h @@ -0,0 +1,175 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "CGroupChar.h" +#include "mmapper2character.h" + +#include +#include +#include +#include +#include + +class QObject; +class QPainter; +class QRect; + +class NODISCARD_QOBJECT GroupProxyModel final : public QSortFilterProxyModel +{ + Q_OBJECT + +public: + explicit GroupProxyModel(QObject *parent = nullptr); + ~GroupProxyModel() final; + + void refresh(); + +protected: + bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; + +private: + SharedGroupChar getCharacterFromSource(const QModelIndex &source_index) const; +}; + +// NOTE: paint() is implemented in groupwidget.cpp, since it depends on the +// GroupImageCache/getImage() helpers that remain there for the QTableView-based +// GroupDelegate. GroupStateData itself is just a plain-data snapshot produced by +// GroupModel::data() for ColumnTypeEnum::STATE. +class NODISCARD GroupStateData final +{ +private: + QColor m_color; + CharacterPositionEnum m_position = CharacterPositionEnum::UNDEFINED; + CharacterAffectFlags m_affects; + int m_count = 0; + int m_height = 23; + +public: + GroupStateData() = default; + explicit GroupStateData(const QColor &color, + CharacterPositionEnum position, + CharacterAffectFlags affects); + +public: + void paint(QPainter *pPainter, const QRect &rect); + NODISCARD int getWidth() const { return static_cast(m_count) * m_height; } +}; +Q_DECLARE_METATYPE(GroupStateData) + +#define XFOREACH_COLUMNTYPE(X) \ + X(NAME, name, Name, "Name") \ + X(HP, hp, Hp, "HP") \ + X(MANA, mana, Mana, "Mana") \ + X(MOVES, moves, Moves, "Moves") \ + X(STATE, state, State, "State") \ + X(ROOM_NAME, room_name, RoomName, "Room Name") \ + /* define column types above */ + +#define X_COUNT(UPPER_CASE, lower_case, CamelCase, friendly) +1 +static constexpr const int GROUP_COLUMN_COUNT = XFOREACH_COLUMNTYPE(X_COUNT); +#undef X_COUNT + +enum class NODISCARD ColumnTypeEnum { +#define X_DECL_COLUMNTYPE(UPPER_CASE, lower_case, CamelCase, friendly) UPPER_CASE, + XFOREACH_COLUMNTYPE(X_DECL_COLUMNTYPE) +#undef X_DECL_COLUMNTYPE +}; + +static_assert(GROUP_COLUMN_COUNT == static_cast(ColumnTypeEnum::ROOM_NAME) + 1, "# of columns"); + +// Role URL scheme for the "stateIcons" role (Role::StateIconsRole below): +// image://groupicons/// +// selects the standard or inverted (white-icon) variant, mirroring +// GroupImageCache's invert condition: mmqt::textColor(charColor) == Qt::white. +// is the same "lower_case" token used by +// Filenames.cpp's getFilenameSuffix() (e.g. "standing", "sanctuary"). +class NODISCARD_QOBJECT GroupModel final : public QAbstractTableModel +{ + Q_OBJECT + +public: + // Custom roles, in addition to the standard Qt::DisplayRole/ToolTipRole + // consumed by the QTableView-based GroupWidget. All roles are answered + // from data() regardless of the QModelIndex's column. + enum Role { + NameRole = Qt::UserRole + 1, + CharColorRole, + TextColorRole, + HpTextRole, + ManaTextRole, + MovesTextRole, + HpRatioRole, + ManaRatioRole, + MovesRatioRole, + HpLowRole, + MovesLowRole, + ManaHiddenRole, + StateIconsRole, + StateTipRole, + HpTipRole, + ManaTipRole, + MovesTipRole, + RoomNameRole, + IsYouRole, + IsNpcRole, + CanCenterRole, + }; + +private: + GroupVector m_characters; + bool m_mapLoaded = false; + bool m_anyMana = false; + +public: + explicit GroupModel(QObject *parent = nullptr); + +public: + void setMapLoaded(const bool val) { m_mapLoaded = val; } + +public: + NODISCARD SharedGroupChar getCharacter(int row) const; + NODISCARD const GroupVector &getCharacters() const { return m_characters; } + void setCharacters(const GroupVector &newChars); + void insertCharacter(const SharedGroupChar &newCharacter); + void removeCharacterById(GroupId charId); + void updateCharacter(const SharedGroupChar &updatedCharacter); + void resetModel(); + +public: + // True when at least one character has (or has had) mana; recomputed on + // every character add/remove/update/reset. + NODISCARD bool getAnyMana() const { return m_anyMana; } + NODISCARD bool moveRow(int from, int to); + +signals: + void sig_anyManaChanged(); + +private: + NODISCARD QVariant dataForCharacter(const SharedGroupChar &character, + ColumnTypeEnum column, + int role) const; + NODISCARD QVariant roleDataForCharacter(const SharedGroupChar &character, int role) const; + NODISCARD int findIndexById(GroupId charId) const; + void updateAnyMana(); + +protected: + NODISCARD int rowCount(const QModelIndex &parent) const override; + NODISCARD int columnCount(const QModelIndex &parent) const override; + + NODISCARD QVariant data(const QModelIndex &index, int role) const override; + NODISCARD QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + NODISCARD QHash roleNames() const override; + + // Drag and drop overrides + NODISCARD Qt::ItemFlags flags(const QModelIndex &index) const override; + NODISCARD Qt::DropActions supportedDropActions() const override; + NODISCARD QStringList mimeTypes() const override; + NODISCARD QMimeData *mimeData(const QModelIndexList &indexes) const override; + NODISCARD bool dropMimeData(const QMimeData *data, + Qt::DropAction action, + int row, + int column, + const QModelIndex &parent) override; +}; diff --git a/src/group/groupwidget.cpp b/src/group/groupwidget.cpp index 713874a75..b502f4d59 100644 --- a/src/group/groupwidget.cpp +++ b/src/group/groupwidget.cpp @@ -6,7 +6,6 @@ #include "../configuration/configuration.h" #include "../display/Filenames.h" -#include "../global/Timer.h" #include "../map/roomid.h" #include "../mapdata/mapdata.h" #include "../mapdata/roomselection.h" @@ -34,8 +33,6 @@ #include #include -static constexpr const char *GROUP_MIME_TYPE = "application/vnd.mm_groupchar.row"; - namespace { // anonymous class NODISCARD GroupImageCache final @@ -77,82 +74,8 @@ NODISCARD static auto &getImage(const QString &filename, const bool invert) // NOTE: Assumes we're single-threaded; otherwise we'd need a lock here. return g_groupImageCache.getImage(filename, invert); } - -NODISCARD static const char *getColumnFriendlyName(const ColumnTypeEnum column) -{ -#define X_DECL_COLUMNTYPE(UPPER_CASE, lower_case, CamelCase, friendly) \ - case ColumnTypeEnum::UPPER_CASE: \ - return friendly; - - switch (column) { - XFOREACH_COLUMNTYPE(X_DECL_COLUMNTYPE) - default: - qWarning() << "Unsupported column type" << static_cast(column); - return ""; - } -#undef X_DECL_COLUMNTYPE -} } // namespace -GroupProxyModel::GroupProxyModel(QObject *const parent) - : QSortFilterProxyModel(parent) -{} - -GroupProxyModel::~GroupProxyModel() = default; - -void GroupProxyModel::refresh() -{ - // Triggers re-filter and re-sort - invalidate(); -} - -SharedGroupChar GroupProxyModel::getCharacterFromSource(const QModelIndex &source_index) const -{ - const GroupModel *srcModel = qobject_cast(sourceModel()); - if (!srcModel || !source_index.isValid()) { - return nullptr; - } - - return srcModel->getCharacter(source_index.row()); -} - -bool GroupProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const -{ - if (!getConfig().groupManager.npcHide) { - return true; - } - - QModelIndex sourceIndex = sourceModel()->index(source_row, 0, source_parent); - SharedGroupChar character = getCharacterFromSource(sourceIndex); - if (character && character->isNpc()) { - return false; - } - - return true; -} - -GroupStateData::GroupStateData(const QColor &color, - const CharacterPositionEnum position, - const CharacterAffectFlags affects) - : m_color(color) - , m_position(position) - , m_affects(affects) -{ - if (position != CharacterPositionEnum::UNDEFINED) { - ++m_count; - } - // Increment imageCount for each active affect - for (const CharacterAffectEnum affect : ALL_CHARACTER_AFFECTS) { - if (affects.contains(affect)) { - ++m_count; - } - } - // Users spam search/reveal/flush so pad an extra position to reduce eye strain - if (!affects.contains(CharacterAffectEnum::WAITING)) { - ++m_count; - } -} - void GroupStateData::paint(QPainter *const pPainter, const QRect &rect) { auto &painter = deref(pPainter); @@ -380,451 +303,6 @@ QSize GroupDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIn return QStyledItemDelegate::sizeHint(option, index); } -GroupModel::GroupModel(QObject *const parent) - : QAbstractTableModel(parent) -{} - -void GroupModel::setCharacters(const GroupVector &newGameChars) -{ - DECL_TIMER(t, __FUNCTION__); - - std::unordered_set newGameCharIds; - newGameCharIds.reserve(newGameChars.size()); - for (const auto &pGameChar : newGameChars) { - const auto &gameChar = deref(pGameChar); - newGameCharIds.insert(gameChar.getId()); - } - - GroupVector resultingCharacterList; - resultingCharacterList.reserve(m_characters.size() + newGameChars.size()); - - // Temporary vectors to hold truly new players, NPCs, and all truly new characters - GroupVector trulyNewPlayers; - trulyNewPlayers.reserve(newGameChars.size()); - GroupVector trulyNewNpcs; - trulyNewNpcs.reserve(newGameChars.size()); - GroupVector allTrulyNewCharsInOriginalOrder; - allTrulyNewCharsInOriginalOrder.reserve(newGameChars.size()); - - // Preserve existing characters - std::unordered_set existingIds; - existingIds.reserve(m_characters.size()); - for (const auto &pExistingChar : m_characters) { - const auto &existingChar = deref(pExistingChar); - existingIds.insert(existingChar.getId()); - if (newGameCharIds.count(existingChar.getId())) { - resultingCharacterList.push_back(pExistingChar); - } - } - - // Identify truly new characters and categorize them as NPC or player - for (const auto &pGameChar : newGameChars) { - const auto &gameChar = deref(pGameChar); - if (existingIds.find(gameChar.getId()) == existingIds.end()) { - allTrulyNewCharsInOriginalOrder.push_back(pGameChar); - if (gameChar.isNpc()) { - trulyNewNpcs.push_back(pGameChar); - } else { - trulyNewPlayers.push_back(pGameChar); - } - } - } - - // Insert the newly identified characters into the resulting list based on configuration. - if (getConfig().groupManager.npcSortBottom) { - // Find the insertion point for new players: before the first NPC in the preserved list. - auto itPlayerInsertPos = resultingCharacterList.begin(); - while (itPlayerInsertPos != resultingCharacterList.end()) { - if (*itPlayerInsertPos && (*itPlayerInsertPos)->isNpc()) { - break; - } - ++itPlayerInsertPos; - } - - // Insert truly new players at the determined position. - if (!trulyNewPlayers.empty()) { - resultingCharacterList.insert(itPlayerInsertPos, - trulyNewPlayers.begin(), - trulyNewPlayers.end()); - } - // Insert truly new NPCs at the end of the list. - if (!trulyNewNpcs.empty()) { - resultingCharacterList.insert(resultingCharacterList.end(), - trulyNewNpcs.begin(), - trulyNewNpcs.end()); - } - } else { - // If no special NPC sorting, just append all truly new characters in their original order. - if (!allTrulyNewCharsInOriginalOrder.empty()) { - resultingCharacterList.insert(resultingCharacterList.end(), - allTrulyNewCharsInOriginalOrder.begin(), - allTrulyNewCharsInOriginalOrder.end()); - } - } - - beginResetModel(); - m_characters = std::move(resultingCharacterList); - endResetModel(); -} - -int GroupModel::findIndexById(const GroupId charId) const -{ - if (charId == INVALID_GROUPID) { - return -1; - } - auto it = std::find_if(m_characters.begin(), - m_characters.end(), - [charId](const SharedGroupChar &c) { return c && c->getId() == charId; }); - if (it != m_characters.end()) { - return static_cast(std::distance(m_characters.begin(), it)); - } - return -1; -} - -void GroupModel::insertCharacter(const SharedGroupChar &newCharacter) -{ - assert(newCharacter); - if (newCharacter->getId() == INVALID_GROUPID) { - return; - } - - auto calculateInsertIndex = [this, &newCharacter]() -> int { - if (getConfig().groupManager.npcSortBottom && !newCharacter->isNpc()) { - auto it = std::find_if(m_characters.begin(), - m_characters.end(), - [](const SharedGroupChar &c) { return c && c->isNpc(); }); - return static_cast(std::distance(m_characters.begin(), it)); - } - return static_cast(m_characters.size()); - }; - - const int newIndex = calculateInsertIndex(); - assert(newIndex >= 0 && newIndex <= static_cast(m_characters.size())); - - beginInsertRows(QModelIndex(), newIndex, newIndex); - m_characters.insert(m_characters.begin() + newIndex, newCharacter); - endInsertRows(); -} - -void GroupModel::removeCharacterById(const GroupId charId) -{ - const int index = findIndexById(charId); - if (index == -1) { - return; - } - - beginRemoveRows(QModelIndex(), index, index); - m_characters.erase(m_characters.begin() + index); - endRemoveRows(); -} - -void GroupModel::updateCharacter(const SharedGroupChar &updatedCharacter) -{ - assert(updatedCharacter); - const GroupId charId = updatedCharacter->getId(); - const int index = findIndexById(charId); - if (index == -1) { - insertCharacter(updatedCharacter); - return; - } - - SharedGroupChar &existingChar = m_characters[static_cast(index)]; - existingChar = updatedCharacter; - - emit dataChanged(this->index(index, 0), - this->index(index, columnCount(QModelIndex()) - 1), - {Qt::DisplayRole, - Qt::BackgroundRole, - Qt::ForegroundRole, - Qt::ToolTipRole, - Qt::UserRole + 1}); -} - -SharedGroupChar GroupModel::getCharacter(int row) const -{ - if (row >= 0 && row < static_cast(m_characters.size())) { - return m_characters.at(static_cast(row)); - } - return nullptr; -} - -void GroupModel::resetModel() -{ - beginResetModel(); - endResetModel(); -} - -int GroupModel::rowCount(const QModelIndex & /* parent */) const -{ - return static_cast(m_characters.size()); -} - -int GroupModel::columnCount(const QModelIndex & /* parent */) const -{ - return GROUP_COLUMN_COUNT; -} - -NODISCARD static QString getPrettyName(const CharacterPositionEnum position) -{ -#define X_CASE(UPPER_CASE, lower_case, CamelCase, friendly) \ - do { \ - case CharacterPositionEnum::UPPER_CASE: \ - return QStringLiteral(friendly); \ - } while (false); - switch (position) { - XFOREACH_CHARACTER_POSITION(X_CASE) - } - return QString::asprintf("(CharacterPositionEnum)%d", static_cast(position)); -#undef X_CASE -} -NODISCARD static QString getPrettyName(const CharacterAffectEnum affect) -{ -#define X_CASE(UPPER_CASE, lower_case, CamelCase, friendly) \ - do { \ - case CharacterAffectEnum::UPPER_CASE: \ - return QStringLiteral(friendly); \ - } while (false); - switch (affect) { - XFOREACH_CHARACTER_AFFECT(X_CASE) - } - return QString::asprintf("(CharacterAffectEnum)%d", static_cast(affect)); -#undef X_CASE -} - -QVariant GroupModel::dataForCharacter(const SharedGroupChar &pCharacter, - const ColumnTypeEnum column, - const int role) const -{ - const CGroupChar &character = deref(pCharacter); - - const auto formatStat = [&character](int numerator, int denomenator) -> QString { - if (numerator == 0 && denomenator == 0) { - return QLatin1String(""); - } - - if (character.getType() == CharacterTypeEnum::NPC) { - const double pct = denomenator > 0 ? static_cast(numerator) / denomenator : 0.0; - return QString("%1%").arg(static_cast(std::round(pct * 100.0))); - } - - return QString("%1 / %2").arg(numerator).arg(denomenator); - }; - - // Map column to data - switch (role) { - case Qt::DisplayRole: - switch (column) { - case ColumnTypeEnum::NAME: - if (character.getLabel().isEmpty() - || character.getName().getStdStringViewUtf8() - == character.getLabel().getStdStringViewUtf8()) { - return character.getName().toQString(); - } else { - return QString("%1 (%2)").arg(character.getName().toQString(), - character.getLabel().toQString()); - } - case ColumnTypeEnum::HP: - return formatStat(character.getHits(), character.getMaxHits()); - case ColumnTypeEnum::MANA: - return formatStat(character.getMana(), character.getMaxMana()); - case ColumnTypeEnum::MOVES: - return formatStat(character.getMoves(), character.getMaxMoves()); - case ColumnTypeEnum::STATE: - return QVariant::fromValue(GroupStateData(character.getColor(), - character.getPosition(), - character.getAffects())); - case ColumnTypeEnum::ROOM_NAME: - if (character.getRoomName().isEmpty()) { - return QStringLiteral("Somewhere"); - } else { - return character.getRoomName().toQString(); - } - default: - qWarning() << "Unsupported column" << static_cast(column); - break; - } - break; - - case Qt::BackgroundRole: - return QVariant(); - - case Qt::ForegroundRole: - return QVariant(); - - case Qt::TextAlignmentRole: - if (column != ColumnTypeEnum::NAME && column != ColumnTypeEnum::ROOM_NAME) { - // NOTE: There's no QVariant(AlignmentFlag) constructor. - return static_cast(Qt::AlignCenter); - } - break; - - case Qt::ToolTipRole: { - switch (column) { - case ColumnTypeEnum::HP: - case ColumnTypeEnum::MANA: - case ColumnTypeEnum::MOVES: { - const int cur = (column == ColumnTypeEnum::HP) ? character.getHits() - : (column == ColumnTypeEnum::MANA) ? character.getMana() - : character.getMoves(); - const int max = (column == ColumnTypeEnum::HP) ? character.getMaxHits() - : (column == ColumnTypeEnum::MANA) ? character.getMaxMana() - : character.getMaxMoves(); - if (max > 0) { - const double pct = static_cast(cur) / max; - return QString("%1%").arg(static_cast(std::round(pct * 100.0))); - } - return QVariant(); - } - case ColumnTypeEnum::STATE: { - QString prettyName; - prettyName += getPrettyName(character.getPosition()); - for (const CharacterAffectEnum affect : ALL_CHARACTER_AFFECTS) { - if (character.getAffects().contains(affect)) { - prettyName.append(QStringLiteral(", ")).append(getPrettyName(affect)); - } - } - return prettyName; - } - case ColumnTypeEnum::NAME: - break; - case ColumnTypeEnum::ROOM_NAME: - if (character.getServerId() != INVALID_SERVER_ROOMID) { - return QString("%1").arg(character.getServerId().asUint32()); - } - break; - } - break; - } - - default: - break; - } - - return QVariant(); -} - -QVariant GroupModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) { - return QVariant(); - } - - if (index.row() >= 0 && index.row() < static_cast(m_characters.size())) { - const SharedGroupChar &character = m_characters.at(static_cast(index.row())); - return dataForCharacter(character, static_cast(index.column()), role); - } - - return QVariant(); -} - -QVariant GroupModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - switch (role) { - case Qt::DisplayRole: - if (orientation == Qt::Orientation::Horizontal) { - return getColumnFriendlyName(static_cast(section)); - } - break; - } - return QVariant(); -} - -Qt::ItemFlags GroupModel::flags(const QModelIndex &index) const -{ - if (!index.isValid()) { - return Qt::NoItemFlags; - } - return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; -} - -Qt::DropActions GroupModel::supportedDropActions() const -{ - return Qt::MoveAction; -} - -QStringList GroupModel::mimeTypes() const -{ - QStringList types; - types << GROUP_MIME_TYPE; - return types; -} - -QMimeData *GroupModel::mimeData(const QModelIndexList &indexes) const -{ - QMimeData *mimeDataObj = new QMimeData(); - QByteArray encodedData; - QDataStream stream(&encodedData, QIODevice::WriteOnly); - if (!indexes.isEmpty() && indexes.first().isValid()) { - stream << indexes.first().row(); - } - mimeDataObj->setData(GROUP_MIME_TYPE, encodedData); - return mimeDataObj; -} - -bool GroupModel::dropMimeData( - const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) -{ - if (action == Qt::IgnoreAction) { - return true; - } - if (!data->hasFormat(GROUP_MIME_TYPE) || column > 0) { - return false; - } - - QByteArray encodedData = data->data(GROUP_MIME_TYPE); - QDataStream stream(&encodedData, QIODevice::ReadOnly); - if (stream.atEnd()) { - return false; - } - int sourceRow; - stream >> sourceRow; - - int targetInsertionIndex; - if (parent.isValid()) { - targetInsertionIndex = parent.row(); - } else if (row != -1) { - targetInsertionIndex = row; - } else { - targetInsertionIndex = static_cast(m_characters.size()); - } - - if (sourceRow == targetInsertionIndex - || (sourceRow == targetInsertionIndex - 1 && targetInsertionIndex > sourceRow)) { - return false; - } - - if (targetInsertionIndex < 0) { - targetInsertionIndex = 0; - } - if (targetInsertionIndex > static_cast(m_characters.size())) { - targetInsertionIndex = static_cast(m_characters.size()); - } - - if (!beginMoveRows(QModelIndex(), sourceRow, sourceRow, QModelIndex(), targetInsertionIndex)) { - return false; - } - - SharedGroupChar movedChar = m_characters[static_cast(sourceRow)]; - m_characters.erase(m_characters.begin() + sourceRow); - - int actualInsertionIdx = targetInsertionIndex; - if (sourceRow < targetInsertionIndex) { - actualInsertionIdx--; - } - - if (actualInsertionIdx < 0) { - actualInsertionIdx = 0; - } - if (actualInsertionIdx > static_cast(m_characters.size())) { - actualInsertionIdx = static_cast(m_characters.size()); - } - - m_characters.insert(m_characters.begin() + actualInsertionIdx, movedChar); - - endMoveRows(); - return true; -} - GroupWidget::GroupWidget(Mmapper2Group *const group, MapData *const md, QWidget *const parent) : QWidget(parent) , m_group(group) @@ -939,6 +417,7 @@ GroupWidget::GroupWidget(Mmapper2Group *const group, MapData *const md, QWidget this, &GroupWidget::slot_onCharacterUpdated); connect(m_group, &Mmapper2Group::sig_groupReset, this, &GroupWidget::slot_onGroupReset); + connect(m_model, &GroupModel::sig_anyManaChanged, this, &GroupWidget::updateColumnVisibility); updateColumnVisibility(); updatePulseTimer(); @@ -961,16 +440,7 @@ QSize GroupWidget::sizeHint() const void GroupWidget::updateColumnVisibility() { // Hide unnecessary columns like mana if everyone is a zorc/troll - const auto one_character_had_mana = [this]() -> bool { - for (const auto &character : deref(m_model).getCharacters()) { - if (character && (character->getMana() > 0 || character->getMaxMana() > 0)) { - return true; - } - } - return false; - }; - const bool hide_mana = !one_character_had_mana(); - m_table->setColumnHidden(static_cast(ColumnTypeEnum::MANA), hide_mana); + m_table->setColumnHidden(static_cast(ColumnTypeEnum::MANA), !deref(m_model).getAnyMana()); } void GroupWidget::updatePulseTimer() @@ -1011,7 +481,6 @@ void GroupWidget::slot_onCharacterAdded(SharedGroupChar character) { assert(character); deref(m_model).insertCharacter(character); - updateColumnVisibility(); updatePulseTimer(); } @@ -1019,7 +488,6 @@ void GroupWidget::slot_onCharacterRemoved(const GroupId characterId) { assert(characterId != INVALID_GROUPID); deref(m_model).removeCharacterById(characterId); - updateColumnVisibility(); updatePulseTimer(); } @@ -1027,19 +495,11 @@ void GroupWidget::slot_onCharacterUpdated(SharedGroupChar character) { assert(character); deref(m_model).updateCharacter(character); - - const int manaCol = static_cast(ColumnTypeEnum::MANA); - const bool hasMana = character->getMana() > 0 || character->getMaxMana() > 0; - if (m_table->isColumnHidden(manaCol) == hasMana) { - updateColumnVisibility(); - } - updatePulseTimer(); } void GroupWidget::slot_onGroupReset(const GroupVector &newCharacterList) { deref(m_model).setCharacters(newCharacterList); - updateColumnVisibility(); updatePulseTimer(); } diff --git a/src/group/groupwidget.h b/src/group/groupwidget.h index 5abe9db08..fe416e5bb 100644 --- a/src/group/groupwidget.h +++ b/src/group/groupwidget.h @@ -4,9 +4,9 @@ // Author: Nils Schimmelmann (Jahara) #include "CGroupChar.h" +#include "GroupModel.h" #include "mmapper2character.h" -#include #include #include #include @@ -20,44 +20,6 @@ class QObject; class QTableView; class QTimer; -class NODISCARD_QOBJECT GroupProxyModel final : public QSortFilterProxyModel -{ - Q_OBJECT - -public: - explicit GroupProxyModel(QObject *parent = nullptr); - ~GroupProxyModel() final; - - void refresh(); - -protected: - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; - -private: - SharedGroupChar getCharacterFromSource(const QModelIndex &source_index) const; -}; - -class NODISCARD GroupStateData final -{ -private: - QColor m_color; - CharacterPositionEnum m_position = CharacterPositionEnum::UNDEFINED; - CharacterAffectFlags m_affects; - int m_count = 0; - int m_height = 23; - -public: - GroupStateData() = default; - explicit GroupStateData(const QColor &color, - CharacterPositionEnum position, - CharacterAffectFlags affects); - -public: - void paint(QPainter *pPainter, const QRect &rect); - NODISCARD int getWidth() const { return static_cast(m_count) * m_height; } -}; -Q_DECLARE_METATYPE(GroupStateData) - class NODISCARD_QOBJECT GroupDelegate final : public QStyledItemDelegate { Q_OBJECT @@ -73,75 +35,6 @@ class NODISCARD_QOBJECT GroupDelegate final : public QStyledItemDelegate const QModelIndex &index) const override; }; -#define XFOREACH_COLUMNTYPE(X) \ - X(NAME, name, Name, "Name") \ - X(HP, hp, Hp, "HP") \ - X(MANA, mana, Mana, "Mana") \ - X(MOVES, moves, Moves, "Moves") \ - X(STATE, state, State, "State") \ - X(ROOM_NAME, room_name, RoomName, "Room Name") \ - /* define column types above */ - -#define X_COUNT(UPPER_CASE, lower_case, CamelCase, friendly) +1 -static constexpr const int GROUP_COLUMN_COUNT = XFOREACH_COLUMNTYPE(X_COUNT); -#undef X_COUNT - -enum class NODISCARD ColumnTypeEnum { -#define X_DECL_COLUMNTYPE(UPPER_CASE, lower_case, CamelCase, friendly) UPPER_CASE, - XFOREACH_COLUMNTYPE(X_DECL_COLUMNTYPE) -#undef X_DECL_COLUMNTYPE -}; - -static_assert(GROUP_COLUMN_COUNT == static_cast(ColumnTypeEnum::ROOM_NAME) + 1, "# of columns"); - -class NODISCARD_QOBJECT GroupModel final : public QAbstractTableModel -{ - Q_OBJECT - -private: - GroupVector m_characters; - bool m_mapLoaded = false; - -public: - explicit GroupModel(QObject *parent = nullptr); - -public: - void setMapLoaded(const bool val) { m_mapLoaded = val; } - -public: - NODISCARD SharedGroupChar getCharacter(int row) const; - NODISCARD const GroupVector &getCharacters() const { return m_characters; } - void setCharacters(const GroupVector &newChars); - void insertCharacter(const SharedGroupChar &newCharacter); - void removeCharacterById(GroupId charId); - void updateCharacter(const SharedGroupChar &updatedCharacter); - void resetModel(); - -private: - NODISCARD QVariant dataForCharacter(const SharedGroupChar &character, - ColumnTypeEnum column, - int role) const; - NODISCARD int findIndexById(GroupId charId) const; - -protected: - NODISCARD int rowCount(const QModelIndex &parent) const override; - NODISCARD int columnCount(const QModelIndex &parent) const override; - - NODISCARD QVariant data(const QModelIndex &index, int role) const override; - NODISCARD QVariant headerData(int section, Qt::Orientation orientation, int role) const override; - - // Drag and drop overrides - NODISCARD Qt::ItemFlags flags(const QModelIndex &index) const override; - NODISCARD Qt::DropActions supportedDropActions() const override; - NODISCARD QStringList mimeTypes() const override; - NODISCARD QMimeData *mimeData(const QModelIndexList &indexes) const override; - NODISCARD bool dropMimeData(const QMimeData *data, - Qt::DropAction action, - int row, - int column, - const QModelIndex &parent) override; -}; - class NODISCARD_QOBJECT GroupWidget final : public QWidget { Q_OBJECT diff --git a/src/group/mmapper2group.h b/src/group/mmapper2group.h index daa965226..93d8b8043 100644 --- a/src/group/mmapper2group.h +++ b/src/group/mmapper2group.h @@ -81,7 +81,7 @@ class NODISCARD_QOBJECT Mmapper2Group final : public QObject signals: // MainWindow::log (via MainWindow) void sig_log(const QString &, const QString &); - // MapCanvas::requestUpdate (via MainWindow) + // MapCanvasWindow::requestUpdate (via MainWindow) void sig_updateMapCanvas(); // redraw the opengl screen // GroupWidget::updateLabels (via GroupWidget) void sig_characterAdded(SharedGroupChar character); diff --git a/src/main.cpp b/src/main.cpp index bf1502856..fd6b1579d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -100,23 +101,25 @@ static void tryAutoLoadMap(MainWindow &mw) if constexpr (CURRENT_PLATFORM == PlatformEnum::Wasm) { if constexpr (NO_MAP_RESOURCE) { return; - } - // On WASM the map is sideloaded from the network; fetch it asynchronously. - auto *nam = new QNetworkAccessManager(&mw); - auto *reply = nam->get(QNetworkRequest(QUrl(getAssetsPath() + "map/arda"))); - QObject::connect(reply, &QNetworkReply::finished, &mw, [&mw, reply, nam]() { - if (reply->error() == QNetworkReply::NoError) { - try { - mw.loadFile(MapSource::alloc(QStringLiteral("arda"), reply->readAll())); - } catch (const std::exception &e) { - qCritical() << "[main] Failed to load sideloaded map:" << e.what(); + } else { + // On WASM the map is sideloaded from the network; fetch it + // asynchronously. + auto *nam = new QNetworkAccessManager(&mw); + auto *reply = nam->get(QNetworkRequest(QUrl(getAssetsPath() + "map/arda"))); + QObject::connect(reply, &QNetworkReply::finished, &mw, [&mw, reply, nam]() { + if (reply->error() == QNetworkReply::NoError) { + try { + mw.loadFile(MapSource::alloc(QStringLiteral("arda"), reply->readAll())); + } catch (const std::exception &e) { + qCritical() << "[main] Failed to load sideloaded map:" << e.what(); + } + } else { + qWarning() << "[main] Failed to fetch sideloaded map:" << reply->errorString(); } - } else { - qWarning() << "[main] Failed to fetch sideloaded map:" << reply->errorString(); - } - reply->deleteLater(); - nam->deleteLater(); - }); + reply->deleteLater(); + nam->deleteLater(); + }); + } } else { if (!NO_MAP_RESOURCE) { // Check the system assets directory @@ -176,6 +179,14 @@ int main(int argc, char **argv) } QApplication app(argc, argv); + + const double uiScale = getConfig().general.uiFontScale; + if (uiScale > 0.0 && !qFuzzyCompare(uiScale, 1.0)) { + QFont f = QApplication::font(); + f.setPointSizeF(f.pointSizeF() * uiScale); + QApplication::setFont(f); + } + tryInitDrMingw(); auto tryLoadingWinSock = std::make_unique(); auto themeManager = std::make_unique(&app); @@ -184,8 +195,10 @@ int main(int argc, char **argv) } tryLoadEmojis(getResourceFilenameRaw("emojis", "short-codes.json")); - auto mw = std::make_unique(); + + std::unique_ptr mw = std::make_unique(); tryAutoLoadMap(*mw); + const int ret = QApplication::exec(); qDebug() << "QApplication::exec() returned" << ret; mw.reset(); diff --git a/src/mainwindow/CompactLayout.h b/src/mainwindow/CompactLayout.h new file mode 100644 index 000000000..dd4316d63 --- /dev/null +++ b/src/mainwindow/CompactLayout.h @@ -0,0 +1,46 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "../global/macros.h" + +#include + +// Layout policy for small (phone-sized) windows, shared by whatever shell +// hosts the UI; the shell decides how to realize it (see +// MainWindow::setCompactLayout()). +namespace CompactLayout { + +// A screen narrower or shorter than this (logical pixels) starts in the +// compact layout: a single menu, one panel at a time, no toolbars. +static constexpr const int MIN_WIDTH = 720; +static constexpr const int MIN_HEIGHT = 480; + +// Share of the window height given to the client (terminal) panel while +// compact; the map gets what remains. +static constexpr const double CLIENT_HEIGHT_FRACTION = 0.55; + +// Font scale for the panel tab strip while compact, so the tabs are large +// enough for a finger. +static constexpr const double TAB_FONT_SCALE = 1.4; + +NODISCARD constexpr bool isCompact(const QSize size) noexcept +{ + return size.width() < MIN_WIDTH || size.height() < MIN_HEIGHT; +} + +// The size the policy is applied to. A window can't usefully exceed its +// screen, but the expanded layout's minimum size can force it to (phones), +// and it is that minimum the decision is about to change, so the screen +// bounds the window size. +NODISCARD constexpr QSize probeSize(const QSize window, const QSize screen) noexcept +{ + return screen.isValid() ? window.boundedTo(screen) : window; +} + +NODISCARD constexpr int clientHeight(const QSize size) noexcept +{ + return static_cast(static_cast(size.height()) * CLIENT_HEIGHT_FRACTION); +} + +} // namespace CompactLayout diff --git a/src/mainwindow/UpdateChecker.cpp b/src/mainwindow/UpdateChecker.cpp new file mode 100644 index 000000000..06c8f48bf --- /dev/null +++ b/src/mainwindow/UpdateChecker.cpp @@ -0,0 +1,280 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "UpdateChecker.h" + +#include "../configuration/configuration.h" +#include "../global/ConfigConsts-Computed.h" +#include "../global/RAII.h" +#include "../global/Version.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { // anonymous + +NODISCARD const char *getArchitectureRegexPattern() +{ + // See Qt documentation for expected keys + static const std::array, 4> archPatterns = { + {{"arm64", "(arm64|aarch64)"}, + {"x86_64", "(x86_64|amd64|x64)"}, + {"i386", "(i386|x86(?!_64))"}, + {"arm", "(arm(?!64)|armhf)"}}}; + + static auto findPattern = [](const QString &arch) -> const char * { + const auto it = std::find_if(archPatterns.begin(), + archPatterns.end(), + [&arch](const auto &pair) { + return mmqt::toStdStringUtf8(arch) == pair.first; + }); + return (it != archPatterns.end()) ? it->second : nullptr; + }; + + if (auto pattern = findPattern(QSysInfo::currentCpuArchitecture())) { + return pattern; + } + if (auto fallback = findPattern(QSysInfo::buildCpuArchitecture())) { + return fallback; + } + abort(); +} + +} // namespace + +CompareVersion::CompareVersion(const QString &versionStr) noexcept +{ + static const QRegularExpression versionRx(R"(v?(\d+)\.(\d+)\.(\d+))"); + auto result = versionRx.match(versionStr); + if (result.hasMatch()) { + m_parts[0] = result.captured(1).toInt(); + m_parts[1] = result.captured(2).toInt(); + m_parts[2] = result.captured(3).toInt(); + } +} + +bool CompareVersion::operator>(const CompareVersion &other) const +{ + for (size_t i = 0; i < m_parts.size(); ++i) { + auto myPart = m_parts.at(i); + auto otherPart = other.m_parts.at(i); + if (myPart == otherPart) { + continue; + } + if (myPart > otherPart) { + return true; + } + break; + } + return false; +} + +bool CompareVersion::operator==(const CompareVersion &other) const +{ + return m_parts == other.m_parts; +} + +QString CompareVersion::toQString() const +{ + const auto &parts = m_parts; + return QString("%1.%2.%3").arg(parts.at(0)).arg(parts.at(1)).arg(parts.at(2)); +} + +UpdateChecker::UpdateChecker(QObject *const parent) + : QObject(parent) +{ + connect(&m_manager, &QNetworkAccessManager::finished, this, &UpdateChecker::managerFinished); +} + +void UpdateChecker::check() +{ + setUpdateStatus(tr("Checking for new version..."), false, false); + + auto url = isMMapperBeta() + ? QStringLiteral("https://github.com/_gh/api/repos/mume/mmapper/git/ref/tags/beta") + : QStringLiteral("https://github.com/_gh/api/repos/mume/mmapper/releases/latest"); + QNetworkRequest request(url); + request.setHeader(QNetworkRequest::ServerHeader, "application/json"); + m_manager.get(request); +} + +bool UpdateChecker::upgrade() +{ + if (m_downloadUrl.isEmpty()) { + return false; + } + return QDesktopServices::openUrl(m_downloadUrl); +} + +void UpdateChecker::setUpdateStatus(const QString &message, + bool enableUpgradeButton, + bool showDialog) +{ + m_statusText = message; + emit sig_statusTextChanged(); + m_upgradeAvailable = enableUpgradeButton; + emit sig_upgradeAvailableChanged(); + if (showDialog) { + emit sig_showDialog(); + } +} + +QString UpdateChecker::findDownloadUrlForRelease(const QJsonObject &releaseObject) const +{ + // Compile architecture-specific regex + static const auto archRegex = QRegularExpression(getArchitectureRegexPattern(), + QRegularExpression::CaseInsensitiveOption); + + auto assets = releaseObject.value("assets").toArray(); + for (const QJsonValueRef item : assets) { + const auto asset = item.toObject(); + const QString name = asset.value("name").toString(); + const QString url = asset.value("browser_download_url").toString(); + + if (name.isEmpty() || url.isEmpty()) { + continue; + } + + if (!name.contains(archRegex)) { + continue; + } + + switch (CURRENT_PACKAGE) { + case PackageEnum::Source: + break; + case PackageEnum::Deb: + if (name.endsWith(".deb", Qt::CaseInsensitive)) { + return url; + } + break; + case PackageEnum::Dmg: + if (name.endsWith(".dmg", Qt::CaseInsensitive)) { + return url; + } + break; + case PackageEnum::Nsis: + if (name.endsWith(".exe", Qt::CaseInsensitive)) { + return url; + } + break; + case PackageEnum::AppImage: + if (name.endsWith(".AppImage", Qt::CaseInsensitive)) { + return url; + } + break; + case PackageEnum::AppX: + if (name.endsWith(".appx", Qt::CaseInsensitive)) { + return url; + } + break; + case PackageEnum::Flatpak: + if (name.endsWith(".flatpak", Qt::CaseInsensitive)) { + return url; + } + break; + case PackageEnum::Snap: + if (name.endsWith(".snap", Qt::CaseInsensitive)) { + return url; + } + break; + case PackageEnum::Wasm: + if (name.endsWith(".zip", Qt::CaseInsensitive)) { + return url; + } + break; + } + } + + const QString fallbackUrl = releaseObject.value("html_url").toString(); + if (!fallbackUrl.isEmpty()) { + return fallbackUrl; + } + + return "https://github.com/MUME/MMapper/releases"; +} + +void UpdateChecker::managerFinished(QNetworkReply *reply) +{ + const RAIICallback deleteLaterRAII{[&reply]() { reply->deleteLater(); }}; + // REVISIT: Timeouts, errors, etc + if (reply->error() != QNetworkReply::NoError) { + qWarning() << reply->errorString(); + return; + } + const QString answer = reply->readAll(); + QJsonParseError error; + const QJsonDocument doc = QJsonDocument::fromJson(answer.toUtf8(), &error); + if (doc.isNull()) { + qWarning() << error.errorString(); + return; + } + if (!doc.isObject()) { + qWarning() << answer; + return; + } + const QJsonObject obj = doc.object(); + + if (isMMapperBeta() && reply->request().url().toString().contains("/ref/tags/")) { + const QJsonObject objNode = obj.value("object").toObject(); + const QString remoteCommitHash = objNode.value("sha").toString(); + const QString localCommitHash = std::invoke([]() -> QString { + static const QRegularExpression hashRegex(R"(-g([0-9a-fA-F]+)$)"); + QRegularExpressionMatch match = hashRegex.match(QString::fromUtf8(getMMapperVersion())); + if (match.hasMatch()) { + return match.captured(1); + } + return ""; + }); + qInfo() << "Updater comparing: CURRENT=" << localCommitHash + << "LATEST=" << remoteCommitHash.left(10); + if (!localCommitHash.isEmpty() && remoteCommitHash.startsWith(localCommitHash)) { + setUpdateStatus(tr("You are on the latest beta!"), false, false); + return; + } + + QNetworkRequest request( + QStringLiteral("https://github.com/_gh/api/repos/mume/mmapper/releases/tags/beta")); + request.setHeader(QNetworkRequest::ServerHeader, "application/json"); + m_manager.get(request); + return; + } + + QString latestTag; + if (!isMMapperBeta()) { + if (!obj.contains("tag_name") || !obj["tag_name"].isString()) { + qWarning() << "Release 'tag_name' is missing or not a string."; + setUpdateStatus(tr("Could not determine release version details."), false, false); + return; + } + latestTag = obj["tag_name"].toString(); + const QString currentVersion = QString::fromUtf8(getMMapperVersion()); + const CompareVersion latest(latestTag); + static CompareVersion current(currentVersion); + qInfo() << "Updater comparing: CURRENT=" << current << "LATEST=" << latest; + if (current == latest) { + setUpdateStatus(tr("You are up to date!"), false, false); + return; + } else if (current > latest) { + setUpdateStatus(tr("No newer update available."), false, false); + return; + } + } + m_downloadUrl = findDownloadUrlForRelease(obj); + setUpdateStatus(QString("A new %1version of MMapper is available!" + "\n" + "\n" + "Press 'Upgrade' to download %2!") + .arg(isMMapperBeta() ? "beta " : "", isMMapperBeta() ? "it" : latestTag), + true, + true); +} diff --git a/src/mainwindow/UpdateChecker.h b/src/mainwindow/UpdateChecker.h new file mode 100644 index 000000000..5756e4c21 --- /dev/null +++ b/src/mainwindow/UpdateChecker.h @@ -0,0 +1,85 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "../global/Array.h" +#include "../global/macros.h" + +#include +#include +#include +#include + +class QJsonObject; +class QNetworkReply; + +class NODISCARD CompareVersion final +{ +private: + MMapper::Array m_parts; + +public: + explicit CompareVersion(const QString &versionStr) noexcept; + +public: + NODISCARD bool operator>(const CompareVersion &other) const; + NODISCARD bool operator==(const CompareVersion &other) const; + + NODISCARD int major() const { return m_parts[0]; } + NODISCARD int minor() const { return m_parts[1]; } + NODISCARD int patch() const { return m_parts[2]; } + +public: + NODISCARD QString toQString() const; + explicit operator QString() const { return toQString(); } + friend QDebug operator<<(QDebug os, const CompareVersion &compareVersion) + { + return os << compareVersion.toQString(); + } +}; + +// Widget-free network/version-check logic, so the same implementation can +// back any UI showing update status. Owns the single QNetworkAccessManager +// instance for the check; see check()/upgrade(). +class NODISCARD_QOBJECT UpdateChecker final : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QString statusText READ getStatusText NOTIFY sig_statusTextChanged) + Q_PROPERTY(bool upgradeAvailable READ isUpgradeAvailable NOTIFY sig_upgradeAvailableChanged) + +private: + QNetworkAccessManager m_manager; + QString m_downloadUrl; + QString m_statusText; + bool m_upgradeAvailable = false; + +public: + explicit UpdateChecker(QObject *parent); + + NODISCARD const QString &getStatusText() const { return m_statusText; } + NODISCARD bool isUpgradeAvailable() const { return m_upgradeAvailable; } + + // Starts (or restarts) a check against GitHub for a newer release. + Q_INVOKABLE void check(); + + // Opens the discovered download URL in the user's browser. Returns + // false (and does nothing else) if there is no URL yet, or the OS + // failed to open it. + Q_INVOKABLE bool upgrade(); + +signals: + void sig_statusTextChanged(); + void sig_upgradeAvailableChanged(); + // Emitted when a newer version was found, so a UI showing this checker + // should raise itself in front of the user. + void sig_showDialog(); + +private slots: + void managerFinished(QNetworkReply *reply); + +private: + void setUpdateStatus(const QString &message, bool enableUpgradeButton, bool showDialog); + NODISCARD QString findDownloadUrlForRelease(const QJsonObject &releaseObject) const; +}; diff --git a/src/mainwindow/UpdateDialog.cpp b/src/mainwindow/UpdateDialog.cpp index 71eabd19e..0ae53da0c 100644 --- a/src/mainwindow/UpdateDialog.cpp +++ b/src/mainwindow/UpdateDialog.cpp @@ -4,96 +4,13 @@ #include "UpdateDialog.h" -#include "../configuration/configuration.h" -#include "../global/ConfigConsts-Computed.h" -#include "../global/RAII.h" -#include "../global/Version.h" - -#include -#include -#include - -#include #include -#include -#include -#include -#include +#include #include -#include -#include - -namespace { // anonymous - -NODISCARD const char *getArchitectureRegexPattern() -{ - // See Qt documentation for expected keys - static const std::array, 4> archPatterns = { - {{"arm64", "(arm64|aarch64)"}, - {"x86_64", "(x86_64|amd64|x64)"}, - {"i386", "(i386|x86(?!_64))"}, - {"arm", "(arm(?!64)|armhf)"}}}; - - static auto findPattern = [](const QString &arch) -> const char * { - const auto it = std::find_if(archPatterns.begin(), - archPatterns.end(), - [&arch](const auto &pair) { - return mmqt::toStdStringUtf8(arch) == pair.first; - }); - return (it != archPatterns.end()) ? it->second : nullptr; - }; - - if (auto pattern = findPattern(QSysInfo::currentCpuArchitecture())) { - return pattern; - } - if (auto fallback = findPattern(QSysInfo::buildCpuArchitecture())) { - return fallback; - } - abort(); -} - -} // namespace - -CompareVersion::CompareVersion(const QString &versionStr) noexcept -{ - static const QRegularExpression versionRx(R"(v?(\d+)\.(\d+)\.(\d+))"); - auto result = versionRx.match(versionStr); - if (result.hasMatch()) { - m_parts[0] = result.captured(1).toInt(); - m_parts[1] = result.captured(2).toInt(); - m_parts[2] = result.captured(3).toInt(); - } -} - -bool CompareVersion::operator>(const CompareVersion &other) const -{ - for (size_t i = 0; i < m_parts.size(); ++i) { - auto myPart = m_parts.at(i); - auto otherPart = other.m_parts.at(i); - if (myPart == otherPart) { - continue; - } - if (myPart > otherPart) { - return true; - } - break; - } - return false; -} - -bool CompareVersion::operator==(const CompareVersion &other) const -{ - return m_parts == other.m_parts; -} - -QString CompareVersion::toQString() const -{ - const auto &parts = m_parts; - return QString("%1.%2.%3").arg(parts.at(0)).arg(parts.at(1)).arg(parts.at(2)); -} UpdateDialog::UpdateDialog(QWidget *const parent) : QDialog(parent) + , m_checker(this) { setWindowTitle("MMapper Updater"); setWindowIcon(QIcon(":/icons/mmapper-lo.svg")); @@ -101,9 +18,10 @@ UpdateDialog::UpdateDialog(QWidget *const parent) m_text = new QLabel(this); m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); m_buttonBox->button(QDialogButtonBox::Ok)->setText(tr("&Upgrade")); + m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(m_checker.isUpgradeAvailable()); connect(m_buttonBox, &QDialogButtonBox::accepted, this, &UpdateDialog::accepted); connect(m_buttonBox, &QDialogButtonBox::accepted, this, [this]() { - if (QDesktopServices::openUrl(m_downloadUrl)) { + if (m_checker.upgrade()) { close(); } }); @@ -113,181 +31,20 @@ UpdateDialog::UpdateDialog(QWidget *const parent) mainLayout->addWidget(m_text); mainLayout->addWidget(m_buttonBox); - connect(&m_manager, &QNetworkAccessManager::finished, this, &UpdateDialog::managerFinished); -} - -void UpdateDialog::open() -{ - m_text->setText(tr("Checking for new version...")); - m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - - auto url = isMMapperBeta() - ? QStringLiteral("https://github.com/_gh/api/repos/mume/mmapper/git/ref/tags/beta") - : QStringLiteral("https://github.com/_gh/api/repos/mume/mmapper/releases/latest"); - QNetworkRequest request(url); - request.setHeader(QNetworkRequest::ServerHeader, "application/json"); - m_manager.get(request); -} - -void UpdateDialog::setUpdateStatus(const QString &message, - bool enableUpgradeButton, - bool showAndUpdateDialog) -{ - m_text->setText(message); - m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(enableUpgradeButton); - if (showAndUpdateDialog) { + connect(&m_checker, &UpdateChecker::sig_statusTextChanged, this, [this]() { + m_text->setText(m_checker.getStatusText()); + }); + connect(&m_checker, &UpdateChecker::sig_upgradeAvailableChanged, this, [this]() { + m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(m_checker.isUpgradeAvailable()); + }); + connect(&m_checker, &UpdateChecker::sig_showDialog, this, [this]() { show(); raise(); activateWindow(); - } -} - -QString UpdateDialog::findDownloadUrlForRelease(const QJsonObject &releaseObject) const -{ - // Compile architecture-specific regex - static const auto archRegex = QRegularExpression(getArchitectureRegexPattern(), - QRegularExpression::CaseInsensitiveOption); - - auto assets = releaseObject.value("assets").toArray(); - for (const QJsonValueRef item : assets) { - const auto asset = item.toObject(); - const QString name = asset.value("name").toString(); - const QString url = asset.value("browser_download_url").toString(); - - if (name.isEmpty() || url.isEmpty()) { - continue; - } - - if (!name.contains(archRegex)) { - continue; - } - - switch (CURRENT_PACKAGE) { - case PackageEnum::Source: - break; - case PackageEnum::Deb: - if (name.endsWith(".deb", Qt::CaseInsensitive)) { - return url; - } - break; - case PackageEnum::Dmg: - if (name.endsWith(".dmg", Qt::CaseInsensitive)) { - return url; - } - break; - case PackageEnum::Nsis: - if (name.endsWith(".exe", Qt::CaseInsensitive)) { - return url; - } - break; - case PackageEnum::AppImage: - if (name.endsWith(".AppImage", Qt::CaseInsensitive)) { - return url; - } - break; - case PackageEnum::AppX: - if (name.endsWith(".appx", Qt::CaseInsensitive)) { - return url; - } - break; - case PackageEnum::Flatpak: - if (name.endsWith(".flatpak", Qt::CaseInsensitive)) { - return url; - } - break; - case PackageEnum::Snap: - if (name.endsWith(".snap", Qt::CaseInsensitive)) { - return url; - } - break; - case PackageEnum::Wasm: - if (name.endsWith(".zip", Qt::CaseInsensitive)) { - return url; - } - break; - } - } - - const QString fallbackUrl = releaseObject.value("html_url").toString(); - if (!fallbackUrl.isEmpty()) { - return fallbackUrl; - } - - return "https://github.com/MUME/MMapper/releases"; + }); } -void UpdateDialog::managerFinished(QNetworkReply *reply) +void UpdateDialog::open() { - const RAIICallback deleteLaterRAII{[&reply]() { reply->deleteLater(); }}; - // REVISIT: Timeouts, errors, etc - if (reply->error() != QNetworkReply::NoError) { - qWarning() << reply->errorString(); - return; - } - const QString answer = reply->readAll(); - QJsonParseError error; - const QJsonDocument doc = QJsonDocument::fromJson(answer.toUtf8(), &error); - if (doc.isNull()) { - qWarning() << error.errorString(); - return; - } - if (!doc.isObject()) { - qWarning() << answer; - return; - } - const QJsonObject obj = doc.object(); - - if (isMMapperBeta() && reply->request().url().toString().contains("/ref/tags/")) { - const QJsonObject objNode = obj.value("object").toObject(); - const QString remoteCommitHash = objNode.value("sha").toString(); - const QString localCommitHash = std::invoke([]() -> QString { - static const QRegularExpression hashRegex(R"(-g([0-9a-fA-F]+)$)"); - QRegularExpressionMatch match = hashRegex.match(QString::fromUtf8(getMMapperVersion())); - if (match.hasMatch()) { - return match.captured(1); - } - return ""; - }); - qInfo() << "Updater comparing: CURRENT=" << localCommitHash - << "LATEST=" << remoteCommitHash.left(10); - if (!localCommitHash.isEmpty() && remoteCommitHash.startsWith(localCommitHash)) { - setUpdateStatus(tr("You are on the latest beta!"), false, false); - return; - } - - QNetworkRequest request( - QStringLiteral("https://github.com/_gh/api/repos/mume/mmapper/releases/tags/beta")); - request.setHeader(QNetworkRequest::ServerHeader, "application/json"); - m_manager.get(request); - return; - } - - QString latestTag; - if (!isMMapperBeta()) { - if (!obj.contains("tag_name") || !obj["tag_name"].isString()) { - qWarning() << "Release 'tag_name' is missing or not a string."; - setUpdateStatus(tr("Could not determine release version details."), false, false); - return; - } - latestTag = obj["tag_name"].toString(); - const QString currentVersion = QString::fromUtf8(getMMapperVersion()); - const CompareVersion latest(latestTag); - static CompareVersion current(currentVersion); - qInfo() << "Updater comparing: CURRENT=" << current << "LATEST=" << latest; - if (current == latest) { - setUpdateStatus(tr("You are up to date!"), false, false); - return; - } else if (current > latest) { - setUpdateStatus(tr("No newer update available."), false, false); - return; - } - } - m_downloadUrl = findDownloadUrlForRelease(obj); - setUpdateStatus(QString("A new %1version of MMapper is available!" - "\n" - "\n" - "Press 'Upgrade' to download %2!") - .arg(isMMapperBeta() ? "beta " : "", isMMapperBeta() ? "it" : latestTag), - true, - true); + m_checker.check(); } diff --git a/src/mainwindow/UpdateDialog.h b/src/mainwindow/UpdateDialog.h index 64a3a2205..2ea9c79b2 100644 --- a/src/mainwindow/UpdateDialog.h +++ b/src/mainwindow/UpdateDialog.h @@ -3,47 +3,19 @@ // Copyright (C) 2019 The MMapper Authors // Author: Nils Schimmelmann (Jahara) -#include "../global/Array.h" +#include "../global/macros.h" +#include "UpdateChecker.h" -#include #include #include #include -#include -#include - -class NODISCARD CompareVersion final -{ -private: - MMapper::Array m_parts; - -public: - explicit CompareVersion(const QString &versionStr) noexcept; - -public: - NODISCARD bool operator>(const CompareVersion &other) const; - NODISCARD bool operator==(const CompareVersion &other) const; - - NODISCARD int major() const { return m_parts[0]; } - NODISCARD int minor() const { return m_parts[1]; } - NODISCARD int patch() const { return m_parts[2]; } - -public: - NODISCARD QString toQString() const; - explicit operator QString() const { return toQString(); } - friend QDebug operator<<(QDebug os, const CompareVersion &compareVersion) - { - return os << compareVersion.toQString(); - } -}; class NODISCARD_QOBJECT UpdateDialog : public QDialog { Q_OBJECT private: - QNetworkAccessManager m_manager; - QString m_downloadUrl; + UpdateChecker m_checker; QLabel *m_text = nullptr; QDialogButtonBox *m_buttonBox = nullptr; @@ -51,11 +23,4 @@ class NODISCARD_QOBJECT UpdateDialog : public QDialog explicit UpdateDialog(QWidget *parent); void open() override; - -private slots: - void managerFinished(QNetworkReply *reply); - -private: - void setUpdateStatus(const QString &message, bool enableUpgradeButton, bool showAndUpdateDialog); - QString findDownloadUrlForRelease(const QJsonObject &releaseObject) const; }; diff --git a/src/mainwindow/findroomsdlg.h b/src/mainwindow/findroomsdlg.h index 732f7e144..c12aea48e 100644 --- a/src/mainwindow/findroomsdlg.h +++ b/src/mainwindow/findroomsdlg.h @@ -24,7 +24,7 @@ #pragma clang diagnostic pop #endif -class MapCanvas; +class MapCanvasWindow; class MapData; class QCloseEvent; class QObject; diff --git a/src/mainwindow/infomarkseditdlg.cpp b/src/mainwindow/infomarkseditdlg.cpp index 5b92aba16..a9c06730d 100644 --- a/src/mainwindow/infomarkseditdlg.cpp +++ b/src/mainwindow/infomarkseditdlg.cpp @@ -7,7 +7,7 @@ #include "../configuration/configuration.h" #include "../display/InfomarkSelection.h" -#include "../display/mapcanvas.h" +#include "../display/MapCanvasWindow.h" #include "../global/window_utils.h" #include "../map/coordinate.h" #include "../map/infomark.h" @@ -30,7 +30,7 @@ InfomarksEditDlg::InfomarksEditDlg(QWidget *const parent) void InfomarksEditDlg::setInfomarkSelection(const std::shared_ptr &is, MapData *const md, - MapCanvas *const mc) + MapCanvasWindow *const mc) { // NOTE: the selection is allowed to be null. assert(md != nullptr); diff --git a/src/mainwindow/infomarkseditdlg.h b/src/mainwindow/infomarkseditdlg.h index 8de008104..23eac54b4 100644 --- a/src/mainwindow/infomarkseditdlg.h +++ b/src/mainwindow/infomarkseditdlg.h @@ -17,7 +17,7 @@ class Coordinate; class InfomarkSelection; -class MapCanvas; +class MapCanvasWindow; class MapData; class QCloseEvent; class QObject; @@ -33,7 +33,7 @@ class NODISCARD_QOBJECT InfomarksEditDlg final : public QDialog, private Ui::Inf std::shared_ptr m_selection; std::vector m_markers; MapData *m_mapData = nullptr; - MapCanvas *m_mapCanvas = nullptr; + MapCanvasWindow *m_mapCanvas = nullptr; public: explicit InfomarksEditDlg(QWidget *parent); @@ -41,7 +41,7 @@ class NODISCARD_QOBJECT InfomarksEditDlg final : public QDialog, private Ui::Inf void setInfomarkSelection(const std::shared_ptr &is, MapData *md, - MapCanvas *mc); + MapCanvasWindow *mc); private: void connectAll(); diff --git a/src/mainwindow/mainwindow-async.cpp b/src/mainwindow/mainwindow-async.cpp index c97ecd801..a0727c94a 100644 --- a/src/mainwindow/mainwindow-async.cpp +++ b/src/mainwindow/mainwindow-async.cpp @@ -3,9 +3,8 @@ #include "mainwindow-async.h" -#include "../client/ClientWidget.h" #include "../display/MapCanvasData.h" -#include "../display/mapcanvas.h" +#include "../display/MapCanvasWindow.h" #include "../display/mapwindow.h" #include "../global/AnsiOstream.h" #include "../global/AnsiTextUtils.h" @@ -15,13 +14,13 @@ #include "../global/utils.h" #include "../global/window_utils.h" #include "../mapstorage/MapDestination.h" +#include "../mapstorage/MapLoadHelper.h" #include "../mapstorage/MmpMapStorage.h" #include "../mapstorage/PandoraMapStorage.h" #include "../mapstorage/XmlMapStorage.h" #include "../mapstorage/jsonmapstorage.h" #include "../mapstorage/mapstorage.h" #include "../pathmachine/mmapper2pathmachine.h" -#include "findroomsdlg.h" #include "mainwindow.h" #include "utils.h" @@ -46,130 +45,6 @@ constexpr auto yellow = getRawAnsi(AnsiColor16Enum::yellow); namespace mwa_detail { -NODISCARD bool detectMm2Binary(QIODevice &device) -{ - auto result = getMM2FileVersion(device); - device.seek(0); - return result.has_value(); -} - -// MMapper2 XML map (as opposed to Pandora XML map) -NODISCARD bool detectMm2Xml(QIODevice &device) -{ - const QByteArray line = device.readLine(64); - const QByteArray line2 = device.readLine(64); - device.seek(0); - return line.contains("xml version") && line2.contains("mmapper2xml"); -} - -// Pandora XML map -NODISCARD bool detectPandora(QIODevice &device) -{ - QXmlStreamReader xml(&device); - xml.readNextStartElement(); - if (xml.error() != QXmlStreamReader::NoError) { - device.seek(0); - return false; - } - if (xml.name() != QStringLiteral("map")) { - device.seek(0); - return false; - } - if (xml.attributes().isEmpty() || !xml.attributes().hasAttribute("rooms")) { - device.seek(0); - return false; - } - device.seek(0); - return true; -} - -template -NODISCARD std::unique_ptr make(const AbstractMapStorage::Data &data, - MainWindow *const mw) -{ - return std::make_unique(data, mw); -} - -class NODISCARD FileFormatHelper final -{ -public: - using DetectFn = bool (*)(QIODevice &); - using MakeFn = std::unique_ptr (*)(const AbstractMapStorage::Data &data, - MainWindow *mw); - -private: - DetectFn m_detect = nullptr; - MakeFn m_make = nullptr; - -public: - explicit FileFormatHelper(const DetectFn d, const MakeFn m) - : m_detect{d} - , m_make{m} - { - assert(m_detect != nullptr); - assert(m_make != nullptr); - if (m_detect == nullptr || m_make == nullptr) { - std::abort(); - } - } - -private: - static void logException(const mm::source_location loc) - { - try { - std::rethrow_exception(std::current_exception()); - } catch (const std::exception &ex) { - mm::WarningOstream{loc} << ex.what(); - } catch (...) { - mm::WarningOstream{loc} << "Unknown exception."; - } - } - -public: - NODISCARD bool detect(QIODevice &device) const - { - try { - return m_detect(device); - } catch (...) { - logException(MM_SOURCE_LOCATION()); - return false; - } - } - NODISCARD std::unique_ptr make(const AbstractMapStorage::Data &data, - MainWindow *mw) const - { - try { - return m_make(data, mw); - } catch (...) { - logException(MM_SOURCE_LOCATION()); - throw; - } - } -}; - -const std::array formats{ - FileFormatHelper{&detectMm2Binary, &make}, - FileFormatHelper{&detectMm2Xml, &make}, - FileFormatHelper{&detectPandora, &make}, -}; - -NODISCARD bool hasRooms(const RawMapLoadData &data) -{ - return !data.rooms.empty(); -} - -NODISCARD bool hasMarkers(const RawMapLoadData &data) -{ - return !data.markers.empty(); -} - -// true if the map contains either rooms or markers; -// e.g. the map might ONLY contain markers. -NODISCARD bool hasValidData(const RawMapLoadData &data) -{ - return hasRooms(data) || hasMarkers(data); -} - template NODISCARD PollResultEnum wait_for(std::future &future, const std::chrono::milliseconds ms) { @@ -202,55 +77,13 @@ NODISCARD std::optional extract(std::future> &future, MainWi namespace background { -NODISCARD std::optional load_map_data(AbstractMapStorage &storage) -{ - if (!storage.canLoad()) { - return std::nullopt; - } - - ProgressCounter &pc = storage.getProgressCounter(); - pc.setCurrentTask(ProgressMsg{/*"phase 1: "*/ "load from disk"}); - std::optional opt_data = storage.loadData(); - if (!opt_data) { - return std::nullopt; - } - - auto &data = opt_data.value(); - pc.reset(); - - pc.setCurrentTask(ProgressMsg{/*"phase 2: "*/ "construct map from raw rooms and infomarks"}); - auto mapPair = Map::fromRooms(pc, - std::exchange(data.rooms, {}), - std::exchange(data.markers, {})); - - pc.setCurrentTask(ProgressMsg{"finished building map"}); - - MapLoadData result; - result.mapPair = std::exchange(mapPair, {}); - result.position = data.position; - result.filename = data.filename; - result.readonly = data.readonly; - - return result; -} +// The map-loading/merging logic lives in maploadhelper::loadMapData()/ +// maploadhelper::mergeMapData() (see mapstorage/MapLoadHelper.h) so other +// hosts can share it without depending on MainWindow. NODISCARD std::optional merge_map_data(AbstractMapStorage &storage, const MapData &mapData) { - if (!storage.canLoad()) { - return std::nullopt; - } - - ProgressCounter &pc = storage.getProgressCounter(); - pc.setCurrentTask(ProgressMsg{"phase 1: load from disk"}); - std::optional opt_data = storage.loadData(); - - if (!opt_data || !mwa_detail::hasValidData(*opt_data)) { - return std::nullopt; - } - - pc.setCurrentTask(ProgressMsg{"phase 2: merge the new map data"}); - // TODO: move ownership of the counter out of the storage object - return MapData::mergeMapData(pc, mapData.getCurrentMap(), opt_data.value()); + return maploadhelper::mergeMapData(storage, mapData.getCurrentMap()); } NODISCARD bool save(AbstractMapStorage &storage, const MapData &mapData, const SaveModeEnum mode) @@ -497,8 +330,8 @@ NODISCARD ProgressCounter &MainWindow::AsyncIO::getProgressCounter() const void MainWindow::AsyncIO::resetExtraBlockers() { - // NOTE: ~ExtraBlockers() calls ~CanvasHider(), which calls MapCanvas::show(), - // which calls MapCanvas::paintGL(), which kicks off an async job to create the map + // NOTE: ~ExtraBlockers() calls ~CanvasHider(), which calls MapCanvasWindow::show(), + // which calls MapCanvasWindow::paintGL(), which kicks off an async job to create the map // batches, so this should not be called before mapCanvas.slot_dataLoaded(), // since that function flags async map batches to be ignored. When that happens, // we have to build the meshes twice before they're displayed. @@ -555,7 +388,7 @@ struct NODISCARD MainWindow::AsyncLoader final : public AsyncBase { AbstractMapStorage &storage = deref(m_pStorage); storage.setProgressCounter(sharedPc); - return background::load_map_data(storage); + return maploadhelper::loadMapData(storage); } private: @@ -742,21 +575,7 @@ MainWindow::AsyncSaver::~AsyncSaver() = default; std::unique_ptr MainWindow::getLoadOrMergeMapStorage( std::shared_ptr &pSource) { - auto tmp = std::invoke([this, &pSource]() -> std::unique_ptr { - const AbstractMapStorage::Data data{pSource}; - auto &source = deref(pSource); - auto pDevice = source.getIODevice(); - auto &device = deref(pDevice); - for (const auto &fmt : mwa_detail::formats) { - if (!device.seek(0)) { - throw std::runtime_error("Failed to seek to beginning."); - } - if (fmt.detect(device)) { - return fmt.make(data, this); - } - } - throw std::runtime_error("Unrecognized file format"); - }); + auto tmp = maploadhelper::detectAndCreateStorage(pSource, this); AbstractMapStorage *const pStorage = tmp.get(); connect(pStorage, &AbstractMapStorage::sig_log, this, &MainWindow::slot_log); diff --git a/src/mainwindow/mainwindow-compact.cpp b/src/mainwindow/mainwindow-compact.cpp new file mode 100644 index 000000000..c1c0262fa --- /dev/null +++ b/src/mainwindow/mainwindow-compact.cpp @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +// The compact layout for small (phone-sized) windows: everything MainWindow +// does differently while compact lives here, so that the policy +// (CompactLayout.h) and its realization can be read as one unit. The layout +// is chosen once at startup from the screen (see showEvent()) and is +// otherwise a manual Window > "Compact Layout" toggle; it does not follow +// window resizes, since flipping the whole window layout under the user is +// worse than a briefly cramped one. +// Elsewhere in MainWindow only three places consult m_compact: the menu bar +// and status bar toggles (slot_setShowMenuBar(), slot_setShowStatusBar()) +// and the hidden menu bar's hover peek (eventFilter()). + +#include "../client/ClientWidget.h" +#include "../client/displaywidget.h" +#include "../configuration/configuration.h" +#include "../display/mapwindow.h" +#include "../global/ConfigConsts-Computed.h" +#include "CompactLayout.h" +#include "mainwindow.h" + +#include + +#include +#include +#include + +QToolButton *MainWindow::createMenuButton() +{ + // "\u2630": the whole menu (see m_appMenu). + QMenu *const menu = m_appMenu; + auto *const menuButton = new QToolButton(statusBar()); + menuButton->setText(QStringLiteral("\u2630")); + menuButton->setToolTip(tr("Menu")); + menuButton->setToolButtonStyle(Qt::ToolButtonTextOnly); + menuButton->setAutoRaise(true); + QFont font = menuButton->font(); + font.setPointSizeF(font.pointSizeF() * CompactLayout::TAB_FONT_SCALE); + menuButton->setFont(font); + // Not setMenu()/InstantPopup: QToolButton shows its menu with + // QMenu::exec(), a nested event loop, which is unavailable on wasm. + connect(menuButton, &QToolButton::clicked, menu, [menuButton, menu]() { + menu->popup(menuButton->mapToGlobal(QPoint(0, 0))); + }); + return menuButton; +} + +QWidget *MainWindow::createCompactActionBar() +{ + auto *const bar = new QWidget(statusBar()); + auto *const layout = new QHBoxLayout(bar); + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(0); + + // The map operations touch has no wheel or keyboard for (zoom is a pinch). + for (QAction *const action : {layerUpAct, layerDownAct, centerOnPlayerAct}) { + auto *const button = new QToolButton(bar); + button->setDefaultAction(action); + button->setIconSize(QSize(24, 24)); + button->setAutoRaise(true); + layout->addWidget(button); + } + return bar; +} + +void MainWindow::setCompactLayout(const bool compact) +{ + if (!m_layoutRestored) { + return; // see showEvent() + } + if (compact == m_compact) { + return; + } + m_compact = compact; + compactLayoutAct->setChecked(compact); + applyCompactMenuBar(compact); + + if (compact) { + m_expandedState = saveState(); + if (!m_compactState.isEmpty() && restoreState(m_compactState)) { + applyCompactChrome(true); + fitCompactWindowToScreen(); + return; + } + + // No usable compact state yet: build the default one. + buildDefaultCompactLayout(); + applyCompactChrome(true); + fitCompactWindowToScreen(); + } else { + m_compactState = saveState(); + if (!restoreState(m_expandedState)) { + qWarning() << "Unable to restore the expanded window layout"; + } + applyCompactChrome(false); + } +} + +void MainWindow::buildDefaultCompactLayout() +{ + for (QToolBar *const toolBar : findChildren()) { + toolBar->hide(); + } + + // One tabbed group so a single panel shows at a time, below the + // map; hidden docks stay hidden and appear as tabs when shown. + const std::array docks{m_dockDialogClient, + m_dockDialogGroup, + m_dockDialogRoom, + m_dockDialogDescription, + m_dockDialogLog, + m_dockDialogAdventure, + m_dockDialogTimers, + m_dockDialogAsync}; + QDockWidget *first = nullptr; + for (QDockWidget *const dock : docks) { + dock->setFloating(false); + addDockWidget(Qt::BottomDockWidgetArea, dock); + if (first == nullptr) { + first = dock; + } else { + tabifyDockWidget(first, dock); + } + } + + // The client is what a phone user is here for: put its tab in front + // and give the group its share of the height, leaving the map above. + m_dockDialogClient->raise(); + resizeDocks({m_dockDialogClient}, + {CompactLayout::clientHeight(compactLayoutProbeSize())}, + Qt::Vertical); +} + +void MainWindow::slot_resetWindowLayout() +{ + // Both layouts go back to their defaults: the one showing right now, and + // the stored one for the other mode. The docks' visibility is part of + // the state, so hidden panels come back too. + if (m_compact) { + buildDefaultCompactLayout(); + applyCompactChrome(true); + m_expandedState = m_defaultExpandedState; + } else { + if (!restoreState(m_defaultExpandedState)) { + qWarning() << "Unable to restore the default window layout"; + } + m_compactState.clear(); + fitClientDockToTerminal(); + } +} + +void MainWindow::fitClientDockToTerminal() +{ + // The default expanded layout gives the client its configured terminal + // size (80x24 unless changed) when the window has room for that and + // the map; QMainWindow's own default split does not consult it. + const QSize terminal = deref(m_dockDialogClient).widget()->sizeHint(); + const QSize mapMin = deref(m_mapWindow).minimumSize(); + if (width() - terminal.width() >= mapMin.width()) { + resizeDocks({m_dockDialogClient}, {terminal.width()}, Qt::Horizontal); + } + if (height() - terminal.height() >= mapMin.height()) { + resizeDocks({m_dockDialogClient}, {terminal.height()}, Qt::Vertical); + } +} + +QSize MainWindow::compactLayoutProbeSize() const +{ + const QScreen *const scr = screen(); + return CompactLayout::probeSize(size(), scr != nullptr ? scr->availableSize() : QSize()); +} + +void MainWindow::fitCompactWindowToScreen() +{ + // Once the compact layout's smaller minimum size has taken effect (the + // layout settles on the next event loop pass), pull a window that the + // expanded layout had pushed past the screen's edge back onto it. + QMetaObject::invokeMethod( + this, + [this]() { + const QScreen *const scr = screen(); + if (scr == nullptr) { + return; + } + const QRect avail = scr->availableGeometry(); + if (width() > avail.width() || height() > avail.height()) { + setGeometry(avail); + } + }, + Qt::QueuedConnection); +} + +void MainWindow::applyPanelScrollGesture(const bool compact) +{ + // Kinetic scrolling for every panel (client output, log, tables). Mouse + // and wheel input are unaffected when expanded. While compact the + // gesture is taken from the (synthesized) left button instead, since a + // browser can deliver a finger as pointer/mouse events rather than + // touch events; QScroller holds the press back until it is clear the + // finger is not scrolling, so a held press still selects text. + const auto gesture = compact ? QScroller::LeftMouseButtonGesture : QScroller::TouchGesture; + for (QAbstractScrollArea *const area : findChildren()) { + if (qobject_cast(area) != nullptr) { + continue; // scrolls touch itself; see DisplayWidget::mousePressEvent() + } + QScroller::grabGesture(area->viewport(), gesture); + } +} + +void MainWindow::applyCompactChrome(const bool compact) +{ + deref(m_clientWidget).setCompactLayout(compact); + applyPanelScrollGesture(compact); + deref(m_mapWindow).setScrollBarsSuppressed(compact); + // The action bar lives in the status bar, which therefore has to be + // shown while compact regardless of the setting. The path machine's + // state label and the size grip (touch cannot use it) make room for + // it on a phone-width bar. + m_compactActionBar->setVisible(compact); + m_pathMachineStatus->setVisible(!compact); + statusBar()->setSizeGripEnabled(!compact); + statusBar()->setVisible(compact || getConfig().general.showStatusBar); + + // Dock title bars: one tab strip already names the visible panel, and + // the float/close buttons are not touch targets, so the title bars are + // replaced by empty widgets while compact (which also pins the docks). + for (QDockWidget *const dock : findChildren()) { + QWidget *const old = dock->titleBarWidget(); + dock->setTitleBarWidget(compact ? new QWidget(dock) : nullptr); + delete old; + } + + // The tab strip QMainWindow creates for tabified docks: stretch the + // tabs across the width and use a larger font so they are finger-sized. + for (QTabBar *const tabBar : findChildren()) { + if (qobject_cast(tabBar->parentWidget()) == nullptr) { + continue; // a widget's own tab bar, not the dock strip + } + tabBar->setExpanding(compact); + QFont font = this->font(); + if (compact) { + font.setPointSizeF(font.pointSizeF() * CompactLayout::TAB_FONT_SCALE); + } + tabBar->setFont(font); + } +} + +void MainWindow::applyCompactMenuBar(const bool compact) +{ + // While compact the menu bar's row is given back to the content; the + // menus are reached through the status bar's "\u2630" button instead + // (see m_appMenu). The Mac's native menu bar lives outside the + // window, so it costs no space and is left alone (see + // slot_setShowMenuBar()). + if constexpr (CURRENT_PLATFORM != PlatformEnum::Mac) { + menuBar()->setVisible(!compact && getConfig().general.showMenuBar); + m_menuButton->setVisible(compact); + } +} diff --git a/src/mainwindow/mainwindow.cpp b/src/mainwindow/mainwindow.cpp index 6af18f036..8647333d4 100644 --- a/src/mainwindow/mainwindow.cpp +++ b/src/mainwindow/mainwindow.cpp @@ -6,6 +6,7 @@ #include "mainwindow.h" +#include "../adventure/AdventureLogModel.h" #include "../adventure/adventuretracker.h" #include "../adventure/adventurewidget.h" #include "../adventure/xpstatuswidget.h" @@ -15,7 +16,7 @@ #include "../clock/mumeclockwidget.h" #include "../display/InfomarkSelection.h" #include "../display/MapCanvasData.h" -#include "../display/mapcanvas.h" +#include "../display/MapCanvasWindow.h" #include "../display/mapwindow.h" #include "../global/AsyncTasks.h" #include "../global/PrintUtils.h" @@ -36,6 +37,7 @@ #include "../timers/TimerWidget.h" #include "../viewers/TopLevelWindows.h" #include "AudioVolumeSlider.h" +#include "CompactLayout.h" #include "MapZoomSlider.h" #include "TasksPanel.h" #include "UpdateDialog.h" @@ -47,6 +49,7 @@ #include "roomeditattrdlg.h" #include "utils.h" +#include #include #include @@ -158,7 +161,7 @@ MainWindow::MainWindow() m_mediaLibrary = new MediaLibrary(this); m_audioManager = new AudioManager(deref(m_mediaLibrary), deref(m_gameObserver), this); - // View -> Side Panels -> Log Panel + // Window -> Side Panels -> Log Panel std::invoke([this] { auto *const dock = new QDockWidget(tr("Log Panel"), this); dock->setObjectName("DockWidgetLog"); @@ -174,11 +177,12 @@ MainWindow::MainWindow() dock->setWidget(logWindow); dock->hide(); - m_dockDialogLog = dock; m_logWindow = logWindow; + + m_dockDialogLog = dock; }); - // View -> Side Panels -> Group Panel and Tools -> Group Manager + // Window -> Side Panels -> Group Panel and Tools -> Group Manager std::invoke([this] { auto *const w = new GroupWidget(m_groupManager, m_mapData, this); auto *const dock = new QDockWidget(tr("Group Panel"), this); @@ -194,7 +198,7 @@ MainWindow::MainWindow() m_dockDialogGroup = dock; }); - // View -> Side Panels -> Room Panel (Mobs) + // Window -> Side Panels -> Room Panel (Mobs) std::invoke([this] { auto *const roomManager = new RoomManager(this); roomManager->setObjectName("RoomManager"); @@ -219,6 +223,7 @@ MainWindow::MainWindow() dock->hide(); m_roomWidget = w; + m_dockDialogRoom = dock; }); @@ -232,8 +237,9 @@ MainWindow::MainWindow() std::invoke([this] { auto *const adv = new AdventureTracker(deref(m_gameObserver), this); + + // Window -> Side Panels -> Adventure Panel (Trophy XP, Achievements, Hints, etc) auto *const w = new AdventureWidget(deref(adv), this); - // View -> Side Panels -> Adventure Panel (Trophy XP, Achievements, Hints, etc) auto *const dock = new QDockWidget(tr("Adventure Panel"), this); dock->setObjectName("DockWidgetGameConsole"); dock->setAllowedAreas(Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea); @@ -243,12 +249,13 @@ MainWindow::MainWindow() dock->setWidget(w); dock->hide(); - m_adventureTracker = adv; m_adventureWidget = w; + + m_adventureTracker = adv; m_dockDialogAdventure = dock; }); - // View -> Side Panels -> Description / Area Panel + // Window -> Side Panels -> Description / Area Panel std::invoke([this] { auto *const w = new DescriptionWidget(deref(m_mediaLibrary), this); auto *const dock = new QDockWidget(tr("Description Panel"), this); @@ -267,6 +274,7 @@ MainWindow::MainWindow() std::invoke([this] { auto *const timers = new CTimers(this); + auto *const w = new TimerWidget(deref(timers), this); auto *const dock = new QDockWidget(tr("Timers Panel"), this); dock->setObjectName("DockWidgetTimers"); @@ -275,8 +283,9 @@ MainWindow::MainWindow() dock->setWidget(w); dock->hide(); - m_timers = timers; m_timerWidget = w; + + m_timers = timers; m_dockDialogTimers = dock; }); @@ -321,7 +330,7 @@ MainWindow::MainWindow() }); }); - // View -> Side Panels -> Client Panel + // Window -> Side Panels -> Client Panel std::invoke([this] { auto *const timers = m_dockDialogTimers; std::ignore = deref(timers); @@ -332,7 +341,7 @@ MainWindow::MainWindow() deref(m_groupManager), deref(m_mumeClock), deref(m_timers), - deref(getCanvas()), + deref(getCanvas()).getCore(), deref(m_gameObserver), this); @@ -399,6 +408,9 @@ MainWindow::MainWindow() connect(m_mapData, &MapData::sig_generateBaseMap, this, &MainWindow::slot_generateBaseMap); + applyPanelScrollGesture(false); + + m_defaultExpandedState = saveState(); readSettings(); g_mainWindow = this; } @@ -434,7 +446,8 @@ void MainWindow::readSettings() #define XFOREACH_MY_SETTINGS(X) \ X(firstRun) \ X(windowGeometry) \ - X(windowState) + X(windowState) \ + X(windowStateCompact) // member variable declarations XFOREACH_MY_SETTINGS(X_DECL) @@ -477,13 +490,17 @@ void MainWindow::readSettings() // Check if the window was moved to a screen with a different DPI getCanvas()->screenChanged(); } + + m_compactState = settings.windowStateCompact; } void MainWindow::writeSettings() { auto &savedConfig = setConfig().general; savedConfig.windowGeometry = saveGeometry(); - savedConfig.windowState = saveState(); + // Each layout persists its own state; see setCompactLayout(). + savedConfig.windowState = m_compact ? m_expandedState : saveState(); + savedConfig.windowStateCompact = m_compact ? saveState() : m_compactState; } void MainWindow::wireConnections() @@ -493,51 +510,59 @@ void MainWindow::wireConnections() m_pathMachine, &PathMachine::slot_releaseAllPaths); - MapCanvas *const canvas = getCanvas(); - connect(m_mapData, &MapFrontend::sig_clearingMap, canvas, &MapCanvas::slot_clearAllSelections); + MapCanvasWindow *const canvas = getCanvas(); - connect(m_pathMachine, - &Mmapper2PathMachine::sig_playerMoved, + connect(m_mapData, + &MapFrontend::sig_clearingMap, canvas, - &MapCanvas::slot_moveMarker); + &MapCanvasWindow::slot_clearAllSelections); connect(m_pathMachine, &Mmapper2PathMachine::sig_playerMoved, - m_descriptionWidget, - [this](const RoomId &id) { - if (const auto room = m_mapData->getRoomHandle(id)) { - m_descriptionWidget->updateRoom(room); - m_audioManager->onAreaChanged(room.getArea()); - } - }); + canvas, + &MapCanvasWindow::slot_moveMarker); + + connect(m_pathMachine, &Mmapper2PathMachine::sig_playerMoved, this, [this](const RoomId &id) { + if (const auto room = m_mapData->getRoomHandle(id)) { + updateDescriptionRoom(room); + m_audioManager->onAreaChanged(room.getArea()); + } + }); connect(m_mapData, &MapData::sig_onPositionChange, this, [this]() { m_pathMachine->onPositionChange(m_mapData->getCurrentRoomId()); - m_descriptionWidget->updateRoom(m_mapData->getCurrentRoom()); + updateDescriptionRoom(m_mapData->getCurrentRoom()); m_audioManager->onAreaChanged(m_mapData->getCurrentRoom().getArea()); }); connect(m_mapData, &MapData::sig_onForcedPositionChange, canvas, - &MapCanvas::slot_onForcedPositionChange); + &MapCanvasWindow::slot_onForcedPositionChange); // moved to mapwindow connect(m_mapData, &MapData::sig_mapSizeChanged, m_mapWindow, &MapWindow::slot_setScrollBars); - connect(m_prespammedPath, &PrespammedPath::sig_update, canvas, &MapCanvas::slot_requestUpdate); + connect(m_prespammedPath, + &PrespammedPath::sig_update, + canvas, + &MapCanvasWindow::slot_requestUpdate); connect(m_mapData, &MapData::sig_log, this, &MainWindow::slot_log); - connect(canvas, &MapCanvas::sig_log, this, &MainWindow::slot_log); + connect(canvas, &MapCanvasWindow::sig_log, this, &MainWindow::slot_log); connect(m_mapData, &MapData::sig_onDataChanged, this, [this]() { this->updateMapModified(); }); - connect(zoomInAct, &QAction::triggered, canvas, &MapCanvas::slot_zoomIn); - connect(zoomOutAct, &QAction::triggered, canvas, &MapCanvas::slot_zoomOut); - connect(zoomResetAct, &QAction::triggered, canvas, &MapCanvas::slot_zoomReset); + connect(zoomInAct, &QAction::triggered, canvas, &MapCanvasWindow::slot_zoomIn); + connect(centerOnPlayerAct, &QAction::triggered, canvas, &MapCanvasWindow::slot_centerOnPlayer); + connect(zoomOutAct, &QAction::triggered, canvas, &MapCanvasWindow::slot_zoomOut); + connect(zoomResetAct, &QAction::triggered, canvas, &MapCanvasWindow::slot_zoomReset); - connect(canvas, &MapCanvas::sig_newRoomSelection, this, &MainWindow::slot_newRoomSelection); - connect(canvas, &MapCanvas::sig_selectionChanged, this, [this]() { + connect(canvas, + &MapCanvasWindow::sig_newRoomSelection, + this, + &MainWindow::slot_newRoomSelection); + connect(canvas, &MapCanvasWindow::sig_selectionChanged, this, [this]() { if (m_roomSelection != nullptr && m_roomSelection->size()) { auto anyRoomAtOffset = [this](const Coordinate offset) -> bool { const auto &sel = deref(m_roomSelection); @@ -557,25 +582,28 @@ void MainWindow::wireConnections() } }); connect(canvas, - &MapCanvas::sig_newConnectionSelection, + &MapCanvasWindow::sig_newConnectionSelection, this, &MainWindow::slot_newConnectionSelection); connect(canvas, - &MapCanvas::sig_newInfomarkSelection, + &MapCanvasWindow::sig_newInfomarkSelection, this, &MainWindow::slot_newInfomarkSelection); connect(canvas, - &MapCanvas::sig_customContextMenuRequested, + &MapCanvasWindow::sig_customContextMenuRequested, this, &MainWindow::slot_showContextMenu); - connect(canvas, &MapCanvas::sig_dismissContextMenu, this, &MainWindow::slot_closeContextMenu); + connect(canvas, + &MapCanvasWindow::sig_dismissContextMenu, + this, + &MainWindow::slot_closeContextMenu); // Group connect(m_groupManager, &Mmapper2Group::sig_log, this, &MainWindow::slot_log); connect(m_groupManager, &Mmapper2Group::sig_updateMapCanvas, canvas, - &MapCanvas::slot_requestUpdate); + &MapCanvasWindow::slot_requestUpdate); connect(m_mapData, &MapFrontend::sig_clearingMap, m_groupWidget, &GroupWidget::slot_mapUnloaded); @@ -599,7 +627,7 @@ void MainWindow::wireConnections() connect(m_findRoomsDlg, &FindRoomsDlg::sig_newRoomSelection, canvas, - &MapCanvas::slot_setRoomSelection); + &MapCanvasWindow::slot_setRoomSelection); connect(m_findRoomsDlg, &FindRoomsDlg::sig_center, m_mapWindow, @@ -680,6 +708,7 @@ void MainWindow::createActions() exitAct = new QAction(QIcon::fromTheme("application-exit"), tr("E&xit"), this); exitAct->setShortcut(tr("Ctrl+Q")); + exitAct->setMenuRole(QAction::QuitRole); exitAct->setStatusTip(tr("Exit the application")); connect(exitAct, &QAction::triggered, this, &QWidget::close); if constexpr (CURRENT_PLATFORM == PlatformEnum::Wasm) { @@ -705,6 +734,7 @@ void MainWindow::createActions() tr("&Preferences"), this); preferencesAct->setShortcut(tr("Ctrl+P")); + preferencesAct->setMenuRole(QAction::PreferencesRole); preferencesAct->setStatusTip(tr("MMapper preferences")); connect(preferencesAct, &QAction::triggered, this, &MainWindow::slot_onPreferences); @@ -712,6 +742,7 @@ void MainWindow::createActions() mmapperCheckForUpdateAct = new QAction(QIcon(":/icons/mmapper-lo.svg"), tr("Check for &update"), this); + mmapperCheckForUpdateAct->setMenuRole(QAction::ApplicationSpecificRole); connect(mmapperCheckForUpdateAct, &QAction::triggered, this, @@ -731,6 +762,12 @@ void MainWindow::createActions() settingUpMmapperAct = new QAction(QIcon::fromTheme("help-faq"), tr("Get &Help"), this); connect(settingUpMmapperAct, &QAction::triggered, this, &MainWindow::slot_openSettingUpMmapper); + newcomerGuideAct = new QAction(QIcon::fromTheme("help-contents"), tr("&Newcomer's Guide"), this); + newcomerGuideAct->setStatusTip(tr("Open the guide for people new to MUME in your browser")); + connect(newcomerGuideAct, &QAction::triggered, this, []() { + QDesktopServices::openUrl(QUrl("https://docs.mume.org/newcomers")); + }); + actionReportIssue = new QAction(QIcon::fromTheme("help-browser"), tr("Report an &Issue..."), this); @@ -742,10 +779,12 @@ void MainWindow::createActions() connect(newbieAct, &QAction::triggered, this, &MainWindow::slot_openNewbieHelp); aboutAct = new QAction(QIcon::fromTheme("help-about"), tr("About &MMapper"), this); aboutAct->setStatusTip(tr("Show the application's About box")); + aboutAct->setMenuRole(QAction::AboutRole); connect(aboutAct, &QAction::triggered, this, &MainWindow::slot_about); aboutQtAct = new QAction(tr("About &Qt"), this); aboutQtAct->setStatusTip(tr("Show the Qt library's About box")); - connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); + aboutQtAct->setMenuRole(QAction::AboutQtRole); + connect(aboutQtAct, &QAction::triggered, this, &MainWindow::slot_aboutQt); zoomInAct = new QAction(QIcon::fromTheme("zoom-in", QIcon(":/icons/viewmag+.png")), tr("Zoom In"), @@ -781,6 +820,16 @@ void MainWindow::createActions() connect(showMenuBarAct, &QAction::triggered, this, &MainWindow::slot_setShowMenuBar); } + compactLayoutAct = new QAction(tr("Compact Layout"), this); + compactLayoutAct->setStatusTip( + tr("One panel at a time below the map, with the menus and map controls in the status bar")); + compactLayoutAct->setCheckable(true); + connect(compactLayoutAct, &QAction::toggled, this, &MainWindow::setCompactLayout); + + resetWindowLayoutAct = new QAction(tr("Reset Window Layout"), this); + resetWindowLayoutAct->setStatusTip(tr("Put the panels and toolbars back where they started")); + connect(resetWindowLayoutAct, &QAction::triggered, this, &MainWindow::slot_resetWindowLayout); + layerUpAct = new QAction(QIcon::fromTheme("go-up", QIcon(":/icons/layerup.png")), tr("Layer Up"), this); @@ -813,6 +862,11 @@ void MainWindow::createActions() layerResetAct->setStatusTip(tr("Layer Reset")); connect(layerResetAct, &QAction::triggered, this, &MainWindow::slot_onLayerReset); + centerOnPlayerAct = new QAction(QIcon::fromTheme("mark-location", QIcon(":/icons/goto.png")), + tr("Center on Player"), + this); + centerOnPlayerAct->setStatusTip(tr("Center the map on the player's room")); + mouseMode.modeConnectionSelectAct = new QAction(QIcon(":/icons/connectionselection.png"), tr("Select Connection"), this); @@ -978,24 +1032,24 @@ void MainWindow::createActions() findRoomsAct->setShortcut(tr("Ctrl+F")); connect(findRoomsAct, &QAction::triggered, this, &MainWindow::slot_onFindRoom); - clientAct = new QAction(QIcon(":/icons/online.png"), tr("&Launch mud client"), this); - clientAct->setStatusTip(tr("Launch the integrated mud client")); + clientAct = new QAction(QIcon(":/icons/terminal.png"), tr("&Play MUME"), this); + clientAct->setStatusTip(tr("Play MUME right here in MMapper")); connect(clientAct, &QAction::triggered, this, &MainWindow::slot_onLaunchClient); saveLogAct = new QAction(QIcon::fromTheme("document-save", QIcon(":/icons/save.png")), - tr("Save Log as &Plain Text..."), + tr("Save Game Log as &Text..."), this); connect(saveLogAct, &QAction::triggered, m_clientWidget, &ClientWidget::slot_saveLog); - saveLogAct->setStatusTip(tr("Save log as plain text file")); + saveLogAct->setStatusTip(tr("Save the game log as a plain text file")); saveLogAsHtmlAct = new QAction(QIcon::fromTheme("document-save", QIcon(":/icons/save.png")), - tr("Save Log as &HTML..."), + tr("Save Game Log as &HTML..."), this); connect(saveLogAsHtmlAct, &QAction::triggered, m_clientWidget, &ClientWidget::slot_saveLogAsHtml); - saveLogAsHtmlAct->setStatusTip(tr("Save log as HTML file")); + saveLogAsHtmlAct->setStatusTip(tr("Save the game log as an HTML file")); releaseAllPathsAct = new QAction(QIcon(":/icons/cancel.png"), tr("Release All Paths"), this); releaseAllPathsAct->setStatusTip(tr("Release all paths")); @@ -1115,7 +1169,10 @@ void MainWindow::createActions() rebuildMeshesAct = new QAction(QIcon(":/icons/graphicscfg.png"), tr("&Rebuild World"), this); rebuildMeshesAct->setStatusTip(tr("Reconstruct the world mesh to fix graphical rendering bugs")); rebuildMeshesAct->setCheckable(false); - connect(rebuildMeshesAct, &QAction::triggered, getCanvas(), &MapCanvas::slot_rebuildMeshes); + connect(rebuildMeshesAct, + &QAction::triggered, + getCanvas(), + &MapCanvasWindow::slot_rebuildMeshes); } static void setConfigMapMode(const MapModeEnum mode) @@ -1196,7 +1253,7 @@ void MainWindow::hideCanvas(const bool hide) // REVISIT: It seems that updates don't work if the canvas is hidden, // so we may want to save mapChanged() and other similar requests // and send them after we show the canvas. - if (MapCanvas *const canvas = getCanvas()) { + if (MapCanvasWindow *const canvas = getCanvas()) { if (hide) { canvas->hide(); } else { @@ -1228,11 +1285,6 @@ void MainWindow::setupMenuBar() } editMenu = menuBar()->addMenu(tr("&Edit")); - modeMenu = editMenu->addMenu(QIcon(":/icons/online.png"), tr("&Mode")); - modeMenu->addAction(mapperMode.playModeAct); - modeMenu->addAction(mapperMode.mapModeAct); - modeMenu->addAction(mapperMode.offlineModeAct); - editMenu->addSeparator(); editMenu->addAction(m_undoAction); editMenu->addAction(m_redoAction); editMenu->addSeparator(); @@ -1267,11 +1319,35 @@ void MainWindow::setupMenuBar() editMenu->addSeparator(); editMenu->addAction(findRoomsAct); - editMenu->addAction(preferencesAct); viewMenu = menuBar()->addMenu(tr("&View")); - viewMenu->addAction(mouseMode.modeMoveSelectAct); - QMenu *toolbars = viewMenu->addMenu(tr("&Toolbars")); + // Every mouse mode in one place (the checkable group shows the current + // one); each also stays next to the operations it enables, above. + QMenu *mouseModeMenu = viewMenu->addMenu(QIcon::fromTheme("input-mouse"), tr("&Mouse Mode")); + mouseModeMenu->addAction(mouseMode.modeMoveSelectAct); + mouseModeMenu->addAction(mouseMode.modeRoomRaypickAct); + mouseModeMenu->addAction(mouseMode.modeRoomSelectAct); + mouseModeMenu->addAction(mouseMode.modeInfomarkSelectAct); + mouseModeMenu->addAction(mouseMode.modeConnectionSelectAct); + mouseModeMenu->addAction(mouseMode.modeCreateInfomarkAct); + mouseModeMenu->addAction(mouseMode.modeCreateRoomAct); + mouseModeMenu->addAction(mouseMode.modeCreateConnectionAct); + mouseModeMenu->addAction(mouseMode.modeCreateOnewayConnectionAct); + viewMenu->addSeparator(); + viewMenu->addAction(zoomInAct); + viewMenu->addAction(zoomOutAct); + viewMenu->addAction(zoomResetAct); + viewMenu->addSeparator(); + viewMenu->addAction(layerUpAct); + viewMenu->addAction(layerDownAct); + viewMenu->addAction(layerResetAct); + viewMenu->addSeparator(); + viewMenu->addAction(centerOnPlayerAct); + viewMenu->addSeparator(); + viewMenu->addAction(rebuildMeshesAct); + + windowMenu = menuBar()->addMenu(tr("&Window")); + QMenu *toolbars = windowMenu->addMenu(tr("&Toolbars")); toolbars->addAction(fileToolBar->toggleViewAction()); toolbars->addAction(mapperModeToolBar->toggleViewAction()); toolbars->addAction(mouseModeToolBar->toggleViewAction()); @@ -1281,7 +1357,7 @@ void MainWindow::setupMenuBar() toolbars->addAction(connectionToolBar->toggleViewAction()); toolbars->addAction(settingsToolBar->toggleViewAction()); toolbars->addAction(audioToolBar->toggleViewAction()); - QMenu *sidepanels = viewMenu->addMenu(tr("&Side Panels")); + QMenu *sidepanels = windowMenu->addMenu(tr("&Side Panels")); sidepanels->addAction(m_dockDialogLog->toggleViewAction()); sidepanels->addAction(m_dockDialogClient->toggleViewAction()); sidepanels->addAction(m_dockDialogGroup->toggleViewAction()); @@ -1290,38 +1366,38 @@ void MainWindow::setupMenuBar() sidepanels->addAction(m_dockDialogDescription->toggleViewAction()); sidepanels->addAction(m_dockDialogTimers->toggleViewAction()); sidepanels->addAction(m_dockDialogAsync->toggleViewAction()); - viewMenu->addSeparator(); - viewMenu->addAction(zoomInAct); - viewMenu->addAction(zoomOutAct); - viewMenu->addAction(zoomResetAct); - viewMenu->addSeparator(); - viewMenu->addAction(layerUpAct); - viewMenu->addAction(layerDownAct); - viewMenu->addAction(layerResetAct); - viewMenu->addSeparator(); - viewMenu->addAction(rebuildMeshesAct); - viewMenu->addSeparator(); - viewMenu->addAction(showStatusBarAct); - viewMenu->addAction(showScrollBarsAct); + windowMenu->addSeparator(); + windowMenu->addAction(showStatusBarAct); + windowMenu->addAction(showScrollBarsAct); if constexpr (CURRENT_PLATFORM != PlatformEnum::Mac) { - viewMenu->addAction(showMenuBarAct); + windowMenu->addAction(showMenuBarAct); } - viewMenu->addAction(alwaysOnTopAct); + windowMenu->addAction(alwaysOnTopAct); + windowMenu->addSeparator(); + windowMenu->addAction(compactLayoutAct); + windowMenu->addAction(resetWindowLayoutAct); settingsMenu = menuBar()->addMenu(tr("&Tools")); - QMenu *clientMenu = settingsMenu->addMenu(QIcon(":/icons/terminal.png"), - tr("&Integrated Mud Client")); - clientMenu->addAction(clientAct); - clientMenu->addAction(saveLogAct); - clientMenu->addAction(saveLogAsHtmlAct); + modeMenu = settingsMenu->addMenu(QIcon(":/icons/online.png"), tr("&Mode")); + modeMenu->addAction(mapperMode.playModeAct); + modeMenu->addAction(mapperMode.mapModeAct); + modeMenu->addAction(mapperMode.offlineModeAct); + settingsMenu->addSeparator(); + settingsMenu->addAction(clientAct); + settingsMenu->addAction(saveLogAct); + settingsMenu->addAction(saveLogAsHtmlAct); + settingsMenu->addSeparator(); QMenu *pathMachineMenu = settingsMenu->addMenu(QIcon(":/icons/goto.png"), tr("&Path Machine")); pathMachineMenu->addAction(mouseMode.modeRoomSelectAct); pathMachineMenu->addSeparator(); pathMachineMenu->addAction(gotoRoomAct); pathMachineMenu->addAction(forceRoomAct); pathMachineMenu->addAction(releaseAllPathsAct); + settingsMenu->addSeparator(); + settingsMenu->addAction(preferencesAct); helpMenu = menuBar()->addMenu(tr("&Help")); + helpMenu->addAction(newcomerGuideAct); helpMenu->addAction(settingUpMmapperAct); helpMenu->addAction(actionReportIssue); if constexpr (!NO_UPDATER) { @@ -1336,14 +1412,15 @@ void MainWindow::setupMenuBar() mumeMenu->addAction(mumeWikiAct); helpMenu->addSeparator(); helpMenu->addAction(aboutAct); - if constexpr (CURRENT_PLATFORM != PlatformEnum::Wasm) { - helpMenu->addAction(aboutQtAct); - } - - // Qt activates a menu action's shortcut only through a visible menu bar, - // which "Always Show Menubar" can hide; held by the window as well, the - // shortcuts always work. - for (QMenu *const topLevel : {fileMenu, editMenu, viewMenu, settingsMenu, helpMenu}) { + helpMenu->addAction(aboutQtAct); + + m_appMenu = new QMenu(QStringLiteral("\u2630 ") + tr("Menu"), this); + for (QMenu *const topLevel : + {fileMenu, editMenu, viewMenu, windowMenu, settingsMenu, helpMenu}) { + m_appMenu->addMenu(topLevel); + // Qt activates a menu action's shortcut only through a visible menu + // bar, and the bar is hidden while compact or by "Always Show + // Menubar"; held by the window as well, the shortcuts always work. addActions(collectActions(*topLevel)); } } @@ -1400,6 +1477,12 @@ void MainWindow::slot_showContextMenu(const QPoint &pos) } } contextMenu.addSeparator(); + // The menus themselves, only when nothing else on screen leads to them: + // no menu bar, and no "\u2630" button (compact layout) in a shown status bar. + const bool menusReachable = menuBar()->isVisible() || (m_compact && statusBar()->isVisible()); + if (!menusReachable) { + contextMenu.addMenu(m_appMenu); + } QMenu *mouseMenu = contextMenu.addMenu(QIcon::fromTheme("input-mouse"), "Mouse Mode"); mouseMenu->addAction(mouseMode.modeMoveSelectAct); mouseMenu->addAction(mouseMode.modeRoomRaypickAct); @@ -1433,8 +1516,8 @@ void MainWindow::slot_alwaysOnTop() void MainWindow::slot_setShowStatusBar() { const bool showStatusBar = this->showStatusBarAct->isChecked(); - statusBar()->setVisible(showStatusBar); setConfig().general.showStatusBar = showStatusBar; + statusBar()->setVisible(showStatusBar || m_compact); // see applyCompactChrome() show(); } @@ -1459,7 +1542,11 @@ void MainWindow::slot_setShowMenuBar() m_dockDialogRoom->setMouseTracking(!showMenuBar); if (showMenuBar) { - menuBar()->show(); + // While compact the bar stays hidden (see applyCompactMenuBar()); + // the setting applies once the window is expanded again. + if (!m_compact) { + menuBar()->show(); + } m_dockDialogAdventure->removeEventFilter(this); m_dockDialogClient->removeEventFilter(this); m_dockDialogGroup->removeEventFilter(this); @@ -1560,6 +1647,7 @@ void MainWindow::setupToolBars() void MainWindow::setupStatusBar() { showStatusForever(tr("Say friend and enter...")); + statusBar()->insertPermanentWidget(0, new MumeClockWidget(deref(m_gameObserver), deref(m_mumeClock), @@ -1574,9 +1662,18 @@ void MainWindow::setupStatusBar() }); statusBar()->insertPermanentWidget(0, xpStatus); - auto *const pathmachineStatus = new QLabel(statusBar()); - connect(m_pathMachine, &Mmapper2PathMachine::sig_state, pathmachineStatus, &QLabel::setText); - statusBar()->insertPermanentWidget(0, pathmachineStatus); + m_pathMachineStatus = new QLabel(statusBar()); + connect(m_pathMachine, &Mmapper2PathMachine::sig_state, m_pathMachineStatus, &QLabel::setText); + statusBar()->insertPermanentWidget(0, m_pathMachineStatus); + + // Permanent: QStatusBar hides its normal widgets (and paints over their + // area) whenever a temporary message is shown, e.g. a menu's status tip. + m_menuButton = createMenuButton(); + m_menuButton->hide(); + statusBar()->insertPermanentWidget(0, m_menuButton); + m_compactActionBar = createCompactActionBar(); + m_compactActionBar->hide(); + statusBar()->insertPermanentWidget(1, m_compactActionBar); } void MainWindow::slot_onPreferences() @@ -1605,7 +1702,8 @@ void MainWindow::slot_onPreferences() } auto &configDialog = deref(m_configDialog); - configDialog.show(); + configDialog.setCompactLayout(m_compact); + mmqt::showFittedToScreen(configDialog); configDialog.raise(); configDialog.activateWindow(); } @@ -1651,7 +1749,10 @@ void MainWindow::slot_newInfomarkSelection(InfomarkSelection *const is) bool MainWindow::eventFilter(QObject *const obj, QEvent *const event) { - if (QApplication::activeWindow() == this && event->type() == QEvent::MouseMove) { + // The hidden menu bar's hover "peek" (see slot_setShowMenuBar()); in + // the compact layout the bar is always shown instead, since touch has + // no hover (see setCompactLayout()). + if (!m_compact && QApplication::activeWindow() == this && event->type() == QEvent::MouseMove) { if (const auto *const mouseEvent = dynamic_cast(event)) { QRect rect = geometry(); rect.setHeight(menuBar()->sizeHint().height()); @@ -1742,10 +1843,26 @@ void MainWindow::showEvent(QShowEvent *const event) // Start services on startup startServices(); + // The expanded layout from readSettings() is now realized, so + // saveState() is meaningful; only from here on may the layout switch. + // Queued so the first show's own layout pass has finished. The + // startup choice comes from the screen, since the expanded layout's + // minimum size can push the window past a phone's edge. + QMetaObject::invokeMethod( + this, + [this, firstRun = getConfig().general.firstRun]() { + m_layoutRestored = true; + setCompactLayout(CompactLayout::isCompact(compactLayoutProbeSize())); + if (firstRun && !m_compact) { + fitClientDockToTerminal(); + } + }, + Qt::QueuedConnection); + connect(window()->windowHandle(), &QWindow::screenChanged, this, [this]() { MapWindow &window = deref(m_mapWindow); CanvasDisabler canvasDisabler{window}; - MapCanvas &canvas = deref(getCanvas()); + MapCanvasWindow &canvas = deref(getCanvas()); canvas.screenChanged(); }); }); @@ -1757,6 +1874,11 @@ void MainWindow::slot_newFile() maybeSave([this]() { forceNewFile(); }); } +void MainWindow::updateDescriptionRoom(const RoomHandle &room) +{ + deref(m_descriptionWidget).updateRoom(room); +} + void MainWindow::forceNewFile() { { @@ -1769,7 +1891,7 @@ void MainWindow::forceNewFile() setCurrentFile(""); getCanvas()->slot_dataLoaded(); m_groupWidget->slot_mapLoaded(); - m_descriptionWidget->updateRoom(RoomHandle{}); + updateDescriptionRoom(RoomHandle{}); m_audioManager->onAreaChanged(RoomArea{}); /* @@ -1830,6 +1952,28 @@ void MainWindow::slot_reload() }); } +void MainWindow::slot_aboutQt() +{ + if constexpr (CURRENT_PLATFORM != PlatformEnum::Wasm) { + QApplication::aboutQt(); + return; + } + // QMessageBox::aboutQt() runs a nested event loop, which is unavailable + // on wasm; this is its non-blocking twin. + auto &box = mmqt::showInformation( + this, + tr("About Qt"), + tr("

About Qt

" + "

This program uses Qt version %1.

" + "

Qt is a C++ toolkit for cross-platform application development.

" + "

Please see qt.io for an overview of Qt, " + "and qt.io/licensing for " + "licensing information.

") + .arg(QString::fromLatin1(qVersion()))); + box.setTextFormat(Qt::RichText); + box.setIconPixmap(QPixmap(QStringLiteral(":/qt-project.org/qmessagebox/images/qtlogo-64.png"))); +} + void MainWindow::slot_about() { auto *about = new AboutDialog(this); @@ -1871,12 +2015,14 @@ void MainWindow::showAsyncFailure(const QString &fileName, void MainWindow::slot_onFindRoom() { - m_findRoomsDlg->show(); + mmqt::showFittedToScreen(deref(m_findRoomsDlg)); } void MainWindow::slot_onLaunchClient() { m_dockDialogClient->show(); + m_dockDialogClient->raise(); + deref(m_clientWidget).play(); } void MainWindow::setCurrentFile(const QString &fileName) @@ -1969,7 +2115,7 @@ void MainWindow::slot_onEditInfomarkSelection() auto *dlg = new InfomarksEditDlg(this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setInfomarkSelection(m_infoMarkSelection, m_mapData, getCanvas()); - dlg->show(); + mmqt::showFittedToScreen(*dlg); } void MainWindow::slot_onCreateRoom() @@ -1992,7 +2138,7 @@ void MainWindow::slot_onEditRoomSelection() { auto &roomEditDialog = deref(m_roomEditAttrDlg); roomEditDialog.setRoomSelection(m_roomSelection, m_mapData, getCanvas()); - roomEditDialog.show(); + mmqt::showFittedToScreen(roomEditDialog); connect(&roomEditDialog, &QDialog::finished, this, [this](MAYBE_UNUSED int result) { m_roomEditAttrDlg.reset(); }); @@ -2016,7 +2162,7 @@ void MainWindow::slot_onDeleteInfomarkSelection() } } - MapCanvas *const canvas = getCanvas(); + MapCanvasWindow *const canvas = getCanvas(); canvas->slot_clearInfomarkSelection(); } @@ -2035,7 +2181,7 @@ void MainWindow::slot_onDeleteRoomSelection() void MainWindow::slot_onDeleteConnectionSelection() { if (m_connectionSelection == nullptr) { - return; // previously called mapChanged for no good reason + return; } const auto &first = m_connectionSelection->getFirst(); @@ -2043,7 +2189,7 @@ void MainWindow::slot_onDeleteConnectionSelection() const auto &r1 = first.room; const auto &r2 = second.room; if (!r1 || !r2) { - return; // previously called mapChanged for no good reason + return; } const ExitDirEnum dir1 = first.direction; @@ -2229,21 +2375,21 @@ void MainWindow::keyReleaseEvent(QKeyEvent *event) QWidget::keyReleaseEvent(event); } -MapCanvas *MainWindow::getCanvas() const +MapCanvasWindow *MainWindow::getCanvas() const { return m_mapWindow->getCanvas(); } void MainWindow::mapChanged() const { - if (MapCanvas *const canvas = getCanvas()) { + if (MapCanvasWindow *const canvas = getCanvas()) { canvas->slot_mapChanged(); } } void MainWindow::setCanvasMouseMode(const CanvasMouseModeEnum mode) { - if (MapCanvas *const canvas = getCanvas()) { + if (MapCanvasWindow *const canvas = getCanvas()) { canvas->slot_setCanvasMouseMode(mode); } } @@ -2273,8 +2419,7 @@ void MainWindow::onSuccessfulLoad(const MapLoadData &mapLoadData) groupWidget.slot_mapLoaded(); pathMachine.onMapLoaded(); if (const auto room = mapData.getCurrentRoom()) { - auto &widget = deref(m_descriptionWidget); - widget.updateRoom(room); + updateDescriptionRoom(room); deref(m_audioManager).onAreaChanged(room.getArea()); } diff --git a/src/mainwindow/mainwindow.h b/src/mainwindow/mainwindow.h index 772255868..cee2e19dd 100644 --- a/src/mainwindow/mainwindow.h +++ b/src/mainwindow/mainwindow.h @@ -12,6 +12,7 @@ #include "../mapdata/roomselection.h" #include "../mapstorage/MapDestination.h" #include "../mapstorage/MapSource.h" +#include "../proxy/ProxyHost.h" #include "AsyncTypes.h" #include @@ -37,7 +38,7 @@ class GameObserver; class GroupWidget; class HotkeyManager; class InfomarkSelection; -class MapCanvas; +class MapCanvasWindow; class MapData; class MapWindow; class Mmapper2Group; @@ -49,6 +50,7 @@ class QAction; class QActionGroup; class QCloseEvent; class QFileDialog; +class QLabel; class QMenu; class QObject; class QPoint; @@ -56,6 +58,7 @@ class QProgressDialog; class QShowEvent; class QTextBrowser; class QToolBar; +class QToolButton; class QWidget; class RoomEditAttrDlg; class RoomManager; @@ -69,7 +72,7 @@ class MapDestination; struct MapLoadData; -class NODISCARD_QOBJECT MainWindow final : public QMainWindow +class NODISCARD_QOBJECT MainWindow final : public QMainWindow, public ProxyHost { Q_OBJECT @@ -109,6 +112,8 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow ClientWidget *m_clientWidget = nullptr; UpdateDialog *m_updateDialog = nullptr; + std::unique_ptr m_configDialog; + AdventureTracker *m_adventureTracker = nullptr; AdventureWidget *m_adventureWidget = nullptr; MediaLibrary *m_mediaLibrary = nullptr; @@ -135,6 +140,14 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow QToolBar *connectionToolBar = nullptr; QToolBar *settingsToolBar = nullptr; QToolBar *audioToolBar = nullptr; + // Compact-layout only (see setCompactLayout()): a row of buttons in the + // status bar for the map operations touch has no wheel or keyboard + // for (layers, centering). Not a QToolBar, so it stays out of + // saveState() and does not cost a row of its own. + QWidget *m_compactActionBar = nullptr; + // "\u2630" in the status bar while compact: m_appMenu. + QToolButton *m_menuButton = nullptr; + QLabel *m_pathMachineStatus = nullptr; QMenu *fileMenu = nullptr; QMenu *editMenu = nullptr; @@ -142,10 +155,34 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow QMenu *roomMenu = nullptr; QMenu *connectionMenu = nullptr; QMenu *viewMenu = nullptr; + QMenu *windowMenu = nullptr; QMenu *settingsMenu = nullptr; QMenu *helpMenu = nullptr; + // The top-level menus above as submenus of one menu: the "\u2630" button + // while compact, and an entry of the map's context menu whenever neither + // the menu bar nor that button is on screen, so that a touch user (no + // hover to "peek" a hidden menu bar with) can always reach them by a + // long-press on the map. A QAction can sit in several widgets at once, + // so the menus stay in the menu bar as well. + QMenu *m_appMenu = nullptr; QMenu *mumeMenu = nullptr; QMenu *onlineTutorialsMenu = nullptr; + // Compact layout for small windows; see setCompactLayout(). While + // compact, the menu bar is hidden and the top-level menus above are + // reached through m_menuButton, every dock + // is tabified into one group, and the toolbars are hidden. + // The two layouts each keep their own saveState(): m_expandedState / + // m_compactState hold the one not currently applied, and both are + // persisted (Configuration::general.windowState / windowStateCompact). + // m_layoutRestored gates the switch until the first show has realized + // the layout readSettings() restored, so nothing earlier can capture + // or clobber a layout. + QByteArray m_expandedState; + QByteArray m_compactState; + // The constructor's arrangement, for "Reset Window Layout". + QByteArray m_defaultExpandedState; + bool m_compact = false; + bool m_layoutRestored = false; QAction *newAct = nullptr; QAction *openAct = nullptr; @@ -168,6 +205,7 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow QAction *mumeForumAct = nullptr; QAction *mumeWikiAct = nullptr; QAction *settingUpMmapperAct = nullptr; + QAction *newcomerGuideAct = nullptr; QAction *newbieAct = nullptr; QAction *actionReportIssue = nullptr; QAction *aboutAct = nullptr; @@ -177,6 +215,8 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow QAction *zoomResetAct = nullptr; QAction *alwaysOnTopAct = nullptr; QAction *showStatusBarAct = nullptr; + QAction *compactLayoutAct = nullptr; + QAction *resetWindowLayoutAct = nullptr; QAction *showScrollBarsAct = nullptr; QAction *showMenuBarAct = nullptr; QAction *preferencesAct = nullptr; @@ -184,6 +224,7 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow QAction *layerUpAct = nullptr; QAction *layerDownAct = nullptr; QAction *layerResetAct = nullptr; + QAction *centerOnPlayerAct = nullptr; struct NODISCARD MouseModeActions final { @@ -239,8 +280,6 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow QAction *releaseAllPathsAct = nullptr; QAction *rebuildMeshesAct = nullptr; - std::unique_ptr m_configDialog; - struct AsyncBase; struct AsyncIO; struct AsyncLoader; @@ -259,6 +298,14 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow NODISCARD HotkeyManager &getHotkeyManager() const { return deref(m_hotkeyManager); } NODISCARD CTimers &getTimers() const { return deref(m_timers); } +private: + // ProxyHost + void virt_log(const QString &mod, const QString &msg) final { slot_log(mod, msg); } + void virt_setMode(const MapModeEnum mode) final { slot_setMode(mode); } + NODISCARD HotkeyManager &virt_getHotkeyManager() const final { return getHotkeyManager(); } + NODISCARD QObject &virt_asQObject() final { return *this; } + +public: NODISCARD bool saveFile(const QString &fileName, SaveModeEnum mode, SaveFormatEnum format); void loadFile(std::shared_ptr source); void setCurrentFile(const QString &fileName); @@ -276,9 +323,23 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow void showEvent(QShowEvent *event) override; NODISCARD bool eventFilter(QObject *obj, QEvent *event) override; +private: + void setCompactLayout(bool compact); + void buildDefaultCompactLayout(); + void fitClientDockToTerminal(); + void slot_resetWindowLayout(); + void applyCompactMenuBar(bool compact); + NODISCARD QWidget *createCompactActionBar(); + NODISCARD QToolButton *createMenuButton(); + void applyCompactChrome(bool compact); + void applyPanelScrollGesture(bool compact); + NODISCARD QSize compactLayoutProbeSize() const; + void fitCompactWindowToScreen(); + private: void startServices(); void forceNewFile(); + void promptOpenFile(); void showWarning(const QString &s); void showStatusInternal(const QString &txt, int duration); void showStatusShort(const QString &txt) { showStatusInternal(txt, 2000); } @@ -305,7 +366,6 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow // Blocking variant for closeEvent(), which cannot be deferred. Desktop only. NODISCARD bool maybeSaveBlocking(); NODISCARD bool handleMaybeSaveResult(int result); - void promptOpenFile(); struct ActionDisabler; void disableActions(bool value); @@ -328,13 +388,15 @@ class NODISCARD_QOBJECT MainWindow final : public QMainWindow }; void hideCanvas(bool hide); - NODISCARD MapCanvas *getCanvas() const; + NODISCARD MapCanvasWindow *getCanvas() const; void mapChanged() const; void setCanvasMouseMode(CanvasMouseModeEnum mode); void setMapModified(bool); void updateMapModified(); private: + // Pushes the given room's description into m_descriptionWidget. + void updateDescriptionRoom(const RoomHandle &room); void applyGroupAction(const std::function &getChange); void onSuccessfulLoad(const MapLoadData &mapLoadData); void onSuccessfulMerge(const Map &map); @@ -352,6 +414,7 @@ public slots: NODISCARD bool slot_exportWebMap(); NODISCARD bool slot_exportMmpMap(); void slot_about(); + void slot_aboutQt(); NODISCARD bool slot_generateBaseMap(); diff --git a/src/mainwindow/roomeditattrdlg.cpp b/src/mainwindow/roomeditattrdlg.cpp index 269f25034..e314af83c 100644 --- a/src/mainwindow/roomeditattrdlg.cpp +++ b/src/mainwindow/roomeditattrdlg.cpp @@ -9,7 +9,7 @@ #include "../client/displaywidget.h" #include "../configuration/configuration.h" #include "../display/Filenames.h" -#include "../display/mapcanvas.h" +#include "../display/MapCanvasWindow.h" #include "../global/AnsiOstream.h" #include "../global/Consts.h" #include "../global/PrintUtils.h" @@ -559,7 +559,7 @@ void RoomEditAttrDlg::roomListCurrentIndexChanged(int /*unused*/) void RoomEditAttrDlg::setRoomSelection(const SharedRoomSelection &rs, MapData *const md, - MapCanvas *const mc) + MapCanvasWindow *const mc) { m_roomSelection = rs; m_mapData = md; @@ -601,7 +601,10 @@ void RoomEditAttrDlg::setRoomSelection(const SharedRoomSelection &rs, updateDialog(RoomHandle{}); } - connect(this, &RoomEditAttrDlg::sig_requestUpdate, m_mapCanvas, &MapCanvas::slot_requestUpdate); + connect(this, + &RoomEditAttrDlg::sig_requestUpdate, + m_mapCanvas, + &MapCanvasWindow::slot_requestUpdate); } void RoomEditAttrDlg::updateDialog(const RoomHandle &r) diff --git a/src/mainwindow/roomeditattrdlg.h b/src/mainwindow/roomeditattrdlg.h index e1ea78453..b0787acdf 100644 --- a/src/mainwindow/roomeditattrdlg.h +++ b/src/mainwindow/roomeditattrdlg.h @@ -27,7 +27,7 @@ #include class Change; -class MapCanvas; +class MapCanvasWindow; class MapData; class QListWidgetItem; class QObject; @@ -59,7 +59,7 @@ class NODISCARD_QOBJECT RoomEditAttrDlg final : public QDialog, private Ui::Room SharedRoomSelection m_roomSelection; MapData *m_mapData = nullptr; - MapCanvas *m_mapCanvas = nullptr; + MapCanvasWindow *m_mapCanvas = nullptr; std::unique_ptr m_hiddenShortcut; bool m_noteSelected = false; bool m_noteDirty = false; @@ -121,7 +121,7 @@ class NODISCARD_QOBJECT RoomEditAttrDlg final : public QDialog, private Ui::Room void sig_requestUpdate(); public slots: - void setRoomSelection(const SharedRoomSelection &, MapData *, MapCanvas *); + void setRoomSelection(const SharedRoomSelection &, MapData *, MapCanvasWindow *); // selection page void roomListCurrentIndexChanged(int); diff --git a/src/mapstorage/MapLoadHelper.cpp b/src/mapstorage/MapLoadHelper.cpp new file mode 100644 index 000000000..a56f34c39 --- /dev/null +++ b/src/mapstorage/MapLoadHelper.cpp @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "MapLoadHelper.h" + +#include "../global/AnsiOstream.h" +#include "../global/AnsiTextUtils.h" +#include "../global/macros.h" +#include "../global/utils.h" +#include "../mapdata/mapdata.h" +#include "PandoraMapStorage.h" +#include "XmlMapStorage.h" +#include "mapstorage.h" + +#include +#include +#include + +#include + +namespace { // anonymous + +NODISCARD bool detectMm2Binary(QIODevice &device) +{ + auto result = getMM2FileVersion(device); + device.seek(0); + return result.has_value(); +} + +// MMapper2 XML map (as opposed to Pandora XML map) +NODISCARD bool detectMm2Xml(QIODevice &device) +{ + const QByteArray line = device.readLine(64); + const QByteArray line2 = device.readLine(64); + device.seek(0); + return line.contains("xml version") && line2.contains("mmapper2xml"); +} + +// Pandora XML map +NODISCARD bool detectPandora(QIODevice &device) +{ + QXmlStreamReader xml(&device); + xml.readNextStartElement(); + if (xml.error() != QXmlStreamReader::NoError) { + device.seek(0); + return false; + } + if (xml.name() != QStringLiteral("map")) { + device.seek(0); + return false; + } + if (xml.attributes().isEmpty() || !xml.attributes().hasAttribute("rooms")) { + device.seek(0); + return false; + } + device.seek(0); + return true; +} + +template +NODISCARD std::unique_ptr make(const AbstractMapStorage::Data &data, + QObject *const parent) +{ + return std::make_unique(data, parent); +} + +class NODISCARD FileFormatHelper final +{ +public: + using DetectFn = bool (*)(QIODevice &); + using MakeFn = std::unique_ptr (*)(const AbstractMapStorage::Data &data, + QObject *parent); + +private: + DetectFn m_detect = nullptr; + MakeFn m_make = nullptr; + +public: + explicit FileFormatHelper(const DetectFn d, const MakeFn m) + : m_detect{d} + , m_make{m} + { + assert(m_detect != nullptr); + assert(m_make != nullptr); + if (m_detect == nullptr || m_make == nullptr) { + std::abort(); + } + } + +private: + static void logException(const mm::source_location loc) + { + try { + std::rethrow_exception(std::current_exception()); + } catch (const std::exception &ex) { + mm::WarningOstream{loc} << ex.what(); + } catch (...) { + mm::WarningOstream{loc} << "Unknown exception."; + } + } + +public: + NODISCARD bool detect(QIODevice &device) const + { + try { + return m_detect(device); + } catch (...) { + logException(MM_SOURCE_LOCATION()); + return false; + } + } + NODISCARD std::unique_ptr make(const AbstractMapStorage::Data &data, + QObject *const parent) const + { + try { + return m_make(data, parent); + } catch (...) { + logException(MM_SOURCE_LOCATION()); + throw; + } + } +}; + +const std::array formats{ + FileFormatHelper{&detectMm2Binary, &make}, + FileFormatHelper{&detectMm2Xml, &make}, + FileFormatHelper{&detectPandora, &make}, +}; + +} // namespace + +namespace maploadhelper { + +std::unique_ptr detectAndCreateStorage(const std::shared_ptr &pSource, + QObject *const parent) +{ + const AbstractMapStorage::Data data{pSource}; + auto &source = deref(pSource); + auto pDevice = source.getIODevice(); + auto &device = deref(pDevice); + for (const auto &fmt : formats) { + if (!device.seek(0)) { + throw std::runtime_error("Failed to seek to beginning."); + } + if (fmt.detect(device)) { + return fmt.make(data, parent); + } + } + throw std::runtime_error("Unrecognized file format"); +} + +std::optional loadMapData(AbstractMapStorage &storage) +{ + if (!storage.canLoad()) { + return std::nullopt; + } + + ProgressCounter &pc = storage.getProgressCounter(); + pc.setCurrentTask(ProgressMsg{/*"phase 1: "*/ "load from disk"}); + std::optional opt_data = storage.loadData(); + if (!opt_data) { + return std::nullopt; + } + + auto &data = opt_data.value(); + pc.reset(); + + pc.setCurrentTask(ProgressMsg{/*"phase 2: "*/ "construct map from raw rooms and infomarks"}); + auto mapPair = Map::fromRooms(pc, + std::exchange(data.rooms, {}), + std::exchange(data.markers, {})); + + pc.setCurrentTask(ProgressMsg{"finished building map"}); + + MapLoadData result; + result.mapPair = std::exchange(mapPair, {}); + result.position = data.position; + result.filename = data.filename; + result.readonly = data.readonly; + + return result; +} + +std::optional mergeMapData(AbstractMapStorage &storage, const Map ¤tMap) +{ + if (!storage.canLoad()) { + return std::nullopt; + } + + ProgressCounter &pc = storage.getProgressCounter(); + pc.setCurrentTask(ProgressMsg{"phase 1: load from disk"}); + std::optional opt_data = storage.loadData(); + + if (!opt_data || (opt_data->rooms.empty() && opt_data->markers.empty())) { + return std::nullopt; + } + + pc.setCurrentTask(ProgressMsg{"phase 2: merge the new map data"}); + return MapData::mergeMapData(pc, currentMap, opt_data.value()); +} + +} // namespace maploadhelper diff --git a/src/mapstorage/MapLoadHelper.h b/src/mapstorage/MapLoadHelper.h new file mode 100644 index 000000000..5dbb691f3 --- /dev/null +++ b/src/mapstorage/MapLoadHelper.h @@ -0,0 +1,46 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "MapSource.h" +#include "RawMapData.h" +#include "abstractmapstorage.h" + +#include +#include + +#include + +// Widget-free map-storage helpers shared by MainWindow's async load path +// (see mainwindow/mainwindow-async.cpp's getLoadOrMergeMapStorage()/ +// background::load_map_data(), which delegate here). +// +// Neither function here touches QtWidgets, QProgressDialog, or MainWindow -- +// they only need a QObject* to parent the storage object to (for lifetime/ +// sig_log wiring, which callers still do themselves) and an +// AbstractMapStorage& with its ProgressCounter already attached. That keeps +// the format detection and background load logic reusable by any caller, +// without pulling in MainWindow's QProgressDialog/CanvasDisabler/ +// ExtraBlockers machinery. +namespace maploadhelper { + +// Sniffs pSource's IODevice against every known map format (MMapper2 binary, +// MMapper2/Pandora XML) and constructs the matching AbstractMapStorage +// subclass, parented to `parent`. Throws std::runtime_error("Unrecognized +// file format") if none match. Callers are responsible for connecting +// AbstractMapStorage::sig_log to their own log sink. +NODISCARD std::unique_ptr detectAndCreateStorage( + const std::shared_ptr &pSource, QObject *parent); + +// Loads raw map data from storage and constructs a Map from it. Safe to call +// on a background thread; storage's ProgressCounter must already be set (via +// AbstractMapStorage::setProgressCounter()) before calling this. +NODISCARD std::optional loadMapData(AbstractMapStorage &storage); + +// Loads raw map data from storage and merges it into currentMap. Safe to +// call on a background thread; storage's ProgressCounter must already be +// set before calling this. Returns std::nullopt if storage can't load, or +// if the loaded data has neither rooms nor markers. +NODISCARD std::optional mergeMapData(AbstractMapStorage &storage, const Map ¤tMap); + +} // namespace maploadhelper diff --git a/src/media/AudioManager.cpp b/src/media/AudioManager.cpp index 6ccd9e41e..1ed3bd62c 100644 --- a/src/media/AudioManager.cpp +++ b/src/media/AudioManager.cpp @@ -16,6 +16,7 @@ #endif #include +#include #include AudioManager::AudioManager(MediaLibrary &library, GameObserver &observer, QObject *const parent) @@ -35,6 +36,10 @@ AudioManager::AudioManager(MediaLibrary &library, GameObserver &observer, QObjec m_observer.sig2_gainedLevel.connect(m_lifetime, [this]() { playSound("level-up"); }); + if constexpr (CURRENT_PLATFORM == PlatformEnum::Wasm) { + QCoreApplication::instance()->installEventFilter(this); + } + setConfig().audio.registerChangeCallback(m_lifetime, [this]() { updateOutputDevices(); m_sfx->updateVolume(); @@ -78,6 +83,23 @@ void AudioManager::onAreaChanged(const RoomArea &area) m_music->playMusic(m_library.findAudio("areas", name)); } +bool AudioManager::eventFilter(QObject *const obj, QEvent *const event) +{ + switch (event->type()) { + case QEvent::KeyPress: + case QEvent::MouseButtonPress: + case QEvent::TouchBegin: + if (!getConfig().audio.isUnlocked()) { + setConfig().audio.setUnlocked(); + } + QCoreApplication::instance()->removeEventFilter(this); + break; + default: + break; + } + return QObject::eventFilter(obj, event); +} + void AudioManager::playSound(const QString &soundName) { m_sfx->playSound(soundName); diff --git a/src/media/AudioManager.h b/src/media/AudioManager.h index 06740e655..843dae3c2 100644 --- a/src/media/AudioManager.h +++ b/src/media/AudioManager.h @@ -31,6 +31,11 @@ class NODISCARD_QOBJECT AudioManager final : public QObject void onAreaChanged(const RoomArea &area); void playSound(const QString &soundName); +protected: + // wasm: the browser lets audio start only from a user gesture, so the + // first key press or tap anywhere in the application unlocks it. + NODISCARD bool eventFilter(QObject *obj, QEvent *event) override; + private: void updateVolumes(); void updateOutputDevices(); diff --git a/src/media/DescriptionWidget.cpp b/src/media/DescriptionWidget.cpp index 4b8e3d622..650fc5d08 100644 --- a/src/media/DescriptionWidget.cpp +++ b/src/media/DescriptionWidget.cpp @@ -11,10 +11,10 @@ #include "../map/mmapper2room.h" #include "../preferences/ansicombo.h" #include "MediaLibrary.h" +#include "StackBlur.h" #include #include -#include #include #include @@ -184,54 +184,7 @@ void DescriptionWidget::updateBackground() return; } - static const auto stackBlur = [](QImage &image, const int radius) { - const int w = image.width(); - const int h = image.height(); - const int div = 2 * radius + 1; - std::vector linePixels; - - // Horizontal blur - linePixels.resize(static_cast(w)); - for (int y = 0; y < h; ++y) { - for (int x = 0; x < w; ++x) { - linePixels[static_cast(x)] = image.pixel(x, y); - } - for (int x = 0; x < w; ++x) { - int rSum = 0, gSum = 0, bSum = 0, aSum = 0; - for (int i = -radius; i <= radius; ++i) { - size_t idx = static_cast(std::clamp(x + i, 0, w - 1)); - QRgb pixel = linePixels[idx]; - rSum += qRed(pixel); - gSum += qGreen(pixel); - bSum += qBlue(pixel); - aSum += qAlpha(pixel); - } - image.setPixel(x, y, qRgba(rSum / div, gSum / div, bSum / div, aSum / div)); - } - } - - // Vertical blur - linePixels.resize(static_cast(h)); - for (int x = 0; x < w; ++x) { - for (int y = 0; y < h; ++y) { - linePixels[static_cast(y)] = image.pixel(x, y); - } - for (int y = 0; y < h; ++y) { - int rSum = 0, gSum = 0, bSum = 0, aSum = 0; - for (int i = -radius; i <= radius; ++i) { - size_t idy = static_cast(std::clamp(y + i, 0, h - 1)); - QRgb pixel = linePixels[idy]; - rSum += qRed(pixel); - gSum += qGreen(pixel); - bSum += qBlue(pixel); - aSum += qAlpha(pixel); - } - image.setPixel(x, y, qRgba(rSum / div, gSum / div, bSum / div, aSum / div)); - } - } - }; - - stackBlur(blurSource, blurRadius); + mm::stackBlur(blurSource, blurRadius); const QImage fullBlurredBgImage = blurSource.scaled(widgetSize, Qt::IgnoreAspectRatio, diff --git a/src/media/MediaLibrary.cpp b/src/media/MediaLibrary.cpp index 335c87073..5fbd731c9 100644 --- a/src/media/MediaLibrary.cpp +++ b/src/media/MediaLibrary.cpp @@ -241,21 +241,30 @@ void MediaLibrary::scanDirectories() // Scan resources in increasing order of priority: QRC < Sideloaded Assets < User Resources. // Duplicate keys encountered later will overwrite earlier ones. + const qsizetype qrcImagesBefore = m_imageFiles.size(); scanPath(QLatin1String(":/areas"), QLatin1String(":/")); scanPath(QLatin1String(":/rooms"), QLatin1String(":/")); scanPath(QLatin1String(":/sounds"), QLatin1String(":/")); + qInfo() << "[description] scanned :/ (qrc):" << (m_imageFiles.size() - qrcImagesBefore) + << "image files."; if constexpr (CURRENT_PLATFORM != PlatformEnum::Wasm) { const QString &assetsDir = getAssetsPath(); + const qsizetype assetsImagesBefore = m_imageFiles.size(); scanPath(assetsDir + "areas", assetsDir); scanPath(assetsDir + "rooms", assetsDir); scanPath(assetsDir + "sounds", assetsDir); + qInfo() << "[description] scanned" << assetsDir << ":" + << (m_imageFiles.size() - assetsImagesBefore) << "image files."; } const auto &resourcesDir = getConfig().canvas.resourcesDirectory; + const qsizetype resourcesImagesBefore = m_imageFiles.size(); scanPath(resourcesDir + "/areas", resourcesDir); scanPath(resourcesDir + "/rooms", resourcesDir); scanPath(resourcesDir + "/sounds", resourcesDir); + qInfo() << "[description] scanned" << resourcesDir << ":" + << (m_imageFiles.size() - resourcesImagesBefore) << "image files."; qInfo() << "Scanned media directories. Found" << m_audioFiles.size() << "audio files and" << m_imageFiles.size() << "image files."; diff --git a/src/media/MediaLibrary.h b/src/media/MediaLibrary.h index a1e25520d..2cd197c13 100644 --- a/src/media/MediaLibrary.h +++ b/src/media/MediaLibrary.h @@ -35,6 +35,9 @@ class NODISCARD_QOBJECT MediaLibrary final : public QObject NODISCARD QString findAudio(const QString &subDir, const QString &name) const; NODISCARD QString findImage(const QString &subDir, const QString &name) const; + // Lets callers report "0 images found" hints without duplicating + // scanDirectories()'s bookkeeping. + NODISCARD int numImages() const { return static_cast(m_imageFiles.size()); } void fetchAsync(const QString &path, std::function callback); diff --git a/src/media/StackBlur.cpp b/src/media/StackBlur.cpp new file mode 100644 index 000000000..dd8e1b002 --- /dev/null +++ b/src/media/StackBlur.cpp @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "StackBlur.h" + +#include +#include +#include + +#include + +namespace mm { + +void stackBlur(QImage &image, const int radius) +{ + const int w = image.width(); + const int h = image.height(); + if (w <= 0 || h <= 0 || radius <= 0) { + return; + } + + const int div = 2 * radius + 1; + std::vector linePixels; + + // Horizontal blur + linePixels.resize(static_cast(w)); + for (int y = 0; y < h; ++y) { + for (int x = 0; x < w; ++x) { + linePixels[static_cast(x)] = image.pixel(x, y); + } + for (int x = 0; x < w; ++x) { + int rSum = 0, gSum = 0, bSum = 0, aSum = 0; + for (int i = -radius; i <= radius; ++i) { + size_t idx = static_cast(std::clamp(x + i, 0, w - 1)); + QRgb pixel = linePixels[idx]; + rSum += qRed(pixel); + gSum += qGreen(pixel); + bSum += qBlue(pixel); + aSum += qAlpha(pixel); + } + image.setPixel(x, y, qRgba(rSum / div, gSum / div, bSum / div, aSum / div)); + } + } + + // Vertical blur + linePixels.resize(static_cast(h)); + for (int x = 0; x < w; ++x) { + for (int y = 0; y < h; ++y) { + linePixels[static_cast(y)] = image.pixel(x, y); + } + for (int y = 0; y < h; ++y) { + int rSum = 0, gSum = 0, bSum = 0, aSum = 0; + for (int i = -radius; i <= radius; ++i) { + size_t idy = static_cast(std::clamp(y + i, 0, h - 1)); + QRgb pixel = linePixels[idy]; + rSum += qRed(pixel); + gSum += qGreen(pixel); + bSum += qBlue(pixel); + aSum += qAlpha(pixel); + } + image.setPixel(x, y, qRgba(rSum / div, gSum / div, bSum / div, aSum / div)); + } + } +} + +} // namespace mm diff --git a/src/media/StackBlur.h b/src/media/StackBlur.h new file mode 100644 index 000000000..8e9669c80 --- /dev/null +++ b/src/media/StackBlur.h @@ -0,0 +1,16 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +class QImage; + +namespace mm { + +// In-place box-blur approximation (separable horizontal then vertical +// pass). `radius` must be >= 0; a radius of 0 leaves the image unchanged. +// `image` must already be in a format QImage::pixel()/setPixel() can +// address (e.g. Format_ARGB32_Premultiplied); 0x0 images are handled as a +// no-op. +extern void stackBlur(QImage &image, int radius); + +} // namespace mm diff --git a/src/mpi/RemoteEditDocumentOps.cpp b/src/mpi/RemoteEditDocumentOps.cpp new file mode 100644 index 000000000..8863ad75e --- /dev/null +++ b/src/mpi/RemoteEditDocumentOps.cpp @@ -0,0 +1,481 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "RemoteEditDocumentOps.h" + +#include "../global/AnsiTextUtils.h" +#include "../global/Consts.h" +#include "../global/LineUtils.h" +#include "../global/TabUtils.h" +#include "../global/TextBuffer.h" +#include "../global/TextUtils.h" + +#include +#include +#include +#include + +#include +#include + +using namespace char_consts; + +namespace mmqt { + +int measureTabAndAnsiAware(const QString &s) +{ + int col = 0; + for (const AnsiStringToken token : mmqt::AnsiTokenizer{s}) { + using Type = decltype(token.type); + switch (token.type) { + case Type::Ansi: + break; + case Type::Newline: + /* unexpected */ + col = 0; + break; + case Type::Space: + case Type::Control: + case Type::Word: + col = mmqt::measureExpandedTabsOneLine(token.getQStringView(), col); + break; + } + } + return col; +} + +bool remoteEditLineHasTabs(const QTextCursor &line) +{ + if (line.isNull()) { + return false; + } + const auto &block = line.block(); + if (!block.isValid()) { + return false; + } + return block.text().indexOf(C_TAB) >= 0; +} + +void remoteEditExpandTabsOnLine(QTextCursor line) +{ + const QTextBlock &block = line.block(); + const QString &s = block.text(); + + TextBuffer prefix; + prefix.appendExpandedTabs(QStringView{s}, 0); + + line.setPosition(block.position()); + line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + line.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); + line.insertText(prefix.getQString()); +} + +void remoteEditTryRemoveLeadingSpaces(QTextCursor line, const int max_spaces) +{ + const auto &block = line.block(); + if (!block.isValid()) { + return; + } + + const auto &text = block.text(); + if (text.isEmpty()) { + return; + } + + const int to_remove = std::invoke([&text, max_spaces]() -> int { + const int len = std::min(max_spaces, static_cast(text.length())); + int n = 0; + while (n < len && text.at(n) == C_SPACE) { + ++n; + } + return n; + }); + + if (to_remove == 0) { + return; + } + + line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + line.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, to_remove); + line.removeSelectedText(); +} + +void remoteEditInsertPrefix(QTextCursor line, const QString &prefix) +{ + line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + line.insertText(prefix); +} + +void remoteEditPrefixPartialSelection(QTextCursor cur, const QString &prefix) +{ + RemoteEditUndoGroup raii(cur); + remoteEditForeachPartlySelectedBlock(cur, [&prefix](const QTextCursor &line) -> void { + if (remoteEditLineHasTabs(line)) { + remoteEditExpandTabsOnLine(line); + } + remoteEditInsertPrefix(line, prefix); + }); +} + +void remoteEditUnindentPartialSelection(QTextCursor cur) +{ + RemoteEditUndoGroup raii(cur); + remoteEditForeachPartlySelectedBlock(cur, [](const QTextCursor &line) -> void { + if (remoteEditLineHasTabs(line)) { + remoteEditExpandTabsOnLine(line); + } + remoteEditTryRemoveLeadingSpaces(line, 2); + }); +} + +void remoteEditJoinLines(QTextCursor cur) +{ + RemoteEditUndoGroup raii(cur); + + auto *const doc = cur.document(); + const auto from = doc->findBlock(cur.selectionStart()); + auto to = doc->findBlock(cur.selectionEnd()); + + /* Feature: join the next line if only one line is selected */ + if (from == to) { + if (cur.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor)) { + to = doc->findBlock(cur.selectionEnd()); + } + } + + TextBuffer buffer; + remoteEditForeachPartlySelectedBlock(cur, [&buffer](const QTextCursor line) -> void { + const QTextBlock block = line.block(); + const QString text = block.text(); + if (text.isEmpty()) { + return; + } + + if (!buffer.isEmpty()) { + buffer.append(C_SPACE); + } + buffer.appendExpandedTabs(QStringView{text}); + }); + + /* adjust the selection to cover select everything in the blocks */ + const int a = from.position(); + const int b = to.position() + to.length() - 1; + cur.setPosition(a); + cur.setPosition(b, QTextCursor::KeepAnchor); + cur.insertText(buffer.getQString()); +} + +void remoteEditJustifyLines(QTextCursor cur, const int maxLength) +{ + RemoteEditUndoGroup raii(cur); + + auto *const doc = cur.document(); + const auto from = doc->findBlock(cur.selectionStart()); + const auto to = doc->findBlock(cur.selectionEnd()); + const auto toBlockNumber = to.blockNumber(); + if (!from.isValid()) { + return; + } + + const int a = from.position(); + const int b = to.position() + to.length() - 1; + + TextBuffer buffer; + for (auto it = from; it.isValid() && it.blockNumber() <= toBlockNumber; it = it.next()) { + const auto &text = it.text(); + if (text.isEmpty()) { + continue; + } + + if (!buffer.isEmpty()) { + buffer.append(C_SPACE); + } + buffer.appendJustified(QStringView{text}, maxLength); + } + + cur.setPosition(a); + cur.setPosition(b, QTextCursor::KeepAnchor); + cur.insertText(buffer.getQString()); +} + +QString remoteEditJustifyText(const QString &text, const int maxLength) +{ + TextBuffer result; + result.reserve(static_cast(text.length())); + mmqt::foreachLine(text, [&result, maxLength](const QStringView line, bool /*hasNewline*/) { + result.appendJustified(line, maxLength); + result.append(C_NEWLINE); + }); + return result.getQString(); +} + +void remoteEditExpandTabs(QTextCursor cur) +{ + RemoteEditUndoGroup raii(cur); + remoteEditForeachPartlySelectedBlock(cur, [](QTextCursor line) -> void { + if (remoteEditLineHasTabs(line)) { + remoteEditExpandTabsOnLine(line); + } + }); +} + +void remoteEditRemoveTrailingWhitespace(QTextCursor cur) +{ + RemoteEditUndoGroup raii(cur); + remoteEditForeachPartlySelectedBlock(cur, [](QTextCursor line) -> void { + static const QRegularExpression trailingWhitespace(R"([[:space:]]+$)"); + assert(trailingWhitespace.isValid()); + QString text = line.block().text(); + if (!text.contains(trailingWhitespace)) { + return; + } + + text.remove(trailingWhitespace); + line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + line.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); + line.insertText(text); + }); +} + +void remoteEditRemoveDuplicateSpaces(QTextCursor cur) +{ + RemoteEditUndoGroup raii(cur); + remoteEditForeachPartlySelectedBlock(cur, [](QTextCursor line) -> void { + static const QRegularExpression spaces(R"((\t|[[:space:]]{2,}))"); + assert(spaces.isValid()); + QString text = line.block().text(); + if (!text.contains(spaces)) { + return; + } + + text.replace(spaces, string_consts::S_SPACE); + line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + line.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); + line.insertText(text); + }); +} + +std::optional remoteEditNormalizeAnsi(const QString &text) +{ + if (!mmqt::containsAnsi(text)) { + return std::nullopt; + } + + TextBuffer output = mmqt::normalizeAnsi(ANSI_COLOR_SUPPORT_HI, text); + if (!output.hasTrailingNewline()) { + output.append(C_NEWLINE); + } + + return output.getQString(); +} + +RemoteEditFindOutcome remoteEditFind(QTextDocument &doc, + const QTextCursor &cursor, + const QString &term, + const QTextDocument::FindFlags flags) +{ + RemoteEditFindOutcome outcome; + outcome.cursor = cursor; + if (term.isEmpty()) { + return outcome; + } + + if (QTextCursor found = doc.find(term, cursor, flags); !found.isNull()) { + outcome.result = RemoteEditFindResultEnum::FOUND; + outcome.cursor = found; + return outcome; + } + + // Wrap around + QTextCursor wrapStart(&doc); + wrapStart.movePosition(flags.testFlag(QTextDocument::FindBackward) ? QTextCursor::End + : QTextCursor::Start); + if (QTextCursor found = doc.find(term, wrapStart, flags); !found.isNull()) { + outcome.result = RemoteEditFindResultEnum::FOUND_AFTER_WRAP; + outcome.cursor = found; + return outcome; + } + + return outcome; +} + +bool remoteEditReplaceCurrentIfMatches(QTextCursor &cursor, + const QString &findTerm, + const QString &replaceTerm, + const QTextDocument::FindFlags flags) +{ + if (!cursor.hasSelection()) { + return false; + } + + const QString selectedText = cursor.selectedText(); + const Qt::CaseSensitivity cs = flags.testFlag(QTextDocument::FindCaseSensitively) + ? Qt::CaseSensitive + : Qt::CaseInsensitive; + if (QString::compare(selectedText, findTerm, cs) != 0) { + return false; + } + + cursor.insertText(replaceTerm); + return true; +} + +int remoteEditReplaceAll(QTextDocument &doc, + const QString &findTerm, + const QString &replaceTerm, + const QTextDocument::FindFlags flags) +{ + if (findTerm.isEmpty()) { + return 0; + } + + int replacements = 0; + QTextCursor undoCursor(&doc); + RemoteEditUndoGroup raii(undoCursor); + + QTextCursor pos(&doc); + for (QTextCursor found = doc.find(findTerm, pos, flags); !found.isNull(); + found = doc.find(findTerm, found, flags)) { + found.insertText(replaceTerm); + ++replacements; + } + + return replacements; +} + +std::optional remoteEditGotoLine(QTextDocument &doc, const int lineNum) +{ + QTextCursor cursor(&doc); + cursor.movePosition(QTextCursor::Start); + if (cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor, lineNum - 1)) { + return cursor; + } + return std::nullopt; +} + +namespace { // anonymous + +struct NODISCARD CursorColumnInfo final +{ + int actual = 0; + int tab_aware = 0; + int tab_and_ansi_aware = 0; +}; + +NODISCARD CursorColumnInfo getCursorColumn(QTextCursor &cursor) +{ + const int pos = cursor.positionInBlock(); + const auto &block = cursor.block(); + const auto &text = block.text().left(pos); + + CursorColumnInfo cci; + cci.actual = pos; + cci.tab_aware = mmqt::measureExpandedTabsOneLine(text, 0); + cci.tab_and_ansi_aware = mmqt::measureTabAndAnsiAware(text); + return cci; +} + +struct NODISCARD CursorAnsiInfo final +{ + TextBuffer buffer; + + explicit operator bool() const { return !buffer.isEmpty(); } +}; + +NODISCARD CursorAnsiInfo getCursorAnsi(QTextCursor cursor) +{ + const int pos = cursor.positionInBlock(); + + CursorAnsiInfo result; + const auto &line = cursor.block().text(); + mmqt::foreachAnsi(line, [pos, &result](auto start, const QStringView sv) { + if (result || pos < start || pos >= start + sv.length()) { + return; + } + + if (!mmqt::isValidAnsiColor(sv)) { + result.buffer.append("*invalid*"); + return; + } + + auto &buffer = result.buffer; + + if (const auto optAnsi = mmqt::parseAnsiColor(RawAnsi{}, sv)) { + const auto &ansi = *optAnsi; + if (ansi == RawAnsi{}) { + buffer.append("reset"); + } else { + std::ostringstream oss; + to_stream(oss, ansi); + buffer.append(mmqt::toQStringUtf8(oss.str())); + } + } else { + result.buffer.append("*error"); + } + }); + return result; +} + +NODISCARD bool linesHaveTabs(const QTextCursor &cur) +{ + return remoteEditExistsPartlySelectedBlock(cur, [](const QTextCursor &it) -> bool { + return remoteEditLineHasTabs(it); + }); +} + +NODISCARD bool linesHaveTrailingSpace(const QTextCursor &cur) +{ + return remoteEditExistsPartlySelectedBlock(cur, [](const QTextCursor &it) -> bool { + const auto &block = it.block(); + const auto &line = block.text(); + return mmqt::findTrailingWhitespace(line) >= 0; + }); +} + +NODISCARD bool hasLongLines(const QTextCursor &cur) +{ + return remoteEditExistsPartlySelectedBlock(cur, [](const QTextCursor &line) -> bool { + const auto &block = line.block(); + const auto &s = block.text(); + return mmqt::measureTabAndAnsiAware(s) > 80; + }); +} + +} // namespace + +RemoteEditStatusInfo computeRemoteEditStatus(const QTextCursor &cursorIn) +{ + QTextCursor cur = cursorIn; + RemoteEditStatusInfo info; + + const auto cci = getCursorColumn(cur); + info.line = cur.blockNumber() + 1; + info.col = cci.tab_and_ansi_aware + 1; + if (cci.tab_aware != cci.tab_and_ansi_aware) { + info.nonAnsiAwareCol = cci.tab_aware + 1; + } + + if (cur.hasSelection()) { + const QString selection = cur.selection().toPlainText(); + RemoteEditSelectionInfo sel; + sel.chars = static_cast(selection.length()); + sel.lines = static_cast(selection.count(C_NEWLINE) + + (selection.endsWith(C_NEWLINE) ? 0 : 1)); + info.selection = sel; + } else if (auto ansi = getCursorAnsi(cur)) { + info.ansiCode = ansi.buffer.getQString(); + } + + QTextCursor errCur = cur; + if (!errCur.hasSelection()) { + errCur.select(QTextCursor::Document); + } + info.hasTabs = linesHaveTabs(errCur); + info.hasTrailingSpace = linesHaveTrailingSpace(errCur); + info.hasLongLines = hasLongLines(errCur); + + return info; +} + +} // namespace mmqt diff --git a/src/mpi/RemoteEditDocumentOps.h b/src/mpi/RemoteEditDocumentOps.h new file mode 100644 index 000000000..effae9841 --- /dev/null +++ b/src/mpi/RemoteEditDocumentOps.h @@ -0,0 +1,223 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "../global/macros.h" + +#include +#include + +#include +#include +#include +#include +#include + +// Widget-free core of the MPI remote editor's text operations, find/replace, goto-line, +// and status-bar computation. Everything here operates on QTextDocument/QTextCursor +// (QtGui), so it has no dependency on the QWidget-based RemoteEditWidget. +namespace mmqt { + +// REVISIT: Figure out how to tweak logic to accept actual maximum length of 80 +inline constexpr int REMOTE_EDIT_MAX_LENGTH = 79; + +NODISCARD int measureTabAndAnsiAware(const QString &s); + +/// Groups everything done in its scope into a single undo action on the cursor's document. +class NODISCARD RemoteEditUndoGroup final +{ +private: + QTextCursor m_cursor; + +public: + explicit RemoteEditUndoGroup(const QTextCursor &cursor) + : m_cursor{cursor} + { + m_cursor.beginEditBlock(); + } + ~RemoteEditUndoGroup() { m_cursor.endEditBlock(); } +}; + +struct NODISCARD RemoteEditLineRange final +{ + NODISCARD static QTextCursor beg(QTextCursor cur) + { + auto from = cur.document()->findBlock(cur.selectionStart()); + return QTextCursor(from); + } + + NODISCARD static QTextCursor end(QTextCursor cur) + { + const auto &to = cur.document()->findBlock(cur.selectionEnd()); + auto endCursor = QTextCursor(to); + if (!endCursor.isNull()) { + endCursor.movePosition(QTextCursor::NextBlock); + } + return endCursor; + } +}; + +/// Caller is responsible for not invalidating the end cursor. +/// +/// callback(QTextCursor); +/// -or- +/// callback(const QTextCursor&); +template +void remoteEditForeachPartlySelectedBlock(QTextCursor cur, Callback &&callback) +{ + auto beg = RemoteEditLineRange::beg(cur); + auto end = RemoteEditLineRange::end(cur); + for (auto it = beg; !it.isNull() && it <= end;) { + if (it.block().isValid()) { + callback(static_cast(it)); + } + if (!it.movePosition(QTextCursor::NextBlock)) { + break; + } + } +} + +enum class NODISCARD RemoteEditCallbackResultEnum { KEEP_GOING, STOP }; + +/// Caller is responsible for not invalidating the end cursor. +/// +/// RemoteEditCallbackResultEnum callback(QTextCursor); +/// -or- +/// RemoteEditCallbackResultEnum callback(const QTextCursor&); +template + requires(std::is_invocable_r_v) +void remoteEditForeachPartlySelectedBlockUntil(QTextCursor cur, Callback &&callback) +{ + auto beg = RemoteEditLineRange::beg(cur); + auto end = RemoteEditLineRange::end(cur); + for (auto it = beg; !it.isNull() && it < end;) { + if (it.block().isValid()) { + if (callback(static_cast(it)) + == RemoteEditCallbackResultEnum::STOP) { + return; + } + } + if (!it.movePosition(QTextCursor::NextBlock)) { + break; + } + } +} + +template + requires(std::is_invocable_r_v) +bool remoteEditExistsPartlySelectedBlock(QTextCursor cur, Callback &&callback) +{ + bool result = false; + remoteEditForeachPartlySelectedBlockUntil(cur, + [&result, &callback]( + QTextCursor it) -> RemoteEditCallbackResultEnum { + if (callback(it)) { + result = true; + return RemoteEditCallbackResultEnum::STOP; + } + return RemoteEditCallbackResultEnum::KEEP_GOING; + }); + return result; +} + +NODISCARD bool remoteEditLineHasTabs(const QTextCursor &line); +void remoteEditExpandTabsOnLine(QTextCursor line); +void remoteEditTryRemoveLeadingSpaces(QTextCursor line, int max_spaces); +void remoteEditInsertPrefix(QTextCursor line, const QString &prefix); + +// --- Text operations (each groups its edits into a single undo action) --- + +/// 2-space block indentation of all partly-selected lines (tabs on those lines are +/// expanded first). +void remoteEditPrefixPartialSelection(QTextCursor cur, const QString &prefix); + +/// 2-space block de-indentation of all partly-selected lines (tabs on those lines are +/// expanded first). +void remoteEditUnindentPartialSelection(QTextCursor cur); + +/// Join all partly-selected lines into one (joining the next line too if only one line +/// is selected), replacing tabs with their expansion and separating lines with a space. +void remoteEditJoinLines(QTextCursor cur); + +/// Justify all partly-selected lines to maxLength columns. +void remoteEditJustifyLines(QTextCursor cur, int maxLength); + +/// Justify the entire document to maxLength columns; returns the new document text. +NODISCARD QString remoteEditJustifyText(const QString &text, int maxLength); + +/// Expand tabs (to 8-character tabstops) on all partly-selected lines. +void remoteEditExpandTabs(QTextCursor cur); + +/// Remove trailing whitespace from all partly-selected lines. +void remoteEditRemoveTrailingWhitespace(QTextCursor cur); + +/// Collapse tabs and runs of 2+ whitespace characters to a single space on all +/// partly-selected lines. +void remoteEditRemoveDuplicateSpaces(QTextCursor cur); + +/// Normalizes ANSI codes in the whole document; returns std::nullopt if the text +/// contains no ANSI codes at all (a no-op). +NODISCARD std::optional remoteEditNormalizeAnsi(const QString &text); + +// --- Find / replace --- + +enum class NODISCARD RemoteEditFindResultEnum { NOT_FOUND, FOUND, FOUND_AFTER_WRAP }; + +struct NODISCARD RemoteEditFindOutcome final +{ + RemoteEditFindResultEnum result = RemoteEditFindResultEnum::NOT_FOUND; + // Valid selection cursor when result != NOT_FOUND; otherwise unset. + QTextCursor cursor; +}; + +/// Finds the next occurrence of term starting from cursor; if not found, wraps around +/// to the start (or end, for a backward search) of the document and tries once more. +NODISCARD RemoteEditFindOutcome remoteEditFind(QTextDocument &doc, + const QTextCursor &cursor, + const QString &term, + QTextDocument::FindFlags flags); + +/// If cursor currently has a selection matching findTerm (per the case-sensitivity in +/// flags), replaces it with replaceTerm. Returns whether a replacement was made. +NODISCARD bool remoteEditReplaceCurrentIfMatches(QTextCursor &cursor, + const QString &findTerm, + const QString &replaceTerm, + QTextDocument::FindFlags flags); + +/// Replaces every occurrence of findTerm in the whole document with replaceTerm, as a +/// single undo action. Returns the number of replacements made. +NODISCARD int remoteEditReplaceAll(QTextDocument &doc, + const QString &findTerm, + const QString &replaceTerm, + QTextDocument::FindFlags flags); + +// --- Goto line --- + +/// Returns a cursor positioned at the start of 1-based lineNum, or std::nullopt if the +/// document doesn't have that many lines. +NODISCARD std::optional remoteEditGotoLine(QTextDocument &doc, int lineNum); + +// --- Status bar --- + +struct NODISCARD RemoteEditSelectionInfo final +{ + int chars = 0; + int lines = 0; +}; + +struct NODISCARD RemoteEditStatusInfo final +{ + int line = 1; // 1-based + int col = 1; // 1-based, tab+ansi aware + std::optional nonAnsiAwareCol; // 1-based; set only if it differs from col + std::optional selection; + QString ansiCode; // only meaningful when !selection + bool hasTabs = false; + bool hasTrailingSpace = false; + bool hasLongLines = false; +}; + +NODISCARD RemoteEditStatusInfo computeRemoteEditStatus(const QTextCursor &cursor); + +} // namespace mmqt diff --git a/src/mpi/RemoteEditHighlighter.cpp b/src/mpi/RemoteEditHighlighter.cpp new file mode 100644 index 000000000..fc1b9c3cc --- /dev/null +++ b/src/mpi/RemoteEditHighlighter.cpp @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "RemoteEditHighlighter.h" + +#include "../global/AnsiTextUtils.h" +#include "../global/CharUtils.h" +#include "../global/Charset.h" +#include "../global/Consts.h" +#include "../global/TextUtils.h" +#include "../global/entities.h" +#include "../global/utils.h" + +#include + +#include +#include + +using namespace char_consts; + +namespace { +constexpr QColor darkOrangeQColor{0xFF, 0x8C, 0x00}; +constexpr bool USE_TOOLTIPS = false; +} // namespace + +RemoteEditHighlighter::RemoteEditHighlighter(QTextDocument *const document, const int maxLength) + : QSyntaxHighlighter(document) + , m_maxLength{maxLength} +{} + +RemoteEditHighlighter::~RemoteEditHighlighter() = default; + +QTextCharFormat RemoteEditHighlighter::getBackgroundFormat(const Qt::GlobalColor color) +{ + QTextCharFormat fmt; + fmt.setBackground(QBrush{color}); + return fmt; +} + +QTextCharFormat RemoteEditHighlighter::getBackgroundFormat(const QColor &color) +{ + QTextCharFormat fmt; + fmt.setBackground(QBrush{color}); + return fmt; +} + +void RemoteEditHighlighter::highlightTabs(const QString &line) +{ + if (line.indexOf(C_TAB) < 0) { + return; + } + + const QTextCharFormat fmt = getBackgroundFormat(Qt::yellow); + // REVISIT: Should this be in TabUtils? + mmqt::foreachCharPos(line, C_TAB, [this, &fmt](const auto at) { + setFormat(static_cast(at), 1, fmt); + }); +} + +void RemoteEditHighlighter::highlightOverflow(const QString &line) +{ + const int breakPos = (mmqt::measureTabAndAnsiAware(line) <= m_maxLength) ? -1 : m_maxLength; + if (breakPos < 0) { + return; + } + + const auto getFmt = []() -> QTextCharFormat { + QTextCharFormat fmt; + fmt.setFontUnderline(true); + fmt.setUnderlineStyle(QTextCharFormat::UnderlineStyle::WaveUnderline); + fmt.setUnderlineColor(Qt::red); + return fmt; + }; + + const int length = static_cast(line.length()) - breakPos; + setFormat(breakPos, length, getFmt()); +} + +void RemoteEditHighlighter::highlightTrailingSpace(const QString &line) +{ + const int breakPos = mmqt::findTrailingWhitespace(line); + if (breakPos < 0) { + return; + } + + const int length = static_cast(line.length()) - breakPos; + setFormat(breakPos, length, getBackgroundFormat(Qt::red)); +} + +void RemoteEditHighlighter::highlightAnsi(const QString &line) +{ + const auto red = getBackgroundFormat(Qt::red); + const auto cyan = getBackgroundFormat(Qt::cyan); + + mmqt::foreachAnsi(line, [this, &red, &cyan](const auto start, const QStringView sv) { + setFormat(static_cast(start), + static_cast(sv.length()), + mmqt::isValidAnsiColor(sv) ? cyan : red); + }); +} + +void RemoteEditHighlighter::highlightEntities(const QString &line) +{ + const auto red = getBackgroundFormat(Qt::red); + const auto darkOrange = getBackgroundFormat(darkOrangeQColor); + const auto yellow = getBackgroundFormat(Qt::yellow); + + struct NODISCARD MyEntityCallback final : entities::EntityCallback + { + private: + RemoteEditHighlighter &m_self; + const QTextCharFormat &m_red; + const QTextCharFormat &m_darkOrange; + const QTextCharFormat &m_yellow; + + public: + explicit MyEntityCallback(RemoteEditHighlighter &self, + const QTextCharFormat &red, + const QTextCharFormat &darkOrange, + const QTextCharFormat &yellow) + : m_self{self} + , m_red{red} + , m_darkOrange{darkOrange} + , m_yellow{yellow} + {} + + private: + void virt_decodedEntity(int start, int len, OptQChar decoded) final + { + const auto get_fmt = [this, &decoded]() -> const QTextCharFormat & { + if (!decoded) { + return m_red; + } + const auto val = decoded->unicode(); + return (val < 256) ? m_yellow : m_darkOrange; + }; + + m_self.setFormat(start, len, get_fmt()); + } + } callback{*this, red, darkOrange, yellow}; + entities::foreachEntity(QStringView{line}, callback); +} + +void RemoteEditHighlighter::highlightEncodingErrors(const QString &line) +{ + const auto red = getBackgroundFormat(Qt::red); + const auto darkOrange = getBackgroundFormat(darkOrangeQColor); + const auto yellow = getBackgroundFormat(Qt::yellow); + const auto cyan = getBackgroundFormat(Qt::cyan); + + using OptFmt = std::optional; +#define DECL_FMT(name, color, tooltip) \ + OptFmt opt_##name{}; \ + const auto get_##name##_fmt = [&opt_##name, &color]() -> const QTextCharFormat & { \ + auto &opt = opt_##name; \ + if (!opt) { \ + opt = color; \ + if (USE_TOOLTIPS) { \ + opt.value().setToolTip(tooltip); \ + } \ + } \ + return opt.value(); \ + } + DECL_FMT(unicode, red, "Unicode"); + DECL_FMT(nbsp, cyan, "NBSP"); + DECL_FMT(utf8, yellow, "UTF-8"); + DECL_FMT(unprintable, darkOrange, "(unprintable)"); + +#undef DECL_FMT + + int pos = 0; + QChar last; + bool hasLast = false; + for (const auto &qc : line) { + if (qc.unicode() > 0xFF) { + // no valid representation + // TODO: add a means of transliterating things like special quotes + // Does Qt offer this feature somewhere? + // If not, consider iconv -t LATIN1//TRANSLIT + + setFormat(pos, 1, get_unicode_fmt()); + } else { + const char c = mmqt::toLatin1(qc); + switch (c) { + case C_NBSP: + setFormat(pos, 1, get_nbsp_fmt()); + break; + case C_ESC: + case C_TAB: // REVISIT: move tab handler to here? + /* handled elsewhere */ + break; + default: { + const auto uc = static_cast(c); + if (hasLast + && (isClamped(uc, 0x80, 0xBF) + && (last == char16_t(0xC2) || last == char16_t(0xC3)))) { + // Sometimes these are UTF-8 encoded Latin1 values, + // but they could also be intended, so they're not errors. + // TODO: add a feature to fix these on a case-by-case basis? + setFormat(pos - 1, 2, get_utf8_fmt()); + } else if (ascii::isCntrl(c) || !::isPrintLatin1(c)) { + setFormat(pos, 1, get_unprintable_fmt()); + } + } + } + } + + last = qc; + hasLast = true; + ++pos; + } +} diff --git a/src/mpi/RemoteEditHighlighter.h b/src/mpi/RemoteEditHighlighter.h new file mode 100644 index 000000000..5d9f6c4dd --- /dev/null +++ b/src/mpi/RemoteEditHighlighter.h @@ -0,0 +1,50 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2019 The MMapper Authors +// Author: Nils Schimmelmann (Jahara) + +#include "../global/macros.h" +#include "RemoteEditDocumentOps.h" + +#include +#include +#include +#include + +class QTextDocument; + +// Widget-free syntax highlighter for the remote editor: flags tabs, overflowing lines, +// trailing whitespace, ANSI escapes, HTML-style entities, and encoding errors. +// QSyntaxHighlighter is QtGui (not QtWidgets), so this class has no widget dependency. +class NODISCARD RemoteEditHighlighter final : public QSyntaxHighlighter +{ +private: + const int m_maxLength; + +public: + explicit RemoteEditHighlighter(QTextDocument *document, + int maxLength = mmqt::REMOTE_EDIT_MAX_LENGTH); + ~RemoteEditHighlighter() final; + +protected: + void highlightBlock(const QString &line) override + { + highlightTabs(line); + highlightOverflow(line); + highlightTrailingSpace(line); + highlightAnsi(line); + highlightEntities(line); + highlightEncodingErrors(line); + } + +private: + NODISCARD static QTextCharFormat getBackgroundFormat(Qt::GlobalColor color); + NODISCARD static QTextCharFormat getBackgroundFormat(const QColor &color); + + void highlightTabs(const QString &line); + void highlightOverflow(const QString &line); + void highlightTrailingSpace(const QString &line); + void highlightAnsi(const QString &line); + void highlightEntities(const QString &line); + void highlightEncodingErrors(const QString &line); +}; diff --git a/src/mpi/remoteeditwidget.cpp b/src/mpi/remoteeditwidget.cpp index 035ff228a..77147806f 100644 --- a/src/mpi/remoteeditwidget.cpp +++ b/src/mpi/remoteeditwidget.cpp @@ -7,31 +7,29 @@ #include "../client/displaywidget.h" #include "../configuration/configuration.h" #include "../global/AnsiTextUtils.h" -#include "../global/CharUtils.h" #include "../global/Consts.h" -#include "../global/LineUtils.h" #include "../global/TabUtils.h" #include "../global/TextUtils.h" -#include "../global/entities.h" -#include "../global/utils.h" #include "../global/window_utils.h" #include "../viewers/AnsiViewWindow.h" +#include "RemoteEditDocumentOps.h" +#include "RemoteEditHighlighter.h" #include "findreplacewidget.h" #include "gotowidget.h" #include -#include #include #include #include #include +using namespace char_consts; + #include #include #include #include #include -#include #include #include #include @@ -39,260 +37,10 @@ #include #include -using namespace char_consts; - -static constexpr QColor darkOrangeQColor{0xFF, 0x8C, 0x00}; static constexpr const bool USE_TOOLTIPS = false; -// REVISIT: Figure out how to tweak logic to accept actual maximum length of 80 -static constexpr const int MAX_LENGTH = 79; -namespace mmqt { -NODISCARD static int measureTabAndAnsiAware(const QString &s) -{ - int col = 0; - for (const AnsiStringToken token : mmqt::AnsiTokenizer{s}) { - using Type = decltype(token.type); - switch (token.type) { - case Type::Ansi: - break; - case Type::Newline: - /* unexpected */ - col = 0; - break; - case Type::Space: - case Type::Control: - case Type::Word: - col = mmqt::measureExpandedTabsOneLine(token.getQStringView(), col); - break; - } - } - return col; -} -} // namespace mmqt class QWidget; -/// Groups everything in the scope as a single undo action. -class NODISCARD RaiiGroupUndoActions final -{ -private: - QTextCursor m_cursor; - -public: - explicit RaiiGroupUndoActions(const QTextCursor &cursor) - : m_cursor{cursor} - { - m_cursor.beginEditBlock(); - } - ~RaiiGroupUndoActions() { m_cursor.endEditBlock(); } -}; - -class NODISCARD LineHighlighter final : public QSyntaxHighlighter -{ -private: - const int m_maxLength; - -public: - explicit LineHighlighter(int maxLength, QTextDocument *parent); - ~LineHighlighter() final; - - void highlightBlock(const QString &line) override - { - highlightTabs(line); - highlightOverflow(line); - highlightTrailingSpace(line); - highlightAnsi(line); - highlightEntities(line); - highlightEncodingErrors(line); - } - - NODISCARD static QTextCharFormat getBackgroundFormat(const Qt::GlobalColor color) - { - QTextCharFormat fmt; - fmt.setBackground(QBrush{color}); - return fmt; - } - NODISCARD static QTextCharFormat getBackgroundFormat(const QColor &color) - { - QTextCharFormat fmt; - fmt.setBackground(QBrush{color}); - return fmt; - } - - void highlightTabs(const QString &line) - { - if (line.indexOf(C_TAB) < 0) { - return; - } - - const QTextCharFormat fmt = getBackgroundFormat(Qt::yellow); - // REVISIT: Should this be in TabUtils? - mmqt::foreachCharPos(line, C_TAB, [this, &fmt](const auto at) { - setFormat(static_cast(at), 1, fmt); - }); - } - - void highlightOverflow(const QString &line) - { - const int breakPos = (mmqt::measureTabAndAnsiAware(line) <= m_maxLength) ? -1 : m_maxLength; - if (breakPos < 0) { - return; - } - - const auto getFmt = []() -> QTextCharFormat { - QTextCharFormat fmt; - fmt.setFontUnderline(true); - fmt.setUnderlineStyle(QTextCharFormat::UnderlineStyle::WaveUnderline); - fmt.setUnderlineColor(Qt::red); - return fmt; - }; - - const int length = static_cast(line.length()) - breakPos; - setFormat(breakPos, length, getFmt()); - } - - void highlightTrailingSpace(const QString &line) - { - const int breakPos = mmqt::findTrailingWhitespace(line); - if (breakPos < 0) { - return; - } - - const int length = static_cast(line.length()) - breakPos; - setFormat(breakPos, length, getBackgroundFormat(Qt::red)); - } - - void highlightAnsi(const QString &line) - { - const auto red = getBackgroundFormat(Qt::red); - const auto cyan = getBackgroundFormat(Qt::cyan); - - mmqt::foreachAnsi(line, [this, &red, &cyan](const auto start, const QStringView sv) { - setFormat(static_cast(start), - static_cast(sv.length()), - mmqt::isValidAnsiColor(sv) ? cyan : red); - }); - } - - void highlightEntities(const QString &line) - { - const auto red = getBackgroundFormat(Qt::red); - const auto darkOrange = getBackgroundFormat(darkOrangeQColor); - const auto yellow = getBackgroundFormat(Qt::yellow); - - struct NODISCARD MyEntityCallback final : entities::EntityCallback - { - private: - LineHighlighter &m_self; - const QTextCharFormat &m_red; - const QTextCharFormat &m_darkOrange; - const QTextCharFormat &m_yellow; - - public: - explicit MyEntityCallback(LineHighlighter &self, - const QTextCharFormat &red, - const QTextCharFormat &darkOrange, - const QTextCharFormat &yellow) - : m_self{self} - , m_red{red} - , m_darkOrange{darkOrange} - , m_yellow{yellow} - {} - - private: - void virt_decodedEntity(int start, int len, OptQChar decoded) final - { - const auto get_fmt = [this, &decoded]() -> const QTextCharFormat & { - if (!decoded) { - return m_red; - } - const auto val = decoded->unicode(); - return (val < 256) ? m_yellow : m_darkOrange; - }; - - m_self.setFormat(start, len, get_fmt()); - } - } callback{*this, red, darkOrange, yellow}; - entities::foreachEntity(QStringView{line}, callback); - } - - void highlightEncodingErrors(const QString &line) - { - const auto red = getBackgroundFormat(Qt::red); - const auto darkOrange = getBackgroundFormat(darkOrangeQColor); - const auto yellow = getBackgroundFormat(Qt::yellow); - const auto cyan = getBackgroundFormat(Qt::cyan); - - using OptFmt = std::optional; -#define DECL_FMT(name, color, tooltip) \ - OptFmt opt_##name{}; \ - const auto get_##name##_fmt = [&opt_##name, &color]() -> const QTextCharFormat & { \ - auto &opt = opt_##name; \ - if (!opt) { \ - opt = color; \ - if (USE_TOOLTIPS) { \ - opt.value().setToolTip(tooltip); \ - } \ - } \ - return opt.value(); \ - } - DECL_FMT(unicode, red, "Unicode"); - DECL_FMT(nbsp, cyan, "NBSP"); - DECL_FMT(utf8, yellow, "UTF-8"); - DECL_FMT(unprintable, darkOrange, "(unprintable)"); - -#undef DECL_FMT - - int pos = 0; - QChar last; - bool hasLast = false; - for (const auto &qc : line) { - if (qc.unicode() > 0xFF) { - // no valid representation - // TODO: add a means of transliterating things like special quotes - // Does Qt offer this feature somewhere? - // If not, consider iconv -t LATIN1//TRANSLIT - - setFormat(pos, 1, get_unicode_fmt()); - } else { - const char c = mmqt::toLatin1(qc); - switch (c) { - case C_NBSP: - setFormat(pos, 1, get_nbsp_fmt()); - break; - case C_ESC: - case C_TAB: // REVISIT: move tab handler to here? - /* handled elsewhere */ - break; - default: { - const auto uc = static_cast(c); - if (hasLast - && (isClamped(uc, 0x80, 0xBF) - && (last == char16_t(0xC2) || last == char16_t(0xC3)))) { - // Sometimes these are UTF-8 encoded Latin1 values, - // but they could also be intended, so they're not errors. - // TODO: add a feature to fix these on a case-by-case basis? - setFormat(pos - 1, 2, get_utf8_fmt()); - } else if (ascii::isCntrl(c) || !::isPrintLatin1(c)) { - setFormat(pos, 1, get_unprintable_fmt()); - } - } - } - } - - last = qc; - hasLast = true; - ++pos; - } - } -}; - -LineHighlighter::LineHighlighter(const int maxLength, QTextDocument *const parent) - : QSyntaxHighlighter(parent) - , m_maxLength{maxLength} -{} - -LineHighlighter::~LineHighlighter() = default; - RemoteTextEdit::RemoteTextEdit(const QString &initialText, QWidget *const parent) : base(parent) { @@ -363,160 +111,10 @@ void RemoteTextEdit::handle_toolTip(QEvent *const event) const QToolTip::showText(helpEvent->globalPos(), QString("%1 (%2)").arg(tooltip).arg(unicode_buf)); } -NODISCARD static bool lineHasTabs(const QTextCursor &line) -{ - if (line.isNull()) { - return false; - } - const auto &block = line.block(); - if (!block.isValid()) { - return false; - } - return block.text().indexOf(C_TAB) >= 0; -} - -static void expandTabs(QTextCursor line) -{ - const QTextBlock &block = line.block(); - const QString &s = block.text(); - - mmqt::TextBuffer prefix; - prefix.appendExpandedTabs(QStringView{s}, 0); - - line.setPosition(block.position()); - line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - line.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); - line.insertText(prefix.getQString()); -} - -static void tryRemoveLeadingSpaces(QTextCursor line, const int max_spaces) -{ - const auto &block = line.block(); - if (!block.isValid()) { - return; - } - - const auto &text = block.text(); - if (text.isEmpty()) { - return; - } - - const int to_remove = std::invoke([&text, max_spaces]() -> int { - const int len = std::min(max_spaces, static_cast(text.length())); - int n = 0; - while (n < len && text.at(n) == C_SPACE) { - ++n; - } - return n; - }); - - if (to_remove == 0) { - return; - } - - line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - line.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, to_remove); - line.removeSelectedText(); -} - -struct NODISCARD LineRange final -{ - NODISCARD static auto beg(QTextCursor cur) - { - auto from = cur.document()->findBlock(cur.selectionStart()); - auto begCursor = QTextCursor(from); - return begCursor; - } - - NODISCARD static auto end(QTextCursor cur) - { - const auto &to = cur.document()->findBlock(cur.selectionEnd()); - auto endCursor = QTextCursor(to); - if (!endCursor.isNull()) { - endCursor.movePosition(QTextCursor::NextBlock); - } - return endCursor; - } -}; - -/// Caller is responsible for not invalidating the end cursor. -/// -/// callback(QTextCursor); -/// -or- -/// callback(const QTextCursor&); -template -static void foreach_partly_selected_block(QTextCursor cur, Callback &&callback) -{ - auto beg = LineRange::beg(cur); - auto end = LineRange::end(cur); - for (auto it = beg; !it.isNull() && it <= end;) { - if (it.block().isValid()) { - callback(static_cast(it)); - } - if (!it.movePosition(QTextCursor::NextBlock)) { - break; - } - } -} - -enum class NODISCARD CallbackResultEnum { KEEP_GOING, STOP }; - -// Caller is responsible for not invalidating the end cursor. -/// -/// CallbackResultEnum callback(QTextCursor); -/// -or- -/// CallbackResultEnum callback(const QTextCursor&); -template - requires(std::is_invocable_r_v) -static void foreach_partly_selected_block_until(QTextCursor cur, Callback &&callback) -{ - auto beg = LineRange::beg(cur); - auto end = LineRange::end(cur); - for (auto it = beg; !it.isNull() && it < end;) { - if (it.block().isValid()) { - if (callback(static_cast(it)) == CallbackResultEnum::STOP) { - return; - } - } - if (!it.movePosition(QTextCursor::NextBlock)) { - break; - } - } -} - -template - requires(std::is_invocable_r_v) -bool exists_partly_selected_block(QTextCursor cur, Callback &&callback) -{ - bool result = false; - foreach_partly_selected_block_until(cur, - [&result, &callback](QTextCursor it) -> CallbackResultEnum { - if (callback(it)) { - result = true; - return CallbackResultEnum::STOP; - } - return CallbackResultEnum::KEEP_GOING; - }); - return result; -} - -static void insertPrefix(QTextCursor line, const QString &prefix) -{ - line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - line.insertText(prefix); -} - /* perform a 2-space block indentation of all partly-selected lines */ void RemoteTextEdit::prefixPartialSelection(const QString &prefix) { - auto cur = textCursor(); - RaiiGroupUndoActions raii(cur); - foreach_partly_selected_block(cur, [&prefix](const QTextCursor &line) -> void { - if (lineHasTabs(line)) { - expandTabs(line); - } - insertPrefix(line, prefix); - }); + mmqt::remoteEditPrefixPartialSelection(textCursor(), prefix); } void RemoteTextEdit::handleEventTab(QKeyEvent *const event) @@ -528,7 +126,7 @@ void RemoteTextEdit::handleEventTab(QKeyEvent *const event) } /* otherwise, insert a real tab, expand it, and restore the cursor */ - RaiiGroupUndoActions raii(cur); + mmqt::RemoteEditUndoGroup raii(cur); cur.insertText(string_consts::S_TAB); @@ -536,7 +134,7 @@ void RemoteTextEdit::handleEventTab(QKeyEvent *const event) const auto &block = cur.block(); const QString &s = block.text().left(col_before); const int col_after = mmqt::measureExpandedTabsOneLine(s, 0); - expandTabs(cur); + mmqt::remoteEditExpandTabsOnLine(cur); cur.setPosition(block.position() + col_after); setTextCursor(cur); @@ -546,52 +144,12 @@ void RemoteTextEdit::handleEventTab(QKeyEvent *const event) void RemoteTextEdit::handleEventBacktab(QKeyEvent *const event) { event->accept(); - auto cur = textCursor(); - RaiiGroupUndoActions raii(cur); - foreach_partly_selected_block(cur, [](const QTextCursor &line) -> void { - if (lineHasTabs(line)) { - expandTabs(line); - } - tryRemoveLeadingSpaces(line, 2); - }); + mmqt::remoteEditUnindentPartialSelection(textCursor()); } void RemoteTextEdit::joinLines() { - auto cur = textCursor(); - RaiiGroupUndoActions raii(cur); - - auto doc = document(); - const auto from = doc->findBlock(cur.selectionStart()); - auto to = doc->findBlock(cur.selectionEnd()); - - /* Feature: join the next line if only one line is selected */ - if (from == to) { - if (cur.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor)) { - to = doc->findBlock(cur.selectionEnd()); - } - } - - mmqt::TextBuffer buffer; - foreach_partly_selected_block(cur, [&buffer](const QTextCursor line) -> void { - const QTextBlock block = line.block(); - const QString text = block.text(); - if (text.isEmpty()) { - return; - } - - if (!buffer.isEmpty()) { - buffer.append(C_SPACE); - } - buffer.appendExpandedTabs(QStringView{text}); - }); - - /* adjust the selection to cover select everything in the blocks */ - const int a = from.position(); - const int b = to.position() + to.length() - 1; - cur.setPosition(a); - cur.setPosition(b, QTextCursor::KeepAnchor); - cur.insertText(buffer.getQString()); + mmqt::remoteEditJoinLines(textCursor()); } void RemoteTextEdit::quoteLines() @@ -601,36 +159,7 @@ void RemoteTextEdit::quoteLines() void RemoteTextEdit::justifyLines(const int maxLen) { - auto cur = textCursor(); - RaiiGroupUndoActions raii(cur); - - auto doc = document(); - const auto from = doc->findBlock(cur.selectionStart()); - const auto to = doc->findBlock(cur.selectionEnd()); - const auto toBlockNumber = to.blockNumber(); - if (!from.isValid()) { - return; - } - - const int a = from.position(); - const int b = to.position() + to.length() - 1; - - mmqt::TextBuffer buffer; - for (auto it = from; it.isValid() && it.blockNumber() <= toBlockNumber; it = it.next()) { - const auto &text = it.text(); - if (text.isEmpty()) { - continue; - } - - if (!buffer.isEmpty()) { - buffer.append(C_SPACE); - } - buffer.appendJustified(QStringView{text}, maxLen); - } - - cur.setPosition(a); - cur.setPosition(b, QTextCursor::KeepAnchor); - cur.insertText(buffer.getQString()); + mmqt::remoteEditJustifyLines(textCursor(), maxLen); } void RemoteTextEdit::replaceAll(const QString &str) @@ -745,7 +274,7 @@ auto RemoteEditWidget::createTextEdit() -> Editor * pTextEdit->showWhitespace(false); auto *const doc = pTextEdit->document(); - new LineHighlighter(MAX_LENGTH, doc); + new RemoteEditHighlighter(doc, mmqt::REMOTE_EDIT_MAX_LENGTH); return pTextEdit; } @@ -755,10 +284,8 @@ auto RemoteEditWidget::createGotoWidget() -> GotoWidget * pGotoWidget->hide(); connect(pGotoWidget, &GotoWidget::sig_gotoLineRequested, this, [this](int lineNum) { - QTextCursor cursor = m_textEdit->textCursor(); - cursor.movePosition(QTextCursor::Start); - if (cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor, lineNum - 1)) { - m_textEdit->setTextCursor(cursor); + if (auto cursor = mmqt::remoteEditGotoLine(*m_textEdit->document(), lineNum)) { + m_textEdit->setTextCursor(*cursor); m_textEdit->ensureCursorVisible(); slot_updateStatus(QString("Moved to line %1").arg(lineNum)); m_gotoWidget->hide(); @@ -1091,26 +618,26 @@ void RemoteEditWidget::slot_handleFindRequested(const QString &term, QTextDocume return; } - QTextCursor originalCursor = m_textEdit->textCursor(); - - if (m_textEdit->find(term, flags)) { + const auto outcome = mmqt::remoteEditFind(*m_textEdit->document(), + m_textEdit->textCursor(), + term, + flags); + switch (outcome.result) { + case mmqt::RemoteEditFindResultEnum::FOUND: + m_textEdit->setTextCursor(outcome.cursor); slot_updateStatus(QString("Found: '%1'").arg(term)); - return; - } - - // Wrap around - m_textEdit->moveCursor(flags.testFlag(QTextDocument::FindBackward) ? QTextCursor::End - : QTextCursor::Start); - if (m_textEdit->find(term, flags)) { + break; + case mmqt::RemoteEditFindResultEnum::FOUND_AFTER_WRAP: + m_textEdit->setTextCursor(outcome.cursor); slot_updateStatus(QString("Found (from %1): '%2'") .arg(flags.testFlag(QTextDocument::FindBackward) ? "end" : "top") .arg(term)); - return; + break; + case mmqt::RemoteEditFindResultEnum::NOT_FOUND: + // Cursor was never moved, so there's nothing to restore. + slot_updateStatus(QString("Not found: '%1'").arg(term)); + break; } - - // Restore original cursor if not found - m_textEdit->setTextCursor(originalCursor); - slot_updateStatus(QString("Not found: '%1'").arg(term)); } void RemoteEditWidget::slot_handleReplaceCurrentRequested(const QString &findTerm, @@ -1122,15 +649,9 @@ void RemoteEditWidget::slot_handleReplaceCurrentRequested(const QString &findTer } QTextCursor cursor = m_textEdit->textCursor(); - if (cursor.hasSelection()) { - QString selectedText = cursor.selectedText(); - Qt::CaseSensitivity cs = flags.testFlag(QTextDocument::FindCaseSensitively) - ? Qt::CaseSensitive - : Qt::CaseInsensitive; - if (QString::compare(selectedText, findTerm, cs) == 0) { - cursor.insertText(replaceTerm); - slot_updateStatus(QString("Replaced: '%1'").arg(findTerm)); - } + if (mmqt::remoteEditReplaceCurrentIfMatches(cursor, findTerm, replaceTerm, flags)) { + m_textEdit->setTextCursor(cursor); + slot_updateStatus(QString("Replaced: '%1'").arg(findTerm)); } // Always find the next occurrence after attempting replacement @@ -1145,23 +666,11 @@ void RemoteEditWidget::slot_handleReplaceAllRequested(const QString &findTerm, return; } - int replacements = 0; QTextCursor originalCursor = m_textEdit->textCursor(); - m_textEdit->moveCursor(QTextCursor::Start); - m_textEdit->textCursor().beginEditBlock(); - - while (m_textEdit->find(findTerm, flags)) { - QTextCursor matchCursor = m_textEdit->textCursor(); - if (matchCursor.hasSelection()) { - matchCursor.insertText(replaceTerm); - replacements++; - } else { - // Should not happen with QTextEdit::find, but as a safeguard - break; - } - } - - m_textEdit->textCursor().endEditBlock(); + const int replacements = mmqt::remoteEditReplaceAll(*m_textEdit->document(), + findTerm, + replaceTerm, + flags); m_textEdit->setTextCursor(originalCursor); if (replacements > 0) { @@ -1172,240 +681,86 @@ void RemoteEditWidget::slot_handleReplaceAllRequested(const QString &findTerm, } } -struct NODISCARD CursorColumnInfo final -{ - int actual = 0; - int tab_aware = 0; - int tab_and_ansi_aware = 0; -}; - -NODISCARD static CursorColumnInfo getCursorColumn(QTextCursor &cursor) -{ - const int pos = cursor.positionInBlock(); - const auto &block = cursor.block(); - const auto &text = block.text().left(pos); - - CursorColumnInfo cci; - cci.actual = pos; - cci.tab_aware = mmqt::measureExpandedTabsOneLine(text, 0); - cci.tab_and_ansi_aware = mmqt::measureTabAndAnsiAware(text); - return cci; -} - -struct NODISCARD CursorAnsiInfo final -{ - mmqt::TextBuffer buffer; - // RawAnsi ansi; - - explicit operator bool() const { return !buffer.isEmpty(); } -}; - -NODISCARD static CursorAnsiInfo getCursorAnsi(QTextCursor cursor) -{ - const int pos = cursor.positionInBlock(); - - CursorAnsiInfo result; - const auto &line = cursor.block().text(); - mmqt::foreachAnsi(line, [pos, &result](auto start, const QStringView sv) { - if (result || pos < start || pos >= start + sv.length()) { - return; - } - - if (!mmqt::isValidAnsiColor(sv)) { - result.buffer.append("*invalid*"); - // result.ansi = {}; - return; - } - - auto &buffer = result.buffer; - - if (const auto optAnsi = mmqt::parseAnsiColor(RawAnsi{}, sv)) { - const auto &ansi = *optAnsi; - // result.ansi = ansi; - if (ansi == RawAnsi{}) { - buffer.append("reset"); - } else { - std::ostringstream oss; - to_stream(oss, ansi); - buffer.append(mmqt::toQStringUtf8(oss.str())); - } - } else { - result.buffer.append("*error"); - // result.ansi = {}; - } - }); - return result; -} - -NODISCARD static bool linesHaveTabs(const QTextCursor &cur) -{ - return exists_partly_selected_block(cur, [](const QTextCursor &it) -> bool { - return lineHasTabs(it); - }); -} - -NODISCARD static bool linesHaveTrailingSpace(const QTextCursor &cur) -{ - return exists_partly_selected_block(cur, [](const QTextCursor &it) -> bool { - const auto &block = it.block(); - const auto &line = block.text(); - return mmqt::findTrailingWhitespace(line) >= 0; - }); -} - -NODISCARD static bool hasLongLines(const QTextCursor &cur) -{ - return exists_partly_selected_block(cur, [](const QTextCursor &line) -> bool { - const auto &block = line.block(); - const auto &s = block.text(); - return mmqt::measureTabAndAnsiAware(s) > 80; - }); -} - void RemoteEditWidget::slot_updateStatusBar() { - auto cur = m_textEdit->textCursor(); + const auto info = mmqt::computeRemoteEditStatus(m_textEdit->textCursor()); - const auto cci = getCursorColumn(cur); - const int row = cur.blockNumber() + 1; - QString status = QString("Line %1, Column %2").arg(row).arg(cci.tab_and_ansi_aware + 1); - if (cci.tab_aware != cci.tab_and_ansi_aware) { - status.append(QString(" (non-ansi-aware: %1)").arg(cci.tab_aware + 1)); + QString status = QString("Line %1, Column %2").arg(info.line).arg(info.col); + if (info.nonAnsiAwareCol) { + status.append(QString(" (non-ansi-aware: %1)").arg(*info.nonAnsiAwareCol)); } - if (cur.hasSelection()) { + if (info.selection) { const auto plural = [](auto n) { return (n == 1) ? "" : "s"; }; - const QString selection = cur.selection().toPlainText(); - const auto selectionLength = selection.length(); - const auto selectionLines = selection.count(C_NEWLINE) - + (selection.endsWith(C_NEWLINE) ? 0 : 1); - status.append(QString(", Selection: %1 char%2 on %3 line%4") - .arg(selectionLength) - .arg(plural(selectionLength)) - .arg(selectionLines) - .arg(plural(selectionLines))); - } else if (auto ansi = getCursorAnsi(cur)) { - status.append(QString(", AnsiCode: {%1}").arg(ansi.buffer.getQString())); + .arg(info.selection->chars) + .arg(plural(info.selection->chars)) + .arg(info.selection->lines) + .arg(plural(info.selection->lines))); + } else if (!info.ansiCode.isEmpty()) { + status.append(QString(", AnsiCode: {%1}").arg(info.ansiCode)); } - const auto report_errors = [&cur, &status]() { - const bool hasSelection = cur.hasSelection(); - if (!hasSelection) { - cur.select(QTextCursor::Document); + const bool hasSelection = info.selection.has_value(); + bool first = true; + const auto err = [&first, &hasSelection, &status](auto &&x) { + if (first) { + status.append(hasSelection ? ", Selected-Lines-Err: " : ", Document-Err: "); + first = false; + } else { + status.append(", "); } + status.append(std::forward(x)); + }; - bool first = true; - const auto err = [&first, &hasSelection, &status](auto &&x) { - if (first) { - status.append(hasSelection ? ", Selected-Lines-Err: " : ", Document-Err: "); - first = false; - } else { - status.append(", "); - } - status.append(std::forward(x)); - }; + if (info.hasTabs) { + err("Tabs"); + } - if (linesHaveTabs(cur)) { - err("Tabs"); - } + if (info.hasTrailingSpace) { + err("Trailing-Spaces"); + } - if (linesHaveTrailingSpace(cur)) { - err("Trailing-Spaces"); - } + if (info.hasLongLines) { + err("Long-lines"); + } - if (hasLongLines(cur)) { - err("Long-lines"); - } + if (first) { + status.append(hasSelection ? ", Selected-Lines: Ok" : ", Document: Ok"); + } - if (first) { - status.append(hasSelection ? ", Selected-Lines: Ok" : ", Document: Ok"); - } - }; - report_errors(); m_statusBar->showMessage(status); } void RemoteEditWidget::slot_justifyText() { const QString &old = m_textEdit->toPlainText(); - mmqt::TextBuffer text; - text.reserve(static_cast(old.length())); - mmqt::foreachLine(old, - [&text, maxLen = MAX_LENGTH](const QStringView line, bool /*hasNewline*/) { - text.appendJustified(line, maxLen); - text.append(C_NEWLINE); - }); - m_textEdit->replaceAll(text.getQString()); + m_textEdit->replaceAll(mmqt::remoteEditJustifyText(old, mmqt::REMOTE_EDIT_MAX_LENGTH)); } // TODO: Set the tabstops for the edit control to 8 spaces, so the text won't jump when you expand tabs. void RemoteEditWidget::slot_expandTabs() { - const QTextCursor &cur = m_textEdit->textCursor(); - RaiiGroupUndoActions raii{cur}; - - foreach_partly_selected_block(cur, [](QTextCursor line) -> void { - if (lineHasTabs(line)) { - ::expandTabs(line); - } - }); + mmqt::remoteEditExpandTabs(m_textEdit->textCursor()); } void RemoteEditWidget::slot_removeTrailingWhitespace() { - const QTextCursor &cur = m_textEdit->textCursor(); - RaiiGroupUndoActions raii{cur}; - - foreach_partly_selected_block(cur, [](QTextCursor line) -> void { - static const QRegularExpression trailingWhitespace(R"([[:space:]]+$)"); - assert(trailingWhitespace.isValid()); - QString text = line.block().text(); - if (!text.contains(trailingWhitespace)) { - return; - } - - text.remove(trailingWhitespace); - line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - line.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); - line.insertText(text); - }); + mmqt::remoteEditRemoveTrailingWhitespace(m_textEdit->textCursor()); } void RemoteEditWidget::slot_removeDuplicateSpaces() { - const QTextCursor &cur = m_textEdit->textCursor(); - RaiiGroupUndoActions raii{cur}; - - foreach_partly_selected_block(cur, [](QTextCursor line) -> void { - static const QRegularExpression spaces(R"((\t|[[:space:]]{2,}))"); - assert(spaces.isValid()); - QString text = line.block().text(); - if (!text.contains(spaces)) { - return; - } - - text.replace(spaces, string_consts::S_SPACE); - line.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - line.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); - line.insertText(text); - }); + mmqt::remoteEditRemoveDuplicateSpaces(m_textEdit->textCursor()); } void RemoteEditWidget::slot_normalizeAnsi() { const QString &old = m_textEdit->toPlainText(); - if (!mmqt::containsAnsi(old)) { - return; + if (auto output = mmqt::remoteEditNormalizeAnsi(old)) { + m_textEdit->replaceAll(*output); } - - mmqt::TextBuffer output = mmqt::normalizeAnsi(ANSI_COLOR_SUPPORT_HI, old); - if (!output.hasTrailingNewline()) { - output.append(C_NEWLINE); - } - - m_textEdit->replaceAll(output.getQString()); } void RemoteEditWidget::slot_previewAnsi() @@ -1441,7 +796,7 @@ void RemoteEditWidget::slot_toggleWhitespace() void RemoteEditWidget::slot_justifyLines() { - m_textEdit->justifyLines(MAX_LENGTH); + m_textEdit->justifyLines(mmqt::REMOTE_EDIT_MAX_LENGTH); } RemoteEditWidget::~RemoteEditWidget() diff --git a/src/mpi/remoteeditwidget.h b/src/mpi/remoteeditwidget.h index f8a07269f..76e0e7088 100644 --- a/src/mpi/remoteeditwidget.h +++ b/src/mpi/remoteeditwidget.h @@ -19,7 +19,6 @@ struct EditViewCommand; struct EditCommand2; -class AnsiViewWindow; class QCloseEvent; class QMenu; class QMenuBar; @@ -151,7 +150,9 @@ class NODISCARD_QOBJECT RemoteEditWidget : public QDialog QScopedPointer m_textEdit; QScopedPointer m_gotoWidget; QScopedPointer m_findReplaceWidget; - std::unique_ptr m_preview; + // See AnsiViewWindow.h's makeAnsiViewWindow() doc comment for why this + // holds a plain QDialog rather than AnsiViewWindow. + std::unique_ptr m_preview; public: explicit RemoteEditWidget(bool editSession, QString title, QString body, QWidget *parent); @@ -167,7 +168,6 @@ class NODISCARD_QOBJECT RemoteEditWidget : public QDialog private: NODISCARD Editor *createTextEdit(); - void promptDiscardChanges(); NODISCARD GotoWidget *createGotoWidget(); NODISCARD FindReplaceWidget *createFindReplaceWidget(); @@ -179,6 +179,7 @@ class NODISCARD_QOBJECT RemoteEditWidget : public QDialog void addSave(QMenu *fileMenu); void addExit(QMenu *fileMenu); void addStatusBar(const Editor *pTextEdit); + void promptDiscardChanges(); signals: void sig_cancel(); diff --git a/src/opengl/OpenGL.cpp b/src/opengl/OpenGL.cpp index 3d53e6ae7..d8ec14ded 100644 --- a/src/opengl/OpenGL.cpp +++ b/src/opengl/OpenGL.cpp @@ -272,16 +272,36 @@ float OpenGL::getDevicePixelRatio() const return getFunctions().getDevicePixelRatio(); } +float OpenGL::getHostDevicePixelRatio() const +{ + return getFunctions().getHostDevicePixelRatio(); +} + void OpenGL::glViewport(GLint x, GLint y, GLsizei w, GLsizei h) { getFunctions().glViewport(x, y, w, h); } +void OpenGL::glFinish() +{ + getFunctions().glFinish(); +} + void OpenGL::setDevicePixelRatio(const float devicePixelRatio) { getFunctions().setDevicePixelRatio(devicePixelRatio); } +void OpenGL::setRenderScale(const float renderScale) +{ + getFunctions().setRenderScale(renderScale); +} + +float OpenGL::getRenderScale() const +{ + return getFunctions().getRenderScale(); +} + // NOTE: Technically we could assert that the SharedMMTexture::getId() == id, // but this is treated as an opaque pointer and we don't include the header for it. void OpenGL::setTextureLookup(const MMTextureId id, SharedMMTexture tex) diff --git a/src/opengl/OpenGL.h b/src/opengl/OpenGL.h index ad45bbb09..cad4b8d9f 100644 --- a/src/opengl/OpenGL.h +++ b/src/opengl/OpenGL.h @@ -52,8 +52,12 @@ class NODISCARD OpenGL final void initializeRenderer(float devicePixelRatio); NODISCARD const char *glGetString(GLenum name); NODISCARD int glGetInteger(GLenum name); + void glFinish(); void setDevicePixelRatio(float devicePixelRatio); NODISCARD float getDevicePixelRatio() const; + NODISCARD float getHostDevicePixelRatio() const; + void setRenderScale(float renderScale); + NODISCARD float getRenderScale() const; NODISCARD bool isRendererInitialized() const { return m_rendererInitialized; } public: diff --git a/src/opengl/legacy/Legacy.cpp b/src/opengl/legacy/Legacy.cpp index f9b337da7..886a2bb3d 100644 --- a/src/opengl/legacy/Legacy.cpp +++ b/src/opengl/legacy/Legacy.cpp @@ -541,6 +541,11 @@ void Functions::blitFboToDefault() getFBO().resolve(); if (const GLuint textureId = getFBO().resolvedTextureId(); textureId != 0) { + // Present at the host's full resolution regardless of the render + // scale the FBO was drawn at; the next paint sets the viewport again. + const Viewport present = getPresentViewport(); + Base::glViewport(present.offset.x, present.offset.y, present.size.x, present.size.y); + const auto state = GLRenderState() .withBlend(BlendModeEnum::NONE) .withDepthFunction(std::nullopt) diff --git a/src/opengl/legacy/Legacy.h b/src/opengl/legacy/Legacy.h index 6ab4f184d..debb08814 100644 --- a/src/opengl/legacy/Legacy.h +++ b/src/opengl/legacy/Legacy.h @@ -143,6 +143,10 @@ class NODISCARD Functions : protected QOpenGLExtraFunctions, glm::mat4 m_viewProj = glm::mat4(1); Viewport m_viewport; float m_devicePixelRatio = 1.f; + // Offscreen rendering happens at devicePixelRatio * renderScale; the + // result is presented at the host's full devicePixelRatio (see + // blitFboToDefault()). Below 1 trades sharpness for FBO memory. + float m_renderScale = 1.f; std::unique_ptr m_shaderPrograms; std::unique_ptr m_sharedVaos; std::unique_ptr m_sharedVbos; @@ -160,7 +164,11 @@ class NODISCARD Functions : protected QOpenGLExtraFunctions, DELETE_CTORS_AND_ASSIGN_OPS(Functions); public: - NODISCARD float getDevicePixelRatio() const { return m_devicePixelRatio; } + // Render-target (FBO) pixels per logical unit: what glyph atlases, line + // widths and point sizes are sized in. + NODISCARD float getDevicePixelRatio() const { return m_devicePixelRatio * m_renderScale; } + // The host's own ratio, i.e. default-framebuffer pixels per logical unit. + NODISCARD float getHostDevicePixelRatio() const { return m_devicePixelRatio; } void setDevicePixelRatio(const float devicePixelRatio) { @@ -172,6 +180,15 @@ class NODISCARD Functions : protected QOpenGLExtraFunctions, m_devicePixelRatio = devicePixelRatio; } + NODISCARD float getRenderScale() const { return m_renderScale; } + void setRenderScale(const float renderScale) + { + if (!std::isfinite(renderScale) || !isClamped(renderScale, 0.25f, 1.f)) { + throw std::invalid_argument("renderScale"); + } + m_renderScale = renderScale; + } + public: using Base::initializeOpenGLFunctions; @@ -206,6 +223,7 @@ class NODISCARD Functions : protected QOpenGLExtraFunctions, using Base::glDrawElementsInstanced; using Base::glEnable; using Base::glEnableVertexAttribArray; + using Base::glFinish; using Base::glGenBuffers; using Base::glGenerateMipmap; using Base::glGenTransformFeedbacks; @@ -270,10 +288,11 @@ class NODISCARD Functions : protected QOpenGLExtraFunctions, } private: + // Logical -> offscreen (FBO) pixels. NODISCARD float scalef(const float f) const { static_assert(std::is_same_v); - return f * m_devicePixelRatio; + return f * getDevicePixelRatio(); } NODISCARD int scalei(const int n) const @@ -286,6 +305,7 @@ class NODISCARD Functions : protected QOpenGLExtraFunctions, public: NODISCARD Viewport getViewport() const { return m_viewport; } + // The viewport in offscreen (FBO) pixels. NODISCARD Viewport getPhysicalViewport() const { const auto &offset = m_viewport.offset; @@ -293,6 +313,17 @@ class NODISCARD Functions : protected QOpenGLExtraFunctions, return Viewport{{scalei(offset.x), scalei(offset.y)}, {scalei(size.x), scalei(size.y)}}; } + // The viewport in the host's (default framebuffer) pixels. + NODISCARD Viewport getPresentViewport() const + { + const auto scale = [this](const int n) { + return static_cast(std::lround(static_cast(n) * getHostDevicePixelRatio())); + }; + const auto &offset = m_viewport.offset; + const auto &size = m_viewport.size; + return Viewport{{scale(offset.x), scale(offset.y)}, {scale(size.x), scale(size.y)}}; + } + public: NODISCARD glm::mat4 getProjectionMatrix() const { return m_viewProj; } diff --git a/src/parser/AbstractParser-Config.cpp b/src/parser/AbstractParser-Config.cpp index bc0fdb2e1..3fe671464 100644 --- a/src/parser/AbstractParser-Config.cpp +++ b/src/parser/AbstractParser-Config.cpp @@ -4,7 +4,7 @@ #include "../configuration/NamedConfig.h" #include "../configuration/configuration.h" #include "../display/MapCanvasData.h" -#include "../display/mapcanvas.h" +#include "../display/MapCanvasWindow.h" #include "../global/AnsiOstream.h" #include "../global/Consts.h" #include "../global/NamedColors.h" @@ -18,6 +18,7 @@ #include "abstractparser.h" #include +#include #include #include @@ -206,14 +207,14 @@ void AbstractParser::doConfig(const StringView cmd) // static because it has no captures static const auto getZoom = []() -> float { - if (auto primary = MapCanvas::getPrimary()) { + if (auto primary = MapCanvasWindow::getPrimary()) { return primary->getRawZoom(); } return 1.f; }; const auto setZoom = [this](float f) -> bool { - if (auto primary = MapCanvas::getPrimary()) { + if (auto primary = MapCanvasWindow::getPrimary()) { primary->setZoom(f); this->graphicsSettingsChanged(); return true; @@ -373,39 +374,37 @@ void AbstractParser::doConfig(const StringView cmd) } // REVISIT: Ideally we support external editor as well + auto onSave = [weakParser = QPointer(this)]( + const QString &edited) { + if (weakParser.isNull()) { + return; + } + + QTemporaryFile tempRead(QDir::tempPath() + "/mmapper_XXXXXX.ini"); + tempRead.setAutoRemove(true); + if (tempRead.open()) { + QString name = tempRead.fileName(); + tempRead.write(edited.toUtf8()); + tempRead.close(); + + { + auto &cfg = setConfig(); + QSettings settings(name, QSettings::IniFormat); + cfg.readFrom(settings); + cfg.write(); + } + + weakParser->sendToUser(SendToUserSourceEnum::FromMMapper, + "\nConfiguration imported and persisted.\n"); + weakParser->sendOkToUser(); + } + }; + auto *editor = new RemoteEditWidget(true, "MMapper Client Configuration", content, nullptr); - QObject::connect(editor, - &RemoteEditWidget::sig_save, - [weakParser = QPointer(this)]( - const QString &edited) { - if (weakParser.isNull()) { - return; - } - - QTemporaryFile tempRead(QDir::tempPath() - + "/mmapper_XXXXXX.ini"); - tempRead.setAutoRemove(true); - if (tempRead.open()) { - QString name = tempRead.fileName(); - tempRead.write(edited.toUtf8()); - tempRead.close(); - - { - auto &cfg = setConfig(); - QSettings settings(name, QSettings::IniFormat); - cfg.readFrom(settings); - cfg.write(); - } - - weakParser->sendToUser( - SendToUserSourceEnum::FromMMapper, - "\nConfiguration imported and persisted.\n"); - weakParser->sendOkToUser(); - } - }); + QObject::connect(editor, &RemoteEditWidget::sig_save, std::move(onSave)); editor->setAttribute(Qt::WA_DeleteOnClose); editor->show(); diff --git a/src/preferences/AnsiColorTables.cpp b/src/preferences/AnsiColorTables.cpp new file mode 100644 index 000000000..0124f2a21 --- /dev/null +++ b/src/preferences/AnsiColorTables.cpp @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "AnsiColorTables.h" + +#include "../global/TextUtils.h" + +#include +#include + +#include +#include + +namespace AnsiColorTables { + +const std::vector &colorTable() +{ + static const std::vector table = [] { + std::vector result; + result.reserve(17); + + const auto add = [&result](const AnsiColor16 color) { + Entry entry; + entry.color = color; + entry.description = mmqt::toQStringUtf8(color.isDefault() ? "none" + : color.to_string_view()); + result.push_back(std::move(entry)); + }; + + add(AnsiColor16{}); + +#define X_ADD(n, lower, UPPER) \ + add(AnsiColor16{AnsiColor16Enum::lower}); \ + add(AnsiColor16{AnsiColor16Enum::UPPER}); + XFOREACH_ANSI_COLOR_0_7(X_ADD) +#undef X_ADD + + assert(result.size() == 17); + return result; + }(); + return table; +} + +ParsedColor colorFromString(const QString &colString) +{ + // No need to proceed if the color is empty + if (colString.isEmpty()) { + return ParsedColor{}; + } + + static const QRegularExpression re(R"(^\[((?:\d+[;:])*\d+)m$)"); + if (!re.match(colString).hasMatch()) { + qWarning() << "String did not contain valid ANSI: " << colString; + return ParsedColor{}; + } + + const AnsiColorState state = std::invoke([&colString]() -> AnsiColorState { + AnsiColorState result_state; + QString tmpStr = colString; + tmpStr.chop(1); + tmpStr.remove(0, 1); + for (const auto &s : tmpStr.split(";", Qt::SplitBehaviorFlags::SkipEmptyParts)) { + const auto n = s.toInt(); + result_state.receive(n); + } + return result_state; + }); + + if (!state.hasCompleteState()) { + qWarning() << "String did not contain valid ANSI: " << colString; + } + + const RawAnsi raw = state.getRawAnsi(); + + ParsedColor color; + color.fg = toAnsiColor16(raw.fg); + color.bg = toAnsiColor16(raw.bg); + color.bold = raw.hasBold(); + color.italic = raw.hasItalic(); + color.underline = raw.hasUnderline(); + return color; +} + +QString generateAnsiString(const AnsiColor16 fg, + const AnsiColor16 bg, + const bool bold, + const bool italic, + const bool underline) +{ + RawAnsi raw; + + raw.fg = AnsiColorVariant{fg}; + raw.bg = AnsiColorVariant{bg}; + + if (bold) { + raw.setBold(); + } + if (italic) { + raw.setItalic(); + } + if (underline) { + raw.setUnderline(); + } + + if (raw == RawAnsi{}) { + return ""; + } + + const AnsiString s = ansi_string(ANSI_COLOR_SUPPORT_HI, raw); + if (s.isEmpty()) { + return ""; + } + + auto sv = s.getStdStringView(); + assert(sv.front() == char_consts::C_ESC); + assert(sv.back() == 'm'); + sv.remove_prefix(1); + return mmqt::toQStringUtf8(sv); +} + +} // namespace AnsiColorTables diff --git a/src/preferences/AnsiColorTables.h b/src/preferences/AnsiColorTables.h new file mode 100644 index 000000000..a340a65fe --- /dev/null +++ b/src/preferences/AnsiColorTables.h @@ -0,0 +1,61 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "../global/AnsiTextUtils.h" +#include "../global/macros.h" + +#include + +#include +#include + +// Widget-free home for the ANSI 16-color swatch table and string <-> color +// conversions used by preferences/ansicombo.{h,cpp}'s AnsiCombo widget (see +// AnsiCombo::initColours()/colorFromString()), which delegates to this file +// instead of duplicating the logic. +namespace AnsiColorTables { + +// One entry in the 17-row fg/bg swatch list: index 0 is always the +// "default" (no color) entry, followed by one row per XFOREACH_ANSI_COLOR_0_7 +// color in low-then-high order (black, BLACK, red, RED, ...), matching +// AnsiCombo::initColours()'s UI ordering. +struct NODISCARD Entry final +{ + AnsiColor16 color; + QString description; // e.g. "none", "red", "RED" +}; + +NODISCARD const std::vector &colorTable(); + +// Mirrors AnsiCombo::AnsiColor (see ansicombo.h): the decoded fg/bg/style +// state of a single ANSI escape-sequence string. +struct NODISCARD ParsedColor final +{ + AnsiColor16 bg; + AnsiColor16 fg; + bool bold = false; + bool italic = false; + bool underline = false; + + NODISCARD AnsiColor16Enum getBg() const { return bg.color.value_or(AnsiColor16Enum::white); } + NODISCARD AnsiColor16Enum getFg() const { return fg.color.value_or(AnsiColor16Enum::black); } + NODISCARD QColor getBgColor() const { return mmqt::toQColor(getBg()); } + NODISCARD QColor getFgColor() const { return mmqt::toQColor(getFg()); } + NODISCARD QString getBgName() const { return mmqt::toQStringUtf8(bg.to_string_view()); } + NODISCARD QString getFgName() const { return mmqt::toQStringUtf8(fg.to_string_view()); } +}; + +// \return the decoded fg/bg/style state of an ANSI escape-sequence string +// like "[1;32m", or a default-constructed ParsedColor if it isn't valid. +NODISCARD ParsedColor colorFromString(const QString &ansiString); + +// Builds the ANSI escape-sequence string with the leading ESC stripped (e.g. +// "[1;32m", the same representation Configuration::ParserSettings:: +// roomNameColor/roomDescColor store) for the given fg/bg/style combination, +// or an empty string for the default (no style at all) combination. Mirrors +// AnsiColorDialog::slot_generateNewAnsiColor()'s getColor lambda. +NODISCARD QString +generateAnsiString(AnsiColor16 fg, AnsiColor16 bg, bool bold, bool italic, bool underline); + +} // namespace AnsiColorTables diff --git a/src/preferences/ManagePasswordDialog.cpp b/src/preferences/ManagePasswordDialog.cpp index c0b90515e..eddeef9ea 100644 --- a/src/preferences/ManagePasswordDialog.cpp +++ b/src/preferences/ManagePasswordDialog.cpp @@ -16,6 +16,12 @@ ManagePasswordDialog::ManagePasswordDialog(QWidget *parent) { ui->setupUi(this); + // On-screen keyboards: no auto-capitalization or prediction for account + // names, and additionally no learning/history for the password. + ui->accountName->setInputMethodHints(Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText); + ui->accountPassword->setInputMethodHints(Qt::ImhSensitiveData | Qt::ImhNoAutoUppercase + | Qt::ImhNoPredictiveText); + if constexpr (CURRENT_PLATFORM == PlatformEnum::Wasm) { setWindowTitle("Manage Account"); ui->label_2->hide(); diff --git a/src/preferences/ansicombo.cpp b/src/preferences/ansicombo.cpp index 8f68aae97..da4f54130 100644 --- a/src/preferences/ansicombo.cpp +++ b/src/preferences/ansicombo.cpp @@ -45,17 +45,17 @@ void AnsiCombo::setAnsiCode(const AnsiColor16 ansiCode) assert(getAnsiCode() == ansiCode); } -NODISCARD static AnsiCombo::AnsiItem initAnsiItem(const AnsiColor16 ansiCode, +NODISCARD static AnsiCombo::AnsiItem initAnsiItem(const AnsiColorTables::Entry &tableEntry, const AnsiColor16LocationEnum mode) { - auto defColor = mode == AnsiColor16LocationEnum::Foreground ? AnsiColor16Enum::black - : AnsiColor16Enum::white; - - const AnsiColor16Enum color = ansiCode.color.value_or(defColor); - - auto make_pix = [color]() { + // The "no color" swatch's fill has no genuine ANSI color to draw, so it + // falls back to black for foreground and white for background, just to + // visually distinguish the two combos' "none" rows. + const auto defColor = mode == AnsiColor16LocationEnum::Foreground ? AnsiColor16Enum::black + : AnsiColor16Enum::white; + auto make_pix = [&tableEntry, defColor]() { QPixmap pix(20, 20); - pix.fill(mmqt::toQColor(color)); + pix.fill(mmqt::toQColor(tableEntry.color.color.value_or(defColor))); // Draw border { QPainter paint(&pix); @@ -66,11 +66,10 @@ NODISCARD static AnsiCombo::AnsiItem initAnsiItem(const AnsiColor16 ansiCode, }; AnsiCombo::AnsiItem retVal; - retVal.color = ansiCode; + retVal.color = tableEntry.color; retVal.loc = mode; retVal.picture = make_pix(); - retVal.description = mmqt::toQStringUtf8(ansiCode.isDefault() ? "none" - : ansiCode.to_string_view()); + retVal.description = tableEntry.description; return retVal; } @@ -87,64 +86,16 @@ void AnsiCombo::initColours(const AnsiColor16LocationEnum change) addItem(item.picture, item.description, userData); }; - add(initAnsiItem(AnsiColor16{}, m_mode)); - -#define X_INIT(N, lower, UPPER) \ - add(initAnsiItem(AnsiColor16{AnsiColor16Enum::lower}, m_mode)); \ - add(initAnsiItem(AnsiColor16{AnsiColor16Enum::UPPER}, m_mode)); - - XFOREACH_ANSI_COLOR_0_7(X_INIT) - -#undef X_INIT + for (const AnsiColorTables::Entry &entry : AnsiColorTables::colorTable()) { + add(initAnsiItem(entry, m_mode)); + } this->setAnsiCode(AnsiColor16{}); } AnsiCombo::AnsiColor AnsiCombo::colorFromString(const QString &colString) { - auto stdString = colString.toUtf8().toStdString(); - - // No need to proceed if the color is empty - if (colString.isEmpty()) { - return AnsiColor{}; - } - - // TODO: use existing test (prepend an ESC if necessary) - static const QRegularExpression re(R"(^\[((?:\d+[;:])*\d+)m$)"); - if (!re.match(colString).hasMatch()) { - qWarning() << "String did not contain valid ANSI: " << colString; - return AnsiColor{}; - } - - // TODO: use existing interface to split the string - const AnsiColorState state = std::invoke([&colString]() -> AnsiColorState { - AnsiColorState result_state; - QString tmpStr = colString; - tmpStr.chop(1); - tmpStr.remove(0, 1); - for (const auto &s : tmpStr.split(";", Qt::SplitBehaviorFlags::SkipEmptyParts)) { - const auto n = s.toInt(); - result_state.receive(n); - } - return result_state; - }); - - if (!state.hasCompleteState()) { - qWarning() << "String did not contain valid ANSI: " << colString; - } - - auto toAnsiColor = [](const RawAnsi &raw) { - AnsiColor color; - color.fg = toAnsiColor16(raw.fg); - color.bg = toAnsiColor16(raw.bg); - color.bold = raw.hasBold(); - color.italic = raw.hasItalic(); - color.underline = raw.hasUnderline(); - return color; - }; - - const RawAnsi raw = state.getRawAnsi(); - return toAnsiColor(raw); + return AnsiColorTables::colorFromString(colString); } // TODO: move this some place more appropriate. diff --git a/src/preferences/ansicombo.h b/src/preferences/ansicombo.h index f5fee50a8..ff96b6334 100644 --- a/src/preferences/ansicombo.h +++ b/src/preferences/ansicombo.h @@ -6,6 +6,7 @@ #include "../global/AnsiTextUtils.h" #include "../global/macros.h" +#include "AnsiColorTables.h" #include @@ -100,29 +101,10 @@ class NODISCARD_QOBJECT AnsiCombo : public QComboBox NODISCARD AnsiColor16 getAnsiCode() const; void setAnsiCode(AnsiColor16); - struct NODISCARD AnsiColor final - { - AnsiColor16 bg; - AnsiColor16 fg; - bool bold = false; - bool italic = false; - bool underline = false; - - public: - NODISCARD AnsiColor16Enum getBg() const - { - return bg.color.value_or(AnsiColor16Enum::white); - } - NODISCARD AnsiColor16Enum getFg() const - { - return fg.color.value_or(AnsiColor16Enum::black); - } - NODISCARD QColor getBgColor() const { return mmqt::toQColor(getBg()); } - NODISCARD QColor getFgColor() const { return mmqt::toQColor(getFg()); } - - NODISCARD QString getBgName() const { return mmqt::toQStringUtf8(bg.to_string_view()); } - NODISCARD QString getFgName() const { return mmqt::toQStringUtf8(fg.to_string_view()); } - }; + // Alias (rather than a separate struct with the same fields) so callers + // can keep using AnsiCombo::AnsiColor's members directly; the definition + // and colorFromString() logic live in the widget-free AnsiColorTables.h. + using AnsiColor = AnsiColorTables::ParsedColor; /// \return true if string is valid ANSI color code NODISCARD static AnsiColor colorFromString(const QString &ansiString); diff --git a/src/preferences/clientpage.cpp b/src/preferences/clientpage.cpp index 7a2d46f1e..758d8c2eb 100644 --- a/src/preferences/clientpage.cpp +++ b/src/preferences/clientpage.cpp @@ -5,12 +5,14 @@ #include "clientpage.h" #include "../configuration/configuration.h" +#include "../global/ConfigConsts-Computed.h" #include "../global/macros.h" #include "ui_clientpage.h" #include #include #include +#include #include #include #include @@ -52,6 +54,26 @@ ClientPage::ClientPage(QWidget *parent) { ui->setupUi(this); + if constexpr (CURRENT_PLATFORM == PlatformEnum::Wasm) { + ui->howToPlayGroupBox->hide(); // only the built-in client exists + } + const auto setGameClient = [](const GameClientEnum client) { + return [client](const bool checked) { + if (checked) { + setConfig().general.gameClient = client; + } + }; + }; + connect(ui->askRadioButton, &QRadioButton::toggled, this, setGameClient(GameClientEnum::ASK)); + connect(ui->builtInRadioButton, + &QRadioButton::toggled, + this, + setGameClient(GameClientEnum::BUILT_IN)); + connect(ui->externalRadioButton, + &QRadioButton::toggled, + this, + setGameClient(GameClientEnum::EXTERNAL)); + connect(ui->fontPushButton, &QAbstractButton::pressed, this, &ClientPage::slot_onChangeFont); connect(ui->bgColorPushButton, &QAbstractButton::pressed, @@ -129,6 +151,20 @@ void ClientPage::slot_loadConfig() { updateFontAndColors(); + switch (getConfig().general.gameClient) { + case GameClientEnum::ASK: + ui->askRadioButton->setChecked(true); + break; + case GameClientEnum::BUILT_IN: + ui->builtInRadioButton->setChecked(true); + break; + case GameClientEnum::EXTERNAL: + ui->externalRadioButton->setChecked(true); + break; + } + ui->externalRadioButton->setText(tr("Use my own MUD client (connect it to localhost, port %1)") + .arg(getConfig().connection.localPort)); + const auto &settings = getConfig().integratedClient; ui->columnsSpinBox->setValue(settings.columns); ui->rowsSpinBox->setValue(settings.rows); diff --git a/src/preferences/clientpage.ui b/src/preferences/clientpage.ui index 04de6229e..5ef842c3d 100644 --- a/src/preferences/clientpage.ui +++ b/src/preferences/clientpage.ui @@ -6,6 +6,36 @@ Form
+ + + + How do you play? + + + + + + Ask each time MMapper starts + + + + + + + Play in MMapper + + + + + + + Use my own MUD client (connect it to localhost, port 4242) + + + + + + diff --git a/src/preferences/configdialog.cpp b/src/preferences/configdialog.cpp index 0dc59b742..d467e02a0 100644 --- a/src/preferences/configdialog.cpp +++ b/src/preferences/configdialog.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -99,7 +100,7 @@ ConfigDialog::ConfigDialog(QWidget *const parent) addPage(generalPage, tr("General"), ":/icons/generalcfg.png"); addPage(graphicsPage, tr("Graphics"), ":/icons/graphicscfg.png"); addPage(parserPage, tr("Parser"), ":/icons/parsercfg.png"); - addPage(clientPage, tr("Integrated Client"), ":/icons/terminal.png"); + addPage(clientPage, tr("Game Client"), ":/icons/terminal.png"); addPage(groupPage, tr("Group Panel"), ":/icons/group-recolor.png"); addPage(autoLogPage, tr("Auto Logger"), ":/icons/autologgercfg.png"); addPage(audioPage, tr("Audio"), ":/icons/audiocfg.png"); @@ -183,6 +184,22 @@ void ConfigDialog::showEvent(QShowEvent *const event) event->accept(); } +void ConfigDialog::setCompactLayout(const bool compact) +{ + ui->mainSplitter->setOrientation(compact ? Qt::Vertical : Qt::Horizontal); + + // On a phone the dialog must be able to shrink below the pages' natural + // width (MinimumExpanding makes that width the dialog's minimum), and a + // finger must scroll the pages and the page list (see + // MainWindow::applyPanelScrollGesture() for the gesture choice). + ui->pagesScrollArea->setSizePolicy(compact ? QSizePolicy::Expanding + : QSizePolicy::MinimumExpanding, + QSizePolicy::Expanding); + const auto gesture = compact ? QScroller::LeftMouseButtonGesture : QScroller::TouchGesture; + QScroller::grabGesture(ui->pagesScrollArea->viewport(), gesture); + QScroller::grabGesture(ui->contentsWidget->viewport(), gesture); +} + void ConfigDialog::scrollToWidget(QWidget *target, bool focus) { const int targetY = target->mapTo(ui->scrollAreaWidgetContents, QPoint(0, 0)).y(); diff --git a/src/preferences/configdialog.h b/src/preferences/configdialog.h index 2a92aad5e..754f64c0d 100644 --- a/src/preferences/configdialog.h +++ b/src/preferences/configdialog.h @@ -42,6 +42,10 @@ class ConfigDialog final : public QDialog explicit ConfigDialog(QWidget *parent = nullptr); ~ConfigDialog() override; + // Stacks the page list above the pages (instead of beside them) so the + // dialog fits a narrow screen. + void setCompactLayout(bool compact); + private: void scrollToWidget(QWidget *target, bool focus = false); diff --git a/src/preferences/generalpage.cpp b/src/preferences/generalpage.cpp index 4db2c9a23..21fb2ba92 100644 --- a/src/preferences/generalpage.cpp +++ b/src/preferences/generalpage.cpp @@ -91,6 +91,11 @@ GeneralPage::GeneralPage(QWidget *parent) this, &GeneralPage::slot_displayMumeClockStateChanged); + connect(ui->uiFontScaleSpinBox, + QOverload::of(&QDoubleSpinBox::valueChanged), + this, + [](const double value) { setConfig().general.uiFontScale = value; }); + connect(ui->displayXPStatusCheckBox, &QCheckBox::stateChanged, this, @@ -323,6 +328,7 @@ void GeneralPage::slot_loadConfig() ui->displayMumeClockCheckBox->setChecked(config.mumeClock.display); ui->displayXPStatusCheckBox->setChecked(config.adventurePanel.getDisplayXPStatus()); + ui->uiFontScaleSpinBox->setValue(general.uiFontScale); ui->proxyConnectionStatusCheckBox->setChecked(connection.proxyConnectionStatus); diff --git a/src/preferences/generalpage.ui b/src/preferences/generalpage.ui index be82f2a4e..40e7b8e2c 100644 --- a/src/preferences/generalpage.ui +++ b/src/preferences/generalpage.ui @@ -163,6 +163,44 @@ + + + + UI font scale: + + + uiFontScaleSpinBox + + + + + + + Multiplier applied to the application font size at startup. Takes effect after restarting MMapper. + + + Qt::FocusPolicy::StrongFocus + + + x + + + 2 + + + 0.500000000000000 + + + 3.000000000000000 + + + 0.100000000000000 + + + 1.000000000000000 + + +
diff --git a/src/preferences/graphicspage.cpp b/src/preferences/graphicspage.cpp index 6d909bf9e..00a053ae2 100644 --- a/src/preferences/graphicspage.cpp +++ b/src/preferences/graphicspage.cpp @@ -59,6 +59,21 @@ GraphicsPage::GraphicsPage(QWidget *parent) graphicsSettingsChanged(); } }); + connect(ui->renderScaleComboBox, + &QComboBox::currentTextChanged, + this, + [this](const QString & /*text*/) { + if (ui->renderScaleComboBox->isEnabled()) { + const int scale = ui->renderScaleComboBox + ->itemData(ui->renderScaleComboBox->currentIndex()) + .toInt(); + if (scale > 0) { + setConfig().canvas.renderScale.set(scale); + syncAntialiasingSamplesComboBox(); + graphicsSettingsChanged(); + } + } + }); connect(ui->trilinearFilteringCheckBox, &QCheckBox::stateChanged, this, [this](int /*unused*/) { setConfig().canvas.trilinearFiltering.set(ui->trilinearFilteringCheckBox->isChecked()); graphicsSettingsChanged(); @@ -119,6 +134,24 @@ void GraphicsPage::slot_loadConfig() setIconColor(ui->darkLitPushButton, settings.roomDarkLitColor); setIconColor(ui->connectionNormalPushButton, settings.connectionNormalColor); + { + ui->renderScaleComboBox->setEnabled(false); + ui->renderScaleComboBox->clear(); + static constexpr std::array scales{50, 75, 100}; + for (const int s : scales) { + QString label = QString("%1%").arg(s); + if (s == 100) { + label += " (Native)"; + } + ui->renderScaleComboBox->addItem(label, s); + } + const int currentScale = settings.renderScale.get(); + const int index = utils::clampNonNegative( + ui->renderScaleComboBox->findData(QVariant(currentScale), Qt::UserRole)); + ui->renderScaleComboBox->setCurrentIndex(index); + ui->renderScaleComboBox->setEnabled(true); + } + { ui->antialiasingSamplesComboBox->setEnabled(false); ui->antialiasingSamplesComboBox->clear(); @@ -129,12 +162,9 @@ void GraphicsPage::slot_loadConfig() i = 1; } } - const auto samples = std::min(settings.antialiasingSamples.get(), maxSamples); - const int index = utils::clampNonNegative( - ui->antialiasingSamplesComboBox->findData(QVariant(samples), Qt::UserRole)); - ui->antialiasingSamplesComboBox->setCurrentIndex(index); - ui->antialiasingSamplesComboBox->setEnabled(true); + syncAntialiasingSamplesComboBox(); } + ui->trilinearFilteringCheckBox->setChecked(settings.trilinearFiltering.get()); ui->drawUnsavedChanges->setChecked(settings.showUnsavedChanges.get()); @@ -147,6 +177,24 @@ void GraphicsPage::slot_loadConfig() ui->weatherTimeOfDaySlider->setValue(settings.weatherTimeOfDayIntensity.get()); } +void GraphicsPage::syncAntialiasingSamplesComboBox() +{ + // Shows "Off" while the render scale is below 100% (MapCanvas ignores + // MSAA there) without touching the stored setting: the combo's handler + // only writes to the config while the combo is enabled, so it is + // disabled before its index changes. + const auto &settings = getConfig().canvas; + const bool scaled = settings.renderScale.get() < 100; + auto &combo = deref(ui->antialiasingSamplesComboBox); + combo.setEnabled(false); + const int effectiveSamples = scaled ? 0 : settings.antialiasingSamples.get(); + const auto samples = std::min(effectiveSamples, OpenGLConfig::getMaxSamples()); + combo.setCurrentIndex(utils::clampNonNegative(combo.findData(QVariant(samples), Qt::UserRole))); + combo.setEnabled(!scaled); + combo.setToolTip(scaled ? "Anti-aliasing (MSAA) is disabled when Render Scale is below 100%." + : ""); +} + void GraphicsPage::changeColorClicked(XNamedColor &namedColor, QPushButton *const pushButton) { const QColor origColor = namedColor.getColor().getQColor(); diff --git a/src/preferences/graphicspage.h b/src/preferences/graphicspage.h index 1135cce98..6370c4320 100644 --- a/src/preferences/graphicspage.h +++ b/src/preferences/graphicspage.h @@ -31,6 +31,7 @@ class NODISCARD_QOBJECT GraphicsPage final : public QWidget private: void changeColorClicked(XNamedColor &color, QPushButton *pushButton); + void syncAntialiasingSamplesComboBox(); void graphicsSettingsChanged() { emit sig_graphicsSettingsChanged(); } Ui::GraphicsPage *const ui; std::unique_ptr m_advanced; diff --git a/src/preferences/graphicspage.ui b/src/preferences/graphicspage.ui index d6ac0506f..a07fa56d0 100644 --- a/src/preferences/graphicspage.ui +++ b/src/preferences/graphicspage.ui @@ -145,6 +145,38 @@
+ + + Render scale: + + + renderScaleComboBox + + + + + + + Qt::FocusPolicy::StrongFocus + + + + 50% + + + + + 75% + + + + + 100% (Native) + + + + + Trilinear filtering diff --git a/src/proxy/ProxyHost.cpp b/src/proxy/ProxyHost.cpp new file mode 100644 index 000000000..44f3bee48 --- /dev/null +++ b/src/proxy/ProxyHost.cpp @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "ProxyHost.h" + +ProxyHost::~ProxyHost() = default; diff --git a/src/proxy/ProxyHost.h b/src/proxy/ProxyHost.h new file mode 100644 index 000000000..e39d0dc12 --- /dev/null +++ b/src/proxy/ProxyHost.h @@ -0,0 +1,48 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "../global/ConfigEnums.h" +#include "../global/macros.h" + +#include +#include + +class HotkeyManager; + +// The callbacks Proxy/ConnectionListener need from their owning host, so +// they don't depend on the concrete type MainWindow. The host implements +// this alongside its own QObject base -- see mainwindow.h's `class +// MainWindow final : public QMainWindow, public ProxyHost`. +// ConnectionListener's parent must implement this interface (see proxy.cpp's +// getProxyHost()). +class NODISCARD ProxyHost +{ +public: + virtual ~ProxyHost(); + +public: + // Funnels Proxy/parser log messages ("mod", "message") into the host's + // log surface. + void log(const QString &mod, const QString &msg) { virt_log(mod, msg); } + + // The mud can request a mapper-mode switch via the MPI protocol (see + // ProxyMudConnectionApi::virt_onSetMode() in proxy.cpp); the host applies + // it the same way a user clicking the mapper-mode toolbar buttons would. + void setMode(const MapModeEnum mode) { virt_setMode(mode); } + + // The parser needs this to expand user-defined hotkey aliases. + NODISCARD HotkeyManager &getHotkeyManager() const { return virt_getHotkeyManager(); } + + // RemoteEdit needs a QObject parent to outlive the Proxy that spawned it + // (see Proxy::allocRemoteEdit()'s "Caution: RemoteEdit outlives the + // proxy" comment); this exposes the host's own QObject identity for that + // purpose. Implementations should just `return *this;`. + NODISCARD QObject &asQObject() { return virt_asQObject(); } + +private: + virtual void virt_log(const QString &mod, const QString &msg) = 0; + virtual void virt_setMode(MapModeEnum mode) = 0; + NODISCARD virtual HotkeyManager &virt_getHotkeyManager() const = 0; + NODISCARD virtual QObject &virt_asQObject() = 0; +}; diff --git a/src/proxy/proxy.cpp b/src/proxy/proxy.cpp index 0d269daaa..90ef5dfd4 100644 --- a/src/proxy/proxy.cpp +++ b/src/proxy/proxy.cpp @@ -18,7 +18,6 @@ #include "../global/Version.h" #include "../global/io.h" #include "../group/mmapper2group.h" -#include "../mainwindow/mainwindow.h" #include "../map/parseevent.h" #include "../mpi/mpifilter.h" #include "../mpi/remoteedit.h" @@ -58,14 +57,14 @@ const volatile bool g_showVersionInWelcomeMessage = IS_DEBUG_BUILD; // constexpr const auto whiteOnCyan = getRawAnsi(AnsiColor16Enum::white, AnsiColor16Enum::cyan); -NODISCARD MainWindow &getMainWindow(ConnectionListener &listener) +NODISCARD ProxyHost &getProxyHost(ConnectionListener &listener) { // dynamic cast can fail - auto *const mw = dynamic_cast(listener.parent()); - if (mw == nullptr) { - throw std::runtime_error("ConnectionListener's parent must be MainWindow"); + auto *const host = dynamic_cast(listener.parent()); + if (host == nullptr) { + throw std::runtime_error("ConnectionListener's parent must implement ProxyHost"); } - return *mw; + return *host; } } // namespace @@ -184,8 +183,7 @@ Proxy::Proxy(Badge, , m_timers(ct) , m_mapCanvas(mca) , m_gameObserver(go) - // REVISIT: It would be better to just pass in the MainWindow directly. - , m_mainWindow{::getMainWindow(listener)} + , m_host{::getProxyHost(listener)} , m_userSocket{std::move(userSocket)} { // @@ -319,7 +317,7 @@ void Proxy::allocMudSocket() NODISCARD RemoteEdit &getRemoteEdit() { return getProxy().getRemoteEdit(); } NODISCARD UserTelnet &getUserTelnet() { return getProxy().getUserTelnet(); } NODISCARD Mmapper2Group &getGroupManager() { return getProxy().getGroupManager(); } - NODISCARD MainWindow &getMainWindow() { return getProxy().getMainWindow(); } + NODISCARD ProxyHost &getHost() { return getProxy().getHost(); } NODISCARD GameObserver &getGameObserver() { return getProxy().getGameObserver(); } private: @@ -371,7 +369,7 @@ void Proxy::allocMudSocket() if ((false)) { getProxy().log(msg); } else { - getMainWindow().slot_log("Proxy", msg); + getHost().log("Proxy", msg); } } }; @@ -586,7 +584,7 @@ void Proxy::allocParser() NODISCARD MudTelnet &getMudTelnet() { return getProxy().getMudTelnet(); } NODISCARD UserTelnet &getUserTelnet() { return getProxy().getUserTelnet(); } NODISCARD GameObserver &getGameObserver() { return getProxy().getGameObserver(); } - NODISCARD MainWindow &getMainWindow() { return getProxy().getMainWindow(); } + NODISCARD ProxyHost &getHost() { return getProxy().getHost(); } NODISCARD MapCanvas &getMapCanvas() { return getProxy().getMapCanvas(); } NODISCARD Mmapper2PathMachine &getPathMachine() { return getProxy().getPathMachine(); } NODISCARD PrespammedPath &getPrespam() { return getProxy().getPrespam(); } @@ -714,17 +712,14 @@ void Proxy::allocParser() void virt_onShowPath(const CommandQueue &path) final { getPrespam().slot_setPath(path); } void virt_onMapChanged() final { getMapCanvas().slot_mapChanged(); } void virt_onGraphicsSettingsChanged() final { getMapCanvas().graphicsSettingsChanged(); } - void virt_onLog(const QString &mod, const QString &msg) final - { - getMainWindow().slot_log(mod, msg); - } + void virt_onLog(const QString &mod, const QString &msg) final { getHost().log(mod, msg); } void virt_onNewRoomSelection(const SigRoomSelection &sel) final { getMapCanvas().slot_setRoomSelection(sel); } // (via user command) - void virt_onSetMode(const MapModeEnum mode) final { getMainWindow().slot_setMode(mode); } + void virt_onSetMode(const MapModeEnum mode) final { getHost().setMode(mode); } }; auto &pipe = getPipeline(); @@ -743,7 +738,7 @@ void Proxy::allocParser() deref(gmcp), m_groupManager.getGroupManagerApi(), m_gameObserver, - m_mainWindow.getHotkeyManager(), + m_host.getHotkeyManager(), this, deref(out), deref(parserCommon)); @@ -752,7 +747,7 @@ void Proxy::allocParser() deref(conn), deref(gmcp), m_groupManager.getGroupManagerApi(), - m_mainWindow.getHotkeyManager(), + m_host.getHotkeyManager(), this, deref(out), deref(parserCommon), @@ -839,7 +834,7 @@ void Proxy::allocMpiFilter() void Proxy::allocRemoteEdit() { // Caution: RemoteEdit outlives the proxy, since it manages windows. - m_remoteEdit = mmqt::makeQPointer(&m_mainWindow); + m_remoteEdit = mmqt::makeQPointer(&m_host.asQObject()); struct NODISCARD LocalMpiFilterToMud final : public MpiFilterToMud { @@ -1199,7 +1194,7 @@ void Proxy::sendPromptToUser() void Proxy::log(const QString &msg) { - getMainWindow().slot_log("Proxy", msg); + getHost().log("Proxy", msg); } RemoteEdit &Proxy::getRemoteEdit() diff --git a/src/proxy/proxy.h b/src/proxy/proxy.h index 04e7295db..605febd6a 100644 --- a/src/proxy/proxy.h +++ b/src/proxy/proxy.h @@ -13,6 +13,7 @@ #include "../observer/gameobserver.h" #include "../parser/SendToUserSourceEnum.h" #include "GmcpMessage.h" +#include "ProxyHost.h" #include "ProxyParserApi.h" #include "TaggedBytes.h" @@ -30,7 +31,6 @@ class AbstractParser; class CTimers; class ConnectionListener; -class MainWindow; class MapCanvas; class MapData; class Mmapper2Group; @@ -77,7 +77,7 @@ class NODISCARD_QOBJECT Proxy final : public QObject CTimers &m_timers; MapCanvas &m_mapCanvas; GameObserver &m_gameObserver; - MainWindow &m_mainWindow; + ProxyHost &m_host; std::unique_ptr m_userSocket; private: @@ -286,7 +286,7 @@ class NODISCARD_QOBJECT Proxy final : public QObject NODISCARD Pipeline &getPipeline() { return deref(m_pipeline); } NODISCARD GameObserver &getGameObserver() { return m_gameObserver; } - NODISCARD MainWindow &getMainWindow() { return m_mainWindow; } + NODISCARD ProxyHost &getHost() { return m_host; } NODISCARD MapCanvas &getMapCanvas() { return m_mapCanvas; } NODISCARD Mmapper2Group &getGroupManager() { return m_groupManager; } NODISCARD MumeClock &getMumeClock() { return m_mumeClock; } diff --git a/src/roompanel/RoomModel.cpp b/src/roompanel/RoomModel.cpp new file mode 100644 index 000000000..de140be82 --- /dev/null +++ b/src/roompanel/RoomModel.cpp @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2021 The MMapper Authors +// Author: Massimiliano Ghilardi (Cosmos) +// Author: Nils Schimmelmann (Jahara) + +#include "RoomModel.h" + +#include "../global/Color.h" +#include "../global/Consts.h" +#include "RoomMobs.h" + +#include +#include + +namespace { // anonymous +const QVariant empty; +constexpr const uint8_t ROOM_COLUMN_COUNT = 7; +static_assert(ROOM_COLUMN_COUNT == static_cast(RoomModel::ColumnTypeEnum::MOUNT) + 1, + "# of columns"); +} // namespace + +// ---------------------------- RoomModel -------------------------------------- + +RoomModel::RoomModel(QObject *const parent, const RoomMobs &room) + : QAbstractTableModel{parent} + , m_room{room} +{} + +int RoomModel::rowCount(const QModelIndex & /* parent */) const +{ + return std::max(1, static_cast(m_mobVector.size())); +} + +int RoomModel::columnCount(const QModelIndex & /* parent */) const +{ + return ROOM_COLUMN_COUNT; +} + +QVariant RoomModel::headerData(int column, Qt::Orientation orientation, int role) const +{ + if (orientation == Qt::Orientation::Horizontal && role == Qt::DisplayRole) { + switch (static_cast(column)) { + case ColumnTypeEnum::NAME: + return "Name"; + case ColumnTypeEnum::LABEL: + return "Label"; + case ColumnTypeEnum::POSITION: + return "Position"; + case ColumnTypeEnum::EFFECTS: + return "Effects"; + case ColumnTypeEnum::WEAPON: + return "Weapon"; + case ColumnTypeEnum::FIGHTING: + return "Fighting"; + case ColumnTypeEnum::MOUNT: + return "Mount"; + default: + if (m_debug) { + qWarning() << "Unsupported column" << column; + } + break; + } + } + return QVariant(); +} + +Qt::ItemFlags RoomModel::flags(const QModelIndex &index) const +{ + return Qt::ItemFlag::ItemIsEnabled | Qt::ItemFlag::ItemIsSelectable + | QAbstractTableModel::flags(index); +} + +QVariant RoomModel::data(const QModelIndex &index, int role) const +{ + if (index.isValid()) { + const int row = index.row(); + const int column = index.column(); + + switch (role) { + case Qt::DisplayRole: + if (isFightingYOU(row, column)) { + // replace you -> YOU for better visibility + return QStringLiteral("YOU"); + } + return getMobField(row, column); + case Qt::BackgroundRole: + case RowBackgroundRole: + if (isEnemy(row, column)) { + // highlight enemy players + // REVISIT: Ideally, this could be configurable. + return QColor(Qt::yellow); + } + break; + case Qt::ForegroundRole: + case RowForegroundRole: + if (isFightingYOU(row, column)) { + // highlight "YOU" in fighting column + return QColor(Qt::red); + } else if (isEnemy(row, column)) { + // highlight enemy players + return mmqt::textColor(Qt::yellow); + } + break; + default: + break; + } + } + return empty; +} + +QHash RoomModel::roleNames() const +{ + QHash roles = QAbstractTableModel::roleNames(); + roles[Qt::DisplayRole] = "display"; + roles[RowBackgroundRole] = "rowBackground"; + roles[RowForegroundRole] = "rowForeground"; + return roles; +} + +SharedRoomMob RoomModel::getMob(const int row) const +{ + if (row >= 0 && static_cast(row) < m_mobVector.size()) { + return m_mobVector.at(static_cast(row)); + } + return nullptr; +} + +RoomMob::Field RoomModel::getField(const ColumnTypeEnum column) const +{ + switch (column) { + case ColumnTypeEnum::NAME: + return RoomMob::Field::NAME; + case ColumnTypeEnum::LABEL: + return RoomMob::Field::LABELS; + case ColumnTypeEnum::POSITION: + return RoomMob::Field::POSITION; + case ColumnTypeEnum::EFFECTS: + return RoomMob::Field::FLAGS; + case ColumnTypeEnum::WEAPON: + return RoomMob::Field::WEAPON; + case ColumnTypeEnum::FIGHTING: + return RoomMob::Field::FIGHTING; + case ColumnTypeEnum::MOUNT: + return RoomMob::Field::MOUNT; + } + abort(); +} + +const QVariant &RoomModel::getMobField(const int row, const int column) const +{ + SharedRoomMob mob = getMob(row); + if (!mob) { + return empty; + } + + const RoomMob::Field i = getField(static_cast(column)); + const QVariant &variant = mob->getField(i); + + // immediately return non-Id based fields + if (variant.typeId() != QMetaType::UInt) { + return variant; + } + + // field contains the ID of another mob: try to resolve it + const auto iter = m_mobsById.find(variant.toUInt()); + if (iter != m_mobsById.end()) { + const SharedRoomMob mob2 = iter->second; + if (mob2) { + return mob2->getField(RoomMob::Field::NAME); + } + } + if (m_debug) { + qDebug() << "mob id" << variant << "not found"; + } + // failed to resolve ID of another mob: + // clear the ID before MUME reuses it + mob->setField(i, empty); + return empty; +} + +bool RoomModel::isEnemy(const int row, const int column) const +{ + if (column < static_cast(ColumnTypeEnum::LABEL) + || column > static_cast(ColumnTypeEnum::WEAPON)) { + const auto &variant = getMobField(row, column); + if (variant == empty || variant.typeId() != QMetaType::QString) { + return false; + } + + // *an Orc* + // *a grim Man* + // *Foobar the Elf* + // etc. + const QString &str = variant.toString(); + return !str.isEmpty() && str.front() == mmqt::QC_ASTERISK; + } + return false; +} + +bool RoomModel::isFightingYOU(const int row, const int column) const +{ + if (column == static_cast(ColumnTypeEnum::FIGHTING)) { + const SharedRoomMob mob = getMob(row); + return mob && mob->getField(RoomMob::Field::FIGHTING).toString() == QStringLiteral("you"); + } + return false; +} + +void RoomModel::update() +{ + beginResetModel(); + m_room.updateModel(m_mobsById, m_mobVector); + endResetModel(); +} diff --git a/src/roompanel/RoomModel.h b/src/roompanel/RoomModel.h new file mode 100644 index 000000000..177764d2c --- /dev/null +++ b/src/roompanel/RoomModel.h @@ -0,0 +1,68 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2021 The MMapper Authors +// Author: Massimiliano Ghilardi (Cosmos) +// Author: Nils Schimmelmann (Jahara) + +#include "RoomMob.h" + +#include +#include +#include + +#include +#include +#include + +class RoomMobs; + +class NODISCARD_QOBJECT RoomModel final : public QAbstractTableModel +{ + Q_OBJECT + +public: + enum class NODISCARD ColumnTypeEnum : uint8_t { + NAME = 0, + LABEL, + POSITION, + EFFECTS, + WEAPON, + FIGHTING, + MOUNT, + }; + + // Custom roles, in addition to the standard + // Qt::DisplayRole/BackgroundRole/ForegroundRole consumed by the + // QTableView-based RoomWidget. + enum Role { + RowBackgroundRole = Qt::UserRole + 1, + RowForegroundRole, + }; + +private: + const RoomMobs &m_room; + std::unordered_map m_mobsById; + std::vector m_mobVector; + bool m_debug = false; + +public: + RoomModel(QObject *parent, const RoomMobs &room); + + NODISCARD int rowCount(const QModelIndex &parent) const override; + NODISCARD int columnCount(const QModelIndex &parent) const override; + + NODISCARD QVariant data(const QModelIndex &index, int role) const override; + NODISCARD QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + NODISCARD Qt::ItemFlags flags(const QModelIndex &parent) const override; + NODISCARD QHash roleNames() const override; + + void update(); + +private: + NODISCARD SharedRoomMob getMob(int row) const; + NODISCARD RoomMob::Field getField(ColumnTypeEnum column) const; + NODISCARD const QVariant &getMobField(int row, int column) const; + NODISCARD bool isEnemy(int row, int column) const; + NODISCARD bool isFightingYOU(int row, int column) const; + +}; // class RoomModel diff --git a/src/roompanel/RoomWidget.cpp b/src/roompanel/RoomWidget.cpp index a5b265441..853b685b9 100644 --- a/src/roompanel/RoomWidget.cpp +++ b/src/roompanel/RoomWidget.cpp @@ -16,196 +16,6 @@ #include #include -namespace { // anonymous -const QVariant empty; -constexpr const uint8_t ROOM_COLUMN_COUNT = 7; -static_assert(ROOM_COLUMN_COUNT == static_cast(RoomModel::ColumnTypeEnum::MOUNT) + 1, - "# of columns"); -} // namespace - -// ---------------------------- RoomModel -------------------------------------- - -RoomModel::RoomModel(QObject *const parent, const RoomMobs &room) - : QAbstractTableModel{parent} - , m_room{room} -{} - -int RoomModel::rowCount(const QModelIndex & /* parent */) const -{ - return std::max(1, static_cast(m_mobVector.size())); -} - -int RoomModel::columnCount(const QModelIndex & /* parent */) const -{ - return ROOM_COLUMN_COUNT; -} - -QVariant RoomModel::headerData(int column, Qt::Orientation orientation, int role) const -{ - if (orientation == Qt::Orientation::Horizontal && role == Qt::DisplayRole) { - switch (static_cast(column)) { - case ColumnTypeEnum::NAME: - return "Name"; - case ColumnTypeEnum::LABEL: - return "Label"; - case ColumnTypeEnum::POSITION: - return "Position"; - case ColumnTypeEnum::EFFECTS: - return "Effects"; - case ColumnTypeEnum::WEAPON: - return "Weapon"; - case ColumnTypeEnum::FIGHTING: - return "Fighting"; - case ColumnTypeEnum::MOUNT: - return "Mount"; - default: - if (m_debug) { - qWarning() << "Unsupported column" << column; - } - break; - } - } - return QVariant(); -} - -Qt::ItemFlags RoomModel::flags(const QModelIndex &index) const -{ - return Qt::ItemFlag::ItemIsEnabled | Qt::ItemFlag::ItemIsSelectable - | QAbstractTableModel::flags(index); -} - -QVariant RoomModel::data(const QModelIndex &index, int role) const -{ - if (index.isValid()) { - const int row = index.row(); - const int column = index.column(); - - switch (role) { - case Qt::DisplayRole: - if (isFightingYOU(row, column)) { - // replace you -> YOU for better visibility - return QStringLiteral("YOU"); - } - return getMobField(row, column); - case Qt::BackgroundRole: - if (isEnemy(row, column)) { - // highlight enemy players - // REVISIT: Ideally, this could be configurable. - return QColor(Qt::yellow); - } - break; - case Qt::ForegroundRole: - if (isFightingYOU(row, column)) { - // highlight "YOU" in fighting column - return QColor(Qt::red); - } else if (isEnemy(row, column)) { - // highlight enemy players - return mmqt::textColor(Qt::yellow); - } - break; - default: - break; - } - } - return empty; -} - -SharedRoomMob RoomModel::getMob(const int row) const -{ - if (row >= 0 && static_cast(row) < m_mobVector.size()) { - return m_mobVector.at(static_cast(row)); - } - return nullptr; -} - -RoomMob::Field RoomModel::getField(const ColumnTypeEnum column) const -{ - switch (column) { - case ColumnTypeEnum::NAME: - return RoomMob::Field::NAME; - case ColumnTypeEnum::LABEL: - return RoomMob::Field::LABELS; - case ColumnTypeEnum::POSITION: - return RoomMob::Field::POSITION; - case ColumnTypeEnum::EFFECTS: - return RoomMob::Field::FLAGS; - case ColumnTypeEnum::WEAPON: - return RoomMob::Field::WEAPON; - case ColumnTypeEnum::FIGHTING: - return RoomMob::Field::FIGHTING; - case ColumnTypeEnum::MOUNT: - return RoomMob::Field::MOUNT; - } - abort(); -} - -const QVariant &RoomModel::getMobField(const int row, const int column) const -{ - SharedRoomMob mob = getMob(row); - if (!mob) { - return empty; - } - - const RoomMob::Field i = getField(static_cast(column)); - const QVariant &variant = mob->getField(i); - - // immediately return non-Id based fields - if (variant.typeId() != QMetaType::UInt) { - return variant; - } - - // field contains the ID of another mob: try to resolve it - const auto iter = m_mobsById.find(variant.toUInt()); - if (iter != m_mobsById.end()) { - const SharedRoomMob mob2 = iter->second; - if (mob2) { - return mob2->getField(RoomMob::Field::NAME); - } - } - if (m_debug) { - qDebug() << "mob id" << variant << "not found"; - } - // failed to resolve ID of another mob: - // clear the ID before MUME reuses it - mob->setField(i, empty); - return empty; -} - -bool RoomModel::isEnemy(const int row, const int column) const -{ - if (column < static_cast(ColumnTypeEnum::LABEL) - || column > static_cast(ColumnTypeEnum::WEAPON)) { - const auto &variant = getMobField(row, column); - if (variant == empty || variant.typeId() != QMetaType::QString) { - return false; - } - - // *an Orc* - // *a grim Man* - // *Foobar the Elf* - // etc. - const QString &str = variant.toString(); - return !str.isEmpty() && str.front() == mmqt::QC_ASTERISK; - } - return false; -} - -bool RoomModel::isFightingYOU(const int row, const int column) const -{ - if (column == static_cast(ColumnTypeEnum::FIGHTING)) { - const SharedRoomMob mob = getMob(row); - return mob && mob->getField(RoomMob::Field::FIGHTING).toString() == QStringLiteral("you"); - } - return false; -} - -void RoomModel::update() -{ - beginResetModel(); - m_room.updateModel(m_mobsById, m_mobVector); - endResetModel(); -} - // ------------------------------- RoomWidget ---------------------------------- RoomWidget::RoomWidget(RoomManager &rm, QWidget *const parent) : QWidget{parent} diff --git a/src/roompanel/RoomWidget.h b/src/roompanel/RoomWidget.h index c101f31d7..641a11ee8 100644 --- a/src/roompanel/RoomWidget.h +++ b/src/roompanel/RoomWidget.h @@ -4,65 +4,16 @@ // Author: Massimiliano Ghilardi (Cosmos) // Author: Nils Schimmelmann (Jahara) -#include "RoomMob.h" +#include "RoomModel.h" -#include -#include -#include - -#include -#include #include #include #include class RoomManager; -class RoomMobs; class QObject; class QTableView; -class NODISCARD_QOBJECT RoomModel final : public QAbstractTableModel -{ - Q_OBJECT - -public: - enum class NODISCARD ColumnTypeEnum : uint8_t { - NAME = 0, - LABEL, - POSITION, - EFFECTS, - WEAPON, - FIGHTING, - MOUNT, - }; - -private: - const RoomMobs &m_room; - std::unordered_map m_mobsById; - std::vector m_mobVector; - bool m_debug = false; - -public: - RoomModel(QObject *parent, const RoomMobs &room); - - NODISCARD int rowCount(const QModelIndex &parent) const override; - NODISCARD int columnCount(const QModelIndex &parent) const override; - - NODISCARD QVariant data(const QModelIndex &index, int role) const override; - NODISCARD QVariant headerData(int section, Qt::Orientation orientation, int role) const override; - NODISCARD Qt::ItemFlags flags(const QModelIndex &parent) const override; - - void update(); - -private: - NODISCARD SharedRoomMob getMob(int row) const; - NODISCARD RoomMob::Field getField(ColumnTypeEnum column) const; - NODISCARD const QVariant &getMobField(int row, int column) const; - NODISCARD bool isEnemy(int row, int column) const; - NODISCARD bool isFightingYOU(int row, int column) const; - -}; // class RoomModel - class NODISCARD_QOBJECT RoomWidget final : public QWidget { Q_OBJECT diff --git a/src/timers/TimerModel.cpp b/src/timers/TimerModel.cpp index a309a2621..d734b7836 100644 --- a/src/timers/TimerModel.cpp +++ b/src/timers/TimerModel.cpp @@ -45,9 +45,17 @@ TimerModel::TimerModel(CTimers &timers, QObject *parent) connect(&m_refreshTimer, &QTimer::timeout, this, [this]() { if (m_allTimers.empty()) return; + // An empty roles vector means "all roles changed". This must stay + // empty rather than {Qt::DisplayRole, ProgressRole}: consumers that + // bind to the custom TimeRole/NameRole/ExpiredRole (see roleNames() + // below) rather than Qt::DisplayRole would otherwise see those + // bindings never re-evaluate, freezing the on-screen time. The + // widget-based TimerWidget/TimerDelegate repaint on every + // dataChanged() regardless of the roles list, so that path is + // unaffected either way. emit dataChanged(index(0, ColName), index(static_cast(m_allTimers.size()) - 1, ColCount - 1), - {Qt::DisplayRole, ProgressRole}); + {}); startRefreshTimer(); }); @@ -77,6 +85,17 @@ QVariant TimerModel::data(const QModelIndex &index, int role) const const TTimer *timer = m_allTimers[static_cast(index.row())]; + // Custom roles are read from column 0, so they are handled independently + // of index.column() by delegating to the same per-column formatting + // logic used by Qt::DisplayRole. + if (role == NameRole) { + return data(this->index(index.row(), ColName), Qt::DisplayRole); + } else if (role == TimeRole) { + return data(this->index(index.row(), ColTime), Qt::DisplayRole); + } else if (role == ExpiredRole) { + return timer->isExpired(); + } + if (role == Qt::DisplayRole || role == Qt::ToolTipRole) { switch (index.column()) { case ColName: { @@ -112,6 +131,16 @@ QVariant TimerModel::data(const QModelIndex &index, int role) const return QVariant(); } +QHash TimerModel::roleNames() const +{ + QHash roles = QAbstractTableModel::roleNames(); + roles[NameRole] = "name"; + roles[TimeRole] = "time"; + roles[ProgressRole] = "progress"; + roles[ExpiredRole] = "expired"; + return roles; +} + QVariant TimerModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { @@ -183,6 +212,24 @@ bool TimerModel::dropMimeData( return true; } +void TimerModel::moveRow(int from, int to) +{ + // Mirrors dropMimeData()'s validation and reorder call exactly, since + // this is the same "move row `from` so it lands at position `to`" + // operation, reached programmatically instead of through a + // QAbstractItemView's drag-and-drop. CTimers::moveTimer() emits + // sig_timersUpdated(), which updateTimerList() is already connected to, + // so the model resets and views pick up the new order. + if (from < 0 || static_cast(from) >= m_allTimers.size()) + return; + if (to < 0 || to > static_cast(m_allTimers.size())) + return; + if (from == to || from == to - 1) + return; + + m_timers.moveTimer(from, to); +} + const TTimer *TimerModel::timerAt(int row) const { if (row < 0 || static_cast(row) >= m_allTimers.size()) diff --git a/src/timers/TimerModel.h b/src/timers/TimerModel.h index b3c9a93b7..3733412c6 100644 --- a/src/timers/TimerModel.h +++ b/src/timers/TimerModel.h @@ -25,7 +25,7 @@ class NODISCARD_QOBJECT TimerModel final : public QAbstractTableModel public: enum Column { ColName = 0, ColTime, ColCount }; - enum Role { ProgressRole = Qt::UserRole + 1 }; + enum Role { ProgressRole = Qt::UserRole + 1, NameRole, TimeRole, ExpiredRole }; public: explicit TimerModel(CTimers &timers, QObject *parent = nullptr); @@ -36,6 +36,7 @@ class NODISCARD_QOBJECT TimerModel final : public QAbstractTableModel NODISCARD QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + NODISCARD QHash roleNames() const override; NODISCARD Qt::ItemFlags flags(const QModelIndex &index) const override; NODISCARD Qt::DropActions supportedDropActions() const override; @@ -49,6 +50,12 @@ class NODISCARD_QOBJECT TimerModel final : public QAbstractTableModel NODISCARD const TTimer *timerAt(int row) const; + // Reorders the underlying CTimers storage and emits the matching + // beginMoveRows()/endMoveRows() pair so a view can animate the move + // instead of resetting the whole list. Mirrors the sequence + // dropMimeData() uses for drag-and-drop from a QAbstractItemView. + void moveRow(int from, int to); + private slots: void updateTimerList(); diff --git a/src/viewers/AnsiViewWindow.cpp b/src/viewers/AnsiViewWindow.cpp index a0d99c258..ddd7ba4b0 100644 --- a/src/viewers/AnsiViewWindow.cpp +++ b/src/viewers/AnsiViewWindow.cpp @@ -53,9 +53,9 @@ AnsiViewWindow::AnsiViewWindow(const QString &program, AnsiViewWindow::~AnsiViewWindow() = default; -std::unique_ptr makeAnsiViewWindow(const QString &program, - const QString &title, - std::string_view body) +std::unique_ptr makeAnsiViewWindow(const QString &program, + const QString &title, + std::string_view body) { return std::make_unique(program, title, body); } diff --git a/src/viewers/AnsiViewWindow.h b/src/viewers/AnsiViewWindow.h index 1729eaebd..0d35a4082 100644 --- a/src/viewers/AnsiViewWindow.h +++ b/src/viewers/AnsiViewWindow.h @@ -25,6 +25,11 @@ class NODISCARD AnsiViewWindow final : public QDialog // Yes, this interface is a bit silly to mix Qt and std types, // but the program/title are for the UI, // while the body is interpreted to format text into a document. -NODISCARD std::unique_ptr makeAnsiViewWindow(const QString &program, - const QString &title, - std::string_view body); +// +// Returns a QDialog rather than a concrete AnsiViewWindow so callers (see +// mpi/remoteeditwidget.h's m_preview and viewers/LaunchAsyncViewer.h) never +// need AnsiViewWindow to be a complete type; the object returned is always +// an AnsiViewWindow, which is-a QDialog. +NODISCARD std::unique_ptr makeAnsiViewWindow(const QString &program, + const QString &title, + std::string_view body); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d5ad5a7b3..a69ed3e8c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -49,6 +49,8 @@ target_link_libraries(mm_test # Clock set(clock_SRCS + ../src/clock/ClockStrings.cpp + ../src/clock/ClockStrings.h ../src/clock/mumeclock.cpp ../src/clock/mumeclock.h ../src/clock/mumemoment.cpp @@ -143,23 +145,33 @@ set_target_properties( ) add_test(NAME TestProxy COMMAND TestProxy) +# MapScroller is a plain, rendering-independent QObject (see +# ../src/display/MapScroller.h's file comment: deliberately has no +# dependency on MapCanvas/OpenGL), so it's linked directly into +# TestMainWindow below for mapScrollerScrollMath(). +set(map_scroller_SRCS + ../src/display/MapScroller.cpp + ../src/display/MapScroller.h +) # MainWindow set(mainwindow_SRCS ../src/global/Version.h ../src/mainwindow/AudioVolumeSlider.cpp ../src/mainwindow/AudioVolumeSlider.h - ../src/mainwindow/UpdateDialog.cpp - ../src/mainwindow/UpdateDialog.h + ../src/mainwindow/UpdateChecker.cpp + ../src/mainwindow/UpdateChecker.h ) set(TestMainWindow_SRCS TestMainWindow.cpp) -add_executable(TestMainWindow ${TestMainWindow_SRCS} ${mainwindow_SRCS}) -add_dependencies(TestMainWindow mm_test mm_global) +add_executable(TestMainWindow ${TestMainWindow_SRCS} ${mainwindow_SRCS} ${map_scroller_SRCS}) +add_dependencies(TestMainWindow mm_test mm_global mm_map) target_link_libraries(TestMainWindow + mm_map mm_test mm_global Qt6::Network Qt6::Test Qt6::Widgets + Qt6::OpenGL coverage_config) set_target_properties( TestMainWindow PROPERTIES @@ -190,11 +202,17 @@ set_target_properties( add_test(NAME TestGlobal COMMAND TestGlobal) # Group -set(TestGroup_SRCS +set(group_SRCS + ../src/group/CGroupChar.cpp + ../src/group/CGroupChar.h + ../src/group/GroupModel.cpp + ../src/group/GroupModel.h ../src/group/enums.cpp ../src/group/enums.h - TestGroup.cpp + ../src/group/mmapper2character.cpp + ../src/group/mmapper2character.h ) +set(TestGroup_SRCS ${group_SRCS} TestGroup.cpp) add_executable(TestGroup ${TestGroup_SRCS}) add_dependencies(TestGroup mm_test mm_global mm_map) target_link_libraries(TestGroup @@ -241,6 +259,8 @@ add_test(NAME TestMap COMMAND TestMap) # Adventure set(adventure_SRCS + ../src/adventure/AdventureLogModel.cpp + ../src/adventure/AdventureLogModel.h ../src/adventure/adventuresession.cpp ../src/adventure/adventuresession.h ../src/adventure/adventuretracker.cpp @@ -328,6 +348,8 @@ set(room_manager ../src/roompanel/RoomMob.cpp ../src/roompanel/RoomManager.cpp ../src/roompanel/RoomManager.h + ../src/roompanel/RoomModel.cpp + ../src/roompanel/RoomModel.h ) set(RoomManager roompanel/TestRoomManager.cpp) add_executable(TestRoomManager ${room_manager} ${RoomManager}) @@ -361,3 +383,42 @@ set_target_properties( COMPILE_FLAGS "${WARNING_FLAGS}" ) add_test(NAME TestHotkeyManager COMMAND TestHotkeyManager) + +# Media +set(description_panel_SRCS + ../src/media/StackBlur.cpp + ../src/media/StackBlur.h +) +set(TestMedia_SRCS TestMedia.cpp TestMedia.h) +add_executable(TestMedia ${TestMedia_SRCS} ${description_panel_SRCS}) +add_dependencies(TestMedia mm_test mm_global) +target_link_libraries(TestMedia mm_test mm_global Qt6::Gui Qt6::Test coverage_config) +set_target_properties( + TestMedia PROPERTIES + CXX_STANDARD 20 + CXX_STANDARD_REQUIRED ON + CXX_EXTENSIONS OFF + COMPILE_FLAGS "${WARNING_FLAGS}" +) +add_test(NAME TestMedia COMMAND TestMedia) + +# Client +set(TestClient_SRCS + TestClient.cpp + TestClient.h + ../src/client/InputHistory.cpp + ../src/client/InputHistory.h + ../src/mpi/RemoteEditDocumentOps.cpp + ../src/mpi/RemoteEditDocumentOps.h +) +add_executable(TestClient ${TestClient_SRCS}) +add_dependencies(TestClient mm_test mm_global) +target_link_libraries(TestClient mm_test mm_global Qt6::Gui Qt6::Test coverage_config) +set_target_properties( + TestClient PROPERTIES + CXX_STANDARD 20 + CXX_STANDARD_REQUIRED ON + CXX_EXTENSIONS OFF + COMPILE_FLAGS "${WARNING_FLAGS}" +) +add_test(NAME TestClient COMMAND TestClient) diff --git a/tests/TestCTimers.cpp b/tests/TestCTimers.cpp index b3e34c4fe..8e97bc577 100644 --- a/tests/TestCTimers.cpp +++ b/tests/TestCTimers.cpp @@ -263,4 +263,75 @@ void TestCTimers::testMoveTimer() QCOMPARE(QString::fromStdString(it->getName()), QString("T3")); } +void TestCTimers::testModelRoleNames() +{ + CTimers timers(nullptr); + TimerModel model(timers, nullptr); + + QHash roles = model.roleNames(); + QVERIFY(roles.values().contains("name")); + QVERIFY(roles.values().contains("time")); + QVERIFY(roles.values().contains("progress")); + QVERIFY(roles.values().contains("expired")); + + QCOMPARE(roles[TimerModel::NameRole], QByteArray("name")); + QCOMPARE(roles[TimerModel::TimeRole], QByteArray("time")); + QCOMPARE(roles[TimerModel::ProgressRole], QByteArray("progress")); + QCOMPARE(roles[TimerModel::ExpiredRole], QByteArray("expired")); +} + +void TestCTimers::testModelCustomRoleData() +{ + CTimers timers(nullptr); + TimerModel model(timers, nullptr); + + timers.addTimer("T1", "D1"); + + QModelIndex idx = model.index(0, 0); + + QVariant nameVal = model.data(idx, TimerModel::NameRole); + QVERIFY(nameVal.isValid()); + QCOMPARE(nameVal.toString(), QString("T1 ")); + + QVariant timeVal = model.data(idx, TimerModel::TimeRole); + QVERIFY(timeVal.isValid()); + QVERIFY(!timeVal.toString().isEmpty()); + + QVariant expiredVal = model.data(idx, TimerModel::ExpiredRole); + QVERIFY(expiredVal.isValid()); + QCOMPARE(expiredVal.toBool(), false); +} + +void TestCTimers::timerModelTickUpdatesAllRoles() +{ + // Regression test: consumers bind to the custom TimeRole/NameRole/ExpiredRole + // (see TimerModel::roleNames()), not Qt::DisplayRole, so TimerModel's periodic + // refresh lambda must emit dataChanged() with an *empty* roles vector (meaning + // "all roles changed"); a non-empty {Qt::DisplayRole, ProgressRole} list would + // leave those bindings stale, making a running count-up timer's on-screen time + // look frozen even though the underlying data keeps updating. + CTimers timers(nullptr); + timers.addTimer("count-up", ""); + + TimerModel model(timers, nullptr); + const QModelIndex idx = model.index(0, TimerModel::ColTime); + + QSignalSpy spy(&model, &TimerModel::dataChanged); + const QVariant before = model.data(idx, TimerModel::TimeRole); + + // The refresh timer fires every 50ms; wait for at least one tick. + QTRY_VERIFY_WITH_TIMEOUT(!spy.isEmpty(), 2000); + + const QList lastSignal = spy.constLast(); + const auto roles = lastSignal.at(2).value>(); + QVERIFY2(roles.isEmpty(), + "dataChanged() must report an empty roles list (\"all roles changed\") so " + "custom-role bindings (time/name/expired) re-evaluate"); + + // formatMs() only has second granularity, so give it long enough for + // the displayed elapsed time to actually roll over and confirm the + // underlying data really is live, not just the signal shape. + QTRY_VERIFY_WITH_TIMEOUT(model.data(idx, TimerModel::TimeRole) != before, 2000); +} + QTEST_MAIN(TestCTimers) diff --git a/tests/TestCTimers.h b/tests/TestCTimers.h index c7e2455b8..8d3ef231d 100644 --- a/tests/TestCTimers.h +++ b/tests/TestCTimers.h @@ -30,4 +30,7 @@ private Q_SLOTS: void testModelDataRetrieval(); void testModelUpdates(); void testMoveTimer(); + void testModelRoleNames(); + void testModelCustomRoleData(); + void timerModelTickUpdatesAllRoles(); }; diff --git a/tests/TestClient.cpp b/tests/TestClient.cpp new file mode 100644 index 000000000..ad8251608 --- /dev/null +++ b/tests/TestClient.cpp @@ -0,0 +1,372 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "TestClient.h" + +#include "../src/client/InputHistory.h" +#include "../src/configuration/configuration.h" +#include "../src/mpi/RemoteEditDocumentOps.h" + +#include +#include +#include + +TestClient::TestClient() +{ + setEnteredMain(); +} + +TestClient::~TestClient() = default; + +namespace { // anonymous + +// Local replicas of InputWidget::forwardHistory()/backwardHistory() (see +// inputwidget.cpp), operating directly on an InputHistory instance instead +// of a QPlainTextEdit, so the iterator dance (including its boundary +// asymmetry) can be pinned without constructing a QWidget. +struct NODISCARD HistoryNav final +{ + InputHistory &history; + QString text; + bool boundaryHit = false; + QString boundaryMessage; + + explicit HistoryNav(InputHistory &history_) + : history(history_) + {} + + // Mirrors InputWidget::backwardHistory() (Up key). + void up() + { + boundaryHit = false; + if (history.atEnd()) { + boundaryHit = true; + boundaryMessage = "Reached end of input history"; + return; + } + text = history.value(); + if (!history.atEnd()) { + history.forward(); + } + } + + // Mirrors InputWidget::forwardHistory() (Down key). + void down() + { + boundaryHit = false; + text.clear(); + if (history.atFront()) { + boundaryHit = true; + boundaryMessage = "Reached beginning of input history"; + return; + } + if (history.atEnd()) { + history.backward(); + } + if (!history.atFront()) { + history.backward(); + text = history.value(); + } + } +}; + +} // namespace + +void TestClient::inputHistoryDedupVsBackOnly() +{ + // InputHistory::addInputLine() only dedups against back() (the OLDEST + // entry, since push_front() is used to add the newest), not against the + // most-recently-added entry. This is a deliberate pin of that quirk. + InputHistory history; + history.addInputLine("a"); + history.addInputLine("a"); // back() == "a" -> not added again + HistoryNav nav(history); + nav.up(); + QCOMPARE(nav.text, QStringLiteral("a")); + nav.up(); + QVERIFY(nav.boundaryHit); // only one entry total + + InputHistory history2; + history2.addInputLine("a"); + history2.addInputLine("b"); + // Exercises adding "a" again: back() ("a", the oldest entry) equals the + // new string, so it does NOT get re-added. + history2.addInputLine("a"); + HistoryNav nav2(history2); + nav2.up(); + QCOMPARE(nav2.text, QStringLiteral("b")); + nav2.up(); + QCOMPARE(nav2.text, QStringLiteral("a")); + nav2.up(); + QVERIFY(nav2.boundaryHit); // only two entries total: [b, a] +} + +void TestClient::inputHistoryEmptyLineSkipped() +{ + InputHistory history; + history.addInputLine(QString()); + HistoryNav nav(history); + nav.up(); + QVERIFY(nav.boundaryHit); +} + +void TestClient::inputHistoryCap() +{ + const int savedLimit = getConfig().integratedClient.linesOfInputHistory; + setConfig().integratedClient.linesOfInputHistory = 2; + + InputHistory history; + history.addInputLine("one"); + history.addInputLine("two"); + history.addInputLine("three"); + + HistoryNav nav(history); + nav.up(); + QCOMPARE(nav.text, QStringLiteral("three")); + nav.up(); + QCOMPARE(nav.text, QStringLiteral("two")); + nav.up(); + QVERIFY(nav.boundaryHit); // "one" was trimmed by the cap + + setConfig().integratedClient.linesOfInputHistory = savedLimit; +} + +void TestClient::inputHistoryNavigation() +{ + const int savedLimit = getConfig().integratedClient.linesOfInputHistory; + setConfig().integratedClient.linesOfInputHistory = 100; + + InputHistory history; + history.addInputLine("cmd1"); + history.addInputLine("cmd2"); + history.addInputLine("cmd3"); + + HistoryNav nav(history); + nav.up(); + QCOMPARE(nav.text, QStringLiteral("cmd3")); + nav.up(); + QCOMPARE(nav.text, QStringLiteral("cmd2")); + nav.up(); + QCOMPARE(nav.text, QStringLiteral("cmd1")); + nav.up(); + QVERIFY(nav.boundaryHit); + QCOMPARE(nav.boundaryMessage, QStringLiteral("Reached end of input history")); + // Text is left untouched (still the last retrieved value) on this boundary. + QCOMPARE(nav.text, QStringLiteral("cmd1")); + + // Pin the down-navigation asymmetry: the first Down after running off + // the end skips over "cmd1" (the value last shown by up()) and lands on + // "cmd2" instead. + nav.down(); + QVERIFY(!nav.boundaryHit); + QCOMPARE(nav.text, QStringLiteral("cmd2")); + nav.down(); + QCOMPARE(nav.text, QStringLiteral("cmd3")); + nav.down(); + QVERIFY(nav.boundaryHit); + QCOMPARE(nav.boundaryMessage, QStringLiteral("Reached beginning of input history")); + // Text is cleared on this boundary. + QCOMPARE(nav.text, QString()); + + setConfig().integratedClient.linesOfInputHistory = savedLimit; +} + +void TestClient::tabHistoryWordExtraction() +{ + const int savedCap = getConfig().integratedClient.tabCompletionDictionarySize; + setConfig().integratedClient.tabCompletionDictionarySize = 100; + + TabHistory history; + // MIN_WORD_LENGTH is 3, and the extraction requires length > 3, so only + // words of 4+ characters are kept ("cat" and "at" are dropped, "look" + // and "kill" are kept). Newest word is pushed to the front, so the + // dictionary order is [kill, look]. + history.addInputLine("look at cat and kill"); + + // "kill" is returned normally; "look" is the last (oldest) dictionary + // entry, so finding it reverts to nullopt per nextMatch()'s wraparound + // contract (see InputHistory.h), and the iterator resets. + QCOMPARE(history.nextMatch(""), std::make_optional(QStringLiteral("kill"))); + QCOMPARE(history.nextMatch(""), std::optional{}); + QCOMPARE(history.nextMatch(""), std::make_optional(QStringLiteral("kill"))); + + setConfig().integratedClient.tabCompletionDictionarySize = savedCap; +} + +void TestClient::tabHistoryCap() +{ + const int savedCap = getConfig().integratedClient.tabCompletionDictionarySize; + setConfig().integratedClient.tabCompletionDictionarySize = 2; + + TabHistory history; + history.addInputLine("alpha"); + history.addInputLine("bravo"); + history.addInputLine("gamma"); + + // Only the two most-recently-added words survive the cap: [gamma, bravo]. + // "bravo" is the last (oldest) entry, so per nextMatch()'s wraparound + // contract it reverts to nullopt instead of being returned directly. + QCOMPARE(history.nextMatch(""), std::make_optional(QStringLiteral("gamma"))); + QCOMPARE(history.nextMatch(""), std::optional{}); + + setConfig().integratedClient.tabCompletionDictionarySize = savedCap; +} + +void TestClient::tabHistoryNextMatchCycling() +{ + const int savedCap = getConfig().integratedClient.tabCompletionDictionarySize; + setConfig().integratedClient.tabCompletionDictionarySize = 100; + + TabHistory history; + history.addInputLine("apple avocado banana apricot"); + // Dictionary (newest first): apricot, banana, avocado, apple. Only + // "apricot" and "apple" start with "ap" ("avocado" starts with "av"). + + QCOMPARE(history.nextMatch("ap"), std::make_optional(QStringLiteral("apricot"))); + // "apple" is the next match, but it is also the last overall dictionary + // entry: per TabHistory::nextMatch()'s documented wraparound contract, + // finding a match on the final entry reverts to nullopt (mirroring + // InputWidget::tabComplete()'s apply-then-immediately-revert quirk for + // that case) and resets the iterator, skipping over "banana" and + // "avocado" along the way without returning them (they don't match). + QCOMPARE(history.nextMatch("ap"), std::optional{}); + // The iterator was reset, so the cycle restarts from the newest entry. + QCOMPARE(history.nextMatch("ap"), std::make_optional(QStringLiteral("apricot"))); + + // No match at all also yields nullopt and resets. + QCOMPARE(history.nextMatch("zzz"), std::optional{}); + QCOMPARE(history.nextMatch("ap"), std::make_optional(QStringLiteral("apricot"))); + + setConfig().integratedClient.tabCompletionDictionarySize = savedCap; +} + +// --- RemoteEditDocumentOps --- +// Widget-free core of the MPI remote editor's text operations; exercised directly +// against a QTextDocument (no RemoteEditWidget/QPlainTextEdit involved). + +void TestClient::remoteEditJustifyTextRewrapsLongLines() +{ + const QString input = QStringLiteral("one two three four five six seven eight nine ten\n"); + const QString result = mmqt::remoteEditJustifyText(input, 20); + + const QStringList lines = result.split(QChar('\n'), Qt::SkipEmptyParts); + QVERIFY(lines.size() > 1); + for (const QString &line : lines) { + QVERIFY2(line.length() <= 20, qPrintable(line)); + } + // All the original words must still be present, just rewrapped. + for (const char *word : + {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}) { + QVERIFY(result.contains(QString::fromLatin1(word))); + } +} + +void TestClient::remoteEditExpandTabsExpandsSelection() +{ + QTextDocument doc; + doc.setPlainText(QStringLiteral("a\tb")); + + QTextCursor cur(&doc); + cur.select(QTextCursor::Document); + mmqt::remoteEditExpandTabs(cur); + + const QString text = doc.toPlainText(); + QVERIFY(!text.contains(QChar('\t'))); + // Tab stops are every 8 columns, so "a" (1 col) + tab expands to 7 spaces. + QCOMPARE(text, QStringLiteral("a") + QString(7, QChar(' ')) + QStringLiteral("b")); +} + +void TestClient::remoteEditRemoveDuplicateSpacesCollapses() +{ + QTextDocument doc; + doc.setPlainText(QStringLiteral("a b c")); + + QTextCursor cur(&doc); + cur.select(QTextCursor::Document); + mmqt::remoteEditRemoveDuplicateSpaces(cur); + + QCOMPARE(doc.toPlainText(), QStringLiteral("a b c")); +} + +void TestClient::remoteEditJoinLinesCombinesBlocks() +{ + QTextDocument doc; + doc.setPlainText(QStringLiteral("line one\nline two")); + + // Only the first (and only non-final) block is selected; joinLines' "join the next + // line if only one line is selected" feature should pull in the final block too. + QTextCursor cur(&doc); + cur.movePosition(QTextCursor::Start); + cur.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); + mmqt::remoteEditJoinLines(cur); + + QCOMPARE(doc.toPlainText(), QStringLiteral("line one line two")); +} + +void TestClient::remoteEditPrefixPartialSelectionQuotesLines() +{ + QTextDocument doc; + doc.setPlainText(QStringLiteral("abc\ndef")); + + QTextCursor cur(&doc); + cur.select(QTextCursor::Document); + mmqt::remoteEditPrefixPartialSelection(cur, QStringLiteral("> ")); + + QCOMPARE(doc.toPlainText(), QStringLiteral("> abc\n> def")); +} + +void TestClient::remoteEditFindWrapsAround() +{ + QTextDocument doc; + doc.setPlainText(QStringLiteral("foo bar foo")); + + // Position the cursor after the last "foo", so a forward search must wrap around + // to find the first occurrence. + QTextCursor cur(&doc); + cur.movePosition(QTextCursor::End); + + const auto outcome = mmqt::remoteEditFind(doc, cur, QStringLiteral("foo"), {}); + QCOMPARE(outcome.result, mmqt::RemoteEditFindResultEnum::FOUND_AFTER_WRAP); + QCOMPARE(outcome.cursor.selectedText(), QStringLiteral("foo")); + QCOMPARE(outcome.cursor.selectionStart(), 0); + + // Searching for something absent must report NOT_FOUND and leave the returned + // cursor equal to the one that was passed in. + const auto missing = mmqt::remoteEditFind(doc, cur, QStringLiteral("nope"), {}); + QCOMPARE(missing.result, mmqt::RemoteEditFindResultEnum::NOT_FOUND); +} + +void TestClient::remoteEditReplaceAllReplacesEveryOccurrence() +{ + QTextDocument doc; + doc.setPlainText(QStringLiteral("foo bar foo baz foo")); + + const int replacements = mmqt::remoteEditReplaceAll(doc, + QStringLiteral("foo"), + QStringLiteral("qux"), + {}); + QCOMPARE(replacements, 3); + QCOMPARE(doc.toPlainText(), QStringLiteral("qux bar qux baz qux")); +} + +void TestClient::remoteEditStatusReportsTabsLongLinesAndTrailingSpace() +{ + QTextDocument doc; + const QString longLine(85, QChar('x')); + doc.setPlainText(QStringLiteral("a\tb\n") + longLine + QStringLiteral("\ntrailing \n")); + + QTextCursor cur(&doc); + cur.movePosition(QTextCursor::Start); + const auto info = mmqt::computeRemoteEditStatus(cur); + + QCOMPARE(info.line, 1); + QCOMPARE(info.col, 1); + QVERIFY(!info.selection); + QVERIFY(info.hasTabs); + QVERIFY(info.hasLongLines); + QVERIFY(info.hasTrailingSpace); +} + +QTEST_MAIN(TestClient) + +#include "TestClient.moc" diff --git a/tests/TestClient.h b/tests/TestClient.h new file mode 100644 index 000000000..047b4d318 --- /dev/null +++ b/tests/TestClient.h @@ -0,0 +1,38 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "../src/global/macros.h" + +#include + +class NODISCARD_QOBJECT TestClient final : public QObject +{ + Q_OBJECT + +public: + TestClient(); + ~TestClient() final; + +private Q_SLOTS: + // InputHistory + void inputHistoryDedupVsBackOnly(); + void inputHistoryEmptyLineSkipped(); + void inputHistoryCap(); + void inputHistoryNavigation(); + + // TabHistory + void tabHistoryWordExtraction(); + void tabHistoryCap(); + void tabHistoryNextMatchCycling(); + + // RemoteEditDocumentOps (widget-free core of the MPI remote editor) + void remoteEditJustifyTextRewrapsLongLines(); + void remoteEditExpandTabsExpandsSelection(); + void remoteEditRemoveDuplicateSpacesCollapses(); + void remoteEditJoinLinesCombinesBlocks(); + void remoteEditPrefixPartialSelectionQuotesLines(); + void remoteEditFindWrapsAround(); + void remoteEditReplaceAllReplacesEveryOccurrence(); + void remoteEditStatusReportsTabsLongLinesAndTrailingSpace(); +}; diff --git a/tests/TestGroup.cpp b/tests/TestGroup.cpp index 08073b5f9..8a7bf20fa 100644 --- a/tests/TestGroup.cpp +++ b/tests/TestGroup.cpp @@ -3,12 +3,20 @@ #include "TestGroup.h" +#include "../src/configuration/configuration.h" +#include "../src/group/CGroupChar.h" +#include "../src/group/GroupModel.h" #include "../src/group/enums.h" #include #include -TestGroup::TestGroup() = default; +TestGroup::TestGroup() +{ + // GroupModel::insertCharacter()/setCharacters() read getConfig(), which + // asserts that setEnteredMain() has run first (see configuration.cpp). + setEnteredMain(); +} TestGroup::~TestGroup() = default; void TestGroup::enumsTest() @@ -16,4 +24,104 @@ void TestGroup::enumsTest() test::test_group_enums(); } +void TestGroup::roleNamesTest() +{ + GroupModel model; + // rowCount()/data()/roleNames() are protected on GroupModel (only Qt's view + // internals call them, via a QAbstractItemModel* the same way GroupWidget's + // QTableView does); reach them through the public base-class interface. + QAbstractItemModel &base = model; + const QHash roles = base.roleNames(); + const QList names = roles.values(); + + for (const char *expected : {"name", + "charColor", + "textColor", + "hpText", + "manaText", + "movesText", + "hpRatio", + "manaRatio", + "movesRatio", + "hpLow", + "movesLow", + "manaHidden", + "stateIcons", + "stateTip", + "roomName", + "isYou", + "isNpc", + "canCenter"}) { + QVERIFY2(names.contains(QByteArray(expected)), expected); + } +} + +void TestGroup::characterRoleDataTest() +{ + GroupModel model; + QAbstractItemModel &base = model; + + SharedGroupChar character = CGroupChar::alloc(); + character->setId(GroupId{1}); + character->setColor(QColor(Qt::black)); + character->setPosition(CharacterPositionEnum::STANDING); + character->setScore(/*hp=*/20, + /*maxhp=*/100, + /*mana=*/0, + /*maxmana=*/0, + /*moves=*/10, + /*maxmoves=*/100); + + model.insertCharacter(character); + QCOMPARE(base.rowCount(QModelIndex()), 1); + + const QModelIndex idx = base.index(0, 0); + QVERIFY(idx.isValid()); + + QCOMPARE(base.data(idx, GroupModel::HpRatioRole).toDouble(), 0.20); + QVERIFY(base.data(idx, GroupModel::HpLowRole).toBool()); + QVERIFY(base.data(idx, GroupModel::MovesLowRole).toBool()); + QVERIFY(base.data(idx, GroupModel::ManaHiddenRole).toBool()); + QCOMPARE(base.data(idx, GroupModel::ManaTextRole).toString(), QStringLiteral("--")); + QVERIFY(!base.data(idx, GroupModel::HpTextRole).toString().isEmpty()); + QVERIFY(!base.data(idx, GroupModel::StateIconsRole).toStringList().isEmpty()); + + // anyMana stays false since the only character has no mana pool. + QVERIFY(!model.getAnyMana()); + + // A character with unknown maxima (max <= 0) must not report low stats, + // matching GroupDelegate's pulse decision for unknown state. + SharedGroupChar unknown = CGroupChar::alloc(); + unknown->setId(GroupId{2}); + unknown->setColor(QColor(Qt::white)); + unknown->setScore(/*hp=*/0, /*maxhp=*/0, /*mana=*/0, /*maxmana=*/0, /*moves=*/0, /*maxmoves=*/0); + model.insertCharacter(unknown); + const QModelIndex idx2 = base.index(1, 0); + QVERIFY(!base.data(idx2, GroupModel::HpLowRole).toBool()); + QVERIFY(!base.data(idx2, GroupModel::MovesLowRole).toBool()); +} + +void TestGroup::moveRowTest() +{ + GroupModel model; + QAbstractItemModel &base = model; + for (uint32_t i = 1; i <= 3; ++i) { + SharedGroupChar character = CGroupChar::alloc(); + character->setId(GroupId{i}); + model.insertCharacter(character); + } + QCOMPARE(base.rowCount(QModelIndex()), 3); + + // Out-of-bounds and no-op moves are rejected. + QVERIFY(!model.moveRow(-1, 0)); + QVERIFY(!model.moveRow(0, 100)); + QVERIFY(!model.moveRow(0, 0)); + QVERIFY(!model.moveRow(0, 1)); + + QVERIFY(model.moveRow(0, 2)); + QCOMPARE(model.getCharacter(0)->getId(), GroupId{2}); + QCOMPARE(model.getCharacter(1)->getId(), GroupId{1}); + QCOMPARE(model.getCharacter(2)->getId(), GroupId{3}); +} + QTEST_MAIN(TestGroup) diff --git a/tests/TestGroup.h b/tests/TestGroup.h index c7a6332eb..1c2d2c2d1 100644 --- a/tests/TestGroup.h +++ b/tests/TestGroup.h @@ -16,4 +16,7 @@ class NODISCARD_QOBJECT TestGroup final : public QObject private Q_SLOTS: static void enumsTest(); + static void roleNamesTest(); + static void characterRoleDataTest(); + static void moveRowTest(); }; diff --git a/tests/TestMainWindow.cpp b/tests/TestMainWindow.cpp index 3ec4d723b..4d826f86f 100644 --- a/tests/TestMainWindow.cpp +++ b/tests/TestMainWindow.cpp @@ -4,12 +4,16 @@ #include "TestMainWindow.h" #include "../src/configuration/configuration.h" -#include "../src/global/Version.h" +#include "../src/display/MapCanvasConfig.h" +#include "../src/display/MapScroller.h" #include "../src/mainwindow/AudioVolumeSlider.h" -#include "../src/mainwindow/UpdateDialog.h" +#include "../src/mainwindow/CompactLayout.h" +#include "../src/mainwindow/UpdateChecker.h" +#include "../src/map/coordinate.h" #include #include +#include #include const char *getMMapperVersion() @@ -87,4 +91,81 @@ void TestMainWindow::audioToolbarTest() QCOMPARE(getConfig().audio.getSoundVolume(), 10); } +void TestMainWindow::mapScrollerScrollMath() +{ + // Regression test for MapScroller's world<->scroll-unit conversion + // (see MapScroller.h/.cpp), which mirrors MapWindow's known map bounds. + MapScroller scroller; + + // A 10x6-unit known map (mirrors MapData::sig_mapSizeChanged's + // min/max Coordinates, which MapScroller::slot_setScrollBars() + // receives). + const Coordinate min{-2, -3, 0}; + const Coordinate max{8, 3, 0}; + + scroller.slot_setScrollBars(min, max); + + // size() is (max - min) = (10, 6); range is size * SCROLL_SCALE. + QCOMPARE(scroller.getHorizontalScrollMax(), 10 * MapCanvasConfig::SCROLL_SCALE); + QCOMPARE(scroller.getVerticalScrollMax(), 6 * MapCanvasConfig::SCROLL_SCALE); + + // worldToScroll() must invert scrollToWorld() (modulo the integer + // rounding baked into scroll units). + const glm::vec2 world{1.0f, 2.0f}; + const glm::ivec2 scroll = scroller.worldToScroll(world); + const glm::vec2 roundTripped = scroller.scrollToWorld(scroll); + QVERIFY(std::abs(roundTripped.x - world.x) < 0.01f); + QVERIFY(std::abs(roundTripped.y - world.y) < 0.01f); + + // Spot-check an exact known value: world == min maps to scroll (0, dims.y) + // (Y is negated/flipped -- see KnownMapSize::worldToScroll()'s comment). + const glm::ivec2 scrollAtMin = scroller.worldToScroll(glm::vec2{min.x, min.y}); + QCOMPARE(scrollAtMin.x, 0); + QCOMPARE(scrollAtMin.y, 6 * MapCanvasConfig::SCROLL_SCALE); + + // ... and world == max maps to scroll (dims.x, 0). + const glm::ivec2 scrollAtMax = scroller.worldToScroll(glm::vec2{max.x, max.y}); + QCOMPARE(scrollAtMax.x, 10 * MapCanvasConfig::SCROLL_SCALE); + QCOMPARE(scrollAtMax.y, 0); + + // Continuous-scroll timer: starting a non-zero step must fire + // sig_continuousScrollStep() periodically until stopped. + QSignalSpy stepSpy(&scroller, &MapScroller::sig_continuousScrollStep); + scroller.slot_continuousScroll(1, 0); + QTRY_VERIFY_WITH_TIMEOUT(!stepSpy.isEmpty(), 2000); + QCOMPARE(stepSpy.constLast().at(0).toInt(), 1); + QCOMPARE(stepSpy.constLast().at(1).toInt(), 0); + + scroller.slot_continuousScroll(0, 0); + stepSpy.clear(); + QTest::qWait(250); + QCOMPARE(stepSpy.count(), 0); +} + +void TestMainWindow::compactLayoutPolicy() +{ + using namespace CompactLayout; + + // Exactly at the breakpoint is not compact; one pixel short on either + // axis is. + QVERIFY(!isCompact(QSize(MIN_WIDTH, MIN_HEIGHT))); + QVERIFY(!isCompact(QSize(1920, 1080))); + QVERIFY(isCompact(QSize(MIN_WIDTH - 1, MIN_HEIGHT))); + QVERIFY(isCompact(QSize(MIN_WIDTH, MIN_HEIGHT - 1))); + // Landscape phone: wide enough but too short. + QVERIFY(isCompact(QSize(800, 360))); + + QCOMPARE(clientHeight(QSize(400, 1000)), 550); + QCOMPARE(clientHeight(QSize(400, 0)), 0); + + // A window the expanded layout's minimum size has pushed past a phone's + // screen is judged by the screen, so the compact layout still engages. + QCOMPARE(probeSize(QSize(1080, 900), QSize(390, 664)), QSize(390, 664)); + QVERIFY(isCompact(probeSize(QSize(1080, 900), QSize(390, 664)))); + // A window smaller than its screen is judged by itself. + QCOMPARE(probeSize(QSize(600, 420), QSize(1920, 1080)), QSize(600, 420)); + // No screen: the window size stands. + QCOMPARE(probeSize(QSize(1080, 900), QSize()), QSize(1080, 900)); +} + QTEST_MAIN(TestMainWindow) diff --git a/tests/TestMainWindow.h b/tests/TestMainWindow.h index 3be94c218..02c647ee3 100644 --- a/tests/TestMainWindow.h +++ b/tests/TestMainWindow.h @@ -18,4 +18,6 @@ class NODISCARD_QOBJECT TestMainWindow final : public QObject private Q_SLOTS: void updaterTest(); void audioToolbarTest(); + void mapScrollerScrollMath(); + void compactLayoutPolicy(); }; diff --git a/tests/TestMedia.cpp b/tests/TestMedia.cpp new file mode 100644 index 000000000..8eb8b20e7 --- /dev/null +++ b/tests/TestMedia.cpp @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "TestMedia.h" + +#include "../src/media/StackBlur.h" + +#include + +#include +#include + +namespace { // anonymous + +NODISCARD QImage makeGradient(const int w, const int h) +{ + QImage image(w, h, QImage::Format_ARGB32_Premultiplied); + for (int y = 0; y < h; ++y) { + for (int x = 0; x < w; ++x) { + const int r = (x * 255) / std::max(1, w - 1); + const int g = (y * 255) / std::max(1, h - 1); + image.setPixel(x, y, qRgba(r, g, 128, 255)); + } + } + return image; +} + +} // namespace + +TestMedia::TestMedia() = default; + +TestMedia::~TestMedia() = default; + +void TestMedia::stackBlurPreservesSize() +{ + QImage image = makeGradient(32, 24); + const QSize before = image.size(); + mm::stackBlur(image, 3); + QCOMPARE(image.size(), before); +} + +void TestMedia::stackBlurChangesGradient() +{ + const QImage original = makeGradient(32, 24); + QImage blurred = original; + mm::stackBlur(blurred, 3); + + QCOMPARE(blurred.size(), original.size()); + QVERIFY(blurred != original); + + // Determinism: blurring an identical copy again from scratch must + // produce byte-identical output. + QImage blurredAgain = original; + mm::stackBlur(blurredAgain, 3); + QCOMPARE(blurredAgain, blurred); +} + +void TestMedia::stackBlurZeroRadiusIsNoop() +{ + const QImage original = makeGradient(16, 16); + QImage image = original; + mm::stackBlur(image, 0); + QCOMPARE(image, original); +} + +void TestMedia::stackBlurHandlesTinyImage() +{ + QImage image(1, 1, QImage::Format_ARGB32_Premultiplied); + image.setPixel(0, 0, qRgba(10, 20, 30, 255)); + + // Must not crash even though the requested radius is far larger than + // the image; DescriptionImageProvider clamps radius against (w-1)/2 and + // (h-1)/2 before calling this, but stackBlur() itself must stay safe. + mm::stackBlur(image, 5); + QCOMPARE(image.size(), QSize(1, 1)); + + QImage empty; + mm::stackBlur(empty, 5); // must not crash on a null image either + QVERIFY(empty.isNull()); +} + +QTEST_MAIN(TestMedia) + +#include "TestMedia.moc" diff --git a/tests/TestMedia.h b/tests/TestMedia.h new file mode 100644 index 000000000..433be3216 --- /dev/null +++ b/tests/TestMedia.h @@ -0,0 +1,22 @@ +#pragma once +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 The MMapper Authors + +#include "../src/global/macros.h" + +#include + +class NODISCARD_QOBJECT TestMedia final : public QObject +{ + Q_OBJECT + +public: + TestMedia(); + ~TestMedia() final; + +private Q_SLOTS: + void stackBlurPreservesSize(); + void stackBlurChangesGradient(); + void stackBlurZeroRadiusIsNoop(); + void stackBlurHandlesTinyImage(); +}; diff --git a/tests/roompanel/TestRoomManager.cpp b/tests/roompanel/TestRoomManager.cpp index f2021a1df..153deaeae 100644 --- a/tests/roompanel/TestRoomManager.cpp +++ b/tests/roompanel/TestRoomManager.cpp @@ -7,7 +7,9 @@ #include "../src/global/tests.h" #include "../src/proxy/GmcpMessage.h" #include "../src/roompanel/RoomManager.h" +#include "../src/roompanel/RoomModel.h" +#include #include namespace { // anonymous const auto mysterieuse = std::invoke([]() -> QString { @@ -135,6 +137,66 @@ void TestRoomManager::testParseGmcpUpdateValidMessage() QVERIFY(updatedMob); } +void TestRoomManager::testRoomModelEnemyColors() +{ + auto &manager = m_manager; + manager.slot_reset(); + + RoomModel model(nullptr, manager.getRoom()); + model.update(); + + // Row 0 is the placeholder empty row when there are no mobs. + const QModelIndex normalName = model.index(0, static_cast(RoomModel::ColumnTypeEnum::NAME)); + QVERIFY(!model.data(normalName, RoomModel::RowBackgroundRole).isValid()); + QVERIFY(!model.data(normalName, RoomModel::RowForegroundRole).isValid()); + + // A name wrapped in asterisks (e.g. "*an Orc*") marks an enemy player. + QJsonObject enemyObj = {{"id", 3}, {"name", "*an Orc*"}, {"position", "standing"}}; + auto jsonStr = makeCompactJson(enemyObj); + GmcpMessage addMessage(GmcpMessageTypeEnum::ROOM_CHARS_ADD, jsonStr); + manager.slot_parseGmcpInput(addMessage); + model.update(); + + const QModelIndex enemyName = model.index(0, static_cast(RoomModel::ColumnTypeEnum::NAME)); + const QVariant background = model.data(enemyName, RoomModel::RowBackgroundRole); + QVERIFY(background.isValid()); + QCOMPARE(background.value(), QColor(Qt::yellow)); + + const QVariant foreground = model.data(enemyName, RoomModel::RowForegroundRole); + QVERIFY(foreground.isValid()); + + // The LABEL column is explicitly excluded from enemy highlighting. + const QModelIndex enemyLabel = model.index(0, + static_cast(RoomModel::ColumnTypeEnum::LABEL)); + QVERIFY(!model.data(enemyLabel, RoomModel::RowBackgroundRole).isValid()); +} + +void TestRoomManager::testRoomModelFightingYouColors() +{ + auto &manager = m_manager; + manager.slot_reset(); + + QJsonObject fightingObj = {{"id", 4}, + {"name", "an angry troll"}, + {"position", "standing"}, + {"fighting", "you"}}; + auto jsonStr = makeCompactJson(fightingObj); + GmcpMessage addMessage(GmcpMessageTypeEnum::ROOM_CHARS_ADD, jsonStr); + manager.slot_parseGmcpInput(addMessage); + + RoomModel model(nullptr, manager.getRoom()); + model.update(); + + const QModelIndex fightingIndex = model.index(0, + static_cast( + RoomModel::ColumnTypeEnum::FIGHTING)); + QCOMPARE(model.data(fightingIndex, Qt::DisplayRole).toString(), QStringLiteral("YOU")); + + const QVariant foreground = model.data(fightingIndex, RoomModel::RowForegroundRole); + QVERIFY(foreground.isValid()); + QCOMPARE(foreground.value(), QColor(Qt::red)); +} + int main(int argc, char **argv) { QCoreApplication app(argc, argv); diff --git a/tests/roompanel/TestRoomManager.h b/tests/roompanel/TestRoomManager.h index 1ec71891e..1d4fe84d4 100644 --- a/tests/roompanel/TestRoomManager.h +++ b/tests/roompanel/TestRoomManager.h @@ -26,4 +26,6 @@ private Q_SLOTS: void testParseGmcpAddValidMessage(); void testParseGmcpInvalidMessage(); void testParseGmcpUpdateValidMessage(); + void testRoomModelEnemyColors(); + void testRoomModelFightingYouColors(); }; diff --git a/tests/testadventure.cpp b/tests/testadventure.cpp index dfe1073a0..9b80491a2 100644 --- a/tests/testadventure.cpp +++ b/tests/testadventure.cpp @@ -3,6 +3,7 @@ #include "testadventure.h" +#include "../src/adventure/AdventureLogModel.h" #include "../src/adventure/adventuresession.h" #include "../src/adventure/adventuretracker.h" #include "../src/global/Charset.h" @@ -305,4 +306,117 @@ void TestAdventure::testE2E() QCOMPARE(killedMobs, expectedMobs); } +void TestAdventure::testLogModelInitialContent() +{ + GameObserver observer; + AdventureTracker tracker{observer, nullptr}; + AdventureLogModel model{tracker, nullptr}; + + QCOMPARE(model.rowCount(), 1); + QString expectedDefault = AdventureLogModel::DEFAULT_MSG; + while (expectedDefault.endsWith('\n')) { + expectedDefault.chop(1); + } + QCOMPARE(model.data(model.index(0), Qt::DisplayRole).toString(), expectedDefault); + + QHash roles = model.roleNames(); + QCOMPARE(roles.value(Qt::DisplayRole), QByteArray("display")); +} + +void TestAdventure::testLogModelSignals() +{ + GameObserver observer; + AdventureTracker tracker{observer, nullptr}; + AdventureLogModel model{tracker, nullptr}; + + // sig_accomplishedTask with no xp is ignored (spam avoidance). + tracker.sig_accomplishedTask(0.0); + QCOMPARE(model.rowCount(), 1); + + tracker.sig_accomplishedTask(500.0); + QCOMPARE(model.rowCount(), 2); + QCOMPARE(model.data(model.index(1)).toString(), + QString(AdventureLogModel::ACCOMPLISH_MSG) + .arg(AdventureSession::formatPoints(500.0)) + .chopped(1)); + + tracker.sig_achievedSomething("Did a thing", 0.0); + QCOMPARE(model.rowCount(), 3); + QCOMPARE(model.data(model.index(2)).toString(), + QString(AdventureLogModel::ACHIEVE_MSG).arg("Did a thing").chopped(1)); + + tracker.sig_achievedSomething("Did a bigger thing", 100.0); + QCOMPARE(model.rowCount(), 4); + QCOMPARE(model.data(model.index(3)).toString(), + QString(AdventureLogModel::ACHIEVE_MSG_XP) + .arg("Did a bigger thing", AdventureSession::formatPoints(100.0)) + .chopped(1)); + + // sig_diedInGame with no xp lost is ignored. + tracker.sig_diedInGame(0.0); + QCOMPARE(model.rowCount(), 4); + + tracker.sig_diedInGame(-42.0); + QCOMPARE(model.rowCount(), 5); + QCOMPARE(model.data(model.index(4)).toString(), + QString(AdventureLogModel::DIED_MSG) + .arg(AdventureSession::formatPoints(-42.0)) + .chopped(1)); + + tracker.sig_gainedLevel(); + QCOMPARE(model.rowCount(), 6); + QCOMPARE(model.data(model.index(5)).toString(), + QString(AdventureLogModel::GAINED_LEVEL_MSG).chopped(1)); + + tracker.sig_killedMob("A goblin", 25.0); + QCOMPARE(model.rowCount(), 7); + QCOMPARE(model.data(model.index(6)).toString(), + QString(AdventureLogModel::KILL_TROPHY_MSG) + .arg("A goblin", AdventureSession::formatPoints(25.0)) + .chopped(1)); + + tracker.sig_receivedHint("Try harder"); + QCOMPARE(model.rowCount(), 8); + QCOMPARE(model.data(model.index(7)).toString(), + QString(AdventureLogModel::HINT_MSG).arg("Try harder").chopped(1)); +} + +void TestAdventure::testLogModelMaxLinesCap() +{ + GameObserver observer; + AdventureTracker tracker{observer, nullptr}; + AdventureLogModel model{tracker, nullptr}; + + for (int i = 0; i < AdventureLogModel::MAX_LINES + 10; ++i) { + tracker.sig_gainedLevel(); + } + + QCOMPARE(model.rowCount(), AdventureLogModel::MAX_LINES); + // The oldest entries (including the default welcome message) should + // have been dropped, leaving only "gained level" lines behind. + const QString expectedLine = QString(AdventureLogModel::GAINED_LEVEL_MSG).chopped(1); + QCOMPARE(model.data(model.index(0)).toString(), expectedLine); + QCOMPARE(model.data(model.index(AdventureLogModel::MAX_LINES - 1)).toString(), expectedLine); +} + +void TestAdventure::testLogModelClear() +{ + GameObserver observer; + AdventureTracker tracker{observer, nullptr}; + AdventureLogModel model{tracker, nullptr}; + + tracker.sig_gainedLevel(); + tracker.sig_gainedLevel(); + QCOMPARE(model.rowCount(), 3); + + model.clear(); + + QCOMPARE(model.rowCount(), 1); + QString expectedDefault = AdventureLogModel::DEFAULT_MSG; + while (expectedDefault.endsWith('\n')) { + expectedDefault.chop(1); + } + QCOMPARE(model.data(model.index(0)).toString(), expectedDefault); +} + QTEST_MAIN(TestAdventure) diff --git a/tests/testadventure.h b/tests/testadventure.h index ba4575cfa..afd4d501f 100644 --- a/tests/testadventure.h +++ b/tests/testadventure.h @@ -17,4 +17,8 @@ private slots: static void testHintParser(); static void testKillAndXPParser(); static void testE2E(); + static void testLogModelInitialContent(); + static void testLogModelSignals(); + static void testLogModelMaxLinesCap(); + static void testLogModelClear(); }; diff --git a/tests/testclock.cpp b/tests/testclock.cpp index 9fb01bd4d..63111f918 100644 --- a/tests/testclock.cpp +++ b/tests/testclock.cpp @@ -3,6 +3,7 @@ #include "testclock.h" +#include "../src/clock/ClockStrings.h" #include "../src/clock/mumeclock.h" #include "../src/configuration/configuration.h" #include "../src/global/HideQDebug.h" @@ -529,4 +530,27 @@ void TestClock::moonClockTest() static_cast(MumeMoonVisibilityEnum::BRIGHT)); } +void TestClock::clockStringsTest() +{ + // Spot-check a couple of enum -> string mappings used by + // MumeClockWidget (see ClockStrings.h/.cpp). + QCOMPARE(clockstrings::moonPhaseEmoji(MumeMoonPhaseEnum::FULL_MOON), + QString::fromUtf8("\xF0\x9F\x8C\x95")); + QCOMPARE(clockstrings::moonPhaseEmoji(MumeMoonPhaseEnum::UNKNOWN), QString()); + + QCOMPARE(clockstrings::seasonText(MumeSeasonEnum::WINTER), QStringLiteral("Winter")); + QCOMPARE(clockstrings::seasonText(MumeSeasonEnum::UNKNOWN), QString()); + + QCOMPARE(clockstrings::weatherEmoji(PromptWeatherEnum::RAIN), + QString::fromUtf8("\xF0\x9F\x8C\xA7")); + QCOMPARE(clockstrings::weatherTooltip(PromptWeatherEnum::RAIN), QStringLiteral("Rainy")); + QCOMPARE(clockstrings::weatherEmoji(PromptWeatherEnum::NICE), QString()); + QCOMPARE(clockstrings::weatherTooltip(PromptWeatherEnum::NICE), QString()); + + QCOMPARE(clockstrings::fogEmoji(PromptFogEnum::HEAVY_FOG), + QString::fromUtf8("\xF0\x9F\x8C\xAB\xF0\x9F\x8C\xAB")); + QCOMPARE(clockstrings::fogTooltip(PromptFogEnum::HEAVY_FOG), QStringLiteral("Heavy Fog")); + QCOMPARE(clockstrings::fogEmoji(PromptFogEnum::NO_FOG), QString()); +} + QTEST_MAIN(TestClock) diff --git a/tests/testclock.h b/tests/testclock.h index 2470a72c2..1b3521344 100644 --- a/tests/testclock.h +++ b/tests/testclock.h @@ -24,4 +24,5 @@ private Q_SLOTS: void parseClockTimeTest(); void precsionTimeoutTest(); void moonClockTest(); + void clockStringsTest(); };