-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathMainWindowController.swift
2890 lines (2498 loc) · 103 KB
/
MainWindowController.swift
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// MainWindowController.swift
// iina
//
// Created by lhc on 8/7/16.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
import Mustache
import WebKit
fileprivate let isMacOS11: Bool = {
var res = false
if #available(macOS 11.0, *) {
if #available(macOS 12.0, *) {} else {
res = true
}
}
return res
}()
fileprivate let TitleBarHeightNormal: CGFloat = {
if #available(macOS 10.16, *) {
return 28
} else {
return 22
}
}()
fileprivate let TitleBarHeightWithOSC: CGFloat = TitleBarHeightNormal + 24 + 10
fileprivate let TitleBarHeightWithOSCInFullScreen: CGFloat = 24 + 10
fileprivate let OSCTopMainViewMarginTop: CGFloat = 26
fileprivate let OSCTopMainViewMarginTopInFullScreen: CGFloat = 6
fileprivate let SettingsWidth: CGFloat = 360
fileprivate let PlaylistMinWidth: CGFloat = 240
fileprivate let PlaylistMaxWidth: CGFloat = 400
fileprivate let InteractiveModeBottomViewHeight: CGFloat = 60
fileprivate let UIAnimationDuration = 0.25
fileprivate let OSDAnimationDuration = 0.5
fileprivate let SideBarAnimationDuration = 0.2
fileprivate let CropAnimationDuration = 0.2
fileprivate extension NSStackView.VisibilityPriority {
static let detachEarly = NSStackView.VisibilityPriority(rawValue: 850)
static let detachEarlier = NSStackView.VisibilityPriority(rawValue: 800)
static let detachEarliest = NSStackView.VisibilityPriority(rawValue: 750)
}
class MainWindowController: PlayerWindowController {
override var windowNibName: NSNib.Name {
return NSNib.Name("MainWindowController")
}
@objc let monospacedFont: NSFont = {
let fontSize = NSFont.systemFontSize(for: .small)
return NSFont.monospacedDigitSystemFont(ofSize: fontSize, weight: .regular)
}()
// MARK: - Constants
/** Minimum window size. */
let minSize = NSMakeSize(285, 120)
/** For Force Touch. */
let minimumPressDuration: TimeInterval = 0.5
// MARK: - Objects, Views
override var videoView: VideoView {
return _videoView
}
lazy private var _videoView: VideoView = VideoView(frame: window!.contentView!.bounds, player: player)
/** The quick setting sidebar (video, audio, subtitles). */
lazy var quickSettingView: QuickSettingViewController = {
let quickSettingView = QuickSettingViewController()
quickSettingView.mainWindow = self
return quickSettingView
}()
/** The playlist and chapter sidebar. */
lazy var playlistView: PlaylistViewController = {
let playlistView = PlaylistViewController()
playlistView.mainWindow = self
return playlistView
}()
/** The control view for interactive mode. */
var cropSettingsView: CropBoxViewController?
private lazy var magnificationGestureRecognizer: NSMagnificationGestureRecognizer = {
return NSMagnificationGestureRecognizer(target: self, action: #selector(MainWindowController.handleMagnifyGesture(recognizer:)))
}()
/** For auto hiding UI after a timeout. */
var hideControlTimer: Timer?
var hideOSDTimer: Timer?
/** For blacking out other screens. */
var screens: [NSScreen] = []
var cachedScreenCount = 0
var blackWindows: [NSWindow] = []
lazy var rotation: Int = {
return player.mpv.getInt(MPVProperty.videoParamsRotate)
}()
// MARK: - Status
override var isOntop: Bool {
didSet {
updateOnTopIcon()
}
}
/** For mpv's `geometry` option. We cache the parsed structure
so never need to parse it every time. */
var cachedGeometry: GeometryDef?
var mousePosRelatedToWindow: CGPoint?
var isDragging: Bool = false
var isResizingSidebar: Bool = false
var pipStatus = PIPStatus.notInPIP
var isInInteractiveMode: Bool = false
var isVideoLoaded: Bool = false
var shouldApplyInitialWindowSize = true
var isWindowHidden: Bool = false
var isWindowMiniaturizedDueToPip = false
// might use another obj to handle slider?
var isMouseInWindow: Bool = false
var isMouseInSlider: Bool = false
var isFastforwarding: Bool = false
var isPausedDueToInactive: Bool = false
var isPausedDueToMiniaturization: Bool = false
var isPausedPriorToInteractiveMode: Bool = false
var lastMagnification: CGFloat = 0.0
/** Views that will show/hide when cursor moving in/out the window. */
var fadeableViews: [NSView] = []
// Left and right arrow buttons
/** The maximum pressure recorded when clicking on the arrow buttons. */
var maxPressure: Int32 = 0
/** The value of speedValueIndex before Force Touch. */
var oldIndex: Int = AppData.availableSpeedValues.count / 2
/** When the arrow buttons were last clicked. */
var lastClick = Date()
/** The index of current speed in speed value array. */
var speedValueIndex: Int = AppData.availableSpeedValues.count / 2 {
didSet {
if speedValueIndex < 0 || speedValueIndex >= AppData.availableSpeedValues.count {
speedValueIndex = AppData.availableSpeedValues.count / 2
}
}
}
/** For force touch action */
var isCurrentPressInSecondStage = false
/** Whether current osd needs user interaction to be dismissed */
var isShowingPersistentOSD = false
var osdContext: Any?
// MARK: - Enums
// Window state
enum FullScreenState: Equatable {
case windowed
case animating(toFullscreen: Bool, legacy: Bool, priorWindowedFrame: NSRect)
case fullscreen(legacy: Bool, priorWindowedFrame: NSRect)
var isFullscreen: Bool {
switch self {
case .fullscreen: return true
case let .animating(toFullscreen: toFullScreen, legacy: _, priorWindowedFrame: _): return toFullScreen
default: return false
}
}
var priorWindowedFrame: NSRect? {
get {
switch self {
case .windowed: return nil
case .animating(_, _, let p): return p
case .fullscreen(_, let p): return p
}
}
set {
guard let newRect = newValue else { return }
switch self {
case .windowed: return
case let .animating(toFullscreen, legacy, _):
self = .animating(toFullscreen: toFullscreen, legacy: legacy, priorWindowedFrame: newRect)
case let .fullscreen(legacy, _):
self = .fullscreen(legacy: legacy, priorWindowedFrame: newRect)
}
}
}
mutating func startAnimatingToFullScreen(legacy: Bool, priorWindowedFrame: NSRect) {
self = .animating(toFullscreen: true, legacy: legacy, priorWindowedFrame: priorWindowedFrame)
}
mutating func startAnimatingToWindow() {
guard case .fullscreen(let legacy, let priorWindowedFrame) = self else { return }
self = .animating(toFullscreen: false, legacy: legacy, priorWindowedFrame: priorWindowedFrame)
}
mutating func finishAnimating() {
switch self {
case .windowed, .fullscreen: assertionFailure("something went wrong with the state of the world. One must be .animating to finishAnimating. Not \(self)")
case .animating(let toFullScreen, let legacy, let frame):
if toFullScreen {
self = .fullscreen(legacy: legacy, priorWindowedFrame: frame)
} else{
self = .windowed
}
}
}
}
var fsState: FullScreenState = .windowed {
didSet {
switch fsState {
case .fullscreen: player.mpv.setFlag(MPVOption.Window.fullscreen, true)
case .animating: break
case .windowed: player.mpv.setFlag(MPVOption.Window.fullscreen, false)
}
}
}
// Animation state
/// Animation state of he hide/show part
enum UIAnimationState {
case shown, hidden, willShow, willHide
}
var animationState: UIAnimationState = .shown
var osdAnimationState: UIAnimationState = .hidden
var sidebarAnimationState: UIAnimationState = .hidden
// Sidebar
/** Type of the view embedded in sidebar. */
enum SideBarViewType {
case hidden // indicating that sidebar is hidden. Should only be used by `sideBarStatus`
case settings
case playlist
func width() -> CGFloat {
switch self {
case .settings:
return SettingsWidth
case .playlist:
return CGFloat(Preference.integer(for: .playlistWidth)).clamped(to: PlaylistMinWidth...PlaylistMaxWidth)
default:
Logger.fatal("SideBarViewType.width shouldn't be called here")
}
}
}
var sideBarStatus: SideBarViewType = .hidden
enum PIPStatus {
case notInPIP
case inPIP
case intermediate
}
enum InteractiveMode {
case crop
case freeSelecting
func viewController() -> CropBoxViewController {
var vc: CropBoxViewController
switch self {
case .crop:
vc = CropSettingsViewController()
case .freeSelecting:
vc = FreeSelectingViewController()
}
return vc
}
}
// MARK: - Observed user defaults
private var oscIsInitialized = false
// Cached user default values
private lazy var oscPosition: Preference.OSCPosition = Preference.enum(for: .oscPosition)
private lazy var arrowBtnFunction: Preference.ArrowButtonAction = Preference.enum(for: .arrowButtonAction)
private lazy var pinchAction: Preference.PinchAction = Preference.enum(for: .pinchAction)
lazy var displayTimeAndBatteryInFullScreen: Bool = Preference.bool(for: .displayTimeAndBatteryInFullScreen)
private let localObservedPrefKeys: [Preference.Key] = [
.oscPosition,
.showChapterPos,
.arrowButtonAction,
.pinchAction,
.blackOutMonitor,
.useLegacyFullScreen,
.displayTimeAndBatteryInFullScreen,
.controlBarToolbarButtons,
.alwaysShowOnTopIcon
]
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath, let change = change else { return }
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
switch keyPath {
case PK.oscPosition.rawValue:
if let newValue = change[.newKey] as? Int {
setupOnScreenController(withPosition: Preference.OSCPosition(rawValue: newValue) ?? .floating)
}
case PK.showChapterPos.rawValue:
if let newValue = change[.newKey] as? Bool {
(playSlider.cell as! PlaySliderCell).drawChapters = newValue
}
case PK.verticalScrollAction.rawValue:
if let newValue = change[.newKey] as? Int {
verticalScrollAction = Preference.ScrollAction(rawValue: newValue)!
}
case PK.horizontalScrollAction.rawValue:
if let newValue = change[.newKey] as? Int {
horizontalScrollAction = Preference.ScrollAction(rawValue: newValue)!
}
case PK.arrowButtonAction.rawValue:
if let newValue = change[.newKey] as? Int {
arrowBtnFunction = Preference.ArrowButtonAction(rawValue: newValue)!
updateArrowButtonImage()
}
case PK.pinchAction.rawValue:
if let newValue = change[.newKey] as? Int {
pinchAction = Preference.PinchAction(rawValue: newValue)!
}
case PK.blackOutMonitor.rawValue:
if let newValue = change[.newKey] as? Bool {
if fsState.isFullscreen {
newValue ? blackOutOtherMonitors() : removeBlackWindow()
}
}
case PK.useLegacyFullScreen.rawValue:
resetCollectionBehavior()
case PK.displayTimeAndBatteryInFullScreen.rawValue:
if let newValue = change[.newKey] as? Bool {
displayTimeAndBatteryInFullScreen = newValue
if !newValue {
additionalInfoView.isHidden = true
}
}
case PK.controlBarToolbarButtons.rawValue:
if let newValue = change[.newKey] as? [Int] {
setupOSCToolbarButtons(newValue.compactMap(Preference.ToolBarButton.init(rawValue:)))
}
case PK.alwaysShowOnTopIcon.rawValue:
updateOnTopIcon()
default:
return
}
}
// MARK: - Outlets
var standardWindowButtons: [NSButton] {
get {
return ([.closeButton, .miniaturizeButton, .zoomButton, .documentIconButton] as [NSWindow.ButtonType]).compactMap {
window?.standardWindowButton($0)
}
}
}
/** Get the `NSTextField` of widow's title. */
var titleTextField: NSTextField? {
get {
return window?.standardWindowButton(.closeButton)?.superview?.subviews.compactMap({ $0 as? NSTextField }).first
}
}
var titlebarAccesoryViewController: NSTitlebarAccessoryViewController!
@IBOutlet var titlebarAccessoryView: NSView!
/** Current OSC view. */
var currentControlBar: NSView?
@IBOutlet weak var sideBarRightConstraint: NSLayoutConstraint!
@IBOutlet weak var sideBarWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomBarBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var titleBarHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var oscTopMainViewTopConstraint: NSLayoutConstraint!
@IBOutlet weak var fragControlViewMiddleButtons1Constraint: NSLayoutConstraint!
@IBOutlet weak var fragControlViewMiddleButtons2Constraint: NSLayoutConstraint!
@IBOutlet weak var titleBarView: NSVisualEffectView!
@IBOutlet weak var titleBarBottomBorder: NSBox!
@IBOutlet weak var titlebarOnTopButton: NSButton!
@IBOutlet weak var controlBarFloating: ControlBarView!
@IBOutlet weak var controlBarBottom: NSVisualEffectView!
@IBOutlet weak var timePreviewWhenSeek: NSTextField!
@IBOutlet weak var leftArrowButton: NSButton!
@IBOutlet weak var rightArrowButton: NSButton!
@IBOutlet weak var settingsButton: NSButton!
@IBOutlet weak var playlistButton: NSButton!
@IBOutlet weak var sideBarView: NSVisualEffectView!
@IBOutlet weak var bottomView: NSView!
@IBOutlet weak var bufferIndicatorView: NSVisualEffectView!
@IBOutlet weak var bufferProgressLabel: NSTextField!
@IBOutlet weak var bufferSpin: NSProgressIndicator!
@IBOutlet weak var bufferDetailLabel: NSTextField!
@IBOutlet var thumbnailPeekView: ThumbnailPeekView!
@IBOutlet weak var additionalInfoView: NSVisualEffectView!
@IBOutlet weak var additionalInfoLabel: NSTextField!
@IBOutlet weak var additionalInfoStackView: NSStackView!
@IBOutlet weak var additionalInfoTitle: NSTextField!
@IBOutlet weak var additionalInfoBatteryView: NSView!
@IBOutlet weak var additionalInfoBattery: NSTextField!
@IBOutlet weak var oscFloatingTopView: NSStackView!
@IBOutlet weak var oscFloatingBottomView: NSView!
@IBOutlet weak var oscBottomMainView: NSStackView!
@IBOutlet weak var oscTopMainView: NSStackView!
@IBOutlet var fragControlView: NSStackView!
@IBOutlet var fragToolbarView: NSStackView!
@IBOutlet var fragVolumeView: NSView!
@IBOutlet var fragSliderView: NSView!
@IBOutlet var fragControlViewMiddleView: NSView!
@IBOutlet var fragControlViewLeftView: NSView!
@IBOutlet var fragControlViewRightView: NSView!
@IBOutlet weak var leftArrowLabel: NSTextField!
@IBOutlet weak var rightArrowLabel: NSTextField!
@IBOutlet weak var osdVisualEffectView: NSVisualEffectView!
@IBOutlet weak var osdStackView: NSStackView!
@IBOutlet weak var osdLabel: NSTextField!
@IBOutlet weak var osdAccessoryText: NSTextField!
@IBOutlet weak var osdAccessoryProgress: NSProgressIndicator!
@IBOutlet weak var pipOverlayView: NSVisualEffectView!
lazy var pluginOverlayViewContainer: NSView! = {
guard let window = window, let cv = window.contentView else { return nil }
let view = NSView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
cv.addSubview(view, positioned: .below, relativeTo: bufferIndicatorView)
Utility.quickConstraints(["H:|[v]|", "V:|[v]|"], ["v": view])
return view
}()
lazy var subPopoverView = playlistView.subPopover?.contentViewController?.view
var videoViewConstraints: [NSLayoutConstraint.Attribute: NSLayoutConstraint] = [:]
private var oscFloatingLeadingTrailingConstraint: [NSLayoutConstraint]?
override var mouseActionDisabledViews: [NSView?] {[sideBarView, currentControlBar, titleBarView, subPopoverView]}
// MARK: - PIP
lazy var _pip: PIPViewController = {
let pip = PIPViewController()
if #available(macOS 10.12, *) {
pip.delegate = self
}
return pip
}()
@available(macOS 10.12, *)
var pip: PIPViewController {
_pip
}
var pipVideo: NSViewController!
// MARK: - Initialization
override func windowDidLoad() {
super.windowDidLoad()
guard let window = window else { return }
window.styleMask.insert(.fullSizeContentView)
// need to deal with control bar, so we handle it manually
// w.isMovableByWindowBackground = true
// set background color to black
window.backgroundColor = .black
titleBarView.layerContentsRedrawPolicy = .onSetNeedsDisplay
titlebarAccesoryViewController = NSTitlebarAccessoryViewController()
titlebarAccesoryViewController.view = titlebarAccessoryView
titlebarAccesoryViewController.layoutAttribute = .right
window.addTitlebarAccessoryViewController(titlebarAccesoryViewController)
updateOnTopIcon()
// size
window.minSize = minSize
if let wf = windowFrameFromGeometry() {
window.setFrame(wf, display: false)
}
window.aspectRatio = AppData.sizeWhenNoVideo
// sidebar views
sideBarView.isHidden = true
// osc views
fragControlView.addView(fragControlViewLeftView, in: .center)
fragControlView.addView(fragControlViewMiddleView, in: .center)
fragControlView.addView(fragControlViewRightView, in: .center)
setupOnScreenController(withPosition: oscPosition)
let buttons = (Preference.array(for: .controlBarToolbarButtons) as? [Int] ?? []).compactMap(Preference.ToolBarButton.init(rawValue:))
setupOSCToolbarButtons(buttons)
updateArrowButtonImage()
// fade-able views
fadeableViews.append(contentsOf: standardWindowButtons as [NSView])
fadeableViews.append(titleBarView)
fadeableViews.append(titlebarAccessoryView)
// video view
guard let cv = window.contentView else { return }
cv.autoresizesSubviews = false
addVideoViewToWindow()
window.setIsVisible(true)
// gesture recognizer
cv.addGestureRecognizer(magnificationGestureRecognizer)
// Work around a bug in macOS Ventura where HDR content becomes dimmed when playing in full
// screen mode once overlaying views are fully hidden (issue #3844). After applying this
// workaround another bug in Ventura where an external monitor goes black could not be
// reproduced (issue #4015). The workaround adds a tiny subview with such a low alpha level it
// is invisible to the human eye. This workaround may not be effective in all cases.
if #available(macOS 13, *) {
let view = NSView(frame: NSRect(origin: .zero, size: NSSize(width: 0.1, height: 0.1)))
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.black.cgColor
view.layer?.opacity = 0.01
cv.addSubview(view)
}
player.initVideo()
// init quick setting view now
let _ = quickSettingView
// buffer indicator view
bufferIndicatorView.roundCorners(withRadius: 10)
updateBufferIndicatorView()
// thumbnail peek view
window.contentView?.addSubview(thumbnailPeekView)
thumbnailPeekView.isHidden = true
// other initialization
osdAccessoryProgress.usesThreadedAnimation = false
if #available(macOS 10.14, *) {
titleBarBottomBorder.fillColor = NSColor(named: .titleBarBorder)!
}
cachedScreenCount = NSScreen.screens.count
[titleBarView, osdVisualEffectView, controlBarBottom, controlBarFloating, sideBarView, osdVisualEffectView, pipOverlayView].forEach {
$0?.state = .active
}
// hide other views
osdVisualEffectView.isHidden = true
osdVisualEffectView.roundCorners(withRadius: 10)
additionalInfoView.roundCorners(withRadius: 10)
leftArrowLabel.isHidden = true
rightArrowLabel.isHidden = true
timePreviewWhenSeek.isHidden = true
bottomView.isHidden = true
pipOverlayView.isHidden = true
if player.disableUI { hideUI() }
// add user default observers
observedPrefKeys.append(contentsOf: localObservedPrefKeys)
localObservedPrefKeys.forEach { key in
UserDefaults.standard.addObserver(self, forKeyPath: key.rawValue, options: .new, context: nil)
}
// add notification observers
addObserver(to: .default, forName: .iinaFileLoaded, object: player) { [unowned self] _ in
self.quickSettingView.reload()
}
addObserver(to: .default, forName: NSApplication.didChangeScreenParametersNotification) { [unowned self] _ in
// This observer handles a situation that the user connected a new screen or removed a screen
let screenCount = NSScreen.screens.count
if self.fsState.isFullscreen && Preference.bool(for: .blackOutMonitor) && self.cachedScreenCount != screenCount {
self.removeBlackWindow()
self.blackOutOtherMonitors()
}
// Update the cached value
self.cachedScreenCount = screenCount
self.videoView.updateDisplayLink()
// In normal full screen mode AppKit will automatically adjust the window frame if the window
// is moved to a new screen such as when the window is on an external display and that display
// is disconnected. In legacy full screen mode IINA is responsible for adjusting the window's
// frame.
guard self.fsState.isFullscreen, Preference.bool(for: .useLegacyFullScreen) else { return }
setWindowFrameForLegacyFullScreen()
}
player.events.emit(.windowLoaded)
}
/** Set material for OSC and title bar */
override internal func setMaterial(_ theme: Preference.Theme?) {
if #available(macOS 10.14, *) {
super.setMaterial(theme)
return
}
guard let window = window, let theme = theme else { return }
let (appearance, material) = Utility.getAppearanceAndMaterial(from: theme)
let isDarkTheme = appearance?.isDark ?? true
(playSlider.cell as? PlaySliderCell)?.isInDarkTheme = isDarkTheme
[titleBarView, controlBarFloating, controlBarBottom, osdVisualEffectView, pipOverlayView, additionalInfoView, bufferIndicatorView].forEach {
$0?.material = material
$0?.appearance = appearance
}
sideBarView.material = .dark
sideBarView.appearance = NSAppearance(named: .vibrantDark)
window.appearance = appearance
}
private func addVideoViewToWindow() {
guard let cv = window?.contentView else { return }
cv.addSubview(videoView, positioned: .below, relativeTo: nil)
videoView.translatesAutoresizingMaskIntoConstraints = false
// add constraints
([.top, .bottom, .left, .right] as [NSLayoutConstraint.Attribute]).forEach { attr in
videoViewConstraints[attr] = NSLayoutConstraint(item: videoView, attribute: attr, relatedBy: .equal, toItem: cv, attribute: attr, multiplier: 1, constant: 0)
videoViewConstraints[attr]!.isActive = true
}
}
private func setupOSCToolbarButtons(_ buttons: [Preference.ToolBarButton]) {
var buttons = buttons
if #available(macOS 10.12.2, *) {} else {
buttons = buttons.filter { $0 != .pip }
}
fragToolbarView.views.forEach { fragToolbarView.removeView($0) }
for buttonType in buttons {
let button = NSButton()
button.bezelStyle = .regularSquare
button.isBordered = false
button.image = buttonType.image()
button.action = #selector(self.toolBarButtonAction(_:))
button.tag = buttonType.rawValue
button.translatesAutoresizingMaskIntoConstraints = false
button.refusesFirstResponder = true
button.toolTip = buttonType.description()
let buttonWidth = buttons.count == 5 ? "20" : "24"
Utility.quickConstraints(["H:[btn(\(buttonWidth))]", "V:[btn(24)]"], ["btn": button])
fragToolbarView.addView(button, in: .trailing)
}
}
private func setupOnScreenController(withPosition newPosition: Preference.OSCPosition) {
guard !oscIsInitialized || oscPosition != newPosition else { return }
oscIsInitialized = true
let isSwitchingToTop = newPosition == .top
let isSwitchingFromTop = oscPosition == .top
let isFloating = newPosition == .floating
if let cb = currentControlBar {
// remove current osc view from fadeable views
fadeableViews = fadeableViews.filter { $0 != cb }
}
// reset
([controlBarFloating, controlBarBottom, oscTopMainView] as [NSView]).forEach { $0.isHidden = true }
titleBarHeightConstraint.constant = TitleBarHeightNormal
controlBarFloating.isDragging = false
// detach all fragment views
[oscFloatingTopView, oscTopMainView, oscBottomMainView].forEach { stackView in
stackView!.views.forEach {
stackView!.removeView($0)
}
}
[fragSliderView, fragControlView, fragToolbarView, fragVolumeView].forEach {
$0!.removeFromSuperview()
}
let isInFullScreen = fsState.isFullscreen
if isSwitchingToTop {
if isInFullScreen {
addBackTitlebarViewToFadeableViews()
oscTopMainViewTopConstraint.constant = OSCTopMainViewMarginTopInFullScreen
titleBarHeightConstraint.constant = TitleBarHeightWithOSCInFullScreen
} else {
oscTopMainViewTopConstraint.constant = OSCTopMainViewMarginTop
titleBarHeightConstraint.constant = TitleBarHeightWithOSC
}
// Remove this if it's acceptable in 10.13-
// titleBarBottomBorder.isHidden = true
} else {
// titleBarBottomBorder.isHidden = false
}
if isSwitchingFromTop {
if isInFullScreen {
titleBarView.isHidden = true
removeTitlebarViewFromFadeableViews()
}
}
oscPosition = newPosition
// add fragment views
switch oscPosition {
case .floating:
currentControlBar = controlBarFloating
fragControlView.setVisibilityPriority(.detachOnlyIfNecessary, for: fragControlViewLeftView)
fragControlView.setVisibilityPriority(.detachOnlyIfNecessary, for: fragControlViewRightView)
oscFloatingTopView.addView(fragVolumeView, in: .leading)
oscFloatingTopView.addView(fragToolbarView, in: .trailing)
oscFloatingTopView.addView(fragControlView, in: .center)
// Setting the visibility priority to detach only will cause freeze when resizing the window
// (and triggering the detach) in macOS 11.
if !isMacOS11 {
oscFloatingTopView.setVisibilityPriority(.detachOnlyIfNecessary, for: fragVolumeView)
oscFloatingTopView.setVisibilityPriority(.detachOnlyIfNecessary, for: fragToolbarView)
oscFloatingTopView.setClippingResistancePriority(.defaultLow, for: .horizontal)
}
oscFloatingBottomView.addSubview(fragSliderView)
Utility.quickConstraints(["H:|[v]|", "V:|[v]|"], ["v": fragSliderView])
Utility.quickConstraints(["H:|-(>=0)-[v]-(>=0)-|"], ["v": fragControlView])
// center control bar
let cph = Preference.float(for: .controlBarPositionHorizontal)
let cpv = Preference.float(for: .controlBarPositionVertical)
controlBarFloating.xConstraint.constant = window!.frame.width * CGFloat(cph)
controlBarFloating.yConstraint.constant = window!.frame.height * CGFloat(cpv)
case .top:
oscTopMainView.isHidden = false
currentControlBar = nil
fragControlView.setVisibilityPriority(.notVisible, for: fragControlViewLeftView)
fragControlView.setVisibilityPriority(.notVisible, for: fragControlViewRightView)
oscTopMainView.addView(fragVolumeView, in: .trailing)
oscTopMainView.addView(fragToolbarView, in: .trailing)
oscTopMainView.addView(fragControlView, in: .leading)
oscTopMainView.addView(fragSliderView, in: .leading)
oscTopMainView.setClippingResistancePriority(.defaultLow, for: .horizontal)
oscTopMainView.setVisibilityPriority(.mustHold, for: fragSliderView)
oscTopMainView.setVisibilityPriority(.detachEarly, for: fragVolumeView)
oscTopMainView.setVisibilityPriority(.detachEarlier, for: fragToolbarView)
case .bottom:
currentControlBar = controlBarBottom
fragControlView.setVisibilityPriority(.notVisible, for: fragControlViewLeftView)
fragControlView.setVisibilityPriority(.notVisible, for: fragControlViewRightView)
oscBottomMainView.addView(fragVolumeView, in: .trailing)
oscBottomMainView.addView(fragToolbarView, in: .trailing)
oscBottomMainView.addView(fragControlView, in: .leading)
oscBottomMainView.addView(fragSliderView, in: .leading)
oscBottomMainView.setClippingResistancePriority(.defaultLow, for: .horizontal)
oscBottomMainView.setVisibilityPriority(.mustHold, for: fragSliderView)
oscBottomMainView.setVisibilityPriority(.detachEarly, for: fragVolumeView)
oscBottomMainView.setVisibilityPriority(.detachEarlier, for: fragToolbarView)
}
if currentControlBar != nil {
fadeableViews.append(currentControlBar!)
}
showUI()
if isFloating {
fragControlViewMiddleButtons1Constraint.constant = 24
fragControlViewMiddleButtons2Constraint.constant = 24
oscFloatingLeadingTrailingConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=10)-[v]-(>=10)-|",
options: [], metrics: nil, views: ["v": controlBarFloating as Any])
NSLayoutConstraint.activate(oscFloatingLeadingTrailingConstraint!)
} else {
fragControlViewMiddleButtons1Constraint.constant = 16
fragControlViewMiddleButtons2Constraint.constant = 16
if let constraints = oscFloatingLeadingTrailingConstraint {
controlBarFloating.superview?.removeConstraints(constraints)
oscFloatingLeadingTrailingConstraint = nil
}
}
}
// MARK: - Mouse / Trackpad events
@discardableResult
override func handleKeyBinding(_ keyBinding: KeyMapping) -> Bool {
let success = super.handleKeyBinding(keyBinding)
if success && keyBinding.action.first! == MPVCommand.screenshot.rawValue {
player.sendOSD(.screenshot)
}
return success
}
override func pressureChange(with event: NSEvent) {
if isCurrentPressInSecondStage == false && event.stage == 2 {
performMouseAction(Preference.enum(for: .forceTouchAction))
isCurrentPressInSecondStage = true
} else if event.stage == 1 {
isCurrentPressInSecondStage = false
}
}
override func mouseDown(with event: NSEvent) {
// do nothing if it's related to floating OSC
guard !controlBarFloating.isDragging else { return }
// record current mouse pos
mousePosRelatedToWindow = event.locationInWindow
// playlist resizing
if sideBarStatus == .playlist {
let sf = sideBarView.frame
if NSPointInRect(mousePosRelatedToWindow!, NSMakeRect(sf.origin.x - 4, sf.origin.y, 4, sf.height)) {
isResizingSidebar = true
}
}
}
override func mouseDragged(with event: NSEvent) {
if isResizingSidebar {
// resize sidebar
let currentLocation = event.locationInWindow
let newWidth = window!.frame.width - currentLocation.x - 2
sideBarWidthConstraint.constant = newWidth.clamped(to: PlaylistMinWidth...PlaylistMaxWidth)
} else if !fsState.isFullscreen {
// move the window by dragging
isDragging = true
guard !controlBarFloating.isDragging else { return }
if mousePosRelatedToWindow != nil {
window?.performDrag(with: event)
}
}
}
override func mouseUp(with event: NSEvent) {
mousePosRelatedToWindow = nil
if isDragging {
// if it's a mouseup after dragging window
isDragging = false
} else if isResizingSidebar {
// if it's a mouseup after resizing sidebar
isResizingSidebar = false
Preference.set(Int(sideBarWidthConstraint.constant), for: .playlistWidth)
} else {
// if it's a mouseup after clicking
if event.clickCount == 1 && !isMouseEvent(event, inAnyOf: [sideBarView, subPopoverView]) && sideBarStatus != .hidden {
hideSideBar()
return
}
if event.clickCount == 2 && isMouseEvent(event, inAnyOf: [titleBarView]) {
let userDefault = UserDefaults.standard.string(forKey: "AppleActionOnDoubleClick")
if userDefault == "Minimize" {
window?.performMiniaturize(nil)
} else if userDefault == "Maximize" {
window?.performZoom(nil)
}
return
}
super.mouseUp(with: event)
}
}
override internal func performMouseAction(_ action: Preference.MouseClickAction) {
super.performMouseAction(action)
switch action {
case .fullscreen:
toggleWindowFullScreen()
case .hideOSC:
hideUI()
case .togglePIP:
if #available(macOS 10.12, *) {
menuTogglePIP(.dummy)
}
default:
break
}
}
override func scrollWheel(with event: NSEvent) {
guard !isInInteractiveMode else { return }
guard !isMouseEvent(event, inAnyOf: [sideBarView, titleBarView, subPopoverView]) else { return }
if isMouseEvent(event, inAnyOf: [fragSliderView]) && playSlider.isEnabled {
seekOverride = true
} else if isMouseEvent(event, inAnyOf: [fragVolumeView]) && volumeSlider.isEnabled {
volumeOverride = true
} else {
guard !isMouseEvent(event, inAnyOf: [currentControlBar]) else { return }
}
super.scrollWheel(with: event)
seekOverride = false
volumeOverride = false
}
override func mouseEntered(with event: NSEvent) {
guard !isInInteractiveMode else { return }
guard let obj = event.trackingArea?.userInfo?["obj"] as? Int else {
Logger.log("No data for tracking area", level: .warning)
return
}
mouseExitEnterCount += 1
if obj == 0 {
// main window
isMouseInWindow = true
showUI()
updateTimer()
} else if obj == 1 {
// slider
if controlBarFloating.isDragging { return }
isMouseInSlider = true
if !controlBarFloating.isDragging {
timePreviewWhenSeek.isHidden = false
thumbnailPeekView.isHidden = !player.info.thumbnailsReady
}
let mousePos = playSlider.convert(event.locationInWindow, from: nil)
updateTimeLabel(mousePos.x, originalPos: event.locationInWindow)
}
}
override func mouseExited(with event: NSEvent) {
guard !isInInteractiveMode else { return }
guard let obj = event.trackingArea?.userInfo?["obj"] as? Int else {
Logger.log("No data for tracking area", level: .warning)
return
}
mouseExitEnterCount += 1
if obj == 0 {
// main window
isMouseInWindow = false
if controlBarFloating.isDragging { return }
destroyTimer()
hideUI()
} else if obj == 1 {
// slider
isMouseInSlider = false
timePreviewWhenSeek.isHidden = true
let mousePos = playSlider.convert(event.locationInWindow, from: nil)
updateTimeLabel(mousePos.x, originalPos: event.locationInWindow)
thumbnailPeekView.isHidden = true
}
}
override func mouseMoved(with event: NSEvent) {
guard !isInInteractiveMode else { return }
let mousePos = playSlider.convert(event.locationInWindow, from: nil)
if isMouseInSlider {
updateTimeLabel(mousePos.x, originalPos: event.locationInWindow)
}
if isMouseInWindow {
showUI()
}
// check whether mouse is in osc
if isMouseEvent(event, inAnyOf: [currentControlBar, titleBarView]) {
destroyTimer()
} else {
updateTimer()
}
}
@objc func handleMagnifyGesture(recognizer: NSMagnificationGestureRecognizer) {
guard pinchAction != .none else { return }
guard !isInInteractiveMode, let window = window, let screenFrame = NSScreen.main?.visibleFrame else { return }