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;
84 - (void)updateToolbar;
88 @interface NSWindow (NSWindowPrivate)
89 // Note: This hack allows us to set content shadowing separately from
90 // the window shadow. This is apparently what webkit and terminal do.
91 - (void)_setContentHasShadow:(BOOL)shadow; // new Tiger private method
93 // This is a private api that makes textured windows not have rounded corners.
94 // We want this on Leopard.
95 - (void)setBottomCornerRounded:(BOOL)rounded;
99 @interface NSWindow (NSLeopardOnly)
100 // Note: These functions are Leopard-only, use -[NSObject respondsToSelector:]
101 // before calling them to make sure everything works on Tiger too.
103 #ifndef CGFLOAT_DEFINED
104 // On Leopard, CGFloat is float on 32bit and double on 64bit. On Tiger,
105 // we can't use this anyways, so it's just here to keep the compiler happy.
106 // However, when we're compiling for Tiger and running on Leopard, we
107 // might need the correct typedef, so this piece is copied from ATSTypes.h
109 typedef double CGFloat;
111 typedef float CGFloat;
114 - (void)setAutorecalculatesContentBorderThickness:(BOOL)b forEdge:(NSRectEdge)e;
115 - (void)setContentBorderThickness:(CGFloat)b forEdge:(NSRectEdge)e;
121 @implementation MMWindowController
123 - (id)initWithVimController:(MMVimController *)controller
125 #ifndef NSAppKitVersionNumber10_4 // needed for non-10.5 sdk
126 # define NSAppKitVersionNumber10_4 824
128 unsigned styleMask = NSTitledWindowMask | NSClosableWindowMask
129 | NSMiniaturizableWindowMask | NSResizableWindowMask
130 | NSUnifiedTitleAndToolbarWindowMask;
132 // Use textured background on Leopard or later (skip the 'if' on Tiger for
133 // polished metal window).
134 if ([[NSUserDefaults standardUserDefaults] boolForKey:MMTexturedWindowKey]
135 || (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_4))
136 styleMask |= NSTexturedBackgroundWindowMask;
138 // NOTE: The content rect is only used the very first time MacVim is
139 // started (or rather, when ~/Library/Preferences/org.vim.MacVim.plist does
140 // not exist). The chosen values will put the window somewhere near the
141 // top and in the middle of a 1024x768 screen.
142 MMWindow *win = [[MMWindow alloc]
143 initWithContentRect:NSMakeRect(242,364,480,360)
145 backing:NSBackingStoreBuffered
149 self = [super initWithWindow:win];
150 if (!self) return nil;
152 vimController = controller;
153 decoratedWindow = [win retain];
155 // Window cascading is handled by MMAppController.
156 [self setShouldCascadeWindows:NO];
158 // NOTE: Autoresizing is enabled for the content view, but only used
159 // for the tabline separator. The vim view must be resized manually
160 // because of full-screen considerations, and because its size depends
161 // on whether the tabline separator is visible or not.
162 NSView *contentView = [win contentView];
163 [contentView setAutoresizesSubviews:YES];
165 vimView = [[MMVimView alloc] initWithFrame:[contentView frame]
166 vimController:vimController];
167 [vimView setAutoresizingMask:NSViewNotSizable];
168 [contentView addSubview:vimView];
170 [win setDelegate:self];
171 [win setInitialFirstResponder:[vimView textView]];
173 if ([win styleMask] & NSTexturedBackgroundWindowMask) {
174 // On Leopard, we want to have a textured window to have nice
175 // looking tabs. But the textured window look implies rounded
176 // corners, which looks really weird -- disable them. This is a
177 // private api, though.
178 if ([win respondsToSelector:@selector(setBottomCornerRounded:)])
179 [win setBottomCornerRounded:NO];
181 // When the tab bar is toggled, it changes color for the fraction
182 // of a second, probably because vim sends us events in a strange
183 // order, confusing appkit's content border heuristic for a short
184 // while. This can be worked around with these two methods. There
185 // might be a better way, but it's good enough.
186 if ([win respondsToSelector:@selector(
187 setAutorecalculatesContentBorderThickness:forEdge:)])
188 [win setAutorecalculatesContentBorderThickness:NO
190 if ([win respondsToSelector:
191 @selector(setContentBorderThickness:forEdge:)])
192 [win setContentBorderThickness:0 forEdge:NSMaxYEdge];
195 // Make us safe on pre-tiger OSX
196 if ([win respondsToSelector:@selector(_setContentHasShadow:)])
197 [win _setContentHasShadow:NO];
206 [decoratedWindow release]; decoratedWindow = nil;
207 [windowAutosaveKey release]; windowAutosaveKey = nil;
208 [vimView release]; vimView = nil;
213 - (NSString *)description
216 @"%@ : setupDone=%d windowAutosaveKey=%@ vimController=%@";
217 return [NSString stringWithFormat:format,
218 [self className], setupDone, windowAutosaveKey, vimController];
221 - (MMVimController *)vimController
223 return vimController;
226 - (MMVimView *)vimView
231 - (NSString *)windowAutosaveKey
233 return windowAutosaveKey;
236 - (void)setWindowAutosaveKey:(NSString *)key
238 [windowAutosaveKey autorelease];
239 windowAutosaveKey = [key copy];
244 ASLogDebug(@"%@ %s", [self className], _cmd);
246 if (fullscreenEnabled) {
247 // If we are closed while still in fullscreen, end fullscreen mode,
248 // release ourselves (because this won't happen in MMWindowController)
249 // and perform close operation on the original window.
250 [self leaveFullscreen];
256 [vimView removeFromSuperviewWithoutNeedingDisplay];
259 // It is feasible (though unlikely) that the user quits before the window
260 // controller is released, make sure the edit flag is cleared so no warning
261 // dialog is displayed.
262 [decoratedWindow setDocumentEdited:NO];
264 [[self window] orderOut:self];
269 // Indicates that the window is ready to be displayed, but do not display
270 // (or place) it yet -- that is done in showWindow.
272 [self addNewTabViewItem];
276 [self updateResizeConstraints];
277 [self resizeWindowToFitContentSize:[vimView desiredSize]
283 // Actually show the window on screen. However, if openWindow hasn't
284 // already been called nothing will happen (the window will be displayed
286 if (!setupDone) return;
288 [[MMAppController sharedInstance] windowControllerWillOpen:self];
289 [[self window] makeKeyAndOrderFront:self];
292 - (void)updateTabsWithData:(NSData *)data
294 [vimView updateTabsWithData:data];
297 - (void)selectTabWithIndex:(int)idx
299 [vimView selectTabWithIndex:idx];
302 - (void)setTextDimensionsWithRows:(int)rows columns:(int)cols isLive:(BOOL)live
305 ASLogDebug(@"setTextDimensionsWithRows:%d columns:%d isLive:%d isReply:%d",
306 rows, cols, live, reply);
308 // NOTE: The only place where the (rows,columns) of the vim view are
309 // modified is here and when entering/leaving full-screen. Setting these
310 // values have no immediate effect, the actual resizing of the view is done
311 // in processInputQueueDidFinish.
313 // The 'live' flag indicates that this resize originated from a live
314 // resize; it may very well happen that the view is no longer in live
315 // resize when this message is received. We refrain from changing the view
316 // size when this flag is set, otherwise the window might jitter when the
317 // user drags to resize the window.
319 // The 'reply' flag indicates that this resize originated in MacVim and
320 // that Vim is now replying to that resize to make sure that it comes into
323 [vimView setDesiredRows:rows columns:cols];
325 if (setupDone && !live) {
326 shouldResizeVimView = YES;
327 keepOnScreen = !reply;
331 - (void)setTitle:(NSString *)title
334 [decoratedWindow setTitle:title];
337 - (void)setDocumentFilename:(NSString *)filename
342 // Ensure file really exists or the path to the proxy icon will look weird.
343 // If the file does not exists, don't show a proxy icon.
344 if (![[NSFileManager defaultManager] fileExistsAtPath:filename])
347 [decoratedWindow setRepresentedFilename:filename];
350 - (void)setToolbar:(NSToolbar *)toolbar
352 // The full-screen window has no toolbar.
353 [decoratedWindow setToolbar:toolbar];
355 // HACK! Redirect the pill button so that we can ask Vim to hide the
357 NSButton *pillButton = [decoratedWindow
358 standardWindowButton:NSWindowToolbarButton];
360 [pillButton setAction:@selector(toggleToolbar:)];
361 [pillButton setTarget:self];
365 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
367 [vimView createScrollbarWithIdentifier:ident type:type];
370 - (BOOL)destroyScrollbarWithIdentifier:(long)ident
372 BOOL scrollbarHidden = [vimView destroyScrollbarWithIdentifier:ident];
373 shouldResizeVimView = shouldResizeVimView || scrollbarHidden;
375 return scrollbarHidden;
378 - (BOOL)showScrollbarWithIdentifier:(long)ident state:(BOOL)visible
380 BOOL scrollbarToggled = [vimView showScrollbarWithIdentifier:ident
382 shouldResizeVimView = shouldResizeVimView || scrollbarToggled;
384 return scrollbarToggled;
387 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
389 [vimView setScrollbarPosition:pos length:len identifier:ident];
392 - (void)setScrollbarThumbValue:(float)val proportion:(float)prop
393 identifier:(long)ident
395 [vimView setScrollbarThumbValue:val proportion:prop identifier:ident];
398 - (void)setDefaultColorsBackground:(NSColor *)back foreground:(NSColor *)fore
400 // NOTE: This is called when the transparency changes so set the opacity
401 // flag on the window here (should be faster if the window is opaque).
402 BOOL isOpaque = [back alphaComponent] == 1.0f;
403 [decoratedWindow setOpaque:isOpaque];
404 if (fullscreenEnabled)
405 [fullscreenWindow setOpaque:isOpaque];
407 [vimView setDefaultColorsBackground:back foreground:fore];
410 - (void)setFont:(NSFont *)font
412 [[NSFontManager sharedFontManager] setSelectedFont:font isMultiple:NO];
413 [[vimView textView] setFont:font];
414 [self updateResizeConstraints];
417 - (void)setWideFont:(NSFont *)font
419 [[vimView textView] setWideFont:font];
422 - (void)processInputQueueDidFinish
424 // NOTE: Resizing is delayed until after all commands have been processed
425 // since it often happens that more than one command will cause a resize.
426 // If we were to immediately resize then the vim view size would jitter
427 // (e.g. hiding/showing scrollbars often happens several time in one
429 // Also delay toggling the toolbar until after scrollbars otherwise
430 // problems arise when showing toolbar and scrollbar at the same time, i.e.
433 if (shouldResizeVimView) {
434 shouldResizeVimView = NO;
436 NSSize contentSize = [vimView desiredSize];
437 contentSize = [self constrainContentSizeToScreenSize:contentSize];
438 contentSize = [vimView constrainRows:NULL columns:NULL
440 [vimView setFrameSize:contentSize];
442 if (fullscreenEnabled) {
443 [[fullscreenWindow contentView] setNeedsDisplay:YES];
444 [fullscreenWindow centerView];
446 [self resizeWindowToFitContentSize:contentSize
447 keepOnScreen:keepOnScreen];
453 if (updateToolbarFlag != 0)
454 [self updateToolbar];
457 - (void)showTabBar:(BOOL)on
459 [[vimView tabBarControl] setHidden:!on];
461 // Showing the tabline may result in the tabline separator being hidden or
462 // shown; this does not apply to full-screen mode.
464 NSToolbar *toolbar = [decoratedWindow toolbar];
465 if (([decoratedWindow styleMask] & NSTexturedBackgroundWindowMask)
467 [self hideTablineSeparator:![toolbar isVisible]];
469 [self hideTablineSeparator:NO];
472 if (([decoratedWindow styleMask] & NSTexturedBackgroundWindowMask)
474 [self hideTablineSeparator:on];
476 [self hideTablineSeparator:YES];
481 - (void)showToolbar:(BOOL)on size:(int)size mode:(int)mode
483 NSToolbar *toolbar = [decoratedWindow toolbar];
484 if (!toolbar) return;
486 [toolbar setSizeMode:size];
487 [toolbar setDisplayMode:mode];
489 // Positive flag shows toolbar, negative hides it.
490 updateToolbarFlag = on ? 1 : -1;
492 // NOTE: If the window is not visible we must toggle the toolbar
493 // immediately, otherwise "set go-=T" in .gvimrc will lead to the toolbar
494 // showing its hide animation every time a new window is opened. (See
495 // processInputQueueDidFinish for the reason why we need to delay toggling
496 // the toolbar when the window is visible.)
497 if (![decoratedWindow isVisible])
498 [self updateToolbar];
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 ASLogDebug(@"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
763 if (fullscreenEnabled) {
764 // HACK! The full-screen is not supposed to be able to be moved. If we
765 // do get here while in full-screen something unexpected happened (e.g.
766 // the full-screen window was on an external display that got
767 // unplugged) and we handle this situation by leaving full-screen.
768 [self leaveFullscreen];
772 if (windowAutosaveKey) {
773 NSRect frame = [decoratedWindow frame];
774 NSPoint topLeft = { frame.origin.x, NSMaxY(frame) };
775 NSString *topLeftString = NSStringFromPoint(topLeft);
777 [[NSUserDefaults standardUserDefaults]
778 setObject:topLeftString forKey:windowAutosaveKey];
782 - (NSSize)windowWillResize:(NSWindow *)win toSize:(NSSize)proposedFrameSize
784 // Make sure the window isn't resized to be larger than the "visible frame"
785 // for the current screen. Do this here instead of setting the window max
786 // size in updateResizeConstraints since the screen's visible frame may
787 // change at any time (dock could move, resolution could change, window
788 // could be moved to another screen, ...).
790 return proposedFrameSize;
792 // NOTE: Not called in full-screen mode so use "visibleFrame" instead of
794 NSRect maxFrame = [self constrainFrame:[[win screen] visibleFrame]];
796 if (proposedFrameSize.width > maxFrame.size.width)
797 proposedFrameSize.width = maxFrame.size.width;
798 if (proposedFrameSize.height > maxFrame.size.height)
799 proposedFrameSize.height = maxFrame.size.height;
801 return proposedFrameSize;
804 - (void)windowDidResize:(id)sender
806 if (!setupDone || fullscreenEnabled) return;
808 // NOTE: Since we have no control over when the window may resize (Cocoa
809 // may resize automatically) we simply set the view to fill the entire
810 // window. The vim view takes care of notifying Vim if the number of
811 // (rows,columns) changed.
812 [vimView setFrameSize:[self contentSize]];
815 - (NSRect)windowWillUseStandardFrame:(NSWindow *)win
816 defaultFrame:(NSRect)frame
818 // By default the window is maximized in the vertical direction only.
819 // Holding down the Cmd key maximizes the window in the horizontal
820 // direction. If the MMZoomBoth user default is set, then the window
821 // maximizes in both directions by default, unless the Cmd key is held in
822 // which case the window only maximizes in the vertical direction.
824 NSEvent *event = [NSApp currentEvent];
825 BOOL cmdLeftClick = [event type] == NSLeftMouseUp
826 && [event modifierFlags] & NSCommandKeyMask;
827 BOOL zoomBoth = [[NSUserDefaults standardUserDefaults]
828 boolForKey:MMZoomBothKey];
830 // The "default frame" represents the maximal size of a zoomed window.
831 // Constrain this frame so that the content fits an even number of rows and
833 frame = [self constrainFrame:frame];
835 if (!((zoomBoth && !cmdLeftClick) || (!zoomBoth && cmdLeftClick))) {
836 // Zoom in horizontal direction only.
837 NSRect currentFrame = [win frame];
838 frame.size.width = currentFrame.size.width;
839 frame.origin.x = currentFrame.origin.x;
848 // -- Services menu delegate -------------------------------------------------
850 - (id)validRequestorForSendType:(NSString *)sendType
851 returnType:(NSString *)returnType
853 if ([sendType isEqual:NSStringPboardType]
854 && [self askBackendForStarRegister:nil])
857 return [super validRequestorForSendType:sendType returnType:returnType];
860 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard
861 types:(NSArray *)types
863 if (![types containsObject:NSStringPboardType])
866 return [self askBackendForStarRegister:pboard];
869 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard
871 // Replace the current selection with the text on the pasteboard.
872 NSArray *types = [pboard types];
873 if ([types containsObject:NSStringPboardType]) {
874 NSString *input = [NSString stringWithFormat:@"s%@",
875 [pboard stringForType:NSStringPboardType]];
876 [vimController addVimInput:input];
883 @end // MMWindowController
887 @implementation MMWindowController (Private)
889 - (NSSize)contentSize
891 // NOTE: Never query the content view directly for its size since it may
892 // not return the same size as contentRectForFrameRect: (e.g. when in
893 // windowed mode and the tabline separator is visible)!
894 NSWindow *win = [self window];
895 return [win contentRectForFrameRect:[win frame]].size;
898 - (void)resizeWindowToFitContentSize:(NSSize)contentSize
899 keepOnScreen:(BOOL)onScreen
901 NSRect frame = [decoratedWindow frame];
902 NSRect contentRect = [decoratedWindow contentRectForFrameRect:frame];
904 // Keep top-left corner of the window fixed when resizing.
905 contentRect.origin.y -= contentSize.height - contentRect.size.height;
906 contentRect.size = contentSize;
908 NSRect newFrame = [decoratedWindow frameRectForContentRect:contentRect];
910 if ([decoratedWindow screen]) {
911 // Ensure that the window fits inside the visible part of the screen.
912 // NOTE: Not called in full-screen mode so use "visibleFrame' instead
914 NSRect maxFrame = [[decoratedWindow screen] visibleFrame];
915 maxFrame = [self constrainFrame:maxFrame];
917 if (newFrame.size.width > maxFrame.size.width) {
918 newFrame.size.width = maxFrame.size.width;
919 newFrame.origin.x = maxFrame.origin.x;
921 if (newFrame.size.height > maxFrame.size.height) {
922 newFrame.size.height = maxFrame.size.height;
923 newFrame.origin.y = maxFrame.origin.y;
927 if (newFrame.origin.y < maxFrame.origin.y)
928 newFrame.origin.y = maxFrame.origin.y;
929 if (NSMaxX(newFrame) > NSMaxX(maxFrame))
930 newFrame.origin.x = NSMaxX(maxFrame) - newFrame.size.width;
934 [decoratedWindow setFrame:newFrame display:YES];
937 - (NSSize)constrainContentSizeToScreenSize:(NSSize)contentSize
939 NSWindow *win = [self window];
943 // NOTE: This may be called in both windowed and full-screen mode. The
944 // "visibleFrame" method does not overlap menu and dock so should not be
945 // used in full-screen.
946 NSRect screenRect = fullscreenEnabled ? [[win screen] frame]
947 : [[win screen] visibleFrame];
948 NSRect rect = [win contentRectForFrameRect:screenRect];
950 if (contentSize.height > rect.size.height)
951 contentSize.height = rect.size.height;
952 if (contentSize.width > rect.size.width)
953 contentSize.width = rect.size.width;
958 - (NSRect)constrainFrame:(NSRect)frame
960 // Constrain the given (window) frame so that it fits an even number of
962 NSRect contentRect = [decoratedWindow contentRectForFrameRect:frame];
963 NSSize constrainedSize = [vimView constrainRows:NULL
965 toSize:contentRect.size];
967 contentRect.origin.y += contentRect.size.height - constrainedSize.height;
968 contentRect.size = constrainedSize;
970 return [decoratedWindow frameRectForContentRect:contentRect];
973 - (void)updateResizeConstraints
975 if (!setupDone) return;
977 // Set the resize increments to exactly match the font size; this way the
978 // window will always hold an integer number of (rows,columns).
979 NSSize cellSize = [[vimView textView] cellSize];
980 [decoratedWindow setContentResizeIncrements:cellSize];
982 NSSize minSize = [vimView minSize];
983 [decoratedWindow setContentMinSize:minSize];
986 - (NSTabViewItem *)addNewTabViewItem
988 return [vimView addNewTabViewItem];
991 - (BOOL)askBackendForStarRegister:(NSPasteboard *)pb
993 // TODO: Can this be done with evaluateExpression: instead?
995 id backendProxy = [vimController backendProxy];
999 reply = [backendProxy starRegisterToPasteboard:pb];
1001 @catch (NSException *ex) {
1002 ASLogNotice(@"starRegisterToPasteboard: failed: pid=%d reason=%@",
1003 [vimController pid], ex);
1010 - (void)hideTablineSeparator:(BOOL)hide
1012 // The full-screen window has no tabline separator so we operate on
1013 // decoratedWindow instead of [self window].
1014 if ([decoratedWindow hideTablineSeparator:hide]) {
1015 // The tabline separator was toggled so the content view must change
1017 [self updateResizeConstraints];
1018 shouldResizeVimView = YES;
1022 - (void)doFindNext:(BOOL)next
1024 NSString *query = nil;
1027 // Use current query if the search field is selected.
1028 id searchField = [[self searchFieldItem] view];
1029 if (searchField && [[searchField stringValue] length] > 0 &&
1030 [decoratedWindow firstResponder] == [searchField currentEditor])
1031 query = [searchField stringValue];
1035 // Use find pasteboard for next query.
1036 NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1037 NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
1038 if ([pb availableTypeFromArray:types])
1039 query = [pb stringForType:NSStringPboardType];
1042 NSString *input = nil;
1044 // NOTE: The '/' register holds the last search string. By setting it
1045 // (using the '@/' syntax) we fool Vim into thinking that it has
1046 // already searched for that string and then we can simply use 'n' or
1047 // 'N' to find the next/previous match.
1048 input = [NSString stringWithFormat:@"<C-\\><C-N>:let @/='%@'<CR>%c",
1049 query, next ? 'n' : 'N'];
1051 input = next ? @"<C-\\><C-N>n" : @"<C-\\><C-N>N";
1054 [vimController addVimInput:input];
1057 - (void)updateToolbar
1059 NSToolbar *toolbar = [decoratedWindow toolbar];
1060 if (nil == toolbar || 0 == updateToolbarFlag) return;
1062 // Positive flag shows toolbar, negative hides it.
1063 BOOL on = updateToolbarFlag > 0 ? YES : NO;
1064 [toolbar setVisible:on];
1066 if (([decoratedWindow styleMask] & NSTexturedBackgroundWindowMask) == 0) {
1068 [self hideTablineSeparator:YES];
1070 [self hideTablineSeparator:![[vimView tabBarControl] isHidden]];
1073 // Textured windows don't have a line below there title bar, so we
1074 // need the separator in this case as well. In fact, the only case
1075 // where we don't need the separator is when the tab bar control
1076 // is visible (because it brings its own separator).
1077 [self hideTablineSeparator:![[vimView tabBarControl] isHidden]];
1080 updateToolbarFlag = 0;
1083 @end // MMWindowController (Private)