-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScreenshotManager.swift
More file actions
595 lines (495 loc) · 20.3 KB
/
Copy pathScreenshotManager.swift
File metadata and controls
595 lines (495 loc) · 20.3 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
import Foundation
import AppKit
import CoreGraphics
import UserNotifications
import AVFoundation
import Sentry
import ScreenCaptureKit
// MARK: - Custom Error Types
enum ScreenCapError: LocalizedError {
case noDisplayFound
case permissionDenied
case captureKitError(String)
case fileWriteError(String)
case imageProcessingError
case invalidSaveDirectory(String)
var errorDescription: String? {
switch self {
case .noDisplayFound: return "No display found"
case .permissionDenied: return "Screen recording permission denied"
case .captureKitError(let msg): return "ScreenCaptureKit error: \(msg)"
case .fileWriteError(let msg): return "Error saving: \(msg)"
case .imageProcessingError: return "Could not process the image"
case .invalidSaveDirectory(let msg): return "Invalid save directory: \(msg)"
}
}
}
// MARK: - Recent Capture Model
struct RecentCapture: Identifiable, Codable {
let id: UUID
let filename: String
let filePath: String
let captureType: String
let timestamp: Date
init(filename: String, filePath: String, captureType: String) {
self.id = UUID()
self.filename = filename
self.filePath = filePath
self.captureType = captureType
self.timestamp = Date()
}
}
// MARK: - Screenshot Manager
class ScreenshotManager: ObservableObject {
private let userDefaults = UserDefaults.standard
static let maxRecentCaptures = 10
// MARK: - Published State
@Published var recentCaptures: [RecentCapture] = []
@Published var copyToClipboard: Bool = false
// MARK: - Configuration Properties
private var filePrefix: String {
let raw = userDefaults.string(forKey: "filePrefix") ?? "Screenshot"
return Self.sanitizeFilename(raw)
}
private var saveDirectory: URL {
if let savedPath = userDefaults.string(forKey: "saveDirectory"),
let url = URL(string: savedPath) {
return url
}
if let desktopURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first {
return desktopURL
}
return FileManager.default.homeDirectoryForCurrentUser
}
private var includeTimestamp: Bool {
return userDefaults.bool(forKey: "includeTimestamp")
}
private var imageFormat: String {
return userDefaults.string(forKey: "imageFormat") ?? "png"
}
private var floatingPreviewTime: Double {
let time = userDefaults.double(forKey: "floatingPreviewTime")
return time > 0 ? time : 10.0
}
// MARK: - Initialization
init() {
setupDefaultSettings()
requestNotificationPermission()
loadRecentCaptures()
copyToClipboard = userDefaults.bool(forKey: "copyToClipboard")
}
// MARK: - Filename Sanitization
static func sanitizeFilename(_ input: String) -> String {
let forbidden = CharacterSet(charactersIn: "/\\:*?\"<>|.")
let sanitized = input.components(separatedBy: forbidden).joined(separator: "_")
let trimmed = sanitized.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? "Screenshot" : String(trimmed.prefix(100))
}
// MARK: - Directory Validation
func validateSaveDirectory(_ url: URL) -> Result<Void, ScreenCapError> {
var isDirectory: ObjCBool = false
guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory),
isDirectory.boolValue else {
return .failure(.invalidSaveDirectory("Directory does not exist"))
}
guard FileManager.default.isWritableFile(atPath: url.path) else {
return .failure(.invalidSaveDirectory("Directory is not writable"))
}
return .success(())
}
// MARK: - Permission Checking (Async)
private func checkScreenRecordingPermissionAsync() async -> Bool {
do {
let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
return !content.displays.isEmpty
} catch {
return false
}
}
private func showPermissionAlert() {
DispatchQueue.main.async {
let alert = NSAlert()
alert.messageText = "Screen Recording Permissions Required"
alert.informativeText = "ScreenCap needs permissions to capture the screen.\n\n1. Go to System Settings > Privacy & Security\n2. Select 'Screen Recording'\n3. Turn on the switch for ScreenCap\n4. Restart the application"
alert.alertStyle = .warning
alert.addButton(withTitle: "Open Settings")
alert.addButton(withTitle: "Cancel")
let response = alert.runModal()
if response == .alertFirstButtonReturn {
if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture") {
let opened = NSWorkspace.shared.open(url)
if !opened {
print("Could not open System Settings")
let error = NSError(domain: "ScreenCap", code: 100, userInfo: [NSLocalizedDescriptionKey: "Could not open System Settings"])
SentrySDK.capture(error: error)
}
}
}
}
}
private func setupDefaultSettings() {
if userDefaults.object(forKey: "filePrefix") == nil {
userDefaults.set("Screenshot", forKey: "filePrefix")
}
if userDefaults.object(forKey: "includeTimestamp") == nil {
userDefaults.set(false, forKey: "includeTimestamp")
}
if userDefaults.object(forKey: "imageFormat") == nil {
userDefaults.set("png", forKey: "imageFormat")
}
}
private func requestNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, error in
if let error = error {
print("Error requesting notification permission: \(error)")
SentrySDK.capture(error: error)
}
}
}
private func checkNotificationPermission(completion: @escaping (Bool) -> Void) {
UNUserNotificationCenter.current().getNotificationSettings { settings in
DispatchQueue.main.async {
completion(settings.authorizationStatus == .authorized)
}
}
}
// MARK: - Capture Methods (Now Async)
func captureFullScreen() {
Task {
guard await checkScreenRecordingPermissionAsync() else {
await MainActor.run { showPermissionAlert() }
return
}
await performFullScreenCapture()
}
}
@MainActor
private func performFullScreenCapture() async {
guard let screen = NSScreen.main else {
showError("Could not access the main screen")
return
}
let rect = screen.frame
await captureRectWithScreenCaptureKit(rect, description: "full screen")
}
func captureSelection() {
Task {
guard await checkScreenRecordingPermissionAsync() else {
await MainActor.run { showPermissionAlert() }
return
}
await performSelectionCapture()
}
}
private func performSelectionCapture() async {
let tempPath = "/tmp/screencap_\(UUID().uuidString).png"
let task = Process()
task.launchPath = "/usr/sbin/screencapture"
task.arguments = ["-i", "-s", tempPath]
do {
try task.run()
task.waitUntilExit()
await MainActor.run {
self.processTemporaryScreenshot(at: tempPath, description: "selection")
}
} catch {
await MainActor.run {
self.showError("Error starting selection capture: \(error.localizedDescription)")
SentrySDK.capture(error: error)
}
}
}
func captureWindow() {
Task {
guard await checkScreenRecordingPermissionAsync() else {
await MainActor.run { showPermissionAlert() }
return
}
await performWindowCapture()
}
}
private func performWindowCapture() async {
let tempPath = "/tmp/screencap_\(UUID().uuidString).png"
let task = Process()
task.launchPath = "/usr/sbin/screencapture"
task.arguments = ["-i", "-w", tempPath]
do {
try task.run()
task.waitUntilExit()
await MainActor.run {
self.processTemporaryScreenshot(at: tempPath, description: "window")
}
} catch {
await MainActor.run {
self.showError("Error starting window capture: \(error.localizedDescription)")
SentrySDK.capture(error: error)
}
}
}
// MARK: - Multi-Monitor Support
func captureDisplay(at index: Int) {
Task {
guard await checkScreenRecordingPermissionAsync() else {
await MainActor.run { showPermissionAlert() }
return
}
do {
let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
guard index < content.displays.count else {
await MainActor.run { self.showError("Display not found") }
return
}
let display = content.displays[index]
let filter = SCContentFilter(display: display, excludingWindows: [])
let configuration = SCStreamConfiguration()
configuration.width = display.width
configuration.height = display.height
configuration.showsCursor = true
configuration.scalesToFit = false
let cgImage = try await SCScreenshotManager.captureImage(
contentFilter: filter,
configuration: configuration
)
await MainActor.run {
let size = NSSize(width: display.width, height: display.height)
let nsImage = NSImage(cgImage: cgImage, size: size)
self.saveImage(nsImage, description: "display \(index + 1)")
}
} catch {
await MainActor.run {
self.showError("Capture error: \(error.localizedDescription)")
SentrySDK.capture(error: error)
}
}
}
}
func getAvailableDisplays() async -> [SCDisplay] {
do {
let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
return content.displays
} catch {
return []
}
}
// MARK: - ScreenCaptureKit Capture
private func captureRectWithScreenCaptureKit(_ rect: NSRect, description: String) async {
do {
let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
guard let display = content.displays.first else {
await MainActor.run { self.showError("No display found") }
return
}
let filter = SCContentFilter(display: display, excludingWindows: [])
let configuration = SCStreamConfiguration()
configuration.width = Int(rect.width)
configuration.height = Int(rect.height)
configuration.sourceRect = rect
configuration.showsCursor = true
configuration.scalesToFit = false
let cgImage = try await SCScreenshotManager.captureImage(
contentFilter: filter,
configuration: configuration
)
await MainActor.run {
let nsImage = NSImage(cgImage: cgImage, size: rect.size)
self.saveImage(nsImage, description: description)
}
} catch {
await MainActor.run {
self.showError("ScreenCaptureKit error: \(error.localizedDescription)")
SentrySDK.capture(error: error)
}
}
}
// MARK: - Image Processing & Saving
private func processTemporaryScreenshot(at tempPath: String, description: String) {
defer {
// Always clean up temp file
try? FileManager.default.removeItem(atPath: tempPath)
}
guard FileManager.default.fileExists(atPath: tempPath),
let nsImage = NSImage(contentsOfFile: tempPath) else {
// User cancelled the capture
return
}
saveImage(nsImage, description: description)
}
private func saveImage(_ image: NSImage, description: String) {
// Validate save directory
if case .failure(let error) = validateSaveDirectory(saveDirectory) {
showError(error.localizedDescription)
return
}
let filename = generateFilename()
let fileURL = saveDirectory.appendingPathComponent(filename)
guard let imageData = getImageData(from: image) else {
showError("Could not process the image")
return
}
// Write file on background queue to avoid blocking UI
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
do {
try imageData.write(to: fileURL)
DispatchQueue.main.async {
guard let self = self else { return }
// Copy to clipboard if enabled
if self.copyToClipboard {
self.copyImageToClipboard(image)
}
// Track recent capture
self.addRecentCapture(filename: filename, filePath: fileURL.path, captureType: description)
self.showSuccess("\(description) capture saved: \(filename)")
self.showFloatingPreview(image: image)
}
} catch {
DispatchQueue.main.async {
self?.showError("Error saving: \(error.localizedDescription)")
SentrySDK.capture(error: error)
}
}
}
}
private func showFloatingPreview(image: NSImage) {
let previewWindow = FloatingPreviewWindow(image: image, autoCloseTime: floatingPreviewTime)
previewWindow.makeKeyAndOrderFront(nil)
}
// MARK: - Clipboard Support
private func copyImageToClipboard(_ image: NSImage) {
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.writeObjects([image])
}
func updateCopyToClipboard(_ enabled: Bool) {
copyToClipboard = enabled
userDefaults.set(enabled, forKey: "copyToClipboard")
}
// MARK: - Recent Captures
private func loadRecentCaptures() {
guard let data = userDefaults.data(forKey: "recentCaptures"),
let captures = try? JSONDecoder().decode([RecentCapture].self, from: data) else {
return
}
recentCaptures = captures
}
private func saveRecentCaptures() {
guard let data = try? JSONEncoder().encode(recentCaptures) else { return }
userDefaults.set(data, forKey: "recentCaptures")
}
private func addRecentCapture(filename: String, filePath: String, captureType: String) {
let capture = RecentCapture(filename: filename, filePath: filePath, captureType: captureType)
recentCaptures.insert(capture, at: 0)
if recentCaptures.count > Self.maxRecentCaptures {
recentCaptures = Array(recentCaptures.prefix(Self.maxRecentCaptures))
}
saveRecentCaptures()
}
func clearRecentCaptures() {
recentCaptures.removeAll()
saveRecentCaptures()
}
func openRecentCapture(_ capture: RecentCapture) {
let url = URL(fileURLWithPath: capture.filePath)
NSWorkspace.shared.open(url)
}
func revealRecentCapture(_ capture: RecentCapture) {
let url = URL(fileURLWithPath: capture.filePath)
NSWorkspace.shared.activateFileViewerSelecting([url])
}
// MARK: - Filename Generation
func generateFilename() -> String {
var filename = filePrefix
if includeTimestamp {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd_HH-mm-ss"
filename += "_\(formatter.string(from: Date()))"
} else {
var counter = 1
var testFilename: String
repeat {
testFilename = "\(filename)_\(counter).\(imageFormat)"
counter += 1
} while FileManager.default.fileExists(atPath: saveDirectory.appendingPathComponent(testFilename).path)
return testFilename
}
return "\(filename).\(imageFormat)"
}
private func getImageData(from image: NSImage) -> Data? {
guard let tiffData = image.tiffRepresentation,
let bitmapRep = NSBitmapImageRep(data: tiffData) else {
return nil
}
switch imageFormat.lowercased() {
case "png":
return bitmapRep.representation(using: .png, properties: [:])
case "jpg", "jpeg":
return bitmapRep.representation(using: .jpeg, properties: [.compressionFactor: 0.9])
default:
return bitmapRep.representation(using: .png, properties: [:])
}
}
// MARK: - Notifications
private func showSuccess(_ message: String) {
checkNotificationPermission { hasPermission in
if hasPermission {
let content = UNMutableNotificationContent()
content.title = "ScreenCap"
content.body = message
content.sound = .default
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error showing success notification: \(error)")
SentrySDK.capture(error: error)
}
}
} else {
print("Success: \(message) (notification permission not granted)")
}
}
}
private func showError(_ message: String) {
checkNotificationPermission { hasPermission in
if hasPermission {
let content = UNMutableNotificationContent()
content.title = "ScreenCap - Error"
content.body = message
content.sound = .default
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error showing error notification: \(error)")
SentrySDK.capture(error: error)
}
}
} else {
print("Error: \(message) (notification permission not granted)")
}
}
}
// MARK: - Settings Management
func updatePrefix(_ newPrefix: String) {
userDefaults.set(newPrefix, forKey: "filePrefix")
}
func updateSaveDirectory(_ newDirectory: URL) {
if case .failure(let error) = validateSaveDirectory(newDirectory) {
showError(error.localizedDescription)
return
}
userDefaults.set(newDirectory.absoluteString, forKey: "saveDirectory")
}
func updateIncludeTimestamp(_ include: Bool) {
userDefaults.set(include, forKey: "includeTimestamp")
}
func updateImageFormat(_ format: String) {
userDefaults.set(format, forKey: "imageFormat")
}
func updateFloatingPreviewTime(_ time: Double) {
userDefaults.set(time, forKey: "floatingPreviewTime")
}
// MARK: - Getters for Settings
func getCurrentPrefix() -> String { return filePrefix }
func getCurrentSaveDirectory() -> URL { return saveDirectory }
func getCurrentIncludeTimestamp() -> Bool { return includeTimestamp }
func getCurrentImageFormat() -> String { return imageFormat }
func getCurrentFloatingPreviewTime() -> Double { return floatingPreviewTime }
}