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

AppKit Documentation

Post

Replies

Boosts

Views

Activity

Crash When Clicking on Definition View Created by AppKit's showDefinition(for:at)
I'm encountering a crash issue in my macOS application when clicking on the view generated by AppKit's showDefinition(for:at) function. I'm seeking assistance to resolve this issue. **Problem Description: ** I'm developing a macOS application where I utilize the showDefinition(for:at) function provided by AppKit to display the definition view of words. However, whenever I click on this view, the application crashes abruptly. **Error Message: ** The crash log reveals the following error message: Fault: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)' Attempts Made: Tried wrapping relevant code blocks with DispatchQueue.main.async, suspecting a threading issue. Making the DefinitionWindow variable a global one to manually control its lifecycle Development Environment: macOS Version: 14.3.1 Xcode Version: 15 Below is a complete and reproducible code snippet that can be directly executed within a terminal project template. Please note that it requires Accessibility permissions to be granted in the Privacy settings. import Cocoa import SwiftUI import AppKit class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { [weak self] event in guard let self = self else { return } if event.modifierFlags.contains(.command) && event.charactersIgnoringModifiers == "c" { self.ShowWordDefinition() } } NSApp.servicesProvider = self NSApp.registerServicesMenuSendTypes([.string], returnTypes: []) } func ShowWordDefinition(){ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { let attributedString = NSAttributedString(string:NSPasteboard.general.string(forType: .string)!) let DefinitionWindow = NSWindow(contentRect: NSRect(origin: .zero, size: NSSize(width: 1, height: 1)), styleMask: [.borderless], backing: .buffered, defer: false) // on the top DefinitionWindow.level = .floating let pointInWindow = NSPoint(x:0,y:0); //default value DefinitionWindow.contentView?.showDefinition(for: attributedString, at: pointInWindow) DefinitionWindow.orderFront(nil) } } } let delegate = AppDelegate() let app = NSApplication.shared app.delegate = delegate app.run() full crash log reveals the following error message: FAULT: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)' with backtrace ( "0 CoreFoundation __exceptionPreprocess + 176", "1 libobjc.A.dylib objc_exception_throw + 60", "2 CoreFoundation +[NSException exceptionWithName:reason:userInfo:] + 0", "3 ViewBridge assertCGError + 80", "4 ViewBridge -[NSRemoteView _serviceWindowWouldActivate] + 724", "5 CoreFoundation __invoking___ + 148", "6 CoreFoundation -[NSInvocation invoke] + 428", "7 ViewBridge __deferNSXPCInvocationOntoMainThread_block_invoke + 120", "8 ViewBridge __wrapBlockWithVoucher_block_invoke + 56", "9 ViewBridge deferredBlockOpportunity_block_invoke_2 + 360", "10 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28", "11 CoreFoundation __CFRunLoopDoBlocks + 356", "12 CoreFoundation __CFRunLoopRun + 2440", "13 CoreFoundation CFRunLoopRunSpecific + 608", "14 HIToolbox RunCurrentEventLoopInMode + 292", "15 HIToolbox ReceiveNextEventCommon + 648", "16 HIToolbox _BlockUntilNextEventMatchingListInModeWithFilter + 76", "17 AppKit _DPSNextEvent + 660", "18 AppKit -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716", "19 AppKit -[NSApplication run] + 476", "20 try main + 160", "21 dyld start + 2360" ) Just a reminder, the application will crash when you click on the displayed definition window. Potential Questions and Concerns: Could there be an issue related to UI transitions or the main thread? How exactly does the showDefinition(for:at) process work internally? Maybe , the view's display level being raised when clicked caused conflict? If anyone could provide any insights or guidance on resolving this issue, it would be greatly appreciated. Thank you!
0
0
346
Mar ’24
What is changing the size of my window on first appearance?
I have some old code that a user has prodded me into trying to resolve. The issue is that the window does not size correctly on its first appearance. Stepping through my code, on initial entry to the windowDidLoad method, the size is (800, 472), which seems to correspond with the size in Interface Builder. I go and calculate the size that I want, and in one case it turns out to be (1235, 435), and I use setContentSize to get the window to the correct size. However, it is not that size when it appears, and when I get a chance to look at it, the size is (816, 435). When it runs through the same code in response to the user setting the scale, the size is correctly (1235, 435). Just to be non-deterministic, sometimes the height is 411. The numbers may change, but the difference in height is always either 0 or 24. Is there something that runs after windowDidLoad that changes the window size? Or any other clues to track down why the size changes?
3
0
507
Feb ’24
Print dialog issues with objective-c projects on Sonoma
Hello, I have some older objective-c projects that are about creating reports of tables and gantt charts and printing those reports. They work fine on Ventura and BigSur, but after upgrading to Sonoma, I encountered some problems with the Print dialog and options. Specifically, the page preview is not working, and the Close button does not close the dialog and is not responsive. I have to force quit the app to exit the Print dialog. This makes it impossible to print my reports properly. I wonder if this is a bug with Sonoma or with objective-c, and if there is any workaround or fix for this issue. I appreciate any help or advice from the community or the Apple support team. Thank you.
0
0
433
Feb ’24
Crash When Clicking on Definition View Created by AppKit's showDefinition(for:at)
I'm encountering a crash issue in my macOS application when clicking on the view generated by AppKit's showDefinition(for:at) function. I'm seeking assistance to resolve this issue. Problem Description: I'm developing a macOS application where I utilize the showDefinition(for:at) function provided by AppKit to display the definition view of words. However, whenever I click on this view, the application crashes abruptly. Error Message: The crash log reveals the following error message: Fault: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)' Attempts Made: Tried wrapping relevant code blocks with DispatchQueue.main.async, suspecting a threading issue. Making the DefinitionWindow variable a global one to manually control its lifecycle Development Environment: macOS Version: 14.3.1 Xcode Version: 15 I've included a snippet of the function where the view is created: func ShowDefinition(selectedText : String) { DispatchQueue.main.async { let DefinitionWindow = NSWindow(contentRect: NSRect(origin: self.mouseLocation, size: NSSize(width: 1, height: 1)), styleMask: [.borderless], backing: .buffered, defer: false) DefinitionWindow.level = .floating guard let mainScreenFrame = NSScreen.main?.frame else { return } DefinitionWindow.contentView?.showDefinition(for: attributedString, at: pointInWindow) DefinitionWindow.orderFront(nil) } } Potential Questions and Concerns: Could there be an issue related to UI transitions or the main thread? How exactly does the showDefinition(for:at) process work internally? Maybe , the view's display level being raised when clicked caused conflict? If anyone could provide any insights or guidance on resolving this issue, it would be greatly appreciated. Thank you!
0
0
247
Feb ’24
Crash When Clicking on Definition View Created by AppKit's showDefinition(for:at)
I'm encountering a crash issue in my macOS application when clicking on the view generated by AppKit's showDefinition(for:at) function. I'm seeking assistance to resolve this issue. Problem Description: I'm developing a macOS application where I utilize the showDefinition(for:at) function provided by AppKit to display the definition view of words. However, whenever I click on this view, the application crashes abruptly. Error Message: The crash log reveals the following error message: Fault: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)' Attempts Made: Tried wrapping relevant code blocks with DispatchQueue.main.async, suspecting a threading issue. Development Environment: macOS Version: 14.3.1 Xcode Version: 15.2 I've included a snippet of the function where the view is created: func showWordDefinition(selectedText: String) { DispatchQueue.main.async { let DefinitionWindow = NSWindow(contentRect: NSRect(origin: self.mouseLocation, size: NSSize(width: 1, height: 1)), styleMask: [.borderless], backing: .buffered, defer: false) DefinitionWindow.level = .floating guard let mainScreenFrame = NSScreen.main?.frame else { return } DefinitionWindow.contentView?.showDefinition(for: attributedString, at: pointInWindow) DefinitionWindow.orderFront(nil) } Potential Questions and Concerns: Could there be an issue related to UI transitions or the main thread? How exactly does the showDefinition(for:) process work internally? Maybe , the view's display level being raised when clicked? If anyone could provide any insights or guidance on resolving this issue, it would be greatly appreciated. Thank you!
0
0
233
Feb ’24
How to detect the location of a mouseDown event using Swift?
How to detect the location of a mouseDown event using Swift? With the following code snippet, I get the error "Cannot find type 'NSEvent' in scope"? import SpriteKit func mouseDown(with event: NSEvent) { if let ourScene = GameScene(fileNamed: "GameScene") { let location = event.location(in: view) let node:SKNode = ourScene.atPoint(location) if (node.name == "creditsInfo") { showCredits() } } // if let ourScene } // mouseDown Anybody have a floodlight to shine on this very basic error?
5
0
959
Feb ’24
NSTextList support in macOS 14
This WWDC video (https://developer.apple.com/videos/play/wwdc2022/10090/) shows using NSTextList in TextKit 2 on both iOS and macOS to create bulleted lists in UITextView and NSTextView, respectively. The sample code still works on iOS, but doesn't work on macOS Here's a screenshot from the wwdc talk: Here's the same sample code running on macOS 14.3: Anyone know how to make NSTextList work on macOS 14? Is this a regression, did something change with the api, or has the functionality been removed?
2
3
685
Feb ’24
Issue setting a folder icon on Synology NAS
I have code which uses NSWorkspace setIcon:forFile:options: to place icons on folders. The code works everywhere except on a Synology NAS. (QNAP works fine). The method returns failed regardless of the NSWorkspaceIconCreationOptions set on the call. I would have chalked this up to a driver issue except that the user can manually set the icons on the Finder's Get Info panel. This implies that there is another method that I'm missing. Any ideas as to what this is?
0
0
346
Feb ’24
notification about change visible window
Hello, I am trying to get a notification about change visible (top) window on Desktop. I am using NSWorkspaceDidActivateApplicationNotification notification and it works fine except situation of minimize current active application. Nothing is posted in notification center if active window is minimized. Are there any way to get some notification about change top window which is currently displayed on Desktop? Thank you in advance for your help!
0
0
383
Feb ’24
monitor input events
Hello, I need to monitor input events and convert keycode to symbol. E.g. convert kHIDUsage_KeyboardQ to symbol according to used keyboard layout. Are there any API to get current keyboard layout (language) in C++? If I understand correctly, the API TISGetInputSourceProperty() is deprecated. Are there any way to monitor keyboard layout changed? (some system notification in case of keyboard layout change) Are there any way to translate keycode to symbol except UCKeyTranslate() which is part of deprecated Unicode Utilities? Thank you in advance.
1
0
594
Feb ’24
NSWindow Suddenly Closes After NSTextField Ends Editing (By Clicking into Another NSTextField)
Configuration: I have a NSTextField (multiline) inside an NSWindow. I have another NSTextField (single line) inside an NSBox (which is in the same window). The multiline text field is first responder and is editing. I click on the single line text field inside the NSBox to edit that one. The NSWindow just closes. This is on Sonoma 14.2.1. I subclassed NSWindow and override the close method and put a breakpoint. Here's the call stack that leads to the window suddenly closing: #1 0x0000000189c73d90 in -[NSWindow __close] () #2 0x000000032343 in -[NSApplication(NSResponder) sendAction:to:from:] () #3 0x0000000189b543ac in -[NSControl sendAction:to:] () #4 0x0000000189b542f0 in __26-[NSCell _sendActionFrom:]_block_invoke () #5 0x0000000189b54218 in -[NSCell _sendActionFrom:] () #6 0x0000000189b5413c in -[NSButtonCell _sendActionFrom:] () #7 0x0000000189c4c508 in __29-[NSButtonCell performClick:]_block_invoke () #8 0x0000000189c4c264 in -[NSButtonCell performClick:] () #9 0x0000000189b545a8 in -[NSApplication(NSResponder) sendAction:to:from:] () #10 0x0000000189b543ac in -[NSControl sendAction:to:] () #11 0x0000000189befb48 in -[NSTextField textDidEndEditing:] () #12 0x0000000__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ () #13 0x000000018625c65c in ___CFXRegistrationPost_block_invoke () #14 0x000000018625c5a4 in _CFXRegistrationPost () #15 0x00000001861971dc in _CFXNotificationPost () #16 0x0000000187289ff0 in -[NSNotificationCenter postNotificationName:object:userInfo:] () #17 0x0000000189bef754 in -[NSTextView(NSSharing) resignFirstResponder] () #18 0x0000000189a9fab8 in -[NSWindow _realMakeFirstResponder:] () #19 0x0000000189b4f18c in -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] () #20 0x0000000189ada79c in -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] () #21 0x0000000189ada45c in -[NSWindow(NSEventRouting) sendEvent:] () #22 0x000000018a1879f4 in -[NSApplication(NSEventRouting) sendEvent:] () #23 0x0000000189dd6908 in -[NSApplication _handleEvent:] () #24 0x00000001899a1d74 in -[NSApplication run] () The mouse click is no where near the close button in the title bar.
2
0
587
Feb ’24
drawRect broken in Xcode 15/Sonoma
I'm manually placing a subclass of NSView into the parent view using addSubview:positioned:relativeTo. The dirtyRect passed to drawRect: is wildly incorrect. Can folks attempt to reproduce and file bugs? This is awfully close to the release of Sonoma, and I feel like folks with bezier curves (or maybe other drawing code?) in their NSView subclasses are going to experience problems. To reproduce, place a view (I'm using an NSImageView) as a subview within a view. Then, create a subclass of NSView and draw a bezier curve in the drawRect method. Add an instance of this subclass as a subview of your original view. I'm offsetting the x value for clarity. When I build with Xcode 15 and run on Ventura or earlier, I get the correct result. Or, if I build with Xcode 14.3 and run on Sonoma I get the correct result. However, when I build in Xcode 15 and run on the RC build of Sonoma, I get a whacky result. I get something like (origin = (x = -264, y = -146), size = (width = 480, height = 388)) for the dirtyRect in the error case, while the rect is supposed to be (origin = (x = 0, y = 0), size = (width = 48, height = 48)) (I'm basing the frame of the new view on the original image.) Thanks!
4
1
1.8k
Sep ’23
NSTextField problem in XCode 15.2
Because my MacOS app has a user-programmable interface, my coding creates lots of interface elements programmatically. Soon after an update to MacOS 14.3.1, I found some of these element (NSTextFields) did not draw correctly. I had not changed any code but the appearance changed for the worse (the text in the text field did not appear). I then noticed: The problem occurs when I compile in XCode 15.2 (15C500b) Version and run on computer with Sonoma 14.3.1 (23D60) If I instead compile in XCode Version 14.1 (14B47b) on Ventura 13.0.1 (22A400) and copy the app to my computer with Sonoma 14.3.1 (23D60)all works as expected. These results seem to imply XCode 15.2 does not compile correctly? Is this known issue or is there a fix?
2
0
750
Feb ’24
[NSView drawRect:] is called only once, however two different renderings are generated
I have a custom NSView embedded in a NSScrollView. [NSView drawRect:] is called once, when the window is created and displayed, and the rendering is exactly how it should be. Then I resize (shrink) the window, which does not make [NSView drawRect:] being called again, as no new part of my view needs to be drawn; however, the window's content is flushed again on screen, and the rendering is now different. How could this be possible? I am logging a message in my [NSView drawRect:] implementation, so I am absolutely certain that it is called only once in this scenario. Is it possible that a single drawing instruction ([NSBezierPath stroke], in this case) called only once actually produces two different rendered images, in two different drawing buffers, and that the buffer flushed to the screen can change depending on the size of the window?? Now, what is different in the rendering? Two things: antialiasing is performed differently (the line width is 0.25 pixel), correctly in the first case, and not very smoothly in the second case. I also changed [NSBezierPath setFlatness:], and this flatness is taken in account in the first case, and unchanged (default flatness) in the second case. When I continue to resize the window, enlarging then shrinking it, drawRect: is called when I enlarge it, and depending on the window size, sometimes I get the "correct" rendering, and sometimes the "wrong" one (for the whole view; it is not limited to the newly revealed area). I have a built-in display set to "more space", and an external non-retina monitor; with "desktop & dock" settings set to "displays have different Spaces", in case this has any impact on the situation.
3
0
492
Feb ’24
[macOS Sonoma] screencapture CLI no longer includes DPI information
Using the screencapture CLI on macOS Sonoma 14.0 (23A344) results in a 72dpi image file, no matter if it was captured on a retina display or not. For example, using screencapture -i ~/Desktop/test.png in Terminal lets me create a selective screenshot, but the resulting file does not contain any DPI metadata (checked using mdls ~/Desktop/test.png), nor does the image itself have the correct DPI information (should be 144, but it's always 72; checked using Preview.app). I noticed a (new?) flag option, -r, for which the documentation states: -r Do not add screen dpi meta data to captured file. Is that flag somehow automatically set? Setting it myself makes no difference and obviously results in a no-dpi-in-metadata and wrong-dpi-in-image file. The only two ways I got the correct DPI information in a resulting image file was using the default options (forced by -p): screencapture -i -p, and by making the capture go to the clipboard screencapture -i -c. Sadly, I can't use those in my case. Feedback filed: FB13208235 I'd appreciate any pointers, Matthias
4
2
1.4k
Sep ’23
NSTextField and NSAttributedString
I'm trying to put an attributed string in to an NSTextField the user creates in their document. I cannot use an NSTextView. The problem is once the textfield is created attributes cannot be edited. Also I work in Objective-c because reasons. So when the field is created this is the code used: [attribDict setObject:[self.editor.delegate foregroundColor] forKey:NSForegroundColorAttributeName]; [attribDict setObject:aFont forKey:NSFontAttributeName]; [attribDict setObject:[self.editor.delegate backgroundColor] forKey:NSBackgroundColorAttributeName]; [attribDict setObject:self.editor.delegate.strokeColor forKey:NSStrokeColorAttributeName]; [attribDict setObject:[NSNumber numberWithInt:-self.editor.delegate.strokeWidth] forKey:NSStrokeWidthAttributeName]; This part works if I set all the attributes before I create the textfield. But I need to be able to edit attributes on the string. For that I use this code: NSFont * aFont = [NSFont fontWithName:self.delegate.fontSelectorButton.title size:self.delegate.fontSize.intValue]; NSMutableDictionary * attribDict = [[NSMutableDictionary alloc]init]; [attribDict setObject:[self.delegate foregroundColor] forKey:NSForegroundColorAttributeName]; [attribDict setObject:aFont forKey:NSFontAttributeName]; [attribDict setObject:[self.delegate backgroundColor] forKey:NSBackgroundColorAttributeName]; [attribDict setObject:self.delegate.strokeColor forKey:NSStrokeColorAttributeName]; [attribDict setObject:[NSNumber numberWithInt:self.delegate.strokeWidth] forKey:NSStrokeWidthAttributeName]; [textShape updateTextAttributesFromDictionary:attribDict]; And finally this is called the change the string attributes: -(void)updateTextAttributesFromDictionary:(NSDictionary*)attribs { self.stringAttributes = attribs; NSMutableAttributedString * as = [[NSMutableAttributedString alloc]initWithAttributedString:self.myTextField.attributedStringValue]; [as beginEditing]; [as setAttributes:attribs range:NSMakeRange(0, as.length)]; [as endEditing]; self.myTextField.attributedStringValue = as; } I have tried just setting the new attributes and get nothing. The above code however gives me wildly unpredictable results. Sometimes the NSTextfield gets a background color that cannot be altered. Sometimes the text vanishes. Sometimes all attributes are lost, sometimes if I include a stroke color and width I get the stroke but no fill. That's the most common. Is there some fundimental NSTextField short coming I'm missing? Is there something I'm missing with NSAttributedString? Are NSAttributedStrings not compatible with NSTextField?
0
0
488
Feb ’24
Cocoa binding to NSButton messes with enabled state
When an NSButton's value and hidden state are bound to properties, changing either property enables the button. See example code: @interface MyClass () @property (nonatomic) BOOL buttonHidden; @property (nonatomic) BOOL buttonState; @end @implementation MyClass { __weak IBOutlet NSButton *button; // The button is in a view designed in IB } - (void)awakeFromNib { [super awakeFromNib]; [button bind:NSHiddenBinding toObject:self withKeyPath:@"buttonHidden" options:nil]; [button bind:NSValueBinding toObject:self withKeyPath:@"buttonState" options:nil]; button.enabled = NO; self.buttonHidden = NO; // This enables the button. If this line isn't executed, the buttons stays disabled. } @end Note that the issue occurs only of both properties are bound. I wonder if this is by design or a bug.
0
0
426
Feb ’24