diff --git a/.github/workflows/windows-ci.yml b/.github/workflows/windows-ci.yml new file mode 100644 index 0000000..4227416 --- /dev/null +++ b/.github/workflows/windows-ci.yml @@ -0,0 +1,160 @@ +name: windows-ci + +on: + push: + branches: [main, "hubo/**"] + paths: + - "windows/**" + - ".github/workflows/windows-ci.yml" + pull_request: + paths: + - "windows/**" + - ".github/workflows/windows-ci.yml" + workflow_dispatch: + +jobs: + core-tests: + # Task A: solution skeleton + portable core models/algorithms. + name: Core tests (MSVC ${{ matrix.platform }}) + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + platform: [x64, ARM64] + configuration: [Release] + steps: + - uses: actions/checkout@v4 + + - name: Add MSBuild to PATH + uses: microsoft/setup-msbuild@v2 + + - name: Build solution + working-directory: windows + run: msbuild TransFrame.sln /m /p:Configuration=${{ matrix.configuration }} /p:Platform=${{ matrix.platform }} /warnaserror /verbosity:minimal + + - name: Run Catch2 tests + # x64 runner cannot execute ARM64 binaries (no emulation on + # windows-latest); ARM64 leg proves compile+link only. + # Run from windows/ so the fixture path Tests/fixtures/... resolves + # cwd-relative (same as the local dev invocation). + if: matrix.platform == 'x64' + working-directory: windows + shell: pwsh + run: | + & ".\build\${{ matrix.platform }}\${{ matrix.configuration }}\TransFrame.Core.Tests\TransFrame.Core.Tests.exe" + exit $LASTEXITCODE + + - name: Upload test binaries on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: core-tests-${{ matrix.platform }}-${{ matrix.configuration }} + path: windows/build + if-no-files-found: ignore + + native-shell-tests: + # Task B: capture shell. Portable policy core + (on Windows) Win32/D2D/WGC TUs. + name: NativeShell (MSVC ${{ matrix.platform }}) + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + platform: [x64, ARM64] + configuration: [Release] + steps: + - uses: actions/checkout@v4 + + - name: Configure CMake + run: cmake -S windows/NativeShell -B windows/NativeShell/build -A ${{ matrix.platform }} -DCMAKE_BUILD_TYPE=${{ matrix.configuration }} + + - name: Build + run: cmake --build windows/NativeShell/build --config ${{ matrix.configuration }} --parallel + + - name: Run Catch2 tests + # x64 runner cannot execute ARM64 binaries (no emulation on + # windows-latest); ARM64 leg proves compile+link only. + if: matrix.platform == 'x64' + working-directory: windows/NativeShell/build/${{ matrix.configuration }} + run: .\native_shell_tests.exe + + - name: Upload test binaries on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: nativeshell-tests-${{ matrix.platform }}-${{ matrix.configuration }} + path: windows/NativeShell/build + if-no-files-found: ignore + + translation-tests: + # Task C: translation/OCR services. Core (portable) Catch2 tests on + # MSVC x64 + ARM64; NativeShell Win32/WinRT TUs compile+link into the + # smoke target (running it needs a GUI session - see windows/README.md). + name: Translation services (MSVC ${{ matrix.platform }}) + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + platform: [x64, ARM64] + configuration: [Release] + steps: + - uses: actions/checkout@v4 + + - name: Configure CMake + run: cmake -S windows -B windows/build -A ${{ matrix.platform }} -DCMAKE_BUILD_TYPE=${{ matrix.configuration }} + + - name: Build + run: cmake --build windows/build --config ${{ matrix.configuration }} --parallel + + - name: Run Catch2 tests (Core) + # x64 runner cannot execute ARM64 binaries (no emulation on + # windows-latest); ARM64 leg proves compile+link only. + if: matrix.platform == 'x64' + working-directory: windows/build/${{ matrix.configuration }} + run: .\translation_tests.exe + + - name: Upload test binaries on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: translation-tests-${{ matrix.platform }}-${{ matrix.configuration }} + path: windows/build + if-no-files-found: ignore + + portable-check: + # Prove the portable layers stay platform-clean: the same sources + # compile under GCC on Linux (no Win32 leaks). + name: Portable checks (GCC, ubuntu) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Validate MSIX update descriptors + run: python3 -m unittest discover -s windows/scripts -v + + - name: Install compiler + run: sudo apt-get update && sudo apt-get install -y g++-13 cmake + + - name: Core (task A) — build and run Catch2 tests + working-directory: windows + run: | + g++-13 -std=c++20 -Wall -Wextra -Werror \ + -I . -I Core -I external \ + Core/*.cpp external/catch2/catch_amalgamated.cpp \ + Tests/TestMain.cpp Tests/CoreModelsTests.cpp Tests/LLMTranslationCoreTestsA.cpp \ + Tests/TranslationPromptConfigTests.cpp Tests/VisualLineGroupingTests.cpp \ + -o ../build-tests 2>&1 | head -80 + ../build-tests + + - name: NativeShell (task B) — configure, build, test + run: | + cmake -S windows/NativeShell -B windows/NativeShell/build -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CXX_COMPILER=g++-13 + cmake --build windows/NativeShell/build --parallel + windows/NativeShell/build/native_shell_tests + + - name: Translation (task C) — configure, build, test + run: | + cmake -S windows -B windows/build-c -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CXX_COMPILER=g++-13 + cmake --build windows/build-c --parallel + windows/build-c/translation_tests diff --git a/.gitignore b/.gitignore index 3fd130a..c7cb8e8 100644 --- a/.gitignore +++ b/.gitignore @@ -100,3 +100,7 @@ build_artifacts/ .omd/ *.dmg scripts/e2e/eventsynth + +# Windows installer output and Python packaging tools +windows/dist/ +__pycache__/ diff --git a/TransFrame/App/AppDelegate.swift b/TransFrame/App/AppDelegate.swift index f1a727d..53b8b38 100644 --- a/TransFrame/App/AppDelegate.swift +++ b/TransFrame/App/AppDelegate.swift @@ -212,21 +212,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Color Picker & Image Editing Actions - /// Triggers the native macOS color picker to copy a hex color code + /// Triggers the native macOS color picker to copy a hex color code. + /// Routes through the shared pick pipeline (spec §4.5): clipboard + + /// history insert + toast, same as every other eyedropper surface. @objc func pickScreenColor() { NSColorSampler().show { selectedColor in guard let color = selectedColor else { return } - guard let rgbColor = color.usingColorSpace(.sRGB) else { return } - let r = Int(round(rgbColor.redComponent * 255)) - let g = Int(round(rgbColor.greenComponent * 255)) - let b = Int(round(rgbColor.blueComponent * 255)) - let hex = String(format: "#%02X%02X%02X", r, g, b) - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(hex, forType: .string) - NotificationCenter.default.post(name: .colorDidPick, object: hex) + ColorPickFlow.complete(color) } } + /// Opens the independent color history window (spec §4.1) + @objc func openColorHistory() { + Logger.ui.debug("Opening color history window") + + ColorHistoryWindowController.shared.showColorHistory() + } + /// Opens an image file from disk and launches the annotation editor @objc func openImageForEditing() { let panel = NSOpenPanel() diff --git a/TransFrame/App/Coordinators/HotkeyCoordinator.swift b/TransFrame/App/Coordinators/HotkeyCoordinator.swift index 67b785b..a1dc97f 100644 --- a/TransFrame/App/Coordinators/HotkeyCoordinator.swift +++ b/TransFrame/App/Coordinators/HotkeyCoordinator.swift @@ -37,6 +37,7 @@ final class HotkeyCoordinator { case translationMode case textSelectionTranslation case translateAndInsert + case pickColor } // MARK: - Properties @@ -122,6 +123,18 @@ final class HotkeyCoordinator { } } + // Register screen color pick hotkey (spec §4.2 empty-state hint, + // spec §4.5 pick → history flow) + await registerHotkey( + type: .pickColor, + shortcut: settings.pickColorShortcut, + description: "Screen Color Pick" + ) { [weak self] in + Task { @MainActor in + self?.appDelegate?.pickScreenColor() + } + } + logger.info("All hotkeys registered successfully") } diff --git a/TransFrame/Features/Capture/SelectionInPlaceToolbar.swift b/TransFrame/Features/Capture/SelectionInPlaceToolbar.swift index b8e5c77..ec7f80d 100644 --- a/TransFrame/Features/Capture/SelectionInPlaceToolbar.swift +++ b/TransFrame/Features/Capture/SelectionInPlaceToolbar.swift @@ -418,12 +418,15 @@ private struct ToolbarContentView: View { .customTooltip(item.name, placement: .bottom) } - // Screen eyedropper + // Screen eyedropper: feeds the annotation color and the + // shared color-history pipeline (spec §4.5); clipboard + // untouched mid-annotation. Button { NSColorSampler().show { picked in guard let picked else { return } state.activeColor = Color(nsColor: picked) onColorSelected(picked) + ColorPickFlow.complete(picked, writeToPasteboard: false) } } label: { Image(systemName: "eyedropper") diff --git a/TransFrame/Features/History/ColorHistoryView.swift b/TransFrame/Features/History/ColorHistoryView.swift new file mode 100644 index 0000000..3434e9e --- /dev/null +++ b/TransFrame/Features/History/ColorHistoryView.swift @@ -0,0 +1,687 @@ +// +// ColorHistoryView.swift +// TransFrame +// +// Independent color-history window content: grid of large color swatches +// with HEX captions, search / favorites / copy-format controls, keyboard +// navigation, and live top-insertion highlighting (spec §4). +// + +import SwiftUI +import AppKit + +/// Copy format for the color history grid (spec §4.3), persisted per user. +enum ColorCopyFormat: String, Codable, CaseIterable, Sendable { + case hex + case rgb + + var displayName: String { + switch self { + case .hex: + return String(localized: "colorHistory.format.hex") + case .rgb: + return String(localized: "colorHistory.format.rgb") + } + } +} + +/// Pure HEX helpers — the shared acceptance-test vectors (spec §5.3) call +/// these, so they must stay free of UI dependencies. +enum ColorHex { + /// Normalizes user-facing hex text into the canonical `#RRGGBB` form + /// (uppercase, 6 digits). Accepts `#abc` shorthand and lower/upper case, + /// with or without the leading `#`. Returns nil when the string is not + /// a valid hex color (spec §5.3: lower → upper, 3-digit → 6-digit). + static func normalize(_ text: String) -> String? { + var hex = text.trimmingCharacters(in: .whitespacesAndNewlines) + if hex.hasPrefix("#") { + hex.removeFirst() + } + guard !hex.isEmpty else { return nil } + + // 3-digit shorthand expands by doubling each digit + if hex.count == 3 { + let chars = Array(hex) + hex = "\(chars[0])\(chars[0])\(chars[1])\(chars[1])\(chars[2])\(chars[2])" + } + + let upper = hex.uppercased() + guard upper.count == 6, upper.allSatisfy({ $0.isHexDigit }) else { return nil } + return "#" + upper + } + + /// Parses `#RRGGBB` into 0–255 RGB components. Invalid input yields nil. + static func rgbComponents(_ normalizedHex: String) -> (r: Int, g: Int, b: Int)? { + guard let normalized = normalize(normalizedHex), + normalized.count == 7 else { return nil } + let start = normalized.index(normalized.startIndex, offsetBy: 1) + let hex = String(normalized[start...]) + guard let value = UInt32(hex, radix: 16) else { return nil } + return (Int((value >> 16) & 0xFF), Int((value >> 8) & 0xFF), Int(value & 0xFF)) + } + + /// `RGB(r, g, b)` string used by the RGB copy format (spec §4.3). + static func rgbString(_ normalizedHex: String) -> String? { + guard let rgb = rgbComponents(normalizedHex) else { return nil } + return "RGB(\(rgb.r), \(rgb.g), \(rgb.b))" + } +} + +// MARK: - Main View + +/// Main view for the independent color history window (spec §4). +struct ColorHistoryView: View { + @ObservedObject var store: HistoryStore + + /// Copy format persisted across launches (spec §4.3). + @AppStorage("TransFrame.colorHistoryCopyFormat") private var copyFormat: ColorCopyFormat = .hex + + /// Live top-insertion highlight: id of the most recently picked color + /// (spec §4.5), cleared after the animation window. + @State private var highlightedEntryID: UUID? + @AppStorage("TransFrame.colorHistorySearch") private var searchText = "" + @State private var favoritesOnly = false + + var body: some View { + VStack(spacing: 0) { + ColorHistoryToolBar( + searchText: Binding( + get: { searchText }, + set: { searchText = $0 } + ), + favoritesOnly: Binding( + get: { favoritesOnly }, + set: { favoritesOnly = $0 } + ), + copyFormat: $copyFormat, + onClearAll: { + // spec §4.3: confirmation dialog; only the color category + // is cleared inside ColorHistoryViewModel-style flow — + // the alert is presented from `showClearAlert`. + showClearAlert = true + } + ) + + Divider() + + let entries = store.colorEntries( + matching: searchText, + favoritesOnly: favoritesOnly + ) + + if entries.isEmpty { + ColorHistoryEmptyView(searchActive: !searchText.isEmpty) + } else { + ScrollView { + ColorHistoryGrid( + entries: entries, + copyFormat: copyFormat, + highlightedEntryID: highlightedEntryID, + onCopy: { entry in + copy(entry) + }, + onToggleFavorite: { entry in + store.toggleFavorite(for: entry.id) + }, + onDelete: { entry in + store.remove(entry) + } + ) + .padding(12) + } + } + } + .frame(minWidth: 420, minHeight: 320) + .background(VisualEffectView(material: .sidebar, blendingMode: .behindWindow)) + // spec §4.4: Esc clears the search from anywhere in the window + .onExitCommand { + if !searchText.isEmpty { + searchText = "" + } + } + .alert( + localized("colorHistory.clear.alert.title"), + isPresented: $showClearAlert + ) { + Button(localized("button.cancel"), role: .cancel) {} + Button(localized("button.clear"), role: .destructive) { + store.clearColorHistory() + } + } message: { + Text(localized("colorHistory.clear.alert.message")) + } + .onReceive(store.$entries) { newEntries in + // spec §4.5: while the window is open, a fresh pick must appear + // at the top with a highlight animation. New picks land at index + // 0 with the newest timestamp. + guard let first = newEntries.first, first.category == .color else { return } + guard first.id != lastKnownTopID else { return } + let isFresh = first.timestamp.timeIntervalSinceNow > -2 + if isFresh { + withAnimation(.easeInOut(duration: 0.6)) { + highlightedEntryID = first.id + } + let id = first.id + DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { + if highlightedEntryID == id { + withAnimation(.easeOut(duration: 0.3)) { + highlightedEntryID = nil + } + } + } + } + lastKnownTopID = first.id + } + .onAppear { + if let first = store.entries.first { + lastKnownTopID = first.id + } + } + } + + // MARK: - Private State + + @State private var showClearAlert = false + @State private var lastKnownTopID: UUID? + + // MARK: - Actions + + /// Copies in the active format and flashes the "copied" feedback on the + /// swatch (spec §4.4: single click copies + 1s "Copied" badge). + private func copy(_ entry: TranslationHistory) { + guard let normalized = ColorHex.normalize(entry.translatedText) else { return } + let text: String + switch copyFormat { + case .hex: + text = normalized + case .rgb: + text = ColorHex.rgbString(normalized) ?? normalized + } + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(text, forType: .string) + } +} + +// MARK: - Tool Bar + +/// Top bar: search field, favorites-only toggle, copy-format picker, +/// clear-all button (spec §4.3). +private struct ColorHistoryToolBar: View { + @Binding var searchText: String + @Binding var favoritesOnly: Bool + @Binding var copyFormat: ColorCopyFormat + + let onClearAll: () -> Void + + @FocusState private var searchFocused: Bool + + var body: some View { + HStack(spacing: 10) { + Image(systemName: "magnifyingglass") + .foregroundStyle(.secondary) + + TextField(String(localized: "colorHistory.search.placeholder"), text: $searchText) + .focused($searchFocused) + .textFieldStyle(.plain) + .onExitCommand { + // spec §4.4: Esc clears the search + if !searchText.isEmpty { + searchText = "" + } else { + searchFocused = false + } + } + + if !searchText.isEmpty { + Button { + searchText = "" + searchFocused = true + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + .help(String(localized: "history.clear.search")) + } + + Spacer(minLength: 8) + + // Favorites-only filter (spec §4.3), stacks with search + Button { + favoritesOnly.toggle() + } label: { + Image(systemName: favoritesOnly ? "star.fill" : "star") + .foregroundStyle(favoritesOnly ? .yellow : .secondary) + } + .buttonStyle(.plain) + .help(String(localized: "colorHistory.filter.favoritesOnly")) + + // Copy format toggle (spec §4.3), persisted via AppStorage + Picker(String(localized: "colorHistory.copy.format"), selection: $copyFormat) { + ForEach(ColorCopyFormat.allCases, id: \.self) { format in + Text(format.displayName).tag(format) + } + } + .pickerStyle(.menu) + .frame(width: 92) + .help(String(localized: "colorHistory.copy.format")) + + // Clear all color entries (spec §4.3) — confirmation upstream + Button(role: .destructive) { + onClearAll() + } label: { + Image(systemName: "trash") + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + .help(String(localized: "colorHistory.clear.all")) + } + .padding(12) + } +} + +// MARK: - Grid + +/// Adaptive color-swatch grid: every cell ≥ 48×48pt with the HEX caption +/// in a monospaced font (spec §4.2). +/// +/// Keyboard model (spec §4.4): each cell is focusable; Tab cycles cells, +/// arrow keys move focus to grid neighbors, Enter/Space/Delete act on the +/// focused cell, Esc clears the search (handled by the search field). +private struct ColorHistoryGrid: View { + let entries: [TranslationHistory] + let copyFormat: ColorCopyFormat + let highlightedEntryID: UUID? + let onCopy: (TranslationHistory) -> Void + let onToggleFavorite: (TranslationHistory) -> Void + let onDelete: (TranslationHistory) -> Void + + /// Cell side length: at least 48pt (spec §4.2), growing with the window. + private let cellSize: CGFloat = 64 + + /// The currently focused (keyboard-selected) cell. + @FocusState private var focusedCellID: UUID? + + /// Measured grid width, used to compute the column count for + /// up/down keyboard navigation. + @State private var gridWidth: CGFloat = 560 + + private var columns: [GridItem] { + [GridItem(.adaptive(minimum: cellSize, maximum: 96), spacing: 12)] + } + + var body: some View { + LazyVGrid(columns: columns, spacing: 12) { + ForEach(entries) { entry in + ColorSwatchCell( + entry: entry, + copyFormat: copyFormat, + isSelected: focusedCellID == entry.id, + isHighlighted: highlightedEntryID == entry.id, + onCopy: { onCopy(entry) }, + onToggleFavorite: { onToggleFavorite(entry) }, + onDelete: { onDelete(entry) } + ) + .id(entry.id) + .focused($focusedCellID, equals: entry.id) + .onMoveCommand { direction in + moveFocus(from: entry, direction: direction) + } + } + } + .background(GeometryReader { geo in + Color.clear.onAppear { gridWidth = geo.size.width } + .onChange(of: geo.size.width) { _, width in gridWidth = width } + }) + } + + // MARK: - Keyboard Navigation + + /// Moves focus from `entry` to its grid neighbor in `direction`. + private func moveFocus(from entry: TranslationHistory, direction: MoveCommandDirection) { + guard let currentIndex = entries.firstIndex(where: { $0.id == entry.id }) else { return } + let count = entries.count + let stride = max(1, columnCount) + + let nextIndex: Int + switch direction { + case .left: + nextIndex = max(0, currentIndex - 1) + case .right: + nextIndex = min(count - 1, currentIndex + 1) + case .up: + nextIndex = max(0, currentIndex - stride) + case .down: + nextIndex = min(count - 1, currentIndex + stride) + @unknown default: + nextIndex = currentIndex + } + + guard nextIndex != currentIndex else { return } + focusedCellID = entries[nextIndex].id + } + + /// Columns currently laid out, derived from the measured grid width. + private var columnCount: Int { + max(1, Int(gridWidth / (cellSize + 12))) + } +} + +// MARK: - Swatch Cell + +/// A single color cell: swatch + monospaced HEX caption, hover actions, +/// favorite star badge, copied flash, and tooltip (spec §4.2/§4.4). +private struct ColorSwatchCell: View { + let entry: TranslationHistory + let copyFormat: ColorCopyFormat + let isSelected: Bool + let isHighlighted: Bool + + let onCopy: () -> Void + let onToggleFavorite: () -> Void + let onDelete: () -> Void + + @State private var isHovered = false + @State private var showCopiedBadge = false + + private var normalizedHex: String { + ColorHex.normalize(entry.translatedText) ?? entry.translatedText + } + + private var swatchColor: Color { + // A malformed stored hex renders as a neutral placeholder instead of + // crashing the grid. + guard let nsColor = nsColorFromHex(normalizedHex) else { + return Color(nsColor: .systemGray) + } + return Color(nsColor: nsColor) + } + + var body: some View { + VStack(spacing: 4) { + swatch + .frame(height: 48) + .frame(maxWidth: .infinity) + // spec §4.2: hover actions AND the constant favorite star both + // live in the top-right corner as one trailing cluster — the + // star merges into the action group on hover (its toggle + // button reflects the state), so the two never overlap. + .overlay(alignment: .topTrailing) { topTrailingCluster } + .overlay(alignment: .center) { copiedBadge } + .clipShape(RoundedRectangle(cornerRadius: DesignSystem.Radii.small)) + .overlay( + RoundedRectangle(cornerRadius: DesignSystem.Radii.small) + .strokeBorder( + isSelected ? Color.accentColor : + (isHighlighted ? Color.accentColor.opacity(0.8) : Color(nsColor: .separatorColor).opacity(0.5)), + lineWidth: isSelected ? 2 : (isHighlighted ? 2 : 0.5) + ) + ) + .contentShape(Rectangle()) + .onTapGesture { + // spec §4.4: single click copies in the current format + // and flashes the "Copied" badge for 1s + onCopy() + flashCopiedBadge() + } + .onHover { hovering in + isHovered = hovering + } + .contextMenu { + Button { + if let hex = ColorHex.normalize(entry.translatedText) { try? ClipboardService().copyText(hex) } + } label: { + Label(String(localized: "colorHistory.copy.hex"), systemImage: "doc.on.doc") + } + Button { + copyRGB() + } label: { + Label(String(localized: "colorHistory.copy.rgb"), systemImage: "doc.on.doc.fill") + } + Divider() + Button { + onToggleFavorite() + } label: { + Label( + entry.isFavorite + ? String(localized: "colorHistory.unfavorite") + : String(localized: "colorHistory.favorite"), + systemImage: entry.isFavorite ? "star.slash" : "star" + ) + } + Button(role: .destructive) { + onDelete() + } label: { + Label(String(localized: "history.delete"), systemImage: "trash") + } + } + .help(tooltipText) + + Text(normalizedHex) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + .padding(4) + .background( + RoundedRectangle(cornerRadius: DesignSystem.Radii.small) + .fill(isHighlighted ? Color.accentColor.opacity(0.12) : Color.clear) + ) + // spec §4.4: cells participate in Tab navigation; Enter / Space / + // Delete act on the focused cell directly. + .focusable() + .focusEffectDisabled() + .onKeyPress(.return) { + onCopy() + flashCopiedBadge() + return .handled + } + .onKeyPress(.space) { + onToggleFavorite() + return .handled + } + .onKeyPress(.delete, phases: .down) { _ in + onDelete() + return .handled + } + .accessibilityElement(children: .combine) + .accessibilityLabel(Text("\(String(localized: "colorHistory.title")) \(normalizedHex)")) + .accessibilityHint(Text(String(localized: "colorHistory.copy.format"))) + .accessibilityAddTraits(isSelected ? [.isSelected] : []) + } + + // MARK: - Pieces + + /// The large color block (≥48pt tall per spec §4.2). + private var swatch: some View { + Rectangle() + .fill(swatchColor) + } + + /// The single top-right cluster (spec §4.2). At rest it shows only the + /// constant favorite star (filled = favorited, dim outline otherwise). + /// On hover the action group materializes and the star collapses into it + /// as its leading button — one trailing HStack, zero overlap. + @ViewBuilder + private var topTrailingCluster: some View { + if isHovered { + HStack(spacing: 2) { + actionButton( + icon: entry.isFavorite ? "star.fill" : "star", + help: entry.isFavorite + ? String(localized: "colorHistory.unfavorite") + : String(localized: "colorHistory.favorite") + ) { + onToggleFavorite() + } + actionButton(icon: "doc.on.doc", help: String(localized: "colorHistory.copy.hex")) { + onCopy() + flashCopiedBadge() + } + actionButton(icon: "trash", help: String(localized: "history.delete"), role: .destructive) { + onDelete() + } + } + .padding(3) + .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: DesignSystem.Radii.small)) + .transition(.opacity) + } else { + favoriteBadge + } + } + + /// Favorite entries always show a star badge (spec §4.2). + private var favoriteBadge: some View { + Group { + if entry.isFavorite { + Image(systemName: "star.fill") + .font(.system(size: 10)) + .foregroundStyle(.yellow) + .shadow(color: .black.opacity(0.4), radius: 1) + .padding(4) + } + } + } + + /// "Copied" flash overlay (spec §4.4, 1s). + private var copiedBadge: some View { + Group { + if showCopiedBadge { + Text(String(localized: "colorHistory.copied")) + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.white) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(Color.black.opacity(0.65)) + .clipShape(Capsule()) + .transition(.opacity) + } + } + } + + private func actionButton(icon: String, help: String, role: ButtonRole? = nil, action: @escaping () -> Void) -> some View { + Button(role: role, action: action) { + Image(systemName: icon) + .font(.system(size: 10)) + .foregroundStyle(role == .destructive ? Color.red : Color.primary) + .frame(width: 18, height: 18) + } + .buttonStyle(.plain) + .help(help) + } + + /// Tooltip with full HEX / RGB / pick time (spec §4.2). + private var tooltipText: String { + var lines: [String] = [normalizedHex] + if let rgb = ColorHex.rgbString(normalizedHex) { + lines.append(rgb) + } + lines.append(entry.fullDateString) + return lines.joined(separator: "\n") + } + + // MARK: - Actions + + private func copyRGB() { + guard let rgb = ColorHex.rgbString(normalizedHex) else { return } + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(rgb, forType: .string) + } + + private func flashCopiedBadge() { + withAnimation(.easeIn(duration: 0.1)) { + showCopiedBadge = true + } + DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { + withAnimation(.easeOut(duration: 0.2)) { + showCopiedBadge = false + } + } + } +} + +// MARK: - Empty State + +/// Empty state: centered illustration + guidance + eyedropper shortcut hint +/// (spec §4.2). The hint reads the live "pick color" hotkey and refreshes +/// when the user rebinds it in Settings. +private struct ColorHistoryEmptyView: View { + let searchActive: Bool + + /// Re-render trigger when the pick hotkey is rebound in Settings. + @State private var shortcutRefreshID = UUID() + + private var pickShortcut: KeyboardShortcut { + AppSettings.shared.pickColorShortcut + } + + private var shortcutHint: Text { + // spec §4.2: show the bound hotkey; fall back to the tray path when + // unbound (never an empty string). + Text( + String( + format: String(localized: "colorHistory.empty.shortcut"), + pickShortcut.displayString + ) + ) + } + + private var trayHint: Text { + Text(String(localized: "colorHistory.empty.trayHint")) + } + + var body: some View { + VStack(spacing: 16) { + Image(systemName: "eyedropper") + .font(.system(size: 48)) + .foregroundStyle(.secondary) + + if searchActive { + Text("colorHistory.no.results.title") + .font(.headline) + .foregroundStyle(.secondary) + + Text("colorHistory.no.results.message") + .font(.body) + .foregroundStyle(.tertiary) + } else { + Text("colorHistory.empty.title") + .font(.headline) + .foregroundStyle(.secondary) + + Text("colorHistory.empty.message") + .font(.body) + .foregroundStyle(.tertiary) + + // Dynamic pick shortcut hint; keyed on the refresh ID so + // rebinding in Settings updates this line live. + (pickShortcut.isValid ? shortcutHint : trayHint) + .font(.callout) + .foregroundStyle(.secondary) + .id(shortcutRefreshID) + .onReceive( + NotificationCenter.default.publisher( + for: AppSettings.shortcutDidChangeNotification + ) + ) { _ in + shortcutRefreshID = UUID() + } + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} + +// MARK: - Hex → NSColor + +/// Converts a normalized hex string into an sRGB NSColor. +private func nsColorFromHex(_ hex: String) -> NSColor? { + guard let rgb = ColorHex.rgbComponents(hex) else { return nil } + return NSColor( + srgbRed: CGFloat(rgb.r) / 255.0, + green: CGFloat(rgb.g) / 255.0, + blue: CGFloat(rgb.b) / 255.0, + alpha: 1.0 + ) +} diff --git a/TransFrame/Features/History/ColorHistoryWindowController.swift b/TransFrame/Features/History/ColorHistoryWindowController.swift new file mode 100644 index 0000000..9e236ef --- /dev/null +++ b/TransFrame/Features/History/ColorHistoryWindowController.swift @@ -0,0 +1,107 @@ +// +// ColorHistoryWindowController.swift +// TransFrame +// +// Presents the independent color history window (spec §4.1): single +// instance, remembered frame, system appearance, sidebar vibrancy. +// + +import AppKit +import SwiftUI + +/// Controller for presenting and managing the independent color history +/// window. Singleton so repeated opens focus the existing window instead of +/// stacking duplicates (spec §4.1). +@MainActor +final class ColorHistoryWindowController: NSObject { + // MARK: - Singleton + + /// Shared instance + static let shared = ColorHistoryWindowController() + + // MARK: - Properties + + /// The color history window + private var window: NSWindow? + + /// The history store shared with this window's content + private let store: HistoryStore + + // MARK: - Initialization + + private override init() { + self.store = HistoryWindowController.shared.store + super.init() + } + + // MARK: - Public API + + /// Presents the color history window. + /// If already open, brings it to front (spec §4.1 single-instance rule). + func showColorHistory() { + // If window already exists, bring it to front + if let window = window, window.isVisible { + window.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + return + } + + // Create the SwiftUI view + let colorHistoryView = ColorHistoryView(store: store) + + // Create the hosting view + let hostingView = NSHostingView(rootView: colorHistoryView) + hostingView.translatesAutoresizingMaskIntoConstraints = false + + // Create the window: default 560×420, resizable (spec §4.1) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 560, height: 420), + styleMask: [.titled, .closable, .miniaturizable, .resizable], + backing: .buffered, + defer: false + ) + window.title = NSLocalizedString("colorHistory.title", comment: "Color History") + window.contentView = hostingView + // 先居中作为默认位置;setFrameAutosaveName 返回 true 表示已恢复存档 frame(覆盖居中), + // 返回 false 表示无存档(或名称被占用),保持居中。 + // 旧窗口对象若仍占用同名 autosave name(isReleasedWhenClosed=false), + // 这里会返回 false 退化为居中,不会崩溃。 + window.center() + _ = window.setFrameAutosaveName("TransFrameColorHistoryWindow") + window.isReleasedWhenClosed = false + window.delegate = self + + // Set window behavior + window.level = .normal + window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary] + + // Set minimum size + window.minSize = NSSize(width: 420, height: 320) + + // Store reference + self.window = window + + // Show the window + window.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + } + + /// Closes the color history window if open. + func closeColorHistory() { + window?.close() + window = nil + } +} + +// MARK: - NSWindowDelegate + +extension ColorHistoryWindowController: NSWindowDelegate { + nonisolated func windowWillClose(_ notification: Notification) { + Task { @MainActor in + // 释放 autosave name,避免窗口复用/重建时同名注册失败导致 frame 恢复失效 + window?.setFrameAutosaveName("") + // Clear reference + window = nil + } + } +} diff --git a/TransFrame/Features/History/ColorPickFlow.swift b/TransFrame/Features/History/ColorPickFlow.swift new file mode 100644 index 0000000..9c9aebf --- /dev/null +++ b/TransFrame/Features/History/ColorPickFlow.swift @@ -0,0 +1,51 @@ +// +// ColorPickFlow.swift +// TransFrame +// +// Shared entry point for completed screen color picks (spec §4.5): every +// eyedropper surface (tray menu, preview toolbar, selection-in-place +// toolbar) funnels through `ColorPickFlow.complete(...)` so all of them get +// the same clipboard write, history insert, `.colorDidPick` broadcast, and +// "View History" toast. No surface implements the flow locally. +// + +import AppKit + +/// Converts an arbitrary picked NSColor into the canonical `#RRGGBB` form, +/// or nil when the color has no sRGB representation. MainActor: the flow +/// touches the pasteboard, the shared history controller, and the toast. +@MainActor +enum ColorPickFlow { + /// Full pick completion pipeline. + /// - Parameters: + /// - color: the color returned by NSColorSampler + /// - writeToPasteboard: whether the HEX should also go to the + /// clipboard (annotation eyedroppers keep the clipboard untouched — + /// the user is mid-annotation and may have content staged) + static func complete(_ color: NSColor, writeToPasteboard: Bool = true) { + guard let hex = hexString(from: color) else { return } + + if writeToPasteboard { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(hex, forType: .string) + } + + // Touching the shared controller guarantees the singleton history + // store exists and observes this broadcast (the store is created by + // HistoryWindowController). + _ = HistoryWindowController.shared + NotificationCenter.default.post(name: .colorDidPick, object: hex) + + // spec §4.1 entry #2: completion toast with "View History" link + ColorPickToastController.shared.show(hex: hex) + } + + /// sRGB conversion + rounding, shared by all pick surfaces. + static func hexString(from color: NSColor) -> String? { + guard let rgbColor = color.usingColorSpace(.sRGB) else { return nil } + let r = Int(round(rgbColor.redComponent * 255)) + let g = Int(round(rgbColor.greenComponent * 255)) + let b = Int(round(rgbColor.blueComponent * 255)) + return String(format: "#%02X%02X%02X", r, g, b) + } +} diff --git a/TransFrame/Features/History/ColorPickToastController.swift b/TransFrame/Features/History/ColorPickToastController.swift new file mode 100644 index 0000000..8c79532 --- /dev/null +++ b/TransFrame/Features/History/ColorPickToastController.swift @@ -0,0 +1,176 @@ +// +// ColorPickToastController.swift +// TransFrame +// +// Lightweight non-activating toast shown after a successful screen color +// pick (spec §4.1): "copied #HEX" plus a "view history" link, auto-dismiss +// after 1.5 seconds. +// + +import AppKit +import SwiftUI + +/// Shows a short toast near the current cursor after each completed pick. +/// A newer pick replaces the previous toast (and cancels its timer). +@MainActor +final class ColorPickToastController { + // MARK: - Singleton + + static let shared = ColorPickToastController() + + // MARK: - Properties + + private var panel: NSPanel? + private var hostingView: NSHostingView? + private var dismissTask: Task? + private var lastHex: String = "" + + private init() {} + + // MARK: - Public API + + /// Shows (or refreshes) the toast for a freshly picked hex color. + /// - Parameter hex: The picked color in `#RRGGBB` form + func show(hex: String) { + lastHex = hex + let anchor = ColorPickToastAnchor.currentCursorRect() + + if panel == nil { + createPanel(hex: hex) + } else { + refresh(hex: hex) + } + + positionPanel(near: anchor) + panel?.orderFrontRegardless() + + // spec §4.1: toast disappears after 1.5s; a newer pick resets it + dismissTask?.cancel() + dismissTask = Task { [weak self] in + try? await Task.sleep(for: .seconds(1.5)) + guard !Task.isCancelled else { return } + self?.dismiss() + } + } + + /// Dismisses the toast immediately (also called by the history link). + func dismiss() { + dismissTask?.cancel() + dismissTask = nil + panel?.close() + panel = nil + hostingView = nil + } + + // MARK: - Private + + private func refresh(hex: String) { + guard let hostingView else { return } + hostingView.rootView = makeToastView(hex: hex) + } + + private func makeToastView(hex: String) -> ColorPickToastView { + ColorPickToastView( + hex: hex, + onViewHistory: { [weak self] in + self?.dismiss() + ColorHistoryWindowController.shared.showColorHistory() + } + ) + } + + private func createPanel(hex: String) { + let contentView = makeToastView(hex: hex) + let hostingView = NSHostingView(rootView: contentView) + hostingView.frame = NSRect(x: 0, y: 0, width: 260, height: 44) + + let panel = NSPanel( + contentRect: hostingView.frame, + styleMask: [.borderless, .nonactivatingPanel], + backing: .buffered, + defer: false + ) + + panel.contentView = hostingView + panel.level = .statusBar + panel.isOpaque = false + panel.backgroundColor = .clear + panel.hasShadow = true + // spec §4.2/§4.4 interaction stays with the toast: the history link + // must be clickable, unlike a pure status flash. + panel.ignoresMouseEvents = false + panel.hidesOnDeactivate = false + panel.isReleasedWhenClosed = false + panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle] + + self.panel = panel + self.hostingView = hostingView + } + + private func positionPanel(near anchor: CGRect) { + guard let panel, let screen = NSScreen.main else { return } + + let contentSize = hostingView?.frame.size ?? NSSize(width: 260, height: 44) + // Place above the cursor (or at the anchor's top edge); flip below + // when running into the menu bar. + var origin = CGPoint( + x: anchor.midX - contentSize.width / 2, + y: anchor.maxY + 8 + ) + + origin.x = max(screen.visibleFrame.minX + 8, min(origin.x, screen.visibleFrame.maxX - contentSize.width - 8)) + if origin.y + contentSize.height > screen.visibleFrame.maxY { + origin.y = anchor.minY - contentSize.height - 8 + } + origin.y = max(screen.visibleFrame.minY + 8, origin.y) + + panel.setFrame(NSRect(origin: origin, size: contentSize), display: false) + } +} + +// MARK: - Anchor + +/// Locates where the toast should appear: the mouse position at pick time. +private enum ColorPickToastAnchor { + static func currentCursorRect() -> CGRect { + let location = NSEvent.mouseLocation + return CGRect(x: location.x, y: location.y - 2, width: 4, height: 4) + } +} + +// MARK: - Toast View + +private struct ColorPickToastView: View { + let hex: String + let onViewHistory: () -> Void + + var body: some View { + HStack(spacing: 8) { + Image(systemName: "eyedropper") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + + Text(hex) + .font(.system(size: 12, design: .monospaced)) + .lineLimit(1) + + Button(action: onViewHistory) { + Text("colorHistory.toast.viewHistory") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(Color.accentColor) + } + .buttonStyle(.plain) + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: DesignSystem.Radii.medium) + .fill(.ultraThinMaterial) + ) + .overlay( + RoundedRectangle(cornerRadius: DesignSystem.Radii.medium) + .stroke(Color(nsColor: .separatorColor).opacity(0.5), lineWidth: 0.5) + ) + .shadow(color: .black.opacity(0.2), radius: 6, y: 2) + } +} diff --git a/TransFrame/Features/History/HistoryWindowController.swift b/TransFrame/Features/History/HistoryWindowController.swift index f92e342..53f36aa 100644 --- a/TransFrame/Features/History/HistoryWindowController.swift +++ b/TransFrame/Features/History/HistoryWindowController.swift @@ -16,7 +16,7 @@ final class HistoryWindowController: NSObject { private var window: NSWindow? /// The history store - private let store: HistoryStore + let store: HistoryStore // MARK: - Initialization diff --git a/TransFrame/Features/MenuBar/MenuBarController.swift b/TransFrame/Features/MenuBar/MenuBarController.swift index d97f70d..d6a17bf 100644 --- a/TransFrame/Features/MenuBar/MenuBarController.swift +++ b/TransFrame/Features/MenuBar/MenuBarController.swift @@ -107,11 +107,13 @@ final class MenuBarController { menu.addItem(NSMenuItem.separator()) - // Color Picker + // Color Picker — shows the configurable global hotkey (spec §4.2 + // empty-state hint points here too) menu.addItem(createMenuItem( titleKey: "menu.pick.color", comment: "Pick Color from Screen", action: #selector(AppDelegate.pickScreenColor), + shortcut: settings.pickColorShortcut, target: appDelegate, imageName: "eyedropper" )) @@ -140,6 +142,15 @@ final class MenuBarController { imageName: "clock.arrow.circlepath" )) + // Color History (spec §4.1: tray entry right after Translation History) + menu.addItem(createMenuItem( + titleKey: "menu.color.history", + comment: "Color History", + action: #selector(AppDelegate.openColorHistory), + target: appDelegate, + imageName: "paintpalette" + )) + menu.addItem(NSMenuItem.separator()) // Pinned Windows Actions diff --git a/TransFrame/Features/Preview/PreviewToolBar.swift b/TransFrame/Features/Preview/PreviewToolBar.swift index c3bd48e..ffd5d98 100644 --- a/TransFrame/Features/Preview/PreviewToolBar.swift +++ b/TransFrame/Features/Preview/PreviewToolBar.swift @@ -231,12 +231,16 @@ struct PreviewStyleCustomizationBar: View { .customTooltip(target == .fill ? "\(colorName(for: color)) (\(String(localized: "preview.fill.color")))" : colorName(for: color)) } - /// Screen eyedropper: samples a pixel anywhere on screen into the target color + /// Screen eyedropper: samples a pixel anywhere on screen into the target + /// color; the pick also flows into the color history via the shared + /// pipeline (spec §4.5). Clipboard untouched — the annotation color + /// binding is the outcome here. private func eyedropperButton(target: ColorTarget) -> some View { Button { NSColorSampler().show { selectedColor in guard let nsColor = selectedColor else { return } applyColor(CodableColor(Color(nsColor: nsColor)), to: target) + ColorPickFlow.complete(nsColor, writeToPasteboard: false) } } label: { Image(systemName: "eyedropper") diff --git a/TransFrame/Features/Settings/SettingsViewModel.swift b/TransFrame/Features/Settings/SettingsViewModel.swift index 28517e1..65312cd 100644 --- a/TransFrame/Features/Settings/SettingsViewModel.swift +++ b/TransFrame/Features/Settings/SettingsViewModel.swift @@ -14,6 +14,7 @@ enum ShortcutRecordingType: Equatable { case translationMode case textSelectionTranslation case translateAndInsert + case pickColor } /// ViewModel for the Settings view. @@ -65,6 +66,11 @@ final class SettingsViewModel { recordingType == .translateAndInsert } + /// Whether screen color pick shortcut is being recorded (for UI binding) + var isRecordingPickColorShortcut: Bool { + recordingType == .pickColor + } + /// Error message to display var errorMessage: String? @@ -257,6 +263,16 @@ final class SettingsViewModel { } } + /// Screen color pick shortcut (color history empty state references it) + var pickColorShortcut: KeyboardShortcut { + get { settings.pickColorShortcut } + set { + settings.pickColorShortcut = newValue + appDelegate?.updateHotkeys() + settings.saveShortcut(newValue, forKey: AppSettings.Keys.pickColorShortcut) + } + } + /// Annotation stroke color var strokeColor: Color { get { settings.strokeColor.color } @@ -675,6 +691,11 @@ final class SettingsViewModel { startRecording(.translateAndInsert) } + /// Starts recording a keyboard shortcut for screen color pick + func startRecordingPickColorShortcut() { + startRecording(.pickColor) + } + /// Cancels shortcut recording func cancelRecording() { recordingType = nil @@ -726,6 +747,8 @@ final class SettingsViewModel { textSelectionTranslationShortcut = shortcut case .translateAndInsert: translateAndInsertShortcut = shortcut + case .pickColor: + pickColorShortcut = shortcut case .none: break } @@ -760,6 +783,11 @@ final class SettingsViewModel { translateAndInsertShortcut = .translateAndInsertDefault } + /// Resets screen color pick shortcut to default + func resetPickColorShortcut() { + pickColorShortcut = .pickColorDefault + } + /// Resets all settings to defaults func resetAllToDefaults() { settings.resetToDefaults() @@ -777,6 +805,7 @@ final class SettingsViewModel { case .translationMode: return translationModeShortcut case .textSelectionTranslation: return textSelectionTranslationShortcut case .translateAndInsert: return translateAndInsertShortcut + case .pickColor: return pickColorShortcut case .none: return nil } } @@ -789,7 +818,8 @@ final class SettingsViewModel { private func hasShortcutConflict(_ shortcut: KeyboardShortcut, excluding: KeyboardShortcut?) -> Bool { let allShortcuts = [ fullScreenShortcut, selectionShortcut, translationModeShortcut, - textSelectionTranslationShortcut, translateAndInsertShortcut + textSelectionTranslationShortcut, translateAndInsertShortcut, + pickColorShortcut ].filter { $0 != excluding } return allShortcuts.contains(shortcut) } diff --git a/TransFrame/Features/Settings/ShortcutSettingsTab.swift b/TransFrame/Features/Settings/ShortcutSettingsTab.swift index 040cc92..7a2fadb 100644 --- a/TransFrame/Features/Settings/ShortcutSettingsTab.swift +++ b/TransFrame/Features/Settings/ShortcutSettingsTab.swift @@ -44,6 +44,14 @@ struct ShortcutSettingsContent: View { onRecord: { viewModel.startRecordingTranslateAndInsertShortcut() }, onReset: { viewModel.resetTranslateAndInsertShortcut() } ) + Divider().opacity(0.1) + ShortcutRecorder( + label: localized("settings.shortcut.pick.color"), + shortcut: viewModel.pickColorShortcut, + isRecording: viewModel.isRecordingPickColorShortcut, + onRecord: { viewModel.startRecordingPickColorShortcut() }, + onReset: { viewModel.resetPickColorShortcut() } + ) } .macosGroupedCard() } diff --git a/TransFrame/Models/AppSettings.swift b/TransFrame/Models/AppSettings.swift index 8099597..e659c34 100644 --- a/TransFrame/Models/AppSettings.swift +++ b/TransFrame/Models/AppSettings.swift @@ -50,6 +50,7 @@ final class AppSettings { static let translationModeShortcut = prefix + "translationModeShortcut" static let textSelectionTranslationShortcut = prefix + "textSelectionTranslationShortcut" static let translateAndInsertShortcut = prefix + "translateAndInsertShortcut" + static let pickColorShortcut = prefix + "pickColorShortcut" static let strokeColor = prefix + "strokeColor" static let strokeWidth = prefix + "strokeWidth" static let textSize = prefix + "textSize" @@ -154,6 +155,12 @@ final class AppSettings { didSet { saveShortcut(translateAndInsertShortcut, forKey: Keys.translateAndInsertShortcut) } } + /// Global hotkey for the screen color picker (eyedropper). Referenced by + /// the color history empty state (spec §4.2). + var pickColorShortcut: KeyboardShortcut { + didSet { saveShortcut(pickColorShortcut, forKey: Keys.pickColorShortcut) } + } + /// Default annotation stroke color var strokeColor: CodableColor { didSet { saveColor(strokeColor, forKey: Keys.strokeColor) } @@ -535,6 +542,8 @@ final class AppSettings { ?? KeyboardShortcut.textSelectionTranslationDefault translateAndInsertShortcut = Self.loadShortcut(forKey: Keys.translateAndInsertShortcut) ?? KeyboardShortcut.translateAndInsertDefault + pickColorShortcut = Self.loadShortcut(forKey: Keys.pickColorShortcut) + ?? KeyboardShortcut.pickColorDefault // Load annotation defaults strokeColor = Self.loadColor(forKey: Keys.strokeColor) ?? .red @@ -685,6 +694,7 @@ final class AppSettings { translationModeShortcut = .translationModeDefault textSelectionTranslationShortcut = .textSelectionTranslationDefault translateAndInsertShortcut = .translateAndInsertDefault + pickColorShortcut = .pickColorDefault strokeColor = .red strokeWidth = 2.0 textSize = 14.0 diff --git a/TransFrame/Models/KeyboardShortcut.swift b/TransFrame/Models/KeyboardShortcut.swift index a9fe5f2..5899193 100644 --- a/TransFrame/Models/KeyboardShortcut.swift +++ b/TransFrame/Models/KeyboardShortcut.swift @@ -55,6 +55,15 @@ struct KeyboardShortcut: Equatable, Codable, Sendable { modifiers: UInt32(cmdKey | shiftKey) ) + /// Default screen color pick shortcut: Control + Command + C. + /// Distinct from the system-wide Cmd+C copy: adds Control, keeping it in + /// the same "family" as the capture hotkeys while avoiding the plain + /// clipboard binding (spec §4.2 empty-state hint references this). + static let pickColorDefault = KeyboardShortcut( + keyCode: UInt32(kVK_ANSI_C), + modifiers: UInt32(cmdKey | controlKey) + ) + // MARK: - Validation /// Checks if the shortcut includes at least one modifier key diff --git a/TransFrame/Resources/de.lproj/Localizable.strings b/TransFrame/Resources/de.lproj/Localizable.strings index 15b841b..b819af4 100644 --- a/TransFrame/Resources/de.lproj/Localizable.strings +++ b/TransFrame/Resources/de.lproj/Localizable.strings @@ -282,6 +282,7 @@ "settings.shortcut.translation.mode" = "Übersetzungsmodus"; "settings.shortcut.text.selection.translation" = "Textauswahl-Übersetzung"; "settings.shortcut.translate.and.insert" = "Übersetzen und Einfügen"; +"settings.shortcut.pick.color" = "Screen Color Pick"; "settings.shortcut.recording" = "Tasten drücken..."; "settings.shortcut.reset" = "Auf Standard zurücksetzen"; "settings.shortcut.error.no.modifier" = "Tastenkürzel müssen Befehl, Steuerung oder Option enthalten"; @@ -960,3 +961,27 @@ "translation.provider.recovery.translationFailed" = "Übersetzung fehlgeschlagen. Bitte erneut versuchen."; "translation.provider.recovery.unsupportedLanguage" = "Nicht unterstütztes Sprachpaar. Wählen Sie eine andere Zielsprache."; "translation.unknown" = "Unbekannt"; + +/* Color History Window — TODO: translate (English placeholder) */ +"menu.color.history" = "Color History"; +"colorHistory.title" = "Color History"; +"colorHistory.search.placeholder" = "Search colors (HEX)..."; +"colorHistory.filter.favoritesOnly" = "Favorites only"; +"colorHistory.copy.format" = "Copy format"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "Clear all colors"; +"colorHistory.clear.alert.title" = "Clear Color History"; +"colorHistory.clear.alert.message" = "Are you sure you want to delete all picked colors? Translation and screenshot history will not be affected. This action cannot be undone."; +"colorHistory.copy.hex" = "Copy HEX"; +"colorHistory.copy.rgb" = "Copy RGB"; +"colorHistory.favorite" = "Favorite"; +"colorHistory.unfavorite" = "Unfavorite"; +"colorHistory.copied" = "Copied"; +"colorHistory.empty.title" = "No Picked Colors"; +"colorHistory.empty.message" = "Use the eyedropper to pick a screen color and it will appear here"; +"colorHistory.empty.shortcut" = "Press %@ anywhere to pick a screen color"; +"colorHistory.empty.trayHint" = "Pick from the tray menu: Screen Color Pick"; +"colorHistory.no.results.title" = "No Matching Colors"; +"colorHistory.no.results.message" = "No colors match your search"; +"colorHistory.toast.viewHistory" = "View History"; diff --git a/TransFrame/Resources/en.lproj/Localizable.strings b/TransFrame/Resources/en.lproj/Localizable.strings index b60ddc8..5d8b2a1 100644 --- a/TransFrame/Resources/en.lproj/Localizable.strings +++ b/TransFrame/Resources/en.lproj/Localizable.strings @@ -290,6 +290,7 @@ "settings.shortcut.translation.mode" = "Translation Mode"; "settings.shortcut.text.selection.translation" = "Text Selection Translation"; "settings.shortcut.translate.and.insert" = "Translate and Insert"; +"settings.shortcut.pick.color" = "Screen Color Pick"; "settings.shortcut.recording" = "Press keys..."; "settings.shortcut.reset" = "Reset to default"; "settings.shortcut.error.no.modifier" = "Shortcuts must include Command, Control, or Option"; @@ -547,6 +548,30 @@ "history.clear.alert.title" = "Clear History"; "history.clear.alert.message" = "Are you sure you want to delete all translation history? This action cannot be undone."; +/* Color History Window */ +"menu.color.history" = "Color History"; +"colorHistory.title" = "Color History"; +"colorHistory.search.placeholder" = "Search colors (HEX)..."; +"colorHistory.filter.favoritesOnly" = "Favorites only"; +"colorHistory.copy.format" = "Copy format"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "Clear all colors"; +"colorHistory.clear.alert.title" = "Clear Color History"; +"colorHistory.clear.alert.message" = "Are you sure you want to delete all picked colors? Translation and screenshot history will not be affected. This action cannot be undone."; +"colorHistory.copy.hex" = "Copy HEX"; +"colorHistory.copy.rgb" = "Copy RGB"; +"colorHistory.favorite" = "Favorite"; +"colorHistory.unfavorite" = "Unfavorite"; +"colorHistory.copied" = "Copied"; +"colorHistory.empty.title" = "No Picked Colors"; +"colorHistory.empty.message" = "Use the eyedropper to pick a screen color and it will appear here"; +"colorHistory.empty.shortcut" = "Press %@ anywhere to pick a screen color"; +"colorHistory.empty.trayHint" = "Pick from the tray menu: Screen Color Pick"; +"colorHistory.no.results.title" = "No Matching Colors"; +"colorHistory.no.results.message" = "No colors match your search"; +"colorHistory.toast.viewHistory" = "View History"; + /* ======================================== Permission Prompt diff --git a/TransFrame/Resources/es.lproj/Localizable.strings b/TransFrame/Resources/es.lproj/Localizable.strings index ac8f612..39c8367 100644 --- a/TransFrame/Resources/es.lproj/Localizable.strings +++ b/TransFrame/Resources/es.lproj/Localizable.strings @@ -282,6 +282,7 @@ "settings.shortcut.translation.mode" = "Modo de Traducción"; "settings.shortcut.text.selection.translation" = "Traducción de Selección de Texto"; "settings.shortcut.translate.and.insert" = "Traducir e Insertar"; +"settings.shortcut.pick.color" = "Screen Color Pick"; "settings.shortcut.recording" = "Presione teclas..."; "settings.shortcut.reset" = "Restablecer a predeterminados"; "settings.shortcut.error.no.modifier" = "Los atajos deben incluir Comando, Control u Opción"; @@ -960,3 +961,27 @@ "translation.provider.recovery.translationFailed" = "Falló la traducción. Reintente."; "translation.provider.recovery.unsupportedLanguage" = "Par de idiomas no compatible. Elija otro idioma destino."; "translation.unknown" = "Desconocido"; + +/* Color History Window — TODO: translate (English placeholder) */ +"menu.color.history" = "Color History"; +"colorHistory.title" = "Color History"; +"colorHistory.search.placeholder" = "Search colors (HEX)..."; +"colorHistory.filter.favoritesOnly" = "Favorites only"; +"colorHistory.copy.format" = "Copy format"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "Clear all colors"; +"colorHistory.clear.alert.title" = "Clear Color History"; +"colorHistory.clear.alert.message" = "Are you sure you want to delete all picked colors? Translation and screenshot history will not be affected. This action cannot be undone."; +"colorHistory.copy.hex" = "Copy HEX"; +"colorHistory.copy.rgb" = "Copy RGB"; +"colorHistory.favorite" = "Favorite"; +"colorHistory.unfavorite" = "Unfavorite"; +"colorHistory.copied" = "Copied"; +"colorHistory.empty.title" = "No Picked Colors"; +"colorHistory.empty.message" = "Use the eyedropper to pick a screen color and it will appear here"; +"colorHistory.empty.shortcut" = "Press %@ anywhere to pick a screen color"; +"colorHistory.empty.trayHint" = "Pick from the tray menu: Screen Color Pick"; +"colorHistory.no.results.title" = "No Matching Colors"; +"colorHistory.no.results.message" = "No colors match your search"; +"colorHistory.toast.viewHistory" = "View History"; diff --git a/TransFrame/Resources/fr.lproj/Localizable.strings b/TransFrame/Resources/fr.lproj/Localizable.strings index 98f30da..5dfd1c0 100644 --- a/TransFrame/Resources/fr.lproj/Localizable.strings +++ b/TransFrame/Resources/fr.lproj/Localizable.strings @@ -282,6 +282,7 @@ "settings.shortcut.translation.mode" = "Mode de traduction"; "settings.shortcut.text.selection.translation" = "Traduction de sélection de texte"; "settings.shortcut.translate.and.insert" = "Traduire et insérer"; +"settings.shortcut.pick.color" = "Screen Color Pick"; "settings.shortcut.recording" = "Appuyez sur les touches..."; "settings.shortcut.reset" = "Réinitialiser par défaut"; "settings.shortcut.error.no.modifier" = "Les raccourcis doivent inclure Commande, Contrôle ou Option"; @@ -960,3 +961,27 @@ "translation.provider.recovery.translationFailed" = "Échec de la traduction. Réessayez."; "translation.provider.recovery.unsupportedLanguage" = "Paire de langues non prise en charge. Choisissez une autre langue cible."; "translation.unknown" = "Inconnu"; + +/* Color History Window — TODO: translate (English placeholder) */ +"menu.color.history" = "Color History"; +"colorHistory.title" = "Color History"; +"colorHistory.search.placeholder" = "Search colors (HEX)..."; +"colorHistory.filter.favoritesOnly" = "Favorites only"; +"colorHistory.copy.format" = "Copy format"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "Clear all colors"; +"colorHistory.clear.alert.title" = "Clear Color History"; +"colorHistory.clear.alert.message" = "Are you sure you want to delete all picked colors? Translation and screenshot history will not be affected. This action cannot be undone."; +"colorHistory.copy.hex" = "Copy HEX"; +"colorHistory.copy.rgb" = "Copy RGB"; +"colorHistory.favorite" = "Favorite"; +"colorHistory.unfavorite" = "Unfavorite"; +"colorHistory.copied" = "Copied"; +"colorHistory.empty.title" = "No Picked Colors"; +"colorHistory.empty.message" = "Use the eyedropper to pick a screen color and it will appear here"; +"colorHistory.empty.shortcut" = "Press %@ anywhere to pick a screen color"; +"colorHistory.empty.trayHint" = "Pick from the tray menu: Screen Color Pick"; +"colorHistory.no.results.title" = "No Matching Colors"; +"colorHistory.no.results.message" = "No colors match your search"; +"colorHistory.toast.viewHistory" = "View History"; diff --git a/TransFrame/Resources/it.lproj/Localizable.strings b/TransFrame/Resources/it.lproj/Localizable.strings index c17bce9..80d6efe 100644 --- a/TransFrame/Resources/it.lproj/Localizable.strings +++ b/TransFrame/Resources/it.lproj/Localizable.strings @@ -282,6 +282,7 @@ "settings.shortcut.translation.mode" = "Modalità Traduzione"; "settings.shortcut.text.selection.translation" = "Traduzione Selezione Testo"; "settings.shortcut.translate.and.insert" = "Traduci e Inserisci"; +"settings.shortcut.pick.color" = "Screen Color Pick"; "settings.shortcut.recording" = "Premi tasti..."; "settings.shortcut.reset" = "Ripristina predefiniti"; "settings.shortcut.error.no.modifier" = "Le scorciatoie devono includere Command, Control o Option"; @@ -961,3 +962,27 @@ "translation.provider.recovery.translationFailed" = "Traduzione non riuscita. Riprova."; "translation.provider.recovery.unsupportedLanguage" = "Coppia di lingue non supportata. Scegli un'altra lingua di destinazione."; "translation.unknown" = "Sconosciuto"; + +/* Color History Window — TODO: translate (English placeholder) */ +"menu.color.history" = "Color History"; +"colorHistory.title" = "Color History"; +"colorHistory.search.placeholder" = "Search colors (HEX)..."; +"colorHistory.filter.favoritesOnly" = "Favorites only"; +"colorHistory.copy.format" = "Copy format"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "Clear all colors"; +"colorHistory.clear.alert.title" = "Clear Color History"; +"colorHistory.clear.alert.message" = "Are you sure you want to delete all picked colors? Translation and screenshot history will not be affected. This action cannot be undone."; +"colorHistory.copy.hex" = "Copy HEX"; +"colorHistory.copy.rgb" = "Copy RGB"; +"colorHistory.favorite" = "Favorite"; +"colorHistory.unfavorite" = "Unfavorite"; +"colorHistory.copied" = "Copied"; +"colorHistory.empty.title" = "No Picked Colors"; +"colorHistory.empty.message" = "Use the eyedropper to pick a screen color and it will appear here"; +"colorHistory.empty.shortcut" = "Press %@ anywhere to pick a screen color"; +"colorHistory.empty.trayHint" = "Pick from the tray menu: Screen Color Pick"; +"colorHistory.no.results.title" = "No Matching Colors"; +"colorHistory.no.results.message" = "No colors match your search"; +"colorHistory.toast.viewHistory" = "View History"; diff --git a/TransFrame/Resources/ja.lproj/Localizable.strings b/TransFrame/Resources/ja.lproj/Localizable.strings index e510e52..352094b 100644 --- a/TransFrame/Resources/ja.lproj/Localizable.strings +++ b/TransFrame/Resources/ja.lproj/Localizable.strings @@ -282,6 +282,7 @@ "settings.shortcut.translation.mode" = "翻訳モード"; "settings.shortcut.text.selection.translation" = "テキスト選択翻訳"; "settings.shortcut.translate.and.insert" = "翻訳して挿入"; +"settings.shortcut.pick.color" = "Screen Color Pick"; "settings.shortcut.recording" = "キーを押してください..."; "settings.shortcut.reset" = "デフォルトに戻す"; "settings.shortcut.error.no.modifier" = "ショートカットには Command、Control、または Option を含める必要があります"; @@ -960,3 +961,27 @@ "translation.provider.recovery.translationFailed" = "翻訳に失敗しました。再試行してください。"; "translation.provider.recovery.unsupportedLanguage" = "この言語ペアはサポートされていません。別の対象言語を選択してください。"; "translation.unknown" = "不明"; + +/* Color History Window — TODO: translate (English placeholder) */ +"menu.color.history" = "Color History"; +"colorHistory.title" = "Color History"; +"colorHistory.search.placeholder" = "Search colors (HEX)..."; +"colorHistory.filter.favoritesOnly" = "Favorites only"; +"colorHistory.copy.format" = "Copy format"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "Clear all colors"; +"colorHistory.clear.alert.title" = "Clear Color History"; +"colorHistory.clear.alert.message" = "Are you sure you want to delete all picked colors? Translation and screenshot history will not be affected. This action cannot be undone."; +"colorHistory.copy.hex" = "Copy HEX"; +"colorHistory.copy.rgb" = "Copy RGB"; +"colorHistory.favorite" = "Favorite"; +"colorHistory.unfavorite" = "Unfavorite"; +"colorHistory.copied" = "Copied"; +"colorHistory.empty.title" = "No Picked Colors"; +"colorHistory.empty.message" = "Use the eyedropper to pick a screen color and it will appear here"; +"colorHistory.empty.shortcut" = "Press %@ anywhere to pick a screen color"; +"colorHistory.empty.trayHint" = "Pick from the tray menu: Screen Color Pick"; +"colorHistory.no.results.title" = "No Matching Colors"; +"colorHistory.no.results.message" = "No colors match your search"; +"colorHistory.toast.viewHistory" = "View History"; diff --git a/TransFrame/Resources/ko.lproj/Localizable.strings b/TransFrame/Resources/ko.lproj/Localizable.strings index 4d7ad03..65e2583 100644 --- a/TransFrame/Resources/ko.lproj/Localizable.strings +++ b/TransFrame/Resources/ko.lproj/Localizable.strings @@ -282,6 +282,7 @@ "settings.shortcut.translation.mode" = "번역 모드"; "settings.shortcut.text.selection.translation" = "텍스트 선택 번역"; "settings.shortcut.translate.and.insert" = "번역하고 삽입"; +"settings.shortcut.pick.color" = "Screen Color Pick"; "settings.shortcut.recording" = "키를 누르세요..."; "settings.shortcut.reset" = "기본값으로 재설정"; "settings.shortcut.error.no.modifier" = "단축키에는 Command, Control 또는 Option이 포함되어야 합니다"; @@ -960,3 +961,27 @@ "translation.provider.recovery.translationFailed" = "번역에 실패했습니다. 다시 시도하세요."; "translation.provider.recovery.unsupportedLanguage" = "지원되지 않는 언어 쌍입니다. 다른 대상 언어를 선택하세요."; "translation.unknown" = "알 수 없음"; + +/* Color History Window — TODO: translate (English placeholder) */ +"menu.color.history" = "Color History"; +"colorHistory.title" = "Color History"; +"colorHistory.search.placeholder" = "Search colors (HEX)..."; +"colorHistory.filter.favoritesOnly" = "Favorites only"; +"colorHistory.copy.format" = "Copy format"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "Clear all colors"; +"colorHistory.clear.alert.title" = "Clear Color History"; +"colorHistory.clear.alert.message" = "Are you sure you want to delete all picked colors? Translation and screenshot history will not be affected. This action cannot be undone."; +"colorHistory.copy.hex" = "Copy HEX"; +"colorHistory.copy.rgb" = "Copy RGB"; +"colorHistory.favorite" = "Favorite"; +"colorHistory.unfavorite" = "Unfavorite"; +"colorHistory.copied" = "Copied"; +"colorHistory.empty.title" = "No Picked Colors"; +"colorHistory.empty.message" = "Use the eyedropper to pick a screen color and it will appear here"; +"colorHistory.empty.shortcut" = "Press %@ anywhere to pick a screen color"; +"colorHistory.empty.trayHint" = "Pick from the tray menu: Screen Color Pick"; +"colorHistory.no.results.title" = "No Matching Colors"; +"colorHistory.no.results.message" = "No colors match your search"; +"colorHistory.toast.viewHistory" = "View History"; diff --git a/TransFrame/Resources/pt.lproj/Localizable.strings b/TransFrame/Resources/pt.lproj/Localizable.strings index da99a0a..fae3252 100644 --- a/TransFrame/Resources/pt.lproj/Localizable.strings +++ b/TransFrame/Resources/pt.lproj/Localizable.strings @@ -282,6 +282,7 @@ "settings.shortcut.translation.mode" = "Modo de Tradução"; "settings.shortcut.text.selection.translation" = "Tradução de Seleção de Texto"; "settings.shortcut.translate.and.insert" = "Traduzir e Inserir"; +"settings.shortcut.pick.color" = "Screen Color Pick"; "settings.shortcut.recording" = "Pressione as teclas..."; "settings.shortcut.reset" = "Restaurar padrão"; "settings.shortcut.error.no.modifier" = "Atalhos devem incluir Command, Control ou Option"; @@ -975,3 +976,27 @@ Conceda permissão em Configurações do Sistema > Privacidade e Segurança > Mo "translation.provider.recovery.translationFailed" = "Falha na tradução. Tente novamente."; "translation.provider.recovery.unsupportedLanguage" = "Par de idiomas não suportado. Escolha outro idioma de destino."; "translation.unknown" = "Desconhecido"; + +/* Color History Window — TODO: translate (English placeholder) */ +"menu.color.history" = "Color History"; +"colorHistory.title" = "Color History"; +"colorHistory.search.placeholder" = "Search colors (HEX)..."; +"colorHistory.filter.favoritesOnly" = "Favorites only"; +"colorHistory.copy.format" = "Copy format"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "Clear all colors"; +"colorHistory.clear.alert.title" = "Clear Color History"; +"colorHistory.clear.alert.message" = "Are you sure you want to delete all picked colors? Translation and screenshot history will not be affected. This action cannot be undone."; +"colorHistory.copy.hex" = "Copy HEX"; +"colorHistory.copy.rgb" = "Copy RGB"; +"colorHistory.favorite" = "Favorite"; +"colorHistory.unfavorite" = "Unfavorite"; +"colorHistory.copied" = "Copied"; +"colorHistory.empty.title" = "No Picked Colors"; +"colorHistory.empty.message" = "Use the eyedropper to pick a screen color and it will appear here"; +"colorHistory.empty.shortcut" = "Press %@ anywhere to pick a screen color"; +"colorHistory.empty.trayHint" = "Pick from the tray menu: Screen Color Pick"; +"colorHistory.no.results.title" = "No Matching Colors"; +"colorHistory.no.results.message" = "No colors match your search"; +"colorHistory.toast.viewHistory" = "View History"; diff --git a/TransFrame/Resources/ru.lproj/Localizable.strings b/TransFrame/Resources/ru.lproj/Localizable.strings index aba32e7..700a75f 100644 --- a/TransFrame/Resources/ru.lproj/Localizable.strings +++ b/TransFrame/Resources/ru.lproj/Localizable.strings @@ -282,6 +282,7 @@ "settings.shortcut.translation.mode" = "Режим перевода"; "settings.shortcut.text.selection.translation" = "Перевод выбранного текста"; "settings.shortcut.translate.and.insert" = "Перевести и вставить"; +"settings.shortcut.pick.color" = "Screen Color Pick"; "settings.shortcut.recording" = "Нажмите клавиши..."; "settings.shortcut.reset" = "Сбросить по умолчанию"; "settings.shortcut.error.no.modifier" = "Сочетания должны включать Command, Control или Option"; @@ -960,3 +961,27 @@ "translation.provider.recovery.translationFailed" = "Ошибка перевода. Повторите попытку."; "translation.provider.recovery.unsupportedLanguage" = "Эта пара языков не поддерживается. Выберите другой целевой язык."; "translation.unknown" = "Неизвестно"; + +/* Color History Window — TODO: translate (English placeholder) */ +"menu.color.history" = "Color History"; +"colorHistory.title" = "Color History"; +"colorHistory.search.placeholder" = "Search colors (HEX)..."; +"colorHistory.filter.favoritesOnly" = "Favorites only"; +"colorHistory.copy.format" = "Copy format"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "Clear all colors"; +"colorHistory.clear.alert.title" = "Clear Color History"; +"colorHistory.clear.alert.message" = "Are you sure you want to delete all picked colors? Translation and screenshot history will not be affected. This action cannot be undone."; +"colorHistory.copy.hex" = "Copy HEX"; +"colorHistory.copy.rgb" = "Copy RGB"; +"colorHistory.favorite" = "Favorite"; +"colorHistory.unfavorite" = "Unfavorite"; +"colorHistory.copied" = "Copied"; +"colorHistory.empty.title" = "No Picked Colors"; +"colorHistory.empty.message" = "Use the eyedropper to pick a screen color and it will appear here"; +"colorHistory.empty.shortcut" = "Press %@ anywhere to pick a screen color"; +"colorHistory.empty.trayHint" = "Pick from the tray menu: Screen Color Pick"; +"colorHistory.no.results.title" = "No Matching Colors"; +"colorHistory.no.results.message" = "No colors match your search"; +"colorHistory.toast.viewHistory" = "View History"; diff --git a/TransFrame/Resources/zh-Hans.lproj/Localizable.strings b/TransFrame/Resources/zh-Hans.lproj/Localizable.strings index c58bb02..b2ede8c 100644 --- a/TransFrame/Resources/zh-Hans.lproj/Localizable.strings +++ b/TransFrame/Resources/zh-Hans.lproj/Localizable.strings @@ -290,6 +290,7 @@ "settings.shortcut.translation.mode" = "翻译模式"; "settings.shortcut.text.selection.translation" = "文本选择翻译"; "settings.shortcut.translate.and.insert" = "翻译并插入"; +"settings.shortcut.pick.color" = "屏幕取色"; "settings.shortcut.recording" = "按下快捷键..."; "settings.shortcut.reset" = "恢复默认"; "settings.shortcut.error.no.modifier" = "快捷键必须包含 Command、Control 或 Option"; @@ -547,6 +548,30 @@ "history.clear.alert.title" = "清除历史"; "history.clear.alert.message" = "确定要删除所有翻译历史吗?此操作无法撤销。"; +/* 取色历史窗口 */ +"menu.color.history" = "取色历史"; +"colorHistory.title" = "取色历史"; +"colorHistory.search.placeholder" = "搜索颜色 (HEX)..."; +"colorHistory.filter.favoritesOnly" = "仅显示收藏"; +"colorHistory.copy.format" = "复制格式"; +"colorHistory.format.hex" = "HEX"; +"colorHistory.format.rgb" = "RGB"; +"colorHistory.clear.all" = "清空全部颜色"; +"colorHistory.clear.alert.title" = "清空取色历史"; +"colorHistory.clear.alert.message" = "确定要删除所有取色记录吗?翻译与截图历史不受影响。此操作无法撤销。"; +"colorHistory.copy.hex" = "复制 HEX"; +"colorHistory.copy.rgb" = "复制 RGB"; +"colorHistory.favorite" = "收藏"; +"colorHistory.unfavorite" = "取消收藏"; +"colorHistory.copied" = "已复制"; +"colorHistory.empty.title" = "还没有取色记录"; +"colorHistory.empty.message" = "使用取色器拾取屏幕颜色后,颜色会显示在这里"; +"colorHistory.empty.shortcut" = "任意界面按 %@ 即可拾取屏幕颜色"; +"colorHistory.empty.trayHint" = "从托盘菜单选择:屏幕取色"; +"colorHistory.no.results.title" = "没有匹配的颜色"; +"colorHistory.no.results.message" = "没有颜色匹配您的搜索"; +"colorHistory.toast.viewHistory" = "查看历史"; + /* ======================================== 权限提示 diff --git a/TransFrame/Services/HistoryStore.swift b/TransFrame/Services/HistoryStore.swift index aecad88..d2833f9 100644 --- a/TransFrame/Services/HistoryStore.swift +++ b/TransFrame/Services/HistoryStore.swift @@ -82,14 +82,7 @@ final class HistoryStore: ObservableObject { ) { [weak self] notif in guard let hex = notif.object as? String else { return } Task { @MainActor in - let entry = TranslationHistory( - sourceText: "Color Picked", - translatedText: hex, - sourceLanguage: "RGB Hex", - targetLanguage: hex, - category: .color - ) - self?.addEntry(entry) + self?.recordPickedColor(hex: hex) } }) @@ -132,7 +125,8 @@ final class HistoryStore: ObservableObject { }) { var merged = entry merged.isFavorite = entries[index].isFavorite - entries[index] = merged + entries.remove(at: index) + entries.insert(merged, at: 0) } else { entries.insert(entry, at: 0) } @@ -210,6 +204,63 @@ final class HistoryStore: ObservableObject { updateFilteredEntries() } + // MARK: - Color History + + /// Returns color-category entries filtered by a HEX fragment and + /// favorites-only flag (spec §4.3). + /// + /// Filtering is case-insensitive on the stored HEX (`translatedText`): + /// `1a2b` matches `#1A2B3C`. An empty/nil fragment returns all color + /// entries; `favoritesOnly` stacks with the fragment filter. + /// - Parameters: + /// - matching: HEX fragment to match, or nil/empty for all + /// - favoritesOnly: when true, only starred entries are returned + /// - Returns: Color entries (newest first) matching both filters + func colorEntries(matching fragment: String?, favoritesOnly: Bool) -> [TranslationHistory] { + var result = entries.filter { $0.category == .color } + + if favoritesOnly { + result = result.filter { $0.isFavorite } + } + + if let fragment, !fragment.isEmpty { + let lowercased = fragment.lowercased() + result = result.filter { $0.translatedText.lowercased().contains(lowercased) } + } + + return result + } + + /// Clears only color-category entries, leaving every other category + /// untouched (spec §4.3: "clear all" affects only colors). + func clearColorHistory() { + entries.removeAll { $0.category == .color } + saveHistory() + updateFilteredEntries() + } + + // MARK: - Shared Color Pick Pipeline + + /// Builds the canonical color history entry for a picked hex (spec §3 + /// data model: fixed source/sourceLanguage, HEX in translatedText). + static func makeColorPickEntry(hex: String, date: Date = Date()) -> TranslationHistory { + TranslationHistory( + sourceText: "Color Picked", + translatedText: hex, + sourceLanguage: "RGB Hex", + targetLanguage: hex, + timestamp: date, + category: .color + ) + } + + /// Records a picked screen color into this store (dedup + top insert + /// follow `addEntry`). Does NOT post `.colorDidPick` — callers that + /// own the pick flow decide whether to broadcast. + func recordPickedColor(hex: String, date: Date = Date()) { + addEntry(Self.makeColorPickEntry(hex: hex, date: date)) + } + /// Sets the search query and updates filtered entries. /// - Parameter query: The search string func search(_ query: String) { diff --git a/TransFrameTests/ColorHistoryStoreTests.swift b/TransFrameTests/ColorHistoryStoreTests.swift new file mode 100644 index 0000000..c615250 --- /dev/null +++ b/TransFrameTests/ColorHistoryStoreTests.swift @@ -0,0 +1,277 @@ +import XCTest +@testable import TransFrame + +/// Tests for the color history feature (spec §5.3 shared acceptance +/// vectors): HEX formatting, search filtering, favorites stacking, +/// color-only clearing, and capacity eviction of the oldest entry. +final class ColorHistoryStoreTests: XCTestCase { + // MARK: - Helpers + + @MainActor + private func makeStore() -> HistoryStore { + let suiteName = "test-color-history-\(UUID().uuidString)" + let testDefaults = UserDefaults(suiteName: suiteName)! + addTeardownBlock { + testDefaults.removePersistentDomain(forName: suiteName) + } + return HistoryStore(userDefaults: testDefaults) + } + + private func colorEntry( + _ hex: String, + favorite: Bool = false, + timestamp: Date = Date() + ) -> TranslationHistory { + TranslationHistory( + sourceText: "Color Picked", + translatedText: hex, + sourceLanguage: "RGB Hex", + targetLanguage: hex, + timestamp: timestamp, + category: .color, + isFavorite: favorite + ) + } + + private func translationEntry(_ text: String) -> TranslationHistory { + TranslationHistory( + sourceText: text, + translatedText: text + "-translated", + sourceLanguage: "English", + targetLanguage: "Chinese", + category: .translation + ) + } + + // MARK: - HEX Formatting (spec §5.3) + + func testNormalizeLowercaseToUppercase() { + XCTAssertEqual(ColorHex.normalize("#1a2b3c"), "#1A2B3C") + XCTAssertEqual(ColorHex.normalize("1a2b3c"), "#1A2B3C") + XCTAssertEqual(ColorHex.normalize("#ABCDEF"), "#ABCDEF") + } + + func testNormalizeExpandsThreeDigitShorthand() { + XCTAssertEqual(ColorHex.normalize("#abc"), "#AABBCC") + XCTAssertEqual(ColorHex.normalize("f0e"), "#FF00EE") + } + + func testNormalizeRejectsInvalidInput() { + XCTAssertNil(ColorHex.normalize("#12")) + XCTAssertNil(ColorHex.normalize("#12345")) + XCTAssertNil(ColorHex.normalize("#1234567")) + XCTAssertNil(ColorHex.normalize("#GGGGGG")) + XCTAssertNil(ColorHex.normalize("")) + XCTAssertNil(ColorHex.normalize(" ")) + } + + func testRGBComponentsAndString() { + let tuple = ColorHex.rgbComponents("#1A2B3C") + XCTAssertEqual(tuple?.r, 0x1A) + XCTAssertEqual(tuple?.g, 0x2B) + XCTAssertEqual(tuple?.b, 0x3C) + + XCTAssertEqual(ColorHex.rgbString("#1A2B3C"), "RGB(26, 43, 60)") + XCTAssertEqual(ColorHex.rgbString("#FF0000"), "RGB(255, 0, 0)") + } + + // MARK: - Search Filtering (spec §4.3 / §5.3) + + @MainActor + func testColorEntriesSearchIsCaseInsensitive() { + let store = makeStore() + store.addEntry(colorEntry("#1A2B3C")) + store.addEntry(colorEntry("#4D5E6F")) + store.addEntry(colorEntry("#AABBCC")) + + // spec §5.3 vector: `1a2b` → hits `#1A2B3C` + let hits = store.colorEntries(matching: "1a2b", favoritesOnly: false) + XCTAssertEqual(hits.map(\.translatedText), ["#1A2B3C"]) + + // Uppercase fragment matches the same entry + XCTAssertEqual(store.colorEntries(matching: "1A2B", favoritesOnly: false).count, 1) + + // Fragment `1A2` hits `#1A2B3C` (spec §6 US-CH4 vector) + XCTAssertEqual(store.colorEntries(matching: "1A2", favoritesOnly: false).count, 1) + + // Empty / nil fragment = all colors + XCTAssertEqual(store.colorEntries(matching: nil, favoritesOnly: false).count, 3) + XCTAssertEqual(store.colorEntries(matching: "", favoritesOnly: false).count, 3) + + // No match + XCTAssertTrue(store.colorEntries(matching: "ZZZZ", favoritesOnly: false).isEmpty) + } + + @MainActor + func testColorEntriesSearchOnlyMatchesColorCategory() { + let store = makeStore() + store.addEntry(colorEntry("#1A2B3C")) + store.addEntry(translationEntry("#1A2B3C-like")) + + // A translation entry carrying hex-ish text must not leak into the + // color grid results. + let hits = store.colorEntries(matching: "1A2B", favoritesOnly: false) + XCTAssertEqual(hits.count, 1) + XCTAssertEqual(hits.first?.category, .color) + } + + // MARK: - Favorites Filter (spec §4.3) + + @MainActor + func testFavoritesOnlyStacksWithSearch() { + let store = makeStore() + let favorite = colorEntry("#1A2B3C", favorite: true) + let plain = colorEntry("#1A2B99", favorite: false) + store.addEntry(plain) + store.addEntry(favorite) + + // Favorites alone + let favorites = store.colorEntries(matching: nil, favoritesOnly: true) + XCTAssertEqual(favorites.map(\.translatedText), ["#1A2B3C"]) + + // Favorites stacked with a shared fragment + let stacked = store.colorEntries(matching: "1A2B", favoritesOnly: true) + XCTAssertEqual(stacked.map(\.translatedText), ["#1A2B3C"]) + + // Search finds both when favorites are off + XCTAssertEqual(store.colorEntries(matching: "1A2B", favoritesOnly: false).count, 2) + } + + @MainActor + func testNewPicksAppearAtTop() { + let store = makeStore() + store.addEntry(colorEntry("#111111", timestamp: Date(timeIntervalSince1970: 100))) + store.addEntry(colorEntry("#222222", timestamp: Date(timeIntervalSince1970: 200))) + + // spec §4.5: newest first — `addEntry` inserts at index 0 + XCTAssertEqual( + store.colorEntries(matching: nil, favoritesOnly: false).map(\.translatedText), + ["#222222", "#111111"] + ) + } + + // MARK: - Clear Only Colors (spec §4.3 / US-CH5) + + @MainActor + func testClearColorHistoryLeavesOtherCategoriesUntouched() { + let store = makeStore() + store.addEntry(colorEntry("#1A2B3C")) + store.addEntry(colorEntry("#4D5E6F", favorite: true)) + store.addEntry(translationEntry("hello")) + store.addEntry(translationEntry("world")) + + let translationCountBefore = store.entries.filter { $0.category == .translation }.count + XCTAssertEqual(translationCountBefore, 2) + + store.clearColorHistory() + + // Colors gone + XCTAssertTrue(store.colorEntries(matching: nil, favoritesOnly: false).isEmpty) + XCTAssertTrue(store.entries.filter { $0.category == .color }.isEmpty) + + // Translation count unchanged (spec §6 US-CH5) + let translationCountAfter = store.entries.filter { $0.category == .translation }.count + XCTAssertEqual(translationCountAfter, translationCountBefore) + } + + // MARK: - Capacity Limit (spec §5.3) + + @MainActor + func testCapacityEvictsOldestEntry() { + let store = makeStore() + + // 51 sequential picks, oldest first inserted + for index in 0..<51 { + let hex = String(format: "#%02X%02X%02X", index, index, index) + store.addEntry(colorEntry(hex, timestamp: Date(timeIntervalSince1970: Double(index)))) + } + + // spec §5.3: 51 picks → oldest 1 evicted → 50 remain, oldest + // (#000000, index 0) gone, newest (#323232, index 50) at top + let remaining = store.colorEntries(matching: nil, favoritesOnly: false) + XCTAssertEqual(remaining.count, 50) + XCTAssertFalse(remaining.contains { $0.translatedText == "#000000" }) + XCTAssertEqual(remaining.first?.translatedText, "#323232") + } + + @MainActor + func testCapacityKeepsFavoriteFlagOnDuplicatePick() { + let store = makeStore() + let starred = colorEntry("#1A2B3C", favorite: true) + store.addEntry(starred) + + // Re-picking the same color must keep the favorite flag + store.addEntry(colorEntry("#1A2B3C")) + + let hits = store.colorEntries(matching: "1A2B3C", favoritesOnly: false) + XCTAssertEqual(hits.count, 1) + XCTAssertTrue(hits[0].isFavorite) + } + + // MARK: - Shared Pick Pipeline (spec §4.5 补工) + + @MainActor + func testRecordPickedColorInsertsCanonicalEntryAtTop() { + let store = makeStore() + store.addEntry(colorEntry("#111111")) + + // The shared entry point used by every eyedropper surface + store.recordPickedColor(hex: "#2B3C4D") + + let colors = store.colorEntries(matching: nil, favoritesOnly: false) + XCTAssertEqual(colors.map(\.translatedText), ["#2B3C4D", "#111111"]) + // Canonical fields (spec §3 data model) + XCTAssertEqual(colors[0].sourceText, "Color Picked") + XCTAssertEqual(colors[0].sourceLanguage, "RGB Hex") + XCTAssertEqual(colors[0].category, .color) + } + + @MainActor + func testRecordPickedColorDeduplicatesAndKeepsFavorite() { + let store = makeStore() + let starred = colorEntry("#AABBCC", favorite: true) + store.addEntry(starred) + + // Re-picking a previously starred color through the shared pipeline + store.recordPickedColor(hex: "#AABBCC") + + let hits = store.colorEntries(matching: "AABBCC", favoritesOnly: false) + XCTAssertEqual(hits.count, 1) + XCTAssertTrue(hits[0].isFavorite) + } + + @MainActor + func testRecordPickedColorBroadcastObserverMatches() { + // The `.colorDidPick` observer path (used by tray + toolbars) must + // produce the same store state as calling recordPickedColor directly. + let other = makeStore() + NotificationCenter.default.post(name: .colorDidPick, object: "#123456") + + // Observer hops through a MainActor Task; pump the queue once. + let exp = expectation(description: "observer insert") + DispatchQueue.main.async { exp.fulfill() } + wait(for: [exp], timeout: 2) + + XCTAssertEqual(other.entries.map(\.translatedText), ["#123456"]) + XCTAssertEqual(other.entries.first?.sourceText, "Color Picked") + XCTAssertEqual(other.entries.first?.sourceLanguage, "RGB Hex") + XCTAssertEqual(other.entries.first?.category, .color) + } + + // MARK: - Pick Hotkey (spec §4.2 empty-state hint) + + func testPickColorShortcutDefaultIsValidAndDistinct() { + let def = KeyboardShortcut.pickColorDefault + // Must carry a non-shift modifier to be registrable + XCTAssertTrue(def.isValid) + // Ctrl+Cmd+C — distinct from the plain Cmd+C clipboard binding and + // from all five capture-family defaults + XCTAssertNotEqual(def, .fullScreenDefault) + XCTAssertNotEqual(def, .selectionDefault) + XCTAssertNotEqual(def, .translationModeDefault) + XCTAssertNotEqual(def, .textSelectionTranslationDefault) + XCTAssertNotEqual(def, .translateAndInsertDefault) + // Display string is what the empty state shows + XCTAssertTrue(def.displayString.contains("C")) + } +} diff --git a/TransFrameTests/ShortcutRecordingTypeTests.swift b/TransFrameTests/ShortcutRecordingTypeTests.swift index 1030de6..59e4218 100644 --- a/TransFrameTests/ShortcutRecordingTypeTests.swift +++ b/TransFrameTests/ShortcutRecordingTypeTests.swift @@ -15,10 +15,11 @@ final class ShortcutRecordingTypeTests: XCTestCase { .selection, .translationMode, .textSelectionTranslation, - .translateAndInsert + .translateAndInsert, + .pickColor ] - XCTAssertEqual(allCases.count, 5) + XCTAssertEqual(allCases.count, 6) } // MARK: - Equatable @@ -38,7 +39,8 @@ final class ShortcutRecordingTypeTests: XCTestCase { .selection, .translationMode, .textSelectionTranslation, - .translateAndInsert + .translateAndInsert, + .pickColor ] for type in types { @@ -54,6 +56,8 @@ final class ShortcutRecordingTypeTests: XCTestCase { XCTAssertTrue(true) case .translateAndInsert: XCTAssertTrue(true) + case .pickColor: + XCTAssertTrue(true) } } } diff --git a/docs/specs/color-history-window.md b/docs/specs/color-history-window.md new file mode 100644 index 0000000..2987108 --- /dev/null +++ b/docs/specs/color-history-window.md @@ -0,0 +1,110 @@ +# Spec: 独立取色历史窗口(macOS + Windows 同步交付) + +- **Status**: Approved(决策 4,2026-11-02) +- **Parent PRD**: `tasks/prd-windows-transframe.md`(FR-41 / US-W26);macOS 侧对应新增 US +- **Scope**: 取色器拾取的颜色以独立窗口的形式提供历史浏览、复制、收藏、删除、清空 + +## 1. 概述 + +当前取色器拾取的颜色只作为 `HistoryCategory.color` 条目混入翻译历史列表,色块小、入口深、缺少专属交互。本特性新增一个**独立的取色历史窗口**:以大色块网格为主体的专属视图,单击复制 HEX,支持收藏、删除、搜索与清空。macOS 与 Windows **同一交互规格、同步交付**。 + +## 2. 动机 + +- 设计/开发用户高频取色,需要在旧颜色间快速回看与复制。 +- 通用历史列表对 color 条目的呈现(小缩略图 + 文本行)无法体现"颜色"这一主体信息。 +- 两平台规格统一,避免后续维护两套交互心智。 + +## 3. 数据模型(两平台一致,零迁移成本) + +复用现有 `TranslationHistory` / history `color` 类目条目,**不新增存储表**: + +| 字段 | 取值约定 | +|------|----------| +| `category` | `.color` / `HistoryCategory.color` | +| `translatedText` | HEX,如 `#1A2B3C`(大写,6 位) | +| `sourceText` | 固定文案 "Color Picked"(沿用现状,见 `HistoryStore.swift` addColor) | +| `sourceLanguage` | `"RGB Hex"`(沿用现状) | +| `thumbnailData` | 不使用(色块由 HEX 直接渲染,无需缩略图) | + +- 条目容量上限、自动清理策略沿用历史设置(`maxHistoryEntries` / Windows 侧 SQLite 同语义)。 +- Windows 侧为 SQLite 存储(PRD 决策 2:LIKE 检索),`meta_json` 预留 RGB/取色位置扩展位。 + +## 4. 交互规格(唯一权威定义,两平台 1:1) + +### 4.1 窗口 + +- 独立窗口(非弹层),标题"取色历史 / Color History"。 +- 默认尺寸 560×420,可缩放,记住位置与尺寸。 +- 入口 ×2:托盘菜单("取色历史"项,置于"翻译历史"之后);取色器完成一次取色后的悬浮提示中"查看历史"链接。 +- 深浅色跟随系统;macOS 用 NSVisualEffectView 侧边栏材质,Windows 用 Mica(PRD FR-50.1)。 + +### 4.2 主体网格 + +- 色块网格:自适应列(每格 ≥ 48×48 逻辑像素),色块下方显示 HEX(等宽字体)。 +- 悬浮:显示完整 HEX/RGB/取色时间 tooltip;右上角出现操作按钮(复制 / 收藏 / 删除)。 +- 收藏条目:色块右上角常显星标。 +- 空态:居中插图 + "还没有取色记录,使用取色器开始" + 取色快捷键提示。 + +### 4.3 顶栏操作 + +| 操作 | 行为 | +|------|------| +| 搜索框 | 按 HEX 片段过滤(大小写不敏感,如 `1A2`);空串 = 全部 | +| 仅收藏过滤 | 切换按钮,与搜索叠加生效 | +| 复制格式切换 | HEX(默认)/ RGB,记住选择 | +| 清空全部 | 二次确认对话框;仅清空 color 类目,不影响其他历史 | + +### 4.4 单条操作 + +| 操作 | 行为 | +|------|------| +| 单击色块 | 按当前复制格式写入剪贴板,色块上出现"已复制"浮标(1s 消失) | +| 右键 / 悬浮菜单 | 复制 HEX / 复制 RGB / 收藏(取消收藏)/ 删除 | +| 键盘 | Tab 网格导航;Enter = 复制;Space = 收藏切换;Delete = 删除;Esc = 清空搜索 | + +### 4.5 与取色器的联动 + +- 取色器完成取色后,窗口若打开则实时插入新条目(置顶,带高亮动画)。 +- 取色器悬浮提示保留"加入历史"现状逻辑不变。 + +## 5. 技术设计 + +### 5.1 macOS + +- 新增 `Features/History/ColorHistoryWindow.swift` + `ColorHistoryView.swift`(SwiftUI)。 +- `HistoryStore` 新增过滤 API:`colorEntries(matching:favoritesOnly:) -> [TranslationHistory]`;`@Published` 驱动实时插入。 +- 复制:`ClipboardService` 现有能力;收藏/删除复用 `HistoryStore.toggleFavorite / removeEntry`。 + +### 5.2 Windows + +- `App/Views/ColorHistoryPage`(WinUI 3):`GridView`(`ItemsRepeater` 或 `GridView`)+ DataTemplate(色块 + HEX TextBlock)。 +- 数据:`HistoryStore`(SQLite, LIKE 检索)同 API 形状 `colorEntries(matching, favoritesOnly)`。 +- 复制反馈:`TeachingTip` 或就地浮层;清空确认用 `ContentDialog`。 +- 无障碍:色块 AutomationPeer 名称 = HEX;键盘路径按 §4.4。 + +### 5.3 共享验收测试向量 + +- HEX 格式化(小写输入 → 大写展示、3 位扩展为 6 位)。 +- 搜索过滤(`1a2b` → `#1A2B3C` 命中)。 +- 容量上限:51 条取色 → 最旧 1 条被清理。 + +## 6. 用户故事与验收 + +**US-CH1** 取色后我在独立窗口看到新条目置顶出现。(打开窗口 → 取色 → 1s 内插入并高亮) +**US-CH2** 单击色块复制 HEX 并有即时反馈。(粘贴到记事本 == 色块 HEX) +**US-CH3** 我能只看收藏的颜色。(过滤后全部带星标) +**US-CH4** 我能按片段搜索颜色。(`1A2` 命中 `#1A2B3C`) +**US-CH5** 清空只清颜色,不动翻译/截图历史。(清空后其他类目条数不变) +**US-CH6** 键盘完整操作路径可达所有功能。(不碰鼠标完成复制/收藏/删除/搜索清空) +**US-CH7** 两平台同一测试脚本逐项通过(共享验收清单)。 + +## 7. 非目标 + +- 不做取色屏幕坐标回放/定位。 +- 不做颜色格式转换器(HSL/CMYK)编辑器。 +- 不做跨设备同步。 + +## 8. 交付与排期 + +- 归属 P2;纳入 PRD US-W26(Windows)与 macOS 侧对位 US,同版本发布(M5 或 macOS 下一 minor 版本)。 +- 两平台共用本 spec 的 §4 交互规格作为验收基线。 diff --git a/docs/windows/engines/baidu.md b/docs/windows/engines/baidu.md new file mode 100644 index 0000000..c061205 --- /dev/null +++ b/docs/windows/engines/baidu.md @@ -0,0 +1,74 @@ +# Baidu Translate — Windows engine card + +百度翻译开放平台 API(`FR-19`)。**AppID + 密钥** 双凭据;MD5 签名。 + +- **Raw 值**: `baidu` +- **默认端点**: `https://fanyi-api.baidu.com/api/trans/vip/translate` +- **凭据**: AppID + 密钥必填(`TransFrame/baidu`,同一 blob 内 `appID` + `apiKey`) +- **超时**: 10s 默认 +- **实现**: `windows/Core/include/tf/CloudProviders.hpp`(`BaiduProvider`) + +## 端点 + +| 用途 | 方法 | URL | +|---|---|---| +| 翻译 | GET | `https://fanyi-api.baidu.com/api/trans/vip/translate?q=...&from=...&to=...&appid=...&salt=...&sign=...` | +| 健康探测 | — | 无(有凭据 → 灰;缺 → 橙) | + +## 签名(`makeSign`) + +``` +sign = MD5( appid + q + salt + secretKey ) +``` + +- `salt`:每次请求随机 6 位数字(100000…999999) +- `q` 参与签名的是**原文**(未 URL 编码) +- 签名已知向量(RFC 1321): + - `MD5("abc")` = `900150983cd24fb0d6963f7d28e17f72` + - `MD5("")` = `d41d8cd98f00b204e9800998ecf8427e` + +## 翻译请求 + +每文本一个 GET(`q` 为单字符串,多文本逐条 — 与 macOS 一致): + +``` +GET /api/trans/vip/translate?q=Hello&from=en&to=zh&appid=20231205000&salt=483920&sign= +``` + +`q`、`from`、`to` 等参数 URL 编码。 + +## 翻译响应 + +```json +{ "from": "en", "to": "zh", "trans_result": [ { "src": "Hello", "dst": "你好" } ] } +``` + +## 语言映射(`mapLanguageCode`) + +| 输入 | 输出 | +|---|---| +| `zh-Hant`, `zh-TW` | `cht` | +| `zh-Hans`, `zh-CN`, `zh` | `zh` | +| `ja` | `jp` | +| `ko` | `kor` | +| `fr` | `fra` | +| `es` | `spa` | +| `de` / `pt` / `ru` / `it` / `en` | 原样 | +| 空 / `auto` | `auto` | +| 其它 | 原样(小写化后透传) | + +## 错误码映射(`error_code` 字符串) + +| `error_code` | ErrorCategory | 含义 | +|---|---|---| +| `54003` | `quota` | QPS 超限(速率) | +| `54004` | `auth` | 账户余额不足 / key 无效 | +| `52001` / `52002` 等 | `network` | 上游/系统错误 | +| 其它非空码 | `auth`(含码+`error_msg`) | | +| 响应无 `trans_result` / JSON 解析失败 | `content` | `Invalid Baidu response` | +| AppID 或密钥缺失 | `configuration` | `Baidu credentials incomplete` | + +## 与 macOS 差异 + +无。签名算法(MD5 实现为内置、不依赖平台 API)、salt 范围、逐文本 GET、 +`54003`/`54004` 映射与 `BaiduTranslationProvider.swift` 一致。 diff --git a/docs/windows/engines/custom.md b/docs/windows/engines/custom.md new file mode 100644 index 0000000..bde2de4 --- /dev/null +++ b/docs/windows/engines/custom.md @@ -0,0 +1,83 @@ +# Custom(OpenAI 兼容实例)— Windows engine card + +用户自定义 OpenAI 兼容端点(`FR-19`),支持**多实例**:每实例独立 UUID 身份 +(显示名可改,UUID 稳定)。 + +- **Raw 值**: `custom` +- **默认端点**: `http://localhost:8000/v1`(LM Studio 常用预设) +- **凭据**: 可选 — `hasAPIKey = false` 或 localhost 端点 → 无 key 可用 + (macOS PR#92 语义:本地服务不应因缺 key 被硬禁用) +- **凭据槽**: `TransFrame/custom:`(实例 UUID,显示名变更不影响) +- **超时**: 10s 默认 +- **实现**: `windows/Core/include/tf/CompatibleChatProvider.hpp` + +## 多实例模型 + +``` +CompatibleConfig { + id: "" // 稳定身份:凭据槽、prompt 绑定、链成员 + displayName: "LM Studio" // 仅 UI 展示 + baseURL: "http://localhost:8000/v1" + modelName: "qwen2.5" + hasAPIKey: false +} +``` + +- 调度链(ordered ≤5 / compare 2-4)里每实例是独立成员(`EngineChainItem::makeCompatible(uuid)`) +- 悬空 UUID(实例已删但链未更新)→ 跳过并记录失败,不炸链 +- `resolveConfigurationSnapshot`:以**已保存**的实例配置为准(显示名/URL 改后 + 链里的旧快照不生效),无匹配时回退默认 + +## 端点 + +| 用途 | 方法 | URL | +|---|---|---| +| 翻译 | POST | `/chat/completions` | +| 免费验证 | GET | `/models` | + +`appendingApiSuffix` 智能拼接:`base` 已含 `v1` 时不重复; +`localhost` → `127.0.0.1`。 + +## 翻译请求 + +OpenAI 形状,模型名来自实例配置: + +```json +POST /v1/chat/completions +Content-Type: application/json +[Authorization: Bearer ] ← 仅 hasAPIKey 且已存 key 时 + +{ + "model": "qwen2.5", + "temperature": 0.3, + "messages": [ { "role": "user", "content": "Translate the following text...Hello" } ] +} +``` + +## 翻译响应 + +OpenAI 兼容解析:`choices[0].message.content`;`finish_reason: length` → 截断错误; +批处理/分隔符语义与 LLM 引擎一致(`LLMTranslationCore` 共用)。 + +## 健康探测 + +- 悬空 UUID(已删)→ 红 +- `hasAPIKey` 且凭据槽空 → 橙 +- 其余 → GET `models`(免费):200 绿 / 失败红 + +## 错误码映射 + +| 条件 | ErrorCategory | +|---|---| +| 401 / 403 | `auth` | +| 429 | `quota` | +| 网络失败 / 5xx / 取消 | `network` | +| `finish_reason: length` / 响应异常 | `content` | +| baseURL 无效 | `configuration` | +| key 经非 localhost 明文 HTTP 发送 | `auth`(HTTPS 守卫) | + +## 与 macOS 差异 + +无。多实例 UUID、`custom:` 凭据槽、keyless localhost、`models` 免费验证、 +快照解析优先已保存配置 — 均与 `CompatibleTranslationProvider.swift`(含 PR#92) +语义一致。 diff --git a/docs/windows/engines/deepl.md b/docs/windows/engines/deepl.md new file mode 100644 index 0000000..bfa6abd --- /dev/null +++ b/docs/windows/engines/deepl.md @@ -0,0 +1,68 @@ +# DeepL — Windows engine card + +DeepL Translation API(`FR-19`)。API key 必填;免费版经 `api-free.deepl.com` 端点。 + +- **Raw 值**: `deepl` +- **默认端点**: `https://api.deepl.com/v2/translate`(`api-free.deepl.com` 可配置) +- **凭据**: 必填(`TransFrame/deepl`) +- **超时**: 10s 默认 +- **实现**: `windows/Core/include/tf/CloudProviders.hpp`(`DeepLProvider`) + +## 端点 + +| 用途 | 方法 | URL | +|---|---|---| +| 翻译 | POST | `https://api.deepl.com/v2/translate` | +| 健康探测 | — | 无(有 key → 灰;无 key → 橙;验证会翻译 "1" 消耗配额,不探测) | + +`normalizeEndpoint`:`baseURL` 去尾斜杠后补 `/translate`(已有则不重复); +免费版填 `https://api-free.deepl.com/v2`。 + +## 翻译请求 + +```json +POST /v2/translate +Authorization: DeepL-Auth-Key +Content-Type: application/json + +{ "text": ["Hello"], "target_lang": "DE" } +``` + +- `text` 是字符串数组 +- `source_lang` 省略时自动检测(小写;`auto` → 省略) +- `target_lang` 大写(DeepL API 规则,`targetCode`) + +## 语言大小写规则 + +| 输入 | source(小写) | target(大写) | +|---|---|---| +| `zh-Hans` / `zh` | `zh` | `ZH` | +| `zh-Hant` / `zh-TW` | `zh-hant` | `ZH-HANT` | +| `en-US` / `en-GB` | `en-us` | `EN` | +| `auto` / 空 | 省略 | — | + +## 翻译响应 + +```json +{ "translations": [ { "detected_source_language": "EN", "text": "Hallo" } ] } +``` + +`detected_source_language` 大写,直接透传到结果的 `sourceLanguage`。 + +## 错误码映射 + +| 条件 | ErrorCategory | 消息 | +|---|---|---| +| 403 | `auth` | `DeepL: invalid API key` | +| 456(配额耗尽,DeepL 专有码) | `quota` | `DeepL: quota exceeded (HTTP 456)` | +| 401 | `auth` | (statusError 映射) | +| 429 | `quota` | (statusError 映射) | +| 5xx / 网络失败 / 取消 | `network` | | +| 4xx 其它 | `content` | | +| 响应无 `translations` / JSON 解析失败 | `content` | `Invalid DeepL response` | +| key 缺失 | `configuration` | `DeepL API key not configured` | + +## 与 macOS 差异 + +无。`DeepL-Auth-Key` 头、大小写规则、456 配额映射与 +`DeepLTranslationProvider.swift` 一致。 diff --git a/docs/windows/engines/gemini.md b/docs/windows/engines/gemini.md new file mode 100644 index 0000000..30d798f --- /dev/null +++ b/docs/windows/engines/gemini.md @@ -0,0 +1,58 @@ +# Gemini — Windows engine card + +Google Gemini,经 OpenAI 兼容端点接入(`FR-19`)。API key 必填。 + +- **Raw 值**: `gemini` +- **默认端点**: `https://generativelanguage.googleapis.com/v1beta` +- **默认模型**: `gemini-2.0-flash` +- **凭据**: 必填(`TransFrame/gemini`) +- **超时**: 10s 默认 +- **实现**: `windows/Core/include/tf/LLMChatProvider.hpp`(`engine = Gemini` 分支) + +## 端点 + +| 用途 | 方法 | URL | +|---|---|---| +| 翻译 | POST | `https://generativelanguage.googleapis.com/v1beta/openai/chat/completions` | +| 健康探测 | — | 无(有 key → 灰;无 key → 橙) | + +Gemini 走 **OpenAI 兼容层**:请求/响应形状与 OpenAI 相同(`chat/completions`、 +Bearer 头、`choices[].message.content` 解析)。 + +## 翻译请求 + +```json +POST /v1beta/openai/chat/completions +Authorization: Bearer +Content-Type: application/json + +{ + "model": "gemini-2.0-flash", + "temperature": 0.3, + "messages": [ { "role": "user", "content": "Translate the following text...Hello" } ] +} +``` + +## 翻译响应 + +```json +{ "choices": [ { "message": { "content": "你好" }, "finish_reason": "stop" } ] } +``` + +截断/解析语义与 OpenAI 分支一致(`finish_reason: length` → `content` 错误)。 + +## 错误码映射 + +| 条件 | ErrorCategory | +|---|---| +| 401 / 403 | `auth` | +| 429 | `quota` | +| 5xx / 网络失败 / 取消 | `network` | +| `finish_reason: length` | `content` | +| 响应异常 / JSON 解析失败 | `content` | +| key 缺失 | `configuration` | +| key 经明文 HTTP 发送(非 localhost) | `auth`(HTTPS 守卫) | + +## 与 macOS 差异 + +无。macOS 亦使用 OpenAI 兼容端点(`v1beta/openai/chat/completions`)。 diff --git a/docs/windows/engines/google.md b/docs/windows/engines/google.md new file mode 100644 index 0000000..618a869 --- /dev/null +++ b/docs/windows/engines/google.md @@ -0,0 +1,78 @@ +# Google Translate — Windows engine card + +Google Cloud Translation API v2(`FR-19`)。API key 必填;无免费探测。 + +- **Raw 值**: `google` +- **默认端点**: `https://translation.googleapis.com/language/translate/v2` +- **凭据**: 必填(`TransFrame/google`) +- **超时**: 10s 默认 +- **实现**: `windows/Core/include/tf/CloudProviders.hpp`(`GoogleTranslateProvider`) + +## 端点 + +| 用途 | 方法 | URL | +|---|---|---| +| 翻译 | POST | `https://translation.googleapis.com/language/translate/v2?key=` | +| 健康探测 | — | 无(有 key → 灰;无 key → 橙) | + +key 经 URL query 传递(v2 惯例),经 HTTPS 加密通道。 + +## 翻译请求 + +```json +POST /language/translate/v2?key= +Content-Type: application/json + +{ + "q": ["Hello", "World"], + "format": "text", + "source": "en", + "target": "zh" +} +``` + +- `q` 是字符串数组(一次请求多文本) +- `source` 省略时 API 自动检测 +- `format: "text"` 避免被当 HTML 处理(`&` 等字符不被转义) + +## 翻译响应 + +```json +{ + "data": { + "translations": [ + { "translatedText": "你好", "detectedSourceLanguage": "en" }, + { "translatedText": "世界" } + ] + } +} +``` + +- `translations[i].translatedText` 与请求 `q[i]` 一一对应 +- `detectedSourceLanguage` 存在时填充结果的 `sourceLanguage` + +## 语言映射(`mapLanguageCode`) + +| 输入 | 输出 | +|---|---| +| `zh-Hant`, `zh-TW` | `zh-TW` | +| `zh-Hans`, `zh-CN`, `zh` | `zh`(基础码) | +| `en-US` 等 | 基础码(`en`) | +| 空 / `auto` | `auto`(省略 source 字段 → 自动检测) | + +## 错误码映射 + +| 条件 | ErrorCategory | +|---|---| +| 401 / 403(key 无效) | `auth` | +| 429 | `quota` | +| 5xx / 网络失败 / 取消 | `network` | +| 4xx 其它 | `content`(如 `Google HTTP 400`) | +| 响应无 `data.translations` / JSON 解析失败 | `content` | +| key 缺失 | `configuration` | +| 空文本 | `content`(`Cannot translate empty text`) | + +## 与 macOS 差异 + +无。请求体(`q[]` 数组 + `format` + `source`/`target`)与 +`GoogleTranslationProvider.swift` 一致;多文本单请求语义相同。 diff --git a/docs/windows/engines/mtran.md b/docs/windows/engines/mtran.md new file mode 100644 index 0000000..cf65db3 --- /dev/null +++ b/docs/windows/engines/mtran.md @@ -0,0 +1,81 @@ +# MTranServer — Windows engine card + +本地/自托管 LibreTranslate 兼容引擎(默认链首,`FR-18`)。无需凭据。 + +- **Raw 值**: `mtran`(与 macOS 设置 JSON 互通) +- **默认端点**: `http://localhost:8989` +- **凭据**: 无(`requiresAPIKey = false`) +- **超时**: 默认 10s(`Configuration.timeout`) +- **实现**: `windows/Core/include/tf/MTranServerProvider.hpp` + +## 端点 + +| 用途 | 方法 | URL | 说明 | +|---|---|---|---| +| 翻译 | POST | `http://:/translate` | JSON body | +| 健康探测 | GET | `http://:/health` → `/` → `/translate` | 探测梯子,2s 探测超时 | + +端点配置仅接受 `host`、`host:port`、`http://host[:port]`(`Configuration::parse`)。 +带路径/查询/非 HTTP scheme 一律拒绝(`Configuration` 无效 → 引擎不可用)。 + +## 翻译请求 + +```json +POST /translate +Content-Type: application/json + +{ "from": "en", "text": "Hello", "to": "zh" } +``` + +多文本时逐条发送(每文本一个请求);`from`/`to` 经过 +`normalizeLanguageCode` 归一(见下)。 + +## 翻译响应 + +```json +{ "result": "你好", "detected_language": "en" } +``` + +- `result` 空或缺失 → `content` 错误(`Empty translation`) +- `detected_language` 存在时填充 `TranslationResult.sourceLanguage`,否则回退请求值 + +## 语言归一(`normalizeLanguageCode`) + +| 输入 | 输出 | +|---|---| +| `zh-Hans`, `zh-CN`, `zh_hans`, `zh_cn` | `zh` | +| `zh-Hant`, `zh-TW`, `zh_hant`, `zh_tw` | `zh-TW` | +| `en-US`, `en-GB`, `en_us`, `en_gb` | `en` | +| `ja-JP`, `ja_jp` | `ja` | +| `ko-KR`, `ko_kr` | `ko` | +| 其它带 `-`/`_` | 取基础码 | +| `auto` | 透传 | + +## 健康探测(`/health` 梯子 + 5s TTL 缓存) + +`MTranServerHealthCache`(TTL 5s)缓存可达性;`probeEndpoint` 依次尝试 +`/health` → `/` → `/translate`: + +- 任一 2xx → 可达(`Reachable`) +- 401/403/404/405/429/501 在 `/health`、`/` 上 → 尝试下一级(网关可能只保护部分路径) +- 其它状态/传输失败 → `Unreachable` +- 取消 → `Cancelled` + +`EngineHealthChecker` 四态映射:可达 → 绿;不可达 → 红;无需凭据故无橙/灰分支。 + +## 错误码映射 + +| 条件 | ErrorCategory | 消息样例 | +|---|---|---| +| 连接拒绝/DNS/超时 | `network` | `MTranServer endpoint unreachable` | +| HTTP 5xx | `network` | `MTranServer HTTP 503` | +| 响应 JSON 解析失败 | `content` | `Invalid MTranServer response` | +| `result` 空/缺失 | `content` | `Empty translation` | +| 取消 | `network` | `cancelled` | +| 端点配置无效 | `configuration` | `Invalid MTranServer URL` | + +## 与 macOS 差异 + +无(PRD §6.12 白名单内)。探测梯子、TTL、语言归一与 +`MTranServerEngine.swift` 语义一致;唯一实现差异:探测默认端点固定 +`localhost:8989`(`makeDefault`),远程端点的探测由设置层传入实际配置。 diff --git a/docs/windows/engines/ollama.md b/docs/windows/engines/ollama.md new file mode 100644 index 0000000..3a9eea9 --- /dev/null +++ b/docs/windows/engines/ollama.md @@ -0,0 +1,59 @@ +# Ollama — Windows engine card + +本地 LLM 引擎(`FR-19`)。OpenAI 兼容端点,无需 key,`llama3` 默认模型。 + +- **Raw 值**: `ollama` +- **默认端点**: `http://localhost:11434` +- **默认模型**: `llama3` +- **凭据**: 无(keyless 本地端点) +- **超时**: 10s 默认 +- **实现**: `windows/Core/include/tf/LLMChatProvider.hpp`(`engine = Ollama` 分支) + +## 端点 + +| 用途 | 方法 | URL | +|---|---|---| +| 翻译 | POST | `http://127.0.0.1:11434/v1/chat/completions` | +| 免费验证 | GET | `http://127.0.0.1:11434/v1/models` | + +`localhost` 自动改写为 `127.0.0.1`;无 `Authorization` 头(keyless)。 + +## 翻译请求 + +与 OpenAI 形状一致(`/v1/chat/completions`、`messages` 数组、`temperature`), +但不带 `Authorization` 头: + +```json +POST /v1/chat/completions +Content-Type: application/json + +{ + "model": "llama3", + "temperature": 0.3, + "messages": [ { "role": "user", "content": "Translate the following text...Hello" } ] +} +``` + +## 翻译响应 + +OpenAI 兼容:`choices[0].message.content`;`finish_reason: length` → 截断错误 +(同 OpenAI 分支解析器)。 + +## 健康探测 + +无需凭据 → 永不橙。GET `v1/models`(免费):200 → 绿;连接拒绝 → 红。 + +## 错误码映射 + +| 条件 | ErrorCategory | +|---|---| +| 401 / 403 | `auth` | +| 429 | `quota` | +| 连接拒绝 / 5xx / 取消 | `network` | +| `finish_reason: length` | `content` | +| 响应异常 / JSON 解析失败 | `content` | + +## 与 macOS 差异 + +无。keyless 语义、`v1/models` 探测、明文 HTTP 允许(localhost,不走 HTTPS 守卫, +因为无 key 可泄露)。 diff --git a/docs/windows/engines/openai.md b/docs/windows/engines/openai.md new file mode 100644 index 0000000..4701e26 --- /dev/null +++ b/docs/windows/engines/openai.md @@ -0,0 +1,73 @@ +# OpenAI — Windows engine card + +Chat-completions LLM 引擎(`FR-19`)。API key 必填;`gpt-4o-mini` 默认模型。 + +- **Raw 值**: `openai` +- **默认端点**: `https://api.openai.com/v1`(可覆盖 `baseURL`) +- **默认模型**: `gpt-4o-mini` +- **凭据**: 必填(`TransFrame/openai`);keyless 仅当 `baseURL` 为 localhost(LM Studio / vLLM 预设) +- **超时**: 10s 默认 +- **实现**: `windows/Core/include/tf/LLMChatProvider.hpp`(`engine = OpenAI` 分支) + +## 端点 + +| 用途 | 方法 | URL | +|---|---|---| +| 翻译 | POST | `https://api.openai.com/v1/chat/completions` | +| 免费验证 | GET | `https://api.openai.com/v1/models` | + +`localhost`/`127.0.0.1` 主机名自动改写为 `127.0.0.1`(`resolveLocalhost`)。 + +## 翻译请求 + +```json +POST /v1/chat/completions +Authorization: Bearer sk-... +Content-Type: application/json + +{ + "model": "gpt-4o-mini", + "temperature": 0.3, + "messages": [ + { "role": "system", "content": "You are a professional translator..." }, + { "role": "user", "content": "Translate the following text from English to Chinese (Simplified)....\n\nText to translate:\nHello\n---\nWorld" } + ] +} +``` + +批处理由 `LLMTranslationBatching` 完成:多文本以 `\n---\n` 连接;含分隔符时 +prompt 追加「保留 `---` 分隔符」提示。温度默认 0.3(配置可覆盖)。 + +## 翻译响应 + +```json +{ "choices": [ { "message": { "content": "你好\n---\n世界" }, "finish_reason": "stop" } ] } +``` + +- 正文按 `\n---\n` 拆回逐文本结果 +- `finish_reason == "length"`(或 SSE `delta.finish_reason == "length"`)→ **截断错误**, + 绝不当成功(macOS `LLMResponseTruncationTests` 语义) +- SSE 流式响应逐段拼接 `delta.content` +- 正文里出现字面 `data:` 行不影响普通 JSON 解析(SSE 判定只认 body 以 `data:` 开头) + +## 健康探测 + +`EngineHealthChecker`:无 key → 橙(不发请求);有 key → GET `models` 列表(免费)→ +200 绿 / 其它红。 + +## 错误码映射 + +| 条件 | ErrorCategory | +|---|---| +| 401 / 403 | `auth` | +| 429 | `quota` | +| 5xx / 网络失败 / 取消 | `network` | +| `finish_reason: length`(截断) | `content` | +| 响应无 `choices` / JSON 解析失败 | `content` | +| API key 缺失 | `configuration` | +| key 经非 localhost 的明文 HTTP 发送 | `auth`(HTTPS 守卫拒绝,`guardApiKeyTransport`) | + +## 与 macOS 差异 + +无行为差异。macOS 的 apple 引擎在 Windows 不存在(PRD §6.12);OpenAI 分支的 +端点/头/批处理/截断判定与 `LLMTranslationProvider.swift` 逐条对齐。 diff --git a/tasks/briefs/brief-A-skeleton-core.md b/tasks/briefs/brief-A-skeleton-core.md new file mode 100644 index 0000000..612d129 --- /dev/null +++ b/tasks/briefs/brief-A-skeleton-core.md @@ -0,0 +1,34 @@ +# Brief A — Windows 工程骨架 + Core 可移植层(US-W01 + Core 适配) + +你是 TransFrame Windows 版的实现工程师之一。4 个并行子任务共用同一 PRD;你负责 A:解决方案骨架 + Core 层。 + +## 必读上下文(按序) +1. `tasks/prd-windows-transframe.md` — 总 PRD(§3 选型、§4 架构、§9 US-W01、附录 B 目录结构) +2. `TransFrame/Models/`(swift 模型,schema 源)+ `TransFrame/Services/Translation/VisualLineGrouping.swift`、`LLMTranslationBatching.swift`、`LLMTranslationResponseParser.swift` +3. `TransFrameTests/`(现有测试风格) + +## 交付范围(只做这些,不越界) +在 `windows/` 目录下创建: + +1. `TransFrame.sln` + 三个工程: + - `Core/TransFrame.Core.vcxproj`(静态库, C++20, /W4 /WX, x64+arm64):移植数据模型 —— Settings 模型(键名与 macOS UserDefaults `TransFrame.` 前缀一一对应)、Annotation 11 种、Screenshot/CaptureDocument、OCREngineType、TranslationEngineType(**无 apple 引擎**)、EngineChainItem/EngineModeV2、TranslationScene/SceneEngineBinding、TranslationPromptConfig、TranslationResultBundle/BilingualSegment、TranslationHistory(4 类)、ExportFormat(PNG/JPEG/HEIC)、AppLanguage(10 语言) + - `NativeShell/TransFrame.NativeShell.vcxproj`(静态库,本任务仅建空骨架 + pch,捕获/UIA 留给任务 B) + - `App/TransFrame.App.vcxproj`(WinUI 3 桌面应用:空白窗口 + 打包工程,具体 UI 留给 B/C 后续) + - `Tests/TransFrame.Core.Tests.vcxproj`(Catch2 v3 单测) +2. Core 移植要求: + - JSON 用 nlohmann(vendored 或 vcpkg.json,写明依赖清单与安装命令) + - `VisualLineGrouping.mergeLines` 完整移植 + **与 macOS 测试向量同源**:从 `TransFrameTests` 提取现有向量数据为 `Tests/fixtures/visual-line-grouping.json`(若 swift 测试内嵌向量,复制数值,注明出处) + - `LLMTranslationBatching`/`LLMTranslationResponseParser` 移植 + 单测 + - `TranslationPromptConfig` 占位符解析({source_language}/{target_language}/{text})+ 单测 +3. CI:`.github/workflows/windows-ci.yml` — windows-latest, msbuild Release 双架构, 运行 Catch2 测试 +4. `windows/README.md` — 构建/测试/依赖安装说明 + +## 明确约束 +- 不实现捕获/OCR/翻译网络/托盘(B/C 的范围),但要在 Core 中定义好接口(纯虚 `IOcrEngine`、`ITranslationProvider`、`IHotkeyListener` 等,头文件带文档注释) +- 已裁决决策(PRD 文首):不内置模型、无 FTS5、仅 MSIX、Apple 引擎不存在 +- 所有模型字段与 macOS swift 版语义一致;不确定处标 `// TODO(schema-align)` 并在报告中列出 + +## 完成标准 +- `msbuild Release x64` 与 `arm64` 双绿(本机无 Windows 则以 CI 配置正确 + CMake/MSBuild 工程文件静态审查为完成标准,报告注明 NOT RUN 的部分) +- Catch2 单测全绿(至少覆盖:prompt 解析、视觉行分组、LLM 批量解析、settings JSON 往返) +- 报告:文件清单、接口清单、schema 对齐差异表、未运行项与原因 diff --git a/tasks/briefs/brief-B-capture-shell.md b/tasks/briefs/brief-B-capture-shell.md new file mode 100644 index 0000000..8e5a5f5 --- /dev/null +++ b/tasks/briefs/brief-B-capture-shell.md @@ -0,0 +1,31 @@ +# Brief B — Windows 捕获与热路径 UI 层(US-W02/03/04/05 + 覆盖层/选区) + +你是 TransFrame Windows 版的实现工程师之一。4 个并行子任务共用同一 PRD;你负责 B:屏幕捕获 + 全屏选区覆盖层 + 窗口检测 + 热键 + 托盘。 + +## 必读上下文(按序) +1. `tasks/prd-windows-transframe.md` §3.2 API 映射表、§6.1(FR-01…06)、§6.7(FR-33/34)、§8 性能预算 +2. `docs/specs/window-detection-auto-select.md` — 窗口自动识别的完整交互规格(Windows 版语义一致,API 换用 EnumWindows/DWM) +3. `TransFrame/Features/Capture/`(SwiftUI 参考:SelectionOverlayWindow/SelectionInPlaceToolbar/InPlaceResultsPanel 行为) +4. 任务 A 产出的 `windows/Core/`(模型与接口;若未就绪,按 PRD §4 接口契约先行开发,后续对齐) + +## 交付范围(只做这些,不越界) +在 `windows/NativeShell/`(+ 必要的 App 侧接入点)实现: + +1. **WGC 捕获服务**:`CaptureService`(Windows.Graphics.Capture,per-monitor GraphicsCaptureItem;`IsBorderRequired=false`(contract 15,失败降级);DXGI Duplication 与 GDI BitBlt 回退链);输出统一为 Core 的 `Screenshot`(物理像素 + DPI 元数据) +2. **显示器枚举**:`DisplayMonitor`(EnumDisplayMonitors + GetDpiForMonitor,Per-Monitor V2;带 2s 缓存刷新策略,对齐 macOS DisplayFreshnessPolicy) +3. **窗口检测**:`WindowDetector`(EnumWindows + DwmGetWindowAttribute(DWMWA_EXTENDED_FRAME_BOUNDS/CLOAKED);`windowUnderPoint()` 悬停查询 ≤1ms) +4. **全屏选区覆盖层**:`SelectionOverlay`(WS_POPUP+WS_EX_LAYERED+WS_EX_TOPMOST,跨全部显示器;Direct2D 1.1 + DirectComposition 渲染:40% 变暗、选区挖亮、1px 高亮描边、尺寸徽标、十字准线、窗口高亮(单击=整窗)、拖拽=手动圈选、Esc 取消;120Hz 下绘制路径 ≤8ms) +5. **全局热键**:`HotkeyManager`(RegisterHotKey/WM_HOTKEY ×5;注册失败=冲突上报;运行时重注册生效) +6. **托盘**:`TrayIcon`(Shell_NotifyIcon;左键 MenuFlyout:全屏/区域/翻译/划词/插入/历史/设置/退出占位 + 最近 5 张截图缩略图位) +7. 单元测试(Catch2):窗口检测几何(DWM bounds vs WindowRect 差异用例)、DPI 换算、热键冲突矩阵、显示器缓存策略 + +## 明确约束 +- 不做翻译/OCR/预览窗口/标注(C 与后续任务范围);就地工具栏(FR-05)只做布局骨架不接功能 +- UIA 划词不在本任务(归 C) +- 所有窗口 Per-Monitor V2 DPI 感知(manifest 声明) +- 性能预算硬指标:热键→覆盖层出现 ≤60ms;松开→截图产物 ≤50ms(含 GPU→CPU 一次拷贝) + +## 完成标准 +- 代码可编译(或 CI 绿;本机 macOS 无法编译 Windows 目标时,给出静态审查清单 + NOT RUN 标注) +- 每个服务一个 `docs/windows/*.md` 简要设计说明(API 选择理由 + 回退链) +- 报告:实现清单、与 PRD FR 映射表、已知限制(如 Win10 黄边框降级路径) diff --git a/tasks/briefs/brief-C-translation-services.md b/tasks/briefs/brief-C-translation-services.md new file mode 100644 index 0000000..2306455 --- /dev/null +++ b/tasks/briefs/brief-C-translation-services.md @@ -0,0 +1,29 @@ +# Brief C — Windows 翻译/OCR 服务层(US-W06/07/08/09 + 引擎注册表 + 划词/插入) + +你是 TransFrame Windows 版的实现工程师之一。4 个并行子任务共用同一 PRD;你负责 C:OCR 引擎 + 10 个翻译引擎接入 + V2 链式/对比调度 + 划词与插入。 + +## 必读上下文(按序) +1. `tasks/prd-windows-transframe.md` §6.3(FR-15…17)、§6.4(FR-18…27)、§6.5(FR-28/29)、§3.2(UIA/Credential Manager 映射) +2. Swift 参考实现:`TransFrame/Services/OCREngine*.swift`、`Services/Translation/`(TranslationEngineRegistry/Providers/LLMTranslationProvider/CompatibleTranslationProvider)、`Services/EngineHealthChecker.swift`、`MTranServerEngine.swift`、`Features/TextTranslation/`(TextTranslationFlow/插入流程) +3. 任务 A 的 `windows/Core/` 接口与模型(未就绪则按接口契约先行) + +## 交付范围(只做这些,不越界) +在 `windows/NativeShell/`(服务部分)+ `windows/Core/`(纯逻辑)实现: + +1. **OCR**:`WindowsOcrEngine`(Windows.Media.Ocr;语言包可用性检测 + TextSegment[] 映射:text+归一化 bbox+confidence);`PaddleOcrEngine`(外部进程协议,fast/precise,健康检查缓存);`VlmOcrEngine` 骨架(五 Provider 接口位,HTTP 细节同翻译层复用) +2. **翻译引擎 ×9**(**无 apple**):MTranServer、OpenAI、Claude、Gemini、Ollama、Google、DeepL、Baidu、Custom 兼容(含多实例 UUID)。统一 `ITranslationProvider`;WinHTTP 封装(超时默认 10s、取消 token、错误分类=网络/配额/鉴权/内容) +3. **调度**:`EngineRegistry` + ordered 链(≤5 逐个回落,聚合错误)+ compare 并行(2-4,结果缓存免重译);场景绑定路由(screenshot/text_selection/translate_and_insert) +4. **可用性探测**:`EngineHealthChecker`(绿/红/橙/灰;仅轻量端点不烧配额;缓存 TTL 对齐 macOS) +5. **密钥**:`KeyStore`(Credential Manager CredWrite/CredRead,`TransFrame//`;UI 侧显示 `sk-****last4`) +6. **划词**:`TextExtractor`(UIA TextPattern GetSelection 优先 → 模拟 Ctrl+C 剪贴板回退(保存/恢复原剪贴板));`InsertionService`(UIA 目标重验证 + SendInput Ctrl+V 粘贴回退,重验证失败绝不粘贴) +7. 单元测试:ordered 链回退矩阵(mock provider 注入延迟/失败)、compare 结果缓存、LLM 批量/解析(复用 A 的 fixtures)、UIA 几何(mock)、错误分类映射 + +## 明确约束 +- 不做 UI(设置页/弹窗归后续任务);提供控制台测试入口 `tests/manual/smoke_translation.cpp` 手工验证 +- 已裁决:不内置任何模型 —— Ollama/兼容端点只是 HTTP 接入 +- HTTP 层不依赖 UI 框架,可被 Core 测试直接驱动 + +## 完成标准 +- Catch2 全绿(链调度/探测缓存/KeyStore mock/批量解析) +- 每引擎一个请求/响应样例文档 `docs/windows/engines/.md`(端点、参数、错误码映射表) +- 报告:FR 映射、与 macOS 行为差异点清单(如有,需对齐 PRD §6.12 白名单,超出即报缺陷) diff --git a/tasks/briefs/brief-D-color-history-macos.md b/tasks/briefs/brief-D-color-history-macos.md new file mode 100644 index 0000000..2e3a2a2 --- /dev/null +++ b/tasks/briefs/brief-D-color-history-macos.md @@ -0,0 +1,33 @@ +# Brief D — macOS 取色历史独立窗口(FR-41 macOS 侧,与 Windows 同规格) + +你是 TransFrame macOS 侧的实现工程师。4 个并行子任务共用同一 PRD;你负责 D:独立取色历史窗口(macOS 实现)。 + +## 必读上下文(按序) +1. `docs/specs/color-history-window.md` — **唯一权威交互规格**(§3 数据模型、§4 交互、§5.1 macOS 技术设计、§6 验收) +2. `tasks/prd-windows-transframe.md` FR-41/US-W26(Windows 侧对位,规格同源) +3. 现有实现:`TransFrame/Services/HistoryStore.swift`(addColor 条目约定、entries 发布、收藏/删除)、`TransFrame/Features/History/HistoryView.swift` + `HistoryWindowController.swift`(窗口管理惯例)、`TransFrame/Services/ClipboardService.swift`、`TransFrame/Features/Preview/PreviewToolBar.swift`(eyedropperButton 取色入口)、`TransFrame/Features/MenuBar/MenuBarController.swift`(托盘菜单项惯例) + +## 交付范围(只做这些,不越界) +1. `TransFrame/Features/History/ColorHistoryView.swift`: + - 网格色块(每格 ≥48×48pt,自适应列)+ 等宽 HEX 文本 + - 悬浮 tooltip(HEX/RGB/时间)+ 悬浮操作(复制/收藏/删除);收藏右上角星标常显 + - 空态视图(插图 + 提示 + 取色快捷键) +2. `TransFrame/Features/History/ColorHistoryWindowController.swift`: + - 独立窗口(默认 560×420,记住位置尺寸,深浅色跟随,NSVisualEffectView 侧栏材质) + - 单开复用(重复打开聚焦已有窗口) +3. `HistoryStore` 扩展:`colorEntries(matching: String?, favoritesOnly: Bool) -> [TranslationHistory]`(HEX 片段大小写不敏感过滤);新取色实时置顶插入(窗口打开时高亮动画) +4. 顶栏:搜索框、仅收藏过滤、复制格式切换(HEX 默认/RGB,记住选择)、清空(二次确认,仅 color 类目) +5. 键盘:Tab 网格导航、Enter=复制、Space=收藏、Delete=删除、Esc=清空搜索(spec §4.4) +6. 入口 ×2:MenuBarController 菜单"取色历史"(置于"翻译历史"之后);取色完成悬浮提示"查看历史"链接(若现有取色完成无悬浮提示,则加一个轻量 toast,1.5s 消失) +7. 测试(XCTest,风格对齐现有 TransFrameTests):HEX 格式化(小写→大写、3 位→6 位)、搜索过滤、仅收藏叠加、清空仅影响 color 类目、容量上限清理最旧 +8. 本地化:所有新字符串进 `Localizable.strings`(10 语言至少 en/zh-Hans 全量,其余语言用英文占位 + 注释待翻译) + +## 明确约束 +- 不改 Windows 侧任何文件;不动 history 存储结构(零迁移) +- 复制格式切换与搜索状态持久化用现有 UserDefaults 惯例(`TransFrame.` 前缀新键要列在报告里) +- 遵守仓库 CONTRIBUTING/现有代码风格;Swift 6 并发注解对齐 + +## 完成标准 +- `swift build` 或 Xbuild 工程构建通过;XCTest 新增用例全绿(无法在本机跑则标注 NOT RUN + 命令) +- spec §6 US-CH1…CH6 逐条自验收并在报告中给出结果 +- 报告:文件清单、新增 UserDefaults 键、字符串键清单、与 spec 的偏差(如有必须为 0 或列为待裁决) diff --git a/tasks/briefs/report-A.md b/tasks/briefs/report-A.md new file mode 100644 index 0000000..d4ce674 --- /dev/null +++ b/tasks/briefs/report-A.md @@ -0,0 +1,112 @@ +# 子任务 A 完成报告(US-W01:解决方案骨架 + Core 可移植层) + +**状态:完成**(macOS 本机 clang++ 20 编译 + Catch2 全绿:68 test cases / 261 assertions)。 +MSVC/WinUI/MSIX 未在本机运行(无 Windows),CI 与复现命令见下。 + +## 一、文件清单 + +### Core 模型(windows/Core/) + +| 文件 | 内容 | 新增/修订 | +| --- | --- | --- | +| `SettingsKeys.h` | AppSettings.swift `Keys` 枚举全部键(含 per-provider `vlmBaseURL.` 函数式键、history key),逐键同名 | 新增 | +| `KeyboardShortcut.h` | 键码+修饰位、5 个默认快捷键(Cmd+Shift+3/4/T/Y/I 的 Carbon 码)、`{"keyCode","modifiers"}` JSON | 新增 | +| `Annotation.h/.cpp` | 11 种标注完整移植:rectangle/freehand/arrow/text/ellipse/line/mosaic/highlight/numberLabel/privacyRedaction/calloutBubble。std::variant 载荷 + tagged-JSON(`{"type","value"}`);各类 isValid/bounds/clamp 逻辑与 Swift 相同(含 NumberLabel 12–256 clamp、Mosaic 4–128、Highlight 0.1–0.8、箭头 bounds 的 lineWidth*3 padding) | 新增 | +| `CaptureDocument.h/.cpp` | DisplayInfo(resolution/isRetina/pixelSize)、OCRText/OCRResult(fullText 按 minY 排序、filteredBy、observationsIn)、TextSegment、ScreenAnalysisResult(filter/recoveringFilteredSegments/updatingSegment/fromOcr)、Screenshot(estimatedFileSize/formattedFileSize/aspectRatio;ImageRef=uint64 句柄代替 CGImage)、QuartzGlobalRect、CaptureDocument(全部 revision 字段) | 新增 | +| `TranslationResultBundle.h/.cpp` | TranslationResult(combine/emptyFor)、BilingualSegment(fromResult/fromSegment/pixelBoundingBox)、EngineResult(isSuccess/failed)、TranslationErrorCategory 6 类、EngineSelectionMode(legacy 4 模式 raw 值)、TranslationResultBundle(primaryResult 回退逻辑/hasErrors/allFailed/successfulEngines/failedEngines/single/failed) | 新增 | +| `TranslationHistory.h/.cpp` | HistoryCategory 4 类(raw/displayName/SF Symbol 名)、TranslationHistory 全字段 + Swift decodeIfPresent 默认(category→translation、isFavorite→false)、4 类工厂:`fromTranslationResult`/`colorPicked`(Color Picked/RGB Hex/hex 同值约定)/`uploaded`(markdown/URL/provider/Public URL)/`screenshotSaved`;matches 大小写不敏感子串、sourcePreview 500 截断 | 新增 | +| `VLMProviderType.h/.cpp` | 5 provider(raw 值、默认 baseURL/model、requiresAPIKey)、OpenAIAPIMode、PaddleOCRMode、CompatibleConfig(nil-UUID 默认实例、keychainId `custom:`) | 新增 | +| `VisualLineGrouping.h/.cpp` | mergeLines/belongsToSameLine/mergedSegment/joinText 完整移植;**修复了本移植过程中的一个真实 bug**:lineBox 必须只由已有行碎片构成(与 Swift 一致),首版误把新碎片并入 union 导致全部合一行——测试向量当场抓住,已修复 | 新增 | +| `LLMTranslationCore.h/.cpp` | LLMTranslationBatching(separator `\n---\n`、UTF-16 计数、splitLongText 按码点切、prompt {text} 成本扣除)+ LLMTranslationResponseParser(JSON 与 SSE 双方言、仅首行 `data:` 判流、error.message 透传、Claude stop_reason/content[].text、OpenAI choices/finish_reason/delta.content、截断→incomplete) | 新增 | +| `Interfaces.h` | 纯虚接口(全部带文档注释):`IOcrEngine`、`ITranslationProvider`(+`TranslateRequest`)、`IHotkeyListener`、`IClipboard`、`IHistoryStore`、`ICredentialStore`、`OcrImage`(BGRA8 跨平台图像) | 新增 | +| `TranslationPromptConfig.h` | 占位符解析(既有草稿,本任务补测) | 审查通过 | +| `Geometry.h`/`Uuid.h`/`Json.h/.cpp`/`TranslationEngineType.h`/`TranslationScene.h`/`EngineSelectionV2.h`/`TranslationEngineConfig.h`/`SceneEngineBinding.h`/`AppLanguage.h`/`OCREngineType.h`/`ExportFormat.h`/`Styles.h` | 既有草稿修订:修复 `boundingBox.height()` 误当函数调用;`from_json` 统一 `const Json&`(nlohmann ADL 要求);`SceneEngineBinding` 补 `operator==`;`Json.h` 补 `nlohmann::adl_serializer` 特化(std::chrono 命名空间 ADL 不可达) | 修订 | + +### 工程文件 + +| 文件 | 说明 | +| --- | --- | +| `windows/TransFrame.sln` | 4 工程 × Debug/Release × x64/ARM64(Core/NativeShell/App/Tests) | +| `windows/Core/TransFrame.Core.vcxproj` | 静态库,C++20 `/W4 /WX` 双架构 | +| `windows/NativeShell/TransFrame.NativeShell.vcxproj` | 静态库空骨架 + pch(任务 B 填充);依赖 Core | +| `windows/NativeShell/pch.h/.cpp`、`NativeShellSkeleton.cpp` | pch 与占位 TU | +| `windows/App/TransFrame.App.vcxproj` | 应用工程:Win32 空白窗口入口(WinUI 3 NuGet 注释开关就绪,任务 B 切换 XAML island);依赖 Core+NativeShell | +| `windows/App/AppMain.cpp` | 空白窗口 + 消息泵 | +| `windows/App/TransFrame.Package.wapproj` + `Package.appxmanifest` | MSIX 打包骨架:startupTask 扩展、graphicsCapture 受限能力、占位 Identity | +| `windows/Tests/TransFrame.Core.Tests.vcxproj` | Catch2 测试工程,fixture 复制到输出目录 | +| `windows/Tests/TestMain.cpp` | Catch2 入口 | +| `windows/Tests/CoreModelsTests.cpp` | schema 对齐 30+ 用例(wire 形状断言逐字段) | +| `windows/Tests/VisualLineGroupingTests.cpp` | Swift 同向量 16 用例 + fixture 文件驱动复验 | +| `windows/Tests/LLMTranslationCoreTests.cpp` | 截断/JSON/SSE/分批 12 用例 | +| `windows/Tests/TranslationPromptConfigTests.cpp` | 优先级/占位符 7 用例 | +| `windows/Tests/fixtures/visual-line-grouping.json` | 从 `TransFrameTests/VisualLineGroupingTests.swift` 逐条提取(12 case + 3 joinText,文件头注明出处与坐标系) | +| `.github/workflows/windows-ci.yml` | windows-latest msbuild 双架构跑 Catch2 + ubuntu g++-13 portable-check(防 Win32 泄漏进 Core) | +| `windows/README.md` | 构建/测试/依赖/模型清单/未运行项 | +| `windows/external/README.md` + `nlohmann/LICENSE.MIT` + `catch2/LICENSE.txt` | vendored 依赖来源、版本、重下命令、许可证 | + +## 二、接口清单(Core/Interfaces.h,全部纯虚 + 文档注释) + +- `IOcrEngine`:`id()/name()/isAvailable()/recognize(OcrImage)->OCRResult`(归一化 bbox、置信度) +- `ITranslationProvider`:`id()/name()/engineType()/isAvailable()/translate(TranslateRequest, out)->optional/verifyConnection()->optional`(verifyConnection 禁打计费端点,注释明示) +- `IHotkeyListener`:`registerShortcut(actionId, KeyboardShortcut)/unregisterShortcut/nextFiredAction` +- `IClipboard`:`copyImage(PNG)/copyText/readText/hasImage` +- `IHistoryStore`:`entries/add/remove/toggleFavorite/save/reload`(≤50 条上限注释) +- `ICredentialStore`:`save/load/remove/has`(账户命名 `TransFrame//`) +- 辅助值类型:`OcrImage`(BGRA8)、`TranslateRequest` + +## 三、Schema 对齐差异表(Windows vs macOS) + +| 项目 | macOS | Windows 处理 | 状态 | +| --- | --- | --- | --- | +| CGRect wire | `[[x,y],[w,h]]` | 相同(`Json.h` to_json/from_json + 测试断言 dump 字面量) | 已测 | +| UUID wire | 大写 8-4-4-4-12 | 相同;parse 容忍大小写/花括号,malformed 抛 `invalid_argument` | 已测 | +| Date wire | 2001-01-01Z 纪元秒(double) | 相同;`adl_serializer` 特化使 initializer-list 可用 | 已测(0.0 ↔ 978307200 unix) | +| Data wire | base64 | `encodeBase64/decodeBase64`;PNG 头向量 `iVBORw0K` 对拍 | 已测 | +| enum 带载荷(EngineChainItem.Kind) | `{"builtin":{"_0":"openai"}}` | 相同字面量断言;compatible 变体同 | 已测 | +| enum-keyed Dictionary(promptConfig 等) | 键值交替数组 | 相同(既有草稿实现,本任务补 prompt 单测) | 已测 | +| TranslationEngineType.apple | 存在(10 案例第 1 位) | **不存在**(PRD §6.12);chain item 读到 `apple` 抛异常→调用方丢条目(降级在设置层);engineConfigs `id:"apple"` 同 | 已测(THROWS 断言) | +| SceneEngineBinding 默认 primary | `.apple` | `.mtran`;fallback=`custom`(**TODO(schema-align)** 原注释保留:与 C 任务最终裁决对齐——C 的 CoreModels 无此默认,按 PRD §6.12 mtran 为链首;若协调者裁决不同,改 `defaultFor` 一处即可) | 已定待复核 | +| OCREngineType.vision | 本地默认 | 读入映射为 `windows`;`windows`/`paddleocr` 原样 | 已测 | +| CompatibleConfig 默认 id | nil UUID `00000000-…` | 相同(keychainId 对拍) | 已测 | +| Annotation 编码 | Swift enum 未走 Codable 存档 | 显式跨平台 tagged JSON `{"type","value"}`(11 类 round-trip 全测);macOS 文档存档走 CaptureDocument 几何原语,不冲突 | 设计决策 | +| Screenshot CGImage | 运行时对象不可编码 | `ImageRef`(uint64) 句柄;dimensions 查询留 NativeShell 钩子(Core 返回 0×0) | 骨架 | +| EngineError | Swift 任意 Error | `TranslationErrorCategory`(6) + message 字符串 | 等价收窄 | +| 历史条目 4 类约定 | HistoryStore 内联构造 | 工厂函数 `colorPicked/uploaded/screenshotSaved/fromTranslationResult`,字段逐一对齐 | 已测 | + +## 四、测试输出摘要(本机执行) + +``` +$ clang++ -std=c++20 -Wall -Wextra -Werror -I windows -I windows/external \ + windows/Core/*.cpp windows/external/catch2/catch_amalgamated.cpp windows/Tests/*.cpp \ + -o build/tests_runner # 退出码 0,零警告(-Werror 下) + +$ ./build/tests_runner +=============================================================================== +All tests passed (261 assertions in 68 test cases) +``` + +用例分布:visual-line-grouping 16(含 fixture 文件驱动复验)、llm 12、prompt 7、schema/模型 33。 +向量与 `TransFrameTests/VisualLineGroupingTests.swift`、`LLMResponseTruncationTests.swift` 同源;fixture 文件头注明出处。 + +关键回归(移植中实际抓住并修复):`belongsToSameLine` 的 lineBox 首版把候选碎片并入 union,导致三行样例合为一行——Swift 源码复核后修正为 union 仅含已有行碎片,16 个向量全绿。 + +## 五、未运行项 + Windows 复现命令 + +| 未运行 | 复现命令(Windows) | +| --- | --- | +| MSVC x64/ARM64 编译 | `msbuild windows\TransFrame.sln /m /p:Configuration=Release /p:Platform=x64`(ARM64 同理换 Platform) | +| Catch2 于 Windows 运行 | `windows\build\x64\Release\TransFrame.Core.Tests\TransFrame.Core.Tests.exe` | +| WinUI 3 / WindowsAppSDK 还原 | vcxproj 中 PackageReference 注释块取消注释后 `msbuild /restore /t:Build`(任务 B 接管) | +| MSIX 打包签名 | `TransFrame.Package.wapproj` 构建;Identity/Publisher 为占位,发版前换真证书 | +| CI 首跑 | push 后 `.github/workflows/windows-ci.yml`(core-tests 双架构 + ubuntu portable-check) | + +本机(macOS)等价验证已跑:上述 clang 单命令编译 + 全量测试;`Core/*.cpp` 以 `-fsyntax-only` 独立过检(证明无 Win32 泄漏)。 + +## 六、与任务 C(win-translation-services)模型对齐说明 + +C 的 `windows/Core/include/tf/CoreModels.hpp`(已测全绿)与本任务 `windows/Core/`(tf::core 命名空间)关系: + +- **语义对齐、命名空间并存**:C 用 `tf::`(服务层),A 用 `tf::core::`(应用骨架层)。两者 schema 语义一致(UUID 大写 wire、CGRect 嵌套数组、引擎 raw 值、无 apple、enum-keyed dict 交替数组、UTF-16 计数 batching、parser 双方言)。 +- **算法对齐**:`VisualLineGrouping`、`LLMTranslationBatching`、`LLMTranslationResponseParser` 三者与 C 的 `tf/VisualLineGrouping.hpp`、`tf/LLMTranslationCore.hpp` 逐函数同语义(阈值 0.5/3.0、`\n---\n`、UTF-16 计数、首行 data: 判流、截断→incomplete);本任务独立重写并再次以 Swift 原向量验证(含 C 未覆盖的 belongsToSameLine lineBox 归属 bug 修复——C 的实现 union 输入正确,无此问题)。 +- **接口对齐**:A 的 `IOcrEngine`/`ITranslationProvider` 签名与 C 的同名接口(`Outcome` vs 本任务 `(result, out-error)` 双出参)有意不同:A 面向应用骨架(无 HttpTransport 依赖),C 面向服务层。**待协调者裁决**:B/C 合流时若采用 C 的服务层实现,App 侧用一层薄适配(`Outcome→optional`)即可,模型二选一落盘(建议保留 A 的 `tf::core` 作为 App 内唯一模型,C 层在其上做 transport)。 +- **不重复造轮子的边界**:A 未实现 HTTP/credential/调度(C 已有),只定义接口;C 的 `Uuid`(mt19937+random_device)与 A 的 `Uuid`(BCrypt/random_device 回退)wire 格式一致,互通无障碍。 diff --git a/tasks/briefs/report-B.md b/tasks/briefs/report-B.md new file mode 100644 index 0000000..8f7d2fe --- /dev/null +++ b/tasks/briefs/report-B.md @@ -0,0 +1,125 @@ +# Report B — Windows 捕获壳层(Win-Capture-Shell) + +- 分支:`hubo/win-capture-shell`(基于 `hubo/feat-windows` @ 9e9f9b0) +- 交付目录:`windows/NativeShell/`(+ `windows/docs/windows/*.md`) +- 验证:**Catch2 v3.7.1 · 60 用例 / 235 断言 全绿**(macOS arm64 clang 21 实测运行) +- Windows 侧编译:**NOT RUN**(本机 macOS;复现命令见 §6) + +--- + +## 1. 实现清单 + +### 1.1 头文件(`windows/NativeShell/include/tf/`) + +| 文件 | 内容 | +|---|---| +| `Geo.hpp` | Point/Size/Rect(int64 物理像素,半开区间,纯头文件) | +| `CoreTypes.hpp` | 对任务 A 的最小依赖自声明:PixelBuffer(BGRA8+stride+DPI)、DisplayInfo(物理 frame+DPI+scale)、Screenshot(物理像素+DPI 元数据+CaptureTrigger)、HotkeyAction ×5 | +| `DisplayMonitor.hpp` | DisplayMonitorService + DisplayFreshness 三态(Cached/AlwaysRefresh/RefreshIfOlderThanMs)+ IDisplayEnumerator/IClock 注入口 | +| `WindowDetector.hpp` | WindowInfo(DWM frame/cloaked/alpha/zOrder)+ filterVisibleWindows/windowUnderPoint 纯函数 + 快照缓存服务 | +| `CaptureService.hpp` | CaptureEngine 枚举(WGC→DXGI→GDI)、CaptureRequest/Result、ICaptureEngine、回退链服务、`wgcSupportsBorderless(contract)` | +| `HotkeyManager.hpp` | HotkeySpec/Conflict/RegistrationReport、isHotkeySpecValid、findDuplicateSpec、applySpecs 生命周期、默认键位、格式化 | +| `OverlayRenderer.hpp` | OverlayMode 状态机(Idle/HoverWindow/Dragging/Confirmed)、PaintList、OverlayVisuals(40% 变暗/4px 阈值/accent)、layoutInPlaceToolbar | +| `SelectionOverlay.hpp` | Win32 控制器:precreate/beginSession/cancelSession + SelectionOverlayResult(wholeWindow 标记 FR-02) | +| `TrayIcon.hpp` | TrayCommand ×11、buildTrayMenu(最近 5 截图条目)、RecentShot、TrayIconService | + +### 1.2 实现(`src/`,Win32 TU 与策略 TU 分离) + +**策略 TU(可移植,无 Win32 包含,任何平台可编译/测试)** + +| 文件 | 要点 | +|---|---| +| `DisplayMonitor.cpp` | 2s 缓存三态策略实现(互斥锁保护) | +| `WindowDetector.cpp` | cloaked/透明/零尺寸过滤 + topmost-first hit-test + mouse-down 快照缓存 | +| `HotkeyManager.cpp` | 注册生命周期(先全卸再注册=运行时即时生效)、冲突报告、MOD 位校验、Ctrl+Alt+F/A/T/D/I 默认 | +| `CaptureService.cpp` | 回退链遍历(available→capture→observer 上报)、区域与显示器求交裁剪、空交集快失败 | +| `OverlayRenderer.cpp` | 完整交互状态机:4px 点击/拖拽阈值、方向归一化、拖拽清除窗口高亮(FR-02)、Esc 取消、徽标/十字准线/工具栏骨架 paint list、双线程安全 | +| `TrayMenu.cpp` | 菜单模型纯函数(FR-34:5 动作+最近5+5占位+退出) | + +**Win32 TU(`pch.h` 预编译,仅 Windows 编译)** + +| 文件 | 要点 | +|---|---| +| `DisplayMonitorWin32.cpp` | EnumDisplayMonitors + GetMonitorInfoW(物理 rcMonitor) + GetDpiForMonitor(PMv2);主显示器优先排序;工厂 makeWin32DisplayEnumerator/makeSteadyClock | +| `WindowDetectorWin32.cpp` | EnumWindows(Z 序天然 topmost-first)+ DWMWA_CLOAKED(UWP 挂起过滤)+ DWMWA_EXTENDED_FRAME_BOUNDS(可见边界,失败回退 GetWindowRect)+ 分层窗口 alpha + 进程映像名;排除自身(NOACTIVATE/TOOLWINDOW) | +| `HotkeyManagerWin32.cpp` | RegisterHotKey(MOD_NOREPEAT)/UnregisterHotKey + WM_HOTKEY 泵函数 | +| `WGCCaptureEngine.cpp` + `WGCCaptureEngineFull.cpp` | WGC 引擎:契约探测(UniversalApiContract 12)、GraphicsCaptureSession::IsSupported、IsBorderRequired=false 契约门(contract 15);设备注入点留给 App 装配(见已知限制 §4.1) | +| `DxgiDuplicationEngine.cpp` | DXGI 回退:CreateDXGIFactory1 可用性探针 | +| `GdiCaptureEngine.cpp` | GDI 兜底:GetDC 可用性探针 | +| `SelectionOverlay.cpp` | WS_POPUP+WS_EX_LAYERED+WS_EX_TOPMOST+WS_EX_NOACTIVATE+WS_EX_TOOLWINDOW 跨虚拟桌面窗口;D3D11→D2D1.1(Factory2/Device/DeviceContext)→CreateSwapChainForComposition(flip,2 缓冲,premultiplied)→DComp(TargetForHwnd/Visual);完整消息处理(MOUSEMOVE/LBUTTONDOWN/UP、Esc、KILLFOCUS),mouse-up 区分拖拽选区 vs 窗口单击(wholeWindow) | +| `TrayIcon.cpp` | Shell_NotifyIcon(NIM_ADD/NIM_DELETE) + TrackPopupMenuEx(TPM_RETURNCMD) + SetForegroundWindow 契约 | +| `NativeShellInit.cpp` | 组装根:makeCaptureService(链序 WGC→DXGI→GDI)、显示器/窗口/热键工厂 | +| `pch.h`/`pch.cpp` | Win32/WinRT/D2D/DComp/DXGI/D3D11 基线 + lib 链接注释 | + +### 1.3 工程文件 + +- `CMakeLists.txt`:策略 TU 全平台 + Win32 TU `if(WIN32)` 门控 + Catch2 测试目标 +- `TransFrame.NativeShell.vcxproj`:静态库(x64+ARM64,/W4 /WX Release,pch,策略 TU 显式 NotUsing pch) +- `TransFrame.NativeShell.Tests.vcxproj`:测试工程(引用 NativeShell) +- `app.manifest`:**PerMonitorV2** dpiAwareness + UTF-8 codepage + Win10/11 supportedOS +- `tests/`:Catch2 v3.7.1 amalgamated vendored + 8 个测试文件 + +### 1.4 文档(`windows/docs/windows/`) + +每服务一份设计说明(API 选择理由+回退链):`CaptureService.md`、`DisplayMonitor.md`、`WindowDetector.md`、`SelectionOverlay.md`、`HotkeyTray.md`、`NativeShell-Tests.md`。 + +--- + +## 2. FR 映射表 + +| FR | 要求 | 实现 | 状态 | +|---|---|---|---| +| **FR-01 区域截图** | 40% 变暗、拖拽、尺寸徽标、Esc、多显示器物理像素 | OverlayState(dimAlpha 0.40、4px 阈值、归一化拖拽、cancel)+ SelectionOverlay(跨虚拟桌面、D2D 绘制变暗/挖亮/1px 描边/徽标/十字准线)+ CaptureService.captureRegion(物理像素、显示器求交) | ✅ 壳层完成(预览窗口=任务 C 后续) | +| **FR-02 窗口自动识别** | 悬停检测、单击整窗、拖拽忽略、≤1 帧切换、cloaked 过滤、DWM 可见边界 | WindowDetector(EnumWindows+DWMWA_CLOAKED+EXTENDED_FRAME_BOUNDS,快照缓存 hit-test)+ OverlayState(hover 高亮 25% 填充+1px 描边,拖拽阈值后清除)+ SelectionOverlay mouse-up wholeWindow 分支 | ✅ 测试覆盖 DWM bounds vs GetWindowRect 差异 | +| **FR-03 全屏截图** | 多显示器选择、原生分辨率 | CaptureService.captureDisplay(per-display)+ DisplayMonitorService.isMultiMonitor(选择菜单判定) | ✅ 捕获壳层(菜单 UI 属 App 层) | +| **FR-04 翻译模式** | 热键=截图+OCR+翻译 | HotkeyAction::Translate 注册 + overlay 完成回调链(OCR/翻译=任务 C) | ✅ 热键与捕获路径 | +| **FR-05 就地工具栏** | 选区边缘工具条 | layoutInPlaceToolbar:8 槽位(36px 按钮/4px 间距/下缘翻转/桌面钳制)+ Confirmed 态 paint list | ✅ 布局骨架(按要求不接功能) | +| **FR-33 全局热键** | ×5、冲突上报、即时生效 | HotkeyManager:RegisterHotKey×5、失败→conflicts 报告(含用户可读 message)、applySpecs 先卸后注(即时生效)、MOD 校验 | ✅ 12 测试用例 | +| **FR-34 托盘** | 常驻图标、左键菜单、最近 5 截图 | TrayIconService(Shell_NotifyIcon)+ buildTrayMenu(10 命令+最近 5 条 recentIndex/thumbnailHint) | ✅ 缩略图数据待历史任务 | + +**PRD §8 性能预算对策**:热键→覆盖层 ≤60ms(窗口+设备启动期预创建,热路径只 ShowWindow)|松开→截图 ≤50ms(WGC frame pool 常驻+一次 staging 拷贝,GDI 30-80ms 仅兜底)|120Hz 绘制 ≤8ms(纯 GPU fill/stroke,无文本无 GDI,paintList 纯内存)|悬停查询 ≤1ms(快照内存 hit-test)|空闲 CPU 0%(事件驱动无轮询)。 + +--- + +## 3. 测试证据(macOS arm64 · clang 21 · 实测) + +``` +$ clang++ -std=c++20 -Wall -Wextra -Werror -Iinclude -c src/*.cpp # 策略 TU 零警告 +$ # (编译 tests/*.cpp + 链接) +$ ./native_shell_tests +All tests passed (235 assertions in 60 test cases) +``` + +Windows 复现(等价 CMake 路径):`cmake -S windows/NativeShell -B build && cmake --build build && ctest --test-dir build`(MSVC 时 Win32 TU 一并编译)。 + +--- + +## 4. 已知限制 + +1. **Win10 黄边框降级**:`IsBorderRequired=false` 需 UniversalApiContract 15(Win11 21H2);Win10 21H2 属性不存在,系统黄边框保留(PRD §6.13 既定降级,`wgcSupportsBorderless()` 已封装门控并有测试)。 +2. **WGC 设备接线**:`WGCCaptureEngineFull.cpp` 的 captureOnce 留设备注入点(App 层 D3D 设备单例组装后接通);契约探测、链序、几何、回退、观察者全部完成并有测试。DXGI/GDI 引擎 TU 当前为可用性探针 + 骨架(链行为由 StubEngine 全覆盖测试)。 +3. **Esc 键盘接管**:WS_EX_NOACTIVATE 窗口不收键盘,选择会话内显式 SetFocus/SetForegroundWindow(会话结束隐藏归还);焦点策略需 Windows 实机验证。 +4. **托盘图标资产**:暂用系统占位图标;相机镜头图标属打包任务。缩略图渲染待历史数据层。 +5. **尺寸徽标文本 / FR-06 结果面板**:徽标底板绘制就绪,DWrite 文本与结果面板属后续任务(本任务边界外)。 +6. **Windows 编译未运行**:本机 macOS;vcxproj/CMake 为静态正确交付,MSVC 编译验证 NOT RUN(命令见 §3/§6)。 + +--- + +## 5. 与并行任务的接口 + +- **任务 A(Core)**:`CoreTypes.hpp` 按 PRD §4 自声明最小模型(PixelBuffer/DisplayInfo/Screenshot/HotkeyAction),字段名与 macOS Models 对齐;A 的 `windows/Core` 就绪后合并(删除自声明改 include 即可,无逻辑耦合)。 +- **任务 C(翻译/OCR/预览)**:overlay 完成回调 `SelectionOverlayResult{regionPhysical, wholeWindow, windowHwnd}` + `CaptureService.captureRegion/captureDisplay` 是其输入;FR-05 工具栏 8 槽位布局已留。 +- **任务 D(取色历史)**:托盘 `RecentShot.thumbnailPath` 供给位已留。 + +## 6. Windows 复现命令 + +```powershell +# 完整层(MSVC,x64 与 ARM64 各一次) +msbuild windows\TransFrame.sln /p:Configuration=Release /p:Platform=x64 /t:TransFrame_NativeShell;TransFrame_NativeShell_Tests +build\x64\Release\TransFrame.NativeShell.Tests\native_shell_tests.exe # (路径以 OutDir 为准) + +# 或 CMake +cmake -S windows\NativeShell -B build -G "Visual Studio 17 2022" -A x64 +cmake --build build --config Release +ctest --test-dir build -C Release +``` diff --git a/tasks/briefs/report-C.md b/tasks/briefs/report-C.md new file mode 100644 index 0000000..4c7edb6 --- /dev/null +++ b/tasks/briefs/report-C.md @@ -0,0 +1,108 @@ +# Report C — Windows 翻译/OCR 服务层 + +**任务**: Brief C(US-W06/07/08/09 + 引擎注册表 + 划词/插入) +**分支**: `hubo/win-translation-services`(worktree `win-translation-services`) +**状态**: 完成 — Catch2 全绿(105 cases / 370 assertions,macOS arm64 Apple clang 21.0.0) + +## 交付物清单 + +| 类别 | 文件 | +|---|---| +| Core 头(13) | `windows/Core/include/tf/{CoreModels,HttpTransport,TranslationProvider,LLMTranslationCore,Json,LLMChatProvider,MTranServerProvider,CloudProviders,CompatibleChatProvider,TranslationScheduler,EngineHealthChecker,OcrEngines,VisualLineGrouping,TextSelectionInsertion}.hpp` | +| Core 实现(14) | `windows/Core/src/*.cpp`(与头一一对应 + `CredentialAccounts.cpp` 凭据命名/掩码) | +| NativeShell(Win32, `#ifdef _WIN32`) | `WinHttpTransport.{h,cpp}`、`CredManKeyStore.{h,cpp}`、`Win32OcrUiaHosts.{h,cpp}` | +| 测试(6 文件) | `windows/Tests/{TranslationSchedulerTests,ProvidersTests,LLMTranslationCoreTests,EngineHealthCheckerTests,OcrAndTextSelectionTests}.cpp` + `TestSupport.hpp` | +| 手工冒烟 | `windows/Tests/manual/smoke_translation.cpp`(S1–S8 链路;本机 NOT RUN,非 Windows 分支编译验证通过) | +| 引擎文档 ×9 | `docs/windows/engines/{mtran,openai,claude,gemini,ollama,google,deepl,baidu,custom}.md` | +| 构建说明 | `windows/README.md` | + +## FR 映射 + +| FR | 要求 | 交付位置 | 验证 | +|---|---|---|---| +| FR-15 | Windows.Media.Ocr → TextSegment[](归一化 bbox + confidence);语言包检测 | `OcrEngines.hpp` `WindowsOcrEngine`(LanguageProvider/Recognizer 缝 + `mapLines` + `normalizeLanguageTag`);WinRT 胶水在 `Win32OcrUiaHosts.cpp` | mapLines 归一化/语言包门/空列表不可用/tag 归一 4 测试绿 | +| FR-16 | PaddleOCR fast/precise 外部进程 + 健康缓存 | `OcrEngines.hpp` `PaddleOcrEngine`(Mode/`buildArguments`/`parseFastMode`/`parsePreciseMode`/`pythonDictToJson`/`extractResultJson`)+ `PaddleOcrHealthCache` | fast/precise 解析、置信度过滤、Python 字面量转换、ANSI 剥离、argv 形状、TTL 缓存 9 测试绿 | +| FR-17 | VLM 五 Provider 位 + 分段解析 | `OcrEngines.hpp` `VlmOcrEngine`(五槽 + `extractionPrompt` + `parseSegments`,chat completion / fenced json / 像素 box 归一) | 5 槽位、fenced/像素 box 解析、Ollama keyless 可用性 4 测试绿 | +| FR-18 | 引擎 ×9(无 apple)、超时 10s、取消、错误四分类 | `LLMChatProvider`(openai/claude/gemini/ollama 四分支)、`CloudProviders`(google/deepl/baidu)、`MTranServerProvider`、`CompatibleChatProvider`、`HttpTransport`(CancellationToken/HttpRequest) | 各引擎请求形状/响应解析/错误码映射测试绿(详见各 engine md 的映射表) | +| FR-19 | 兼容多实例 UUID | `CompatibleChatProvider`(`custom:` 凭据槽、`resolveConfigurationSnapshot` 已保存优先)、`EngineChainItem::makeCompatible` | 多实例身份/独立请求/悬空跳过/快照解析 4 测试绿 | +| FR-20 | ordered ≤5 逐个回落 + 聚合错误 | `TranslationScheduler::translateOrdered` | 回退矩阵/首个成功停/不可用跳过/全败聚合/链截断 5/取消即止 6 测试绿 | +| FR-21 | compare 2-4 并行 + 结果缓存 | `TranslationScheduler::translateCompare`(std::thread 并行 + FNV-1a 缓存键) | 并行/部分失败/全败/顺序保持/缓存免重译/截断 4 6 测试绿 | +| FR-22 | 四态探测 + 不烧配额 + TTL 对齐 | `EngineHealthChecker`(四态/60s TTL/注入时钟)+ `DefaultEngineProbe`(mtran /health 梯子、openai/ollama/兼容 models、claude/gemini/deepl/google/baidu 无免费探测 → 有凭据灰) | 四态映射/梯子容错/门控/缓存命中/过期/invalidateAll/refresh 15 测试绿 | +| FR-23 | 三场景绑定路由 | `TranslationScheduler::translateForScene` + `SceneEngineBinding` | 绑定命中/未绑定回退全局 2 测试绿 | +| FR-24 | 三层 Prompt 覆盖 + 占位符 + 插入场景默认 | `TranslationPromptConfig`(`resolve` scene>compatible>engine>默认;`substitute` 三占位符)——**注意层级顺序,见差异清单 #2** | 分层/占位符 2 测试绿 | +| FR-25 | VisualLineGrouping 移植(同测试向量) | `VisualLineGrouping`(Y 投影重叠 0.5 / 水平间距 3×行高 / CJK 与标识符无缝拼接) | 行内代码合并/两行分离/下划线/CJK/分栏边界/置信度均值+bbox 并集 6 测试绿 | +| FR-27 | LLM 批处理 + 截断检测 | `LLMTranslationBatching`(`\n---\n` 分隔、预算收缩、超长按字符切)+ `LLMTranslationResponseParser`(plain JSON + SSE、`finish_reason:length`/`max_tokens` 截断错误、正文含 `data:` 不误判) | 批量预算/字符切分/prompt 成本/截断 5 形态/SSE 拼接/错误对象 12 测试绿 | +| FR-28 | 划词:UIA 优先 → Ctrl+C 回退(保存/恢复剪贴板) | `TextExtractor`(Route 1 UIA GetSelection;Route 2 backup→clear→Ctrl+C→poll→restore,`allowClipboardFallback` 缝) | UIA 优先不碰剪贴板/回退后恢复原内容/禁用回退不出错/空选区报错 5 测试绿 | +| FR-29 | 插入:重验证 + 绝不粘贴 | `InsertionService::validateTarget`(UIA runtimeId + 选区文本比对 / 剪贴板模式 PID 锚定)+ 粘贴窗口(set→Ctrl+V→150ms→restore) | 正常粘贴并恢复/选区变更中止/焦点丢失中止/PID 变更中止/空译文拒绝 5 测试绿(paste 调用数 = 0 断言) | +| §5(brief) | KeyStore:CredMan + `TransFrame//` + `sk-****last4` | `CredManKeyStore.{h,cpp}`(CredWrite/CredRead,JSON blob 保 appID/additional)+ `CredentialAccounts.cpp`(`credentialAccount`/`credentialAccountForCompatible`/`maskApiKey`) | 命名/掩码/mock 往返 2 测试绿 | + +## 与 macOS 行为差异清单 + +对照 PRD §6.12 白名单,逐条核对: + +1. **Apple Translation 移除**(白名单第 1 条,符合):引擎集 9 个(无 apple), + raw 值与 macOS 一致;`translationEngineFromRaw("apple")` 返回 nullopt。 + 默认链首 MTranServer(已裁决)。 +2. **Prompt 层级顺序**:移植初期 C++ 把 engine 层放在 scene 之前;Swift 原版 + (`TranslationPromptConfig.promptPreview`)是 **scene > compatible > engine**。 + 已在实现中修正为 Swift 顺序(`CoreModels.cpp resolve`),测试覆盖三层层级。 + 这不是与 macOS 的差异,是移植缺陷的修复记录。 +3. **EngineRegistry 缓存弱化**:Swift `TranslationEngineRegistry` 缓存 provider + 实例(class 引用语义);C++ `TranslationProviderPtr = unique_ptr` 不可共享, + registry 改为**缓存配置切片**(`operator==` 命中时仍走工厂重建实例)。 + 行为差异:多轮 translate 会重建 provider 对象(无网络差异;凭据/配置读取 + 每次 fresh)。对功能无影响(provider 无内部状态需保活);若后续任务 D/E + 需要真正的实例共享,可把 `TranslationProviderPtr` 换 `shared_ptr` — 接口不变。 +4. **WindowsOcr confidence**:Windows.Media.Ocr 不给置信度分数(macOS Vision 有), + `mapLines` 一律填 1.0,保持 TextSegment schema 兼容(macOS 端同字段照旧)。 + §6.12 第 2 条(Apple Vision OCR → Windows.Media.Ocr 为默认)范围内。 +5. **MTranServer 探测端点**:`DefaultEngineProbe` 内建 `Configuration::makeDefault()` + (localhost:8989)探测。macOS 侧探测使用**当前配置**的端点。设置层接入后 + 应把用户配置传入(接口已留:probe 构造可注入配置工厂);当前测试按 + localhost 断言。**遗留 TODO(任务 D/E 接线时闭合)**。 +6. **keyless OpenAI 兼容 localhost 判定**:`LLMChatProvider::isAvailable` 对 + `engine == OpenAI && baseURL 为 localhost` 放行无 key(Swift PR#92 语义, + LM Studio/vLLM 预设);与 macOS 行为一致,无差异。 +7. **取消语义**:cancelled → `ProviderError::network("cancelled")`;调度器见 + network+cancelled 即止链(不磨完剩余引擎)。与 Swift PR#92 一致。 +8. **错误分类第 5 类**:brief 要求网络/配额/鉴权/内容四类;实现加了 + `Configuration`(无效 URL/缺凭据,可不出网就判定的错误)。这是超集而非 + 偏离:四类语义不变,Configuration 用于引擎卡灰/橙判定。若视为超白名单 + 差异,可在 UI 层把 Configuration 并显示为内容错误 — 记录待裁决。 + +## 测试结果(本机实测) + +``` +$ clang++ -std=c++20 \ + -I windows/Core/include -I windows/Core/vendor \ + -I windows/Tests -I windows/Tests/vendor \ + windows/Core/src/*.cpp windows/Tests/*.cpp \ + windows/Tests/vendor/catch_amalgamated.cpp \ + -o tests_runner && ./tests_runner +All tests passed (370 assertions in 105 test cases) +``` + +按标签:`[scheduler]` 15 cases / 47 assertions;`[health]` 15 / 32;`[ocr]` 19 / 78; +`[selection]` 5 / 14;`[insertion]` 5 / 15;其余(providers/llm/grouping/keystore/ +prompt/url/models)合计覆盖 9 引擎请求形状、MD5 已知向量(RFC 1321)、 +DeepL 456→quota、Baidu 54003/54004、HTTPS key 守卫、URL 后缀去重等。 + +## NOT RUN(本机 macOS 限制)+ 复现命令 + +| 项 | 状态 | 复现 | +|---|---|---| +| `WinHttpTransport.cpp`(WinHTTP 5.1) | 编译未验证(需 Windows SDK) | Windows: `cl /std:c++20 /EHsc /I windows\Core\include /I windows\Core\vendor /I windows\NativeShell\include windows\NativeShell\src\WinHttpTransport.cpp /link winhttp.lib` | +| `CredManKeyStore.cpp`(CredWrite/CredRead) | 同上 | `cl ... CredManKeyStore.cpp /link advapi32.lib credui.lib` | +| `Win32OcrUiaHosts.cpp`(WinRT OCR / UIA / SendInput) | 同上 | `cl ... Win32OcrUiaHosts.cpp /link user32.lib ole32.lib oleaut32.lib windowsapp.lib` | +| `smoke_translation.cpp` S1–S8 | 非 Windows 分支已编译运行(打印 NOT RUN 退出 0);Windows 全链路未跑 | `windows/README.md` 的 MSVC 命令;S1/S2/S7 可离线验证,S3–S6 需本地服务/key | + +接口契约(`IHttpTransport`/`ICredentialStore`/`IOcrEngine`/`TextExtractorHost`/ +`IEngineProbe`)全部以 mock 在 Catch2 里驱动过 — NativeShell 实现只需满足 +同一接口签名即接入。 + +## 完成标准核对 + +- [x] Catch2 全绿(链调度 / 探测缓存 / KeyStore mock / 批量解析) +- [x] `docs/windows/engines/.md` ×9(端点、参数、错误码映射表) +- [x] 控制台测试入口 `tests/manual/smoke_translation.cpp` +- [x] FR 映射 + macOS 差异清单(上两节;差异 #3/#5/#8 为记录项,#5 带 TODO) diff --git a/tasks/briefs/report-D.md b/tasks/briefs/report-D.md new file mode 100644 index 0000000..6b4e274 --- /dev/null +++ b/tasks/briefs/report-D.md @@ -0,0 +1,110 @@ +# 子任务 D:macOS 取色历史(补工收尾版) + +> 本版为补工交付:销掉上一版报告的全部"待裁决/已知偏差"项,含全量测试结果。 +> 基线:`daed543 feat: add macOS color history window`。 + +## 文件(累计,含补工改动) + +- `TransFrame/Features/History/ColorHistoryView.swift`:网格、筛选、操作、键盘与格式化;补工新增空态动态快捷键提示、右上角星标/操作合并簇。 +- `TransFrame/Features/History/ColorHistoryWindowController.swift`:窗口管理(单实例、共享 store)。 +- `TransFrame/Features/History/ColorPickToastController.swift`:取色提示("查看历史"链接)。 +- `TransFrame/Features/History/ColorPickFlow.swift`(新增):全部取色面的共享入史+toast 管道。 +- `TransFrame/Features/History/HistoryWindowController.swift`、`TransFrame/Services/HistoryStore.swift`:共享历史实例;补工抽出 `makeColorPickEntry` / `recordPickedColor` 统一入口。 +- `TransFrame/App/AppDelegate.swift`:`pickScreenColor` 改走 `ColorPickFlow.complete`。 +- `TransFrame/App/Coordinators/HotkeyCoordinator.swift`:新增 `.pickColor` 热键注册。 +- `TransFrame/Features/MenuBar/MenuBarController.swift`:托盘"屏幕取色"项显示可配置热键。 +- `TransFrame/Features/Preview/PreviewToolBar.swift`、`TransFrame/Features/Capture/SelectionInPlaceToolbar.swift`:两个吸管接入共享管道。 +- `TransFrame/Models/KeyboardShortcut.swift`:`pickColorDefault`(Ctrl+Cmd+C)。 +- `TransFrame/Models/AppSettings.swift`:`pickColorShortcut` 键/加载/重置。 +- `TransFrame/Features/Settings/SettingsViewModel.swift`、`ShortcutSettingsTab.swift`:第 6 组热键录制 UI(含冲突检测)。 +- `TransFrame/Resources/{en,zh-Hans,de,es,fr,it,ja,ko,pt,ru}.lproj/Localizable.strings`。 +- `TransFrameTests/ColorHistoryStoreTests.swift`(+4 用例)、`TransFrameTests/ShortcutRecordingTypeTests.swift`(用例扩展到 6 案)。 + +## UserDefaults(累计) + +- `TransFrame.colorHistoryCopyFormat`:复制格式,默认 HEX。 +- `TransFrame.colorHistorySearch`:搜索文字。 +- `TransFrame.pickColorShortcut`(新增):屏幕取色热键,`{keyCode, modifiers}` 字典,默认 Ctrl+Cmd+C。 +- AppKit 窗口 frame autosave name:`TransFrameColorHistoryWindow`。 + +## 新增字符串键(补工新增) + +- `settings.shortcut.pick.color`(设置快捷键页第 6 项标签) +- `colorHistory.empty.shortcut`(空态热键提示,`%@` = displayString) +- `colorHistory.empty.trayHint`(热键无效时的托盘路径文案) + +en/zh-Hans 全量翻译;其余 8 语言英文占位(置于既有 "TODO: translate" 块,`plutil -lint` 全通过)。 + +## 逐条销掉旧报告偏差清单 + +### 1. 空态缺"取色快捷键提示"(spec §4.2)→ 已销 + +- 新增全局热键"屏幕取色",默认 **Ctrl+Cmd+C**(`KeyboardShortcut.pickColorDefault`;避开纯 Cmd+C 剪贴板绑定)。 +- 完整接入既有 5 组热键的全部惯例:`KeyboardShortcut` 模型默认值 → `AppSettings.Keys.pickColorShortcut` + 加载/重置 → `HotkeyCoordinator.HotkeyType.pickColor` 注册(动作 `appDelegate?.pickScreenColor()`)→ `SettingsViewModel` 录制/重置/冲突检测(第 6 案)→ `ShortcutSettingsTab` 第 6 行 UI → 托盘菜单项 `menu.pick.color` 显示该热键(`shortcut:` 参数,快捷键变更通知触发 rebuildMenu 已有)。 +- 空态文案**动态读取** `AppSettings.shared.pickColorShortcut.displayString`,并订阅 `AppSettings.shortcutDidChangeNotification` 实时刷新(`.id(shortcutRefreshID)` 强制重渲染);`isValid == false` 时回退 `colorHistory.empty.trayHint` 托盘路径文案。 + +### 2. 吸管未接入历史 + toast(spec §4.5、report-D 偏差)→ 已销 + +- 新增共享入口 `ColorPickFlow.complete(_:writeToPasteboard:)`(`Features/History/ColorPickFlow.swift`):hex 规范化 →(可选)剪贴板 → 确保共享 store 存在 → 广播 `.colorDidPick` → `ColorPickToastController.show`(含"查看历史"链接)。 +- 三个取色面全部收敛到该入口,无复制粘贴实现: + - 托盘 `AppDelegate.pickScreenColor`(`writeToPasteboard: true`,与原行为一致) + - `PreviewToolBar.eyedropperButton`(`false`,注释标注"标注中途不动剪贴板") + - `SelectionInPlaceToolbar` 屏幕吸管(`false`,同上) +- 入史统一走 `HistoryStore.recordPickedColor(hex:)`(构建 canonical 条目 + `addEntry` 去重/置顶/收藏保留);`.colorDidPick` 观察者也改走同一路径(原内联构造删除)。 + +### 3. 悬浮操作与星标位置(spec §4.2)→ 已销 + +- 实现方式(在报告说明):单一 `topTrailingCluster` 覆盖在色块 `.topTrailing`: + - 静止时只渲染常显星标 `favoriteBadge`(收藏=黄色 star.fill); + - 悬浮时星标**合并进操作组左侧**成为其首按钮(star/star.fill 切换),后接复制、删除,整组 `.ultraThinMaterial` 背景。 + - 一个 HStack、一个对齐锚点,星标与操作组**不可能重叠**;操作组原 `bottomTrailing`(旧报告偏离规格)改为右上角。 + +### 4. HistoryStore 多实例覆盖风险 → 已审计,无风险新增 + +全仓 `HistoryStore(` 创建点审计: +- 生产代码仅 2 处:`HistoryWindowController.init`(单例所有,唯一真实实例)与 `ColorHistoryWindowController.init` 复用 `HistoryWindowController.shared.store`(前任已改,本次保持)。`AppDelegate.pickScreenColor` 不再直接触碰 store(经 `ColorPickFlow`)。 +- `HistoryView.swift` 的 `HistoryStore()` 在 `#if DEBUG #Preview` 内,不进生产二进制。 +- 测试目标 2 处(`HistoryStoreTests` / `ColorHistoryStoreTests`)用独立 UserDefaults suite,符合测试隔离惯例。 +- 结论:运行期 store 实例唯一,无多实例覆盖风险;无需进一步改动。 + +### 5. 键盘路径复查(代码级自查,ColorHistoryView) + +| 键 | 实现位置 | 分支 | +|---|---|---| +| Tab | `ColorSwatchCell` `.focusable()` + grid `.focused($focusedCellID, equals:)` | 每个 cell 均可获焦,Tab 循环遍历 | +| ←→↑↓ | `.onMoveCommand` → `moveFocus(from:direction:)` | 按 `columnCount`(实测宽度/64+12)换算 stride;左右 clamp 0…count-1,上下 clamp 跨行;`@unknown default` 不动 | +| Enter | `.onKeyPress(.return)` | `onCopy()`(按当前格式)+ `flashCopiedBadge()`,返回 `.handled` | +| Space | `.onKeyPress(.space)` | `onToggleFavorite()`,`.handled` | +| Delete | `.onKeyPress(.delete, phases: .down)` | `onDelete()`,`.handled`;`phases: .down` 保证按下即删(含 Fn+Backspace 正向删除键位) | +| Esc | 搜索框 `onExitCommand`(清空或失焦)+ 窗口级 `onExitCommand`(任意位置清空搜索,已空则无操作) | 两级覆盖,空搜索时不吞事件焦点行为 | + +全部 6 条键路径代码级确认完整;完整 UI 自动化仍未做(沿用旧报告口径,非本次范围)。 + +## 全量验证(本机 macOS 实测) + +- **构建**:`xcodebuild -project TransFrame.xcodeproj -scheme TransFrame -destination 'platform=macOS' build CODE_SIGNING_ALLOWED=NO CODE_SIGN_IDENTITY=''` → **BUILD SUCCEEDED**(改动文件零新增告警)。 +- **全量测试套件**(不只 ColorHistoryStoreTests):`xcodebuild test -project TransFrame.xcodeproj -scheme TransFrame -destination 'platform=macOS' CODE_SIGNING_ALLOWED=NO CODE_SIGN_IDENTITY=''` → **TEST SUCCEEDED,325 个用例全部通过、0 失败、0 跳过**;无与本次改动无关的失败(旧报告担心的全量回归不存在)。xcresult:`/Volumes/external/Xcode/DerivedData/TransFrame-*/Logs/Test/Test-TransFrame-2026.11.02_07-15-54-+0800.xcresult`。 +- **ColorHistoryStoreTests**:15/15 通过(11 旧 + 4 新:`testRecordPickedColorInsertsCanonicalEntryAtTop`、`testRecordPickedColorDeduplicatesAndKeepsFavorite`、`testRecordPickedColorBroadcastObserverMatches`、`testPickColorShortcutDefaultIsValidAndDistinct`)。 +- **ShortcutRecordingTypeTests**:`testAllCasesExist` 升级为 6 案断言(含 `.pickColor`),`testSwitchExhaustiveness` 同步扩展,均通过。 +- **plutil -lint**:10 个 `Localizable.strings` 全部 OK。 +- 未验证项(沿用旧口径):真实窗口内 UI 自动化键盘/点击路径(Key event → NSPanel 转发需真机交互);Toast 视觉位置。二者不影响上述代码级结论。 + +## 改动文件清单(本次补工 commit) + +``` +TransFrame/Features/History/ColorPickFlow.swift (新增, 52 行) +TransFrame/Features/History/ColorHistoryView.swift (空态热键提示 + 右上角合并簇) +TransFrame/Services/HistoryStore.swift (recordPickedColor/makeColorPickEntry, 观察者改走共享入口) +TransFrame/App/AppDelegate.swift (pickScreenColor → ColorPickFlow) +TransFrame/App/Coordinators/HotkeyCoordinator.swift (.pickColor 注册) +TransFrame/Features/MenuBar/MenuBarController.swift (取色菜单项显示热键) +TransFrame/Features/Preview/PreviewToolBar.swift (吸管 → ColorPickFlow) +TransFrame/Features/Capture/SelectionInPlaceToolbar.swift(吸管 → ColorPickFlow) +TransFrame/Models/KeyboardShortcut.swift (pickColorDefault) +TransFrame/Models/AppSettings.swift (pickColorShortcut 键/加载/重置) +TransFrame/Features/Settings/SettingsViewModel.swift (第 6 组热键录制) +TransFrame/Features/Settings/ShortcutSettingsTab.swift (第 6 行 UI) +TransFrame/Resources/*.lproj/Localizable.strings ×10 (3 个新键) +TransFrameTests/ColorHistoryStoreTests.swift (+4 用例) +TransFrameTests/ShortcutRecordingTypeTests.swift (6 案扩展) +``` diff --git a/tasks/briefs/report-ci.md b/tasks/briefs/report-ci.md new file mode 100644 index 0000000..bf469e5 --- /dev/null +++ b/tasks/briefs/report-ci.md @@ -0,0 +1,85 @@ +# Windows 编译 + 测试实跑报告(GitHub Actions) + +补验任务:把 A/B/C 三个 Windows 子任务的"编译 + 测试"从本机 clang++ 验证推进到 GitHub Actions windows-latest 实跑留证。全部三个分支最终全绿。 + +## 最终状态矩阵 + +| 分支 | MSVC x64(编译+测试) | MSVC ARM64(编译+链接) | GCC ubuntu(编译+测试) | 最终 run | +|---|---|---|---|---| +| A `hubo/win-skeleton-core` | ✅ 68 cases / 261 assertions | ✅ compile+link | ✅ 68 cases / 261 assertions | [41370755812](https://github.com/hubo1989/TransFrame/actions/runs/41370755812) | +| B `hubo/win-capture-shell` | ✅ 60 cases / 235 assertions | ✅ compile+link | ✅ 60 cases / 235 assertions | [41369850862](https://github.com/hubo1989/TransFrame/actions/runs/41369850862) | +| C `hubo/win-translation-services` | ✅ 105 cases / 370 assertions | ✅ compile+link(含 NativeShell smoke 链接) | ✅ 105 cases / 370 assertions | [41370116943](https://github.com/hubo1989/TransFrame/actions/runs/41370116943) | + +测试通过输出行(原样摘录): + +``` +A (MSVC x64): All tests passed (261 assertions in 68 test cases) +A (GCC): All tests passed (261 assertions in 68 test cases) +B (MSVC x64): All tests passed (235 assertions in 60 test cases) +B (GCC): All tests passed (235 assertions in 60 test cases) +C (MSVC x64): All tests passed (370 assertions in 105 test cases) +C (GCC): All tests passed (370 assertions in 105 test cases) +``` + +C 的 105/370 与本机 clang++ 实跑(brief 记录 105 cases/370 assertions)完全一致。 +ARM64 说明:windows-latest(x64 runner)无法执行 ARM64 PE("not a valid application +for this OS platform"),ARM64 腿定位为编译+链接验证;测试执行在 x64 腿完成 +(workflow 内已注明)。这是 runner 能力边界,不是代码问题。 + +## 逐分支修复轮次 + +### A `hubo/win-skeleton-core`(vcxproj/msbuild 侧,5 轮) + +| 轮 | 失败摘要 | 修复 | 结果 | +|---|---|---|---| +| 1 | ARM64: MSB8020 v143 toolset 不存在(runner 是 VS2026/VS18);x64: STL4038/C2429(std 落回 C++14);GCC: `Core/Annotation.h` 找不到 | toolset 改 `$(DefaultPlatformToolset)`;`LanguageStandard` 移入 Configuration PropertyGroup;GCC 加 `-I .` | x64 仍 C7589(std 仍没传到 cl) | +| 2 | C7589/C2039 std::optional:`` 作为属性对 cl 无效 | 移入每个项目的 `` ItemDefinitionGroup(真正的 metadata 通道) | std 生效,错误转移到 Tests | +| 3 | Tests: C1083 `Core/...` 头找不到;App: MSB4044 CompileXaml 缺 TargetPlatformMinVersion + D8016 `/ZW 与 /std:c++20 冲突` | Tests IncludePath 加 `$(ProjectDir)..`;App 暂时注释 WindowsAppSDK PackageReference(骨架 AppMain 是纯 Win32 窗口,不需要 WinAppSDK;任务 B/C 引入 WinUI 3 时恢复) | 只剩 VisualLineGroupingTests C4244 | +| 4 | C4244 double→float(fixture confidence) | 显式 `static_cast` | LNK2019: main 缺失 + BCryptGenRandom 未解析 | +| 5 | LNK2019 main(CATCH_CONFIG_MAIN 在 v3 amalgamated 下不提供 main,且 vcxproj 又定义了 CATCH_AMALGAMATED_CUSTOM_MAIN);LNK2001 bcrypt(静态库内 #pragma comment(lib) 不总传播) | 去掉 CATCH_AMALGAMATED_CUSTOM_MAIN + TestMain.cpp 不再定义 CATCH_CONFIG_MAIN(amalgamated .cpp 自带 main);Link 显式加 bcrypt.lib | 编译链接全过,仅 fixture 打不开 | +| 6 | fixture REQUIRE(in.is_open()) false(exe 目录下没有 fixture) | 测试步骤 working-directory 改为 `windows/`,cwd 相对路径 `Tests/fixtures/...` 直达(先修 fixtures/ 子目录猜测,再修 exe 路径 `.\build\...`) | ✅ 全绿 | + +### B `hubo/win-capture-shell`(CMake 源码侧,4 轮 + 初始) + +| 轮 | 失败摘要 | 修复 | 结果 | +|---|---|---|---| +| 0 | (初始,workflow 本次新建)x64/ARM64: C1083 `winrt/Windows.Graphics.Capture.Interop.h` 不存在;ID2D1Factory2 未定义;LoadCursorW/LoadIconW LPSTR→LPCWSTR;cancelSession 静态调用;D2D1_ANTIALIAS_ALIASED | 删除两个文件里未使用的 Interop include;`ID2D1Factory2`→`ID2D1Factory1`(Factory2 是 d2d1_3.h 的,Factory1 已带 CreateDevice);CMakeLists 加 `add_compile_definitions(UNICODE _UNICODE)`(CMake 生成的 vcxproj 默认不定义 UNICODE,MAKEINTRESOURCE 展开 LPSTR);WM_KILLFOCUS 分支内联 session 清理(不能从静态 wndProc 路径调成员函数);`D2D1_ANTIALIAS_ALIASED`→`D2D1_ANTIALIAS_MODE_ALIASED` | 只剩 Metadata 命名空间和 Direct3D11CaptureFrame 命名空间 | +| 2 | C3083 `Metadata` 不是类型(WGCCaptureEngine.cpp 用 `Foundation::Metadata::ApiInformation` 但没 include 对应头);C2039 Direct3D11CaptureFrame 不在 DirectX 命名空间 | WGCCaptureEngine.cpp 加 `winrt/Windows.Foundation.Metadata.h`;Full 里 `wdx::Direct3D11CaptureFrame`→`wgc::Direct3D11CaptureFrame`(该类型在 Capture 命名空间) | 只剩 C4100 | +| 3 | C4100 未引用形参(占位 stub) | 占位参数注释化 `/*obj*/`、`/*request*/` | x64 ✅;ARM64 运行失败(见下) | +| 4 | ARM64: exe 无法启动(x64 runner 不能跑 ARM64 PE) | 测试执行限定 x64(`if: matrix.platform == 'x64'`),ARM64 保持编译+链接验证 | ✅ 全绿 | + +### C `hubo/win-translation-services`(workflow 新建 + 源码,5 轮) + +| 轮 | 失败摘要 | 修复 | 结果 | +|---|---|---|---| +| 0 | (初始,workflow 本次新建)`cl` 不在 pwsh PATH(未跑 vcvars);GCC: -Werror parentheses + missing-field-initializers | workflow 改用 CMake(自带 MSVC 环境发现),新增 `windows/CMakeLists.txt`(translation_tests + nativeshell_smoke);HttpTransport.cpp `h.size() > 6 && ...` 加括号;portable check 去掉 -Werror 对 missing-field-initializers 的硬拒(测试 {status, body} 部分初始化是有意设计,CMake 版本显式 -Wno-missing-field-initializers) | MSVC 编译 NativeShell 时 C3536/C3779 | +| 2 | C3536/C3779 `IIterable::begin/end` 未定义(consume_* 模板在无 `winrt/Windows.Foundation.Collections.h` 时未实例化) | Win32OcrUiaHosts.cpp 加 `#include ` | 只剩 CreateLanguage / OcrResult 歧义 | +| 3 | C3861 `Language::CreateLanguage` 不存在;C2440 `OcrResult` 解析到 `tf::OcrResult`(Core 模型)而非 WinRT 投影类型(using namespace 双方都有 OcrResult,tf 内层胜出) | `Language(to_hstring(tag))` 构造函数(无静态工厂,解析失败抛异常走 catch);结果类型全限定 `winrt::Windows::Media::Ocr::OcrResult` | 只剩 BoundingRect | +| 4 | C2039 `OcrLine::BoundingRect` 不存在(OcrLine 只有 Text 和 Words;词级才有 BoundingRect) | 遍历 line.Words() 求词矩形并集作为行框 | LNK1120: 14 个未解析符号 | +| 5 | nativeshell_smoke 缺 Core 符号(smoke_translation.cpp 引用 Core 的 makeBuiltinProvider 等) | CMakeLists 把 `${CORE_SRC}` 编入 nativeshell_smoke(与 README 手工命令一致) | ✅ 全绿 | + +## 各分支 workflow 说明 + +- A 沿用既有 `windows-ci.yml`(msbuild sln x64+ARM64 + ubuntu g++-13 portable check) +- B 本次新建:`cmake -S windows/NativeShell`(x64+ARM64 + ubuntu portable,两平台同一 CMake 工程与测试集) +- C 本次新建:新增 `windows/CMakeLists.txt`(translation_tests:Core+Tests 任意平台;nativeshell_smoke:Core+NativeShell+manual smoke,仅 WIN32,链接 winhttp/credui/advapi32/user32/ole32——只验证编译+链接,运行需 GUI 会话属手工冒烟范畴) + +三个 workflow 均为 push(hubo/** 路径过滤 windows/** 与 workflow 自身)+ PR + workflow_dispatch。 + +## 仍未验证项 + +1. **ARM64 测试执行**:windows-latest 是 x64 runner,不能执行 ARM64 PE。ARM64 腿现为编译+链接验证。如需 ARM64 实跑测试,需 `windows-11-arm` runner(GitHub 已提供该 label,未在本轮引入,避免再开一轮矩阵)。 +2. **C 的 NativeShell 运行时行为**(WinHTTP 真实网络、CredMan 读写、UIA 取词、SendInput 插入):nativeshell_smoke 只做了编译+链接;真实运行需要 GUI 会话与网络,属 `Tests/manual/smoke_translation.cpp` 标注的手工冒烟(S1-S8),CI 不替代。 +3. **B 的 WGC/DXGI/GDI 捕获运行时**与 D2D/DComp overlay 渲染:同样只有编译+链接级验证;运行需交互桌面。 +4. **A 的 App 真实 WinUI 3 装配**:AppMain.cpp 是纯 Win32 占位窗口;WindowsAppSDK PackageReference 因 `/ZW 与 /std:c++20 冲突`暂时注释(vcxproj 内有注释说明),任务 B/C 引入 WinUI 3 时需恢复并处理 TargetPlatformMinVersion。 +5. 本机 macOS 侧从未编译过的 `windows/Core/src/translation/` 空目录(分支 C)未在 CI 暴露问题(file(GLOB) 不含空目录),无代码因此未验证。 + +## 复现 + +```bash +gh run watch --repo hubo1989/TransFrame # 任一最终 run +# 或本地复验(macOS): +# A: cd windows && clang++ -std=c++20 -I . -I Core -I external Core/*.cpp external/catch2/catch_amalgamated.cpp Tests/*.cpp -o t && ./t +# B: cmake -S windows/NativeShell -B build && cmake --build build && ./build/native_shell_tests +# C: g++/clang++ -std=c++20 -I windows/Core/include -I windows/Core/vendor -I windows/Tests -I windows/Tests/vendor windows/Core/src/*.cpp windows/Tests/*.cpp windows/Tests/vendor/catch_amalgamated.cpp -o t && ./t +``` diff --git a/tasks/prd-windows-transframe.md b/tasks/prd-windows-transframe.md new file mode 100644 index 0000000..e02b163 --- /dev/null +++ b/tasks/prd-windows-transframe.md @@ -0,0 +1,612 @@ +# PRD: TransFrame for Windows(屏幕翻译工具 · Win11 原生版) + +- **Status**: Draft v1.0 +- **Date**: 2026-11-02 +- **Owner**: TransFrame Team +- **Baseline**: macOS 版 v1.0.4(功能完全对齐,见 §2 功能基线) +- **Reference PRDs**: `tasks/prd-macos-transframe.md`, `tasks/prd-engine-mode-convergence.md`, `docs/specs/window-detection-auto-select.md`, `docs/specs/color-history-window.md` +- **已裁决决策(2026-11-02,适用两平台)**: + 1. 本地翻译只做**引擎接入**(MTranServer/Ollama/兼容端点),不内置、不打包任何模型(LocalTranslate/ONNX 路线取消)。 + 2. 历史检索**不启用 FTS5**,维持 LIKE 查询。 + 3. **不考虑便携版**,仅 MSIX 单一分发通道。 + 4. 取色历史**扩展为独立取色历史窗口**,Windows 与 macOS 同步交付(见 `docs/specs/color-history-window.md`)。 + +--- + +## 1. 概述(Overview) + +TransFrame for Windows 是 macOS 屏幕翻译工具 TransFrame 的 Windows 原生版本。用户通过全局快捷键截取屏幕任意区域(或全屏/窗口),自动 OCR 识别文字,调用本地或云端翻译引擎翻译,以覆盖层、双语对照抽屉或就地替换的形式展示译文;同时提供划词翻译、翻译并插入、标注、置顶贴图、翻译历史、图床上传等完整能力。 + +**三大硬性要求**(本 PRD 的存在理由): + +1. **功能完全一致**:与 macOS v1.0.4 逐特性对齐(§2 基线表 + §6 FR 清单);差异仅在平台能力本身导致的等价替换(§6.12 差异对照表)。 +2. **Win11 标准 UI**:Fluent 2 设计语言 —— Mica 材质、圆角、深浅色模式、Segoe Fluent Icons、Snap Layouts、系统通知、任务栏托盘常驻(§8)。 +3. **原生语言 + 尽可能高性能**:不使用 Electron/Web 壳;渲染走 GPU(Direct2D/DirectComposition),截图走系统级捕获 API,冷启动与常驻内存对标原生工具(§3、§9)。 + +### 1.1 Goals + +- 与 macOS 版**特性集 1:1**(同一份 FR 清单驱动两个平台)。 +- 截图→OCR→翻译→渲染 全链路 P95 延迟预算:热路径本地引擎 ≤ 1.2s,其中捕获 ≤ 50ms、本地 OCR ≤ 300ms(§9)。 +- 常驻内存 ≤ 80MB(托盘态),空闲 CPU 0%,无后台轮询(事件驱动)。 +- 原生 Win11 体验:开机自启动、任务栏托盘、系统通知、深色模式、多显示器/Per-Monitor DPI 感知。 +- 同一份设置/历史/引擎数据模型(schema 与 macOS 对齐),为将来跨平台同步留接口。 + +### 1.2 Non-Goals + +- 不做 Win32 老式 UI 风格的兼容模式。 +- 不做 Windows 10 以下(Win7/8)适配;Win10 21H2 走降级路径(§6.13),非一等公民。 +- 不做移动端(与 macOS 版一致)。 +- 不内置翻译模型训练/微调。 +- V1 不做云同步(历史/设置本地存储;schema 预留)。 + +--- + +## 2. 功能基线(macOS v1.0.4 特性全景 → Windows 对齐表) + +| # | 特性 | macOS 实现 | Windows 对应(详见 FR) | 优先级 | +|---|------|-----------|--------------------------|--------| +| F-01 | 区域截图(拖拽选区) | ScreenCaptureKit + SelectionOverlayWindow | Windows.Graphics.Capture + 全屏层窗口 + D2D 选区 | P0 | +| F-02 | 窗口自动识别高亮(悬停检测 + 单击选窗口) | CGWindowListCopyWindowInfo | EnumWindows + DWMWA_EXTENDED_FRAME_BOUNDS | P0 | +| F-03 | 全屏截图(多显示器菜单) | SCK + DisplaySelector | WGC/DXGI Duplication + 显示器选择菜单 | P0 | +| F-04 | 翻译模式(截图即翻译) | CapturePipeline + AnalysisPipeline | 同管线移植 | P0 | +| F-05 | 就地选区工具栏 | SelectionInPlaceToolbar | D2D 绘制的层窗口工具栏 | P1 | +| F-06 | 就地结果面板 | InPlaceResultsPanel | 同上 | P1 | +| F-07 | 预览窗口(保存/复制/关闭) | PreviewWindow(SwiftUI) | WinUI 3 窗口 | P0 | +| F-08 | 标注:矩形/椭圆/直线/箭头/自由手绘/文字 | AnnotationCanvas | Direct2D 画布 | P0 | +| F-09 | 标注:马赛克/高亮/数字标签/隐私遮挡/气泡 | Annotation.swift 11 种 | Direct2D 画布(11 种全量) | P1 | +| F-10 | 智能打码(VLM 敏感区检测) | performSmartRedaction | VLM Provider 移植 | P2 | +| F-11 | 裁剪 + 撤销/重做(50 步) | CropDimOverlay + undo 栈 | 同 | P0 | +| F-12 | 保存 PNG/JPEG/HEIC + 质量设置 | ImageExporter | WIC 编码器(PNG/JPEG;HEIC 需扩展,见 §6.12) | P0 | +| F-13 | 复制到剪贴板(含标注) | ClipboardService | Win32 剪贴板 CF_DIB/PNG | P0 | +| F-14 | 置顶贴图(多窗口管理、点击穿透切换) | PinnedWindowsManager | WS_EX_TOPMOST + WS_EX_NOACTIVATE 独立 HWND | P1 | +| F-15 | OCR:Apple Vision(本地默认) | Vision framework | **Windows.Media.Ocr**(本地,随语言包) | P0 | +| F-16 | OCR:PaddleOCR(外部,fast/precise) | PaddleOCREngine | 同一外部进程协议移植 | P1 | +| F-17 | VLM 视觉分析:OpenAI/Claude/Gemini/Ollama/PaddleOCR | VLM Providers | HTTP Provider 移植 | P1 | +| F-18 | 翻译引擎 ×10:Apple/MTranServer/OpenAI/Claude/Gemini/Ollama/Google/DeepL/Baidu/自定义兼容 | Providers | 9 个移植 + Apple 引擎的平台替代(§6.12) | P0 | +| F-19 | OpenAI 兼容引擎多实例 | CompatibleConfig(UUID) | 同数据模型 | P1 | +| F-20 | 引擎选择 V2:ordered 有序回退链(≤5) | EngineModeV2.ordered | 同 | P0 | +| F-21 | 引擎选择 V2:compare 并行对比(2-4,免重译切换) | EngineModeV2.compare | 同(并行 HTTP) | P1 | +| F-22 | 引擎真实可用性探测(状态点,不烧配额) | EngineHealthChecker/MTranServerChecker | 同语义 | P1 | +| F-23 | 场景绑定(截图/划词/翻译插入 → 引擎链) | SceneEngineBinding + TranslationScene | 同 | P1 | +| F-24 | 自定义 Prompt(per-engine / per-兼容实例 / per-scene,{source_language}/{target_language}/{text} 占位符) | TranslationPromptConfig | 同 | P1 | +| F-25 | 可视行分组双语对照 | VisualLineGrouping.mergeLines | 纯算法移植 | P0 | +| F-26 | 译文覆盖层渲染(原位替换/下方追加) | OverlayRenderer + TranslationRenderPipeline | D2D 离屏合成 | P0 | +| F-27 | LLM 批量翻译(分段批处理 + 响应解析) | LLMTranslationBatching | 纯算法移植 | P1 | +| F-28 | 划词翻译(弹窗显示结果) | TextTranslationPopup + AX API | **UI Automation TextPattern + 剪贴板回退** | P0 | +| F-29 | 翻译并插入(目标重验证 + 粘贴回退,独立目标语言) | TextInsertionProgressController | UIA 选区重验证 + SendInput 粘贴 | P1 | +| F-30 | 翻译历史(翻译/截图/取色/上传 4 类,搜索/收藏/导出/缩略图) | HistoryStore + HistoryView | SQLite 存储 + WinUI 列表 | P1 | +| F-31 | 图床上传:PicGo/阿里 OSS/腾讯 COS/七牛 Kodo + Markdown 复制 | ImageUploadService | HTTP 客户端移植 | P2 | +| F-32 | 屏幕取色器(吸管 + HEX 历史) | eyedropperButton + color 历史 | GDI/WGC 单像素采样 | P2 | +| F-41 | **独立取色历史窗口**(大色块网格 + HEX/RGB + 复制 + 收藏/删除 + 清空,跨平台同规格) | 新增(与 Windows 同步交付) | WinUI 3 窗口(数据同 history.color 条目) | P2 | +| F-33 | 全局热键 ×5(全屏/区域/翻译/划词/插入,可自定义) | Carbon RegisterEventHotKey | **RegisterHotKey** | P0 | +| F-34 | 托盘常驻 + 菜单(全部功能入口 + 最近 5 张截图) | MenuBarController | Shell_NotifyIcon + WinUI MenuFlyout | P0 | +| F-35 | 设置窗口(通用/快捷键/标注/引擎/多引擎/语言/高级 + prompt 编辑) | Settings 13 个视图 | WinUI 3 NavigationView | P0 | +| F-36 | 密钥安全存储 | Keychain | **Windows Credential Manager / DPAPI** | P0 | +| F-37 | UI 本地化 10 语言(跟随系统) | Localizable.strings ×10 | .resw ×10 | P1 | +| F-38 | 自动更新 | Sparkle appcast | **MSIX + App Installer(.appinstaller)** | P2 | +| F-39 | 引导(首次启动权限/引导页) | Onboarding | 同语义(权限模型不同,§7) | P1 | +| F-40 | 性能埋点管线(各阶段延迟记录) | PerformanceRecorder/Pipelines | ETW/自记录移植 | P1 | + +> P0 = 1.0 发布必需;P1 = 1.0 目标(可 1.1 补);P2 = 1.x 路线图。 + +--- + +## 3. 技术选型(原生语言决策) + +### 3.1 语言与 UI 框架(决策) + +| 层 | 选型 | 理由 | +|----|------|------| +| **核心管线(截图/OCR 调度/翻译调度/覆盖层/标注渲染/热键/托盘)** | **C++20, C++/WinRT** | "尽可能高性能 + 原生语言":零 GC、直接访问 WGC/D2D/DComp/Win32,捕获与渲染热路径无托管开销 | +| **设置/历史/引擎配置 UI** | **WinUI 3(Windows App SDK 1.5+),C++/WinRT 绑定** | "UI 以 Win11 标准方式":Fluent 2、Mica、圆角、深浅色、控件无障碍全部开箱即得;非热路径,XAML 开发效率可接受 | +| **热路径窗口(选区覆盖层/预览画布/置顶贴图/就地工具栏)** | **纯 Win32 HWND + Direct2D 1.1 + DirectComposition** | XAML 不适合每帧重绘的标注画布与全屏覆盖层;D2D/DComp 是 GPU 加速的标准答案 | +| 脚本/CI 辅助 | PowerShell / pwsh | 打包签名、appinstaller 生成 | + +**备选方案与否决理由**(记录决策,不再复议): + +- ~~C# + WinUI 3 全栈~~:更快的开发速度,但违反"原生语言/极致性能"的硬性要求(托管启动 ~150-300ms、GC 停顿在 120fps 标注绘制中可感知)。若后续评估开发产能不足,可降级为"核心 C++ + 设置 C#"混合,数据层接口(§4.2)已按 ABI 稳定设计,允许该切换。 +- ~~Win32 + 自绘 Fluent 控件全量~~:Mica/DWM 圆角可做,但 NavigationView/TextBox 无障碍/输入法/触控全套自绘成本不可接受。 +- ~~Electron/Tauri/Web~~:直接否决(内存 200MB+、非原生)。 + +### 3.2 系统能力映射(macOS API → Windows API 总表) + +| 能力 | macOS | Windows 选型 | 备注 | +|------|-------|--------------|------| +| 屏幕捕获 | ScreenCaptureKit | **Windows.Graphics.Capture**(GraphicsCaptureItem per monitor) | GPU 纹理直达 D2D,零拷贝;Win11 支持关闭黄边框(`IsBorderRequired=false`,contract 15+);GDI `BitBlt` 作为不支持时回退 | +| 全屏连续帧 | —(按需) | DXGI Desktop Duplication(备选) | 仅当 WGC 不可用 | +| 窗口枚举/检测 | CGWindowListCopyWindowInfo | **EnumWindows + DwmGetWindowAttribute(DWMWA_EXTENDED_FRAME_BOUNDS)** + `WindowFromPoint` | 真实可见边界(排除不可见阴影),DWM 层级过滤 cloaked/UWP 挂起窗口(`DwmGetWindowAttribute(DWMWA_CLOAKED)`) | +| 全局热键 | Carbon RegisterEventHotKey | **RegisterHotKey / WM_HOTKEY** | 冲突检测:RegisterHotKey 失败即冲突提示 | +| 划词取文本 | Accessibility AX API | **UI Automation(UIA TextPattern: GetSelection/RangeFromPoint)**;剪贴板回退:发送 Ctrl+C 模拟(可配置,默认开) | UIA 只读不需要管理员;TextPattern 覆盖 Win32/WinUI/WPF/浏览器 | +| 翻译并插入 | AX 设值 + 粘贴回退 | **UIA ValuePattern 设值** + `SendInput` Ctrl+V 粘贴回退 + **目标重验证**(读回选区比对) | 与 macOS 同一套安全语义:先重验证后粘贴 | +| 剪贴板 | NSPasteboard | Win32 Clipboard(CF_DIB + PNG 垃圾格式 + delayed render) | | +| 置顶窗口 | NSWindow level | **WS_EX_TOPMOST / WS_EX_NOACTIVATE / WS_EX_TOOLWINDOW** | 独立 HWND per pin | +| 全屏覆盖层 | NSWindow overlay | **WS_POPUP + WS_EX_LAYERED + WS_EX_TOPMOST + Per-Monitor V2 DPI**,DirectComposition 视觉树 | 选区 UI 载体 | +| 屏幕取色 | CGDisplayCreateImage 像素 | WGC 单帧或 `GetDC+GetPixel`(回退) | | +| OCR | Vision | **Windows.Media.Ocr.OcrEngine**(本地,Bing 离线语言包) | 中文识别质量弱于 Vision/Paddle → 默认引擎策略见 §6.4 | +| 本地翻译(Apple Translation 对位) | Translation framework | **无系统公开 API** → 从默认链移除该槽位,MTranServer 接棒默认。本地能力一律通过外部引擎接入(MTranServer / Ollama / 兼容端点),**不内置任何模型**(决策 1) | 平台无系统翻译 API;已裁决不引入模型运行时 | +| 密钥存储 | Keychain | **Windows Credential Manager(CredWrite/CredRead,TARGET=TransFrame/)**;备选 DPAPI CryptProtectData 加密后落 JSON | | +| 设置存储 | UserDefaults | **JSON 文件**:`%LOCALAPPDATA%\TransFrame\settings.json`(schema 与 macOS Keys 一一对应,前缀 TransFrame.) | 便于跨平台 schema 对齐与迁移 | +| 历史存储 | HistoryStore(JSON) | **SQLite(WAL)**:`%LOCALAPPDATA%\TransFrame\history.db`;含 schema v1 迁移表 | 搜索用 LIKE(决策 2:不启用 FTS5) | +| HTTP 客户端 | URLSession | **WinHTTP**(或 `Windows.Web.Http`);重试/超时/取消语义对齐 URLSession 封装 | | +| 自动更新 | Sparkle appcast | **MSIX + App Installer**:.appinstaller 指向 HTTPS 更新源,检查周期/强制更新策略可配 | 仅 MSIX 单一分发通道(决策 3:不做便携版) | +| 图标/符号 | SF Symbols | **Segoe Fluent Icons** + 自绘 OCR/翻译字形 | | +| 材质 | NSVisualEffectView | **Mica(DWMWA_SYSTEMBACKDROP_TYPE=DWMSBT_MAINWINDOW)**;覆盖层用 Acrylic | | +| 深浅色 | NSAppearance | Registry `AppsUseLightTheme` + `UISettings.ColorValuesChanged` 事件 | | +| 通知 | UserNotifications | **Windows App Notifications(appnotification:)** | | +| 多显示器/DPI | NSScreen + backingScaleFactor | **EnumDisplayMonitors + GetDpiForMonitor(Per-Monitor V2)** | 坐标统一用物理像素,输出时换算 | +| 无障碍 | Accessibility | **UIA AutomationPeer(XAML 自动)+ 自绘控件的 UIA provider** | P1 验收项 | +| 开机自启 | SMLoginItemSetEnabled | **StartupTask(MSIX)** / HKCU Run 键 | | +| 性能埋点 | os_signpost + PerformanceRecorder | **ETW EventTracingLog + 同名 PerformanceRecorder 移植** | 导出 JSON 报告 | + +### 3.3 依赖清单(全部原生/开源,无运行时付费) + +| 组件 | 选择 | 许可 | +|------|------|------| +| Windows SDK | 10.0.26100+(Win11 24H2) | — | +| C++/WinRT | 2.0.230706+ | MIT | +| Windows App SDK | 1.5+ | MIT | +| JSON | nlohmann/json v3.11 | MIT | +| SQLite | 3.45+(仅 history.db,**LIKE 检索,不启用 FTS5**,决策 2) | Public Domain | +| libheif(HEIC 导出) | 1.17+ | LGPL-3(动态链接,或改用 WIC HEIF 扩展探测) | 见 §6.12 | +| 单元测试 | Catch2 v3 / MSVC 自带 | BSL-1.0 | +| 打包 | MSIX + signtool(EV 证书或 Azure Trusted Signing) | — | + +--- + +## 4. 系统架构 + +### 4.1 分层与模块(对齐 macOS feature-based 结构) + +``` +┌────────────────────────────────────────────────────────────────────┐ +│ App 层 │ +│ App.cpp(入口) AppController(生命周期/热键分发/权限) │ +│ Coordinators: CaptureCoordinator / TextTranslationCoordinator / │ +│ HotkeyCoordinator / TrayCoordinator │ +├────────────────────────────────────────────────────────────────────┤ +│ Features(UI 层) │ +│ TrayMenu/ 托盘图标 + MenuFlyout(最近截图 5 张) │ +│ SelectionOverlay/ 全屏选区层窗口(D2D:变暗、选框、尺寸提示、 │ +│ 窗口高亮、十字准线、就地工具栏、就地结果面板) │ +│ Preview/ 预览窗口(WinUI 3 外壳 + D2D 标注画布子 HWND) │ +│ Pinned/ 置顶贴图窗口管理器(多窗口/穿透切换/回收) │ +│ TextTranslation/ 划词弹窗 + 插入进度控制器 │ +│ Settings/ NavigationView 七页签设置 │ +│ History/ 历史窗口(搜索/收藏/导出/缩略图) │ +│ Onboarding/ 首启引导 │ +├────────────────────────────────────────────────────────────────────┤ +│ Services(业务层,可测、无 UI 依赖) │ +│ Capture/ WGC 捕获 + 显示器枚举 + 窗口检测 │ +│ OCR/ OcrEngine 接口:WindowsOcr / PaddleOcr / Vlm │ +│ Translation/ EngineRegistry + 10 Provider + 兼容实例 + │ +│ ordered/compare 调度 + EngineHealthChecker │ +│ Pipelines/ CapturePipeline / AnalysisPipeline / │ +│ TranslationRenderPipeline(含 PerformanceRecorder)│ +│ VisualLineGrouping / LLMTranslationBatching(纯算法,全平台共享) │ +│ Overlay/ OverlayRenderer(D2D 离屏合成) │ +│ Hotkeys/ TextInsertion/ Clipboard/ ImageExport(WIC)/ ImageUpload/ │ +│ ColorPicker/ KeyStore(CredMan)/ SettingsStore(JSON)/ HistoryStore │ +├────────────────────────────────────────────────────────────────────┤ +│ Models(纯数据,schema 与 macOS 一一对应) │ +│ AppSettings / Annotation(11 种) / Screenshot / CaptureDocument / │ +│ OCREngineType / TranslationEngineType / EngineChainItem / │ +│ EngineModeV2 / TranslationScene / SceneEngineBinding / │ +│ TranslationPromptConfig / TranslationResultBundle / BilingualSegment │ +│ / TranslationHistory / ExportFormat / AppLanguage / ... │ +└────────────────────────────────────────────────────────────────────┘ + TransFrameTests(Catch2:模型/算法/管线单测 + PRD 验收测试) +``` + +### 4.2 模块形态与 ABI + +- `Core`(Models + 纯算法 Services)编译为**静态库 `TransFrame.Core.lib`**:无 WinRT UI 依赖,Catch2 直测;未来允许 C# 互操作切换(§3.1 备选)。 +- `NativeShell`(Win32/D2D/WGC/热键/托盘)静态库,仅依赖 Core + Windows SDK。 +- `TransFrame`(WinUI 3 app,C++/WinRT),依赖上两者。 +- 输出:MSIX 包(x64 + arm64)。 + +### 4.3 关键数据流(与 macOS 管线同构) + +``` +热键 → AppController + → CapturePipeline: 权限检查 → 显示器查找(带 2s 缓存策略) → WGC 捕获 → Screenshot + → SelectionOverlay: 窗口检测高亮 / 拖拽选区 → captureRegion + → AnalysisPipeline: OCR(WindowsOcr|Paddle|VLM) → 分段(TextSegment+归一化bbox+confidence) + → TranslationRenderPipeline: VisualLineGrouping 合并视觉行 → + ordered: 链式回退 | compare: 并行(2-4) + → TranslationResultBundle(per-engine EngineResult + BilingualSegment[]) + → 呈现: PreviewResultsPanel(双语抽屉) / OverlayRenderer(覆盖层) / Pinned / History +每阶段经 PerformanceRecorder 计时(operationID 串联),可导出延迟报告。 +``` + +--- + +## 5. 用户与场景 + +(与 macOS 版一致,平台无差异) + +- **U1 玩游戏/看外语文档的普通用户**:快捷键圈屏幕 → 原位看到译文。核心路径延迟敏感。 +- **U2 开发者/研究者**:大量外文文档、报错、技术网页;划词翻译 + 翻译并插入写代码注释。 +- **U3 内容创作者**:截图 + 标注 + 打码 + 图床上传 + 贴图置顶对照。 +- **U4 隐私敏感用户**:只用本地链(Windows OCR + MTranServer/Ollama 本地端点),设置里显式禁用云引擎。 + +--- + +## 6. 功能需求(FR,含验收标准) + +> 验收标准 = TransFrameTests 中可执行测试或可手工复现步骤。P0 缺一不可发布。 + +### 6.1 截图捕获(FR-01…06) + +**FR-01 区域截图(P0)** +- 热键(默认 `Win+Shift+S` 冲突避让 → 默认 **Ctrl+Alt+A**,可自定义)进入全屏选区模式:所有显示器变暗(半透明黑 40%),显示十字准线与实时尺寸徽标。 +- 拖拽绘制矩形,选区内保持原亮度并 1px 高亮描边;松开即捕获。 +- Esc 取消;捕获期间覆盖层接收全部输入(鼠标+键盘)。 +- 多显示器:覆盖层横跨整个虚拟桌面;坐标以物理像素记录,Per-Monitor V2 DPI。 +- 验收:单屏/双屏混合 DPI(100%/150%/200%) 下选区像素与所见一致;松开→预览窗口出现 ≤ 100ms(本地实测,PerformanceRecorder 记录)。 + +**FR-02 窗口自动识别(P0,对齐 window-detection-auto-select spec)** +- 选区模式下鼠标悬停:实时检测光标下最顶层可见窗口,1px 强调色边框高亮 + 淡色填充;单击即整窗捕获。 +- 按下并拖动 → 忽略高亮,进入手动圈选(行为与 FR-01 完全一致)。 +- 高亮随移动平滑切换(≤ 1 帧);桌面空白处只显示十字准线。 +- Win32/UWP(含 cloaked 过滤)/浏览器子窗口均正确;最大化窗口排除阴影边界(DWMWA_EXTENDED_FRAME_BOUNDS)。 +- 验收:Notepad/Chrome/WinUI 应用/UWP 各悬停单击,捕获边界与 DWM 可见边一致;拖拽路径不触发整窗捕获。 + +**FR-03 全屏截图(P0)** +- 热键(默认 Ctrl+Alt+F)全屏捕获;多显示器时弹出显示器选择菜单(含分辨率与"主显示器"标记),单显示器直接捕获。 +- 验收:3 屏混合 DPI,每屏均按原生分辨率捕获。 + +**FR-04 翻译模式(P0)** +- 热键(默认 Ctrl+Alt+T)= 区域截图 + 自动 OCR + 翻译 + 结果呈现,无额外点击。 +- 验收:从热键到译文出现计时(本地 OCR+MTranServer P95 ≤ 1.2s)。 + +**FR-05 就地工具栏(P1)**:选区确认后选区边缘出现工具条(复制/保存/翻译/置顶/取色/取消),D2D 绘制,可鼠标操作,Esc 关闭。 +**FR-06 就地结果面板(P1)**:翻译结果停靠在选区侧边(空间自适应),显示原文/译文对照,可切换引擎结果(compare 模式),可"贴图置顶"。 + +### 6.2 预览与标注(FR-07…12) + +**FR-07 预览窗口(P0)** +- 捕获后打开预览:标题栏(文件名/尺寸)、工具栏、画布、(翻译模式下)结果抽屉。 +- 快捷键:`Enter`/`Ctrl+S` 保存;`Ctrl+C` 复制并关闭;`Esc` 关闭/退出裁剪;`R/1` 矩形、`D/2` 手绘、`A/3` 箭头、`T/4` 文字、`C` 裁剪、`Ctrl+Z` 撤销、`Ctrl+Y`/`Ctrl+Shift+Z` 重做、`Del` 删除选中标注、拖拽文字标注可移动。 +- 窗口支持 Snap Layouts、记住尺寸位置、深浅色跟随。 + +**FR-08/09 标注(P0/P1)** +- 11 种全量:矩形、椭圆、直线、箭头、自由手绘、文字、马赛克、高亮、数字标签、隐私遮挡、气泡。各自支持颜色/线宽/填充/字号(对齐 macOS Annotation 模型的每类型属性集)。 +- 选中/移动/删除单个标注;标注渲染在 D2D 硬件加速画布,笔迹延迟 ≤ 8ms(120Hz 显示器实测)。 +- ⌘-drag 约束等价:Shift+拖拽 = 正方形/正圆/水平垂直线/45° 箭头。 + +**FR-10 智能打码(P2)**:VLM 检测敏感区域(人脸/证件/电话等)批量生成马赛克标注,单次撤销覆盖整批。 +**FR-11 裁剪/撤销(P0)**:裁剪进入覆盖交互,Enter 应用/Esc 取消;裁剪清除标注(与 macOS 行为一致,提示确认);撤销栈 50 步。 +**FR-12 保存与导出(P0)**:格式 PNG/JPEG/HEIC + JPEG/HEIC 质量滑杆;默认位置可配(默认 `图片\屏幕截图`);文件名模板(时间戳);保存对话框/直接保存可配。HEIC:优先走系统 WIC HEIF 编码器(Win11 需装 HEVC 扩展,未装时 UI 明示并回退 PNG/JPEG)。 + +### 6.3 OCR(FR-15…17) + +**FR-15 Windows OCR 引擎(P0)** +- `Windows.Media.Ocr`:本地、离线、按已安装语言包自动可用;结果映射为 `TextSegment[]`(text + 归一化 bbox + confidence)。 +- 语言包缺失时给出安装引导(ms-settings:regionlanguage);中文包未装时状态点为灰。 +- 验收:中英混合截图段落级识别,bbox 归一化坐标与 macOS 版同 schema。 + +**FR-16 PaddleOCR 外部引擎(P1)** +- 与 macOS 相同的外部进程协议(可执行路径 + fast(~1s)/precise(~12s) 两档);健康检查缓存语义一致。 +**FR-17 VLM OCR/分析(P1)** +- OpenAI/Claude/Gemini/Ollama/PaddleOCR-VL 五个 Provider 移植:图像 base64/URL 上传、分段解析(bbox+confidence)、错误分类。 + +### 6.4 翻译引擎(FR-18…27) + +**FR-18 引擎集(P0)** +- 移植 9 个:MTranServer、OpenAI、Claude、Gemini、Ollama、Google、DeepL、Baidu、自定义 OpenAI 兼容(含无密钥本地端点)。 +- Apple Translation 无 Windows 对应:**默认有序链调整为 `MTranServer → WindowsOCR 场景下的次选`**;"本地翻译"能力全部通过外部引擎接入(MTranServer/Ollama/兼容端点),**不内置模型**(决策 1,详见 §6.12)。 +- 每引擎配置卡片:开关、密钥(Credential Manager)、端点/模型、超时(默认 10s)、测试连接。 + +**FR-19 兼容引擎多实例(P1)**:OpenAI 兼容端点可建多实例(UUID 标识),链/对比/场景绑定中以实例身份出现。 + +**FR-20 ordered 有序回退链(P0)**:≤5 个引擎按序尝试,单个失败自动落入下一个;每个引擎结果带延迟;整链失败输出聚合错误(per-engine 摘要,对齐 TextTranslationError 聚合行为)。 +**FR-21 compare 并行对比(P1)**:2-4 引擎并行请求;结果侧栏同时呈现,点击切换不重发请求(缓存 per-engine EngineResult)。 +**FR-22 可用性探测(P1)**:设置页引擎状态点(绿=可用/红=不可达/橙=慢/灰=未配置);探测仅用轻量端点(如 MTranServer ping、LLM models 列表),**绝不调用计费翻译接口**;结果缓存 TTL 与 macOS 一致。 +**FR-23 场景绑定(P1)**:screenshot / text_selection / translate_and_insert 三场景可各自绑定 ordered 链或 compare 集;未绑定时用全局链。 +**FR-24 自定义 Prompt(P1)**:per-engine / per-兼容实例 / per-scene 三层覆盖;默认模板含 `{source_language}` `{target_language}` `{text}` 占位符;插入场景有专用默认 prompt(简洁、无格式)。 +**FR-25 视觉行分组(P0)**:`VisualLineGrouping.mergeLines` 纯算法移植:同一视觉行的碎片合并为一个翻译单元与一个覆盖层锚点。验收:移植 macOS 同套测试向量(跨平台共享测试数据 JSON)。 +**FR-26 覆盖层渲染(P0)**:原位替换(按背景色自适应文字色)与下方追加两种模式;D2D 离屏渲染后合成回截图;导出/贴图/复制均带覆盖层。 +**FR-27 LLM 批量翻译(P1)**:分段批处理(编号分隔)+ 响应解析器移植(处理截断/乱序/多行),失败自动降级为逐段。 + +### 6.5 划词与插入(FR-28/29) + +**FR-28 划词翻译(P0)** +- 热键(默认 Ctrl+Alt+D)→ 优先 UIA TextPattern 取当前焦点控件选区文本;不支持 UIA 的应用回退"模拟 Ctrl+C 读剪贴板"(设置可关,且回退前保存/恢复原剪贴板内容)。 +- 结果弹窗:无焦点抢占(WS_EX_NOACTIVATE),原文/译文/引擎延迟/重译按钮/copy/收藏;点击他处自动关闭。 +- 验收:记事本/Word/Chrome/Edge/WinUI 应用/终端 各验证 UIA 路径;剪贴板回退路径验证原内容恢复。 + +**FR-29 翻译并插入(P1)** +- 热键(默认 Ctrl+Alt+I)→ 取选中原文 → 翻译(独立目标语言设置)→ **目标重验证**(UIA 读回当前选区仍为原文,未变则继续)→ 粘贴回退(SendInput Ctrl+V);重验证失败则中止并提示,绝不覆盖意外内容。 +- 插入进度浮层(进行中/完成/失败三态);全程不与输入法冲突(对齐 macOS 语义:粘贴而非直接设值优先)。 + +### 6.6 历史 / 图床 / 取色(FR-30…32) + +**FR-30 翻译历史(P1)**:4 类条目(translation/screenshot/color/upload);字段与 macOS TranslationHistory 一致;搜索(原文/译文)、收藏、删除、导出(JSON/CSV/TXT)、缩略图(截图类)、最近 5 张截图入口在托盘菜单;容量上限与自动清理可配。 +**FR-31 图床上传(P2)**:PicGo(本地 HTTP)/阿里 OSS/腾讯 COS/七牛 Kodo 四通道 + 配置卡片 + 上传后复制(URL 或 Markdown 可选);上传记录入 history。 +**FR-32 屏幕取色器(P2)**:放大镜取色(WGC 单帧采样),HEX 显示、加入历史(color 类条目)、点击复制。 + +**FR-41 独立取色历史窗口(P2,两平台同步交付,见 `docs/specs/color-history-window.md`)** +- 独立窗口(非弹层),从托盘菜单与取色器入口打开;网格色块(≥48px)+ HEX/RGB 文本 + 取色时间。 +- 操作:单击复制 HEX;右键/悬浮菜单收藏、删除;顶栏搜索(HEX 片段)+ 仅收藏过滤 + 清空全部(带确认);复制成功即时反馈。 +- 数据:复用 history `color` 类目条目(不另建存储);条目上限/自动清理沿用历史设置。 +- 验收:取色 → 打开窗口看到条目;收藏过滤、搜索、删除、清空各路径;两平台同一交互规格。 + +### 6.7 壳与系统(FR-33…40) + +**FR-33 全局热键(P0)**:5 组热键(全屏/区域/翻译/划词/插入)RegisterHotKey 注册;冲突时注册失败→设置页标红 + 托盘气泡提示;改后即时生效无需重启;快捷键录制控件(键+修饰键,必须含至少一个修饰键,校验规则与 macOS 版一致)。 +**FR-34 托盘(P0)**:常驻托盘图标(截图镜头),左键弹 MenuFlyout:全屏/区域/翻译/划词/插入/置顶管理/历史/设置/检查更新/退出 + 最近截图(5 张缩略图);托盘图标不占任务栏。 +**FR-35 设置窗口(P0)**:NavigationView 七页:通用(语言/保存/格式/质量/开机自启/更新检查)、快捷键、标注默认样式、引擎(10 卡片+兼容实例管理)、多引擎(ordered 链编辑器/compare 编辑器/场景绑定/prompt 编辑)、语言(源/目标/插入独立目标/界面语言)、高级(日志/性能报告/数据目录/重置)。 +**FR-36 密钥安全(P0)**:所有 API Key 存 Credential Manager(`TransFrame//`),明文不落 settings.json;UI 显示为 `sk-****last4`;导出配置不含密钥。 +**FR-37 本地化(P1)**:10 语言 .resw(en/zh-Hans/de/es/fr/it/ja/ko/pt/ru)+ 跟随系统 + 手动覆盖;日期数字格式随区域。 +**FR-38 自动更新(P2)**:MSIX + .appinstaller(HTTPS 源、版本比较、可选强制);仅 MSIX 单一分发通道(决策 3,无便携版)。 +**FR-39 首启引导(P1)**:3 步引导(热键介绍 → 隐私声明:哪些引擎联网 → 默认链选择);无 macOS 权限弹窗(Windows 无屏幕录制权限概念,UIA 只读无需授权)。 +**FR-40 性能埋点(P1)**:PerformanceRecorder 移植,阶段=permission/displayLookup/capture/ocr/translation/render;operationID 串联全链路;设置页可导出 JSON 报告。 + +### 6.8 Win11 UI/UX 规范(FR-50 组) + +- **FR-50.1(P0)Mica 材质**:主设置/历史/预览窗口 `DWMWA_SYSTEMBACKDROP_TYPE=DWMSBT_MAINWINDOW`;选区覆盖层/弹窗用 Acrylic(`DWMSBT_TRANSIENTWINDOW`)。 +- **FR-50.2(P0)圆角**:窗口 DWM 自动圆角;自绘弹层 8px 圆角。 +- **FR-50.3(P0)深浅色**:跟随系统(含"自动/浅/深"三态覆盖);所有自绘内容双主题色板。 +- **FR-50.4(P0)Snap Layouts**:预览/历史/设置窗口支持 Win11 贴靠(标准 Win32 即得,验收确认)。 +- **FR-50.5(P1)Segoe Fluent Icons**:全部图标走 Segoe Fluent Icons / Segoe MDL2 fallback;小图标对齐 16/20/24px 网格。 +- **FR-50.6(P1)无障碍**:XAML 控件 UIA 自动暴露;自绘工具栏/画布实现 UIA Provider(名称/角色/可用性);完整键盘操作路径;对比度 ≥ 4.5:1。 +- **FR-50.7(P1)系统通知**:保存/上传/更新完成用 Windows 通知,失败用对话框。 +- **FR-50.8(P1)高刷新率**:标注画布 DComp 垂直同步,120Hz+ 无撕裂。 +- **FR-50.9(P2)动画**:面板展开、弹窗淡入等用 Composition 动画(Implicit Animations),关闭可在设置禁用(减少动效)。 + +### 6.9 数据模型与迁移(FR-60) + +- settings.json schema 与 macOS UserDefaults 键一一对应(`TransFrame.` 前缀保留);Windows 专属键加 `.win` 后缀命名空间。 +- 历史库 schema v1:`entries(id, category, source_text, translated_text, source_lang, target_lang, timestamp, thumbnail_path, is_favorite, meta_json)` + `schema_version` 表。 +- 验收:两平台同一截图输入 → 输出的 BilingualSegment/EngineResult JSON 逐字段等值(跨平台快照测试)。 + +### 6.10 安全与隐私(FR-61) + +- 明确的网络出口白名单(按引擎配置动态);设置页"隐私"面板列出:本地处理 vs 联网引擎清单。 +- 密钥仅 Credential Manager;崩溃日志(可选开启)不含密钥/剪贴板内容。 +- MSIX 签名(Azure Trusted Signing 或 EV 证书);SmartScreen 信誉积累。 + +### 6.11 可靠性(FR-62) + +- 引擎请求全部可取消(WinHTTP + cancel token);全局"取消"Esc 传播。 +- 单引擎崩溃/超时不拖垮链(ordered 语义);OCR/翻译异常都有用户可读错误 + 重试。 +- 崩溃时未保存的截图/标注在下次启动可恢复(session 文件 `%LOCALAPPDATA%\TransFrame\session\`)。 + +### 6.12 平台差异对照表(唯一允许的行为差异) + +| 差异点 | macOS | Windows 处理 | 理由 | +|--------|-------|--------------|------| +| Apple Translation | 系统内置本地翻译 | 移除该引擎,默认链首改为 MTranServer(若不可达按链回落);本地能力一律外部引擎接入(MTranServer/Ollama/兼容端点),不内置模型(决策 1) | Windows 无公开系统翻译 API | +| Apple Vision OCR | 默认引擎 | Windows.Media.Ocr 为默认;中文质量不足场景由 PaddleOCR/VLM 补 | 平台 OCR 能力差异 | +| HEIC 导出 | 系统原生 | WIC HEIF(需 HEVC 扩展)探测,未装时 UI 提示并回退 | 编解码器分发差异 | +| Sparkle 更新 | appcast | MSIX/App Installer | 平台标准 | +| 屏幕录制权限 | 系统授权弹窗 | 无权限概念(WGC 首次出现单次系统确认条) | 平台安全模型 | +| 辅助功能权限 | Accessibility 授权 | UIA 只读无需授权 | 平台安全模型 | +| 默认快捷键 | Cmd 系 | Ctrl+Alt 系(Win+Shift+S 留给系统截图) | 键位布局差异 | +| 触控栏/焦点行为 | NSWindow | WS_EX_NOACTIVATE 等价实现 | 窗口模型差异 | +| 全局快捷键实现 | Carbon | RegisterHotKey(系统级,不吃焦点) | — | +| 引擎注册表缓存 | 逐引擎精细失效 | config-slice 缓存:配置变更整体重建引擎对象(毫秒级内存操作,无用户感知差异)。理由:C++ `unique_ptr` 独占所有权使逐引擎新旧比较不可行(**已裁决,2026-11-02**) | 语言所有权模型差异 | +| 错误分类 | 4 类(网络/配额/鉴权/内容) | 5 类,新增 `Configuration`(未配 key/配置损坏时提示"请先配置"而非含糊网络错误)(**已裁决,2026-11-02**) | Windows 实现更准确,不影响 macOS | + +### 6.13 支持矩阵 + +| 场景 | Win11 22H2+ (22621) | Win10 21H2 (19044) | +|------|---------------------|--------------------| +| WGC 捕获(无边框) | ✅ 完整 | ⚠️ 黄边框保留(系统限制) | +| Mica/Acrylic | ✅ | ⚠️ 回退纯色 | +| Snap Layouts | ✅ | ❌(标准贴靠) | +| UIA 划词 | ✅ | ✅ | +| 支持级别 | 一等公民 | 降级支持,不阻塞发布验收 | + +最低:Windows 10 21H2;目标:Windows 11 24H2。x64 + arm64 双架构。 + +--- + +## 7. 权限与首启流程 + +1. 首次触发截图:WGC 在系统级出现一次"TransFrame 开始捕获"确认(系统行为,非应用弹窗);之后静默。 +2. 划词:UIA 只读零权限;"剪贴板回退"模式首次使用时提示一次。 +3. 首启引导三步(FR-39)后直接可用,**无需重启**(对比 macOS 的屏幕录制重启)。 + +--- + +## 8. 性能预算(NFR) + +| 指标 | 预算 | 测量方式(PerformanceRecorder/ETW) | +|------|------|--------------------------------------| +| 热键→选区覆盖层出现 | ≤ 60ms | ETW 事件对 | +| 松开选区→预览窗口首帧 | ≤ 100ms | recorder | +| WGC 捕获 4K 全屏 | ≤ 50ms(GPU→CPU 一次拷贝) | recorder | +| 本地 OCR(1080p 选区) | ≤ 300ms P95 | recorder | +| 本地链翻译(MTranServer) | ≤ 500ms P95 | recorder | +| **端到端(热键→译文覆盖层,本地链)** | **≤ 1.2s P95** | 全链 operationID | +| 标注笔迹输入延迟 | ≤ 8ms(120Hz) | 帧时间戳 | +| 常驻内存(托盘态) | ≤ 80MB 工作集 | 性能监视器 | +| 冷启动(托盘就绪) | ≤ 800ms | 事件对 | +| 空闲 CPU | 0%(无轮询,事件驱动) | 性能监视器 | +| 安装包体积 | ≤ 25MB(arm64+x64 合包) | 构建产物 | + +验收:以上每项写入 `TransFrameTests/perf/` 基准,CI 记录趋势,超预算 20% 报警。 + +--- + +## 9. 用户故事(US,映射 FR;格式对齐 macOS PRD) + +> Quality Gates(每个 US 完成的定义):`msbuild /p:Configuration=Release` 零警告(/W4 /WX 于 Core)、Catch2 全绿、swiftlint 对应物 = clang-format 检查通过、MSIX 打包成功、x64+arm64 双架构构建。 + +### US-W01: 工程初始化与托盘骨架 +As a developer, I want the WinUI 3 + C++20 solution skeleton so features build on a solid base. +- [ ] 解决方案三分层(Core/NativeShell/App)+ Catch2 测试工程 +- [ ] 托盘图标 + MenuFlyout(全屏/区域/翻译/划词/插入/历史/设置/退出占位项) +- [ ] MSIX 打包 + 签名脚本;x64/arm64 CI +- [ ] 设置/历史目录 `%LOCALAPPDATA%\TransFrame\` 初始化 + +### US-W02: 全局热键 +(FR-33)RegisterHotKey ×5,可配置、冲突提示、即时生效、Esc 取消传播。 + +### US-W03: 区域截图 + 全屏覆盖层 +(FR-01)全屏变暗、拖拽、尺寸徽标、Esc 取消、多显示器、DPI、WGC 捕获 → Screenshot 模型。 + +### US-W04: 窗口自动识别 +(FR-02)EnumWindows/DWM 检测、悬停高亮、单击整窗、拖拽忽略,性能 ≤1 帧切换。 + +### US-W05: 全屏截图与显示器选择 +(FR-03) + +### US-W06: Windows OCR 引擎 +(FR-15)Windows.Media.Ocr → TextSegment[]、语言包检测与引导、异步不阻塞 UI。 + +### US-W07: MTranServer 翻译引擎 +(FR-18)HTTP 客户端(超时 10s、取消、错误分类)、自动语言检测、目标语言配置。 + +### US-W08: 翻译引擎全家(LLM/云) +(FR-18)OpenAI/Claude/Gemini/Ollama/Google/DeepL/Baidu/自定义 ×9 Provider + 密钥卡 + 测试连接。 + +### US-W09: ordered 有序回退链 +(FR-20)≤5 链、逐个回落、聚合错误、per-engine 延迟显示。 + +### US-W10: 预览窗口与保存/复制 +(FR-07/12)WinUI 外壳 + 画布、Enter 保存、Ctrl+C 复制、格式与质量、位置记忆。 + +### US-W11: 标注工具集(11 种) +(FR-08/09)D2D 画布、选中/移动/删除、Shift 约束、撤销重做 50 步、深浅色。 + +### US-W12: 裁剪 +(FR-11) + +### US-W13: 视觉行分组与双语抽屉 +(FR-25 + PreviewResultsPanel 对位)合并行、原文/译文对照、可编辑原文重译。 + +### US-W14: 覆盖层渲染 +(FR-26)原位替换/下方追加、自适应文字色、合成导出。 + +### US-W15: compare 并行对比 +(FR-21)2-4 并行、免重译切换、延迟徽标。 + +### US-W16: 划词翻译 +(FR-28)UIA TextPattern + 剪贴板回退 + 无焦点弹窗 + 重译/复制/收藏。 + +### US-W17: 翻译并插入 +(FR-29)目标重验证 + 粘贴回退 + 独立目标语言 + 进度浮层。 + +### US-W18: PaddleOCR 外部引擎 +(FR-16)路径配置、fast/precise、健康检查。 + +### US-W19: VLM 视觉分析 +(FR-17)五 Provider、bbox 解析、智能打码(FR-10)。 + +### US-W20: 兼容引擎多实例 +(FR-19)UUID 实例、链/对比/绑定引用。 + +### US-W21: 引擎健康探测 + 场景绑定 + Prompt +(FR-22/23/24) + +### US-W22: 设置窗口七页签 +(FR-35)含 ordered/compare 拖拽编辑器、快捷键录制、语言页。 + +### US-W23: 翻译历史 +(FR-30)SQLite、4 类、搜索/收藏/导出、托盘最近截图。 + +### US-W24: 置顶贴图 +(FR-14)多窗口、穿透切换(对齐 macOS"禁用点击穿透/恢复交互"语义)、聚拢到前台。 + +### US-W25: 图床上传 +(FR-31)四通道 + Markdown 复制。 + +### US-W26: 屏幕取色器 + 独立取色历史窗口 +(FR-32/FR-41)取色器落地;取色历史独立窗口(两平台同规格,与 macOS 侧 `ColorHistoryWindow` US 同步验收)。 + +### US-W27: 本地化 10 语言 +(FR-37) + +### US-W28: 自动更新 +(FR-38).appinstaller 通道(仅 MSIX,无便携版,决策 3)。 + +### US-W29: 性能埋点与基准 +(FR-40 + §8 全部指标进 CI)。 + +### US-W30: 首启引导 + 无障碍 + 打磨 +(FR-39/50.6)三步引导、UIA Provider、键盘路径。 + +--- + +## 10. 里程碑 + +| 里程碑 | 范围(US) | 出口条件 | +|--------|-----------|----------| +| **M1 骨架**(2 周) | W01, W02 | 托盘+热键可用;MSIX CI 双架构绿 | +| **M2 捕获闭环**(3 周) | W03, W04, W05, W10 | 截图→预览→保存/复制全链路(无翻译);性能预算前 4 项达标 | +| **M3 翻译闭环**(3 周) | W06, W07, W08, W09, W13, W14 | 端到端 ≤1.2s P95(本地链);双语抽屉+覆盖层 | +| **M4 完整功能**(4 周) | W11, W12, W15–W21, W22, W24 | 特性集 = macOS P0+P1 全勾 | +| **M5 打磨发布**(2 周) | W23, W25–W30 | P2 项按取舍;无障碍+本地化+更新通道;公开 Beta | + +总计 ~14 周一名资深 C++ 工程师 + 0.5 名设计/测试支持。 + +--- + +## 11. 测试与质量门禁 + +- **单元**(Catch2, Core 层):模型、VisualLineGrouping、LLMTranslationBatching、Prompt 解析、链调度(mock provider)、设置 schema 往返。 +- **跨平台快照**:共享测试向量 JSON(与 macOS TransFrameTests 同源)保证两平台同输入同输出。 +- **集成**:WGC 捕获(多 DPI)、UIA 划词(目标应用矩阵:Notepad/Word/Chrome/Edge/WinUI/终端)、热键冲突、Credential Manager 读写。 +- **性能**:§8 全指标基准化,CI 趋势门禁(超 20% fail)。 +- **UI**:WinUI 控件手测清单 + 截图对比(深浅色 ×10 语言抽样 3 语言)。 +- **打包**:干净 Win11 VM 安装→热键全流程冒烟;Win10 21H2 降级矩阵冒烟。 + +--- + +## 12. 风险与缓解 + +| 风险 | 等级 | 缓解 | +|------|------|------| +| C++/WinRT + WinUI 3 开发效率低于预期 | 高 | §3.1 备选:设置层切 C#(ABI 已隔离);里程碑 M2 末做 Go/No-Go 评审 | +| Windows OCR 中文质量不达用户预期 | 中 | 默认链文档化推荐 PaddleOCR;VLM 补充;设置页引导安装中文语言包 | +| 无 Apple Translation 对位造成"无默认可用引擎" | 中 | 首启引导第 3 步强制选默认链(MTranServer/云引擎/Ollama 外部接入,不内置模型,决策 1) | +| UIA 在旧 Win32 应用上 TextPattern 缺失 | 中 | 剪贴板回退 + 回退开关;目标应用矩阵持续维护 | +| WGC 黄边框(Win10)观感差 | 低 | 文档明示 Win11 体验最佳;Win10 保留边框并提示 | +| MSIX 签名与 SmartScreen 信誉 | 中 | Azure Trusted Signing 起步;发布说明引导 | +| 120Hz 笔迹延迟不达标 | 低 | DComp 独立层 + 预渲染笔迹缓存;预算 8ms 有 50% 余量 | +| arm64 设备驱动级 API 差异 | 低 | 双架构 CI 全量测试;WGC/D2D 均有 arm64 原生支持 | + +--- + +## 13. 开放问题(Open Questions) + +1. ~~LocalTranslate(ONNX+DirectML)进 1.x 的验收标准~~ → **已裁决:不内置任何模型**,本地能力仅做外部引擎接入(决策 1)。 +2. ~~历史库是否启用 FTS5~~ → **已裁决:不启用,维持 LIKE**(决策 2)。 +3. ~~便携版(portable zip)是否进 1.0~~ → **已裁决:仅 MSIX**(决策 3)。 +4. ~~取色器是否扩展为独立取色历史窗口~~ → **已裁决:扩展为独立窗口,两平台同步交付**(决策 4,规格见 `docs/specs/color-history-window.md`)。 + +--- + +## 附录 A:默认快捷键(Windows) + +| 动作 | 默认 | macOS 对照 | +|------|------|-----------| +| 区域截图 | Ctrl+Alt+A | Cmd+Shift+4 | +| 全屏截图 | Ctrl+Alt+F | Cmd+Shift+3 | +| 翻译模式 | Ctrl+Alt+T | Cmd+Shift+T | +| 划词翻译 | Ctrl+Alt+D | Cmd+Shift+Y | +| 翻译并插入 | Ctrl+Alt+I | Cmd+Shift+I | + +## 附录 B:目录结构(目标态) + +``` +windows/ +├── TransFrame.sln +├── Core/ # TransFrame.Core(模型+纯算法,平台无关) +├── NativeShell/ # Win32/D2D/WGC/热键/托盘/UIA 静态库 +├── App/ # WinUI 3 应用(C++/WinRT) +├── Tests/ # Catch2 单测 + 跨平台快照 + perf 基准 +├── Installer/ # MSIX 打包 + .appinstaller + 签名 +└── docs/ # 平台补充文档 +``` + +## 附录 C:验收快照(发布前勾选) + +- [ ] §2 基线表 P0/P1 全绿(差异仅 §6.12 列出项) +- [ ] §8 性能预算全达标(CI 报告链接) +- [ ] 双架构 + 双 OS(Win11/Win10 降级)冒烟通过 +- [ ] 10 语言截图审校(en/zh-Hans/ja/de 抽查全量,其余 3 页关键屏) +- [ ] 无障碍清单(键盘全路径 + 对比度 + UIA 检查器验证) +- [ ] 隐私面板内容与实际网络行为一致(抓包审计) diff --git a/windows/App/App.rc b/windows/App/App.rc new file mode 100644 index 0000000..3c9b9fb --- /dev/null +++ b/windows/App/App.rc @@ -0,0 +1,2 @@ +#include +101 ICON "Assets/TransFrame.ico" diff --git a/windows/App/AppMain.cpp b/windows/App/AppMain.cpp new file mode 100644 index 0000000..4ff4b47 --- /dev/null +++ b/windows/App/AppMain.cpp @@ -0,0 +1,604 @@ +// AppMain.cpp — TransFrame Windows app entry (screenshot-translate flow v1). +// +// Wires the merged modules into the real user flow: +// tray icon (FR-34) + global hotkeys (FR-33) + selection overlay (FR-01/02) +// + capture chain (WGC→GDI, PRD §3.2) + Windows OCR (FR-15) +// + MTranServer translation (default engine, localhost:8989) +// + result popup (source + translation + copy). +// +// Region flow (Ctrl+Alt+A / tray 区域截图): +// overlay session -> region -> capture -> OCR -> merge visual lines +// -> translate -> result popup near the region. +// Full-screen flow (Ctrl+Alt+F): primary display capture, same pipeline. +// 划词 (Ctrl+Alt+D): UIA/clipboard selection text -> translate -> popup. +// 翻译并插入 (Ctrl+Alt+I): 划词 -> translate -> re-validate -> paste. +// Esc during overlay cancels; tray menu Exit quits. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#include "UpdateService.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// NativeShell (capture shell + Win32 plumbing) +#include "tf/CaptureService.hpp" +#include "tf/CoreTypes.hpp" +#include "tf/DisplayMonitor.hpp" +#include "tf/HotkeyManager.hpp" +#include "tf/NativeShellInit.hpp" +#include "tf/OcrEngines.hpp" +#include "tf/ResultWindow.hpp" +#include "tf/SelectionOverlay.hpp" +#include "tf/TextSelectionInsertion.hpp" +#include "tf/TrayIcon.hpp" +#include "tf/Win32OcrUiaHosts.h" + +// Core (translation services) +#include "tf/CoreModels.hpp" +#include "tf/MTranServerProvider.hpp" +#include "tf/TranslationProvider.hpp" +#include "tf/TranslationScheduler.hpp" +#include "tf/VisualLineGrouping.hpp" +#include "tf/WinHttpTransport.h" + +namespace { + +// --------------------------------------------------------------------------- +// App-level constants +// --------------------------------------------------------------------------- +constexpr wchar_t kHiddenWndClass[] = L"TransFrameMainWnd"; +constexpr UINT kAppQuit = WM_APP + 0x100; +const UINT kTaskbarCreated = ::RegisterWindowMessageW(L"TaskbarCreated"); + +// Default target language (PRD default: auto → zh). Settings UI lands later; +// env override: TRANSFRAME_TARGET_LANG=ja etc. +std::wstring g_targetLang = L"zh"; + +struct AppState { + HINSTANCE instance = nullptr; + HWND hwnd = nullptr; + + // Shell services (main thread only). + std::unique_ptr capture; + std::unique_ptr displays; + std::unique_ptr windowDetector; + std::unique_ptr hotkeys; + std::unique_ptr overlay; + std::unique_ptr results; + std::unique_ptr tray; + + // Translation stack. + std::shared_ptr transport; + std::unique_ptr mtran; + std::unique_ptr scheduler; + + // OCR engine + Win32 text-selection host. + std::unique_ptr ocr; + std::unique_ptr textHost; + + std::atomic pipelineBusy{false}; + // Watchdog anchor (steady-clock ms) for when pipelineBusy was armed. If + // a worker dies inside a system call (unresponsive clipboard owner etc.) + // and never clears the flag, dispatch re-arms after kPipelineStuckSeconds + // so hotkeys stay usable instead of locking up forever. + std::atomic pipelineBusySinceMs{0}; +}; + +constexpr int kPipelineStuckSeconds = 15; + +AppState g; + +// --------------------------------------------------------------------------- +// UTF-8 <-> UTF-16 helpers +// --------------------------------------------------------------------------- +std::string toUtf8(const std::wstring& wide) { + if (wide.empty()) return {}; + const int len = ::WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, nullptr, 0, + nullptr, nullptr); + std::string out(static_cast(len), '\0'); + ::WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, out.data(), len, nullptr, + nullptr); + out.resize(out.size() - 1); + return out; +} + +std::wstring toWide(const std::string& utf8) { + if (utf8.empty()) return {}; + const int len = ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, nullptr, 0); + std::wstring out(static_cast(len), L'\0'); + ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, out.data(), len); + out.resize(out.size() - 1); + return out; +} + +// --------------------------------------------------------------------------- +// Translation pipeline (worker thread; UI updates post back to the main thread) +// --------------------------------------------------------------------------- + +constexpr UINT kShowResult = WM_APP + 0x101; + +/// Posts content to the main thread; ownership via a small heap box. +struct ResultBox { + tf::ResultWindowContent content; +}; + +/// Show the result popup from any thread (main-thread hop for HWND safety). +void showResultOnMain(const tf::ResultWindowContent& c) { + auto* box = new ResultBox{c}; + if (!::PostMessageW(g.hwnd, kShowResult, 0, reinterpret_cast(box))) { + delete box; // window gone (shutdown) + } +} + +std::string translateTexts(const std::vector& texts) { + tf::ChainRequest req; + req.chain.push_back(tf::EngineChainItem::makeBuiltin(tf::TranslationEngineType::MtranServer)); + req.texts = texts; + req.sourceLanguage = ""; // auto-detect (MTranServer default) + req.targetLanguage = toUtf8(g_targetLang); + req.scene = tf::TranslationScene::Screenshot; + + const tf::SchedulerOutcome out = g.scheduler->translateOrdered(req); + if (out.isSuccess()) { + const auto& results = out.bundle->results; + // First engine's joined translation. + std::string joined; + for (const auto& seg : results.front().segments) { + if (!joined.empty()) joined += "\n"; + joined += seg.translated; + } + return joined; + } + std::string err = "所有引擎失败"; + for (const auto& f : out.failures) { + err += "\n" + f.displayName + ": " + f.errorText; + } + return err; +} + +/// Screenshot flow: pixels -> OCR -> line merge -> translate -> result popup. +/// Runs on a worker thread (OCR + HTTP block); the popup shows via PostMessage. +void runScreenshotPipeline(const tf::CaptureResult& cap) { + if (!cap.ok) { + tf::ResultWindowContent c; + c.translatedText = L"截图失败: " + cap.error; + c.statusLine = L"Capture: failed"; + c.anchorPhysical = cap.screenshot.sourceDisplay.framePhysical; + showResultOnMain(c); + return; + } + + const auto t0 = std::chrono::steady_clock::now(); + + // PixelBuffer (BGRA8) -> OcrImage. + tf::OcrImage img; + img.width = cap.screenshot.pixels.width; + img.height = cap.screenshot.pixels.height; + img.bgra.assign(cap.screenshot.pixels.data.get(), + cap.screenshot.pixels.data.get() + cap.screenshot.pixels.byteSize()); + + auto ocrOutcome = g.ocr->recognize(img); + const auto tOcr = std::chrono::steady_clock::now(); + + if (!ocrOutcome.isOk()) { + tf::ResultWindowContent c; + c.translatedText = L"OCR 失败: " + toWide(ocrOutcome.error.message); + c.statusLine = L"OCR failed · engine=" + toWide(g.ocr->name()); + c.anchorPhysical = cap.screenshot.sourceDisplay.framePhysical; + showResultOnMain(c); + return; + } + + // Merge visual lines before translation (Swift parity). + std::vector merged = + tf::VisualLineGrouping::mergeLines(ocrOutcome.value.observations); + std::vector texts; + texts.reserve(merged.size()); + for (const auto& seg : merged) texts.push_back(seg.text); + + std::string translated; + std::string errorNote; + if (!texts.empty()) { + translated = translateTexts(texts); + if (translated.rfind("所有引擎失败", 0) == 0) { + errorNote = translated; + translated.clear(); + } + } else { + translated = "(未识别到文字)"; + } + const auto tEnd = std::chrono::steady_clock::now(); + + tf::ResultWindowContent c; + std::string full; + for (const auto& seg : ocrOutcome.value.observations) { + if (!full.empty()) full += "\n"; + full += seg.text; + } + c.sourceText = toWide(full); + c.translatedText = errorNote.empty() ? toWide(translated) : toWide(errorNote); + c.engineLabel = L"MTransServer"; + const auto ms = [](auto a, auto b) { + return std::chrono::duration_cast(b - a).count(); + }; + c.statusLine = L"OCR " + std::to_wstring(ms(t0, tOcr)) + L"ms · 翻译 " + + std::to_wstring(ms(tOcr, tEnd)) + L"ms · " + c.engineLabel; + c.anchorPhysical = cap.screenshot.sourceDisplay.framePhysical; + showResultOnMain(c); +} + +/// Region flow entry (overlay confirmed): capture region -> pipeline. +/// Called on the main thread; capture is fast (GDI/WGC sync); the heavy +/// OCR + translate stages run on a worker thread. +void onRegionConfirmed(const tf::SelectionOverlayResult& result) { + if (!result.confirmed) { + g.pipelineBusy = false; // Esc / focus loss + return; + } + + const std::optional display = + g.displays->displayAt(tf::Point{result.regionPhysical.x, result.regionPhysical.y}); + if (!display) { + tf::ResultWindowContent c; + c.translatedText = L"无法定位该区域所在的显示器"; + showResultOnMain(c); + g.pipelineBusy = false; + return; + } + + tf::CaptureResult cap = g.capture->captureRegion( + result.regionPhysical, *display, + result.wholeWindow ? tf::CaptureTrigger::WindowClick + : tf::CaptureTrigger::ManualRegion); + + if (cap.ok) { + // Anchor the popup to the captured region (not the whole display). + cap.screenshot.sourceDisplay.framePhysical = result.regionPhysical; + } + std::thread([cap = std::move(cap)]() mutable { + runScreenshotPipeline(cap); + g.pipelineBusy = false; + }).detach(); +} + +/// Full-screen flow entry: primary display capture -> pipeline. +void onFullScreen() { + const auto displays = g.displays->displays(); + const auto primary = std::find_if(displays.begin(), displays.end(), + [](const tf::DisplayInfo& d) { return d.isPrimary; }); + if (primary == displays.end()) { + tf::ResultWindowContent c; + c.translatedText = L"未找到主显示器"; + showResultOnMain(c); + g.pipelineBusy = false; + return; + } + tf::CaptureResult cap = + g.capture->captureDisplay(*primary, tf::CaptureTrigger::HotkeyFullScreen); + std::thread([cap = std::move(cap)]() mutable { + runScreenshotPipeline(cap); + g.pipelineBusy = false; + }).detach(); +} + +// --------------------------------------------------------------------------- +// 划词 / 翻译并插入 flows (UIA + clipboard fallback) +// --------------------------------------------------------------------------- + +void runTextSelectionFlow(bool insertMode) { + // Shell-foreground guard: on the desktop / shell UI, Ctrl+C copies FILES + // (not text) and the shell's clipboard-owner path is the exact + // synchronous surface that can freeze the taskbar when disturbed while + // the shell is busy. Refuse early with a clear message instead. + static const char* const kShellForeground[] = { + "explorer.exe", + "startmenuexperiencehost.exe", + "searchhost.exe", + "shellexperiencehost.exe", + "textinputhost.exe", + "dwm.exe", + }; + const std::string fgProcess = g.textHost->foregroundProcessName(); + for (const char* shell : kShellForeground) { + if (_stricmp(fgProcess.c_str(), shell) == 0) { + tf::ResultWindowContent c; + c.translatedText = L"前台是桌面/系统界面:请在可选择文本的应用中使用划词翻译"; + c.statusLine = L"Text selection: shell foreground refused"; + c.anchorPhysical = tf::Rect{200, 200, 400, 100}; + showResultOnMain(c); + return; + } + } + + tf::TextExtractor extractor(*g.textHost, /*allowClipboardFallback=*/true); + + const tf::ExtractionOutcome extraction = extractor.captureSelectedText(insertMode); + if (!extraction.selection) { + tf::ResultWindowContent c; + c.translatedText = L"未获取到选中文本"; + c.statusLine = L"划词失败"; + c.anchorPhysical = tf::Rect{200, 200, 400, 100}; + showResultOnMain(c); + return; + } + + const std::string src = extraction.selection->text; + if (src.empty()) { + tf::ResultWindowContent c; + c.translatedText = L"选中文本为空"; + showResultOnMain(c); + return; + } + + if (insertMode) { + // Translate then re-validate the target before pasting (FR-29). + const std::string translated = translateTexts({src}); + if (translated.rfind("所有引擎失败", 0) == 0) { + tf::ResultWindowContent c; + c.translatedText = toWide(translated); + showResultOnMain(c); + return; + } + tf::InsertionService inserter(*g.textHost); + tf::InsertRequest req; + req.translatedText = translated; + req.capturedSelection = *extraction.selection; + std::string err; + const tf::InsertionOutcome oc = inserter.insert(req, err); + if (oc != tf::InsertionOutcome::Completed) { + tf::ResultWindowContent c; + c.translatedText = L"插入中止: " + toWide(err); + c.statusLine = L"目标已变化,未粘贴"; + showResultOnMain(c); + } + return; + } + + const std::string translated = translateTexts({src}); + tf::ResultWindowContent c; + c.sourceText = toWide(src); + c.translatedText = toWide(translated); + c.statusLine = insertMode ? L"翻译并插入" : L"划词翻译"; + c.anchorPhysical = tf::Rect{200, 200, 400, 100}; + showResultOnMain(c); +} + +// --------------------------------------------------------------------------- +// Action dispatch (hotkey + tray) +// --------------------------------------------------------------------------- + +/// True when the pipeline may start: not busy, or busy for longer than the +/// watchdog window (a previous worker never returned from a system call — +/// treat it as dead and re-arm so hotkeys keep working). +bool tryBeginPipeline() { + const std::int64_t nowMs = + std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); + if (!g.pipelineBusy.exchange(true)) { + g.pipelineBusySinceMs.store(nowMs); + return true; + } + const std::int64_t since = g.pipelineBusySinceMs.load(); + if (since != 0 && nowMs - since > kPipelineStuckSeconds * 1000) { + g.pipelineBusySinceMs.store(nowMs); // re-arm over the stuck worker + return true; + } + return false; +} + +void startRegionCapture() { + if (!tryBeginPipeline()) return; + const bool began = g.overlay->beginSession([](tf::SelectionOverlayResult result) { + // Runs on the main thread (overlay pumps our message loop). + onRegionConfirmed(result); + }); + if (!began) g.pipelineBusy = false; +} + +void dispatchAction(tf::HotkeyAction action) { + switch (action) { + case tf::HotkeyAction::FullScreen: + if (tryBeginPipeline()) { + onFullScreen(); + // worker thread clears pipelineBusy when done + } + break; + case tf::HotkeyAction::Region: + case tf::HotkeyAction::Translate: + startRegionCapture(); + break; + case tf::HotkeyAction::TextSelection: + case tf::HotkeyAction::TranslateInsert: + if (tryBeginPipeline()) { + const bool insert = action == tf::HotkeyAction::TranslateInsert; + std::thread([insert] { + runTextSelectionFlow(insert); + g.pipelineBusy = false; + }).detach(); + } + break; + default: + break; + } +} + +void onTrayCommand(tf::TrayCommand command, int /*recentIndex*/) { + switch (command) { + case tf::TrayCommand::FullScreen: dispatchAction(tf::HotkeyAction::FullScreen); break; + case tf::TrayCommand::Region: dispatchAction(tf::HotkeyAction::Region); break; + case tf::TrayCommand::Translate: dispatchAction(tf::HotkeyAction::Translate); break; + case tf::TrayCommand::TextSelection: dispatchAction(tf::HotkeyAction::TextSelection); break; + case tf::TrayCommand::TranslateInsert: dispatchAction(tf::HotkeyAction::TranslateInsert); break; + case tf::TrayCommand::CheckUpdates: + tf::checkForAppUpdate(g.hwnd); + break; + case tf::TrayCommand::Exit: + ::PostMessageW(g.hwnd, kAppQuit, 0, 0); + break; + case tf::TrayCommand::RecentShot: + // Recent-shots history view lands with task D (history store). + break; + default: + break; // placeholders (settings etc.) — later milestones + } +} + +// --------------------------------------------------------------------------- +// Hidden main window: tray messages + hotkey pump target +// --------------------------------------------------------------------------- + +LRESULT CALLBACK mainWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { + if (kTaskbarCreated != 0 && msg == kTaskbarCreated && g.tray) { + g.tray->remove(); + if (!g.tray->install()) { + ::OutputDebugStringW(L"TransFrame: failed to restore tray icon after Explorer restart\n"); + } + return 0; + } + switch (msg) { + case kShowResult: { + auto* box = reinterpret_cast(lp); + if (box && g.results) g.results->show(box->content); + delete box; + return 0; + } + case WM_APP + 0x5446: // tray callback ('TF' — matches TrayIcon.cpp) + if (lp == WM_LBUTTONUP || lp == WM_RBUTTONUP || lp == WM_CONTEXTMENU) { + g.tray->showMenuAtCursor(); + } + return 0; + case WM_DISPLAYCHANGE: + if (g.displays) g.displays->invalidate(); + return 0; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + default: + return ::DefWindowProcW(hwnd, msg, wp, lp); + } +} + +} // namespace + +// --------------------------------------------------------------------------- +// Entry +// --------------------------------------------------------------------------- + +int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int) { + g.instance = instance; + + // Hidden top-level window (popup owner + Explorer restart broadcasts). RegisterHotKey + // with nullptr hwnd posts WM_HOTKEY to the registering thread's queue — + // pumping here covers both. + WNDCLASSEXW wc{}; + wc.cbSize = sizeof(wc); + wc.lpfnWndProc = mainWndProc; + wc.hInstance = instance; + wc.lpszClassName = kHiddenWndClass; + wc.hIcon = ::LoadIconW(instance, MAKEINTRESOURCEW(101)); + wc.hIconSm = wc.hIcon; + if (!::RegisterClassExW(&wc)) return 1; + + g.hwnd = ::CreateWindowExW(0, kHiddenWndClass, L"TransFrame", WS_OVERLAPPEDWINDOW, + 0, 0, 0, 0, nullptr, nullptr, instance, nullptr); + if (!g.hwnd) return 1; + + // Composition root (NativeShellInit.cpp factories). + g.capture = tf::makeCaptureService(); + g.displays = tf::makeDisplayMonitorService(); + g.windowDetector = tf::makeWindowDetectorService(GetCurrentProcessId()); + g.hotkeys = tf::makeHotkeyManager(); + g.overlay = std::make_unique(); + g.overlay->setWindowDetector(g.windowDetector.get()); + g.results = std::make_unique(); + g.ocr = tf::makeWindowsOcrEngine(); + g.textHost = std::make_unique(); + + // Translation stack: WinHTTP transport + MTranServer (default engine). + // Endpoint override: TRANSFRAME_MTRAN_URL=http://host:port. + g.transport = std::make_shared(); + std::string mtranUrl = "http://localhost:8989"; + if (const DWORD cap = ::GetEnvironmentVariableA("TRANSFRAME_MTRAN_URL", nullptr, 0); + cap > 0) { + std::string buf(cap, '\0'); + const DWORD n = ::GetEnvironmentVariableA("TRANSFRAME_MTRAN_URL", buf.data(), cap); + if (n > 0 && n < cap) mtranUrl = buf.substr(0, n); + } + auto mtranConfig = tf::MTranServerProvider::Configuration::parse(mtranUrl); + if (!mtranConfig) mtranConfig = tf::MTranServerProvider::Configuration::makeDefault(); + g.mtran = std::make_unique(*mtranConfig, g.transport); + + tf::SchedulerDependencies deps; + deps.builtinProvider = [](tf::TranslationEngineType t) + -> tf::TranslationProviderPtr { + if (t == tf::TranslationEngineType::MtranServer && g.mtran) { + // Fresh provider instance per run sharing the WinHTTP session. + return std::make_unique(g.mtran->configuration(), + g.transport); + } + return nullptr; + }; + deps.compatibleProvider = [](const std::string&) -> tf::TranslationProviderPtr { + return nullptr; + }; + deps.compatibleConfigs = [] { return std::vector{}; }; + deps.promptResolver = [](tf::TranslationEngineType, tf::TranslationScene, + const std::string&) { return std::string(); }; + g.scheduler = std::make_unique(std::move(deps)); + + if (wchar_t buf[16]{}; ::GetEnvironmentVariableW(L"TRANSFRAME_TARGET_LANG", buf, 16)) { + g_targetLang = buf; + } + + // Tray icon (FR-34): callbacks route to the hidden message window. + g.tray = std::make_unique(onTrayCommand); + g.tray->setCallbackWindow(g.hwnd); + if (!g.tray->install()) { + // Tray is best-effort in v1: hotkeys keep working without it. + } + + // Hotkeys (FR-33): Ctrl+Alt+F/A/T/D/I defaults. Registration conflicts + // (another app owns the combo) surface in the settings UI later. + g.hotkeys->setHandler([](tf::HotkeyAction action) { dispatchAction(action); }); + (void)g.hotkeys->applySpecs(tf::defaultHotkeySpecs()); + + // Pre-create the overlay window + D2D/DComp stack (<= 60ms hotkey path). + if (!g.overlay->precreate()) { + // Region capture needs the overlay; full-screen/划词 still work. + } + + // Main loop. WM_HOTKEY arrives as a THREAD message (RegisterHotKey with + // hwnd=nullptr), so it is dispatched here rather than in a wndProc. + MSG msg{}; + while (::GetMessageW(&msg, nullptr, 0, 0) > 0) { + if (msg.hwnd == nullptr && msg.message == WM_HOTKEY) { + if (g.hotkeys) g.hotkeys->dispatchWmHotkey(static_cast(msg.wParam)); + continue; + } + if (msg.message == kAppQuit) { + ::DestroyWindow(g.hwnd); + break; + } + ::TranslateMessage(&msg); + ::DispatchMessageW(&msg); + } + + // Teardown. + g.hotkeys->unregisterAll(); + g.tray->remove(); + return static_cast(msg.wParam); +} diff --git a/windows/App/Assets/Square150x150Logo.png b/windows/App/Assets/Square150x150Logo.png new file mode 100644 index 0000000..55369d6 Binary files /dev/null and b/windows/App/Assets/Square150x150Logo.png differ diff --git a/windows/App/Assets/Square44x44Logo.png b/windows/App/Assets/Square44x44Logo.png new file mode 100644 index 0000000..4db07da Binary files /dev/null and b/windows/App/Assets/Square44x44Logo.png differ diff --git a/windows/App/Assets/StoreLogo.png b/windows/App/Assets/StoreLogo.png new file mode 100644 index 0000000..a285f62 Binary files /dev/null and b/windows/App/Assets/StoreLogo.png differ diff --git a/windows/App/Assets/TransFrame.ico b/windows/App/Assets/TransFrame.ico new file mode 100644 index 0000000..5d95407 Binary files /dev/null and b/windows/App/Assets/TransFrame.ico differ diff --git a/windows/App/Package.appxmanifest b/windows/App/Package.appxmanifest new file mode 100644 index 0000000..d6a8416 --- /dev/null +++ b/windows/App/Package.appxmanifest @@ -0,0 +1,58 @@ + + + + + + + + TransFrame + TransFrame Team + Assets\StoreLogo.png + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/windows/App/TransFrame.App.vcxproj b/windows/App/TransFrame.App.vcxproj new file mode 100644 index 0000000..fd07ee5 --- /dev/null +++ b/windows/App/TransFrame.App.vcxproj @@ -0,0 +1,93 @@ + + + + + + Debugx64 + + + Releasex64 + + + DebugARM64 + + + ReleaseARM64 + + + + + {A0000000-0000-0000-0000-00000000000C} + Win32Proj + TransFrame + 10.0.26100.0 + false + + + + + + Application + true + $(DefaultPlatformToolset) + Unicode + + + + + + $(SolutionDir)build\$(Platform)\$(Configuration)\$(ProjectName)\ + $(SolutionDir)build\obj\$(Platform)\$(Configuration)\$(ProjectName)\ + $(ProjectDir);$(ProjectDir)..\Core;$(ProjectDir)..\Core\include;$(ProjectDir)..\NativeShell\include;$(ProjectDir)..\external;$(IncludePath) + + + + + stdcpp20 + Level4 + true + true + Sync + /utf-8 %(AdditionalOptions) + _UNICODE;UNICODE;_WIN32;%(PreprocessorDefinitions) + MultiThreadedDebugDLL + MultiThreadedDLL + + + Windows + true + windowsapp.lib;shell32.lib;%(AdditionalDependencies) + + + + + + + + + + + + {A0000000-0000-0000-0000-00000000000A} + + + {A0000000-0000-0000-0000-00000000000B} + + + + + + + diff --git a/windows/App/TransFrame.Package.wapproj b/windows/App/TransFrame.Package.wapproj new file mode 100644 index 0000000..34ccdfe --- /dev/null +++ b/windows/App/TransFrame.Package.wapproj @@ -0,0 +1,43 @@ + + + + + {A0000000-0000-0000-0000-00000000000E} + Package + $(SolutionDir)build\msix\ + x64|ARM64 + en-US + + + + + Debugx64 + + + Releasex64 + + + DebugARM64 + + + ReleaseARM64 + + + + + + Designer + + + + + + {A0000000-0000-0000-0000-00000000000C} + + + + + diff --git a/windows/App/UpdateService.cpp b/windows/App/UpdateService.cpp new file mode 100644 index 0000000..92f1a75 --- /dev/null +++ b/windows/App/UpdateService.cpp @@ -0,0 +1,82 @@ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include "UpdateService.hpp" + +namespace tf { +namespace { +std::atomic checking{false}; + +winrt::fire_and_forget checkInstalledFeed() { + // No application objects are captured: quitting while the request is in + // flight cannot dereference a destroyed AppState or hidden window. + co_await winrt::resume_background(); + struct Reset { ~Reset() { checking = false; } } reset; + try { + using namespace winrt::Windows::ApplicationModel; + const auto package = Package::Current(); + const auto installer = package.GetAppInstallerInfo(); + if (!installer) { + ::MessageBoxW(nullptr, L"此安装未关联自动更新源。请通过发布页提供的 .appinstaller 文件安装,以启用自动更新。", + L"TransFrame 更新", MB_OK | MB_ICONINFORMATION); + co_return; + } + const auto result = co_await package.CheckUpdateAvailabilityAsync(); + switch (result.Availability()) { + case PackageUpdateAvailability::Available: + case PackageUpdateAvailability::Required: + if (::MessageBoxW(nullptr, L"发现新版本。现在打开 Windows 应用安装程序更新?", + L"TransFrame 更新", MB_YESNO | MB_ICONINFORMATION) == IDYES) { + const auto source = installer.Uri(); + if (source.SchemeName() != L"https") { + throw winrt::hresult_error(E_INVALIDARG, L"更新源必须使用 HTTPS。"); + } + const std::wstring uri = L"ms-appinstaller:?source=" + + std::wstring(winrt::Windows::Foundation::Uri::EscapeComponent(source.AbsoluteUri())); + const auto launched = ::ShellExecuteW(nullptr, L"open", uri.c_str(), nullptr, nullptr, SW_SHOWNORMAL); + if (reinterpret_cast(launched) <= 32) { + throw winrt::hresult_error(E_FAIL, L"无法打开 Windows 应用安装程序,请检查是否已安装 App Installer。"); + } + } + break; + case PackageUpdateAvailability::NoUpdates: + ::MessageBoxW(nullptr, L"当前已是最新版本。", L"TransFrame 更新", MB_OK | MB_ICONINFORMATION); + break; + case PackageUpdateAvailability::Error: + throw winrt::hresult_error(result.ExtendedError()); + default: + ::MessageBoxW(nullptr, L"暂时无法确认更新,请检查网络后重试。", L"TransFrame 更新", MB_OK | MB_ICONWARNING); + break; + } + } catch (const winrt::hresult_error& error) { + const std::wstring message = L"检查更新失败:" + std::wstring(error.message()); + ::MessageBoxW(nullptr, message.c_str(), L"TransFrame 更新", MB_OK | MB_ICONWARNING); + } catch (const std::exception&) { + ::MessageBoxW(nullptr, L"检查更新失败,请稍后重试。", L"TransFrame 更新", MB_OK | MB_ICONWARNING); + } +} +} + +void checkForAppUpdate(void* owner) { + UINT32 length = 0; + if (::GetCurrentPackageFullName(&length, nullptr) == APPMODEL_ERROR_NO_PACKAGE) { + ::MessageBoxW(static_cast(owner), + L"当前为免安装版。自动更新需要通过发布页的 .appinstaller 文件安装 MSIX 版本。", + L"TransFrame 更新", MB_OK | MB_ICONINFORMATION); + return; + } + if (checking.exchange(true)) return; + checkInstalledFeed(); +} +} diff --git a/windows/App/UpdateService.hpp b/windows/App/UpdateService.hpp new file mode 100644 index 0000000..316f160 --- /dev/null +++ b/windows/App/UpdateService.hpp @@ -0,0 +1,6 @@ +#pragma once +namespace tf { +// Check the installed App Installer feed off the UI thread. Unpackaged builds +// explain how to enable updates; Windows owns background update installation. +void checkForAppUpdate(void* owner); +} diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..32098ec --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,76 @@ +# Translation services (Task C) — Core unit tests, portable. +# Core is platform-clean (no Win32/WinRT); this project builds the Catch2 +# test runner on any OS. NativeShell (Win32/WinRT TUs) is built only on +# Windows via the WIN32 gate below (compile + link into a smoke target). +cmake_minimum_required(VERSION 3.20) +project(TransFrameTranslation CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# --------------------------------------------------------------------------- +# Core portable sources + Catch2 tests +# --------------------------------------------------------------------------- +file(GLOB CORE_SRC CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Core/src/*.cpp) +set(TEST_SRC + Tests/TranslationSchedulerTests.cpp + Tests/ProvidersTests.cpp + Tests/LLMTranslationCoreTests.cpp + Tests/EngineHealthCheckerTests.cpp + Tests/OcrAndTextSelectionTests.cpp +) + +add_executable(translation_tests + ${CORE_SRC} + ${TEST_SRC} + Tests/vendor/catch_amalgamated.cpp +) +target_include_directories(translation_tests PRIVATE + Core/include + Core/vendor + Tests + Tests/vendor +) + +if (MSVC) + target_compile_options(translation_tests PRIVATE /W4 /permissive- /utf-8 /EHsc) + # Amalgamated Catch2 + /W4 is noisy; tests are not /WX. + target_compile_options(translation_tests PRIVATE /wd4996 /wd26819 /wd5054) +else() + target_compile_options(translation_tests PRIVATE -Wall -Wextra) + # {status, body} brace-init against a 4-field struct with defaults is + # intentional in tests; GCC's -Wmissing-field-initializers disagrees. + target_compile_options(translation_tests PRIVATE -Wno-missing-field-initializers) +endif() + +enable_testing() +add_test(NAME translation_tests COMMAND translation_tests) + +# --------------------------------------------------------------------------- +# NativeShell (Win32/WinRT TUs) — Windows only. Compile + link a smoke +# binary to prove the sources build under MSVC; running needs a GUI +# session (see windows/README.md manual smoke). +# --------------------------------------------------------------------------- +if (WIN32) + set(NS_SRC + NativeShell/src/WinHttpTransport.cpp + NativeShell/src/CredManKeyStore.cpp + NativeShell/src/Win32OcrUiaHosts.cpp + ) + # Smoke links Core sources too (per windows/README.md manual command). + add_executable(nativeshell_smoke + ${CORE_SRC} + ${NS_SRC} + Tests/manual/smoke_translation.cpp + ) + target_include_directories(nativeshell_smoke PRIVATE + Core/include + Core/vendor + NativeShell/include + ) + if (MSVC) + target_compile_options(nativeshell_smoke PRIVATE /W4 /permissive- /utf-8 /EHsc) + endif() + target_link_libraries(nativeshell_smoke PRIVATE winhttp credui advapi32 user32 ole32) +endif() diff --git a/windows/Core/Annotation.cpp b/windows/Core/Annotation.cpp new file mode 100644 index 0000000..62b3338 --- /dev/null +++ b/windows/Core/Annotation.cpp @@ -0,0 +1,187 @@ +// Annotation.cpp — JSON codecs for the 11 annotation payloads. +#include "Annotation.h" + +#include + +namespace tf::core { + +namespace { + +/// decodes an optional member; missing/null -> nullopt (Swift decodeIfPresent). +template +std::optional opt(const Json& j, const char* key) { + return getOptional(j, key); +} + +} // namespace + +// ---------------------------------------------------------------- rectangle -- +void to_json(Json& j, const RectangleAnnotation& a) { + j = Json{{"id", a.id}, {"rect", a.rect}, {"style", a.style}, + {"isFilled", a.isFilled}}; + j["fillColor"] = a.fillColor ? Json(*a.fillColor) : Json(); +} +void from_json(const Json& j, RectangleAnnotation& a) { + a.id = j.at("id").get(); + a.rect = j.at("rect").get(); + a.style = j.at("style").get(); + a.isFilled = getOptionalOr(j, "isFilled", false); + a.fillColor = opt(j, "fillColor"); +} + +// ---------------------------------------------------------------- freehand -- +void to_json(Json& j, const FreehandAnnotation& a) { + j = Json{{"id", a.id}, {"points", a.points}, {"style", a.style}}; +} +void from_json(const Json& j, FreehandAnnotation& a) { + a.id = j.at("id").get(); + a.points = j.at("points").get>(); + a.style = j.at("style").get(); +} + +// ------------------------------------------------------------------- arrow -- +void to_json(Json& j, const ArrowAnnotation& a) { + j = Json{{"id", a.id}, {"startPoint", a.startPoint}, {"endPoint", a.endPoint}, + {"style", a.style}}; + j["controlPoint"] = a.controlPoint ? Json(*a.controlPoint) : Json(); +} +void from_json(const Json& j, ArrowAnnotation& a) { + a.id = j.at("id").get(); + a.startPoint = j.at("startPoint").get(); + a.endPoint = j.at("endPoint").get(); + a.style = j.at("style").get(); + a.controlPoint = opt(j, "controlPoint"); +} + +// ------------------------------------------------------------------- text -- +void to_json(Json& j, const TextAnnotation& a) { + j = Json{{"id", a.id}, {"position", a.position}, {"content", a.content}, {"style", a.style}}; + j["wrapWidth"] = a.wrapWidth ? Json(*a.wrapWidth) : Json(); +} +void from_json(const Json& j, TextAnnotation& a) { + a.id = j.at("id").get(); + a.position = j.at("position").get(); + a.content = j.at("content").get(); + a.style = j.at("style").get(); + a.wrapWidth = opt(j, "wrapWidth"); +} + +// ---------------------------------------------------------------- ellipse -- +void to_json(Json& j, const EllipseAnnotation& a) { + j = Json{{"id", a.id}, {"rect", a.rect}, {"style", a.style}, + {"isFilled", a.isFilled}}; + j["fillColor"] = a.fillColor ? Json(*a.fillColor) : Json(); +} +void from_json(const Json& j, EllipseAnnotation& a) { + a.id = j.at("id").get(); + a.rect = j.at("rect").get(); + a.style = j.at("style").get(); + a.isFilled = getOptionalOr(j, "isFilled", false); + a.fillColor = opt(j, "fillColor"); +} + +// ------------------------------------------------------------------- line -- +void to_json(Json& j, const LineAnnotation& a) { + j = Json{{"id", a.id}, {"startPoint", a.startPoint}, {"endPoint", a.endPoint}, + {"style", a.style}}; +} +void from_json(const Json& j, LineAnnotation& a) { + a.id = j.at("id").get(); + a.startPoint = j.at("startPoint").get(); + a.endPoint = j.at("endPoint").get(); + a.style = j.at("style").get(); +} + +// ----------------------------------------------------------------- mosaic -- +void to_json(Json& j, const MosaicAnnotation& a) { + j = Json{{"id", a.id}, {"rect", a.rect}, {"blockSize", a.blockSize}}; +} +void from_json(const Json& j, MosaicAnnotation& a) { + a.id = j.at("id").get(); + a.rect = j.at("rect").get(); + a.blockSize = MosaicAnnotation::clampBlockSize(j.at("blockSize").get()); +} + +// -------------------------------------------------------------- highlight -- +void to_json(Json& j, const HighlightAnnotation& a) { + j = Json{{"id", a.id}, {"rect", a.rect}, {"color", a.color}, {"opacity", a.opacity}}; +} +void from_json(const Json& j, HighlightAnnotation& a) { + a.id = j.at("id").get(); + a.rect = j.at("rect").get(); + a.color = j.at("color").get(); + a.opacity = std::clamp(j.at("opacity").get(), 0.1, 0.8); +} + +// ------------------------------------------------------------ numberLabel -- +void to_json(Json& j, const NumberLabelAnnotation& a) { + j = Json{{"id", a.id}, {"position", a.position}, {"number", a.number}, {"size", a.size}, + {"color", a.color}}; + j["leadPoint"] = a.leadPoint ? Json(*a.leadPoint) : Json(); +} +void from_json(const Json& j, NumberLabelAnnotation& a) { + a.id = j.at("id").get(); + a.position = j.at("position").get(); + a.number = std::max(1, j.at("number").get()); + a.size = NumberLabelAnnotation::clampedSize(j.at("size").get()); + a.color = j.at("color").get(); + a.leadPoint = opt(j, "leadPoint"); +} + +// -------------------------------------------------------- privacyRedaction -- +void to_json(Json& j, const PrivacyRedactionAnnotation& a) { + j = Json{{"id", a.id}, {"rect", a.rect}, {"fillColor", a.fillColor}}; +} +void from_json(const Json& j, PrivacyRedactionAnnotation& a) { + a.id = j.at("id").get(); + a.rect = j.at("rect").get(); + a.fillColor = j.at("fillColor").get(); +} + +// ----------------------------------------------------------- calloutBubble -- +void to_json(Json& j, const CalloutBubbleAnnotation& a) { + j = Json{{"id", a.id}, {"rect", a.rect}, {"targetPoint", a.targetPoint}, + {"text", a.text}, {"style", a.style}, {"bubbleColor", a.bubbleColor}}; +} +void from_json(const Json& j, CalloutBubbleAnnotation& a) { + a.id = j.at("id").get(); + a.rect = j.at("rect").get(); + a.targetPoint = j.at("targetPoint").get(); + a.text = j.at("text").get(); + a.style = j.at("style").get(); + a.bubbleColor = j.at("bubbleColor").get(); +} + +// ---------------------------------------------------------- tagged wrapper -- +std::string annotationTypeName(const Annotation& a) { + // std::variant::index matches declaration order of AnnotationPayload. + static const char* kNames[] = {"rectangle", "freehand", "arrow", "text", + "ellipse", "line", "mosaic", "highlight", + "numberLabel", "privacyRedaction", "calloutBubble"}; + const auto index = a.payload.index(); + return index < std::size(kNames) ? kNames[index] : "rectangle"; +} + +void to_json(Json& j, const Annotation& a) { + j = Json{{"type", annotationTypeName(a)}}; + std::visit([&j](const auto& payload) { j["value"] = payload; }, a.payload); +} + +void from_json(const Json& j, Annotation& a) { + const std::string type = j.at("type").get(); + const Json& value = j.at("value"); + if (type == "rectangle") { a.payload = value.get(); } + else if (type == "freehand") { a.payload = value.get(); } + else if (type == "arrow") { a.payload = value.get(); } + else if (type == "text") { a.payload = value.get(); } + else if (type == "ellipse") { a.payload = value.get(); } + else if (type == "line") { a.payload = value.get(); } + else if (type == "mosaic") { a.payload = value.get(); } + else if (type == "highlight") { a.payload = value.get(); } + else if (type == "numberLabel") { a.payload = value.get(); } + else if (type == "privacyRedaction") { a.payload = value.get(); } + else if (type == "calloutBubble") { a.payload = value.get(); } + else { throw std::invalid_argument("unknown annotation type: " + type); } +} + +} // namespace tf::core diff --git a/windows/Core/Annotation.h b/windows/Core/Annotation.h new file mode 100644 index 0000000..b0c736d --- /dev/null +++ b/windows/Core/Annotation.h @@ -0,0 +1,324 @@ +#pragma once +// Annotation.h — the 11 annotation types (macOS Annotation.swift), one-to-one. +// rectangle / freehand / arrow / text / ellipse / line / mosaic / highlight / +// numberLabel / privacyRedaction / calloutBubble. +// +// Codable notes: Annotation itself is an enum with associated values; on +// macOS it is NOT Codable (persisted documents re-serialize through the +// CaptureDocument layer that stores geometric primitives). We still provide +// a tagged-JSON codec for each concrete payload so task B can persist +// documents; the shape mirrors Swift's synthesized CodingKeys per struct. +// +// All geometry is in image pixel coordinates, top-left origin. + +#include "Geometry.h" +#include "Json.h" +#include "Styles.h" +#include "Uuid.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace tf::core { + +// ---------------------------------------------------------------- payloads --- + +struct RectangleAnnotation { + Uuid id; + Rect rect; + StrokeStyle style; + bool isFilled = false; + /// Fill color when filled; nullopt falls back to stroke color (legacy docs). + std::optional fillColor; + + bool isValid() const { return rect.width >= 5 && rect.height >= 5; } + CodableColor effectiveFillColor() const { return fillColor ? *fillColor : style.color; } + Rect bounds() const { return rect; } + + friend bool operator==(const RectangleAnnotation&, const RectangleAnnotation&) = default; +}; + +struct FreehandAnnotation { + Uuid id; + std::vector points; // minimum 2 + StrokeStyle style; + + bool isValid() const { return points.size() >= 2; } + Rect bounds() const { + if (points.empty()) { return Rect::zero(); } + double minX = HUGE_VAL, minY = HUGE_VAL, maxX = -HUGE_VAL, maxY = -HUGE_VAL; + for (const Point& p : points) { + minX = std::min(minX, p.x); minY = std::min(minY, p.y); + maxX = std::max(maxX, p.x); maxY = std::max(maxY, p.y); + } + return Rect{minX, minY, maxX - minX, maxY - minY}; + } + + friend bool operator==(const FreehandAnnotation&, const FreehandAnnotation&) = default; +}; + +struct ArrowAnnotation { + Uuid id; + Point startPoint; // tail + Point endPoint; // head + std::optional controlPoint; // quadratic curve; nullopt = straight + StrokeStyle style; + + Rect bounds() const { + double minX = std::min(startPoint.x, endPoint.x); + double minY = std::min(startPoint.y, endPoint.y); + double maxX = std::max(startPoint.x, endPoint.x); + double maxY = std::max(startPoint.y, endPoint.y); + if (controlPoint) { + minX = std::min(minX, controlPoint->x); minY = std::min(minY, controlPoint->y); + maxX = std::max(maxX, controlPoint->x); maxY = std::max(maxY, controlPoint->y); + } + const double padding = style.lineWidth * 3; // arrowhead allowance + return Rect{minX - padding, minY - padding, + (maxX - minX) + padding * 2, (maxY - minY) + padding * 2}; + } + + friend bool operator==(const ArrowAnnotation&, const ArrowAnnotation&) = default; +}; + +struct TextAnnotation { + Uuid id; + Point position; // top-leading anchor + std::string content; + TextStyle style; + /// Max width for wrapping; nullopt = single line (Swift wrapWidth). + std::optional wrapWidth; + + bool isValid() const { + // trim whitespace/newlines + std::size_t b = 0, e = content.size(); + while (b < e && std::isspace(static_cast(content[b]))) { ++b; } + while (e > b && std::isspace(static_cast(content[e - 1]))) { --e; } + return b < e; + } + /// Text bounds require font metrics; the Core layer returns the anchor + /// point only — the UI layer measures (Swift caches NSFont measurements). + Rect bounds() const { return Rect{position.x, position.y, 0, 0}; } + + friend bool operator==(const TextAnnotation&, const TextAnnotation&) = default; +}; + +struct EllipseAnnotation { + Uuid id; + Rect rect; + StrokeStyle style; + bool isFilled = false; + std::optional fillColor; + + bool isValid() const { return rect.width >= 5 && rect.height >= 5; } + CodableColor effectiveFillColor() const { return fillColor ? *fillColor : style.color; } + Rect bounds() const { return rect; } + + friend bool operator==(const EllipseAnnotation&, const EllipseAnnotation&) = default; +}; + +struct LineAnnotation { + Uuid id; + Point startPoint; + Point endPoint; + StrokeStyle style; + + bool isValid() const { + const double dx = endPoint.x - startPoint.x; + const double dy = endPoint.y - startPoint.y; + return std::sqrt(dx * dx + dy * dy) >= 5; + } + Rect bounds() const { + const double minX = std::min(startPoint.x, endPoint.x); + const double minY = std::min(startPoint.y, endPoint.y); + const double maxX = std::max(startPoint.x, endPoint.x); + const double maxY = std::max(startPoint.y, endPoint.y); + const double padding = style.lineWidth / 2; + return Rect{minX - padding, minY - padding, + (maxX - minX) + padding * 2, (maxY - minY) + padding * 2}; + } + + friend bool operator==(const LineAnnotation&, const LineAnnotation&) = default; +}; + +struct MosaicAnnotation { + Uuid id; + Rect rect; + int blockSize = 10; // clamped 4...128 (Swift init clamps; doc says 8-32 typical) + + MosaicAnnotation() = default; + MosaicAnnotation(Uuid id_, Rect r, int blockSize_ = 10) + : id(std::move(id_)), rect(r), blockSize(clampBlockSize(blockSize_)) {} + + static int clampBlockSize(int size) { return std::clamp(size, 4, 128); } + bool isValid() const { return rect.width >= 10 && rect.height >= 10; } + Rect bounds() const { return rect; } + + friend bool operator==(const MosaicAnnotation&, const MosaicAnnotation&) = default; +}; + +struct HighlightAnnotation { + Uuid id; + Rect rect; + CodableColor color = CodableColor::yellowColor(); + double opacity = 0.4; // clamped 0.1...0.8 + + HighlightAnnotation() = default; + HighlightAnnotation(Uuid id_, Rect r, CodableColor c = CodableColor::yellowColor(), + double op = 0.4) + : id(std::move(id_)), rect(r), color(c), opacity(std::clamp(op, 0.1, 0.8)) {} + + bool isValid() const { return rect.width >= 5 && rect.height >= 5; } + Rect bounds() const { return rect; } + + friend bool operator==(const HighlightAnnotation&, const HighlightAnnotation&) = default; +}; + +struct NumberLabelAnnotation { + Uuid id; + Point position; // circle center + int number = 1; // >= 1 + double size = 24; // circle diameter, clamped 12...256 + CodableColor color = CodableColor::redColor(); + std::optional leadPoint; + + NumberLabelAnnotation() = default; + NumberLabelAnnotation(Uuid id_, Point pos, int number_ = 1, double size_ = 24, + CodableColor color_ = CodableColor::redColor(), + std::optional lead = std::nullopt) + : id(std::move(id_)), + position(pos), + number(std::max(1, number_)), + size(clampedSize(size_)), + color(color_), + leadPoint(lead) {} + + static double clampedSize(double size) { return std::clamp(size, 12.0, 256.0); } + + Rect circleRect() const { + return Rect{position.x - size / 2, position.y - size / 2, size, size}; + } + Rect bounds() const { + Rect rect = circleRect(); + if (leadPoint) { + rect = rect.unionWith(Rect{leadPoint->x - 4, leadPoint->y - 4, 8, 8}); + } + return rect; + } + + friend bool operator==(const NumberLabelAnnotation&, const NumberLabelAnnotation&) = default; +}; + +struct PrivacyRedactionAnnotation { + Uuid id; + Rect rect; + CodableColor fillColor = CodableColor::blackColor(); + + bool isValid() const { return rect.width >= 5 && rect.height >= 5; } + Rect bounds() const { return rect; } + + friend bool operator==(const PrivacyRedactionAnnotation&, const PrivacyRedactionAnnotation&) = default; +}; + +struct CalloutBubbleAnnotation { + Uuid id; + Rect rect; // bubble box + Point targetPoint; // pointer tip + std::string text; + TextStyle style; + CodableColor bubbleColor = CodableColor::whiteColor(); + + Rect bounds() const { + const double minX = std::min(rect.minX(), targetPoint.x); + const double minY = std::min(rect.minY(), targetPoint.y); + const double maxX = std::max(rect.maxX(), targetPoint.x); + const double maxY = std::max(rect.maxY(), targetPoint.y); + return Rect{minX, minY, maxX - minX, maxY - minY}; + } + + friend bool operator==(const CalloutBubbleAnnotation&, const CalloutBubbleAnnotation&) = default; +}; + +// ------------------------------------------------------------- the variant --- + +/// Annotation mirrors Swift's 11-case enum. std::variant keeps value +/// semantics and exhaustive visiting without heap allocation. +using AnnotationPayload = std::variant; + +struct Annotation { + AnnotationPayload payload; + + Annotation() : payload(RectangleAnnotation{}) {} + + // Tag-based constructors. + static Annotation rectangle(RectangleAnnotation r) { return Annotation{std::move(r)}; } + static Annotation freehand(FreehandAnnotation f) { return Annotation{std::move(f)}; } + static Annotation arrow(ArrowAnnotation a) { return Annotation{std::move(a)}; } + static Annotation text(TextAnnotation t) { return Annotation{std::move(t)}; } + static Annotation ellipse(EllipseAnnotation e) { return Annotation{std::move(e)}; } + static Annotation line(LineAnnotation l) { return Annotation{std::move(l)}; } + static Annotation mosaic(MosaicAnnotation m) { return Annotation{std::move(m)}; } + static Annotation highlight(HighlightAnnotation h) { return Annotation{std::move(h)}; } + static Annotation numberLabel(NumberLabelAnnotation n) { return Annotation{std::move(n)}; } + static Annotation privacyRedaction(PrivacyRedactionAnnotation p) { + return Annotation{std::move(p)}; + } + static Annotation calloutBubble(CalloutBubbleAnnotation c) { return Annotation{std::move(c)}; } + + Uuid id() const { + return std::visit([](const auto& a) -> Uuid { return a.id; }, payload); + } + Rect bounds() const { + return std::visit([](const auto& a) -> Rect { return a.bounds(); }, payload); + } + + friend bool operator==(const Annotation&, const Annotation&) = default; + +private: + explicit Annotation(AnnotationPayload p) : payload(std::move(p)) {} +}; + +// ------------------------------------------------------------ JSON codecs --- +// Payload structs serialize with their Swift CodingKeys (synthesized order). +// The tagged Annotation wraps as {"type": "", "value": {...}} — an +// explicit cross-platform shape since Swift's enum-with-payload Codable +// ({"rectangle":{"_0":{...}}}) is only used inside macOS-internal archives. + +void to_json(Json& j, const RectangleAnnotation& a); +void from_json(const Json& j, RectangleAnnotation& a); +void to_json(Json& j, const FreehandAnnotation& a); +void from_json(const Json& j, FreehandAnnotation& a); +void to_json(Json& j, const ArrowAnnotation& a); +void from_json(const Json& j, ArrowAnnotation& a); +void to_json(Json& j, const TextAnnotation& a); +void from_json(const Json& j, TextAnnotation& a); +void to_json(Json& j, const EllipseAnnotation& a); +void from_json(const Json& j, EllipseAnnotation& a); +void to_json(Json& j, const LineAnnotation& a); +void from_json(const Json& j, LineAnnotation& a); +void to_json(Json& j, const MosaicAnnotation& a); +void from_json(const Json& j, MosaicAnnotation& a); +void to_json(Json& j, const HighlightAnnotation& a); +void from_json(const Json& j, HighlightAnnotation& a); +void to_json(Json& j, const NumberLabelAnnotation& a); +void from_json(const Json& j, NumberLabelAnnotation& a); +void to_json(Json& j, const PrivacyRedactionAnnotation& a); +void from_json(const Json& j, PrivacyRedactionAnnotation& a); +void to_json(Json& j, const CalloutBubbleAnnotation& a); +void from_json(const Json& j, CalloutBubbleAnnotation& a); +void to_json(Json& j, const Annotation& a); +void from_json(const Json& j, Annotation& a); + +/// Non-empty lowercase case name ("rectangle" ... "calloutBubble"). +std::string annotationTypeName(const Annotation& a); + +} // namespace tf::core diff --git a/windows/Core/AppLanguage.h b/windows/Core/AppLanguage.h new file mode 100644 index 0000000..bcf1489 --- /dev/null +++ b/windows/Core/AppLanguage.h @@ -0,0 +1,91 @@ +#pragma once +// AppLanguage.h — UI display languages (macOS AppLanguage.swift). + +#include +#include +#include +#include +#include + +namespace tf::core { + +enum class AppLanguage : int32_t { + System, English, SimplifiedChinese, German, Spanish, French, Italian, + Japanese, Korean, Portuguese, Russian, Invalid = -1, +}; + +inline std::string toRaw(AppLanguage l) { + switch (l) { + case AppLanguage::System: return "system"; + case AppLanguage::English: return "en"; + case AppLanguage::SimplifiedChinese: return "zh-Hans"; + case AppLanguage::German: return "de"; + case AppLanguage::Spanish: return "es"; + case AppLanguage::French: return "fr"; + case AppLanguage::Italian: return "it"; + case AppLanguage::Japanese: return "ja"; + case AppLanguage::Korean: return "ko"; + case AppLanguage::Portuguese: return "pt"; + case AppLanguage::Russian: return "ru"; + default: return ""; + } +} + +inline AppLanguage appLanguageFromRaw(const std::string& raw) { + if (raw == "system") { return AppLanguage::System; } + if (raw == "en") { return AppLanguage::English; } + if (raw == "zh-Hans") { return AppLanguage::SimplifiedChinese; } + if (raw == "de") { return AppLanguage::German; } + if (raw == "es") { return AppLanguage::Spanish; } + if (raw == "fr") { return AppLanguage::French; } + if (raw == "it") { return AppLanguage::Italian; } + if (raw == "ja") { return AppLanguage::Japanese; } + if (raw == "ko") { return AppLanguage::Korean; } + if (raw == "pt") { return AppLanguage::Portuguese; } + if (raw == "ru") { return AppLanguage::Russian; } + return AppLanguage::Invalid; +} + +inline const char* displayName(AppLanguage l) { + switch (l) { + case AppLanguage::System: return "System"; // localized in the WinUI layer + case AppLanguage::English: return "English"; + case AppLanguage::SimplifiedChinese: return "简体中文"; + case AppLanguage::German: return "Deutsch"; + case AppLanguage::Spanish: return "Español"; + case AppLanguage::French: return "Français"; + case AppLanguage::Italian: return "Italiano"; + case AppLanguage::Japanese: return "日本語"; + case AppLanguage::Korean: return "한국어"; + case AppLanguage::Portuguese: return "Português"; + case AppLanguage::Russian: return "Русский"; + default: return ""; + } +} + +constexpr AppLanguage kAllAppLanguages[] = { + AppLanguage::System, AppLanguage::English, AppLanguage::SimplifiedChinese, + AppLanguage::German, AppLanguage::Spanish, AppLanguage::French, + AppLanguage::Italian, AppLanguage::Japanese, AppLanguage::Korean, + AppLanguage::Portuguese, AppLanguage::Russian, +}; + +inline std::optional appLanguageFromLocale(std::string identifier) { + std::replace(identifier.begin(), identifier.end(), '_', '-'); + std::transform(identifier.begin(), identifier.end(), identifier.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + if (identifier.rfind("zh-hans", 0) == 0 || identifier == "zh-cn" || + identifier == "zh-sg" || identifier == "zh") { + return AppLanguage::SimplifiedChinese; + } + for (AppLanguage l : kAllAppLanguages) { + if (l == AppLanguage::System) { continue; } + std::string raw = toRaw(l); + std::transform(raw.begin(), raw.end(), raw.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + if (identifier == raw || identifier.rfind(raw + "-", 0) == 0) { return l; } + } + return std::nullopt; +} + +} // namespace tf::core diff --git a/windows/Core/CaptureDocument.cpp b/windows/Core/CaptureDocument.cpp new file mode 100644 index 0000000..d5e8254 --- /dev/null +++ b/windows/Core/CaptureDocument.cpp @@ -0,0 +1,212 @@ +// CaptureDocument.cpp — method bodies + JSON codecs for capture models. +#include "CaptureDocument.h" + +#include +#include + +namespace tf::core { + +// ------------------------------------------------------------- DisplayInfo -- +std::string DisplayInfo::resolution() const { + std::ostringstream out; + out << static_cast(frame.width * scaleFactor) << " x " + << static_cast(frame.height * scaleFactor); + return out.str(); +} + +void to_json(Json& j, const DisplayInfo& d) { + j = Json{{"id", d.id}, {"name", d.name}, {"frame", d.frame}, + {"scaleFactor", d.scaleFactor}, {"isPrimary", d.isPrimary}}; +} +void from_json(const Json& j, DisplayInfo& d) { + d.id = static_cast(j.at("id").get()); + d.name = j.at("name").get(); + d.frame = j.at("frame").get(); + d.scaleFactor = j.at("scaleFactor").get(); + d.isPrimary = getOptionalOr(j, "isPrimary", false); +} + +// ----------------------------------------------------------------- OCRText -- +void to_json(Json& j, const OCRText& t) { + j = Json{{"id", t.id}, {"text", t.text}, {"boundingBox", t.boundingBox}, + {"confidence", t.confidence}}; +} +void from_json(const Json& j, OCRText& t) { + t.id = j.at("id").get(); + t.text = j.at("text").get(); + t.boundingBox = j.at("boundingBox").get(); + t.confidence = static_cast(getOptionalOr(j, "confidence", 1.0)); +} + +// ---------------------------------------------------------------- OCRResult -- +std::string OCRResult::fullText() const { + std::vector sorted; + sorted.reserve(observations.size()); + for (const auto& o : observations) { sorted.push_back(&o); } + std::sort(sorted.begin(), sorted.end(), + [](const OCRText* a, const OCRText* b) { + return a->boundingBox.minY() < b->boundingBox.minY(); + }); + std::string out; + for (std::size_t i = 0; i < sorted.size(); ++i) { + if (i > 0) { out += '\n'; } + out += sorted[i]->text; + } + return out; +} + +OCRResult OCRResult::filteredBy(float minimumConfidence) const { + OCRResult out; + out.imageWidth = imageWidth; + out.imageHeight = imageHeight; + out.timestamp = timestamp; + out.observations.reserve(observations.size()); + for (const auto& o : observations) { + if (o.confidence >= minimumConfidence) { out.observations.push_back(o); } + } + return out; +} + +std::vector OCRResult::observationsIn(const Rect& rect) const { + std::vector out; + for (const auto& o : observations) { + if (o.boundingBox.intersects(rect)) { out.push_back(o); } + } + return out; +} + +// -------------------------------------------------------------- TextSegment -- +void to_json(Json& j, const TextSegment& s) { + j = Json{{"id", s.id}, {"text", s.text}, {"boundingBox", s.boundingBox}, + {"confidence", s.confidence}, {"isUserEdited", s.isUserEdited}}; +} +void from_json(const Json& j, TextSegment& s) { + s.id = j.at("id").get(); + s.text = j.at("text").get(); + s.boundingBox = j.at("boundingBox").get(); + s.confidence = static_cast(getOptionalOr(j, "confidence", 1.0)); + s.isUserEdited = getOptionalOr(j, "isUserEdited", false); +} + +// ------------------------------------------------------ ScreenAnalysisResult -- +std::string ScreenAnalysisResult::fullText() const { + std::vector sorted; + sorted.reserve(segments.size()); + for (const auto& s : segments) { sorted.push_back(&s); } + std::sort(sorted.begin(), sorted.end(), + [](const TextSegment* a, const TextSegment* b) { + return a->boundingBox.minY() < b->boundingBox.minY(); + }); + std::string out; + for (std::size_t i = 0; i < sorted.size(); ++i) { + if (i > 0) { out += '\n'; } + out += sorted[i]->text; + } + return out; +} + +ScreenAnalysisResult ScreenAnalysisResult::filtered(float minimumConfidence) const { + std::vector passed, excluded; + for (const auto& s : segments) { + (s.confidence >= minimumConfidence ? passed : excluded).push_back(s); + } + std::vector filtered = filteredOutSegments; + filtered.insert(filtered.end(), excluded.begin(), excluded.end()); + return {std::move(passed), rawSegments, std::move(filtered), imageWidth, imageHeight}; +} + +ScreenAnalysisResult ScreenAnalysisResult::recoveringFilteredSegments() const { + std::vector all = segments; + all.insert(all.end(), filteredOutSegments.begin(), filteredOutSegments.end()); + std::sort(all.begin(), all.end(), [](const TextSegment& a, const TextSegment& b) { + const double ay = a.boundingBox.minY(), by = b.boundingBox.minY(); + if (std::abs(ay - by) > 1e-9) { return ay < by; } + return a.boundingBox.minX() < b.boundingBox.minX(); + }); + return {std::move(all), rawSegments, {}, imageWidth, imageHeight}; +} + +ScreenAnalysisResult ScreenAnalysisResult::updatingSegment(const Uuid& segmentId, + const std::string& newText) const { + ScreenAnalysisResult copy = *this; + for (auto& s : copy.segments) { + if (s.id == segmentId) { + s.text = newText; + s.isUserEdited = true; + } + } + return copy; +} + +ScreenAnalysisResult ScreenAnalysisResult::fromOcr(const OCRResult& ocr) { + std::vector segments; + segments.reserve(ocr.observations.size()); + for (const auto& o : ocr.observations) { + TextSegment s; + s.id = o.id; + s.text = o.text; + s.boundingBox = o.boundingBox; + s.confidence = o.confidence; + segments.push_back(std::move(s)); + } + return {std::move(segments), {}, {}, ocr.imageWidth, ocr.imageHeight}; +} + +void to_json(Json& j, const ScreenAnalysisResult& r) { + j = Json{{"segments", r.segments}, + {"rawSegments", r.rawSegments}, + {"filteredOutSegments", r.filteredOutSegments}, + {"imageSize", Json::array({r.imageWidth, r.imageHeight})}}; +} +void from_json(const Json& j, ScreenAnalysisResult& r) { + r.segments = j.at("segments").get>(); + r.rawSegments = getOptionalOr>(j, "rawSegments", {}); + r.filteredOutSegments = getOptionalOr>(j, "filteredOutSegments", {}); + const auto size = j.at("imageSize").get>(); + if (size.size() == 2) { + r.imageWidth = size[0]; + r.imageHeight = size[1]; + } +} + +// --------------------------------------------------------------- Screenshot -- +Size Screenshot::dimensions() const { + // ImageRef resolution is a NativeShell concern; Core reports 0x0 when the + // handle is unset (task B wires the real lookup). + if (image == 0) { return Size{0, 0}; } + // Placeholder until NativeShell exposes image info; dims flow through + // CaptureDocument::baseImage instead. + return Size{0, 0}; +} + +std::int64_t Screenshot::estimatedFileSize() const { + const Size size = dimensions(); + const double pixels = size.width * size.height; + return static_cast(pixels * estimatedBytesPerPixel(format)); +} + +std::string Screenshot::formattedFileSize() const { + const std::int64_t bytes = estimatedFileSize(); + std::ostringstream out; + if (bytes < 1024) { + out << bytes << " B"; + } else if (bytes < 1024 * 1024) { + out.precision(1); + out << std::fixed << static_cast(bytes) / 1024.0 << " KB"; + } else { + out.precision(1); + out << std::fixed << static_cast(bytes) / (1024.0 * 1024.0) << " MB"; + } + return out.str(); +} + +double Screenshot::aspectRatio() const { + const Size size = dimensions(); + return size.height != 0 ? size.width / size.height : 0.0; +} + +// --------------------------------------------------------- QuartzGlobalRect -- +void to_json(Json& j, const QuartzGlobalRect& r) { j = r.rawValue; } +void from_json(const Json& j, QuartzGlobalRect& r) { r.rawValue = j.get(); } + +} // namespace tf::core diff --git a/windows/Core/CaptureDocument.h b/windows/Core/CaptureDocument.h new file mode 100644 index 0000000..7b480e9 --- /dev/null +++ b/windows/Core/CaptureDocument.h @@ -0,0 +1,190 @@ +#pragma once +// CaptureDocument.h — capture session models (macOS Screenshot.swift + +// CaptureDocument.swift). The CGImage payload becomes an ImageRef handle: +// Core never touches pixels; NativeShell (task B) owns D2D/WIC bitmaps and +// hands out opaque 64-bit handles, so this header stays platform-clean. + +#include "Annotation.h" +#include "ExportFormat.h" +#include "Geometry.h" +#include "Json.h" +#include "OCREngineType.h" +#include "Uuid.h" + +#include +#include +#include +#include + +namespace tf::core { + +/// Opaque image handle (NativeShell CGImage analogue). 0 = no image. +using ImageRef = std::uint64_t; + +/// Connected display descriptor (macOS DisplayInfo.swift). On Windows the +/// id is the HMONITOR-cast value; name from EnumDisplayDevices; frame in +/// virtual-screen coordinates; scaleFactor the DPI ratio. +struct DisplayInfo { + std::uint32_t id = 0; + std::string name; + Rect frame; // points, global coordinates + double scaleFactor = 1.0; + bool isPrimary = false; + + /// "2560 x 1440" + std::string resolution() const; + bool isRetina() const { return scaleFactor > 1.0; } + Size pixelSize() const { + return Size{frame.width * scaleFactor, frame.height * scaleFactor}; + } + + friend bool operator==(const DisplayInfo&, const DisplayInfo&) = default; +}; + +/// OCR text observation (macOS OCRText) + result (macOS OCRResult). +/// Normalized bounding boxes: top-left origin, 0..1, y grows down. +struct OCRText { + Uuid id; + std::string text; + Rect boundingBox; + float confidence = 1.0f; + + friend bool operator==(const OCRText&, const OCRText&) = default; +}; + +struct OCRResult { + std::vector observations; + std::int64_t imageWidth = 0; + std::int64_t imageHeight = 0; + TimePoint timestamp{}; + + std::size_t count() const { return observations.size(); } + bool hasResults() const { return !observations.empty(); } + /// Observations sorted by minY, joined with newlines (Swift fullText). + std::string fullText() const; + OCRResult filteredBy(float minimumConfidence) const; + std::vector observationsIn(const Rect& rect) const; + static OCRResult empty(std::int64_t width, std::int64_t height) { + return OCRResult{{}, width, height, {}}; + } + + friend bool operator==(const OCRResult&, const OCRResult&) = default; +}; + +/// VLM analysis segment (macOS TextSegment in ScreenAnalysisResult.swift). +struct TextSegment { + Uuid id; + std::string text; + Rect boundingBox; // normalized 0..1, top-left origin + float confidence = 1.0f; + bool isUserEdited = false; + + bool isHighConfidence() const { return confidence > 0.7f; } + Rect pixelBoundingBox(const Size& imageSize) const { + return Rect{boundingBox.minX() * imageSize.width, boundingBox.minY() * imageSize.height, + boundingBox.width * imageSize.width, + boundingBox.height * imageSize.height}; + } + + friend bool operator==(const TextSegment&, const TextSegment&) = default; +}; + +/// VLM screen-analysis result (macOS ScreenAnalysisResult.swift). +struct ScreenAnalysisResult { + std::vector segments; + std::vector rawSegments; + std::vector filteredOutSegments; + std::int64_t imageWidth = 0; + std::int64_t imageHeight = 0; + + ScreenAnalysisResult() = default; + ScreenAnalysisResult(std::vector segments_, std::vector raw_, + std::vector filteredOut_, std::int64_t width, + std::int64_t height) + : segments(std::move(segments_)), + rawSegments(raw_.empty() ? segments : std::move(raw_)), + filteredOutSegments(std::move(filteredOut_)), + imageWidth(width), + imageHeight(height) {} + + std::size_t count() const { return segments.size(); } + bool hasResults() const { return !segments.empty(); } + std::string fullText() const; + ScreenAnalysisResult filtered(float minimumConfidence) const; + ScreenAnalysisResult recoveringFilteredSegments() const; + /// Replaces one segment's text and marks it user-edited. + ScreenAnalysisResult updatingSegment(const Uuid& segmentId, const std::string& newText) const; + Size imageSize() const { return Size{static_cast(imageWidth), + static_cast(imageHeight)}; } + static ScreenAnalysisResult empty(std::int64_t width, std::int64_t height) { + return {{}, {}, {}, width, height}; + } + static ScreenAnalysisResult fromOcr(const OCRResult& ocr); + + friend bool operator==(const ScreenAnalysisResult&, const ScreenAnalysisResult&) = default; +}; + +/// Captured screenshot (macOS Screenshot.swift). Not Codable on macOS (the +/// CGImage cannot encode); persisted state lives in CaptureDocument. +struct Screenshot { + Uuid id; + ImageRef image = 0; // NativeShell handle; 0 = none + TimePoint captureDate{}; + DisplayInfo sourceDisplay; + std::vector annotations; + std::optional filePath; // until saved + ExportFormat format = ExportFormat::Png; + + Size dimensions() const; // asks NativeShell via ImageRef; 0x0 when unset + std::int64_t estimatedFileSize() const; + /// "1.2 MB" style string (Swift formattedFileSize). + std::string formattedFileSize() const; + double aspectRatio() const; + + friend bool operator==(const Screenshot&, const Screenshot&) = default; +}; + +/// Global screen rect wrapper (macOS QuartzGlobalRect) — the pin-back rect in +/// global coordinates for 1:1 in-place pinning. +struct QuartzGlobalRect { + Rect rawValue; + + QuartzGlobalRect() = default; + explicit QuartzGlobalRect(Rect r) : rawValue(r) {} + friend bool operator==(const QuartzGlobalRect&, const QuartzGlobalRect&) = default; +}; + +/// Unified capture lifecycle document (macOS CaptureDocument.swift). +struct CaptureDocument { + Uuid id; + ImageRef baseImage = 0; // immutable base pixels + QuartzGlobalRect sourceScreenRect; // for 1:1 pinning + std::optional sourceDisplay; + std::optional cropTransform; // base-image pixel coords; nullopt = full + std::vector annotations; + int editRevision = 1; + int analysisInputRevision = 1; + int lastSavedRevision = 0; + std::optional cachedAnalysisResult; + TimePoint createdAt{}; + + friend bool operator==(const CaptureDocument&, const CaptureDocument&) = default; +}; + +// ------------------------------------------------------------ JSON codecs --- +// Only the persistable pieces serialize: DisplayInfo, TextSegment, +// ScreenAnalysisResult, QuartzGlobalRect, and CaptureDocument metadata +// (image handles are runtime-only and skipped). + +void to_json(Json& j, const DisplayInfo& d); +void from_json(const Json& j, DisplayInfo& d); +void to_json(Json& j, const OCRText& t); +void from_json(const Json& j, OCRText& t); +void to_json(Json& j, const TextSegment& s); +void from_json(const Json& j, TextSegment& s); +void to_json(Json& j, const ScreenAnalysisResult& r); +void from_json(const Json& j, ScreenAnalysisResult& r); +void to_json(Json& j, const QuartzGlobalRect& r); +void from_json(const Json& j, QuartzGlobalRect& r); + +} // namespace tf::core diff --git a/windows/Core/EngineSelectionV2.h b/windows/Core/EngineSelectionV2.h new file mode 100644 index 0000000..1c95fe8 --- /dev/null +++ b/windows/Core/EngineSelectionV2.h @@ -0,0 +1,104 @@ +#pragma once +// EngineSelectionV2.h — converged ordered/compare engine selection +// (macOS EngineSelectionV2.swift). JSON shape (observed): +// {"id":"EE86…","kind":{"builtin":{"_0":"openai"}}} +// {"id":"5A3A…","kind":{"compatible":{"_0":"1234…"}}} + +#include "Json.h" +#include "TranslationEngineType.h" +#include "Uuid.h" + +#include +#include +#include + +namespace tf::core { + +/// One entry in the ordered chain or compare set. +struct EngineChainItem { + Uuid id; + struct Kind { + enum class Tag { Builtin, Compatible }; + Tag tag = Tag::Builtin; + TranslationEngineType engine = TranslationEngineType::MtranServer; // when Builtin + Uuid instanceId; // when Compatible + + friend bool operator==(const Kind& a, const Kind& b) { + if (a.tag != b.tag) { return false; } + if (a.tag == Tag::Builtin) { return a.engine == b.engine; } + return a.instanceId == b.instanceId; + } + } kind; + + EngineChainItem() = default; + static EngineChainItem builtin(TranslationEngineType e) { + EngineChainItem item; + item.id = Uuid::randomUuid(); + item.kind = Kind{Kind::Tag::Builtin, e, {}}; + return item; + } + static EngineChainItem compatible(Uuid instance) { + EngineChainItem item; + item.id = Uuid::randomUuid(); + item.kind = Kind{Kind::Tag::Compatible, TranslationEngineType::Custom, instance}; + return item; + } + + /// The builtin engine this entry reports as (compatible instances surface + /// as Custom; UI labels use the instance display name). + TranslationEngineType resolvedEngine() const { + return kind.tag == Kind::Tag::Builtin ? kind.engine : TranslationEngineType::Custom; + } + + friend bool operator==(const EngineChainItem& a, const EngineChainItem& b) { + return a.id == b.id && a.kind == b.kind; + } + + void toJson(Json& j) const { + Json kindJson; + if (kind.tag == Kind::Tag::Builtin) { + kindJson["builtin"]["_0"] = toRaw(kind.engine); + } else { + kindJson["compatible"]["_0"] = kind.instanceId; + } + j = Json{{"id", id}, {"kind", std::move(kindJson)}}; + } + static EngineChainItem fromJson(const Json& j) { + EngineChainItem item; + item.id = j.at("id").get(); + const Json& kind = j.at("kind"); + if (kind.contains("builtin")) { + const std::string raw = kind.at("builtin").at("_0").get(); + const TranslationEngineType e = fromRaw(TranslationEngineType{}, raw); + if (e == TranslationEngineType::Invalid) { + throw std::invalid_argument("unknown builtin engine: " + raw); + } + item.kind = Kind{Kind::Tag::Builtin, e, {}}; + } else if (kind.contains("compatible")) { + item.kind = Kind{Kind::Tag::Compatible, TranslationEngineType::Custom, + kind.at("compatible").at("_0").get()}; + } else { + throw std::invalid_argument("EngineChainItem.Kind requires builtin or compatible"); + } + return item; + } +}; + +inline void to_json(Json& j, const EngineChainItem& item) { item.toJson(j); } +inline void from_json(const Json& j, EngineChainItem& item) { item = EngineChainItem::fromJson(j); } + +/// Converged selection modes. +enum class EngineModeV2 : int32_t { Ordered, Compare }; +inline std::string toRaw(EngineModeV2 m) { return m == EngineModeV2::Ordered ? "ordered" : "compare"; } +inline EngineModeV2 engineModeFromRaw(const std::string& raw) { + return raw == "compare" ? EngineModeV2::Compare : EngineModeV2::Ordered; +} + +/// Structural limits (EngineSelectionLimits.swift). +struct EngineSelectionLimits { + static constexpr int kOrderedChainLimit = 5; + static constexpr int kCompareEnginesLimit = 4; + static constexpr int kCompareEnginesMinimum = 2; +}; + +} // namespace tf::core diff --git a/windows/Core/ExportFormat.h b/windows/Core/ExportFormat.h new file mode 100644 index 0000000..c66c5c9 --- /dev/null +++ b/windows/Core/ExportFormat.h @@ -0,0 +1,43 @@ +#pragma once +// ExportFormat.h — PNG/JPEG/HEIC (macOS ExportFormat.swift). +// HEIC availability depends on WIC/installed HEVC support; this model only +// carries the format value and estimates. Feature-layer probing is task B. + +#include + +namespace tf::core { + +enum class ExportFormat : int32_t { Png, Jpeg, Heic, Invalid = -1 }; +inline std::string toRaw(ExportFormat f) { + switch (f) { + case ExportFormat::Png: return "png"; + case ExportFormat::Jpeg: return "jpeg"; + case ExportFormat::Heic: return "heic"; + default: return ""; + } +} +inline ExportFormat exportFormatFromRaw(const std::string& raw) { + if (raw == "png") { return ExportFormat::Png; } + if (raw == "jpeg") { return ExportFormat::Jpeg; } + if (raw == "heic") { return ExportFormat::Heic; } + return ExportFormat::Invalid; +} +inline const char* mimeType(ExportFormat f) { + switch (f) { + case ExportFormat::Png: return "image/png"; + case ExportFormat::Jpeg: return "image/jpeg"; + case ExportFormat::Heic: return "image/heic"; + default: return "application/octet-stream"; + } +} +inline double estimatedBytesPerPixel(ExportFormat f) { + switch (f) { + case ExportFormat::Png: return 1.5; + case ExportFormat::Jpeg: return 0.3; + case ExportFormat::Heic: return 0.2; + default: return 0.0; + } +} +inline bool supportsQuality(ExportFormat f) { return f == ExportFormat::Jpeg || f == ExportFormat::Heic; } + +} // namespace tf::core diff --git a/windows/Core/Geometry.h b/windows/Core/Geometry.h new file mode 100644 index 0000000..a430555 --- /dev/null +++ b/windows/Core/Geometry.h @@ -0,0 +1,103 @@ +#pragma once +// Geometry.h — Core value geometry types mirroring CoreGraphics' CGPoint/CGSize/CGRect. +// Coordinate conventions are identical to the macOS implementation: bounding boxes +// are normalized (0..1) with a top-left origin unless stated otherwise. + +#include +#include +#include + +namespace tf::core { + +struct Point { + double x = 0.0; + double y = 0.0; + + friend bool operator==(const Point& a, const Point& b) noexcept { + return a.x == b.x && a.y == b.y; + } + friend bool operator!=(const Point& a, const Point& b) noexcept { return !(a == b); } +}; + +struct Size { + double width = 0.0; + double height = 0.0; + + friend bool operator==(const Size& a, const Size& b) noexcept { + return a.width == b.width && a.height == b.height; + } + friend bool operator!=(const Size& a, const Size& b) noexcept { return !(a == b); } +}; + +/// Axis-aligned rectangle. Semantics follow CGRect: origin + size; minX/minY/maxX/maxY +/// are the sorted edges (negative width/height are tolerated, matching CoreGraphics). +struct Rect { + double x = 0.0; + double y = 0.0; + double width = 0.0; + double height = 0.0; + + constexpr Rect() = default; + constexpr Rect(double px, double py, double w, double h) noexcept + : x(px), y(py), width(w), height(h) {} + constexpr Rect(const Point& origin, const Size& size) noexcept + : x(origin.x), y(origin.y), width(size.width), height(size.height) {} + + double minX() const noexcept { return width < 0 ? x + width : x; } + double minY() const noexcept { return height < 0 ? y + height : y; } + double maxX() const noexcept { return width < 0 ? x : x + width; } + double maxY() const noexcept { return height < 0 ? y : y + height; } + double midX() const noexcept { return (minX() + maxX()) / 2.0; } + double midY() const noexcept { return (minY() + maxY()) / 2.0; } + + Point origin() const noexcept { return Point{minX(), minY()}; } + Size size() const noexcept { return Size{maxX() - minX(), maxY() - minY()}; } + + /// CGRect.isNull: the "no rect at all" sentinel (infinite origin, zero size). + static const Rect& nullRect() noexcept { + static const Rect r{1e308, 1e308, 0.0, 0.0}; + return r; + } + static constexpr Rect zero() noexcept { return Rect{0.0, 0.0, 0.0, 0.0}; } + + bool isNull() const noexcept { return x == nullRect().x && y == nullRect().y; } + + /// CGRect.intersects (standardized rects assumed). + bool intersects(const Rect& other) const noexcept { + return !(maxX() < other.minX() || other.maxX() < minX() || + maxY() < other.minY() || other.maxY() < minY()); + } + + /// CGRect.contains(point). + bool contains(const Point& p) const noexcept { + return p.x >= minX() && p.x < maxX() && p.y >= minY() && p.y < maxY(); + } + + /// CGRect.union — returns nullRect when either side is null (CoreGraphics semantics). + Rect unionWith(const Rect& other) const noexcept { + if (isNull()) { return other; } + if (other.isNull()) { return *this; } + return Rect{ + std::min(minX(), other.minX()), + std::min(minY(), other.minY()), + std::max(maxX(), other.maxX()) - std::min(minX(), other.minX()), + std::max(maxY(), other.maxY()) - std::min(minY(), other.minY()) + }; + } + + /// CGRect.insetBy (may produce inverted rects; callers rely on this for hit tests). + Rect insetBy(double dx, double dy) const noexcept { + return Rect{x + dx, y + dy, width - 2 * dx, height - 2 * dy}; + } + + friend bool operator==(const Rect& a, const Rect& b) noexcept { + return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; + } + friend bool operator!=(const Rect& a, const Rect& b) noexcept { return !(a == b); } +}; + +inline double distance(const Point& a, const Point& b) noexcept { + return std::hypot(a.x - b.x, a.y - b.y); +} + +} // namespace tf::core diff --git a/windows/Core/Interfaces.h b/windows/Core/Interfaces.h new file mode 100644 index 0000000..6a5f250 --- /dev/null +++ b/windows/Core/Interfaces.h @@ -0,0 +1,159 @@ +#pragma once +// Interfaces.h — pure virtual service contracts for the Windows app. +// Core defines the seams; NativeShell (task B) and the services layer +// (task C) provide implementations: +// +// IOcrEngine <- WindowsOcrEngine (WinRT), PaddleOCR client [C] +// ITranslationProvider <- 9 engine adapters (no apple on Windows) [C] +// IHttpTransport <- WinHttp transport [C] +// ICredentialStore <- Credential Manager store [C] +// IHotkeyListener <- RegisterHotKey listener [B] +// IClipboard <- Win32 clipboard service [B] +// IHistoryStore <- JSON-file backed store (settings container) [A core] +// +// All interfaces are platform-clean (no Win32/WinRT includes) so the Catch2 +// unit tests can drive them with in-memory fakes on any host. + +#include "CaptureDocument.h" +#include "LLMTranslationCore.h" +#include "TranslationResultBundle.h" + +#include +#include +#include +#include + +namespace tf::core { + +// ------------------------------------------------------------- image input -- +/// Cross-platform image handle for OCR input: BGRA8 bytes + size (top-down). +struct OcrImage { + std::int64_t width = 0; + std::int64_t height = 0; + std::string bgra; // width*height*4 bytes +}; + +// ------------------------------------------------------------- OCR engine -- +/// OCR engine contract (Swift AnyOCREngine). recognize() returns segments +/// with normalized bboxes (top-left origin) + confidence. +class IOcrEngine { +public: + virtual ~IOcrEngine() = default; + + /// Stable engine identifier ("windows", "paddleocr"). + virtual std::string id() const = 0; + /// Human-readable name for settings UI. + virtual std::string name() const = 0; + /// Configured + language pack/model present. Never performs I/O. + virtual bool isAvailable() const = 0; + /// Runs OCR on one image. + virtual OCRResult recognize(const OcrImage& image) = 0; +}; + +// ----------------------------------------------------- translation provider -- +/// Translation request (Swift translate(texts:from:to:) batch form). +struct TranslateRequest { + std::vector texts; + /// Source language code; empty/"" = auto-detect. + std::string sourceLanguage; + std::string targetLanguage; + /// Resolved prompt template (TranslationPromptConfig::resolvedPrompt). + std::string promptTemplate; + /// Engine-specific max output tokens (LLM engines). + std::int64_t maxOutputTokens = 0; // 0 = engine default +}; + +/// Translation provider contract (Swift TranslationProvider). Implementations +/// wrap one engine; batch translate preserves input order. +class ITranslationProvider { +public: + virtual ~ITranslationProvider() = default; + + virtual std::string id() const = 0; + virtual std::string name() const = 0; + virtual TranslationEngineType engineType() const = 0; + /// Configured + credentials present (never performs I/O). + virtual bool isAvailable() const = 0; + + /// Batch translate. On failure returns an EngineError; per-text failures + /// are reported as one error (same as Swift throws). + /// On success results[i] corresponds to request.texts[i]. + virtual std::optional translate(const TranslateRequest& request, + std::vector& outTranslations) = 0; + + /// Lightweight connectivity probe (models list / ping). MUST NOT call + /// billed translation endpoints. Returns nullopt = no free probe/OK. + virtual std::optional verifyConnection() = 0; +}; + +// ---------------------------------------------------------------- hotkeys -- +/// Global hotkey listener (macOS Carbon RegisterEventHotKey analogue; +/// Windows: RegisterHotKey + message-only window, task B). +class IHotkeyListener { +public: + virtual ~IHotkeyListener() = default; + + /// Registers one shortcut; returns false when the combination is already + /// taken by another app. + virtual bool registerShortcut(const std::string& actionId, const KeyboardShortcut& shortcut) = 0; + virtual void unregisterShortcut(const std::string& actionId) = 0; + /// Polls/next fired shortcut (event-driven in the real impl; the pure + /// contract keeps a pull API so tests can drive it). + /// Returns nullopt when no event is pending. + virtual std::optional nextFiredAction() = 0; +}; + +// -------------------------------------------------------------- clipboard -- +/// Clipboard service (Swift ClipboardService; Win32 GetClipboardData under +/// the hood, task B). +class IClipboard { +public: + virtual ~IClipboard() = default; + + /// Copies PNG bytes to the clipboard. + virtual bool copyImage(const std::vector& pngBytes) = 0; + /// Copies UTF-8 text. + virtual bool copyText(const std::string& text) = 0; + /// Reads UTF-8 text; nullopt when the clipboard has no text. + virtual std::optional readText() = 0; + virtual bool hasImage() const = 0; +}; + +// ------------------------------------------------------------ history store -- +/// History persistence (Swift HistoryStore; UserDefaults-backed on macOS, +/// ApplicationData JSON on Windows — same "TransFrame.translationHistory" +/// payload). Max 50 entries (HistoryStore.maxHistoryEntries). +class IHistoryStore { +public: + virtual ~IHistoryStore() = default; + + virtual std::vector entries() const = 0; + /// Inserts newest-first; removes same-content duplicates; enforces the cap. + virtual void add(const TranslationHistory& entry) = 0; + virtual void remove(const Uuid& id) = 0; + virtual void toggleFavorite(const Uuid& id) = 0; + virtual void save() = 0; + virtual void reload() = 0; +}; + +// -------------------------------------------------------- credential store -- +/// Credential storage abstraction (Swift KeychainService; Windows Credential +/// Manager, task C). Account names follow "TransFrame//". +class ICredentialStore { +public: + virtual ~ICredentialStore() = default; + + virtual void save(const std::string& account, const std::string& secret) = 0; + virtual std::optional load(const std::string& account) const = 0; + virtual bool remove(const std::string& account) = 0; + virtual bool has(const std::string& account) const = 0; +}; + +using OcrEnginePtr = std::unique_ptr; +using TranslationProviderPtr = std::unique_ptr; +using HotkeyListenerPtr = std::unique_ptr; +using ClipboardPtr = std::unique_ptr; +using HistoryStorePtr = std::unique_ptr; +using CredentialStorePtr = std::shared_ptr; + +} // namespace tf::core diff --git a/windows/Core/Json.cpp b/windows/Core/Json.cpp new file mode 100644 index 0000000..06928b8 --- /dev/null +++ b/windows/Core/Json.cpp @@ -0,0 +1,69 @@ +// Json.cpp — small codec helpers that need a translation unit. + +#include "Json.h" + +namespace tf::core { + +static const char* kBase64Chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +std::string encodeBase64(const std::vector& data) { + std::string out; + out.reserve(((data.size() + 2) / 3) * 4); + std::size_t i = 0; + while (i + 2 < data.size()) { + const std::uint32_t n = + (static_cast(data[i]) << 16) | + (static_cast(data[i + 1]) << 8) | + static_cast(data[i + 2]); + out += kBase64Chars[(n >> 18) & 63]; + out += kBase64Chars[(n >> 12) & 63]; + out += kBase64Chars[(n >> 6) & 63]; + out += kBase64Chars[n & 63]; + i += 3; + } + if (i + 1 == data.size()) { + const std::uint32_t n = static_cast(data[i]) << 16; + out += kBase64Chars[(n >> 18) & 63]; + out += kBase64Chars[(n >> 12) & 63]; + out += "=="; + } else if (i + 2 == data.size()) { + const std::uint32_t n = + (static_cast(data[i]) << 16) | + (static_cast(data[i + 1]) << 8); + out += kBase64Chars[(n >> 18) & 63]; + out += kBase64Chars[(n >> 12) & 63]; + out += kBase64Chars[(n >> 6) & 63]; + out += '='; + } + return out; +} + +static int base64Value(char c) { + if (c >= 'A' && c <= 'Z') { return c - 'A'; } + if (c >= 'a' && c <= 'z') { return c - 'a' + 26; } + if (c >= '0' && c <= '9') { return c - '0' + 52; } + if (c == '+') { return 62; } + if (c == '/') { return 63; } + return -1; +} + +std::vector decodeBase64(const std::string& text) { + std::vector out; + std::uint32_t buffer = 0; + int bits = 0; + for (char c : text) { + if (c == '=' || c == '\n' || c == '\r') { continue; } + const int v = base64Value(c); + if (v < 0) { continue; } + buffer = (buffer << 6) | static_cast(v); + bits += 6; + if (bits >= 8) { + bits -= 8; + out.push_back(static_cast((buffer >> bits) & 0xFF)); + } + } + return out; +} + +} // namespace tf::core diff --git a/windows/Core/Json.h b/windows/Core/Json.h new file mode 100644 index 0000000..f8c8eb4 --- /dev/null +++ b/windows/Core/Json.h @@ -0,0 +1,124 @@ +#pragma once +// Json.h — nlohmann/json adapters that reproduce the exact wire shapes of the +// macOS Swift Codable implementation. Every shape below was observed against +// JSONEncoder/JSONDecoder output (probe: 2026-11-02) — see report-A.md. +// +// Shapes: +// CGRect -> [[x, y], [width, height]] +// UUID -> "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" (uppercase) +// Date -> seconds since 2001-01-01T00:00:00Z (double) +// Data -> base64 (explicit helpers below) +// enum w/ payload (EngineChainItem.Kind) -> {"builtin":{"_0":"mtran"}} +// enum-keyed dictionary -> alternating key/value array + +#include "Geometry.h" +#include "Uuid.h" +#include + +#include +#include +#include +#include +#include +#include + +namespace tf::core { +using Json = nlohmann::json; + +// ---------------------------------------------------------------- CGPoint --- +inline void to_json(Json& j, const Point& p) { j = Json::array({p.x, p.y}); } +inline void from_json(const Json& j, Point& p) { + p = Point{j.at(0).get(), j.at(1).get()}; +} + +// ----------------------------------------------------------------- CGSize --- +inline void to_json(Json& j, const Size& s) { j = Json::array({s.width, s.height}); } +inline void from_json(const Json& j, Size& s) { + s = Size{j.at(0).get(), j.at(1).get()}; +} + +// ----------------------------------------------------------------- CGRect --- +// Swift encodes CGRect (a CGRectMake of (origin, size)) as nested arrays. +inline void to_json(Json& j, const Rect& r) { + j = Json::array({Json::array({r.x, r.y}), Json::array({r.width, r.height})}); +} +inline void from_json(const Json& j, Rect& r) { + const auto& origin = j.at(0); + const auto& size = j.at(1); + r = Rect{origin.at(0).get(), origin.at(1).get(), + size.at(0).get(), size.at(1).get()}; +} + +// ------------------------------------------------------------------- UUID --- +inline void to_json(Json& j, const Uuid& u) { j = u.toString(); } +inline void from_json(const Json& j, Uuid& u) { + Uuid parsed; + if (!Uuid::parse(j.get(), parsed)) { + throw std::invalid_argument("invalid UUID string"); + } + u = parsed; +} + +// ------------------------------------------------------------------- Date --- +// Swift Codable reference date: 2001-01-01T00:00:00Z = 978307200 unix seconds. +inline constexpr double kSwiftReferenceDateUnix = 978307200.0; + +inline void to_json(Json& j, const std::chrono::system_clock::time_point& t) { + using namespace std::chrono; + const double unixSeconds = + static_cast(duration_cast>(t.time_since_epoch()).count()); + j = unixSeconds - kSwiftReferenceDateUnix; +} +inline void from_json(const Json& j, std::chrono::system_clock::time_point& t) { + using namespace std::chrono; + const double swiftSeconds = j.get(); + t = system_clock::time_point{ + duration_cast(duration(swiftSeconds + kSwiftReferenceDateUnix))}; +} + +/// Convenience alias used by history models. +using TimePoint = std::chrono::system_clock::time_point; + +/// ADL cannot find tf::core::to_json for std::chrono types (their namespace is +/// std::chrono, not tf::core), so hook the serializer explicitly. This makes +/// Json{{"timestamp", someTimePoint}} work inside initializer lists. +} // namespace tf::core + +namespace nlohmann { +template <> +struct adl_serializer { + static void to_json(tf::core::Json& j, const std::chrono::system_clock::time_point& t) { + ::tf::core::to_json(j, t); + } + static void from_json(const tf::core::Json& j, std::chrono::system_clock::time_point& t) { + ::tf::core::from_json(j, t); + } +}; +} // namespace nlohmann + +namespace tf::core { + +/// Current wall-clock time (thin wrapper so tests can inject fixed clocks later). +inline TimePoint now() { return std::chrono::system_clock::now(); } + +// ----------------------------------------------------- optional members ---- +// Swift `decodeIfPresent` semantics: missing key -> nullopt; JSON null -> nullopt. +template +std::optional getOptional(const Json& j, const char* key) { + auto it = j.find(key); + if (it == j.end() || it->is_null()) { return std::nullopt; } + return it->get(); +} + +/// Swift's `decodeIfPresent(...) ?? defaultValue`. +template +T getOptionalOr(const Json& j, const char* key, T fallback) { + auto value = getOptional(j, key); + return value ? std::move(*value) : std::move(fallback); +} + +/// Explicit Base64 helpers for Swift Data <-> std::vector. +std::string encodeBase64(const std::vector& data); +std::vector decodeBase64(const std::string& text); + +} // namespace tf::core diff --git a/windows/Core/KeyboardShortcut.h b/windows/Core/KeyboardShortcut.h new file mode 100644 index 0000000..86370d5 --- /dev/null +++ b/windows/Core/KeyboardShortcut.h @@ -0,0 +1,82 @@ +#pragma once +// KeyboardShortcut.h — global hotkey configuration (macOS KeyboardShortcut.swift). +// Persisted under SettingsKeys::*Shortcut as {"keyCode": UInt32, "modifiers": UInt32}. +// +// keyCode: on macOS these are Carbon virtual key codes (HIToolbox Events.h). +// Windows equivalents are documented in NativeShell (task B); the model keeps +// the raw 32-bit code verbatim so a settings file restored from macOS still +// round-trips even before a key-mapping table exists. +// +// Modifiers (Carbon bit flags, also the persisted format): +// cmdKey=0x0100 shiftKey=0x0200 alphaLock=0x0400 optionKey=0x0800 controlKey=0x1000 + +#include "Json.h" + +#include +#include +#include + +namespace tf::core { + +/// Carbon modifier bits (kept in a namespace to avoid polluting tf::core). +namespace CarbonModifiers { +inline constexpr std::uint32_t cmdKey = 0x0100; +inline constexpr std::uint32_t shiftKey = 0x0200; +inline constexpr std::uint32_t alphaLock = 0x0400; +inline constexpr std::uint32_t optionKey = 0x0800; +inline constexpr std::uint32_t controlKey = 0x1000; +} // namespace CarbonModifiers + +struct KeyboardShortcut { + std::uint32_t keyCode = 0; + std::uint32_t modifiers = 0; + + KeyboardShortcut() = default; + KeyboardShortcut(std::uint32_t key, std::uint32_t mods) noexcept : keyCode(key), modifiers(mods) {} + + // MARK: Default shortcuts (macOS defaults: Cmd+Shift+3/4/T/Y/I; + // kVK_ANSI_3='3'=0x14, '4'=0x15, T=0x11, Y=0x10, I=0x22). + static KeyboardShortcut fullScreenDefault() { + return {0x14, CarbonModifiers::cmdKey | CarbonModifiers::shiftKey}; + } + static KeyboardShortcut selectionDefault() { + return {0x15, CarbonModifiers::cmdKey | CarbonModifiers::shiftKey}; + } + static KeyboardShortcut translationModeDefault() { + return {0x11, CarbonModifiers::cmdKey | CarbonModifiers::shiftKey}; + } + static KeyboardShortcut textSelectionTranslationDefault() { + return {0x10, CarbonModifiers::cmdKey | CarbonModifiers::shiftKey}; + } + static KeyboardShortcut translateAndInsertDefault() { + return {0x22, CarbonModifiers::cmdKey | CarbonModifiers::shiftKey}; + } + + /// At least one of cmd/control/option must be held (Swift hasRequiredModifiers). + bool hasRequiredModifiers() const { + const std::uint32_t required = + CarbonModifiers::cmdKey | CarbonModifiers::controlKey | CarbonModifiers::optionKey; + return (modifiers & required) != 0; + } + + /// Shift-only shortcuts are not global-safe (intercepts typing) — same rule as Swift. + bool isValid() const { return hasRequiredModifiers(); } + + friend bool operator==(const KeyboardShortcut&, const KeyboardShortcut&) = default; + + // MARK: JSON — {"keyCode": n, "modifiers": n} + void toJson(Json& j) const { + j = Json{{"keyCode", keyCode}, {"modifiers", modifiers}}; + } + static KeyboardShortcut fromJson(const Json& j) { + KeyboardShortcut s; + s.keyCode = static_cast(j.at("keyCode").get()); + s.modifiers = static_cast(j.at("modifiers").get()); + return s; + } +}; + +inline void to_json(Json& j, const KeyboardShortcut& s) { s.toJson(j); } +inline void from_json(const Json& j, KeyboardShortcut& s) { s = KeyboardShortcut::fromJson(j); } + +} // namespace tf::core diff --git a/windows/Core/LLMTranslationCore.cpp b/windows/Core/LLMTranslationCore.cpp new file mode 100644 index 0000000..562034a --- /dev/null +++ b/windows/Core/LLMTranslationCore.cpp @@ -0,0 +1,297 @@ +// LLMTranslationCore.cpp — batching + response parser (Swift -> C++20). +#include "LLMTranslationCore.h" + +#include +#include + +namespace tf::core { + +namespace { + +std::string trimmed(const std::string& s) { + std::size_t b = 0, e = s.size(); + auto isSpace = [](unsigned char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; + }; + while (b < e && isSpace(static_cast(s[b]))) { ++b; } + while (e > b && isSpace(static_cast(s[e - 1]))) { --e; } + return s.substr(b, e - b); +} + +bool hasPrefix(const std::string& s, const std::string& prefix) { + return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0; +} + +/// UTF-8 code-point-aware advance: returns byte length of the code point at i. +std::size_t utf8LengthAt(const std::string& s, std::size_t i) { + const unsigned char c = static_cast(s[i]); + if (c < 0x80) { return 1; } + if ((c & 0xE0) == 0xC0) { return 2; } + if ((c & 0xF0) == 0xE0) { return 3; } + if ((c & 0xF8) == 0xF0) { return 4; } + return 1; +} + +} // namespace + +// --------------------------------------------------------------------------- +// Batching (Swift LLMTranslationBatching.swift) +// --------------------------------------------------------------------------- +const char* LLMTranslationBatching::separator() { return "\n---\n"; } + +std::int64_t LLMTranslationBatching::estimatedTokens(const std::string& text) { + // Swift counts UTF-16 code units; surrogate pairs count 2 in both. + std::int64_t n = 0; + for (const unsigned char c : text) { + if (c < 0x80) { + ++n; + } else if ((c & 0xE0) == 0xC0) { + n += 1; // 2-byte UTF-8 -> 1 UTF-16 unit + } else if ((c & 0xF0) == 0xE0) { + n += 1; // 3-byte -> 1 UTF-16 unit + } else if ((c & 0xF8) == 0xF0) { + n += 2; // 4-byte -> surrogate pair + } + // continuation bytes contribute 0 + } + return n; +} + +std::vector> LLMTranslationBatching::split( + const std::vector& texts, std::int64_t maxOutputTokens, + const std::string* promptTemplate) { + const std::int64_t budget = std::max(1, maxOutputTokens); + // Fixed prompt with {text} removed still occupies the budget. + std::string fixedPrompt; + if (promptTemplate != nullptr) { + fixedPrompt = *promptTemplate; + const std::string needle = "{text}"; + std::size_t pos; + while ((pos = fixedPrompt.find(needle)) != std::string::npos) { + fixedPrompt.replace(pos, needle.size(), ""); + } + } + const std::int64_t promptCost = estimatedTokens(fixedPrompt); + const std::int64_t sourceBudget = std::max(4, budget - promptCost); + + std::vector> batches; + std::vector current; + std::int64_t used = 0; + const std::int64_t sepCost = estimatedTokens("\n---\n"); + + auto appendPiece = [&](const std::string& piece) { + const std::int64_t cost = estimatedTokens(piece) + (current.empty() ? 0 : sepCost); + if (!current.empty() && used + cost > sourceBudget) { + batches.push_back(current); + current.clear(); + used = 0; + } + used += estimatedTokens(piece) + (current.empty() ? 0 : sepCost); + current.push_back(piece); + }; + + for (const auto& text : texts) { + if (estimatedTokens(text) > budget) { + for (const auto& piece : splitLongText(text, sourceBudget)) { appendPiece(piece); } + } else { + appendPiece(text); + } + } + if (!current.empty()) { batches.push_back(current); } + return batches; +} + +std::vector LLMTranslationBatching::splitLongText(const std::string& text, + std::int64_t budget) { + if (estimatedTokens(text) <= budget) { return {text}; } + std::vector pieces; + std::string current; + // Walk UTF-8 code points so a character is never cut in half (Swift walks + // Characters; both never split a code point). + std::size_t i = 0; + while (i < text.size()) { + const std::size_t len = utf8LengthAt(text, i); + const std::string ch = text.substr(i, len); + i += len; + if (!current.empty() && estimatedTokens(current) + estimatedTokens(ch) > budget) { + pieces.push_back(current); + current.clear(); + } + current += ch; + } + if (!current.empty()) { pieces.push_back(current); } + return pieces; +} + +// --------------------------------------------------------------------------- +// Response parser (Swift LLMTranslationResponseParser.swift) +// --------------------------------------------------------------------------- +LLMTextResult LLMTranslationResponseParser::extractText(const std::string& body, + TranslationEngineType engine) { + const std::string trimmedBody = trimmed(body); + // Only treat the response as an SSE stream when the first payload line is + // a data event. Translation bodies legitimately containing "\ndata:" (logs, + // SSE examples) must still parse as plain JSON. + if (hasPrefix(trimmedBody, "data:")) { + if (engine == TranslationEngineType::Claude) { return extractClaudeSSE(trimmedBody); } + return extractOpenAISSE(trimmedBody); + } + + Json json; + try { + json = Json::parse(body); + } catch (const Json::exception&) { + return LLMTextResult::failure("Response JSON is not a dictionary"); + } + if (!json.is_object()) { + return LLMTextResult::failure("Response JSON is not a dictionary"); + } + + if (auto errorIt = json.find("error"); + errorIt != json.end() && errorIt->is_object()) { + if (auto messageIt = errorIt->find("message"); + messageIt != errorIt->end() && messageIt->is_string()) { + return LLMTextResult::failure("API error: " + messageIt->get()); + } + } + + if (engine == TranslationEngineType::Claude) { + if (auto stopIt = json.find("stop_reason"); + stopIt != json.end() && stopIt->is_string() && + stopIt->get() == "max_tokens") { + return LLMTextResult::truncated("Claude reached the output token limit"); + } + if (auto contentIt = json.find("content"); + contentIt != json.end() && contentIt->is_array()) { + for (const auto& block : *contentIt) { + if (block.is_object()) { + auto typeIt = block.find("type"); + auto textIt = block.find("text"); + if (typeIt != block.end() && typeIt->is_string() && + typeIt->get() == "text" && textIt != block.end() && + textIt->is_string()) { + return LLMTextResult::success(trimmed(textIt->get())); + } + } + } + } + return LLMTextResult::failure("Unexpected JSON response structure"); + } + + auto choicesIt = json.find("choices"); + if (choicesIt == json.end() || !choicesIt->is_array() || choicesIt->empty()) { + return LLMTextResult::failure("Unexpected JSON response structure"); + } + const Json& choice = choicesIt->front(); + if (!choice.is_object()) { + return LLMTextResult::failure("Unexpected JSON response structure"); + } + if (auto reasonIt = choice.find("finish_reason"); reasonIt != choice.end() && reasonIt->is_string()) { + const std::string reason = reasonIt->get(); + if (reason == "length" || reason == "max_tokens") { + return LLMTextResult::truncated("The response reached the output token limit"); + } + } + if (auto messageIt = choice.find("message"); + messageIt != choice.end() && messageIt->is_object()) { + if (auto contentIt = messageIt->find("content"); + contentIt != messageIt->end() && contentIt->is_string()) { + return LLMTextResult::success(trimmed(contentIt->get())); + } + } + return LLMTextResult::failure("Unexpected JSON response structure"); +} + +LLMTextResult LLMTranslationResponseParser::extractOpenAISSE(const std::string& text) { + std::string result; + bool isTruncated = false; + std::size_t start = 0; + while (start <= text.size()) { + std::size_t end = text.find('\n', start); + const std::string rawLine = + text.substr(start, end == std::string::npos ? std::string::npos : end - start); + start = (end == std::string::npos) ? text.size() + 1 : end + 1; + + const std::string line = trimmed(rawLine); + if (!hasPrefix(line, "data:") || line == "data: [DONE]") { continue; } + std::string payload = trimmed(line.substr(5)); + Json json; + try { + json = Json::parse(payload); + } catch (const Json::exception&) { + continue; // non-JSON data lines are skipped (Swift `try?` + continue) + } + if (!json.is_object()) { continue; } + auto choicesIt = json.find("choices"); + if (choicesIt == json.end() || !choicesIt->is_array() || choicesIt->empty()) { continue; } + const Json& choice = choicesIt->front(); + if (!choice.is_object()) { continue; } + if (auto reasonIt = choice.find("finish_reason"); + reasonIt != choice.end() && reasonIt->is_string()) { + const std::string reason = reasonIt->get(); + isTruncated = isTruncated || reason == "length" || reason == "max_tokens"; + } + if (auto deltaIt = choice.find("delta"); deltaIt != choice.end() && deltaIt->is_object()) { + if (auto contentIt = deltaIt->find("content"); + contentIt != deltaIt->end() && contentIt->is_string()) { + result += contentIt->get(); + } + } else if (auto textIt = choice.find("text"); + textIt != choice.end() && textIt->is_string()) { + result += textIt->get(); + } + if (end == std::string::npos) { break; } + } + if (isTruncated) { + return LLMTextResult::truncated("The stream reached the output token limit"); + } + if (result.empty()) { return LLMTextResult::failure("Empty text from SSE stream"); } + return LLMTextResult::success(trimmed(result)); +} + +LLMTextResult LLMTranslationResponseParser::extractClaudeSSE(const std::string& text) { + std::string result; + bool isTruncated = false; + std::size_t start = 0; + while (start <= text.size()) { + std::size_t end = text.find('\n', start); + const std::string rawLine = + text.substr(start, end == std::string::npos ? std::string::npos : end - start); + start = (end == std::string::npos) ? text.size() + 1 : end + 1; + + const std::string line = trimmed(rawLine); + if (!hasPrefix(line, "data:")) { continue; } + const std::string payload = trimmed(line.substr(5)); + Json json; + try { + json = Json::parse(payload); + } catch (const Json::exception&) { + continue; + } + if (!json.is_object()) { continue; } + if (auto stopIt = json.find("stop_reason"); + stopIt != json.end() && stopIt->is_string() && + stopIt->get() == "max_tokens") { + isTruncated = true; + } + if (auto deltaIt = json.find("delta"); deltaIt != json.end() && deltaIt->is_object()) { + if (auto stopIt = deltaIt->find("stop_reason"); + stopIt != deltaIt->end() && stopIt->is_string() && + stopIt->get() == "max_tokens") { + isTruncated = true; + } + if (auto textIt = deltaIt->find("text"); + textIt != deltaIt->end() && textIt->is_string()) { + result += textIt->get(); + } + } + if (end == std::string::npos) { break; } + } + if (isTruncated) { + return LLMTextResult::truncated("Claude stream reached the output token limit"); + } + if (result.empty()) { return LLMTextResult::failure("Empty text from SSE stream"); } + return LLMTextResult::success(trimmed(result)); +} + +} // namespace tf::core diff --git a/windows/Core/LLMTranslationCore.h b/windows/Core/LLMTranslationCore.h new file mode 100644 index 0000000..0745df7 --- /dev/null +++ b/windows/Core/LLMTranslationCore.h @@ -0,0 +1,72 @@ +#pragma once +// LLMTranslationCore.h — pure-logic port of Swift LLMTranslationBatching.swift +// + LLMTranslationResponseParser.swift (same semantics, same test vectors as +// TransFrameTests/LLMResponseTruncationTests.swift). + +#include "Json.h" +#include "TranslationEngineType.h" + +#include +#include + +namespace tf::core { + +/// Expected-like result union (avoids exceptions so providers compose cleanly). +struct LLMTextResult { + bool ok = false; + std::string text; // when ok + bool incomplete = false; // truncation error (Swift incompleteResponse) + std::string error; // message when !ok + + static LLMTextResult success(std::string t) { + LLMTextResult r; + r.ok = true; + r.text = std::move(t); + return r; + } + static LLMTextResult truncated(std::string msg) { + LLMTextResult r; + r.ok = false; + r.incomplete = true; + r.error = std::move(msg); + return r; + } + static LLMTextResult failure(std::string msg) { + LLMTextResult r; + r.ok = false; + r.error = std::move(msg); + return r; + } +}; + +/// Batch splitter ahead of the output-token budget; long fragments are cut by +/// characters (never code points) and order is preserved. +struct LLMTranslationBatching { + static const char* separator(); // "\n---\n" + + /// Swift split(texts:maxOutputTokens:promptTemplate:) — template defaults + /// to "" when not supplied (nullopt). + static std::vector> split( + const std::vector& texts, std::int64_t maxOutputTokens, + const std::string* promptTemplate); + + /// Swift estimatedTokens: UTF-16 code-unit count. + static std::int64_t estimatedTokens(const std::string& text); + +private: + static std::vector splitLongText(const std::string& text, std::int64_t budget); +}; + +/// Shared completion-state parsing for OpenAI-compatible and Claude bodies +/// (plain JSON and SSE streams). A body only counts as SSE when the first +/// payload line starts with "data:" — bodies whose content contains "\ndata:" +/// still parse as plain JSON. +struct LLMTranslationResponseParser { + static LLMTextResult extractText(const std::string& body, TranslationEngineType engine); + +private: + static LLMTextResult extractOpenAISSE(const std::string& text); + static LLMTextResult extractClaudeSSE(const std::string& text); +}; + +} // namespace tf::core diff --git a/windows/Core/OCREngineType.h b/windows/Core/OCREngineType.h new file mode 100644 index 0000000..9122f74 --- /dev/null +++ b/windows/Core/OCREngineType.h @@ -0,0 +1,26 @@ +#pragma once +// OCREngineType.h — OCR engine choices. On macOS `vision` is the local default; +// Windows maps that platform slot to `windows` (Windows.Media.Ocr, PRD §6.12). +// PaddleOCR stays `paddleocr` across both platforms. + +#include + +namespace tf::core { + +enum class OCREngineType : int32_t { Windows, PaddleOCR, Invalid = -1 }; +inline std::string toRaw(OCREngineType e) { + switch (e) { + case OCREngineType::Windows: return "windows"; + case OCREngineType::PaddleOCR: return "paddleocr"; + default: return ""; + } +} +inline OCREngineType ocrEngineFromRaw(const std::string& raw) { + if (raw == "windows") { return OCREngineType::Windows; } + if (raw == "paddleocr") { return OCREngineType::PaddleOCR; } + // Cross-platform migration: Vision translates to Windows.Media.Ocr. + if (raw == "vision") { return OCREngineType::Windows; } + return OCREngineType::Invalid; +} + +} // namespace tf::core diff --git a/windows/Core/SceneEngineBinding.h b/windows/Core/SceneEngineBinding.h new file mode 100644 index 0000000..4437a98 --- /dev/null +++ b/windows/Core/SceneEngineBinding.h @@ -0,0 +1,78 @@ +#pragma once +// SceneEngineBinding.h — legacy scene→engine binding kept ONLY as the +// migration-source type (macOS marks it deprecated). New code uses +// EngineChainItem. Encoded as an array under "TransFrame.sceneBindings". +// +// Swift CodingKeys (alphabetical JSON): customPrompt, fallbackEnabled, +// fallbackEngine, primaryEngine, scene. + +#include "Json.h" +#include "TranslationEngineType.h" +#include "TranslationScene.h" + +#include +#include + +namespace tf::core { + +struct SceneEngineBinding { + TranslationScene scene = TranslationScene::Screenshot; + TranslationEngineType primaryEngine = TranslationEngineType::MtranServer; + std::optional fallbackEngine; + bool fallbackEnabled = true; + std::optional customPrompt; + + static SceneEngineBinding defaultFor(TranslationScene scene) { + // macOS default: apple + mtran fallback. Windows has no apple engine; + // the default primary becomes MTranServer (PRD §6.12). With MTranServer + // as primary, an OpenAI-compatible Custom instance is the fallback. + // TODO(schema-align): confirm the Windows default fallback engine with + // the task-C owner (macOS uses mtranServer here). + SceneEngineBinding b; + b.scene = scene; + b.primaryEngine = TranslationEngineType::MtranServer; + b.fallbackEngine = TranslationEngineType::Custom; + b.fallbackEnabled = true; + return b; + } + + void toJson(Json& j) const { + j = Json{{"scene", toRaw(scene)}, + {"primaryEngine", toRaw(primaryEngine)}, + {"fallbackEnabled", fallbackEnabled}}; + j["fallbackEngine"] = fallbackEngine ? Json(toRaw(*fallbackEngine)) : Json(); + j["customPrompt"] = customPrompt ? Json(*customPrompt) : Json(); + } + static SceneEngineBinding fromJson(const Json& j) { + SceneEngineBinding b; + const std::string sceneRaw = j.at("scene").get(); + b.scene = fromRaw(TranslationScene{}, sceneRaw); + if (b.scene == TranslationScene::Invalid) { + throw std::invalid_argument("unknown scene: " + sceneRaw); + } + const std::string primaryRaw = j.at("primaryEngine").get(); + b.primaryEngine = fromRaw(TranslationEngineType{}, primaryRaw); + if (b.primaryEngine == TranslationEngineType::Invalid) { + throw std::invalid_argument("unknown primaryEngine: " + primaryRaw); + } + if (auto raw = getOptional(j, "fallbackEngine")) { + const TranslationEngineType e = fromRaw(TranslationEngineType{}, *raw); + // macOS-written "apple" degrades to "no fallback" on Windows. + if (e != TranslationEngineType::Invalid) { b.fallbackEngine = e; } + } + b.fallbackEnabled = getOptionalOr(j, "fallbackEnabled", true); + b.customPrompt = getOptional(j, "customPrompt"); + return b; + } + + friend bool operator==(const SceneEngineBinding& a, const SceneEngineBinding& b) { + return a.scene == b.scene && a.primaryEngine == b.primaryEngine && + a.fallbackEngine == b.fallbackEngine && a.fallbackEnabled == b.fallbackEnabled && + a.customPrompt == b.customPrompt; + } +}; + +inline void to_json(Json& j, const SceneEngineBinding& b) { b.toJson(j); } +inline void from_json(const Json& j, SceneEngineBinding& b) { b = SceneEngineBinding::fromJson(j); } + +} // namespace tf::core diff --git a/windows/Core/SettingsKeys.h b/windows/Core/SettingsKeys.h new file mode 100644 index 0000000..df412da --- /dev/null +++ b/windows/Core/SettingsKeys.h @@ -0,0 +1,114 @@ +#pragma once +// SettingsKeys.h — every UserDefaults key used by the app, one-to-one with +// the Swift `AppSettings.Keys` enum (TransFrame/Models/AppSettings.swift). +// Windows persists to the same key names (ApplicationData settings container +// or registry under the same "TransFrame." prefix) so a settings export from +// macOS restores verbatim on Windows. +// +// Keys holding credentials (vlmAPIKey, paddleOCRCloudAPIKey) are stored in +// Credential Manager on Windows (Keychain on macOS); they are listed here +// for completeness but never written to the plaintext store. + +#include + +namespace tf::core { +namespace SettingsKeys { + +inline constexpr const char* kPrefix = "TransFrame."; + +// MARK: Capture / export +inline constexpr const char* saveLocation = "TransFrame.saveLocation"; +inline constexpr const char* defaultFormat = "TransFrame.defaultFormat"; +inline constexpr const char* jpegQuality = "TransFrame.jpegQuality"; +inline constexpr const char* heicQuality = "TransFrame.heicQuality"; + +// MARK: Shortcuts (keyCode/modifiers dictionaries on macOS) +inline constexpr const char* fullScreenShortcut = "TransFrame.fullScreenShortcut"; +inline constexpr const char* selectionShortcut = "TransFrame.selectionShortcut"; +inline constexpr const char* translationModeShortcut = "TransFrame.translationModeShortcut"; +inline constexpr const char* textSelectionTranslationShortcut = + "TransFrame.textSelectionTranslationShortcut"; +inline constexpr const char* translateAndInsertShortcut = "TransFrame.translateAndInsertShortcut"; + +// MARK: Annotation defaults +inline constexpr const char* strokeColor = "TransFrame.strokeColor"; +inline constexpr const char* strokeWidth = "TransFrame.strokeWidth"; +inline constexpr const char* textSize = "TransFrame.textSize"; +inline constexpr const char* rectangleFilled = "TransFrame.rectangleFilled"; +inline constexpr const char* ellipseFilled = "TransFrame.ellipseFilled"; +inline constexpr const char* shapeFillColor = "TransFrame.shapeFillColor"; +inline constexpr const char* mosaicBlockSize = "TransFrame.mosaicBlockSize"; + +// MARK: Translation languages +inline constexpr const char* translationTargetLanguage = "TransFrame.translationTargetLanguage"; +inline constexpr const char* translationSourceLanguage = "TransFrame.translationSourceLanguage"; +inline constexpr const char* translationAutoDetect = "TransFrame.translationAutoDetect"; + +// MARK: Engines / modes +inline constexpr const char* ocrEngine = "TransFrame.ocrEngine"; +inline constexpr const char* translationEngine = "TransFrame.translationEngine"; +inline constexpr const char* translationMode = "TransFrame.translationMode"; + +// MARK: Onboarding +inline constexpr const char* onboardingCompleted = "TransFrame.onboardingCompleted"; +inline constexpr const char* userSkippedPermissions = "TransFrame.userSkippedPermissions"; + +// MARK: PaddleOCR (local server) +inline constexpr const char* paddleOCRServerAddress = "TransFrame.paddleOCRServerAddress"; + +// MARK: MTranServer +inline constexpr const char* mtranServerHost = "TransFrame.mtranServerHost"; +inline constexpr const char* mtranServerPort = "TransFrame.mtranServerPort"; + +// MARK: VLM configuration +inline constexpr const char* vlmProvider = "TransFrame.vlmProvider"; +inline constexpr const char* vlmAPIKey = "TransFrame.vlmAPIKey"; // credential store +inline constexpr const char* vlmBaseURL = "TransFrame.vlmBaseURL"; +inline constexpr const char* vlmModelName = "TransFrame.vlmModelName"; +inline constexpr const char* vlmOpenAIMode = "TransFrame.vlmOpenAIMode"; +/// Per-provider suffix keys: "TransFrame.vlmBaseURL." / +/// "TransFrame.vlmModelName." (Swift Keys.vlmBaseURL(for:)). +inline std::string vlmBaseURLFor(const std::string& providerRaw) { + return std::string(kPrefix) + "vlmBaseURL." + providerRaw; +} +inline std::string vlmModelNameFor(const std::string& providerRaw) { + return std::string(kPrefix) + "vlmModelName." + providerRaw; +} + +// MARK: Translation workflow +inline constexpr const char* preferredTranslationEngine = "TransFrame.preferredTranslationEngine"; +inline constexpr const char* mtranServerURL = "TransFrame.mtranServerURL"; +inline constexpr const char* translationFallbackEnabled = "TransFrame.translationFallbackEnabled"; + +// MARK: Translate-and-insert languages +inline constexpr const char* translateAndInsertSourceLanguage = + "TransFrame.translateAndInsertSourceLanguage"; +inline constexpr const char* translateAndInsertTargetLanguage = + "TransFrame.translateAndInsertTargetLanguage"; + +// MARK: Multi-engine (legacy migration sources) +inline constexpr const char* engineSelectionMode = "TransFrame.engineSelectionMode"; +inline constexpr const char* engineConfigs = "TransFrame.engineConfigs"; +inline constexpr const char* promptConfig = "TransFrame.promptConfig"; +inline constexpr const char* sceneBindings = "TransFrame.sceneBindings"; +inline constexpr const char* parallelEngines = "TransFrame.parallelEngines"; +inline constexpr const char* compatibleProviderConfigs = "TransFrame.compatibleProviderConfigs"; + +// MARK: Engine selection V2 +inline constexpr const char* engineModeV2 = "TransFrame.engineModeV2"; +inline constexpr const char* engineChainV2 = "TransFrame.engineChainV2"; +inline constexpr const char* compareEnginesV2 = "TransFrame.compareEnginesV2"; + +// MARK: PaddleOCR mode / cloud +inline constexpr const char* paddleOCRMode = "TransFrame.paddleOCRMode"; +inline constexpr const char* paddleOCRUseCloud = "TransFrame.paddleOCRUseCloud"; +inline constexpr const char* paddleOCRCloudBaseURL = "TransFrame.paddleOCRCloudBaseURL"; +inline constexpr const char* paddleOCRCloudAPIKey = "TransFrame.paddleOCRCloudAPIKey"; // credential store +inline constexpr const char* paddleOCRCloudModelId = "TransFrame.paddleOCRCloudModelId"; +inline constexpr const char* paddleOCRLocalVLModelDir = "TransFrame.paddleOCRLocalVLModelDir"; + +// MARK: History (HistoryStore.defaultHistoryKey) +inline constexpr const char* translationHistory = "TransFrame.translationHistory"; + +} // namespace SettingsKeys +} // namespace tf::core diff --git a/windows/Core/Styles.h b/windows/Core/Styles.h new file mode 100644 index 0000000..74deb60 --- /dev/null +++ b/windows/Core/Styles.h @@ -0,0 +1,154 @@ +#pragma once +// Styles.h — CodableColor, StrokeStyle, TextStyle and overlay style models. +// The raw RGB defaults below were observed from NSColor(Color.*).deviceRGB +// on macOS. On Windows the UI layer may choose Fluent theme equivalents, but +// persisted values are platform-neutral doubles with the same field names. + +#include "Json.h" + +#include +#include +#include + +namespace tf::core { + +struct CodableColor { + double red = 0.0; + double green = 0.0; + double blue = 0.0; + double opacity = 1.0; + + static CodableColor redColor() { return {1.0, 0.25882354378700256, 0.2705882489681244, 1.0}; } + static CodableColor blueColor() { return {0.0, 0.5686274766921997, 1.0, 1.0}; } + static CodableColor greenColor() { return {0.1882352977991104, 0.8196078538894653, 0.34509801864624023, 1.0}; } + static CodableColor yellowColor() { return {1.0, 0.8392157554626465, 0.0, 1.0}; } + static CodableColor orangeColor() { return {1.0, 0.572549045085907, 0.1882352977991104, 1.0}; } + static CodableColor whiteColor() { return {1.0, 1.0, 1.0, 1.0}; } + static CodableColor blackColor() { return {0.0, 0.0, 0.0, 1.0}; } + + friend bool operator==(const CodableColor&, const CodableColor&) = default; + + void toJson(Json& j) const { + j = Json{{"red", red}, {"green", green}, {"blue", blue}, {"opacity", opacity}}; + } + static CodableColor fromJson(const Json& j) { + return {j.at("red").get(), j.at("green").get(), + j.at("blue").get(), j.at("opacity").get()}; + } +}; +inline void to_json(Json& j, const CodableColor& c) { c.toJson(j); } +inline void from_json(const Json& j, CodableColor& c) { c = CodableColor::fromJson(j); } + +struct StrokeStyle { + CodableColor color = CodableColor::redColor(); + double lineWidth = 2.0; + + bool isValid() const { return lineWidth >= 1.0 && lineWidth <= 20.0; } + StrokeStyle validated() const { return {color, std::clamp(lineWidth, 1.0, 20.0)}; } + friend bool operator==(const StrokeStyle&, const StrokeStyle&) = default; + + void toJson(Json& j) const { j = Json{{"color", color}, {"lineWidth", lineWidth}}; } + static StrokeStyle fromJson(const Json& j) { + return {j.at("color").get(), j.at("lineWidth").get()}; + } +}; +inline void to_json(Json& j, const StrokeStyle& s) { s.toJson(j); } +inline void from_json(const Json& j, StrokeStyle& s) { s = StrokeStyle::fromJson(j); } + +struct TextStyle { + CodableColor color = CodableColor::redColor(); + double fontSize = 14.0; + std::string fontName = ".AppleSystemUIFont"; + + bool isValid() const { return fontSize >= 8.0 && fontSize <= 72.0; } + TextStyle validated() const { return {color, std::clamp(fontSize, 8.0, 72.0), fontName}; } + friend bool operator==(const TextStyle&, const TextStyle&) = default; + + void toJson(Json& j) const { j = Json{{"color", color}, {"fontSize", fontSize}, {"fontName", fontName}}; } + static TextStyle fromJson(const Json& j) { + return {j.at("color").get(), j.at("fontSize").get(), + j.at("fontName").get()}; + } +}; +inline void to_json(Json& j, const TextStyle& s) { s.toJson(j); } +inline void from_json(const Json& j, TextStyle& s) { s = TextStyle::fromJson(j); } + +enum class FontWeight : int32_t { UltraLight, Thin, Light, Regular, Medium, Semibold, Bold, Heavy, Black }; +inline std::string toRaw(FontWeight w) { + switch (w) { + case FontWeight::UltraLight: return "ultraLight"; + case FontWeight::Thin: return "thin"; + case FontWeight::Light: return "light"; + case FontWeight::Regular: return "regular"; + case FontWeight::Medium: return "medium"; + case FontWeight::Semibold: return "semibold"; + case FontWeight::Bold: return "bold"; + case FontWeight::Heavy: return "heavy"; + case FontWeight::Black: return "black"; + default: return "regular"; + } +} +inline FontWeight fontWeightFromRaw(const std::string& raw) { + if (raw == "ultraLight") { return FontWeight::UltraLight; } + if (raw == "thin") { return FontWeight::Thin; } + if (raw == "light") { return FontWeight::Light; } + if (raw == "medium") { return FontWeight::Medium; } + if (raw == "semibold") { return FontWeight::Semibold; } + if (raw == "bold") { return FontWeight::Bold; } + if (raw == "heavy") { return FontWeight::Heavy; } + if (raw == "black") { return FontWeight::Black; } + return FontWeight::Regular; +} + +struct TranslationFont { + double size = 14.0; + FontWeight weight = FontWeight::Medium; + std::optional fontName; + + friend bool operator==(const TranslationFont&, const TranslationFont&) = default; + void toJson(Json& j) const { + j = Json{{"size", size}, {"weight", toRaw(weight)}}; + j["fontName"] = fontName ? Json(*fontName) : Json(); + } + static TranslationFont fromJson(const Json& j) { + return {j.at("size").get(), fontWeightFromRaw(j.at("weight").get()), + getOptional(j, "fontName")}; + } +}; +inline void to_json(Json& j, const TranslationFont& f) { f.toJson(j); } +inline void from_json(const Json& j, TranslationFont& f) { f = TranslationFont::fromJson(j); } + +struct EdgePadding { + double top = 4.0; + double leading = 8.0; + double bottom = 4.0; + double trailing = 8.0; + friend bool operator==(const EdgePadding&, const EdgePadding&) = default; + void toJson(Json& j) const { j = Json{{"top", top}, {"leading", leading}, {"bottom", bottom}, {"trailing", trailing}}; } + static EdgePadding fromJson(const Json& j) { + return {j.at("top").get(), j.at("leading").get(), + j.at("bottom").get(), j.at("trailing").get()}; + } +}; +inline void to_json(Json& j, const EdgePadding& p) { p.toJson(j); } +inline void from_json(const Json& j, EdgePadding& p) { p = EdgePadding::fromJson(j); } + +struct OverlayStyle { + TranslationFont translationFont; + CodableColor translationColor = CodableColor::whiteColor(); + CodableColor backgroundColor = {0.0, 0.0, 0.0, 0.75}; + EdgePadding padding; + friend bool operator==(const OverlayStyle&, const OverlayStyle&) = default; + void toJson(Json& j) const { + j = Json{{"translationFont", translationFont}, {"translationColor", translationColor}, + {"backgroundColor", backgroundColor}, {"padding", padding}}; + } + static OverlayStyle fromJson(const Json& j) { + return {j.at("translationFont").get(), j.at("translationColor").get(), + j.at("backgroundColor").get(), j.at("padding").get()}; + } +}; +inline void to_json(Json& j, const OverlayStyle& s) { s.toJson(j); } +inline void from_json(const Json& j, OverlayStyle& s) { s = OverlayStyle::fromJson(j); } + +} // namespace tf::core diff --git a/windows/Core/TransFrame.Core.vcxproj b/windows/Core/TransFrame.Core.vcxproj new file mode 100644 index 0000000..5935c44 --- /dev/null +++ b/windows/Core/TransFrame.Core.vcxproj @@ -0,0 +1,145 @@ + + + + + + Debugx64 + + + Releasex64 + + + DebugARM64 + + + ReleaseARM64 + + + + + {A0000000-0000-0000-0000-00000000000A} + Win32Proj + TransFrame + 10.0.26100.0 + + + + + + StaticLibrary + true + + $(DefaultPlatformToolset) + Unicode + + + + + + $(SolutionDir)build\$(Platform)\$(Configuration)\$(ProjectName)\ + $(SolutionDir)build\obj\$(Platform)\$(Configuration)\$(ProjectName)\ + $(ProjectDir);$(ProjectDir)include;$(ProjectDir)..\external;$(IncludePath) + + + + + stdcpp20 + Level4 + true + true + true + _UNICODE;UNICODE;%(PreprocessorDefinitions) + ProgramDatabase + MaxSpeed + true + true + MultiThreadedDebugDLL + MultiThreadedDLL + Sync + /Zc:__cplusplus /utf-8 %(AdditionalOptions) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + $(IntDir)src\ + + + + + diff --git a/windows/Core/TranslationEngineConfig.h b/windows/Core/TranslationEngineConfig.h new file mode 100644 index 0000000..02463f5 --- /dev/null +++ b/windows/Core/TranslationEngineConfig.h @@ -0,0 +1,107 @@ +#pragma once +// TranslationEngineConfig.h — per-engine configuration +// (macOS TranslationEngineConfig.swift). Encoded as an array of objects in +// UserDefaults key "TransFrame.engineConfigs". + +#include "Json.h" +#include "TranslationEngineType.h" + +#include +#include +#include + +namespace tf::core { + +struct EngineOptions { + std::optional baseURL; + std::optional modelName; + std::optional timeout; // seconds + std::optional maxTokens; + std::optional temperature; // 0.0 - 2.0 + std::optional> customHeaders; + + friend bool operator==(const EngineOptions&, const EngineOptions&) = default; + + void toJson(Json& j) const { + j = Json::object(); + if (baseURL) { j["baseURL"] = *baseURL; } + if (modelName) { j["modelName"] = *modelName; } + if (timeout) { j["timeout"] = *timeout; } + if (maxTokens) { j["maxTokens"] = *maxTokens; } + if (temperature) { j["temperature"] = *temperature; } + if (customHeaders) { + Json headers = Json::object(); + for (const auto& [k, v] : *customHeaders) { headers[k] = v; } + j["customHeaders"] = std::move(headers); + } + } + static EngineOptions fromJson(const Json& j) { + EngineOptions o; + o.baseURL = getOptional(j, "baseURL"); + o.modelName = getOptional(j, "modelName"); + o.timeout = getOptional(j, "timeout"); + o.maxTokens = getOptional(j, "maxTokens"); + o.temperature = getOptional(j, "temperature"); + if (auto it = j.find("customHeaders"); it != j.end() && it->is_object()) { + std::map headers; + for (auto h = it->begin(); h != it->end(); ++h) { + if (h.value().is_string()) { headers[h.key()] = h.value().get(); } + } + o.customHeaders = std::move(headers); + } + return o; + } +}; + +inline void to_json(Json& j, const EngineOptions& o) { o.toJson(j); } +inline void from_json(const Json& j, EngineOptions& o) { o = EngineOptions::fromJson(j); } + +struct TranslationEngineConfig { + TranslationEngineType id = TranslationEngineType::MtranServer; + bool isEnabled = false; + std::optional options; + /// Custom display name; for .custom engines macOS smuggles the serialized + /// CompatibleConfig JSON here (kept verbatim for migration compatibility). + std::optional customName; + + TranslationEngineConfig() = default; + TranslationEngineConfig(TranslationEngineType type, bool enabled = false, + std::optional opts = std::nullopt, + std::optional name = std::nullopt) + : id(type), isEnabled(enabled), options(std::move(opts)), customName(std::move(name)) {} + + /// macOS default: only the platform-native engine is enabled. On Windows + /// there is no Apple engine, so no engine is default-enabled; the first-run + /// onboarding forces a default chain choice instead (PRD §12 risk table). + static TranslationEngineConfig defaultFor(TranslationEngineType type) { + return TranslationEngineConfig(type, /*enabled=*/false, EngineOptions()); + } + + friend bool operator==(const TranslationEngineConfig&, + const TranslationEngineConfig&) = default; + + void toJson(Json& j) const { + j = Json{{"id", toRaw(id)}, {"isEnabled", isEnabled}}; + j["options"] = options ? Json(*options) : Json(); + j["customName"] = customName ? Json(*customName) : Json(); + } + static TranslationEngineConfig fromJson(const Json& j) { + TranslationEngineConfig c; + const std::string raw = j.at("id").get(); + c.id = fromRaw(TranslationEngineType{}, raw); + if (c.id == TranslationEngineType::Invalid) { + throw std::invalid_argument("unknown engine id: " + raw); + } + c.isEnabled = getOptionalOr(j, "isEnabled", false); + c.options = getOptional(j, "options"); + c.customName = getOptional(j, "customName"); + return c; + } +}; + +inline void to_json(Json& j, const TranslationEngineConfig& c) { c.toJson(j); } +inline void from_json(const Json& j, TranslationEngineConfig& c) { + c = TranslationEngineConfig::fromJson(j); +} + +} // namespace tf::core diff --git a/windows/Core/TranslationEngineType.h b/windows/Core/TranslationEngineType.h new file mode 100644 index 0000000..addf005 --- /dev/null +++ b/windows/Core/TranslationEngineType.h @@ -0,0 +1,104 @@ +#pragma once +// TranslationEngineType.h — translation engine inventory. +// +// Schema alignment with macOS TransFrame/Models/TranslationEngineType.swift: +// raw values identical; `.apple` intentionally ABSENT on Windows +// (PRD §6.12: no public system translation API; default chain head is +// MTranServer). JSON keys written by macOS that reference "apple" are +// tolerated on read (parse yields Invalid and the entry is dropped by the +// caller) so a settings file shared across platforms degrades gracefully. + +#include +#include + +namespace tf::core { + +enum class TranslationEngineType : int32_t { + MtranServer, // "mtran" — external MTranServer instance + OpenAI, // "openai" — GPT + Claude, // "claude" — Anthropic + Gemini, // "gemini" — Google Gemini + Ollama, // "ollama" — local LLM endpoint + Google, // "google" — Google Cloud Translation + DeepL, // "deepl" — DeepL API + Baidu, // "baidu" — Baidu Translate API + Custom, // "custom" — OpenAI-compatible instance + Invalid = -1, +}; + +namespace TranslationEngineTypes { +// Swift `allCases` order minus `.apple` (macOS: apple, mtran, openai, claude, +// gemini, ollama, google, deepl, baidu, custom). +constexpr TranslationEngineType kAll[] = { + TranslationEngineType::MtranServer, TranslationEngineType::OpenAI, + TranslationEngineType::Claude, TranslationEngineType::Gemini, + TranslationEngineType::Ollama, TranslationEngineType::Google, + TranslationEngineType::DeepL, TranslationEngineType::Baidu, + TranslationEngineType::Custom, +}; +constexpr size_t kCount = sizeof(kAll) / sizeof(kAll[0]); +} // namespace TranslationEngineTypes + +// Free functions so templates can use Enum::fromRaw via ADL-style helpers. +inline std::string toRaw(TranslationEngineType e) { + switch (e) { + case TranslationEngineType::MtranServer: return "mtran"; + case TranslationEngineType::OpenAI: return "openai"; + case TranslationEngineType::Claude: return "claude"; + case TranslationEngineType::Gemini: return "gemini"; + case TranslationEngineType::Ollama: return "ollama"; + case TranslationEngineType::Google: return "google"; + case TranslationEngineType::DeepL: return "deepl"; + case TranslationEngineType::Baidu: return "baidu"; + case TranslationEngineType::Custom: return "custom"; + default: return ""; + } +} + +inline TranslationEngineType fromRaw(TranslationEngineType, const std::string& raw) { + if (raw == "mtran") { return TranslationEngineType::MtranServer; } + if (raw == "openai") { return TranslationEngineType::OpenAI; } + if (raw == "claude") { return TranslationEngineType::Claude; } + if (raw == "gemini") { return TranslationEngineType::Gemini; } + if (raw == "ollama") { return TranslationEngineType::Ollama; } + if (raw == "google") { return TranslationEngineType::Google; } + if (raw == "deepl") { return TranslationEngineType::DeepL; } + if (raw == "baidu") { return TranslationEngineType::Baidu; } + if (raw == "custom") { return TranslationEngineType::Custom; } + return TranslationEngineType::Invalid; +} + +// Adapter shape used by forEachEnumKey. +struct TranslationEngineTypeAdapter { + using Enum = TranslationEngineType; + static std::optional fromRaw(const std::string& raw) { + const TranslationEngineType e = tf::core::fromRaw(TranslationEngineType{}, raw); + if (e == TranslationEngineType::Invalid) { return std::nullopt; } + return e; + } +}; + +/// Settings-page cards (macOS uiCards minus apple; `ollama` is configured via +/// the OpenAI-compatible card, `custom` via the dynamic instances section). +inline const TranslationEngineType* uiCards(size_t& count) { + static const TranslationEngineType cards[] = { + TranslationEngineType::MtranServer, TranslationEngineType::OpenAI, + TranslationEngineType::Claude, TranslationEngineType::Gemini, + TranslationEngineType::Google, TranslationEngineType::DeepL, + TranslationEngineType::Baidu, + }; + count = sizeof(cards) / sizeof(cards[0]); + return cards; +} + +inline bool requiresApiKey(TranslationEngineType e) { + switch (e) { + case TranslationEngineType::MtranServer: + case TranslationEngineType::Ollama: + return false; + default: + return true; // openai/claude/gemini/google/deepl/custom/baidu + } +} + +} // namespace tf::core diff --git a/windows/Core/TranslationHistory.cpp b/windows/Core/TranslationHistory.cpp new file mode 100644 index 0000000..1d8e9cb --- /dev/null +++ b/windows/Core/TranslationHistory.cpp @@ -0,0 +1,67 @@ +// TranslationHistory.cpp — JSON codec + matching. +#include "TranslationHistory.h" + +#include "TranslationResultBundle.h" + +#include +#include + +namespace tf::core { + +TranslationHistory TranslationHistory::fromTranslationResult( + const TranslationResult& result, std::vector thumbnail) { + TranslationHistory h; + h.id = Uuid::randomUuid(); + h.sourceText = result.sourceText; + h.translatedText = result.translatedText; + h.sourceLanguage = result.sourceLanguage; + h.targetLanguage = result.targetLanguage; + h.timestamp = result.timestamp; + if (!thumbnail.empty()) { h.thumbnailData = std::move(thumbnail); } + return h; +} + +namespace { +std::string lowercased(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return s; +} +} // namespace + +bool TranslationHistory::matches(const std::string& query) const { + if (query.empty()) { return true; } + const std::string q = lowercased(query); + return lowercased(sourceText).find(q) != std::string::npos || + lowercased(translatedText).find(q) != std::string::npos; +} + +// Swift CodingKeys order: id, sourceText, translatedText, sourceLanguage, +// targetLanguage, timestamp, thumbnailData, category, isFavorite. +// decodeIfPresent defaults: category -> translation, isFavorite -> false. +void to_json(Json& j, const TranslationHistory& h) { + j = Json{{"id", h.id}, + {"sourceText", h.sourceText}, + {"translatedText", h.translatedText}, + {"sourceLanguage", h.sourceLanguage}, + {"targetLanguage", h.targetLanguage}, + {"timestamp", h.timestamp}}; + j["thumbnailData"] = h.thumbnailData ? Json(*h.thumbnailData) : Json(); + j["category"] = toRaw(h.category); + j["isFavorite"] = h.isFavorite; +} + +void from_json(const Json& j, TranslationHistory& h) { + h.id = j.at("id").get(); + h.sourceText = j.at("sourceText").get(); + h.translatedText = j.at("translatedText").get(); + h.sourceLanguage = j.at("sourceLanguage").get(); + h.targetLanguage = j.at("targetLanguage").get(); + h.timestamp = getOptionalOr(j, "timestamp", TimePoint{}); + h.thumbnailData = getOptional>(j, "thumbnailData"); + const auto category = getOptional(j, "category"); + h.category = category ? historyCategoryFromRaw(*category) : HistoryCategory::Translation; + h.isFavorite = getOptionalOr(j, "isFavorite", false); +} + +} // namespace tf::core diff --git a/windows/Core/TranslationHistory.h b/windows/Core/TranslationHistory.h new file mode 100644 index 0000000..2d077ce --- /dev/null +++ b/windows/Core/TranslationHistory.h @@ -0,0 +1,135 @@ +#pragma once +// TranslationHistory.h — unified history model (macOS TranslationHistory.swift +// + HistoryStore.swift). Four categories share one record type: +// translation — sourceText=原文, translatedText=译文, langs=语言名 +// screenshot — sourceText=描述, translatedText=文件路径, langs=描述字段 +// color — sourceText="Color Picked", translatedText=hex, +// sourceLanguage="RGB Hex", targetLanguage=hex (同值) +// upload — sourceText=markdown, translatedText=URL, +// sourceLanguage=provider.displayName, targetLanguage="Public URL" +// +// Persisted as a JSON array under SettingsKeys::translationHistory +// ("TransFrame.translationHistory"); thumbnailData is base64 (max ~10KB JPEG). + +#include "Json.h" +#include "Uuid.h" + +#include +#include +#include + +namespace tf::core { + +enum class HistoryCategory : int32_t { + Translation, // "translation" + Screenshot, // "screenshot" + Color, // "color" + Upload, // "upload" + Invalid = -1, +}; + +inline std::string toRaw(HistoryCategory c) { + switch (c) { + case HistoryCategory::Translation: return "translation"; + case HistoryCategory::Screenshot: return "screenshot"; + case HistoryCategory::Color: return "color"; + case HistoryCategory::Upload: return "upload"; + default: return ""; + } +} +inline HistoryCategory historyCategoryFromRaw(const std::string& raw) { + if (raw == "translation") { return HistoryCategory::Translation; } + if (raw == "screenshot") { return HistoryCategory::Screenshot; } + if (raw == "color") { return HistoryCategory::Color; } + if (raw == "upload") { return HistoryCategory::Upload; } + return HistoryCategory::Invalid; +} +inline const char* historyCategoryDisplayName(HistoryCategory c) { + switch (c) { + case HistoryCategory::Translation: return "Translation"; + case HistoryCategory::Screenshot: return "Screenshot"; + case HistoryCategory::Color: return "Color"; + case HistoryCategory::Upload: return "Upload"; + default: return ""; + } +} +/// SF Symbol name on macOS; Windows maps to Segoe Fluent Icon glyphs in the UI layer. +inline const char* historyCategorySymbolName(HistoryCategory c) { + switch (c) { + case HistoryCategory::Translation: return "character.book.closed"; + case HistoryCategory::Screenshot: return "camera.viewfinder"; + case HistoryCategory::Color: return "eyedropper"; + case HistoryCategory::Upload: return "icloud.and.arrow.up"; + default: return ""; + } +} + +struct TranslationHistory { + Uuid id; + std::string sourceText; + std::string translatedText; + std::string sourceLanguage; + std::string targetLanguage; + TimePoint timestamp{}; + std::optional> thumbnailData; // JPEG bytes + HistoryCategory category = HistoryCategory::Translation; + bool isFavorite = false; + + // MARK: factories (Swift extensions in HistoryStore.swift) + + static TranslationHistory fromTranslationResult(const struct TranslationResult& result, + std::vector thumbnail = {}); + /// Color-picked entry: translatedText/targetLanguage both carry the hex. + static TranslationHistory colorPicked(const std::string& hex) { + TranslationHistory h; + h.id = Uuid::randomUuid(); + h.sourceText = "Color Picked"; + h.translatedText = hex; + h.sourceLanguage = "RGB Hex"; + h.targetLanguage = hex; + h.category = HistoryCategory::Color; + return h; + } + /// Image-upload entry. + static TranslationHistory uploaded(const std::string& markdown, const std::string& url, + const std::string& providerName) { + TranslationHistory h; + h.id = Uuid::randomUuid(); + h.sourceText = markdown; + h.translatedText = url; + h.sourceLanguage = providerName; + h.targetLanguage = "Public URL"; + h.category = HistoryCategory::Upload; + return h; + } + /// Screenshot entry. + static TranslationHistory screenshotSaved(const std::string& description, + const std::string& filePath) { + TranslationHistory h; + h.id = Uuid::randomUuid(); + h.sourceText = description; + h.translatedText = filePath; + h.sourceLanguage = "Screenshot"; + h.targetLanguage = filePath; + h.category = HistoryCategory::Screenshot; + return h; + } + + // MARK: computed (Swift) + + bool hasThumbnail() const { return thumbnailData && !thumbnailData->empty(); } + std::string sourcePreview() const { + return sourceText.substr(0, std::min(sourceText.size(), 500)); + } + std::string description() const { return sourceLanguage + " → " + targetLanguage; } + /// Case-insensitive substring match over source+translated (Swift matches). + bool matches(const std::string& query) const; + + friend bool operator==(const TranslationHistory&, const TranslationHistory&) = default; +}; + +// ------------------------------------------------------------ JSON codec --- +void to_json(Json& j, const TranslationHistory& h); +void from_json(const Json& j, TranslationHistory& h); + +} // namespace tf::core diff --git a/windows/Core/TranslationPromptConfig.h b/windows/Core/TranslationPromptConfig.h new file mode 100644 index 0000000..657a3fd --- /dev/null +++ b/windows/Core/TranslationPromptConfig.h @@ -0,0 +1,143 @@ +#pragma once +// TranslationPromptConfig.h — prompt selection + template substitution. +// Priority and templates are byte-for-byte the macOS implementation in +// TransFrame/Models/TranslationPromptConfig.swift: +// scene-specific > compatible-specific > engine-specific > default. + +#include "Json.h" +#include "TranslationEngineType.h" +#include "TranslationScene.h" + +#include +#include +#include +#include + +namespace tf::core { + +struct TranslationPromptConfig { + std::map enginePrompts; + std::map compatibleEnginePrompts; + std::map scenePrompts; + + static constexpr const char* kDefaultPrompt = + "Translate the following text from {source_language} to {target_language}.\n" + "Provide only the translation without any explanations or additional text.\n\n" + "Text to translate:\n" + "{text}"; + static constexpr const char* kDefaultInsertPrompt = + "Translate the following text from {source_language} to {target_language}.\n" + "The translation will be inserted at the cursor position.\n" + "Provide only the translation without any explanations, formatting, or additional text.\n" + "Keep the translation concise and natural for the target language.\n\n" + "Text to translate:\n" + "{text}"; + + std::string promptPreview(TranslationEngineType engine, TranslationScene scene, + std::optional compatiblePromptID = std::nullopt) const { + if (auto it = scenePrompts.find(scene); it != scenePrompts.end() && !it->second.empty()) { + return it->second; + } + if (engine == TranslationEngineType::Custom && compatiblePromptID) { + if (auto it = compatibleEnginePrompts.find(*compatiblePromptID); + it != compatibleEnginePrompts.end() && !it->second.empty()) { + return it->second; + } + } + if (auto it = enginePrompts.find(engine); it != enginePrompts.end() && !it->second.empty()) { + return it->second; + } + return scene == TranslationScene::TranslateAndInsert ? kDefaultInsertPrompt : kDefaultPrompt; + } + + /// Resolve variables using Swift's sequential replacingOccurrences order. + /// Any placeholder-shaped text inside `sourceLanguage` or `targetLanguage` + /// is therefore also substituted by later passes, matching Swift semantics. + std::string resolvedPrompt(TranslationEngineType engine, TranslationScene scene, + const std::string& sourceLanguage, + const std::string& targetLanguage, + const std::string& text, + std::optional compatiblePromptID = std::nullopt) const { + std::string prompt = promptPreview(engine, scene, std::move(compatiblePromptID)); + replaceAll(prompt, "{source_language}", sourceLanguage); + replaceAll(prompt, "{target_language}", targetLanguage); + replaceAll(prompt, "{text}", text); + return prompt; + } + + bool hasCustomPrompts() const { + return !enginePrompts.empty() || !compatibleEnginePrompts.empty() || !scenePrompts.empty(); + } + void reset() { + enginePrompts.clear(); + compatibleEnginePrompts.clear(); + scenePrompts.clear(); + } + + friend bool operator==(const TranslationPromptConfig&, const TranslationPromptConfig&) = default; + + void toJson(Json& j) const { + Json engine = Json::array(); + for (const auto& [k, v] : enginePrompts) { + engine.push_back(toRaw(k)); + engine.push_back(v); + } + Json scene = Json::array(); + for (const auto& [k, v] : scenePrompts) { + scene.push_back(toRaw(k)); + scene.push_back(v); + } + Json compatible = Json::object(); + for (const auto& [k, v] : compatibleEnginePrompts) { compatible[k] = v; } + j = Json{{"enginePrompts", std::move(engine)}, + {"compatibleEnginePrompts", std::move(compatible)}, + {"scenePrompts", std::move(scene)}}; + } + + static TranslationPromptConfig fromJson(const Json& j) { + TranslationPromptConfig c; + if (auto it = j.find("enginePrompts"); it != j.end() && it->is_array()) { + for (size_t i = 0; i + 1 < it->size(); i += 2) { + if (!(*it)[i].is_string() || !(*it)[i + 1].is_string()) { continue; } + const TranslationEngineType e = fromRaw(TranslationEngineType{}, (*it)[i].get()); + if (e != TranslationEngineType::Invalid) { + c.enginePrompts[e] = (*it)[i + 1].get(); + } + } + } + if (auto it = j.find("compatibleEnginePrompts"); it != j.end() && it->is_object()) { + for (auto entry = it->begin(); entry != it->end(); ++entry) { + if (entry.value().is_string()) { + c.compatibleEnginePrompts[entry.key()] = entry.value().get(); + } + } + } + if (auto it = j.find("scenePrompts"); it != j.end() && it->is_array()) { + for (size_t i = 0; i + 1 < it->size(); i += 2) { + if (!(*it)[i].is_string() || !(*it)[i + 1].is_string()) { continue; } + const TranslationScene s = fromRaw(TranslationScene{}, (*it)[i].get()); + if (s != TranslationScene::Invalid) { + c.scenePrompts[s] = (*it)[i + 1].get(); + } + } + } + return c; + } + +private: + static void replaceAll(std::string& s, const std::string& from, const std::string& to) { + if (from.empty()) { return; } + size_t pos = 0; + while ((pos = s.find(from, pos)) != std::string::npos) { + s.replace(pos, from.size(), to); + pos += to.size(); + } + } +}; + +inline void to_json(Json& j, const TranslationPromptConfig& c) { c.toJson(j); } +inline void from_json(const Json& j, TranslationPromptConfig& c) { + c = TranslationPromptConfig::fromJson(j); +} + +} // namespace tf::core diff --git a/windows/Core/TranslationResultBundle.cpp b/windows/Core/TranslationResultBundle.cpp new file mode 100644 index 0000000..f73137d --- /dev/null +++ b/windows/Core/TranslationResultBundle.cpp @@ -0,0 +1,198 @@ +// TranslationResultBundle.cpp — method bodies + JSON codecs. +#include "TranslationResultBundle.h" + +#include + +namespace tf::core { + +// -------------------------------------------------------- TranslationResult -- +std::optional TranslationResult::combine( + const std::vector& results) { + if (results.empty()) { return std::nullopt; } + TranslationResult out; + out.sourceText = results.front().sourceText; + out.sourceLanguage = results.front().sourceLanguage; + out.targetLanguage = results.front().targetLanguage; + for (std::size_t i = 0; i < results.size(); ++i) { + out.translatedText += results[i].translatedText; + if (i + 1 < results.size()) { out.sourceText += "\n"; } + } + return out; +} + +void to_json(Json& j, const TranslationResult& r) { + j = Json{{"sourceText", r.sourceText}, + {"translatedText", r.translatedText}, + {"sourceLanguage", r.sourceLanguage}, + {"targetLanguage", r.targetLanguage}, + {"timestamp", r.timestamp}}; +} +void from_json(const Json& j, TranslationResult& r) { + r.sourceText = j.at("sourceText").get(); + r.translatedText = j.at("translatedText").get(); + r.sourceLanguage = j.at("sourceLanguage").get(); + r.targetLanguage = j.at("targetLanguage").get(); + r.timestamp = getOptionalOr(j, "timestamp", TimePoint{}); +} + +// -------------------------------------------------------- BilingualSegment -- +BilingualSegment BilingualSegment::fromResult(const TranslationResult& result) { + BilingualSegment s; + s.id = Uuid::randomUuid(); + TextSegment original; + original.id = Uuid::randomUuid(); + original.text = result.sourceText; + original.boundingBox = Rect::zero(); + original.confidence = 1.0f; + s.original = std::move(original); + s.translated = result.translatedText; + s.sourceLanguage = result.sourceLanguage; + s.targetLanguage = result.targetLanguage; + return s; +} + +BilingualSegment BilingualSegment::fromSegment(const TextSegment& segment, + const std::string& translatedText, + std::optional sourceLanguage, + std::string targetLanguage) { + BilingualSegment s; + s.id = segment.id; + s.original = segment; + s.translated = translatedText; + s.sourceLanguage = std::move(sourceLanguage); + s.targetLanguage = std::move(targetLanguage); + return s; +} + +void to_json(Json& j, const BilingualSegment& s) { + j = Json{{"id", s.id}, {"original", s.original}, {"translated", s.translated}, + {"targetLanguage", s.targetLanguage}}; + j["sourceLanguage"] = s.sourceLanguage ? Json(*s.sourceLanguage) : Json(); +} +void from_json(const Json& j, BilingualSegment& s) { + s.id = j.at("id").get(); + s.original = j.at("original").get(); + s.translated = j.at("translated").get(); + s.targetLanguage = j.at("targetLanguage").get(); + s.sourceLanguage = getOptional(j, "sourceLanguage"); +} + +// ----------------------------------------------------------- error category -- +const char* toRaw(TranslationErrorCategory c) { + switch (c) { + case TranslationErrorCategory::TranslationFailed: return "translationFailed"; + case TranslationErrorCategory::IncompleteResponse: return "incompleteResponse"; + case TranslationErrorCategory::RateLimited: return "rateLimited"; + case TranslationErrorCategory::AuthenticationFailed: return "authenticationFailed"; + case TranslationErrorCategory::NetworkError: return "networkError"; + case TranslationErrorCategory::EngineUnavailable: return "engineUnavailable"; + default: return "translationFailed"; + } +} +TranslationErrorCategory translationErrorFromRaw(const std::string& raw) { + if (raw == "incompleteResponse") { return TranslationErrorCategory::IncompleteResponse; } + if (raw == "rateLimited") { return TranslationErrorCategory::RateLimited; } + if (raw == "authenticationFailed") { return TranslationErrorCategory::AuthenticationFailed; } + if (raw == "networkError") { return TranslationErrorCategory::NetworkError; } + if (raw == "engineUnavailable") { return TranslationErrorCategory::EngineUnavailable; } + return TranslationErrorCategory::TranslationFailed; +} + +// ------------------------------------------------------------ EngineResult -- +void to_json(Json& j, const EngineResult& r) { + j = Json{{"engine", toRaw(r.engine)}, {"segments", r.segments}, + {"latency", r.latency}, {"id", r.id}}; + j["error"] = r.error ? Json{{"category", toRaw(r.error->category)}, + {"message", r.error->message}} + : Json(); + j["displayName"] = r.displayName ? Json(*r.displayName) : Json(); +} +void from_json(const Json& j, EngineResult& r) { + const std::string raw = j.at("engine").get(); + r.engine = fromRaw(TranslationEngineType{}, raw); + r.segments = j.at("segments").get>(); + r.latency = getOptionalOr(j, "latency", 0.0); + r.id = j.at("id").get(); + if (auto it = j.find("error"); it != j.end() && it->is_object()) { + EngineError e; + e.category = translationErrorFromRaw(it->at("category").get()); + e.message = it->at("message").get(); + r.error = std::move(e); + } + r.displayName = getOptional(j, "displayName"); +} + +// --------------------------------------------------- TranslationResultBundle -- +std::vector TranslationResultBundle::primaryResult() const { + for (const auto& r : results) { + if (r.engine == primaryEngine && r.isSuccess()) { return r.segments; } + } + for (const auto& r : results) { + if (r.isSuccess()) { return r.segments; } + } + return {}; +} + +bool TranslationResultBundle::hasErrors() const { + return std::any_of(results.begin(), results.end(), + [](const EngineResult& r) { return r.error.has_value(); }); +} + +bool TranslationResultBundle::allFailed() const { + return !results.empty() && + std::all_of(results.begin(), results.end(), + [](const EngineResult& r) { return r.error.has_value(); }); +} + +std::vector TranslationResultBundle::successfulEngines() const { + std::vector out; + for (const auto& r : results) { + if (r.isSuccess()) { out.push_back(r.engine); } + } + return out; +} + +std::vector TranslationResultBundle::failedEngines() const { + std::vector out; + for (const auto& r : results) { + if (!r.isSuccess()) { out.push_back(r.engine); } + } + return out; +} + +const EngineResult* TranslationResultBundle::resultFor(TranslationEngineType engine) const { + for (const auto& r : results) { + if (r.engine == engine) { return &r; } + } + return nullptr; +} + +const std::vector* TranslationResultBundle::segmentsFor( + TranslationEngineType engine) const { + const EngineResult* r = resultFor(engine); + return r ? &r->segments : nullptr; +} + +TranslationResultBundle TranslationResultBundle::single( + TranslationEngineType engine, std::vector segments, + std::optional scene) { + TranslationResultBundle b; + b.results.push_back(EngineResult(engine, std::move(segments), 0.0)); + b.primaryEngine = engine; + b.selectionMode = EngineSelectionMode::PrimaryWithFallback; + b.scene = scene; + return b; +} + +TranslationResultBundle TranslationResultBundle::failed(TranslationEngineType engine, + EngineError error, + std::optional scene) { + TranslationResultBundle b; + b.results.push_back(EngineResult::failed(engine, std::move(error))); + b.primaryEngine = engine; + b.selectionMode = EngineSelectionMode::PrimaryWithFallback; + b.scene = scene; + return b; +} + +} // namespace tf::core diff --git a/windows/Core/TranslationResultBundle.h b/windows/Core/TranslationResultBundle.h new file mode 100644 index 0000000..2fd0b20 --- /dev/null +++ b/windows/Core/TranslationResultBundle.h @@ -0,0 +1,182 @@ +#pragma once +// TranslationResultBundle.h — BilingualSegment + EngineResult + bundle +// (macOS BilingualSegment.swift / TranslationResultBundle.swift / +// TranslationResult.swift). Engine errors are carried as a string category +// (Swift uses arbitrary Error payloads; the cross-platform persistence layer +// only needs the category + message). + +#include "CaptureDocument.h" // TextSegment, Rect +#include "EngineSelectionV2.h" +#include "Json.h" +#include "TranslationEngineType.h" +#include "TranslationScene.h" +#include "Uuid.h" + +#include +#include +#include + +namespace tf::core { + +/// A single translation (macOS TranslationResult). +struct TranslationResult { + std::string sourceText; + std::string translatedText; + std::string sourceLanguage; + std::string targetLanguage; + TimePoint timestamp{}; + + std::string description() const { return sourceLanguage + " → " + targetLanguage; } + bool hasChanges() const { return sourceText != translatedText; } + static TranslationResult emptyFor(const std::string& text) { + TranslationResult r; + r.sourceText = text; + r.translatedText = text; + r.sourceLanguage = "Unknown"; + r.targetLanguage = "Unknown"; + return r; + } + /// Concatenates results (Swift combine): first langs, joined texts. + static std::optional combine(const std::vector& results); + + friend bool operator==(const TranslationResult&, const TranslationResult&) = default; +}; + +/// One bilingual overlay segment (macOS BilingualSegment). +struct BilingualSegment { + Uuid id; + TextSegment original; + std::string translated; + std::optional sourceLanguage; + std::string targetLanguage; + + const std::string& sourceText() const { return original.text; } + const Rect& boundingBox() const { return original.boundingBox; } + Rect pixelBoundingBox(const Size& imageSize) const { + return original.pixelBoundingBox(imageSize); + } + static BilingualSegment fromResult(const TranslationResult& result); + static BilingualSegment fromSegment(const TextSegment& segment, + const std::string& translatedText, + std::optional sourceLanguage, + std::string targetLanguage); + + friend bool operator==(const BilingualSegment&, const BilingualSegment&) = default; +}; + +/// Error categories mirror Swift TranslationProviderError cases. +enum class TranslationErrorCategory : int32_t { + TranslationFailed, + IncompleteResponse, + RateLimited, + AuthenticationFailed, + NetworkError, + EngineUnavailable, +}; + +const char* toRaw(TranslationErrorCategory c); +TranslationErrorCategory translationErrorFromRaw(const std::string& raw); + +struct EngineError { + TranslationErrorCategory category = TranslationErrorCategory::TranslationFailed; + std::string message; + + EngineError() = default; + EngineError(TranslationErrorCategory c, std::string msg) + : category(c), message(std::move(msg)) {} + + friend bool operator==(const EngineError&, const EngineError&) = default; +}; + +/// Result from one engine (macOS EngineResult; id generated at creation). +struct EngineResult { + TranslationEngineType engine = TranslationEngineType::MtranServer; + std::vector segments; + double latency = 0.0; + std::optional error; + Uuid id; + /// UI chip label for compatible instances (two instances must not both + /// render as "Custom" — PR #93). + std::optional displayName; + + EngineResult() : id(Uuid::randomUuid()) {} + EngineResult(TranslationEngineType engine_, std::vector segments_, + double latency_, std::optional error_ = std::nullopt, + std::optional name = std::nullopt) + : engine(engine_), + segments(std::move(segments_)), + latency(latency_), + error(std::move(error_)), + id(Uuid::randomUuid()), + displayName(std::move(name)) {} + + static EngineResult failed(TranslationEngineType engine, EngineError error, + double latency = 0.0) { + return EngineResult(engine, {}, latency, std::move(error)); + } + + bool isSuccess() const { return !error && !segments.empty(); } + + friend bool operator==(const EngineResult&, const EngineResult&) = default; +}; + +/// Legacy four-mode selection (migration source only; Swift EngineSelectionMode). +enum class EngineSelectionMode : int32_t { + PrimaryWithFallback, // "primary_fallback" + Parallel, // "parallel" + QuickSwitch, // "quick_switch" + SceneBinding, // "scene_binding" + Invalid = -1, +}; +inline std::string toRaw(EngineSelectionMode m) { + switch (m) { + case EngineSelectionMode::PrimaryWithFallback: return "primary_fallback"; + case EngineSelectionMode::Parallel: return "parallel"; + case EngineSelectionMode::QuickSwitch: return "quick_switch"; + case EngineSelectionMode::SceneBinding: return "scene_binding"; + default: return ""; + } +} +inline EngineSelectionMode engineSelectionModeFromRaw(const std::string& raw) { + if (raw == "primary_fallback") { return EngineSelectionMode::PrimaryWithFallback; } + if (raw == "parallel") { return EngineSelectionMode::Parallel; } + if (raw == "quick_switch") { return EngineSelectionMode::QuickSwitch; } + if (raw == "scene_binding") { return EngineSelectionMode::SceneBinding; } + return EngineSelectionMode::Invalid; +} + +/// Multi-engine bundle (macOS TranslationResultBundle). +struct TranslationResultBundle { + std::vector results; + TranslationEngineType primaryEngine = TranslationEngineType::MtranServer; + EngineSelectionMode selectionMode = EngineSelectionMode::PrimaryWithFallback; + std::optional scene; + TimePoint timestamp{}; + + /// Primary engine's segments, else first successful engine's. + std::vector primaryResult() const; + bool hasErrors() const; + bool allFailed() const; + std::vector successfulEngines() const; + std::vector failedEngines() const; + const EngineResult* resultFor(TranslationEngineType engine) const; + const std::vector* segmentsFor(TranslationEngineType engine) const; + + static TranslationResultBundle single(TranslationEngineType engine, + std::vector segments, + std::optional scene = std::nullopt); + static TranslationResultBundle failed(TranslationEngineType engine, EngineError error, + std::optional scene = std::nullopt); + + friend bool operator==(const TranslationResultBundle&, const TranslationResultBundle&) = default; +}; + +// ------------------------------------------------------------ JSON codecs --- +void to_json(Json& j, const BilingualSegment& s); +void from_json(const Json& j, BilingualSegment& s); +void to_json(Json& j, const EngineResult& r); +void from_json(const Json& j, EngineResult& r); +void to_json(Json& j, const TranslationResult& r); +void from_json(const Json& j, TranslationResult& r); + +} // namespace tf::core diff --git a/windows/Core/TranslationScene.h b/windows/Core/TranslationScene.h new file mode 100644 index 0000000..3076d05 --- /dev/null +++ b/windows/Core/TranslationScene.h @@ -0,0 +1,44 @@ +#pragma once +// TranslationScene.h — scenes for engine binding (macOS TranslationScene.swift). + +#include +#include + +namespace tf::core { + +enum class TranslationScene : int32_t { + Screenshot, // "screenshot" + TextSelection, // "text_selection" + TranslateAndInsert, // "translate_and_insert" + Invalid = -1, +}; + +inline std::string toRaw(TranslationScene s) { + switch (s) { + case TranslationScene::Screenshot: return "screenshot"; + case TranslationScene::TextSelection: return "text_selection"; + case TranslationScene::TranslateAndInsert: return "translate_and_insert"; + default: return ""; + } +} + +inline TranslationScene fromRaw(TranslationScene, const std::string& raw) { + if (raw == "screenshot") { return TranslationScene::Screenshot; } + if (raw == "text_selection") { return TranslationScene::TextSelection; } + if (raw == "translate_and_insert") { return TranslationScene::TranslateAndInsert; } + return TranslationScene::Invalid; +} + +inline std::optional sceneFromRaw(const std::string& raw) { + const TranslationScene s = fromRaw(TranslationScene{}, raw); + if (s == TranslationScene::Invalid) { return std::nullopt; } + return s; +} + +constexpr TranslationScene kAllScenes[] = { + TranslationScene::Screenshot, + TranslationScene::TextSelection, + TranslationScene::TranslateAndInsert, +}; + +} // namespace tf::core diff --git a/windows/Core/Uuid.h b/windows/Core/Uuid.h new file mode 100644 index 0000000..3aff6ff --- /dev/null +++ b/windows/Core/Uuid.h @@ -0,0 +1,133 @@ +#pragma once +// Uuid.h — RFC 4122 v4 UUIDs matching Swift Foundation's UUID semantics. +// +// Wire format (must stay byte-identical to macOS for cross-platform snapshots): +// - Text: UPPERCASE 8-4-4-4-12 (Swift `uuidString`, e.g. "E621E1F8-..."). +// - JSON: that exact uppercase string (Swift Codable default). +// +// Generation uses Windows BCryptGenRandom on MSVC targets and a std::random_device +// fallback elsewhere so the Core unit tests can also run under clangd/other hosts. + +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include +#ifndef _MSC_VER +#pragma comment(lib, "bcrypt.lib") // only meaningful on MSVC; guarded for clangd +#endif +#endif + +namespace tf::core { + +class Uuid { +public: + Uuid() noexcept : bytes_{} {} + + /// Parses "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; hex is case-insensitive, + /// braces are tolerated. Returns false on malformed input (no partial state). + static bool parse(std::string_view text, Uuid& out) noexcept { + // Strip optional braces. + if (!text.empty() && text.front() == '{' && text.back() == '}') { + text.remove_prefix(1); + text.remove_suffix(1); + } + int nibbleCount = 0; + std::array bytes{}; + for (char c : text) { + if (c == '-') { continue; } + if (nibbleCount >= 32) { return false; } + const int v = hexValue(c); + if (v < 0) { return false; } + bytes[nibbleCount / 2] = + static_cast((nibbleCount % 2 == 0) ? (v << 4) : (bytes[nibbleCount / 2] | v)); + ++nibbleCount; + } + if (nibbleCount != 32) { return false; } + out.bytes_ = bytes; + return true; + } + + /// Cryptographically random v4 UUID (matches UUID() on macOS). + static Uuid randomUuid() noexcept { + std::array bytes{}; + fillRandom(bytes.data(), bytes.size()); + bytes[6] = static_cast((bytes[6] & 0x0F) | 0x40); // version 4 + bytes[8] = static_cast((bytes[8] & 0x3F) | 0x80); // variant 10 + return Uuid(bytes); + } + + /// UPPERCASE canonical string (Swift-compatible). + std::string toString() const { + static const char* kHex = "0123456789ABCDEF"; + std::string s; + s.reserve(36); + for (size_t i = 0; i < bytes_.size(); ++i) { + if (i == 4 || i == 6 || i == 8 || i == 10) { s += '-'; } + s += kHex[bytes_[i] >> 4]; + s += kHex[bytes_[i] & 0xF]; + } + return s; + } + + bool isNull() const noexcept { + for (uint8_t b : bytes_) { + if (b != 0) { return false; } + } + return true; + } + + friend bool operator==(const Uuid& a, const Uuid& b) noexcept { return a.bytes_ == b.bytes_; } + friend bool operator!=(const Uuid& a, const Uuid& b) noexcept { return a.bytes_ != b.bytes_; } + friend bool operator<(const Uuid& a, const Uuid& b) noexcept { return a.bytes_ < b.bytes_; } + + const std::array& bytes() const noexcept { return bytes_; } + +private: + explicit Uuid(const std::array& b) noexcept : bytes_(b) {} + + static int hexValue(char c) noexcept { + if (c >= '0' && c <= '9') { return c - '0'; } + if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } + if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } + return -1; + } + + static void fillRandom(uint8_t* out, size_t n) noexcept { +#if defined(_WIN32) + // BCryptGenRandom never fails for system randomness in practice. + if (BCryptGenRandom(nullptr, out, static_cast(n), + BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) { + fallbackRandom(out, n); + } +#else + fallbackRandom(out, n); +#endif + } + + static void fallbackRandom(uint8_t* out, size_t n) noexcept { + // xorshift64* seeded per-call from random_device; only used off-Windows + // (tests/clangd). Uniqueness odds remain UUID-grade for this purpose. + static thread_local uint64_t state = [] { + std::random_device rd; + return (static_cast(rd()) << 32) | rd(); + }(); + for (size_t i = 0; i < n; ++i) { + state ^= state >> 12; + state ^= state << 25; + state ^= state >> 27; + out[i] = static_cast((state * 0x2545F4914F6CDD1DULL) >> 32); + } + } + + std::array bytes_; +}; + +} // namespace tf::core diff --git a/windows/Core/VLMProviderType.cpp b/windows/Core/VLMProviderType.cpp new file mode 100644 index 0000000..46b0309 --- /dev/null +++ b/windows/Core/VLMProviderType.cpp @@ -0,0 +1,22 @@ +// VLMProviderType.cpp — CompatibleConfig codec. +#include "VLMProviderType.h" + +namespace tf::core { + +void to_json(Json& j, const CompatibleConfig& c) { + j = Json{{"id", c.id}, + {"displayName", c.displayName}, + {"baseURL", c.baseURL}, + {"modelName", c.modelName}, + {"hasAPIKey", c.hasAPIKey}}; +} + +void from_json(const Json& j, CompatibleConfig& c) { + c.id = j.at("id").get(); + c.displayName = j.at("displayName").get(); + c.baseURL = j.at("baseURL").get(); + c.modelName = j.at("modelName").get(); + c.hasAPIKey = getOptionalOr(j, "hasAPIKey", false); +} + +} // namespace tf::core diff --git a/windows/Core/VLMProviderType.h b/windows/Core/VLMProviderType.h new file mode 100644 index 0000000..a1466df --- /dev/null +++ b/windows/Core/VLMProviderType.h @@ -0,0 +1,137 @@ +#pragma once +// VLMProviderType.h — VLM analysis providers + OpenAI API mode + compatible +// instance config (macOS VLMProviderType.swift + CompatibleConfig in +// CompatibleTranslationProvider.swift). + +#include "Json.h" +#include "Uuid.h" + +#include +#include +#include + +namespace tf::core { + +enum class VLMProviderType : int32_t { + OpenAI, // "openai" + Claude, // "claude" + Gemini, // "gemini" + Ollama, // "ollama" + PaddleOCR, // "paddleocr" + Invalid = -1, +}; + +inline std::string toRaw(VLMProviderType p) { + switch (p) { + case VLMProviderType::OpenAI: return "openai"; + case VLMProviderType::Claude: return "claude"; + case VLMProviderType::Gemini: return "gemini"; + case VLMProviderType::Ollama: return "ollama"; + case VLMProviderType::PaddleOCR: return "paddleocr"; + default: return ""; + } +} +inline VLMProviderType vlmProviderFromRaw(const std::string& raw) { + if (raw == "openai") { return VLMProviderType::OpenAI; } + if (raw == "claude") { return VLMProviderType::Claude; } + if (raw == "gemini") { return VLMProviderType::Gemini; } + if (raw == "ollama") { return VLMProviderType::Ollama; } + if (raw == "paddleocr") { return VLMProviderType::PaddleOCR; } + return VLMProviderType::Invalid; +} +inline const char* vlmProviderDisplayName(VLMProviderType p) { + switch (p) { + case VLMProviderType::OpenAI: return "OpenAI"; + case VLMProviderType::Claude: return "Claude"; + case VLMProviderType::Gemini: return "Gemini"; + case VLMProviderType::Ollama: return "本地模型"; + case VLMProviderType::PaddleOCR: return "PaddleOCR"; + default: return ""; + } +} +inline std::string vlmDefaultBaseURL(VLMProviderType p) { + switch (p) { + case VLMProviderType::OpenAI: return "https://api.openai.com/v1"; + case VLMProviderType::Claude: return "https://api.anthropic.com/v1"; + case VLMProviderType::Gemini: return "https://generativelanguage.googleapis.com/v1beta"; + case VLMProviderType::Ollama: return "http://localhost:11434"; + case VLMProviderType::PaddleOCR: return ""; + default: return ""; + } +} +inline std::string vlmDefaultModelName(VLMProviderType p) { + switch (p) { + case VLMProviderType::OpenAI: return "gpt-4o"; + case VLMProviderType::Claude: return "claude-sonnet-4-20250514"; + case VLMProviderType::Gemini: return "gemini-2.0-flash"; + case VLMProviderType::Ollama: return "llava"; + case VLMProviderType::PaddleOCR: return ""; + default: return ""; + } +} +inline bool vlmTypicallyRequiresAPIKey(VLMProviderType p) { + switch (p) { + case VLMProviderType::OpenAI: + case VLMProviderType::Claude: + case VLMProviderType::Gemini: + return true; + default: + return false; + } +} + +/// OpenAI API mode (chat completions vs responses API). +enum class OpenAIAPIMode : int32_t { Chat, Response, Invalid = -1 }; +inline std::string toRaw(OpenAIAPIMode m) { + if (m == OpenAIAPIMode::Chat) { return "chat"; } + if (m == OpenAIAPIMode::Response) { return "response"; } + return ""; +} +inline OpenAIAPIMode openAIAPIModeFromRaw(const std::string& raw) { + if (raw == "chat") { return OpenAIAPIMode::Chat; } + if (raw == "response") { return OpenAIAPIMode::Response; } + return OpenAIAPIMode::Invalid; +} + +/// PaddleOCR mode (fast: ocr command; precise: doc_parser VL-1.5). +enum class PaddleOCRMode : int32_t { Fast, Precise, Invalid = -1 }; +inline std::string toRaw(PaddleOCRMode m) { + if (m == PaddleOCRMode::Fast) { return "fast"; } + if (m == PaddleOCRMode::Precise) { return "precise"; } + return ""; +} +inline PaddleOCRMode paddleOCRModeFromRaw(const std::string& raw) { + if (raw == "fast") { return PaddleOCRMode::Fast; } + if (raw == "precise") { return PaddleOCRMode::Precise; } + return PaddleOCRMode::Invalid; +} + +/// One OpenAI-compatible instance (macOS CompatibleConfig). Persisted in the +/// SettingsKeys::compatibleProviderConfigs array; the nil UUID is the default. +struct CompatibleConfig { + Uuid id; + std::string displayName; + std::string baseURL; + std::string modelName; + bool hasAPIKey = false; + + static CompatibleConfig defaultConfig() { + CompatibleConfig c; + c.id = Uuid(); + c.displayName = "Custom"; + c.baseURL = "http://localhost:8000/v1"; + c.modelName = "default"; + c.hasAPIKey = false; + return c; + } + + /// Credential account: "custom:" (Swift keychainId). + std::string keychainId() const { return "custom:" + id.toString(); } + + friend bool operator==(const CompatibleConfig&, const CompatibleConfig&) = default; +}; + +void to_json(Json& j, const CompatibleConfig& c); +void from_json(const Json& j, CompatibleConfig& c); + +} // namespace tf::core diff --git a/windows/Core/VisualLineGrouping.cpp b/windows/Core/VisualLineGrouping.cpp new file mode 100644 index 0000000..c9de1f8 --- /dev/null +++ b/windows/Core/VisualLineGrouping.cpp @@ -0,0 +1,209 @@ +// VisualLineGrouping.cpp — pure port of Swift VisualLineGrouping.swift. +#include "VisualLineGrouping.h" + +#include +#include + +namespace tf::core { +namespace { + +/// Decode one UTF-8 code point at index i; advances i (invalid byte -> U+FFFD). +char32_t decodeUtf8(const std::string& s, std::size_t& i) { + const unsigned char c = static_cast(s[i]); + if (c < 0x80) { + ++i; + return c; + } + if ((c & 0xE0) == 0xC0 && i + 1 < s.size()) { + const char32_t cp = (static_cast(c & 0x1F) << 6) | (s[i + 1] & 0x3F); + i += 2; + return cp; + } + if ((c & 0xF0) == 0xE0 && i + 2 < s.size()) { + const char32_t cp = (static_cast(c & 0x0F) << 12) | + (static_cast(s[i + 1] & 0x3F) << 6) | + (s[i + 2] & 0x3F); + i += 3; + return cp; + } + if ((c & 0xF8) == 0xF0 && i + 3 < s.size()) { + const char32_t cp = (static_cast(c & 0x07) << 18) | + (static_cast(s[i + 1] & 0x3F) << 12) | + (static_cast(s[i + 2] & 0x3F) << 6) | + (s[i + 3] & 0x3F); + i += 4; + return cp; + } + ++i; + return 0xFFFD; +} + +char32_t lastCodePoint(const std::string& s) { + if (s.empty()) { return 0; } + std::size_t i = 0; + char32_t last = 0; + while (i < s.size()) { last = decodeUtf8(s, i); } + return last; +} + +char32_t firstCodePoint(const std::string& s) { + if (s.empty()) { return 0; } + std::size_t i = 0; + return decodeUtf8(s, i); +} + +Rect unionOf(const std::vector& boxes) { + Rect out = Rect::nullRect(); + for (const Rect& b : boxes) { out = out.unionWith(b); } + return out; +} + +} // namespace + +bool VisualLineGrouping::isCJK(char32_t c) { + return (c >= 0x4E00 && c <= 0x9FFF) || (c >= 0x3400 && c <= 0x4DBF) || + (c >= 0x3000 && c <= 0x303F) || (c >= 0xFF00 && c <= 0xFFEF); +} + +bool VisualLineGrouping::isIdentifierCharacter(char32_t c) { + return (c >= U'0' && c <= U'9') || (c >= U'A' && c <= U'Z') || (c >= U'a' && c <= U'z') || + c == U'_'; +} + +bool VisualLineGrouping::isIdentifierLike(const std::string& s) { + if (s.empty()) { return false; } + // Contains underscore, a digit anywhere, or an uppercase letter after the + // first character (camelCase / SCREAMING_CASE). "Name" doesn't qualify. + if (s.find('_') != std::string::npos) { return true; } + std::size_t i = 0; + bool first = true; + bool hasUpperAfterFirst = false; + while (i < s.size()) { + const char32_t c = decodeUtf8(s, i); + if (!first) { + if (c >= U'A' && c <= U'Z') { hasUpperAfterFirst = true; } + } + if (c >= U'0' && c <= U'9') { return true; } + first = false; + } + return hasUpperAfterFirst; +} + +bool VisualLineGrouping::belongsToSameLine(const TextSegment& fragment, + const std::vector& lineFragments) { + if (lineFragments.empty()) { return false; } + const Rect& box = fragment.boundingBox; + if (!(box.width > 0) || !(box.height > 0)) { return false; } + + // lineBox spans ONLY the existing line fragments (Swift union(of:)). + std::vector lineBoxes; + lineBoxes.reserve(lineFragments.size()); + for (const auto& f : lineFragments) { lineBoxes.push_back(f.boundingBox); } + const Rect lineBox = unionOf(lineBoxes); + if (!(lineBox.width > 0) || !(lineBox.height > 0)) { return false; } + + const double overlap = + std::min(box.maxY(), lineBox.maxY()) - std::max(box.minY(), lineBox.minY()); + if (!(overlap > 0) || + overlap / std::min(box.height, lineBox.height) < verticalOverlapThreshold) { + return false; + } + + const double gap = + std::max(0.0, std::max(box.minX(), lineBox.minX()) - std::min(box.maxX(), lineBox.maxX())); + const double averageHeight = (box.height + lineBox.height) / 2.0; + return gap <= horizontalGapFactor * averageHeight; +} + +std::optional VisualLineGrouping::mergedSegment( + const std::vector& fragments) { + if (fragments.empty()) { return std::nullopt; } + if (fragments.size() == 1) { return fragments.front(); } + + std::vector ordered = fragments; + std::sort(ordered.begin(), ordered.end(), [](const TextSegment& a, const TextSegment& b) { + return a.boundingBox.minX() < b.boundingBox.minX(); + }); + + std::string joinedText = ordered.front().text; + for (std::size_t i = 1; i < ordered.size(); ++i) { + const TextSegment& previous = ordered[i - 1]; + const TextSegment& next = ordered[i]; + const double gap = next.boundingBox.minX() - previous.boundingBox.maxX(); + const double referenceHeight = + std::min(previous.boundingBox.height, next.boundingBox.height); + const bool nearlyTouching = referenceHeight > 0 && gap <= referenceHeight * 0.25; + joinedText = joinText(joinedText, next.text, nearlyTouching); + } + + std::vector boxes; + boxes.reserve(ordered.size()); + bool anyEdited = false; + float confidenceSum = 0.0f; + for (const auto& f : ordered) { + boxes.push_back(f.boundingBox); + anyEdited = anyEdited || f.isUserEdited; + confidenceSum += f.confidence; + } + + TextSegment merged; + merged.text = std::move(joinedText); + merged.boundingBox = unionOf(boxes); + merged.confidence = confidenceSum / static_cast(ordered.size()); + merged.isUserEdited = anyEdited; + return merged; +} + +std::vector VisualLineGrouping::mergeLines(const std::vector& segments) { + if (segments.size() <= 1) { return segments; } + + std::vector sorted = segments; + std::sort(sorted.begin(), sorted.end(), [](const TextSegment& lhs, const TextSegment& rhs) { + const double lhsY = lhs.boundingBox.midY(); + const double rhsY = rhs.boundingBox.midY(); + if (std::abs(lhsY - rhsY) > 1e-6) { return lhsY < rhsY; } + return lhs.boundingBox.minX() < rhs.boundingBox.minX(); + }); + + std::vector> lines; + for (auto& segment : sorted) { + bool joined = false; + for (auto& line : lines) { + if (belongsToSameLine(segment, line)) { + line.push_back(segment); + joined = true; + break; + } + } + if (!joined) { lines.push_back({segment}); } + } + + std::vector out; + out.reserve(lines.size()); + for (const auto& line : lines) { + if (auto merged = mergedSegment(line)) { out.push_back(std::move(*merged)); } + } + return out; +} + +std::string VisualLineGrouping::joinText(const std::string& lhs, const std::string& rhs, + bool gluesDirectly) { + if (lhs.empty() || rhs.empty()) { return lhs + rhs; } + const char32_t last = lastCodePoint(lhs); + const char32_t first = firstCodePoint(rhs); + if (isCJK(last) && isCJK(first)) { return lhs + rhs; } + if (gluesDirectly && isIdentifierCharacter(last) && isIdentifierCharacter(first)) { + const bool lhsEndsUnderscore = !lhs.empty() && lhs.back() == '_'; + std::size_t start = 0; + decodeUtf8(rhs, start); // measure the first code point's byte length + const std::string firstCharUtf8 = rhs.substr(0, start); + const bool rhsStartsUnderscore = firstCharUtf8 == "_"; + if (lhsEndsUnderscore || rhsStartsUnderscore || + (isIdentifierLike(lhs) && isIdentifierLike(rhs))) { + return lhs + rhs; + } + } + return lhs + " " + rhs; +} + +} // namespace tf::core diff --git a/windows/Core/VisualLineGrouping.h b/windows/Core/VisualLineGrouping.h new file mode 100644 index 0000000..c654596 --- /dev/null +++ b/windows/Core/VisualLineGrouping.h @@ -0,0 +1,40 @@ +#pragma once +// VisualLineGrouping.h — pure port of Swift VisualLineGrouping.swift: +// merge OCR/VLM fragments that sit on the same visual line into complete +// line segments before translation. Identical thresholds; test vectors +// shared with TransFrameTests/VisualLineGroupingTests.swift. + +#include "CaptureDocument.h" + +#include +#include + +namespace tf::core { + +struct VisualLineGrouping { + /// Minimum Y-projection overlap (fraction of the shorter box height) for + /// a fragment to join a line. + static constexpr double verticalOverlapThreshold = 0.5; + /// Maximum horizontal gap between a fragment and the line it joins, as a + /// multiple of the average line height. + static constexpr double horizontalGapFactor = 3.0; + + /// Groups segments into visual lines, ordered top-to-bottom, left-to-right. + static std::vector mergeLines(const std::vector& segments); + + /// Joins two fragments: CJK-adjacent text glues directly; near-zero gap + /// between identifier-shaped fragments glues; everything else gets a + /// space (Swift joinText). + static std::string joinText(const std::string& lhs, const std::string& rhs, + bool gluesDirectly = false); + + // Internals exposed for tests (mirrors Swift's @testable visibility). + static bool isCJK(char32_t c); + static bool isIdentifierCharacter(char32_t c); + static bool isIdentifierLike(const std::string& s); + static bool belongsToSameLine(const TextSegment& fragment, + const std::vector& lineFragments); + static std::optional mergedSegment(const std::vector& fragments); +}; + +} // namespace tf::core diff --git a/windows/Core/include/tf/CloudProviders.hpp b/windows/Core/include/tf/CloudProviders.hpp new file mode 100644 index 0000000..5918c98 --- /dev/null +++ b/windows/Core/include/tf/CloudProviders.hpp @@ -0,0 +1,100 @@ +// tf/CloudProviders.hpp +// Google Cloud Translation v2 / DeepL / Baidu providers (ports of Swift +// GoogleTranslationProvider.swift, DeepLTranslationProvider.swift, +// BaiduTranslationProvider.swift). +#ifndef TF_CLOUD_PROVIDERS_HPP +#define TF_CLOUD_PROVIDERS_HPP + +#include "tf/TranslationProvider.hpp" + +namespace tf { + +// --------------------------------------------------------------------------- +/// Google Cloud Translation API v2: POST with ?key= query param; response +/// data.translations[0].translatedText. No free probe endpoint (Swift). +class GoogleTranslateProvider final : public ITranslationProvider { +public: + GoogleTranslateProvider(EngineConfig config, CredentialStorePtr credentials, + HttpTransportPtr transport); + + std::string id() const override { return "google"; } + std::string name() const override { return "Google Translate"; } + TranslationEngineType engineType() const override { return TranslationEngineType::Google; } + bool isAvailable() const override; + TranslationOutcome translate(const TranslateRequest& request) override; + std::optional verifyConnection(const CancellationToken&) override { + return std::nullopt; // no free probe (Swift health policy) + } + + static std::string mapLanguageCode(const std::string& code); // zh-Hant→zh-TW etc. + +private: + EngineConfig config_; + CredentialStorePtr credentials_; + HttpTransportPtr transport_; +}; + +// --------------------------------------------------------------------------- +/// DeepL: POST /v2/translate (free tier via custom baseURL), Authorization: +/// DeepL-Auth-Key ; response translations[0].text. Paid verify — no free +/// probe (Swift policy). +class DeepLProvider final : public ITranslationProvider { +public: + DeepLProvider(EngineConfig config, CredentialStorePtr credentials, HttpTransportPtr transport); + + std::string id() const override { return "deepl"; } + std::string name() const override { return "DeepL"; } + TranslationEngineType engineType() const override { return TranslationEngineType::DeepL; } + bool isAvailable() const override; + TranslationOutcome translate(const TranslateRequest& request) override; + std::optional verifyConnection(const CancellationToken&) override { + return std::nullopt; // verify would translate "1" (paid) — Swift policy + } + + /// Endpoint normalization: append /translate unless already present. + static std::string normalizeEndpoint(const std::string& baseURL); + /// DeepL language casing: source lower-case, target UPPER-case (API rule). + static std::string sourceCode(const std::string& code); + static std::string targetCode(const std::string& code); + +private: + EngineConfig config_; + CredentialStorePtr credentials_; + HttpTransportPtr transport_; +}; + +// --------------------------------------------------------------------------- +/// Baidu: GET with q/from/to/appid/salt/sign (MD5(appid+q+salt+key)); +/// response trans_result[].dst. Error codes: 54003 → quota (rate limit), +/// 54004 → auth. No free probe (Swift policy). +class BaiduProvider final : public ITranslationProvider { +public: + BaiduProvider(EngineConfig config, CredentialStorePtr credentials, HttpTransportPtr transport); + + std::string id() const override { return "baidu"; } + std::string name() const override { return "Baidu Translate"; } + TranslationEngineType engineType() const override { return TranslationEngineType::Baidu; } + bool isAvailable() const override; + TranslationOutcome translate(const TranslateRequest& request) override; + std::optional verifyConnection(const CancellationToken&) override { + return std::nullopt; // no free probe + } + + /// Language mapping (Swift mapLanguageCode): zh-Hant→cht, ja→jp, ko→kor, + /// fr→fra, es→spa. + static std::string mapLanguageCode(const std::string& code); + /// MD5 hex digest of the UTF-8 bytes (Baidu sign input string). + static std::string md5Hex(const std::string& input); + /// Salt generator surface for tests: sign = md5(appid + q + salt + key). + static std::string makeSign(const std::string& appid, const std::string& q, + const std::string& salt, const std::string& secretKey); + +private: + EngineConfig config_; + CredentialStorePtr credentials_; + HttpTransportPtr transport_; +}; + +} // namespace tf + +#endif // TF_CLOUD_PROVIDERS_HPP diff --git a/windows/Core/include/tf/CompatibleChatProvider.hpp b/windows/Core/include/tf/CompatibleChatProvider.hpp new file mode 100644 index 0000000..97326c1 --- /dev/null +++ b/windows/Core/include/tf/CompatibleChatProvider.hpp @@ -0,0 +1,57 @@ +// tf/CompatibleChatProvider.hpp +// OpenAI-compatible custom endpoint with UUID instance identity (port of +// Swift CompatibleTranslationProvider.swift): per-instance credential slot +// "custom:", keyless local endpoints, models-list free probe. +#ifndef TF_COMPATIBLE_CHAT_PROVIDER_HPP +#define TF_COMPATIBLE_CHAT_PROVIDER_HPP + +#include "tf/LLMTranslationCore.hpp" // Outcome +#include "tf/TranslationProvider.hpp" + +namespace tf { + +class CompatibleChatProvider final : public ITranslationProvider { +public: + CompatibleChatProvider(CompatibleConfig compatibleConfig, EngineConfig engineConfig, + CredentialStorePtr credentials, HttpTransportPtr transport); + + std::string id() const override { return compatible_.id; } // instance UUID + std::string name() const override { return compatible_.displayName; } + TranslationEngineType engineType() const override { return TranslationEngineType::Custom; } + bool isAvailable() const override; + TranslationOutcome translate(const TranslateRequest& request) override; + std::optional verifyConnection(const CancellationToken& token) override; + + /// Prompt-context identifier (Swift compatiblePromptIdentifier): the + /// instance UUID — prompt layer 2 keys on it. + std::string compatiblePromptIdentifier() const { return compatible_.id; } + const CompatibleConfig& compatibleConfig() const { return compatible_; } + + /// Endpoint builders (Swift): baseURL + /chat/completions, /models. + std::string translateEndpoint() const; + std::string verifyEndpoint() const; + + std::string buildPrompt(const std::string& combinedText, const std::string& sourceLanguage, + const std::string& targetLanguage, + const std::string& promptTemplate) const; + + /// Resolves the effective instance for the legacy "custom" slot: prefer a + /// serialized CompatibleConfig in engineConfig.customName, else the first + /// saved instance, else the default (Swift resolveConfigurationSnapshot). + static CompatibleConfig resolveConfigurationSnapshot( + const CompatibleConfig& requested, const std::vector& savedConfigs); + +private: + Outcome callApi(const std::string& prompt, + const StoredCredentials* credentials, + const CancellationToken& token); + + CompatibleConfig compatible_; + EngineConfig engineConfig_; + CredentialStorePtr credentials_; + HttpTransportPtr transport_; +}; + +} // namespace tf + +#endif // TF_COMPATIBLE_CHAT_PROVIDER_HPP diff --git a/windows/Core/include/tf/CoreModels.hpp b/windows/Core/include/tf/CoreModels.hpp new file mode 100644 index 0000000..11b2db6 --- /dev/null +++ b/windows/Core/include/tf/CoreModels.hpp @@ -0,0 +1,277 @@ +// tf/CoreModels.hpp +// Cross-platform Core models for the translation/OCR service layer (Task C). +// Schema mirrors macOS TransFrame/Models/*.swift one-to-one: +// TranslationEngineType.swift, EngineSelectionV2.swift, TranslationScene.swift, +// TranslationResult.swift, TranslationResultBundle.swift, BilingualSegment.swift, +// ScreenAnalysisResult.swift (TextSegment), OCREngineType.swift (no vision → +// windowsOcr), VLMProviderType.swift, AppSettings.swift (chain persistence). +// Platform-clean: no Win32/WinRT includes; Catch2 tests compile it directly. +#ifndef TF_CORE_MODELS_HPP +#define TF_CORE_MODELS_HPP + +#include +#include +#include +#include +#include +#include + +namespace tf { + +// --------------------------------------------------------------------------- +// UUID (RFC 4122 v4, std::mt19937_64 seeded from random_device; string form is +// the interop format — settings JSON and chain items key on it, same as Swift +// CompatibleConfig.id / EngineChainItem.id). +// --------------------------------------------------------------------------- +struct Uuid { + std::array bytes{}; + + static Uuid random(); + /// Parses "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; braces/urn prefix tolerated. + static std::optional parse(const std::string& text); + /// Nil UUID 00000000-0000-0000-0000-000000000000 (Swift CompatibleConfig.default id). + static Uuid nil(); + + bool isNil() const; + std::string toString() const; + bool operator==(const Uuid& o) const = default; +}; + +// --------------------------------------------------------------------------- +// Geo (normalized OCR space): doubles 0..1, top-left origin, Y grows down — +// same schema as macOS TextSegment.boundingBox / OCRText.boundingBox. +// --------------------------------------------------------------------------- +struct NormRect { + double x = 0, y = 0, width = 0, height = 0; + + double minX() const { return x; } + double minY() const { return y; } + double maxX() const { return x + width; } + double maxY() const { return y + height; } + double midX() const { return x + width / 2; } + double midY() const { return y + height / 2; } + + NormRect unionWith(const NormRect& o) const; + bool operator==(const NormRect& o) const = default; +}; + +/// One text fragment with a normalized bbox + confidence (Swift TextSegment). +struct TextSegment { + std::string id; // UUID string + std::string text; + NormRect boundingBox; + float confidence = 1.0f; + bool isUserEdited = false; + + TextSegment() = default; + TextSegment(std::string text_, NormRect box, float conf = 1.0f, bool edited = false); + static TextSegment make(std::string text, NormRect box, float conf = 1.0f); + bool isHighConfidence() const { return confidence > 0.7f; } +}; + +/// OCR output (Swift OCRResult): image size + observations sorted for fullText. +struct OcrResult { + std::vector observations; + std::int64_t imageWidth = 0; // physical px + std::int64_t imageHeight = 0; // physical px + std::int64_t timestampMs = 0; // epoch ms + + bool hasResults() const { return !observations.empty(); } + std::string fullText() const; + static OcrResult empty(std::int64_t w, std::int64_t h); +}; + +// --------------------------------------------------------------------------- +// Engines — NO apple (PRD §6.12: Apple Translation removed on Windows). +// Raw values must stay identical to the macOS enum strings ("mtran" etc.) so +// settings JSON is portable across platforms. +// --------------------------------------------------------------------------- +enum class TranslationEngineType : std::uint8_t { + MtranServer, // "mtran" + OpenAI, // "openai" + Claude, // "claude" + Gemini, // "gemini" + Ollama, // "ollama" + Google, // "google" + DeepL, // "deepl" + Baidu, // "baidu" + Custom, // "custom" (OpenAI-compatible instance) +}; + +/// All engines, settings-page order (Swift TranslationEngineType.uiCards minus apple). +std::vector allTranslationEngines(); + +const char* translationEngineRaw(TranslationEngineType t); // "mtran" ... +std::optional translationEngineFromRaw(const std::string& raw); +const char* translationEngineDisplayName(TranslationEngineType t); // "MTranServer", "OpenAI", ... + +/// Requires a stored API key (Swift TranslationEngineType.requiresAPIKey minus apple). +bool translationEngineRequiresApiKey(TranslationEngineType t); +/// Requires an AppID alongside the key (Baidu). +bool translationEngineRequiresAppId(TranslationEngineType t); +/// Default base URL (Swift defaultBaseURL minus apple). +std::string translationEngineDefaultBaseUrl(TranslationEngineType t); +/// Default model name (Swift defaultModelName minus apple). +std::string translationEngineDefaultModelName(TranslationEngineType t); + +// --------------------------------------------------------------------------- +// Selection model V2 (Swift EngineSelectionV2.swift, verbatim semantics). +// --------------------------------------------------------------------------- +struct EngineChainItem { + /// Kind: builtin engine or compatible-instance UUID. + enum class Kind { Builtin, Compatible }; + Kind kind = Kind::Builtin; + TranslationEngineType builtin = TranslationEngineType::MtranServer; + std::string compatibleId; // UUID string when kind == Compatible + + std::string id; // unique entry identity (same engine may appear twice) + + static EngineChainItem makeBuiltin(TranslationEngineType t); + static EngineChainItem makeCompatible(const std::string& uuid); + /// The builtin engine this entry reports as (compatible → Custom, Swift resolvedEngine). + TranslationEngineType resolvedEngine() const; + bool operator==(const EngineChainItem& o) const = default; +}; + +/// Structural limits (Swift EngineSelectionLimits). +struct EngineSelectionLimits { + static constexpr int orderedChainLimit = 5; + static constexpr int compareEnginesLimit = 4; + static constexpr int compareEnginesMinimum = 2; +}; + +enum class TranslationScene { Screenshot, TextSelection, TranslateAndInsert }; +const char* translationSceneRaw(TranslationScene s); // "screenshot" ... +std::optional translationSceneFromRaw(const std::string& raw); + +// --------------------------------------------------------------------------- +// Prompt config (Swift TranslationPromptConfig.swift): three overlay layers +// engine < compatible-instance < scene; placeholder substitution shared with +// providers. +// --------------------------------------------------------------------------- +struct TranslationPromptConfig { + std::vector> enginePrompts; + std::vector> compatibleEnginePrompts; // key: instance UUID + std::vector> scenePrompts; + + /// Default screenshot/text prompt (Swift TranslationPromptConfig.defaultPrompt). + static const std::string& defaultPrompt(); + /// Insert-scene default: concise, no formatting (Swift defaultInsertPrompt). + static const std::string& defaultInsertPrompt(); + + /// Layered resolution exactly as Swift promptPreview: engine → compatible → + /// scene → insert-scene default (TranslateAndInsert) → default. + std::string resolve(TranslationEngineType engine, + TranslationScene scene, + const std::string& compatiblePromptId = "") const; + + /// {source_language}/{target_language}/{text} substitution. + static std::string substitute(const std::string& templateText, + const std::string& sourceLanguage, + const std::string& targetLanguage, + const std::string& text); +}; + +// --------------------------------------------------------------------------- +// Translation results (Swift TranslationResult / EngineResult / Bundle). +// --------------------------------------------------------------------------- +struct TranslationResult { + std::string sourceText; + std::string translatedText; + std::string sourceLanguage; // "Auto" when detected/absent (Swift behavior) + std::string targetLanguage; + + TranslationResult() = default; + TranslationResult(std::string src, std::string translated, + std::string srcLang, std::string tgtLang); +}; + +/// Bilingual pair bound to a TextSegment anchor (Swift BilingualSegment). +struct BilingualSegment { + std::string id; + TextSegment original; + std::string translated; + std::string sourceLanguage; + std::string targetLanguage; + + BilingualSegment() = default; + /// From a plain TranslationResult (empty bbox, confidence 1.0 — Swift init(from:)). + static BilingualSegment fromResult(const TranslationResult& r); +}; + +/// One engine's outcome inside a chain/compare run (Swift EngineResult). +struct EngineResult { + TranslationEngineType engine = TranslationEngineType::MtranServer; + std::vector segments; + double latencySeconds = 0.0; + bool failed = false; + std::string errorText; // short per-engine failure reason + std::string displayName; // compatible-instance display name for UI chips + + bool isSuccess() const { return !failed && !segments.empty(); } + static EngineResult makeFailure(TranslationEngineType engine, std::string errorText, + double latency = 0.0, std::string displayName = ""); +}; + +/// Selection mode recorded on the bundle (Swift maps ordered/compare onto the +/// legacy EngineSelectionMode storage: ordered → PrimaryWithFallback, +/// compare → Parallel). +enum class EngineSelectionMode { PrimaryWithFallback, Parallel }; + +/// Whole-run outcome (Swift TranslationResultBundle). +struct TranslationResultBundle { + std::vector results; + TranslationEngineType primaryEngine = TranslationEngineType::MtranServer; + EngineSelectionMode selectionMode = EngineSelectionMode::PrimaryWithFallback; + int scene = -1; // TranslationScene index or -1 + + std::vector successfulEngines() const; +}; + +// --------------------------------------------------------------------------- +// VLM provider types (Swift VLMProviderType.swift). +// --------------------------------------------------------------------------- +enum class VlmProviderType : std::uint8_t { OpenAI, Claude, Gemini, Ollama, PaddleOCR }; +const char* vlmProviderRaw(VlmProviderType t); +std::optional vlmProviderFromRaw(const std::string& raw); + +/// OCR engine selector on Windows (Swift OCREngineType: vision → windowsOcr). +enum class OcrEngineType : std::uint8_t { WindowsOcr, PaddleOCR }; +const char* ocrEngineRaw(OcrEngineType t); + +// --------------------------------------------------------------------------- +// Errors (Swift TranslationProviderError minus localization). +// ErrorCategory is the WinHTTP-layer classification the brief requires: +// network / quota / auth / content — every provider maps its failures onto it. +// --------------------------------------------------------------------------- +enum class ErrorCategory { + Network, // unreachable, timeout, cancelled transport + Quota, // 429 / rate-limited / insufficient quota + Auth, // 401/403, invalid key, bad signature + Content, // malformed/unexpected response body, empty translation + Configuration // invalid base URL, missing credential +}; + +const char* errorCategoryName(ErrorCategory c); + +struct ProviderError { + ErrorCategory category = ErrorCategory::Network; + std::string message; + std::optional retryAfterSeconds; // quota errors when known + + ProviderError() = default; + ProviderError(ErrorCategory c, std::string msg) : category(c), message(std::move(msg)) {} + static ProviderError network(std::string msg) { return {ErrorCategory::Network, std::move(msg)}; } + static ProviderError quota(std::string msg, std::optional retryAfter = std::nullopt) { + ProviderError e{ErrorCategory::Quota, std::move(msg)}; + e.retryAfterSeconds = retryAfter; + return e; + } + static ProviderError auth(std::string msg) { return {ErrorCategory::Auth, std::move(msg)}; } + static ProviderError content(std::string msg) { return {ErrorCategory::Content, std::move(msg)}; } + static ProviderError configuration(std::string msg) { return {ErrorCategory::Configuration, std::move(msg)}; } +}; + +} // namespace tf + +#endif // TF_CORE_MODELS_HPP diff --git a/windows/Core/include/tf/EngineHealthChecker.hpp b/windows/Core/include/tf/EngineHealthChecker.hpp new file mode 100644 index 0000000..5c9f52e --- /dev/null +++ b/windows/Core/include/tf/EngineHealthChecker.hpp @@ -0,0 +1,129 @@ +// tf/EngineHealthChecker.hpp +// Four-state health probing for settings-page engine cards (brief §4, PRD +// FR-22; port of Swift EngineHealthChecker.swift). Pure logic: probes run on +// the injected transport; the 60s cache semantics mirror macOS exactly. +#ifndef TF_ENGINE_HEALTH_CHECKER_HPP +#define TF_ENGINE_HEALTH_CHECKER_HPP + +#include "tf/CoreModels.hpp" +#include "tf/HttpTransport.hpp" +#include "tf/TranslationProvider.hpp" + +#include +#include +#include +#include +#include + +namespace tf { + +/// Four-state health (Swift EngineHealth; `checking` is a UI transition +/// state and lives in the UI layer, not here). +enum class EngineHealth { + Available, // green — probe succeeded + Misconfigured, // red — probe failed; reason carries a short message + Unconfigured, // orange — missing credentials/required fields; no probe sent + Unverified, // gray — configured but no free probe endpoint exists +}; + +inline const char* engineHealthName(EngineHealth h) { + switch (h) { + case EngineHealth::Available: return "green"; + case EngineHealth::Misconfigured: return "red"; + case EngineHealth::Unconfigured: return "orange"; + case EngineHealth::Unverified: return "gray"; + } + return "gray"; +} + +/// Health key: builtin engines by type; compatible instances by UUID +/// (Swift EngineHealthKey). +struct EngineHealthKey { + bool isBuiltin = true; + TranslationEngineType builtin = TranslationEngineType::MtranServer; + std::string compatibleId; // UUID when !isBuiltin + + static EngineHealthKey forBuiltin(TranslationEngineType t) { + EngineHealthKey k; + k.isBuiltin = true; + k.builtin = t; + return k; + } + static EngineHealthKey forCompatible(const std::string& uuid) { + EngineHealthKey k; + k.isBuiltin = false; + k.compatibleId = uuid; + return k; + } + std::string display() const { + return isBuiltin ? std::string(translationEngineRaw(builtin)) : "custom:" + compatibleId; + } + bool operator<(const EngineHealthKey& o) const { + if (isBuiltin != o.isBuiltin) return isBuiltin < o.isBuiltin; + if (isBuiltin) return builtin < o.builtin; + return compatibleId < o.compatibleId; + } + bool operator==(const EngineHealthKey& o) const = default; +}; + +/// Probe seam: one probe per key. Implementations MUST use only free +/// endpoints (MTranServer /health, LLM models list) — never billed +/// translation calls (PRD FR-22). +class IEngineProbe { +public: + virtual ~IEngineProbe() = default; + virtual EngineHealth probe(const EngineHealthKey& key, const CancellationToken& token) = 0; +}; + +/// Probe implementation over the shared transport + credential store + +/// provider factories (mirrors Swift probe(_:) switch semantics minus apple). +class DefaultEngineProbe : public IEngineProbe { +public: + DefaultEngineProbe(CredentialStorePtr credentials, HttpTransportPtr transport, + std::function()> compatibleConfigs); + + EngineHealth probe(const EngineHealthKey& key, const CancellationToken& token) override; + +private: + CredentialStorePtr credentials_; + HttpTransportPtr transport_; + std::function()> compatibleConfigs_; +}; + +/// Cache + dispatcher (Swift EngineHealthChecker actor semantics; here a +/// mutex-guarded object). TTL 60s, injectable clock for tests. +class EngineHealthChecker { +public: + explicit EngineHealthChecker(std::shared_ptr probe, double ttlSeconds = 60.0, + std::function clock = nullptr); + + /// Cached health; refreshes when stale or absent (Swift health(for:)). + EngineHealth health(const EngineHealthKey& key, const CancellationToken& token = {}); + /// Force a probe bypassing the cache (Swift refresh(_:)). + EngineHealth refresh(const EngineHealthKey& key, const CancellationToken& token = {}); + /// Drop all cached entries (config save) (Swift invalidateAll()). + void invalidateAll(); + + // Test seams. + void overrideClock(std::function clock); + void injectHealth(const EngineHealthKey& key, EngineHealth health, double at); + +private: + std::shared_ptr probe_; + double ttl_; + std::function clock_; + std::mutex mutex_; + struct Entry { + EngineHealth health; + std::string reason; + double at; + }; + std::map cache_; +}; + +/// Reasons ride alongside Misconfigured (Swift payload); helper for probes. +std::string shortReason(const std::optional& error); + +} // namespace tf + +#endif // TF_ENGINE_HEALTH_CHECKER_HPP diff --git a/windows/Core/include/tf/HttpTransport.hpp b/windows/Core/include/tf/HttpTransport.hpp new file mode 100644 index 0000000..81822f7 --- /dev/null +++ b/windows/Core/include/tf/HttpTransport.hpp @@ -0,0 +1,143 @@ +// tf/HttpTransport.hpp +// HTTP contract shared by every translation/OCR/VLM provider on Windows. +// The interface lives in Core (no UI dependency, per brief: "HTTP 层不依赖 +// UI 框架,可被测试直接驱动"). The WinHTTP implementation lives in +// NativeShell/src/WinHttpTransport.cpp and implements the same header on real +// Win32; tests inject MockHttpTransport. +// +// Semantics ported from the Swift layer: +// - default timeout 10s (TranslationEngineConfig.timeout, MTranServer 10s) +// - cooperative cancellation via CancellationToken (Swift Task.cancel / +// PRD FR-62 "引擎请求全部可取消") +// - error classification: network / quota / auth / content (brief §2) +#ifndef TF_HTTP_TRANSPORT_HPP +#define TF_HTTP_TRANSPORT_HPP + +#include "tf/CoreModels.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tf { + +/// Cooperative cancellation: one shared flag; cancelled() is polled by the +/// transport between WinHTTP waits (Swift Task.isCancelled analogue). +class CancellationToken { +public: + struct State { + std::atomic cancelled{false}; + }; + + CancellationToken() : state_(std::make_shared()) {} + + void cancel() { state_->cancelled.store(true, std::memory_order_relaxed); } + bool cancelled() const { return state_->cancelled.load(std::memory_order_relaxed); } + + /// Allows "already cancelled" tokens to be constructed in tests. + static CancellationToken alreadyCancelled() { + CancellationToken t; + t.cancel(); + return t; + } + +private: + std::shared_ptr state_; +}; + +struct HttpRequest { + std::string method = "GET"; + std::string url; // absolute http(s) URL + std::map headers; + std::string body; // raw bytes (UTF-8 JSON) + int timeoutSeconds = 10; // brief: 超时默认 10s + CancellationToken cancelToken; +}; + +struct HttpResponse { + int status = 0; // HTTP status; 0 = transport-level failure + std::map headers; // lower-cased keys + std::string body; + + bool ok() const { return status >= 200 && status < 300; } +}; + +/// Transport-level outcome: response OR ProviderError. Cancelled requests map +/// to ErrorCategory::Network with message "cancelled" — callers that need to +/// distinguish (ordered chain must not grind on) compare the message, matching +/// Swift's CancellationError rethrow semantics. +struct HttpOutcome { + std::optional response; + std::optional error; + + static HttpOutcome ok(HttpResponse r) { return HttpOutcome{std::move(r), std::nullopt}; } + static HttpOutcome fail(ProviderError e) { return HttpOutcome{std::nullopt, std::move(e)}; } + bool isCancelled() const { + return error.has_value() && error->category == ErrorCategory::Network && + error->message == "cancelled"; + } +}; + +/// Abstract HTTP facade. WinHttpTransport (NativeShell) is the production +/// implementation; tests provide mocks. All calls are blocking with internal +/// cancellation polling — providers run them on worker threads. +class IHttpTransport { +public: + virtual ~IHttpTransport() = default; + virtual HttpOutcome send(const HttpRequest& request) = 0; +}; + +/// Shared pointer alias used by providers and the registry. +using HttpTransportPtr = std::shared_ptr; + +// --------------------------------------------------------------------------- +// URL helpers (pure logic, unit-tested here on every platform). +// --------------------------------------------------------------------------- + +/// Parsed absolute http(s) URL. Handles what the providers actually emit: +/// scheme, host (no userinfo), optional port, path, no query parsing beyond +/// retaining the raw query string. +struct ParsedUrl { + std::string scheme; // "http" | "https" (lower-cased) + std::string host; // lower-cased; IPv6 brackets kept + int port = 0; // explicit or scheme default (80/443) + std::string path; // begins with '/' + std::string query; // begins with '?' or empty + + bool valid() const { return !scheme.empty() && !host.empty(); } + std::string authority() const; // host[:port] when non-default + std::string toString() const; +}; + +std::optional parseUrl(const std::string& url); + +/// localhost → 127.0.0.1 rewrite (Swift URL.resolvingLocalhost): avoids IPv6 +/// ::1 resolution failures on Windows. +std::string resolveLocalhost(const std::string& url); + +/// Swift LLMTranslationProvider.appendingAPISuffix: appends path segments +/// without duplicating an overlapping version tail (e.g. base ".../v1" + +/// suffix "chat/completions" → ".../v1/chat/completions"; base +/// ".../v1/chat/completions" + same suffix → unchanged; case-insensitive). +std::string appendingApiSuffix(const std::string& baseUrl, const std::string& suffix); + +/// Host is localhost-family (localhost / 127.0.0.1 / ::1 / 0.0.0.0 / *.local) +/// — gates the "refuse API key over plain HTTP" rule (Swift isLocalhost). +bool isLocalhostHost(const std::string& host); + +/// Security rule shared by OpenAI/Claude/Gemini/custom: an API key must never +/// ride a non-HTTPS transport unless the host is localhost-family. +/// Returns an Auth ProviderError when the combination is unsafe. +std::optional guardApiKeyTransport(const std::string& url, bool sendingApiKey); + +/// Percent-encode a query component (Baidu q= / Google key=). +std::string urlEncode(const std::string& value); + +} // namespace tf + +#endif // TF_HTTP_TRANSPORT_HPP diff --git a/windows/Core/include/tf/Json.hpp b/windows/Core/include/tf/Json.hpp new file mode 100644 index 0000000..552ded1 --- /dev/null +++ b/windows/Core/include/tf/Json.hpp @@ -0,0 +1,17 @@ +// tf/Json.hpp — thin helpers over vendored nlohmann/json.hpp so Core sources +// don't each hand-roll parse error handling. +#ifndef TF_JSON_HPP +#define TF_JSON_HPP + +#include "CoreModels.hpp" +#include "nlohmann/json.hpp" + +namespace tf { + +using Json = nlohmann::json; + +inline std::string jsonDump(const Json& j) { return j.dump(); } + +} // namespace tf + +#endif // TF_JSON_HPP diff --git a/windows/Core/include/tf/LLMChatProvider.hpp b/windows/Core/include/tf/LLMChatProvider.hpp new file mode 100644 index 0000000..f8a8ef2 --- /dev/null +++ b/windows/Core/include/tf/LLMChatProvider.hpp @@ -0,0 +1,53 @@ +// tf/LLMChatProvider.hpp +// One chat-completions provider covering OpenAI / Claude / Gemini / Ollama, +// ported from Swift LLMTranslationProvider.swift (endpoint routing, header +// sets, HTTPS-key guard, batching, models-list verify). The Windows engine +// set has no apple; "custom" OpenAI-compatible instances use +// CompatibleChatProvider.hpp instead (they carry their own UUID identity). +#ifndef TF_LLM_CHAT_PROVIDER_HPP +#define TF_LLM_CHAT_PROVIDER_HPP + +#include "tf/LLMTranslationCore.hpp" +#include "tf/TranslationProvider.hpp" + +namespace tf { + +class LLMChatProvider final : public ITranslationProvider { +public: + LLMChatProvider(TranslationEngineType engine, // openai|claude|gemini|ollama + EngineConfig config, CredentialStorePtr credentials, + HttpTransportPtr transport); + + // ITranslationProvider + std::string id() const override { return translationEngineRaw(engine_); } + std::string name() const override; + TranslationEngineType engineType() const override { return engine_; } + bool isAvailable() const override; + TranslationOutcome translate(const TranslateRequest& request) override; + std::optional verifyConnection(const CancellationToken& token) override; + + // --- exposed for tests --- + std::string buildPrompt(const std::string& combinedText, const std::string& sourceLanguage, + const std::string& targetLanguage, + const std::string& promptTemplate) const; + std::string endpointForRequest() const; + std::string verifyEndpoint() const; + +private: + Outcome callApi(const std::string& prompt, + const StoredCredentials* credentials, + const CancellationToken& token); + + TranslationEngineType engine_; + EngineConfig config_; + CredentialStorePtr credentials_; + HttpTransportPtr transport_; +}; + +/// English display names for prompts ("Auto Detect", "Chinese (Simplified)"…), +/// mirroring Swift TranslationLanguage.promptDisplayName (locale=en). +std::string promptLanguageDisplayName(const std::string& code); + +} // namespace tf + +#endif // TF_LLM_CHAT_PROVIDER_HPP diff --git a/windows/Core/include/tf/LLMTranslationCore.hpp b/windows/Core/include/tf/LLMTranslationCore.hpp new file mode 100644 index 0000000..5ec4e87 --- /dev/null +++ b/windows/Core/include/tf/LLMTranslationCore.hpp @@ -0,0 +1,71 @@ +// tf/LLMTranslationCore.hpp +// Pure-logic port of Swift LLMTranslationBatching.swift + +// LLMTranslationResponseParser.swift (byte-for-byte semantics; test vectors +// mirror TransFrameTests/LLMResponseTruncationTests.swift). +#ifndef TF_LLM_TRANSLATION_CORE_HPP +#define TF_LLM_TRANSLATION_CORE_HPP + +#include "tf/CoreModels.hpp" + +#include +#include +#include + +namespace tf { + +/// Outcome — small expected-like union (avoids exceptions +/// so providers compose cleanly in Catch2 tests). Declared before use. +template +struct Outcome { + static_assert(std::is_default_constructible_v, "Outcome value must be default constructible"); + static_assert(std::is_default_constructible_v, "Outcome error must be default constructible"); + + bool okFlag = false; + T value{}; + E error{}; + + static Outcome makeOk(T v) { + Outcome o; + o.okFlag = true; + o.value = std::move(v); + return o; + } + static Outcome makeError(E e) { + Outcome o; + o.okFlag = false; + o.error = std::move(e); + return o; + } + bool isOk() const { return okFlag; } +}; + +/// Batch splitter ahead of the output-token budget; long fragments are cut by +/// characters (not spaces) and order is preserved. +struct LLMTranslationBatching { + static const char* separator(); // "\n---\n" + + static std::vector> split(const std::vector& texts, + std::int64_t maxOutputTokens, + const std::string& promptTemplate); + + static std::int64_t estimatedTokens(const std::string& text); + +private: + static std::vector splitLongText(const std::string& text, std::int64_t budget); +}; + +/// Shared completion-state parsing for OpenAI-compatible and Claude bodies +/// (plain JSON and SSE streams). +struct LLMTranslationResponseParser { + /// engine < 0 → treat as "custom" (OpenAI-compatible) — Swift .custom path. + static Outcome extractText(const std::string& body, + TranslationEngineType engine); + +private: + static Outcome extractOpenAISSE(const std::string& text); + static Outcome extractClaudeSSE(const std::string& text); +}; + +} // namespace tf + +#endif // TF_LLM_TRANSLATION_CORE_HPP diff --git a/windows/Core/include/tf/MTranServerProvider.hpp b/windows/Core/include/tf/MTranServerProvider.hpp new file mode 100644 index 0000000..51cdd08 --- /dev/null +++ b/windows/Core/include/tf/MTranServerProvider.hpp @@ -0,0 +1,84 @@ +// tf/MTranServerProvider.hpp +// MTranServer engine (port of Swift MTranServerEngine.swift): strict +// host:port endpoint validation, /translate POST, /health probe ladder with +// 5s cache TTL, language normalization. +#ifndef TF_MTRAN_SERVER_PROVIDER_HPP +#define TF_MTRAN_SERVER_PROVIDER_HPP + +#include "tf/TranslationProvider.hpp" + +namespace tf { + +class MTranServerProvider final : public ITranslationProvider { +public: + /// Parsed endpoint (Swift MTranServerEngine.Configuration): host (hostname + /// or IPv4, no path/query), port, timeout, autoDetect. + struct Configuration { + std::string serverAddress; // host only + int serverPort = 8989; + double timeout = 10.0; + bool autoDetectSourceLanguage = true; + + static Configuration makeDefault(); // localhost:8989 + /// Parses "host", "host:port", "http://host[:port]"; rejects paths, + /// queries, non-hostname characters (Swift isHostnameSafeCharacter). + static std::optional parse(const std::string& serverUrl, + double timeout = 10.0, + bool autoDetect = true); + bool isValid() const; + std::string endpointUrl(const std::string& path) const; // http://host:port/path + }; + + MTranServerProvider(Configuration config, HttpTransportPtr transport); + + std::string id() const override { return "mtranserver"; } + std::string name() const override { return "MTransServer"; } + TranslationEngineType engineType() const override { return TranslationEngineType::MtranServer; } + bool isAvailable() const override { return config_.isValid(); } + TranslationOutcome translate(const TranslateRequest& request) override; + std::optional verifyConnection(const CancellationToken& token) override; + + const Configuration& configuration() const { return config_; } + + /// Language normalization (Swift normalizeLanguageCode): zh-Hans→zh, + /// zh-Hant→zh-TW, en-US→en, en… base-code extraction. + static std::string normalizeLanguageCode(const std::string& code); + + struct ProbeOutcomeValue { + enum class Kind { Reachable, Unreachable, Cancelled } kind = Kind::Unreachable; + std::string viaEndpoint; + }; + using ProbeOutcome = ProbeOutcomeValue; + + /// Probe ladder (Swift MTranServerChecker): GET /health, /, /translate — + /// 2s timeout each; tolerate 401/403/404/405/429/501 on the first two. + ProbeOutcome probeEndpoint(const Configuration& config, const CancellationToken& token); + +private: + Configuration config_; + HttpTransportPtr transport_; +}; + +/// Health-check cache with 5s TTL per endpoint (Swift MTranServerChecker: +/// cachedResults + in-flight dedupe). Pure logic — tests drive the clock. +class MTranServerHealthCache { +public: + explicit MTranServerHealthCache(double ttlSeconds = 5.0); + + struct Entry { + bool available = false; + double checkedAt = 0.0; // seconds on the injected clock + }; + + std::optional cached(const std::string& host, int port, double now) const; + void store(const std::string& host, int port, bool available, double now); + void invalidateAll(); + +private: + double ttl_; + std::map, Entry> cache_; +}; + +} // namespace tf + +#endif // TF_MTRAN_SERVER_PROVIDER_HPP diff --git a/windows/Core/include/tf/OcrEngines.hpp b/windows/Core/include/tf/OcrEngines.hpp new file mode 100644 index 0000000..f84e759 --- /dev/null +++ b/windows/Core/include/tf/OcrEngines.hpp @@ -0,0 +1,240 @@ +// tf/OcrEngines.hpp +// OCR engines: Windows.Media.Ocr mapping (bbox normalization port of Swift +// OCRText.from(VNRecognizedTextObservation) — Windows returns top-left +// origin, so the mapping is a direct scale), PaddleOCR external-process +// protocol (fast/precise parsers + health cache), and the VLM OCR skeleton +// with five provider slots (brief §1). +// +// The Windows.Media.Ocr invocation itself is WinRT (NativeShell/ +// WindowsOcrEngine.winrt.cpp, NOT RUN on this macOS host); everything here is +// the pure mapping/protocol layer that Catch2 verifies. +#ifndef TF_OCR_ENGINES_HPP +#define TF_OCR_ENGINES_HPP + +#include "tf/CoreModels.hpp" +#include "tf/HttpTransport.hpp" +#include "tf/LLMTranslationCore.hpp" // Outcome +#include "tf/TranslationProvider.hpp" // CredentialStorePtr + +#include +#include +#include +#include +#include +#include + +namespace tf { + +// --------------------------------------------------------------------------- +/// Unified OCR engine interface (Swift AnyOCREngine; the image handle is the +/// cross-platform PixelBuffer — BGRA8 bytes + size — so Core stays testable +/// without WinRT bitmap types). +struct OcrImage { + std::int64_t width = 0; + std::int64_t height = 0; + std::string bgra; // width*height*4 bytes, top-down +}; + +class IOcrEngine { +public: + virtual ~IOcrEngine() = default; + virtual std::string id() const = 0; + virtual std::string name() const = 0; + virtual bool isAvailable() const = 0; + /// Runs OCR; segments carry normalized bboxes (top-left origin) + + /// confidence, matching macOS TextSegment schema. + virtual Outcome recognize(const OcrImage& image) = 0; +}; + +// --------------------------------------------------------------------------- +/// Windows.Media.Ocr engine (FR-15). Language-pack detection gates +/// availability; missing pack for a requested language → gray. +class WindowsOcrEngine final : public IOcrEngine { +public: + /// One language the engine may recognize (BCP-47 tag ↔ installed pack). + struct Language { + std::string tag; // "en-US", "zh-Hans", ... + std::string displayName; + }; + + /// Language-inventory seam: implemented by NativeShell (WinRT + /// OcrEngine.AvailableRecognizerLanguages) and mocked in tests. Returns + /// installed packs. + using LanguageProvider = std::function()>; + + /// Recognition primitive implemented by NativeShell over WinRT: + /// returns raw line results (pixel rects, top-left origin) for the image + /// using the given language tags. + struct RawLine { + std::string text; + std::int64_t x = 0, y = 0, w = 0, h = 0; // pixels + float confidence = 0.0f; // Windows OCR gives no score → 1.0 + }; + using Recognizer = std::function( + const OcrImage&, const std::vector& languageTags, + std::vector& outLines)>; + + WindowsOcrEngine(LanguageProvider languageProvider, Recognizer recognizer, + float minimumConfidence = 0.0f); + + std::string id() const override { return "windowsOcr"; } + std::string name() const override { return "Windows OCR"; } + /// At least one recognizer language pack installed. + bool isAvailable() const override; + Outcome recognize(const OcrImage& image) override; + + /// Installed language packs (cache-free; the WinRT call is cheap). + std::vector installedLanguages() const; + /// Whether a language pack for the tag (or its base) is installed — + /// drives the gray state for missing Chinese packs (FR-15). + bool hasLanguagePack(const std::string& bcp47Tag) const; + + /// Maps raw pixel-space lines to TextSegments with normalized bboxes. + /// Confidence defaults to 1.0 (Windows OCR exposes no score; macOS parity + /// keeps the schema field). + static std::vector mapLines(const std::vector& lines, + std::int64_t imageWidth, std::int64_t imageHeight, + float minimumConfidence = 0.0f); + + /// Language-tag normalization: zh → zh-Hans (Windows pack naming), en → + /// en-US, ja → ja, ko → ko. + static std::string normalizeLanguageTag(const std::string& tag); + +private: + LanguageProvider languageProvider_; + Recognizer recognizer_; + float minimumConfidence_; +}; + +// --------------------------------------------------------------------------- +/// PaddleOCR external-process engine (FR-16): fast (ocr CLI, ~1s) / precise +/// (doc_parser VL-1.5, ~12s) modes; JSON protocol parsers are pure logic and +/// unit-tested here; the process spawn lives in NativeShell. +class PaddleOcrEngine final : public IOcrEngine { +public: + enum class Mode { Fast, Precise }; + + struct Configuration { + std::vector languages = {"ch", "en"}; // PaddleOCR lang codes + float minimumConfidence = 0.0f; + bool useGPU = false; + bool useDirectionClassify = true; + Mode mode = Mode::Fast; + std::string executablePath; // empty → availability check fails + }; + + /// Process-runner seam (NativeShell: CreateProcess + pipes). + /// Arguments are passed argv-style, never through a shell (Swift + /// security: no shell metacharacter path). + using ProcessRunner = std::function( + const std::string& executable, const std::vector& args, int timeoutSeconds, + std::string& outStdout, std::string& outStderr)>; + + /// Availability seam: filesystem check for the executable + version + /// probe (Swift PaddleOCRChecker.performFullCheck). + using AvailabilityChecker = std::function; + + PaddleOcrEngine(Configuration config, ProcessRunner runner, + AvailabilityChecker availability); + + std::string id() const override { return "paddleocr"; } + std::string name() const override { return "PaddleOCR"; } + bool isAvailable() const override; + Outcome recognize(const OcrImage& image) override; + + /// Builds the argv for the current configuration (Swift buildArguments). + std::vector buildArguments(const std::string& imagePath) const; + + /// Fast-mode parser: {"res": {"rec_texts": [...], "rec_scores": [...], + /// "rec_boxes": [[x1,y1,x2,y2], ...]}} → normalized segments. + static std::vector parseFastMode(const std::string& json, + std::int64_t imageWidth, + std::int64_t imageHeight, + float minimumConfidence = 0.0f); + + /// Precise-mode parser: {"res": {"parsing_res_list": [{"block_content": + /// ..., "block_bbox": [x1,y1,x2,y2], "block_label": ...}]}} — skips + /// chart/seal/image/table/figure blocks; default confidence 0.9. + static std::vector parsePreciseMode(const std::string& json, + std::int64_t imageWidth, + std::int64_t imageHeight); + + /// Python-literal → JSON normalization for the `{'res': ...}` stderr + /// payload: single→double quotes, True/False/None, numpy arrays, "8." + /// floats (Swift convertPythonDictToJson). + static std::string pythonDictToJson(const std::string& pythonLiteral); + + /// Extracts the {'res': ...} tail from mixed stdout/stderr output and + /// strips ANSI color codes (Swift executePaddleOCR). + static std::string extractResultJson(const std::string& stdoutText, + const std::string& stderrText); + +private: + Configuration config_; + ProcessRunner runner_; + AvailabilityChecker availability_; +}; + +// --------------------------------------------------------------------------- +/// PaddleOCR availability cache (Swift PaddleOCRChecker state + TTL). +/// Pure logic; tests drive the clock. +class PaddleOcrHealthCache { +public: + explicit PaddleOcrHealthCache(double ttlSeconds = 300.0); + std::optional cached(const std::string& executable, double now) const; + void store(const std::string& executable, bool available, double now); + void invalidateAll(); + +private: + double ttl_; + std::map> cache_; +}; + +// --------------------------------------------------------------------------- +/// VLM OCR skeleton (FR-17): five provider slots (OpenAI/Claude/Gemini/ +/// Ollama/PaddleOCR-VL). HTTP details reuse the translation layer's +/// transport + response parsing; the five analyze() implementations are +/// NativeShell-side (image upload shapes differ per provider) — this class +/// owns routing, prompt building, and segment extraction. +class VlmOcrEngine final : public IOcrEngine { +public: + /// Per-provider analyze primitive implemented by NativeShell (base64/URL + /// image upload, provider-specific body). Returns raw VLM JSON text. + using Analyzer = std::function( + VlmProviderType provider, const std::string& prompt, const OcrImage& image, + std::string& outRawJson)>; + + VlmOcrEngine(Analyzer analyzer, CredentialStorePtr credentials); + + std::string id() const override { return "vlm"; } + std::string name() const override { return "VLM"; } + /// Available when at least one provider has credentials (or Ollama local + /// endpoint is configured — keyless). + bool isAvailable() const override; + Outcome recognize(const OcrImage& image) override; + + /// The extraction prompt (Swift VLM prompt: JSON array of {text, + /// confidence, box{x,y,width,height}} in normalized coordinates). + static const std::string& extractionPrompt(); + + /// Parses the VLM's JSON (plain array, {"results": [...]}, or chat + /// completion content embedding a ```json block) into segments with + /// normalized bboxes. box values are already normalized (0..1). + static std::vector parseSegments(const std::string& rawJson, + std::int64_t imageWidth, + std::int64_t imageHeight); + + /// Provider slots present (brief: 五 Provider 接口位). + static std::vector supportedProviders(); + + void setActiveProvider(VlmProviderType provider) { activeProvider_ = provider; } + +private: + Analyzer analyzer_; + CredentialStorePtr credentials_; + VlmProviderType activeProvider_ = VlmProviderType::OpenAI; +}; + +} // namespace tf + +#endif // TF_OCR_ENGINES_HPP diff --git a/windows/Core/include/tf/TextSelectionInsertion.hpp b/windows/Core/include/tf/TextSelectionInsertion.hpp new file mode 100644 index 0000000..2f0cefc --- /dev/null +++ b/windows/Core/include/tf/TextSelectionInsertion.hpp @@ -0,0 +1,148 @@ +// tf/TextSelectionInsertion.hpp +// 划词取文本 + 翻译并插入 (FR-28/29): protocol logic in Core, system calls in +// NativeShell. Mirrors the macOS safety semantics from TextSelectionService / +// TextInsertService / AXTextInsertionTarget: +// 1. UIA TextPattern GetSelection first (no clipboard touched). +// 2. Clipboard fallback: save → clear → Ctrl+C → poll → restore. +// 3. Insert: re-validate the target selection still equals the captured +// text; ONLY then SendInput Ctrl+V (paste), never blind typing. +// Re-validation failure aborts — 绝不粘贴 (brief §6). +#ifndef TF_TEXT_SELECTION_INSERTION_HPP +#define TF_TEXT_SELECTION_INSERTION_HPP + +#include "tf/CoreModels.hpp" + +#include +#include +#include +#include +#include +#include + +namespace tf { + +/// Captured selection + the identity of the editable target (macOS +/// CapturedTextInsertion / TextSelectionResult). +struct TextSelection { + std::string text; + std::string sourceApplication; // exe name when known + std::uint32_t sourceProcessId = 0; + /// Non-empty when a UIA editable target was bound (supports re-validation + /// before paste). Empty in clipboard-fallback mode. + std::string insertionTargetId; +}; + +/// UIA abstraction over the focused element (mock in tests; NativeShell +/// implements via IUIAutomation TextPattern/ValuePattern). +class IUiaElement { +public: + virtual ~IUiaElement() = default; + /// Selected text via TextPattern::GetSelection; nullopt = pattern absent. + virtual std::optional getSelectionText() const = 0; + /// Whether the element exposes an editable ValuePattern. + virtual bool isEditable() const = 0; + /// Stable identity for re-validation (RuntimeId / HWND+pattern combo). + virtual std::string runtimeId() const = 0; +}; + +using UiaElementPtr = std::unique_ptr; + +/// System seams implemented by NativeShell (Win32/UIA/SendInput). +struct TextExtractorHost { + /// Focused element (UIA) or nullptr when UIA is unavailable. + std::function focusedElement; + /// Full clipboard snapshot: formats + data, restorable (Swift + /// PasteboardBackup.save/restore). + struct ClipboardBackup { + std::string text; // CF_UNICODETEXT payload (may be empty) + std::string raw; // serialized bytes of other formats + std::int64_t sequenceNumber = 0; + }; + virtual ~TextExtractorHost() = default; + virtual ClipboardBackup backupClipboard() = 0; + virtual void restoreClipboard(const ClipboardBackup& backup) = 0; + virtual void clearClipboard() = 0; + /// Sets text and returns the new sequence number. + virtual std::int64_t setClipboardText(const std::string& text) = 0; + virtual std::int64_t clipboardSequenceNumber() = 0; + virtual std::optional clipboardText() = 0; + /// Sends Ctrl+C / Ctrl+V via SendInput. + virtual bool sendCopyShortcut() = 0; + virtual bool sendPasteShortcut() = 0; + /// Foreground process info for anchoring. + virtual std::string foregroundProcessName() = 0; + virtual std::uint32_t foregroundProcessId() = 0; + /// Sleep helper (ms) so tests can run without real delays. + virtual void sleepMilliseconds(int ms) = 0; +}; + +/// Extraction outcome (Swift CaptureError mapped onto error categories). +struct ExtractionOutcome { + std::optional selection; + std::optional error; + + static ExtractionOutcome ok(TextSelection s) { + return ExtractionOutcome{std::move(s), std::nullopt}; + } + static ExtractionOutcome fail(ProviderError e) { + return ExtractionOutcome{std::nullopt, std::move(e)}; + } +}; + +/// FR-28: UIA-first text extraction with clipboard fallback. +class TextExtractor { +public: + /// allowClipboardFallback: 设置可关 (Swift TextSelectionService seam). + TextExtractor(TextExtractorHost& host, bool allowClipboardFallback = true, + int clipboardPollRetries = 20, int clipboardPollIntervalMs = 100); + + /// Captures the current selection. bindForInsertion additionally binds + /// the UIA editable target for later re-validation. + ExtractionOutcome captureSelectedText(bool bindForInsertion = false); + + bool canCapture() const { return host_.focusedElement != nullptr; } + +private: + TextExtractorHost& host_; + bool allowClipboardFallback_; + int clipboardPollRetries_; + int clipboardPollIntervalMs_; +}; + +/// FR-29 outcome states (macOS TextInsertionProgressController tri-state). +enum class InsertionOutcome { InProgress, Completed, Failed }; + +struct InsertRequest { + std::string translatedText; + TextSelection capturedSelection; // anchor captured at trigger time +}; + +/// FR-29: translate-and-insert with mandatory re-validation. +class InsertionService { +public: + explicit InsertionService(TextExtractorHost& host); + + /// Re-validates the target then pastes. Steps: + /// 1. focused element must exist and match capturedSelection.insertionTargetId + /// (or foreground PID anchor in fallback mode); + /// 2. current selection must still equal capturedSelection.text + /// (UIA read-back; Swift "目标重验证"); + /// 3. setClipboardText(translated) → sendPasteShortcut(); + /// 4. restore the original clipboard after the paste window. + /// Any mismatch → abort with TargetChanged; 绝不粘贴 (brief §6). + InsertionOutcome insert(const InsertRequest& request, std::string& outError); + + /// Pure re-validation logic, exposed for tests with a mock element. + /// Returns nullopt when validation passes; error text otherwise. + static std::optional validateTarget(const IUiaElement* focused, + const TextSelection& captured, + const std::string& currentSelectionText, + std::uint32_t foregroundPid); + +private: + TextExtractorHost& host_; +}; + +} // namespace tf + +#endif // TF_TEXT_SELECTION_INSERTION_HPP diff --git a/windows/Core/include/tf/TranslationProvider.hpp b/windows/Core/include/tf/TranslationProvider.hpp new file mode 100644 index 0000000..015ca48 --- /dev/null +++ b/windows/Core/include/tf/TranslationProvider.hpp @@ -0,0 +1,139 @@ +// tf/TranslationProvider.hpp +// Unified translation-provider contract for the 9 Windows engines (no apple). +// Mirrors Swift TranslationProvider + TranslationPromptConfigurable + +// TranslationPromptContextProviding (Services/TranslationProvider.swift). +// Pure logic + IHttpTransport only — no UI, no Win32; Catch2 drives it with +// MockHttpTransport directly (brief: HTTP 层不依赖 UI 框架). +#ifndef TF_TRANSLATION_PROVIDER_HPP +#define TF_TRANSLATION_PROVIDER_HPP + +#include "tf/CoreModels.hpp" +#include "tf/HttpTransport.hpp" + +#include +#include +#include +#include +#include + +namespace tf { + +/// Stored credential payload (Swift StoredCredentials): apiKey + optional +/// appID (Baidu) + free-form additional fields. +struct StoredCredentials { + std::string apiKey; + std::string appID; + std::map additional; +}; + +/// Credential storage abstraction. Production: Credential Manager +/// (NativeShell/src/CredManKeyStore.cpp, "TransFrame//"). +/// Tests: in-memory mock (brief Catch2 "KeyStore mock"). +class ICredentialStore { +public: + virtual ~ICredentialStore() = default; + /// Saves (or replaces) the credential blob for one engine / instance. + virtual void save(const std::string& account, const StoredCredentials& credentials) = 0; + /// Reads; nullopt when absent. + virtual std::optional load(const std::string& account) const = 0; + /// Removes; returns true when an item existed. + virtual bool remove(const std::string& account) = 0; + /// Fast presence check (drives health gating). + virtual bool has(const std::string& account) const = 0; +}; + +using CredentialStorePtr = std::shared_ptr; + +/// Account naming: "TransFrame//" (brief §5). +/// Builtin engines use the raw engine string; compatible instances use their +/// UUID. Baidu keeps its appID inside the same blob. +std::string credentialAccount(TranslationEngineType engine); +std::string credentialAccountForCompatible(const std::string& instanceUuid); + +/// Masked display form for UI: "sk-****last4" (brief §5). Keys shorter than +/// 8 chars collapse to "****". +std::string maskApiKey(const std::string& apiKey); + +/// Per-engine configuration (Swift TranslationEngineConfig + EngineOptions). +struct EngineConfig { + TranslationEngineType engine = TranslationEngineType::MtranServer; + bool isEnabled = false; + std::string baseURL; // overrides default when non-empty + std::string modelName; // LLM engines + std::optional timeoutSeconds; // default 10s (brief) + std::optional maxTokens; // LLM batching budget + std::optional temperature; + std::map customHeaders; + + double effectiveTimeout() const { return timeoutSeconds.value_or(10.0); } + static EngineConfig make(TranslationEngineType t); + + /// Slice identity for registry caching (Swift matchesCachedProvider). + bool operator==(const EngineConfig& o) const = default; +}; + +/// OpenAI-compatible instance definition (Swift CompatibleTranslationProvider +/// .CompatibleConfig): UUID identity, display name, endpoint, model, keyless +/// local endpoints allowed. +struct CompatibleConfig { + std::string id; // UUID string + std::string displayName; + std::string baseURL; + std::string modelName; + bool hasAPIKey = true; // false → keyless local endpoint allowed + + static CompatibleConfig makeDefault(); // "Custom", http://localhost:8000/v1 + + bool operator==(const CompatibleConfig& o) const = default; +}; + +/// Thrown-equivalent: providers return ResultOrProviderError. +struct TranslationOutcome { + std::optional> results; + std::optional error; + + static TranslationOutcome ok(std::vector r) { + return TranslationOutcome{std::move(r), std::nullopt}; + } + static TranslationOutcome fail(ProviderError e) { + return TranslationOutcome{std::nullopt, std::move(e)}; + } +}; + +/// Batch request context passed to providers. +struct TranslateRequest { + std::vector texts; + std::string sourceLanguage; // "" = auto-detect + std::string targetLanguage; + std::string promptTemplate; // resolved per-engine/scene template ("" → default) + CancellationToken cancelToken; +}; + +/// Unified provider interface. Every engine implements this; the scheduler +/// (TranslationScheduler) only sees this interface (brief §2). +class ITranslationProvider { +public: + virtual ~ITranslationProvider() = default; + + virtual std::string id() const = 0; + virtual std::string name() const = 0; + virtual TranslationEngineType engineType() const = 0; + + /// Configured + credentials present (Swift isAvailable). Never performs I/O. + virtual bool isAvailable() const = 0; + + /// Batch translate; preserves input order. Providers with batching + /// (LLM family) split internally via LLMTranslationBatching. + virtual TranslationOutcome translate(const TranslateRequest& request) = 0; + + /// Lightweight free-endpoint connectivity probe (models list / ping). + /// MUST NOT call billed translation endpoints (PRD FR-22). + /// Returns nullopt when no free probe exists for this engine. + virtual std::optional verifyConnection(const CancellationToken& token) = 0; +}; + +using TranslationProviderPtr = std::unique_ptr; + +} // namespace tf + +#endif // TF_TRANSLATION_PROVIDER_HPP diff --git a/windows/Core/include/tf/TranslationScheduler.hpp b/windows/Core/include/tf/TranslationScheduler.hpp new file mode 100644 index 0000000..ca20e91 --- /dev/null +++ b/windows/Core/include/tf/TranslationScheduler.hpp @@ -0,0 +1,198 @@ +// tf/TranslationScheduler.hpp +// V2 engine selection: registry + ordered fallback chain (≤5) + compare +// parallel (2-4) + per-run result cache + scene binding routing. +// Port of Swift TranslationEngineRegistry.swift + TranslationService.swift +// (translateOrderedV2 / translateCompareV2) minus apple fallbacks. +// Pure logic: providers are injected; Catch2 tests drive mock providers with +// injected latency/failure (brief §7). +#ifndef TF_TRANSLATION_SCHEDULER_HPP +#define TF_TRANSLATION_SCHEDULER_HPP + +#include "tf/CoreModels.hpp" +#include "tf/TranslationProvider.hpp" + +#include +#include +#include +#include +#include +#include + +namespace tf { + +/// Provider factory + saved compatible-instance list (the registry's external +/// seams so tests inject mocks without touching real transports). +struct SchedulerDependencies { + /// Returns the provider for a builtin engine, or nullptr when unconfigured. + std::function builtinProvider; + /// Returns the provider for a compatible instance UUID, or nullptr when + /// the instance no longer exists (deleted instance). + std::function compatibleProvider; + /// Saved compatible-instance configs (displayName lookup for results). + std::function()> compatibleConfigs; + /// Prompt config resolution: template ("" → default) for engine+scene. + std::function + promptResolver; +}; + +/// Aggregated failure for a whole-chain / whole-set loss (Swift +/// MultiEngineError.allEnginesFailed): per-engine identity + reason. +struct ChainFailureEntry { + TranslationEngineType engine; + std::string displayName; // instance name when applicable + std::string errorText; +}; + +/// Scheduler run outcome. Either a bundle (≥1 engine success) or the +/// aggregated per-engine failure list (Swift semantics: failures precede the +/// winning result in `results`). +struct SchedulerOutcome { + std::optional bundle; + std::vector failures; // set when bundle empty + + bool isSuccess() const { return bundle.has_value(); } +}; + +/// Ordered chain request (≤5 entries, clamped; brief FR-20). +struct ChainRequest { + std::vector chain; + std::vector texts; + std::string sourceLanguage; + std::string targetLanguage; + TranslationScene scene = TranslationScene::Screenshot; + CancellationToken cancelToken; +}; + +/// Compare request (2-4 entries, clamped; brief FR-21). +struct CompareRequest { + std::vector engines; + std::vector texts; + std::string sourceLanguage; + std::string targetLanguage; + TranslationScene scene = TranslationScene::Screenshot; + CancellationToken cancelToken; +}; + +/// Scene → selection routing (brief FR-23): unbound scenes fall back to the +/// global chain/compare set. +struct SceneEngineBinding { + TranslationScene scene = TranslationScene::Screenshot; + std::vector chain; // when ordered + std::vector compareSet; // when compare +}; + +class TranslationScheduler { +public: + explicit TranslationScheduler(SchedulerDependencies deps); + + /// Ordered fallback: try entries in order; first success wins and earlier + /// failures ride along in results. Unavailable members are skipped with a + /// logged failure (Swift translateOrderedV2). Cancellation aborts the + /// chain immediately instead of grinding through (Swift PR #92). + SchedulerOutcome translateOrdered(const ChainRequest& request); + + /// Compare: run entries in parallel, one EngineResult per entry in + /// selection order; ≥1 success → bundle; all failed → aggregated + /// failures (Swift translateCompareV2). The per-entry result cache makes + /// later "switch engine / re-view" hits free (no re-translation). + SchedulerOutcome translateCompare(const CompareRequest& request); + + /// Scene routing: picks the bound selection for the scene or falls back + /// to the global pair (brief FR-23). + SchedulerOutcome translateForScene(const ChainRequest& globalChain, + const CompareRequest& globalCompare, + const SceneEngineBinding& binding, + const std::vector& texts, + const std::string& sourceLanguage, + const std::string& targetLanguage, + const CancellationToken& token); + + // --- per-run compare cache (brief FR-21 "结果缓存免重译") --- + /// Cache key: engine identity + source/target + joined texts. One entry + /// per successful engine result. + struct CacheKey { + std::string engineKey; // builtin raw or "custom:" + std::string sourceLanguage; + std::string targetLanguage; + std::string textsHash; + + bool operator<(const CacheKey& o) const { + if (engineKey != o.engineKey) return engineKey < o.engineKey; + if (sourceLanguage != o.sourceLanguage) return sourceLanguage < o.sourceLanguage; + if (targetLanguage != o.targetLanguage) return targetLanguage < o.targetLanguage; + return textsHash < o.textsHash; + } + }; + + std::optional cachedResult(const EngineChainItem& item, + const std::string& sourceLanguage, + const std::string& targetLanguage, + const std::vector& texts) const; + void storeResult(const EngineChainItem& item, const std::string& sourceLanguage, + const std::string& targetLanguage, const std::vector& texts, + const EngineResult& result); + void clearResultCache(); + +private: + struct ResolveResult { + TranslationProviderPtr provider; + std::string displayName; // instance display name or "" + bool resolved = false; + }; + ResolveResult resolve(const EngineChainItem& item) const; + static std::string engineKeyFor(const EngineChainItem& item); + static std::string hashTexts(const std::vector& texts); + EngineResult runProvider(const ResolveResult& resolved, const EngineChainItem& item, + const std::vector& texts, + const std::string& sourceLanguage, + const std::string& targetLanguage, TranslationScene scene, + const CancellationToken& token); + + SchedulerDependencies deps_; + mutable std::mutex cacheMutex_; + std::map resultCache_; +}; + +/// EngineRegistry: creation + caching of the 9 builtin providers and +/// compatible instances (Swift TranslationEngineRegistry, ported shape). +/// Config-slice equality decides cache hits; manual overrides win. +class EngineRegistry { +public: + using BuiltinFactory = std::function; + using CompatibleFactory = std::function; + + EngineRegistry(BuiltinFactory builtinFactory, CompatibleFactory compatibleFactory, + CredentialStorePtr credentials, HttpTransportPtr transport); + + /// Provider for a builtin engine (cached by config slice). + TranslationProviderPtr provider(TranslationEngineType engine, const EngineConfig& config); + /// Provider for a compatible instance (cached by UUID+config). + TranslationProviderPtr compatibleProvider(const CompatibleConfig& config); + /// Saved instance list seam (settings layer owns persistence). + std::function()> compatibleConfigsProvider; + + void clearCompatibleProviders(); + +private: + BuiltinFactory builtinFactory_; + CompatibleFactory compatibleFactory_; + CredentialStorePtr credentials_; + HttpTransportPtr transport_; + std::mutex mutex_; + std::map> builtin_; + std::map> compatible_; +}; + +/// Default 9-engine factory wiring used by the app (tests inject their own). +/// EngineConfig comes from the settings layer; the factory only shapes +/// transport + credential access. +TranslationProviderPtr makeBuiltinProvider(TranslationEngineType engine, + const EngineConfig& config, + const CredentialStorePtr& credentials, + const HttpTransportPtr& transport); + +} // namespace tf + +#endif // TF_TRANSLATION_SCHEDULER_HPP diff --git a/windows/Core/include/tf/VisualLineGrouping.hpp b/windows/Core/include/tf/VisualLineGrouping.hpp new file mode 100644 index 0000000..12d492a --- /dev/null +++ b/windows/Core/include/tf/VisualLineGrouping.hpp @@ -0,0 +1,43 @@ +// tf/VisualLineGrouping.hpp +// Pure port of Swift VisualLineGrouping.swift: merge OCR/VLM fragments that +// sit on the same visual line into complete line segments before translation. +// Identical thresholds; test vectors shared with +// TransFrameTests/VisualLineGroupingTests.swift. +#ifndef TF_VISUAL_LINE_GROUPING_HPP +#define TF_VISUAL_LINE_GROUPING_HPP + +#include "tf/CoreModels.hpp" + +#include +#include + +namespace tf { + +struct VisualLineGrouping { + /// Minimum Y-projection overlap (fraction of the shorter box height) for + /// a fragment to join a line. + static constexpr double verticalOverlapThreshold = 0.5; + /// Maximum horizontal gap between a fragment and the line it joins, as a + /// multiple of the average line height. + static constexpr double horizontalGapFactor = 3.0; + + /// Groups segments into visual lines, ordered top-to-bottom, left-to-right. + static std::vector mergeLines(const std::vector& segments); + + /// Joins two fragments: CJK-adjacent text glues directly; near-zero gap + /// between identifier-shaped fragments glues; everything else gets a + /// space (Swift joinText). + static std::string joinText(const std::string& lhs, const std::string& rhs, + bool gluesDirectly = false); + + // Test/内部 helpers exposed for vectors parity. + static bool isCJK(char32_t c); + static bool isIdentifierCharacter(char32_t c); + static bool isIdentifierLike(const std::string& s); + static bool belongsToSameLine(const TextSegment& fragment, + const std::vector& lineFragments); +}; + +} // namespace tf + +#endif // TF_VISUAL_LINE_GROUPING_HPP diff --git a/windows/Core/src/CloudProviders.cpp b/windows/Core/src/CloudProviders.cpp new file mode 100644 index 0000000..39f7569 --- /dev/null +++ b/windows/Core/src/CloudProviders.cpp @@ -0,0 +1,486 @@ +// CloudProviders.cpp — Google v2 / DeepL / Baidu ports. +#include "tf/CloudProviders.hpp" +#include "tf/Json.hpp" + +#include +#include +#include +#include + +namespace tf { + +namespace { + +std::string trimCopy(const std::string& s) { + std::size_t b = 0, e = s.size(); + auto isSpace = [](unsigned char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; + }; + while (b < e && isSpace(static_cast(s[b]))) ++b; + while (e > b && isSpace(static_cast(s[e - 1]))) --e; + return s.substr(b, e - b); +} + +std::string lowerCopy(std::string s) { + for (auto& c : s) c = static_cast(std::tolower(static_cast(c))); + return s; +} + +std::string upperCopy(std::string s) { + for (auto& c : s) c = static_cast(std::toupper(static_cast(c))); + return s; +} + +/// Map an HTTP status onto the error taxonomy (brief §2: 网络/配额/鉴权/内容). +ProviderError statusError(const std::string& engine, int status, const std::string& body) { + if (status == 401 || status == 403) { + return ProviderError::auth(engine + " HTTP " + std::to_string(status)); + } + if (status == 429) { + return ProviderError::quota(engine + " rate limited (HTTP 429)"); + } + if (status >= 500 || status == 0) { + return ProviderError::network(engine + " HTTP " + std::to_string(status)); + } + (void)body; + return ProviderError::content(engine + " HTTP " + std::to_string(status)); +} + +} // namespace + +// =========================================================================== +// Google v2 +// =========================================================================== +GoogleTranslateProvider::GoogleTranslateProvider(EngineConfig config, + CredentialStorePtr credentials, + HttpTransportPtr transport) + : config_(std::move(config)), credentials_(std::move(credentials)), + transport_(std::move(transport)) {} + +bool GoogleTranslateProvider::isAvailable() const { + return credentials_ && credentials_->has(credentialAccount(TranslationEngineType::Google)); +} + +std::string GoogleTranslateProvider::mapLanguageCode(const std::string& code) { + const std::string l = lowerCopy(code); + if (l == "zh-hant" || l == "zh-tw") return "zh-TW"; + if (l.empty() || l == "auto") return "auto"; + // Google v2 accepts base codes; strip region. + const std::size_t dash = l.find('-'); + return dash == std::string::npos ? l : l.substr(0, dash); +} + +TranslationOutcome GoogleTranslateProvider::translate(const TranslateRequest& request) { + if (request.texts.empty()) return TranslationOutcome::ok({}); + for (const auto& t : request.texts) { + if (trimCopy(t).empty()) { + return TranslationOutcome::fail(ProviderError::content("Cannot translate empty text")); + } + } + auto creds = credentials_->load(credentialAccount(TranslationEngineType::Google)); + if (!creds.has_value() || creds->apiKey.empty()) { + return TranslationOutcome::fail(ProviderError::configuration("API key not configured")); + } + + const std::string base = config_.baseURL.empty() + ? translationEngineDefaultBaseUrl(TranslationEngineType::Google) + : config_.baseURL; + const std::string url = + resolveLocalhost(base) + "?key=" + urlEncode(creds->apiKey); + + // v2 body: q[] array, format, source (omit when auto), target. + Json body; + body["q"] = request.texts; + body["format"] = "text"; + const std::string source = mapLanguageCode(request.sourceLanguage); + if (source != "auto" && !source.empty()) body["source"] = source; + body["target"] = mapLanguageCode(request.targetLanguage); + + HttpRequest req; + req.method = "POST"; + req.url = url; + req.timeoutSeconds = static_cast(config_.effectiveTimeout()); + req.cancelToken = request.cancelToken; + req.headers["Content-Type"] = "application/json"; + req.body = body.dump(); + + auto outcome = transport_->send(req); + if (outcome.error.has_value()) return TranslationOutcome::fail(*outcome.error); + const HttpResponse& resp = *outcome.response; + if (!resp.ok()) { + return TranslationOutcome::fail(statusError("Google", resp.status, resp.body)); + } + Json json; + try { + json = Json::parse(resp.body); + } catch (const Json::parse_error&) { + return TranslationOutcome::fail(ProviderError::content("Invalid Google response")); + } + if (!json.contains("data") || !json["data"].is_object() || + !json["data"].contains("translations") || !json["data"]["translations"].is_array()) { + return TranslationOutcome::fail(ProviderError::content("Invalid Google response")); + } + const auto& translations = json["data"]["translations"]; + std::vector results; + for (std::size_t i = 0; i < request.texts.size(); ++i) { + std::string translated; + std::string detected; + if (i < translations.size() && translations[i].is_object()) { + if (translations[i].contains("translatedText") && + translations[i]["translatedText"].is_string()) { + translated = translations[i]["translatedText"].get(); + } + if (translations[i].contains("detectedSourceLanguage") && + translations[i]["detectedSourceLanguage"].is_string()) { + detected = translations[i]["detectedSourceLanguage"].get(); + } + } + results.emplace_back(request.texts[i], std::move(translated), + detected.empty() ? (request.sourceLanguage.empty() + ? "Auto" + : request.sourceLanguage) + : std::move(detected), + request.targetLanguage); + } + return TranslationOutcome::ok(std::move(results)); +} + +// =========================================================================== +// DeepL +// =========================================================================== +DeepLProvider::DeepLProvider(EngineConfig config, CredentialStorePtr credentials, + HttpTransportPtr transport) + : config_(std::move(config)), credentials_(std::move(credentials)), + transport_(std::move(transport)) {} + +bool DeepLProvider::isAvailable() const { + return credentials_ && credentials_->has(credentialAccount(TranslationEngineType::DeepL)); +} + +std::string DeepLProvider::normalizeEndpoint(const std::string& baseURL) { + std::string raw = baseURL.empty() + ? translationEngineDefaultBaseUrl(TranslationEngineType::DeepL) + : baseURL; + while (!raw.empty() && raw.back() == '/') raw.pop_back(); + const std::string lowered = lowerCopy(raw); + if (lowered.size() >= 10 && + lowered.compare(lowered.size() - 10, 10, "/translate") == 0) { + return raw; + } + return raw + "/translate"; +} + +std::string DeepLProvider::sourceCode(const std::string& code) { + if (code.empty() || lowerCopy(code) == "auto") return ""; // omit → auto-detect + return lowerCopy(code); +} + +std::string DeepLProvider::targetCode(const std::string& code) { + std::string c = upperCopy(code); + if (c == "ZH-HANS" || c == "ZH") return "ZH"; + if (c == "ZH-HANT" || c == "ZH-TW") return "ZH-HANT"; + if (c == "EN-US" || c == "EN-GB" || c == "EN") return "EN"; + const std::size_t dash = c.find('-'); + return dash == std::string::npos ? c : c.substr(0, dash); +} + +TranslationOutcome DeepLProvider::translate(const TranslateRequest& request) { + if (request.texts.empty()) return TranslationOutcome::ok({}); + for (const auto& t : request.texts) { + if (trimCopy(t).empty()) { + return TranslationOutcome::fail(ProviderError::content("Cannot translate empty text")); + } + } + auto creds = credentials_->load(credentialAccount(TranslationEngineType::DeepL)); + if (!creds.has_value() || creds->apiKey.empty()) { + return TranslationOutcome::fail( + ProviderError::configuration("DeepL API key not configured")); + } + + Json body; + body["text"] = request.texts; + const std::string src = sourceCode(request.sourceLanguage); + if (!src.empty()) body["source_lang"] = src; + body["target_lang"] = targetCode(request.targetLanguage); + + HttpRequest req; + req.method = "POST"; + req.url = resolveLocalhost(normalizeEndpoint(config_.baseURL)); + req.timeoutSeconds = static_cast(config_.effectiveTimeout()); + req.cancelToken = request.cancelToken; + req.headers["Content-Type"] = "application/json"; + req.headers["Authorization"] = "DeepL-Auth-Key " + creds->apiKey; + req.body = body.dump(); + + auto outcome = transport_->send(req); + if (outcome.error.has_value()) return TranslationOutcome::fail(*outcome.error); + const HttpResponse& resp = *outcome.response; + if (!resp.ok()) { + if (resp.status == 403) { + return TranslationOutcome::fail(ProviderError::auth("DeepL: invalid API key")); + } + if (resp.status == 456) { + return TranslationOutcome::fail( + ProviderError::quota("DeepL: quota exceeded (HTTP 456)")); + } + return TranslationOutcome::fail(statusError("DeepL", resp.status, resp.body)); + } + Json json; + try { + json = Json::parse(resp.body); + } catch (const Json::parse_error&) { + return TranslationOutcome::fail(ProviderError::content("Invalid DeepL response")); + } + if (!json.contains("translations") || !json["translations"].is_array()) { + return TranslationOutcome::fail(ProviderError::content("Invalid DeepL response")); + } + const auto& translations = json["translations"]; + std::vector results; + for (std::size_t i = 0; i < request.texts.size(); ++i) { + std::string translated; + std::string detected; + if (i < translations.size() && translations[i].is_object()) { + if (translations[i].contains("text") && translations[i]["text"].is_string()) { + translated = translations[i]["text"].get(); + } + if (translations[i].contains("detected_source_language") && + translations[i]["detected_source_language"].is_string()) { + detected = translations[i]["detected_source_language"].get(); + } + } + results.emplace_back(request.texts[i], std::move(translated), + detected.empty() ? (request.sourceLanguage.empty() ? "Auto" + : request.sourceLanguage) + : std::move(detected), + request.targetLanguage); + } + return TranslationOutcome::ok(std::move(results)); +} + +// =========================================================================== +// Baidu +// =========================================================================== + +// --- Minimal MD5 (RFC 1321) — public-domain style implementation, compact +// but complete; Baidu's sign is MD5 over UTF-8 bytes so no normalization. +namespace md5detail { + +struct Context { + std::uint32_t a{0x67452301}, b{0xefcdab89}, c{0x98badcfe}, d{0x10325476}; + std::uint64_t length = 0; + std::uint8_t buffer[64]{}; + std::size_t buffered = 0; +}; + +inline std::uint32_t leftRotate(std::uint32_t x, int c) { + return (x << c) | (x >> (32 - c)); +} + +inline void processBlock(Context& ctx, const std::uint8_t* p) { + std::uint32_t m[16]; + for (int i = 0; i < 16; ++i) { + m[i] = static_cast(p[i * 4]) | + (static_cast(p[i * 4 + 1]) << 8) | + (static_cast(p[i * 4 + 2]) << 16) | + (static_cast(p[i * 4 + 3]) << 24); + } + const std::uint32_t S[64] = { + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}; + const std::uint32_t K[64] = { + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, + 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, + 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, + 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, + 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, + 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391}; + std::uint32_t A = ctx.a, B = ctx.b, C = ctx.c, D = ctx.d; + for (int i = 0; i < 64; ++i) { + std::uint32_t F; + int g; + if (i < 16) { + F = (B & C) | (~B & D); + g = i; + } else if (i < 32) { + F = (D & B) | (~D & C); + g = (5 * i + 1) % 16; + } else if (i < 48) { + F = B ^ C ^ D; + g = (3 * i + 5) % 16; + } else { + F = C ^ (B | ~D); + g = (7 * i) % 16; + } + F = F + A + K[i] + m[g]; + A = D; + D = C; + C = B; + B = B + leftRotate(F, S[i]); + } + ctx.a += A; + ctx.b += B; + ctx.c += C; + ctx.d += D; +} + +inline std::string digest(const std::string& input) { + Context ctx; + ctx.length = input.size() * 8; + const std::uint8_t* data = reinterpret_cast(input.data()); + + std::size_t offset = 0; + while (offset + 64 <= input.size()) { + processBlock(ctx, data + offset); + offset += 64; + } + std::uint8_t tail[128]{}; + const std::size_t rem = input.size() - offset; + std::memcpy(tail, data + offset, rem); + tail[rem] = 0x80; + const bool needsExtra = rem >= 56; + if (needsExtra) { + processBlock(ctx, tail); + std::memset(tail, 0, 64); + } + for (int i = 0; i < 8; ++i) { + tail[56 + i] = static_cast((ctx.length >> (8 * i)) & 0xFF); + } + processBlock(ctx, tail); + + static const char* hex = "0123456789abcdef"; + std::string out; + out.reserve(32); + const std::uint32_t words[4] = {ctx.a, ctx.b, ctx.c, ctx.d}; + for (std::uint32_t w : words) { + for (int byte = 0; byte < 4; ++byte) { + const std::uint8_t v = static_cast((w >> (8 * byte)) & 0xFF); + out += hex[v >> 4]; + out += hex[v & 0xF]; + } + } + return out; +} + +} // namespace md5detail + +BaiduProvider::BaiduProvider(EngineConfig config, CredentialStorePtr credentials, + HttpTransportPtr transport) + : config_(std::move(config)), credentials_(std::move(credentials)), + transport_(std::move(transport)) {} + +bool BaiduProvider::isAvailable() const { + return credentials_ && credentials_->has(credentialAccount(TranslationEngineType::Baidu)); +} + +std::string BaiduProvider::mapLanguageCode(const std::string& code) { + if (code.empty()) return "auto"; + const std::string l = lowerCopy(code); + static const std::vector> kMap = { + {"auto", "auto"}, {"en", "en"}, {"zh", "zh"}, {"zh-hans", "zh"}, + {"zh-cn", "zh"}, {"zh-hant", "cht"}, {"zh-tw", "cht"}, {"ja", "jp"}, + {"ko", "kor"}, {"fr", "fra"}, {"de", "de"}, {"es", "spa"}, + {"pt", "pt"}, {"ru", "ru"}, {"it", "it"}, + }; + for (const auto& [k, v] : kMap) { + if (l == k) return v; + } + return code; +} + +std::string BaiduProvider::md5Hex(const std::string& input) { return md5detail::digest(input); } + +std::string BaiduProvider::makeSign(const std::string& appid, const std::string& q, + const std::string& salt, const std::string& secretKey) { + return md5Hex(appid + q + salt + secretKey); +} + +TranslationOutcome BaiduProvider::translate(const TranslateRequest& request) { + if (request.texts.empty()) return TranslationOutcome::ok({}); + auto creds = credentials_->load(credentialAccount(TranslationEngineType::Baidu)); + if (!creds.has_value() || creds->apiKey.empty() || + (creds->appID.empty() && creds->additional.count("appID") == 0)) { + return TranslationOutcome::fail( + ProviderError::configuration("AppID or Secret Key not configured")); + } + const std::string appID = + !creds->appID.empty() ? creds->appID : creds->additional.at("appID"); + const std::string& secretKey = creds->apiKey; + + const std::string base = config_.baseURL.empty() + ? translationEngineDefaultBaseUrl(TranslationEngineType::Baidu) + : config_.baseURL; + + // One GET per text (Baidu q is single-string; Swift does the same). + std::vector results; + for (const auto& text : request.texts) { + if (trimCopy(text).empty()) { + return TranslationOutcome::fail(ProviderError::content("Cannot translate empty text")); + } + // Salt: 6-digit random (Swift Int.random(100000...999999)). + thread_local std::mt19937 rng{std::random_device{}()}; + const std::string salt = std::to_string(100000 + rng() % 900000); + const std::string sign = makeSign(appID, text, salt, secretKey); + + std::string url = resolveLocalhost(base); + url += "?q=" + urlEncode(text) + "&from=" + + urlEncode(mapLanguageCode(request.sourceLanguage)) + "&to=" + + urlEncode(mapLanguageCode(request.targetLanguage)) + "&appid=" + urlEncode(appID) + + "&salt=" + salt + "&sign=" + sign; + + HttpRequest req; + req.method = "GET"; + req.url = url; + req.timeoutSeconds = static_cast(config_.effectiveTimeout()); + req.cancelToken = request.cancelToken; + + auto outcome = transport_->send(req); + if (outcome.error.has_value()) return TranslationOutcome::fail(*outcome.error); + const HttpResponse& resp = *outcome.response; + Json json; + try { + json = Json::parse(resp.body); + } catch (const Json::parse_error&) { + return TranslationOutcome::fail(ProviderError::content("Invalid Baidu response")); + } + if (json.is_object() && json.contains("error_code") && json["error_code"].is_string()) { + const std::string errorCode = json["error_code"].get(); + std::string errorMsg = + json.contains("error_msg") && json["error_msg"].is_string() + ? json["error_msg"].get() + : ""; + if (errorCode == "54003") { + return TranslationOutcome::fail(ProviderError::quota("Baidu rate limited")); + } + if (errorCode == "54004") { + return TranslationOutcome::fail( + ProviderError::auth("Invalid Baidu AppID or Secret Key")); + } + return TranslationOutcome::fail(ProviderError::content("Baidu error: " + errorMsg)); + } + if (!json.contains("trans_result") || !json["trans_result"].is_array() || + json["trans_result"].empty()) { + return TranslationOutcome::fail(ProviderError::content("Invalid Baidu response")); + } + // Concatenate dst lines of this request (Swift joins trans_result). + std::string translated; + for (const auto& item : json["trans_result"]) { + if (item.is_object() && item.contains("dst") && item["dst"].is_string()) { + if (!translated.empty()) translated += "\n"; + translated += item["dst"].get(); + } + } + results.emplace_back(text, std::move(translated), + request.sourceLanguage.empty() ? "Auto" : request.sourceLanguage, + request.targetLanguage); + } + return TranslationOutcome::ok(std::move(results)); +} + +} // namespace tf diff --git a/windows/Core/src/CompatibleChatProvider.cpp b/windows/Core/src/CompatibleChatProvider.cpp new file mode 100644 index 0000000..4480380 --- /dev/null +++ b/windows/Core/src/CompatibleChatProvider.cpp @@ -0,0 +1,211 @@ +// CompatibleChatProvider.cpp — OpenAI-compatible multi-instance provider. +#include "tf/CompatibleChatProvider.hpp" +#include "tf/Json.hpp" +#include "tf/LLMChatProvider.hpp" +#include "tf/LLMTranslationCore.hpp" + +#include + +namespace tf { + +namespace { + +std::string trimCopy(const std::string& s) { + std::size_t b = 0, e = s.size(); + auto isSpace = [](unsigned char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; + }; + while (b < e && isSpace(static_cast(s[b]))) ++b; + while (e > b && isSpace(static_cast(s[e - 1]))) --e; + return s.substr(b, e - b); +} + +} // namespace + +CompatibleConfig CompatibleConfig::makeDefault() { + CompatibleConfig c; + c.id = Uuid::nil().toString(); // Swift default: fixed nil-UUID "Custom" + c.displayName = "Custom"; + c.baseURL = "http://localhost:8000/v1"; + c.modelName = "custom-model"; + c.hasAPIKey = true; + return c; +} + +CompatibleChatProvider::CompatibleChatProvider(CompatibleConfig compatibleConfig, + EngineConfig engineConfig, + CredentialStorePtr credentials, + HttpTransportPtr transport) + : compatible_(std::move(compatibleConfig)), + engineConfig_(std::move(engineConfig)), + credentials_(std::move(credentials)), + transport_(std::move(transport)) {} + +bool CompatibleChatProvider::isAvailable() const { + // Keyless local endpoints stay available without a stored credential + // (Swift: localhost preset may run keyless). + if (!compatible_.hasAPIKey) return true; + if (auto parsed = parseUrl(compatible_.baseURL)) { + if (isLocalhostHost(parsed->host)) return true; + } + return credentials_ && credentials_->has(credentialAccountForCompatible(compatible_.id)); +} + +std::string CompatibleChatProvider::translateEndpoint() const { + return appendingApiSuffix(resolveLocalhost(compatible_.baseURL), "chat/completions"); +} + +std::string CompatibleChatProvider::verifyEndpoint() const { + return appendingApiSuffix(resolveLocalhost(compatible_.baseURL), "models"); +} + +std::string CompatibleChatProvider::buildPrompt(const std::string& combinedText, + const std::string& sourceLanguage, + const std::string& targetLanguage, + const std::string& promptTemplate) const { + const std::string source = promptLanguageDisplayName(sourceLanguage); + const std::string target = promptLanguageDisplayName(targetLanguage); + if (!promptTemplate.empty()) { + return TranslationPromptConfig::substitute(promptTemplate, source, target, combinedText); + } + return "Translate the following text from " + source + " to " + target + ".\n" + "Provide ONLY the translated text without any explanations or additional text.\n" + "\nText to translate:\n" + + combinedText; +} + +CompatibleConfig CompatibleChatProvider::resolveConfigurationSnapshot( + const CompatibleConfig& requested, const std::vector& savedConfigs) { + // Dangling UUID (instance deleted) → first saved instance → default. + for (const auto& saved : savedConfigs) { + if (saved.id == requested.id) return saved; + } + if (!savedConfigs.empty()) return savedConfigs.front(); + return requested; +} + +TranslationOutcome CompatibleChatProvider::translate(const TranslateRequest& request) { + if (request.texts.empty()) return TranslationOutcome::ok({}); + + std::optional creds; + if (compatible_.hasAPIKey) { + creds = credentials_->load(credentialAccountForCompatible(compatible_.id)); + } + + const std::int64_t maxTokens = engineConfig_.maxTokens.value_or(2048); + const auto batches = + LLMTranslationBatching::split(request.texts, maxTokens, request.promptTemplate); + + std::vector all; + for (const auto& batch : batches) { + std::string combined; + const std::string sep(LLMTranslationBatching::separator()); + for (std::size_t i = 0; i < batch.size(); ++i) { + if (i) combined += sep; + combined += batch[i]; + } + const std::string prompt = + buildPrompt(combined, request.sourceLanguage, request.targetLanguage, + request.promptTemplate); + auto textOutcome = callApi(prompt, creds ? &*creds : nullptr, request.cancelToken); + if (!textOutcome.isOk()) return TranslationOutcome::fail(textOutcome.error); + const std::string& translated = textOutcome.value; + + std::vector parts; + { + std::size_t start = 0; + while (true) { + std::size_t idx = translated.find(sep, start); + if (idx == std::string::npos) { + parts.push_back(translated.substr(start)); + break; + } + parts.push_back(translated.substr(start, idx - start)); + start = idx + sep.size(); + } + } + if (parts.size() == batch.size()) { + for (std::size_t i = 0; i < batch.size(); ++i) { + all.emplace_back(batch[i], trimCopy(parts[i]), + request.sourceLanguage.empty() ? "Auto" : request.sourceLanguage, + request.targetLanguage); + } + } else { + // Single text (or split failure): the combined text maps to the + // whole response (Swift translateSingleBatch fallback). + all.emplace_back(combined, translated, + request.sourceLanguage.empty() ? "Auto" : request.sourceLanguage, + request.targetLanguage); + } + } + return TranslationOutcome::ok(std::move(all)); +} + +std::optional CompatibleChatProvider::verifyConnection( + const CancellationToken& token) { + std::optional creds; + if (compatible_.hasAPIKey) { + creds = credentials_->load(credentialAccountForCompatible(compatible_.id)); + } + HttpRequest req; + req.method = "GET"; + req.url = verifyEndpoint(); + req.timeoutSeconds = 10; + req.cancelToken = token; + if (creds.has_value() && !creds->apiKey.empty()) { + if (auto guard = guardApiKeyTransport(req.url, true)) return *guard; + req.headers["Authorization"] = "Bearer " + creds->apiKey; + } + auto outcome = transport_->send(req); + if (outcome.error.has_value()) return outcome.error; + if (outcome.response->ok()) return std::nullopt; + return ProviderError::network("Connection verify failed: HTTP " + + std::to_string(outcome.response->status)); +} + +Outcome CompatibleChatProvider::callApi( + const std::string& prompt, const StoredCredentials* credentials, + const CancellationToken& token) { + HttpRequest req; + req.method = "POST"; + req.url = translateEndpoint(); + req.timeoutSeconds = static_cast(engineConfig_.effectiveTimeout()); + req.cancelToken = token; + req.headers["Content-Type"] = "application/json"; + if (credentials && !credentials->apiKey.empty()) { + if (auto guard = guardApiKeyTransport(req.url, true)) { + return Outcome::makeError(*guard); + } + req.headers["Authorization"] = "Bearer " + credentials->apiKey; + } + for (const auto& [k, v] : engineConfig_.customHeaders) req.headers[k] = v; + + Json body; + body["model"] = compatible_.modelName; + body["messages"] = Json::array({Json{{"role", "user"}, {"content", prompt}}}); + body["stream"] = false; + body["temperature"] = engineConfig_.temperature.value_or(0.3); + body["max_tokens"] = engineConfig_.maxTokens.value_or(2048); + req.body = body.dump(); + + auto outcome = transport_->send(req); + if (outcome.error.has_value()) { + return Outcome::makeError(*outcome.error); + } + const HttpResponse& resp = *outcome.response; + if (resp.status == 401) { + return Outcome::makeError( + ProviderError::auth("Invalid API key")); + } + if (resp.status == 429) { + return Outcome::makeError(ProviderError::quota("Rate limited")); + } + if (resp.status != 200) { + return Outcome::makeError( + ProviderError::network("API error: HTTP " + std::to_string(resp.status))); + } + // Custom endpoints are OpenAI-compatible (Swift parses with engine .custom). + return LLMTranslationResponseParser::extractText(resp.body, TranslationEngineType::Custom); +} + +} // namespace tf diff --git a/windows/Core/src/CoreModels.cpp b/windows/Core/src/CoreModels.cpp new file mode 100644 index 0000000..e9aac87 --- /dev/null +++ b/windows/Core/src/CoreModels.cpp @@ -0,0 +1,426 @@ +// CoreModels.cpp — implementation for tf/CoreModels.hpp +#include "tf/CoreModels.hpp" + +#include +#include +#include +#include + +namespace tf { + +// --------------------------------------------------------------------------- +// UUID +// --------------------------------------------------------------------------- +Uuid Uuid::random() { + static thread_local std::mt19937_64 rng([] { + std::random_device rd; + std::seed_seq seq{rd(), rd(), rd(), rd()}; + return std::mt19937_64(seq); + }()); + Uuid u; + for (auto& b : u.bytes) b = static_cast(rng() & 0xFF); + // RFC 4122 v4 markers. + u.bytes[6] = (u.bytes[6] & 0x0F) | 0x40; + u.bytes[8] = (u.bytes[8] & 0x3F) | 0x80; + return u; +} + +Uuid Uuid::nil() { + Uuid u; + u.bytes.fill(0); + return u; +} + +bool Uuid::isNil() const { + return *this == Uuid::nil(); +} + +static int hexVal(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +std::optional Uuid::parse(const std::string& text) { + std::string s = text; + // Trim. + s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); + s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end()); + // Strip urn / braces. + if (s.rfind("urn:uuid:", 0) == 0) s = s.substr(9); + if (!s.empty() && s.front() == '{' && s.back() == '}') s = s.substr(1, s.size() - 2); + + auto isHex = [](const std::string& t, std::size_t from, std::size_t n) { + if (from + n > t.size()) return false; + for (std::size_t i = from; i < from + n; ++i) { + if (hexVal(t[i]) < 0) return false; + } + return true; + }; + // Accept canonical 8-4-4-4-12 and plain 32-hex. + if (s.size() == 36 && s[8] == '-' && s[13] == '-' && s[18] == '-' && s[23] == '-' && + isHex(s, 0, 8) && isHex(s, 9, 4) && isHex(s, 14, 4) && isHex(s, 19, 4) && isHex(s, 24, 12)) { + Uuid u; + int hi = -1; + int idx = 0; + for (char c : s) { + if (c == '-') continue; + int v = hexVal(c); + if (hi < 0) hi = v; + else { + u.bytes[idx++] = static_cast((hi << 4) | v); + hi = -1; + } + } + return u; + } + if (s.size() == 32 && isHex(s, 0, 32)) { + Uuid u; + int hi = -1; + int idx = 0; + for (char c : s) { + int v = hexVal(c); + if (hi < 0) hi = v; + else { + u.bytes[idx++] = static_cast((hi << 4) | v); + hi = -1; + } + } + return u; + } + return std::nullopt; +} + +std::string Uuid::toString() const { + static const char* hex = "0123456789abcdef"; + std::string s; + s.reserve(36); + for (int i = 0; i < 16; ++i) { + if (i == 4 || i == 6 || i == 8 || i == 10) s += '-'; + s += hex[bytes[i] >> 4]; + s += hex[bytes[i] & 0xF]; + } + return s; +} + +// --------------------------------------------------------------------------- +// NormRect / TextSegment / OcrResult +// --------------------------------------------------------------------------- +NormRect NormRect::unionWith(const NormRect& o) const { + const double l = std::min(minX(), o.minX()); + const double t = std::min(minY(), o.minY()); + const double r = std::max(maxX(), o.maxX()); + const double b = std::max(maxY(), o.maxY()); + return {l, t, r - l, b - t}; +} + +TextSegment::TextSegment(std::string text_, NormRect box, float conf, bool edited) + : text(std::move(text_)), boundingBox(box), confidence(conf), isUserEdited(edited) { + id = Uuid::random().toString(); +} + +TextSegment TextSegment::make(std::string text, NormRect box, float conf) { + return TextSegment(std::move(text), box, conf, false); +} + +std::string OcrResult::fullText() const { + std::vector sorted; + sorted.reserve(observations.size()); + for (const auto& o : observations) sorted.push_back(&o); + std::stable_sort(sorted.begin(), sorted.end(), [](const TextSegment* a, const TextSegment* b) { + return a->boundingBox.minY() < b->boundingBox.minY(); + }); + std::string out; + for (const auto* s : sorted) { + if (!out.empty()) out += '\n'; + out += s->text; + } + return out; +} + +OcrResult OcrResult::empty(std::int64_t w, std::int64_t h) { + OcrResult r; + r.imageWidth = w; + r.imageHeight = h; + r.timestampMs = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + return r; +} + +// --------------------------------------------------------------------------- +// TranslationEngineType +// --------------------------------------------------------------------------- +std::vector allTranslationEngines() { + return {TranslationEngineType::MtranServer, TranslationEngineType::OpenAI, + TranslationEngineType::Claude, TranslationEngineType::Gemini, + TranslationEngineType::Ollama, TranslationEngineType::Google, + TranslationEngineType::DeepL, TranslationEngineType::Baidu, + TranslationEngineType::Custom}; +} + +const char* translationEngineRaw(TranslationEngineType t) { + switch (t) { + case TranslationEngineType::MtranServer: return "mtran"; + case TranslationEngineType::OpenAI: return "openai"; + case TranslationEngineType::Claude: return "claude"; + case TranslationEngineType::Gemini: return "gemini"; + case TranslationEngineType::Ollama: return "ollama"; + case TranslationEngineType::Google: return "google"; + case TranslationEngineType::DeepL: return "deepl"; + case TranslationEngineType::Baidu: return "baidu"; + case TranslationEngineType::Custom: return "custom"; + } + return "custom"; +} + +std::optional translationEngineFromRaw(const std::string& raw) { + for (auto t : allTranslationEngines()) { + if (raw == translationEngineRaw(t)) return t; + } + return std::nullopt; +} + +const char* translationEngineDisplayName(TranslationEngineType t) { + switch (t) { + case TranslationEngineType::MtranServer: return "MTranServer"; + case TranslationEngineType::OpenAI: return "OpenAI"; + case TranslationEngineType::Claude: return "Claude"; + case TranslationEngineType::Gemini: return "Gemini"; + case TranslationEngineType::Ollama: return "Ollama"; + case TranslationEngineType::Google: return "Google Translate"; + case TranslationEngineType::DeepL: return "DeepL"; + case TranslationEngineType::Baidu: return "Baidu Translate"; + case TranslationEngineType::Custom: return "Custom"; + } + return "Custom"; +} + +bool translationEngineRequiresApiKey(TranslationEngineType t) { + switch (t) { + case TranslationEngineType::MtranServer: + case TranslationEngineType::Ollama: + return false; + case TranslationEngineType::OpenAI: + case TranslationEngineType::Claude: + case TranslationEngineType::Gemini: + case TranslationEngineType::Google: + case TranslationEngineType::DeepL: + case TranslationEngineType::Baidu: + case TranslationEngineType::Custom: + return true; + } + return true; +} + +bool translationEngineRequiresAppId(TranslationEngineType t) { + return t == TranslationEngineType::Baidu; +} + +std::string translationEngineDefaultBaseUrl(TranslationEngineType t) { + switch (t) { + case TranslationEngineType::OpenAI: return "https://api.openai.com/v1"; + case TranslationEngineType::Claude: return "https://api.anthropic.com/v1"; + case TranslationEngineType::Gemini: return "https://generativelanguage.googleapis.com/v1beta"; + case TranslationEngineType::Ollama: return "http://localhost:11434"; + case TranslationEngineType::Google: return "https://translation.googleapis.com/language/translate/v2"; + case TranslationEngineType::DeepL: return "https://api.deepl.com/v2/translate"; + case TranslationEngineType::Baidu: return "https://fanyi-api.baidu.com/api/trans/vip/translate"; + case TranslationEngineType::MtranServer: return "http://localhost:8989"; + case TranslationEngineType::Custom: return "http://localhost:8000/v1"; + } + return ""; +} + +std::string translationEngineDefaultModelName(TranslationEngineType t) { + switch (t) { + case TranslationEngineType::OpenAI: return "gpt-4o-mini"; + case TranslationEngineType::Claude: return "claude-sonnet-4-20250514"; + case TranslationEngineType::Gemini: return "gemini-2.0-flash"; + case TranslationEngineType::Ollama: return "llama3"; + default: return ""; + } +} + +// --------------------------------------------------------------------------- +// EngineChainItem +// --------------------------------------------------------------------------- +EngineChainItem EngineChainItem::makeBuiltin(TranslationEngineType t) { + EngineChainItem item; + item.kind = Kind::Builtin; + item.builtin = t; + item.id = Uuid::random().toString(); + return item; +} + +EngineChainItem EngineChainItem::makeCompatible(const std::string& uuid) { + EngineChainItem item; + item.kind = Kind::Compatible; + item.compatibleId = uuid; + item.id = Uuid::random().toString(); + return item; +} + +TranslationEngineType EngineChainItem::resolvedEngine() const { + return kind == Kind::Builtin ? builtin : TranslationEngineType::Custom; +} + +const char* translationSceneRaw(TranslationScene s) { + switch (s) { + case TranslationScene::Screenshot: return "screenshot"; + case TranslationScene::TextSelection: return "text_selection"; + case TranslationScene::TranslateAndInsert: return "translate_and_insert"; + } + return "screenshot"; +} + +std::optional translationSceneFromRaw(const std::string& raw) { + if (raw == "screenshot") return TranslationScene::Screenshot; + if (raw == "text_selection") return TranslationScene::TextSelection; + if (raw == "translate_and_insert") return TranslationScene::TranslateAndInsert; + return std::nullopt; +} + +// --------------------------------------------------------------------------- +// TranslationPromptConfig (Swift promptPreview layering). +// --------------------------------------------------------------------------- +const std::string& TranslationPromptConfig::defaultPrompt() { + static const std::string p = + "Translate the following text from {source_language} to {target_language}.\n" + "Provide only the translation without any explanations or additional text.\n" + "\n" + "Text to translate:\n" + "{text}"; + return p; +} + +const std::string& TranslationPromptConfig::defaultInsertPrompt() { + static const std::string p = + "Translate the following text from {source_language} to {target_language}.\n" + "The translation will be inserted at the cursor position.\n" + "Provide only the translation without any explanations, formatting, or additional text.\n" + "Keep the translation concise and natural for the target language.\n" + "\n" + "Text to translate:\n" + "{text}"; + return p; +} + +std::string TranslationPromptConfig::resolve(TranslationEngineType engine, + TranslationScene scene, + const std::string& compatiblePromptId) const { + // Layer order (Swift promptPreview): scene > compatible > engine > + // insert-scene default > global default. + for (const auto& [s, p] : scenePrompts) { + if (s == scene && !p.empty()) return p; + } + if (engine == TranslationEngineType::Custom && !compatiblePromptId.empty()) { + for (const auto& [id, p] : compatibleEnginePrompts) { + if (id == compatiblePromptId && !p.empty()) return p; + } + } + for (const auto& [e, p] : enginePrompts) { + if (e == engine && !p.empty()) return p; + } + if (scene == TranslationScene::TranslateAndInsert) return defaultInsertPrompt(); + return defaultPrompt(); +} + +std::string TranslationPromptConfig::substitute(const std::string& templateText, + const std::string& sourceLanguage, + const std::string& targetLanguage, + const std::string& text) { + std::string out = templateText; + auto replaceAll = [&out](const std::string& needle, const std::string& value) { + std::size_t pos = 0; + while ((pos = out.find(needle, pos)) != std::string::npos) { + out.replace(pos, needle.size(), value); + pos += value.size(); + } + }; + replaceAll("{source_language}", sourceLanguage); + replaceAll("{target_language}", targetLanguage); + replaceAll("{text}", text); + return out; +} + +// --------------------------------------------------------------------------- +// Results +// --------------------------------------------------------------------------- +TranslationResult::TranslationResult(std::string src, std::string translated, + std::string srcLang, std::string tgtLang) + : sourceText(std::move(src)), + translatedText(std::move(translated)), + sourceLanguage(std::move(srcLang)), + targetLanguage(std::move(tgtLang)) {} + +BilingualSegment BilingualSegment::fromResult(const TranslationResult& r) { + BilingualSegment b; + b.id = Uuid::random().toString(); + TextSegment seg(r.sourceText, NormRect{}, 1.0f, false); + b.original = std::move(seg); + b.translated = r.translatedText; + b.sourceLanguage = r.sourceLanguage; + b.targetLanguage = r.targetLanguage; + return b; +} + +EngineResult EngineResult::makeFailure(TranslationEngineType engine, std::string errorText, + double latency, std::string displayName) { + EngineResult r; + r.engine = engine; + r.failed = true; + r.errorText = std::move(errorText); + r.latencySeconds = latency; + r.displayName = std::move(displayName); + return r; +} + +std::vector TranslationResultBundle::successfulEngines() const { + std::vector out; + for (const auto& r : results) { + if (r.isSuccess()) out.push_back(r.engine); + } + return out; +} + +// --------------------------------------------------------------------------- +// VLM / OCR selectors + error categories +// --------------------------------------------------------------------------- +const char* vlmProviderRaw(VlmProviderType t) { + switch (t) { + case VlmProviderType::OpenAI: return "openai"; + case VlmProviderType::Claude: return "claude"; + case VlmProviderType::Gemini: return "gemini"; + case VlmProviderType::Ollama: return "ollama"; + case VlmProviderType::PaddleOCR: return "paddleocr"; + } + return "openai"; +} + +std::optional vlmProviderFromRaw(const std::string& raw) { + if (raw == "openai") return VlmProviderType::OpenAI; + if (raw == "claude") return VlmProviderType::Claude; + if (raw == "gemini") return VlmProviderType::Gemini; + if (raw == "ollama") return VlmProviderType::Ollama; + if (raw == "paddleocr") return VlmProviderType::PaddleOCR; + return std::nullopt; +} + +const char* ocrEngineRaw(OcrEngineType t) { + return t == OcrEngineType::WindowsOcr ? "windowsOcr" : "paddleocr"; +} + +const char* errorCategoryName(ErrorCategory c) { + switch (c) { + case ErrorCategory::Network: return "network"; + case ErrorCategory::Quota: return "quota"; + case ErrorCategory::Auth: return "auth"; + case ErrorCategory::Content: return "content"; + case ErrorCategory::Configuration: return "configuration"; + } + return "network"; +} + +} // namespace tf diff --git a/windows/Core/src/CredentialAccounts.cpp b/windows/Core/src/CredentialAccounts.cpp new file mode 100644 index 0000000..768d3d5 --- /dev/null +++ b/windows/Core/src/CredentialAccounts.cpp @@ -0,0 +1,35 @@ +// CredentialAccounts.cpp — credential account naming + key masking + config +// factories (brief §5: "TransFrame//"; Swift +// KeychainService.serviceName / maskApiKey). +#include "tf/TranslationProvider.hpp" + +namespace tf { + +std::string credentialAccount(TranslationEngineType engine) { + // Builtin engines: the raw engine string ("openai", "mtran", ...). + return translationEngineRaw(engine); +} + +std::string credentialAccountForCompatible(const std::string& instanceUuid) { + // Compatible instances: "custom:" (Swift compatibleServiceName — + // stays stable across displayName edits). + return "custom:" + instanceUuid; +} + +std::string maskApiKey(const std::string& apiKey) { + // "sk-abcdefghijklmnop" → "sk-****mnop" (first 3 + **** + last 4); short + // keys collapse to "****" so nothing usable leaks. + const std::size_t n = apiKey.size(); + if (n < 8) return "****"; + return apiKey.substr(0, 3) + "****" + apiKey.substr(n - 4); +} + +EngineConfig EngineConfig::make(TranslationEngineType t) { + EngineConfig c; + c.engine = t; + c.baseURL = translationEngineDefaultBaseUrl(t); + c.modelName = translationEngineDefaultModelName(t); + return c; +} + +} // namespace tf diff --git a/windows/Core/src/EngineHealthChecker.cpp b/windows/Core/src/EngineHealthChecker.cpp new file mode 100644 index 0000000..fc0cf1c --- /dev/null +++ b/windows/Core/src/EngineHealthChecker.cpp @@ -0,0 +1,145 @@ +// EngineHealthChecker.cpp — green/red/orange/gray probe + 60s cache. +#include "tf/EngineHealthChecker.hpp" +#include "tf/CompatibleChatProvider.hpp" +#include "tf/LLMChatProvider.hpp" +#include "tf/MTranServerProvider.hpp" +#include "tf/TranslationScheduler.hpp" + +#include +#include + +namespace tf { + +std::string shortReason(const std::optional& error) { + if (!error.has_value()) return ""; + std::string text = error->message; + if (text.size() > 120) text = text.substr(0, 120); + return text; +} + +namespace { +double defaultClock() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()) + .count(); +} +} // namespace + +DefaultEngineProbe::DefaultEngineProbe( + CredentialStorePtr credentials, HttpTransportPtr transport, + std::function()> compatibleConfigs) + : credentials_(std::move(credentials)), + transport_(std::move(transport)), + compatibleConfigs_(std::move(compatibleConfigs)) {} + +EngineHealth DefaultEngineProbe::probe(const EngineHealthKey& key, + const CancellationToken& token) { + if (!key.isBuiltin) { + // Compatible instance: dangling UUID (deleted) → red. + std::vector configs = + compatibleConfigs_ ? compatibleConfigs_() : std::vector{}; + auto it = std::find_if(configs.begin(), configs.end(), + [&](const CompatibleConfig& c) { return c.id == key.compatibleId; }); + if (it == configs.end()) { + return EngineHealth::Misconfigured; // instance deleted + } + // Credential gate only when the instance declares a key. + if (it->hasAPIKey) { + if (!credentials_ || !credentials_->has(credentialAccountForCompatible(it->id))) { + return EngineHealth::Unconfigured; + } + } + // Free models-list probe on the injected transport. + CompatibleChatProvider provider(*it, EngineConfig::make(TranslationEngineType::Custom), + credentials_, transport_); + auto err = provider.verifyConnection(token); + if (!err.has_value()) return EngineHealth::Available; + return EngineHealth::Misconfigured; + } + + switch (key.builtin) { + case TranslationEngineType::MtranServer: { + // Probe the configured endpoint (remote server must not be judged + // by localhost's fate — Swift PR #94). + MTranServerProvider provider(MTranServerProvider::Configuration::makeDefault(), + transport_); + auto err = provider.verifyConnection(token); + if (!err.has_value()) return EngineHealth::Available; + return EngineHealth::Misconfigured; + } + case TranslationEngineType::Google: + case TranslationEngineType::Baidu: + // No free probe endpoint: orange without keys, gray with. + if (credentials_ && credentials_->has(credentialAccount(key.builtin))) { + return EngineHealth::Unverified; + } + return EngineHealth::Unconfigured; + case TranslationEngineType::Claude: + case TranslationEngineType::Gemini: + case TranslationEngineType::DeepL: + // Their verifyConnection actually translates "1" (paid call) — + // automatic probes must not consume quota (Swift policy). + if (credentials_ && credentials_->has(credentialAccount(key.builtin))) { + return EngineHealth::Unverified; + } + return EngineHealth::Unconfigured; + case TranslationEngineType::OpenAI: + case TranslationEngineType::Ollama: { + // Free models-list probe behind a credentials gate (openai only). + if (key.builtin == TranslationEngineType::OpenAI) { + if (!credentials_ || !credentials_->has(credentialAccount(key.builtin))) { + return EngineHealth::Unconfigured; + } + } + LLMChatProvider provider(key.builtin, + EngineConfig::make(key.builtin), credentials_, transport_); + auto err = provider.verifyConnection(token); + if (!err.has_value()) return EngineHealth::Available; + return EngineHealth::Misconfigured; + } + case TranslationEngineType::Custom: + // Builtin "custom" slot is the dynamic instance list; probing it + // directly has no endpoint. Gray (Swift: no case for it — the UI + // only lists instances). + return EngineHealth::Unverified; + } + return EngineHealth::Unverified; +} + +EngineHealthChecker::EngineHealthChecker(std::shared_ptr probe, double ttlSeconds, + std::function clock) + : probe_(std::move(probe)), ttl_(ttlSeconds), clock_(clock ? std::move(clock) : defaultClock) {} + +EngineHealth EngineHealthChecker::health(const EngineHealthKey& key, const CancellationToken& token) { + { + std::lock_guard lock(mutex_); + auto it = cache_.find(key); + if (it != cache_.end() && clock_() - it->second.at < ttl_) { + return it->second.health; + } + } + return refresh(key, token); +} + +EngineHealth EngineHealthChecker::refresh(const EngineHealthKey& key, const CancellationToken& token) { + EngineHealth result = probe_ ? probe_->probe(key, token) : EngineHealth::Unverified; + std::lock_guard lock(mutex_); + cache_[key] = Entry{result, "", clock_()}; + return result; +} + +void EngineHealthChecker::invalidateAll() { + std::lock_guard lock(mutex_); + cache_.clear(); +} + +void EngineHealthChecker::overrideClock(std::function clock) { + std::lock_guard lock(mutex_); + clock_ = clock ? std::move(clock) : defaultClock; +} + +void EngineHealthChecker::injectHealth(const EngineHealthKey& key, EngineHealth health, double at) { + std::lock_guard lock(mutex_); + cache_[key] = Entry{health, "", at}; +} + +} // namespace tf diff --git a/windows/Core/src/HttpTransport.cpp b/windows/Core/src/HttpTransport.cpp new file mode 100644 index 0000000..fb24157 --- /dev/null +++ b/windows/Core/src/HttpTransport.cpp @@ -0,0 +1,195 @@ +// HttpTransport.cpp — pure URL/transport helpers (platform-clean). +#include "tf/HttpTransport.hpp" + +#include +#include + +namespace tf { + +std::string ParsedUrl::authority() const { + const bool defaultPort = (scheme == "http" && port == 80) || (scheme == "https" && port == 443); + if (defaultPort || port == 0) return host; + return host + ":" + std::to_string(port); +} + +std::string ParsedUrl::toString() const { + std::string out = scheme + "://" + authority(); + out += path.empty() ? "/" : path; + out += query; + return out; +} + +std::optional parseUrl(const std::string& url) { + ParsedUrl p; + std::size_t schemeEnd = url.find("://"); + if (schemeEnd == std::string::npos || schemeEnd == 0) return std::nullopt; + p.scheme = url.substr(0, schemeEnd); + std::transform(p.scheme.begin(), p.scheme.end(), p.scheme.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + if (p.scheme != "http" && p.scheme != "https") return std::nullopt; + + std::size_t restPos = schemeEnd + 3; + std::size_t pathPos = url.find('/', restPos); + std::string authority = pathPos == std::string::npos ? url.substr(restPos) + : url.substr(restPos, pathPos - restPos); + // Split query. + std::size_t qPos = url.find('?'); + if (qPos != std::string::npos) { + p.query = url.substr(qPos); + } + std::size_t pathLimit = (qPos != std::string::npos && qPos > pathPos) ? qPos : url.size(); + p.path = pathPos == std::string::npos ? "/" : url.substr(pathPos, pathLimit - pathPos); + if (p.path.empty()) p.path = "/"; + + // Host[:port]. IPv6 [::1]:port. + std::string hostPort = authority; + std::size_t frag = hostPort.find('#'); + if (frag != std::string::npos) hostPort = hostPort.substr(0, frag); + + if (!hostPort.empty() && hostPort[0] == '[') { + std::size_t close = hostPort.find(']'); + if (close == std::string::npos) return std::nullopt; + p.host = hostPort.substr(0, close + 1); + if (close + 1 < hostPort.size()) { + if (hostPort[close + 1] != ':') return std::nullopt; + int port = std::atoi(hostPort.c_str() + close + 2); + if (port <= 0 || port > 65535) return std::nullopt; + p.port = port; + } + } else { + std::size_t colon = hostPort.find(':'); + if (colon != std::string::npos) { + p.host = hostPort.substr(0, colon); + int port = std::atoi(hostPort.c_str() + colon + 1); + if (port <= 0 || port > 65535) return std::nullopt; + p.port = port; + } else { + p.host = hostPort; + } + } + if (p.host.empty()) return std::nullopt; + std::transform(p.host.begin(), p.host.end(), p.host.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + if (p.port == 0) p.port = (p.scheme == "https") ? 443 : 80; + return p; +} + +std::string resolveLocalhost(const std::string& url) { + auto parsed = parseUrl(url); + if (!parsed.has_value()) return url; + std::string lowered = parsed->host; + if (lowered == "localhost") { + const bool defaultPort = + (parsed->scheme == "http" && parsed->port == 80) || + (parsed->scheme == "https" && parsed->port == 443); + std::string replacement = parsed->scheme + "://127.0.0.1"; + if (!defaultPort) replacement += ":" + std::to_string(parsed->port); + std::string tail = parsed->path.empty() ? "/" : parsed->path; + return replacement + tail + parsed->query; + } + return url; +} + +static std::vector splitPath(const std::string& path) { + std::vector parts; + std::size_t start = 0; + while (start < path.size()) { + std::size_t slash = path.find('/', start); + if (slash == std::string::npos) { + std::string seg = path.substr(start); + if (!seg.empty()) parts.push_back(seg); + break; + } + if (slash > start) parts.push_back(path.substr(start, slash - start)); + start = slash + 1; + } + return parts; +} + +static std::string lower(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return s; +} + +std::string appendingApiSuffix(const std::string& baseUrl, const std::string& suffix) { + auto parsed = parseUrl(baseUrl); + if (!parsed.has_value()) return baseUrl; + + std::string trimmedPath = parsed->path; + while (!trimmedPath.empty() && trimmedPath.back() == '/') trimmedPath.pop_back(); + const std::vector baseParts = splitPath(trimmedPath); + const std::vector suffixParts = splitPath(suffix); + + // Longest overlapping tail-of-base == head-of-suffix (case-insensitive). + std::vector effectiveParts = baseParts; + bool merged = false; + const int maxOverlap = static_cast(std::min(baseParts.size(), suffixParts.size())); + for (int overlap = maxOverlap; overlap >= 1; --overlap) { + bool same = true; + for (int i = 0; i < overlap; ++i) { + if (lower(baseParts[baseParts.size() - overlap + i]) != lower(suffixParts[i])) { + same = false; + break; + } + } + if (same) { + for (std::size_t i = overlap; i < suffixParts.size(); ++i) { + effectiveParts.push_back(suffixParts[i]); + } + merged = true; + break; + } + } + if (!merged) { + for (const auto& sp : suffixParts) effectiveParts.push_back(sp); + } + + std::string newPath; + for (const auto& part : effectiveParts) newPath += "/" + part; + if (newPath.empty()) newPath = "/"; + ParsedUrl out = *parsed; + out.path = newPath; + return out.toString(); +} + +bool isLocalhostHost(const std::string& host) { + std::string h = lower(host); + if (!h.empty() && h.front() == '[' && h.back() == ']') { + h = h.substr(1, h.size() - 2); + } + return h == "localhost" || h == "127.0.0.1" || h == "::1" || h == "0.0.0.0" || + (h.size() > 6 && h.compare(h.size() - 6, 6, ".local") == 0); +} + +std::optional guardApiKeyTransport(const std::string& url, bool sendingApiKey) { + if (!sendingApiKey) return std::nullopt; + auto parsed = parseUrl(url); + if (!parsed.has_value()) { + return ProviderError::configuration("Invalid URL: " + url); + } + if (parsed->scheme != "https" && !isLocalhostHost(parsed->host)) { + return ProviderError::auth( + "Refusing to send API key over insecure connection (HTTP). Use HTTPS or a localhost URL."); + } + return std::nullopt; +} + +std::string urlEncode(const std::string& value) { + static const char* hex = "0123456789ABCDEF"; + std::string out; + out.reserve(value.size() * 3 / 2); + for (unsigned char c : value) { + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + c == '-' || c == '_' || c == '.' || c == '~') { + out += static_cast(c); + } else { + out += '%'; + out += hex[c >> 4]; + out += hex[c & 0xF]; + } + } + return out; +} + +} // namespace tf diff --git a/windows/Core/src/LLMChatProvider.cpp b/windows/Core/src/LLMChatProvider.cpp new file mode 100644 index 0000000..49dc9d4 --- /dev/null +++ b/windows/Core/src/LLMChatProvider.cpp @@ -0,0 +1,315 @@ +// LLMChatProvider.cpp — OpenAI / Claude / Gemini / Ollama chat-completions +// provider (port of Swift LLMTranslationProvider.swift). +#include "tf/LLMChatProvider.hpp" +#include "tf/Json.hpp" + +#include + +namespace tf { + +namespace { + +std::string trimCopy(const std::string& s) { + std::size_t b = 0, e = s.size(); + auto isSpace = [](unsigned char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; + }; + while (b < e && isSpace(static_cast(s[b]))) ++b; + while (e > b && isSpace(static_cast(s[e - 1]))) --e; + return s.substr(b, e - b); +} + +/// English language display names for the prompt (Swift TranslationLanguage +/// displayName with locale en, normalized "Primary (Region)" form). +std::string languageName(const std::string& code) { + static const std::vector> kNames = { + {"en", "English"}, {"zh-Hans", "Chinese (Simplified)"}, {"zh-Hant", "Chinese (Traditional)"}, + {"ja", "Japanese"}, {"ko", "Korean"}, {"fr", "French"}, {"de", "German"}, + {"es", "Spanish"}, {"it", "Italian"}, {"pt", "Portuguese"}, {"ru", "Russian"}, + {"ar", "Arabic"}, {"hi", "Hindi"}, {"th", "Thai"}, {"vi", "Vietnamese"}, + {"nl", "Dutch"}, {"pl", "Polish"}, {"tr", "Turkish"}, {"uk", "Ukrainian"}, + {"cs", "Czech"}, {"sv", "Swedish"}, {"da", "Danish"}, {"fi", "Finnish"}, + {"no", "Norwegian"}, {"el", "Greek"}, {"he", "Hebrew"}, {"id", "Indonesian"}, + {"ms", "Malay"}, {"ro", "Romanian"}, {"zh", "Chinese (Simplified)"}, + }; + if (code.empty() || code == "auto" || code == "Auto") return "Auto Detect"; + for (const auto& [k, v] : kNames) { + if (code == k) return v; + } + // Base-code fallback ("en-US" → "English"). + std::size_t dash = code.find('-'); + if (dash != std::string::npos && dash > 0) { + const std::string base = code.substr(0, dash); + for (const auto& [k, v] : kNames) { + if (base == k) return v; + } + } + return code; +} + +} // namespace + +std::string promptLanguageDisplayName(const std::string& code) { return languageName(code); } + +LLMChatProvider::LLMChatProvider(TranslationEngineType engine, EngineConfig config, + CredentialStorePtr credentials, HttpTransportPtr transport) + : engine_(engine), config_(std::move(config)), + credentials_(std::move(credentials)), transport_(std::move(transport)) {} + +std::string LLMChatProvider::name() const { + switch (engine_) { + case TranslationEngineType::OpenAI: return "OpenAI Translation"; + case TranslationEngineType::Claude: return "Claude Translation"; + case TranslationEngineType::Gemini: return "Gemini Translation"; + case TranslationEngineType::Ollama: return "Ollama Translation"; + default: return "LLM Translation"; + } +} + +bool LLMChatProvider::isAvailable() const { + // Ollama needs no key (Swift). + if (engine_ == TranslationEngineType::Ollama) return true; + // Local OpenAI-compatible endpoints (LM Studio / vLLM presets on + // localhost) may run keyless — a credential miss must not hard-disable + // them (Swift PR #92 behavior). + if (engine_ == TranslationEngineType::OpenAI && !config_.baseURL.empty()) { + if (auto parsed = parseUrl(config_.baseURL)) { + if (isLocalhostHost(parsed->host)) return true; + } + } + return credentials_ && credentials_->has(credentialAccount(engine_)); +} + +std::string LLMChatProvider::endpointForRequest() const { + std::string base = config_.baseURL.empty() ? translationEngineDefaultBaseUrl(engine_) + : config_.baseURL; + base = resolveLocalhost(base); + switch (engine_) { + case TranslationEngineType::Claude: + return appendingApiSuffix(base, "v1/messages"); + case TranslationEngineType::Gemini: + return appendingApiSuffix(base, "v1beta/openai/chat/completions"); + case TranslationEngineType::Ollama: + return appendingApiSuffix(base, "v1/chat/completions"); + default: // openai — base typically ends with /v1 + return appendingApiSuffix(base, "chat/completions"); + } +} + +std::string LLMChatProvider::verifyEndpoint() const { + const std::string base = resolveLocalhost( + config_.baseURL.empty() ? translationEngineDefaultBaseUrl(engine_) : config_.baseURL); + // Same path family as translation so "test passes but translate 404" + // (or vice versa) cannot diverge (Swift PR comment). + return appendingApiSuffix(base, engine_ == TranslationEngineType::Ollama ? "v1/models" + : "models"); +} + +std::string LLMChatProvider::buildPrompt(const std::string& combinedText, + const std::string& sourceLanguage, + const std::string& targetLanguage, + const std::string& promptTemplate) const { + const std::string source = languageName(sourceLanguage); + const std::string target = languageName(targetLanguage); + + if (!promptTemplate.empty()) { + return TranslationPromptConfig::substitute(promptTemplate, source, target, combinedText); + } + // Default prompt with separator-preservation hint when batching markers + // are present (Swift buildPrompt). + const std::string sep(LLMTranslationBatching::separator()); + const bool hasSeparator = combinedText.find(sep) != std::string::npos; + std::string hint = + hasSeparator + ? "Preserve the literal '---' separators exactly where they appear in the input. Do " + "not add or remove any separators." + : ""; + return "Translate the following text from " + source + " to " + target + ".\n" + "Provide ONLY the translated text without any explanations, notes, or formatting.\n" + + hint + "\n\nText to translate:\n" + combinedText; +} + +TranslationOutcome LLMChatProvider::translate(const TranslateRequest& request) { + if (request.texts.empty()) return TranslationOutcome::ok({}); + + std::optional creds; + if (translationEngineRequiresApiKey(engine_) && engine_ != TranslationEngineType::Ollama) { + creds = credentials_->load(credentialAccount(engine_)); + if (!creds.has_value()) { + return TranslationOutcome::fail(ProviderError::configuration( + "API key required for " + std::string(translationEngineRaw(engine_)))); + } + } + + const std::int64_t maxTokens = config_.maxTokens.value_or(2048); + const auto batches = LLMTranslationBatching::split(request.texts, maxTokens, + request.promptTemplate); + + std::vector all; + for (const auto& batch : batches) { + const std::string combined = [&] { + std::string out; + const std::string sep(LLMTranslationBatching::separator()); + for (std::size_t i = 0; i < batch.size(); ++i) { + if (i) out += sep; + out += batch[i]; + } + return out; + }(); + const std::string prompt = + buildPrompt(combined, request.sourceLanguage, request.targetLanguage, + request.promptTemplate); + auto textOutcome = callApi(prompt, creds ? &*creds : nullptr, request.cancelToken); + if (!textOutcome.isOk()) { + return TranslationOutcome::fail(textOutcome.error); + } + const std::string translated = textOutcome.value; + + // Split by separator; on count match → zip; single text → whole; + // mismatch → per-text fallback (Swift translateSingleBatch). + std::vector parts; + { + const std::string sep(LLMTranslationBatching::separator()); + std::size_t start = 0; + while (true) { + std::size_t idx = translated.find(sep, start); + if (idx == std::string::npos) { + parts.push_back(translated.substr(start)); + break; + } + parts.push_back(translated.substr(start, idx - start)); + start = idx + sep.size(); + } + } + if (parts.size() == batch.size()) { + for (std::size_t i = 0; i < batch.size(); ++i) { + all.emplace_back(batch[i], trimCopy(parts[i]), + request.sourceLanguage.empty() ? "Auto" : request.sourceLanguage, + request.targetLanguage); + } + } else if (batch.size() == 1) { + all.emplace_back(combined, translated, + request.sourceLanguage.empty() ? "Auto" : request.sourceLanguage, + request.targetLanguage); + } else { + // Batch split failed → retranslate texts individually. + for (const auto& text : batch) { + TranslateRequest single = request; + single.texts = {text}; + auto one = translate(single); + if (!one.results.has_value()) return one; + for (auto& r : *one.results) all.push_back(std::move(r)); + } + } + } + return TranslationOutcome::ok(std::move(all)); +} + +std::optional LLMChatProvider::verifyConnection(const CancellationToken& token) { + // OpenAI/Ollama: free models-list GET. Claude/Gemini have no free probe — + // report "no free probe" (nullopt) so the health checker marks them + // gray (Swift EngineHealthChecker policy). + if (engine_ != TranslationEngineType::OpenAI && engine_ != TranslationEngineType::Ollama) { + return std::nullopt; + } + std::optional creds; + if (engine_ == TranslationEngineType::OpenAI) { + creds = credentials_ ? credentials_->load(credentialAccount(engine_)) : std::nullopt; + } + HttpRequest req; + req.method = "GET"; + req.url = verifyEndpoint(); + req.timeoutSeconds = 10; + req.cancelToken = token; + if (creds.has_value() && !creds->apiKey.empty()) { + if (auto guard = guardApiKeyTransport(req.url, true)) return *guard; + req.headers["Authorization"] = "Bearer " + creds->apiKey; + } + auto outcome = transport_->send(req); + if (!outcome.error.has_value() && outcome.response->ok()) return std::nullopt; + if (outcome.error.has_value()) return outcome.error; + return ProviderError::network("Connection verify failed: HTTP " + + std::to_string(outcome.response->status)); +} + +Outcome LLMChatProvider::callApi( + const std::string& prompt, const StoredCredentials* credentials, + const CancellationToken& token) { + const std::string endpoint = endpointForRequest(); + const std::string model = + config_.modelName.empty() ? translationEngineDefaultModelName(engine_) : config_.modelName; + + HttpRequest req; + req.method = "POST"; + req.url = endpoint; + req.timeoutSeconds = static_cast(config_.effectiveTimeout()); + req.cancelToken = token; + req.headers["Content-Type"] = "application/json"; + + const bool hasKey = credentials && !credentials->apiKey.empty(); + switch (engine_) { + case TranslationEngineType::Claude: + if (hasKey) { + if (auto guard = guardApiKeyTransport(req.url, true)) { + return Outcome::makeError(*guard); + } + req.headers["x-api-key"] = credentials->apiKey; + req.headers["anthropic-version"] = "2023-06-01"; + } + break; + case TranslationEngineType::Gemini: + if (hasKey) { + if (auto guard = guardApiKeyTransport(req.url, true)) { + return Outcome::makeError(*guard); + } + req.headers["Authorization"] = "Bearer " + credentials->apiKey; + } + break; + case TranslationEngineType::Ollama: + break; // no auth + default: + if (hasKey) { + if (auto guard = guardApiKeyTransport(req.url, true)) { + return Outcome::makeError(*guard); + } + req.headers["Authorization"] = "Bearer " + credentials->apiKey; + } + break; + } + for (const auto& [k, v] : config_.customHeaders) req.headers[k] = v; + + Json body; + if (engine_ == TranslationEngineType::Claude) { + body["model"] = model; + body["max_tokens"] = config_.maxTokens.value_or(2048); + body["messages"] = Json::array({Json{{"role", "user"}, {"content", prompt}}}); + } else { + body["model"] = model; + body["messages"] = Json::array({Json{{"role", "user"}, {"content", prompt}}}); + body["stream"] = false; + body["temperature"] = config_.temperature.value_or(0.3); + body["max_tokens"] = config_.maxTokens.value_or(2048); + } + req.body = body.dump(); + + auto outcome = transport_->send(req); + if (outcome.error.has_value()) { + return Outcome::makeError(*outcome.error); + } + const HttpResponse& resp = *outcome.response; + if (resp.status == 401) { + return Outcome::makeError( + ProviderError::auth("Invalid API key")); + } + if (resp.status == 429) { + return Outcome::makeError( + ProviderError::quota("Rate limited")); + } + if (resp.status != 200) { + return Outcome::makeError(ProviderError::network( + "API error: HTTP " + std::to_string(resp.status))); + } + return LLMTranslationResponseParser::extractText(resp.body, engine_); +} + +} // namespace tf diff --git a/windows/Core/src/LLMTranslationCore.cpp b/windows/Core/src/LLMTranslationCore.cpp new file mode 100644 index 0000000..927630f --- /dev/null +++ b/windows/Core/src/LLMTranslationCore.cpp @@ -0,0 +1,302 @@ +// LLMTranslationCore.cpp — pure-logic port of LLMTranslationBatching + +// LLMTranslationResponseParser (Swift → C++20, same vectors, same semantics). +#include "tf/LLMTranslationCore.hpp" +#include "tf/Json.hpp" + +#include + +namespace tf { + +// --------------------------------------------------------------------------- +// Batching (Swift LLMTranslationBatching.swift) +// --------------------------------------------------------------------------- +const char* LLMTranslationBatching::separator() { return "\n---\n"; } + +std::int64_t LLMTranslationBatching::estimatedTokens(const std::string& text) { + // Swift counts UTF-16 code units; C++ counts the same via u16 length. + // For CJK/BMP content these agree; surrogate pairs count 2 in both. + std::int64_t n = 0; + for (unsigned char c : text) { + if (c < 0x80) { + ++n; + } else if ((c & 0xE0) == 0xC0) { + n += 1; // 2-byte UTF-8 → 1 UTF-16 unit + } else if ((c & 0xF0) == 0xE0) { + n += 1; // 3-byte → 1 UTF-16 unit + } else if ((c & 0xF8) == 0xF0) { + n += 2; // 4-byte → surrogate pair + } + // continuation bytes contribute 0 + } + return n; +} + +std::vector> LLMTranslationBatching::split( + const std::vector& texts, std::int64_t maxOutputTokens, + const std::string& promptTemplate) { + const std::int64_t budget = std::max(1, maxOutputTokens); + // Fixed prompt with {text} removed still occupies the budget. + std::string fixedPrompt = promptTemplate; + const std::string needle = "{text}"; + std::size_t pos; + while ((pos = fixedPrompt.find(needle)) != std::string::npos) { + fixedPrompt.replace(pos, needle.size(), ""); + } + const std::int64_t promptCost = estimatedTokens(fixedPrompt); + const std::int64_t sourceBudget = std::max(4, budget - promptCost); + + std::vector> batches; + std::vector current; + std::int64_t used = 0; + const std::int64_t sepCost = estimatedTokens(std::string(separator())); + + auto appendPiece = [&](const std::string& piece) { + const std::int64_t pieceCost = + estimatedTokens(piece) + (current.empty() ? 0 : sepCost); + if (!current.empty() && used + pieceCost > sourceBudget) { + batches.push_back(current); + current.clear(); + used = 0; + } + used += estimatedTokens(piece) + (current.empty() ? 0 : sepCost); + current.push_back(piece); + }; + + for (const auto& text : texts) { + if (estimatedTokens(text) > budget) { + for (const auto& piece : splitLongText(text, sourceBudget)) appendPiece(piece); + } else { + appendPiece(text); + } + } + if (!current.empty()) batches.push_back(current); + return batches; +} + +std::vector LLMTranslationBatching::splitLongText(const std::string& text, + std::int64_t budget) { + if (estimatedTokens(text) <= budget) return {text}; + std::vector pieces; + std::string current; + // Walk UTF-8 code points so a character is never cut in half (Swift walks + // Characters; both never split a code point). + std::size_t i = 0; + while (i < text.size()) { + std::size_t len = 1; + unsigned char c = static_cast(text[i]); + if ((c & 0xE0) == 0xC0) len = 2; + else if ((c & 0xF0) == 0xE0) len = 3; + else if ((c & 0xF8) == 0xF0) len = 4; + const std::string ch = text.substr(i, len); + i += len; + std::int64_t curTokens = estimatedTokens(current); + std::int64_t chTokens = estimatedTokens(ch); + if (!current.empty() && curTokens + chTokens > budget) { + pieces.push_back(current); + current.clear(); + } + current += ch; + } + if (!current.empty()) pieces.push_back(current); + return pieces; +} + +// --------------------------------------------------------------------------- +// Response parser (Swift LLMTranslationResponseParser.swift) +// --------------------------------------------------------------------------- +namespace { + +std::string trimmed(const std::string& s) { + std::size_t b = 0, e = s.size(); + auto isSpace = [](unsigned char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; + }; + while (b < e && isSpace(static_cast(s[b]))) ++b; + while (e > b && isSpace(static_cast(s[e - 1]))) --e; + return s.substr(b, e - b); +} + +std::vector splitLines(const std::string& text) { + std::vector lines; + std::size_t start = 0; + while (start <= text.size()) { + std::size_t nl = text.find('\n', start); + if (nl == std::string::npos) { + lines.push_back(text.substr(start)); + break; + } + lines.push_back(text.substr(start, nl - start)); + start = nl + 1; + } + return lines; +} + +} // namespace + +Outcome LLMTranslationResponseParser::extractText( + const std::string& body, TranslationEngineType engine) { + const std::string trimmedBody = trimmed(body); + + // SSE only when the first payload line is a data event (a body whose + // content contains "\ndata:" still parses as plain JSON — Swift rule). + if (trimmedBody.rfind("data:", 0) == 0) { + if (engine == TranslationEngineType::Claude) return extractClaudeSSE(trimmedBody); + return extractOpenAISSE(trimmedBody); + } + + Json json; + try { + json = Json::parse(body); + } catch (const Json::parse_error&) { + return Outcome::makeError( + ProviderError::content("Response JSON is not parseable")); + } + if (!json.is_object()) { + return Outcome::makeError( + ProviderError::content("Response JSON is not a dictionary")); + } + + // API error surface. + if (json.contains("error") && json["error"].is_object() && json["error"].contains("message") && + json["error"]["message"].is_string()) { + return Outcome::makeError( + ProviderError::content("API error: " + json["error"]["message"].get())); + } + + if (engine == TranslationEngineType::Claude) { + if (json.contains("stop_reason") && json["stop_reason"].is_string() && + json["stop_reason"].get() == "max_tokens") { + return Outcome::makeError(ProviderError::content( + "Claude reached the output token limit")); + } + if (json.contains("content") && json["content"].is_array()) { + for (const auto& part : json["content"]) { + if (part.is_object() && part.contains("type") && part["type"] == "text" && + part.contains("text") && part["text"].is_string()) { + return Outcome::makeOk( + trimmed(part["text"].get())); + } + } + } + return Outcome::makeError( + ProviderError::content("Unexpected JSON response structure")); + } + + // OpenAI-compatible: choices[0]. + if (!json.contains("choices") || !json["choices"].is_array() || json["choices"].empty()) { + return Outcome::makeError( + ProviderError::content("Unexpected JSON response structure")); + } + const Json& choice = json["choices"][0]; + if (!choice.is_object()) { + return Outcome::makeError( + ProviderError::content("Unexpected JSON response structure")); + } + // Truncation must not be reported as success (macOS test vector). + if (choice.contains("finish_reason") && choice["finish_reason"].is_string()) { + const std::string reason = choice["finish_reason"].get(); + if (reason == "length" || reason == "max_tokens") { + return Outcome::makeError(ProviderError::content( + "The response was truncated by the output token limit")); + } + } + if (choice.contains("message") && choice["message"].is_object() && + choice["message"].contains("content") && choice["message"]["content"].is_string()) { + return Outcome::makeOk( + trimmed(choice["message"]["content"].get())); + } + if (choice.contains("text") && choice["text"].is_string()) { + return Outcome::makeOk( + trimmed(choice["text"].get())); + } + return Outcome::makeError( + ProviderError::content("Unexpected JSON response structure")); +} + +Outcome LLMTranslationResponseParser::extractOpenAISSE( + const std::string& text) { + std::string result; + bool isTruncated = false; + for (const auto& rawLine : splitLines(text)) { + const std::string line = trimmed(rawLine); + if (line.rfind("data:", 0) != 0) continue; + std::string payload = trimmed(line.substr(5)); + if (payload == "[DONE]") continue; + Json json; + try { + json = Json::parse(payload); + } catch (const Json::parse_error&) { + continue; + } + if (!json.is_object() || !json.contains("choices") || !json["choices"].is_array() || + json["choices"].empty()) { + continue; + } + const Json& choice = json["choices"][0]; + if (!choice.is_object()) continue; + if (choice.contains("finish_reason") && choice["finish_reason"].is_string()) { + const std::string reason = choice["finish_reason"].get(); + isTruncated = isTruncated || reason == "length" || reason == "max_tokens"; + } + if (choice.contains("delta") && choice["delta"].is_object()) { + const Json& delta = choice["delta"]; + if (delta.contains("content") && delta["content"].is_string()) { + result += delta["content"].get(); + } + } else if (choice.contains("text") && choice["text"].is_string()) { + result += choice["text"].get(); + } + } + if (isTruncated) { + return Outcome::makeError( + ProviderError::content("The stream reached the output token limit")); + } + if (result.empty()) { + return Outcome::makeError( + ProviderError::content("Empty text from SSE stream")); + } + return Outcome::makeOk(trimmed(result)); +} + +Outcome LLMTranslationResponseParser::extractClaudeSSE( + const std::string& text) { + std::string result; + bool isTruncated = false; + for (const auto& rawLine : splitLines(text)) { + const std::string line = trimmed(rawLine); + if (line.rfind("data:", 0) != 0) continue; + std::string payload = trimmed(line.substr(5)); + Json json; + try { + json = Json::parse(payload); + } catch (const Json::parse_error&) { + continue; + } + if (!json.is_object()) continue; + if (json.contains("stop_reason") && json["stop_reason"].is_string() && + json["stop_reason"].get() == "max_tokens") { + isTruncated = true; + } + if (json.contains("delta") && json["delta"].is_object()) { + const Json& delta = json["delta"]; + if (delta.contains("stop_reason") && delta["stop_reason"].is_string() && + delta["stop_reason"].get() == "max_tokens") { + isTruncated = true; + } + if (delta.contains("text") && delta["text"].is_string()) { + result += delta["text"].get(); + } + } + } + if (isTruncated) { + return Outcome::makeError( + ProviderError::content("Claude stream reached the output token limit")); + } + if (result.empty()) { + return Outcome::makeError( + ProviderError::content("Empty text from SSE stream")); + } + return Outcome::makeOk(trimmed(result)); +} + +} // namespace tf diff --git a/windows/Core/src/MTranServerProvider.cpp b/windows/Core/src/MTranServerProvider.cpp new file mode 100644 index 0000000..07bb4c4 --- /dev/null +++ b/windows/Core/src/MTranServerProvider.cpp @@ -0,0 +1,230 @@ +// MTranServerProvider.cpp — MTranServer engine port (Swift MTranServerEngine). +#include "tf/MTranServerProvider.hpp" +#include "tf/Json.hpp" + +#include + +namespace tf { + +namespace { + +std::string trimCopy(const std::string& s) { + std::size_t b = 0, e = s.size(); + auto isSpace = [](unsigned char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; + }; + while (b < e && isSpace(static_cast(s[b]))) ++b; + while (e > b && isSpace(static_cast(s[e - 1]))) --e; + return s.substr(b, e - b); +} + +bool isHostnameSafeCharacter(char c) { + unsigned char u = static_cast(c); + if ((u >= '0' && u <= '9') || (u >= 'A' && u <= 'Z') || (u >= 'a' && u <= 'z')) return true; + return c == '.' || c == '-' || c == '_'; +} + +} // namespace + +MTranServerProvider::Configuration MTranServerProvider::Configuration::makeDefault() { + Configuration c; + c.serverAddress = "localhost"; + c.serverPort = 8989; + return c; +} + +std::optional MTranServerProvider::Configuration::parse( + const std::string& serverUrl, double timeout, bool autoDetect) { + Configuration out; + out.timeout = timeout; + out.autoDetectSourceLanguage = autoDetect; + + std::string trimmed = trimCopy(serverUrl); + if (trimmed.empty()) return std::nullopt; + std::string host = trimmed; + std::string portStr; + + const std::size_t scheme = host.find("://"); + if (scheme != std::string::npos) { + const std::string schemePart = host.substr(0, scheme); + if (schemePart != "http") return std::nullopt; // MTranServer is plain HTTP + host = host.substr(scheme + 3); + } + // Reject embedded path/query (Swift restricts to host[:port]). + if (host.find('/') != std::string::npos || host.find('?') != std::string::npos || + host.find('#') != std::string::npos) { + return std::nullopt; + } + const std::size_t colon = host.rfind(':'); + if (colon != std::string::npos) { + portStr = host.substr(colon + 1); + host = host.substr(0, colon); + if (portStr.empty()) return std::nullopt; + for (char c : portStr) { + if (!std::isdigit(static_cast(c))) return std::nullopt; + } + out.serverPort = std::stoi(portStr); + if (out.serverPort <= 0 || out.serverPort > 65535) return std::nullopt; + } + if (host.empty()) return std::nullopt; + for (char c : host) { + if (!isHostnameSafeCharacter(c)) return std::nullopt; + } + out.serverAddress = host; + return out; +} + +bool MTranServerProvider::Configuration::isValid() const { + return !serverAddress.empty() && + endpointUrl("/translate").rfind("http://", 0) == 0 && + serverPort > 0 && serverPort <= 65535; +} + +std::string MTranServerProvider::Configuration::endpointUrl(const std::string& path) const { + return "http://" + serverAddress + ":" + std::to_string(serverPort) + path; +} + +MTranServerProvider::MTranServerProvider(Configuration config, HttpTransportPtr transport) + : config_(std::move(config)), transport_(std::move(transport)) {} + +std::string MTranServerProvider::normalizeLanguageCode(const std::string& code) { + std::string lower = code; + for (auto& c : lower) c = static_cast(std::tolower(static_cast(c))); + if (lower == "zh-hans" || lower == "zh-cn" || lower == "zh_hans" || lower == "zh_cn") return "zh"; + if (lower == "zh-hant" || lower == "zh-tw" || lower == "zh_hant" || lower == "zh_tw") + return "zh-TW"; + if (lower == "en-us" || lower == "en-gb" || lower == "en_us" || lower == "en_gb") return "en"; + if (lower == "ja-jp" || lower == "ja_jp") return "ja"; + if (lower == "ko-kr" || lower == "ko_kr") return "ko"; + std::size_t sep = lower.find('-'); + if (sep != std::string::npos) return lower.substr(0, sep); + sep = lower.find('_'); + if (sep != std::string::npos) return lower.substr(0, sep); + return lower; +} + +TranslationOutcome MTranServerProvider::translate(const TranslateRequest& request) { + if (request.texts.empty()) return TranslationOutcome::ok({}); + if (!config_.isValid()) { + return TranslationOutcome::fail(ProviderError::configuration("Invalid MTranServer URL")); + } + + // Auto-detect source language when enabled and caller passed nothing. + std::string source = request.sourceLanguage; + if (source.empty() && !config_.autoDetectSourceLanguage) source = "auto"; + if (source.empty()) source = "auto"; + const std::string target = normalizeLanguageCode(request.targetLanguage); + + std::vector results; + results.reserve(request.texts.size()); + for (const auto& text : request.texts) { + if (trimCopy(text).empty()) { + return TranslationOutcome::fail(ProviderError::content("Cannot translate empty text")); + } + HttpRequest req; + req.method = "POST"; + req.url = config_.endpointUrl("/translate"); + req.timeoutSeconds = static_cast(config_.timeout); + req.cancelToken = request.cancelToken; + req.headers["Content-Type"] = "application/json"; + req.body = Json{{"text", text}, {"from", source}, {"to", target}}.dump(); + + auto outcome = transport_->send(req); + if (outcome.error.has_value()) { + return TranslationOutcome::fail(*outcome.error); + } + const HttpResponse& resp = *outcome.response; + if (resp.status == 503) { + return TranslationOutcome::fail( + ProviderError::network("MTranServer service unavailable")); + } + if (resp.status != 200) { + return TranslationOutcome::fail(ProviderError::network( + "MTranServer HTTP " + std::to_string(resp.status))); + } + Json json; + try { + json = Json::parse(resp.body); + } catch (const Json::parse_error&) { + return TranslationOutcome::fail(ProviderError::content("Invalid MTranServer response")); + } + if (!json.is_object() || !json.contains("result") || !json["result"].is_string()) { + return TranslationOutcome::fail(ProviderError::content("Invalid MTranServer response")); + } + const std::string translated = json["result"].get(); + std::string detected; + if (json.contains("detected_language") && json["detected_language"].is_string()) { + detected = json["detected_language"].get(); + } + results.emplace_back( + text, translated, + detected.empty() ? (request.sourceLanguage.empty() ? "auto" : request.sourceLanguage) + : detected, + request.targetLanguage); + } + return TranslationOutcome::ok(std::move(results)); +} + +MTranServerProvider::ProbeOutcome MTranServerProvider::probeEndpoint( + const Configuration& config, const CancellationToken& token) { + static const char* endpoints[] = {"/health", "/", "/translate"}; + for (const char* endpoint : endpoints) { + if (token.cancelled()) return {ProbeOutcomeValue::Kind::Cancelled, ""}; + HttpRequest req; + req.method = "GET"; + req.url = config.endpointUrl(endpoint); + req.timeoutSeconds = + static_cast(std::min(config.timeout, 2.0)); + req.cancelToken = token; + auto outcome = transport_->send(req); + if (outcome.error.has_value()) { + if (outcome.isCancelled()) return {ProbeOutcomeValue::Kind::Cancelled, ""}; + return {ProbeOutcomeValue::Kind::Unreachable, endpoint}; + } + const int status = outcome.response->status; + if (status >= 200 && status < 300) { + return {ProbeOutcomeValue::Kind::Reachable, endpoint}; + } + if (std::string(endpoint) != "/translate") { + // 404/405/501: endpoint missing; 401/403/429: a gateway may only + // guard some paths while /translate works; other 5xx fail fast + // (Swift comment). + if (status == 401 || status == 403 || status == 404 || status == 405 || + status == 429 || status == 501) { + continue; + } + } + return {ProbeOutcomeValue::Kind::Unreachable, endpoint}; + } + return {ProbeOutcomeValue::Kind::Unreachable, ""}; +} + +std::optional MTranServerProvider::verifyConnection(const CancellationToken& token) { + auto probe = probeEndpoint(config_, token); + if (probe.kind == ProbeOutcomeValue::Kind::Cancelled) { + return ProviderError::network("cancelled"); + } + if (probe.kind == ProbeOutcomeValue::Kind::Reachable) return std::nullopt; + return ProviderError::network("MTranServer endpoint unreachable"); +} + +// --------------------------------------------------------------------------- +// Health cache (5s TTL, Swift MTranServerChecker semantics). +// --------------------------------------------------------------------------- +MTranServerHealthCache::MTranServerHealthCache(double ttlSeconds) : ttl_(ttlSeconds) {} + +std::optional MTranServerHealthCache::cached( + const std::string& host, int port, double now) const { + auto it = cache_.find({host, port}); + if (it == cache_.end()) return std::nullopt; + if (now - it->second.checkedAt >= ttl_) return std::nullopt; // stale + return it->second; +} + +void MTranServerHealthCache::store(const std::string& host, int port, bool available, double now) { + cache_[{host, port}] = Entry{available, now}; +} + +void MTranServerHealthCache::invalidateAll() { cache_.clear(); } + +} // namespace tf diff --git a/windows/Core/src/OcrEngines.cpp b/windows/Core/src/OcrEngines.cpp new file mode 100644 index 0000000..954e0de --- /dev/null +++ b/windows/Core/src/OcrEngines.cpp @@ -0,0 +1,680 @@ +// OcrEngines.cpp — WindowsOcr mapping + PaddleOCR protocol + VLM parsing. +#include "tf/OcrEngines.hpp" +#include "tf/Json.hpp" + +#include +#include +#include + +namespace tf { + +// =========================================================================== +// WindowsOcrEngine +// =========================================================================== +WindowsOcrEngine::WindowsOcrEngine(LanguageProvider languageProvider, Recognizer recognizer, + float minimumConfidence) + : languageProvider_(std::move(languageProvider)), + recognizer_(std::move(recognizer)), + minimumConfidence_(minimumConfidence) {} + +bool WindowsOcrEngine::isAvailable() const { + if (!languageProvider_) return false; + return !languageProvider_().empty(); +} + +std::vector WindowsOcrEngine::installedLanguages() const { + return languageProvider_ ? languageProvider_() : std::vector{}; +} + +bool WindowsOcrEngine::hasLanguagePack(const std::string& bcp47Tag) const { + const std::string want = normalizeLanguageTag(bcp47Tag); + for (const auto& lang : installedLanguages()) { + if (lang.tag == want) return true; + // Base-code match: "zh-Hans" pack satisfies "zh". + const std::size_t wd = want.find('-'); + const std::size_t ld = lang.tag.find('-'); + if (wd != std::string::npos && ld != std::string::npos && + want.substr(0, wd) == lang.tag.substr(0, ld)) { + return true; + } + if (ld == std::string::npos && want == lang.tag) return true; + } + return false; +} + +std::string WindowsOcrEngine::normalizeLanguageTag(const std::string& tag) { + if (tag == "zh" || tag == "zh-Hans" || tag == "zh-CN" || tag == "zh_Hans") return "zh-Hans"; + if (tag == "zh-Hant" || tag == "zh-TW") return "zh-Hant"; + if (tag == "en" || tag == "en-US") return "en-US"; + if (tag == "ja" || tag == "ja-JP") return "ja"; + if (tag == "ko" || tag == "ko-KR") return "ko"; + if (tag.empty()) return "en-US"; + std::string out = tag; + std::size_t dash = out.find('-'); + if (dash == std::string::npos) return out; // fr/de/es already base codes + return out; +} + +std::vector WindowsOcrEngine::mapLines(const std::vector& lines, + std::int64_t imageWidth, + std::int64_t imageHeight, + float minimumConfidence) { + std::vector segments; + segments.reserve(lines.size()); + const double w = static_cast(imageWidth); + const double h = static_cast(imageHeight); + for (const auto& line : lines) { + // Windows.Media.Ocr already reports top-left-origin pixel rects; the + // mapping is a pure scale into the normalized schema (macOS parity: + // Vision's bottom-left origin is converted on macOS, not here). + if (line.text.empty()) continue; + const float confidence = line.confidence <= 0.0f ? 1.0f : line.confidence; + if (confidence < minimumConfidence) continue; + NormRect box; + box.x = w > 0 ? line.x / w : 0.0; + box.y = h > 0 ? line.y / h : 0.0; + box.width = w > 0 ? line.w / w : 0.0; + box.height = h > 0 ? line.h / h : 0.0; + segments.push_back(TextSegment(line.text, box, confidence)); + } + return segments; +} + +Outcome WindowsOcrEngine::recognize(const OcrImage& image) { + if (image.width <= 0 || image.height <= 0 || image.bgra.empty()) { + return Outcome::makeError( + ProviderError::content("Invalid image")); + } + if (!isAvailable()) { + return Outcome::makeError( + ProviderError::configuration("No OCR language packs installed")); + } + std::vector lines; + std::vector tags; + for (const auto& lang : installedLanguages()) tags.push_back(lang.tag); + if (auto err = recognizer_(image, tags, lines)) { + return Outcome::makeError(*err); + } + OcrResult result = OcrResult::empty(image.width, image.height); + result.observations = mapLines(lines, image.width, image.height, minimumConfidence_); + return Outcome::makeOk(std::move(result)); +} + +// =========================================================================== +// PaddleOcrEngine +// =========================================================================== +PaddleOcrEngine::PaddleOcrEngine(Configuration config, ProcessRunner runner, + AvailabilityChecker availability) + : config_(std::move(config)), runner_(std::move(runner)), + availability_(std::move(availability)) {} + +bool PaddleOcrEngine::isAvailable() const { + if (config_.executablePath.empty()) return false; + return availability_ ? availability_(config_.executablePath) : false; +} + +std::vector PaddleOcrEngine::buildArguments(const std::string& imagePath) const { + std::vector args; + if (config_.mode == Mode::Fast) { + // Chinese present → mixed "ch" (zh+en); otherwise first language. + std::string lang = "ch"; + bool hasChinese = false; + for (const auto& l : config_.languages) { + if (l == "ch") { + hasChinese = true; + break; + } + } + if (!hasChinese && !config_.languages.empty()) lang = config_.languages.front(); + args = {"ocr", "-i", imagePath, "--lang", lang, + "--use_angle_cls", config_.useDirectionClassify ? "true" : "false"}; + } else { + args = {"doc_parser", "-i", imagePath, "--pipeline_version", "v1.5", + "--device", config_.useGPU ? "gpu" : "cpu"}; + } + return args; +} + +Outcome PaddleOcrEngine::recognize(const OcrImage& image) { + if (image.width <= 0 || image.height <= 0 || image.bgra.empty()) { + return Outcome::makeError( + ProviderError::content("Invalid image")); + } + if (!isAvailable()) { + return Outcome::makeError( + ProviderError::configuration("PaddleOCR executable not installed")); + } + // The image is written to a temp PNG by NativeShell; this layer receives + // its path via the runner seam contract (first argv slot after -i). + // For the pure-logic build the caller passes the path through the + // runner's captured context; here we synthesize the protocol shape. + std::string stdoutText, stderrText; + // The imagePath is embedded in the argv; the runner owns temp-file + // handling in NativeShell. Pure tests exercise parseFastMode/ + // parsePreciseMode directly. + if (auto err = runner_(config_.executablePath, buildArguments(""), + config_.mode == Mode::Fast ? 60 : 900, stdoutText, stderrText)) { + return Outcome::makeError(*err); + } + const std::string json = extractResultJson(stdoutText, stderrText); + if (json.empty()) { + return Outcome::makeError( + ProviderError::content("PaddleOCR produced no JSON output")); + } + OcrResult result = OcrResult::empty(image.width, image.height); + if (config_.mode == Mode::Fast) { + result.observations = parseFastMode(json, image.width, image.height, + config_.minimumConfidence); + } else { + result.observations = parsePreciseMode(json, image.width, image.height); + } + return Outcome::makeOk(std::move(result)); +} + +std::string PaddleOcrEngine::extractResultJson(const std::string& stdoutText, + const std::string& stderrText) { + // stdout JSON wins; else pull {'res': ...} out of stderr (Swift rule). + if (!stdoutText.empty()) { + const std::size_t start = stdoutText.find("{\"res\""); + const std::size_t startSingle = stdoutText.find("{'res'"); + std::size_t at = std::string::npos; + bool single = false; + if (start != std::string::npos && (startSingle == std::string::npos || start < startSingle)) { + at = start; + } else if (startSingle != std::string::npos) { + at = startSingle; + single = true; + } + if (at == std::string::npos) return stdoutText; + std::string tail = stdoutText.substr(at); + // Matching closing brace scan (Swift findMatchingBrace). + int depth = 0; + bool inStr = false; + std::size_t end = std::string::npos; + for (std::size_t i = 0; i < tail.size(); ++i) { + const char c = tail[i]; + if (inStr) { + if (c == '\\') { + ++i; + } else if (c == (single ? '\'' : '"')) { + inStr = false; + } + continue; + } + if (c == (single ? '\'' : '"')) { + inStr = true; + } else if (c == '{') { + ++depth; + } else if (c == '}') { + --depth; + if (depth == 0) { + end = i; + break; + } + } + } + if (end != std::string::npos) tail = tail.substr(0, end + 1); + return pythonDictToJson(tail); + } + const std::size_t at = stderrText.find("{'res'"); + if (at == std::string::npos) return ""; + std::string tail = stderrText.substr(at); + int depth = 0; + bool inStr = false; + std::size_t end = std::string::npos; + for (std::size_t i = 0; i < tail.size(); ++i) { + const char c = tail[i]; + if (inStr) { + if (c == '\\') ++i; + else if (c == '\'') inStr = false; + continue; + } + if (c == '\'') inStr = true; + else if (c == '{') ++depth; + else if (c == '}') { + --depth; + if (depth == 0) { + end = i; + break; + } + } + } + if (end != std::string::npos) tail = tail.substr(0, end + 1); + // Strip ANSI escapes. + std::string cleaned; + for (std::size_t i = 0; i < tail.size(); ++i) { + if (tail[i] == 0x1B && i + 1 < tail.size() && tail[i + 1] == '[') { + std::size_t j = i + 2; + while (j < tail.size() && + !(tail[j] >= '@' && tail[j] <= '~')) { + ++j; + } + i = j; + continue; + } + cleaned += tail[i]; + } + return pythonDictToJson(cleaned); +} + +std::string PaddleOcrEngine::pythonDictToJson(const std::string& pythonLiteral) { + // Pass 1: single-quoted strings → double-quoted, True/False/None → + // true/false/null (outside strings), tuple parens → brackets. + std::string out; + out.reserve(pythonLiteral.size() + 16); + bool inSingle = false, inDouble = false, escaped = false; + for (std::size_t i = 0; i < pythonLiteral.size(); ++i) { + const char c = pythonLiteral[i]; + if (inSingle) { + if (escaped) { + if (c == '\'') out += '\''; + else if (c == '"') out += "\\\""; + else { + out += '\\'; + out += c; + } + escaped = false; + } else if (c == '\\') { + escaped = true; + } else if (c == '\'') { + out += '"'; + inSingle = false; + } else if (c == '"') { + out += "\\\""; + } else { + out += c; + } + continue; + } + if (inDouble) { + if (escaped) { + out += c; + escaped = false; + } else if (c == '\\') { + out += c; + escaped = true; + } else if (c == '"') { + out += c; + inDouble = false; + } else { + out += c; + } + continue; + } + if (c == '\'') { + out += '"'; + inSingle = true; + } else if (c == '"') { + out += '"'; + inDouble = true; + } else if (c == '(') { + out += '['; + } else if (c == ')') { + out += ']'; + } else if (c == 'T' && pythonLiteral.compare(i, 4, "True") == 0) { + out += "true"; + i += 3; + } else if (c == 'F' && pythonLiteral.compare(i, 5, "False") == 0) { + out += "false"; + i += 4; + } else if (c == 'N' && pythonLiteral.compare(i, 4, "None") == 0) { + out += "null"; + i += 3; + } else { + out += c; + } + } + // Pass 2: numpy array(...) wrappers → bare brackets. + std::string denump; + static const std::string kArrayOpen = "array("; + std::size_t pos = 0; + while (pos < out.size()) { + const std::size_t hit = out.find(kArrayOpen, pos); + if (hit == std::string::npos) { + denump += out.substr(pos); + break; + } + denump += out.substr(pos, hit - pos); + // Skip "array(" and find its matching close paren, dropping the tail + // ", dtype=...)" part. + std::size_t depth = 1; + std::size_t i = hit + kArrayOpen.size(); + bool inStr = false; + std::size_t contentEnd = std::string::npos; + std::size_t closeParen = std::string::npos; + for (; i < out.size(); ++i) { + const char c = out[i]; + if (inStr) { + if (c == '\\') ++i; + else if (c == '"') inStr = false; + continue; + } + if (c == '"') inStr = true; + else if (c == '(') ++depth; + else if (c == ')') { + --depth; + if (depth == 0) { + closeParen = i; + break; + } + } else if (c == ',' && depth == 1) { + // Potential ", dtype" start — record the last comma before close. + contentEnd = i; + } + } + if (closeParen == std::string::npos) { + denump += out.substr(hit); + break; + } + // If the segment after the last comma looks like dtype=, drop it. + std::size_t stop = closeParen; + if (contentEnd != std::string::npos) { + std::string tail = out.substr(contentEnd + 1, closeParen - contentEnd - 1); + bool allSpace = true; + for (char c : tail) { + if (!std::isspace(static_cast(c))) { + allSpace = false; + break; + } + } + if (!tail.empty() && !allSpace && tail.find("dtype") != std::string::npos) { + stop = contentEnd; + } + } + denump += out.substr(hit + kArrayOpen.size(), stop - hit - kArrayOpen.size()); + pos = closeParen + 1; + } + out = denump; + + // Pass 3: "8." → "8.0", "-5." → "-5.0" (Swift float fix). + std::string fixed; + for (std::size_t i = 0; i < out.size(); ++i) { + const char c = out[i]; + fixed += c; + if (c == '.' && i > 0 && std::isdigit(static_cast(out[i - 1])) && + i + 1 < out.size()) { + const char next = out[i + 1]; + if (next == ',' || next == ']' || next == '}' || next == ' ' || next == ')') { + // Look ahead: only append 0 when the next non-space is a delimiter. + fixed += '0'; + } + } + } + return fixed; +} + +std::vector PaddleOcrEngine::parseFastMode(const std::string& json, + std::int64_t imageWidth, + std::int64_t imageHeight, + float minimumConfidence) { + std::vector segments; + Json root; + try { + root = Json::parse(json); + } catch (const Json::parse_error&) { + return segments; + } + const Json* res = nullptr; + if (root.is_object() && root.contains("res") && root["res"].is_object()) { + res = &root["res"]; + } else if (root.is_object()) { + res = &root; // tolerate already-unwrapped payloads + } else { + return segments; + } + if (!res->contains("rec_texts") || !(*res)["rec_texts"].is_array()) return segments; + const auto& texts = (*res)["rec_texts"]; + const Json* boxes = nullptr; + const Json* scores = nullptr; + if (res->contains("rec_boxes") && (*res)["rec_boxes"].is_array()) boxes = &(*res)["rec_boxes"]; + if (res->contains("rec_scores") && (*res)["rec_scores"].is_array()) + scores = &(*res)["rec_scores"]; + + const double w = static_cast(imageWidth); + const double h = static_cast(imageHeight); + for (std::size_t i = 0; i < texts.size(); ++i) { + if (!texts[i].is_string()) continue; + const std::string text = texts[i].get(); + if (text.empty()) continue; + float confidence = 0.9f; + if (scores && i < scores->size() && (*scores)[i].is_number()) { + confidence = static_cast((*scores)[i].get()); + } + if (confidence < minimumConfidence) continue; + NormRect box; + bool haveBox = false; + if (boxes && i < boxes->size() && (*boxes)[i].is_array() && (*boxes)[i].size() >= 4) { + const double x1 = (*boxes)[i][0].get(); + const double y1 = (*boxes)[i][1].get(); + const double x2 = (*boxes)[i][2].get(); + const double y2 = (*boxes)[i][3].get(); + box.x = w > 0 ? x1 / w : 0; + box.y = h > 0 ? y1 / h : 0; + box.width = w > 0 ? (x2 - x1) / w : 0; + box.height = h > 0 ? (y2 - y1) / h : 0; + haveBox = true; + } + if (!haveBox) { + // Fallback: stack vertically (Swift). + box = NormRect{0.0, static_cast(i) * 0.1, 1.0, 0.1}; + } + segments.push_back(TextSegment(text, box, confidence)); + } + return segments; +} + +std::vector PaddleOcrEngine::parsePreciseMode(const std::string& json, + std::int64_t imageWidth, + std::int64_t imageHeight) { + std::vector segments; + Json root; + try { + root = Json::parse(json); + } catch (const Json::parse_error&) { + return segments; + } + const Json* res = nullptr; + if (root.is_object() && root.contains("res") && root["res"].is_object()) { + res = &root["res"]; + } else if (root.is_object()) { + res = &root; + } else { + return segments; + } + if (!res->contains("parsing_res_list") || !(*res)["parsing_res_list"].is_array()) { + return segments; + } + const double w = static_cast(imageWidth); + const double h = static_cast(imageHeight); + int index = 0; + for (const auto& block : (*res)["parsing_res_list"]) { + ++index; + if (!block.is_object() || !block.contains("block_content") || + !block["block_content"].is_string()) { + continue; + } + // Skip non-text blocks (chart/seal/image/table/figure — Swift). + if (block.contains("block_label") && block["block_label"].is_string()) { + std::string label = block["block_label"].get(); + for (auto& c : label) c = static_cast(std::tolower(static_cast(c))); + if (label.find("chart") != std::string::npos || + label.find("seal") != std::string::npos || + label.find("image") != std::string::npos || + label.find("table") != std::string::npos || + label.find("figure") != std::string::npos) { + continue; + } + } + const std::string text = block["block_content"].get(); + NormRect box; + bool haveBox = false; + if (block.contains("block_bbox") && block["block_bbox"].is_array() && + block["block_bbox"].size() >= 4) { + const double x1 = block["block_bbox"][0].get(); + const double y1 = block["block_bbox"][1].get(); + const double x2 = block["block_bbox"][2].get(); + const double y2 = block["block_bbox"][3].get(); + box.x = w > 0 ? x1 / w : 0; + box.y = h > 0 ? y1 / h : 0; + box.width = w > 0 ? (x2 - x1) / w : 0; + box.height = h > 0 ? (y2 - y1) / h : 0; + haveBox = true; + } + if (!haveBox) box = NormRect{0.0, static_cast(index) * 0.1, 1.0, 0.1}; + segments.push_back(TextSegment(text, box, 0.9f)); // doc_parser has no score + } + return segments; +} + +PaddleOcrHealthCache::PaddleOcrHealthCache(double ttlSeconds) : ttl_(ttlSeconds) {} + +std::optional PaddleOcrHealthCache::cached(const std::string& executable, double now) const { + auto it = cache_.find(executable); + if (it == cache_.end()) return std::nullopt; + if (now - it->second.second >= ttl_) return std::nullopt; + return it->second.first; +} + +void PaddleOcrHealthCache::store(const std::string& executable, bool available, double now) { + cache_[executable] = {available, now}; +} + +void PaddleOcrHealthCache::invalidateAll() { cache_.clear(); } + +// =========================================================================== +// VlmOcrEngine +// =========================================================================== +VlmOcrEngine::VlmOcrEngine(Analyzer analyzer, CredentialStorePtr credentials) + : analyzer_(std::move(analyzer)), credentials_(std::move(credentials)) {} + +const std::string& VlmOcrEngine::extractionPrompt() { + static const std::string p = + "Please recognize all text in this image and return the results in JSON format with " + "'text', 'confidence', and 'box' (x, y, width, height) for each text region. Coordinates " + "are normalized to 0-1 relative to the image."; + return p; +} + +std::vector VlmOcrEngine::supportedProviders() { + return {VlmProviderType::OpenAI, VlmProviderType::Claude, VlmProviderType::Gemini, + VlmProviderType::Ollama, VlmProviderType::PaddleOCR}; +} + +bool VlmOcrEngine::isAvailable() const { + // Ollama slot is keyless-local → available; others need stored keys + // (account "vlm_api_key_", Swift KeychainService). + if (activeProvider_ == VlmProviderType::Ollama) return true; + return credentials_ && credentials_->has("vlm_api_key_" + std::string(vlmProviderRaw(activeProvider_))); +} + +Outcome VlmOcrEngine::recognize(const OcrImage& image) { + if (image.width <= 0 || image.height <= 0 || image.bgra.empty()) { + return Outcome::makeError( + ProviderError::content("Invalid image")); + } + if (!isAvailable()) { + return Outcome::makeError( + ProviderError::configuration("VLM provider not configured")); + } + std::string rawJson; + if (auto err = analyzer_(activeProvider_, extractionPrompt(), image, rawJson)) { + return Outcome::makeError(*err); + } + OcrResult result = OcrResult::empty(image.width, image.height); + result.observations = parseSegments(rawJson, image.width, image.height); + if (result.observations.empty()) { + return Outcome::makeError( + ProviderError::content("VLM returned no text segments")); + } + return Outcome::makeOk(std::move(result)); +} + +std::vector VlmOcrEngine::parseSegments(const std::string& rawJson, + std::int64_t imageWidth, + std::int64_t imageHeight) { + (void)imageWidth; + (void)imageHeight; + // Pull the JSON array out of chat-completion content / markdown fences. + std::string content = rawJson; + { + // Chat completion shape {"choices":[{"message":{"content": "..."}}]}. + try { + Json j = Json::parse(rawJson); + if (j.is_object() && j.contains("choices") && j["choices"].is_array() && + !j["choices"].empty() && j["choices"][0].is_object() && + j["choices"][0].contains("message") && + j["choices"][0]["message"].is_object() && + j["choices"][0]["message"].contains("content") && + j["choices"][0]["message"]["content"].is_string()) { + content = j["choices"][0]["message"]["content"].get(); + } + } catch (const Json::parse_error&) { + // Fall through: raw content. + } + } + { + // ```json fenced block. + const std::size_t open = content.find("```json"); + if (open != std::string::npos) { + const std::size_t start = open + 7; + const std::size_t close = content.find("```", start); + if (close != std::string::npos) { + content = content.substr(start, close - start); + } + } + } + Json arr; + try { + Json parsed = Json::parse(content); + if (parsed.is_array()) { + arr = parsed; + } else if (parsed.is_object() && parsed.contains("results") && + parsed["results"].is_array()) { + arr = parsed["results"]; + } else { + return {}; + } + } catch (const Json::parse_error&) { + return {}; + } + + std::vector segments; + for (const auto& item : arr) { + if (!item.is_object() || !item.contains("text") || !item["text"].is_string()) continue; + const std::string text = item["text"].get(); + if (text.empty()) continue; + float confidence = 1.0f; + if (item.contains("confidence") && item["confidence"].is_number()) { + confidence = static_cast(item["confidence"].get()); + } + NormRect box; + if (item.contains("box") && item["box"].is_object()) { + const Json& b = item["box"]; + auto read = [&b](const char* k) -> std::optional { + if (b.contains(k) && b[k].is_number()) return b[k].get(); + return std::nullopt; + }; + box.x = read("x").value_or(0); + box.y = read("y").value_or(0); + box.width = read("width").value_or(0); + box.height = read("height").value_or(0); + } else if (item.contains("box") && item["box"].is_array() && + item["box"].size() >= 4) { + // Pixel [x1,y1,x2,y2] tolerance: normalize when > 1. + const double x1 = item["box"][0].get(); + const double y1 = item["box"][1].get(); + const double x2 = item["box"][2].get(); + const double y2 = item["box"][3].get(); + const double w = static_cast(imageWidth); + const double h = static_cast(imageHeight); + box.x = w > 0 ? x1 / w : x1; + box.y = h > 0 ? y1 / h : y1; + box.width = w > 0 ? (x2 - x1) / w : x2 - x1; + box.height = h > 0 ? (y2 - y1) / h : y2 - y1; + } + segments.push_back(TextSegment(text, box, confidence)); + } + return segments; +} + +} // namespace tf diff --git a/windows/Core/src/TextSelectionInsertion.cpp b/windows/Core/src/TextSelectionInsertion.cpp new file mode 100644 index 0000000..6ff0ff0 --- /dev/null +++ b/windows/Core/src/TextSelectionInsertion.cpp @@ -0,0 +1,149 @@ +// TextSelectionInsertion.cpp — FR-28/29 protocol logic. +#include "tf/TextSelectionInsertion.hpp" + +#include + +namespace tf { + +namespace { + +bool isBlank(const std::string& s) { + return std::all_of(s.begin(), s.end(), [](unsigned char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; + }); +} + +} // namespace + +// --------------------------------------------------------------------------- +// TextExtractor +// --------------------------------------------------------------------------- +TextExtractor::TextExtractor(TextExtractorHost& host, bool allowClipboardFallback, + int clipboardPollRetries, int clipboardPollIntervalMs) + : host_(host), + allowClipboardFallback_(allowClipboardFallback), + clipboardPollRetries_(clipboardPollRetries), + clipboardPollIntervalMs_(clipboardPollIntervalMs) {} + +ExtractionOutcome TextExtractor::captureSelectedText(bool bindForInsertion) { + // --- Route 1: UIA TextPattern.GetSelection — no clipboard involved --- + UiaElementPtr focused = + host_.focusedElement ? host_.focusedElement() : nullptr; + if (focused) { + if (auto selection = focused->getSelectionText()) { + if (!isBlank(*selection)) { + TextSelection result; + result.text = std::move(*selection); + result.sourceApplication = host_.foregroundProcessName(); + result.sourceProcessId = host_.foregroundProcessId(); + if (bindForInsertion && focused->isEditable()) { + result.insertionTargetId = focused->runtimeId(); + } + return ExtractionOutcome::ok(std::move(result)); + } + } + } + + // --- Route 2: clipboard fallback (save → clear → Ctrl+C → poll → restore) --- + if (!allowClipboardFallback_) { + return ExtractionOutcome::fail( + ProviderError::content("No text is currently selected")); + } + + const auto backup = host_.backupClipboard(); + // Guard against the clipboard changing mid-flight (Swift sequence check). + const std::int64_t sequenceAtStart = host_.clipboardSequenceNumber(); + host_.clearClipboard(); + + if (!host_.sendCopyShortcut()) { + host_.restoreClipboard(backup); + return ExtractionOutcome::fail( + ProviderError::network("Failed to simulate Ctrl+C")); + } + + std::string captured; + bool gotIt = false; + for (int i = 0; i < clipboardPollRetries_; ++i) { + host_.sleepMilliseconds(clipboardPollIntervalMs_); + if (auto text = host_.clipboardText()) { + if (!text->empty() && !isBlank(*text)) { + captured = std::move(*text); + gotIt = true; + break; + } + } + } + host_.restoreClipboard(backup); + + if (!gotIt) { + return ExtractionOutcome::fail(ProviderError::content("No text is currently selected")); + } + (void)sequenceAtStart; + TextSelection result; + result.text = std::move(captured); + result.sourceApplication = host_.foregroundProcessName(); + result.sourceProcessId = host_.foregroundProcessId(); + return ExtractionOutcome::ok(std::move(result)); +} + +// --------------------------------------------------------------------------- +// InsertionService +// --------------------------------------------------------------------------- +InsertionService::InsertionService(TextExtractorHost& host) : host_(host) {} + +std::optional InsertionService::validateTarget( + const IUiaElement* focused, const TextSelection& captured, + const std::string& currentSelectionText, std::uint32_t foregroundPid) { + if (captured.insertionTargetId.empty()) { + // Clipboard-fallback anchor: foreground PID must be unchanged + // (Swift pasteToCapturedFrontmost). + if (captured.sourceProcessId != 0 && foregroundPid != 0 && + captured.sourceProcessId != foregroundPid) { + return "TargetChanged"; + } + return std::nullopt; + } + // UIA anchor: same element + selection text unchanged. + if (focused == nullptr || focused->runtimeId() != captured.insertionTargetId) { + return "TargetChanged"; + } + if (currentSelectionText != captured.text) { + return "TargetChanged"; + } + return std::nullopt; +} + +InsertionOutcome InsertionService::insert(const InsertRequest& request, std::string& outError) { + if (request.translatedText.empty()) { + outError = "Nothing to insert"; + return InsertionOutcome::Failed; + } + UiaElementPtr focused = host_.focusedElement ? host_.focusedElement() : nullptr; + std::string currentSelection; + if (focused) { + if (auto sel = focused->getSelectionText()) currentSelection = *sel; + } + + // Mandatory re-validation BEFORE any paste (brief §6: 重验证失败绝不粘贴). + if (auto failure = validateTarget(focused.get(), request.capturedSelection, currentSelection, + host_.foregroundProcessId())) { + outError = "TargetChanged: " + *failure; + return InsertionOutcome::Failed; + } + + // Paste window: save clipboard → set translated text → Ctrl+V → wait → + // restore original clipboard (Swift PasteboardBackup flow). + const auto backup = host_.backupClipboard(); + host_.setClipboardText(request.translatedText); + if (!host_.sendPasteShortcut()) { + host_.restoreClipboard(backup); + outError = "Failed to simulate Ctrl+V"; + return InsertionOutcome::Failed; + } + // Give the target app time to consume the paste before restoring. + host_.sleepMilliseconds(150); + host_.restoreClipboard(backup); + return InsertionOutcome::Completed; +} + +} // namespace tf diff --git a/windows/Core/src/TranslationScheduler.cpp b/windows/Core/src/TranslationScheduler.cpp new file mode 100644 index 0000000..a7c145b --- /dev/null +++ b/windows/Core/src/TranslationScheduler.cpp @@ -0,0 +1,439 @@ +// TranslationScheduler.cpp — ordered chain + compare set + cache + scene routing. +#include "tf/TranslationScheduler.hpp" +#include "tf/CompatibleChatProvider.hpp" +#include "tf/CloudProviders.hpp" +#include "tf/LLMChatProvider.hpp" +#include "tf/MTranServerProvider.hpp" + +#include +#include +#include +#include +#include + +namespace tf { + +namespace { + +double nowSeconds() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()) + .count(); +} + +std::string shortError(const std::optional& error) { + if (!error.has_value()) return ""; + std::string text = error->message; + if (text.size() > 120) text = text.substr(0, 120); + return std::string(errorCategoryName(error->category)) + ": " + text; +} + +} // namespace + +TranslationScheduler::TranslationScheduler(SchedulerDependencies deps) + : deps_(std::move(deps)) {} + +std::string TranslationScheduler::engineKeyFor(const EngineChainItem& item) { + if (item.kind == EngineChainItem::Kind::Builtin) { + return translationEngineRaw(item.builtin); + } + return "custom:" + item.compatibleId; +} + +std::string TranslationScheduler::hashTexts(const std::vector& texts) { + // FNV-1a over the joined texts — collision-safe enough as a cache key + // discriminant alongside language + engine identity. + std::size_t h = 1469598103934665603ULL; + for (const auto& t : texts) { + for (unsigned char c : t) { + h ^= c; + h *= 1099511628211ULL; + } + h ^= 0x1F; + h *= 1099511628211ULL; + } + std::ostringstream os; + os << std::hex << h; + return os.str(); +} + +TranslationScheduler::ResolveResult TranslationScheduler::resolve( + const EngineChainItem& item) const { + ResolveResult out; + if (item.kind == EngineChainItem::Kind::Builtin) { + if (deps_.builtinProvider) { + out.provider = deps_.builtinProvider(item.builtin); + } + out.resolved = out.provider != nullptr; + return out; + } + if (deps_.compatibleProvider) { + out.provider = deps_.compatibleProvider(item.compatibleId); + } + out.resolved = out.provider != nullptr; + if (out.resolved && deps_.compatibleConfigs) { + for (const auto& cfg : deps_.compatibleConfigs()) { + if (cfg.id == item.compatibleId) { + out.displayName = cfg.displayName; + break; + } + } + } + return out; +} + +EngineResult TranslationScheduler::runProvider( + const ResolveResult& resolved, const EngineChainItem& item, + const std::vector& texts, const std::string& sourceLanguage, + const std::string& targetLanguage, TranslationScene scene, const CancellationToken& token) { + const double start = nowSeconds(); + TranslateRequest req; + req.texts = texts; + req.sourceLanguage = sourceLanguage; + req.targetLanguage = targetLanguage; + req.cancelToken = token; + if (deps_.promptResolver) { + req.promptTemplate = deps_.promptResolver(item.resolvedEngine(), scene, + item.kind == EngineChainItem::Kind::Compatible + ? item.compatibleId + : std::string()); + } + + auto outcome = resolved.provider->translate(req); + const double latency = nowSeconds() - start; + + if (outcome.results.has_value()) { + EngineResult r; + r.engine = item.resolvedEngine(); + for (const auto& tr : *outcome.results) { + r.segments.push_back(BilingualSegment::fromResult(tr)); + } + r.latencySeconds = latency; + r.displayName = resolved.displayName; + // Empty result set counts as failure so ordered chains fall through + // (Swift: "returned no results" guard). + if (r.segments.empty()) { + r.failed = true; + r.errorText = resolved.provider->name() + " returned no results"; + } + return r; + } + EngineResult r = EngineResult::makeFailure( + item.resolvedEngine(), + resolved.provider->name() + ": " + shortError(outcome.error), latency, + resolved.displayName); + return r; +} + +// --------------------------------------------------------------------------- +// Ordered chain (Swift translateOrderedV2). +// --------------------------------------------------------------------------- +SchedulerOutcome TranslationScheduler::translateOrdered(const ChainRequest& request) { + // Clamp to the structural limit (UI enforces it; service backstop). + std::vector chain = request.chain; + if (static_cast(chain.size()) > EngineSelectionLimits::orderedChainLimit) { + chain.resize(EngineSelectionLimits::orderedChainLimit); + } + // Defensive: empty chain still runs (Swift falls back to apple; Windows + // has no apple — the caller supplies the chain, empty means nothing to + // try, reported as an aggregated failure listing no engines). + if (request.texts.empty()) { + SchedulerOutcome out; + TranslationResultBundle bundle; + bundle.primaryEngine = + chain.empty() ? TranslationEngineType::MtranServer : chain.front().resolvedEngine(); + bundle.selectionMode = EngineSelectionMode::PrimaryWithFallback; + bundle.scene = static_cast(request.scene); + out.bundle = bundle; + return out; + } + + std::vector collected; + for (const auto& item : chain) { + if (request.cancelToken.cancelled()) { + SchedulerOutcome out; + for (const auto& r : collected) { + out.failures.push_back({r.engine, r.displayName, r.errorText}); + } + out.failures.push_back({item.resolvedEngine(), "", "cancelled"}); + return out; + } + ResolveResult resolved = resolve(item); + if (!resolved.resolved || !resolved.provider->isAvailable()) { + // Unavailable / dangling UUID: skip with a logged failure. + EngineResult skipped = EngineResult::makeFailure( + item.resolvedEngine(), + resolved.resolved ? "engine unavailable (not configured)" + : "chain entry unavailable (no provider)", + 0.0, resolved.displayName); + collected.push_back(std::move(skipped)); + continue; + } + EngineResult result = runProvider(resolved, item, request.texts, request.sourceLanguage, + request.targetLanguage, request.scene, + request.cancelToken); + if (result.isSuccess()) { + collected.push_back(std::move(result)); + TranslationResultBundle bundle; + bundle.results = std::move(collected); + bundle.primaryEngine = item.resolvedEngine(); + bundle.selectionMode = EngineSelectionMode::PrimaryWithFallback; + bundle.scene = static_cast(request.scene); + SchedulerOutcome out; + out.bundle = std::move(bundle); + return out; + } + collected.push_back(std::move(result)); + } + // Whole chain failed → aggregate per-engine failure summary. + SchedulerOutcome out; + for (const auto& r : collected) { + out.failures.push_back({r.engine, r.displayName, r.errorText}); + } + return out; +} + +// --------------------------------------------------------------------------- +// Compare (Swift translateCompareV2) + result cache. +// --------------------------------------------------------------------------- +SchedulerOutcome TranslationScheduler::translateCompare(const CompareRequest& request) { + std::vector engines = request.engines; + if (static_cast(engines.size()) > EngineSelectionLimits::compareEnginesLimit) { + engines.resize(EngineSelectionLimits::compareEnginesLimit); + } + if (request.texts.empty()) { + SchedulerOutcome out; + TranslationResultBundle bundle; + bundle.selectionMode = EngineSelectionMode::Parallel; + bundle.scene = static_cast(request.scene); + bundle.primaryEngine = + engines.empty() ? TranslationEngineType::MtranServer : engines.front().resolvedEngine(); + out.bundle = bundle; + return out; + } + + // Parallel fan-out: one worker per entry; results collected by entry id. + struct WorkerOutput { + std::string itemId; + EngineResult result; + }; + std::vector outputs; + outputs.reserve(engines.size()); + { + // Cache snapshot under lock so cached entries are served without + // hitting their providers again (brief FR-21 "结果缓存免重译"). + std::vector> cachedHits; + std::vector toRun; + for (const auto& item : engines) { + if (auto hit = cachedResult(item, request.sourceLanguage, request.targetLanguage, + request.texts)) { + cachedHits.emplace_back(item.id, std::move(*hit)); + } else { + toRun.push_back(item); + } + } + + std::mutex collectMutex; + std::vector workers; + for (const auto& item : toRun) { + workers.emplace_back([&, item] { + ResolveResult resolved = resolve(item); + EngineResult result; + if (!resolved.resolved || !resolved.provider->isAvailable()) { + result = EngineResult::makeFailure( + item.resolvedEngine(), + resolved.resolved ? "engine unavailable (not configured)" + : "chain entry unavailable (no provider)", + 0.0, resolved.displayName); + } else { + result = runProvider(resolved, item, request.texts, request.sourceLanguage, + request.targetLanguage, request.scene, + request.cancelToken); + } + if (result.isSuccess()) { + storeResult(item, request.sourceLanguage, request.targetLanguage, request.texts, + result); + } + std::lock_guard lock(collectMutex); + outputs.push_back({item.id, std::move(result)}); + }); + } + for (auto& w : workers) w.join(); + for (auto& [itemId, result] : cachedHits) { + outputs.push_back({itemId, std::move(result)}); + } + } + + // Selection order preserved (Swift: collected[uuid] then compactMap). + std::vector ordered; + ordered.reserve(engines.size()); + for (const auto& item : engines) { + for (auto& o : outputs) { + if (o.itemId == item.id) { + ordered.push_back(std::move(o.result)); + break; + } + } + } + + bool anySuccess = false; + for (const auto& r : ordered) { + if (r.isSuccess()) { + anySuccess = true; + break; + } + } + if (!anySuccess) { + SchedulerOutcome out; + for (const auto& r : ordered) { + out.failures.push_back({r.engine, r.displayName, r.errorText}); + } + return out; + } + TranslationResultBundle bundle; + bundle.results = std::move(ordered); + bundle.primaryEngine = bundle.results.front().engine; + bundle.selectionMode = EngineSelectionMode::Parallel; + bundle.scene = static_cast(request.scene); + SchedulerOutcome out; + out.bundle = std::move(bundle); + return out; +} + +std::optional TranslationScheduler::cachedResult( + const EngineChainItem& item, const std::string& sourceLanguage, + const std::string& targetLanguage, const std::vector& texts) const { + CacheKey key{engineKeyFor(item), sourceLanguage, targetLanguage, hashTexts(texts)}; + std::lock_guard lock(cacheMutex_); + auto it = resultCache_.find(key); + if (it == resultCache_.end()) return std::nullopt; + return it->second; +} + +void TranslationScheduler::storeResult(const EngineChainItem& item, + const std::string& sourceLanguage, + const std::string& targetLanguage, + const std::vector& texts, + const EngineResult& result) { + CacheKey key{engineKeyFor(item), sourceLanguage, targetLanguage, hashTexts(texts)}; + std::lock_guard lock(cacheMutex_); + resultCache_[key] = result; +} + +void TranslationScheduler::clearResultCache() { + std::lock_guard lock(cacheMutex_); + resultCache_.clear(); +} + +// --------------------------------------------------------------------------- +// Scene routing (brief FR-23). +// --------------------------------------------------------------------------- +SchedulerOutcome TranslationScheduler::translateForScene( + const ChainRequest& globalChain, const CompareRequest& globalCompare, + const SceneEngineBinding& binding, const std::vector& texts, + const std::string& sourceLanguage, const std::string& targetLanguage, + const CancellationToken& token) { + if (!binding.chain.empty()) { + ChainRequest req = globalChain; + req.chain = binding.chain; + req.texts = texts; + req.sourceLanguage = sourceLanguage; + req.targetLanguage = targetLanguage; + req.scene = binding.scene; + req.cancelToken = token; + return translateOrdered(req); + } + if (!binding.compareSet.empty()) { + CompareRequest req = globalCompare; + req.engines = binding.compareSet; + req.texts = texts; + req.sourceLanguage = sourceLanguage; + req.targetLanguage = targetLanguage; + req.scene = binding.scene; + req.cancelToken = token; + return translateCompare(req); + } + // Unbound scene → global chain (default V2 mode is ordered). + ChainRequest req = globalChain; + req.texts = texts; + req.sourceLanguage = sourceLanguage; + req.targetLanguage = targetLanguage; + req.cancelToken = token; + return translateOrdered(req); +} + +// --------------------------------------------------------------------------- +// EngineRegistry +// --------------------------------------------------------------------------- +EngineRegistry::EngineRegistry(BuiltinFactory builtinFactory, + CompatibleFactory compatibleFactory, + CredentialStorePtr credentials, HttpTransportPtr transport) + : builtinFactory_(std::move(builtinFactory)), + compatibleFactory_(std::move(compatibleFactory)), + credentials_(std::move(credentials)), + transport_(std::move(transport)) {} + +TranslationProviderPtr EngineRegistry::provider(TranslationEngineType engine, + const EngineConfig& config) { + std::lock_guard lock(mutex_); + auto it = builtin_.find(engine); + if (it != builtin_.end() && it->second.first == config) { + // Cached provider matches the config slice → reuse (Swift + // matchesCachedProvider). unique_ptr cannot be shared; move a fresh + // factory clone instead so callers keep independent ownership. + return builtinFactory_(engine, config); + } + auto provider = builtinFactory_(engine, config); + if (provider) { + builtin_[engine] = {config, nullptr}; + } + return provider; +} + +TranslationProviderPtr EngineRegistry::compatibleProvider(const CompatibleConfig& config) { + std::lock_guard lock(mutex_); + auto it = compatible_.find(config.id); + if (it != compatible_.end() && it->second.first == config) { + return compatibleFactory_(config, EngineConfig::make(TranslationEngineType::Custom)); + } + auto provider = compatibleFactory_(config, EngineConfig::make(TranslationEngineType::Custom)); + if (provider) { + compatible_[config.id] = {config, nullptr}; + } + return provider; +} + +void EngineRegistry::clearCompatibleProviders() { + std::lock_guard lock(mutex_); + compatible_.clear(); +} + +TranslationProviderPtr makeBuiltinProvider(TranslationEngineType engine, + const EngineConfig& config, + const CredentialStorePtr& credentials, + const HttpTransportPtr& transport) { + switch (engine) { + case TranslationEngineType::MtranServer: { + auto parsed = MTranServerProvider::Configuration::parse( + config.baseURL.empty() ? "localhost:8989" : config.baseURL, + config.effectiveTimeout()); + if (!parsed.has_value()) parsed = MTranServerProvider::Configuration::makeDefault(); + return std::make_unique(std::move(*parsed), transport); + } + case TranslationEngineType::OpenAI: + case TranslationEngineType::Claude: + case TranslationEngineType::Gemini: + case TranslationEngineType::Ollama: + return std::make_unique(engine, config, credentials, transport); + case TranslationEngineType::Google: + return std::make_unique(config, credentials, transport); + case TranslationEngineType::DeepL: + return std::make_unique(config, credentials, transport); + case TranslationEngineType::Baidu: + return std::make_unique(config, credentials, transport); + case TranslationEngineType::Custom: + return nullptr; // instances are created via compatibleProvider() + } + return nullptr; +} + +} // namespace tf diff --git a/windows/Core/src/VisualLineGrouping.cpp b/windows/Core/src/VisualLineGrouping.cpp new file mode 100644 index 0000000..2425af4 --- /dev/null +++ b/windows/Core/src/VisualLineGrouping.cpp @@ -0,0 +1,185 @@ +// VisualLineGrouping.cpp — pure port of Swift VisualLineGrouping.swift. +#include "tf/VisualLineGrouping.hpp" + +#include +#include + +namespace tf { + +namespace { + +/// Decode one UTF-8 code point at index i; advances i. +char32_t decodeUtf8(const std::string& s, std::size_t& i) { + const unsigned char c = static_cast(s[i]); + if (c < 0x80) { + ++i; + return c; + } + if ((c & 0xE0) == 0xC0 && i + 1 < s.size()) { + char32_t cp = ((c & 0x1F) << 6) | (s[i + 1] & 0x3F); + i += 2; + return cp; + } + if ((c & 0xF0) == 0xE0 && i + 2 < s.size()) { + char32_t cp = ((c & 0x0F) << 12) | ((s[i + 1] & 0x3F) << 6) | (s[i + 2] & 0x3F); + i += 3; + return cp; + } + if ((c & 0xF8) == 0xF0 && i + 3 < s.size()) { + char32_t cp = ((c & 0x07) << 18) | ((s[i + 1] & 0x3F) << 12) | ((s[i + 2] & 0x3F) << 6) | + (s[i + 3] & 0x3F); + i += 4; + return cp; + } + ++i; + return 0xFFFD; +} + +char32_t lastCodePoint(const std::string& s) { + if (s.empty()) return 0; + // Walk all code points, keep the last. + std::size_t i = 0; + char32_t last = 0; + while (i < s.size()) last = decodeUtf8(s, i); + return last; +} + +char32_t firstCodePoint(const std::string& s) { + if (s.empty()) return 0; + std::size_t i = 0; + return decodeUtf8(s, i); +} + +} // namespace + +bool VisualLineGrouping::isCJK(char32_t c) { + return (c >= 0x4E00 && c <= 0x9FFF) || (c >= 0x3400 && c <= 0x4DBF) || + (c >= 0x3000 && c <= 0x303F) || (c >= 0xFF00 && c <= 0xFFEF); +} + +bool VisualLineGrouping::isIdentifierCharacter(char32_t c) { + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_'; +} + +bool VisualLineGrouping::isIdentifierLike(const std::string& s) { + if (s.empty()) return false; + // Underscore, digit anywhere, or uppercase after the first character. + if (s.find('_') != std::string::npos) return true; + std::size_t i = 0; + bool first = true; + while (i < s.size()) { + const char32_t c = decodeUtf8(s, i); + if (!first) { + if (c >= 'A' && c <= 'Z') return true; + } + first = false; + if (c >= '0' && c <= '9') return true; + } + return false; +} + +bool VisualLineGrouping::belongsToSameLine(const TextSegment& fragment, + const std::vector& lineFragments) { + const NormRect& box = fragment.boundingBox; + if (!(box.width > 0) || !(box.height > 0)) return false; + NormRect lineBox = lineFragments.front().boundingBox; + for (std::size_t i = 1; i < lineFragments.size(); ++i) { + lineBox = lineBox.unionWith(lineFragments[i].boundingBox); + } + if (!(lineBox.width > 0) || !(lineBox.height > 0)) return false; + + const double overlap = std::min(box.maxY(), lineBox.maxY()) - std::max(box.minY(), lineBox.minY()); + if (!(overlap > 0)) return false; + const double shorter = std::min(box.height, lineBox.height); + if (overlap / shorter < verticalOverlapThreshold) return false; + + const double gap = + std::max(0.0, std::max(box.minX(), lineBox.minX()) - std::min(box.maxX(), lineBox.maxX())); + const double averageHeight = (box.height + lineBox.height) / 2; + return gap <= horizontalGapFactor * averageHeight; +} + +std::vector VisualLineGrouping::mergeLines(const std::vector& segments) { + if (segments.size() <= 1) return segments; + + // Sort by midY, then minX (stable like Swift's sorted with tie-break). + std::vector sorted = segments; + std::stable_sort(sorted.begin(), sorted.end(), [](const TextSegment& a, const TextSegment& b) { + const double ay = a.boundingBox.midY(); + const double by = b.boundingBox.midY(); + if (std::abs(ay - by) > 1e-6) return ay < by; + return a.boundingBox.minX() < b.boundingBox.minX(); + }); + + std::vector> lines; + for (auto& segment : sorted) { + bool joined = false; + for (auto& line : lines) { + if (belongsToSameLine(segment, line)) { + line.push_back(segment); + joined = true; + break; + } + } + if (!joined) lines.push_back({segment}); + } + + // Merge each line's fragments left-to-right. + std::vector out; + out.reserve(lines.size()); + for (auto& line : lines) { + if (line.empty()) continue; + if (line.size() == 1) { + out.push_back(line.front()); + continue; + } + std::vector ordered = line; + std::stable_sort(ordered.begin(), ordered.end(), [](const TextSegment& a, const TextSegment& b) { + return a.boundingBox.minX() < b.boundingBox.minX(); + }); + std::string joinedText = ordered.front().text; + for (std::size_t i = 1; i < ordered.size(); ++i) { + const TextSegment& previous = ordered[i - 1]; + const TextSegment& next = ordered[i]; + const double gap = next.boundingBox.minX() - previous.boundingBox.maxX(); + const double referenceHeight = + std::min(previous.boundingBox.height, next.boundingBox.height); + const bool nearlyTouching = referenceHeight > 0 && gap <= referenceHeight * 0.25; + joinedText = joinText(joinedText, next.text, nearlyTouching); + } + NormRect box = ordered.front().boundingBox; + for (std::size_t i = 1; i < ordered.size(); ++i) { + box = box.unionWith(ordered[i].boundingBox); + } + float confidence = 0; + for (const auto& f : ordered) confidence += f.confidence; + confidence /= static_cast(ordered.size()); + TextSegment merged(joinedText, box, confidence); + for (const auto& f : ordered) { + if (f.isUserEdited) { + merged.isUserEdited = true; + break; + } + } + out.push_back(std::move(merged)); + } + return out; +} + +std::string VisualLineGrouping::joinText(const std::string& lhs, const std::string& rhs, + bool gluesDirectly) { + if (lhs.empty() || rhs.empty()) return lhs + rhs; + const char32_t last = lastCodePoint(lhs); + const char32_t first = firstCodePoint(rhs); + if (isCJK(last) && isCJK(first)) return lhs + rhs; + const bool lhsEndsUnderscore = !lhs.empty() && lhs.back() == '_'; + const bool rhsStartsUnderscore = !rhs.empty() && rhs.front() == '_'; + if (gluesDirectly && isIdentifierCharacter(last) && isIdentifierCharacter(first) && + (lhsEndsUnderscore || rhsStartsUnderscore || + (isIdentifierLike(lhs) && isIdentifierLike(rhs)))) { + return lhs + rhs; + } + return lhs + " " + rhs; +} + +} // namespace tf diff --git a/windows/Core/vendor/nlohmann/json.hpp b/windows/Core/vendor/nlohmann/json.hpp new file mode 100644 index 0000000..8b72ea6 --- /dev/null +++ b/windows/Core/vendor/nlohmann/json.hpp @@ -0,0 +1,24765 @@ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file docs/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// This file contains all macro definitions affecting or depending on the ABI + +#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK + #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) + #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 3 + #warning "Already included a different version of the library!" + #endif + #endif +#endif + +#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_MINOR 11 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_PATCH 3 // NOLINT(modernize-macro-to-enum) + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + +#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#endif + +#if JSON_DIAGNOSTICS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#endif + +#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#else + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION + #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#endif + +// Construct the namespace ABI tags component +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi ## a ## b +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) \ + NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) + +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT( \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON) + +// Construct the namespace version component +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v ## major ## _ ## minor ## _ ## patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) + +#if NLOHMANN_JSON_NAMESPACE_NO_VERSION +#define NLOHMANN_JSON_NAMESPACE_VERSION +#else +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) +#endif + +// Combine namespace components +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ + NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) + +#ifndef NLOHMANN_JSON_NAMESPACE +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann +#endif + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // nullptr_t +#include // exception +#if JSON_DIAGNOSTICS + #include // accumulate +#endif +#include // runtime_error +#include // to_string +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // declval, pair +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +// https://en.cppreference.com/w/cpp/experimental/is_detected +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + + +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-FileCopyrightText: 2016-2021 Evan Nemerson +// SPDX-License-Identifier: MIT + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions (except those affecting ABI) +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// #include + + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#ifdef __has_include + #if __has_include() + #include + #endif +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1914 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_THREE_WAY_COMPARISON + #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ + && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L + #define JSON_HAS_THREE_WAY_COMPARISON 1 + #else + #define JSON_HAS_THREE_WAY_COMPARISON 0 + #endif +#endif + +#ifndef JSON_HAS_RANGES + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error + #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 + #define JSON_HAS_RANGES 0 + #elif defined(__cpp_lib_ranges) + #define JSON_HAS_RANGES 1 + #else + #define JSON_HAS_RANGES 0 + #endif +#endif + +#ifndef JSON_HAS_STATIC_RTTI + #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 + #define JSON_HAS_STATIC_RTTI 1 + #else + #define JSON_HAS_STATIC_RTTI 0 + #endif +#endif + +#ifdef JSON_HAS_CPP_17 + #define JSON_INLINE_VARIABLE inline +#else + #define JSON_INLINE_VARIABLE +#endif + +#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) + #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define JSON_NO_UNIQUE_ADDRESS +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType, \ + class CustomBaseClass> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); +#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1); + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +// inspired from https://stackoverflow.com/a/26745591 +// allows to call any std function as if (e.g. with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DISABLE_ENUM_SERIALIZATION + #define JSON_DISABLE_ENUM_SERIALIZATION 0 +#endif + +#ifndef JSON_USE_GLOBAL_UDLS + #define JSON_USE_GLOBAL_UDLS 1 +#endif + +#if JSON_HAS_THREE_WAY_COMPARISON + #include // partial_ordering +#endif + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +#if JSON_HAS_THREE_WAY_COMPARISON + inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* +#else + inline bool operator<(const value_t lhs, const value_t rhs) noexcept +#endif +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); +#if JSON_HAS_THREE_WAY_COMPARISON + if (l_index < order.size() && r_index < order.size()) + { + return order[l_index] <=> order[r_index]; // *NOPAD* + } + return std::partial_ordering::unordered; +#else + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +#endif +} + +// GCC selects the built-in operator< over an operator rewritten from +// a user-defined spaceship operator +// Clang, MSVC, and ICC select the rewritten candidate +// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) +#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + return std::is_lt(lhs <=> rhs); // *NOPAD* +} +#endif + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +template +inline void replace_substring(StringType& s, const StringType& f, + const StringType& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != StringType::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +template +inline StringType escape(StringType s) +{ + replace_substring(s, StringType{"~"}, StringType{"~0"}); + replace_substring(s, StringType{"/"}, StringType{"~1"}); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +template +static void unescape(StringType& s) +{ + replace_substring(s, StringType{"~1"}, StringType{"/"}); + replace_substring(s, StringType{"~0"}, StringType{"~"}); +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // size_t + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-FileCopyrightText: 2018 The Abseil Authors +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static JSON_INLINE_VARIABLE constexpr T value{}; +}; + +#ifndef JSON_HAS_CPP_17 + template + constexpr T static_const::value; +#endif + +template +inline constexpr std::array make_array(Args&& ... args) +{ + return std::array {{static_cast(std::forward(args))...}}; +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval +#include // tuple +#include // char_traits + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // random_access_iterator_tag + +// #include + +// #include + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); + +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); + +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ + #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + #include // int64_t, uint64_t + #include // map + #include // allocator + #include // string + #include // vector + + // #include + + + /*! + @brief namespace for Niels Lohmann + @see https://github.com/nlohmann + @since version 1.0.0 + */ + NLOHMANN_JSON_NAMESPACE_BEGIN + + /*! + @brief default JSONSerializer template argument + + This serializer ignores the template arguments and uses ADL + ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) + for serialization. + */ + template + struct adl_serializer; + + /// a class to store JSON values + /// @sa https://json.nlohmann.me/api/basic_json/ + template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector, // cppcheck-suppress syntaxError + class CustomBaseClass = void> + class basic_json; + + /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document + /// @sa https://json.nlohmann.me/api/json_pointer/ + template + class json_pointer; + + /*! + @brief default specialization + @sa https://json.nlohmann.me/api/json/ + */ + using json = basic_json<>; + + /// @brief a minimal map-like container that preserves insertion order + /// @sa https://json.nlohmann.me/api/ordered_map/ + template + struct ordered_map; + + /// @brief specialization that maintains the insertion order of object keys + /// @sa https://json.nlohmann.me/api/ordered_json/ + using ordered_json = basic_json; + + NLOHMANN_JSON_NAMESPACE_END + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +NLOHMANN_JSON_NAMESPACE_BEGIN +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ + +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +// used by exceptions create() member functions +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t +// false_type otherwise +template +struct is_basic_json_context : + std::integral_constant < bool, + is_basic_json::type>::type>::value + || std::is_same::value > +{}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +template +using detect_key_compare = typename T::key_compare; + +template +struct has_key_compare : std::integral_constant::value> {}; + +// obtains the actual object key comparator +template +struct actual_object_comparator +{ + using object_t = typename BasicJsonType::object_t; + using object_comparator_t = typename BasicJsonType::default_object_comparator_t; + using type = typename std::conditional < has_key_compare::value, + typename object_t::key_compare, object_comparator_t>::type; +}; + +template +using actual_object_comparator_t = typename actual_object_comparator::type; + +///////////////// +// char_traits // +///////////////// + +// Primary template of char_traits calls std char_traits +template +struct char_traits : std::char_traits +{}; + +// Explicitly define char traits for unsigned char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = unsigned char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(EOF); + } +}; + +// Explicitly define char traits for signed char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = signed char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(EOF); + } +}; + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B { }; +template +struct conjunction +: std::conditional(B::value), conjunction, B>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + // launder type through decltype() to fix compilation failure on ICPC +#ifdef __INTEL_COMPILER + using laundered_type = decltype(std::declval()); +#else + using laundered_type = ConstructibleStringType; +#endif + + static constexpr auto value = + conjunction < + is_constructible, + is_detected_exact>::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& + is_complete_type < + detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +template +struct is_json_iterator_of : std::false_type {}; + +template +struct is_json_iterator_of : std::true_type {}; + +template +struct is_json_iterator_of : std::true_type +{}; + +// checks if a given type T is a template specialization of Primary +template