Skip to content

Conversation

@18202781743
Copy link
Contributor

@18202781743 18202781743 commented Jan 23, 2026

  1. Added isValidTextJsonValue helper function to validate JSON strings
  2. Integrated JSON validation in three locations: main editor window,
    OEM dialog, and CLI set command
  3. Prevent invalid JSON input from being processed by returning early
    with warning messages
  4. Maintain existing functionality for valid JSON inputs

Log: Fixed issue where invalid JSON could be entered in text fields

Influence:

  1. Test entering valid JSON in text fields - should work normally
  2. Test entering invalid JSON in text fields - should be rejected with
    warning
  3. Verify CLI set command rejects invalid JSON with appropriate error
    message
  4. Check that valid JSON with various structures (objects, arrays,
    strings) is accepted
  5. Test edge cases like empty strings, malformed JSON syntax
  6. Ensure existing functionality for non-text data types remains
    unaffected

fix: 为文本输入字段添加JSON验证

  1. 新增isValidTextJsonValue辅助函数用于验证JSON字符串
  2. 在三个位置集成了JSON验证:主编辑器窗口、OEM对话框和CLI设置命令
  3. 通过提前返回和警告消息防止处理无效的JSON输入
  4. 保持有效JSON输入的现有功能

Log: 修复了文本字段可能输入无效JSON的问题

Influence:

  1. 测试在文本字段中输入有效JSON - 应正常工作
  2. 测试在文本字段中输入无效JSON - 应被拒绝并显示警告
  3. 验证CLI设置命令拒绝无效JSON并显示适当的错误消息
  4. 检查各种结构(对象、数组、字符串)的有效JSON是否被接受
  5. 测试边缘情况,如空字符串、格式错误的JSON语法
  6. 确保非文本数据类型的现有功能不受影响

PMS: BUG-317315
Change-Id: Ifaf792b26b4bcb6c3c950e4ca2b0aad249c9ae4e

Summary by Sourcery

Add JSON validation for text-based configuration inputs to prevent processing invalid JSON values.

Bug Fixes:

  • Reject invalid JSON entered in text fields in the main editor and OEM dialog instead of attempting to process it.
  • Prevent the CLI set command from accepting invalid JSON text values, returning an error instead.

1. Added isValidTextJsonValue helper function to validate JSON strings
2. Integrated JSON validation in three locations: main editor window,
OEM dialog, and CLI set command
3. Prevent invalid JSON input from being processed by returning early
with warning messages
4. Maintain existing functionality for valid JSON inputs

Log: Fixed issue where invalid JSON could be entered in text fields

Influence:
1. Test entering valid JSON in text fields - should work normally
2. Test entering invalid JSON in text fields - should be rejected with
warning
3. Verify CLI set command rejects invalid JSON with appropriate error
message
4. Check that valid JSON with various structures (objects, arrays,
strings) is accepted
5. Test edge cases like empty strings, malformed JSON syntax
6. Ensure existing functionality for non-text data types remains
unaffected

fix: 为文本输入字段添加JSON验证

1. 新增isValidTextJsonValue辅助函数用于验证JSON字符串
2. 在三个位置集成了JSON验证:主编辑器窗口、OEM对话框和CLI设置命令
3. 通过提前返回和警告消息防止处理无效的JSON输入
4. 保持有效JSON输入的现有功能

Log: 修复了文本字段可能输入无效JSON的问题

Influence:
1. 测试在文本字段中输入有效JSON - 应正常工作
2. 测试在文本字段中输入无效JSON - 应被拒绝并显示警告
3. 验证CLI设置命令拒绝无效JSON并显示适当的错误消息
4. 检查各种结构(对象、数组、字符串)的有效JSON是否被接受
5. 测试边缘情况,如空字符串、格式错误的JSON语法
6. 确保非文本数据类型的现有功能不受影响

PMS: BUG-317315
Change-Id: Ifaf792b26b4bcb6c3c950e4ca2b0aad249c9ae4e
@18202781743 18202781743 requested review from BLumia and mhduiy January 23, 2026 10:28
@sourcery-ai
Copy link

sourcery-ai bot commented Jan 23, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adds centralized JSON validation for text-based configuration inputs and integrates it into the editor UI and CLI set command to prevent invalid JSON from being converted and stored.

Sequence diagram for JSON validation in main editor text field

sequenceDiagram
    actor User
    participant KeyContent
    participant DLineEdit
    participant Helper

    User->>DLineEdit: inputText
    User->>DLineEdit: editingFinished
    DLineEdit->>KeyContent: editingFinished signal
    KeyContent->>DLineEdit: lambda invoked
    DLineEdit->>Helper: isValidTextJsonValue(text)
    Helper-->>DLineEdit: bool isValid

    alt invalid json
        DLineEdit->>DLineEdit: qWarning invalid json value
        DLineEdit->>DLineEdit: return without emitting valueChanged
    else valid json
        DLineEdit->>KeyContent: clearFocus
        DLineEdit->>KeyContent: emit valueChanged(stringToQVariant(text))
    end
Loading

Sequence diagram for JSON validation in CLI set command

sequenceDiagram
    actor User
    participant CommandManager
    participant Helper
    participant ConfigManager

    User->>CommandManager: setCommand
    CommandManager->>CommandManager: parse arguments

    alt type is double
        CommandManager->>ConfigManager: setValue(key, value.toDouble())
        ConfigManager-->>CommandManager: result
        CommandManager-->>User: exit 0
    else type is text
        CommandManager->>Helper: isValidTextJsonValue(value)
        Helper-->>CommandManager: bool isValid
        alt invalid json
            CommandManager->>User: outpuSTDError not a valid json text
            CommandManager-->>User: exit 1
        else valid json
            CommandManager->>ConfigManager: setValue(key, stringToQVariant(value))
            ConfigManager-->>CommandManager: result
            CommandManager-->>User: exit 0
        end
    end
Loading

Updated class diagram for JSON validation helper integration

classDiagram
    class HelperFunctions {
        +static QVariant stringToQVariant(QString s)
        +static bool isValidTextJsonValue(QString s)
        +static QString qvariantToCmd(QVariant v)
    }

    class KeyContent {
        +void setBaseInfo(ConfigGetter getter, QString language)
        +void valueChanged(QVariant value)
    }

    class OEMDialog {
        +QWidget getItemWidget(ConfigGetter getter, DStandardItem item)
        +void treeItemChanged(DStandardItem item)
    }

    class CommandManager {
        +int setCommand()
        +void outpuSTDError(QString message)
    }

    class DLineEdit {
        +QString text()
        +void setText(QString text)
        +void setEnabled(bool enabled)
        +void clearFocus()
    }

    class ConfigManager {
        +void setValue(QString key, QVariant value)
    }

    HelperFunctions <.. KeyContent : uses
    HelperFunctions <.. OEMDialog : uses
    HelperFunctions <.. CommandManager : uses
    DLineEdit <.. KeyContent : uses
    DLineEdit <.. OEMDialog : uses
    ConfigManager <.. CommandManager : uses
Loading

File-Level Changes

Change Details Files
Introduce shared helper to validate JSON text input before converting to QVariant.
  • Add isValidTextJsonValue helper using QJsonDocument::fromJson with QJsonParseError to check JSON validity for QString input.
  • Keep existing stringToQVariant/qvariantToCmd behavior; validation is additive and only used at call sites that treat text as JSON.
dconfig-center/common/helper.hpp
Validate JSON in main editor text field before emitting valueChanged.
  • Wrap DLineEdit editingFinished handler with a validity check using isValidTextJsonValue on the current text.
  • On invalid JSON, log a warning with qWarning and return early without emitting valueChanged or converting via stringToQVariant.
  • On valid JSON, preserve existing behavior (clear focus and emit valueChanged with converted QVariant).
dconfig-center/dde-dconfig-editor/mainwindow.cpp
Validate JSON in OEM dialog text field before updating model and signaling changes.
  • Extend DLineEdit textChanged handler to call isValidTextJsonValue on incoming text.
  • On invalid JSON, log a warning and return early without updating the item data or triggering treeItemChanged.
  • On valid JSON, maintain existing flow: convert with stringToQVariant, set item data with ValueRole, and call treeItemChanged.
dconfig-center/dde-dconfig-editor/oemdialog.cpp
Enforce JSON validity for CLI set command when handling text values.
  • In CommandManager::setCommand, for non-boolean/non-number values, call isValidTextJsonValue on the input string before stringToQVariant conversion.
  • If validation fails, print an error to stderr indicating the value is not valid JSON text and exit with non-zero status code 1.
  • Preserve existing behavior for other types and for valid JSON strings.
dconfig-center/dde-dconfig/main.cpp

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@deepin-ci-robot
Copy link

deepin pr auto review

代码审查报告

整体评估

这段代码添加了一个 isValidTextJsonValue 函数用于验证 JSON 格式,并在多个地方调用该函数来确保输入的值是有效的 JSON 文本。这是一个很好的安全改进,可以防止无效的 JSON 值被处理。

代码审查

1. helper.hpp 中的 isValidTextJsonValue 函数

static bool isValidTextJsonValue(const QString &s)
{
    QJsonParseError error;
    QJsonDocument::fromJson(s.toUtf8(), &error);
    return error.error == QJsonParseError::NoError;
}

优点:

  • 简单直接地验证 JSON 格式
  • 使用 Qt 标准库的 JSON 解析器

改进建议:

  1. 性能优化: 每次调用都会进行完整的 JSON 解析,这在频繁调用的场景下可能影响性能。可以考虑添加缓存或仅在必要时验证。
  2. 空字符串处理: 当前实现将空字符串视为无效 JSON,但这可能是预期行为。如果需要支持空字符串,应明确处理。
  3. 错误信息: 函数只返回布尔值,不提供错误详情。在某些场景下,可能需要知道具体的错误原因。

2. mainwindow.cpp 中的使用

connect(widget, &DLineEdit::editingFinished, widget, [this, widget](){
    if (!isValidTextJsonValue(widget->text())) {
        qWarning() << "invalid json value" << widget->text();
        return;
    }
    widget->clearFocus();
    emit valueChanged(stringToQVariant(widget->text()));
});

改进建议:

  1. 用户体验: 当用户输入无效 JSON 时,只是打印警告而不提供任何用户反馈。应该考虑在 UI 上显示错误提示。
  2. 焦点处理: 当输入无效时,应该保持焦点在输入框上,而不是让用户离开。
  3. 验证时机: editingFinished 信号在失去焦点或按回车时触发。对于实时验证,可以考虑使用 textChanged 信号,但要注意性能影响。

3. oemdialog.cpp 中的使用

connect(widget, &DLineEdit::textChanged, widget, [this, item](const QString &text){
    if (!isValidTextJsonValue(text)) {
        qWarning() << "invalid json value" << text;
        return;
    }
    item->setData(stringToQVariant(text), ValueRole);
    treeItemChanged(item);
});

改进建议:

  1. 性能问题: 使用 textChanged 信号意味着每次击键都会验证 JSON,对于大型 JSON 输入可能会影响性能。
  2. 用户体验: 在用户输入过程中就验证可能会导致频繁的错误提示,影响用户体验。考虑使用防抖(debounce)技术或仅在特定条件下验证。
  3. 错误反馈: 同样缺少对用户的错误反馈机制。

4. main.cpp 中的使用

if (!isValidTextJsonValue(value)) {
    outpuSTDError(QString("the value:[%1] is not a valid json text.").arg(value));
    return 1;
}

优点:

  • 提供了清晰的错误信息
  • 正确处理错误情况并返回错误码

改进建议:

  1. 错误信息一致性: 错误消息格式与其他地方不一致,考虑统一错误消息格式。
  2. 错误处理: 返回错误码1是合理的,但确保调用者正确处理这个错误码。

安全性评估

  1. 输入验证: 添加了 JSON 验证是一个很好的安全实践,可以防止无效或恶意输入导致的问题。
  2. 错误处理: 错误情况被正确处理,不会导致程序崩溃。
  3. 潜在风险: 如果 stringToQVariant 函数本身不安全,即使验证了 JSON 格式,仍可能存在安全问题。建议审查该函数的实现。

综合建议

  1. 用户体验改进: 在 UI 场景中,添加用户可见的错误提示,而不仅仅是控制台警告。
  2. 性能优化: 对于频繁调用的场景,考虑优化 JSON 验证逻辑。
  3. 错误处理一致性: 统一不同场景下的错误处理方式和消息格式。
  4. 代码复用: 考虑将 JSON 验证和错误处理封装成一个更完整的组件,便于复用和维护。

示例改进代码

// helper.hpp
static bool isValidTextJsonValue(const QString &s, QString *errorMsg = nullptr)
{
    QJsonParseError error;
    QJsonDocument::fromJson(s.toUtf8(), &error);
    if (errorMsg && error.error != QJsonParseError::NoError) {
        *errorMsg = error.errorString();
    }
    return error.error == QJsonParseError::NoError;
}

// mainwindow.cpp
connect(widget, &DLineEdit::editingFinished, widget, [this, widget](){
    QString errorMsg;
    if (!isValidTextJsonValue(widget->text(), &errorMsg)) {
        qWarning() << "invalid json value:" << widget->text() << "Error:" << errorMsg;
        DDialog dialog(this);
        dialog.setTitle(tr("Invalid JSON"));
        dialog.setMessage(tr("The entered value is not a valid JSON: %1").arg(errorMsg));
        dialog.exec();
        return;
    }
    widget->clearFocus();
    emit valueChanged(stringToQVariant(widget->text()));
});

这些改进将提供更好的用户体验和更详细的错误信息,同时保持代码的简洁性和安全性。

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • In the UI handlers you only log invalid JSON with qWarning and then return, which means the user sees no feedback and the field keeps showing the invalid text but doesn’t apply; consider either resetting to the last valid value or showing an inline error/tooltip so users understand why their change was ignored.
  • The new isValidTextJsonValue helper treats only strictly valid JSON as acceptable (e.g., unquoted strings and empty input will be rejected); confirm this matches the intended semantics for these text fields, and if not, adjust the helper to allow those cases or normalize them (e.g., auto-wrapping plain text in quotes) before validation.
  • You now have JSON validation in several call sites plus stringToQVariant likely doing its own parsing; consider centralizing the parse-and-convert logic in one helper that can return an error state, so you avoid double-parsing and ensure consistent behavior between the GUI and CLI paths.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the UI handlers you only log invalid JSON with qWarning and then return, which means the user sees no feedback and the field keeps showing the invalid text but doesn’t apply; consider either resetting to the last valid value or showing an inline error/tooltip so users understand why their change was ignored.
- The new isValidTextJsonValue helper treats only strictly valid JSON as acceptable (e.g., unquoted strings and empty input will be rejected); confirm this matches the intended semantics for these text fields, and if not, adjust the helper to allow those cases or normalize them (e.g., auto-wrapping plain text in quotes) before validation.
- You now have JSON validation in several call sites plus stringToQVariant likely doing its own parsing; consider centralizing the parse-and-convert logic in one helper that can return an error state, so you avoid double-parsing and ensure consistent behavior between the GUI and CLI paths.

## Individual Comments

### Comment 1
<location> `dconfig-center/dde-dconfig-editor/mainwindow.cpp:724-726` </location>
<code_context>
         auto widget = new DLineEdit(this);
         widget->setEnabled(canWrite);
         connect(widget, &DLineEdit::editingFinished, widget, [this, widget](){
+            if (!isValidTextJsonValue(widget->text())) {
+                qWarning() << "invalid json value" << widget->text();
+                return;
+            }
</code_context>

<issue_to_address>
**suggestion:** Invalid JSON is only logged, with no in-UI feedback or rollback of the edited value.

Since you `return` after logging, the invalid JSON leaves the edit text and focus unchanged and never emits `valueChanged`, so from the user’s perspective the change just “does nothing.” If the goal is to reject bad input, please also provide visible feedback (e.g., revert to last valid value or show an error/invalid state) so the failure isn’t silent in the UI.

Suggested implementation:

```cpp
        auto widget = new DLineEdit(this);
        widget->setEnabled(canWrite);
        // track last valid value for rollback on invalid input
        widget->setProperty("lastValidText", widget->text());

        connect(widget, &DLineEdit::editingFinished, widget, [this, widget](){
            if (!isValidTextJsonValue(widget->text())) {
                qWarning() << "invalid json value" << widget->text();

                // revert to last valid value and select it to provide visible feedback
                const QString lastValidText = widget->property("lastValidText").toString();
                widget->setText(lastValidText);
                widget->selectAll();

                return;
            }

            // update last valid value on successful edit
            widget->setProperty("lastValidText", widget->text());

            widget->clearFocus();
            emit valueChanged(stringToQVariant(widget->text()));
        });

```

If the widget’s initial value is set elsewhere (e.g., `widget->setText(initialValue);`), it would be best to also call `widget->setProperty("lastValidText", widget->text());` immediately after that, so the first invalid edit correctly rolls back to the loaded value instead of an empty string.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 724 to +726
connect(widget, &DLineEdit::editingFinished, widget, [this, widget](){
if (!isValidTextJsonValue(widget->text())) {
qWarning() << "invalid json value" << widget->text();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Invalid JSON is only logged, with no in-UI feedback or rollback of the edited value.

Since you return after logging, the invalid JSON leaves the edit text and focus unchanged and never emits valueChanged, so from the user’s perspective the change just “does nothing.” If the goal is to reject bad input, please also provide visible feedback (e.g., revert to last valid value or show an error/invalid state) so the failure isn’t silent in the UI.

Suggested implementation:

        auto widget = new DLineEdit(this);
        widget->setEnabled(canWrite);
        // track last valid value for rollback on invalid input
        widget->setProperty("lastValidText", widget->text());

        connect(widget, &DLineEdit::editingFinished, widget, [this, widget](){
            if (!isValidTextJsonValue(widget->text())) {
                qWarning() << "invalid json value" << widget->text();

                // revert to last valid value and select it to provide visible feedback
                const QString lastValidText = widget->property("lastValidText").toString();
                widget->setText(lastValidText);
                widget->selectAll();

                return;
            }

            // update last valid value on successful edit
            widget->setProperty("lastValidText", widget->text());

            widget->clearFocus();
            emit valueChanged(stringToQVariant(widget->text()));
        });

If the widget’s initial value is set elsewhere (e.g., widget->setText(initialValue);), it would be best to also call widget->setProperty("lastValidText", widget->text()); immediately after that, so the first invalid edit correctly rolls back to the loaded value instead of an empty string.

@deepin-ci-robot
Copy link

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: 18202781743, BLumia, mhduiy

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@18202781743 18202781743 merged commit 528403c into linuxdeepin:master Jan 26, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants