Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions TransFrame/App/Coordinators/TextTranslationCoordinator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,11 @@ final class TextTranslationCoordinator {
// Step 1: Capture selected text
let textSelectionService = TextSelectionService.shared
let selectedText: String
let insertionTarget: CapturedTextInsertion?

do {
let selectionResult = try await textSelectionService.captureSelectedText()
let selectionResult = try await textSelectionService.captureSelectedText(bindForInsertion: true)
insertionTarget = selectionResult.insertionTarget
selectedText = selectionResult.text
logger.info("Captured selected text: \(selectedText.count) characters")
} catch let error as TextSelectionService.CaptureError {
Expand Down Expand Up @@ -239,7 +241,7 @@ final class TextTranslationCoordinator {
showInsertionProgress(message: String(localized: "translateAndInsert.progress.inserting"))

do {
try await TextInsertService.shared.deleteSelectionAndInsert(translatedText)
try TextInsertService.shared.replaceSelection(with: translatedText, captured: insertionTarget)
logger.info("Successfully inserted translated text")
} catch let error as TextInsertService.InsertError {
logger.error("Text insertion failed: \(error.localizedDescription)")
Expand All @@ -248,6 +250,11 @@ final class TextTranslationCoordinator {
alert.alertStyle = .warning
alert.messageText = String(localized: "textTranslation.error.insertFailed")
alert.informativeText = error.localizedDescription
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
if pasteboard.setString(translatedText, forType: .string) {
alert.informativeText += "\n\n" + String(localized: "textTranslation.error.insertFailed.copied")
}
alert.addButton(withTitle: String(localized: "common.ok"))
alert.runModal()
} catch {
Expand Down
120 changes: 87 additions & 33 deletions TransFrame/Features/Capture/InPlaceResultsPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,20 @@ struct InPlaceResultsPanel: View {
.buttonStyle(.plain)
.customTooltip(String(localized: "preview.panel.rerun"))

Button {
copy(currentTabText)
} label: {
Image(systemName: "doc.on.doc")
.font(.system(size: 11))
.frame(width: 20, height: 20)
if model.activeTab == .translate {
translationCopyButtons
} else {
Button {
copy(currentTabText)
} label: {
Image(systemName: "doc.on.doc")
.font(.system(size: 11))
.frame(width: 20, height: 20)
}
.buttonStyle(.plain)
.disabled(currentTabText.isEmpty)
.customTooltip(String(localized: "preview.panel.copyAll"))
}
.buttonStyle(.plain)
.disabled(currentTabText.isEmpty)
.customTooltip(String(localized: "preview.panel.copyAll"))

Button {
model.onClose?()
Expand Down Expand Up @@ -164,34 +168,42 @@ struct InPlaceResultsPanel: View {
}
}

/// 国旗横排一键切换目标语言,避免下拉二次点击。
private var targetLanguagePicker: some View {
HStack(spacing: 6) {
Text(String(localized: "preview.panel.targetLanguage"))
.font(.caption)
.foregroundStyle(.secondary)
Menu {
ForEach(Self.targetLanguages, id: \.self) { language in
Button {
guard AppSettings.shared.translationTargetLanguage != language else { return }
AppSettings.shared.translationTargetLanguage = language
model.onRerun?()
} label: {
if AppSettings.shared.translationTargetLanguage == language {
Label(language.localizedName, systemImage: "checkmark")
} else {
Text(language.localizedName)
}
}
}
} label: {
Text(AppSettings.shared.translationTargetLanguage?.localizedName ?? "—")
.font(.caption)
HStack(spacing: 4) {
ForEach(Self.targetLanguages, id: \.self) { language in
languageFlagButton(for: language)
}
.controlSize(.small)
.fixedSize()
}
Comment on lines +173 to 177

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)
}
}
}

}

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

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 {

guard AppSettings.shared.translationTargetLanguage != language else { return }
AppSettings.shared.translationTargetLanguage = language
model.onRerun?()
Comment on lines +180 to +185

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?
// ... 统一渲染与交互,两个面板复用
}

} label: {
Text(language.flagEmoji)
.font(.system(size: 16))
.frame(width: 27, height: 22)
}
.buttonStyle(.plain)
.background(
isSelected
? Color.accentColor.opacity(0.28)
: Color.primary.opacity(0.06)
)
.clipShape(RoundedRectangle(cornerRadius: 5))
.overlay(
RoundedRectangle(cornerRadius: 5)
.strokeBorder(isSelected ? Color.accentColor : Color.clear, lineWidth: 1)
)
.customTooltip(language.localizedName)
.accessibilityLabel(Text(language.localizedName))
.accessibilityAddTraits(isSelected ? [.isSelected] : [])
}

// MARK: - Helpers

private var currentTabText: String {
Expand Down Expand Up @@ -234,10 +246,52 @@ struct InPlaceResultsPanel: View {
NSPasteboard.general.setString(text, forType: .string)
}

/// 翻译结果三键复制:原文 / 译文 / 全部(原文译文交替,与面板显示一致)。
private var translationCopyButtons: some View {
HStack(spacing: 3) {
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")
)
Comment on lines +252 to +259

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";

panelCopyButton(
title: String(localized: "preview.panel.copyAll"),
text: ResultsTextBuilder.translationText(segments: model.segments).string
)
}
}

private func panelCopyButton(title: String, text: String) -> some View {
Button {
copy(text)
flashMessage(title)
} label: {
HStack(spacing: 3) {
Image(systemName: "doc.on.doc")
.font(.system(size: 10))
Text(title)
.font(.caption2)
}
.padding(.horizontal, 6)
.frame(height: 20)
}
.buttonStyle(.plain)
.background(Color.primary.opacity(0.06), in: RoundedRectangle(cornerRadius: 4))
.disabled(text.isEmpty)
.customTooltip(title)
}

/// Shows the copy feedback; a newer flash invalidates older timers, so
/// rapid line clicks don't clear each other's message early.
private func flashCopy(line: String) {
copiedFlash = String(localized: "preview.panel.copyLine") + ": " + line
flashMessage(String(localized: "preview.panel.copyLine") + ": " + line)
}

private func flashMessage(_ message: String) {
copiedFlash = message
flashGeneration += 1
let generation = flashGeneration
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
Expand Down
30 changes: 0 additions & 30 deletions TransFrame/Features/Capture/SelectionOverlayWindow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,6 @@ final class SelectionOverlayView: NSView, SelectionToolbarDelegate, NSTextFieldD
if isBeautifyEnabled {
drawBeautifyPreview(for: sel, context: context)
}
if case .selected = state {
drawBilingualOverlay(for: sel)
}
drawSelectionBox(sel, context: context)
switch state {
case .selected:
Expand Down Expand Up @@ -415,33 +412,6 @@ final class SelectionOverlayView: NSView, SelectionToolbarDelegate, NSTextFieldD
context.restoreGState()
}

/// Draws each translated segment as a strip just below its original
/// text inside the selection — in-image bilingual view; the original
/// screenshot stays fully visible. Only while the translate tab is active.
private func drawBilingualOverlay(for selRect: CGRect) {
guard resultsModel.isVisible,
resultsModel.activeTab == .translate,
!resultsModel.segments.isEmpty else { return }

NSGraphicsContext.saveGraphicsState()
defer { NSGraphicsContext.restoreGraphicsState() }
NSBezierPath(rect: selRect).addClip()
for segment in resultsModel.segments {
guard let strip = BilingualOverlayLayout.translationStrip(for: segment, in: selRect.size) else { continue }
let attr = NSAttributedString(string: segment.translated, attributes: [
.font: NSFont.systemFont(ofSize: strip.fontSize, weight: .medium),
.foregroundColor: NSColor.white
])
let frame = strip.frame.offsetBy(dx: selRect.minX, dy: selRect.minY)
NSColor.black.withAlphaComponent(0.78).setFill()
NSBezierPath(roundedRect: frame, xRadius: 3, yRadius: 3).fill()
attr.draw(
with: strip.textFrame.offsetBy(dx: selRect.minX, dy: selRect.minY),
options: [.usesLineFragmentOrigin, .usesFontLeading]
)
}
}

private func drawSelectionBox(_ rect: CGRect, context: CGContext) {
context.saveGState()
context.setStrokeColor(NSColor.controlAccentColor.cgColor)
Expand Down
6 changes: 0 additions & 6 deletions TransFrame/Features/Preview/PreviewAnnotatedImageView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,6 @@ struct PreviewAnnotatedImageView: View {
"Screenshot preview, \(viewModel.dimensionsText), from \(viewModel.displayName)"
))

if !viewModel.isTranslating && viewModel.hasTranslationResults {
BilingualOverlayView(segments: viewModel.bilingualSegments)
.frame(width: imageSize.width, height: imageSize.height)
.clipped()
}

AnnotationCanvas(
annotations: viewModel.annotations,
currentAnnotation: viewModel.currentAnnotation,
Expand Down
119 changes: 86 additions & 33 deletions TransFrame/Features/Preview/PreviewResultsPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,11 @@ struct PreviewResultsPanel: View {
// 无 tab 切换:内容随工具栏最后一次触发的动作而定。

rerunButton
copyAllButton
if viewModel.resultsPanelTab == .translate {
translationCopyButtons
} else {
copyAllButton
}
closeButton
}
.padding(.horizontal, 10)
Expand Down Expand Up @@ -187,43 +191,50 @@ struct PreviewResultsPanel: View {
}
}

/// Quick target-language switcher; changing it re-runs the translation
/// 国旗横排一键切换目标语言,避免下拉二次点击;切换后重跑翻译。
private var targetLanguagePicker: some View {
HStack(spacing: 6) {
Text(String(localized: "preview.panel.targetLanguage"))
.font(.caption)
.foregroundStyle(.secondary)
Menu {
ForEach(Self.targetLanguages, id: \.self) { language in
Button {
guard selectedTargetLanguage != language else { return }
selectedTargetLanguage = language
AppSettings.shared.translationTargetLanguage = language
if viewModel.hasTranslationResults || viewModel.ocrResult != nil {
viewModel.performTranslation()
}
} label: {
if selectedTargetLanguage == language {
Label(language.localizedName, systemImage: "checkmark")
} else {
Text(language.localizedName)
}
}
}
} label: {
Text(selectedTargetLanguage?.localizedName ?? "—")
.font(.caption)
HStack(spacing: 4) {
ForEach(Self.targetLanguages, id: \.self) { language in
languageFlagButton(for: language)
}
.controlSize(.small)
.fixedSize()
.onAppear {
if selectedTargetLanguage == nil {
selectedTargetLanguage = AppSettings.shared.translationTargetLanguage
}
}
.onAppear {
if selectedTargetLanguage == nil {
selectedTargetLanguage = AppSettings.shared.translationTargetLanguage
}
}
}

private func languageFlagButton(for language: TranslationLanguage) -> some View {
let isSelected = selectedTargetLanguage == language
return Button {
guard selectedTargetLanguage != language else { return }
selectedTargetLanguage = language
AppSettings.shared.translationTargetLanguage = language
if viewModel.hasTranslationResults || viewModel.ocrResult != nil {
viewModel.performTranslation()
}
} label: {
Text(language.flagEmoji)
.font(.system(size: 16))
.frame(width: 27, height: 22)
}
.buttonStyle(.plain)
.background(
isSelected
? Color.accentColor.opacity(0.28)
: Color.primary.opacity(0.06)
)
.clipShape(RoundedRectangle(cornerRadius: 5))
.overlay(
RoundedRectangle(cornerRadius: 5)
.strokeBorder(isSelected ? Color.accentColor : Color.clear, lineWidth: 1)
)
.customTooltip(language.localizedName)
.accessibilityLabel(Text(language.localizedName))
.accessibilityAddTraits(isSelected ? [.isSelected] : [])
}

// MARK: - Helpers

private var currentTabText: String {
Expand All @@ -249,10 +260,52 @@ struct PreviewResultsPanel: View {
NSPasteboard.general.setString(text, forType: .string)
}

/// 翻译结果三键复制:原文 / 译文 / 全部(原文译文交替,与面板显示一致)。
private var translationCopyButtons: some View {
HStack(spacing: 3) {
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")
)
Comment on lines +266 to +273

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: 译文已复制到剪贴板。

panelCopyButton(
title: String(localized: "preview.panel.copyAll"),
text: ResultsTextBuilder.translationText(segments: viewModel.bilingualSegments).string
)
}
}

private func panelCopyButton(title: String, text: String) -> some View {
Button {
copyToClipboard(text)
flashMessage(title)
} label: {
HStack(spacing: 3) {
Image(systemName: "doc.on.doc")
.font(.system(size: 10))
Text(title)
.font(.caption2)
}
.padding(.horizontal, 6)
.frame(height: 20)
}
.buttonStyle(.plain)
.background(Color.primary.opacity(0.06), in: RoundedRectangle(cornerRadius: 4))
.disabled(text.isEmpty)
.customTooltip(title)
}

/// Shows the copy feedback; a newer flash invalidates older timers, so
/// rapid line clicks don't clear each other's message early.
private func flashCopy(line: String) {
copiedFlash = String(localized: "preview.panel.copyLine") + ": " + line
flashMessage(String(localized: "preview.panel.copyLine") + ": " + line)
}

private func flashMessage(_ message: String) {
copiedFlash = message
flashGeneration += 1
let generation = flashGeneration
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
Expand Down
Loading
Loading