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 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/component/exportutil/exportutil.cpp b/src/component/exportutil/exportutil.cpp index 3b92e4be..05aac62a 100644 --- a/src/component/exportutil/exportutil.cpp +++ b/src/component/exportutil/exportutil.cpp @@ -235,7 +235,6 @@ auto ExportUtil::getContestantHtmlCode(Contest *contest, Contestant *contestant, htmlCode += "

"; } - htmlCode += QString("

%1

").arg(tr("Return to top")); return htmlCode; } /* @@ -269,7 +268,7 @@ void ExportUtil::writeHtml(QTextStream &out, Contest *contest) { out << R"()"; // Style sheet - out << ""; + // The popup helper is emitted in so that it is already defined while + // the rest of a large (tens of MB) document is still parsing; everything it + // touches at call time (style sheet, templates, body dataset) is looked up + // lazily. Clicking a link before the per-contestant templates have been + // parsed shows a "still loading" alert instead of doing nothing silently. + out << R"LEMONJS( + + )LEMONJS"; + out << "" << contest->getContestTitle().toHtmlEscaped() << " : " << tr("Contest Result") << ""; - out << ""; + out << QString(R"()") + .arg(tr("The browser blocked the popup window. Please allow popups for this page and try again.") + .toHtmlEscaped(), + tr("The details are still loading. Please try again in a moment.") + .toHtmlEscaped()); out << "

"; out << "" << contest->getContestTitle().toHtmlEscaped() << " : " << tr("Rank List") << "

"; - out << "

" << tr("Click names or task scores to jump to details. Judged By LemonLime") << "

"; + out << "

" + << tr("Click names or task scores to view details in a popup window. Judged By LemonLime") << "

"; out << R"(

)"; out << QString(R"()").arg(tr("Rank")); out << QString(R"()").arg(tr("Name")); @@ -314,7 +372,7 @@ void ExportUtil::writeHtml(QTextStream &out, Contest *contest) { for (const auto &[contestant, allScore, sourceIndex, rank] : rankContestants(contestantList)) { out << ""; out << QString("").arg(rank); - out << QString(R"()") + out << QString(R"LEMON()LEMON") .arg(sourceIndex) .arg(contestant->getContestantName().toHtmlEscaped()); @@ -368,7 +426,7 @@ void ExportUtil::writeHtml(QTextStream &out, Contest *contest) { h *= 360, s *= 100, l *= 100; out << QString( - R"()") + R"LEMON()LEMON") .arg(score) .arg(h) .arg(s) @@ -376,7 +434,7 @@ void ExportUtil::writeHtml(QTextStream &out, Contest *contest) { .arg(sourceIndex) .arg(j); } else { - out << QString(R"()") + out << QString(R"LEMON()LEMON") .arg(tr("Invalid")) .arg(sourceIndex) .arg(j); @@ -387,25 +445,20 @@ void ExportUtil::writeHtml(QTextStream &out, Contest *contest) { out << "
%1%1
%1%2%2%1%1%1%1

"; + // Contestant details are stored as text templates instead of DOM nodes, so that + // browsers only render the details actually opened in a popup window (#235) for (int i = 0; i < contestantList.size(); i++) { - out << QString("
").arg(i) << ""; + out << QString(R"("; } out << QString(R"(

Lemonlime Version %1:%2

)") .arg(LEMON_VERSION_STRING) .arg(LEMON_VERSION_BUILD); - out << R"( - - )"; out << ""; out << ""; } @@ -431,7 +484,7 @@ auto ExportUtil::getSmallerContestantHtmlCode(Contest *contest, Contestant *cont if (contestant->getCompileState(i) != CompileSuccessfully) { switch (contestant->getCompileState(i)) { case NoValidGraderFile: - htmlCode += QString("  %1

") + htmlCode += QString("  %1

") .arg(tr("Main grader (grader.*) cannot be found")); break; @@ -567,7 +620,6 @@ auto ExportUtil::getSmallerContestantHtmlCode(Contest *contest, Contestant *cont htmlCode += "

"; } - htmlCode += QString("

%1

").arg(tr("Return to top")); return htmlCode; } @@ -592,20 +644,59 @@ void ExportUtil::writeSmallerHtml(QTextStream &out, Contest *contest) { QList taskList = contest->getTaskList(); out << ""; out << R"()"; - out << ""; + + // Same rationale as in writeHtml(): define the popup helper in + out << R"LEMONJS( + + )LEMONJS"; + out << "" << contest->getContestTitle().toHtmlEscaped() << " : " << tr("Contest Result") << ""; - out << ""; + out << QString(R"()") + .arg(tr("The browser blocked the popup window. Please allow popups for this page and try again.") + .toHtmlEscaped(), + tr("The details are still loading. Please try again in a moment.") + .toHtmlEscaped()); out << "

"; out << "" << contest->getContestTitle().toHtmlEscaped() << " : " << tr("Rank List") << "

"; - out << "

" << tr("Judged By LemonLime") << "

"; + out << "

" + << tr("Click names to view details in a popup window. Judged By LemonLime") << "

"; out << R"(

)"; out << QString("").arg(tr("Rank")); out << QString("").arg(tr("Name")); @@ -617,7 +708,7 @@ void ExportUtil::writeSmallerHtml(QTextStream &out, Contest *contest) { out << QString(""); for (const auto &[contestant, allScore, sourceIndex, rank] : rankContestants(contestantList)) { out << QString("").arg(rank); - out << QString("") + out << QString(R"LEMON()LEMON") .arg(sourceIndex) .arg(contestant->getContestantName().toHtmlEscaped()); @@ -640,10 +731,14 @@ void ExportUtil::writeSmallerHtml(QTextStream &out, Contest *contest) { out << "
%1%1
%1%2%2

"; + // Contestant details are stored as text templates instead of DOM nodes, so that + // browsers only render the details actually opened in a popup window (#235) for (int i = 0; i < contestantList.size(); i++) { - out << QString("
").arg(i) << ""; + out << QString(R"("; } out << ""; 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/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/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..c41f7f30 --- /dev/null +++ b/src/sourceviewer.cpp @@ -0,0 +1,514 @@ +/* + * SPDX-FileCopyrightText: 2026 Project LemonLime + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#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 + +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) { + 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) { + const EditorTheme theme = editorTheme(); + auto *editor = new CodeEditor(theme, tabWidget); + 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(); + 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()); +} + +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/tests/export-util/main.cpp b/tests/export-util/main.cpp index 36fd049f..52cab583 100644 --- a/tests/export-util/main.cpp +++ b/tests/export-util/main.cpp @@ -209,7 +209,7 @@ class ExportUtilTests : public QObject { const QString html = render(rankedContest, smaller); const QRegularExpression rankAndName( - "]*>(\\d+)]*>]*>([^<]+)"); + "]*>(\\d+)]*>]*>([^<]+)"); QList rows; for (const auto &match : rankAndName.globalMatch(html)) rows.append(match.capturedTexts().mid(1)); @@ -218,11 +218,30 @@ class ExportUtilTests : public QObject { {"1", "1", "Bea"}, {"1", "2", "Cal"}, {"3", "0", "Amy"}, {"4", "3", "Dee"}, {"4", "4", "Eve"}}; QCOMPARE(rows, expected); if (! smaller) { - QVERIFY(html.contains("href=\"#c1p0\" class=\"a-0\">100")); + QVERIFY(html.contains("onclick=\"return lemonOpenDetail(1,0)\" class=\"a-0\">100")); QVERIFY(html.contains("Contestant: Bea
")); } } + void scriptTagInjection_data() { addFormats(); } + + void scriptTagInjection() { + QFETCH(bool, smaller); + Contest injectedContest; + injectedContest.setSettings(&settings); + loadContestants(injectedContest, {"alert(1)//"}); + Task task; + task.addTestCase(testCase.get()); + injectedContest.addTask(&task); + + const QString html = render(injectedContest, smaller); + // The escaped contestant name must never terminate a text/template block early: + // exactly one template close and one export script close are expected. + QCOMPARE(html.count(""), 2); + QVERIFY(html.contains("</script>alert(1)//")); + QVERIFY(html.contains("onclick=\"return lemonOpenDetail(")); + } + void fullExport_data() { addFormats(); } void fullExport() { @@ -245,7 +264,11 @@ class ExportUtilTests : public QObject { QCOMPARE(html.count("contestant" + escapedText), 2); QCOMPARE(html.count("task" + escapedText), 2); QVERIFY(! html.contains(")")); + QVERIFY(html.contains("lemon-style")); } }; diff --git a/translations/zh_CN.ts b/translations/zh_CN.ts index 0388869f..6a0e9d41 100755 --- a/translations/zh_CN.ts +++ b/translations/zh_CN.ts @@ -839,8 +839,20 @@ 排名表 - Click names or task scores to jump to details. Judged By LemonLime - 点击名字或单题分数跳转到详细信息。使用 LemonLime 评测 + Click names or task scores to view details in a popup window. Judged By LemonLime + 点击名字或单题分数在弹出窗口中查看详细信息。使用 LemonLime 评测 + + + Click names to view details in a popup window. Judged By LemonLime + 点击名字在弹出窗口中查看详细信息。使用 LemonLime 评测 + + + The browser blocked the popup window. Please allow popups for this page and try again. + 浏览器拦截了弹出窗口,请允许此页面弹窗后重试。 + + + The details are still loading. Please try again in a moment. + 详情仍在加载中,请稍候重试。 Rank @@ -2074,6 +2086,10 @@ Depends: Details 详情 + + View Source + 查看源代码 + Judge 测试 @@ -2188,6 +2204,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..1590bc83 100644 --- a/translations/zh_TW.ts +++ b/translations/zh_TW.ts @@ -839,8 +839,20 @@ 排名表 - Click names or task scores to jump to details. Judged By LemonLime - 點選名稱或單題分數跳轉到詳細資訊。使用 LemonLime 評測 + Click names or task scores to view details in a popup window. Judged By LemonLime + 點選名稱或單題分數在彈出視窗中檢視詳細資訊。使用 LemonLime 評測 + + + Click names to view details in a popup window. Judged By LemonLime + 點選名稱在彈出視窗中檢視詳細資訊。使用 LemonLime 評測 + + + The browser blocked the popup window. Please allow popups for this page and try again. + 瀏覽器攔截了彈出視窗,請允許此頁面彈窗後重試。 + + + The details are still loading. Please try again in a moment. + 詳情仍在載入中,請稍候重試。 Rank @@ -2074,6 +2086,10 @@ Depends: Details 詳情 + + View Source + 查看原始碼 + Judge 測試 @@ -2188,6 +2204,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 diff --git a/unix/test/scripts/redirect.py b/unix/test/scripts/redirect.py index 63979c53..67d6ed47 100644 --- a/unix/test/scripts/redirect.py +++ b/unix/test/scripts/redirect.py @@ -1,22 +1,18 @@ import subprocess -import os import time +from pathlib import Path -pid = os.getpid() -tmpin = f"_tmpin_{pid}" -tmpout = f"_tmpout_{pid}" -tmperr = f"_tmperr_{pid}" +Path("tmpin.txt").write_text("1 1") -with open(tmpin, 'w') as f: - f.writelines(['1 1']) - -p = subprocess.Popen(["./watcher_unix", "./add", "", tmpin, tmpout, tmperr, "1000", "100", "1000", "100", "", "", "0"], shell=False) +p = subprocess.Popen(["./watcher_unix", "./add", "", "tmpin.txt", "tmpout.txt", "tmperr.txt", "1000", "100", "1000", "100", "", "", "0"], shell=False) time.sleep(2) p.kill() assert(p.returncode == 0) -assert(os.path.exists(tmpout)) -with open(tmpout, 'r') as f: - assert(f.read() == "2\n") +assert(Path("tmpout.txt").exists()) +assert(Path("tmpout.txt").read_text() == "2\n") + +for name in ("tmpin.txt", "tmpout.txt", "tmperr.txt"): + Path(name).unlink(missing_ok=True)