forked from macvim-dev/macvim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMMWindowController.m
2084 lines (1769 loc) · 75.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 "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;
- (NSTabViewItem *)addNewTabViewItem;
- (BOOL)askBackendForSelectedText:(NSPasteboard *)pb;
- (void)updateTablineSeparator;
- (void)hideTablineSeparator:(BOOL)hide;
- (void)doFindNext:(BOOL)next;
- (void)updateToolbar;
- (BOOL)maximizeWindow:(int)options;
- (void)applicationDidChangeScreenParameters:(NSNotification *)notification;
- (void)enterNativeFullScreen;
- (void)processAfterWindowPresentedQueue;
+ (NSString *)tabBarStyleForUnified;
+ (NSString *)tabBarStyleForMetal;
@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
{
backgroundDark = NO;
unsigned styleMask = NSWindowStyleMaskTitled
| NSWindowStyleMaskClosable
| NSWindowStyleMaskMiniaturizable
| NSWindowStyleMaskResizable
| NSWindowStyleMaskUnifiedTitleAndToolbar;
// Textured background has been a deprecated feature for a while. For a
// while we kept using it to avoid showing a black line below the title
// bar, but since macOS 11.0 this flag is completely ignored and
// deprecated. Since it's hard to test older versions of macOS well, simply
// preserve the existing functionality on older macOS versions, while not
// setting it in macOS 11+.
BOOL usingTexturedBackground = NO;
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_11_0
if (AVAILABLE_MAC_OS(11, 0)) {
// Don't set the textured background because it's been completely deprecated and won't do anything.
} else {
styleMask = styleMask | NSWindowStyleMaskTexturedBackground;
usingTexturedBackground = YES;
}
#endif
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ([userDefaults boolForKey:MMNoTitleBarWindowKey]) {
// No title bar setting
styleMask &= ~NSWindowStyleMaskTitled;
}
// 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;
resizingDueToMove = NO;
vimController = controller;
decoratedWindow = [win retain];
[self refreshApperanceMode];
// 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];
contentView.wantsLayer = YES;
vimView = [[MMVimView alloc] initWithFrame:[contentView frame]
vimController:vimController];
[vimView setAutoresizingMask:NSViewNotSizable];
[contentView addSubview:vimView];
[win setDelegate:self];
[win setInitialFirstResponder:[vimView textView]];
if (usingTexturedBackground) {
// 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:)]) {
if (![[NSUserDefaults standardUserDefaults]
boolForKey:MMDisableLaunchAnimationKey]) {
[win setAnimationBehavior:NSWindowAnimationBehaviorDocumentWindow];
}
}
#endif
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 110000
if (@available(macos 11.0, *)) {
// macOS 11 will default to a unified toolbar style unless you use the new
// toolbarStyle to tell it to use a "preference" style, which makes it look nice
// and centered.
win.toolbarStyle = NSWindowToolbarStyleUnifiedCompact;
}
#endif
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationDidChangeScreenParameters:)
name:NSApplicationDidChangeScreenParametersNotification
object:NSApp];
return self;
}
- (void)dealloc
{
ASLogDebug(@"");
[decoratedWindow release]; decoratedWindow = nil;
[fullScreenWindow release]; fullScreenWindow = nil;
[windowAutosaveKey release]; windowAutosaveKey = nil;
[vimView release]; vimView = nil;
[toolbar release]; toolbar = nil;
// in case processAfterWindowPresentedQueue wasn't called
[afterWindowPresentedQueue release]; afterWindowPresentedQueue = nil;
[lastSetTitle release]; lastSetTitle = nil;
[documentFilename release]; documentFilename = 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];
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] close];
}
- (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:NO];
[self resizeWindowToFitContentSize:[vimView desiredSize]
keepOnScreen:YES];
[decoratedWindow makeKeyAndOrderFront:self];
[decoratedWindow setBlurRadius:blurRadius];
// 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;
// Process deferred blocks
[self processAfterWindowPresentedQueue];
if (fullScreenWindow) {
// Delayed entering of full-screen happens here (a ":set fu" in a
// GUIEnter auto command could cause this).
[fullScreenWindow enterFullScreen];
fullScreenEnabled = YES;
shouldResizeVimView = YES;
} else if (delayEnterFullScreen) {
[self enterNativeFullScreen];
}
return YES;
}
- (void)moveWindowAcrossScreens:(NSPoint)topLeft
{
// HACK! This method moves a window to a new origin and to a different
// screen. This is primarily useful to avoid a scenario where such a move
// will trigger a resize, even though the frame didn't actually change size.
resizingDueToMove = YES;
[[self window] setFrameTopLeftPoint:topLeft];
resizingDueToMove = NO;
}
- (void)updateTabsWithData:(NSData *)data
{
[vimView updateTabsWithData:data];
}
- (void)selectTabWithIndex:(int)idx
{
[vimView selectTabWithIndex:idx];
}
- (void)setTextDimensionsWithRows:(int)rows columns:(int)cols isLive:(BOOL)live
keepGUISize:(BOOL)keepGUISize
keepOnScreen:(BOOL)onScreen
{
ASLogDebug(@"setTextDimensionsWithRows:%d columns:%d isLive:%d "
"keepGUISize:%d "
"keepOnScreen:%d", rows, cols, live, keepGUISize, 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];
vimView.pendingLiveResize = NO;
if (vimView.pendingLiveResizeQueued) {
// There was already a new size queued while Vim was still processing
// the last one. We need to immediately request another resize now that
// Vim was done with the last message.
//
// This could happen if we are in the middle of rapid resize (e.g.
// double-clicking on the border/corner of window), as we would fire
// off a lot of LiveResizeMsgID messages where some will be
// intentionally omitted to avoid swamping IPC as we rate limit it to
// only one outstanding resize message at a time
// inframeSizeMayHaveChanged:.
vimView.pendingLiveResizeQueued = NO;
[self resizeView];
}
if (setupDone && !live && !keepGUISize) {
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)resizeView
{
if (setupDone)
{
shouldResizeVimView = YES;
shouldKeepGUISize = YES;
}
}
- (void)zoomWithRows:(int)rows columns:(int)cols state:(int)state
{
[self setTextDimensionsWithRows:rows
columns:cols
isLive:NO
keepGUISize: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
{
// Save the original title, if we haven't already.
[title retain]; // retain the title first before release lastSetTitle, since you can call setTitle on lastSetTitle itself.
[lastSetTitle release];
lastSetTitle = title;
// While in live resize the window title displays the dimensions of the
// window so don't clobber this with the new title. We have already set
// lastSetTitle above so once live resize is done we will set it back.
if ([vimView inLiveResize]) {
return;
}
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];
}
}
/// Set the currently edited document's file path, passed in from Vim. Buffers with
/// no file paths will be passed in as empty strings.
- (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 = @"";
[filename retain];
[documentFilename release];
documentFilename = filename;
[self updateDocumentFilename];
}
- (void)updateDocumentFilename
{
if (documentFilename == nil)
return;
const bool showDocumentIcon = [[NSUserDefaults standardUserDefaults] boolForKey:MMTitlebarShowsDocumentIconKey];
NSString *filename = showDocumentIcon ? documentFilename : @"";
[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];
return scrollbarHidden;
}
- (BOOL)showScrollbarWithIdentifier:(int32_t)ident state:(BOOL)visible
{
BOOL scrollbarToggled = [vimView showScrollbarWithIdentifier:ident
state:visible];
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)setBackgroundOption:(int)dark
{
backgroundDark = dark;
if ([[NSUserDefaults standardUserDefaults]
integerForKey:MMAppearanceModeSelectionKey] == MMAppearanceModeSelectionBackgroundOption)
{
[self refreshApperanceMode];
}
}
- (void)refreshApperanceMode
{
// This function calculates what apperance mode (light vs dark mode and
// titlebar settings) to use for this window, depending on what the user
// has selected as a preference.
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
// Transparent title bar setting
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_10
if (AVAILABLE_MAC_OS(10, 10)) {
decoratedWindow.titlebarAppearsTransparent = [ud boolForKey:MMTitlebarAppearsTransparentKey];
}
#endif
// No title bar setting
if ([ud boolForKey:MMNoTitleBarWindowKey]) {
[decoratedWindow setStyleMask:([decoratedWindow styleMask] & ~NSWindowStyleMaskTitled)];
} else {
[decoratedWindow setStyleMask:([decoratedWindow styleMask] | NSWindowStyleMaskTitled)];
}
// Whether to hide shadows or not
if ([ud boolForKey:MMNoWindowShadowKey]) {
[decoratedWindow setHasShadow:NO];
} else {
[decoratedWindow setHasShadow:YES];
}
// Title may have been lost if we hid the title-bar. Reset it.
[self setTitle:lastSetTitle];
[self updateDocumentFilename];
// Dark mode only works on 10.14+ because that's when dark mode was
// introduced.
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_14
if (@available(macos 10.14, *)) {
NSAppearance* desiredAppearance;
switch ([ud integerForKey:MMAppearanceModeSelectionKey])
{
case MMAppearanceModeSelectionLight:
{
desiredAppearance = [NSAppearance appearanceNamed: NSAppearanceNameAqua];
break;
}
case MMAppearanceModeSelectionDark:
{
desiredAppearance = [NSAppearance appearanceNamed: NSAppearanceNameDarkAqua];
break;
}
case MMAppearanceModeSelectionBackgroundOption:
{
if (backgroundDark) {
desiredAppearance = [NSAppearance appearanceNamed: NSAppearanceNameDarkAqua];
} else {
desiredAppearance = [NSAppearance appearanceNamed: NSAppearanceNameAqua];
}
break;
}
case MMAppearanceModeSelectionAuto:
default:
{
// Use the system appearance. This will also auto-switch when OS changes mode.
desiredAppearance = nil;
break;
}
}
decoratedWindow.appearance = desiredAppearance;
fullScreenWindow.appearance = desiredAppearance;
}
#endif
}
- (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];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400
if (@available(macos 10.14, *)) {
// We usually don't really need to change the background color of the
// window, but in 10.14+ we switched to using layer-backed drawing.
// That's fine except when we set 'transparency' to non-zero. The alpha
// is set on the text view, but it won't work if drawn on top of a solid
// window, so we need to set a transparency color here to make the
// transparency show through.
if ([back alphaComponent] == 1) {
// The window's background color affects the title bar tint and
// if we are using a transparent title bar this color will show
// up as well.
// (Note that this won't play well in <=10.12 since we are using
// the deprecated NSWindowStyleMaskTexturedBackground which makes
// the titlebars transparent in those. Consider not using textured
// background.)
[decoratedWindow setBackgroundColor:back];
// Note: We leave the full screen window's background color alone
// because it is affected by 'fuoptions' instead. We just change the
// alpha back to 1 in case it was changed previously because transparency
// was set.
if (fullScreenWindow) {
[fullScreenWindow setBackgroundColor:
[fullScreenWindow.backgroundColor colorWithAlphaComponent:1]];
}
} else {
// HACK! We really want a transparent background color to avoid
// double blending the transparency, but setting alpha=0 leads to
// the window border disappearing and also drag-to-resize becomes a
// lot slower. So hack around it by making it virtually transparent.
[decoratedWindow setBackgroundColor:[back colorWithAlphaComponent:0.001]];
if (fullScreenWindow) {
[fullScreenWindow setBackgroundColor:
[fullScreenWindow.backgroundColor colorWithAlphaComponent:0.001]];
}
}
}
else
#endif
{
// 10.13 or below. As noted above, the window flag
// NSWindowStyleMaskTexturedBackground doesn't play well with window color,
// but if we are toggling the titlebar transparent option, we need to set
// the window background color in order the title bar to be tinted correctly.
if ([[NSUserDefaults standardUserDefaults]
boolForKey:MMTitlebarAppearsTransparentKey]) {
if ([back alphaComponent] != 0) {
[decoratedWindow setBackgroundColor:back];
} else {
// See above HACK for more details. Basically we cannot set a
// color with 0 alpha or the window manager will give it a
// different treatment.
NSColor *clearColor = [back colorWithAlphaComponent:0.001];
[decoratedWindow setBackgroundColor:clearColor];
}
}
}
[vimView setDefaultColorsBackground:back foreground:fore];
}
- (void)setFont:(NSFont *)font
{
const NSWindow* mainWindow = [NSApp mainWindow];
if (mainWindow && (mainWindow == decoratedWindow || mainWindow == fullScreenWindow)) {
// Update the shared font manager with the new font, but only if this is the main window,
// as the font manager is shared among all the windows.
[[NSFontManager sharedFontManager] setSelectedFont:font isMultiple:NO];
}
[[vimView textView] setFont:font];
[self updateResizeConstraints:NO];
shouldMaximizeWindow = YES;
}
- (void)setWideFont:(NSFont *)font
{
[[vimView textView] setWideFont:font];
}
- (void)refreshFonts
{
[[vimView textView] refreshFonts];
}
- (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;
int rows = 0, cols = 0;
// Setting 'guioptions+=k' will make shouldKeepGUISize true, which
// means avoid resizing the window. Instead, resize the view instead
// to keep the GUI window's size consistent.
bool avoidWindowResize = shouldKeepGUISize || fullScreenEnabled;
if (!avoidWindowResize) {
NSSize contentSize = [vimView constrainRows:&rows columns:&cols
toSize:
fullScreenWindow ? [fullScreenWindow frame].size :
fullScreenEnabled ? desiredWindowSize :
[self constrainContentSizeToScreenSize:[vimView desiredSize]]];
[vimView setFrameSize:contentSize];
[self resizeWindowToFitContentSize:contentSize
keepOnScreen:keepOnScreen];
}
else {
NSSize frameSize;
if (fullScreenWindow) {
// Non-native full screen mode.
NSRect desiredFrame = [fullScreenWindow getDesiredFrame];
frameSize = desiredFrame.size;
[vimView setFrameOrigin:desiredFrame.origin]; // This will get set back to normal in MMFullScreenWindow::leaveFullScreen.
} else if (fullScreenEnabled) {
// Native full screen mode.
frameSize = desiredWindowSize;
} else {
frameSize = originalSize;
}
[vimView setFrameSizeKeepGUISize:frameSize];
}
}
keepOnScreen = NO;
shouldKeepGUISize = NO;
}
// Tell Vim view to update its scrollbars which is done once per update.
// Do it last so whatever resizing we have done above will take effect
// immediate too instead of waiting till next frame.
[vimView finishPlaceScrollbars];
// Work around a bug which affects macOS 10.14 and older.
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101500
if (@available(macos 10.15, *)) {
} else
#endif
{
// Ensure that the app waits until the next frame to commit the current
// CATransaction. Without this, layer-backed views display as soon as
// the thread returns to the event loop, potentially drawing *many*
// times for a single screen update. The app correctly waits to draw
// when a window needs display, so mark the window as needing display.
self.window.viewsNeedDisplay = YES;
}
}
- (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.)
//
// Also, the delayed updateToolbar will have the correct shouldKeepGUISize
// set when it's called, which is important for that function to respect
// guioptions 'k'.
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];
}
}
- (void)adjustColumnspace:(int)columnspace
{
if (vimView && [vimView textView]) {
[[vimView textView] setColumnspace:(float)columnspace];
}
}
- (void)liveResizeWillStart
{
if (!setupDone) return;
// 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];
// If we saved the original title while resizing, restore it.
if (lastSetTitle != nil) {
[decoratedWindow setTitle:lastSetTitle];
}
if (vimView.pendingLiveResizeQueued) {
// Similar to setTextDimensionsWithRows:, if there's still outstanding
// resize message queued, we just immediately flush it here to make
// sure Vim will get the most up-to-date size here when we are done
// with live resizing to make sure we don't havae any stale sizes due
// to rate limiting of IPC messages during live resizing..
vimView.pendingLiveResizeQueued = NO;
[self resizeView];
}
}
- (void)setBlurRadius:(int)radius
{
blurRadius = radius;
if (windowPresented) {
[decoratedWindow setBlurRadius:radius];
}
}
- (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.
if (windowPresented) {
[self enterNativeFullScreen];
} else {
delayEnterFullScreen = YES;
}
} else {
// Enter custom full-screen mode.
ASLogInfo(@"Enter custom full-screen");
NSColor *fullscreenBg = back;
// See setDefaultColorsBackground: for why set a transparent