Construct and manage a graphical, event-driven user interface for your macOS app using AppKit.

Posts under AppKit tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

I tried to add a overlay window onto app in full screen mode but failed
As the topic mentioned, I want to add a overlay window onto Apps that are in full screen mode, trying to create some blur effect on the screen. But Apple seems to treat full screen mode Apps differently as a "space." So currently I can only apply the blur effect like this. (This is my Desktop page) But When it doesn't affect the full screen mode Apps. (For example: My Xcode) And I know some of the App down this kind of stuff. Like this This is my current code. Hope someone can tell me how to solve it.
1
0
59
16h
Display interactable UI on macOS login screen
We are developing a lightweight VPN client inside a daemon process that will run even when no user session is active on machine. The lightweight VPN runs in machine context and does not require user session. We would like to display some basic diagnosis information about our lightweight client on macOS login window before user is logged into their machine (in case users need that). So, is it possible to display a UI window on login screen with some basic info that user can interact with. If yes, where can I get started? Please note, this is not an authorization plugin. We are just wanting to display info about our process that runs a lightweight VPN client on macOS login screen.
0
0
49
1d
Programmatically created NSWindow crashes upon close
I am trying to wrap my head around proper lifecycles of NSWindows and how to handle them properly. I have the default macOS app template with a ViewController inside a window that is inside a Window Controller. I also create a simple programatic window in applicationDidFinishLaunching like this: let dummyWindow = CustomWindow(contentRect: .init(origin: .zero, size: .init(width: 200, height: 100)), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: true) dummyWindow.title = "Code window" dummyWindow.makeKeyAndOrderFront(nil) The CustomWindow class is just: class CustomWindow: NSWindow { deinit { print("Deinitializing window...") } } When I close the programatic window (either by calling .close() or by just tapping the red close button, the app crashes with EXC_BAD_ACCESS. Even though I am not accessing the window in any way. One might think it's because of ARC but it's not. One—the window is still strongly referenced by NSApplication.shared.windows even when the local scope of applicationDidFinishLaunching ends. And two—the "Deinitializing window..." is only printed after the window is closed. Closing the Interface Builder window works without any crashes. I dug deep and played with the isReleasedWhenClosed property. It made no difference whether it was false or true for the IB window. It stopped the crashing for the programmatic window though. But this raises three questions: What is accessing the programatic window after it's closed—causing a crash because the default behaviour of NSWindow is to release it—if it's not my code? What is the difference under the hood between a normal window and a window inside a window controller that prevents these crashes? If the recommended approach for programmatic windows is to always set isReleasedWhenClosed = true then how do you actually release a programatic window so that it does not linger in memory indefinetely? If the EXC_BAD_ACCESS means that an object is double de-allocated then that would mean that .close() both releases the window (first release) and removes it from the window list which would mean last strong reference is released and ARC cleans the window out (second release). The theory is supported by me calling .orderOut() instead of close which only removes it from the application list and that does indeed release it without crash. Does this mean programmatic windows should override the close() instance method to call orderOut() instead? This seems like poor API design or I am understanding it wrong?
2
0
77
1d
NSTextInputClient concurrency issues in Swift 6
Hello! In our codebase we have a NSView subclass that conforms to NSTextInputClient. This protocol is currently not marked as a main actor, but in the decade this has been in use here it has always been called on the main thread from AppKit. With Swift 6 (or complete concurrency checking in Swift 5) this conformance causes issues since NSView is a main actor but not this protocol. I've tried a few of the usual fixes (MainActor.assumeIsolated or prefixing the protocol conformance with @preconcurrency) but they were not able to resolve all warnings. So I dug in the AppKit headers and found that NSTextInputClient is usually implemented by the view itself, but that that is not a hard requirement (see NSTextInputContext.h the documentation for the client property or here). With that I turned my NSView subclass extension into a separate class that is not a main actor and in my NSView subclass create an instance of it and NSTextInputContext. This all seems to work fine in my initial tests, the delegate methods are called. But when the window loses and then regains key, I see a warning message in the console output. -[TUINSCursorUIController activate:]: Foo.TextInputClient isn't subclass of NSView. So my question is, am I doing it wrong with the custom class that implements the protocol? Or is the warning wrong? I would also appreciate a hint on how to better resolve the concurrency issues with NSTextInputClient. Is a main actor annotation coming at some point from your end? Thanks! Markus
0
0
107
1w
Opt out of window tiling (macOS 15)
Is there a way to opt certain windows out of tiling in macOS 15? I'm supporting a beloved feature called App Veil[1], which places windows below others that are not owned by the host application. These windows are passive: they don't allow mouse events and cannot be resized or moved. With the new tiling feature on macOS 15, the window manager will rearrange these windows if you choose an arrangement option (such as Arrange Left & Right). Ideally, I'd like to opt out of this behavior altogether for these windows, but I couldn't find a way to do that. The only thing I've found was that I could set a high window level, but that's not really an option as it's important to preserve the ordering so that the windows are directly below the out-of-process windows. 1: https://tuple.app/app-veil
0
0
139
2w
onDisappear (or similar) for macOS Settings/Preferences screen
Hi All, this question has been asked before by others, without any success so far. I'm using the following (standard) method to open the system provided settings screen for my macOS (only) app in SwiftUI. var body: some Scene { Settings { PreferencesView() } if #available(macOS 13, *) { // MenuBarExtra requires macOS 13, but SettingsLink used in here requires macOS 14 MenuBarExtra("...", image: "...") { ... // this one requires macOS 14 if #available(macOS 14, *) { SettingsLink() { Text("Settings...") } } else { Button { NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil) } label: { Image(systemName: "gear") } } } } } I want to know when the settings window closes. onDisappear does not work as the settings window is not really closed, but hidden. So the view stays active. All other hacks I have found neither work. Does anyone have any idea?
1
0
125
2w
Delete button in default NSSavePanel for new document
I just noticed that when closing a new document with edits in MacOS Sonoma that it skips the Save/Don't Save/Cancel panel and goes directly to default NSSavePanel with Delete/Cancel/Save buttons. The problem is that when I click "Delete" nothing happens. It should have simple solution, but I could not find anything. How does one respond to the "Delete" button? My undocumented (as far as I can tell) hack was to implement document:didSave:contextinfo selector for runModalSavePanelForSaveOperation. It appears that in this method for a new document: Delete button has didSave=YES (even though it did not save) and the document fileURL nil Cancel button has didSave=NO and document fileURL nil Save button has didSave=YES and document filieURL to saved file I can handle Delete button this way, but since it is not a documented method, it make me uncomfortable. For example what happens is user clicks "Save", but the save has an error? As an aside, since Apple is now working with ChatGPT, I thought it might provide some help. I asked it how I can respond to "Delete" button in MacOS Sonoma and it said to implement deleteDocument: in your NSDocument subclass. I pointed out to ChatGPT that deleteDocument: does not exist. It said "you are correct" and you should instead check the returned result from runModalSavePanelForSaveOperation and look for "stop" action. I pointed out to ChatGPT that runModalSavePanelForSaveOperation is void and does not return a result, it said again, "you are correct." It gave a third option which basically said to override runModalSavePanelForSaveOperation and build your own save panel from scratch. I didn't know if I should trust this answer. I reverted to my hack and wrote this post. Also ChatGPT never apologized for wasting my time with the wrong answers.
3
0
221
2w
How activate window correctly using activationPolicy
I have the following code: + (BOOL)activateWindow:(NSWindow*)window { if (NSApp.activationPolicy != NSApplicationActivationPolicyRegular) [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; if (window) { [NSApp activate]; //if (window.isMiniaturized) [window deminiaturize:nil]; [window makeKeyAndOrderFront:nil]; } return YES; } + (BOOL)hideWindowFromDock:(NSWindow*)window { if (NSApp.activationPolicy != NSApplicationActivationPolicyProhibited) [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited]; window.isVisible = NO; return YES; } I hide app main window by setting NSApplicationActivationPolicyProhibited if it is minimized or being closed. The code worked most of the time. But since upgrading to Sonoma, sometimes it won't correctly activate main window. The window icon reappears in the dock, but the window won't show up. I have to click on the window icon again to let it 'order front'. Sometimes, I observe a very weird behavior of the window being activated. It 'order front' and then disappears and re-appears.
1
0
286
3w
NSDocument doesn't enable Save when modified
When the user makes changes in my document, I call document.updateChangeCount(.changeDone) which seems to successfully mark the document as changed - the close button has a dot, the proxy icon is disabled, and when closing/quitting I get the save prompt. The problem is that the File > Save command is never enabled, so saving/quitting is the only way I can get it to save. I'm not overriding any menu validation methods in my NSDocument subclass. I do have a validateMenuItem() in my main view controller, but it's only for a popup menu, and setting a breakpoint there confirms that it only gets called for the popup. What else could be preventing Save from getting enabled? Edit: I tried overriding validateUserInterfaceItem() to return true when appropriate, which works, although the Save command then appears as "Save..." so apparently I'm also responsible for updating the title. In any case this seems like it shouldn't be necessary. I wonder if it's because I implement saving in save(to:ofType:for:completionHandler:) rather than one of the other possibilities. I was going to try wirte(to:ofType) instead but that is surprisingly nonisolated, so I'm not sure how I'm expected to safely access my data model from there. I can't do data(ofType:) because saving may involve writing to multiple files.
0
0
177
May ’24
Debug mysterious window resize?
I am unfortunately faced with a large legacy code base in which Storyboards are heavily used. Now, for some reason, the entire app window is resized if a certain View Controller becomes visible. The issue: Apparently, there aren't any conflicting layout constraints (no LAYOUT_CONSTRAINTS_NOT_SATISFIABLE errors are raised on display of the view controller). There are also no calls to setFrame on the corresponding window. So, how do I debug this? Capturing the view hierarchy didn't provide any helpful insights, and ideally I could just force the window to not resize (due to possible constraint errors). Is there any way to achieve something like this? If not, how can I go about debugging this? Any help on this would be greatly appreciated.
0
0
236
May ’24
Spelling/grammar check settings persistence in UITextView on Mac Catalyst
In our Mac Catalyst app running on macOS, the Edit > Spelling and Grammar > Check Spelling While Typing, Check Grammar With Spelling, and Correct Spelling Automatically preferences are reset with each opening of a new text view. How can we make those preferences persistent? Ie, when someone changes those settings for our app's text view, other incarnations of our app's text views should respect the latest preferences. We looked at swizzling NSTextView's toggleAutomaticSpellingCorrection:, saving those to NSUserDefaults, and then reading those preferences when we set up our UITextView subclass, and then setting the UITextInputTraits properties accordingly. However, our approach felt heavy handed, and I'm wondering if we are missing some out-of-the-box functionality that will make those preferences intuitively persistent. Does anyone have any suggestions? Thank you.
0
0
266
May ’24
Can't disable App Sandbox
My Xcode workspace contains build settings for a macOS, iOS, and tvOS application. My Sandbox macOS app builds just fine and works great - and is on the App Store. I am in the process of creating a new build / branch of this app that is not Sandboxed so that I can add IPC (Syphon support) - as I don't think I can use App Groups to enable CFMessage support (which Syphon requires) because Syphon (third party framework) - uses its own naming convention for the ports. Anyway, sandbox support for a Syphon app is a topic for another day (it's actually quite disappointing that I can't release a Syphon version on the App Store). The trouble I am having, is that even afer deleting the App Sandbox entitlement from my project, my App still seems to be running in the App Sandbox, and I can't figure out how to remove the App Sandbox entitlement completely. What I am seeing, is that even after deleting the App Sandbox entitlement (using the project settings and deleting it in the "Signing and Capabilities" tab (and also checking the entitlements file manually to doubly make sure it is gone) - I am still seeing the following error message: *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x8703, name = 'info.v002.Syphon.332143F7-0916-428A-A88A-59B752F95304' See /usr/include/servers/bootstrap_defs.h for the error codes. It is also saving my Application Support data in the ~/Library/Containers folder, and not in ~/Library/ApplicationSupport What step am I missing?
7
0
453
May ’24
Appkit :: TIPKIT :: TipNSPopover :: Tippopover view is not closing when we clicked on the cross icon in MAC OS application.
By Implementing the TipKit framework in the AppKit Mac OS application, we were unable to close the popover when we clicked on the cross icon presented in TipNSPopover view. And any clues about how to implement the TipNSPopover on Handover of NScollectionview ?. When the mouse enters any of the collection view cells, I have to present the TipNSpopover view. Please share your input and thoughts.
1
0
255
May ’24
Test Finder right-click feature in a desktop app using Swift
I'd like to know how to test behavior in Swift on Desktop that needs to interact with external elements, in my case the Finder. My goal is simple: add an option in the right-click menu of the Finder that will open my application with the selected entry or entries (file or folder) from the Finder. I have thus set the elements NSMenuItem, NSMessage, NSPortName, NSRequiredContext (NSApplicationIdentifier: com.apple.finder) etc. I also created a class FinderService with a function performService having this declaration: func performService(_ pboard: NSPasteboard, userData: String, error: AutoreleasingUnsafeMutablePointer<NSString>) { NSLog("performService called!") } And I instantiated my class like this: NSApplication.shared.servicesProvider = FinderService(). However, when I build and launch the application nothing happens, well my application runs fine and the instantiation of the class seems to be correctly called. But when I open my Finder, my action is not displayed in the right-click context menu. And in the logs of my application, no error appears. How can I test this?
0
0
291
May ’24
Shutdown event in macOS
I wanted to identify the shutdown event in macOS, so that If my application is running and the user performs a system shutdown then my application could be notified of the shutdown event and perform finalization. I came across NSWorkspaceWillPowerOffNotification which is exactly what I require, however, I created a sample application to observe for this notification. Is is observed that right before the system shuts down, the OS terminates my application invoking applicationWillTerminate(_:) delegate and the observer method for 'NSWorkspaceWillPowerOffNotification' is not invoked. I could perform my finalization in the applicationWillTerminate, but I wanted to know why is the observer not getting invoked. Also why is NSWorkspaceWillPowerOffNotification, even provided by apple when it invoked the termination delegate before shutdown? below is how I m adding the observer: NotificationCenter.default.addObserver(forName: NSWorkspace.willPowerOffNotification, object: nil, queue: nil, using: AppDelegate.handlePowerOffNotification) Below is my observer function, which just logs: public static func handlePowerOffNotification(_ notification: Notification) { NSLog (AppDelegate.TAG + "System will power off soon! Perform any necessary cleanup tasks.") // custom logger to log to a file TWLog.Log ("System will power off soon! Perform any necessary cleanup tasks.") }
3
0
412
May ’24
Emoji glyph bounding box incorrect in transformed CGContext.
I need to draw an outline of an Emoji glyph bounding box that is drawn in CGContext (macOS 14.4.1). I use NSLayoutManager - (void)drawGlyphsForGlyphRange:(NSRange)glyphsToShow atPoint:(NSPoint)origin; and I can get an emoji glyph bounding box using CoreText CGRect CTFontGetBoundingRectsForGlyphs(CTFontRef font, CTFontOrientation orientation, const CGGlyph *glyphs, CGRect *boundingRects, CFIndex count);. The bounding box is correct until the CGContext to which I draw the string with Emoji is not scaled or rotated. In such a case, an Emoji drawn in context is "sometimes" scaled, so its bounding box is not equal to the bounding box obtained from CoreText. Unfortunately, I can't figure out what the dependencies between glyph size, CGContext rotation, and scale are. I couldn't find any linearity between these variables. For example, an Emoji is drawn correctly at scale 6, rotation 0, when CGContext is rotated by 1 degree, Emoji is downsized by 1 pixel, then back in nominal size when rotation is between 2 and 4 degrees, then downsized for 5 degrees, nominal at 6, etc. Has anyone solved this?
0
0
287
May ’24
Crash in CoreGraphics
My app is crashing in CoreGraphics. As per the observations, it started crashing for Mac OS 14.4 and 14.4.1 on Arm machines. It is observed on multiple machines. Can someone please help on this? Following is the backtrace: Process: MyApp [1300] Path: /Applications/MyApp.app/Contents/MacOS/MyApp Identifier: com.MyCompany.MyApp Version: 7.2.3 (???) Code Type: ARM-64 (Native) Parent Process: launchd [1] User ID: 502 Date/Time: 2024-04-23 20:48:08.7647 +0530 OS Version: macOS 14.4.1 (23E224) Report Version: 12 Anonymous UUID: 6DAE9C94-37AC-96D0-7221-3AAA99D9E5F6 Sleep/Wake UUID: 03812728-62F0-45A4-86FC-07E151462C11 Time Awake Since Boot: 11000 seconds Time Since Wake: 1385 seconds System Integrity Protection: enabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000008 Exception Codes: 0x0000000000000001, 0x0000000000000008 Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11 Terminating Process: exc handler [1300] VM Region Info: 0x8 is not in any region. Bytes before following region: 4338843640 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START ---> __TEXT 1029d8000-1029e4000 [ 48K] r-x/r-x SM=COW /Applications/MyApp.app/Contents/MacOS/MyApp Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 CoreGraphics 0x186aabdac shape_union + 656 1 CoreGraphics 0x186aababc shape_union_with_bounds + 128 2 CoreGraphics 0x186aab9f4 CGRegionCreateUnionWithRect + 240 3 AppKit 0x184b439dc 0x18473e000 + 4217308 4 AppKit 0x184b2ad4c 0x18473e000 + 4115788 5 AppKit 0x184dc358c -[NSViewBackingLayer setNeedsDisplayInRect:] + 176 6 AppKit 0x184790874 -[NSView setNeedsDisplayInRect:] + 396 7 Foundation 0x182070914 __NSThreadPerformPerform + 264 8 CoreFoundation 0x180f21eb0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 9 CoreFoundation 0x180f21e44 __CFRunLoopDoSource0 + 176 10 CoreFoundation 0x180f21bb4 __CFRunLoopDoSources0 + 244 11 CoreFoundation 0x180f207a0 __CFRunLoopRun + 828 12 CoreFoundation 0x180f1fe0c CFRunLoopRunSpecific + 608 13 HIToolbox 0x18b6bb000 RunCurrentEventLoopInMode + 292 14 HIToolbox 0x18b6bae3c ReceiveNextEventCommon + 648 15 HIToolbox 0x18b6bab94 _BlockUntilNextEventMatchingListInModeWithFilter + 76 16 AppKit 0x184778970 _DPSNextEvent + 660 17 AppKit 0x184f6adec -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 700 18 AppKit 0x18476bcb8 -[NSApplication run] + 476 19 libffi.dylib 0x191df8050 ffi_call_SYSV + 80 20 libffi.dylib 0x191e00ae0 ffi_call_int + 1212 21 _objc.cpython-39-darwin.so 0x10700a47c PyObjCFFI_Caller_SimpleSEL + 1204 22 _objc.cpython-39-darwin.so 0x107034e94 objcsel_vectorcall_simple + 768 23 Python 0x104312ddc call_function + 124 24 Python 0x104311ac0 _PyEval_EvalFrameDefault + 29288 25 Python 0x10427a720 _PyFunction_Vectorcall + 628 26 Python 0x104312ddc call_function + 124 27 Python 0x104311ac0 _PyEval_EvalFrameDefault + 29288 28 Python 0x10427a57c _PyFunction_Vectorcall + 208 29 Python 0x104312ddc call_function + 124 30 Python 0x104311a4c _PyEval_EvalFrameDefault + 29172 31 Python 0x10427a57c _PyFunction_Vectorcall + 208 32 Python 0x104312ddc call_function + 124 33 Python 0x104311ac0 _PyEval_EvalFrameDefault + 29288 34 Python 0x10427a57c _PyFunction_Vectorcall + 208 35 Python 0x104312ddc call_function + 124 36 Python 0x104311aec _PyEval_EvalFrameDefault + 29332 37 Python 0x10427a57c _PyFunction_Vectorcall + 208 38 Python 0x104312ddc call_function + 124 39 Python 0x104311aec _PyEval_EvalFrameDefault + 29332 40 Python 0x1043131a0 _PyEval_EvalCode + 620 41 Python 0x10430a7d0 PyEval_EvalCode + 80 42 MyApp 0x1029dd440 0x1029d8000 + 21568 43 MyApp 0x1029dd7c0 0x1029d8000 + 22464 44 dyld 0x180aba0e0 start + 2360
2
0
367
May ’24
NSProgressIndicator bindings don't do anything
I'm trying to bind a NSProgressIndicator to Progress, but with the following code I only get an indeterminate progress indicator with a blue bar forever bouncing left and right, even after the two timers fire. According to the documentation: Progress is indeterminate when the value of the totalUnitCount or completedUnitCount is less than zero or if both values are zero. What am I doing wrong? class ViewController: NSViewController { let progress = Progress() override func loadView() { view = NSView(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) let progressIndicator = NSProgressIndicator(frame: CGRect(x: 100, y: 100, width: 100, height: 100)) progressIndicator.bind(.isIndeterminate, to: progress, withKeyPath: "isIndeterminate") progressIndicator.bind(.value, to: progress, withKeyPath: "completedUnitCount") progressIndicator.bind(.maxValue, to: progress, withKeyPath: "totalUnitCount") progressIndicator.startAnimation(nil) view.addSubview(progressIndicator) progress.completedUnitCount = 3 progress.totalUnitCount = 10 Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in print(1) self.progress.completedUnitCount = 6 } Timer.scheduledTimer(withTimeInterval: 6, repeats: false) { _ in print(2) self.progress.completedUnitCount = 0 self.progress.totalUnitCount = 0 } } }
3
0
332
Jun ’24