Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AppKitNavigation - Navigation #213

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,13 @@ let package = Package(
.target(
name: "AppKitNavigation",
dependencies: [
"SwiftNavigation"
"SwiftNavigation",
"AppKitNavigationShim",
]
),
.target(
name: "AppKitNavigationShim"
),
.testTarget(
name: "UIKitNavigationTests",
dependencies: [
Expand Down
4 changes: 4 additions & 0 deletions [email protected]
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,12 @@ let package = Package(
name: "AppKitNavigation",
dependencies: [
"SwiftNavigation",
"AppKitNavigationShim",
]
),
.target(
name: "AppKitNavigationShim"
),
.testTarget(
name: "UIKitNavigationTests",
dependencies: [
Expand Down
2 changes: 1 addition & 1 deletion Sources/AppKitNavigation/AppKitAnimation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@
return try result!._rethrowGet()

case let .swiftUI(animation):
var result: Swift.Result<Result, Error>?
#if swift(>=6)
var result: Swift.Result<Result, Error>?
if #available(macOS 15, *) {
NSAnimationContext.animate(animation) {
result = Swift.Result(catching: body)
Expand Down
36 changes: 36 additions & 0 deletions Sources/AppKitNavigation/Internal/AssociatedKeys.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#if canImport(AppKit) && !targetEnvironment(macCatalyst)

import AppKit

struct AssociatedKeys {
var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:]

mutating func key<T>(of type: T.Type) -> UnsafeMutableRawPointer {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From what I can tell this is a helper that sets up an associated object. Is it doing anything else? If not, I'm inclined to be consistent with the pattern used in UIKitNavigation, where we define dedicated local keys where needed instead of leveraging a dynamic helper. How's that sound?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again because there is more than one type of object that can navigate, this is mainly used for Observer generic types like Sheet, the classes that can execute it are NSWindow, NSSavePanel, NSAlert, NSPrintPanel.... They are not necessarily of the same type, and each class has a different way of executing a sheet.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because associated keys are local to each object, does the type need to be encoded into the operation? Wouldn't it work the same to use the same static key instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

private func sheetObserver<Content: SheetContent>() -> SheetObserver<Self, Content> {
        if let observer = objc_getAssociatedObject(self, sheetObserverKeys.key(of: Content.self)) as? SheetObserver<Self, Content> {
            return observer
        } else {
            let observer = SheetObserver<Self, Content>(owner: self)
            objc_setAssociatedObject(self, sheetObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            return observer
        }
    }

Because of the one-to-many relationship, a class that executes a sheet may have more than one observer (this class is mainly used to store the object that has been executed sheet), the object that is executed by the sheet is indeterminate, it may be NSAlert or NSWindow. Currently, storing the object that is executed by the sheet is mainly to perform cleanup work, if you have a If you have a better idea, let me know! 😄

let key = AnyHashableMetatype(type)
if let associatedKey = keys[key] {
return associatedKey
} else {
let associatedKey = malloc(1)!
keys[key] = associatedKey
return associatedKey
}
}
}

struct AnyHashableMetatype: Hashable {
static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool {
return lhs.base == rhs.base
}

let base: Any.Type

init(_ base: Any.Type) {
self.base = base
}

func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(base))
}
}

#endif
200 changes: 200 additions & 0 deletions Sources/AppKitNavigation/Navigation/Modal.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
#if canImport(AppKit) && !targetEnvironment(macCatalyst)

import AppKit

@MainActor
private var modalObserverKeys = AssociatedKeys()

private typealias ModalObserver<Content: ModalContent> = NavigationObserver<NSObject, Content>

@MainActor
extension NSObject {
@discardableResult
public func modal<Content: ModalContent>(
isModaled: UIBinding<Bool>,
onDismiss: (() -> Void)? = nil,
content: @escaping () -> Content
) -> ObserveToken {
modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() }
}

@discardableResult
public func modalSession<Content: ModalSessionContent>(
isModaled: UIBinding<Bool>,
onDismiss: (() -> Void)? = nil,
content: @escaping () -> Content
) -> ObserveToken {
modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() }
}

@discardableResult
public func modal<Item: Identifiable, Content: ModalContent>(
item: UIBinding<Item?>,
onDismiss: (() -> Void)? = nil,
content: @escaping (Item) -> Content
) -> ObserveToken {
modal(item: item, id: \.id, onDismiss: onDismiss, content: content)
}

@discardableResult
public func modalSession<Item: Identifiable, Content: ModalSessionContent>(
item: UIBinding<Item?>,
onDismiss: (() -> Void)? = nil,
content: @escaping (Item) -> Content
) -> ObserveToken {
modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content)
}

@_disfavoredOverload
@discardableResult
public func modal<Item: Identifiable, Content: ModalContent>(
item: UIBinding<Item?>,
onDismiss: (() -> Void)? = nil,
content: @escaping (UIBinding<Item>) -> Content
) -> ObserveToken {
modal(item: item, id: \.id, onDismiss: onDismiss, content: content)
}

@_disfavoredOverload
@discardableResult
public func modalSession<Item: Identifiable, Content: ModalSessionContent>(
item: UIBinding<Item?>,
onDismiss: (() -> Void)? = nil,
content: @escaping (UIBinding<Item>) -> Content
) -> ObserveToken {
modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content)
}

@discardableResult
public func modal<Item, ID: Hashable, Content: ModalContent>(
item: UIBinding<Item?>,
id: KeyPath<Item, ID>,
onDismiss: (() -> Void)? = nil,
content: @escaping (Item) -> Content
) -> ObserveToken {
modal(item: item, id: id, onDismiss: onDismiss) {
content($0.wrappedValue)
}
}

@discardableResult
public func modalSession<Item, ID: Hashable, Content: ModalSessionContent>(
item: UIBinding<Item?>,
id: KeyPath<Item, ID>,
onDismiss: (() -> Void)? = nil,
content: @escaping (Item) -> Content
) -> ObserveToken {
modalSession(item: item, id: id, onDismiss: onDismiss) {
content($0.wrappedValue)
}
}

@discardableResult
public func modal<Item, ID: Hashable, Content: ModalContent>(
item: UIBinding<Item?>,
id: KeyPath<Item, ID>,
onDismiss: (() -> Void)? = nil,
content: @escaping (UIBinding<Item>) -> Content
) -> ObserveToken {
modal(item: item, id: id) { $item in
content($item)
} beginModal: { modalContent, _ in
if NSApplication.shared.modalWindow != nil {
NSApplication.shared.stopModal()
onDismiss?()
DispatchQueue.main.async {
ModalWindowsObserver.shared.observeWindow(modalContent.window)
modalContent.appKitNavigationRunModal()
modalContent.onEndNavigation?()
modalContent.onEndNavigation = nil
}

} else {
DispatchQueue.main.async {
ModalWindowsObserver.shared.observeWindow(modalContent.window)
modalContent.appKitNavigationRunModal()
modalContent.onEndNavigation?()
modalContent.onEndNavigation = nil
}
}
} endModal: { _, _ in
NSApplication.shared.stopModal()
onDismiss?()
}
}

@discardableResult
public func modalSession<Item, ID: Hashable, Content: ModalSessionContent>(
item: UIBinding<Item?>,
id: KeyPath<Item, ID>,
onDismiss: (() -> Void)? = nil,
content: @escaping (UIBinding<Item>) -> Content
) -> ObserveToken {
modal(item: item, id: id) { $item in
content($item)
} beginModal: { modalContent, _ in
if let modaledWindow = NSApplication.shared.modalWindow, let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modaledWindow] {
NSApplication.shared.endModalSession(modalSession)
modaledWindow.window.close()
onDismiss?()
DispatchQueue.main.async {
let modalSession = modalContent.appKitNavigationBeginModalSession()
ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession)
}

} else {
DispatchQueue.main.async {
let modalSession = modalContent.appKitNavigationBeginModalSession()
ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession)
}
}
} endModal: { modalContent, _ in
if let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modalContent.window] {
NSApplication.shared.endModalSession(modalSession)
modalContent.window.close()
onDismiss?()
}
}
}

private func modal<Item, ID: Hashable, Content: ModalContent>(
item: UIBinding<Item?>,
id: KeyPath<Item, ID>,
content: @escaping (UIBinding<Item>) -> Content,
beginModal: @escaping (
_ child: Content,
_ transaction: UITransaction
) -> Void,
endModal: @escaping (
_ child: Content,
_ transaction: UITransaction
) -> Void
) -> ObserveToken {
let modalObserver: ModalObserver<Content> = modalObserver()
return modalObserver.observe(
item: item,
id: { $0[keyPath: id] },
content: content,
begin: beginModal,
end: endModal
)
}

private func modalObserver<Content: ModalContent>() -> ModalObserver<Content> {
if let observer = objc_getAssociatedObject(self, modalObserverKeys.key(of: Content.self)) as? ModalObserver<Content> {
return observer
} else {
let observer = ModalObserver<Content>(owner: self)
objc_setAssociatedObject(self, modalObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return observer
}
}
}

extension Navigated where Content: ModalContent {
func clearup() {
NSApplication.shared.stopModal()
}
}

#endif
35 changes: 35 additions & 0 deletions Sources/AppKitNavigation/Navigation/ModalContent.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#if canImport(AppKit) && !targetEnvironment(macCatalyst)

import AppKit

@MainActor
public protocol ModalContent: NavigationContent {
@discardableResult func appKitNavigationRunModal() -> NSApplication.ModalResponse
var window: NSWindow { get }
}

extension NSWindow: ModalContent {
public var window: NSWindow { self }

public func appKitNavigationRunModal() -> NSApplication.ModalResponse {
__appKitNavigationRunModal()
}

@objc func __appKitNavigationRunModal() -> NSApplication.ModalResponse {
NSApplication.shared.runModal(for: self)
}
}

extension NSSavePanel {
override func __appKitNavigationRunModal() -> NSApplication.ModalResponse {
runModal()
}
}

extension NSAlert: ModalContent {
public func appKitNavigationRunModal() -> NSApplication.ModalResponse {
runModal()
}
}

#endif
22 changes: 22 additions & 0 deletions Sources/AppKitNavigation/Navigation/ModalSessionContent.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#if canImport(AppKit) && !targetEnvironment(macCatalyst)

import AppKit

@MainActor
public protocol ModalSessionContent: ModalContent {
func appKitNavigationBeginModalSession() -> NSApplication.ModalSession
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think it's possible to avoid these protocols? In UIKitNavigation we got by using the classes themselves, but maybe I'm missing something?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The controls that can perform ModalSession are not only NSWindow, but also NSAlert, NSSavePanel, etc. The same applies to other Sheet protocols.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try to set aside some time later this week to explore the APIs and get a better understanding of how they all tie together then. Thanks for your patience!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are a few comments about public protocols that might be a little excessive for the public API, if they greatly simplify things internally I think there might be an option to hide them using @_spi 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@maximkrouk I tried it and found that it doesn't work. If you use this protocol for spi, all methods that use this protocol need to be spi-compatible.

}

extension NSWindow: ModalSessionContent {

public func appKitNavigationBeginModalSession() -> NSApplication.ModalSession {
__appKitNavigationBeginModalSession()
}

@objc func __appKitNavigationBeginModalSession() -> NSApplication.ModalSession {
let modalSession = NSApplication.shared.beginModalSession(for: self)
return modalSession
}
Mx-Iris marked this conversation as resolved.
Show resolved Hide resolved
}

#endif
33 changes: 33 additions & 0 deletions Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#if canImport(AppKit) && !targetEnvironment(macCatalyst)

import AppKit
import Combine

@MainActor
class ModalWindowsObserver: NSObject {
static let shared = ModalWindowsObserver()

var windowsCancellable: [NSWindow: AnyCancellable] = [:]

var modalSessionByWindow: [NSWindow: NSApplication.ModalSession] = [:]

func observeWindow(_ window: NSWindow, modalSession: NSApplication.ModalSession? = nil) {
if let modalSession {
modalSessionByWindow[window] = modalSession
}
windowsCancellable[window] = NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: window)
.sink { [weak self] _ in
guard let self else { return }
if let modalSession = modalSessionByWindow[window] {
NSApplication.shared.endModalSession(modalSession)
} else if NSApplication.shared.modalWindow === window {
NSApplication.shared.stopModal()
}
modalSessionByWindow.removeValue(forKey: window)
windowsCancellable[window]?.cancel()
windowsCancellable.removeValue(forKey: window)
}
}
}

#endif
Loading