Keep whole window visible on ":set lines=X columns=Y"
[MacVim.git] / src / MacVim / MMWindowController.m
blob403c85c90ef33e6756165b1417b54f4db2ff5316
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  * MMWindowController
12  *
13  * Handles resizing of windows, acts as an mediator between MMVimView and
14  * MMVimController.
15  *
16  * Resizing in windowed mode:
17  *
18  * In windowed mode resizing can occur either due to the window frame changing
19  * size (e.g. when the user drags to resize), or due to Vim changing the number
20  * of (rows,columns).  The former case is dealt with by letting the vim view
21  * fill the entire content view when the window has resized.  In the latter
22  * case we ensure that vim view fits on the screen.
23  *
24  * The vim view notifies Vim if the number of (rows,columns) does not match the
25  * current number whenver the view size is about to change.  Upon receiving a
26  * dimension change message, Vim notifies the window controller and the window
27  * resizes.  However, the window is never resized programmatically during a
28  * live resize (in order to avoid jittering).
29  *
30  * The window size is constrained to not become too small during live resize,
31  * and it is also constrained to always fit an integer number of
32  * (rows,columns).
33  *
34  * In windowed mode we have to manually draw a tabline separator (due to bugs
35  * in the way Cocoa deals with the toolbar separator) when certain conditions
36  * are met.  The rules for this are as follows:
37  *
38  *   Tabline visible & Toolbar visible  =>  Separator visible
39  *   =====================================================================
40  *         NO        &        NO        =>  YES, if the window is textured
41  *                                           NO, otherwise
42  *         NO        &       YES        =>  YES
43  *        YES        &        NO        =>   NO
44  *        YES        &       YES        =>   NO
45  *
46  *
47  * Resizing in full-screen mode:
48  *
49  * The window never resizes since it fills the screen, however the vim view may
50  * change size, e.g. when the user types ":set lines=60", or when a scrollbar
51  * is toggled.
52  *
53  * It is ensured that the vim view never becomes larger than the screen size
54  * and that it always stays in the center of the screen.
55  *  
56  */
58 #import "MMAppController.h"
59 #import "MMAtsuiTextView.h"
60 #import "MMFindReplaceController.h"
61 #import "MMFullscreenWindow.h"
62 #import "MMTextView.h"
63 #import "MMTypesetter.h"
64 #import "MMVimController.h"
65 #import "MMVimView.h"
66 #import "MMWindow.h"
67 #import "MMWindowController.h"
68 #import "Miscellaneous.h"
69 #import <PSMTabBarControl.h>
73 @interface MMWindowController (Private)
74 - (NSSize)contentSize;
75 - (void)resizeWindowToFitContentSize:(NSSize)contentSize
76                         keepOnScreen:(BOOL)onScreen;
77 - (NSSize)constrainContentSizeToScreenSize:(NSSize)contentSize;
78 - (NSRect)constrainFrame:(NSRect)frame;
79 - (void)updateResizeConstraints;
80 - (NSTabViewItem *)addNewTabViewItem;
81 - (BOOL)askBackendForStarRegister:(NSPasteboard *)pb;
82 - (void)hideTablineSeparator:(BOOL)hide;
83 - (void)doFindNext:(BOOL)next;
84 @end
87 @interface NSWindow (NSWindowPrivate)
88 // Note: This hack allows us to set content shadowing separately from
89 // the window shadow.  This is apparently what webkit and terminal do.
90 - (void)_setContentHasShadow:(BOOL)shadow; // new Tiger private method
92 // This is a private api that makes textured windows not have rounded corners.
93 // We want this on Leopard.
94 - (void)setBottomCornerRounded:(BOOL)rounded;
95 @end
98 @interface NSWindow (NSLeopardOnly)
99 // Note: These functions are Leopard-only, use -[NSObject respondsToSelector:]
100 // before calling them to make sure everything works on Tiger too.
102 #ifndef CGFLOAT_DEFINED
103     // On Leopard, CGFloat is float on 32bit and double on 64bit. On Tiger,
104     // we can't use this anyways, so it's just here to keep the compiler happy.
105     // However, when we're compiling for Tiger and running on Leopard, we
106     // might need the correct typedef, so this piece is copied from ATSTypes.h
107 # ifdef __LP64__
108     typedef double CGFloat;
109 # else
110     typedef float CGFloat;
111 # endif
112 #endif
113 - (void)setAutorecalculatesContentBorderThickness:(BOOL)b forEdge:(NSRectEdge)e;
114 - (void)setContentBorderThickness:(CGFloat)b forEdge:(NSRectEdge)e;
115 @end
120 @implementation MMWindowController
122 - (id)initWithVimController:(MMVimController *)controller
124 #ifndef NSAppKitVersionNumber10_4  // needed for non-10.5 sdk
125 # define NSAppKitVersionNumber10_4 824
126 #endif
127     unsigned styleMask = NSTitledWindowMask | NSClosableWindowMask
128             | NSMiniaturizableWindowMask | NSResizableWindowMask
129             | NSUnifiedTitleAndToolbarWindowMask;
131     // Use textured background on Leopard or later (skip the 'if' on Tiger for
132     // polished metal window).
133     if ([[NSUserDefaults standardUserDefaults] boolForKey:MMTexturedWindowKey]
134             || (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_4))
135         styleMask |= NSTexturedBackgroundWindowMask;
137     // NOTE: The content rect is only used the very first time MacVim is
138     // started (or rather, when ~/Library/Preferences/org.vim.MacVim.plist does
139     // not exist).  The chosen values will put the window somewhere near the
140     // top and in the middle of a 1024x768 screen.
141     MMWindow *win = [[MMWindow alloc]
142             initWithContentRect:NSMakeRect(242,364,480,360)
143                       styleMask:styleMask
144                         backing:NSBackingStoreBuffered
145                           defer:YES];
146     [win autorelease];
148     self = [super initWithWindow:win];
149     if (!self) return nil;
151     vimController = controller;
152     decoratedWindow = [win retain];
154     // Window cascading is handled by MMAppController.
155     [self setShouldCascadeWindows:NO];
157     // NOTE: Autoresizing is enabled for the content view, but only used
158     // for the tabline separator.  The vim view must be resized manually
159     // because of full-screen considerations, and because its size depends
160     // on whether the tabline separator is visible or not.
161     NSView *contentView = [win contentView];
162     [contentView setAutoresizesSubviews:YES];
164     vimView = [[MMVimView alloc] initWithFrame:[contentView frame]
165                                  vimController:vimController];
166     [vimView setAutoresizingMask:NSViewNotSizable];
167     [contentView addSubview:vimView];
169     [win setDelegate:self];
170     [win setInitialFirstResponder:[vimView textView]];
171     
172     if ([win styleMask] & NSTexturedBackgroundWindowMask) {
173         // On Leopard, we want to have a textured window to have nice
174         // looking tabs. But the textured window look implies rounded
175         // corners, which looks really weird -- disable them. This is a
176         // private api, though.
177         if ([win respondsToSelector:@selector(setBottomCornerRounded:)])
178             [win setBottomCornerRounded:NO];
180         // When the tab bar is toggled, it changes color for the fraction
181         // of a second, probably because vim sends us events in a strange
182         // order, confusing appkit's content border heuristic for a short
183         // while.  This can be worked around with these two methods.  There
184         // might be a better way, but it's good enough.
185         if ([win respondsToSelector:@selector(
186                 setAutorecalculatesContentBorderThickness:forEdge:)])
187             [win setAutorecalculatesContentBorderThickness:NO
188                                                    forEdge:NSMaxYEdge];
189         if ([win respondsToSelector:
190                 @selector(setContentBorderThickness:forEdge:)])
191             [win setContentBorderThickness:0 forEdge:NSMaxYEdge];
192     }
194     // Make us safe on pre-tiger OSX
195     if ([win respondsToSelector:@selector(_setContentHasShadow:)])
196         [win _setContentHasShadow:NO];
198     return self;
201 - (void)dealloc
203     LOG_DEALLOC
205     [decoratedWindow release];  decoratedWindow = nil;
206     [windowAutosaveKey release];  windowAutosaveKey = nil;
207     [vimView release];  vimView = nil;
209     [super dealloc];
212 - (NSString *)description
214     NSString *format =
215         @"%@ : setupDone=%d windowAutosaveKey=%@ vimController=%@";
216     return [NSString stringWithFormat:format,
217         [self className], setupDone, windowAutosaveKey, vimController];
220 - (MMVimController *)vimController
222     return vimController;
225 - (MMVimView *)vimView
227     return vimView;
230 - (NSString *)windowAutosaveKey
232     return windowAutosaveKey;
235 - (void)setWindowAutosaveKey:(NSString *)key
237     [windowAutosaveKey autorelease];
238     windowAutosaveKey = [key copy];
241 - (void)cleanup
243     //NSLog(@"%@ %s", [self className], _cmd);
245     if (fullscreenEnabled) {
246         // If we are closed while still in fullscreen, end fullscreen mode,
247         // release ourselves (because this won't happen in MMWindowController)
248         // and perform close operation on the original window.
249         [self leaveFullscreen];
250     }
252     setupDone = NO;
253     vimController = nil;
255     [vimView removeFromSuperviewWithoutNeedingDisplay];
256     [vimView cleanup];
258     // It is feasible (though unlikely) that the user quits before the window
259     // controller is released, make sure the edit flag is cleared so no warning
260     // dialog is displayed.
261     [decoratedWindow setDocumentEdited:NO];
263     [[self window] orderOut:self];
266 - (void)openWindow
268     // Indicates that the window is ready to be displayed, but do not display
269     // (or place) it yet -- that is done in showWindow.
271     [self addNewTabViewItem];
273     setupDone = YES;
275     [self updateResizeConstraints];
276     [self resizeWindowToFitContentSize:[vimView desiredSize]
277                           keepOnScreen:YES];
280 - (void)showWindow
282     // Actually show the window on screen.  However, if openWindow hasn't
283     // already been called nothing will happen (the window will be displayed
284     // later).
285     if (!setupDone) return;
287     [[MMAppController sharedInstance] windowControllerWillOpen:self];
288     [[self window] makeKeyAndOrderFront:self];
291 - (void)updateTabsWithData:(NSData *)data
293     [vimView updateTabsWithData:data];
296 - (void)selectTabWithIndex:(int)idx
298     [vimView selectTabWithIndex:idx];
301 - (void)setTextDimensionsWithRows:(int)rows columns:(int)cols isLive:(BOOL)live
302                           isReply:(BOOL)reply
304     //NSLog(@"setTextDimensionsWithRows:%d columns:%d isLive:%d isReply:%d",
305     //        rows, cols, live, reply);
307     // NOTE: The only place where the (rows,columns) of the vim view are
308     // modified is here and when entering/leaving full-screen.  Setting these
309     // values have no immediate effect, the actual resizing of the view is done
310     // in processCommandQueueDidFinish.
311     //
312     // The 'live' flag indicates that this resize originated from a live
313     // resize; it may very well happen that the view is no longer in live
314     // resize when this message is received.  We refrain from changing the view
315     // size when this flag is set, otherwise the window might jitter when the
316     // user drags to resize the window.
317     //
318     // The 'reply' flag indicates that this resize originated in MacVim and
319     // that Vim is now replying to that resize to make sure that it comes into
320     // effect.
322     [vimView setDesiredRows:rows columns:cols];
324     if (setupDone && !live) {
325         shouldResizeVimView = YES;
326         keepOnScreen = !reply;
327     }
330 - (void)setTitle:(NSString *)title
332     if (title)
333         [decoratedWindow setTitle:title];
336 - (void)setDocumentFilename:(NSString *)filename
338     if (!filename)
339         return;
341     // Ensure file really exists or the path to the proxy icon will look weird.
342     // If the file does not exists, don't show a proxy icon.
343     if (![[NSFileManager defaultManager] fileExistsAtPath:filename])
344         filename = @"";
346     [decoratedWindow setRepresentedFilename:filename];
349 - (void)setToolbar:(NSToolbar *)toolbar
351     // The full-screen window has no toolbar.
352     [decoratedWindow setToolbar:toolbar];
354     // HACK! Redirect the pill button so that we can ask Vim to hide the
355     // toolbar.
356     NSButton *pillButton = [decoratedWindow
357             standardWindowButton:NSWindowToolbarButton];
358     if (pillButton) {
359         [pillButton setAction:@selector(toggleToolbar:)];
360         [pillButton setTarget:self];
361     }
364 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
366     [vimView createScrollbarWithIdentifier:ident type:type];
369 - (BOOL)destroyScrollbarWithIdentifier:(long)ident
371     BOOL scrollbarHidden = [vimView destroyScrollbarWithIdentifier:ident];   
372     shouldResizeVimView = shouldResizeVimView || scrollbarHidden;
374     return scrollbarHidden;
377 - (BOOL)showScrollbarWithIdentifier:(long)ident state:(BOOL)visible
379     BOOL scrollbarToggled = [vimView showScrollbarWithIdentifier:ident
380                                                            state:visible];
381     shouldResizeVimView = shouldResizeVimView || scrollbarToggled;
383     return scrollbarToggled;
386 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
388     [vimView setScrollbarPosition:pos length:len identifier:ident];
391 - (void)setScrollbarThumbValue:(float)val proportion:(float)prop
392                     identifier:(long)ident
394     [vimView setScrollbarThumbValue:val proportion:prop identifier:ident];
397 - (void)setDefaultColorsBackground:(NSColor *)back foreground:(NSColor *)fore
399     // NOTE: This is called when the transparency changes so set the opacity
400     // flag on the window here (should be faster if the window is opaque).
401     BOOL isOpaque = [back alphaComponent] == 1.0f;
402     [decoratedWindow setOpaque:isOpaque];
403     if (fullscreenEnabled)
404         [fullscreenWindow setOpaque:isOpaque];
406     [vimView setDefaultColorsBackground:back foreground:fore];
409 - (void)setFont:(NSFont *)font
411     [[NSFontManager sharedFontManager] setSelectedFont:font isMultiple:NO];
412     [[vimView textView] setFont:font];
413     [self updateResizeConstraints];
416 - (void)setWideFont:(NSFont *)font
418     [[vimView textView] setWideFont:font];
421 - (void)processCommandQueueDidFinish
423     // IMPORTANT!  No synchronous DO calls are allowed in this method.  They
424     // may cause the command queue to get processed out of order.
426     // NOTE: Resizing is delayed until after all commands have been processed
427     // since it often happens that more than one command will cause a resize.
428     // If we were to immediately resize then the vim view size would jitter
429     // (e.g.  hiding/showing scrollbars often happens several time in one
430     // update).
432     if (shouldResizeVimView) {
433         shouldResizeVimView = NO;
435         NSSize contentSize = [vimView desiredSize];
436         contentSize = [self constrainContentSizeToScreenSize:contentSize];
437         contentSize = [vimView constrainRows:NULL columns:NULL
438                                       toSize:contentSize];
439         [vimView setFrameSize:contentSize];
441         if (fullscreenEnabled) {
442             [[fullscreenWindow contentView] setNeedsDisplay:YES];
443             [fullscreenWindow centerView];
444         } else {
445             [self resizeWindowToFitContentSize:contentSize
446                                   keepOnScreen:keepOnScreen];
447         }
449         keepOnScreen = NO;
450     }
453 - (void)showTabBar:(BOOL)on
455     [[vimView tabBarControl] setHidden:!on];
457     // Showing the tabline may result in the tabline separator being hidden or
458     // shown; this does not apply to full-screen mode.
459     if (!on) {
460         NSToolbar *toolbar = [decoratedWindow toolbar]; 
461         if (([decoratedWindow styleMask] & NSTexturedBackgroundWindowMask)
462                 == 0) {
463             [self hideTablineSeparator:![toolbar isVisible]];
464         } else {
465             [self hideTablineSeparator:NO];
466         }
467     } else {
468         if (([decoratedWindow styleMask] & NSTexturedBackgroundWindowMask)
469                 == 0) {
470             [self hideTablineSeparator:on];
471         } else {
472             [self hideTablineSeparator:YES];
473         }
474     }
477 - (void)showToolbar:(BOOL)on size:(int)size mode:(int)mode
479     NSToolbar *toolbar = [decoratedWindow toolbar];
480     if (!toolbar) return;
482     [toolbar setSizeMode:size];
483     [toolbar setDisplayMode:mode];
484     [toolbar setVisible:on];
486     if (([decoratedWindow styleMask] & NSTexturedBackgroundWindowMask) == 0) {
487         if (!on) {
488             [self hideTablineSeparator:YES];
489         } else {
490             [self hideTablineSeparator:![[vimView tabBarControl] isHidden]];
491         }
492     } else {
493         // Textured windows don't have a line below there title bar, so we
494         // need the separator in this case as well. In fact, the only case
495         // where we don't need the separator is when the tab bar control
496         // is visible (because it brings its own separator).
497         [self hideTablineSeparator:![[vimView tabBarControl] isHidden]];
498     }
501 - (void)setMouseShape:(int)shape
503     [[vimView textView] setMouseShape:shape];
506 - (void)adjustLinespace:(int)linespace
508     if (vimView && [vimView textView]) {
509         [[vimView textView] setLinespace:(float)linespace];
510         shouldResizeVimView = YES;
511     }
514 - (void)liveResizeWillStart
516     // Save the original title, if we haven't already.
517     if (lastSetTitle == nil) {
518         lastSetTitle = [[decoratedWindow title] retain];
519     }
522 - (void)liveResizeDidEnd
524     if (!setupDone) return;
526     // NOTE: During live resize messages from MacVim to Vim are often dropped
527     // (because too many messages are sent at once).  This may lead to
528     // inconsistent states between Vim and MacVim; to avoid this we send a
529     // synchronous resize message to Vim now (this is not fool-proof, but it
530     // does seem to work quite well).
532     int constrained[2];
533     NSSize textViewSize = [[vimView textView] frame].size;
534     [[vimView textView] constrainRows:&constrained[0] columns:&constrained[1]
535                                toSize:textViewSize];
537     //NSLog(@"End of live resize, notify Vim that text dimensions are %dx%d",
538     //       constrained[1], constrained[0]);
540     NSData *data = [NSData dataWithBytes:constrained length:2*sizeof(int)];
541     BOOL sendOk = [vimController sendMessageNow:SetTextDimensionsMsgID
542                                            data:data
543                                         timeout:.5];
545     if (!sendOk) {
546         // Sending of synchronous message failed.  Force the window size to
547         // match the last dimensions received from Vim, otherwise we end up
548         // with inconsistent states.
549         [self resizeWindowToFitContentSize:[vimView desiredSize]
550                               keepOnScreen:NO];
551     }
553     // If we saved the original title while resizing, restore it.
554     if (lastSetTitle != nil) {
555         [decoratedWindow setTitle:lastSetTitle];
556         [lastSetTitle release];
557         lastSetTitle = nil;
558     }
561 - (void)enterFullscreen:(int)fuoptions backgroundColor:(NSColor *)back
563     if (fullscreenEnabled) return;
565     fullscreenWindow = [[MMFullscreenWindow alloc]
566         initWithWindow:decoratedWindow view:vimView backgroundColor:back];
567     [fullscreenWindow enterFullscreen:fuoptions];    
568     [fullscreenWindow setDelegate:self];
569     fullscreenEnabled = YES;
571     // The resize handle disappears so the vim view needs to update the
572     // scrollbars.
573     shouldResizeVimView = YES;
576 - (void)leaveFullscreen
578     if (!fullscreenEnabled) return;
580     fullscreenEnabled = NO;
581     [fullscreenWindow leaveFullscreen];    
582     [fullscreenWindow release];
583     fullscreenWindow = nil;
585     // The vim view may be too large to fit the screen, so update it.
586     shouldResizeVimView = YES;
589 - (void)setFullscreenBackgroundColor:(NSColor *)back
591     if (fullscreenEnabled)
592         [fullscreenWindow setBackgroundColor:back];
595 - (void)setBuffersModified:(BOOL)mod
597     // NOTE: We only set the document edited flag on the decorated window since
598     // the full-screen window has no close button anyway.  (It also saves us
599     // from keeping track of the flag in two different places.)
600     [decoratedWindow setDocumentEdited:mod];
604 - (IBAction)addNewTab:(id)sender
606     [vimView addNewTab:sender];
609 - (IBAction)toggleToolbar:(id)sender
611     [vimController sendMessage:ToggleToolbarMsgID data:nil];
614 - (IBAction)performClose:(id)sender
616     // NOTE: With the introduction of :macmenu it is possible to bind
617     // File.Close to ":conf q" but at the same time have it send off the
618     // performClose: action.  For this reason we no longer need the CloseMsgID
619     // message.  However, we still need File.Close to send performClose:
620     // otherwise Cmd-w will not work on dialogs.
621     [self vimMenuItemAction:sender];
624 - (IBAction)findNext:(id)sender
626     [self doFindNext:YES];
629 - (IBAction)findPrevious:(id)sender
631     [self doFindNext:NO];
634 - (IBAction)vimMenuItemAction:(id)sender
636     if (![sender isKindOfClass:[NSMenuItem class]]) return;
638     // TODO: Make into category on NSMenuItem which returns descriptor.
639     NSMenuItem *item = (NSMenuItem*)sender;
640     NSMutableArray *desc = [NSMutableArray arrayWithObject:[item title]];
642     NSMenu *menu = [item menu];
643     while (menu) {
644         [desc insertObject:[menu title] atIndex:0];
645         menu = [menu supermenu];
646     }
648     // The "MainMenu" item is part of the Cocoa menu and should not be part of
649     // the descriptor.
650     if ([[desc objectAtIndex:0] isEqual:@"MainMenu"])
651         [desc removeObjectAtIndex:0];
653     NSDictionary *attrs = [NSDictionary dictionaryWithObject:desc
654                                                       forKey:@"descriptor"];
655     [vimController sendMessage:ExecuteMenuMsgID data:[attrs dictionaryAsData]];
658 - (IBAction)vimToolbarItemAction:(id)sender
660     NSArray *desc = [NSArray arrayWithObjects:@"ToolBar", [sender label], nil];
661     NSDictionary *attrs = [NSDictionary dictionaryWithObject:desc
662                                                       forKey:@"descriptor"];
663     [vimController sendMessage:ExecuteMenuMsgID data:[attrs dictionaryAsData]];
666 - (IBAction)fontSizeUp:(id)sender
668     [[NSFontManager sharedFontManager] modifyFont:
669             [NSNumber numberWithInt:NSSizeUpFontAction]];
672 - (IBAction)fontSizeDown:(id)sender
674     [[NSFontManager sharedFontManager] modifyFont:
675             [NSNumber numberWithInt:NSSizeDownFontAction]];
678 - (IBAction)findAndReplace:(id)sender
680     int tag = [sender tag];
681     MMFindReplaceController *fr = [MMFindReplaceController sharedInstance];
682     int flags = 0;
684     // NOTE: The 'flags' values must match the FRD_ defines in gui.h (except
685     // for 0x100 which we use to indicate a backward search).
686     switch (tag) {
687         case 1: flags = 0x100; break;
688         case 2: flags = 3; break;
689         case 3: flags = 4; break;
690     }
692     if ([fr matchWord])
693         flags |= 0x08;
694     if (![fr ignoreCase])
695         flags |= 0x10;
697     NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
698             [fr findString],                @"find",
699             [fr replaceString],             @"replace",
700             [NSNumber numberWithInt:flags], @"flags",
701             nil];
703     [vimController sendMessage:FindReplaceMsgID data:[args dictionaryAsData]];
706 - (BOOL)validateMenuItem:(NSMenuItem *)item
708     if ([item action] == @selector(vimMenuItemAction:)
709             || [item action] == @selector(performClose:))
710         return [item tag];
712     return YES;
715 // -- NSWindow delegate ------------------------------------------------------
717 - (void)windowDidBecomeMain:(NSNotification *)notification
719     [[MMAppController sharedInstance] setMainMenu:[vimController mainMenu]];
720     [vimController sendMessage:GotFocusMsgID data:nil];
722     if ([vimView textView]) {
723         NSFontManager *fm = [NSFontManager sharedFontManager];
724         [fm setSelectedFont:[[vimView textView] font] isMultiple:NO];
725     }
728 - (void)windowDidResignMain:(NSNotification *)notification
730     [vimController sendMessage:LostFocusMsgID data:nil];
733 - (BOOL)windowShouldClose:(id)sender
735     // Don't close the window now; Instead let Vim decide whether to close the
736     // window or not.
737     [vimController sendMessage:VimShouldCloseMsgID data:nil];
738     return NO;
741 - (void)windowDidMove:(NSNotification *)notification
743     if (setupDone && windowAutosaveKey) {
744         NSRect frame = [decoratedWindow frame];
745         NSPoint topLeft = { frame.origin.x, NSMaxY(frame) };
746         NSString *topLeftString = NSStringFromPoint(topLeft);
748         [[NSUserDefaults standardUserDefaults]
749             setObject:topLeftString forKey:windowAutosaveKey];
750     }
753 - (NSSize)windowWillResize:(NSWindow *)win toSize:(NSSize)proposedFrameSize
755     // Make sure the window isn't resized to be larger than the "visible frame"
756     // for the current screen.  Do this here instead of setting the window max
757     // size in updateResizeConstraints since the screen's visible frame may
758     // change at any time (dock could move, resolution could change, window
759     // could be moved to another screen, ...).
761     NSRect maxFrame = [self constrainFrame:[[win screen] visibleFrame]];
763     if (proposedFrameSize.width > maxFrame.size.width)
764         proposedFrameSize.width = maxFrame.size.width;
765     if (proposedFrameSize.height > maxFrame.size.height)
766         proposedFrameSize.height = maxFrame.size.height;
768     return proposedFrameSize;
771 - (void)windowDidResize:(id)sender
773     if (!setupDone || fullscreenEnabled) return;
775     // NOTE: Since we have no control over when the window may resize (Cocoa
776     // may resize automatically) we simply set the view to fill the entire
777     // window.  The vim view takes care of notifying Vim if the number of
778     // (rows,columns) changed.
779     [vimView setFrameSize:[self contentSize]];
782 - (NSRect)windowWillUseStandardFrame:(NSWindow *)win
783                         defaultFrame:(NSRect)frame
785     // By default the window is maximized in the vertical direction only.
786     // Holding down the Cmd key maximizes the window in the horizontal
787     // direction.  If the MMZoomBoth user default is set, then the window
788     // maximizes in both directions by default, unless the Cmd key is held in
789     // which case the window only maximizes in the vertical direction.
791     NSEvent *event = [NSApp currentEvent];
792     BOOL cmdLeftClick = [event type] == NSLeftMouseUp
793             && [event modifierFlags] & NSCommandKeyMask;
794     BOOL zoomBoth = [[NSUserDefaults standardUserDefaults]
795             boolForKey:MMZoomBothKey];
797     // The "default frame" represents the maximal size of a zoomed window.
798     // Constrain this frame so that the content fits an even number of rows and
799     // columns.
800     frame = [self constrainFrame:frame];
802     if (!((zoomBoth && !cmdLeftClick) || (!zoomBoth && cmdLeftClick))) {
803         // Zoom in horizontal direction only.
804         NSRect currentFrame = [win frame];
805         frame.size.width = currentFrame.size.width;
806         frame.origin.x = currentFrame.origin.x;
807     }
809     return frame;
815 // -- Services menu delegate -------------------------------------------------
817 - (id)validRequestorForSendType:(NSString *)sendType
818                      returnType:(NSString *)returnType
820     if ([sendType isEqual:NSStringPboardType]
821             && [self askBackendForStarRegister:nil])
822         return self;
824     return [super validRequestorForSendType:sendType returnType:returnType];
827 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard
828                              types:(NSArray *)types
830     if (![types containsObject:NSStringPboardType])
831         return NO;
833     return [self askBackendForStarRegister:pboard];
836 @end // MMWindowController
840 @implementation MMWindowController (Private)
842 - (NSSize)contentSize
844     // NOTE: Never query the content view directly for its size since it may
845     // not return the same size as contentRectForFrameRect: (e.g. when in
846     // windowed mode and the tabline separator is visible)!
847     NSWindow *win = [self window];
848     return [win contentRectForFrameRect:[win frame]].size;
851 - (void)resizeWindowToFitContentSize:(NSSize)contentSize
852                         keepOnScreen:(BOOL)onScreen
854     NSRect frame = [decoratedWindow frame];
855     NSRect contentRect = [decoratedWindow contentRectForFrameRect:frame];
857     // Keep top-left corner of the window fixed when resizing.
858     contentRect.origin.y -= contentSize.height - contentRect.size.height;
859     contentRect.size = contentSize;
861     NSRect newFrame = [decoratedWindow frameRectForContentRect:contentRect];
863     // Ensure that the window fits inside the visible part of the screen.
864     NSRect maxFrame = [[decoratedWindow screen] visibleFrame];
865     maxFrame = [self constrainFrame:maxFrame];
867     if (newFrame.size.width > maxFrame.size.width) {
868         newFrame.size.width = maxFrame.size.width;
869         newFrame.origin.x = maxFrame.origin.x;
870     }
871     if (newFrame.size.height > maxFrame.size.height) {
872         newFrame.size.height = maxFrame.size.height;
873         newFrame.origin.y = maxFrame.origin.y;
874     }
876     if (onScreen) {
877         if (newFrame.origin.y < maxFrame.origin.y)
878             newFrame.origin.y = maxFrame.origin.y;
879         if (NSMaxX(newFrame) > NSMaxX(maxFrame))
880             newFrame.origin.x = NSMaxX(maxFrame) - newFrame.size.width;
881     }
883     [decoratedWindow setFrame:newFrame display:YES];
886 - (NSSize)constrainContentSizeToScreenSize:(NSSize)contentSize
888     NSWindow *win = [self window];
889     NSRect rect = [win contentRectForFrameRect:[[win screen] visibleFrame]];
891     if (contentSize.height > rect.size.height)
892         contentSize.height = rect.size.height;
893     if (contentSize.width > rect.size.width)
894         contentSize.width = rect.size.width;
896     return contentSize;
899 - (NSRect)constrainFrame:(NSRect)frame
901     // Constrain the given (window) frame so that it fits an even number of
902     // rows and columns.
903     NSRect contentRect = [decoratedWindow contentRectForFrameRect:frame];
904     NSSize constrainedSize = [vimView constrainRows:NULL
905                                             columns:NULL
906                                              toSize:contentRect.size];
908     contentRect.origin.y += contentRect.size.height - constrainedSize.height;
909     contentRect.size = constrainedSize;
911     return [decoratedWindow frameRectForContentRect:contentRect];
914 - (void)updateResizeConstraints
916     if (!setupDone) return;
918     // Set the resize increments to exactly match the font size; this way the
919     // window will always hold an integer number of (rows,columns).
920     NSSize cellSize = [[vimView textView] cellSize];
921     [decoratedWindow setContentResizeIncrements:cellSize];
923     NSSize minSize = [vimView minSize];
924     [decoratedWindow setContentMinSize:minSize];
927 - (NSTabViewItem *)addNewTabViewItem
929     return [vimView addNewTabViewItem];
932 - (BOOL)askBackendForStarRegister:(NSPasteboard *)pb
934     // TODO: Can this be done with evaluateExpression: instead?
935     BOOL reply = NO;
936     id backendProxy = [vimController backendProxy];
938     if (backendProxy) {
939         @try {
940             reply = [backendProxy starRegisterToPasteboard:pb];
941         }
942         @catch (NSException *e) {
943             NSLog(@"WARNING: Caught exception in %s: \"%@\"", _cmd, e);
944         }
945     }
947     return reply;
950 - (void)hideTablineSeparator:(BOOL)hide
952     // The full-screen window has no tabline separator so we operate on
953     // decoratedWindow instead of [self window].
954     if ([decoratedWindow hideTablineSeparator:hide]) {
955         // The tabline separator was toggled so the content view must change
956         // size.
957         [self updateResizeConstraints];
958         shouldResizeVimView = YES;
959     }
962 - (void)doFindNext:(BOOL)next
964     NSString *query = nil;
966 #if 0
967     // Use current query if the search field is selected.
968     id searchField = [[self searchFieldItem] view];
969     if (searchField && [[searchField stringValue] length] > 0 &&
970             [decoratedWindow firstResponder] == [searchField currentEditor])
971         query = [searchField stringValue];
972 #endif
974     if (!query) {
975         // Use find pasteboard for next query.
976         NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
977         NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
978         if ([pb availableTypeFromArray:types])
979             query = [pb stringForType:NSStringPboardType];
980     }
982     NSString *input = nil;
983     if (query) {
984         // NOTE: The '/' register holds the last search string.  By setting it
985         // (using the '@/' syntax) we fool Vim into thinking that it has
986         // already searched for that string and then we can simply use 'n' or
987         // 'N' to find the next/previous match.
988         input = [NSString stringWithFormat:@"<C-\\><C-N>:let @/='%@'<CR>%c",
989                 query, next ? 'n' : 'N'];
990     } else {
991         input = next ? @"<C-\\><C-N>n" : @"<C-\\><C-N>N"; 
992     }
994     [vimController addVimInput:input];
997 @end // MMWindowController (Private)