1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
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.
13 * Handles resizing of windows, acts as an mediator between MMVimView and
16 * Resizing in windowed mode:
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.
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).
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
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:
38 * Tabline visible & Toolbar visible => Separator visible
39 * =====================================================================
40 * NO & NO => YES, if the window is textured
47 * Resizing in full-screen mode:
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
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.
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"
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;
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;
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
108 typedef double CGFloat;
110 typedef float CGFloat;
113 - (void)setAutorecalculatesContentBorderThickness:(BOOL)b forEdge:(NSRectEdge)e;
114 - (void)setContentBorderThickness:(CGFloat)b forEdge:(NSRectEdge)e;
120 @implementation MMWindowController
122 - (id)initWithVimController:(MMVimController *)controller
124 #ifndef NSAppKitVersionNumber10_4 // needed for non-10.5 sdk
125 # define NSAppKitVersionNumber10_4 824
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)
144 backing:NSBackingStoreBuffered
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]];
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
189 if ([win respondsToSelector:
190 @selector(setContentBorderThickness:forEdge:)])
191 [win setContentBorderThickness:0 forEdge:NSMaxYEdge];
194 // Make us safe on pre-tiger OSX
195 if ([win respondsToSelector:@selector(_setContentHasShadow:)])
196 [win _setContentHasShadow:NO];
205 [decoratedWindow release]; decoratedWindow = nil;
206 [windowAutosaveKey release]; windowAutosaveKey = nil;
207 [vimView release]; vimView = nil;
212 - (NSString *)description
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
230 - (NSString *)windowAutosaveKey
232 return windowAutosaveKey;
235 - (void)setWindowAutosaveKey:(NSString *)key
237 [windowAutosaveKey autorelease];
238 windowAutosaveKey = [key copy];
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];
255 [vimView removeFromSuperviewWithoutNeedingDisplay];
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];
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];
275 [self updateResizeConstraints];
276 [self resizeWindowToFitContentSize:[vimView desiredSize]
282 // Actually show the window on screen. However, if openWindow hasn't
283 // already been called nothing will happen (the window will be displayed
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
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.
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.
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
322 [vimView setDesiredRows:rows columns:cols];
324 if (setupDone && !live) {
325 shouldResizeVimView = YES;
326 keepOnScreen = !reply;
330 - (void)setTitle:(NSString *)title
333 [decoratedWindow setTitle:title];
336 - (void)setDocumentFilename:(NSString *)filename
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])
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
356 NSButton *pillButton = [decoratedWindow
357 standardWindowButton:NSWindowToolbarButton];
359 [pillButton setAction:@selector(toggleToolbar:)];
360 [pillButton setTarget:self];
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
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
432 if (shouldResizeVimView) {
433 shouldResizeVimView = NO;
435 NSSize contentSize = [vimView desiredSize];
436 contentSize = [self constrainContentSizeToScreenSize:contentSize];
437 contentSize = [vimView constrainRows:NULL columns:NULL
439 [vimView setFrameSize:contentSize];
441 if (fullscreenEnabled) {
442 [[fullscreenWindow contentView] setNeedsDisplay:YES];
443 [fullscreenWindow centerView];
445 [self resizeWindowToFitContentSize:contentSize
446 keepOnScreen:keepOnScreen];
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.
460 NSToolbar *toolbar = [decoratedWindow toolbar];
461 if (([decoratedWindow styleMask] & NSTexturedBackgroundWindowMask)
463 [self hideTablineSeparator:![toolbar isVisible]];
465 [self hideTablineSeparator:NO];
468 if (([decoratedWindow styleMask] & NSTexturedBackgroundWindowMask)
470 [self hideTablineSeparator:on];
472 [self hideTablineSeparator:YES];
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) {
488 [self hideTablineSeparator:YES];
490 [self hideTablineSeparator:![[vimView tabBarControl] isHidden]];
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]];
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;
514 - (void)liveResizeWillStart
516 if (!setupDone) return;
518 // Save the original title, if we haven't already.
519 if (lastSetTitle == nil) {
520 lastSetTitle = [[decoratedWindow title] retain];
523 // NOTE: During live resize Cocoa goes into "event tracking mode". We have
524 // to add the backend connection to this mode in order for resize messages
525 // from Vim to reach MacVim. We do not wish to always listen to requests
526 // in event tracking mode since then MacVim could receive DO messages at
527 // unexpected times (e.g. when a key equivalent is pressed and the menu bar
528 // momentarily lights up).
529 id proxy = [vimController backendProxy];
530 NSConnection *connection = [(NSDistantObject*)proxy connectionForProxy];
531 [connection addRequestMode:NSEventTrackingRunLoopMode];
534 - (void)liveResizeDidEnd
536 if (!setupDone) return;
538 // See comment above regarding event tracking mode.
539 id proxy = [vimController backendProxy];
540 NSConnection *connection = [(NSDistantObject*)proxy connectionForProxy];
541 [connection removeRequestMode:NSEventTrackingRunLoopMode];
543 // NOTE: During live resize messages from MacVim to Vim are often dropped
544 // (because too many messages are sent at once). This may lead to
545 // inconsistent states between Vim and MacVim; to avoid this we send a
546 // synchronous resize message to Vim now (this is not fool-proof, but it
547 // does seem to work quite well).
550 NSSize textViewSize = [[vimView textView] frame].size;
551 [[vimView textView] constrainRows:&constrained[0] columns:&constrained[1]
552 toSize:textViewSize];
554 //NSLog(@"End of live resize, notify Vim that text dimensions are %dx%d",
555 // constrained[1], constrained[0]);
557 NSData *data = [NSData dataWithBytes:constrained length:2*sizeof(int)];
558 BOOL sendOk = [vimController sendMessageNow:SetTextDimensionsMsgID
563 // Sending of synchronous message failed. Force the window size to
564 // match the last dimensions received from Vim, otherwise we end up
565 // with inconsistent states.
566 [self resizeWindowToFitContentSize:[vimView desiredSize]
570 // If we saved the original title while resizing, restore it.
571 if (lastSetTitle != nil) {
572 [decoratedWindow setTitle:lastSetTitle];
573 [lastSetTitle release];
578 - (void)enterFullscreen:(int)fuoptions backgroundColor:(NSColor *)back
580 if (fullscreenEnabled) return;
582 fullscreenWindow = [[MMFullscreenWindow alloc]
583 initWithWindow:decoratedWindow view:vimView backgroundColor:back];
584 [fullscreenWindow enterFullscreen:fuoptions];
585 [fullscreenWindow setDelegate:self];
586 fullscreenEnabled = YES;
588 // The resize handle disappears so the vim view needs to update the
590 shouldResizeVimView = YES;
593 - (void)leaveFullscreen
595 if (!fullscreenEnabled) return;
597 fullscreenEnabled = NO;
598 [fullscreenWindow leaveFullscreen];
599 [fullscreenWindow release];
600 fullscreenWindow = nil;
602 // The vim view may be too large to fit the screen, so update it.
603 shouldResizeVimView = YES;
606 - (void)setFullscreenBackgroundColor:(NSColor *)back
608 if (fullscreenEnabled)
609 [fullscreenWindow setBackgroundColor:back];
612 - (void)setBuffersModified:(BOOL)mod
614 // NOTE: We only set the document edited flag on the decorated window since
615 // the full-screen window has no close button anyway. (It also saves us
616 // from keeping track of the flag in two different places.)
617 [decoratedWindow setDocumentEdited:mod];
621 - (IBAction)addNewTab:(id)sender
623 [vimView addNewTab:sender];
626 - (IBAction)toggleToolbar:(id)sender
628 [vimController sendMessage:ToggleToolbarMsgID data:nil];
631 - (IBAction)performClose:(id)sender
633 // NOTE: With the introduction of :macmenu it is possible to bind
634 // File.Close to ":conf q" but at the same time have it send off the
635 // performClose: action. For this reason we no longer need the CloseMsgID
636 // message. However, we still need File.Close to send performClose:
637 // otherwise Cmd-w will not work on dialogs.
638 [self vimMenuItemAction:sender];
641 - (IBAction)findNext:(id)sender
643 [self doFindNext:YES];
646 - (IBAction)findPrevious:(id)sender
648 [self doFindNext:NO];
651 - (IBAction)vimMenuItemAction:(id)sender
653 if (![sender isKindOfClass:[NSMenuItem class]]) return;
655 // TODO: Make into category on NSMenuItem which returns descriptor.
656 NSMenuItem *item = (NSMenuItem*)sender;
657 NSMutableArray *desc = [NSMutableArray arrayWithObject:[item title]];
659 NSMenu *menu = [item menu];
661 [desc insertObject:[menu title] atIndex:0];
662 menu = [menu supermenu];
665 // The "MainMenu" item is part of the Cocoa menu and should not be part of
667 if ([[desc objectAtIndex:0] isEqual:@"MainMenu"])
668 [desc removeObjectAtIndex:0];
670 NSDictionary *attrs = [NSDictionary dictionaryWithObject:desc
671 forKey:@"descriptor"];
672 [vimController sendMessage:ExecuteMenuMsgID data:[attrs dictionaryAsData]];
675 - (IBAction)vimToolbarItemAction:(id)sender
677 NSArray *desc = [NSArray arrayWithObjects:@"ToolBar", [sender label], nil];
678 NSDictionary *attrs = [NSDictionary dictionaryWithObject:desc
679 forKey:@"descriptor"];
680 [vimController sendMessage:ExecuteMenuMsgID data:[attrs dictionaryAsData]];
683 - (IBAction)fontSizeUp:(id)sender
685 [[NSFontManager sharedFontManager] modifyFont:
686 [NSNumber numberWithInt:NSSizeUpFontAction]];
689 - (IBAction)fontSizeDown:(id)sender
691 [[NSFontManager sharedFontManager] modifyFont:
692 [NSNumber numberWithInt:NSSizeDownFontAction]];
695 - (IBAction)findAndReplace:(id)sender
697 int tag = [sender tag];
698 MMFindReplaceController *fr = [MMFindReplaceController sharedInstance];
701 // NOTE: The 'flags' values must match the FRD_ defines in gui.h (except
702 // for 0x100 which we use to indicate a backward search).
704 case 1: flags = 0x100; break;
705 case 2: flags = 3; break;
706 case 3: flags = 4; break;
711 if (![fr ignoreCase])
714 NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
715 [fr findString], @"find",
716 [fr replaceString], @"replace",
717 [NSNumber numberWithInt:flags], @"flags",
720 [vimController sendMessage:FindReplaceMsgID data:[args dictionaryAsData]];
723 - (BOOL)validateMenuItem:(NSMenuItem *)item
725 if ([item action] == @selector(vimMenuItemAction:)
726 || [item action] == @selector(performClose:))
732 // -- NSWindow delegate ------------------------------------------------------
734 - (void)windowDidBecomeMain:(NSNotification *)notification
736 [[MMAppController sharedInstance] setMainMenu:[vimController mainMenu]];
737 [vimController sendMessage:GotFocusMsgID data:nil];
739 if ([vimView textView]) {
740 NSFontManager *fm = [NSFontManager sharedFontManager];
741 [fm setSelectedFont:[[vimView textView] font] isMultiple:NO];
745 - (void)windowDidResignMain:(NSNotification *)notification
747 [vimController sendMessage:LostFocusMsgID data:nil];
750 - (BOOL)windowShouldClose:(id)sender
752 // Don't close the window now; Instead let Vim decide whether to close the
754 [vimController sendMessage:VimShouldCloseMsgID data:nil];
758 - (void)windowDidMove:(NSNotification *)notification
760 if (setupDone && windowAutosaveKey) {
761 NSRect frame = [decoratedWindow frame];
762 NSPoint topLeft = { frame.origin.x, NSMaxY(frame) };
763 NSString *topLeftString = NSStringFromPoint(topLeft);
765 [[NSUserDefaults standardUserDefaults]
766 setObject:topLeftString forKey:windowAutosaveKey];
770 - (NSSize)windowWillResize:(NSWindow *)win toSize:(NSSize)proposedFrameSize
772 // Make sure the window isn't resized to be larger than the "visible frame"
773 // for the current screen. Do this here instead of setting the window max
774 // size in updateResizeConstraints since the screen's visible frame may
775 // change at any time (dock could move, resolution could change, window
776 // could be moved to another screen, ...).
778 NSRect maxFrame = [self constrainFrame:[[win screen] visibleFrame]];
780 if (proposedFrameSize.width > maxFrame.size.width)
781 proposedFrameSize.width = maxFrame.size.width;
782 if (proposedFrameSize.height > maxFrame.size.height)
783 proposedFrameSize.height = maxFrame.size.height;
785 return proposedFrameSize;
788 - (void)windowDidResize:(id)sender
790 if (!setupDone || fullscreenEnabled) return;
792 // NOTE: Since we have no control over when the window may resize (Cocoa
793 // may resize automatically) we simply set the view to fill the entire
794 // window. The vim view takes care of notifying Vim if the number of
795 // (rows,columns) changed.
796 [vimView setFrameSize:[self contentSize]];
799 - (NSRect)windowWillUseStandardFrame:(NSWindow *)win
800 defaultFrame:(NSRect)frame
802 // By default the window is maximized in the vertical direction only.
803 // Holding down the Cmd key maximizes the window in the horizontal
804 // direction. If the MMZoomBoth user default is set, then the window
805 // maximizes in both directions by default, unless the Cmd key is held in
806 // which case the window only maximizes in the vertical direction.
808 NSEvent *event = [NSApp currentEvent];
809 BOOL cmdLeftClick = [event type] == NSLeftMouseUp
810 && [event modifierFlags] & NSCommandKeyMask;
811 BOOL zoomBoth = [[NSUserDefaults standardUserDefaults]
812 boolForKey:MMZoomBothKey];
814 // The "default frame" represents the maximal size of a zoomed window.
815 // Constrain this frame so that the content fits an even number of rows and
817 frame = [self constrainFrame:frame];
819 if (!((zoomBoth && !cmdLeftClick) || (!zoomBoth && cmdLeftClick))) {
820 // Zoom in horizontal direction only.
821 NSRect currentFrame = [win frame];
822 frame.size.width = currentFrame.size.width;
823 frame.origin.x = currentFrame.origin.x;
832 // -- Services menu delegate -------------------------------------------------
834 - (id)validRequestorForSendType:(NSString *)sendType
835 returnType:(NSString *)returnType
837 if ([sendType isEqual:NSStringPboardType]
838 && [self askBackendForStarRegister:nil])
841 return [super validRequestorForSendType:sendType returnType:returnType];
844 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard
845 types:(NSArray *)types
847 if (![types containsObject:NSStringPboardType])
850 return [self askBackendForStarRegister:pboard];
853 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard
855 // Replace the current selection with the text on the pasteboard.
856 NSArray *types = [pboard types];
857 if ([types containsObject:NSStringPboardType]) {
858 NSString *input = [NSString stringWithFormat:@"s%@",
859 [pboard stringForType:NSStringPboardType]];
860 [vimController addVimInput:input];
867 @end // MMWindowController
871 @implementation MMWindowController (Private)
873 - (NSSize)contentSize
875 // NOTE: Never query the content view directly for its size since it may
876 // not return the same size as contentRectForFrameRect: (e.g. when in
877 // windowed mode and the tabline separator is visible)!
878 NSWindow *win = [self window];
879 return [win contentRectForFrameRect:[win frame]].size;
882 - (void)resizeWindowToFitContentSize:(NSSize)contentSize
883 keepOnScreen:(BOOL)onScreen
885 NSRect frame = [decoratedWindow frame];
886 NSRect contentRect = [decoratedWindow contentRectForFrameRect:frame];
888 // Keep top-left corner of the window fixed when resizing.
889 contentRect.origin.y -= contentSize.height - contentRect.size.height;
890 contentRect.size = contentSize;
892 NSRect newFrame = [decoratedWindow frameRectForContentRect:contentRect];
894 // Ensure that the window fits inside the visible part of the screen.
895 NSRect maxFrame = [[decoratedWindow screen] visibleFrame];
896 maxFrame = [self constrainFrame:maxFrame];
898 if (newFrame.size.width > maxFrame.size.width) {
899 newFrame.size.width = maxFrame.size.width;
900 newFrame.origin.x = maxFrame.origin.x;
902 if (newFrame.size.height > maxFrame.size.height) {
903 newFrame.size.height = maxFrame.size.height;
904 newFrame.origin.y = maxFrame.origin.y;
908 if (newFrame.origin.y < maxFrame.origin.y)
909 newFrame.origin.y = maxFrame.origin.y;
910 if (NSMaxX(newFrame) > NSMaxX(maxFrame))
911 newFrame.origin.x = NSMaxX(maxFrame) - newFrame.size.width;
914 [decoratedWindow setFrame:newFrame display:YES];
917 - (NSSize)constrainContentSizeToScreenSize:(NSSize)contentSize
919 NSWindow *win = [self window];
920 NSRect rect = [win contentRectForFrameRect:[[win screen] visibleFrame]];
922 if (contentSize.height > rect.size.height)
923 contentSize.height = rect.size.height;
924 if (contentSize.width > rect.size.width)
925 contentSize.width = rect.size.width;
930 - (NSRect)constrainFrame:(NSRect)frame
932 // Constrain the given (window) frame so that it fits an even number of
934 NSRect contentRect = [decoratedWindow contentRectForFrameRect:frame];
935 NSSize constrainedSize = [vimView constrainRows:NULL
937 toSize:contentRect.size];
939 contentRect.origin.y += contentRect.size.height - constrainedSize.height;
940 contentRect.size = constrainedSize;
942 return [decoratedWindow frameRectForContentRect:contentRect];
945 - (void)updateResizeConstraints
947 if (!setupDone) return;
949 // Set the resize increments to exactly match the font size; this way the
950 // window will always hold an integer number of (rows,columns).
951 NSSize cellSize = [[vimView textView] cellSize];
952 [decoratedWindow setContentResizeIncrements:cellSize];
954 NSSize minSize = [vimView minSize];
955 [decoratedWindow setContentMinSize:minSize];
958 - (NSTabViewItem *)addNewTabViewItem
960 return [vimView addNewTabViewItem];
963 - (BOOL)askBackendForStarRegister:(NSPasteboard *)pb
965 // TODO: Can this be done with evaluateExpression: instead?
967 id backendProxy = [vimController backendProxy];
971 reply = [backendProxy starRegisterToPasteboard:pb];
973 @catch (NSException *e) {
974 NSLog(@"WARNING: Caught exception in %s: \"%@\"", _cmd, e);
981 - (void)hideTablineSeparator:(BOOL)hide
983 // The full-screen window has no tabline separator so we operate on
984 // decoratedWindow instead of [self window].
985 if ([decoratedWindow hideTablineSeparator:hide]) {
986 // The tabline separator was toggled so the content view must change
988 [self updateResizeConstraints];
989 shouldResizeVimView = YES;
993 - (void)doFindNext:(BOOL)next
995 NSString *query = nil;
998 // Use current query if the search field is selected.
999 id searchField = [[self searchFieldItem] view];
1000 if (searchField && [[searchField stringValue] length] > 0 &&
1001 [decoratedWindow firstResponder] == [searchField currentEditor])
1002 query = [searchField stringValue];
1006 // Use find pasteboard for next query.
1007 NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1008 NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
1009 if ([pb availableTypeFromArray:types])
1010 query = [pb stringForType:NSStringPboardType];
1013 NSString *input = nil;
1015 // NOTE: The '/' register holds the last search string. By setting it
1016 // (using the '@/' syntax) we fool Vim into thinking that it has
1017 // already searched for that string and then we can simply use 'n' or
1018 // 'N' to find the next/previous match.
1019 input = [NSString stringWithFormat:@"<C-\\><C-N>:let @/='%@'<CR>%c",
1020 query, next ? 'n' : 'N'];
1022 input = next ? @"<C-\\><C-N>n" : @"<C-\\><C-N>N";
1025 [vimController addVimInput:input];
1028 @end // MMWindowController (Private)