Post

Replies

Boosts

Views

Activity

How can I set my window title in Cocoa?
I have a simple cocoa project, it has the default files like AppDelegate.m, AppDelegate.h , ViewController.h and ViewController.m what I want is to set the Window title to the dimension of the current window and update it as the user resizes it. My Storyboard has an Application Scene, a Window Controller Scene and a test Scene which contains my view: how do I go about this? should my ViewController or AppController implement NSWindowDelegate ?
2
0
320
Sep ’24
autoreleasepool still gives me a memory leak
So I have this program that displays events on the window using NSWindow and a NSTextField. Basically it tracks the mouse position and the keyboard state. I created a simple class named MyEventWindow: // // MyEventWindow.h // AppTest #ifndef MyEventWindow_h #define MyEventWindow_h @interface MyEventWindow : NSWindow { } @property(nonatomic, strong) NSTextField* label; @property(nonatomic, strong) NSString* labelText; - (BOOL)windowShouldClose:(id)sender; - (instancetype) init; - (void) setLabelText:(NSString *)labelText; @end @implementation MyEventWindow -(instancetype) init { self = [super initWithContentRect:NSMakeRect(100, 100, 300, 300) styleMask:(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable) backing:NSBackingStoreBuffered defer:NO]; if( !self ) { return nil; } [self setTitle: @"Event tracker"]; [self setIsVisible: YES]; _label = [[NSTextField alloc] initWithFrame:NSMakeRect(5, 100, 290, 100)]; [_label setBezeled: NO]; [_label setDrawsBackground: NO]; [_label setEditable: NO]; [_label setSelectable: YES]; NSFont *currentFont = [_label font]; NSFont *resizedFont = [NSFont fontWithName:[currentFont fontName] size:18]; NSFont *boldFont = [[NSFontManager sharedFontManager] convertFont:resizedFont toHaveTrait:NSFontBoldTrait]; // convert the bold font to have the italic trait NSFont *boldItalicFont = [[NSFontManager sharedFontManager] convertFont:boldFont toHaveTrait:NSFontItalicTrait]; [_label setFont:boldItalicFont]; [_label setTextColor:[NSColor colorWithSRGBRed:0.0 green:0.5 blue:0.0 alpha:1.0]]; // attach label to the damn window [[self contentView] addSubview: _label]; return self; } -(BOOL)windowShouldClose:(id)sender { return YES; } -(void) setLabelText:(NSString *)newText { [_label setStringValue: newText]; } @end #endif /* MyEventWindow_h */ Then in the main file I try to handle event loop manually: // // main.m #import <Cocoa/Cocoa.h> #import "MyEventWindow.h" NSString* NSEventTypeToNSString(NSEventType eventType); NSString* NSEventModifierFlagsToNSString(NSEventModifierFlags modifierFlags); int main(int argc, char* argv[]) { @autoreleasepool { [NSApplication sharedApplication]; MyEventWindow* eventWindow = [[MyEventWindow alloc] init]; [eventWindow makeKeyAndOrderFront:nil]; NSString* log = [NSString string]; // my own message loop [NSApp finishLaunching]; while (true) { @autoreleasepool { NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate: [NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES]; log = [NSString stringWithFormat:@"Event [type=%@ location={%d, %d} modifierFlags={%@}]", NSEventTypeToNSString([event type]), (int)[event locationInWindow].x, (int)[event locationInWindow].y, NSEventModifierFlagsToNSString([event modifierFlags])]; //NSLog(@"log: %@", log); [eventWindow setLabelText: log]; [NSApp sendEvent:event]; //[NSApp updateWindows]; // redundant? } } } return 0; } NSString* NSEventTypeToNSString(NSEventType eventType) { switch (eventType) { case NSEventTypeLeftMouseDown: return @"LeftMouseDown"; case NSEventTypeLeftMouseUp: return @"LeftMouseUp"; case NSEventTypeRightMouseDown: return @"RightMouseDown"; case NSEventTypeRightMouseUp: return @"RightMouseUp"; case NSEventTypeMouseMoved: return @"MouseMoved"; case NSEventTypeLeftMouseDragged: return @"LeftMouseDragged"; case NSEventTypeRightMouseDragged: return @"RightMouseDragged"; case NSEventTypeMouseEntered: return @"MouseEntered"; case NSEventTypeMouseExited: return @"MouseExited"; case NSEventTypeKeyDown: return @"KeyDown"; case NSEventTypeKeyUp: return @"KeyUp"; case NSEventTypeFlagsChanged: return @"FlagsChanged"; case NSEventTypeAppKitDefined: return @"AppKitDefined"; case NSEventTypeSystemDefined: return @"SystemDefined"; case NSEventTypeApplicationDefined: return @"ApplicationDefined"; case NSEventTypePeriodic: return @"Periodic"; case NSEventTypeCursorUpdate: return @"CursorUpdate"; case NSEventTypeScrollWheel: return @"ScrollWheel"; case NSEventTypeTabletPoint: return @"TabletPoint"; case NSEventTypeTabletProximity: return @"TabletProximity"; case NSEventTypeOtherMouseDown: return @"OtherMouseDown"; case NSEventTypeOtherMouseUp: return @"OtherMouseUp"; case NSEventTypeOtherMouseDragged: return @"OtherMouseDragged"; default: return [NSString stringWithFormat:@"%lu", eventType]; } } NSString* NSEventModifierFlagsToNSString(NSEventModifierFlags modifierFlags) { NSString* result = @""; if ((modifierFlags & NSEventModifierFlagCapsLock) == NSEventModifierFlagCapsLock) result = [result stringByAppendingString:@"CapsLock, "]; if ((modifierFlags & NSEventModifierFlagShift) == NSEventModifierFlagShift) result = [result stringByAppendingString:@"NShift, "]; if ((modifierFlags & NSEventModifierFlagControl) == NSEventModifierFlagControl) result = [result stringByAppendingString:@"Control, "]; if ((modifierFlags & NSEventModifierFlagOption) == NSEventModifierFlagOption) result = [result stringByAppendingString:@"Option, "]; if ((modifierFlags & NSEventModifierFlagCommand) == NSEventModifierFlagCommand) result = [result stringByAppendingString:@"Command, "]; if ((modifierFlags & NSEventModifierFlagNumericPad) == NSEventModifierFlagNumericPad) result = [result stringByAppendingString:@"NumericPad, "]; if ((modifierFlags & NSEventModifierFlagHelp) == NSEventModifierFlagHelp) result = [result stringByAppendingString:@"Help, "]; if ((modifierFlags & NSEventModifierFlagFunction) == NSEventModifierFlagFunction) result = [result stringByAppendingString:@"Function, "]; return result; } in main I added a second @autoreleasepool inside the while loop it seemed to decrease memory usage significanly, however if I keep moving my mouse a lot the memory usage will still increase. I don't think this should be happening since the labelText is being destroying and recreated each iteration, is something wrong with my code? Why do I have a memory leak here? Any feedback regarding the code is also appreciated Cheers
1
0
332
Sep ’24
How can I fix CLIENT ERROR: TUINSRemoteViewController does not override -viewServiceDidTerminateWithError:
I created a simple application which displays a window with a sample text and I'm supposed to use an alert when the user chooses to close the application, if he presses ok in the alert the application will close, if he presses cancel it goes on. So pretty simple code, I have a window class: // // MyWindow.h // AppTest // // Created by sanya on 11/09/24. // #ifndef MyWindow_h #define MyWindow_h @interface Window : NSWindow { NSTextField* label; } - (instancetype)init; - (BOOL)windowShouldClose:(id)sender; @end @implementation Window -(instancetype)init { label = [[[NSTextField alloc] initWithFrame:NSMakeRect(5, 100, 290, 100)] autorelease]; [label setStringValue:@"Hello, World!"]; [label setBezeled:NO]; [label setDrawsBackground:NO]; [label setEditable:YES]; [label setSelectable:YES]; [label setTextColor:[NSColor colorWithSRGBRed:0.0 green:0.5 blue:0.0 alpha:1.0]]; [label setFont:[[NSFontManager sharedFontManager] convertFont:[[NSFontManager sharedFontManager] convertFont:[NSFont fontWithName:[[label font] fontName] size:45] toHaveTrait:NSFontBoldTrait] toHaveTrait:NSFontItalicTrait]]; [super initWithContentRect:NSMakeRect(0, 0, 300, 300) styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; [self setTitle:@"Hello world (label)"]; [[self contentView] addSubview:label]; [self center]; [self setIsVisible:YES]; return self; } - (BOOL)windowShouldClose:(id)sender { BOOL bClose = NO; CFOptionFlags responseFlags = 0; // Display the alert CFUserNotificationDisplayAlert( 0, kCFUserNotificationNoteAlertLevel, NULL, NULL, NULL, CFSTR("Alert Title"), CFSTR("This is a message displayed in the alert."), CFSTR("OK"), CFSTR("Cancel"), NULL, &responseFlags ); if (responseFlags == kCFUserNotificationDefaultResponse) { NSLog(@"User clicked OK"); bClose = YES; } else if (responseFlags == kCFUserNotificationAlternateResponse) { NSLog(@"User clicked Cancel"); } if( bClose ) [NSApp terminate:sender]; return bClose; } @end #endif /* MyWindow_h */ And in the main function I just initialize it: int main(int argc, const char * argv[]) { [NSApplication sharedApplication]; [[[[Window alloc] init] autorelease] makeMainWindow]; [NSApp run]; } It seems to work but if click 'Cancel' on the dialog , xcode gives me the following warning: CLIENT ERROR: TUINSRemoteViewController does not override -viewServiceDidTerminateWithError: and thus cannot react to catastrophic errors beyond logging them So i'm obviously not doing this in the correct way, how can I fix this? Also, any feedback on this code as a whole is highly appreciated.
1
1
361
Sep ’24
Cannot enable Network Extensions - Objective-C
So I wanted to get my hands dirty with objective-c so I decided to create a project to list all outbound traffic, after digging a little I found that I could use the Network Extension API. I created a simple command line project with xcode and tried to load this extension but for some reason I can't get it to work. I don't have a developer license yet and I'm not sure if it has anything to do with the problem I'm facing. This is just some test code so there are 2 free functions, one for loading the system extension and another for checking its status: // activates the extension? BOOL toggleNetworkExtension(NSUInteger action) { BOOL toggled = NO; __block BOOL wasError = NO; __block NEFilterProviderConfiguration* config = nil; dispatch_semaphore_t semaphore = 0; semaphore = dispatch_semaphore_create(0); NSLog(@"toggling the network extension"); [NEFilterManager.sharedManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) { if(nil != error) { wasError = YES; NSLog(@"loadFromPreferencesWithCompletionHandler error"); } dispatch_semaphore_signal(semaphore); }]; NSLog(@"waiting for the network extension configuration..."); if(YES == wasError) goto fail; NSLog(@"loaded current filter configuration for the network extension"); if(1 == action) { NSLog(@"activating network extension...") ; if(nil == NEFilterManager.sharedManager.providerConfiguration) { config = [[NEFilterProviderConfiguration alloc] init]; config.filterPackets = NO; config.filterSockets = YES; NEFilterManager.sharedManager.providerConfiguration = config; } NEFilterManager.sharedManager.enabled = YES; } else { NSLog(@"deactivating the network extension..."); NEFilterManager.sharedManager.enabled = NO; } { [NEFilterManager.sharedManager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) { if(nil != error) { wasError = YES; NSLog(@"saveToPreferencesWithCompletionHandler error!"); } dispatch_semaphore_signal(semaphore); }]; } NSLog(@"waiting for network extension configuration to save..."); if(YES == wasError) goto fail; NSLog(@"saved current filter configuration for the network extension"); toggled = YES; fail: return toggled; } Then there's this function to check if the extension is enabled which for some reason always returns false. BOOL isNetworkExtensionEnabled(void) { __block BOOL isEnabled = NO; dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); [NEFilterManager.sharedManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error with loadFromPreferencesWithCompletionHandler"); } else { isEnabled = NEFilterManager.sharedManager.enabled; } dispatch_semaphore_signal(semaphore); }]; return isEnabled; } Is something wrong is this code or is this related to entitlements or the developer license? As a side note I have already disabled SIP not sure if it matters in this case. Thanks in advance.
1
0
415
Sep ’24