\n"+s+""+r+">\n"}listitem(e){let t="";if(e.task){const n=this.checkbox({checked:!!e.checked});e.loose?"paragraph"===e.tokens[0]?.type?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&"text"===e.tokens[0].tokens[0].type&&(e.tokens[0].tokens[0].text=n+" "+W(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" ",escaped:!0}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`${t} \n`}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`${this.parser.parseInline(e)}
\n`}table(e){let t="",n="";for(let t=0;t${s}`),"\n"}tablerow({text:e}){return`\n${e} \n`}tablecell(e){const t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`${n}>\n`}strong({tokens:e}){return`${this.parser.parseInline(e)} `}em({tokens:e}){return`${this.parser.parseInline(e)} `}codespan({text:e}){return`${W(e,!0)}`}br(e){return" "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){const s=this.parser.parseInline(n),r=Y(e);if(null===r)return s;let i='"+s+" ",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));const r=Y(e);if(null===r)return W(n);let i=` ",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:W(e.text)}}class le{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}}class oe{options;renderer;textRenderer;constructor(t){this.options=t||e.defaults,this.options.renderer=this.options.renderer||new ie,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new le}static parse(e,t){return new oe(t).parse(e)}static parseInline(e,t){return new oe(t).parseInline(e)}parse(e,t=!0){let n="";for(let s=0;s{const r=e[s].flat(1/0);n=n.concat(this.walkTokens(r,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new ie(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;const s=n,r=e.renderer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new se(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const s=n,r=e.tokenizer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new ae;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if(["options","block"].includes(n))continue;const s=n,r=e.hooks[s],i=t[s];ae.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async)return Promise.resolve(r.call(t,e)).then((e=>i.call(t,e)));const n=r.call(t,e);return i.call(t,n)}:t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return re.lex(e,t??this.defaults)}parser(e,t){return oe.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{const s={...n},r={...this.defaults,...s},i=this.onError(!!r.silent,!!r.async);if(!0===this.defaults.async&&!1===s.async)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(null==t)return i(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof t)return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));r.hooks&&(r.hooks.options=r,r.hooks.block=e);const l=r.hooks?r.hooks.provideLexer():e?re.lex:re.lexInline,o=r.hooks?r.hooks.provideParser():e?oe.parse:oe.parseInline;if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(t):t).then((e=>l(e,r))).then((e=>r.hooks?r.hooks.processAllTokens(e):e)).then((e=>r.walkTokens?Promise.all(this.walkTokens(e,r.walkTokens)).then((()=>e)):e)).then((e=>o(e,r))).then((e=>r.hooks?r.hooks.postprocess(e):e)).catch(i);try{r.hooks&&(t=r.hooks.preprocess(t));let e=l(t,r);r.hooks&&(e=r.hooks.processAllTokens(e)),r.walkTokens&&this.walkTokens(e,r.walkTokens);let n=o(e,r);return r.hooks&&(n=r.hooks.postprocess(n)),n}catch(e){return i(e)}}}onError(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="An error occurred:
"+W(n.message+"",!0)+" ";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}}const he=new ce;function pe(e,t){return he.parse(e,t)}pe.options=pe.setOptions=function(e){return he.setOptions(e),pe.defaults=he.defaults,n(pe.defaults),pe},pe.getDefaults=t,pe.defaults=e.defaults,pe.use=function(...e){return he.use(...e),pe.defaults=he.defaults,n(pe.defaults),pe},pe.walkTokens=function(e,t){return he.walkTokens(e,t)},pe.parseInline=he.parseInline,pe.Parser=oe,pe.parser=oe.parse,pe.Renderer=ie,pe.TextRenderer=le,pe.Lexer=re,pe.lexer=re.lex,pe.Tokenizer=se,pe.Hooks=ae,pe.parse=pe;const ue=pe.options,ge=pe.setOptions,ke=pe.use,de=pe.walkTokens,fe=pe.parseInline,xe=pe,be=oe.parse,me=re.lex;e.Hooks=ae,e.Lexer=re,e.Marked=ce,e.Parser=oe,e.Renderer=ie,e.TextRenderer=le,e.Tokenizer=se,e.getDefaults=t,e.lexer=me,e.marked=pe,e.options=ue,e.parse=xe,e.parseInline=fe,e.parser=be,e.setOptions=ge,e.use=ke,e.walkTokens=de}));
7 |
--------------------------------------------------------------------------------
/TextPix/TextPix.entitlements:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.security.app-sandbox
6 |
7 | com.apple.security.files.user-selected.read-only
8 |
9 | com.apple.security.network.client
10 |
11 | com.apple.security.network.server
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/TextPix/TextPixApp.swift:
--------------------------------------------------------------------------------
1 | //
2 | // TextPixApp.swift
3 | // TextPix
4 | //
5 | // Created by HAIRONG ZHU on 2025/4/29.
6 | //
7 |
8 | import SwiftUI
9 | import KeyboardShortcuts
10 | import UserNotifications
11 |
12 | @main
13 | struct TextPixApp: App {
14 | @StateObject private var appState = AppState.shared
15 | private let screenshotManager = ScreenshotManager()
16 | private let keyboardManager: KeyboardManager
17 |
18 | init() {
19 | keyboardManager = KeyboardManager(screenshotManager: screenshotManager)
20 | _ = NotificationManager.shared
21 | }
22 |
23 | var body: some Scene {
24 | MenuBarExtra("TextPix", systemImage: "text.viewfinder") {
25 | MainTabView()
26 | .frame(minWidth: 600, minHeight: 450)
27 | }
28 | .menuBarExtraStyle(.window)
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/TextPix/Tools/GPTImageRequestManager.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import SwiftUI
3 |
4 | @MainActor
5 | class GPTImageRequestManager {
6 | private let appState = AppState.shared
7 |
8 | // 将NSImage转换为Base64字符串
9 | private func convertImageToBase64(_ image: NSImage) -> String? {
10 | guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
11 | return nil
12 | }
13 |
14 | let bitmapRep = NSBitmapImageRep(cgImage: cgImage)
15 | guard let data = bitmapRep.representation(using: .jpeg, properties: [.compressionFactor: 0.7]) else {
16 | return nil
17 | }
18 |
19 | return data.base64EncodedString()
20 | }
21 |
22 | // 使用图片和系统提示词发送API请求
23 | @MainActor
24 | func requestCompletion(image: NSImage, systemPrompt: String) async throws {
25 | guard let base64Image = convertImageToBase64(image) else {
26 | throw NSError(domain: "GPTImageRequestManager", code: 1, userInfo: [NSLocalizedDescriptionKey: "无法将图片转换为base64格式"])
27 | }
28 |
29 | appState.isProcessing = true
30 |
31 | // 使用defer确保函数退出时isLoading设为false
32 | defer {
33 | appState.isProcessing = false
34 | }
35 |
36 | // 创建API请求URL
37 | let url = URL(string: appState.endpoint)!
38 | var request = URLRequest(url: url)
39 | request.httpMethod = "POST"
40 | request.addValue("Bearer \(appState.apiKey)", forHTTPHeaderField: "Authorization")
41 | request.addValue("application/json", forHTTPHeaderField: "Content-Type")
42 |
43 | // 创建请求体
44 | let messages: [[String: Any]] = [
45 | [
46 | "role": "system",
47 | "content": appState.systemPrompt
48 | ],
49 | [
50 | "role": "user",
51 | "content": [
52 | [
53 | "type": "image_url",
54 | "image_url": [
55 | "url": "data:image/jpeg;base64,\(base64Image)"
56 | ]
57 | ]
58 | ]
59 | ]
60 | ]
61 |
62 | // 先生成一个通用的 requestBody
63 | var requestBody: [String: Any] = [
64 | "model": appState.model,
65 | "messages": messages
66 | ]
67 |
68 | // 只有在 inferenceEnabled==true 时再补充 reasoning_effort 字段
69 | if appState.inferenceEnabled {
70 | requestBody["reasoning_effort"] = appState.inferenceLevel
71 | }
72 |
73 | do {
74 | request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)
75 | } catch {
76 | throw NSError(domain: "GPTImageRequestManager", code: 3, userInfo: [NSLocalizedDescriptionKey: "请求体序列化失败"])
77 | }
78 |
79 | // 发送请求
80 | do {
81 | let (data, response) = try await URLSession.shared.data(for: request)
82 |
83 | // 检查响应是否有效
84 | guard let httpResponse = response as? HTTPURLResponse else {
85 | throw NSError(domain: "GPTImageRequestManager", code: 2, userInfo: [NSLocalizedDescriptionKey: "无效的HTTP响应"])
86 | }
87 |
88 | if httpResponse.statusCode != 200 {
89 | let errorString = String(data: data, encoding: .utf8) ?? "未知错误"
90 | throw NSError(domain: "GPTImageRequestManager", code: httpResponse.statusCode, userInfo: [NSLocalizedDescriptionKey: errorString])
91 | }
92 |
93 | // 解析响应
94 | let decoder = JSONDecoder()
95 | let apiResponse = try decoder.decode(APIResponse.self, from: data)
96 |
97 | if let content = apiResponse.choices.first?.message.content {
98 | await MainActor.run {
99 | appState.markdownText = content
100 | }
101 | } else {
102 | await MainActor.run {
103 | appState.markdownText = "响应中没有内容"
104 | }
105 | }
106 |
107 | } catch {
108 | await MainActor.run {
109 | appState.markdownText = "错误: \(error.localizedDescription)"
110 | }
111 | throw error
112 | }
113 | }
114 |
115 | // 用于解码API响应的结构体
116 | struct APIResponse: Codable {
117 | let id: String
118 | let object: String
119 | let created: Int
120 | let model: String
121 | let choices: [Choice]
122 | let usage: Usage
123 | }
124 |
125 | struct Choice: Codable {
126 | let index: Int
127 | let message: Message
128 | let finishReason: String?
129 |
130 | enum CodingKeys: String, CodingKey {
131 | case index
132 | case message
133 | case finishReason = "finish_reason"
134 | }
135 | }
136 |
137 | struct Message: Codable {
138 | let role: String
139 | let content: String
140 | }
141 |
142 | struct Usage: Codable {
143 | let promptTokens: Int
144 | let completionTokens: Int
145 | let totalTokens: Int
146 |
147 | enum CodingKeys: String, CodingKey {
148 | case promptTokens = "prompt_tokens"
149 | case completionTokens = "completion_tokens"
150 | case totalTokens = "total_tokens"
151 | }
152 | }
153 | }
154 |
--------------------------------------------------------------------------------
/TextPix/Tools/KeyboardManager.swift:
--------------------------------------------------------------------------------
1 | //
2 | // KeyboardManager.swift
3 | // TextPix
4 | //
5 | // Created by HAIRONG ZHU on 2025/4/30.
6 | //
7 |
8 | import KeyboardShortcuts
9 | import SwiftUI
10 |
11 | extension KeyboardShortcuts.Name {
12 | static let capture = Self(
13 | "capture",
14 | default: .init(.two, modifiers: [.command, .shift])
15 | )
16 | }
17 |
18 | class KeyboardManager {
19 | private let screenshotManager: ScreenshotManager
20 |
21 | init(screenshotManager: ScreenshotManager) {
22 | self.screenshotManager = screenshotManager
23 | setupShortcuts()
24 | }
25 |
26 | private func setupShortcuts() {
27 | KeyboardShortcuts.onKeyUp(for: .capture) { [weak self] in
28 | guard let self = self else { return }
29 | Task {
30 | await self.screenshotManager.captureWithSystemPicker()
31 | }
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/TextPix/Tools/NotificationManager.swift:
--------------------------------------------------------------------------------
1 | //
2 | // NotificationManager.swift
3 | // TextPix
4 | //
5 | // Created by HAIRONG ZHU on 2025/6/13.
6 | //
7 |
8 | import Foundation
9 | import UserNotifications
10 |
11 | /// 统一的本地通知封装
12 | @MainActor
13 | final class NotificationManager: NSObject, UNUserNotificationCenterDelegate {
14 |
15 | static let shared = NotificationManager() // 单例
16 | private override init() {
17 | super.init()
18 | let center = UNUserNotificationCenter.current()
19 | center.delegate = self // 让前台也能弹横幅
20 | Task { await requestAuthorization() }
21 | }
22 |
23 | /// 通知权限申请(只在第一次调用时弹窗)
24 | private func requestAuthorization() async {
25 | let center = UNUserNotificationCenter.current()
26 | do {
27 | try await center.requestAuthorization(options: [.alert, .sound, .badge])
28 | } catch {
29 | // 权限弹窗被系统阻止时也不影响主流程
30 | print("Notification authorization error: \(error.localizedDescription)")
31 | }
32 | }
33 |
34 | /// 发送 OCR 结果通知
35 | func sendOCRResult(success: Bool, errorMessage: String? = nil) {
36 | let content = UNMutableNotificationContent()
37 | content.title = success ? "识别成功" : "识别失败"
38 | content.body = success ? "文本已生成并可复制使用。" : (errorMessage ?? "未知错误")
39 | content.sound = success ? .default : UNNotificationSound(named: UNNotificationSoundName("Glass.aiff"))
40 |
41 | let request = UNNotificationRequest(
42 | identifier: UUID().uuidString,
43 | content: content,
44 | trigger: nil // 立即送达
45 | )
46 | UNUserNotificationCenter.current().add(request)
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/TextPix/Tools/OCRService.swift:
--------------------------------------------------------------------------------
1 | //
2 | // OCRService.swift
3 | // TextPix
4 | //
5 | // Created by Trae AI on 2025/5/2.
6 | //
7 |
8 | import Foundation
9 | import SwiftUI
10 |
11 | @MainActor
12 | class OCRService {
13 | private let gptManager = GPTImageRequestManager()
14 | private let appState = AppState.shared
15 |
16 | func performOCR(on image: NSImage) async {
17 | await MainActor.run {
18 | appState.markdownText = "正在识别中..."
19 | appState.isProcessing = true
20 | appState.selectedTab = 0 // 切换到OCR结果标签页
21 | }
22 |
23 | do {
24 | // 使用 GPTImageRequestManager 发送请求
25 | // 注意:GPTImageRequestManager 内部已经处理了 appState.isProcessing 和 appState.ocrText 的更新
26 | // 这里我们只需要调用它,它会在完成或失败时更新 AppState
27 | try await gptManager.requestCompletion(image: image, systemPrompt: appState.systemPrompt)
28 | // 成功时,gptManager 内部会更新 appState.markdownText
29 | NotificationManager.shared.sendOCRResult(success: true)
30 |
31 | if (appState.autoCopy) {
32 | // 自动复制到剪切板
33 | let pasteboard = NSPasteboard.general
34 | pasteboard.clearContents()
35 | pasteboard.setString(appState.markdownText, forType: .string)
36 | }
37 | } catch {
38 | // 失败时,gptManager 内部会更新 appState.markdownText 为错误信息
39 | NotificationManager.shared.sendOCRResult(success: false, errorMessage: error.localizedDescription)
40 | // 确保即使出错也更新状态
41 | appState.isProcessing = false
42 | // 保留 gptManager 设置的错误信息
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/TextPix/Tools/ScreenshotManager.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ScreenshotManager.swift
3 | // TextPix
4 | //
5 | // Created by HAIRONG ZHU on 2025/4/29.
6 | //
7 |
8 | import SwiftUI
9 |
10 | @MainActor
11 | class ScreenshotManager: ObservableObject {
12 | private let appState = AppState.shared
13 | private let ocrService = OCRService() // 添加 OCR 服务实例
14 |
15 | func captureWithSystemPicker() async {
16 | let tmp = URL(fileURLWithPath: NSTemporaryDirectory())
17 | .appendingPathComponent(UUID().uuidString + ".png")
18 |
19 | let task = Process()
20 | task.launchPath = "/usr/sbin/screencapture"
21 | task.arguments = ["-i", "-x", tmp.path] // -x 静默、-i 交互
22 | task.launch()
23 | task.waitUntilExit()
24 |
25 | if FileManager.default.fileExists(atPath: tmp.path),
26 | let img = NSImage(contentsOf: tmp) {
27 | appState.screenshotImage = img
28 | // 截图成功后,调用 OCR 服务
29 | Task {
30 | await ocrService.performOCR(on: img)
31 | }
32 | }
33 | }
34 | }
35 |
36 |
--------------------------------------------------------------------------------
/TextPix/Views/MainTabView.swift:
--------------------------------------------------------------------------------
1 | //
2 | // MainTabView.swift
3 | // TextPix
4 | //
5 | // Created by HAIRONG ZHU on 2025/5/1.
6 | //
7 |
8 | import SwiftUI
9 |
10 | struct MainTabView: View {
11 | @ObservedObject private var appState = AppState.shared
12 |
13 | var body: some View {
14 | TabView(selection: $appState.selectedTab) {
15 | OCRResultView()
16 | .tag(0)
17 | .tabItem {
18 | Label("OCR", systemImage: "text.viewfinder")
19 | }
20 |
21 | ScreenshotView()
22 | .tag(1)
23 | .tabItem {
24 | Label("Original", systemImage: "photo")
25 | }
26 |
27 | SettingsView()
28 | .tag(2)
29 | .tabItem {
30 | Label("Setting", systemImage: "gear")
31 | }
32 | }
33 | .padding()
34 | }
35 | }
36 |
37 | #Preview {
38 | MainTabView()
39 | }
40 |
--------------------------------------------------------------------------------
/TextPix/Views/OCRResultView.swift:
--------------------------------------------------------------------------------
1 | //
2 | // MarkDownDisplay.swift
3 | // TextPix
4 | //
5 | // Created by HAIRONG ZHU on 2025/5/1.
6 | //
7 |
8 | import SwiftUI
9 | import WebKit
10 | import Combine
11 |
12 | struct OCRResultView: View {
13 | @ObservedObject private var appState = AppState.shared
14 |
15 | var body: some View {
16 | Group {
17 | if appState.isProcessing {
18 | VStack {
19 | ProgressView()
20 | .progressViewStyle(CircularProgressViewStyle())
21 | .scaleEffect(1.5)
22 | Text("正在识别中...")
23 | .font(.headline)
24 | .padding(.top)
25 | }
26 | .frame(maxWidth: .infinity, maxHeight: .infinity)
27 | } else {
28 | VStack {
29 | MarkdownLatexView(markdownText: appState.markdownText)
30 | .frame(minHeight: 100)
31 | .border(Color.gray.opacity(0.3))
32 | .padding(.horizontal)
33 |
34 | Divider()
35 |
36 | TextEditor(text: $appState.markdownText)
37 | .font(.system(size: 14, design: .monospaced))
38 | .padding(4)
39 | .border(Color.gray.opacity(0.3))
40 | .padding(.horizontal)
41 |
42 | Button("Copy to Clipboard") {
43 | let pasteboard = NSPasteboard.general
44 | pasteboard.clearContents()
45 | pasteboard.setString(appState.markdownText, forType: .string)
46 | }
47 | .padding(.bottom)
48 | }
49 | }
50 | }
51 | }
52 |
53 | struct MarkdownLatexView: NSViewRepresentable {
54 | let markdownText: String
55 |
56 | func makeNSView(context: NSViewRepresentableContext) -> WKWebView {
57 | let configuration = WKWebViewConfiguration()
58 | let preferences = WKPreferences()
59 |
60 | // 现代方式启用 JavaScript
61 | let webpagePreferences = WKWebpagePreferences()
62 | webpagePreferences.allowsContentJavaScript = true
63 | configuration.defaultWebpagePreferences = webpagePreferences
64 |
65 | configuration.preferences = preferences
66 | configuration.userContentController.add(context.coordinator, name: "heightUpdate")
67 |
68 | let webView = WKWebView(frame: .zero, configuration: configuration)
69 | webView.navigationDelegate = context.coordinator
70 |
71 | // macOS版本特有设置
72 | webView.allowsMagnification = true
73 |
74 | // 初始化时加载HTML模板
75 | loadHTMLTemplate(webView: webView)
76 |
77 | return webView
78 | }
79 |
80 | func updateNSView(_ webView: WKWebView, context: NSViewRepresentableContext) {
81 | // 只有在页面已加载完成后才执行更新
82 | if context.coordinator.isHTMLLoaded {
83 | updateMarkdownContent(webView: webView)
84 | }
85 | }
86 |
87 | private func loadHTMLTemplate(webView: WKWebView) {
88 | guard let base = Bundle.main.resourceURL else {
89 | print("找不到主资源目录")
90 | return
91 | }
92 |
93 | let html = """
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
126 |
127 |
128 |
129 |
146 |
147 |
148 | """
149 |
150 | webView.loadHTMLString(html, baseURL: base)
151 | }
152 |
153 | private func updateMarkdownContent(webView: WKWebView) {
154 | // 转义特殊字符
155 | let escapedMarkdown = markdownText.replacingOccurrences(of: "\\", with: "\\\\")
156 | .replacingOccurrences(of: "\"", with: "\\\"")
157 | .replacingOccurrences(of: "\n", with: "\\n")
158 |
159 | // 使用JavaScript更新内容而不是重新加载整个页面
160 | let updateScript = "updateMarkdown(\"\(escapedMarkdown)\");"
161 | webView.evaluateJavaScript(updateScript) { (result, error) in
162 | if let error = error {
163 | print("更新Markdown内容时出错: \(error.localizedDescription)")
164 | }
165 | }
166 | }
167 |
168 | func makeCoordinator() -> Coordinator {
169 | Coordinator(self)
170 | }
171 |
172 | class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
173 | var parent: MarkdownLatexView
174 | var isHTMLLoaded = false
175 |
176 | init(_ parent: MarkdownLatexView) {
177 | self.parent = parent
178 | super.init()
179 | }
180 |
181 | func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
182 | // 网页加载完成后, 标记状态并更新初始内容
183 | isHTMLLoaded = true
184 | parent.updateMarkdownContent(webView: webView)
185 | }
186 |
187 | func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
188 | // 处理JavaScript消息
189 | if message.name == "heightUpdate", let height = message.body as? CGFloat {
190 | print("内容高度: \(height)")
191 | // 这里可以执行更多基于高度的逻辑, 如调整视图大小
192 | }
193 | }
194 | }
195 | }
196 | }
197 |
--------------------------------------------------------------------------------
/TextPix/Views/ScreenshotView.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ScreenshotView.swift
3 | // TextPix
4 | //
5 | // Created by HAIRONG ZHU on 2025/5/1.
6 | //
7 |
8 | import SwiftUI
9 |
10 | struct ScreenshotView: View {
11 | @ObservedObject private var appState = AppState.shared
12 |
13 | var body: some View {
14 | VStack {
15 | if let image = appState.screenshotImage {
16 | Image(nsImage: image)
17 | .resizable()
18 | .aspectRatio(contentMode: .fit)
19 | .frame(maxWidth: .infinity, maxHeight: .infinity)
20 | .padding()
21 | .background(Color.gray.opacity(0.1))
22 | .cornerRadius(8)
23 | } else {
24 | VStack(spacing: 20) {
25 | Image(systemName: "photo")
26 | .font(.system(size: 60))
27 | .foregroundColor(.gray)
28 |
29 | Text("试着截一张图吧")
30 | .font(.headline)
31 | }
32 | .frame(maxWidth: .infinity, maxHeight: .infinity)
33 | }
34 | }
35 | .padding()
36 | .frame(minWidth: 400, minHeight: 300)
37 | }
38 | }
39 |
40 | #Preview {
41 | ScreenshotView()
42 | }
43 |
--------------------------------------------------------------------------------
/TextPix/Views/SettingView.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SettingView.swift
3 | // TextPix
4 | //
5 | // Created by HAIRONG ZHU on 2025/4/29.
6 | //
7 |
8 | import SwiftUI
9 | import KeyboardShortcuts
10 |
11 | struct SettingsView: View {
12 | @ObservedObject private var appState = AppState.shared
13 |
14 | var body: some View {
15 | ScrollView {
16 | VStack(alignment: .leading, spacing: 10) {
17 | // 快捷键设置
18 | GroupBox(label: Text("快捷键设置").font(.headline)) {
19 | HStack {
20 | Text("截图快捷键:")
21 | Spacer()
22 | KeyboardShortcuts.Recorder("", name: .capture)
23 | }
24 | }
25 |
26 | // 大语言模型设置
27 | GroupBox(label: Text("LLM设置").font(.headline)) {
28 |
29 | VStack(alignment: .leading, spacing: 2) {
30 | Text("模型")
31 | .font(.caption)
32 | .foregroundColor(.secondary)
33 | TextField("输入模型名称", text: $appState.model)
34 | .textFieldStyle(.roundedBorder)
35 | .font(.subheadline)
36 | .cornerRadius(8)
37 | }
38 |
39 | VStack(alignment: .leading, spacing: 2) {
40 | Text("API 地址")
41 | .font(.caption)
42 | .foregroundColor(.secondary)
43 | TextField("输入API地址", text: $appState.endpoint)
44 | .textFieldStyle(.roundedBorder)
45 | .font(.subheadline)
46 | .cornerRadius(8)
47 | }
48 |
49 | VStack(alignment: .leading, spacing: 2) {
50 | Text("API 密钥")
51 | .font(.caption)
52 | .foregroundColor(.secondary)
53 |
54 | SecureField("输入您的 API 密钥", text: $appState.apiKey)
55 | .textFieldStyle(.roundedBorder)
56 | .font(.subheadline)
57 | .cornerRadius(8)
58 | }
59 |
60 | // 是否开启推理(按钮),以及推理强度列表 low medium high none
61 | HStack(spacing: 2) {
62 | Toggle(isOn: $appState.inferenceEnabled) {
63 | Text("启用推理")
64 | .font(.caption)
65 | .foregroundColor(.secondary)
66 | }
67 | .toggleStyle(SwitchToggleStyle())
68 |
69 | Spacer()
70 | Picker("推理强度", selection: $appState.inferenceLevel) {
71 | Text("low").tag("low")
72 | Text("medium").tag("medium")
73 | Text("high").tag("high")
74 | Text("none").tag("none")
75 | }
76 | .pickerStyle(.segmented)
77 | }
78 | }
79 |
80 | // OCR提示词设置
81 | GroupBox(label: Text("OCR系统提示词").font(.headline)) {
82 | TextEditor(text: $appState.systemPrompt)
83 | .font(.system(size: 12, design: .monospaced))
84 | .textFieldStyle(.roundedBorder)
85 | .cornerRadius(8)
86 | .frame(minHeight: 100)
87 | }
88 |
89 | // 其他
90 | HStack {
91 | // 选择框,是否自动copy
92 | Toggle("OCR结果自动复制到剪切板", isOn: $appState.autoCopy)
93 |
94 | Spacer() // 将按钮推到右侧
95 | Button("Quit") {
96 | NSApplication.shared.terminate(nil)
97 | }
98 | }
99 | .padding()
100 |
101 |
102 |
103 | }
104 | .padding()
105 | }
106 | .frame(minWidth: 500, minHeight: 400)
107 | }
108 | }
109 |
110 | #Preview {
111 | SettingsView()
112 | }
113 |
--------------------------------------------------------------------------------
/images/ocr_code.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kivvi3412/TextPix/3d890bb13470d448f9d5c0f7af227cb44cb37472/images/ocr_code.png
--------------------------------------------------------------------------------
/images/ocr_markdown_latex.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kivvi3412/TextPix/3d890bb13470d448f9d5c0f7af227cb44cb37472/images/ocr_markdown_latex.png
--------------------------------------------------------------------------------