]> git.r.bdr.sh - rbdr/captura/blob - Captura/Presentation/Windows/RecordingWindow.swift
a12c5fb0bbd83db33fdd11aeb38e4b1bc3032e2a
[rbdr/captura] / Captura / Presentation / Windows / RecordingWindow.swift
1 /*
2 Copyright (C) 2024 Rubén Beltrán del Río
3
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.
8
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.
13
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.
16 */
17 import Cocoa
18 import Combine
19
20 class RecordingWindow: NSWindow {
21
22 var pixelDensity: CGFloat {
23 self.screen?.backingScaleFactor ?? 1.0
24 }
25
26 var recordingContentView: RecordingContentView {
27 self.contentView as! RecordingContentView
28 }
29
30 init(_ configuration: CaptureSessionConfiguration, _ button: NSRect?) {
31
32 let boundingBox = NSScreen.screenWithMouse?.frame ?? NSZeroRect
33
34 super.init(
35 contentRect: boundingBox,
36 styleMask: [.borderless],
37 backing: .buffered,
38 defer: false)
39
40
41 self.isReleasedWhenClosed = false
42 self.collectionBehavior = [.canJoinAllSpaces]
43 self.isMovableByWindowBackground = false
44 self.isMovable = false
45 self.canHide = 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
56 self.isOpaque = false
57 self.hasShadow = false
58 }
59
60 // MARK: - Window Behavior Overrides
61
62 override func resetCursorRects() {
63 super.resetCursorRects()
64 let cursor = NSCursor.crosshair
65 self.contentView?.addCursorRect(self.contentView!.bounds, cursor: cursor)
66 }
67
68 override var canBecomeKey: Bool {
69 return true
70 }
71
72 override var canBecomeMain: Bool {
73 return true
74 }
75
76 override func resignMain() {
77 super.resignMain()
78 if (self.contentView as? RecordingContentView)?.state != .recording {
79 self.ignoresMouseEvents = false
80 }
81 }
82
83 override func becomeMain() {
84 super.becomeMain()
85 if (self.contentView as? RecordingContentView)?.state != .recording {
86 (self.contentView as? RecordingContentView)?.state = .idle
87 }
88 }
89 }
90
91 enum RecordingWindowState {
92 case passthrough, idle, drawing, moving, resizing, recording;
93 }
94
95 class RecordingContentView: NSView {
96
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)
105 }
106 }
107 self.buttonOffset = buttonOffset
108 super.init(frame: frame)
109 preventResize = configuration.preventResize
110 preventMove = configuration.preventMove
111 autoStart = configuration.autoStart
112
113 self.bounds = frame
114 self.button = NSRect(x: frame.maxX - buttonOffset.x, y: frame.maxY - buttonOffset.y, width: buttonSize.width, height: buttonSize.height)
115
116 if configuration.x != nil || configuration.y != nil || configuration.width != nil || configuration.height != nil {
117 box = NSRect(
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
122 )
123 }
124
125 if autoStart {
126 DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
127 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
128 }
129 }
130 }
131
132 required init?(coder: NSCoder) {
133 fatalError("init(coder:) has not been implemented")
134 }
135
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
147
148 private var resizeBox: NSRect? {
149 if let box {
150 return NSRect(x: box.maxX - 5, y: box.minY - 5, width: 10, height: 10)
151 }
152 return nil
153 }
154
155 private var shouldPassthrough: Bool {
156 state == .recording || state == .passthrough
157 }
158
159 // MARK: - State changing API
160
161 public func startRecording() {
162 state = .recording
163 window?.ignoresMouseEvents = true
164 }
165
166 public func stopRecording() {
167
168 }
169
170 public func reset() {
171 state = .idle
172 window?.ignoresMouseEvents = false
173 }
174
175 public func startPassthrough() {
176 state = .passthrough
177 window?.ignoresMouseEvents = true
178 }
179
180 public func stopPassthrough() {
181 state = .idle
182 window?.ignoresMouseEvents = false
183 }
184
185 // MARK: - View Behavior Overrides
186
187 override func updateTrackingAreas() {
188 super.updateTrackingAreas()
189
190 for trackingArea in self.trackingAreas {
191 self.removeTrackingArea(trackingArea)
192 }
193
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)
197 }
198
199 override func mouseExited(with event: NSEvent) {
200 if state == .idle && box == nil {
201 self.moveWindow()
202 }
203 }
204
205 override func mouseMoved(with event: NSEvent) {
206
207 self.mouseLocation = self.convert(event.locationInWindow, from: nil)
208
209 if shouldPassthrough {
210 NSCursor.arrow.set()
211 } else {
212 if let box {
213 if resizeBox!.contains(mouseLocation) {
214 NSCursor.arrow.set()
215 } else {
216 if box.contains(mouseLocation) {
217 NSCursor.openHand.set()
218 } else {
219 NSCursor.crosshair.set()
220 }
221 }
222 if let button {
223 if button.contains(mouseLocation) {
224 NSCursor.arrow.set()
225 }
226 }
227 } else {
228 NSCursor.crosshair.set()
229 }
230 }
231
232 self.setNeedsDisplay(self.bounds)
233 }
234
235 override func mouseDragged(with event: NSEvent) {
236 self.mouseLocation = self.convert(event.locationInWindow, from: nil)
237 if state == .drawing {
238 box = NSRect(
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))
243 )
244 }
245
246 if box != nil {
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)
252 }
253
254 if state == .resizing {
255 box = NSRect(
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))
260 )
261 }
262 }
263 self.setNeedsDisplay(self.bounds)
264 }
265
266 override func cursorUpdate(with event: NSEvent) {
267 NSCursor.crosshair.set()
268 }
269
270 override func hitTest(_ point: NSPoint) -> NSView? {
271 return shouldPassthrough ? nil : self
272 }
273
274 override var acceptsFirstResponder: Bool {
275 return true
276 }
277
278 override func mouseDown(with event: NSEvent) {
279 self.origin = self.convert(event.locationInWindow, from: nil)
280 if let box {
281
282 if let button {
283 if button.contains(origin) {
284 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
285 return
286 }
287 }
288
289 if resizeBox!.contains(origin) && !preventResize {
290 self.origin = NSPoint(x: box.minX, y: box.maxY)
291 state = .resizing
292 return
293 }
294 if box.contains(origin) && !preventMove {
295 state = .moving
296 self.boxOrigin = NSPoint(x: box.origin.x, y: box.origin.y)
297 return
298 }
299 }
300
301 if preventResize || preventMove {
302 return
303 }
304
305 state = .drawing
306 }
307
308 override func mouseUp(with event: NSEvent) {
309 if state != .recording {
310 state = .idle
311 }
312 }
313
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)
318 default:
319 super.keyDown(with: event)
320 }
321 }
322
323 override func flagsChanged(with event: NSEvent) {
324 if state == .idle {
325 if event.modifierFlags.contains(.shift) {
326 startPassthrough()
327 } else {
328 stopPassthrough()
329 }
330 }
331 }
332
333 override func draw(_ dirtyRect: NSRect) {
334 if shouldPassthrough {
335 NSColor.clear.setFill()
336 } else {
337 NSColor(white: 1.0, alpha: 0.001).setFill()
338 }
339 dirtyRect.fill()
340
341 let dashLength: CGFloat = 5.0
342 let lineWidth = 0.5
343
344 // Uncomment below to debug button placement visually
345 // if let button {
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()
353 // buttonPath.fill()
354 // }
355
356 if state == .idle && box == nil {
357 let blackLine = NSBezierPath()
358 blackLine.lineWidth = lineWidth
359 blackLine.setLineDash([dashLength, dashLength], count: 2, phase: 0)
360
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)))
364
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))
368
369 NSColor.black.setStroke()
370 blackLine.stroke()
371
372 let whiteLine = NSBezierPath()
373 whiteLine.lineWidth = lineWidth
374 whiteLine.setLineDash([dashLength, dashLength], count: 2, phase: dashLength)
375
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)))
379
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))
383
384 NSColor.white.setStroke()
385 whiteLine.stroke()
386 }
387
388 if let box {
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()
398 blackBox.stroke()
399
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()
409 whiteBox.stroke()
410
411 if state == .recording {
412 return
413 }
414
415 if let resizeBox {
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()
423 clearBox.fill()
424 }
425
426 if state == .moving {
427 let string = "\(Int(box.minX)), \(Int(box.maxY))" as NSString
428 drawText(string, NSPoint(
429 x: box.minX,
430 y: box.maxY
431 ), true)
432 }
433
434 if state == .resizing {
435 let string = "\(Int(mouseLocation.x)), \(Int(mouseLocation.y))" as NSString
436 drawText(string, mouseLocation)
437 }
438
439 if box.contains(mouseLocation) && state != .resizing {
440 return;
441 }
442 }
443
444 // Draw text
445
446 let string = "\(Int(mouseLocation.x)), \(Int(mouseLocation.y))" as NSString
447 drawText(string, mouseLocation)
448 }
449
450 // MARK: - Utilities
451
452 private func drawText(_ text: NSString, _ location: NSPoint, _ isBottomRight: Bool = false) {
453
454 let textAttributes = [
455 NSAttributedString.Key.font: NSFont(name: "Hiragino Mincho ProN", size: 12) ?? NSFont.systemFont(ofSize: 12),
456 NSAttributedString.Key.foregroundColor: NSColor.white,
457 ]
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)
463
464 if (isBottomRight) {
465 rect = rect.offsetBy(dx: -size.width - 2 * offset.x, dy: 0)
466 textRect = textRect.offsetBy(dx: -size.width - 2 * offset.x, dy: 0)
467 }
468
469 NSColor.black.set()
470 rect.fill()
471
472 text.draw(in: textRect, withAttributes: textAttributes)
473 }
474
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()
483
484 if let window = self.window {
485 self.bounds = frame
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()
490 }
491 }
492 }
493 }
494 }