how to implement "show recents" item on OS 10.9 and later - macos

I notice on Mac, every app on docker, when it's not opened and ctrl click it, there will be a pop-up menu, inside has a menu item called "show recents", when open the app this item will become "show all windows". I want to know how to make it work cuz right now, when I click it on my own app, it has nothing to show.
I have tested using doc controller and use noteNewRecentDocumentURL: method, but still, both "open recent" item in "file" and "show recents" in docker, it doesn't show my url I just added.

I do not know, where you click on the app to show the menu. The recent documents list is shown
in the app's File menu in the submenu Open Recent
in the dock menu for the app as a list with one item per document
likely at some other places related to the app
However where it is shown, the list is automatically managed by [NSDocumentController sharedDocumentController], which is added to the project template for document-based applications. If you do not have a document-based application you should re-check, whether this would be the better choice. But you can use [NSDocumentController sharedDocumentController] in a non-document-based application as well:
In some situations, it is worthwhile to subclass NSDocumentController in non-NSDocument-based applications to get some of its features. For example, the NSDocumentController management of the Open Recent menu is useful in applications that don’t use subclasses of NSDocument.
Documentation
There is a section Managing the Open Recent Menu containing the description of the method -noteNewRecentDocumentURL: in the documentation of NSDocumentController. You have to send this message to the shared instance,
whenever you want to add an item to the recent docs list:
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:theURLOfTheDocYourAppOpens];
Please note:
Applications not based on NSDocument must also implement the application:openFile: method in the application delegate to handle requests from the Open Recent menu command.
If you do not want to use the document controller, you have to maintain the list yourself and add it to the different locations manually. You can start here. I do not recommend that.

Here's code for use with Xamarin.Mac.
// Add the file to the menu. Note creation of file url.
void AddFileToOpenRecentMenu(string filePath)
{
var fileUrl = NSUrl.FromFilename(filePath);
NSDocumentController.SharedDocumentController.NoteNewRecentDocumentURL(fileUrl);
}
// Open the file selected from the menu (in AppDelegate.cs)
[Export("application:openFile:")]
public override bool OpenFile(NSApplication sender, string filename)
{
var keepFileInMenu = ProcessFile(filename);
return keepFileInMenu;
}

Related

How can I make my (non-document-based) app respond to openFile:withApplication:?

I have an app, which is a single-window, non-document-based app.
I want to make it respond to NSWorkspace-openFile:withApplication:, but only when the path is to a folder, and also implement the File->Open menu. I'm having trouble tracking down how to do this (without becoming a document-based application).
You have to configure your NSOpenPanel to accept directories:
[myOpenPanel setCanChooseDirectories:YES];
Just check what action the Open menu item is connected to in Interface Builder. If I remember correctly, it would be connected to the "First Responder" object and the method open:. Is that right?
In this case, just implement the open: method in your AppDelegate class. (To understand why the method goes to the delegate, read about "nil-targeted actions" in Hillegass' book, or here: http://www.cocoadev.com/index.pl?NilTargetedAction. The thing to remember is that a control connected to "First Responder" in IB is actually IB's way of denoting that the target is nil.)
Note that you will have to implement the open panel yourself using NSOpenPanel -- see some code for example here: NSOpenPanel setAllowedFileTypes
If this is the same thing as that you're doing in openFile:withApplication:, you will probably want to create a common private method and call that method from both openFile:withApplication: and open:.

How does Xcode setup a document based application?

I am learning Cocoa and my understanding from reading the documentation is that when an application starts the following happens:
A shared application instance is created.
The main nib file is looked up from the applications property list so that the application knows which nib to load.
the run loop is started.
This is fine and makes sense for s single windowed application however I am confused by what xcode does when a document based application is created.
In this case there are two nib files; the first contains the application menu and the second contains the window which represents the NSDocument subclass. when I run the application a new document window is opened automatically.
Based on my understanding of how the application works outlined above I don't understand how my application knows to open the document window once the menu nib has been looked up from the property list. There is no code generated to do this as far as I can see (except for the windowNibName method but where is this called from?)
Can anyone tell me what xcode does differently so that the application knows that it is document based and therefore needs to open a document window?
Update:
What I am trying to understand is how Xcode knows how to do something different if my application is set up as a document based application rather than a single window application. As far as I am aware there is no setting to specify this and Xcode doesn't appear to generate any code to give this different behaviour.
From reading the documents over the last couple of days I think I know how this works but am not sure:
_NSApplication_has a delegate method applicationOpensUntitledFile which is called by the applications delegate.
NSDocumentController is set as the applications delegate by default and the default implementation looks for the presence of the CFBundledTypeInfo to determine if the document is document based or not and responds as is appropriate for the application (I.E. YES for document based application and NO for single window applications).
The majority of the time when a single window application is created the application delegate is replaced by a custom AppController anyway which usually wont contain a definition for the applicationOpenUntitledFile method as it is not appropriate for the type of application.
Hopefully any Cocoa experts can confirm if my understanding is correct or if I am barking up the wrong tree.
When you create a document-based application, you get a few things:
A subclass of NSDocument
A new xib file for this document, in addition to MainMenu.xib
A CFBundleDocumentTypes entry in Info.plist, which tells the app about your NSDocument subclass
When your app opens, the shared NSDocumentController will create a new untitled document using the CFBundleDocumentTypes information.
For more information, read The Document-Based Application Project Template and the rest of the document-based applications guide.
I assume your right. If you create a non based document application, add the document types informations in the -Info.plist and set the delegate of NSApplication in the main.m as following
int main(int argc, const char * argv[])
{
[[NSApplication sharedApplication] setDelegate:[NSDocumentController sharedDocumentController]];
[[NSBundle mainBundle] loadNibNamed:#"MainMenu" owner:NSApp topLevelObjects:nil];
[NSApp run];
}
The behaviour seems to be the same as the the default Document-Based Application template.
No, your assumption is not right, look at the implementation of GNUstep version, in the NSApplication's finishLaunching method:
NSDocumentController *sdc;
sdc = [NSDocumentController sharedDocumentController];
if ([[sdc documentClassNames] count] > 0)
{
didAutoreopen = [sdc _reopenAutosavedDocuments];
}
So it create a instance of NSDocumentController automatically.

Preventing the "Save on Exit" dialogue on exit of a Cocoa Document Application

Hi
I have a Cocoa document based application that I have been building, that allows you to open seperate views and interact with a webview component. However, when ever you have interacted with it, and then go to close the application, a message comes down saying:
"Do you want to save the changes you made in the document “Untitled”?
"Your changes will be lost if you don’t save them."
I wish to make it that when my application is closed, this message is not shown. I do not need any auto-saves or saving options. How do I prevent this message been shown and disable it?
Thanks in advance for any help and support.
Sam
Recently I had the exact same wish to prevent the save dialog from showing up. What I did is put the following method in my custom document class that inherits NSDocument
-(BOOL)isDocumentEdited {
return NO;
}

How do I dismiss an NSPanel when creating or opening a new document?

I am working on a document-based Cocoa application. At startup, the user is presented with a "welcome panel" (of type NSPanel) with buttons for common actions like "Create New Document" and "Open Existing Document". These actions are linked to the first responder's newDocument: and openDocument: actions, respectively, just like the matching items in the File menu.
Everything works as expected...with three caveats:
The welcome panel is not dismissed when creating or opening a new document.
Document windows do not have focus when they are created.
Open document windows do not have the open file represented in the window title bar; likewise, new document windows do not get created with titles like "Untitled", "Untitled 2", "Untitled 3", etc., as expected. (I'm mentioning this not only because it's annoying, but because it may yield some insight into what's going wrong.)
I have partially solved #1 by making my application controller a delegate of the welcome panel. When clicking the "Open Existing Document" button, the panel resigns its key status (since a file browser dialog is being opened), so I can close the panel in the delegate's windowDidResignKey: method. However, I can't figure out how to close the panel when creating a new document, since I can't find a notification that is posted, or a delegate method that is called, when creating a new document. And ultimately, #2 is still a problem, since the document windows don't gain focus when they're created.
I have only subclassed NSDocument -- I'm not using a custom document or window controller at all. I've also tried changing the panel to an NSWindow, thinking that an NSWindow may behave differently, but the same problems are occurring.
Make a custom document controller, and have it know about your Starting Points panel's controller, and hide the window in addDocument: and show it again (if no other documents remain) in removeDocument:.
This is what we did in Adium Xtras Creator. That code is under a BSD license (unlike Adium proper), so you can borrow it if you want.
Instead of linking to the first responder's default actions, just create custom action method in your window controller and set your buttons to trigger those actions. In your method, you need to close the welcome window and then create a new document.
Something like this:
- (IBAction)createNewDocument:(id)sender
{
//this will close the window if you're using NSWindowController
[self close];
[[NSDocumentController sharedDocumentController] newDocument:sender];
}
Or if you're not using an NSWindowController for your welcome window you can just message the window directly:
- (IBAction)createNewDocument:(id)sender
{
//assume you have a "window" outlet connected to your welcome window
[window orderOut:sender];
[[NSDocumentController sharedDocumentController] newDocument:sender];
}

Dropping Files onto Dock Icon in Cocoa

How can I drop a file(or select to open it in Finder) of a type specified in the Info.plist onto my dock icon and then calling a method with the full path of the file?
If you've set up your Info.plist's CFBundleDocumentTypes array properly (either 'LSItemContentTypes' or 'CFBundleTypeExtensions'), then you just need to set up an NSApplication delegate and implement the delegate method, application:openFile:.
If you're expecting multiple files to be dropped at once, implement application:openFiles:.
For promised files (NSFilesPromisePboardType/kPasteboardTypeFileURLPromise) see Dropping promised files on to application icon in Dock.
Here's an updated solution for Xcode 5.
In AppDelegate.m
-(BOOL)application:(NSApplication *)sender openFile:(NSString *)filename
{
NSLog(#"%#", filename);
return YES;
}
And in Xcode setup Document Types under Project > Targets > Info:
Check settings in Info.plist in case you have an empty 'Document Content Type UTIs' array which should be filled out properly or else deleted.
Your Info.plist should look something like this:
On current systems you can use a UTI instead of the old-style four-char types (such as fold above). In Xcode's document type editor, make a new type with:
Name: Folder
Identifier: public.folder
public.folder is a subtype of public.directory. public.folder matches directories that appear as such to the user, i.e. not packages like .app wrappers.
Select your application in the target group of the side pane and use get info. Then in the new window select the properties tab to add a new document type. Name it "Folder" for convenience and the OS Types needs to be "fold"; the store type and role you can leave as is.
If you're actually making a document-based app, setting it up to give you the path will have you doing far more work than you need to. Simply use the document-based application template. The document controller will create an instance of the right class for you; you need only write that class.
An application you create this way will handle file drops (by opening them as documents) for free.

Resources