contextual menu item are not getting activated - cocoa

I am having a problem. My contextual menu is getting displayed but the menu items are not activated.
so my new code for displaying the menu is as follows:
NSMenu *defMenu = [[[NSMenu alloc] initWithTitle:#"default Contextual Menu"] autorelease];
[defMenu insertItemWithTitle:#"Open" action:#selector(openFile) keyEquivalent:#"" atIndex:0];
[defMenu insertItemWithTitle:#"Delete" action:#selector(deleteFile) keyEquivalent:#"" atIndex:1];
return defMenu;
and function declaratons of deleteFile and openFile are as follows:
-(int)openFile;
-(int)deleteFile;
and i am calling my contextual menu as follows:
-(void)doSingleClick
{
if([[NSApp currentEvent] modifierFlags] & NSControlKeyMask)
{
NSLog(#"control clicked.......");
[NSMenu popUpContextMenu:[self defaultMenu] withEvent:[NSApp currentEvent] forView:tableView];
return;
}
}
my contextual menu items are all shaded and cannot be clicked. Please can you tell where i am going wrong.
Thanks

Your openFile: method takes an int as a parameter. Since insertItemWithTitle:action:withObject:keyEquivalent:atIndex: takes an object, the selector you give it must also take an object.
You can use NSNumber to wrap your int as an object, and simply change your openFile: method to take an NSNumber rather than an int. Like so:
[defMenu insertItemWithTitle:#"Open" action:#selector(openFile:) withObject:[NSNumber numberWithInt:5] keyEquivalent:#"" atIndex:0];
- (void)openFile:(NSNumber *)fileNumber {
int rowClicked = [fileNumber intValue];
// Do whatever your old method did here
}
EDIT: To answer your updated question:
The reason your menu items are disabled is that you've only told them what method name to call. You never told the items on which object instance those methods should actually be called. To fix this, you need to set the items' target:
NSMenuItem *openItem = [defMenu insertItemWithTitle:#"Open" action:#selector(openFile:) withObject:[NSNumber numberWithInt:5] keyEquivalent:#"" atIndex:0];
[openItem setTarget:self];
And so forth for each item you've got.

You can't define such an action. An action is a method that takes one object argument representing the object that triggered the action message. You need to create an action in your controller that calls through to the underlying openFile: method.

Related

How to configure content for NSPopUpButton

I have a NSPopUpButton configured with bindings and coredata. Everything is working perfectly, however I would like to add a item that implements an action to "edit the list", like
Item 1
Item 2
Item 3
Item 4
------
Edit List..
Is this Possible to do with Bindings?
I think that the answer is NO, at least not completely. I thought I would provide the content to the button programatically and maintain bindings for the Selected Value , so this is what I came up with
- (void)updateSectorPopupItems
{
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"Sector"];
NSSortDescriptor *sortPosition = [[NSSortDescriptor alloc] initWithKey:#"position" ascending:YES];
[request setSortDescriptors:#[sortPosition]];
NSError *anyError = nil;
NSArray *fetchObjects = [_gdcManagedObjectContext executeFetchRequest:request
error:&anyError];
if (fetchObjects == nil) {
DLog(#"Error:%#", [anyError localizedDescription]);
}
NSMutableArray *sectorNames = [NSMutableArray array];
for (NSManagedObject *sector in fetchObjects) {
[sectorNames addObject:[sector valueForKey:#"sectorCatagory"]];
}
[_sectorPopUpBotton addItemsWithTitles:sectorNames];
NSInteger items = [[_sectorPopUpBotton menu] numberOfItems];
if (![[_sectorPopUpBotton menu] itemWithTag:1] ) {
NSMenuItem *editList = [[NSMenuItem alloc] initWithTitle:#"Edit List..." action:#selector(showSectorWindow:) keyEquivalent:#""];
[editList setTarget:self];
[editList setTag:1];
[[_sectorPopUpBotton menu] insertItem:editList atIndex:items];
}
A couple of problems I'm having with this
1) When adding the Menu Item using
[_sectorPopUpBotton menu] insertItem:editList atIndex:items];
no matter what value is entered in atIndex, the item always appears at the top of the Menu list.
2) I just want the "Edit List..." menuitem to initiate the action, how do I prevent this from being selected as a value?
You might as well do that using an NSMenuDelegate method.
Actually in this way you can also keep the bindings for getting the NSPopUpButton content objects (in your case from the NSArrayController bound to the CoreData stack).
1) Set an object as delegate for the NSPopUpButton internal menu, you can do that in the Interface Builder by drilling down the NSPopUpButton to reveal its internal menu. Select it and then set its delegate in the Connections Inspector panel to the object you have designated to this task. As such delegate you might for example provide the same ViewController object which manages the view where the NSPopUpButton exists.
You'll then need to have the object provided as delegate adhere to the NSMenuDelegate informal protocol.
2) Implement the NSMenuDelegate method menuNeedsUpdate: there you'll add the NSmenuItem(s) (and eventually separators) you want to provide in addition to those already fetched by the NSPopButton's bindings.
An example code would be:
#pragma mark NSMenuDelegate
- (void)menuNeedsUpdate:(NSMenu *)menu {
if ([_thePopUpButton menu] == menu && ![[menu itemArray] containsObject:_editMenuItem]) {
[menu addItem:[NSMenuItem separatorItem]];
[menu addItem:_editMenuItem];
}
}
In this example the _editMenuItem is an NSMenuItem property provided by the object implementing this NSMenuDelegate method. Eventually it could be something as this:
_editMenuItem = [[NSMenuItem alloc] initWithTitle:#"Edit…" action:#selector(openEditPopUpMenuVC:) keyEquivalent:#""];
// Eventually also set the target for the action: where the selector is implemented.
_editMenuItem.target = self;
You'll then implement the method openEditPopUpMenuVC: to present to the user the view responsible for editing the content of the popUpButton (in your case the CoreData objects provided via bindings).
The only problem I haven't yet solved with this approach is that when getting back from the view where the edit happens, the NSPopUpButton will have the new item "Edit…" selected, rather than another "valid" one, which is very inconvenient.

Execute an action from a text field ONLY when enter is pressed [duplicate]

I have two NSTextFields: textFieldUserID and textFieldPassword.
For textFieldPassword, I have a delegate as follows:
- (void)controlTextDidEndEditing:(NSNotification *)aNotification
This delegate gets called when textFieldPassword has focus and I hit the enter key. This is exactly what I want.
My problem is that controlTextDidEndEditing also gets called when textFieldPassword has focus and I move the focus to textFieldUserID (via mouse or tab key). This is NOT what I want.
I tried using controlTextDidChange notification (which is getting called once per key press) but I was unable to figure out how to detect enter key ( [textFieldPassword stringValue] does not include the enter key). Can someone please help me figure this one out?
I also tried to detect if textFieldUserID was a firstResponder, but it did not work for me. Here is the code I tried out:
if ( [[[self window] firstResponder] isKindOfClass:[NSTextView class]] &&
[[self window] fieldEditor:NO forObject:nil] != nil ) {
NSTextField *field = [[[self window] firstResponder] delegate];
if (field == textFieldUserID) {
// do something based upon first-responder status
NSLog(#"is true");
}
}
I sure could use some help here!
If I understood you correctly, you could set an action for the password text field and tell the field to send its action only when the user types Return. Firstly, declare and implement an action in the class responsible for the behaviour when the user types Return on the password field. For example:
#interface SomeClass …
- (IBAction)returnOnPasswordField:(id)sender;
#end
#implementation SomeClass
- (IBAction)returnOnPasswordField:(id)sender {
// do something
}
#end
Making the text field send its action on Return only, and linking the action to a given IBAction and target, can be done either in Interface Builder or programatically.
In Interface Builder, use the Attributes Inspector, choose Action: Sent on Enter Only, and then link the text field action to an IBAction in the object that implements it, potentially the File’s Owner or the First Responder.
If you’d rather do it programatically, then:
// Make the text field send its action only when Return is pressed
[passwordTextFieldCell setSendsActionOnEndEditing:NO];
// The action selector according to the action defined in SomeClass
[passwordTextFieldCell setAction:#selector(returnOnPasswordField:)];
// someObject is the object that implements the action
[passwordTextFieldCell setTarget:someObject];
[passwordTextFieldCell setTarget:self];
[passwordTextFieldCell setAction:#selector(someAction:)];
- (void) someAction{
//handle
}

Cocoa QuickLook initiated by NSTableView Cell

I have an NSTableView that contains 2 different Columns - one is an NSImageCell that shows a file icon, and the second is a custom subclass of NSTextFieldCell that contains a quick look button on the right of the text. When I click the Quick Look button, the following code is invoked:
[[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
This does it's job and shows the blank Quick Look panel saying "No Items Selected." After I did a bit of research on the internet, I implemented a custom NSTableView subclass to be the Delegate and Data Source for the Quick Look panel. I get the notification that Quick Look asks if I want to be the delegate, and I respond with return YES. Even though I implement all methods in both QLPreviewPanelDataSource and QLPreviewPanelDelegate, at runtime I get this error on the console:
2010-12-24 15:32:17.235 BackMeUp[4763:80f] clicked: ~/Desktop/HUDTape.mov
2010-12-24 15:32:17.489 BackMeUp[4763:80f] [QL] QLError(): -[QLPreviewPanel setDelegate:] called while the panel has no controller - Fix this or this will raise soon.
See comments in QLPreviewPanel.h for -acceptsPreviewPanelControl:/-beginPreviewPanelControl:/-endPreviewPanelControl:.
2010-12-24 15:32:17.490 BackMeUp[4763:80f] [QL] QLError(): -[QLPreviewPanel setDataSource:] called while the panel has no controller - Fix this or this will raise soon.
See comments in QLPreviewPanel.h for -acceptsPreviewPanelControl:/-beginPreviewPanelControl:/-endPreviewPanelControl:.
2010-12-24 15:32:17.491 BackMeUp[4763:80f] We can now receive QL Events.
2010-12-24 15:32:18.291 BackMeUp[4763:80f] -[NSPathStore2 stringValue]: unrecognized selector sent to instance 0x5ecb10
2010-12-24 15:32:18.292 BackMeUp[4763:80f] -[NSPathStore2 stringValue]: unrecognized selector sent to instance 0x5ecb10
And the Quick Look panel does not show up, which I find rather odd. The first line above is just that I know the cell has been clicked. Anyways, here is the .m file of the custom table view subclass:
//
// BackupListTableView.m
// BackMeUp
//
// Created by Tristan Seifert on 12/24/10.
// Copyright 2010 24/7 Server. All rights reserved.
//
#import "BackupListTableView.h"
#implementation BackupListTableView
- (void) awakeFromNib {
}
// Quick Look Delegates
- (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel *)panel;
{
[QLPreviewPanel sharedPreviewPanel].delegate = self;
[QLPreviewPanel sharedPreviewPanel].dataSource = self;
NSLog(#"We can now receive QL Events.");
return YES;
}
- (void)beginPreviewPanelControl:(QLPreviewPanel *)panel
{
// This document is now responsible of the preview panel
// It is allowed to set the delegate, data source and refresh panel.
[QLPreviewPanel sharedPreviewPanel].delegate = self;
[QLPreviewPanel sharedPreviewPanel].dataSource = self;
}
- (void)endPreviewPanelControl:(QLPreviewPanel *)panel
{
// This document loses its responsisibility on the preview panel
// Until the next call to -beginPreviewPanelControl: it must not
// change the panel's delegate, data source or refresh it.
return;
}
// Quick Look panel data source
- (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel *)panel
{
return 1;
}
- (id <QLPreviewItem>)previewPanel:(QLPreviewPanel *)panel previewItemAtIndex:(NSInteger)index
{
int selectedRow = [self selectedRow];
return [NSURL URLWithString:[[[self dataSource] tableView:self objectValueForTableColumn:fileColumn row:selectedRow] stringValue]];
}
// Quick Look panel delegate
- (BOOL)previewPanel:(QLPreviewPanel *)panel handleEvent:(NSEvent *)event
{
// redirect all key down events to the table view
return NO;
}
// This delegate method provides the rect on screen from which the panel will zoom.
- (NSRect)previewPanel:(QLPreviewPanel *)panel sourceFrameOnScreenForPreviewItem:(id <QLPreviewItem>)item
{
NSRect iconRect = [self rectOfColumn:1];
/*
// check that the icon rect is visible on screen
NSRect visibleRect = [self visibleRect];
// convert icon rect to screen coordinates
iconRect = [self convertRectToBase:iconRect];
iconRect.origin = [[self window] convertBaseToScreen:iconRect.origin];
*/
return iconRect;
}
// This delegate method provides a transition image between the table view and the preview panel
- (id)previewPanel:(QLPreviewPanel *)panel transitionImageForPreviewItem:(id <QLPreviewItem>)item contentRect:(NSRect *)contentRect
{
int selectedRow = [self selectedRow];
NSImage *fileIcon = [[NSWorkspace sharedWorkspace] iconForFile:[[[self dataSource] tableView:self objectValueForTableColumn:fileColumn row:selectedRow] stringValue]];
return fileIcon;
}
#end
Thanks for any help.
The documentation isn't the best for this, since it's a new feature that was added in 10.6. (Well, there is obviously the class and protocol references, but in my experience, I've always found the Companion Guides to be more helpful in understanding how the objects are intended to be used in a real-world scenario).
The QLPreviewPanelController Protocol Reference defines 3 methods:
QLPreviewPanelController Protocol Reference
The Quick Look preview panel shows previews for items provided by the first object in the responder chain that implements the methods in this protocol. You typically implement these methods in your window controller or delegate. You should never try to modify preview panel state if you’re not controlling the panel.
- (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel *)panel;
- (BOOL)beginPreviewPanelControl:(QLPreviewPanel *)panel;
- (void)endPreviewPanelControl:(QLPreviewPanel *)panel;
I'm guessing that your code should look like this:
- (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel *)panel
{
return YES;
}
You shouldn't be doing anything in that method besides returning YES. acceptsPreviewPanelControl: is sent to every object in the responder chain until something returns YES. By returning YES, that object effectively becomes "the controller". The latter 2 methods are called on the controller object after it returns YES from the first method. So you should only be setting the delegate and datasource in the beginPreviewPanelControl: method (at which time you will be regarded as the current controller).
- (void)beginPreviewPanelControl:(QLPreviewPanel *)panel
{
// This document is now responsible of the preview panel
// It is allowed to set the delegate, data source and refresh panel.
[QLPreviewPanel sharedPreviewPanel].delegate = self;
[QLPreviewPanel sharedPreviewPanel].dataSource = self;
NSLog(#"We can now receive QL Events.");
}
First:
-acceptsPreviewPanelControl should only return YES and not try to set delegate and datasource.
Then, the problem is that you get an exception breaking the panel:
2010-12-24 15:32:18.291 BackMeUp[4763:80f] -[NSPathStore2 stringValue]: unrecognized selector sent to instance 0x5ecb10
The exception is very likely caused by these invocations:
[[[self dataSource] tableView:self objectValueForTableColumn:fileColumn row:selectedRow] stringValue]
Very likely, [[self dataSource] tableView:self objectValueForTableColumn:fileColumn row:selectedRow] is a file path (a NSPathStore instance which is a subclass of NSString) so it does not respond to -stringValue
So replace:
[NSURL URLWithString:[[[self dataSource] tableView:self objectValueForTableColumn:fileColumn row:selectedRow] stringValue]]
by:
[NSURL fileURLWithPath:[[self dataSource] tableView:self objectValueForTableColumn:fileColumn row:selectedRow]]
Also remove the call to -stringValue in transitionImageForPreviewItem.
As a side note, it seems to be suboptimal to load the image at each call of transitionImageForPreviewItem. I suppose you already have the image computed elsewhere (displayed in your table view), try to use it.

How do I set the sender on a NSMenuItem's action?

The Apple documentation says that the sender passed to the NSMenuItem's action can be set to some custom object, but I can't seem to figure out how to do this. Is there a method I'm not seeing someplace in the documentation?
I'm not sure what piece of documentation you're referring to (a link would help).
You can use the -setRepresentedObject: method of NSMenuItem to associate an arbitrary object with a menu item:
//assume "item" is an NSMenuItem object:
NSString* someObj = #"Some Arbitrary Object";
[item setRepresentedObject:someObj];
[item setAction:#selector(doSomething:)];
Then when the menu item sends its action message you can obtain the object:
- (IBAction)doSomething:(id)sender
{
NSLog(#"The menu item's object is %#",[sender representedObject]);
}

Is there an equivalent technique in Cocoa for the synchronous TrackPopupMenu in Windows?

In response to a rightMouse event I want to call a function that displays a context menu, runs it, and responds to the selected menu item. In Windows I can use TrackPopupMenu with the TPM_RETURNCMD flag.
What is the easiest way to implement this in Cocoa? It seems NSMenu:popUpContextMenu wants to post an event to the specified NSView. Must I create a dummy view and wait for the event before returning? If so, how do I "wait" or flush events given I am not returning to my main ?
The 'proper' way to do this in Cocoa is to have your menu item's target and action perform the required method. However, if you must do it within your initial call, you can use [NSView nextEventMatchingMask:] to continually fetch new events that interest you, handle them, and loop. Here's an example which just waits until the right mouse button is released. You'll probably want to use a more complex mask argument, and continually call [NSView nextEventMatchingMask:] until you get what you want.
NSEvent *localEvent = [[self window] nextEventMatchingMask: NSRightMouseUpMask];
I think you'll find the 'proper' way to go much easier.
It appears that popUpContextMenu is already synchronous. Since I didn't see a way to use NSMenu without having it send a notification to an NSView I came up with a scheme that instantiates a temporary NSView. The goal is to display a popup menu and return the selected item in the context of a single function call. Following is code snippets of my proposed solution:
// Dummy View class used to receive Menu Events
#interface DVFBaseView : NSView
{
NSMenuItem* nsMenuItem;
}
- (void) OnMenuSelection:(id)sender;
- (NSMenuItem*)MenuItem;
#end
#implementation DVFBaseView
- (NSMenuItem*)MenuItem
{
return nsMenuItem;
}
- (void)OnMenuSelection:(id)sender
{
nsMenuItem = sender;
}
#end
// Calling Code (in response to rightMouseDown event in my main NSView
void HandleRButtonDown (NSPoint pt)
{
NSRect graphicsRect; // contains an origin, width, height
graphicsRect = NSMakeRect(200, 200, 50, 100);
//-----------------------------
// Create Menu and Dummy View
//-----------------------------
nsMenu = [[[NSMenu alloc] initWithTitle:#"Contextual Menu"] autorelease];
nsView = [[[DVFBaseView alloc] initWithFrame:graphicsRect] autorelease];
NSMenuItem* item = [nsMenu addItemWithTitle:#"Menu Item# 1" action:#selector(OnMenuSelection:) keyEquivalent:#""];
[item setTag:ID_FIRST];
item = [nsMenu addItemWithTitle:#"Menu Item #2" action:#selector(OnMenuSelection:) keyEquivalent:#""];
[item setTag:ID_SECOND];
//---------------------------------------------------------------------------------------------
// Providing a valid windowNumber is key in getting the Menu to display in the proper location
//---------------------------------------------------------------------------------------------
int windowNumber = [(NSWindow*)myWindow windowNumber];
NSRect frame = [(NSWindow*)myWindow frame];
NSPoint wp = {pt.x, frame.size.height - pt.y}; // Origin in lower left
NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined
location:wp
modifierFlags:NSApplicationDefined
timestamp: (NSTimeInterval) 0
windowNumber: windowNumber
context: [NSGraphicsContext currentContext]
subtype:0
data1: 0
data2: 0];
[NSMenu popUpContextMenu:nsMenu withEvent:event forView:nsView];
NSMenuItem* MenuItem = [nsView MenuItem];
switch ([MenuItem tag])
{
case ID_FIRST: HandleFirstCommand(); break;
case ID_SECOND: HandleSecondCommand(); break;
}
}
There is no direct equivalent, except in Carbon, which is deprecated.
For detecting the right-click, follow these instructions. They ensure that you will properly detect right-clicks and right-holds and display the menu when you should and not display it when you shouldn't.
For following events, you might try [[NSRunLoop currentRunLoop] runMode:NSEventTrackingRunLoopMode untilDate:[NSDate distantFuture]]. You will need to call this repeatedly until the user has chosen one of the menu items.
Using nextEventMatchingMask:NSRightMouseUpMask will not work in all, or even most, cases. If the user right-clicks on your control, the right mouse button will go up immediately after it goes down, without selecting a menu item, and the menu item selection will probably (though not necessarily) happen through the left mouse button. Better to just run the run loop repeatedly until the user either selects something or dismisses the menu.
I don't know how to tell that the user has dismissed the menu without selecting anything.

Resources