From 8d3d3b6539821d6da46718fbcaef5f6a3d29f718 Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Sun, 22 Nov 2026 16:36:15 +0800 Subject: [PATCH 01/11] feat(ui): view contestant source code from judging results (#225) Add a read-only SourceViewerDialog with lightweight C-like/Pascal syntax highlighting and UTF-8 fallback to local 8-bit encoding. Reach it from the ResultViewer context menu (View Source, per task) and from clickable source file names in DetailDialog. Submitted source paths are resolved the same way TaskJudger does, including subfolder and communication multi-file tasks. --- src/detaildialog.cpp | 20 ++- src/resultviewer.cpp | 36 +++- src/resultviewer.h | 1 + src/sourceviewer.cpp | 378 ++++++++++++++++++++++++++++++++++++++++++ src/sourceviewer.h | 35 ++++ translations/zh_CN.ts | 23 +++ translations/zh_TW.ts | 23 +++ 7 files changed, 508 insertions(+), 8 deletions(-) create mode 100644 src/sourceviewer.cpp create mode 100644 src/sourceviewer.h diff --git a/src/detaildialog.cpp b/src/detaildialog.cpp index e2d59d45..e94183a1 100644 --- a/src/detaildialog.cpp +++ b/src/detaildialog.cpp @@ -18,6 +18,7 @@ #include "core/task.h" #include "core/testcase.h" #include "judgingdialog.h" +#include "sourceviewer.h" // #include #include @@ -86,9 +87,9 @@ void DetailDialog::refreshViewer(Contest *_contest, Contestant *_contestant) { break; case CompileTimeLimitExceeded: - htmlCode += QString("  %1%2
") - .arg(tr("Source file: ")) - .arg(contestant->getSourceFile(i)); + htmlCode += QString(R"(  %1%2
)") + .arg(tr("Source file: "), contestant->getSourceFile(i).toHtmlEscaped(), + QString::number(i)); htmlCode += QString("  %1

").arg(tr("Compile time limit exceeded")); break; @@ -97,9 +98,9 @@ void DetailDialog::refreshViewer(Contest *_contest, Contestant *_contestant) { break; case CompileError: - htmlCode += QString("  %1%2
") - .arg(tr("Source file: ")) - .arg(contestant->getSourceFile(i)); + htmlCode += QString(R"(  %1%2
)") + .arg(tr("Source file: "), contestant->getSourceFile(i).toHtmlEscaped(), + QString::number(i)); htmlCode += QString("  %1").arg(tr("Compile error")); if (! contestant->getCompileMessage(i).isEmpty()) @@ -118,7 +119,8 @@ void DetailDialog::refreshViewer(Contest *_contest, Contestant *_contestant) { } htmlCode += - QString("  %1%2").arg(tr("Source file: ")).arg(contestant->getSourceFile(i)); + QString(R"(  %1%2)") + .arg(tr("Source file: "), contestant->getSourceFile(i).toHtmlEscaped(), QString::number(i)); } htmlCode += R"()"; @@ -279,6 +281,10 @@ void DetailDialog::anchorClicked(const QUrl &url) { .exec(); } + if (list[0] == "Source") { + SourceViewerDialog::viewSource(this, contest, contestant, list[1].toInt()); + } + if (list[0] == "Message") { QList message = contestant->getMessage(list[1].toInt()); QMessageBox(QMessageBox::NoIcon, tr("Message"), diff --git a/src/resultviewer.cpp b/src/resultviewer.cpp index 40461ec6..19f8afd9 100644 --- a/src/resultviewer.cpp +++ b/src/resultviewer.cpp @@ -17,6 +17,7 @@ #include "core/task.h" #include "detaildialog.h" #include "judgingdialog.h" +#include "sourceviewer.h" // #include #include @@ -71,9 +72,27 @@ void ResultViewer::contextMenuEvent(QContextMenuEvent * /*event*/) { auto *contextMenu = new QMenu(this); - if (selectionRange.size() == 1 && selectionRange[0].rowCount() == 1) { + if (curContest && selectionRange.size() == 1 && selectionRange[0].rowCount() == 1) { contextMenu->addAction(detailInformationAction); contextMenu->setDefaultAction(detailInformationAction); + + // View the source code of the selected contestant (issue #225) + const QList taskList = curContest->getTaskList(); + QList sourceTaskIndices; + + for (int i = 0; i < taskList.size(); i++) { + if (taskList[i]->getTaskType() != Task::AnswersOnly) + sourceTaskIndices.append(i); + } + + if (! sourceTaskIndices.empty()) { + QMenu *viewSourceMenu = contextMenu->addMenu(tr("View Source")); + + for (int i : sourceTaskIndices) { + QAction *viewSourceAction = viewSourceMenu->addAction(taskList[i]->getProblemTitle()); + connect(viewSourceAction, &QAction::triggered, this, [this, i]() { viewSource(i); }); + } + } } if (! selectionRange.empty()) { @@ -436,3 +455,18 @@ void ResultViewer::detailInformation() { dialog->showDialog(); delete dialog; } + +void ResultViewer::viewSource(int taskIndex) { + QList selectionRange = selectedRanges(); + + if (selectionRange.empty() || ! curContest) + return; + + int index = selectionRange[0].topRow(); + Contestant *contestant = curContest->getContestant(item(index, 1)->text()); + + if (contestant == nullptr) + return; + + SourceViewerDialog::viewSource(this, curContest, contestant, taskIndex); +} diff --git a/src/resultviewer.h b/src/resultviewer.h index 72c66f0a..636f1c97 100644 --- a/src/resultviewer.h +++ b/src/resultviewer.h @@ -42,6 +42,7 @@ class ResultViewer : public QTableWidget { private slots: void deleteContestant(); void detailInformation(); + void viewSource(int taskIndex); signals: void contestantDeleted(); diff --git a/src/sourceviewer.cpp b/src/sourceviewer.cpp new file mode 100644 index 00000000..fea03d17 --- /dev/null +++ b/src/sourceviewer.cpp @@ -0,0 +1,378 @@ +/* + * SPDX-FileCopyrightText: 2026 Project LemonLime + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#include "sourceviewer.h" +// +#include "base/settings.h" +#include "core/contest.h" +#include "core/contestant.h" +#include "core/task.h" +// +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +enum class Language { CLike, Pascal }; + +struct HighlightPalette { + QColor keyword; + QColor number; + QColor string; + QColor comment; + QColor preprocessor; +}; + +HighlightPalette highlightPalette() { + const QPalette &palette = QApplication::palette(); + + if (palette.color(QPalette::WindowText).lightness() < palette.color(QPalette::Window).lightness()) { + // Dark background + return {QColor(0x6f, 0xa8, 0xff), QColor(0xe8, 0x7c, 0xb4), QColor(0x7c, 0xd6, 0x7c), + QColor(0x8a, 0x8a, 0x8a), QColor(0xe0, 0xa0, 0x60)}; + } + + // Light background + return {QColor(0x00, 0x00, 0xc0), QColor(0xb0, 0x00, 0x60), QColor(0x00, 0x70, 0x00), + QColor(0x80, 0x80, 0x80), QColor(0x80, 0x40, 0x00)}; +} + +QTextCharFormat makeFormat(const QColor &color) { + QTextCharFormat format; + format.setForeground(color); + return format; +} + +} // namespace + +class SourceHighlighter final : public QSyntaxHighlighter { + public: + explicit SourceHighlighter(QTextDocument *document) : QSyntaxHighlighter(document) { + const HighlightPalette palette = highlightPalette(); + keywordFormat = makeFormat(palette.keyword); + numberFormat = makeFormat(palette.number); + stringFormat = makeFormat(palette.string); + commentFormat = makeFormat(palette.comment); + preprocessorFormat = makeFormat(palette.preprocessor); + } + + void setLanguage(Language newLanguage) { language = newLanguage; } + + protected: + void highlightBlock(const QString &text) override { + + const QSet &keywords = (language == Language::Pascal) ? pascalKeywords() : cKeywords(); + + int index = 0; + const int length = text.length(); + + // Continue a multi-line comment started in a previous block: 1 = /* */ or { }, 2 = (* *) + if (previousBlockState() == 1 || previousBlockState() == 2) { + const QString endMark = previousBlockState() == 1 + ? (language == Language::Pascal ? QStringLiteral("}") : QStringLiteral("*/")) + : QStringLiteral("*)"); + const int end = text.indexOf(endMark); + + if (end < 0) { + setFormat(0, length, commentFormat); + setCurrentBlockState(previousBlockState()); + return; + } + + setFormat(0, end + endMark.length(), commentFormat); + index = end + endMark.length(); + } + + const bool isPascal = language == Language::Pascal; + + while (index < length) { + const QChar current = text.at(index); + + // Line comments + if (current == QLatin1Char('/') && index + 1 < length && text.at(index + 1) == QLatin1Char('/')) { + setFormat(index, length - index, commentFormat); + break; + } + + // Multi-line comment starts + if (isPascal && current == QLatin1Char('{')) { + const int end = text.indexOf(QLatin1Char('}'), index + 1); + + if (end < 0) { + setFormat(index, length - index, commentFormat); + setCurrentBlockState(1); + break; + } + + setFormat(index, end - index + 1, commentFormat); + index = end + 1; + continue; + } + + if (isPascal && current == QLatin1Char('(') && index + 1 < length && + text.at(index + 1) == QLatin1Char('*')) { + const int end = text.indexOf(QLatin1String("*)"), index + 2); + + if (end < 0) { + setFormat(index, length - index, commentFormat); + setCurrentBlockState(2); + break; + } + + setFormat(index, end - index + 2, commentFormat); + index = end + 2; + continue; + } + + if (! isPascal && current == QLatin1Char('/') && index + 1 < length && + text.at(index + 1) == QLatin1Char('*')) { + const int end = text.indexOf(QLatin1String("*/"), index + 2); + + if (end < 0) { + setFormat(index, length - index, commentFormat); + setCurrentBlockState(1); + break; + } + + setFormat(index, end - index + 2, commentFormat); + index = end + 2; + continue; + } + + // Strings ('...' for Pascal, "..." and '...' for C-like) + if (current == QLatin1Char('"') || current == QLatin1Char('\'')) { + int end = index + 1; + + while (end < length) { + if (! isPascal && text.at(end) == QLatin1Char('\\')) { + end += 2; + continue; + } + + if (isPascal && text.at(end) == QLatin1Char('\'') && end + 1 < length && + text.at(end + 1) == QLatin1Char('\'')) { + end += 2; + continue; + } + + if (text.at(end) == current) { + ++end; + break; + } + + ++end; + } + + setFormat(index, qMin(end, length) - index, stringFormat); + index = qMin(end, length); + continue; + } + + // Numbers + if (current.isDigit()) { + int end = index + 1; + + while (end < length && (text.at(end).isDigit() || text.at(end) == QLatin1Char('.') || + (text.at(end).toLower() >= QLatin1Char('a') && + text.at(end).toLower() <= QLatin1Char('f')) || + text.at(end).toLower() == QLatin1Char('x') || + text.at(end).toLower() == QLatin1Char('u') || + text.at(end).toLower() == QLatin1Char('l'))) { + ++end; + } + + setFormat(index, end - index, numberFormat); + index = end; + continue; + } + + // Identifiers and keywords + if (current.isLetter() || current == QLatin1Char('_')) { + int end = index + 1; + + while (end < length && + (text.at(end).isLetterOrNumber() || text.at(end) == QLatin1Char('_'))) { + ++end; + } + + if (keywords.contains(text.mid(index, end - index))) + setFormat(index, end - index, keywordFormat); + + index = end; + continue; + } + + // Preprocessor directives (C-like, first non-whitespace of the line) + if (! isPascal && current == QLatin1Char('#')) { + int start = index; + + while (start > 0 && (text.at(start - 1) == QLatin1Char(' ') || + text.at(start - 1) == QLatin1Char('\t'))) { + --start; + } + + if (text.left(start).trimmed().isEmpty()) { + setFormat(index, length - index, preprocessorFormat); + break; + } + } + + ++index; + } + } + + private: + static const QSet &cKeywords() { + static const QSet keywords = { + "alignas", "alignof", "and", "asm", "auto", "bool", "break", "case", "catch", "char", + "char8_t", "char16_t", "char32_t", "class", "co_await", "co_return", "co_yield", "concept", + "const", "consteval", "constexpr", "constinit", "const_cast", "continue", "decltype", + "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", + "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "java", "long", + "mutable", "namespace", "new", "noexcept", "not", "nullptr", "operator", "override", + "private", "protected", "public", "register", "reinterpret_cast", "requires", "return", + "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", + "template", "this", "throw", "true", "try", "typedef", "typeid", "typename", "union", + "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "final", "package", + "implements", "import", "interface", "boolean", "extends"}; + return keywords; + } + + static const QSet &pascalKeywords() { + static const QSet keywords = { + "and", "array", "begin", "case", "const", "div", "do", "downto", "else", "end", "file", + "for", "function", "goto", "if", "in", "label", "mod", "nil", "not", "of", "or", + "procedure", "program", "record", "repeat", "set", "shl", "shr", "string", "then", "to", + "type", "until", "uses", "var", "while", "with", "xor", "boolean", "byte", "char", + "integer", "longint", "real", "word", "read", "readln", "write", "writeln"}; + return keywords; + } + + Language language = Language::CLike; + QTextCharFormat keywordFormat; + QTextCharFormat numberFormat; + QTextCharFormat stringFormat; + QTextCharFormat commentFormat; + QTextCharFormat preprocessorFormat; +}; + +QString SourceViewerDialog::contestantSourceFilePath(Contest *contest, Contestant *contestant, int taskIndex, + int fileIndex) { + const Task *task = contest->getTask(taskIndex); + + if (task == nullptr || task->getTaskType() == Task::AnswersOnly) + return {}; + + // Communication tasks store a space-separated list of submitted files + const QStringList files = + contestant->getSourceFile(taskIndex).split(' ', Qt::SkipEmptyParts); + + if (fileIndex < 0 || fileIndex >= files.size()) + return {}; + + const QString &fileName = files[fileIndex]; + + if (fileName.isEmpty()) + return {}; + + QString path = Settings::sourcePath() + contestant->getContestantName(); + + if (task->getSubFolderCheck()) + path += QDir::separator() + task->getSourceFileName(); + + path += QDir::separator() + fileName; + return path; +} + +SourceViewerDialog::SourceViewerDialog(QWidget *parent, const QStringList &filePaths, const QString &heading) + : QDialog(parent) { + setModal(true); + setWindowTitle(heading); + resize(760, 560); + + auto *layout = new QVBoxLayout(this); + layout->setContentsMargins(8, 8, 8, 8); + + tabWidget = new QTabWidget(this); + layout->addWidget(tabWidget); + + if (filePaths.size() == 1) + tabWidget->tabBar()->hide(); + + for (const QString &filePath : filePaths) + addEditorTab(filePath); +} + +void SourceViewerDialog::addEditorTab(const QString &filePath) { + auto *editor = new QPlainTextEdit(tabWidget); + editor->setReadOnly(true); + editor->setLineWrapMode(QPlainTextEdit::NoWrap); + editor->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); + + QFile file(filePath); + + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { + const QByteArray data = file.readAll(); + QString content = QString::fromUtf8(data); + + // Fall back to the system's local encoding when the file is not valid UTF-8 + if (content.contains(QChar(0xfffd))) + content = QString::fromLocal8bit(data); + + editor->setPlainText(content); + } + + auto *highlighter = new SourceHighlighter(editor->document()); + const QString suffix = QFileInfo(filePath).suffix().toLower(); + highlighter->setLanguage(suffix == "pas" || suffix == "pp" || suffix == "dpr" ? Language::Pascal + : Language::CLike); + highlighters.append(highlighter); + + tabWidget->addTab(editor, QFileInfo(filePath).fileName()); +} + +void SourceViewerDialog::viewSource(QWidget *parent, Contest *contest, Contestant *contestant, int taskIndex) { + const Task *task = contest->getTask(taskIndex); + QStringList filePaths; + + for (int i = 0;; i++) { + const QString path = contestantSourceFilePath(contest, contestant, taskIndex, i); + + if (path.isEmpty()) + break; + + filePaths.append(path); + } + + if (filePaths.isEmpty() || task == nullptr) { + QMessageBox::information(parent, tr("View Source"), tr("Cannot find the source file of this task.")); + return; + } + + for (const QString &path : filePaths) { + if (! QFile::exists(path)) { + QMessageBox::information(parent, tr("View Source"), + tr("Source file %1 does not exist.").arg(QDir::toNativeSeparators(path))); + return; + } + } + + const QString heading = + tr("Source Code: %1 - %2").arg(contestant->getContestantName(), task->getProblemTitle()); + SourceViewerDialog dialog(parent, filePaths, heading); + dialog.exec(); +} diff --git a/src/sourceviewer.h b/src/sourceviewer.h new file mode 100644 index 00000000..2646e417 --- /dev/null +++ b/src/sourceviewer.h @@ -0,0 +1,35 @@ +/* + * SPDX-FileCopyrightText: 2026 Project LemonLime + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#pragma once +// + +#include +#include + +class Contest; +class Contestant; +class SourceHighlighter; +class QTabWidget; + +class SourceViewerDialog : public QDialog { + Q_OBJECT + + public: + /** Resolve the path of one submitted source file, mirroring TaskJudger's layout. */ + static QString contestantSourceFilePath(Contest *contest, Contestant *contestant, int taskIndex, + int fileIndex); + /** Resolve, load and display the source files of contestant's taskIndex-th task. */ + static void viewSource(QWidget *parent, Contest *contest, Contestant *contestant, int taskIndex); + + private: + explicit SourceViewerDialog(QWidget *parent, const QStringList &filePaths, const QString &heading); + void addEditorTab(const QString &filePath); + + QTabWidget *tabWidget{}; + QList highlighters; +}; diff --git a/translations/zh_CN.ts b/translations/zh_CN.ts index 0388869f..a223a841 100755 --- a/translations/zh_CN.ts +++ b/translations/zh_CN.ts @@ -2074,6 +2074,10 @@ Depends: Details 详情 + + View Source + 查看源代码 + Judge 测试 @@ -2188,6 +2192,25 @@ Depends: 仿 joi2020 + + SourceViewerDialog + + View Source + 查看源代码 + + + Cannot find the source file of this task. + 找不到该任务的源文件。 + + + Source file %1 does not exist. + 源文件 %1 不存在。 + + + Source Code: %1 - %2 + 源代码:%1 - %2 + + StatisticsBrowser diff --git a/translations/zh_TW.ts b/translations/zh_TW.ts index 22070493..0d2c6773 100644 --- a/translations/zh_TW.ts +++ b/translations/zh_TW.ts @@ -2074,6 +2074,10 @@ Depends: Details 詳情 + + View Source + 查看原始碼 + Judge 測試 @@ -2188,6 +2192,25 @@ Depends: + + SourceViewerDialog + + View Source + 查看原始碼 + + + Cannot find the source file of this task. + 找不到該任務的原始碼檔案。 + + + Source file %1 does not exist. + 原始碼檔案 %1 不存在。 + + + Source Code: %1 - %2 + 原始碼:%1 - %2 + + StatisticsBrowser From 2dc11a117d16a49c9c7bf3ee6aead4f4ec360345 Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Sun, 22 Nov 2026 17:08:36 +0800 Subject: [PATCH 02/11] fix(ui): build SourceViewerDialog against Qt 6.11 Include QTabBar/QString explicitly and replace QString::fromLocal8bit (removed in Qt 6.11) with a QStringDecoder using the System codec for the non-UTF-8 fallback. --- src/sourceviewer.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/sourceviewer.cpp b/src/sourceviewer.cpp index fea03d17..443592c8 100644 --- a/src/sourceviewer.cpp +++ b/src/sourceviewer.cpp @@ -21,6 +21,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include @@ -330,8 +334,10 @@ void SourceViewerDialog::addEditorTab(const QString &filePath) { QString content = QString::fromUtf8(data); // Fall back to the system's local encoding when the file is not valid UTF-8 - if (content.contains(QChar(0xfffd))) - content = QString::fromLocal8bit(data); + if (content.contains(QChar(0xfffd))) { + QStringDecoder decoder(QStringConverter::System); + content = decoder(data); + } editor->setPlainText(content); } From 69b358afd75cba89718f7981a4ae928f8daa3368 Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Sun, 22 Nov 2026 17:45:37 +0800 Subject: [PATCH 03/11] feat(ui): polish source viewer colors, line numbers and highlight Fix the inverted light/dark theme detection that rendered light-theme highlight colors on the dark editor background. Use self-contained VS Code-inspired palettes with an explicit editor stylesheet so keywords, strings, comments and identifiers stay readable on both themes, and add a line-number gutter, a current-line highlight, a larger font and 4-space tab stops. --- src/sourceviewer.cpp | 169 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 148 insertions(+), 21 deletions(-) diff --git a/src/sourceviewer.cpp b/src/sourceviewer.cpp index 443592c8..e9c54a00 100644 --- a/src/sourceviewer.cpp +++ b/src/sourceviewer.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -33,26 +34,40 @@ namespace { enum class Language { CLike, Pascal }; -struct HighlightPalette { +// A self-contained color scheme so the viewer stays readable in both the +// application's light and dark themes (VS Code-inspired palettes). The +// editor's base/text colors are set explicitly instead of inheriting the +// application palette, which keeps identifiers, keywords and comments +// clearly apart on any theme. +struct EditorTheme { + QColor background; + QColor text; + QColor currentLine; + QColor selection; QColor keyword; QColor number; QColor string; QColor comment; QColor preprocessor; + QColor lineNumberText; }; -HighlightPalette highlightPalette() { +EditorTheme editorTheme() { const QPalette &palette = QApplication::palette(); - - if (palette.color(QPalette::WindowText).lightness() < palette.color(QPalette::Window).lightness()) { - // Dark background - return {QColor(0x6f, 0xa8, 0xff), QColor(0xe8, 0x7c, 0xb4), QColor(0x7c, 0xd6, 0x7c), - QColor(0x8a, 0x8a, 0x8a), QColor(0xe0, 0xa0, 0x60)}; + const bool darkTheme = palette.color(QPalette::WindowText).lightness() > + palette.color(QPalette::Window).lightness(); + + if (darkTheme) { + return {QColor(0x1e, 0x1e, 0x1e), QColor(0xd4, 0xd4, 0xd4), QColor(0x28, 0x2c, 0x34), + QColor(0x26, 0x4f, 0x78), QColor(0x56, 0x9c, 0xd6), QColor(0xb5, 0xce, 0xa8), + QColor(0xce, 0x91, 0x78), QColor(0x6a, 0x99, 0x55), QColor(0xc5, 0x86, 0xc0), + QColor(0x85, 0x85, 0x85)}; } - // Light background - return {QColor(0x00, 0x00, 0xc0), QColor(0xb0, 0x00, 0x60), QColor(0x00, 0x70, 0x00), - QColor(0x80, 0x80, 0x80), QColor(0x80, 0x40, 0x00)}; + return {QColor(0xff, 0xff, 0xff), QColor(0x1e, 0x1e, 0x1e), QColor(0xf3, 0xf3, 0xf3), + QColor(0xad, 0xd6, 0xff), QColor(0x00, 0x00, 0xff), QColor(0x09, 0x86, 0x58), + QColor(0xa3, 0x15, 0x15), QColor(0x00, 0x80, 0x00), QColor(0xaf, 0x00, 0xdb), + QColor(0x76, 0x76, 0x76)}; } QTextCharFormat makeFormat(const QColor &color) { @@ -65,20 +80,19 @@ QTextCharFormat makeFormat(const QColor &color) { class SourceHighlighter final : public QSyntaxHighlighter { public: - explicit SourceHighlighter(QTextDocument *document) : QSyntaxHighlighter(document) { - const HighlightPalette palette = highlightPalette(); - keywordFormat = makeFormat(palette.keyword); - numberFormat = makeFormat(palette.number); - stringFormat = makeFormat(palette.string); - commentFormat = makeFormat(palette.comment); - preprocessorFormat = makeFormat(palette.preprocessor); + explicit SourceHighlighter(QTextDocument *document, const EditorTheme &theme) + : QSyntaxHighlighter(document) { + keywordFormat = makeFormat(theme.keyword); + numberFormat = makeFormat(theme.number); + stringFormat = makeFormat(theme.string); + commentFormat = makeFormat(theme.comment); + preprocessorFormat = makeFormat(theme.preprocessor); } void setLanguage(Language newLanguage) { language = newLanguage; } protected: void highlightBlock(const QString &text) override { - const QSet &keywords = (language == Language::Pascal) ? pascalKeywords() : cKeywords(); int index = 0; @@ -274,6 +288,103 @@ class SourceHighlighter final : public QSyntaxHighlighter { QTextCharFormat preprocessorFormat; }; +class LineNumberArea; + +// A read-only code editor pane with a line-number gutter and a subtle +// current-line highlight. +class CodeEditor final : public QPlainTextEdit { + public: + CodeEditor(const EditorTheme &editorTheme, QWidget *parent = nullptr); + + int lineNumberAreaWidth() const { + int digits = 1; + + for (int max = qMax(1, blockCount()); max > 9; max /= 10) + ++digits; + + return 14 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits; + } + + void lineNumberAreaPaintEvent(QPaintEvent *event) { + QPainter painter(lineNumberArea); + painter.fillRect(event->rect(), theme.background); + QTextBlock block = firstVisibleBlock(); + int blockNumber = block.blockNumber(); + int top = qRound(blockBoundingGeometry(block).translated(contentOffset()).top()); + int bottom = top + qRound(blockBoundingRect(block).height()); + + while (block.isValid() && top <= event->rect().bottom()) { + if (block.isVisible() && bottom >= event->rect().top()) { + painter.setPen(theme.lineNumberText); + painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), Qt::AlignRight, + QString::number(blockNumber + 1)); + } + + block = block.next(); + top = bottom; + bottom = top + qRound(blockBoundingRect(block).height()); + ++blockNumber; + } + } + + protected: + void resizeEvent(QResizeEvent *event) override { + QPlainTextEdit::resizeEvent(event); + const QRect contents = contentsRect(); + lineNumberArea->setGeometry(contents.left(), contents.top(), lineNumberAreaWidth(), + contents.height()); + } + + private: + void updateLineNumberAreaWidth(int) { setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } + + void updateLineNumberArea(const QRect &rect, int dy) { + if (dy) + lineNumberArea->scroll(0, dy); + else + lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); + + if (rect.contains(viewport()->rect())) + updateLineNumberAreaWidth(0); + } + + void highlightCurrentLine() { + QList selections; + QTextEdit::ExtraSelection selection; + selection.format.setBackground(theme.currentLine); + selection.format.setProperty(QTextFormat::FullWidthSelection, true); + selection.cursor = textCursor(); + selections.append(selection); + setExtraSelections(selections); + } + + QWidget *lineNumberArea; + EditorTheme theme; +}; + +class LineNumberArea final : public QWidget { + public: + explicit LineNumberArea(CodeEditor *editor) : QWidget(editor), editor(editor) {} + + QSize sizeHint() const override { return {editor->lineNumberAreaWidth(), 0}; } + + protected: + void paintEvent(QPaintEvent *event) override { editor->lineNumberAreaPaintEvent(event); } + + private: + CodeEditor *editor; +}; + +CodeEditor::CodeEditor(const EditorTheme &editorTheme, QWidget *parent) + : QPlainTextEdit(parent), theme(editorTheme) { + lineNumberArea = new LineNumberArea(this); + connect(this, &CodeEditor::blockCountChanged, this, &CodeEditor::updateLineNumberAreaWidth); + connect(this, &CodeEditor::updateRequest, this, &CodeEditor::updateLineNumberArea); + connect(this, &CodeEditor::cursorPositionChanged, this, &CodeEditor::highlightCurrentLine); + updateLineNumberAreaWidth(0); + highlightCurrentLine(); +} + QString SourceViewerDialog::contestantSourceFilePath(Contest *contest, Contestant *contestant, int taskIndex, int fileIndex) { const Task *task = contest->getTask(taskIndex); @@ -322,10 +433,26 @@ SourceViewerDialog::SourceViewerDialog(QWidget *parent, const QStringList &fileP } void SourceViewerDialog::addEditorTab(const QString &filePath) { - auto *editor = new QPlainTextEdit(tabWidget); + const EditorTheme theme = editorTheme(); + auto *editor = new CodeEditor(theme, tabWidget); editor->setReadOnly(true); editor->setLineWrapMode(QPlainTextEdit::NoWrap); - editor->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); + + QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont); + font.setPointSizeF(qMax(font.pointSizeF(), 10.5)); + editor->setFont(font); + editor->setTabStopDistance(4 * QFontMetricsF(font).horizontalAdvance(QLatin1Char(' '))); + + // Explicit editor colors: do not inherit the application's text color, which + // may be too dim against the editor background. A stylesheet is used because + // it takes precedence over the platform style's palette handling. + QPalette editorPalette = editor->palette(); + editorPalette.setColor(QPalette::Base, theme.background); + editorPalette.setColor(QPalette::Text, theme.text); + editor->setPalette(editorPalette); + editor->setStyleSheet( + QStringLiteral("QPlainTextEdit { background-color: %1; color: %2; selection-background-color: %3; }") + .arg(theme.background.name(), theme.text.name(), theme.selection.name())); QFile file(filePath); @@ -342,7 +469,7 @@ void SourceViewerDialog::addEditorTab(const QString &filePath) { editor->setPlainText(content); } - auto *highlighter = new SourceHighlighter(editor->document()); + auto *highlighter = new SourceHighlighter(editor->document(), theme); const QString suffix = QFileInfo(filePath).suffix().toLower(); highlighter->setLanguage(suffix == "pas" || suffix == "pp" || suffix == "dpr" ? Language::Pascal : Language::CLike); From b309db05f0cc9e56b4426f159898d6b519aa8077 Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Sun, 22 Nov 2026 17:52:34 +0800 Subject: [PATCH 04/11] feat(ui): use Microsoft YaHei for the source viewer CJK comments in contestant code rendered via an ugly bitmap fallback with the monospace system font; Microsoft YaHei keeps them crisp, with CJK-aware fallback families for other platforms. --- src/sourceviewer.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/sourceviewer.cpp b/src/sourceviewer.cpp index e9c54a00..6aca4701 100644 --- a/src/sourceviewer.cpp +++ b/src/sourceviewer.cpp @@ -16,7 +16,6 @@ #include #include #include -#include #include #include #include @@ -438,8 +437,12 @@ void SourceViewerDialog::addEditorTab(const QString &filePath) { editor->setReadOnly(true); editor->setLineWrapMode(QPlainTextEdit::NoWrap); - QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont); - font.setPointSizeF(qMax(font.pointSizeF(), 10.5)); + // Microsoft YaHei renders CJK comments in contestant code far better than + // the monospace system font, whose CJK glyphs fall back to an ugly bitmap face + QFont font; + font.setFamilies({QStringLiteral("Microsoft YaHei"), QStringLiteral("Microsoft JhengHei"), + QStringLiteral("PingFang SC"), QStringLiteral("Noto Sans CJK SC")}); + font.setPointSizeF(10.5); editor->setFont(font); editor->setTabStopDistance(4 * QFontMetricsF(font).horizontalAdvance(QLatin1Char(' '))); From d4b4c833d32541b29e0ab6b3d2f673f0f5a87f1c Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Sun, 22 Nov 2026 17:59:30 +0800 Subject: [PATCH 05/11] refactor(base): share the per-platform UI font in Lemon::uiFont() Extract the font setup previously inlined in main.cpp's #ifdef blocks into Lemon::uiFont(), activate the Linux (Noto Sans CJK SC) and macOS (PingFang SC) branches that had been left commented out, and let the source code viewer use the same font so CJK comments stay crisp on every platform. Missing families fall back to the platform default. --- src/base/LemonBase.hpp | 17 +++++++++++++++++ src/main.cpp | 13 +------------ src/sourceviewer.cpp | 10 +++++----- 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/src/base/LemonBase.hpp b/src/base/LemonBase.hpp index cd182c84..6bb9a924 100644 --- a/src/base/LemonBase.hpp +++ b/src/base/LemonBase.hpp @@ -9,6 +9,7 @@ // #include #include +#include #include #include @@ -22,6 +23,22 @@ #define LEMON_BUILD_EXTRA_INFO QString(LEMON_BUILD_EXTRA_INFO_STR) namespace Lemon { + // The CJK-capable UI font of the application, shared by the main window + // (main.cpp) and the source code viewer. Missing families fall back to the + // platform default font, so listing them unconditionally is safe. + inline QFont uiFont() { + QFont font; +#ifdef Q_OS_WIN32 + font.setFamilies({"Microsoft YaHei"}); + font.setHintingPreference(QFont::PreferNoHinting); +#elif defined(Q_OS_LINUX) + font.setFamilies({"Noto Sans CJK SC", "WenQuanYi Micro Hei"}); +#elif defined(Q_OS_MAC) + font.setFamilies({"PingFang SC"}); +#endif + return font; + } + inline QStringList LemonAssetsPaths(const QString &dirName) { #define makeAbs(p) QDir(p).absolutePath() // Configuration Path diff --git a/src/main.cpp b/src/main.cpp index 5e16fc7c..b120873f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -52,18 +52,7 @@ int main(int argc, char *argv[]) { return 0; } -#ifdef Q_OS_LINUX - // fonts.setFamily("Noto Sans CJK SC"); -#endif -#ifdef Q_OS_WIN32 - QFont fonts; - fonts.setFamily("Microsoft YaHei"); - fonts.setHintingPreference(QFont::PreferNoHinting); - SingleApplication::setFont(fonts); -#endif -#ifdef Q_OS_MAC - // fonts.setFamily("PingFangSC-Regular"); -#endif + SingleApplication::setFont(Lemon::uiFont()); Q_INIT_RESOURCE(resource); QPixmap pixmap(":/logo/splash2.png"); QSplashScreen screen(pixmap.scaled(450, 191, Qt::KeepAspectRatio, Qt::SmoothTransformation)); diff --git a/src/sourceviewer.cpp b/src/sourceviewer.cpp index 6aca4701..c41f7f30 100644 --- a/src/sourceviewer.cpp +++ b/src/sourceviewer.cpp @@ -7,6 +7,7 @@ #include "sourceviewer.h" // +#include "base/LemonBase.hpp" #include "base/settings.h" #include "core/contest.h" #include "core/contestant.h" @@ -437,11 +438,10 @@ void SourceViewerDialog::addEditorTab(const QString &filePath) { editor->setReadOnly(true); editor->setLineWrapMode(QPlainTextEdit::NoWrap); - // Microsoft YaHei renders CJK comments in contestant code far better than - // the monospace system font, whose CJK glyphs fall back to an ugly bitmap face - QFont font; - font.setFamilies({QStringLiteral("Microsoft YaHei"), QStringLiteral("Microsoft JhengHei"), - QStringLiteral("PingFang SC"), QStringLiteral("Noto Sans CJK SC")}); + // The application-wide CJK font renders CJK comments in contestant code far + // better than the monospace system font, whose CJK glyphs fall back to an + // ugly bitmap face + QFont font = Lemon::uiFont(); font.setPointSizeF(10.5); editor->setFont(font); editor->setTabStopDistance(4 * QFontMetricsF(font).horizontalAdvance(QLatin1Char(' '))); From 2bd3980099b322352e70eaed4fd2cbd3d01a2e6d Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Sun, 22 Nov 2026 19:08:23 +0800 Subject: [PATCH 06/11] chore: ignore local tooling directories .mimosa and .zcode --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 09aae68f..f26d0577 100644 --- a/.gitignore +++ b/.gitignore @@ -69,3 +69,7 @@ build-debug/ .idea/ cmake-build-debug/ .vscode/ + +# Local tooling +.mimosa +.zcode/ \ No newline at end of file From 0f74e3cd7a0cbf75dd9a2af520f4f5189ccd209b Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Mon, 23 Nov 2026 21:41:02 +0800 Subject: [PATCH 07/11] feat(ui): use a monospace font for the source viewer --- src/base/LemonBase.hpp | 17 +++++++++++++++++ src/sourceviewer.cpp | 7 +++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/base/LemonBase.hpp b/src/base/LemonBase.hpp index 6bb9a924..c6fa9289 100644 --- a/src/base/LemonBase.hpp +++ b/src/base/LemonBase.hpp @@ -39,6 +39,23 @@ namespace Lemon { return font; } + // Monospace font for code/program text. The first family is genuinely + // fixed-pitch and is followed by a CJK fallback so Chinese comments still + // render instead of falling back to tofu. Missing families fall back to + // the platform default monospaced font. + inline QFont codeFont() { + QFont font; +#ifdef Q_OS_WIN32 + font.setFamilies({"Consolas", "Microsoft YaHei"}); +#elif defined(Q_OS_LINUX) + font.setFamilies({"DejaVu Sans Mono", "Noto Sans Mono CJK SC"}); +#elif defined(Q_OS_MAC) + font.setFamilies({"Menlo", "PingFang SC"}); +#endif + font.setStyleHint(QFont::Monospace); + return font; + } + inline QStringList LemonAssetsPaths(const QString &dirName) { #define makeAbs(p) QDir(p).absolutePath() // Configuration Path diff --git a/src/sourceviewer.cpp b/src/sourceviewer.cpp index c41f7f30..effe7c15 100644 --- a/src/sourceviewer.cpp +++ b/src/sourceviewer.cpp @@ -438,10 +438,9 @@ void SourceViewerDialog::addEditorTab(const QString &filePath) { editor->setReadOnly(true); editor->setLineWrapMode(QPlainTextEdit::NoWrap); - // The application-wide CJK font renders CJK comments in contestant code far - // better than the monospace system font, whose CJK glyphs fall back to an - // ugly bitmap face - QFont font = Lemon::uiFont(); + // Use a fixed-pitch font so code columns align; the CJK fallback family + // keeps Chinese comments legible instead of showing tofu boxes + QFont font = Lemon::codeFont(); font.setPointSizeF(10.5); editor->setFont(font); editor->setTabStopDistance(4 * QFontMetricsF(font).horizontalAdvance(QLatin1Char(' '))); From 1a9293d25c9727780b28f0077db6824024401bee Mon Sep 17 00:00:00 2001 From: zhuyanyu1234 <2403098188@qq.com> Date: Tue, 24 Nov 2026 21:43:58 +0800 Subject: [PATCH 08/11] chore(gitignore): remove personal settings from .gitignore --- .gitignore | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.gitignore b/.gitignore index f26d0577..09aae68f 100644 --- a/.gitignore +++ b/.gitignore @@ -69,7 +69,3 @@ build-debug/ .idea/ cmake-build-debug/ .vscode/ - -# Local tooling -.mimosa -.zcode/ \ No newline at end of file From 73266a31eaae97cce8bdef6a3ddc53fe7ab10a8f Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Fri, 27 Nov 2026 17:10:58 +0800 Subject: [PATCH 09/11] refactor(ui): use system font fallback instead of hardcoded families --- src/base/LemonBase.hpp | 37 ++++++++++++------------------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/src/base/LemonBase.hpp b/src/base/LemonBase.hpp index c6fa9289..5036ddd8 100644 --- a/src/base/LemonBase.hpp +++ b/src/base/LemonBase.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -23,37 +24,23 @@ #define LEMON_BUILD_EXTRA_INFO QString(LEMON_BUILD_EXTRA_INFO_STR) namespace Lemon { - // The CJK-capable UI font of the application, shared by the main window - // (main.cpp) and the source code viewer. Missing families fall back to the - // platform default font, so listing them unconditionally is safe. + // The UI font follows the platform/user preference. No family is hard-coded: + // the system font fallback (Fontconfig on Linux, DirectWrite on Windows, + // Core Text on macOS) resolves the user's chosen font and supplies CJK + // glyphs automatically. inline QFont uiFont() { QFont font; -#ifdef Q_OS_WIN32 - font.setFamilies({"Microsoft YaHei"}); - font.setHintingPreference(QFont::PreferNoHinting); -#elif defined(Q_OS_LINUX) - font.setFamilies({"Noto Sans CJK SC", "WenQuanYi Micro Hei"}); -#elif defined(Q_OS_MAC) - font.setFamilies({"PingFang SC"}); -#endif + font.setStyleHint(QFont::System); return font; } - // Monospace font for code/program text. The first family is genuinely - // fixed-pitch and is followed by a CJK fallback so Chinese comments still - // render instead of falling back to tofu. Missing families fall back to - // the platform default monospaced font. + // Fixed-pitch font for program text. QFontDatabase::FixedFont asks the + // platform font database (Fontconfig on Linux, DirectWrite on Windows, + // Core Text on macOS) for the user's preferred monospaced font, without + // assuming any specific family name. CJK glyphs are handled by the + // platform's font fallback mechanism. inline QFont codeFont() { - QFont font; -#ifdef Q_OS_WIN32 - font.setFamilies({"Consolas", "Microsoft YaHei"}); -#elif defined(Q_OS_LINUX) - font.setFamilies({"DejaVu Sans Mono", "Noto Sans Mono CJK SC"}); -#elif defined(Q_OS_MAC) - font.setFamilies({"Menlo", "PingFang SC"}); -#endif - font.setStyleHint(QFont::Monospace); - return font; + return QFontDatabase::systemFont(QFontDatabase::FixedFont); } inline QStringList LemonAssetsPaths(const QString &dirName) { From 10b1e8e0c8a9a58d67e41f04d52f7e57ccd482e3 Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Fri, 27 Nov 2026 19:49:42 +0800 Subject: [PATCH 10/11] refactor(ui): open contestant sources in the system editor --- src/base/LemonBase.hpp | 10 - src/detaildialog.cpp | 2 +- src/resultviewer.cpp | 4 +- src/sourceviewer.cpp | 457 ++--------------------------------------- src/sourceviewer.h | 22 +- translations/zh_CN.ts | 6 +- translations/zh_TW.ts | 6 +- 7 files changed, 23 insertions(+), 484 deletions(-) diff --git a/src/base/LemonBase.hpp b/src/base/LemonBase.hpp index 5036ddd8..b5ca5e65 100644 --- a/src/base/LemonBase.hpp +++ b/src/base/LemonBase.hpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include @@ -34,15 +33,6 @@ namespace Lemon { return font; } - // Fixed-pitch font for program text. QFontDatabase::FixedFont asks the - // platform font database (Fontconfig on Linux, DirectWrite on Windows, - // Core Text on macOS) for the user's preferred monospaced font, without - // assuming any specific family name. CJK glyphs are handled by the - // platform's font fallback mechanism. - inline QFont codeFont() { - return QFontDatabase::systemFont(QFontDatabase::FixedFont); - } - inline QStringList LemonAssetsPaths(const QString &dirName) { #define makeAbs(p) QDir(p).absolutePath() // Configuration Path diff --git a/src/detaildialog.cpp b/src/detaildialog.cpp index e94183a1..da220d60 100644 --- a/src/detaildialog.cpp +++ b/src/detaildialog.cpp @@ -282,7 +282,7 @@ void DetailDialog::anchorClicked(const QUrl &url) { } if (list[0] == "Source") { - SourceViewerDialog::viewSource(this, contest, contestant, list[1].toInt()); + SourceViewer::viewSource(this, contest, contestant, list[1].toInt()); } if (list[0] == "Message") { diff --git a/src/resultviewer.cpp b/src/resultviewer.cpp index 19f8afd9..e36027d2 100644 --- a/src/resultviewer.cpp +++ b/src/resultviewer.cpp @@ -76,7 +76,7 @@ void ResultViewer::contextMenuEvent(QContextMenuEvent * /*event*/) { contextMenu->addAction(detailInformationAction); contextMenu->setDefaultAction(detailInformationAction); - // View the source code of the selected contestant (issue #225) + // Open the source code of the selected contestant (issue #225) const QList taskList = curContest->getTaskList(); QList sourceTaskIndices; @@ -468,5 +468,5 @@ void ResultViewer::viewSource(int taskIndex) { if (contestant == nullptr) return; - SourceViewerDialog::viewSource(this, curContest, contestant, taskIndex); + SourceViewer::viewSource(this, curContest, contestant, taskIndex); } diff --git a/src/sourceviewer.cpp b/src/sourceviewer.cpp index effe7c15..855a78fd 100644 --- a/src/sourceviewer.cpp +++ b/src/sourceviewer.cpp @@ -7,394 +7,29 @@ #include "sourceviewer.h" // -#include "base/LemonBase.hpp" #include "base/settings.h" #include "core/contest.h" #include "core/contestant.h" #include "core/task.h" // -#include +#include #include -#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include namespace { -enum class Language { CLike, Pascal }; - -// A self-contained color scheme so the viewer stays readable in both the -// application's light and dark themes (VS Code-inspired palettes). The -// editor's base/text colors are set explicitly instead of inheriting the -// application palette, which keeps identifiers, keywords and comments -// clearly apart on any theme. -struct EditorTheme { - QColor background; - QColor text; - QColor currentLine; - QColor selection; - QColor keyword; - QColor number; - QColor string; - QColor comment; - QColor preprocessor; - QColor lineNumberText; -}; - -EditorTheme editorTheme() { - const QPalette &palette = QApplication::palette(); - const bool darkTheme = palette.color(QPalette::WindowText).lightness() > - palette.color(QPalette::Window).lightness(); - - if (darkTheme) { - return {QColor(0x1e, 0x1e, 0x1e), QColor(0xd4, 0xd4, 0xd4), QColor(0x28, 0x2c, 0x34), - QColor(0x26, 0x4f, 0x78), QColor(0x56, 0x9c, 0xd6), QColor(0xb5, 0xce, 0xa8), - QColor(0xce, 0x91, 0x78), QColor(0x6a, 0x99, 0x55), QColor(0xc5, 0x86, 0xc0), - QColor(0x85, 0x85, 0x85)}; - } - - return {QColor(0xff, 0xff, 0xff), QColor(0x1e, 0x1e, 0x1e), QColor(0xf3, 0xf3, 0xf3), - QColor(0xad, 0xd6, 0xff), QColor(0x00, 0x00, 0xff), QColor(0x09, 0x86, 0x58), - QColor(0xa3, 0x15, 0x15), QColor(0x00, 0x80, 0x00), QColor(0xaf, 0x00, 0xdb), - QColor(0x76, 0x76, 0x76)}; -} - -QTextCharFormat makeFormat(const QColor &color) { - QTextCharFormat format; - format.setForeground(color); - return format; -} - -} // namespace - -class SourceHighlighter final : public QSyntaxHighlighter { - public: - explicit SourceHighlighter(QTextDocument *document, const EditorTheme &theme) - : QSyntaxHighlighter(document) { - keywordFormat = makeFormat(theme.keyword); - numberFormat = makeFormat(theme.number); - stringFormat = makeFormat(theme.string); - commentFormat = makeFormat(theme.comment); - preprocessorFormat = makeFormat(theme.preprocessor); - } - - void setLanguage(Language newLanguage) { language = newLanguage; } - - protected: - void highlightBlock(const QString &text) override { - const QSet &keywords = (language == Language::Pascal) ? pascalKeywords() : cKeywords(); - - int index = 0; - const int length = text.length(); - - // Continue a multi-line comment started in a previous block: 1 = /* */ or { }, 2 = (* *) - if (previousBlockState() == 1 || previousBlockState() == 2) { - const QString endMark = previousBlockState() == 1 - ? (language == Language::Pascal ? QStringLiteral("}") : QStringLiteral("*/")) - : QStringLiteral("*)"); - const int end = text.indexOf(endMark); - - if (end < 0) { - setFormat(0, length, commentFormat); - setCurrentBlockState(previousBlockState()); - return; - } - - setFormat(0, end + endMark.length(), commentFormat); - index = end + endMark.length(); - } - - const bool isPascal = language == Language::Pascal; - - while (index < length) { - const QChar current = text.at(index); - - // Line comments - if (current == QLatin1Char('/') && index + 1 < length && text.at(index + 1) == QLatin1Char('/')) { - setFormat(index, length - index, commentFormat); - break; - } - - // Multi-line comment starts - if (isPascal && current == QLatin1Char('{')) { - const int end = text.indexOf(QLatin1Char('}'), index + 1); - - if (end < 0) { - setFormat(index, length - index, commentFormat); - setCurrentBlockState(1); - break; - } - - setFormat(index, end - index + 1, commentFormat); - index = end + 1; - continue; - } - - if (isPascal && current == QLatin1Char('(') && index + 1 < length && - text.at(index + 1) == QLatin1Char('*')) { - const int end = text.indexOf(QLatin1String("*)"), index + 2); - - if (end < 0) { - setFormat(index, length - index, commentFormat); - setCurrentBlockState(2); - break; - } - - setFormat(index, end - index + 2, commentFormat); - index = end + 2; - continue; - } - - if (! isPascal && current == QLatin1Char('/') && index + 1 < length && - text.at(index + 1) == QLatin1Char('*')) { - const int end = text.indexOf(QLatin1String("*/"), index + 2); - - if (end < 0) { - setFormat(index, length - index, commentFormat); - setCurrentBlockState(1); - break; - } - - setFormat(index, end - index + 2, commentFormat); - index = end + 2; - continue; - } - - // Strings ('...' for Pascal, "..." and '...' for C-like) - if (current == QLatin1Char('"') || current == QLatin1Char('\'')) { - int end = index + 1; - - while (end < length) { - if (! isPascal && text.at(end) == QLatin1Char('\\')) { - end += 2; - continue; - } - - if (isPascal && text.at(end) == QLatin1Char('\'') && end + 1 < length && - text.at(end + 1) == QLatin1Char('\'')) { - end += 2; - continue; - } - - if (text.at(end) == current) { - ++end; - break; - } - - ++end; - } - - setFormat(index, qMin(end, length) - index, stringFormat); - index = qMin(end, length); - continue; - } - - // Numbers - if (current.isDigit()) { - int end = index + 1; - - while (end < length && (text.at(end).isDigit() || text.at(end) == QLatin1Char('.') || - (text.at(end).toLower() >= QLatin1Char('a') && - text.at(end).toLower() <= QLatin1Char('f')) || - text.at(end).toLower() == QLatin1Char('x') || - text.at(end).toLower() == QLatin1Char('u') || - text.at(end).toLower() == QLatin1Char('l'))) { - ++end; - } - - setFormat(index, end - index, numberFormat); - index = end; - continue; - } - - // Identifiers and keywords - if (current.isLetter() || current == QLatin1Char('_')) { - int end = index + 1; - - while (end < length && - (text.at(end).isLetterOrNumber() || text.at(end) == QLatin1Char('_'))) { - ++end; - } - - if (keywords.contains(text.mid(index, end - index))) - setFormat(index, end - index, keywordFormat); - - index = end; - continue; - } - - // Preprocessor directives (C-like, first non-whitespace of the line) - if (! isPascal && current == QLatin1Char('#')) { - int start = index; - - while (start > 0 && (text.at(start - 1) == QLatin1Char(' ') || - text.at(start - 1) == QLatin1Char('\t'))) { - --start; - } - - if (text.left(start).trimmed().isEmpty()) { - setFormat(index, length - index, preprocessorFormat); - break; - } - } - - ++index; - } - } - - private: - static const QSet &cKeywords() { - static const QSet keywords = { - "alignas", "alignof", "and", "asm", "auto", "bool", "break", "case", "catch", "char", - "char8_t", "char16_t", "char32_t", "class", "co_await", "co_return", "co_yield", "concept", - "const", "consteval", "constexpr", "constinit", "const_cast", "continue", "decltype", - "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", - "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "java", "long", - "mutable", "namespace", "new", "noexcept", "not", "nullptr", "operator", "override", - "private", "protected", "public", "register", "reinterpret_cast", "requires", "return", - "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", - "template", "this", "throw", "true", "try", "typedef", "typeid", "typename", "union", - "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "final", "package", - "implements", "import", "interface", "boolean", "extends"}; - return keywords; - } - - static const QSet &pascalKeywords() { - static const QSet keywords = { - "and", "array", "begin", "case", "const", "div", "do", "downto", "else", "end", "file", - "for", "function", "goto", "if", "in", "label", "mod", "nil", "not", "of", "or", - "procedure", "program", "record", "repeat", "set", "shl", "shr", "string", "then", "to", - "type", "until", "uses", "var", "while", "with", "xor", "boolean", "byte", "char", - "integer", "longint", "real", "word", "read", "readln", "write", "writeln"}; - return keywords; - } - - Language language = Language::CLike; - QTextCharFormat keywordFormat; - QTextCharFormat numberFormat; - QTextCharFormat stringFormat; - QTextCharFormat commentFormat; - QTextCharFormat preprocessorFormat; -}; - -class LineNumberArea; - -// A read-only code editor pane with a line-number gutter and a subtle -// current-line highlight. -class CodeEditor final : public QPlainTextEdit { - public: - CodeEditor(const EditorTheme &editorTheme, QWidget *parent = nullptr); - - int lineNumberAreaWidth() const { - int digits = 1; - - for (int max = qMax(1, blockCount()); max > 9; max /= 10) - ++digits; - - return 14 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits; - } - - void lineNumberAreaPaintEvent(QPaintEvent *event) { - QPainter painter(lineNumberArea); - painter.fillRect(event->rect(), theme.background); - QTextBlock block = firstVisibleBlock(); - int blockNumber = block.blockNumber(); - int top = qRound(blockBoundingGeometry(block).translated(contentOffset()).top()); - int bottom = top + qRound(blockBoundingRect(block).height()); - - while (block.isValid() && top <= event->rect().bottom()) { - if (block.isVisible() && bottom >= event->rect().top()) { - painter.setPen(theme.lineNumberText); - painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), Qt::AlignRight, - QString::number(blockNumber + 1)); - } - - block = block.next(); - top = bottom; - bottom = top + qRound(blockBoundingRect(block).height()); - ++blockNumber; - } - } - - protected: - void resizeEvent(QResizeEvent *event) override { - QPlainTextEdit::resizeEvent(event); - const QRect contents = contentsRect(); - lineNumberArea->setGeometry(contents.left(), contents.top(), lineNumberAreaWidth(), - contents.height()); - } - - private: - void updateLineNumberAreaWidth(int) { setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } - - void updateLineNumberArea(const QRect &rect, int dy) { - if (dy) - lineNumberArea->scroll(0, dy); - else - lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); - - if (rect.contains(viewport()->rect())) - updateLineNumberAreaWidth(0); - } - - void highlightCurrentLine() { - QList selections; - QTextEdit::ExtraSelection selection; - selection.format.setBackground(theme.currentLine); - selection.format.setProperty(QTextFormat::FullWidthSelection, true); - selection.cursor = textCursor(); - selections.append(selection); - setExtraSelections(selections); - } - - QWidget *lineNumberArea; - EditorTheme theme; -}; - -class LineNumberArea final : public QWidget { - public: - explicit LineNumberArea(CodeEditor *editor) : QWidget(editor), editor(editor) {} - - QSize sizeHint() const override { return {editor->lineNumberAreaWidth(), 0}; } - - protected: - void paintEvent(QPaintEvent *event) override { editor->lineNumberAreaPaintEvent(event); } - - private: - CodeEditor *editor; -}; - -CodeEditor::CodeEditor(const EditorTheme &editorTheme, QWidget *parent) - : QPlainTextEdit(parent), theme(editorTheme) { - lineNumberArea = new LineNumberArea(this); - connect(this, &CodeEditor::blockCountChanged, this, &CodeEditor::updateLineNumberAreaWidth); - connect(this, &CodeEditor::updateRequest, this, &CodeEditor::updateLineNumberArea); - connect(this, &CodeEditor::cursorPositionChanged, this, &CodeEditor::highlightCurrentLine); - updateLineNumberAreaWidth(0); - highlightCurrentLine(); -} - -QString SourceViewerDialog::contestantSourceFilePath(Contest *contest, Contestant *contestant, int taskIndex, - int fileIndex) { +// Resolve one submitted source file, mirroring TaskJudger's layout (including +// the sub-folder layout used by tasks with SubFolderCheck enabled). +QString contestantSourceFilePath(Contest *contest, Contestant *contestant, int taskIndex, int fileIndex) { const Task *task = contest->getTask(taskIndex); if (task == nullptr || task->getTaskType() == Task::AnswersOnly) return {}; // Communication tasks store a space-separated list of submitted files - const QStringList files = - contestant->getSourceFile(taskIndex).split(' ', Qt::SkipEmptyParts); + const QStringList files = contestant->getSourceFile(taskIndex).split(' ', Qt::SkipEmptyParts); if (fileIndex < 0 || fileIndex >= files.size()) return {}; @@ -413,75 +48,9 @@ QString SourceViewerDialog::contestantSourceFilePath(Contest *contest, Contestan return path; } -SourceViewerDialog::SourceViewerDialog(QWidget *parent, const QStringList &filePaths, const QString &heading) - : QDialog(parent) { - setModal(true); - setWindowTitle(heading); - resize(760, 560); - - auto *layout = new QVBoxLayout(this); - layout->setContentsMargins(8, 8, 8, 8); - - tabWidget = new QTabWidget(this); - layout->addWidget(tabWidget); - - if (filePaths.size() == 1) - tabWidget->tabBar()->hide(); - - for (const QString &filePath : filePaths) - addEditorTab(filePath); -} - -void SourceViewerDialog::addEditorTab(const QString &filePath) { - const EditorTheme theme = editorTheme(); - auto *editor = new CodeEditor(theme, tabWidget); - editor->setReadOnly(true); - editor->setLineWrapMode(QPlainTextEdit::NoWrap); - - // Use a fixed-pitch font so code columns align; the CJK fallback family - // keeps Chinese comments legible instead of showing tofu boxes - QFont font = Lemon::codeFont(); - font.setPointSizeF(10.5); - editor->setFont(font); - editor->setTabStopDistance(4 * QFontMetricsF(font).horizontalAdvance(QLatin1Char(' '))); - - // Explicit editor colors: do not inherit the application's text color, which - // may be too dim against the editor background. A stylesheet is used because - // it takes precedence over the platform style's palette handling. - QPalette editorPalette = editor->palette(); - editorPalette.setColor(QPalette::Base, theme.background); - editorPalette.setColor(QPalette::Text, theme.text); - editor->setPalette(editorPalette); - editor->setStyleSheet( - QStringLiteral("QPlainTextEdit { background-color: %1; color: %2; selection-background-color: %3; }") - .arg(theme.background.name(), theme.text.name(), theme.selection.name())); - - QFile file(filePath); - - if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { - const QByteArray data = file.readAll(); - QString content = QString::fromUtf8(data); - - // Fall back to the system's local encoding when the file is not valid UTF-8 - if (content.contains(QChar(0xfffd))) { - QStringDecoder decoder(QStringConverter::System); - content = decoder(data); - } - - editor->setPlainText(content); - } - - auto *highlighter = new SourceHighlighter(editor->document(), theme); - const QString suffix = QFileInfo(filePath).suffix().toLower(); - highlighter->setLanguage(suffix == "pas" || suffix == "pp" || suffix == "dpr" ? Language::Pascal - : Language::CLike); - highlighters.append(highlighter); - - tabWidget->addTab(editor, QFileInfo(filePath).fileName()); -} +} // namespace -void SourceViewerDialog::viewSource(QWidget *parent, Contest *contest, Contestant *contestant, int taskIndex) { - const Task *task = contest->getTask(taskIndex); +void SourceViewer::viewSource(QWidget *parent, Contest *contest, Contestant *contestant, int taskIndex) { QStringList filePaths; for (int i = 0;; i++) { @@ -493,21 +62,19 @@ void SourceViewerDialog::viewSource(QWidget *parent, Contest *contest, Contestan filePaths.append(path); } - if (filePaths.isEmpty() || task == nullptr) { + if (filePaths.isEmpty()) { QMessageBox::information(parent, tr("View Source"), tr("Cannot find the source file of this task.")); return; } for (const QString &path : filePaths) { - if (! QFile::exists(path)) { + if (! QFileInfo::exists(path)) { QMessageBox::information(parent, tr("View Source"), tr("Source file %1 does not exist.").arg(QDir::toNativeSeparators(path))); return; } } - const QString heading = - tr("Source Code: %1 - %2").arg(contestant->getContestantName(), task->getProblemTitle()); - SourceViewerDialog dialog(parent, filePaths, heading); - dialog.exec(); + for (const QString &path : filePaths) + QDesktopServices::openUrl(QUrl::fromLocalFile(QDir(path).absolutePath())); } diff --git a/src/sourceviewer.h b/src/sourceviewer.h index 2646e417..42e994e5 100644 --- a/src/sourceviewer.h +++ b/src/sourceviewer.h @@ -8,28 +8,18 @@ #pragma once // -#include -#include +#include class Contest; class Contestant; -class SourceHighlighter; -class QTabWidget; +class QWidget; -class SourceViewerDialog : public QDialog { +// Opens a contestant's submitted sources with the user's own editor via the +// platform file association, instead of embedding a syntax-highlighting viewer. +class SourceViewer final : public QObject { Q_OBJECT public: - /** Resolve the path of one submitted source file, mirroring TaskJudger's layout. */ - static QString contestantSourceFilePath(Contest *contest, Contestant *contestant, int taskIndex, - int fileIndex); - /** Resolve, load and display the source files of contestant's taskIndex-th task. */ + /** Open the source file(s) of the contestant's taskIndex-th task in the system editor. */ static void viewSource(QWidget *parent, Contest *contest, Contestant *contestant, int taskIndex); - - private: - explicit SourceViewerDialog(QWidget *parent, const QStringList &filePaths, const QString &heading); - void addEditorTab(const QString &filePath); - - QTabWidget *tabWidget{}; - QList highlighters; }; diff --git a/translations/zh_CN.ts b/translations/zh_CN.ts index a223a841..da35df85 100755 --- a/translations/zh_CN.ts +++ b/translations/zh_CN.ts @@ -2193,7 +2193,7 @@ Depends: - SourceViewerDialog + SourceViewer View Source 查看源代码 @@ -2206,10 +2206,6 @@ Depends: Source file %1 does not exist. 源文件 %1 不存在。 - - Source Code: %1 - %2 - 源代码:%1 - %2 - StatisticsBrowser diff --git a/translations/zh_TW.ts b/translations/zh_TW.ts index 0d2c6773..0585978e 100644 --- a/translations/zh_TW.ts +++ b/translations/zh_TW.ts @@ -2193,7 +2193,7 @@ Depends: - SourceViewerDialog + SourceViewer View Source 查看原始碼 @@ -2206,10 +2206,6 @@ Depends: Source file %1 does not exist. 原始碼檔案 %1 不存在。 - - Source Code: %1 - %2 - 原始碼:%1 - %2 - StatisticsBrowser From c4ae7c14d5c5519bcdb954d878ff55cbfabcb4bc Mon Sep 17 00:00:00 2001 From: zhuyanyu123 <14973542+zhuyanyu123@user.noreply.gitee.com> Date: Sat, 28 Nov 2026 18:34:26 +0800 Subject: [PATCH 11/11] fix(ui): resolve source paths from task config and drop unused font changes --- src/base/LemonBase.hpp | 11 -------- src/main.cpp | 13 +++++++++- src/sourceviewer.cpp | 57 +++++++++++++++++++++--------------------- 3 files changed, 41 insertions(+), 40 deletions(-) diff --git a/src/base/LemonBase.hpp b/src/base/LemonBase.hpp index b5ca5e65..cd182c84 100644 --- a/src/base/LemonBase.hpp +++ b/src/base/LemonBase.hpp @@ -9,7 +9,6 @@ // #include #include -#include #include #include @@ -23,16 +22,6 @@ #define LEMON_BUILD_EXTRA_INFO QString(LEMON_BUILD_EXTRA_INFO_STR) namespace Lemon { - // The UI font follows the platform/user preference. No family is hard-coded: - // the system font fallback (Fontconfig on Linux, DirectWrite on Windows, - // Core Text on macOS) resolves the user's chosen font and supplies CJK - // glyphs automatically. - inline QFont uiFont() { - QFont font; - font.setStyleHint(QFont::System); - return font; - } - inline QStringList LemonAssetsPaths(const QString &dirName) { #define makeAbs(p) QDir(p).absolutePath() // Configuration Path diff --git a/src/main.cpp b/src/main.cpp index b120873f..5e16fc7c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -52,7 +52,18 @@ int main(int argc, char *argv[]) { return 0; } - SingleApplication::setFont(Lemon::uiFont()); +#ifdef Q_OS_LINUX + // fonts.setFamily("Noto Sans CJK SC"); +#endif +#ifdef Q_OS_WIN32 + QFont fonts; + fonts.setFamily("Microsoft YaHei"); + fonts.setHintingPreference(QFont::PreferNoHinting); + SingleApplication::setFont(fonts); +#endif +#ifdef Q_OS_MAC + // fonts.setFamily("PingFangSC-Regular"); +#endif Q_INIT_RESOURCE(resource); QPixmap pixmap(":/logo/splash2.png"); QSplashScreen screen(pixmap.scaled(450, 191, Qt::KeepAspectRatio, Qt::SmoothTransformation)); diff --git a/src/sourceviewer.cpp b/src/sourceviewer.cpp index 855a78fd..36853970 100644 --- a/src/sourceviewer.cpp +++ b/src/sourceviewer.cpp @@ -20,46 +20,47 @@ namespace { -// Resolve one submitted source file, mirroring TaskJudger's layout (including -// the sub-folder layout used by tasks with SubFolderCheck enabled). -QString contestantSourceFilePath(Contest *contest, Contestant *contestant, int taskIndex, int fileIndex) { +// Mirror TaskJudger::traditionalTaskPrepare()'s layout: the contestant's +// source directory gains the task's source-file-name sub-folder only when +// SubFolderCheck is enabled. +QString contestantSourceDir(Contest *contest, Contestant *contestant, int taskIndex) { const Task *task = contest->getTask(taskIndex); - - if (task == nullptr || task->getTaskType() == Task::AnswersOnly) - return {}; - - // Communication tasks store a space-separated list of submitted files - const QStringList files = contestant->getSourceFile(taskIndex).split(' ', Qt::SkipEmptyParts); - - if (fileIndex < 0 || fileIndex >= files.size()) - return {}; - - const QString &fileName = files[fileIndex]; - - if (fileName.isEmpty()) - return {}; - - QString path = Settings::sourcePath() + contestant->getContestantName(); + QString dir = Settings::sourcePath() + contestant->getContestantName(); if (task->getSubFolderCheck()) - path += QDir::separator() + task->getSourceFileName(); + dir += QDir::separator() + task->getSourceFileName(); - path += QDir::separator() + fileName; - return path; + return dir; } } // namespace void SourceViewer::viewSource(QWidget *parent, Contest *contest, Contestant *contestant, int taskIndex) { - QStringList filePaths; + const Task *task = contest->getTask(taskIndex); - for (int i = 0;; i++) { - const QString path = contestantSourceFilePath(contest, contestant, taskIndex, i); + if (task == nullptr || task->getTaskType() == Task::AnswersOnly) { + QMessageBox::information(parent, tr("View Source"), tr("Cannot find the source file of this task.")); + return; + } + + const QString dir = contestantSourceDir(contest, contestant, taskIndex); - if (path.isEmpty()) - break; + // Communication tasks: getSourceFile() holds the compiled names (e.g. + // send.cpp), while getSourceFilesPath() holds the actual submitted files. + // Ordinary tasks: getSourceFile() is one complete file name, which must not + // be split on spaces. + QStringList fileNames; + + if (task->getTaskType() == Task::Communication || task->getTaskType() == Task::CommunicationExec) + fileNames = task->getSourceFilesPath(); + else + fileNames = {contestant->getSourceFile(taskIndex)}; + + QStringList filePaths; - filePaths.append(path); + for (const QString &fileName : fileNames) { + if (! fileName.isEmpty()) + filePaths.append(dir + QDir::separator() + fileName); } if (filePaths.isEmpty()) {