-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathapp.mm
266 lines (219 loc) · 8.17 KB
/
app.mm
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
#include <string.h>
#include "vim.h"
#import "app.h"
#import "window.h"
#import "view.h"
#import "redraw.h"
#import "font.h"
extern char **g_argv;
extern int g_argc;
static VimWindow *activeWindow = 0;
void ignore_sigpipe(void)
{
struct sigaction act;
int r;
memset(&act, 0, sizeof(act));
act.sa_handler = SIG_IGN;
act.sa_flags = SA_RESTART;
r = sigaction(SIGPIPE, &act, NULL);
if (r) {
std::cerr << "Failed to ignore SIGPIPE\n";
exit(-1);
}
}
@implementation AppDelegate
- (NSDictionary *)environmentFromLoginShell:(NSString *)shellPath
{
if (!shellPath.length) {
return nil;
}
NSArray *args = @[@"-l", @"-c", @"env", @"-i"];
NSTask *task = [NSTask new];
task.launchPath = shellPath;
task.arguments = args;
task.standardOutput = [NSPipe new];
task.standardError = [NSPipe new];
[task launch];
[task waitUntilExit];
if (task.terminationStatus != EXIT_SUCCESS) {
NSData *stderrData = ((NSPipe *)task.standardError).fileHandleForReading.readDataToEndOfFile;
NSString *stderror = [[NSString alloc] initWithData:stderrData encoding:NSUTF8StringEncoding];
NSLog(@"%@ %@ failed: %@", task.launchPath, [task.arguments componentsJoinedByString:@" "], stderror);
return nil;
}
NSData *stdoutData = ((NSPipe *)task.standardOutput).fileHandleForReading.readDataToEndOfFile;
NSString *envString = [[NSString alloc] initWithData:stdoutData encoding:NSUTF8StringEncoding];
NSArray *envVars = [envString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableDictionary *env = [NSMutableDictionary new];
for (NSString *s in envVars) {
NSMutableArray *keyvalue = [[s componentsSeparatedByString:@"="] mutableCopy];
if (keyvalue.count < 2) {
continue;
}
NSString *key = keyvalue[0];
[keyvalue removeObjectAtIndex:0];
NSString *value = [keyvalue componentsJoinedByString:@"="];
env[key] = value;
}
return env;
}
/* Attempt to get the environment dictionary for the user's chosen shell, using
the $SHELL environment variable.
If that fails, try again using /bin/bash, which should always be available
on OSX. */
- (void)loadLoginShellEnvironmentVariables
{
NSString *shellPath = [[NSProcessInfo processInfo] environment][@"SHELL"];
NSDictionary *env = [self environmentFromLoginShell:shellPath];
if (!env) {
shellPath = @"/bin/bash";
env = [self environmentFromLoginShell:shellPath];
}
if (!env) {
NSLog(@"Couldn't get environment from $SHELL or /bin/bash, defaulting to existing environment.");
} else {
[env enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
setenv(key.UTF8String, value.UTF8String, 1);
}];
}
}
- (void)newWindow
{
activeWindow = [[[VimWindow alloc] init] retain];
}
- (void)newWindowWithArgs:(const std::vector<char *> &)args
{
activeWindow = [[[VimWindow alloc] initWithArgs:args] retain];
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
if ([activeWindow isVisible]) {
[activeWindow promptBeforeClosingWindow];
return NSTerminateCancel;
}
return NSTerminateNow;
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app
{
/* Save window position on close */
NSRect frameRelativeToScreen =
[activeWindow convertRectToScreen:[activeWindow frame]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger: frameRelativeToScreen.origin.x/2 forKey:@"left"];
[defaults setInteger: frameRelativeToScreen.origin.y/2 forKey:@"bottom"];
return YES;
}
/* Makes sure that there is a "Fixed Width" collection.
If there isn't it creates a collection called "Fixed Width"
adds all monospace fonts to it */
- (void)ensureFixedWidthCollection
{
NSFontManager *fontManager = [NSFontManager sharedFontManager];
NSFontCollection *collection =
[NSFontCollection fontCollectionWithName:@"com.apple.AllFonts"];
NSMutableArray *descriptors = [[NSMutableArray alloc] init];
for (NSFontDescriptor *desc in [collection matchingDescriptors])
{
NSString *name = [desc objectForKey:NSFontNameAttribute];
if ([desc symbolicTraits] & NSFontMonoSpaceTrait){
[descriptors addObject:desc];
}
}
collection = [NSFontCollection fontCollectionWithDescriptors:descriptors];
/* Add collection only to this process */
[NSFontCollection showFontCollection:collection
withName:@"Neovim Monospaced"
visibility:NSFontCollectionVisibilityProcess
error:NULL];
}
- (void)applicationWillFinishLaunching:(NSNotification *)notification
{
didFinishLaunching = NO;
[NSFontManager setFontManagerFactory:[VimFontManager class]];
[self ensureFixedWidthCollection];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults registerDefaults:@{@"width": @80,
@"height": @25,
@"left": @0,
@"bottom": @0,
@"fontName": @"Menlo",
@"fontSize": @11.0}];
[self loadLoginShellEnvironmentVariables];
/* Closing vim subprocesses can result in a SIGPIPE, terminating
the program. So, we ignore it. */
ignore_sigpipe();
NSString *vimDir = [[NSBundle mainBundle] resourcePath];
/* Set both VIM and NVIM for now. TODO: Remove VIM when
https://github.com/neovim/neovim/pull/1927 is merged */
setenv("VIM", [vimDir UTF8String], 1);
setenv("NVIM", [vimDir UTF8String], 1);
/* Since Vim is also a terminal emulator these days, it'll be useful to
have the right locale set. Force UTF-8 too since that's what we'll
be sending. */
NSLocale *locale = [NSLocale currentLocale];
NSString *lang = [locale objectForKey:NSLocaleLanguageCode];
NSString *country = [locale objectForKey:NSLocaleCountryCode];
std::stringstream ss;
ss << [lang UTF8String];
if ([country length])
ss << "_" << [country UTF8String];
ss << ".UTF-8";
setenv("LC_ALL", ss.str().c_str(), 1);
setenv("LANG", ss.str().c_str(), 1);
setenv("NVIM_TUI_ENABLE_TRUE_COLOR", "1", 1);
/* Set working dir */
const char *cwd = 0;
/* Parent PID = 1 then Neovim.app was ran by launchd. In these cases
working directory is set to "/". Change to the user's home directory. */
if (getppid() == 1)
cwd = getenv("HOME");
/* Set CWD if given on command line */
for (int i=0; i<g_argc-1; i++) {
if (!strcmp("--cwd", g_argv[i])) {
cwd = g_argv[i + 1];
break;
}
}
if (cwd)
chdir(cwd);
}
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
/* Pass args on to Neovim. OSX will helpfully add a -psn_XXX arg
which Neovim would choke on, so strip it out. */
std::vector<char *> args;
for (int i = 1; i < g_argc ; i++) {
if (!strncmp("-psn_", g_argv[i], 5))
continue;
if (!strcmp("--cwd", g_argv[i])) {
i += 1;
continue;
}
args.push_back(g_argv[i]);
}
if (initOpenFile != NULL) {
char *filename = const_cast<char *>([initOpenFile UTF8String]);
if (std::find(args.begin(), args.end(), filename) != args.end())
args.push_back(filename);
}
[self newWindowWithArgs:args];
didFinishLaunching = YES;
}
/* OSX calls this when the user opens a file with us through Finder. But, that
alone would be too easy, so it ALSO parses our command line arguments for
us, decides what it thinks is a filename, and calls this for those too.
Hence the initOpenFile and didFinishLaunching dance. */
- (BOOL)application:(NSApplication *)app openFile:(NSString *)filename
{
if (didFinishLaunching) {
std::vector<char *> args;
args.push_back(const_cast<char *>([filename UTF8String]));
activeWindow = [[[VimWindow alloc] initWithArgs:args] retain];
}
else {
initOpenFile = filename;
[initOpenFile retain];
}
return YES;
}
@end