]> git.r.bdr.sh - rbdr/captura/blob - Captura/Presentation/Windows/RecordingWindow.swift
b5c44139cb6a26cac5b0d86c720379764a4c85af
[rbdr/captura] / Captura / Presentation / Windows / RecordingWindow.swift
1 import Cocoa
2 import Combine
3
4 class RecordingWindow: NSWindow {
5
6 var pixelDensity: CGFloat {
7 self.screen?.backingScaleFactor ?? 1.0
8 }
9
10 var recordingContentView: RecordingContentView {
11 self.contentView as! RecordingContentView
12 }
13
14 init(_ configuration: CaptureSessionConfiguration, _ button: NSRect?) {
15
16 let boundingBox = NSScreen.screenWithMouse?.frame ?? NSZeroRect
17
18 super.init(
19 contentRect: boundingBox,
20 styleMask: [.borderless],
21 backing: .buffered,
22 defer: false)
23
24
25 self.isReleasedWhenClosed = false
26 self.collectionBehavior = [.canJoinAllSpaces]
27 self.isMovableByWindowBackground = false
28 self.isMovable = false
29 self.canHide = false
30 self.titlebarAppearsTransparent = true
31 self.setFrame(boundingBox, display: true)
32 self.titleVisibility = .hidden
33 let recordingView = RecordingContentView(configuration, frame: boundingBox, button: button ?? NSZeroRect)
34 recordingView.frame = boundingBox
35 self.contentView = recordingView
36 //self.backgroundColor = NSColor(white: 1.0, alpha: 0.001)
37 self.backgroundColor = NSColor(red: 1.0, green: 0.0, blue: 1.0, alpha: 0.5)
38 self.level = .screenSaver
39 self.isOpaque = false
40 self.hasShadow = false
41
42 print("AAAAH INIT CHANGE")
43 print("AAAAH FRAME X: \(recordingView.frame.minX) \(recordingView.frame.maxX) // Y: \(recordingView.frame.minY) \(recordingView.frame.maxY)")
44 print("AAAAH BOUNDS X: \(recordingView.bounds.minX) \(recordingView.bounds.maxX) // Y: \(recordingView.bounds.minY) \(recordingView.bounds.maxY)")
45 print("AAAAH WIN F X: \(self.frame.minX) \(self.frame.maxX) // Y: \(self.frame.minY) \(self.frame.maxY)")
46 }
47
48 // MARK: - Window Behavior Overrides
49
50 override func resetCursorRects() {
51 super.resetCursorRects()
52 let cursor = NSCursor.crosshair
53 self.contentView?.addCursorRect(self.contentView!.bounds, cursor: cursor)
54 }
55
56 override var canBecomeKey: Bool {
57 return true
58 }
59
60 override var canBecomeMain: Bool {
61 return true
62 }
63
64 override func resignMain() {
65 super.resignMain()
66 if (self.contentView as? RecordingContentView)?.state != .recording {
67 self.ignoresMouseEvents = false
68 }
69 }
70
71 override func becomeMain() {
72 super.becomeMain()
73 if (self.contentView as? RecordingContentView)?.state != .recording {
74 (self.contentView as? RecordingContentView)?.state = .idle
75 }
76 }
77 }
78
79 enum RecordingWindowState {
80 case passthrough, idle, drawing, moving, resizing, recording;
81 }
82
83 class RecordingContentView: NSView {
84
85 init(_ configuration: CaptureSessionConfiguration, frame: NSRect, button: NSRect) {
86 super.init(frame: frame)
87 preventResize = configuration.preventResize
88 preventMove = configuration.preventMove
89 autoStart = configuration.autoStart
90 self.button = button
91
92 for screen in NSScreen.screens {
93 print(screen.frame)
94 // BEFORE YOU WENT TO BED:
95 // You were checking which screen contains the button, so you can calculate the offset which should give you
96 // the location of the button, which you can then use to draw the button at the same offset whenever you need
97 // to change screen! This would keep the behavior of pressing the record button.
98 // If this does work, remember to then test it with a Hi DPI display, because we might need to adjust for pixel
99 // density.
100 // Finally, if it does work, make sure the alternate monitor still responds, by adjusting the behavior of the
101 // real button
102 if screen.frame.intersects(button) {
103 print("CONTAINS! ->")
104 let relativeX = screen.frame.width - button.maxX
105 let relativeY = screen.frame.height - button.maxY
106 print("The rect is at (\(relativeX), \(relativeY)) relative to the top right of the screen frame.")
107 } else {
108 print("NO CONTAINS ->")
109 }
110 print(button)
111 }
112
113 if configuration.x != nil || configuration.y != nil || configuration.width != nil || configuration.height != nil {
114 box = NSRect(
115 x: configuration.x ?? Int(frame.width / 2.0),
116 y: configuration.y ?? Int(frame.height / 2.0),
117 width: configuration.width ?? 400,
118 height: configuration.height ?? 400
119 )
120 }
121
122 if autoStart {
123 DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
124 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
125 }
126 }
127 }
128
129 required init?(coder: NSCoder) {
130 fatalError("init(coder:) has not been implemented")
131 }
132
133 private var buttons: [NSRect] = []
134 public var button: NSRect? = nil
135 @Published public var box: NSRect? = nil
136 public var state: RecordingWindowState = .idle
137 private var mouseLocation: NSPoint = NSPoint()
138 private var origin: NSPoint = NSPoint()
139 private var boxOrigin: NSPoint = NSPoint()
140 private var preventResize = false
141 private var preventMove = false
142 private var autoStart = false
143
144 private var resizeBox: NSRect? {
145 if let box {
146 return NSRect(x: box.maxX - 5, y: box.minY - 5, width: 10, height: 10)
147 }
148 return nil
149 }
150
151 private var shouldPassthrough: Bool {
152 state == .recording || state == .passthrough
153 }
154
155 // MARK: - State changing API
156
157 public func startRecording() {
158 state = .recording
159 window?.ignoresMouseEvents = true
160 }
161
162 public func stopRecording() {
163
164 }
165
166 public func reset() {
167 state = .idle
168 window?.ignoresMouseEvents = false
169 }
170
171 public func startPassthrough() {
172 state = .passthrough
173 window?.ignoresMouseEvents = true
174 }
175
176 public func stopPassthrough() {
177 state = .idle
178 window?.ignoresMouseEvents = false
179 }
180
181 // MARK: - View Behavior Overrides
182
183 override func updateTrackingAreas() {
184 super.updateTrackingAreas()
185
186 for trackingArea in self.trackingAreas {
187 self.removeTrackingArea(trackingArea)
188 }
189
190 let options: NSTrackingArea.Options = [.mouseEnteredAndExited, .activeInKeyWindow, .cursorUpdate, .mouseMoved]
191 let trackingArea = NSTrackingArea(rect: self.bounds, options: options, owner: self, userInfo: nil)
192 self.addTrackingArea(trackingArea)
193 }
194
195 override func mouseExited(with event: NSEvent) {
196 if state == .idle && box == nil {
197 self.moveWindow()
198 }
199 }
200
201 override func mouseMoved(with event: NSEvent) {
202
203 self.mouseLocation = self.convert(event.locationInWindow, from: nil)
204
205 if shouldPassthrough {
206 NSCursor.arrow.set()
207 } else {
208 if let box {
209 if resizeBox!.contains(mouseLocation) {
210 NSCursor.arrow.set()
211 } else {
212 if box.contains(mouseLocation) {
213 NSCursor.openHand.set()
214 } else {
215 NSCursor.crosshair.set()
216 }
217 }
218 if let button {
219 if button.contains(mouseLocation) {
220 NSCursor.arrow.set()
221 }
222 }
223 } else {
224 NSCursor.crosshair.set()
225 }
226 }
227
228 self.setNeedsDisplay(self.bounds)
229 }
230
231 override func mouseDragged(with event: NSEvent) {
232 self.mouseLocation = self.convert(event.locationInWindow, from: nil)
233 if state == .drawing {
234 box = NSRect(
235 x: round(min(origin.x, mouseLocation.x)),
236 y: round(min(origin.y, mouseLocation.y)),
237 width: round(abs(mouseLocation.x - origin.x)),
238 height: round(abs(mouseLocation.y - origin.y))
239 )
240 }
241
242 if box != nil {
243 if state == .moving {
244 NSCursor.closedHand.set()
245 box!.origin = NSPoint(
246 x: self.boxOrigin.x - self.origin.x + self.mouseLocation.x,
247 y: self.boxOrigin.y - self.origin.y + self.mouseLocation.y)
248 }
249
250 if state == .resizing {
251 box = NSRect(
252 x: round(min(origin.x, mouseLocation.x)),
253 y: round(min(origin.y, mouseLocation.y)),
254 width: round(abs(mouseLocation.x - origin.x)),
255 height: round(abs(mouseLocation.y - origin.y))
256 )
257 }
258 }
259 self.setNeedsDisplay(self.bounds)
260 }
261
262 override func cursorUpdate(with event: NSEvent) {
263 NSCursor.crosshair.set()
264 }
265
266 override func hitTest(_ point: NSPoint) -> NSView? {
267 return shouldPassthrough ? nil : self
268 }
269
270 override var acceptsFirstResponder: Bool {
271 return true
272 }
273
274 override func mouseDown(with event: NSEvent) {
275 self.origin = self.convert(event.locationInWindow, from: nil)
276 if let box {
277
278 if let button {
279 if button.contains(origin) {
280 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
281 return
282 }
283 }
284
285 if resizeBox!.contains(origin) && !preventResize {
286 self.origin = NSPoint(x: box.minX, y: box.maxY)
287 state = .resizing
288 return
289 }
290 if box.contains(origin) && !preventMove {
291 state = .moving
292 self.boxOrigin = NSPoint(x: box.origin.x, y: box.origin.y)
293 return
294 }
295 }
296
297 if preventResize || preventMove {
298 return
299 }
300
301 state = .drawing
302 }
303
304 override func mouseUp(with event: NSEvent) {
305 if state != .recording {
306 state = .idle
307 }
308 }
309
310 override func keyDown(with event: NSEvent) {
311 switch event.keyCode {
312 case 53: // Escape key
313 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
314 default:
315 super.keyDown(with: event)
316 }
317 }
318
319 override func flagsChanged(with event: NSEvent) {
320 if state == .idle {
321 if event.modifierFlags.contains(.shift) {
322 startPassthrough()
323 } else {
324 stopPassthrough()
325 }
326 }
327 }
328
329 override func draw(_ dirtyRect: NSRect) {
330 if shouldPassthrough {
331 NSColor.clear.setFill()
332 } else {
333 NSColor(white: 1.0, alpha: 0.001).setFill()
334 }
335 dirtyRect.fill()
336
337 let dashLength: CGFloat = 5.0
338 let lineWidth = 0.5
339
340 if let button {
341 let buttonPath = NSBezierPath()
342 buttonPath.move(to: NSPoint(x: button.minX, y: button.minY))
343 buttonPath.line(to: NSPoint(x: button.maxX, y: button.minY))
344 buttonPath.line(to: NSPoint(x: button.maxX, y: button.maxY))
345 buttonPath.line(to: NSPoint(x: button.minX, y: button.maxY))
346 buttonPath.line(to: NSPoint(x: button.minX, y: button.minY))
347 NSColor(red: 1, green: 0, blue: 1, alpha: 1).setFill()
348 buttonPath.fill()
349 }
350
351 if state == .idle && box == nil {
352 let blackLine = NSBezierPath()
353 blackLine.lineWidth = lineWidth
354 blackLine.setLineDash([dashLength, dashLength], count: 2, phase: 0)
355
356 // Vertical line (Black)
357 blackLine.move(to: NSPoint(x: self.mouseLocation.x, y: NSMinY(self.bounds)))
358 blackLine.line(to: NSPoint(x: self.mouseLocation.x, y: NSMaxY(self.bounds)))
359
360 // Horizontal line (Black)
361 blackLine.move(to: NSPoint(x: NSMinX(self.bounds), y: self.mouseLocation.y))
362 blackLine.line(to: NSPoint(x: NSMaxX(self.bounds), y: self.mouseLocation.y))
363
364 NSColor.black.setStroke()
365 blackLine.stroke()
366
367 let whiteLine = NSBezierPath()
368 whiteLine.lineWidth = lineWidth
369 whiteLine.setLineDash([dashLength, dashLength], count: 2, phase: dashLength)
370
371 // Vertical line (White)
372 whiteLine.move(to: NSPoint(x: self.mouseLocation.x, y: NSMinY(self.bounds)))
373 whiteLine.line(to: NSPoint(x: self.mouseLocation.x, y: NSMaxY(self.bounds)))
374
375 // Horizontal line (White)
376 whiteLine.move(to: NSPoint(x: NSMinX(self.bounds), y: self.mouseLocation.y))
377 whiteLine.line(to: NSPoint(x: NSMaxX(self.bounds), y: self.mouseLocation.y))
378
379 NSColor.white.setStroke()
380 whiteLine.stroke()
381 }
382
383 if let box {
384 let blackBox = NSBezierPath()
385 blackBox.lineWidth = lineWidth
386 blackBox.setLineDash([dashLength, dashLength], count: 2, phase: 0)
387 blackBox.move(to: NSPoint(x: box.minX, y: box.minY))
388 blackBox.line(to: NSPoint(x: box.maxX, y: box.minY))
389 blackBox.line(to: NSPoint(x: box.maxX, y: box.maxY))
390 blackBox.line(to: NSPoint(x: box.minX, y: box.maxY))
391 blackBox.line(to: NSPoint(x: box.minX, y: box.minY))
392 NSColor.black.setStroke()
393 blackBox.stroke()
394
395 let whiteBox = NSBezierPath()
396 whiteBox.lineWidth = lineWidth
397 whiteBox.setLineDash([dashLength, dashLength], count: 2, phase: dashLength)
398 whiteBox.move(to: NSPoint(x: box.minX, y: box.minY))
399 whiteBox.line(to: NSPoint(x: box.maxX, y: box.minY))
400 whiteBox.line(to: NSPoint(x: box.maxX, y: box.maxY))
401 whiteBox.line(to: NSPoint(x: box.minX, y: box.maxY))
402 whiteBox.line(to: NSPoint(x: box.minX, y: box.minY))
403 NSColor.white.setStroke()
404 whiteBox.stroke()
405
406 if state == .recording {
407 return
408 }
409
410 if let resizeBox {
411 let clearBox = NSBezierPath()
412 clearBox.move(to: NSPoint(x: resizeBox.minX, y: resizeBox.minY))
413 clearBox.line(to: NSPoint(x: resizeBox.maxX, y: resizeBox.minY))
414 clearBox.line(to: NSPoint(x: resizeBox.maxX, y: resizeBox.maxY))
415 clearBox.line(to: NSPoint(x: resizeBox.minX, y: resizeBox.maxY))
416 clearBox.line(to: NSPoint(x: resizeBox.minX, y: resizeBox.minY))
417 NSColor(white: 0, alpha: 0.2).setFill()
418 clearBox.fill()
419 }
420
421 if state == .moving {
422 let string = "\(Int(box.minX)), \(Int(box.maxY))" as NSString
423 drawText(string, NSPoint(
424 x: box.minX,
425 y: box.maxY
426 ), true)
427 }
428
429 if state == .resizing {
430 let string = "\(Int(mouseLocation.x)), \(Int(mouseLocation.y))" as NSString
431 drawText(string, mouseLocation)
432 }
433
434 if box.contains(mouseLocation) && state != .resizing {
435 return;
436 }
437 }
438
439 // Draw text
440
441 let string = "\(Int(mouseLocation.x)), \(Int(mouseLocation.y))" as NSString
442 drawText(string, mouseLocation)
443 }
444
445 // MARK: - Utilities
446
447 private func drawText(_ text: NSString, _ location: NSPoint, _ isBottomRight: Bool = false) {
448
449 let textAttributes = [
450 NSAttributedString.Key.font: NSFont(name: "Hiragino Mincho ProN", size: 12) ?? NSFont.systemFont(ofSize: 12),
451 NSAttributedString.Key.foregroundColor: NSColor.white,
452 ]
453 let offset = NSPoint(x: 10, y: 10)
454 let padding = NSPoint(x: 5, y: 2)
455 let size = text.size(withAttributes: textAttributes)
456 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)
457 var textRect = NSRect(x: location.x + offset.x + padding.x, y: location.y + offset.y + padding.y, width: size.width, height: size.height)
458
459 if (isBottomRight) {
460 rect = rect.offsetBy(dx: -size.width - 2 * offset.x, dy: 0)
461 textRect = textRect.offsetBy(dx: -size.width - 2 * offset.x, dy: 0)
462 }
463
464 NSColor.black.set()
465 rect.fill()
466
467 text.draw(in: textRect, withAttributes: textAttributes)
468 }
469
470 private func moveWindow() {
471 print("AAAAH BEFORE WE CHANGE")
472 print("AAAAH FRAME X: \(self.frame.minX) \(self.frame.maxX) // Y: \(self.frame.minY) \(self.frame.maxY)")
473 print("AAAAH BOUNDS X: \(self.bounds.minX) \(self.bounds.maxX) // Y: \(self.bounds.minY) \(self.bounds.maxY)")
474 print("AAAAH WIN F X: \(self.window?.frame.minX) \(self.window?.frame.maxX) // Y: \(self.window?.frame.minY) \(self.window?.frame.maxY)")
475 let screen = NSScreen.screenWithMouse
476 if let currentScreen = self.window?.screen {
477 if currentScreen != screen {
478 let frame = screen?.frame ?? NSZeroRect
479 self.frame = CGRect(origin: NSZeroPoint, size: frame.size)
480 self.bounds = CGRect(origin: NSZeroPoint, size: frame.size)
481 self.updateTrackingAreas()
482
483 if let window = self.window {
484 self.bounds = frame
485 window.setFrame(frame, display: true, animate: false)
486 window.makeKeyAndOrderFront(nil)
487 window.orderFrontRegardless()
488 print("AAAAH AFTER CHANGE")
489 print("AAAAH FRAME X: \(self.frame.minX) \(self.frame.maxX) // Y: \(self.frame.minY) \(self.frame.maxY)")
490 print("AAAAH BOUNDS X: \(self.bounds.minX) \(self.bounds.maxX) // Y: \(self.bounds.minY) \(self.bounds.maxY)")
491 print("AAAAH WIN F X: \(self.window?.frame.minX) \(self.window?.frame.maxX) // Y: \(self.window?.frame.minY) \(self.window?.frame.maxY)")
492 }
493 }
494 }
495 }
496 }