diff options
| author | Ruben Beltran del Rio <ruben@unlimited.pizza> | 2023-07-27 22:32:10 +0200 |
|---|---|---|
| committer | Ruben Beltran del Rio <ruben@unlimited.pizza> | 2023-07-27 22:32:10 +0200 |
| commit | a4e804275517af683afa1733e2db7c383c306f2b (patch) | |
| tree | 643eff7b3648aad15ce569eec0e1d7c9abddc00d /Captura/Presentation/Windows | |
| parent | e834022c9b363804d36045892a305204f2019216 (diff) | |
Use framerate, control stop
Diffstat (limited to 'Captura/Presentation/Windows')
| -rw-r--r-- | Captura/Presentation/Windows/CapturaApp.swift | 374 | ||||
| -rw-r--r-- | Captura/Presentation/Windows/PreferencesWindow.swift | 20 | ||||
| -rw-r--r-- | Captura/Presentation/Windows/RecordingWindow.swift | 391 |
3 files changed, 785 insertions, 0 deletions
diff --git a/Captura/Presentation/Windows/CapturaApp.swift b/Captura/Presentation/Windows/CapturaApp.swift new file mode 100644 index 0000000..87e2560 --- /dev/null +++ b/Captura/Presentation/Windows/CapturaApp.swift @@ -0,0 +1,374 @@ +import SwiftUI +import SwiftData +import Cocoa +import Combine +import ReplayKit + +@main +struct CapturaApp: App { + + @NSApplicationDelegateAdaptor(CapturaAppDelegate.self) var appDelegate + + var body: some Scene { + WindowGroup { + PreferencesScreen() + .handlesExternalEvents(preferring: Set(arrayLiteral: "PreferencesScreen"), allowing: Set(arrayLiteral: "*")) + .frame(width: 650, height: 450) + } + .handlesExternalEvents(matching: Set(arrayLiteral: "PreferencesScreen")) + .modelContainer(for: Item.self) + } +} + +class CapturaAppDelegate: NSObject, NSApplicationDelegate, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureFileOutputRecordingDelegate, NSMenuDelegate { + + @Environment(\.openURL) var openURL + var statusItem: NSStatusItem! + var captureState: CaptureState = .idle + var recordingWindow: RecordingWindow? = nil + var preferencesWindow: PreferencesWindow? = nil + var boxListener: AnyCancellable? = nil + var popover: NSPopover? = nil + var helpShown = false + var receivedFrames = false + var captureSession: AVCaptureSession? = nil + var images: [CGImage] = [] + var outputURL: URL? = nil + var gifCallbackTimer = ContinuousClock.now + var fps = UserDefaults.standard.integer(forKey: "frameRate") + var pixelDensity: CGFloat = 1.0 + var stopTimer: DispatchWorkItem? + + func applicationDidFinishLaunching(_ notification: Notification) { + setupMenu() + NotificationCenter.default.addObserver( + self, + selector: #selector(self.didReceiveNotification(_:)), + name: nil, + object: nil) + closeWindow() + } + + // MARK: - Setup Functions + + + private func setupMenu() { + statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) + + if let button = statusItem.button { + button.image = NSImage(systemSymbolName: "rectangle.dashed.badge.record", accessibilityDescription: "Captura") + } + + statusItem.isVisible = true + statusItem.menu = NSMenu() + statusItem.menu?.delegate = self + + // Create the Popover + popover = NSPopover() + popover?.contentViewController = HelpPopoverViewController() + popover?.behavior = .transient + + + let recordItem = NSMenuItem(title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording), keyEquivalent: "6") + recordItem.keyEquivalentModifierMask = [.command, .shift] + statusItem.menu?.addItem(recordItem) + statusItem.menu?.addItem(NSMenuItem.separator()) + + let preferencesItem = NSMenuItem(title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences), keyEquivalent: "") + statusItem.menu?.addItem(preferencesItem) + + let quitItem = NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: "") + statusItem.menu?.addItem(quitItem) + } + + private func closeWindow() { + if let window = NSApplication.shared.windows.first { + window.close() + } + } + + // MARK: - UI Event Handlers + + func menuWillOpen(_ menu: NSMenu) { + if captureState != .idle { + menu.cancelTracking() + if captureState == .recording { + stopRecording() + } + } + } + + @objc private func onClickStartRecording() { + NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil) + } + + @objc private func onOpenPreferences() { + NSApp.activate(ignoringOtherApps: true) + if preferencesWindow == nil { + preferencesWindow = PreferencesWindow() + } else { + preferencesWindow?.makeKeyAndOrderFront(nil) + } + } + + @objc private func onQuit() { + NSApplication.shared.terminate(self) + } + + @objc private func onClickStatusBar(_ sender: NSStatusBarButton) { + print("CLICK") + if captureState == .recording { + stopRecording() + } + } + + + // MARK: - App State Event Listeners + + @objc func didReceiveNotification(_ notification: Notification) { + switch(notification.name) { + case .startAreaSelection: + startAreaSelection() + case .startRecording: + startRecording() + case .stopRecording: + stopRecording() + case .finalizeRecording: + finalizeRecording() + case .reset: + reset() + default: + return + } + /* + if let data = notification.userInfo?["data"] as? String { + print("Data received: \(data)") + } + */ + } + + + @objc func startAreaSelection() { + helpShown = false + NSApp.activate(ignoringOtherApps: true) + if captureState != .selectingArea { + captureState = .selectingArea + if let button = statusItem.button { + let rectInWindow = button.convert(button.bounds, to: nil) + let rectInScreen = button.window?.convertToScreen(rectInWindow) + recordingWindow = RecordingWindow(rectInScreen) + if let view = recordingWindow?.contentView as? RecordingContentView { + boxListener = view.$box + .debounce(for: .seconds(0.3), scheduler: RunLoop.main) + .sink { newValue in + if newValue != nil { + button.image = NSImage(systemSymbolName: "circle.rectangle.dashed", accessibilityDescription: "Captura") + if !self.helpShown { + self.helpShown = true + self.showPopoverWithMessage("Click here when you're ready to record.") + } + } + } + } + } + } + } + + func startRecording() { + captureState = .recording + fps = UserDefaults.standard.integer(forKey: "frameRate") + outputURL = nil + images = []; + pixelDensity = recordingWindow?.pixelDensity ?? 1.0 + if let view = recordingWindow?.contentView as? RecordingContentView { + view.startRecording() + if let box = view.box { + if let screen = NSScreen.main { + let displayId = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as! CGDirectDisplayID + let screenInput = AVCaptureScreenInput(displayID: displayId) + screenInput?.cropRect = box.insetBy(dx: 1, dy: 1) + + captureSession = AVCaptureSession() + + if let captureSession { + + + if captureSession.canAddInput(screenInput!) { + captureSession.addInput(screenInput!) + } + + let videoOutput = AVCaptureVideoDataOutput() + videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "sample buffer delegate", attributes: [])) + + if captureSession.canAddOutput(videoOutput) { + captureSession.addOutput(videoOutput) + } + + let movieFileOutput = AVCaptureMovieFileOutput() + if captureSession.canAddOutput(movieFileOutput) { + captureSession.addOutput(movieFileOutput) + } + + stopTimer = DispatchWorkItem { + self.stopRecording() + } + DispatchQueue.main.asyncAfter(deadline: .now() + 300, execute: stopTimer!) + + if let button = statusItem.button { + button.image = NSImage(systemSymbolName: "stop.circle", accessibilityDescription: "Captura") + } + + receivedFrames = false + captureSession.startRunning() + guard let picturesDirectoryURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first else { + fatalError("Unable to access user's Pictures directory") + } + + outputURL = picturesDirectoryURL.appendingPathComponent("captura/\(filename())").appendingPathExtension("mp4") + let outputFormatsSetting = OutputFormatSetting(rawValue: UserDefaults.standard.integer(forKey: "outputFormats")) ?? .all + if outputFormatsSetting.shouldSaveMp4() { + movieFileOutput.startRecording(to: outputURL!, recordingDelegate: self) + } + + DispatchQueue.main.asyncAfter(deadline: .now() + 1) { + if !self.receivedFrames { + self.requestPermission() + } + } + } + + + } else { + print("Should error") + } + } + } + } + + func stopRecording() { + stopTimer?.cancel() + captureState = .uploading + captureSession?.stopRunning() + captureSession = nil + Task.detached { + if let outputURL = self.outputURL { + await self.createGif(url: outputURL.deletingPathExtension().appendingPathExtension("gif")) + } + } + reset() + } + + func finalizeRecording() { + captureState = .uploaded + // Stopping the recording + } + + func reset() { + if let button = statusItem.button { + button.image = NSImage(systemSymbolName: "rectangle.dashed.badge.record", accessibilityDescription: "Captura") + } + captureState = .idle + boxListener?.cancel() + recordingWindow?.close() + self.recordingWindow = nil + } + + private func requestPermission() { + reset() + showPopoverWithMessage("Please grant Captura permission to record") + if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") { + NSWorkspace.shared.open(url) + } + } + + func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { + receivedFrames = true + + let now = ContinuousClock.now + + if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(fps)) { + gifCallbackTimer = now + DispatchQueue.main.async { + // Get the CVImageBuffer from the sample buffer + guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } + let ciImage = CIImage(cvImageBuffer: imageBuffer) + let context = CIContext() + if let cgImage = context.createCGImage(ciImage, from: CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(imageBuffer), height: CVPixelBufferGetHeight(imageBuffer))) { + if let cgImage = self.resize(image: cgImage, by: self.pixelDensity) { + self.images.append(cgImage) + } + } + } + } + } + + func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { + if let error = error as? NSError { + if error.domain == AVFoundationErrorDomain && error.code == -11806 { + Task.detached { + await self.createGif(url: outputFileURL.deletingPathExtension().appendingPathExtension("gif")) + } + } + } + } + + private func showPopoverWithMessage(_ message: String) { + if let button = statusItem.button { + (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message) + self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY) + DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { + self.popover?.performClose(nil) + } + } + } + + func filename() -> String { + let dateFormatter = DateFormatter() + dateFormatter.dateStyle = .medium + dateFormatter.timeStyle = .medium + dateFormatter.locale = Locale.current + let dateString = dateFormatter.string(from: Date()).replacingOccurrences(of: ":", with: ".") + + return "Captura \(dateString)" + } + + func createGif(url: URL) async { + + + let outputFormatsSetting = OutputFormatSetting(rawValue: UserDefaults.standard.integer(forKey: "outputFormats")) ?? .all + if !outputFormatsSetting.shouldSaveGif() { + return + } + + let framedelay = String(format: "%.3f", 1.0 / Double(fps)) + let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] + let gifProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFUnclampedDelayTime as String: framedelay]] + let cfURL = url as CFURL + if let destination = CGImageDestinationCreateWithURL(cfURL, UTType.gif.identifier as CFString, images.count, nil) { + CGImageDestinationSetProperties(destination, fileProperties as CFDictionary?) + for image in images { + CGImageDestinationAddImage(destination, image, gifProperties as CFDictionary?) + } + CGImageDestinationFinalize(destination) + } + } + + private func resize(image: CGImage, by scale: CGFloat) -> CGImage? { + let width = Int(CGFloat(image.width) / scale) + let height = Int(CGFloat(image.height) / scale) + + let bitsPerComponent = image.bitsPerComponent + let colorSpace = image.colorSpace ?? CGColorSpace(name: CGColorSpace.sRGB)! + let bitmapInfo = image.bitmapInfo.rawValue + + guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo) else { + return nil + } + + context.interpolationQuality = .high + context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) + + return context.makeImage() + } + +} diff --git a/Captura/Presentation/Windows/PreferencesWindow.swift b/Captura/Presentation/Windows/PreferencesWindow.swift new file mode 100644 index 0000000..40eac0d --- /dev/null +++ b/Captura/Presentation/Windows/PreferencesWindow.swift @@ -0,0 +1,20 @@ +import Cocoa +import SwiftUI + +import Foundation + +class PreferencesWindow: NSWindow { + + init() { + super.init( + contentRect: NSRect(x: 0, y: 0, width: 600, height: 600), + styleMask: [.titled, .closable, .resizable, .fullSizeContentView], + backing: .buffered, + defer: false) + super.center() + self.isReleasedWhenClosed = false + super.setFrameAutosaveName("Preferences Window") + super.contentView = NSHostingView(rootView: PreferencesScreen()) + super.makeKeyAndOrderFront(nil) + } +} diff --git a/Captura/Presentation/Windows/RecordingWindow.swift b/Captura/Presentation/Windows/RecordingWindow.swift new file mode 100644 index 0000000..2bb9928 --- /dev/null +++ b/Captura/Presentation/Windows/RecordingWindow.swift @@ -0,0 +1,391 @@ +import Cocoa +import Combine + +class RecordingWindow: NSWindow { + + var pixelDensity: CGFloat { + self.screen?.backingScaleFactor ?? 1.0 + } + + init(_ button: NSRect?) { + + let screens = NSScreen.screens + var boundingBox = NSZeroRect + for screen in screens { + boundingBox = NSUnionRect(boundingBox, screen.frame) + } + + super.init( + contentRect: boundingBox, + styleMask: [.borderless], + backing: .buffered, + defer: false) + + self.isReleasedWhenClosed = false + self.collectionBehavior = [.canJoinAllSpaces] + self.center() + self.isMovableByWindowBackground = false + self.isMovable = false + self.titlebarAppearsTransparent = true + self.setFrame(boundingBox, display: true) + self.titleVisibility = .hidden + let recordingView = RecordingContentView() + recordingView.frame = boundingBox + recordingView.button = button + self.contentView = recordingView + self.backgroundColor = NSColor(white: 1.0, alpha: 0.001) + self.level = .screenSaver + self.isOpaque = false + self.hasShadow = false + self.makeKeyAndOrderFront(nil) + } + + // MARK: - Window Behavior Overrides + + override func resetCursorRects() { + super.resetCursorRects() + let cursor = NSCursor.crosshair + self.contentView?.addCursorRect(self.contentView!.bounds, cursor: cursor) + } + + override var canBecomeKey: Bool { + return true + } + + override var canBecomeMain: Bool { + return true + } + + override func resignMain() { + super.resignMain() + if (self.contentView as? RecordingContentView)?.state != .recording { + self.ignoresMouseEvents = false + } + } + + override func becomeMain() { + super.becomeMain() + if (self.contentView as? RecordingContentView)?.state != .recording { + (self.contentView as? RecordingContentView)?.state = .idle + } + } +} + +enum RecordingWindowState { + case passthrough, idle, drawing, moving, resizing, recording; +} + +class RecordingContentView: NSView { + + public var button: NSRect? = nil + @Published public var box: NSRect? = nil + public var state: RecordingWindowState = .idle + private var mouseLocation: NSPoint = NSPoint() + private var origin: NSPoint = NSPoint() + private var boxOrigin: NSPoint = NSPoint() + + private var resizeBox: NSRect? { + if let box { + return NSRect(x: box.maxX - 5, y: box.minY - 5, width: 10, height: 10) + } + return nil + } + + private var shouldPassthrough: Bool { + state == .recording || state == .passthrough + } + + // MARK: - State changing API + + public func startRecording() { + state = .recording + window?.ignoresMouseEvents = true + } + + public func stopRecording() { + + } + + public func reset() { + state = .idle + window?.ignoresMouseEvents = false + } + + public func startPassthrough() { + state = .passthrough + window?.ignoresMouseEvents = true + } + + public func stopPassthrough() { + state = .idle + window?.ignoresMouseEvents = false + } + + // MARK: - View Behavior Overrides + + override func updateTrackingAreas() { + super.updateTrackingAreas() + + for trackingArea in self.trackingAreas { + self.removeTrackingArea(trackingArea) + } + + let options: NSTrackingArea.Options = [.mouseEnteredAndExited, .activeInKeyWindow, .cursorUpdate, .mouseMoved] + let trackingArea = NSTrackingArea(rect: self.bounds, options: options, owner: self, userInfo: nil) + self.addTrackingArea(trackingArea) + } + + override func mouseMoved(with event: NSEvent) { + + self.mouseLocation = self.convert(event.locationInWindow, from: nil) + + if shouldPassthrough { + NSCursor.arrow.set() + } else { + if let box { + if resizeBox!.contains(mouseLocation) { + NSCursor.arrow.set() + } else { + if box.contains(mouseLocation) { + NSCursor.openHand.set() + } else { + NSCursor.crosshair.set() + } + } + if let button { + if button.contains(mouseLocation) { + NSCursor.arrow.set() + } + } + } else { + NSCursor.crosshair.set() + } + } + + self.setNeedsDisplay(self.bounds) + } + + override func mouseDragged(with event: NSEvent) { + self.mouseLocation = self.convert(event.locationInWindow, from: nil) + if state == .drawing { + box = NSRect( + x: round(min(origin.x, mouseLocation.x)), + y: round(min(origin.y, mouseLocation.y)), + width: round(abs(mouseLocation.x - origin.x)), + height: round(abs(mouseLocation.y - origin.y)) + ) + } + + if box != nil { + if state == .moving { + NSCursor.closedHand.set() + box!.origin = NSPoint( + x: self.boxOrigin.x - self.origin.x + self.mouseLocation.x, + y: self.boxOrigin.y - self.origin.y + self.mouseLocation.y) + } + + if state == .resizing { + box = NSRect( + x: round(min(origin.x, mouseLocation.x)), + y: round(min(origin.y, mouseLocation.y)), + width: round(abs(mouseLocation.x - origin.x)), + height: round(abs(mouseLocation.y - origin.y)) + ) + } + } + self.setNeedsDisplay(self.bounds) + } + + override func cursorUpdate(with event: NSEvent) { + NSCursor.crosshair.set() + } + + override func hitTest(_ point: NSPoint) -> NSView? { + return shouldPassthrough ? nil : self + } + + override var acceptsFirstResponder: Bool { + return true + } + + override func mouseDown(with event: NSEvent) { + self.origin = self.convert(event.locationInWindow, from: nil) + if let box { + + if let button { + if button.contains(origin) { + NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil) + return + } + } + + if resizeBox!.contains(origin) { + self.origin = NSPoint(x: box.minX, y: box.maxY) + state = .resizing + return + } + if box.contains(origin) { + state = .moving + self.boxOrigin = NSPoint(x: box.origin.x, y: box.origin.y) + return + } + } + + state = .drawing + } + + override func mouseUp(with event: NSEvent) { + if state != .recording { + state = .idle + } + } + + override func keyDown(with event: NSEvent) { + switch event.keyCode { + case 53: // Escape key + NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil) + default: + super.keyDown(with: event) + } + } + + override func flagsChanged(with event: NSEvent) { + if state == .idle { + if event.modifierFlags.contains(.shift) { + startPassthrough() + } else { + stopPassthrough() + } + } + } + + override func draw(_ dirtyRect: NSRect) { + if shouldPassthrough { + NSColor.clear.setFill() + } else { + NSColor(white: 1.0, alpha: 0.001).setFill() + } + dirtyRect.fill() + + let dashLength: CGFloat = 5.0 + let lineWidth = 0.5 + + if state == .idle && box == nil { + let blackLine = NSBezierPath() + blackLine.lineWidth = lineWidth + blackLine.setLineDash([dashLength, dashLength], count: 2, phase: 0) + + // Vertical line (Black) + blackLine.move(to: NSPoint(x: self.mouseLocation.x, y: NSMinY(self.bounds))) + blackLine.line(to: NSPoint(x: self.mouseLocation.x, y: NSMaxY(self.bounds))) + + // Horizontal line (Black) + blackLine.move(to: NSPoint(x: NSMinX(self.bounds), y: self.mouseLocation.y)) + blackLine.line(to: NSPoint(x: NSMaxX(self.bounds), y: self.mouseLocation.y)) + + NSColor.black.setStroke() + blackLine.stroke() + + let whiteLine = NSBezierPath() + whiteLine.lineWidth = lineWidth + whiteLine.setLineDash([dashLength, dashLength], count: 2, phase: dashLength) + + // Vertical line (White) + whiteLine.move(to: NSPoint(x: self.mouseLocation.x, y: NSMinY(self.bounds))) + whiteLine.line(to: NSPoint(x: self.mouseLocation.x, y: NSMaxY(self.bounds))) + + // Horizontal line (White) + whiteLine.move(to: NSPoint(x: NSMinX(self.bounds), y: self.mouseLocation.y)) + whiteLine.line(to: NSPoint(x: NSMaxX(self.bounds), y: self.mouseLocation.y)) + + NSColor.white.setStroke() + whiteLine.stroke() + } + + if let box { + let blackBox = NSBezierPath() + blackBox.lineWidth = lineWidth + blackBox.setLineDash([dashLength, dashLength], count: 2, phase: 0) + blackBox.move(to: NSPoint(x: box.minX, y: box.minY)) + blackBox.line(to: NSPoint(x: box.maxX, y: box.minY)) + blackBox.line(to: NSPoint(x: box.maxX, y: box.maxY)) + blackBox.line(to: NSPoint(x: box.minX, y: box.maxY)) + blackBox.line(to: NSPoint(x: box.minX, y: box.minY)) + NSColor.black.setStroke() + blackBox.stroke() + + let whiteBox = NSBezierPath() + whiteBox.lineWidth = lineWidth + whiteBox.setLineDash([dashLength, dashLength], count: 2, phase: dashLength) + whiteBox.move(to: NSPoint(x: box.minX, y: box.minY)) + whiteBox.line(to: NSPoint(x: box.maxX, y: box.minY)) + whiteBox.line(to: NSPoint(x: box.maxX, y: box.maxY)) + whiteBox.line(to: NSPoint(x: box.minX, y: box.maxY)) + whiteBox.line(to: NSPoint(x: box.minX, y: box.minY)) + NSColor.white.setStroke() + whiteBox.stroke() + + if state == .recording { + return + } + + if let resizeBox { + let clearBox = NSBezierPath() + clearBox.move(to: NSPoint(x: resizeBox.minX, y: resizeBox.minY)) + clearBox.line(to: NSPoint(x: resizeBox.maxX, y: resizeBox.minY)) + clearBox.line(to: NSPoint(x: resizeBox.maxX, y: resizeBox.maxY)) + clearBox.line(to: NSPoint(x: resizeBox.minX, y: resizeBox.maxY)) + clearBox.line(to: NSPoint(x: resizeBox.minX, y: resizeBox.minY)) + NSColor(white: 0, alpha: 0.2).setFill() + clearBox.fill() + } + + if state == .moving { + let string = "\(Int(box.minX)), \(Int(box.maxY))" as NSString + drawText(string, NSPoint( + x: box.minX, + y: box.maxY + ), true) + } + + if state == .resizing { + let string = "\(Int(mouseLocation.x)), \(Int(mouseLocation.y))" as NSString + drawText(string, mouseLocation) + } + + if box.contains(mouseLocation) && state != .resizing { + return; + } + } + + // Draw text + + let string = "\(Int(mouseLocation.x)), \(Int(mouseLocation.y))" as NSString + drawText(string, mouseLocation) + } + + // MARK: - Utilities + + private func drawText(_ text: NSString, _ location: NSPoint, _ isBottomRight: Bool = false) { + + let textAttributes = [ + NSAttributedString.Key.font: NSFont(name: "Hiragino Mincho ProN", size: 12) ?? NSFont.systemFont(ofSize: 12), + NSAttributedString.Key.foregroundColor: NSColor.white, + ] + let offset = NSPoint(x: 10, y: 10) + let padding = NSPoint(x: 5, y: 2) + let size = text.size(withAttributes: textAttributes) + var rect = NSRect(x: location.x + offset.x, y: location.y + offset.y, width: size.width + 2 * padding.x, height: size.height + 2 * padding.y) + var textRect = NSRect(x: location.x + offset.x + padding.x, y: location.y + offset.y + padding.y, width: size.width, height: size.height) + + if (isBottomRight) { + rect = rect.offsetBy(dx: -size.width - 2 * offset.x, dy: 0) + textRect = textRect.offsetBy(dx: -size.width - 2 * offset.x, dy: 0) + } + + NSColor.black.set() + rect.fill() + + text.draw(in: textRect, withAttributes: textAttributes) + } +} |