refactor: use swift shorthand for optional check

This commit is contained in:
lwouis committed 2025-01-12 22:25:45 +01:00
1 parent 941d8afb9a
commit 4c3ec7d067
20 files changed
+57 -58

No files matched your search

+1 -1
View File
@@ -161,7 +161,7 @@ extension NSControl {
return nil
}
set {
if let newValue = newValue {
if let newValue {
let selectorWrapper = SelectorWrapper<NSControl>(withClosure: newValue)
objc_setAssociatedObject(self, &handle, selectorWrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
action = selectorWrapper.selector
+2 -2
View File
@@ -19,7 +19,7 @@ class ATShortcut {
}
func matches(_ id: Int?, _ shortcutState: ShortcutState?, _ keyCode: UInt32?, _ modifiers: NSEvent.ModifierFlags?) -> Bool {
if let id = id, let shortcutState = shortcutState {
if let id, let shortcutState {
let shortcutIndex = id
let shortcutId = KeyboardEventsTestable.globalShortcutsIds.first { $0.value == shortcutIndex }!.key
if shortcutId == self.id {
@@ -29,7 +29,7 @@ class ATShortcut {
}
}
}
if let modifiers = modifiers {
if let modifiers {
let modifiersMatch_ = modifiersMatch(cocoaToCarbonFlags(modifiers))
let newState: ShortcutState = ((shortcut.keyCode == .none || keyCode == shortcut.carbonKeyCode) && modifiersMatch_) ? .down : .up
let flipped = state != newState
+1 -1
View File
@@ -10,7 +10,7 @@ class AppearanceTestable {
/// Let's clamp at 90% like Windows 11
/// Let's clamp at 45% (value for the biggest, 60" screens)
static func comfortableWidth(_ physicalWidth: Double?) -> Double {
if let physicalWidth = physicalWidth {
if let physicalWidth {
return min(0.9, max(0.45, 600.0 / physicalWidth))
}
return 0.9
+8 -8
View File
@@ -34,11 +34,11 @@ class Application: NSObject {
observeEventsIfEligible()
kvObservers = [
runningApplication.observe(\.isFinishedLaunching, options: [.new]) { [weak self] _, _ in
guard let self = self else { return }
guard let self else { return }
self.observeEventsIfEligible()
},
runningApplication.observe(\.activationPolicy, options: [.new]) { [weak self] _, _ in
guard let self = self else { return }
guard let self else { return }
if self.runningApplication.activationPolicy != .regular {
self.removeWindowslessAppWindow()
}
@@ -70,7 +70,7 @@ class Application: NSObject {
func manuallyUpdateWindows(_ group: DispatchGroup? = nil) {
// TODO: this method manually checks windows, but will not find windows on other Spaces
retryAxCallUntilTimeout(group, 5) { [weak self] in
guard let self = self else { return }
guard let self else { return }
var atLeastOneActualWindow = false
if let axWindows_ = try self.axUiElement!.windows(), !axWindows_.isEmpty {
// bug in macOS: sometimes the OS returns multiple duplicate windows (e.g. Mail.app starting at login)
@@ -89,7 +89,7 @@ class Application: NSObject {
let position = try axWindow.position()
atLeastOneActualWindow = true
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
guard let self else { return }
if let window = (Windows.list.first { $0.isEqualRobust(axWindow, wid) }) {
window.title = window.bestEffortTitle(title)
window.size = size
@@ -107,7 +107,7 @@ class Application: NSObject {
}
if (!atLeastOneActualWindow) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
guard let self else { return }
if self.addWindowlessWindowIfNeeded() != nil {
App.app.refreshOpenUi([], .refreshUiAfterExternalEvent)
}
@@ -172,7 +172,7 @@ class Application: NSObject {
}
private func observeEvents() {
guard let axObserver = axObserver else { return }
guard let axObserver else { return }
for notification in [
kAXApplicationActivatedNotification,
kAXMainWindowChangedNotification,
@@ -182,10 +182,10 @@ class Application: NSObject {
kAXApplicationShownNotification,
] {
retryAxCallUntilTimeout { [weak self] in
guard let self = self else { return }
guard let self else { return }
try self.axUiElement!.subscribeToNotification(axObserver, notification, {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
guard let self else { return }
// some apps have `isFinishedLaunching == true` but are actually not finished, and will return .cannotComplete
// we consider them ready when the first subscription succeeds
// windows opened before that point won't send a notification, so check those windows manually here
+10 -10
View File
@@ -87,10 +87,10 @@ class Window {
private func observeEvents() {
AXObserverCreate(application.pid, axObserverCallback, &axObserver)
guard let axObserver = axObserver else { return }
guard let axObserver else { return }
for notification in Window.notifications {
retryAxCallUntilTimeout { [weak self] in
guard let self = self else { return }
guard let self else { return }
try self.axUiElement.subscribeToNotification(axObserver, notification, nil)
}
}
@@ -121,7 +121,7 @@ class Window {
return
}
BackgroundWork.accessibilityCommandsQueue.async { [weak self] in
guard let self = self else { return }
guard let self else { return }
if self.isFullscreen {
self.axUiElement.setAttribute(kAXFullscreenAttribute, false)
}
@@ -141,12 +141,12 @@ class Window {
return
}
BackgroundWork.accessibilityCommandsQueue.async { [weak self] in
guard let self = self else { return }
guard let self else { return }
if self.isFullscreen {
self.axUiElement.setAttribute(kAXFullscreenAttribute, false)
// minimizing is ignored if sent immediatly; we wait for the de-fullscreen animation to be over
BackgroundWork.accessibilityCommandsQueue.asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in
guard let self = self else { return }
guard let self else { return }
self.axUiElement.setAttribute(kAXMinimizedAttribute, true)
}
} else {
@@ -161,7 +161,7 @@ class Window {
return
}
BackgroundWork.accessibilityCommandsQueue.async { [weak self] in
guard let self = self else { return }
guard let self else { return }
self.axUiElement.setAttribute(kAXFullscreenAttribute, !self.isFullscreen)
}
}
@@ -173,7 +173,7 @@ class Window {
App.app.window(withWindowNumber: Int(cgWindowId!))?.makeKeyAndOrderFront(nil)
Windows.previewFocusedWindowIfNeeded()
} else if isWindowlessApp || cgWindowId == nil || Preferences.onlyShowApplications() {
if let bundleUrl = bundleUrl, isWindowlessApp {
if let bundleUrl, isWindowlessApp {
if (try? NSWorkspace.shared.launchApplication(at: bundleUrl, configuration: [:])) == nil {
application.runningApplication.activate(options: .activateAllWindows)
}
@@ -186,7 +186,7 @@ class Window {
// but quickly switches back to another window in that space
// You can reproduce this buggy behaviour by clicking on the dock icon, proving it's an OS bug
BackgroundWork.accessibilityCommandsQueue.async { [weak self] in
guard let self = self else { return }
guard let self else { return }
var psn = ProcessSerialNumber()
GetProcessForPID(self.application.pid, &psn)
_SLPSSetFrontProcessWithOptions(&psn, self.cgWindowId!, SLPSMode.userGenerated.rawValue)
@@ -223,10 +223,10 @@ class Window {
// for some windows (e.g. Slack), the AX API doesn't return a title; we try CG API; finally we resort to the app name
func bestEffortTitle(_ axTitle: String?) -> String {
if let axTitle = axTitle, !axTitle.isEmpty {
if let axTitle, !axTitle.isEmpty {
return axTitle
}
if let cgWindowId = cgWindowId, let cgTitle = cgWindowId.title(), !cgTitle.isEmpty {
if let cgWindowId, let cgTitle = cgWindowId.title(), !cgTitle.isEmpty {
return cgTitle
}
return application.localizedName ?? ""
+2 -2
View File
@@ -150,7 +150,7 @@ class Windows {
if fromMouse && (newIndex != hoveredWindowIndex || lastWindowActivityType == .focus) {
let oldIndex = hoveredWindowIndex
hoveredWindowIndex = newIndex
if let oldIndex = oldIndex {
if let oldIndex {
ThumbnailsView.highlight(oldIndex)
}
index = hoveredWindowIndex
@@ -165,7 +165,7 @@ class Windows {
index = focusedWindowIndex
lastWindowActivityType = .focus
}
guard let index = index else { return }
guard let index else { return }
ThumbnailsView.highlight(index)
let focusedView = ThumbnailsView.recycledViews[index]
App.app.thumbnailsPanel.thumbnailsView.scrollView.contentView.scrollToVisible(focusedView.frame)
+1 -1
View File
@@ -18,7 +18,7 @@ class CliEvents {
fileprivate func handleEvent(_: CFMessagePort?, _: Int32, _ data: CFData?, _: UnsafeMutableRawPointer?) -> Unmanaged<CFData>? {
Logger.debug()
if let data = data,
if let data,
let message = String(data: data as Data, encoding: .utf8) {
Logger.info(message)
let output = CliServer.executeCommandAndSendReponse(message)
+1 -1
View File
@@ -79,7 +79,7 @@ class KeyboardEvents {
eventsOfInterest: eventMask,
callback: cgEventFlagsChangedHandler,
userInfo: nil)
if let eventTap = eventTap {
if let eventTap {
let runLoopSource = CFMachPortCreateRunLoopSource(nil, eventTap, 0)
CFRunLoopAddSource(BackgroundWork.keyboardEventsThread.runLoop, runLoopSource, .commonModes)
} else {
+2 -2
View File
@@ -11,7 +11,7 @@ class MouseEvents {
static func toggle(_ enabled: Bool) {
shouldBeEnabled = enabled
if let eventTap = eventTap {
if let eventTap {
CGEvent.tapEnable(tap: eventTap, enable: enabled)
}
}
@@ -27,7 +27,7 @@ private func observe_() {
eventsOfInterest: eventMask,
callback: handleEvent,
userInfo: nil)
if let eventTap = eventTap {
if let eventTap {
MouseEvents.toggle(false)
let runLoopSource = CFMachPortCreateRunLoopSource(nil, eventTap, 0)
CFRunLoopAddSource(CFRunLoopGetMain(), runLoopSource, .commonModes)
+2 -2
View File
@@ -12,7 +12,7 @@ class TrackpadEvents {
static func toggle(_ enabled: Bool) {
shouldBeEnabled = enabled
if let eventTap = eventTap {
if let eventTap {
CGEvent.tapEnable(tap: eventTap, enable: enabled)
}
}
@@ -27,7 +27,7 @@ private func observe_() {
eventsOfInterest: NSEvent.EventTypeMask.gesture.rawValue,
callback: handleEvent,
userInfo: nil)
if let eventTap = eventTap {
if let eventTap {
let runLoopSource = CFMachPortCreateRunLoopSource(nil, eventTap, 0)
CFRunLoopAddSource(BackgroundWork.keyboardEventsThread.runLoop, runLoopSource, .commonModes)
} else {
+2 -2
View File
@@ -145,7 +145,7 @@ class App: AppCenterApplication {
}
func showSecondaryWindow(_ window: NSWindow?) {
if let window = window {
if let window {
NSScreen.updatePreferred()
NSScreen.preferred.repositionPanel(window)
App.shared.activate(ignoringOtherApps: true)
@@ -300,7 +300,7 @@ extension App: NSApplicationDelegate {
BackgroundWork.startSystemPermissionThread()
permissionsWindow = PermissionsWindow()
SystemPermissions.ensurePermissionsAreGranted { [weak self] in
guard let self = self else { return }
guard let self else { return }
BackgroundWork.start()
NSScreen.updatePreferred()
Appearance.update()
@@ -15,7 +15,7 @@ class PopupButtonLikeSystemSettings: NSPopUpButton {
}
override var intrinsicContentSize: NSSize {
if let selectedItem = selectedItem {
if let selectedItem {
let fakePopUpButton = NSPopUpButton()
fakePopUpButton.addItem(withTitle: title)
fakePopUpButton.item(at: 0)!.image = selectedItem.image
+1 -1
View File
@@ -62,7 +62,7 @@ class Switch: NSButton {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if let switchButton = switchButton {
if let switchButton {
switchButton.draw(dirtyRect)
}
}
+11 -11
View File
@@ -54,8 +54,8 @@ class TableGroupSetView: NSStackView {
// Ensure any remaining views are added
addContinuousTableGroupsToSetViews(&continuousTableGroups, views: &verticalViews, tableGroupSpacing: tableGroupSpacing, padding: padding)
addContinuousOthersToSetViews(&continuousOthers, views: &verticalViews, othersSpacing: othersSpacing, padding: padding, alignment: othersAlignment)
if let toolsView = toolsViews {
addToolsViewToSetViews(toolsView, views: &verticalViews, padding: padding, alignment: toolsAlignment)
if let toolsViews {
addToolsViewToSetViews(toolsViews, views: &verticalViews, padding: padding, alignment: toolsAlignment)
}
if let lastStackView = verticalViews.last {
lastStackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -padding).isActive = true
@@ -228,7 +228,7 @@ class TableGroupView: ClickHoverStackView {
titleStackView.orientation = .vertical
titleStackView.alignment = .leading
titleStackView.spacing = TableGroupView.rowIntraSpacing
if let title = title {
if let title {
titleLabel.stringValue = title
titleLabel.font = NSFont.boldSystemFont(ofSize: 13)
titleLabel.alignment = .natural
@@ -244,7 +244,7 @@ class TableGroupView: ClickHoverStackView {
} else {
titleLabel.isHidden = true
}
if let subTitle = subTitle {
if let subTitle {
subTitleLabel.stringValue = subTitle
subTitleLabel.font = NSFont.systemFont(ofSize: 12)
subTitleLabel.textColor = .gray
@@ -333,7 +333,7 @@ class TableGroupView: ClickHoverStackView {
let leftViews = [TableGroupView.makeText(leftText)]
let mainRow = createMainRow(leftViews: leftViews, rightViews: rightViews)
setMainRow(mainRow, in: rowView)
if let subText = subText {
if let subText {
let subLabel = createSubLabel(with: subText)
setSecondaryRow([subLabel], rowView: rowView, mainRow: mainRow)
} else {
@@ -361,7 +361,7 @@ class TableGroupView: ClickHoverStackView {
let rowView = createRowView()
let mainRow = createMainRow(leftViews: leftViews, rightViews: rightViews)
setMainRow(mainRow, in: rowView)
if let secondaryViews = secondaryViews {
if let secondaryViews {
setSecondaryRow(secondaryViews, rowView: rowView, mainRow: mainRow, orientation: secondaryViewsOrientation, alignment: secondaryViewsAlignment)
} else {
mainRow.bottomAnchor.constraint(equalTo: rowView.bottomAnchor, constant: -TableGroupView.padding).isActive = true
@@ -413,13 +413,13 @@ class TableGroupView: ClickHoverStackView {
leftStackView.orientation = .horizontal
leftStackView.alignment = .leading
leftStackView.spacing = TableGroupView.spacing
if let leftViews = leftViews {
if let leftViews {
leftStackView.setViews(leftViews, in: .leading)
}
let rightStackView = NSStackView()
rightStackView.orientation = .horizontal
rightStackView.spacing = TableGroupView.spacing
if let rightViews = rightViews {
if let rightViews {
rightStackView.setViews(rightViews, in: .leading)
}
mainRow.addArrangedSubview(leftStackView)
@@ -465,7 +465,7 @@ class TableGroupView: ClickHoverStackView {
secondaryRow.orientation = orientation
secondaryRow.alignment = alignment
secondaryRow.spacing = TableGroupView.rowIntraSpacing
if let secondaryRows = secondaryRows {
if let secondaryRows {
secondaryRow.setViews(secondaryRows, in: .leading)
}
rowView.addSubview(secondaryRow)
@@ -513,7 +513,7 @@ class TableGroupView: ClickHoverStackView {
onClick?(event, view)
}
rowView.onMouseEntered = { event, view in
if let onMouseEntered = onMouseEntered {
if let onMouseEntered {
self.rowInfoTables.forEach { table in
if let rowInfo = table.first(where: { $0.view === rowView }) {
self.addMouseEnteredEffects(rowInfo)
@@ -546,7 +546,7 @@ class TableGroupView: ClickHoverStackView {
private func adjustSeparatorWidth(separator: NSView?, isMouseInside: Bool) {
let width = isMouseInside ? width : (width - 2 * TableGroupView.padding)
if let separator = separator {
if let separator {
separator.addOrUpdateConstraint(separator.widthAnchor, width)
}
}
+3 -3
View File
@@ -134,7 +134,7 @@ class ThumbnailView: FlippedView {
@discardableResult
func updateDockLabelIcon(_ dockLabel: String?) -> Bool {
assignIfDifferent(&dockLabelIcon.isHidden, dockLabel == nil || Preferences.hideAppBadges || Appearance.iconSize == 0)
if !dockLabelIcon.isHidden, let dockLabel = dockLabel {
if !dockLabelIcon.isHidden, let dockLabel {
let view = dockLabelIcon.subviews[1] as! ThumbnailFontIconView
let dockLabelInt = Int(dockLabel)
if dockLabelInt == nil || dockLabelInt! > 30 {
@@ -250,7 +250,7 @@ class ThumbnailView: FlippedView {
} else if isHovered {
hoveredView?.label.isHidden = false
focusedView.label.isHidden = true
if let hoveredView = hoveredView {
if let hoveredView {
updateAppIconsLabelFrame(hoveredView)
}
}
@@ -537,7 +537,7 @@ class ThumbnailView: FlippedView {
}
static func thumbnailSize(_ image: NSImage?, _ isWindowlessApp: Bool) -> NSSize {
guard let image = image else { return NSSize(width: 0, height: 0) }
guard let image else { return NSSize(width: 0, height: 0) }
let thumbnailHeightMax = ThumbnailView.maxThumbnailHeight()
- Appearance.edgeInsetsSize * 2
- Appearance.intraCellPadding
+2 -3
View File
@@ -293,12 +293,11 @@ class ScrollView: NSScrollView {
while !(target is ThumbnailView) && target != nil {
target = target!.superview
}
if let target = target, target is ThumbnailView {
if let target = target as? ThumbnailView {
if previousTarget != target {
previousTarget?.showOrHideWindowControls(false)
previousTarget = target as? ThumbnailView
previousTarget = target
}
let target = target as! ThumbnailView
target.mouseMoved()
} else {
if !checkIfWithinInterPadding() {
@@ -31,7 +31,7 @@ class PermissionView: StackView {
buttonStack.translatesAutoresizingMaskIntoConstraints = false
buttonStack.alignment = .centerY
var views = [titleStack, justification, buttonStack]
if let skipCheckbox = skipCheckbox {
if let skipCheckbox {
views.append(skipCheckbox)
}
self.init(views, .vertical, top: GridView.interPadding, right: GridView.interPadding, bottom: GridView.interPadding, left: GridView.interPadding)
@@ -282,12 +282,12 @@ class LabelAndControl: NSObject {
}
let label = makeLabel(labelText)
if labelPosition == .right {
if let suffixText = suffixText {
if let suffixText {
return [control, label, makeSuffix(rawName, suffixText, suffixUrl)]
}
return [control, label]
}
if let suffixText = suffixText {
if let suffixText {
return [label, control, makeSuffix(rawName, suffixText, suffixUrl)]
}
return [label, control]
@@ -350,13 +350,13 @@ class LabelAndControl: NSObject {
} else if control is NSSlider {
return String(format: "%.0f", control.doubleValue) // we are only interested in decimals of the provided double
} else if control is NSButton {
if let controlId = controlId {
if let controlId {
return ((control as! NSButton).state == NSButton.StateValue.on) ? controlId : nil
} else {
return String((control as! NSButton).state == NSButton.StateValue.on)
}
} else if control is Switch {
if let controlId = controlId {
if let controlId {
return ((control as! Switch).state == NSButton.StateValue.on) ? controlId : nil
} else {
return String((control as! Switch).state == NSButton.StateValue.on)
@@ -250,7 +250,7 @@ class ShowHideIllustratedView {
}
func setStateOnApplications(row: ShowHideRowInfo? = nil) {
if let row = row {
if let row {
let isEnabled = !ShowHideIllustratedView.isDisabledOnApplications(row)
row.rightViews.forEach { view in
if let view = view as? Switch {
@@ -174,7 +174,7 @@ class CustomizeStyleSheet: SheetWindow {
}
private func adjustWindowHeight() {
guard let contentView = contentView else { return }
guard let contentView else { return }
// Calculate the fitting height of the content view
let fittingSize = contentView.fittingSize
var windowFrame = frame