1
0
mirror of https://github.com/mpv-player/mpv synced 2025-01-11 09:29:29 +00:00

mac: code cleanup and consistency changes, fix linting issues

This commit is contained in:
der richter 2024-04-27 22:11:33 +02:00
parent 984c890661
commit 8f1189341f
21 changed files with 198 additions and 230 deletions

View File

@ -37,7 +37,7 @@ class AppHub: NSObject {
#endif
let MPV_PROTOCOL: String = "mpv://"
var isApplication: Bool { get { NSApp is Application } }
var isApplication: Bool { return NSApp is Application }
var openEvents: Int = 0
private override init() {

View File

@ -18,9 +18,9 @@
import Cocoa
class Application: NSApplication, NSApplicationDelegate {
var appHub: AppHub { get { return AppHub.shared } }
var eventManager: NSAppleEventManager { get { return NSAppleEventManager.shared() } }
var isBundle: Bool { get { return ProcessInfo.processInfo.environment["MPVBUNDLE"] == "true" } }
var appHub: AppHub { return AppHub.shared }
var eventManager: NSAppleEventManager { return NSAppleEventManager.shared() }
var isBundle: Bool { return ProcessInfo.processInfo.environment["MPVBUNDLE"] == "true" }
var playbackThreadId: mp_thread!
var argc: Int32?
var argv: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?

View File

@ -23,7 +23,7 @@ protocol EventSubscriber: AnyObject {
}
extension EventSubscriber {
var uid: Int { get { return Int(bitPattern: ObjectIdentifier(self)) }}
var uid: Int { return Int(bitPattern: ObjectIdentifier(self)) }
}
extension EventHelper {
@ -31,10 +31,10 @@ extension EventHelper {
struct Event {
var id: String {
get { name + (name.starts(with: "MPV_EVENT_") ? "" : String(format.rawValue)) }
return name + (name.starts(with: "MPV_EVENT_") ? "" : String(format.rawValue))
}
var idReset: String {
get { name + (name.starts(with: "MPV_EVENT_") ? "" : String(MPV_FORMAT_NONE.rawValue)) }
return name + (name.starts(with: "MPV_EVENT_") ? "" : String(MPV_FORMAT_NONE.rawValue))
}
let name: String
let format: mpv_format
@ -62,7 +62,7 @@ extension EventHelper {
class EventHelper {
unowned let appHub: AppHub
var mpv: OpaquePointer?
var events: [String:[Int:EventSubscriber]] = [:]
var events: [String: [Int: EventSubscriber]] = [:]
init?(_ appHub: AppHub, _ mpv: OpaquePointer) {
if !appHub.isApplication {
@ -128,7 +128,7 @@ class EventHelper {
let name = String(cString: property.name)
let format = property.format
for (_, subscriber) in events[name + String(format.rawValue)] ?? [:] {
var event: Event? = nil
var event: Event?
switch format {
case MPV_FORMAT_STRING:
event = .init(name: name, format: format, string: TypeHelper.toString(property.data))

View File

@ -25,24 +25,24 @@ class InputHelper: NSObject {
let keymap: [mp_keymap] = [
// special keys
.init(kVK_Return, MP_KEY_ENTER), .init(kVK_Escape, MP_KEY_ESC),
.init(kVK_Delete, MP_KEY_BACKSPACE), .init(kVK_Tab, MP_KEY_TAB),
.init(kVK_Return, MP_KEY_ENTER), .init(kVK_Escape, MP_KEY_ESC),
.init(kVK_Delete, MP_KEY_BACKSPACE), .init(kVK_Tab, MP_KEY_TAB),
.init(kVK_VolumeUp, MP_KEY_VOLUME_UP), .init(kVK_VolumeDown, MP_KEY_VOLUME_DOWN),
.init(kVK_Mute, MP_KEY_MUTE),
// cursor keys
.init(kVK_UpArrow, MP_KEY_UP), .init(kVK_DownArrow, MP_KEY_DOWN),
.init(kVK_UpArrow, MP_KEY_UP), .init(kVK_DownArrow, MP_KEY_DOWN),
.init(kVK_LeftArrow, MP_KEY_LEFT), .init(kVK_RightArrow, MP_KEY_RIGHT),
// navigation block
.init(kVK_Help, MP_KEY_INSERT), .init(kVK_ForwardDelete, MP_KEY_DELETE),
.init(kVK_Home, MP_KEY_HOME), .init(kVK_End, MP_KEY_END),
.init(kVK_Help, MP_KEY_INSERT), .init(kVK_ForwardDelete, MP_KEY_DELETE),
.init(kVK_Home, MP_KEY_HOME), .init(kVK_End, MP_KEY_END),
.init(kVK_PageUp, MP_KEY_PAGE_UP), .init(kVK_PageDown, MP_KEY_PAGE_DOWN),
// F-keys
.init(kVK_F1, MP_KEY_F + 1), .init(kVK_F2, MP_KEY_F + 2), .init(kVK_F3, MP_KEY_F + 3),
.init(kVK_F4, MP_KEY_F + 4), .init(kVK_F5, MP_KEY_F + 5), .init(kVK_F6, MP_KEY_F + 6),
.init(kVK_F7, MP_KEY_F + 7), .init(kVK_F8, MP_KEY_F + 8), .init(kVK_F9, MP_KEY_F + 9),
.init(kVK_F1, MP_KEY_F + 1), .init(kVK_F2, MP_KEY_F + 2), .init(kVK_F3, MP_KEY_F + 3),
.init(kVK_F4, MP_KEY_F + 4), .init(kVK_F5, MP_KEY_F + 5), .init(kVK_F6, MP_KEY_F + 6),
.init(kVK_F7, MP_KEY_F + 7), .init(kVK_F8, MP_KEY_F + 8), .init(kVK_F9, MP_KEY_F + 9),
.init(kVK_F10, MP_KEY_F + 10), .init(kVK_F11, MP_KEY_F + 11), .init(kVK_F12, MP_KEY_F + 12),
.init(kVK_F13, MP_KEY_F + 13), .init(kVK_F14, MP_KEY_F + 14), .init(kVK_F15, MP_KEY_F + 15),
.init(kVK_F16, MP_KEY_F + 16), .init(kVK_F17, MP_KEY_F + 17), .init(kVK_F18, MP_KEY_F + 18),
@ -54,11 +54,11 @@ class InputHelper: NSObject {
.init(kVK_ANSI_KeypadMultiply, Int32(Character("*").asciiValue ?? 0)),
.init(kVK_ANSI_KeypadDivide, Int32(Character("/").asciiValue ?? 0)),
.init(kVK_ANSI_KeypadEnter, MP_KEY_KPENTER), .init(kVK_ANSI_KeypadDecimal, MP_KEY_KPDEC),
.init(kVK_ANSI_Keypad0, MP_KEY_KP0), .init(kVK_ANSI_Keypad1, MP_KEY_KP1),
.init(kVK_ANSI_Keypad2, MP_KEY_KP2), .init(kVK_ANSI_Keypad3, MP_KEY_KP3),
.init(kVK_ANSI_Keypad4, MP_KEY_KP4), .init(kVK_ANSI_Keypad5, MP_KEY_KP5),
.init(kVK_ANSI_Keypad6, MP_KEY_KP6), .init(kVK_ANSI_Keypad7, MP_KEY_KP7),
.init(kVK_ANSI_Keypad8, MP_KEY_KP8), .init(kVK_ANSI_Keypad9, MP_KEY_KP9),
.init(kVK_ANSI_Keypad0, MP_KEY_KP0), .init(kVK_ANSI_Keypad1, MP_KEY_KP1),
.init(kVK_ANSI_Keypad2, MP_KEY_KP2), .init(kVK_ANSI_Keypad3, MP_KEY_KP3),
.init(kVK_ANSI_Keypad4, MP_KEY_KP4), .init(kVK_ANSI_Keypad5, MP_KEY_KP5),
.init(kVK_ANSI_Keypad6, MP_KEY_KP6), .init(kVK_ANSI_Keypad7, MP_KEY_KP7),
.init(kVK_ANSI_Keypad8, MP_KEY_KP8), .init(kVK_ANSI_Keypad9, MP_KEY_KP9),
.init(0, 0)
]
@ -187,7 +187,7 @@ class InputHelper: NSObject {
}
private func mapType(_ type: NSEvent.EventType) -> Int32 {
let typeMapping: [NSEvent.EventType:UInt32] = [
let typeMapping: [NSEvent.EventType: UInt32] = [
.keyDown: MP_KEY_STATE_DOWN,
.keyUp: MP_KEY_STATE_UP,
.leftMouseDown: MP_KEY_STATE_DOWN,
@ -195,14 +195,14 @@ class InputHelper: NSObject {
.rightMouseDown: MP_KEY_STATE_DOWN,
.rightMouseUp: MP_KEY_STATE_UP,
.otherMouseDown: MP_KEY_STATE_DOWN,
.otherMouseUp: MP_KEY_STATE_UP,
.otherMouseUp: MP_KEY_STATE_UP
]
return Int32(typeMapping[type] ?? 0);
return Int32(typeMapping[type] ?? 0)
}
private func mapModifier(_ modifiers: NSEvent.ModifierFlags) -> Int32 {
var mask: UInt32 = 0;
var mask: UInt32 = 0
if modifiers.contains(.shift) {
mask |= MP_KEY_MODIFIER_SHIFT
@ -221,15 +221,15 @@ class InputHelper: NSObject {
}
private func map(button: Int) -> Int32 {
let buttonMapping: [Int:Int32] = [
let buttonMapping: [Int: Int32] = [
0: SWIFT_MBTN_LEFT,
1: SWIFT_MBTN_RIGHT,
2: SWIFT_MBTN_MID,
3: SWIFT_MBTN_FORWARD,
4: SWIFT_MBTN_BACK,
4: SWIFT_MBTN_BACK
]
return Int32(buttonMapping[button] ?? SWIFT_MBTN9 + Int32(button - 5));
return Int32(buttonMapping[button] ?? SWIFT_MBTN9 + Int32(button - 5))
}
func mapDeadKey(_ event: NSEvent) -> String {
@ -257,12 +257,12 @@ class InputHelper: NSObject {
var action = DND_APPEND
if !append {
action = NSEvent.modifierFlags.contains(.shift) ? DND_APPEND : DND_REPLACE
if (option?.vo.drag_and_drop ?? -1) >= 0 {
if (option?.vo.drag_and_drop ?? -1) >= 0 {
action = mp_dnd_action(UInt32(option?.vo.drag_and_drop ?? Int32(DND_REPLACE.rawValue)))
}
}
let filesClean = files.map{ $0.hasPrefix("file:///.file/id=") ? (URL(string: $0)?.path ?? $0) : $0 }
let filesClean = files.map { $0.hasPrefix("file:///.file/id=") ? (URL(string: $0)?.path ?? $0) : $0 }
var filesPtr = filesClean.map { UnsafeMutablePointer<CChar>(strdup($0)) }
mp_event_drop_files(input, Int32(files.count), &filesPtr, action)
for charPtr in filesPtr { free(UnsafeMutablePointer(mutating: charPtr)) }

View File

@ -47,7 +47,7 @@ class LibmpvHelper {
mpv_render_param()
]
if (mpv_render_context_create(&mpvRenderContext, mpv, &params) < 0) {
if mpv_render_context_create(&mpvRenderContext, mpv, &params) < 0 {
log.error("Render context init has failed.")
exit(1)
}
@ -55,12 +55,8 @@ class LibmpvHelper {
}
let getProcAddress: (@convention(c) (UnsafeMutableRawPointer?, UnsafePointer<Int8>?)
-> UnsafeMutableRawPointer?) =
{
(ctx: UnsafeMutableRawPointer?, name: UnsafePointer<Int8>?)
-> UnsafeMutableRawPointer? in
let symbol: CFString = CFStringCreateWithCString(
kCFAllocatorDefault, name, kCFStringEncodingASCII)
-> UnsafeMutableRawPointer?) = { (_ ctx: UnsafeMutableRawPointer?, name: UnsafePointer<Int8>?) -> UnsafeMutableRawPointer? in
let symbol: CFString = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingASCII)
let identifier = CFBundleGetBundleWithIdentifier("com.apple.opengl" as CFString)
let addr = CFBundleGetFunctionPointerForName(identifier, symbol)
@ -128,7 +124,7 @@ class LibmpvHelper {
mpv_render_param(type: MPV_RENDER_PARAM_SKIP_RENDERING, data: pointers[3]),
mpv_render_param()
]
mpv_render_context_render(mpvRenderContext, &params);
mpv_render_context_render(mpvRenderContext, &params)
}
} else {
glClearColor(0, 0, 0, 1)

View File

@ -22,11 +22,11 @@ class LogHelper {
var log: OpaquePointer?
let logger = Logger(subsystem: "io.mpv", category: "mpv")
let loggerMapping: [Int:OSLogType] = [
let loggerMapping: [Int: OSLogType] = [
MSGL_V: .debug,
MSGL_INFO: .info,
MSGL_WARN: .error,
MSGL_ERR: .fault,
MSGL_ERR: .fault
]
init(_ log: OpaquePointer? = nil) {

View File

@ -74,7 +74,7 @@ class MenuBar: NSObject {
let mainMenu = NSMenu(title: "Main")
let servicesMenu = NSMenu(title: "Services")
var menuConfigs: [Config] = []
var dynamicMenuItems: [Type:[MenuItem]] = [:]
var dynamicMenuItems: [Type: [MenuItem]] = [:]
let appIcon: NSImage
@objc init(_ appHub: AppHub) {
@ -111,7 +111,7 @@ class MenuBar: NSObject {
Config(name: "Show All", action: #selector(NSApp.unhideAllApplications(_:))),
Config(type: .separator),
Config(name: "Quit and Remember Position", action: #selector(command(_:)), target: self, command: "quit-watch-later"),
Config(name: "Quit mpv", key: "q", action: #selector(command(_:)), target: self, command: "quit"),
Config(name: "Quit mpv", key: "q", action: #selector(command(_:)), target: self, command: "quit")
]
let fileMenuConfigs = [
@ -120,7 +120,7 @@ class MenuBar: NSObject {
Config(name: "Open Playlist…", action: #selector(openPlaylist), target: self),
Config(type: .separator),
Config(name: "Close", key: "w", action: #selector(NSWindow.performClose(_:))),
Config(name: "Save Screenshot", action: #selector(command(_:)), target: self, command: "async screenshot"),
Config(name: "Save Screenshot", action: #selector(command(_:)), target: self, command: "async screenshot")
]
let editMenuConfigs = [
@ -130,7 +130,7 @@ class MenuBar: NSObject {
Config(name: "Cut", key: "x", action: #selector(NSText.cut(_:))),
Config(name: "Copy", key: "c", action: #selector(NSText.copy(_:))),
Config(name: "Paste", key: "v", action: #selector(NSText.paste(_:))),
Config(name: "Select All", key: "a", action: #selector(NSResponder.selectAll(_:))),
Config(name: "Select All", key: "a", action: #selector(NSResponder.selectAll(_:)))
]
var viewMenuConfigs = [
@ -141,12 +141,12 @@ class MenuBar: NSObject {
action: #selector(command(_:)),
target: self,
command: "cycle on-all-workspaces"
),
)
]
#if HAVE_MACOS_TOUCHBAR
viewMenuConfigs += [
Config(type: .separator),
Config(name: "Customize Touch Bar…", action: #selector(NSApp.toggleTouchBarCustomizationPalette(_:))),
Config(name: "Customize Touch Bar…", action: #selector(NSApp.toggleTouchBarCustomizationPalette(_:)))
]
#endif
@ -167,7 +167,7 @@ class MenuBar: NSObject {
Config(type: .separator),
Config(name: "Half Size", key: "0", type: .itemHalfSize),
Config(name: "Normal Size", key: "1", type: .itemNormalSize),
Config(name: "Double Size", key: "2", type: .itemDoubleSize),
Config(name: "Double Size", key: "2", type: .itemDoubleSize)
]
let audioMenuConfigs = [
@ -178,7 +178,7 @@ class MenuBar: NSObject {
Config(type: .separator),
Config(name: "Play Audio Later", action: #selector(command(_:)), target: self, command: "add audio-delay 0.1"),
Config(name: "Play Audio Earlier", action: #selector(command(_:)), target: self, command: "add audio-delay -0.1"),
Config(name: "Reset Audio Delay", action: #selector(command(_:)), target: self, command: "set audio-delay 0.0"),
Config(name: "Reset Audio Delay", action: #selector(command(_:)), target: self, command: "set audio-delay 0.0")
]
let subtitleMenuConfigs = [
@ -189,7 +189,7 @@ class MenuBar: NSObject {
Config(type: .separator),
Config(name: "Display Subtitles Later", action: #selector(command(_:)), target: self, command: "add sub-delay 0.1"),
Config(name: "Display Subtitles Earlier", action: #selector(command(_:)), target: self, command: "add sub-delay -0.1"),
Config(name: "Reset Subtitle Delay", action: #selector(command(_:)), target: self, command: "set sub-delay 0.0"),
Config(name: "Reset Subtitle Delay", action: #selector(command(_:)), target: self, command: "set sub-delay 0.0")
]
let playbackMenuConfigs = [
@ -212,12 +212,12 @@ class MenuBar: NSObject {
Config(name: "Previous Chapter", action: #selector(command(_:)), target: self, command: "add chapter -1"),
Config(type: .separator),
Config(name: "Step Forward", action: #selector(command(_:)), target: self, command: "frame-step"),
Config(name: "Step Backward", action: #selector(command(_:)), target: self, command: "frame-back-step"),
Config(name: "Step Backward", action: #selector(command(_:)), target: self, command: "frame-back-step")
]
let windowMenuConfigs = [
Config(name: "Minimize", key: "m", type: .itemMinimize),
Config(name: "Zoom", type: .itemZoom),
Config(name: "Zoom", type: .itemZoom)
]
var helpMenuConfigs = [
@ -229,7 +229,7 @@ class MenuBar: NSObject {
Config(name: "Release Notes…", action: #selector(url(_:)), target: self, url: "https://github.com/mpv-player/mpv/blob/master/RELEASE_NOTES"),
Config(name: "Keyboard Shortcuts…", action: #selector(url(_:)), target: self, url: "https://github.com/mpv-player/mpv/blob/master/etc/input.conf"),
Config(type: .separator),
Config(name: "Report Issue…", action: #selector(url(_:)), target: self, url: "https://github.com/mpv-player/mpv/issues/new/choose"),
Config(name: "Report Issue…", action: #selector(url(_:)), target: self, url: "https://github.com/mpv-player/mpv/issues/new/choose")
]
if ProcessInfo.processInfo.environment["MPVBUNDLE"] == "true" {
helpMenuConfigs += [
@ -247,7 +247,7 @@ class MenuBar: NSObject {
Config(name: "Subtitle", configs: subtitleMenuConfigs),
Config(name: "Playback", configs: playbackMenuConfigs),
Config(name: "Window", configs: windowMenuConfigs),
Config(name: "Help", configs: helpMenuConfigs),
Config(name: "Help", configs: helpMenuConfigs)
]
createMenu(parentMenu: mainMenu, configs: menuConfigs)
@ -290,7 +290,7 @@ class MenuBar: NSObject {
.applicationName: "mpv",
.applicationIcon: appIcon,
.applicationVersion: String(cString: swift_mpv_version),
.init(rawValue: "Copyright"): String(cString: swift_mpv_copyright),
.init(rawValue: "Copyright"): String(cString: swift_mpv_copyright)
])
}
@ -298,7 +298,7 @@ class MenuBar: NSObject {
guard let menuConfig = menuItem.config else { return }
let configPaths: [URL] = [
URL(fileURLWithPath: NSHomeDirectory() + "/.config/mpv/", isDirectory: true),
URL(fileURLWithPath: NSHomeDirectory() + "/.mpv/", isDirectory: true),
URL(fileURLWithPath: NSHomeDirectory() + "/.mpv/", isDirectory: true)
]
for path in configPaths {

View File

@ -25,16 +25,18 @@ class OptionHelper {
var voCachePtr: UnsafeMutablePointer<m_config_cache>
var macCachePtr: UnsafeMutablePointer<m_config_cache>
var voPtr: UnsafeMutablePointer<mp_vo_opts>
{ get { return UnsafeMutablePointer<mp_vo_opts>(OpaquePointer(voCachePtr.pointee.opts)) } }
var macPtr: UnsafeMutablePointer<macos_opts>
{ get { return UnsafeMutablePointer<macos_opts>(OpaquePointer(macCachePtr.pointee.opts)) } }
var voPtr: UnsafeMutablePointer<mp_vo_opts> {
return UnsafeMutablePointer<mp_vo_opts>(OpaquePointer(voCachePtr.pointee.opts))
}
var macPtr: UnsafeMutablePointer<macos_opts> {
return UnsafeMutablePointer<macos_opts>(OpaquePointer(macCachePtr.pointee.opts))
}
// these computed properties return a local copy of the struct accessed:
// - don't use if you rely on the pointers
// - only for reading
var vo: mp_vo_opts { get { return voPtr.pointee } }
var mac: macos_opts { get { return macPtr.pointee } }
var vo: mp_vo_opts { return voPtr.pointee }
var mac: macos_opts { return macPtr.pointee }
init(_ taParent: UnsafeMutableRawPointer, _ global: OpaquePointer?) {
voCachePtr = m_config_cache_alloc(taParent, global, AppHub.shared.getVoConf())

View File

@ -19,7 +19,7 @@ import Cocoa
struct Timing {
let time: UInt64
let closure: () -> ()
let closure: () -> Void
}
class PreciseTimer {
@ -97,14 +97,14 @@ class PreciseTimer {
pthread_join(thread, nil)
}
func scheduleAt(time: UInt64, closure: @escaping () -> ()) {
func scheduleAt(time: UInt64, closure: @escaping () -> Void) {
condition.lock()
let firstEventTime = events.first?.time ?? 0
let lastEventTime = events.last?.time ?? 0
events.append(Timing(time: time, closure: closure))
if lastEventTime > time {
events.sort{ $0.time < $1.time }
events.sort { $0.time < $1.time }
}
condition.signal()
@ -115,7 +115,7 @@ class PreciseTimer {
}
}
let threadSignal: @convention(c) (Int32) -> () = { (sig: Int32) in }
let threadSignal: @convention(c) (Int32) -> Void = { (_ sig: Int32) in }
let entryC: @convention(c) (UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? = { (ptr: UnsafeMutableRawPointer) in
let ptimer: PreciseTimer = TypeHelper.bridge(ptr: ptr)

View File

@ -32,7 +32,7 @@ extension RemoteCommandCenter {
var state: NSEvent.EventType = .applicationDefined
let handler: ConfigHandler
init(key: Int32 = 0, type: KeyType = .normal, handler: @escaping ConfigHandler = { event in return .commandFailed }) {
init(key: Int32 = 0, type: KeyType = .normal, handler: @escaping ConfigHandler = { _ in return .commandFailed }) {
self.key = key
self.type = type
self.handler = handler
@ -42,9 +42,9 @@ extension RemoteCommandCenter {
class RemoteCommandCenter: EventSubscriber {
unowned let appHub: AppHub
var event: EventHelper? { get { return appHub.event } }
var input: InputHelper { get { return appHub.input } }
var configs: [MPRemoteCommand:Config] = [:]
var event: EventHelper? { return appHub.event }
var input: InputHelper { return appHub.input }
var configs: [MPRemoteCommand: Config] = [:]
var disabledCommands: [MPRemoteCommand] = []
var isPaused: Bool = false { didSet { updateInfoCenter() } }
var duration: Double = 0 { didSet { updateInfoCenter() } }
@ -56,8 +56,8 @@ class RemoteCommandCenter: EventSubscriber {
var artist: String? { didSet { updateInfoCenter() } }
var cover: NSImage
var infoCenter: MPNowPlayingInfoCenter { get { return MPNowPlayingInfoCenter.default() } }
var commandCenter: MPRemoteCommandCenter { get { return MPRemoteCommandCenter.shared() } }
var infoCenter: MPNowPlayingInfoCenter { return MPNowPlayingInfoCenter.default() }
var commandCenter: MPRemoteCommandCenter { return MPRemoteCommandCenter.shared() }
init(_ appHub: AppHub) {
self.appHub = appHub
@ -72,7 +72,7 @@ class RemoteCommandCenter: EventSubscriber {
commandCenter.togglePlayPauseCommand: Config(key: MP_KEY_PLAY, handler: keyHandler),
commandCenter.seekForwardCommand: Config(key: MP_KEY_FORWARD, type: .repeatable, handler: keyHandler),
commandCenter.seekBackwardCommand: Config(key: MP_KEY_REWIND, type: .repeatable, handler: keyHandler),
commandCenter.changePlaybackPositionCommand: Config(handler: seekHandler),
commandCenter.changePlaybackPositionCommand: Config(handler: seekHandler)
]
disabledCommands = [
@ -86,7 +86,7 @@ class RemoteCommandCenter: EventSubscriber {
commandCenter.ratingCommand,
commandCenter.likeCommand,
commandCenter.dislikeCommand,
commandCenter.bookmarkCommand,
commandCenter.bookmarkCommand
]
for cmd in disabledCommands {

View File

@ -15,7 +15,6 @@
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
#if !swift(>=5.0)
extension Data {
mutating func withUnsafeMutableBytes<Type>(_ body: (UnsafeMutableRawBufferPointer) throws -> Type) rethrows -> Type {
@ -30,7 +29,7 @@ extension Data {
#if !swift(>=4.2)
extension NSDraggingInfo {
var draggingPasteboard: NSPasteboard {
get { return draggingPasteboard() }
return draggingPasteboard()
}
}
#endif

View File

@ -24,33 +24,25 @@ extension NSDeviceDescriptionKey {
extension NSScreen {
public var displayID: CGDirectDisplayID {
get {
return deviceDescription[.screenNumber] as? CGDirectDisplayID ?? 0
}
return deviceDescription[.screenNumber] as? CGDirectDisplayID ?? 0
}
public var serialNumber: String {
get {
return String(CGDisplaySerialNumber(displayID))
}
return String(CGDisplaySerialNumber(displayID))
}
public var name: String {
get {
// force unwrapping is fine here, regex is guaranteed to be valid
let regex = try! NSRegularExpression(pattern: " \\(\\d+\\)$", options: .caseInsensitive)
return regex.stringByReplacingMatches(
in: localizedName,
range: NSRange(location: 0, length: localizedName.count),
withTemplate: ""
)
}
// force unwrapping is fine here, regex is guaranteed to be valid
let regex = try! NSRegularExpression(pattern: " \\(\\d+\\)$", options: .caseInsensitive)
return regex.stringByReplacingMatches(
in: localizedName,
range: NSRange(location: 0, length: localizedName.count),
withTemplate: ""
)
}
public var uniqueName: String {
get {
return name + " (\(serialNumber))"
}
return name + " (\(serialNumber))"
}
}

View File

@ -72,9 +72,9 @@ extension TouchBar {
class TouchBar: NSTouchBar, NSTouchBarDelegate, EventSubscriber {
unowned let appHub: AppHub
var event: EventHelper? { get { return appHub.event } }
var input: InputHelper { get { return appHub.input } }
var configs: [NSTouchBarItem.Identifier:Config] = [:]
var event: EventHelper? { return appHub.event }
var input: InputHelper { return appHub.input }
var configs: [NSTouchBarItem.Identifier: Config] = [:]
var observers: [NSKeyValueObservation] = []
var isPaused: Bool = false { didSet { updatePlayButton() } }
var position: Double = 0 { didSet { updateTouchBarTimeItems() } }
@ -135,11 +135,11 @@ class TouchBar: NSTouchBar, NSTouchBarDelegate, EventSubscriber {
]
delegate = self
customizationIdentifier = .customId;
customizationIdentifier = .customId
defaultItemIdentifiers = [.play, .previousItem, .nextItem, .seekBar]
customizationAllowedItemIdentifiers = [.play, .seekBar, .previousItem, .nextItem,
.previousChapter, .nextChapter, .cycleAudio, .cycleSubtitle, .currentPosition, .timeLeft]
observers += [observe(\.isVisible, options: [.new]) { object, change in self.changed(visibility: change.newValue) }]
observers += [observe(\.isVisible, options: [.new]) { _, change in self.changed(visibility: change.newValue) }]
event?.subscribe(self, event: .init(name: "duration", format: MPV_FORMAT_DOUBLE))
event?.subscribe(self, event: .init(name: "time-pos", format: MPV_FORMAT_DOUBLE))
@ -159,7 +159,7 @@ class TouchBar: NSTouchBar, NSTouchBarDelegate, EventSubscriber {
item.view = config.handler(config)
item.customizationLabel = config.name
configs[identifier]?.item = item
observers += [item.observe(\.isVisible, options: [.new]) { object, change in self.changed(visibility: change.newValue) }]
observers += [item.observe(\.isVisible, options: [.new]) { _, change in self.changed(visibility: change.newValue) }]
return item
}
@ -167,13 +167,13 @@ class TouchBar: NSTouchBar, NSTouchBarDelegate, EventSubscriber {
return NSButton(image: config.image, target: self, action: #selector(Self.buttonAction(_:)))
}
lazy var createText: ViewHandler = { config in
lazy var createText: ViewHandler = { _ in
let text = NSTextField(labelWithString: "0:00")
text.alignment = .center
return text
}
lazy var createSlider: ViewHandler = { config in
lazy var createSlider: ViewHandler = { _ in
let slider = NSSlider(target: self, action: #selector(Self.seekbarChanged(_:)))
slider.minValue = 0
slider.maxValue = 100
@ -265,10 +265,8 @@ class TouchBar: NSTouchBar, NSTouchBarDelegate, EventSubscriber {
}
func getIdentifierFrom(view: NSView) -> NSTouchBarItem.Identifier? {
for (identifier, config) in configs {
if config.item?.view == view {
return identifier
}
for (identifier, config) in configs where config.item?.view == view {
return identifier
}
return nil
}

View File

@ -27,8 +27,8 @@ class TypeHelper {
}
class func withUnsafeMutableRawPointers(_ arguments: [Any],
pointers: [UnsafeMutableRawPointer?] = [],
closure: (_ pointers: [UnsafeMutableRawPointer?]) -> Void) {
pointers: [UnsafeMutableRawPointer?] = [],
closure: (_ pointers: [UnsafeMutableRawPointer?]) -> Void) {
if arguments.count > 0 {
let args = Array(arguments.dropFirst(1))
var newPtrs = pointers

View File

@ -87,8 +87,7 @@ class CocoaCB: Common, EventSubscriber {
}
func updateWindowSize(_ vo: UnsafeMutablePointer<vo>) {
guard let targetScreen = getTargetScreen(forFullscreen: false) ?? NSScreen.main else
{
guard let targetScreen = getTargetScreen(forFullscreen: false) ?? NSScreen.main else {
log.warning("Couldn't update Window size, no Screen available")
return
}
@ -102,11 +101,10 @@ class CocoaCB: Common, EventSubscriber {
}
override func displayLinkCallback(_ displayLink: CVDisplayLink,
_ inNow: UnsafePointer<CVTimeStamp>,
_ inOutputTime: UnsafePointer<CVTimeStamp>,
_ flagsIn: CVOptionFlags,
_ flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn
{
_ inNow: UnsafePointer<CVTimeStamp>,
_ inOutputTime: UnsafePointer<CVTimeStamp>,
_ flagsIn: CVOptionFlags,
_ flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn {
libmpv.reportRenderFlip()
return kCVReturnSuccess
}
@ -178,10 +176,9 @@ class CocoaCB: Common, EventSubscriber {
}
override func control(_ vo: UnsafeMutablePointer<vo>,
events: UnsafeMutablePointer<Int32>,
request: UInt32,
data: UnsafeMutableRawPointer?) -> Int32
{
events: UnsafeMutablePointer<Int32>,
request: UInt32,
data: UnsafeMutableRawPointer?) -> Int32 {
switch mp_voctrl(request) {
case VOCTRL_PREINIT:
DispatchQueue.main.sync { self.preinit(vo) }

View File

@ -158,11 +158,10 @@ class Common: NSObject {
}
func displayLinkCallback(_ displayLink: CVDisplayLink,
_ inNow: UnsafePointer<CVTimeStamp>,
_ inOutputTime: UnsafePointer<CVTimeStamp>,
_ flagsIn: CVOptionFlags,
_ flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn
{
_ inNow: UnsafePointer<CVTimeStamp>,
_ inOutputTime: UnsafePointer<CVTimeStamp>,
_ flagsIn: CVOptionFlags,
_ flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn {
return kCVReturnSuccess
}
@ -170,8 +169,7 @@ class Common: NSObject {
CVDisplayLinkCreateWithActiveCGDisplays(&link)
guard let screen = getTargetScreen(forFullscreen: false) ?? NSScreen.main,
let link = self.link else
{
let link = self.link else {
log.warning("Couldn't start DisplayLink, no Screen or DisplayLink available")
return
}
@ -261,7 +259,7 @@ class Common: NSObject {
return lux > 0 ? lux : 0
}
var lightSensorCallback: IOServiceInterestCallback = { (ctx, service, messageType, messageArgument) -> Void in
var lightSensorCallback: IOServiceInterestCallback = { (ctx, _ service, _ messageType, _ messageArgument) in
let com = unsafeBitCast(ctx, to: Common.self)
var outputs: UInt32 = 2
@ -291,7 +289,8 @@ class Common: NSObject {
lightSensorIOPort = IONotificationPortCreate(kIOMasterPortDefault)
IONotificationPortSetDispatchQueue(lightSensorIOPort, queue)
var n = io_object_t()
IOServiceAddInterestNotification(lightSensorIOPort, srv, kIOGeneralInterest, lightSensorCallback, TypeHelper.bridge(obj: self), &n)
IOServiceAddInterestNotification(lightSensorIOPort, srv, kIOGeneralInterest, lightSensorCallback,
TypeHelper.bridge(obj: self), &n)
let kr = IOServiceOpen(srv, mach_task_self_, 0, &lightSensor)
IOObjectRelease(srv)
@ -386,10 +385,9 @@ class Common: NSObject {
}
func getScreenBy(name screenName: String?) -> NSScreen? {
for screen in NSScreen.screens {
if [screen.localizedName, screen.name, screen.uniqueName, screen.serialNumber].contains(screenName) {
return screen
}
for screen in NSScreen.screens
where [screen.localizedName, screen.name, screen.uniqueName, screen.serialNumber].contains(screenName) {
return screen
}
return nil
}
@ -436,7 +434,7 @@ class Common: NSObject {
// flip the y origin again
let y = CGFloat(-geo.win.y1)
let x = CGFloat(geo.win.x0)
return screen.convertRectFromBacking(NSMakeRect(x, y, width, height))
return screen.convertRectFromBacking(NSRect(x: x, y: y, width: width, height: height))
}
func getInitProperties(_ vo: UnsafeMutablePointer<vo>) -> (NSScreen, NSRect) {
@ -488,10 +486,9 @@ class Common: NSObject {
func windowDidChangeOcclusionState() {}
@objc func control(_ vo: UnsafeMutablePointer<vo>,
events: UnsafeMutablePointer<Int32>,
request: UInt32,
data: UnsafeMutableRawPointer?) -> Int32
{
events: UnsafeMutablePointer<Int32>,
request: UInt32,
data: UnsafeMutableRawPointer?) -> Int32 {
switch mp_voctrl(request) {
case VOCTRL_CHECK_EVENTS:
events.pointee |= Int32(checkEvents())
@ -508,8 +505,8 @@ class Common: NSObject {
DispatchQueue.main.async {
self.window?.toggleFullScreen(nil)
}
case TypeHelper.toPointer(&option.voPtr.pointee.ontop): fallthrough
case TypeHelper.toPointer(&option.voPtr.pointee.ontop_level):
case TypeHelper.toPointer(&option.voPtr.pointee.ontop),
TypeHelper.toPointer(&option.voPtr.pointee.ontop_level):
DispatchQueue.main.async {
self.window?.setOnTop(Bool(self.option.vo.ontop), Int(self.option.vo.ontop_level))
}
@ -533,10 +530,10 @@ class Common: NSObject {
DispatchQueue.main.async {
self.window?.ignoresMouseEvents = self.option.vo.cursor_passthrough
}
case TypeHelper.toPointer(&option.voPtr.pointee.geometry): fallthrough
case TypeHelper.toPointer(&option.voPtr.pointee.autofit): fallthrough
case TypeHelper.toPointer(&option.voPtr.pointee.autofit_smaller): fallthrough
case TypeHelper.toPointer(&option.voPtr.pointee.autofit_larger):
case TypeHelper.toPointer(&option.voPtr.pointee.geometry),
TypeHelper.toPointer(&option.voPtr.pointee.autofit),
TypeHelper.toPointer(&option.voPtr.pointee.autofit_smaller),
TypeHelper.toPointer(&option.voPtr.pointee.autofit_larger):
DispatchQueue.main.async {
let (_, wr) = self.getInitProperties(vo)
self.window?.updateFrame(wr)
@ -595,7 +592,7 @@ class Common: NSObject {
if lightSensor != 0 {
let lux = data!.assumingMemoryBound(to: Int32.self)
lux.pointee = Int32(lmuToLux(lastLmu))
return VO_TRUE;
return VO_TRUE
}
return VO_NOTIMPL
case VOCTRL_GET_UNFS_WINDOW_SIZE:
@ -610,7 +607,7 @@ class Common: NSObject {
case VOCTRL_SET_UNFS_WINDOW_SIZE:
let sizeData = data!.assumingMemoryBound(to: Int32.self)
let size = UnsafeBufferPointer(start: sizeData, count: 2)
var rect = NSMakeRect(0, 0, CGFloat(size[0]), CGFloat(size[1]))
var rect = NSRect(x: 0, y: 0, width: CGFloat(size[0]), height: CGFloat(size[1]))
DispatchQueue.main.async {
if let screen = self.window?.currentScreen, !Bool(self.option.vo.hidpi_window_scale) {
rect = screen.convertRectFromBacking(rect)
@ -620,7 +617,7 @@ class Common: NSObject {
return VO_TRUE
case VOCTRL_GET_DISPLAY_NAMES:
let dnames = data!.assumingMemoryBound(to: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?.self)
var array: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>? = nil
var array: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?
var count: Int32 = 0
let displayName = getCurrentScreen()?.uniqueName ?? "Unknown"

View File

@ -52,24 +52,24 @@ let glFormatAutoGPU: [CGLPixelFormatAttribute] = [
kCGLPFASupportsAutomaticGraphicsSwitching
]
let attributeLookUp: [UInt32:String] = [
kCGLOGLPVersion_3_2_Core.rawValue: "kCGLOGLPVersion_3_2_Core",
kCGLOGLPVersion_Legacy.rawValue: "kCGLOGLPVersion_Legacy",
kCGLPFAOpenGLProfile.rawValue: "kCGLPFAOpenGLProfile",
UInt32(kCGLRendererGenericFloatID): "kCGLRendererGenericFloatID",
kCGLPFARendererID.rawValue: "kCGLPFARendererID",
kCGLPFAAccelerated.rawValue: "kCGLPFAAccelerated",
kCGLPFADoubleBuffer.rawValue: "kCGLPFADoubleBuffer",
kCGLPFABackingStore.rawValue: "kCGLPFABackingStore",
kCGLPFAColorSize.rawValue: "kCGLPFAColorSize",
kCGLPFAColorFloat.rawValue: "kCGLPFAColorFloat",
let attributeLookUp: [UInt32: String] = [
kCGLOGLPVersion_3_2_Core.rawValue: "kCGLOGLPVersion_3_2_Core",
kCGLOGLPVersion_Legacy.rawValue: "kCGLOGLPVersion_Legacy",
kCGLPFAOpenGLProfile.rawValue: "kCGLPFAOpenGLProfile",
UInt32(kCGLRendererGenericFloatID): "kCGLRendererGenericFloatID",
kCGLPFARendererID.rawValue: "kCGLPFARendererID",
kCGLPFAAccelerated.rawValue: "kCGLPFAAccelerated",
kCGLPFADoubleBuffer.rawValue: "kCGLPFADoubleBuffer",
kCGLPFABackingStore.rawValue: "kCGLPFABackingStore",
kCGLPFAColorSize.rawValue: "kCGLPFAColorSize",
kCGLPFAColorFloat.rawValue: "kCGLPFAColorFloat",
kCGLPFAAllowOfflineRenderers.rawValue: "kCGLPFAAllowOfflineRenderers",
kCGLPFASupportsAutomaticGraphicsSwitching.rawValue: "kCGLPFASupportsAutomaticGraphicsSwitching",
kCGLPFASupportsAutomaticGraphicsSwitching.rawValue: "kCGLPFASupportsAutomaticGraphicsSwitching"
]
class GLLayer: CAOpenGLLayer {
unowned var cocoaCB: CocoaCB
var libmpv: LibmpvHelper { get { return cocoaCB.libmpv } }
var libmpv: LibmpvHelper { return cocoaCB.libmpv }
let displayLock = NSLock()
let cglContext: CGLContextObj
@ -176,7 +176,7 @@ class GLLayer: CAOpenGLLayer {
glGetIntegerv(GLenum(GL_VIEWPORT), &dims)
surfaceSize = NSSize(width: CGFloat(dims[2]), height: CGFloat(dims[3]))
if NSEqualSizes(surfaceSize, NSZeroSize) {
if surfaceSize == NSSize.zero {
surfaceSize = bounds.size
surfaceSize.width *= contentsScale
surfaceSize.height *= contentsScale
@ -228,7 +228,7 @@ class GLLayer: CAOpenGLLayer {
lockCglContext()
CGLSetCurrentContext(cglContext)
if libmpv.isRenderUpdateFrame() {
libmpv.drawRender(NSZeroSize, bufferDepth, cglContext, skip: true)
libmpv.drawRender(NSSize.zero, bufferDepth, cglContext, skip: true)
}
unlockCglContext()
}

View File

@ -19,16 +19,14 @@ import Cocoa
class TitleBar: NSVisualEffectView {
unowned var common: Common
var option: OptionHelper { get { return common.option } }
var option: OptionHelper { return common.option }
var systemBar: NSView? {
get { return common.window?.standardWindowButton(.closeButton)?.superview }
}
var systemBar: NSView? { return common.window?.standardWindowButton(.closeButton)?.superview }
static var height: CGFloat {
get { return NSWindow.frameRect(forContentRect: CGRect.zero, styleMask: .titled).size.height }
return NSWindow.frameRect(forContentRect: CGRect.zero, styleMask: .titled).size.height
}
var buttons: [NSButton] {
get { return ([.closeButton, .miniaturizeButton, .zoomButton] as [NSWindow.ButtonType]).compactMap { common.window?.standardWindowButton($0) } }
return ([.closeButton, .miniaturizeButton, .zoomButton] as [NSWindow.ButtonType]).compactMap { common.window?.standardWindowButton($0) }
}
override var material: NSVisualEffectView.Material {
@ -36,20 +34,16 @@ class TitleBar: NSVisualEffectView {
set {
super.material = newValue
// fix for broken deprecated materials
if material == .light || material == .dark || material == .mediumLight ||
material == .ultraDark
{
if material == .light || material == .dark || material == .mediumLight || material == .ultraDark {
state = .active
} else {
state = .followsWindowActiveState
}
}
}
init(frame: NSRect, window: NSWindow, common com: Common) {
let f = NSMakeRect(0, frame.size.height - TitleBar.height,
frame.size.width, TitleBar.height + 1)
let f = NSRect(x: 0, y: frame.size.height - TitleBar.height, width: frame.size.width, height: TitleBar.height + 1)
common = com
super.init(frame: f)
buttons.forEach { $0.isHidden = true }
@ -133,7 +127,7 @@ class TitleBar: NSVisualEffectView {
let loc = common.view?.convert(window.mouseLocationOutsideOfEventStream, from: nil)
buttons.forEach { $0.isHidden = false }
NSAnimationContext.runAnimationGroup({ (context) -> Void in
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = 0.20
systemBar?.animator().alphaValue = 1
if !window.isInFullscreen && !window.isAnimating {
@ -156,7 +150,7 @@ class TitleBar: NSVisualEffectView {
isHidden = true
return
}
NSAnimationContext.runAnimationGroup({ (context) -> Void in
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = duration
systemBar?.animator().alphaValue = 0
animator().alphaValue = 0
@ -191,7 +185,8 @@ class TitleBar: NSVisualEffectView {
return NSAppearance(named: .accessibilityHighContrastVibrantLight)
case "8", "vibrantDarkHighContrast":
return NSAppearance(named: .accessibilityHighContrastVibrantDark)
case "0", "auto": fallthrough
case "0", "auto":
return nil
default:
return nil
}
@ -199,16 +194,16 @@ class TitleBar: NSVisualEffectView {
func materialFrom(string: String) -> NSVisualEffectView.Material {
switch string {
case "0", "titlebar": return .titlebar
case "1", "selection": return .selection
case "2,", "menu": return .menu
case "3", "popover": return .popover
case "4", "sidebar": return .sidebar
case "5,", "headerView": return .headerView
case "6", "sheet": return .sheet
case "7", "windowBackground": return .windowBackground
case "8", "hudWindow": return .hudWindow
case "9", "fullScreen": return .fullScreenUI
case "0", "titlebar": return .titlebar
case "1", "selection": return .selection
case "2", "menu": return .menu
case "3", "popover": return .popover
case "4", "sidebar": return .sidebar
case "5", "headerView": return .headerView
case "6", "sheet": return .sheet
case "7", "windowBackground": return .windowBackground
case "8", "hudWindow": return .hudWindow
case "9", "fullScreen": return .fullScreenUI
case "10", "toolTip": return .toolTip
case "11", "contentBackground": return .contentBackground
case "12", "underWindowBackground": return .underWindowBackground

View File

@ -19,7 +19,7 @@ import Cocoa
class View: NSView, CALayerDelegate {
unowned var common: Common
var input: InputHelper? { get { return common.input } }
var input: InputHelper? { return common.input }
var tracker: NSTrackingArea?
var hasMouseDown: Bool = false
@ -27,7 +27,6 @@ class View: NSView, CALayerDelegate {
override var isFlipped: Bool { return true }
override var acceptsFirstResponder: Bool { return true }
init(frame: NSRect, common com: Common) {
common = com
super.init(frame: frame)

View File

@ -19,8 +19,8 @@ import Cocoa
class Window: NSWindow, NSWindowDelegate {
weak var common: Common! = nil
var option: OptionHelper { get { return common.option } }
var input: InputHelper? { get { return common.input } }
var option: OptionHelper { return common.option }
var input: InputHelper? { return common.input }
var targetScreen: NSScreen?
var previousScreen: NSScreen?
@ -35,8 +35,8 @@ class Window: NSWindow, NSWindowDelegate {
var isAnimating: Bool = false
let animationLock: NSCondition = NSCondition()
var unfsContentFramePixel: NSRect { get { return convertToBacking(unfsContentFrame) } }
@objc var framePixel: NSRect { get { return convertToBacking(frame) } }
var unfsContentFramePixel: NSRect { return convertToBacking(unfsContentFrame) }
@objc var framePixel: NSRect { return convertToBacking(frame) }
var keepAspect: Bool = true {
didSet {
@ -83,14 +83,14 @@ class Window: NSWindow, NSWindowDelegate {
absoluteWantedOrigin.x += wantedScreen.frame.origin.x
absoluteWantedOrigin.y += wantedScreen.frame.origin.y
if !NSEqualPoints(absoluteWantedOrigin, self.frame.origin) {
if absoluteWantedOrigin != self.frame.origin {
self.setFrameOrigin(absoluteWantedOrigin)
}
}
common = com
title = com.title
minSize = NSMakeSize(160, 90)
minSize = NSSize(width: 160, height: 90)
collectionBehavior = .fullScreenPrimary
ignoresMouseEvents = option.vo.cursor_passthrough
delegate = self
@ -147,8 +147,7 @@ class Window: NSWindow, NSWindowDelegate {
} else {
if !isInFullscreen {
setToFullScreen()
}
else {
} else {
setToWindow()
}
}
@ -166,7 +165,7 @@ class Window: NSWindow, NSWindowDelegate {
guard let tScreen = targetScreen else { return }
common.view?.layerContentsPlacement = .scaleProportionallyToFit
common.titleBar?.hide()
NSAnimationContext.runAnimationGroup({ (context) -> Void in
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = getFsAnimationDuration(duration - 0.05)
window.animator().setFrame(tScreen.frame, display: true)
}, completionHandler: nil)
@ -178,12 +177,12 @@ class Window: NSWindow, NSWindowDelegate {
let intermediateFrame = aspectFit(rect: newFrame, in: currentScreen.frame)
common.titleBar?.hide(0.0)
NSAnimationContext.runAnimationGroup({ (context) -> Void in
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = 0.0
common.view?.layerContentsPlacement = .scaleProportionallyToFill
window.animator().setFrame(intermediateFrame, display: true)
}, completionHandler: {
NSAnimationContext.runAnimationGroup({ (context) -> Void in
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = self.getFsAnimationDuration(duration - 0.05)
self.styleMask.remove(.fullScreen)
window.animator().setFrame(newFrame, display: true)
@ -221,9 +220,9 @@ class Window: NSWindow, NSWindowDelegate {
common.view?.layerContentsPlacement = .scaleProportionallyToFit
}
func endAnimation(_ newFrame: NSRect = NSZeroRect) {
if !NSEqualRects(newFrame, NSZeroRect) && isAnimating {
NSAnimationContext.runAnimationGroup({ (context) -> Void in
func endAnimation(_ newFrame: NSRect = NSRect.zero) {
if newFrame != NSRect.zero && isAnimating {
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = 0.01
self.animator().setFrame(newFrame, display: true)
}, completionHandler: nil )
@ -275,7 +274,7 @@ class Window: NSWindow, NSWindowDelegate {
func waitForAnimation() {
animationLock.lock()
while(isAnimating){
while isAnimating {
animationLock.wait()
}
animationLock.unlock()
@ -374,7 +373,7 @@ class Window: NSWindow, NSWindowDelegate {
let cRect = contentRect(forFrameRect: rect)
let dx = (cRect.size.width - sz.width) / 2
let dy = (cRect.size.height - sz.height) / 2
return NSInsetRect(cRect, dx, dy)
return cRect.insetBy(dx: dx, dy: dy)
}
func aspectFit(rect r: NSRect, in rTarget: NSRect) -> NSRect {
@ -394,7 +393,7 @@ class Window: NSWindow, NSWindowDelegate {
let targetFrame = tScreen.frame
let targetVisibleFrame = tScreen.visibleFrame
let unfsScreenFrame = screen.frame
let visibleWindow = NSIntersectionRect(unfsScreenFrame, newFrame)
let visibleWindow = unfsScreenFrame.intersection(newFrame)
// calculate visible area of every side
let left = newFrame.origin.x - unfsScreenFrame.origin.x
@ -457,8 +456,7 @@ class Window: NSWindow, NSWindowDelegate {
override func constrainFrameRect(_ frameRect: NSRect, to tScreen: NSScreen?) -> NSRect {
if (isAnimating && !isInFullscreen) || (!isAnimating && isInFullscreen ||
level == NSWindow.Level(Int(CGWindowLevelForKey(.desktopWindow))))
{
level == NSWindow.Level(Int(CGWindowLevelForKey(.desktopWindow)))) {
return frameRect
}
@ -471,32 +469,32 @@ class Window: NSWindow, NSWindowDelegate {
let ncf: NSRect = contentRect(forFrameRect: nf)
// screen bounds top and bottom
if NSMaxY(nf) > NSMaxY(vf) {
nf.origin.y = NSMaxY(vf) - NSHeight(nf)
if nf.maxY > vf.maxY {
nf.origin.y = vf.maxY - nf.height
}
if NSMaxY(ncf) < NSMinY(vf) {
nf.origin.y = NSMinY(vf) + NSMinY(ncf) - NSMaxY(ncf)
if ncf.maxY < vf.minY {
nf.origin.y = vf.minY + ncf.minY - ncf.maxY
}
// screen bounds right and left
if NSMinX(nf) > NSMaxX(vf) {
nf.origin.x = NSMaxX(vf) - NSWidth(nf)
if nf.minX > vf.maxX {
nf.origin.x = vf.maxX - nf.width
}
if NSMaxX(nf) < NSMinX(vf) {
nf.origin.x = NSMinX(vf)
if nf.maxX < vf.minX {
nf.origin.x = vf.minX
}
if NSHeight(nf) < NSHeight(vf) && NSHeight(of) > NSHeight(vf) && !isInFullscreen {
if nf.height < vf.height && of.height > vf.height && !isInFullscreen {
// If the window height is smaller than the visible frame, but it was
// bigger previously recenter the smaller window vertically. This is
// needed to counter the 'snap to top' behaviour.
nf.origin.y = (NSHeight(vf) - NSHeight(nf)) / 2
nf.origin.y = (vf.height - nf.height) / 2
}
return nf
}
@objc func setNormalWindowSize() { setWindowScale(1.0) }
@objc func setHalfWindowSize() { setWindowScale(0.5) }
@objc func setHalfWindowSize() { setWindowScale(0.5) }
@objc func setDoubleWindowSize() { setWindowScale(2.0) }
func setWindowScale(_ scale: Double) {
@ -540,9 +538,7 @@ class Window: NSWindow, NSWindowDelegate {
common.windowDidEndLiveResize()
option.setOption(maximized: isZoomed)
if let contentViewFrame = contentView?.frame,
!isAnimating && !isInFullscreen
{
if let contentViewFrame = contentView?.frame, !isAnimating && !isInFullscreen {
unfsContentFrame = convertToScreen(contentViewFrame)
}
}

View File

@ -60,9 +60,7 @@ class MacCommon: Common {
initWindowState()
}
if !NSEqualSizes(window?.unfsContentFramePixel.size ?? NSZeroSize, wr.size) &&
option.vo.auto_window_resize
{
if (window?.unfsContentFramePixel.size ?? NSSize.zero) != wr.size && option.vo.auto_window_resize {
window?.updateSize(wr.size)
}
@ -93,7 +91,7 @@ class MacCommon: Common {
@objc func swapBuffer() {
if option.mac.macos_render_timer > RENDER_TIMER_SYSTEM {
swapLock.lock()
while(swapTime < 1) {
while swapTime < 1 {
swapLock.wait()
}
swapTime = 0
@ -111,11 +109,10 @@ class MacCommon: Common {
}
override func displayLinkCallback(_ displayLink: CVDisplayLink,
_ inNow: UnsafePointer<CVTimeStamp>,
_ inOutputTime: UnsafePointer<CVTimeStamp>,
_ flagsIn: CVOptionFlags,
_ flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn
{
_ inNow: UnsafePointer<CVTimeStamp>,
_ inOutputTime: UnsafePointer<CVTimeStamp>,
_ flagsIn: CVOptionFlags,
_ flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn {
let signalSwap = {
self.swapLock.lock()
self.swapTime += 1