Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically adding "Open Recent' menu to context popup menu

I have a non-document Cocoa application with a menubar icon and status menu. I've added an "Open Recent" menu to the status menu in Interface Builder. Populating the menu works just fine:

[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:
            [NSURL fileURLWithPath:filename]]

Now I would also like to add a second "Open Recent" menu to a context popup menu. How would I create the menu programmatically so that it gets populated with entries automatically as it does for the version in the status menu?

I tried creating a copy of the one in the status menu, but it does not get populated. I assume that NSDocumentController is not aware of the menu (frankly, I don't know how it knows about the one in the status menu).

like image 733
Mark Avatar asked Nov 04 '22 15:11

Mark


1 Answers

For reference, the best documentation on the inner workings of the Open Recent menu that I found is this: http://lapcatsoftware.com/blog/2007/07/10/working-without-a-nib-part-5-open-recent-menu/

Unfortunately, it doesn’t help much with this, because even if you create the menu like this, it will be ignored by NSDocumentController. The menu must exist in the main menu before applicationDidFinishLaunching: call, otherwise it won’t be picked up — and consequently, duplicate ones are ignored too.

What I ended up doing, and what seems to work so far, is this:

The first idea was to pick the corresponding NSMenu from the main menu and attach it into other menus as well, hoping that reference counting will make this work. No such luck, setSubmenu throws if the submenu is already in another NSMenuItem.

So I “reparent” the submenu instead — when I need to show it in another menu, I remove it from the main menu’s Open Recent item and set it as submenu in the new menu. Later, I move it back. It’s an ugly hack, of course, but it gets the job done.

like image 129
Václav Slavík Avatar answered Nov 18 '22 00:11

Václav Slavík