Skip to content

feat(translation): panel-only bilingual results, visual line grouping, flag language switcher - #83

Merged
hubo1989 merged 3 commits into
mainfrom
hubo/translate-improve
Oct 27, 2026
Merged

hubo1989 merged 3 commits into
mainfrom
hubo/translate-improve

Conversation

@hubo1989

Copy link
Copy Markdown
Owner

变更

结果展示重构(按实测反馈迭代)

  • 撤除原位双语覆盖层:密集文字下覆盖原文不可读,译文现在只在右侧结果面板显示,画布保持干净原图,标注工具可随时使用
  • 目标语言国旗横排:下拉改为 🇨🇳🇬🇧🇯🇵🇰🇷🇫🇷🇩🇪🇪🇸🇷🇺 一键切换(已实测 macOS 渲染真彩国旗),切换即重译
  • 三键复制:复制原文 / 复制译文 / 复制全部(原文译文交替,与面板显示一致);OCR 模式保留单键
  • 截屏覆盖层面板与预览窗口面板行为一致

视觉行聚合

  • 送译前将同一视觉行的 OCR/VLM 碎片合并(Y 重叠 ≥50%、横向间距 <3× 行高),行内代码(如 main、DESIGMA_PLUGINS_TOKEN)不再被孤立错译,每个视觉行一个翻译单元与面板行锚点

引擎健壮性(评审遗留跟进)

  • MTranServer 连接预检与状态修复;TranslationEngineRegistry 临时 Provider、基于 mutation revision/creation token 的缓存失效
  • LLM 批量分段与防御性响应解析(截断/坏 JSON);OpenAI/Claude VLM 续写安全;超大图分块分析;文本插入安全

测试

  • 全量 246 项通过(新增:视觉行聚合 16 项、国旗映射、面板像素不被遮挡回归)
  • MTran 取消时序用例偶发抖动,单独复跑通过,与本次改动无关

影响

  • 删除 BilingualOverlayView 及 4 个废弃本地化 key;新增 2 个复制 key
  • 翻译引擎接口无签名变更

…ad safety

- MTranServer: connection precheck (verifyConnection) and state fixes
- TranslationEngineRegistry: temporary providers, cache invalidation via
  mutation revisions and creation tokens
- LLM providers: segment batching and defensive response parsing
  (truncation, malformed JSON) with continuation safety for OpenAI/Claude
- ScreenCoder: tile oversized analysis images; SmartPrivacyRedaction tweaks
- TextInsertionTarget/TextInsertService/TextSelectionService: safer insertion
- Settings/EngineConfigSheet: expose new verification options
…d flag switcher

- Merge same-line OCR/VLM fragments before translation (VisualLineGrouping):
  inline code translates in context and each visual line becomes one unit
- Remove in-image bilingual overlay (unreadable on dense text, obscured the
  original); translations render only in the side panel so the canvas stays
  clean for reading and annotating
- Replace target-language dropdown with a one-click flag row (English = GB);
  switching immediately re-runs the translation
- Add copy original / copy translation / copy all buttons to both panels;
  OCR mode keeps the single copy button
- Regression tests: line grouping (16), panel pixels untouched, flag mapping
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-27T11:43:08.595530Z
We couldn’t complete this review. Comment @codex review to try again.
b414786 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7638514c-9a9c-4686-be18-2fb4a70e5cb5
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

🔍 OpenCodeReview found 28 issue(s) in this PR.

  • ✅ Successfully posted inline: 28 comment(s)

Comment on lines +180 to +182
private func languageFlagButton(for language: TranslationLanguage) -> some View {
let isSelected = AppSettings.shared.translationTargetLanguage == language
return Button {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

maintainability · low
languageFlagButton / panelCopyButton / flashMessage 与 PreviewResultsPanel.swift 中新增的实现几乎逐行相同(仅数据源 model.segments 与 viewModel.bilingualSegments 不同)。两份拷贝今后极易在样式或行为修正时只改一处而产生不一致(本次改动本身就是先在 Menu 版本出现过的 UI 的第二次重写)。建议抽成共享的子视图(如 TargetLanguageFlagRow、TranslationCopyButtonRow),通过 segment 提供闭包或数据参数注入。

Suggestion:

Suggested change
private func languageFlagButton(for language: TranslationLanguage) -> some View {
let isSelected = AppSettings.shared.translationTargetLanguage == language
return Button {
// 与 PreviewResultsPanel 共用 TargetLanguageFlagRow(language:isSelected:onSelect:)
private func languageFlagButton(for language: TranslationLanguage) -> some View {
let isSelected = AppSettings.shared.translationTargetLanguage == language
return Button {

Comment on lines +423 to +425
var options = config.options ?? EngineOptions.default(for: engine) ?? EngineOptions()
options.baseURL = baseURL
options.modelName = modelName

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · low
测试配置中 options.baseURL/modelName 被无条件覆盖,与 saveConfig() 的「非空才更新」逻辑不一致:当表单字段为空时,saveConfig 会保留已有 baseURL,而此处会把空字符串写入测试配置。对 MTranServer 而言 provider 会回退到 UserDefaults 的 .default 配置,导致「测试连接」探测的地址可能与实际保存使用的地址不同,测试结果具有误导性。建议与 saveConfig 保持一致,仅在非空时覆盖。

Suggestion:

Suggested change
var options = config.options ?? EngineOptions.default(for: engine) ?? EngineOptions()
options.baseURL = baseURL
options.modelName = modelName
var options = config.options ?? EngineOptions.default(for: engine) ?? EngineOptions()
if !baseURL.isEmpty { options.baseURL = baseURL }
if !modelName.isEmpty { options.modelName = modelName }

// Restore original settings if test is just for checking
settings.mtranServerHost = originalHost
settings.mtranServerPort = originalPort
let isAvailable = await MTranServerEngine(configuration: config).checkConnection()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · critical
checkConnection(config:) 声明为 async throws -> Bool(见 MTranServerEngine.swift 第 266 行),此处调用缺少 try,无法通过编译。改为 try await ... .checkConnection()。

Suggestion:

Suggested change
let isAvailable = await MTranServerEngine(configuration: config).checkConnection()
let isAvailable = try await MTranServerEngine(configuration: config).checkConnection()

Comment on lines +264 to 267
private struct EndpointKey: Hashable, Sendable {
let host: String
let port: Int
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

other · low
EndpointKey 仅由 host+port 组成,而探测行为还受 Configuration.timeout 影响(request.timeoutInterval = min(timeout, 2.0))。同一 host:port 下不同 timeout 的配置会共享缓存条目与 in-flight 探测:先用短超时配置探测失败(超时)后,结果会被长超时配置的查询命中而误判不可用。由于 TTL 仅 5 秒影响有限,建议要么将 timeout(封顶 2 秒后的值)纳入 EndpointKey,要么将探测超时固定为常量与配置解耦。

Suggestion:

Suggested change
private struct EndpointKey: Hashable, Sendable {
let host: String
let port: Int
}
private struct EndpointKey: Hashable, Sendable {
let host: String
let port: Int
let probeTimeout: TimeInterval
}

Comment on lines +298 to +301
/// Check if MTranServer is available (synchronous property, never performs network I/O)
static var isAvailable: Bool { shared.isAvailable }

let endpoints = ["/health", "/", "/translate"]
for endpoint in endpoints {
var components = URLComponents()
components.scheme = "http"
components.host = host
components.port = port
components.path = endpoint
var isAvailable: Bool { cachedAvailability(for: .default) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · medium
同步属性 isAvailable 现在仅读取 5 秒 TTL 缓存,未命中(冷启动或缓存过期)时永远返回 false,不再回退到实际探测。当前调用方 TranslationEngineType.isAvailable 若在任何 UI/逻辑路径中被读取,将系统性低估可用性。既然已提供 cachedAvailability 与异步 checkAvailability,建议要么在文档中明确该属性为"仅缓存快照"并重命名,要么在缓存未命中时仍触发一次后台异步探测以预热。

Suggestion:

Suggested change
/// Check if MTranServer is available (synchronous property, never performs network I/O)
static var isAvailable: Bool { shared.isAvailable }
let endpoints = ["/health", "/", "/translate"]
for endpoint in endpoints {
var components = URLComponents()
components.scheme = "http"
components.host = host
components.port = port
components.path = endpoint
var isAvailable: Bool { cachedAvailability(for: .default) }
/// Cached-only snapshot of availability; false when no fresh (TTL-valid) probe exists.
/// Use `checkAvailability(...)` for an authoritative answer.
static var isAvailable: Bool { shared.isAvailable }
var isAvailable: Bool { cachedAvailability(for: .default) }

Comment on lines +438 to +447
let keychain = self.keychain
let appleAlreadyRegistered = providers[.apple] != nil

return Task {
switch type {
case .apple:
if appleAlreadyRegistered {
throw RegistryError.alreadyRegistered
}
return AppleTranslationProvider()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · low
appleAlreadyRegistered 在创建 Task 前于 actor 内求值为布尔快照,Task 闭包捕获的是该值而非实时状态。若任务执行前 apple 曾被 unregister,任务会创建第二个 AppleTranslationProvider 并通过返回值交给调用方(不会缓存),与"apple 已注册则抛 alreadyRegistered"的意图不一致;反之,注册后又取消注册的窗口内也可能错误抛出。建议在 Task 内直接检查实时注册状态(如通过回调查询 registry),或依赖外层的 bumpEngineMutationRevision 校验丢弃过期结果。

Suggestion:

Suggested change
let keychain = self.keychain
let appleAlreadyRegistered = providers[.apple] != nil
return Task {
switch type {
case .apple:
if appleAlreadyRegistered {
throw RegistryError.alreadyRegistered
}
return AppleTranslationProvider()
let keychain = self.keychain
return Task {
switch type {
case .apple:
// Re-check registration state inside the task so the guard
// reflects the registry state at completion-check time.
if await self.hasManualOverride(for: .apple) {
throw RegistryError.alreadyRegistered
}
return AppleTranslationProvider()

Comment on lines +33 to +37
if let index = lines.firstIndex(where: { belongsToSameLine(segment, lineFragments: $0) }) {
lines[index].append(segment)
} else {
lines.append([segment])
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · low
mergeLines 采用贪心策略且使用 firstIndex:新片段只与第一个满足垂直重叠 + 间距条件的行合并,而不是与最匹配的行合并。当行距紧凑(如表格、多栏、上下标)导致片段与多行的 union box 同时满足条件时,可能被归入先创建的错误行,造成翻译文本错位。建议选择垂直重叠比例最大的行而非首个匹配行。

guard let first = fragments.first else { return nil }
guard fragments.count > 1 else { return first }

let ordered = fragments.sorted { $0.boundingBox.minX < $1.boundingBox.minX }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · low
mergedSegment 始终按 boundingBox.minX 升序拼接片段。对阿拉伯语、希伯来语等 RTL 文本行,视觉顺序(左→右)与逻辑字符顺序(右→左)相反,按 minX 排序会把该行文本反转后送入翻译引擎,产生错误翻译。建议根据片段文本的书写方向(如检测首字符 Unicode BiDi 类别)决定升序/降序拼接,或在文档中明确声明仅支持 LTR/CJK。

Suggestion:

Suggested change
let ordered = fragments.sorted { $0.boundingBox.minX < $1.boundingBox.minX }
let isRTL = fragments.first.map { fragment in
fragment.text.unicodeScalars.first.map(VisualLineGrouping.isRTLCharacter) ?? false
} ?? false
let ordered = fragments.sorted {
isRTL ? $0.boundingBox.minX > $1.boundingBox.minX : $0.boundingBox.minX < $1.boundingBox.minX
}

Comment on lines +84 to +88
static func joinText(_ lhs: String, _ rhs: String) -> String {
guard let last = lhs.last, let first = rhs.first else { return lhs + rhs }
if isCJK(last), isCJK(first) { return lhs + rhs }
return lhs + " " + rhs
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · medium
joinText 对所有非 CJK-CJK 相邻片段一律插入空格,而该文件文档明确说明 VLM 会把内联代码拆分为独立片段(如 "DESIGMA" + "_PLUGINS_TOKEN"、"main" 等)。此类无空格的标识符/代码文本合并后会被引入原文不存在的空格,恰好落在该模块声称要修复的场景内,导致送入翻译引擎的文本失真。建议对两侧均为字母/数字/符号(无空格边界)的组合不插入空格,或至少排除明显是代码标识符的拼接。

Comment on lines +105 to +107
/// Translation prep step after `filteredForTranslation()`: merges
/// same-line fragments so each visual line is translated as one unit.
func mergingVisualLines() -> ScreenAnalysisResult {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

maintainability · medium
新增的 mergingVisualLines() 在整个生产代码中没有任何调用方(仅测试文件引用),注释声称它是 "Translation prep step after filteredForTranslation()",但实际翻译管线并未接入。这意味着该模块解决同行片段错误合并/错位翻译的目标尚未生效,且合并后的 TextSegment 生成了新的 UUID,一旦后续接入,与 mergingROISegments、updatingSegment 等依赖 segment id 的流程的交互需要重新评估。建议在本次 PR 中实际接入调用方,或明确标注为未启用。

Verified findings fixed:
- MTranServerEngine: reject illegal hostnames (spaces/non-ASCII) before
  percentEncodedHost, avoiding an uncatchable NSException on legacy
  UserDefaults values; regression test added
- LLMTranslationResponseParser: only treat responses starting with 'data:'
  as SSE — translation bodies containing '\ndata:' lines parse as JSON again;
  regression test added
- EngineConfigSheet: empty baseURL/modelName no longer overwrite the test
  config, matching saveConfig semantics so the probe hits the persisted URL
- TranslationEngineType: gateway statuses (401/403/429) on non-translate
  endpoints now fall through to the next endpoint; 5xx still fails fast
  (preserves single-probe semantics, tests added); isAvailable documented
  as a cached-only snapshot
- TranslationEngineRegistry: forceRefresh cancels and drops stale in-flight
  provider creations instead of racing duplicates
- VisualLineGrouping: near-zero-gap identifier fragments (underscore boundary
  or identifier-shaped on both sides) join without an inserted space so
  VLM-split code tokens survive; tests added
- Removed unused ScreenAnalysisResult.mergingVisualLines() extension

Rejected findings (verified false positives): missing-try compile error
(protocol extension checkConnection is non-throwing) and piece-count
mismatch in LLM batching (batching is whole-text grouping with a 1:1
output contract via separator split and per-text retry)
Comment on lines +173 to 177
HStack(spacing: 4) {
ForEach(Self.targetLanguages, id: \.self) { language in
languageFlagButton(for: language)
}
.controlSize(.small)
.fixedSize()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

style · low
8 个国旗按钮固定 27pt 宽,总宽约 240pt(含间距),加上重跑、复制(翻译 tab 下为 3 个文案按钮)、关闭按钮及 flash 提示文本,同一 HStack 在窄面板下可能溢出或被压缩。原下拉菜单仅占一个固定宽度,此处回归风险建议验证最窄面板场景(如考虑 ScrollView(.horizontal) 或减少语言数量)。

Suggestion:

Suggested change
HStack(spacing: 4) {
ForEach(Self.targetLanguages, id: \.self) { language in
languageFlagButton(for: language)
}
.controlSize(.small)
.fixedSize()
}
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 4) {
ForEach(Self.targetLanguages, id: \.self) { language in
languageFlagButton(for: language)
}
}
}

Comment on lines +180 to +185
private func languageFlagButton(for language: TranslationLanguage) -> some View {
let isSelected = AppSettings.shared.translationTargetLanguage == language
return Button {
guard AppSettings.shared.translationTargetLanguage != language else { return }
AppSettings.shared.translationTargetLanguage = language
model.onRerun?()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

maintainability · low
languageFlagButton 与 PreviewResultsPanel 中同名实现几乎逐字重复(含选中态背景、描边、无障碍修饰符),仅取值来源不同(AppSettings vs 本地 @State)。此外此处直接读取 AppSettings.shared,选中态依赖全局单例变化而触发视图刷新,与 Preview 面板基于本地 state 的刷新路径不一致。建议抽取共享的 FlagLanguageSwitcher 组件,并统一状态来源,降低后续双处维护漂移风险。

Suggestion:

Suggested change
private func languageFlagButton(for language: TranslationLanguage) -> some View {
let isSelected = AppSettings.shared.translationTargetLanguage == language
return Button {
guard AppSettings.shared.translationTargetLanguage != language else { return }
AppSettings.shared.translationTargetLanguage = language
model.onRerun?()
struct FlagLanguageSwitcher: View {
let languages: [TranslationLanguage]
@Binding var selection: TranslationLanguage?
// ... 统一渲染与交互,两个面板复用
}

Comment on lines +252 to +259
panelCopyButton(
title: String(localized: "preview.panel.copySource"),
text: model.segments.map(\.sourceText).joined(separator: "\n")
)
panelCopyButton(
title: String(localized: "preview.panel.copyTranslation"),
text: model.segments.map(\.translated).joined(separator: "\n")
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · medium
同 PreviewResultsPanel:"preview.panel.copySource"、"preview.panel.copyTranslation" 本地化键在资源文件中不存在,运行时会显示 key 原文。请补充所有语言的翻译条目。

Suggestion:

Suggested change
panelCopyButton(
title: String(localized: "preview.panel.copySource"),
text: model.segments.map(\.sourceText).joined(separator: "\n")
)
panelCopyButton(
title: String(localized: "preview.panel.copyTranslation"),
text: model.segments.map(\.translated).joined(separator: "\n")
)
"preview.panel.copySource" = "Copy Source";
"preview.panel.copyTranslation" = "Copy Translation";

Comment on lines +266 to +273
panelCopyButton(
title: String(localized: "preview.panel.copySource"),
text: viewModel.bilingualSegments.map(\.sourceText).joined(separator: "\n")
)
panelCopyButton(
title: String(localized: "preview.panel.copyTranslation"),
text: viewModel.bilingualSegments.map(\.translated).joined(separator: "\n")
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · medium
新增本地化键 "preview.panel.copySource"、"preview.panel.copyTranslation" 未在任何 Localizable.strings 中定义(已检索 en/zh-Hans 资源文件均无对应条目)。String(localized:) 在缺失键时会直接显示 key 原文,属于用户可见回归。请为所有支持语言补充这两个键,以及 TextTranslationCoordinator 中新增的 "textTranslation.error.insertFailed.copied" 键。

Suggestion:

Suggested change
panelCopyButton(
title: String(localized: "preview.panel.copySource"),
text: viewModel.bilingualSegments.map(\.sourceText).joined(separator: "\n")
)
panelCopyButton(
title: String(localized: "preview.panel.copyTranslation"),
text: viewModel.bilingualSegments.map(\.translated).joined(separator: "\n")
)
// Localizable.strings (en / zh-Hans 等)
"preview.panel.copySource" = "Copy Source"; // zh: 复制原文
"preview.panel.copyTranslation" = "Copy Translation"; // zh: 复制译文
"textTranslation.error.insertFailed.copied" = "Translation copied to clipboard."; // zh: 译文已复制到剪贴板。

let ys = origins(length: image.height, limit: heightLimit, step: heightStep)
return ys.flatMap { y in xs.map { x in
let rect = CGRect(x: x, y: y, width: min(widthLimit, image.width - x), height: min(heightLimit, image.height - y))
return Tile(image: image.cropping(to: rect) ?? image, pixelRect: rect)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · high
当 cropping(to:) 返回 nil(如内存受限或矩形异常)时回退为整张原图,但 pixelRect 仍是切片矩形。下游 merging 会用这个 pixelRect 把整图的识别框映射到切片区域,产生静默错位结果而非失败。建议 cropping 失败时抛错或至少跳过该 tile,保证 image 与 pixelRect 一致。

Suggestion:

Suggested change
return Tile(image: image.cropping(to: rect) ?? image, pixelRect: rect)
guard let cropped = image.cropping(to: rect) else {
throw VLMProviderError.invalidResponse("Failed to crop image tile")
}
return Tile(image: cropped, pixelRect: rect)

Comment on lines +209 to +210
logger.warning("Batch split failed, retrying only unmatched individual texts")
return try await translateBatches(texts.map { [$0] }, from: sourceLanguage, to: targetLanguage, promptTemplate: promptTemplate)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · high
同样的问题:当批次内包含被切片的长文本时,split 计数失败进入逐条回退(texts.map { [$0] }),但此时 texts 是切片而非原始条目,回退结果条数仍多于调用方输入,且与原始输入的索引映射已丢失。与 LLMTranslationBatching 一并修复:切片需要携带原始条目索引,翻译完成后按索引合并。

Comment on lines +444 to +445
let keychain = self.keychain
let appleAlreadyRegistered = providers[.apple] != nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · low
makeProviderTask 在构造 Task 前同步捕获 appleAlreadyRegistered,而 Task 异步执行。若在创建进行中发生了 register(.apple),此处会基于过期快照错误抛出 alreadyRegistered。由于 appleAlreadyRegistered 仅用于防重复注册,可改为在 Task 内读取最新的注册状态,或直接依赖 provider(for:) 的缓存判断。

Comment on lines +21 to +22
static func mergeLines(in segments: [TextSegment]) -> [TextSegment] {
guard segments.count > 1 else { return segments }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · low
mergeLines 对无效包围盒(width/height ≤ 0)的片段处理不一致:belongsToSameLine 直接返回 false,使该片段总是自成一"行",随后 mergedSegment 因 count == 1 原样返回,空/退化框片段会带着无效锚点继续进入翻译与叠加渲染流程。建议在入口处先过滤掉 box 无效的片段(或统一丢弃/打日志),而不是让它们伪装成独立行存留。

Suggestion:

Suggested change
static func mergeLines(in segments: [TextSegment]) -> [TextSegment] {
guard segments.count > 1 else { return segments }
static func mergeLines(in segments: [TextSegment]) -> [TextSegment] {
let valid = segments.filter { $0.boundingBox.width > 0 && $0.boundingBox.height > 0 }
guard valid.count > 1 else { return valid }

Comment on lines +31 to +38
var lines: [[TextSegment]] = []
for segment in sorted {
if let index = lines.firstIndex(where: { belongsToSameLine(segment, lineFragments: $0) }) {
lines[index].append(segment)
} else {
lines.append([segment])
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · medium
行归属判定基于已 union 扩大的行框(lineBox),且先到先得:片段依次追加后行框不断变宽/变高,多列布局或表格中后续片段可能与已扩大的行框垂直重叠且水平间距达标而错误并入,把不同列、不同行的文本粘成一行。由于 mergeLines 结果直接决定翻译锚点(TranslationRenderPipeline),错合并会导致译文错位叠加。建议归属判定只用该行的首个片段(种子)作为参照,而非随追加扩大的 union 框。

Suggestion:

Suggested change
var lines: [[TextSegment]] = []
for segment in sorted {
if let index = lines.firstIndex(where: { belongsToSameLine(segment, lineFragments: $0) }) {
lines[index].append(segment)
} else {
lines.append([segment])
}
}
var lines: [[TextSegment]] = []
var seeds: [CGRect] = []
for segment in sorted {
if let index = seeds.firstIndex(where: { belongsToSameLine(segment, seed: $0) }) {
lines[index].append(segment)
} else {
lines.append([segment])
seeds.append(segment.boundingBox)
}
}

Comment on lines +96 to +101
if gluesDirectly,
isIdentifierCharacter(last), isIdentifierCharacter(first),
lhs.hasSuffix("_") || rhs.hasPrefix("_")
|| (isIdentifierLike(lhs) && isIdentifierLike(rhs)) {
return lhs + rhs
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · low
isIdentifierLike 对含数字/内部大写字母的普通文本过于宽松:如 "iPhone" 与 "15 Pro" 几乎相触时会被判定为 identifier 并直接粘连成 "iPhone15",丢失空格,影响展示与翻译。建议附加更严格的 token 边界校验(例如拼接后不含空格且与已知标识符模式匹配),或仅信任下划线边界这一条规则。

@hubo1989
hubo1989 merged commit 813082b into main Oct 27, 2026
2 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.

1 participant