/
ViAppController.m
395 lines (343 loc) · 12.8 KB
/
ViAppController.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
#import "ViAppController.h"
#import "ViThemeStore.h"
#import "ViLanguageStore.h"
#import "ViDocument.h"
#import "ViDocumentView.h"
#import "ViDocumentController.h"
#import "ViPreferencesController.h"
#import "TMFileURLProtocol.h"
#import "TxmtURLProtocol.h"
#import "Nu/Nu.h"
#import "JSON.h"
#import "ViError.h"
#import "ViCommandMenuItemView.h"
#import "ViTextView.h"
#include <sys/time.h>
@implementation ViAppController
@synthesize encodingMenu;
- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
NSString *s = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
NSURL *url = [NSURL URLWithString:s];
NSError *error = nil;
[[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:url
display:YES
error:&error];
if (error)
[NSApp presentError:error];
}
- (id)init
{
self = [super init];
if (self) {
[NSApp setDelegate:self];
[[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
}
return self;
}
// Application Delegate method
// stops the application from creating an untitled document on load
- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
return YES;
}
- (void)newBundleLoaded:(NSNotification *)notification
{
/* Check if any open documents got a better language available. */
ViDocument *doc;
for (doc in [[NSDocumentController sharedDocumentController] documents])
if ([doc respondsToSelector:@selector(configureSyntax)])
[doc configureSyntax];
}
+ (NSString *)supportDirectory
{
static NSString *supportDirectory = nil;
if (supportDirectory == nil)
supportDirectory = [@"~/Library/Application Support/Vico" stringByExpandingTildeInPath];
return supportDirectory;
}
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification
{
[NSApp activateIgnoringOtherApps:YES];
[[NSFileManager defaultManager] createDirectoryAtPath:[ViAppController supportDirectory]
withIntermediateDirectories:YES
attributes:nil
error:nil];
NSUserDefaults *userDefs = [NSUserDefaults standardUserDefaults];
/* initialize default defaults */
[userDefs registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:8], @"shiftwidth",
[NSNumber numberWithInt:8], @"tabstop",
[NSNumber numberWithBool:YES], @"autoindent",
[NSNumber numberWithBool:YES], @"smartpair",
[NSNumber numberWithBool:YES], @"ignorecase",
[NSNumber numberWithBool:YES], @"smartcase",
[NSNumber numberWithBool:YES], @"expandtabs",
[NSNumber numberWithBool:YES], @"number",
[NSNumber numberWithBool:YES], @"autocollapse",
[NSNumber numberWithBool:NO], @"hidetab",
[NSNumber numberWithBool:YES], @"searchincr",
[NSNumber numberWithBool:NO], @"showguide",
[NSNumber numberWithBool:YES], @"wrap",
[NSNumber numberWithBool:YES], @"antialias",
[NSNumber numberWithInt:80], @"guidecolumn",
[NSNumber numberWithFloat:11.0], @"fontsize",
@"vim", @"undostyle",
@"Menlo Regular", @"fontname",
@"Sunset", @"theme",
@"(CVS|_darcs|.svn|.git|~$|\\.bak$|\\.o$)", @"skipPattern",
[NSArray arrayWithObject:[NSDictionary dictionaryWithObject:@"textmate" forKey:@"username"]], @"bundleRepositoryUsers",
[NSNumber numberWithBool:YES], @"explorecaseignore",
[NSNumber numberWithBool:NO], @"exploresortfolders",
nil]];
/* Initialize languages and themes. */
[ViLanguageStore defaultStore];
[ViThemeStore defaultStore];
NSArray *opts = [NSArray arrayWithObjects:
@"theme", @"showguide", @"guidecolumn", @"undostyle", nil];
for (NSString *opt in opts)
[userDefs addObserver:self
forKeyPath:opt
options:NSKeyValueObservingOptionNew
context:NULL];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(newBundleLoaded:)
name:ViLanguageStoreBundleLoadedNotification
object:nil];
const NSStringEncoding *encoding = [NSString availableStringEncodings];
NSMutableArray *array = [NSMutableArray array];
NSMenuItem *item;
while (*encoding) {
NSString *title = [NSString localizedNameOfStringEncoding:*encoding];
item = [[NSMenuItem alloc] initWithTitle:title
action:@selector(setEncoding:)
keyEquivalent:@""];
[item setRepresentedObject:[NSNumber numberWithUnsignedLong:*encoding]];
[array addObject:item];
encoding++;
}
NSSortDescriptor *sdesc = [[NSSortDescriptor alloc] initWithKey:@"title"
ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:sdesc]];
for (item in array)
[encodingMenu addItem:item];
[TMFileURLProtocol registerProtocol];
[TxmtURLProtocol registerProtocol];
//shellConn = [NSConnection serviceConnectionWithName:@"chunky bacon" rootObject:self];
shellConn = [NSConnection new];
[shellConn setRootObject:self];
[shellConn registerName:[NSString stringWithFormat:@"vico.%u", (unsigned int)getuid()]];
extern struct timeval launch_start;
struct timeval launch_done, launch_diff;
gettimeofday(&launch_done, NULL);
timersub(&launch_done, &launch_start, &launch_diff);
INFO(@"launched after %fs", launch_diff.tv_sec + (float)launch_diff.tv_usec / 1000000);
NSString *consoleStartup = @"((NuConsoleWindowController alloc) init)";
[[Nu parser] parseEval:consoleStartup];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
ViDocument *doc;
if ([keyPath isEqualToString:@"theme"]) {
for (doc in [[NSDocumentController sharedDocumentController] documents])
if ([doc respondsToSelector:@selector(changeTheme:)])
[doc changeTheme:[[ViThemeStore defaultStore] themeWithName:[change objectForKey:NSKeyValueChangeNewKey]]];
} else if ([keyPath isEqualToString:@"showguide"] || [keyPath isEqualToString:@"guidecolumn"]) {
for (doc in [[NSDocumentController sharedDocumentController] documents])
if ([doc respondsToSelector:@selector(updatePageGuide)])
[doc updatePageGuide];
} else if ([keyPath isEqualToString:@"undostyle"]) {
NSString *undostyle = [change objectForKey:NSKeyValueChangeNewKey];
if (![undostyle isEqualToString:@"vim"] && ![undostyle isEqualToString:@"nvi"])
[[NSUserDefaults standardUserDefaults] setObject:@"vim" forKey:@"undostyle"];
}
}
- (IBAction)showPreferences:(id)sender
{
[[ViPreferencesController sharedPreferences] show];
}
extern BOOL makeNewWindowInsteadOfTab;
- (IBAction)newProject:(id)sender
{
#if 0
NSError *error = nil;
NSDocument *proj = [[NSDocumentController sharedDocumentController] makeUntitledDocumentOfType:@"Project" error:&error];
if (proj) {
[[NSDocumentController sharedDocumentController] addDocument:proj];
[proj makeWindowControllers];
[proj showWindows];
}
else {
NSAlert *alert = [NSAlert alertWithError:error];
[alert runModal];
}
#else
makeNewWindowInsteadOfTab = YES;
[[ViDocumentController sharedDocumentController] newDocument:sender];
#endif
}
#pragma mark -
#pragma mark Shell commands
/* Set some convenient global objects. */
- (void)exportGlobals:(id)parser
{
ViWindowController *winCon = [ViWindowController currentWindowController];
if (winCon) {
[parser setValue:winCon.proxy forKey:@"window"];
[parser setValue:winCon.explorer forKey:@"explorer"];
id<ViViewController> view = [winCon currentView];
if (view) {
[parser setValue:view forKey:@"view"];
if ([view isKindOfClass:[ViDocumentView class]]) {
ViTextView *textView = [(ViDocumentView *)view textView];
[parser setValue:textView.proxy forKey:@"text"];
}
}
ViDocument *doc = [winCon currentDocument];
if (doc)
[parser setValue:doc.proxy forKey:@"document"];
}
}
- (id)evalExpression:(NSString *)expression error:(NSError **)outError
{
id<NuParsing> parser = [Nu parser];
[self exportGlobals:parser];
id code = [parser parse:expression];
if (code == nil) {
if (outError)
*outError = [ViError errorWithFormat:@"parse failed"];
return nil;
}
id result = [parser eval:code];
return result;
}
- (NSString *)eval:(NSString *)script
withScriptPath:(NSString *)path
additionalBindings:(NSDictionary *)bindings
errorString:(NSString **)errorString
backChannel:(NSString *)channelName
{
id<NuParsing> parser = [Nu parser];
[self exportGlobals:parser];
if (channelName) {
NSDistantObject *backChannel = [NSConnection rootProxyForConnectionWithRegisteredName:channelName host:nil];
[parser setValue:backChannel forKey:@"shellCommand"];
}
for (NSString *key in [bindings allKeys])
if ([key isKindOfClass:[NSString class]])
[parser setValue:[bindings objectForKey:key] forKey:key];
DEBUG(@"evaluating script: {{{ %@ }}}", script);
DEBUG(@"additional bindings: %@", bindings);
[Nu loadNuFile:@"nu" fromBundleWithIdentifier:@"nu.programming.framework" withContext:[parser context]];
[Nu loadNuFile:@"bridgesupport" fromBundleWithIdentifier:@"nu.programming.framework" withContext:[parser context]];
[Nu loadNuFile:@"cocoa" fromBundleWithIdentifier:@"nu.programming.framework" withContext:[parser context]];
[Nu loadNuFile:@"nibtools" fromBundleWithIdentifier:@"nu.programming.framework" withContext:[parser context]];
[Nu loadNuFile:@"vico" fromBundleWithIdentifier:@"se.bzero.Vico" withContext:[parser context]];
id code = [parser parse:script];
if (code == nil) {
if (errorString)
*errorString = @"parse failed";
return nil;
}
id result = nil;
@try {
result = [parser eval:code];
}
@catch (NSException *exception) {
DEBUG(@"got exception %@", [exception name]);
if (errorString)
*errorString = [exception reason];
return nil;
}
return [result JSONRepresentation];
}
- (NSError *)openURL:(NSString *)pathOrURL
{
ViDocumentController *docCon = [ViDocumentController sharedDocumentController];
ViDocument *doc = [docCon openDocument:pathOrURL
andDisplay:YES
allowDirectory:YES];
if (doc)
[NSApp activateIgnoringOtherApps:YES];
return nil;
}
- (void)menuNeedsUpdate:(NSMenu *)menu
{
ViRegexp *rx = [[ViRegexp alloc] initWithString:@" +\\((.*?)\\)( *\\((.*?)\\))?$"];
for (NSMenuItem *item in [menu itemArray]) {
NSString *title = nil;
if ([item tag] == 4000) {
title = [item title];
[item setRepresentedObject:title];
} else if ([item tag] == 4001)
title = [item representedObject];
if (title) {
DEBUG(@"updating menuitem %@, title %@", item, title);
ViRegexpMatch *m = [rx matchInString:title];
if (m && [m count] == 4) {
NSMutableString *newTitle = [title mutableCopy];
[newTitle replaceCharactersInRange:[m rangeOfMatchedString]
withString:@""];
DEBUG(@"title %@ -> %@, got %lu matches", title, newTitle, [m count]);
NSRange nrange = [m rangeOfSubstringAtIndex:1]; /* normal range */
NSRange vrange = [m rangeOfSubstringAtIndex:3]; /* visual range */
if (vrange.location == NSNotFound)
vrange = nrange;
BOOL hasSelection = NO;
NSWindow *window = [[NSApplication sharedApplication] mainWindow];
NSResponder *target = [window firstResponder];
if ([target respondsToSelector:@selector(selectedRange)]) {
if ([(NSText *)target selectedRange].length > 0)
hasSelection = YES;
}
/* Replace "Thing / Selection" depending on hasSelection.
*/
NSRange r = [newTitle rangeOfString:@" / Selection"];
if (r.location != NSNotFound) {
if (hasSelection) {
NSCharacterSet *set = [NSCharacterSet letterCharacterSet];
NSInteger l;
for (l = r.location; l > 0; l--)
if (![set characterIsMember:[newTitle characterAtIndex:l - 1]])
break;
NSRange altr = NSMakeRange(l, r.location - l + 3);
if (altr.length > 3)
[newTitle deleteCharactersInRange:altr];
} else
[newTitle deleteCharactersInRange:r];
}
NSString *command = [title substringWithRange:(hasSelection ? vrange : nrange)];
DEBUG(@"command is [%@]", command);
if ([command length] == 0) {
/* use the other match, but disable the menu item */
command = [title substringWithRange:(hasSelection ? nrange : vrange)];
DEBUG(@"disabled command is [%@]", command);
[item setEnabled:NO];
[item setAction:NULL];
} else {
[item setEnabled:YES];
[item setAction:@selector(performNormalModeMenuItem:)];
}
ViCommandMenuItemView *view = (ViCommandMenuItemView *)[item view];
if (view == nil)
view = [[ViCommandMenuItemView alloc] initWithTitle:newTitle
command:command
font:[menu font]];
else {
view.title = newTitle;
view.command = command;
}
[item setView:view];
[item setTitle:newTitle];
}
[item setTag:4001]; /* mark as already updated */
}
}
}
@end