From f83ef40c429722e697fbf8a7724e2f015b68cc59 Mon Sep 17 00:00:00 2001 From: Louis Pontoise Date: Mon, 11 May 2020 04:36:37 +0900 Subject: [PATCH] fix: exotic scenario where the os reports no main screen (closes #330) --- src/logic/Screen.swift | 8 ++++++-- src/logic/Spaces.swift | 22 +++++++++++++--------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/logic/Screen.swift b/src/logic/Screen.swift index 6f0440ef..f11d673f 100644 --- a/src/logic/Screen.swift +++ b/src/logic/Screen.swift @@ -21,10 +21,14 @@ class Screen { window.setFrameOrigin(NSPoint(x: x, y: y)) } - static func uuid(_ screen: NSScreen) -> ScreenUuid { + static func uuid(_ screen: NSScreen) -> ScreenUuid? { let screenNumber = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as! UInt32 let screenUuid = CGDisplayCreateUUIDFromDisplayID(screenNumber).takeRetainedValue() - return CFUUIDCreateString(nil, screenUuid)! + if screenUuid != nil, + let uuid = CFUUIDCreateString(nil, screenUuid) { + return uuid + } + return nil } } diff --git a/src/logic/Spaces.swift b/src/logic/Spaces.swift index 15a27761..8fb94765 100644 --- a/src/logic/Spaces.swift +++ b/src/logic/Spaces.swift @@ -18,8 +18,12 @@ class Spaces { } static func refreshCurrentSpaceId() { - currentSpaceId = CGSManagedDisplayGetCurrentSpace(cgsMainConnectionId, Screen.uuid(NSScreen.main!)) - debugPrint("currentSpaceId", currentSpaceId) + // it seems that in some rare scenarios, some of these values are nil; we wrap to avoid crashing + if let mainScreen = NSScreen.main, + let uuid = Screen.uuid(mainScreen) { + currentSpaceId = CGSManagedDisplayGetCurrentSpace(cgsMainConnectionId, uuid) + debugPrint("currentSpaceId", currentSpaceId) + } } static func initialDiscovery() { @@ -38,13 +42,13 @@ class Spaces { static func allIdsAndIndexes() -> [(CGSSpaceID, SpaceIndex)] { return (CGSCopyManagedDisplaySpaces(cgsMainConnectionId) as! [NSDictionary]) - .map { (display: NSDictionary) -> [NSDictionary] in - display["Spaces"] as! [NSDictionary] - } - .joined().enumerated() - .map { (space: (offset: Int, element: NSDictionary)) -> (CGSSpaceID, SpaceIndex) in - (space.element["id64"]! as! CGSSpaceID, space.offset + 1) - } + .map { (display: NSDictionary) -> [NSDictionary] in + display["Spaces"] as! [NSDictionary] + } + .joined().enumerated() + .map { (space: (offset: Int, element: NSDictionary)) -> (CGSSpaceID, SpaceIndex) in + (space.element["id64"]! as! CGSSpaceID, space.offset + 1) + } } static func otherSpaces() -> [CGSSpaceID] {