2 Copyright (C) 2024 Rubén Beltrán del Río
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see https://captura.tranquil.systems.
20 class RecordingWindow: NSWindow {
22 var pixelDensity: CGFloat {
23 self.screen?.backingScaleFactor ?? 1.0
26 var recordingContentView: RecordingContentView {
27 self.contentView as! RecordingContentView
30 init(_ configuration: CaptureSessionConfiguration, _ button: NSRect?) {
32 let boundingBox = NSScreen.screenWithMouse?.frame ?? NSZeroRect
35 contentRect: boundingBox,
36 styleMask: [.borderless],
41 self.isReleasedWhenClosed = false
42 self.collectionBehavior = [.canJoinAllSpaces]
43 self.isMovableByWindowBackground = false
44 self.isMovable = false
46 self.titlebarAppearsTransparent = true
47 self.setFrame(boundingBox, display: true)
48 self.titleVisibility = .hidden
49 let recordingView = RecordingContentView(configuration, frame: boundingBox, button: button ?? NSZeroRect)
50 recordingView.frame = boundingBox
51 self.contentView = recordingView
52 self.backgroundColor = NSColor(white: 1.0, alpha: 0.001)
53 // uncomment below to debug window placement visually
54 // self.backgroundColor = NSColor(red: 1.0, green: 0.0, blue: 1.0, alpha: 0.5)
55 self.level = .screenSaver
57 self.hasShadow = false
60 // MARK: - Window Behavior Overrides
62 override func resetCursorRects() {
63 super.resetCursorRects()
64 let cursor = NSCursor.crosshair
65 self.contentView?.addCursorRect(self.contentView!.bounds, cursor: cursor)
68 override var canBecomeKey: Bool {
72 override var canBecomeMain: Bool {
76 override func resignMain() {
78 if (self.contentView as? RecordingContentView)?.state != .recording {
79 self.ignoresMouseEvents = false
83 override func becomeMain() {
85 if (self.contentView as? RecordingContentView)?.state != .recording {
86 (self.contentView as? RecordingContentView)?.state = .idle
91 enum RecordingWindowState {
92 case passthrough, idle, drawing, moving, resizing, recording;
95 class RecordingContentView: NSView {
97 init(_ configuration: CaptureSessionConfiguration, frame: NSRect, button: NSRect) {
98 self.buttonSize = button.size
99 var buttonOffset = NSPoint()
100 for screen in NSScreen.screens {
101 if screen.frame.intersects(button) {
102 let relativeY = screen.frame.height - (button.minY - screen.frame.minY)
103 let relativeX = screen.frame.width - (button.minX - screen.frame.minX)
104 buttonOffset = NSPoint(x: relativeX, y: relativeY)
107 self.buttonOffset = buttonOffset
108 super.init(frame: frame)
109 preventResize = configuration.preventResize
110 preventMove = configuration.preventMove
111 autoStart = configuration.autoStart
114 self.button = NSRect(x: frame.maxX - buttonOffset.x, y: frame.maxY - buttonOffset.y, width: buttonSize.width, height: buttonSize.height)
116 if configuration.x != nil || configuration.y != nil || configuration.width != nil || configuration.height != nil {
118 x: configuration.x ?? Int(frame.width / 2.0),
119 y: configuration.y ?? Int(frame.height / 2.0),
120 width: configuration.width ?? 400,
121 height: configuration.height ?? 400
126 DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
127 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
132 required init?(coder: NSCoder) {
133 fatalError("init(coder:) has not been implemented")
136 private let buttonSize: NSSize
137 private let buttonOffset: NSPoint
138 public var button: NSRect? = nil
139 @Published public var box: NSRect? = nil
140 public var state: RecordingWindowState = .idle
141 private var mouseLocation: NSPoint = NSPoint()
142 private var origin: NSPoint = NSPoint()
143 private var boxOrigin: NSPoint = NSPoint()
144 private var preventResize = false
145 private var preventMove = false
146 private var autoStart = false
148 private var resizeBox: NSRect? {
150 return NSRect(x: box.maxX - 5, y: box.minY - 5, width: 10, height: 10)
155 private var shouldPassthrough: Bool {
156 state == .recording || state == .passthrough
159 // MARK: - State changing API
161 public func startRecording() {
163 window?.ignoresMouseEvents = true
166 public func stopRecording() {
170 public func reset() {
172 window?.ignoresMouseEvents = false
175 public func startPassthrough() {
177 window?.ignoresMouseEvents = true
180 public func stopPassthrough() {
182 window?.ignoresMouseEvents = false
185 // MARK: - View Behavior Overrides
187 override func updateTrackingAreas() {
188 super.updateTrackingAreas()
190 for trackingArea in self.trackingAreas {
191 self.removeTrackingArea(trackingArea)
194 let options: NSTrackingArea.Options = [.mouseEnteredAndExited, .activeInKeyWindow, .cursorUpdate, .mouseMoved]
195 let trackingArea = NSTrackingArea(rect: self.bounds, options: options, owner: self, userInfo: nil)
196 self.addTrackingArea(trackingArea)
199 override func mouseExited(with event: NSEvent) {
200 if state == .idle && box == nil {
205 override func mouseMoved(with event: NSEvent) {
207 self.mouseLocation = self.convert(event.locationInWindow, from: nil)
209 if shouldPassthrough {
213 if resizeBox!.contains(mouseLocation) {
216 if box.contains(mouseLocation) {
217 NSCursor.openHand.set()
219 NSCursor.crosshair.set()
223 if button.contains(mouseLocation) {
228 NSCursor.crosshair.set()
232 self.setNeedsDisplay(self.bounds)
235 override func mouseDragged(with event: NSEvent) {
236 self.mouseLocation = self.convert(event.locationInWindow, from: nil)
237 if state == .drawing {
239 x: round(min(origin.x, mouseLocation.x)),
240 y: round(min(origin.y, mouseLocation.y)),
241 width: round(abs(mouseLocation.x - origin.x)),
242 height: round(abs(mouseLocation.y - origin.y))
247 if state == .moving {
248 NSCursor.closedHand.set()
249 box!.origin = NSPoint(
250 x: self.boxOrigin.x - self.origin.x + self.mouseLocation.x,
251 y: self.boxOrigin.y - self.origin.y + self.mouseLocation.y)
254 if state == .resizing {
256 x: round(min(origin.x, mouseLocation.x)),
257 y: round(min(origin.y, mouseLocation.y)),
258 width: round(abs(mouseLocation.x - origin.x)),
259 height: round(abs(mouseLocation.y - origin.y))
263 self.setNeedsDisplay(self.bounds)
266 override func cursorUpdate(with event: NSEvent) {
267 NSCursor.crosshair.set()
270 override func hitTest(_ point: NSPoint) -> NSView? {
271 return shouldPassthrough ? nil : self
274 override var acceptsFirstResponder: Bool {
278 override func mouseDown(with event: NSEvent) {
279 self.origin = self.convert(event.locationInWindow, from: nil)
283 if button.contains(origin) {
284 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
289 if resizeBox!.contains(origin) && !preventResize {
290 self.origin = NSPoint(x: box.minX, y: box.maxY)
294 if box.contains(origin) && !preventMove {
296 self.boxOrigin = NSPoint(x: box.origin.x, y: box.origin.y)
301 if preventResize || preventMove {
308 override func mouseUp(with event: NSEvent) {
309 if state != .recording {
314 override func keyDown(with event: NSEvent) {
315 switch event.keyCode {
316 case 53: // Escape key
317 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
319 super.keyDown(with: event)
323 override func flagsChanged(with event: NSEvent) {
325 if event.modifierFlags.contains(.shift) {
333 override func draw(_ dirtyRect: NSRect) {
334 if shouldPassthrough {
335 NSColor.clear.setFill()
337 NSColor(white: 1.0, alpha: 0.001).setFill()
341 let dashLength: CGFloat = 5.0
344 // Uncomment below to debug button placement visually
346 // let buttonPath = NSBezierPath()
347 // buttonPath.move(to: NSPoint(x: button.minX, y: button.minY))
348 // buttonPath.line(to: NSPoint(x: button.maxX, y: button.minY))
349 // buttonPath.line(to: NSPoint(x: button.maxX, y: button.maxY))
350 // buttonPath.line(to: NSPoint(x: button.minX, y: button.maxY))
351 // buttonPath.line(to: NSPoint(x: button.minX, y: button.minY))
352 // NSColor(red: 1, green: 0, blue: 1, alpha: 1).setFill()
356 if state == .idle && box == nil {
357 let blackLine = NSBezierPath()
358 blackLine.lineWidth = lineWidth
359 blackLine.setLineDash([dashLength, dashLength], count: 2, phase: 0)
361 // Vertical line (Black)
362 blackLine.move(to: NSPoint(x: self.mouseLocation.x, y: NSMinY(self.bounds)))
363 blackLine.line(to: NSPoint(x: self.mouseLocation.x, y: NSMaxY(self.bounds)))
365 // Horizontal line (Black)
366 blackLine.move(to: NSPoint(x: NSMinX(self.bounds), y: self.mouseLocation.y))
367 blackLine.line(to: NSPoint(x: NSMaxX(self.bounds), y: self.mouseLocation.y))
369 NSColor.black.setStroke()
372 let whiteLine = NSBezierPath()
373 whiteLine.lineWidth = lineWidth
374 whiteLine.setLineDash([dashLength, dashLength], count: 2, phase: dashLength)
376 // Vertical line (White)
377 whiteLine.move(to: NSPoint(x: self.mouseLocation.x, y: NSMinY(self.bounds)))
378 whiteLine.line(to: NSPoint(x: self.mouseLocation.x, y: NSMaxY(self.bounds)))
380 // Horizontal line (White)
381 whiteLine.move(to: NSPoint(x: NSMinX(self.bounds), y: self.mouseLocation.y))
382 whiteLine.line(to: NSPoint(x: NSMaxX(self.bounds), y: self.mouseLocation.y))
384 NSColor.white.setStroke()
389 let blackBox = NSBezierPath()
390 blackBox.lineWidth = lineWidth
391 blackBox.setLineDash([dashLength, dashLength], count: 2, phase: 0)
392 blackBox.move(to: NSPoint(x: box.minX, y: box.minY))
393 blackBox.line(to: NSPoint(x: box.maxX, y: box.minY))
394 blackBox.line(to: NSPoint(x: box.maxX, y: box.maxY))
395 blackBox.line(to: NSPoint(x: box.minX, y: box.maxY))
396 blackBox.line(to: NSPoint(x: box.minX, y: box.minY))
397 NSColor.black.setStroke()
400 let whiteBox = NSBezierPath()
401 whiteBox.lineWidth = lineWidth
402 whiteBox.setLineDash([dashLength, dashLength], count: 2, phase: dashLength)
403 whiteBox.move(to: NSPoint(x: box.minX, y: box.minY))
404 whiteBox.line(to: NSPoint(x: box.maxX, y: box.minY))
405 whiteBox.line(to: NSPoint(x: box.maxX, y: box.maxY))
406 whiteBox.line(to: NSPoint(x: box.minX, y: box.maxY))
407 whiteBox.line(to: NSPoint(x: box.minX, y: box.minY))
408 NSColor.white.setStroke()
411 if state == .recording {
416 let clearBox = NSBezierPath()
417 clearBox.move(to: NSPoint(x: resizeBox.minX, y: resizeBox.minY))
418 clearBox.line(to: NSPoint(x: resizeBox.maxX, y: resizeBox.minY))
419 clearBox.line(to: NSPoint(x: resizeBox.maxX, y: resizeBox.maxY))
420 clearBox.line(to: NSPoint(x: resizeBox.minX, y: resizeBox.maxY))
421 clearBox.line(to: NSPoint(x: resizeBox.minX, y: resizeBox.minY))
422 NSColor(white: 0, alpha: 0.2).setFill()
426 if state == .moving {
427 let string = "\(Int(box.minX)), \(Int(box.maxY))" as NSString
428 drawText(string, NSPoint(
434 if state == .resizing {
435 let string = "\(Int(mouseLocation.x)), \(Int(mouseLocation.y))" as NSString
436 drawText(string, mouseLocation)
439 if box.contains(mouseLocation) && state != .resizing {
446 let string = "\(Int(mouseLocation.x)), \(Int(mouseLocation.y))" as NSString
447 drawText(string, mouseLocation)
452 private func drawText(_ text: NSString, _ location: NSPoint, _ isBottomRight: Bool = false) {
454 let textAttributes = [
455 NSAttributedString.Key.font: NSFont(name: "Hiragino Mincho ProN", size: 12) ?? NSFont.systemFont(ofSize: 12),
456 NSAttributedString.Key.foregroundColor: NSColor.white,
458 let offset = NSPoint(x: 10, y: 10)
459 let padding = NSPoint(x: 5, y: 2)
460 let size = text.size(withAttributes: textAttributes)
461 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)
462 var textRect = NSRect(x: location.x + offset.x + padding.x, y: location.y + offset.y + padding.y, width: size.width, height: size.height)
465 rect = rect.offsetBy(dx: -size.width - 2 * offset.x, dy: 0)
466 textRect = textRect.offsetBy(dx: -size.width - 2 * offset.x, dy: 0)
472 text.draw(in: textRect, withAttributes: textAttributes)
475 private func moveWindow() {
476 let screen = NSScreen.screenWithMouse
477 if let currentScreen = self.window?.screen {
478 if currentScreen != screen {
479 let frame = screen?.frame ?? NSZeroRect
480 self.frame = CGRect(origin: NSZeroPoint, size: frame.size)
481 self.bounds = CGRect(origin: NSZeroPoint, size: frame.size)
482 self.updateTrackingAreas()
484 if let window = self.window {
486 self.button = NSRect(x: frame.maxX - buttonOffset.x, y: frame.maxY - buttonOffset.y, width: buttonSize.width, height: buttonSize.height)
487 window.setFrame(frame, display: true, animate: false)
488 window.makeKeyAndOrderFront(nil)
489 window.orderFrontRegardless()