Skip to content

Commit 58a430b

Browse files
committed
Fixed ghost spaces being created
1 parent 0ac983a commit 58a430b

2 files changed

Lines changed: 19 additions & 14 deletions

File tree

macos-spaces/AppDelegate.swift

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -148,17 +148,26 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
148148
let allWindows = CGWindowListCopyWindowInfo(CGWindowListOption.optionAll, kCGNullWindowID)
149149
let currentWindow = CGWindowListCopyWindowInfo(CGWindowListOption.optionOnScreenOnly, kCGNullWindowID)
150150

151-
// Get all desktop ID's in order, and grab currently active desktop
152-
let allMatched = parseWindowData(String(describing: allWindows))
153-
let currentMatched = parseWindowData(String(describing: currentWindow))[0]
151+
// Get all desktop picture names in order, and grab currently active desktop
152+
let allMatched = parseWindowData(String(describing: allWindows),
153+
expression: "(?<=Desktop Picture - )(.*)(?=\\\")")
154+
let currentMatched = parseWindowData(String(describing: currentWindow),
155+
expression: "(?<=Desktop Picture - )(.*)(?=\\\")")
154156

155-
print(allMatched)
157+
// Get ID of desktop picture (to prevent confusion when two desktops share a picture)
158+
var allID = [String]()
159+
for (i, _) in allMatched.enumerated() {
160+
allID.append(parseWindowData(String(describing: allWindows),
161+
expression: "(?<=\(allMatched[i])\";\\n kCGWindowNumber = )(.*)(?=;)")[0])
162+
}
163+
let currentID = parseWindowData(String(describing: allWindows),
164+
expression: "(?<=\(currentMatched[0])\";\\n kCGWindowNumber = )(.*)(?=;)")
156165

157-
totalSpaces = allMatched.count
166+
totalSpaces = allID.count
158167

159168
// Since pattern returns matches in reverse order, subtract matched index from total
160-
for (i, item) in allMatched.enumerated() {
161-
if item == currentMatched {
169+
for (i, item) in allID.enumerated() {
170+
if item == currentID[0] {
162171
return totalSpaces-i
163172
}
164173
}
@@ -167,14 +176,10 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
167176
return 0
168177
}
169178

170-
// Use regex to get the desktop ID
171-
func parseWindowData(_ text: String) -> [String] {
179+
// Use regex to parse key window data
180+
func parseWindowData(_ text: String, expression: String) -> [String] {
172181
do {
173-
// For doing it by desktop image name (note: doesn't work when two desktops have same picture):
174-
// let regex = try NSRegularExpression(pattern: "(?<=Desktop Picture - )(.*)(?=\\\")")
175-
176-
let regex = try NSRegularExpression(
177-
pattern: "(?<=\\.[a-z]{2,4}\\\";\\n kCGWindowNumber = )(.*)(?=;)")
182+
let regex = try NSRegularExpression(pattern: expression)
178183

179184
let results = regex.matches(in: text,
180185
range: NSRange(text.startIndex..., in: text))

0 commit comments

Comments
 (0)