Add files opened/saved from :browse to "Recent Files" menu
[MacVim.git] / src / MacVim / MMAppController.m
blobc3588683e5bff07a2cb2148efa6562a930765a5b
1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
2  *
3  * VIM - Vi IMproved            by Bram Moolenaar
4  *                              MacVim GUI port by Bjorn Winckler
5  *
6  * Do ":help uganda"  in Vim to read copying and usage conditions.
7  * Do ":help credits" in Vim to see a list of people who contributed.
8  * See README.txt for an overview of the Vim source code.
9  */
11  * MMAppController
12  *
13  * MMAppController is the delegate of NSApp and as such handles file open
14  * requests, application termination, etc.  It sets up a named NSConnection on
15  * which it listens to incoming connections from Vim processes.  It also
16  * coordinates all MMVimControllers.
17  *
18  * A new Vim process is started by calling launchVimProcessWithArguments:.
19  * When the Vim process is initialized it notifies the app controller by
20  * sending a connectBackend:pid: message.  At this point a new MMVimController
21  * is allocated.  Afterwards, the Vim process communicates directly with its
22  * MMVimController.
23  *
24  * A Vim process started from the command line connects directly by sending the
25  * connectBackend:pid: message (launchVimProcessWithArguments: is never called
26  * in this case).
27  */
29 #import "MMAppController.h"
30 #import "MMVimController.h"
31 #import "MMWindowController.h"
32 #import "MMPreferenceController.h"
33 #import <unistd.h>
36 #define MM_HANDLE_XCODE_MOD_EVENT 0
40 // Default timeout intervals on all connections.
41 static NSTimeInterval MMRequestTimeout = 5;
42 static NSTimeInterval MMReplyTimeout = 5;
44 static NSString *MMWebsiteString = @"http://code.google.com/p/macvim/";
47 #pragma options align=mac68k
48 typedef struct
50     short unused1;      // 0 (not used)
51     short lineNum;      // line to select (< 0 to specify range)
52     long  startRange;   // start of selection range (if line < 0)
53     long  endRange;     // end of selection range (if line < 0)
54     long  unused2;      // 0 (not used)
55     long  theDate;      // modification date/time
56 } MMSelectionRange;
57 #pragma options align=reset
60 static int executeInLoginShell(NSString *path, NSArray *args);
63 @interface MMAppController (MMServices)
64 - (void)openSelection:(NSPasteboard *)pboard userData:(NSString *)userData
65                 error:(NSString **)error;
66 - (void)openFile:(NSPasteboard *)pboard userData:(NSString *)userData
67            error:(NSString **)error;
68 @end
71 @interface MMAppController (Private)
72 - (MMVimController *)keyVimController;
73 - (MMVimController *)topmostVimController;
74 - (int)launchVimProcessWithArguments:(NSArray *)args;
75 - (NSArray *)filterFilesAndNotify:(NSArray *)files;
76 - (NSArray *)filterOpenFiles:(NSArray *)filenames
77                    arguments:(NSDictionary *)args;
78 #if MM_HANDLE_XCODE_MOD_EVENT
79 - (void)handleXcodeModEvent:(NSAppleEventDescriptor *)event
80                  replyEvent:(NSAppleEventDescriptor *)reply;
81 #endif
82 - (int)findLaunchingProcessWithoutArguments;
83 - (MMVimController *)findUntitledWindow;
84 - (NSMutableDictionary *)extractArgumentsFromOdocEvent:
85     (NSAppleEventDescriptor *)desc;
86 - (void)passArguments:(NSDictionary *)args toVimController:(MMVimController*)vc;
87 @end
89 @interface NSMenu (MMExtras)
90 - (void)recurseSetAutoenablesItems:(BOOL)on;
91 @end
93 @interface NSNumber (MMExtras)
94 - (int)tag;
95 @end
99 @implementation MMAppController
101 + (void)initialize
103     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
104         [NSNumber numberWithBool:NO],   MMNoWindowKey,
105         [NSNumber numberWithInt:64],    MMTabMinWidthKey,
106         [NSNumber numberWithInt:6*64],  MMTabMaxWidthKey,
107         [NSNumber numberWithInt:132],   MMTabOptimumWidthKey,
108         [NSNumber numberWithInt:2],     MMTextInsetLeftKey,
109         [NSNumber numberWithInt:1],     MMTextInsetRightKey,
110         [NSNumber numberWithInt:1],     MMTextInsetTopKey,
111         [NSNumber numberWithInt:1],     MMTextInsetBottomKey,
112         [NSNumber numberWithBool:NO],   MMTerminateAfterLastWindowClosedKey,
113         @"MMTypesetter",                MMTypesetterKey,
114         [NSNumber numberWithFloat:1],   MMCellWidthMultiplierKey,
115         [NSNumber numberWithFloat:-1],  MMBaselineOffsetKey,
116         [NSNumber numberWithBool:YES],  MMTranslateCtrlClickKey,
117         [NSNumber numberWithBool:NO],   MMOpenFilesInTabsKey,
118         [NSNumber numberWithBool:NO],   MMNoFontSubstitutionKey,
119         [NSNumber numberWithBool:NO],   MMLoginShellKey,
120         [NSNumber numberWithBool:NO],   MMAtsuiRendererKey,
121         [NSNumber numberWithInt:MMUntitledWindowAlways],
122                                         MMUntitledWindowKey,
123         [NSNumber numberWithBool:NO],   MMTexturedWindowKey,
124         [NSNumber numberWithBool:NO],   MMZoomBothKey,
125         @"",                            MMLoginShellCommandKey,
126         @"",                            MMLoginShellArgumentKey,
127         nil];
129     [[NSUserDefaults standardUserDefaults] registerDefaults:dict];
131     NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
132     [NSApp registerServicesMenuSendTypes:types returnTypes:types];
135 - (id)init
137     if ((self = [super init])) {
138         fontContainerRef = loadFonts();
140         vimControllers = [NSMutableArray new];
141         pidArguments = [NSMutableDictionary new];
143         // NOTE!  If the name of the connection changes here it must also be
144         // updated in MMBackend.m.
145         NSConnection *connection = [NSConnection defaultConnection];
146         NSString *name = [NSString stringWithFormat:@"%@-connection",
147                  [[NSBundle mainBundle] bundleIdentifier]];
148         //NSLog(@"Registering connection with name '%@'", name);
149         if ([connection registerName:name]) {
150             [connection setRequestTimeout:MMRequestTimeout];
151             [connection setReplyTimeout:MMReplyTimeout];
152             [connection setRootObject:self];
154             // NOTE: When the user is resizing the window the AppKit puts the
155             // run loop in event tracking mode.  Unless the connection listens
156             // to request in this mode, live resizing won't work.
157             [connection addRequestMode:NSEventTrackingRunLoopMode];
158         } else {
159             NSLog(@"WARNING: Failed to register connection with name '%@'",
160                     name);
161         }
162     }
164     return self;
167 - (void)dealloc
169     //NSLog(@"MMAppController dealloc");
171     [pidArguments release];  pidArguments = nil;
172     [vimControllers release];  vimControllers = nil;
173     [openSelectionString release];  openSelectionString = nil;
174     [recentFilesMenuItem release];  recentFilesMenuItem = nil;
176     [super dealloc];
179 - (void)applicationWillFinishLaunching:(NSNotification *)notification
181     // Create the "Open Recent" menu. See
182     // http://lapcatsoftware.com/blog/2007/07/10/working-without-a-nib-part-5-open-recent-menu/
183     // and http://www.cocoabuilder.com/archive/message/cocoa/2007/8/15/187793
184     // for more information.
185     // 
186     // The menu needs to be created and be added to a toplevel menu in
187     // applicationWillFinishLaunching at the latest, otherwise it doesn't work.
189     recentFilesMenuItem = [[NSMenuItem alloc] initWithTitle:@"Open Recent"
190                                               action:nil keyEquivalent:@""];
192     NSMenu *recentFilesMenu = [[NSMenu alloc] initWithTitle:@"Open Recent"];
193     [recentFilesMenu performSelector:@selector(_setMenuName:)
194                           withObject:@"NSRecentDocumentsMenu"];
196     [recentFilesMenu addItemWithTitle:@"Clear Menu"
197                                action:@selector(clearRecentDocuments:)
198                         keyEquivalent:@""];
199     [recentFilesMenuItem setSubmenu:recentFilesMenu];
200     [recentFilesMenu release];  // the menu is retained by recentFilesMenuItem
201     [recentFilesMenuItem setTag:-1];  // must not be 0
203     [[[[NSApp mainMenu] itemWithTitle:@"File"] submenu] addItem:recentFilesMenuItem];
205 #if MM_HANDLE_XCODE_MOD_EVENT
206     [[NSAppleEventManager sharedAppleEventManager]
207             setEventHandler:self
208                 andSelector:@selector(handleXcodeModEvent:replyEvent:)
209               forEventClass:'KAHL'
210                  andEventID:'MOD '];
211 #endif
214 - (void)applicationDidFinishLaunching:(NSNotification *)notification
216     [NSApp setServicesProvider:self];
219 - (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
221     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
222     NSAppleEventManager *aem = [NSAppleEventManager sharedAppleEventManager];
223     NSAppleEventDescriptor *desc = [aem currentAppleEvent];
225     // The user default MMUntitledWindow can be set to control whether an
226     // untitled window should open on 'Open' and 'Reopen' events.
227     int untitledWindowFlag = [ud integerForKey:MMUntitledWindowKey];
228     if ([desc eventID] == kAEOpenApplication
229             && (untitledWindowFlag & MMUntitledWindowOnOpen) == 0)
230         return NO;
231     else if ([desc eventID] == kAEReopenApplication
232             && (untitledWindowFlag & MMUntitledWindowOnReopen) == 0)
233         return NO;
235     // When a process is started from the command line, the 'Open' event will
236     // contain a parameter to surpress the opening of an untitled window.
237     desc = [desc paramDescriptorForKeyword:keyAEPropData];
238     desc = [desc paramDescriptorForKeyword:keyMMUntitledWindow];
239     if (desc && ![desc booleanValue])
240         return NO;
242     // Never open an untitled window if there is at least one open window or if
243     // there are processes that are currently launching.
244     if ([vimControllers count] > 0 || [pidArguments count] > 0)
245         return NO;
247     // NOTE!  This way it possible to start the app with the command-line
248     // argument '-nowindow yes' and no window will be opened by default.
249     return ![ud boolForKey:MMNoWindowKey];
252 - (BOOL)applicationOpenUntitledFile:(NSApplication *)sender
254     [self newWindow:self];
255     return YES;
258 - (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
260     // Opening files works like this:
261     //  a) extract ODB/Xcode/Spotlight parameters from the current Apple event
262     //  b) filter out any already open files (see filterOpenFiles::)
263     //  c) open any remaining files
264     //
265     // A file is opened in an untitled window if there is one (it may be
266     // currently launching, or it may already be visible), otherwise a new
267     // window is opened.
268     //
269     // Each launching Vim process has a dictionary of arguments that are passed
270     // to the process when in checks in (via connectBackend:pid:).  The
271     // arguments for each launching process can be looked up by its PID (in the
272     // pidArguments dictionary).
274     NSMutableDictionary *arguments = [self extractArgumentsFromOdocEvent:
275             [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent]];
277     // Filter out files that are already open
278     filenames = [self filterOpenFiles:filenames arguments:arguments];
280     // Open any files that remain
281     if ([filenames count]) {
282         MMVimController *vc;
283         BOOL openInTabs = [[NSUserDefaults standardUserDefaults]
284             boolForKey:MMOpenFilesInTabsKey];
286         [arguments setObject:filenames forKey:@"filenames"];
287         [arguments setObject:[NSNumber numberWithBool:YES] forKey:@"openFiles"];
289         // Add file names to "Recent Files" menu.
290         int i, count = [filenames count];
291         for (i = 0; i < count; ++i) {
292             // Don't add files that are being edited remotely (using ODB).
293             if ([arguments objectForKey:@"remoteID"]) continue;
295             [[NSDocumentController sharedDocumentController]
296                     noteNewRecentFilePath:[filenames objectAtIndex:i]];
297         }
299         if ((openInTabs && (vc = [self topmostVimController]))
300                || (vc = [self findUntitledWindow])) {
301             // Open files in an already open window.
302             [[[vc windowController] window] makeKeyAndOrderFront:self];
303             [self passArguments:arguments toVimController:vc];
304         } else {
305             // Open files in a launching Vim process or start a new process.
306             int pid = [self findLaunchingProcessWithoutArguments];
307             if (!pid) {
308                 // Pass the filenames to the process straight away.
309                 //
310                 // TODO: It would be nicer if all arguments were passed to the
311                 // Vim process in connectBackend::, but if we don't pass the
312                 // filename arguments here, the window 'flashes' once when it
313                 // opens.  This is due to the 'welcome' screen first being
314                 // displayed, then quickly thereafter the files are opened.
315                 NSArray *fileArgs = [NSArray arrayWithObject:@"-p"];
316                 fileArgs = [fileArgs arrayByAddingObjectsFromArray:filenames];
318                 pid = [self launchVimProcessWithArguments:fileArgs];
320                 if (-1 == pid) {
321                     // TODO: Notify user of failure?
322                     [NSApp replyToOpenOrPrint:
323                         NSApplicationDelegateReplyFailure];
324                     return;
325                 }
327                 // Make sure these files aren't opened again when
328                 // connectBackend:pid: is called.
329                 [arguments setObject:[NSNumber numberWithBool:NO]
330                               forKey:@"openFiles"];
331             }
333             // TODO: If the Vim process fails to start, or if it changes PID,
334             // then the memory allocated for these parameters will leak.
335             // Ensure that this cannot happen or somehow detect it.
337             if ([arguments count] > 0)
338                 [pidArguments setObject:arguments
339                                  forKey:[NSNumber numberWithInt:pid]];
340         }
341     }
343     [NSApp replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
344     // NSApplicationDelegateReplySuccess = 0,
345     // NSApplicationDelegateReplyCancel = 1,
346     // NSApplicationDelegateReplyFailure = 2
349 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
351     return [[NSUserDefaults standardUserDefaults]
352             boolForKey:MMTerminateAfterLastWindowClosedKey];
355 - (NSApplicationTerminateReply)applicationShouldTerminate:
356     (NSApplication *)sender
358     // TODO: Follow Apple's guidelines for 'Graceful Application Termination'
359     // (in particular, allow user to review changes and save).
360     int reply = NSTerminateNow;
361     BOOL modifiedBuffers = NO;
363     // Go through windows, checking for modified buffers.  (Each Vim process
364     // tells MacVim when any buffer has been modified and MacVim sets the
365     // 'documentEdited' flag of the window correspondingly.)
366     NSEnumerator *e = [[NSApp windows] objectEnumerator];
367     id window;
368     while ((window = [e nextObject])) {
369         if ([window isDocumentEdited]) {
370             modifiedBuffers = YES;
371             break;
372         }
373     }
375     if (modifiedBuffers) {
376         NSAlert *alert = [[NSAlert alloc] init];
377         [alert setAlertStyle:NSWarningAlertStyle];
378         [alert addButtonWithTitle:@"Quit"];
379         [alert addButtonWithTitle:@"Cancel"];
380         [alert setMessageText:@"Quit without saving?"];
381         [alert setInformativeText:@"There are modified buffers, "
382             "if you quit now all changes will be lost.  Quit anyway?"];
384         if ([alert runModal] != NSAlertFirstButtonReturn)
385             reply = NSTerminateCancel;
387         [alert release];
388     } else {
389         // No unmodified buffers, but give a warning if there are multiple
390         // windows and/or tabs open.
391         int numWindows = [vimControllers count];
392         int numTabs = 0;
394         // Count the number of open tabs
395         e = [vimControllers objectEnumerator];
396         id vc;
397         while ((vc = [e nextObject])) {
398             NSString *eval = [vc evaluateVimExpression:@"tabpagenr('$')"];
399             if (eval) {
400                 int count = [eval intValue];
401                 if (count > 0 && count < INT_MAX)
402                     numTabs += count;
403             }
404         }
406         if (numWindows > 1 || numTabs > 1) {
407             NSAlert *alert = [[NSAlert alloc] init];
408             [alert setAlertStyle:NSWarningAlertStyle];
409             [alert addButtonWithTitle:@"Quit"];
410             [alert addButtonWithTitle:@"Cancel"];
411             [alert setMessageText:@"Are you sure you want to quit MacVim?"];
413             NSString *info = nil;
414             if (numWindows > 1) {
415                 if (numTabs > numWindows)
416                     info = [NSString stringWithFormat:@"There are %d windows "
417                         "open in MacVim, with a total of %d tabs. Do you want "
418                         "to quit anyway?", numWindows, numTabs];
419                 else
420                     info = [NSString stringWithFormat:@"There are %d windows "
421                         "open in MacVim. Do you want to quit anyway?",
422                         numWindows];
424             } else {
425                 info = [NSString stringWithFormat:@"There are %d tabs open "
426                     "in MacVim. Do you want to quit anyway?", numTabs];
427             }
429             [alert setInformativeText:info];
431             if ([alert runModal] != NSAlertFirstButtonReturn)
432                 reply = NSTerminateCancel;
434             [alert release];
435         }
436     }
439     // Tell all Vim processes to terminate now (otherwise they'll leave swap
440     // files behind).
441     if (NSTerminateNow == reply) {
442         e = [vimControllers objectEnumerator];
443         id vc;
444         while ((vc = [e nextObject]))
445             [vc sendMessage:TerminateNowMsgID data:nil];
446     }
448     return reply;
451 - (void)applicationWillTerminate:(NSNotification *)notification
453 #if MM_HANDLE_XCODE_MOD_EVENT
454     [[NSAppleEventManager sharedAppleEventManager]
455             removeEventHandlerForEventClass:'KAHL'
456                                  andEventID:'MOD '];
457 #endif
459     // This will invalidate all connections (since they were spawned from the
460     // default connection).
461     [[NSConnection defaultConnection] invalidate];
463     // Send a SIGINT to all running Vim processes, so that they are sure to
464     // receive the connectionDidDie: notification (a process has to be checking
465     // the run-loop for this to happen).
466     unsigned i, count = [vimControllers count];
467     for (i = 0; i < count; ++i) {
468         MMVimController *controller = [vimControllers objectAtIndex:i];
469         int pid = [controller pid];
470         if (pid > 0)
471             kill(pid, SIGINT);
472     }
474     if (fontContainerRef) {
475         ATSFontDeactivate(fontContainerRef, NULL, kATSOptionFlagsDefault);
476         fontContainerRef = 0;
477     }
479     [NSApp setDelegate:nil];
482 - (void)removeVimController:(id)controller
484     //NSLog(@"%s%@", _cmd, controller);
486     [[controller windowController] close];
488     [vimControllers removeObject:controller];
490     if (![vimControllers count]) {
491         // Turn on autoenabling of menus (because no Vim is open to handle it),
492         // but do not touch the MacVim menu.  Note that the menus must be
493         // enabled first otherwise autoenabling does not work.
494         NSMenu *mainMenu = [NSApp mainMenu];
495         int i, count = [mainMenu numberOfItems];
496         for (i = 1; i < count; ++i) {
497             NSMenuItem *item = [mainMenu itemAtIndex:i];
498             [item setEnabled:YES];
499             [[item submenu] recurseSetAutoenablesItems:YES];
500         }
501     }
504 - (void)windowControllerWillOpen:(MMWindowController *)windowController
506     NSPoint topLeft = NSZeroPoint;
507     NSWindow *topWin = [[[self topmostVimController] windowController] window];
508     NSWindow *win = [windowController window];
510     if (!win) return;
512     // If there is a window belonging to a Vim process, cascade from it,
513     // otherwise use the autosaved window position (if any).
514     if (topWin) {
515         NSRect frame = [topWin frame];
516         topLeft = NSMakePoint(frame.origin.x, NSMaxY(frame));
517     } else {
518         NSString *topLeftString = [[NSUserDefaults standardUserDefaults]
519             stringForKey:MMTopLeftPointKey];
520         if (topLeftString)
521             topLeft = NSPointFromString(topLeftString);
522     }
524     if (!NSEqualPoints(topLeft, NSZeroPoint)) {
525         if (topWin)
526             topLeft = [win cascadeTopLeftFromPoint:topLeft];
528         [win setFrameTopLeftPoint:topLeft];
529     }
531     if (openSelectionString) {
532         // TODO: Pass this as a parameter instead!  Get rid of
533         // 'openSelectionString' etc.
534         //
535         // There is some text to paste into this window as a result of the
536         // services menu "Open selection ..." being used.
537         [[windowController vimController] dropString:openSelectionString];
538         [openSelectionString release];
539         openSelectionString = nil;
540     }
543 - (IBAction)newWindow:(id)sender
545     [self launchVimProcessWithArguments:nil];
548 - (IBAction)fileOpen:(id)sender
550     NSOpenPanel *panel = [NSOpenPanel openPanel];
551     [panel setAllowsMultipleSelection:YES];
553     int result = [panel runModalForTypes:nil];
554     if (NSOKButton == result)
555         [self application:NSApp openFiles:[panel filenames]];
558 - (IBAction)selectNextWindow:(id)sender
560     unsigned i, count = [vimControllers count];
561     if (!count) return;
563     NSWindow *keyWindow = [NSApp keyWindow];
564     for (i = 0; i < count; ++i) {
565         MMVimController *vc = [vimControllers objectAtIndex:i];
566         if ([[[vc windowController] window] isEqual:keyWindow])
567             break;
568     }
570     if (i < count) {
571         if (++i >= count)
572             i = 0;
573         MMVimController *vc = [vimControllers objectAtIndex:i];
574         [[vc windowController] showWindow:self];
575     }
578 - (IBAction)selectPreviousWindow:(id)sender
580     unsigned i, count = [vimControllers count];
581     if (!count) return;
583     NSWindow *keyWindow = [NSApp keyWindow];
584     for (i = 0; i < count; ++i) {
585         MMVimController *vc = [vimControllers objectAtIndex:i];
586         if ([[[vc windowController] window] isEqual:keyWindow])
587             break;
588     }
590     if (i < count) {
591         if (i > 0) {
592             --i;
593         } else {
594             i = count - 1;
595         }
596         MMVimController *vc = [vimControllers objectAtIndex:i];
597         [[vc windowController] showWindow:self];
598     }
601 - (IBAction)fontSizeUp:(id)sender
603     [[NSFontManager sharedFontManager] modifyFont:
604             [NSNumber numberWithInt:NSSizeUpFontAction]];
607 - (IBAction)fontSizeDown:(id)sender
609     [[NSFontManager sharedFontManager] modifyFont:
610             [NSNumber numberWithInt:NSSizeDownFontAction]];
613 - (IBAction)orderFrontPreferencePanel:(id)sender
615     [[MMPreferenceController sharedPrefsWindowController] showWindow:self];
618 - (IBAction)openWebsite:(id)sender
620     [[NSWorkspace sharedWorkspace] openURL:
621             [NSURL URLWithString:MMWebsiteString]];
624 - (byref id <MMFrontendProtocol>)
625     connectBackend:(byref in id <MMBackendProtocol>)backend
626                pid:(int)pid
628     //NSLog(@"Connect backend (pid=%d)", pid);
629     NSNumber *pidKey = [NSNumber numberWithInt:pid];
630     MMVimController *vc = nil;
632     @try {
633         [(NSDistantObject*)backend
634                 setProtocolForProxy:@protocol(MMBackendProtocol)];
636         vc = [[[MMVimController alloc]
637             initWithBackend:backend pid:pid recentFiles:recentFilesMenuItem]
638             autorelease];
640         if (![vimControllers count]) {
641             // The first window autosaves its position.  (The autosaving
642             // features of Cocoa are not used because we need more control over
643             // what is autosaved and when it is restored.)
644             [[vc windowController] setWindowAutosaveKey:MMTopLeftPointKey];
645         }
647         [vimControllers addObject:vc];
649         id args = [pidArguments objectForKey:pidKey];
650         if (args && [NSNull null] != args)
651             [self passArguments:args toVimController:vc];
653         // HACK!  MacVim does not get activated if it is launched from the
654         // terminal, so we forcibly activate here unless it is an untitled
655         // window opening.  Untitled windows are treated differently, else
656         // MacVim would steal the focus if another app was activated while the
657         // untitled window was loading.
658         if (!args || args != [NSNull null])
659             [NSApp activateIgnoringOtherApps:YES];
661         if (args)
662             [pidArguments removeObjectForKey:pidKey];
664         return vc;
665     }
667     @catch (NSException *e) {
668         NSLog(@"Exception caught in %s: \"%@\"", _cmd, e);
670         if (vc)
671             [vimControllers removeObject:vc];
673         [pidArguments removeObjectForKey:pidKey];
674     }
676     return nil;
679 - (NSArray *)serverList
681     NSMutableArray *array = [NSMutableArray array];
683     unsigned i, count = [vimControllers count];
684     for (i = 0; i < count; ++i) {
685         MMVimController *controller = [vimControllers objectAtIndex:i];
686         if ([controller serverName])
687             [array addObject:[controller serverName]];
688     }
690     return array;
693 @end // MMAppController
698 @implementation MMAppController (MMServices)
700 - (void)openSelection:(NSPasteboard *)pboard userData:(NSString *)userData
701                 error:(NSString **)error
703     if (![[pboard types] containsObject:NSStringPboardType]) {
704         NSLog(@"WARNING: Pasteboard contains no object of type "
705                 "NSStringPboardType");
706         return;
707     }
709     MMVimController *vc = [self topmostVimController];
710     if (vc) {
711         // Open a new tab first, since dropString: does not do this.
712         [vc sendMessage:AddNewTabMsgID data:nil];
713         [vc dropString:[pboard stringForType:NSStringPboardType]];
714     } else {
715         // NOTE: There is no window to paste the selection into, so save the
716         // text, open a new window, and paste the text when the next window
717         // opens.  (If this is called several times in a row, then all but the
718         // last call might be ignored.)
719         if (openSelectionString) [openSelectionString release];
720         openSelectionString = [[pboard stringForType:NSStringPboardType] copy];
722         [self newWindow:self];
723     }
726 - (void)openFile:(NSPasteboard *)pboard userData:(NSString *)userData
727            error:(NSString **)error
729     if (![[pboard types] containsObject:NSStringPboardType]) {
730         NSLog(@"WARNING: Pasteboard contains no object of type "
731                 "NSStringPboardType");
732         return;
733     }
735     // TODO: Parse multiple filenames and create array with names.
736     NSString *string = [pboard stringForType:NSStringPboardType];
737     string = [string stringByTrimmingCharactersInSet:
738             [NSCharacterSet whitespaceAndNewlineCharacterSet]];
739     string = [string stringByStandardizingPath];
741     NSArray *filenames = [self filterFilesAndNotify:
742             [NSArray arrayWithObject:string]];
743     if ([filenames count] > 0) {
744         MMVimController *vc = nil;
745         if (userData && [userData isEqual:@"Tab"])
746             vc = [self topmostVimController];
748         if (vc) {
749             [vc dropFiles:filenames forceOpen:YES];
750         } else {
751             [self application:NSApp openFiles:filenames];
752         }
753     }
756 @end // MMAppController (MMServices)
761 @implementation MMAppController (Private)
763 - (MMVimController *)keyVimController
765     NSWindow *keyWindow = [NSApp keyWindow];
766     if (keyWindow) {
767         unsigned i, count = [vimControllers count];
768         for (i = 0; i < count; ++i) {
769             MMVimController *vc = [vimControllers objectAtIndex:i];
770             if ([[[vc windowController] window] isEqual:keyWindow])
771                 return vc;
772         }
773     }
775     return nil;
778 - (MMVimController *)topmostVimController
780     // Find the topmost visible window which has an associated vim controller.
781     NSEnumerator *e = [[NSApp orderedWindows] objectEnumerator];
782     id window;
783     while ((window = [e nextObject]) && [window isVisible]) {
784         unsigned i, count = [vimControllers count];
785         for (i = 0; i < count; ++i) {
786             MMVimController *vc = [vimControllers objectAtIndex:i];
787             if ([[[vc windowController] window] isEqual:window])
788                 return vc;
789         }
790     }
792     return nil;
795 - (int)launchVimProcessWithArguments:(NSArray *)args
797     int pid = -1;
798     NSString *path = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"Vim"];
800     if (!path) {
801         NSLog(@"ERROR: Vim executable could not be found inside app bundle!");
802         return -1;
803     }
805     NSArray *taskArgs = [NSArray arrayWithObjects:@"-g", @"-f", nil];
806     if (args)
807         taskArgs = [taskArgs arrayByAddingObjectsFromArray:args];
809     BOOL useLoginShell = [[NSUserDefaults standardUserDefaults]
810             boolForKey:MMLoginShellKey];
811     if (useLoginShell) {
812         // Run process with a login shell, roughly:
813         //   echo "exec Vim -g -f args" | ARGV0=-`basename $SHELL` $SHELL [-l]
814         pid = executeInLoginShell(path, taskArgs);
815     } else {
816         // Run process directly:
817         //   Vim -g -f args
818         NSTask *task = [NSTask launchedTaskWithLaunchPath:path
819                                                 arguments:taskArgs];
820         pid = task ? [task processIdentifier] : -1;
821     }
823     if (-1 != pid) {
824         // NOTE: If the process has no arguments, then add a null argument to
825         // the pidArguments dictionary.  This is later used to detect that a
826         // process without arguments is being launched.
827         if (!args)
828             [pidArguments setObject:[NSNull null]
829                              forKey:[NSNumber numberWithInt:pid]];
830     } else {
831         NSLog(@"WARNING: %s%@ failed (useLoginShell=%d)", _cmd, args,
832                 useLoginShell);
833     }
835     return pid;
838 - (NSArray *)filterFilesAndNotify:(NSArray *)filenames
840     // Go trough 'filenames' array and make sure each file exists.  Present
841     // warning dialog if some file was missing.
843     NSString *firstMissingFile = nil;
844     NSMutableArray *files = [NSMutableArray array];
845     unsigned i, count = [filenames count];
847     for (i = 0; i < count; ++i) {
848         NSString *name = [filenames objectAtIndex:i];
849         if ([[NSFileManager defaultManager] fileExistsAtPath:name]) {
850             [files addObject:name];
851         } else if (!firstMissingFile) {
852             firstMissingFile = name;
853         }
854     }
856     if (firstMissingFile) {
857         NSAlert *alert = [[NSAlert alloc] init];
858         [alert addButtonWithTitle:@"OK"];
860         NSString *text;
861         if ([files count] >= count-1) {
862             [alert setMessageText:@"File not found"];
863             text = [NSString stringWithFormat:@"Could not open file with "
864                 "name %@.", firstMissingFile];
865         } else {
866             [alert setMessageText:@"Multiple files not found"];
867             text = [NSString stringWithFormat:@"Could not open file with "
868                 "name %@, and %d other files.", firstMissingFile,
869                 count-[files count]-1];
870         }
872         [alert setInformativeText:text];
873         [alert setAlertStyle:NSWarningAlertStyle];
875         [alert runModal];
876         [alert release];
878         [NSApp replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
879     }
881     return files;
884 - (NSArray *)filterOpenFiles:(NSArray *)filenames
885                    arguments:(NSDictionary *)args
887     // Check if any of the files in the 'filenames' array are open in any Vim
888     // process.  Remove the files that are open from the 'filenames' array and
889     // return it.  If all files were filtered out, then raise the first file in
890     // the Vim process it is open.  Files that are filtered are sent an odb
891     // open event in case theID is not zero.
893     NSMutableDictionary *localArgs =
894             [NSMutableDictionary dictionaryWithDictionary:args];
895     MMVimController *raiseController = nil;
896     NSString *raiseFile = nil;
897     NSMutableArray *files = [filenames mutableCopy];
898     NSString *expr = [NSString stringWithFormat:
899             @"map([\"%@\"],\"bufloaded(v:val)\")",
900             [files componentsJoinedByString:@"\",\""]];
901     unsigned i, count = [vimControllers count];
903     // Ensure that the files aren't opened when passing arguments.
904     [localArgs setObject:[NSNumber numberWithBool:NO] forKey:@"openFiles"];
906     for (i = 0; i < count && [files count]; ++i) {
907         MMVimController *controller = [vimControllers objectAtIndex:i];
909         // Query Vim for which files in the 'files' array are open.
910         NSString *eval = [controller evaluateVimExpression:expr];
911         if (!eval) continue;
913         NSIndexSet *idxSet = [NSIndexSet indexSetWithVimList:eval];
914         if ([idxSet count]) {
915             if (!raiseFile) {
916                 // Remember the file and which Vim that has it open so that
917                 // we can raise it later on.
918                 raiseController = controller;
919                 raiseFile = [files objectAtIndex:[idxSet firstIndex]];
920                 [[raiseFile retain] autorelease];
921             }
923             // Pass (ODB/Xcode/Spotlight) arguments to this process.
924             [localArgs setObject:[files objectsAtIndexes:idxSet]
925                           forKey:@"filenames"];
926             [self passArguments:localArgs toVimController:controller];
928             // Remove all the files that were open in this Vim process and
929             // create a new expression to evaluate.
930             [files removeObjectsAtIndexes:idxSet];
931             expr = [NSString stringWithFormat:
932                     @"map([\"%@\"],\"bufloaded(v:val)\")",
933                     [files componentsJoinedByString:@"\",\""]];
934         }
935     }
937     if (![files count] && raiseFile) {
938         // Raise the window containing the first file that was already open,
939         // and make sure that the tab containing that file is selected.  Only
940         // do this if there are no more files to open, otherwise sometimes the
941         // window with 'raiseFile' will be raised, other times it might be the
942         // window that will open with the files in the 'files' array.
943         raiseFile = [raiseFile stringByEscapingSpecialFilenameCharacters];
944         NSString *input = [NSString stringWithFormat:@"<C-\\><C-N>"
945             ":let oldswb=&swb|let &swb=\"useopen,usetab\"|"
946             "tab sb %@|let &swb=oldswb|unl oldswb|"
947             "cal foreground()|redr|f<CR>", raiseFile];
949         [raiseController addVimInput:input];
950     }
952     return files;
955 #if MM_HANDLE_XCODE_MOD_EVENT
956 - (void)handleXcodeModEvent:(NSAppleEventDescriptor *)event
957                  replyEvent:(NSAppleEventDescriptor *)reply
959 #if 0
960     // Xcode sends this event to query MacVim which open files have been
961     // modified.
962     NSLog(@"reply:%@", reply);
963     NSLog(@"event:%@", event);
965     NSEnumerator *e = [vimControllers objectEnumerator];
966     id vc;
967     while ((vc = [e nextObject])) {
968         DescType type = [reply descriptorType];
969         unsigned len = [[type data] length];
970         NSMutableData *data = [NSMutableData data];
972         [data appendBytes:&type length:sizeof(DescType)];
973         [data appendBytes:&len length:sizeof(unsigned)];
974         [data appendBytes:[reply data] length:len];
976         [vc sendMessage:XcodeModMsgID data:data];
977     }
978 #endif
980 #endif
982 - (int)findLaunchingProcessWithoutArguments
984     NSArray *keys = [pidArguments allKeysForObject:[NSNull null]];
985     if ([keys count] > 0) {
986         //NSLog(@"found launching process without arguments");
987         return [[keys objectAtIndex:0] intValue];
988     }
990     return 0;
993 - (MMVimController *)findUntitledWindow
995     NSEnumerator *e = [vimControllers objectEnumerator];
996     id vc;
997     while ((vc = [e nextObject])) {
998         // TODO: This is a moronic test...should query the Vim process if there
999         // are any open buffers or something like that instead.
1000         NSString *title = [[[vc windowController] window] title];
1001         if ([title hasPrefix:@"[No Name] - VIM"]) {
1002             //NSLog(@"found untitled window");
1003             return vc;
1004         }
1005     }
1007     return nil;
1010 - (NSMutableDictionary *)extractArgumentsFromOdocEvent:
1011     (NSAppleEventDescriptor *)desc
1013     NSMutableDictionary *dict = [NSMutableDictionary dictionary];
1015     // 1. Extract ODB parameters (if any)
1016     NSAppleEventDescriptor *odbdesc = desc;
1017     if (![odbdesc paramDescriptorForKeyword:keyFileSender]) {
1018         // The ODB paramaters may hide inside the 'keyAEPropData' descriptor.
1019         odbdesc = [odbdesc paramDescriptorForKeyword:keyAEPropData];
1020         if (![odbdesc paramDescriptorForKeyword:keyFileSender])
1021             odbdesc = nil;
1022     }
1024     if (odbdesc) {
1025         NSAppleEventDescriptor *p =
1026                 [odbdesc paramDescriptorForKeyword:keyFileSender];
1027         if (p)
1028             [dict setObject:[NSNumber numberWithUnsignedInt:[p typeCodeValue]]
1029                      forKey:@"remoteID"];
1031         p = [odbdesc paramDescriptorForKeyword:keyFileCustomPath];
1032         if (p)
1033             [dict setObject:[p stringValue] forKey:@"remotePath"];
1035         p = [odbdesc paramDescriptorForKeyword:keyFileSenderToken];
1036         if (p)
1037             [dict setObject:p forKey:@"remotePath"];
1038     }
1040     // 2. Extract Xcode parameters (if any)
1041     NSAppleEventDescriptor *xcodedesc =
1042             [desc paramDescriptorForKeyword:keyAEPosition];
1043     if (xcodedesc) {
1044         NSRange range;
1045         MMSelectionRange *sr = (MMSelectionRange*)[[xcodedesc data] bytes];
1047         if (sr->lineNum < 0) {
1048             // Should select a range of lines.
1049             range.location = sr->startRange + 1;
1050             range.length = sr->endRange - sr->startRange + 1;
1051         } else {
1052             // Should only move cursor to a line.
1053             range.location = sr->lineNum + 1;
1054             range.length = 0;
1055         }
1057         [dict setObject:NSStringFromRange(range) forKey:@"selectionRange"];
1058     }
1060     // 3. Extract Spotlight search text (if any)
1061     NSAppleEventDescriptor *spotlightdesc = 
1062             [desc paramDescriptorForKeyword:keyAESearchText];
1063     if (spotlightdesc)
1064         [dict setObject:[spotlightdesc stringValue] forKey:@"searchText"];
1066     return dict;
1069 - (void)passArguments:(NSDictionary *)args toVimController:(MMVimController*)vc
1071     if (!args) return;
1073     // Pass filenames to open if required (the 'openFiles' argument can be used
1074     // to disallow opening of the files).
1075     NSArray *filenames = [args objectForKey:@"filenames"];
1076     if (filenames && [[args objectForKey:@"openFiles"] boolValue]) {
1077         NSString *tabDrop = buildTabDropCommand(filenames);
1078         [vc addVimInput:tabDrop];
1079     }
1081     // Pass ODB data
1082     if (filenames && [args objectForKey:@"remoteID"]) {
1083         [vc odbEdit:filenames
1084              server:[[args objectForKey:@"remoteID"] unsignedIntValue]
1085                path:[args objectForKey:@"remotePath"]
1086               token:[args objectForKey:@"remoteToken"]];
1087     }
1089     // Pass range of lines to select
1090     if ([args objectForKey:@"selectionRange"]) {
1091         NSRange selectionRange = NSRangeFromString(
1092                 [args objectForKey:@"selectionRange"]);
1093         [vc addVimInput:buildSelectRangeCommand(selectionRange)];
1094     }
1096     // Pass search text
1097     NSString *searchText = [args objectForKey:@"searchText"];
1098     if (searchText)
1099         [vc addVimInput:buildSearchTextCommand(searchText)];
1102 @end // MMAppController (Private)
1107 @implementation NSMenu (MMExtras)
1109 - (void)recurseSetAutoenablesItems:(BOOL)on
1111     [self setAutoenablesItems:on];
1113     int i, count = [self numberOfItems];
1114     for (i = 0; i < count; ++i) {
1115         NSMenuItem *item = [self itemAtIndex:i];
1116         [item setEnabled:YES];
1117         NSMenu *submenu = [item submenu];
1118         if (submenu) {
1119             [submenu recurseSetAutoenablesItems:on];
1120         }
1121     }
1124 @end  // NSMenu (MMExtras)
1129 @implementation NSNumber (MMExtras)
1130 - (int)tag
1132     return [self intValue];
1134 @end // NSNumber (MMExtras)
1139     static int
1140 executeInLoginShell(NSString *path, NSArray *args)
1142     // Start a login shell and execute the command 'path' with arguments 'args'
1143     // in the shell.  This ensures that user environment variables are set even
1144     // when MacVim was started from the Finder.
1146     int pid = -1;
1147     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1149     // Determine which shell to use to execute the command.  The user
1150     // may decide which shell to use by setting a user default or the
1151     // $SHELL environment variable.
1152     NSString *shell = [ud stringForKey:MMLoginShellCommandKey];
1153     if (!shell || [shell length] == 0)
1154         shell = [[[NSProcessInfo processInfo] environment]
1155             objectForKey:@"SHELL"];
1156     if (!shell)
1157         shell = @"/bin/bash";
1159     //NSLog(@"shell = %@", shell);
1161     // Bash needs the '-l' flag to launch a login shell.  The user may add
1162     // flags by setting a user default.
1163     NSString *shellArgument = [ud stringForKey:MMLoginShellArgumentKey];
1164     if (!shellArgument || [shellArgument length] == 0) {
1165         if ([[shell lastPathComponent] isEqual:@"bash"])
1166             shellArgument = @"-l";
1167         else
1168             shellArgument = nil;
1169     }
1171     //NSLog(@"shellArgument = %@", shellArgument);
1173     // Build input string to pipe to the login shell.
1174     NSMutableString *input = [NSMutableString stringWithFormat:
1175             @"exec \"%@\"", path];
1176     if (args) {
1177         // Append all arguments, making sure they are properly quoted, even
1178         // when they contain single quotes.
1179         NSEnumerator *e = [args objectEnumerator];
1180         id obj;
1182         while ((obj = [e nextObject])) {
1183             NSMutableString *arg = [NSMutableString stringWithString:obj];
1184             [arg replaceOccurrencesOfString:@"'" withString:@"'\"'\"'"
1185                                     options:NSLiteralSearch
1186                                       range:NSMakeRange(0, [arg length])];
1187             [input appendFormat:@" '%@'", arg];
1188         }
1189     }
1191     // Build the argument vector used to start the login shell.
1192     NSString *shellArg0 = [NSString stringWithFormat:@"-%@",
1193              [shell lastPathComponent]];
1194     char *shellArgv[3] = { (char *)[shellArg0 UTF8String], NULL, NULL };
1195     if (shellArgument)
1196         shellArgv[1] = (char *)[shellArgument UTF8String];
1198     // Get the C string representation of the shell path before the fork since
1199     // we must not call Foundation functions after a fork.
1200     const char *shellPath = [shell fileSystemRepresentation];
1202     // Fork and execute the process.
1203     int ds[2];
1204     if (pipe(ds)) return -1;
1206     pid = fork();
1207     if (pid == -1) {
1208         return -1;
1209     } else if (pid == 0) {
1210         // Child process
1211         if (close(ds[1]) == -1) exit(255);
1212         if (dup2(ds[0], 0) == -1) exit(255);
1214         execv(shellPath, shellArgv);
1216         // Never reached unless execv fails
1217         exit(255);
1218     } else {
1219         // Parent process
1220         if (close(ds[0]) == -1) return -1;
1222         // Send input to execute to the child process
1223         [input appendString:@"\n"];
1224         int bytes = [input lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1226         if (write(ds[1], [input UTF8String], bytes) != bytes) return -1;
1227         if (close(ds[1]) == -1) return -1;
1228     }
1230     return pid;