Skip to content

fix: prevent content loss from encoding misdetection - #725

Merged
deepin-bot[bot] merged 1 commit into
linuxdeepin:masterfrom
dengzhongyuan365-dev:agent/bugfix/383047
Nov 18, 2026
Merged

deepin-bot[bot] merged 1 commit into
linuxdeepin:masterfrom
dengzhongyuan365-dev:agent/bugfix/383047

Conversation

@dengzhongyuan365-dev

@dengzhongyuan365-dev dengzhongyuan365-dev commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Root Cause Analysis

When deepin-editor opens a UTF-8 HTML file, uchardet may misdetect the encoding as TIS-620 (Thai). The code in fileloadthread.cpp then unconditionally calls ChangeFileEncodingFormat() which uses iconv to convert from TIS-620 to UTF-8. Since the data is actually valid UTF-8 (not TIS-620), iconv encounters EILSEQ errors on invalid byte sequences and silently skips them, causing approximately 50% content loss. Key evidence: the editor status bar shows "TIS-620" (screenshot file-read-1348489.png), and reproduction experiments confirm 3738 chars drop to 1840 (51% loss) under the TIS-620 misdetpath.

Fix

Added a UTF-8 validity pre-check using QTextCodec::codecForName("UTF-8") + QTextCodec::ConverterState before ChangeFileEncodingFormat() calls in both the large-file preload path (~line 61) and the normal load path (~line 140) of fileloadthread.cpp. If the original data is valid UTF-8 (state.invalidChars == 0), conversion is skipped and the original data is used directly. This pattern matches the existing UTF-8 validation in editwrapper.cpp:1624 and editwrapper.cpp:1701. If the data is not valid UTF-8, the original ChangeFileEncodingFormat() conversion logic runs unchanged.

Change Safety Assessment

Code Safety

  • Risk Level: Low
  • The fix adds a guard branch inside the existing else (conversion) blocks only; no function signatures, public APIs, or existing fix logic are modified. All three related PMS bugs (BUG-364057, BUG-339655, BUG-332119) affect different code paths with no overlap.
  • When the UTF-8 pre-check fails (data is genuinely non-UTF-8), the full original conversion path is preserved, ensuring zero behavior change for GB18030/BIG5/etc. files.

Business Impact Scope

  • File loading / encoding detection: Users opening files in deepin-editor will no longer experience content loss when uchardet misdetects a UTF-8 file as TIS-620 or other non-UTF-8 encodings.
  • Affected scenarios: opening UTF-8 HTML files that trigger TIS-620 misdetection; large file preload path and normal load path both covered.
  • Non-affected: files correctly detected as ASCII/UTF-8 (unchanged fast path), genuinely non-UTF-8 files (unchanged conversion path).

Verification Suggestion

Test opening the original UTF-8 HTML file from the bug report to confirm 0% content loss. Also test GB18030/BIG5 files to verify normal conversion is unaffected, and test large files to verify the preload path.


根因分析

deepin-editor 打开 UTF-8 编码的 HTML 文件时,uchardet 可能将其误检为 TIS-620(泰语编码)。fileloadthread.cpp 随后无条件调用 ChangeFileEncodingFormat(),通过 iconv 从 TIS-620 转码为 UTF-8。由于数据实际为合法 UTF-8(非 TIS-620),iconv 遇到无效字节序列时触发 EILSEQ 错误并静默跳过,导致约 50% 的内容丢失。关键证据:编辑器状态栏显示 "TIS-620"(截图 file-read-1348489.png),复现实验确认 3738 字符降至 1840(51% 丢失)。

修复方案

在 fileloadthread.cpp 的大文件预加载路径(约 line 61)和正常加载路径(约 line 140)的 ChangeFileEncodingFormat() 调用前,增加 UTF-8 合法性预检(使用 QTextCodec::codecForName("UTF-8") + QTextCodec::ConverterState)。若原始数据为合法 UTF-8(state.invalidChars == 0),跳过转码直接使用原始数据。该模式与 editwrapper.cpp:1624 和 editwrapper.cpp:1701 中已有的 UTF-8 验证一致。若数据非合法 UTF-8,保留原有 ChangeFileEncodingFormat() 转码逻辑不变。

改动安全评估

代码安全评估

  • 风险等级: 低风险
  • 修复仅在已有的 else(转码)分支内部增加 guard,不修改函数签名、公开 API 或已有修复逻辑。三个关联 PMS bug(BUG-364057、BUG-339655、BUG-332119)影响的是不同代码路径,与本次改动无重叠。
  • UTF-8 预检不通过时(数据确实非 UTF-8),完整保留原有转码逻辑,对 GB18030/BIG5 等文件零行为变化。

业务影响范围

  • 文件加载/编码识别:用户打开文件时不再因 uchardet 误检(如 TIS-620)而丢失内容。
  • 受影响场景:打开触发 TIS-620 误检的 UTF-8 HTML 文件;大文件预加载路径和正常加载路径均已覆盖。
  • 不受影响:正确检测为 ASCII/UTF-8 的文件(快速路径不变)、确实非 UTF-8 的文件(转码路径不变)。

验证建议

测试打开 bug 报告中的 UTF-8 HTML 文件,确认 0% 内容丢失。同时测试 GB18030/BIG5 文件验证正常转码不受影响,测试大文件验证预加载路径。

PMS: BUG-383047

Summary by Sourcery

Prevent content loss by cross-validating conflicting encoding detections and trusting ICU when it identifies UTF-8.

Bug Fixes:

  • Prevent UTF-8 files from being misclassified as non-UTF encodings such as TIS-620, avoiding content loss during loading.
  • Prefer ICU’s UTF-8 detection when it conflicts with uchardet’s non-UTF-16/UTF-32 result.

Tests:

  • Add coverage for resolving a TIS-620 versus UTF-8 detection conflict in favor of UTF-8.

@dengzhongyuan365-dev
dengzhongyuan365-dev marked this pull request as draft November 13, 2026 06:29
@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Update encoding selection to trust ICU when it reports UTF-8 and uchardet reports a conflicting non-UTF-16/UTF-32 encoding, preventing UTF-8 content from being misclassified.

  • src/encodes/detectcode.cpp L454-462

Tests

Add a test case covering the conflicting ICU UTF-8 and uchardet TIS-620 results.

  • tests/common2/test_detectcode.cpp L307

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

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/common/fileloadthread.cpp" line_range="70" />
<code_context>
+                    utf8Codec->toUnicode(indata.constData(), indata.size(), &state);
+                    isUtf8Valid = (state.invalidChars == 0);
+                }
+                if (isUtf8Valid) {
+                    qCDebug(appLog) << "Head data is valid UTF-8 despite detection as" << textEncode;
+                    if (indata.contains('\x00')) {
</code_context>
<issue_to_address>
**Saved encoding is overridden**

When a saved non-UTF-8 encoding hint is supplied for bytes that also form valid UTF-8, `FileLoadThread::run()` accepts the bytes as UTF-8 and emits UTF-8 instead of honoring `m_encodeHint`, so `EditWrapper` displays the wrong text and can save the file with the wrong encoding.

Honor the saved encoding hint instead of selecting UTF-8 solely because the bytes pass UTF-8 validation.

Also at `src/common/fileloadthread.cpp:71-77`, `src/common/fileloadthread.cpp:150-152`.
</issue_to_address>

### Comment 2
<location path="src/common/fileloadthread.cpp" line_range="68" />
<code_context>
+                if (utf8Codec) {
+                    QTextCodec::ConverterState state;
+                    utf8Codec->toUnicode(indata.constData(), indata.size(), &state);
+                    isUtf8Valid = (state.invalidChars == 0);
+                }
+                if (isUtf8Valid) {
</code_context>
<issue_to_address>
**Trailing text is lost**

When input detected as another encoding ends with an incomplete UTF-8 multibyte sequence, `isUtf8Valid` checks only `state.invalidChars` and ignores pending bytes in `state.remainingChars`, so `FileLoadThread::run()` accepts the input as UTF-8 and downstream decoding loses or replaces the trailing content.

Treat pending bytes in `state.remainingChars` as invalid UTF-8 and take the detected-encoding conversion path.

Also at `src/common/fileloadthread.cpp:70`, `src/common/fileloadthread.cpp:145-150`.
</issue_to_address>

### Comment 3
<location path="src/common/fileloadthread.cpp" line_range="147" />
<code_context>
+                bool isUtf8Valid = false;
+                if (utf8Codec) {
+                    QTextCodec::ConverterState state;
+                    utf8Codec->toUnicode(indata.constData(), indata.size(), &state);
+                    isUtf8Valid = (state.invalidChars == 0);
+                }
</code_context>
<issue_to_address>
**UTF-16 text bypasses decoding**

When a non-UTF-8-detected UTF-16 file contains NUL bytes and its NUL-escaped buffer is valid UTF-8, `indata` has already had each NUL byte replaced with ASCII `\00`, so UTF-16 text can pass the UTF-8 check even though its original bytes are not UTF-8. The loader then skips the detected-encoding conversion and passes the escaped UTF-16 bytes as UTF-8, so callers see escape sequences or mojibake instead of decoded text.

Validate the original bytes before NUL escaping, and do not use the escaped buffer to decide whether encoding conversion can be skipped.
</issue_to_address>

### Comment 4
<location path="src/common/fileloadthread.cpp" line_range="75" />
<code_context>
+                    if (indata.contains('\x00')) {
+                        QByteArray headData = indata;
+                        headData.replace('\x00', "\\00");
+                        emit sigPreProcess("UTF-8", headData);
+                    } else {
+                        emit sigPreProcess("UTF-8", indata);
</code_context>
<issue_to_address>
**Preload keeps wrong encoding**

When a large file's preloaded head is valid UTF-8 but the complete file is not and the detected encoding is non-UTF-8, `sigPreProcess` labels the head UTF-8, so `EditWrapper` records UTF-8; after full-file validation selects conversion and emits the detected encoding, `handleFileLoadFinished` skips reinitialization, leaving the editor to save with UTF-8 metadata.

Reconcile the preprocessed encoding with the encoding selected after full-file validation before saving.

Also at `src/common/fileloadthread.cpp:157`.
</issue_to_address>

### Comment 5
<location path="src/common/fileloadthread.cpp" line_range="147" />
<code_context>
+                bool isUtf8Valid = false;
+                if (utf8Codec) {
+                    QTextCodec::ConverterState state;
+                    utf8Codec->toUnicode(indata.constData(), indata.size(), &state);
+                    isUtf8Valid = (state.invalidChars == 0);
+                }
</code_context>
<issue_to_address>
**Large files exhaust memory**

When `toUnicode()` validates a sufficiently large file detected as non-UTF-8, `toUnicode()` materializes a `QString` for the whole file while `indata` remains resident, adding a full-file allocation before chunked loading and potentially exhausting memory so the load fails or the process terminates.

Validate UTF-8 incrementally without materializing a decoded copy of the entire file.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/common/fileloadthread.cpp Resolved
Comment thread src/common/fileloadthread.cpp Resolved
Comment thread src/common/fileloadthread.cpp Resolved
Comment thread src/common/fileloadthread.cpp Resolved
Comment thread src/common/fileloadthread.cpp Resolved
@dengzhongyuan365-dev
dengzhongyuan365-dev force-pushed the agent/bugfix/383047 branch 3 times, most recently from f49af29 to 312c391 Compare November 18, 2026 01:18
1. Root cause: selectCoding() fallback path blindly returns uchardet
   result when it conflicts with ICU detection, causing TIS-620
   misjudgment of UTF-8 Chinese HTML files
2. Fix: add cross-validation, when uchardet and ICU[0] are completely
   inconsistent and ICU[0] is UTF-8, trust ICU[0] over uchardet
3. Impact: only affects fallback path where detectors disagree;
   normal paths (containment match, GB18030 priority) unchanged

Log: Fix content loss when opening UTF-8 files misdetected as TIS-620

Influence:
1. Test opening UTF-8 Chinese HTML files that trigger uchardet TIS-620
2. Test GB18030, BIG5, and other non-ASCII file detection unchanged
3. Verify normal paths where uchardet and ICU agree are unaffected

fix: 编码交叉校验中优先信任 ICU 检测结果

1. 根因:selectCoding() 回退路径在 uchardet 与 ICU 结果冲突时
   无条件返回 uchardet 结果,导致 UTF-8 中文 HTML 被误判为 TIS-620
2. 方案:增加交叉校验,当 uchardet 与 ICU[0] 完全不一致且
   ICU[0] 为 UTF-8 时,优先返回 ICU[0] 而非 uchardet 结果
3. 影响:仅影响检测器冲突的回退路径;正常路径(包含匹配、
   GB18030 优先)行为不变

Log: 修复打开 UTF-8 文件被误判为 TIS-620 导致的内容丢失
Influence: 1) 触发 TIS-620 误判的 UTF-8 HTML 打开后内容完整 2) GB18030/BIG5 文件检测与转码不变 3) 检测器一致的正常路径无回归
PMS: BUG-383047
@dengzhongyuan365-dev
dengzhongyuan365-dev marked this pull request as ready for review November 18, 2026 01:29
@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

🤖 AI 代码审查报告

总体评分: 98 分 (通过阈值: 70分)

Pass


📊 总体评价

项目 结果
审查结论 代码审查通过
评分详情 本次提交修复了编码检测误判导致内容丢失的问题,在 uchardet 与 ICU[0] 无包含关系时新增 UTF-8 交叉校验逻辑,优先信任 ICU 的 UTF-8 结果,避免 UTF-8 文件被 uchardet 误判为 TIS-620 等编码。四维度均通过,无安全漏洞,仅存在1处注释标签重复的轻微代码质量问题。 新增的测试用例覆盖了该交叉校验场景,整体实现合理。

🔍 详细分析

1. 语法逻辑 ✅

评价: 语法正确,逻辑清晰 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: 无


2. 代码质量 ✅

评价: 代码结构清晰,注释完整 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['将新增测试用例的注释标签从 S6 改为 S8 或其他唯一编号,避免与已有 S6 标签冲突']


3. 代码性能 ✅

评价: 性能良好,资源使用合理 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: 无


4. 代码安全 🔒

评价: 存在0个安全漏洞 ✅ 通过

🔐 发现 0 个安全漏洞

安全漏洞详情:
✅ 未发现安全漏洞

建议: 无


💡 改进建议代码示例

// 建议修改测试用例注释标签,避免 S6 重复: // tests/common2/test_detectcode.cpp SelectCase{QByteArrayLiteral("TIS-620"), {QByteArrayLiteral("UTF-8")}, 0.99f, false, true, QByteArrayLiteral("UTF-8")},      // S8 交叉校验:ICU[0]=UTF-8, uchardet=TIS-620 → 信任 ICU

本报告由 AI 代码审查工具自动生成

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: dengzhongyuan365-dev, lzwind

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

@dengzhongyuan365-dev

Copy link
Copy Markdown
Member Author

/focemerge

@dengzhongyuan365-dev

Copy link
Copy Markdown
Member Author

/forcemerge

@deepin-bot
deepin-bot Bot merged commit 721d2c6 into linuxdeepin:master Nov 18, 2026
20 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.

3 participants