aboutsummaryrefslogtreecommitdiff
path: root/Captura/Presentation/Windows/RecordingWindow.swift
blob: 71e3a5577605ffd75735886b562b9f1518315ac9 (plain)
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
/*
 Copyright (C) 2024 Rubén Beltrán del Río

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program. If not, see https://captura.tranquil.systems.
 */
import Cocoa
import Combine

class RecordingWindow: NSWindow {

  var pixelDensity: CGFloat {
    self.screen?.backingScaleFactor ?? 1.0
  }

  var recordingContentView: RecordingContentView {
    self.contentView as! RecordingContentView
  }

  init(_ configuration: CaptureSessionConfiguration, _ button: NSRect?) {

    let boundingBox = NSScreen.screenWithMouse?.frame ?? NSZeroRect

    super.init(
      contentRect: boundingBox,
      styleMask: [.borderless],
      backing: .buffered,
      defer: false)

    self.isReleasedWhenClosed = false
    self.collectionBehavior = [.canJoinAllSpaces]
    self.isMovableByWindowBackground = false
    self.isMovable = false
    self.canHide = false
    self.titlebarAppearsTransparent = true
    self.setFrame(boundingBox, display: true)
    self.titleVisibility = .hidden
    let recordingView = RecordingContentView(
      configuration, frame: boundingBox, button: button ?? NSZeroRect)
    recordingView.frame = boundingBox
    self.contentView = recordingView
    self.backgroundColor = NSColor(white: 1.0, alpha: 0.001)
    // uncomment below to debug window placement visually
    // self.backgroundColor = NSColor(red: 1.0, green: 0.0, blue: 1.0, alpha: 0.5)
    self.level = .screenSaver
    self.isOpaque = false
    self.hasShadow = false
  }

  // 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 {

  init(_ configuration: CaptureSessionConfiguration, frame: NSRect, button: NSRect) {
    self.buttonSize = button.size
    var buttonOffset = NSPoint()
    for screen in NSScreen.screens {
      if screen.frame.intersects(button) {
        let relativeY = screen.frame.height - (button.minY - screen.frame.minY)
        let relativeX = screen.frame.width - (button.minX - screen.frame.minX)
        buttonOffset = NSPoint(x: relativeX, y: relativeY)
      }
    }
    self.buttonOffset = buttonOffset
    super.init(frame: frame)
    preventResize = configuration.preventResize
    preventMove = configuration.preventMove
    autoStart = configuration.autoStart

    self.bounds = frame
    self.button = NSRect(
      x: frame.maxX - buttonOffset.x, y: frame.maxY - buttonOffset.y, width: buttonSize.width,
      height: buttonSize.height)

    if configuration.x != nil || configuration.y != nil || configuration.width != nil
      || configuration.height != nil
    {
      box = NSRect(
        x: configuration.x ?? Int(frame.width / 2.0),
        y: configuration.y ?? Int(frame.height / 2.0),
        width: configuration.width ?? 400,
        height: configuration.height ?? 400
      )
    }

    if autoStart {
      DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
        NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
      }
    }
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  private let buttonSize: NSSize
  private let buttonOffset: NSPoint
  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 preventResize = false
  private var preventMove = false
  private var autoStart = false

  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 mouseExited(with event: NSEvent) {
    if state == .idle && box == nil {
      self.moveWindow()
    }
  }

  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) && !preventResize {
        self.origin = NSPoint(x: box.minX, y: box.maxY)
        state = .resizing
        return
      }
      if box.contains(origin) && !preventMove {
        state = .moving
        self.boxOrigin = NSPoint(x: box.origin.x, y: box.origin.y)
        return
      }
    }

    if preventResize || preventMove {
      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

    // Uncomment below to debug button placement visually
    //    if let button {
    //      let buttonPath = NSBezierPath()
    //      buttonPath.move(to: NSPoint(x: button.minX, y: button.minY))
    //      buttonPath.line(to: NSPoint(x: button.maxX, y: button.minY))
    //      buttonPath.line(to: NSPoint(x: button.maxX, y: button.maxY))
    //      buttonPath.line(to: NSPoint(x: button.minX, y: button.maxY))
    //      buttonPath.line(to: NSPoint(x: button.minX, y: button.minY))
    //      NSColor(red: 1, green: 0, blue: 1, alpha: 1).setFill()
    //      buttonPath.fill()
    //    }

    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)
  }

  private func moveWindow() {
    let screen = NSScreen.screenWithMouse
    if let currentScreen = self.window?.screen {
      if currentScreen != screen {
        let frame = screen?.frame ?? NSZeroRect
        self.frame = CGRect(origin: NSZeroPoint, size: frame.size)
        self.bounds = CGRect(origin: NSZeroPoint, size: frame.size)
        self.updateTrackingAreas()

        if let window = self.window {
          self.bounds = frame
          self.button = NSRect(
            x: frame.maxX - buttonOffset.x, y: frame.maxY - buttonOffset.y, width: buttonSize.width,
            height: buttonSize.height)
          window.setFrame(frame, display: true, animate: false)
          window.makeKeyAndOrderFront(nil)
          window.orderFrontRegardless()
        }
      }
    }
  }
}