/
MMWindowController.m
1581 lines (1321 loc) · 55.5 KB
/
MMWindowController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vi:set ts=8 sts=4 sw=4 ft=objc:
*
* VIM - Vi IMproved by Bram Moolenaar
* MacVim GUI port by Bjorn Winckler
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* MMWindowController
*
* Handles resizing of windows, acts as an mediator between MMVimView and
* MMVimController.
*
* Resizing in windowed mode:
*
* In windowed mode resizing can occur either due to the window frame changing
* size (e.g. when the user drags to resize), or due to Vim changing the number
* of (rows,columns). The former case is dealt with by letting the vim view
* fill the entire content view when the window has resized. In the latter
* case we ensure that vim view fits on the screen.
*
* The vim view notifies Vim if the number of (rows,columns) does not match the
* current number whenver the view size is about to change. Upon receiving a
* dimension change message, Vim notifies the window controller and the window
* resizes. However, the window is never resized programmatically during a
* live resize (in order to avoid jittering).
*
* The window size is constrained to not become too small during live resize,
* and it is also constrained to always fit an integer number of
* (rows,columns).
*
* In windowed mode we have to manually draw a tabline separator (due to bugs
* in the way Cocoa deals with the toolbar separator) when certain conditions
* are met. The rules for this are as follows:
*
* Tabline visible & Toolbar visible => Separator visible
* =====================================================================
* NO & NO => YES, if the window is textured
* NO, otherwise
* NO & YES => YES
* YES & NO => NO
* YES & YES => NO
*
*
* Resizing in custom full-screen mode:
*
* The window never resizes since it fills the screen, however the vim view may
* change size, e.g. when the user types ":set lines=60", or when a scrollbar
* is toggled.
*
* It is ensured that the vim view never becomes larger than the screen size
* and that it always stays in the center of the screen.
*
*
* Resizing in native full-screen mode (Mac OS X 10.7+):
*
* The window is always kept centered and resizing works more or less the same
* way as in windowed mode.
*
*/
#import "MMAppController.h"
#import "MMAtsuiTextView.h"
#import "MMFindReplaceController.h"
#import "MMFullScreenWindow.h"
#import "MMTextView.h"
#import "MMTypesetter.h"
#import "MMVimController.h"
#import "MMVimView.h"
#import "MMWindow.h"
#import "MMWindowController.h"
#import "Miscellaneous.h"
#import <PSMTabBarControl/PSMTabBarControl.h>
// These have to be the same as in option.h
#define FUOPT_MAXVERT 0x001
#define FUOPT_MAXHORZ 0x002
#define FUOPT_BGCOLOR_HLGROUP 0x004
@interface MMWindowController (Private)
- (NSSize)contentSize;
- (void)resizeWindowToFitContentSize:(NSSize)contentSize
keepOnScreen:(BOOL)onScreen;
- (NSSize)constrainContentSizeToScreenSize:(NSSize)contentSize;
- (NSRect)constrainFrame:(NSRect)frame;
- (void)updateResizeConstraints;
- (NSTabViewItem *)addNewTabViewItem;
- (BOOL)askBackendForStarRegister:(NSPasteboard *)pb;
- (void)updateTablineSeparator;
- (void)hideTablineSeparator:(BOOL)hide;
- (void)doFindNext:(BOOL)next;
- (void)updateToolbar;
- (BOOL)maximizeWindow:(int)options;
- (void)applicationDidChangeScreenParameters:(NSNotification *)notification;
- (void)enterNativeFullScreen;
@end
@interface NSWindow (NSWindowPrivate)
// Note: This hack allows us to set content shadowing separately from
// the window shadow. This is apparently what webkit and terminal do.
- (void)_setContentHasShadow:(BOOL)shadow; // new Tiger private method
// This is a private api that makes textured windows not have rounded corners.
// We want this on Leopard.
- (void)setBottomCornerRounded:(BOOL)rounded;
@end
@interface NSWindow (NSLeopardOnly)
// Note: These functions are Leopard-only, use -[NSObject respondsToSelector:]
// before calling them to make sure everything works on Tiger too.
- (void)setAutorecalculatesContentBorderThickness:(BOOL)b forEdge:(NSRectEdge)e;
- (void)setContentBorderThickness:(CGFloat)b forEdge:(NSRectEdge)e;
@end
@implementation MMWindowController
- (id)initWithVimController:(MMVimController *)controller
{
unsigned styleMask = NSTitledWindowMask | NSClosableWindowMask
| NSMiniaturizableWindowMask | NSResizableWindowMask
| NSUnifiedTitleAndToolbarWindowMask;
// Use textured background on Leopard or later (skip the 'if' on Tiger for
// polished metal window).
if ([[NSUserDefaults standardUserDefaults] boolForKey:MMTexturedWindowKey]
|| (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_4))
styleMask |= NSTexturedBackgroundWindowMask;
// NOTE: The content rect is only used the very first time MacVim is
// started (or rather, when ~/Library/Preferences/org.vim.MacVim.plist does
// not exist). The chosen values will put the window somewhere near the
// top and in the middle of a 1024x768 screen.
MMWindow *win = [[MMWindow alloc]
initWithContentRect:NSMakeRect(242,364,480,360)
styleMask:styleMask
backing:NSBackingStoreBuffered
defer:YES];
[win autorelease];
self = [super initWithWindow:win];
if (!self) return nil;
vimController = controller;
decoratedWindow = [win retain];
// Window cascading is handled by MMAppController.
[self setShouldCascadeWindows:NO];
// NOTE: Autoresizing is enabled for the content view, but only used
// for the tabline separator. The vim view must be resized manually
// because of full-screen considerations, and because its size depends
// on whether the tabline separator is visible or not.
NSView *contentView = [win contentView];
[contentView setAutoresizesSubviews:YES];
vimView = [[MMVimView alloc] initWithFrame:[contentView frame]
vimController:vimController];
[vimView setAutoresizingMask:NSViewNotSizable];
[contentView addSubview:vimView];
[win setDelegate:self];
[win setInitialFirstResponder:[vimView textView]];
if ([win styleMask] & NSTexturedBackgroundWindowMask) {
// On Leopard, we want to have a textured window to have nice
// looking tabs. But the textured window look implies rounded
// corners, which looks really weird -- disable them. This is a
// private api, though.
if ([win respondsToSelector:@selector(setBottomCornerRounded:)])
[win setBottomCornerRounded:NO];
// When the tab bar is toggled, it changes color for the fraction
// of a second, probably because vim sends us events in a strange
// order, confusing appkit's content border heuristic for a short
// while. This can be worked around with these two methods. There
// might be a better way, but it's good enough.
if ([win respondsToSelector:@selector(
setAutorecalculatesContentBorderThickness:forEdge:)])
[win setAutorecalculatesContentBorderThickness:NO
forEdge:NSMaxYEdge];
if ([win respondsToSelector:
@selector(setContentBorderThickness:forEdge:)])
[win setContentBorderThickness:0 forEdge:NSMaxYEdge];
}
// Make us safe on pre-tiger OSX
if ([win respondsToSelector:@selector(_setContentHasShadow:)])
[win _setContentHasShadow:NO];
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
// Building on Mac OS X 10.7 or greater.
// This puts the full-screen button in the top right of each window
if ([win respondsToSelector:@selector(setCollectionBehavior:)])
[win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
// This makes windows animate when opened
if ([win respondsToSelector:@selector(setAnimationBehavior:)])
[win setAnimationBehavior:NSWindowAnimationBehaviorDocumentWindow];
#endif
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationDidChangeScreenParameters:)
name:NSApplicationDidChangeScreenParametersNotification
object:NSApp];
return self;
}
- (void)dealloc
{
ASLogDebug(@"");
[decoratedWindow release]; decoratedWindow = nil;
[windowAutosaveKey release]; windowAutosaveKey = nil;
[vimView release]; vimView = nil;
[toolbar release]; toolbar = nil;
[super dealloc];
}
- (NSString *)description
{
NSString *format =
@"%@ : setupDone=%d windowAutosaveKey=%@ vimController=%@";
return [NSString stringWithFormat:format,
[self className], setupDone, windowAutosaveKey, vimController];
}
- (MMVimController *)vimController
{
return vimController;
}
- (MMVimView *)vimView
{
return vimView;
}
- (NSString *)windowAutosaveKey
{
return windowAutosaveKey;
}
- (void)setWindowAutosaveKey:(NSString *)key
{
[windowAutosaveKey autorelease];
windowAutosaveKey = [key copy];
}
- (void)cleanup
{
ASLogDebug(@"");
// NOTE: Must set this before possibly leaving full-screen.
setupDone = NO;
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (fullScreenEnabled) {
// If we are closed while still in full-screen, end full-screen mode,
// release ourselves (because this won't happen in MMWindowController)
// and perform close operation on the original window.
[self leaveFullScreen];
}
vimController = nil;
[vimView removeFromSuperviewWithoutNeedingDisplay];
[vimView cleanup];
// It is feasible (though unlikely) that the user quits before the window
// controller is released, make sure the edit flag is cleared so no warning
// dialog is displayed.
[decoratedWindow setDocumentEdited:NO];
[[self window] orderOut:self];
}
- (void)openWindow
{
// Indicates that the window is ready to be displayed, but do not display
// (or place) it yet -- that is done in showWindow.
//
// TODO: Remove this method? Everything can probably be done in
// presentWindow: but must carefully check dependencies on 'setupDone'
// flag.
[self addNewTabViewItem];
setupDone = YES;
}
- (BOOL)presentWindow:(id)unused
{
// If openWindow hasn't already been called then the window will be
// displayed later.
if (!setupDone) return NO;
// Place the window now. If there are multiple screens then a choice is
// made as to which screen the window should be on. This means that all
// code that is executed before this point must not depend on the screen!
[[MMAppController sharedInstance] windowControllerWillOpen:self];
[self updateResizeConstraints];
[self resizeWindowToFitContentSize:[vimView desiredSize]
keepOnScreen:YES];
[decoratedWindow makeKeyAndOrderFront:self];
// HACK! Calling makeKeyAndOrderFront: may cause Cocoa to force the window
// into native full-screen mode (this happens e.g. if a new window is
// opened when MacVim is already in full-screen). In this case we don't
// want the decorated window to pop up before the animation into
// full-screen, so set its alpha to 0.
if (fullScreenEnabled && !fullScreenWindow)
[decoratedWindow setAlphaValue:0];
// Flag that the window is now placed on screen. From now on it is OK for
// code to depend on the screen state. (Such as constraining views etc.)
windowPresented = YES;
if (fullScreenWindow) {
// Delayed entering of full-screen happens here (a ":set fu" in a
// GUIEnter auto command could cause this).
[fullScreenWindow enterFullScreen];
fullScreenEnabled = YES;
} else if (delayEnterFullScreen) {
// Set alpha to zero so that the decorated window doesn't pop up
// before we enter full-screen.
[decoratedWindow setAlphaValue:0];
[self enterNativeFullScreen];
}
return YES;
}
- (void)updateTabsWithData:(NSData *)data
{
[vimView updateTabsWithData:data];
}
- (void)selectTabWithIndex:(int)idx
{
[vimView selectTabWithIndex:idx];
}
- (void)setTextDimensionsWithRows:(int)rows columns:(int)cols isLive:(BOOL)live
keepOnScreen:(BOOL)onScreen
{
ASLogDebug(@"setTextDimensionsWithRows:%d columns:%d isLive:%d "
"keepOnScreen:%d", rows, cols, live, onScreen);
// NOTE: The only place where the (rows,columns) of the vim view are
// modified is here and when entering/leaving full-screen. Setting these
// values have no immediate effect, the actual resizing of the view is done
// in processInputQueueDidFinish.
//
// The 'live' flag indicates that this resize originated from a live
// resize; it may very well happen that the view is no longer in live
// resize when this message is received. We refrain from changing the view
// size when this flag is set, otherwise the window might jitter when the
// user drags to resize the window.
[vimView setDesiredRows:rows columns:cols];
if (setupDone && !live) {
shouldResizeVimView = YES;
keepOnScreen = onScreen;
}
// Autosave rows and columns.
if (windowAutosaveKey && !fullScreenEnabled
&& rows > MMMinRows && cols > MMMinColumns) {
// HACK! If tabline is visible then window will look about one line
// higher than it actually is so increment rows by one before
// autosaving dimension so that the approximate total window height is
// autosaved. This is particularly important when window is maximized
// vertically; if we don't add a row here a new window will appear to
// not be tall enough when the first window is showing the tabline.
// A negative side-effect of this is that the window will redraw on
// startup if the window is too tall to fit on screen (which happens
// for example if 'showtabline=2').
// TODO: Store window pixel dimensions instead of rows/columns?
int autosaveRows = rows;
if (![[vimView tabBarControl] isHidden])
++autosaveRows;
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
[ud setInteger:autosaveRows forKey:MMAutosaveRowsKey];
[ud setInteger:cols forKey:MMAutosaveColumnsKey];
[ud synchronize];
}
}
- (void)zoomWithRows:(int)rows columns:(int)cols state:(int)state
{
[self setTextDimensionsWithRows:rows
columns:cols
isLive:NO
keepOnScreen:YES];
// NOTE: If state==0 then the window should be put in the non-zoomed
// "user state". That is, move the window back to the last stored
// position. If the window is in the zoomed state, the call to change the
// dimensions above will also reposition the window to ensure it fits on
// the screen. However, since resizing of the window is delayed we also
// delay repositioning so that both happen at the same time (this avoid
// situations where the window woud appear to "jump").
if (!state && !NSEqualPoints(NSZeroPoint, userTopLeft))
shouldRestoreUserTopLeft = YES;
}
- (void)setTitle:(NSString *)title
{
if (!title)
return;
[decoratedWindow setTitle:title];
if (fullScreenWindow) {
[fullScreenWindow setTitle:title];
// NOTE: Cocoa does not update the "Window" menu for borderless windows
// so we have to do it manually.
[NSApp changeWindowsItem:fullScreenWindow title:title filename:NO];
}
}
- (void)setDocumentFilename:(NSString *)filename
{
if (!filename)
return;
// Ensure file really exists or the path to the proxy icon will look weird.
// If the file does not exists, don't show a proxy icon.
if (![[NSFileManager defaultManager] fileExistsAtPath:filename])
filename = @"";
[decoratedWindow setRepresentedFilename:filename];
[fullScreenWindow setRepresentedFilename:filename];
}
- (void)setToolbar:(NSToolbar *)theToolbar
{
if (theToolbar != toolbar) {
[toolbar release];
toolbar = [theToolbar retain];
}
// NOTE: Toolbar must be set here or it won't work to show it later.
[decoratedWindow setToolbar:toolbar];
// HACK! Redirect the pill button so that we can ask Vim to hide the
// toolbar.
NSButton *pillButton = [decoratedWindow
standardWindowButton:NSWindowToolbarButton];
if (pillButton) {
[pillButton setAction:@selector(toggleToolbar:)];
[pillButton setTarget:self];
}
}
- (void)createScrollbarWithIdentifier:(int32_t)ident type:(int)type
{
[vimView createScrollbarWithIdentifier:ident type:type];
}
- (BOOL)destroyScrollbarWithIdentifier:(int32_t)ident
{
BOOL scrollbarHidden = [vimView destroyScrollbarWithIdentifier:ident];
shouldResizeVimView = shouldResizeVimView || scrollbarHidden;
shouldMaximizeWindow = shouldMaximizeWindow || scrollbarHidden;
return scrollbarHidden;
}
- (BOOL)showScrollbarWithIdentifier:(int32_t)ident state:(BOOL)visible
{
BOOL scrollbarToggled = [vimView showScrollbarWithIdentifier:ident
state:visible];
shouldResizeVimView = shouldResizeVimView || scrollbarToggled;
shouldMaximizeWindow = shouldMaximizeWindow || scrollbarToggled;
return scrollbarToggled;
}
- (void)setScrollbarPosition:(int)pos length:(int)len identifier:(int32_t)ident
{
[vimView setScrollbarPosition:pos length:len identifier:ident];
}
- (void)setScrollbarThumbValue:(float)val proportion:(float)prop
identifier:(int32_t)ident
{
[vimView setScrollbarThumbValue:val proportion:prop identifier:ident];
}
- (void)setDefaultColorsBackground:(NSColor *)back foreground:(NSColor *)fore
{
// NOTE: This is called when the transparency changes so set the opacity
// flag on the window here (should be faster if the window is opaque).
BOOL isOpaque = [back alphaComponent] == 1.0f;
[decoratedWindow setOpaque:isOpaque];
if (fullScreenWindow)
[fullScreenWindow setOpaque:isOpaque];
[vimView setDefaultColorsBackground:back foreground:fore];
}
- (void)setFont:(NSFont *)font
{
[[NSFontManager sharedFontManager] setSelectedFont:font isMultiple:NO];
[[vimView textView] setFont:font];
[self updateResizeConstraints];
shouldMaximizeWindow = YES;
}
- (void)setWideFont:(NSFont *)font
{
[[vimView textView] setWideFont:font];
}
- (void)processInputQueueDidFinish
{
// NOTE: Resizing is delayed until after all commands have been processed
// since it often happens that more than one command will cause a resize.
// If we were to immediately resize then the vim view size would jitter
// (e.g. hiding/showing scrollbars often happens several time in one
// update).
// Also delay toggling the toolbar until after scrollbars otherwise
// problems arise when showing toolbar and scrollbar at the same time, i.e.
// on "set go+=rT".
// Update toolbar before resizing, since showing the toolbar may require
// the view size to become smaller.
if (updateToolbarFlag != 0)
[self updateToolbar];
// NOTE: If the window has not been presented then we must avoid resizing
// the views since it will cause them to be constrained to the screen which
// has not yet been set!
if (windowPresented && shouldResizeVimView) {
shouldResizeVimView = NO;
// Make sure full-screen window stays maximized (e.g. when scrollbar or
// tabline is hidden) according to 'fuopt'.
BOOL didMaximize = NO;
if (shouldMaximizeWindow && fullScreenEnabled &&
(fullScreenOptions & (FUOPT_MAXVERT|FUOPT_MAXHORZ)) != 0)
didMaximize = [self maximizeWindow:fullScreenOptions];
shouldMaximizeWindow = NO;
// Resize Vim view and window, but don't do this now if the window was
// just reszied because this would make the window "jump" unpleasantly.
// Instead wait for Vim to respond to the resize message and do the
// resizing then.
// TODO: What if the resize message fails to make it back?
if (!didMaximize) {
NSSize originalSize = [vimView frame].size;
NSSize contentSize = [vimView desiredSize];
contentSize = [self constrainContentSizeToScreenSize:contentSize];
int rows = 0, cols = 0;
contentSize = [vimView constrainRows:&rows columns:&cols
toSize:contentSize];
[vimView setFrameSize:contentSize];
if (fullScreenWindow) {
// NOTE! Don't mark the full-screen content view as needing an
// update unless absolutely necessary since when it is updated
// the entire screen is cleared. This may cause some parts of
// the Vim view to be cleared but not redrawn since Vim does
// not realize that we've erased part of the view.
if (!NSEqualSizes(originalSize, contentSize)) {
[[fullScreenWindow contentView] setNeedsDisplay:YES];
[fullScreenWindow centerView];
}
} else {
[self resizeWindowToFitContentSize:contentSize
keepOnScreen:keepOnScreen];
}
}
keepOnScreen = NO;
}
}
- (void)showTabBar:(BOOL)on
{
[[vimView tabBarControl] setHidden:!on];
[self updateTablineSeparator];
shouldMaximizeWindow = YES;
}
- (void)showToolbar:(BOOL)on size:(int)size mode:(int)mode
{
if (!toolbar) return;
[toolbar setSizeMode:size];
[toolbar setDisplayMode:mode];
// Positive flag shows toolbar, negative hides it.
updateToolbarFlag = on ? 1 : -1;
// NOTE: If the window is not visible we must toggle the toolbar
// immediately, otherwise "set go-=T" in .gvimrc will lead to the toolbar
// showing its hide animation every time a new window is opened. (See
// processInputQueueDidFinish for the reason why we need to delay toggling
// the toolbar when the window is visible.)
if (![decoratedWindow isVisible])
[self updateToolbar];
}
- (void)setMouseShape:(int)shape
{
[[vimView textView] setMouseShape:shape];
}
- (void)adjustLinespace:(int)linespace
{
if (vimView && [vimView textView]) {
[[vimView textView] setLinespace:(float)linespace];
shouldMaximizeWindow = shouldResizeVimView = YES;
}
}
- (void)liveResizeWillStart
{
if (!setupDone) return;
// Save the original title, if we haven't already.
if (lastSetTitle == nil) {
lastSetTitle = [[decoratedWindow title] retain];
}
// NOTE: During live resize Cocoa goes into "event tracking mode". We have
// to add the backend connection to this mode in order for resize messages
// from Vim to reach MacVim. We do not wish to always listen to requests
// in event tracking mode since then MacVim could receive DO messages at
// unexpected times (e.g. when a key equivalent is pressed and the menu bar
// momentarily lights up).
id proxy = [vimController backendProxy];
NSConnection *connection = [(NSDistantObject*)proxy connectionForProxy];
[connection addRequestMode:NSEventTrackingRunLoopMode];
}
- (void)liveResizeDidEnd
{
if (!setupDone) return;
// See comment above regarding event tracking mode.
id proxy = [vimController backendProxy];
NSConnection *connection = [(NSDistantObject*)proxy connectionForProxy];
[connection removeRequestMode:NSEventTrackingRunLoopMode];
// NOTE: During live resize messages from MacVim to Vim are often dropped
// (because too many messages are sent at once). This may lead to
// inconsistent states between Vim and MacVim; to avoid this we send a
// synchronous resize message to Vim now (this is not fool-proof, but it
// does seem to work quite well).
// Do NOT send a SetTextDimensionsMsgID message (as opposed to
// LiveResizeMsgID) since then the view is constrained to not be larger
// than the screen the window mostly occupies; this makes it impossible to
// resize the window across multiple screens.
int constrained[2];
NSSize textViewSize = [[vimView textView] frame].size;
[[vimView textView] constrainRows:&constrained[0] columns:&constrained[1]
toSize:textViewSize];
ASLogDebug(@"End of live resize, notify Vim that text dimensions are %dx%d",
constrained[1], constrained[0]);
NSData *data = [NSData dataWithBytes:constrained length:2*sizeof(int)];
BOOL sendOk = [vimController sendMessageNow:LiveResizeMsgID
data:data
timeout:.5];
if (!sendOk) {
// Sending of synchronous message failed. Force the window size to
// match the last dimensions received from Vim, otherwise we end up
// with inconsistent states.
[self resizeWindowToFitContentSize:[vimView desiredSize]
keepOnScreen:NO];
}
// If we saved the original title while resizing, restore it.
if (lastSetTitle != nil) {
[decoratedWindow setTitle:lastSetTitle];
[lastSetTitle release];
lastSetTitle = nil;
}
}
- (void)enterFullScreen:(int)fuoptions backgroundColor:(NSColor *)back
{
if (fullScreenEnabled) return;
BOOL useNativeFullScreen = [[NSUserDefaults standardUserDefaults]
boolForKey:MMNativeFullScreenKey];
// Make sure user is not trying to use native full-screen on systems that
// do not support it.
if (![NSWindow instancesRespondToSelector:@selector(toggleFullScreen:)])
useNativeFullScreen = NO;
fullScreenOptions = fuoptions;
if (useNativeFullScreen) {
// Enter native full-screen mode. Only supported on Mac OS X 10.7+.
if (windowPresented) {
[self enterNativeFullScreen];
} else {
delayEnterFullScreen = YES;
}
} else {
// Enter custom full-screen mode. Always supported.
ASLogInfo(@"Enter custom full-screen");
// fullScreenWindow could be non-nil here if this is called multiple
// times during startup.
[fullScreenWindow release];
fullScreenWindow = [[MMFullScreenWindow alloc]
initWithWindow:decoratedWindow view:vimView backgroundColor:back];
[fullScreenWindow setOptions:fuoptions];
[fullScreenWindow setRepresentedFilename:
[decoratedWindow representedFilename]];
// NOTE: Do not enter full-screen until the window has been presented
// since we don't actually know which screen to use before then. (The
// custom full-screen can appear on any screen, as opposed to native
// full-screen which always uses the main screen.)
if (windowPresented) {
[fullScreenWindow enterFullScreen];
fullScreenEnabled = YES;
// The resize handle disappears so the vim view needs to update the
// scrollbars.
shouldResizeVimView = YES;
}
}
}
- (void)leaveFullScreen
{
if (!fullScreenEnabled) return;
ASLogInfo(@"Exit full-screen");
fullScreenEnabled = NO;
if (fullScreenWindow) {
// Using custom full-screen
[fullScreenWindow leaveFullScreen];
[fullScreenWindow release];
fullScreenWindow = nil;
// The vim view may be too large to fit the screen, so update it.
shouldResizeVimView = YES;
} else {
// Using native full-screen
// NOTE: fullScreenEnabled is used to detect if we enter full-screen
// programatically and so must be set before calling
// realToggleFullScreen:.
NSParameterAssert(fullScreenEnabled == NO);
[decoratedWindow realToggleFullScreen:self];
}
}
- (void)setFullScreenBackgroundColor:(NSColor *)back
{
if (fullScreenWindow)
[fullScreenWindow setBackgroundColor:back];
}
- (void)invFullScreen:(id)sender
{
[vimController addVimInput:@"<C-\\><C-N>:set invfu<CR>"];
}
- (void)setBufferModified:(BOOL)mod
{
// NOTE: We only set the document edited flag on the decorated window since
// the custom full-screen window has no close button anyway. (It also
// saves us from keeping track of the flag in two different places.)
[decoratedWindow setDocumentEdited:mod];
}
- (void)setTopLeft:(NSPoint)pt
{
if (setupDone) {
[decoratedWindow setFrameTopLeftPoint:pt];
} else {
// Window has not been "opened" yet (see openWindow:) but remember this
// value to be used when the window opens.
defaultTopLeft = pt;
}
}
- (BOOL)getDefaultTopLeft:(NSPoint*)pt
{
// A default top left point may be set in .[g]vimrc with the :winpos
// command. (If this has not been done the top left point will be the zero
// point.)
if (pt && !NSEqualPoints(defaultTopLeft, NSZeroPoint)) {
*pt = defaultTopLeft;
return YES;
}
return NO;
}
- (IBAction)addNewTab:(id)sender
{
[vimView addNewTab:sender];
}
- (IBAction)toggleToolbar:(id)sender
{
[vimController sendMessage:ToggleToolbarMsgID data:nil];
}
- (IBAction)performClose:(id)sender
{
// NOTE: With the introduction of :macmenu it is possible to bind
// File.Close to ":conf q" but at the same time have it send off the
// performClose: action. For this reason we no longer need the CloseMsgID
// message. However, we still need File.Close to send performClose:
// otherwise Cmd-w will not work on dialogs.
[self vimMenuItemAction:sender];
}
- (IBAction)findNext:(id)sender
{
[self doFindNext:YES];
}
- (IBAction)findPrevious:(id)sender
{
[self doFindNext:NO];
}
- (IBAction)vimMenuItemAction:(id)sender
{
if (![sender isKindOfClass:[NSMenuItem class]]) return;
// TODO: Make into category on NSMenuItem which returns descriptor.
NSMenuItem *item = (NSMenuItem*)sender;
NSMutableArray *desc = [NSMutableArray arrayWithObject:[item title]];
NSMenu *menu = [item menu];
while (menu) {
[desc insertObject:[menu title] atIndex:0];
menu = [menu supermenu];
}
// The "MainMenu" item is part of the Cocoa menu and should not be part of
// the descriptor.
if ([[desc objectAtIndex:0] isEqual:@"MainMenu"])
[desc removeObjectAtIndex:0];
NSDictionary *attrs = [NSDictionary dictionaryWithObject:desc
forKey:@"descriptor"];
[vimController sendMessage:ExecuteMenuMsgID data:[attrs dictionaryAsData]];
}
- (IBAction)vimToolbarItemAction:(id)sender
{
NSArray *desc = [NSArray arrayWithObjects:@"ToolBar", [sender label], nil];
NSDictionary *attrs = [NSDictionary dictionaryWithObject:desc
forKey:@"descriptor"];
[vimController sendMessage:ExecuteMenuMsgID data:[attrs dictionaryAsData]];
}
- (IBAction)fontSizeUp:(id)sender
{
[[NSFontManager sharedFontManager] modifyFont:
[NSNumber numberWithInt:NSSizeUpFontAction]];
}
- (IBAction)fontSizeDown:(id)sender
{
[[NSFontManager sharedFontManager] modifyFont:
[NSNumber numberWithInt:NSSizeDownFontAction]];
}
- (IBAction)findAndReplace:(id)sender
{
int tag = [sender tag];
MMFindReplaceController *fr = [MMFindReplaceController sharedInstance];
int flags = 0;
// NOTE: The 'flags' values must match the FRD_ defines in gui.h (except
// for 0x100 which we use to indicate a backward search).
switch (tag) {
case 1: flags = 0x100; break;
case 2: flags = 3; break;
case 3: flags = 4; break;
}
if ([fr matchWord])
flags |= 0x08;
if (![fr ignoreCase])
flags |= 0x10;
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
[fr findString], @"find",
[fr replaceString], @"replace",
[NSNumber numberWithInt:flags], @"flags",
nil];
[vimController sendMessage:FindReplaceMsgID data:[args dictionaryAsData]];
}
- (BOOL)validateMenuItem:(NSMenuItem *)item
{
if ([item action] == @selector(vimMenuItemAction:)
|| [item action] == @selector(performClose:))
return [item tag];
return YES;
}
// -- NSWindow delegate ------------------------------------------------------
- (void)windowDidBecomeMain:(NSNotification *)notification
{
[[MMAppController sharedInstance] setMainMenu:[vimController mainMenu]];
[vimController sendMessage:GotFocusMsgID data:nil];
if ([vimView textView]) {
NSFontManager *fm = [NSFontManager sharedFontManager];
[fm setSelectedFont:[[vimView textView] font] isMultiple:NO];
}
}
- (void)windowDidResignMain:(NSNotification *)notification
{
[vimController sendMessage:LostFocusMsgID data:nil];
}
- (BOOL)windowShouldClose:(id)sender
{
// Don't close the window now; Instead let Vim decide whether to close the
// window or not.
[vimController sendMessage:VimShouldCloseMsgID data:nil];
return NO;
}
- (void)windowDidMove:(NSNotification *)notification
{
if (!setupDone)
return;
if (fullScreenEnabled) {
// NOTE: The full-screen is not supposed to be able to be moved. If we
// do get here while in full-screen something unexpected happened (e.g.
// the full-screen window was on an external display that got
// unplugged).
return;
}
NSRect frame = [decoratedWindow frame];
NSPoint topLeft = { frame.origin.x, NSMaxY(frame) };
if (windowAutosaveKey) {
NSString *topLeftString = NSStringFromPoint(topLeft);
[[NSUserDefaults standardUserDefaults]
setObject:topLeftString forKey:windowAutosaveKey];
}
// NOTE: This method is called when the user drags the window, but not when
// the top left point changes programmatically.
// NOTE 2: Vim counts Y-coordinates from the top of the screen.
int pos[2] = {
(int)topLeft.x,
(int)(NSMaxY([[decoratedWindow screen] frame]) - topLeft.y) };
NSData *data = [NSData dataWithBytes:pos length:2*sizeof(int)];
[vimController sendMessage:SetWindowPositionMsgID data:data];
}
- (void)windowDidResize:(id)sender
{
if (!setupDone || fullScreenEnabled) return;
// NOTE: Since we have no control over when the window may resize (Cocoa
// may resize automatically) we simply set the view to fill the entire
// window. The vim view takes care of notifying Vim if the number of