-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContentView.swift
More file actions
358 lines (304 loc) · 12.4 KB
/
ContentView.swift
File metadata and controls
358 lines (304 loc) · 12.4 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import SwiftUI
import AppKit
import Foundation
// 🔑 Put your OpenAI API key here (from platform.openai.com)
private let OPENAI_API_KEY = "" // e.g. "sk-..."
struct ChatMessage: Identifiable {
let id = UUID()
let isUser: Bool
let text: String
}
struct ContentView: View {
@State private var messages: [ChatMessage] = []
@State private var inputText: String = ""
@State private var isSending: Bool = false
@State private var statusText: String = ""
var body: some View {
VStack(spacing: 10) {
// TITLE
Text("Overlay ChatGPT")
.font(.headline)
.foregroundColor(.white.opacity(0.9))
// CHAT AREA
ScrollView {
VStack(alignment: .leading, spacing: 8) {
ForEach(messages) { msg in
HStack {
if msg.isUser { Spacer() }
Text(msg.text)
.padding(8)
.background(msg.isUser ? Color.blue.opacity(0.6)
: Color.white.opacity(0.12))
.foregroundColor(.white)
.cornerRadius(10)
if !msg.isUser { Spacer() }
}
}
}
.frame(maxWidth: .infinity)
}
.frame(minHeight: 140, maxHeight: 220)
// INPUT + SEND (Enter submits)
HStack(spacing: 8) {
TextField("Type your question…", text: $inputText)
.textFieldStyle(.roundedBorder)
.disabled(isSending)
.onSubmit {
sendToChatGPT()
}
Button(isSending ? "…" : "Send") {
sendToChatGPT()
}
.disabled(inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isSending)
}
// STATUS / ERROR TEXT
if !statusText.isEmpty {
Text(statusText)
.font(.caption2)
.foregroundColor(.white.opacity(0.85))
}
// COMMAND BAR
HStack(spacing: 10) {
Button("⌘H") { hideOverlay() }
.keyboardShortcut("h", modifiers: .command)
Button("⌘O") { showOverlay() }
.keyboardShortcut("o", modifiers: .command)
Button("⌘U") { takeScreenshotToClipboard() }
.keyboardShortcut("u", modifiers: .command)
Button("⌘P") { sendScreenshotToChatGPT() }
.keyboardShortcut("p", modifiers: .command)
Button("⌘Q") { quitApp() }
.keyboardShortcut("q", modifiers: .command)
}
.font(.caption)
.buttonStyle(.borderedProminent)
.tint(.blue.opacity(0.7))
}
.padding(16)
.background(
RoundedRectangle(cornerRadius: 18, style: .continuous)
.fill(.ultraThinMaterial)
.background(
RoundedRectangle(cornerRadius: 18, style: .continuous)
.fill(Color.blue.opacity(0.25))
)
)
.overlay(
RoundedRectangle(cornerRadius: 18, style: .continuous)
.stroke(Color.blue.opacity(0.9), lineWidth: 2)
)
.shadow(color: Color.blue.opacity(0.5), radius: 12)
.padding(8)
.frame(width: 430) // wider window
}
// MARK: - Window / commands
private func hideOverlay() {
if let window = NSApplication.shared.windows.first {
window.orderOut(nil)
}
statusText = "Overlay hidden (⌘H). Use ⌘O or Dock icon to show."
}
private func showOverlay() {
if let window = NSApplication.shared.windows.first {
window.makeKeyAndOrderFront(nil)
NSApplication.shared.activate(ignoringOtherApps: true)
}
statusText = ""
}
private func quitApp() {
NSApplication.shared.terminate(nil)
}
// ⌘U – interactive screenshot to clipboard
private func takeScreenshotToClipboard() {
statusText = "Taking screenshot… select an area."
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
process.arguments = ["-i", "-c", "-x"] // interactive, clipboard, no sound
do {
try process.run()
statusText = "Screenshot copied to clipboard. Press ⌘P to send to ChatGPT."
} catch {
statusText = "Failed to start screenshot tool."
}
}
// ⌘P – send screenshot from clipboard to ChatGPT (vision)
private func sendScreenshotToChatGPT() {
let pb = NSPasteboard.general
guard let image = NSImage(pasteboard: pb) else {
statusText = "No image in clipboard. Press ⌘U first."
return
}
guard let dataURL = imageToDataURL(image) else {
statusText = "Could not read screenshot data."
return
}
let prompt = "Please analyze this screenshot and explain what is shown."
messages.append(ChatMessage(isUser: true, text: "[Screenshot sent to ChatGPT]"))
isSending = true
statusText = "Sending screenshot to ChatGPT…"
callChatGPTWithImage(prompt: prompt, imageDataURL: dataURL) { response in
DispatchQueue.main.async {
self.isSending = false
self.statusText = ""
if let response = response {
self.messages.append(ChatMessage(isUser: false, text: response))
} else {
self.messages.append(ChatMessage(isUser: false, text: "⚠️ Error analyzing screenshot."))
}
}
}
}
// MARK: - Text chat
private func sendToChatGPT() {
let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty, !isSending else { return }
messages.append(ChatMessage(isUser: true, text: text))
inputText = ""
isSending = true
statusText = "Contacting ChatGPT…"
callChatGPTText(prompt: text) { response in
DispatchQueue.main.async {
self.isSending = false
self.statusText = ""
if let response = response {
self.messages.append(ChatMessage(isUser: false, text: response))
} else {
self.messages.append(ChatMessage(isUser: false, text: "⚠️ Error talking to ChatGPT."))
}
}
}
}
}
// MARK: - Helpers: convert NSImage → base64 data URL
private func imageToDataURL(_ image: NSImage) -> String? {
guard
let tiffData = image.tiffRepresentation,
let bitmap = NSBitmapImageRep(data: tiffData),
let pngData = bitmap.representation(using: .png, properties: [:])
else { return nil }
let base64 = pngData.base64EncodedString()
return "data:image/png;base64,\(base64)"
}
// MARK: - OpenAI calls (with better error messages)
private func callChatGPTText(prompt: String, completion: @escaping (String?) -> Void) {
guard !OPENAI_API_KEY.isEmpty else {
completion("No API key set in the app.")
return
}
let url = URL(string: "https://api.openai.com/v1/chat/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(OPENAI_API_KEY)", forHTTPHeaderField: "Authorization")
let body: [String: Any] = [
"model": "gpt-4o-mini",
"messages": [
["role": "system", "content": "You are a helpful assistant running inside a small macOS overlay window."],
["role": "user", "content": prompt]
],
"max_tokens": 600
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("❌ Network error:", error)
completion("Network error: \(error.localizedDescription)")
return
}
if let http = response as? HTTPURLResponse, http.statusCode != 200 {
let status = http.statusCode
let bodyText = data.flatMap { String(data: $0, encoding: .utf8) } ?? "<no body>"
print("❌ HTTP \(status): \(bodyText)")
if
let data = data,
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let err = json["error"] as? [String: Any],
let msg = err["message"] as? String {
completion("API error (\(status)): \(msg)")
} else {
completion("API error (\(status)): \(bodyText)")
}
return
}
guard
let data = data,
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let choices = json["choices"] as? [[String: Any]],
let first = choices.first,
let message = first["message"] as? [String: Any],
let content = message["content"] as? String
else {
let bodyText = data.flatMap { String(data: $0, encoding: .utf8) } ?? "<no data>"
print("❌ JSON parse failed, body:", bodyText)
completion("Parse error: could not read response.")
return
}
completion(content)
}.resume()
}
private func callChatGPTWithImage(prompt: String, imageDataURL: String, completion: @escaping (String?) -> Void) {
guard !OPENAI_API_KEY.isEmpty else {
completion("No API key set in the app.")
return
}
let url = URL(string: "https://api.openai.com/v1/chat/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(OPENAI_API_KEY)", forHTTPHeaderField: "Authorization")
let userContent: [[String: Any]] = [
[
"type": "text",
"text": prompt
],
[
"type": "image_url",
"image_url": ["url": imageDataURL]
]
]
let body: [String: Any] = [
"model": "gpt-4o-mini",
"messages": [
["role": "system", "content": "You are a helpful assistant analyzing screenshots from a macOS overlay app."],
["role": "user", "content": userContent]
],
"max_tokens": 800
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("❌ Network error (image):", error)
completion("Network error: \(error.localizedDescription)")
return
}
if let http = response as? HTTPURLResponse, http.statusCode != 200 {
let status = http.statusCode
let bodyText = data.flatMap { String(data: $0, encoding: .utf8) } ?? "<no body>"
print("❌ HTTP \(status) (image): \(bodyText)")
if
let data = data,
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let err = json["error"] as? [String: Any],
let msg = err["message"] as? String {
completion("API error (\(status)): \(msg)")
} else {
completion("API error (\(status)): \(bodyText)")
}
return
}
guard
let data = data,
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let choices = json["choices"] as? [[String: Any]],
let first = choices.first,
let message = first["message"] as? [String: Any],
let content = message["content"] as? String
else {
let bodyText = data.flatMap { String(data: $0, encoding: .utf8) } ?? "<no data>"
print("❌ JSON parse failed (image), body:", bodyText)
completion("Parse error: could not read response.")
return
}
completion(content)
}.resume()
}