source: trunk/ICeCoffEE/ICeCoffEE/ICeCoffEE.m@ 381

Last change on this file since 381 was 381, checked in by Nicholas Riley, 16 years ago

ICeCoffEEShared.h: Remove 10.3 compatibility.

ICeCoffEE.m: Set ICCF_MAX_URL_LEN to 1024 for 1.5dX releases; remove
static which caused compilation failure (can be removed after Terminal
parsing code is better integrated?); remove 10.3 compatibility.

File size: 18.4 KB
RevLine 
[182]1// ICeCoffEE - Internet Config Carbon/Cocoa Editor Extension
[66]2// Nicholas Riley <mailto:icecoffee@sabi.net>
3
4#import "ICeCoffEE.h"
5#import <Carbon/Carbon.h>
6#include <unistd.h>
7#import "ICeCoffEESuper.h"
[320]8#import "ICeCoffEEServices.h"
[183]9#import "ICeCoffEETrigger.h"
[322]10#import "ICeCoffEEParser.h"
[66]11
[74]12iccfPrefRec ICCF_prefs;
[66]13
[74]14NSString *ICCF_ErrString(OSStatus err, NSString *context) {
15 if (err == noErr || err == userCanceledErr) return nil;
[66]16
[74]17 NSString *errNum = [NSString stringWithFormat: @"%ld", err];
18 NSString *errDesc = ICCF_LocalizedString(errNum);
[66]19
[74]20 if (errDesc == NULL || errDesc == errNum)
21 errDesc = [NSString stringWithFormat: ICCF_LocalizedString(@"An unknown error occurred in %@"), context];
22
[66]23 return [NSString stringWithFormat: @"%@ (%d)", errDesc, (int)err];
24}
25
[74]26CFStringRef ICCF_CopyErrString(OSStatus err, CFStringRef context) {
27 if (err == noErr || err == userCanceledErr) return NULL;
28
29 CFStringRef errNum = CFStringCreateWithFormat(NULL, NULL, CFSTR("%ld"), err);
30 CFStringRef errDesc = ICCF_CopyLocalizedString(errNum);
31
32 if (errDesc == NULL || errDesc == errNum) {
33 CFStringRef errDescFormat = ICCF_CopyLocalizedString(CFSTR("An unknown error occurred in %@"));
34 if (errDesc != NULL) CFRelease(errDesc);
35 errDesc = CFStringCreateWithFormat(NULL, NULL, errDescFormat, context);
36 }
37
38 CFStringRef errStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%d)"), errDesc, (int)err);
39
40 if (errNum != NULL) CFRelease(errNum);
41 if (errDesc != NULL) CFRelease(errDesc);
42 return errStr;
43}
44
[139]45CFStringRef ICCF_CopyAppName() {
46 ProcessSerialNumber psn = {0, kCurrentProcess};
47 CFStringRef appName = NULL;
48 CopyProcessName(&psn, &appName);
49 if (appName == NULL) return CFSTR("(unknown)");
50 return appName;
51}
52
[66]53BOOL ICCF_EventIsCommandMouseDown(NSEvent *e) {
[106]54 return ([e type] == NSLeftMouseDown && ([e modifierFlags] & NSCommandKeyMask) != 0 && [e clickCount] == 1);
[66]55}
56
[183]57iccfURLAction ICCF_KeyboardAction(NSEvent *e) {
58 unsigned int modifierFlags = [e modifierFlags];
[106]59 iccfURLAction action;
60 action.presentMenu = (modifierFlags & NSAlternateKeyMask) != 0;
61 action.launchInBackground = (modifierFlags & NSShiftKeyMask) != 0;
62 return action;
[74]63}
64
[375]65// RFC-ordained max URL length, just to avoid passing IC/LS multi-megabyte documents
66#if ICCF_DEBUG
[381]67const long ICCF_MAX_URL_LEN = 1024; // XXX change later
[375]68#else
[381]69const long ICCF_MAX_URL_LEN = 1024;
[375]70#endif
71
72void ICCF_CheckRange(NSRange range) {
73 NSCAssert(range.length > 0, ICCF_LocalizedString(@"No URL is selected"));
74 NSCAssert1(range.length <= ICCF_MAX_URL_LEN, ICCF_LocalizedString(@"The potential URL is longer than %lu characters"), ICCF_MAX_URL_LEN);
75}
76
[79]77ConstStringPtr ICCF_GetHint(ICInstance inst, const char *urlData, Size length, long *selStart, long *selEnd, Boolean *needsSlashes) {
[74]78 Handle h = NewHandle(0);
79 OSStatus err;
[322]80
[74]81 if (h == NULL) return NULL;
[322]82
[74]83 // parse the URL providing a bogus protocol, to get rid of escaped forms
[79]84 err = ICParseURL(inst, "\p*", urlData, length, selStart, selEnd, h);
[74]85 if (err != noErr) return NULL;
[322]86
[74]87 // scan through the parsed URL looking for characters not found in email addresses
88 Size hSize = GetHandleSize(h);
89 if (hSize == 0) return NULL;
[322]90
[74]91 const char *urlParsed = *h;
92 long i = 0;
93 Boolean sawAt = false;
[79]94 if (hSize >= 2 && urlParsed[0] == '*' && urlParsed[1] == ':') {
[74]95 // this is an IC-inserted protocol; skip over it
96 i = 2;
[79]97 *needsSlashes = (hSize < i + 2 || urlParsed[i] != '/' || urlParsed[i + 1] != '/');
98 } else *needsSlashes = false;
[74]99 for ( ; i < hSize ; i++) {
100 char c = urlParsed[i];
101 if (c == '@') {
102 sawAt = true;
103 } else if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
104 (c == '+' || c == '-' || c == '_' || c == '!' || c == '.'))) {
105 DisposeHandle(h);
106 return "\phttp";
107 }
108 }
109 DisposeHandle(h);
[79]110 if (sawAt) {
111 *needsSlashes = false;
112 return "\pmailto";
113 }
114 return "\phttp";
[74]115}
116
[79]117static const char *kICSlashes = "//";
118
119void ICCF_AddSlashes(Handle h, ConstStringPtr hint) {
120 Size sizeBefore = GetHandleSize(h);
121 unsigned char hintLength = StrLength(hint);
122 char *copy = (char *)malloc(sizeBefore);
123 memcpy(copy, *h, sizeBefore);
124 ICLog(@"ICCF_AddSlashes before: |%s|\n", *h);
125 ReallocateHandle(h, sizeBefore + 2);
[322]126
[79]127 // if *h begins with '<hint>:', then copy the slashes after it
[181]128 if (sizeBefore > hintLength + 1 && strncmp((const char *)&hint[1], copy, hintLength) == 0 && copy[hintLength] == ':') {
[79]129 memcpy(*h, copy, hintLength + 1);
130 memcpy(*h + hintLength + 1, kICSlashes, 2);
131 memcpy(*h + hintLength + 3, &copy[hintLength + 1], sizeBefore - hintLength - 1);
132 } else {
133 memcpy(*h, kICSlashes, 2);
134 memcpy(*h + 2, copy, sizeBefore);
135 }
[322]136
[79]137 free(copy);
138 ICLog(@"ICCF_AddSlashes after: |%s|\n", *h);
139}
140
[183]141BOOL ICCF_LaunchURL(NSString *string, iccfURLAction action) {
142 OSStatus err = noErr;
[66]143 long selStart, selEnd;
[272]144 NSMutableString *urlString = [[NSMutableString alloc] init];
145 NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
146 NSScanner *scanner = [[NSScanner alloc] initWithString: string];
147 NSString *fragmentString;
148 while ([scanner scanUpToCharactersFromSet: whitespace intoString: &fragmentString]) {
149 [urlString appendString: fragmentString];
150 }
151 unsigned len = [urlString length];
[66]152
[79]153 Handle h = NULL;
[66]154
155 NS_DURING
[79]156 h = NewHandle(len);
157 if (h == NULL)
158 ICCF_OSErrCAssert(MemError(), @"NewHandle");
[66]159
[272]160 if (CFStringGetBytes((CFStringRef)urlString, CFRangeMake(0, len), kCFStringEncodingASCII, '\0', false, (UInt8 *)*h, len, NULL) != len)
[79]161 ICCF_OSErrCAssert(kTECNoConversionPathErr, @"CFStringGetBytes");
[66]162
163 selStart = 0; selEnd = len;
164
[79]165 Boolean needsSlashes;
166 ConstStringPtr hint = ICCF_GetHint(ICCF_GetInst(), *h, len, &selStart, &selEnd, &needsSlashes);
[167]167 NSCAssert(hint != NULL, @"Internal error: can't get protocol hint for URL");
[74]168
[79]169 if (needsSlashes) {
170 ICCF_AddSlashes(h, hint);
171 len = selEnd = GetHandleSize(h);
172 }
173
[106]174 err = ICCF_DoURLAction(ICCF_GetInst(), hint, *h, selStart, selEnd, action);
175 ICCF_OSErrCAssert(err, @"ICCF_DoURLAction");
[66]176
177 NS_HANDLER
[79]178 DisposeHandle(h);
[272]179 [urlString release];
[66]180 [localException raise];
181 NS_ENDHANDLER
[272]182
[183]183 DisposeHandle(h);
[272]184 [urlString release];
[183]185
186 return (err == noErr);
[66]187}
188
[74]189// XXX not sure what to do if there's already a selection; BBEdit and MLTE extend it, Tex-Edit Plus doesn't.
190Boolean ICCF_enabled = true;
[66]191
[74]192BOOL ICCF_HandleException(NSException *e) {
193 if ([e reason] == nil || [[e reason] length] == 0)
194 return NO;
195
196 if (ICCF_prefs.errorSoundEnabled) NSBeep();
197 if (!ICCF_prefs.errorDialogEnabled) return YES;
198
199 int result = NSRunAlertPanel(ICCF_LocalizedString(@"AlertTitle"), ICCF_LocalizedString(@"AlertMessage%@"), nil, nil, ICCF_LocalizedString(@"AlertDisableButton"), e);
[66]200 if (result != NSAlertDefaultReturn) {
[139]201 result = NSRunAlertPanel(ICCF_LocalizedString(@"DisableAlertTitle"), ICCF_LocalizedString(@"DisableAlertMessage%@"), ICCF_LocalizedString(@"DisableAlertDisableButton"), ICCF_LocalizedString(@"DisableAlertDontDisableButton"), nil,
202 [(NSString *)ICCF_CopyAppName() autorelease]);
[66]203 if (result == NSAlertDefaultReturn)
204 ICCF_enabled = NO;
205 }
[74]206 return YES;
[66]207}
208
[183]209void ICCF_LaunchURLFromTextView(NSTextView *self, NSEvent *triggeringEvent) {
[322]210 NSRange range = [self selectedRange];
[66]211 NSColor *insertionPointColor = [self insertionPointColor];
212 NSString *s = [[self textStorage] string]; // according to the class documentation, sending 'string' is guaranteed to be O(1)
213 int i;
214
215 NS_DURING
216
[74]217 NSCAssert(range.location != NSNotFound, ICCF_LocalizedString(@"There is no insertion point or selection in the text field where you clicked"));
218 NSCAssert(s != nil, ICCF_LocalizedString(@"Sorry, ICeCoffEE is unable to locate the insertion point or selection"));
[66]219
220 ICCF_StartIC();
221
[74]222 NSCAssert([s length] != 0, ICCF_LocalizedString(@"No text was found"));
[66]223
224 if (range.location == [s length]) range.location--; // work around bug in selectionRangeForProposedRange (r. 2845418)
225
[322]226 // XXX is this even worth it to get a starting range? Can just grab back and forth ICCF_MAX_URL_LEN (will need to remove some ICCF_CheckRange calls though)
[66]227 range = [self selectionRangeForProposedRange: range granularity: NSSelectByWord];
228
229 // However, NSSelectByWord does not capture even the approximate boundaries of a URL
230 // (text to a space/line ending character); it'll stop at a period in the middle of a hostname.
231 // So, we expand it as follows:
[320]232
[322]233 range = ICCF_URLEnclosingRange(s, range);
[66]234
235 [self setSelectedRange: range affinity: NSSelectionAffinityDownstream stillSelecting: NO];
236 [self display];
237
[183]238 if (ICCF_LaunchURL([s substringWithRange: range], ICCF_KeyboardAction(triggeringEvent)) && ICCF_prefs.textBlinkEnabled) {
[74]239 for (i = 0 ; i < ICCF_prefs.textBlinkCount ; i++) {
240 NSRange emptyRange = {range.location, 0};
241 [self setSelectedRange: emptyRange affinity: NSSelectionAffinityDownstream stillSelecting: YES];
242 [self display];
243 usleep(kICBlinkDelayUsecs);
244 [self setInsertionPointColor: [self backgroundColor]];
245 [self setSelectedRange: range affinity: NSSelectionAffinityDownstream stillSelecting: YES];
246 [self display];
247 usleep(kICBlinkDelayUsecs);
248 }
249 }
250
[66]251 NS_HANDLER
252 ICCF_HandleException(localException);
253 NS_ENDHANDLER
254
255 ICCF_StopIC();
256 [self setInsertionPointColor: insertionPointColor];
257}
258
259NSString * const ICCF_SERVICES_ITEM = @"ICeCoffEE Services Item";
260
261NSMenuItem *ICCF_ServicesMenuItem() {
262 NSMenuItem *servicesItem;
[182]263 NSString *servicesTitle = nil;
264 NSMenu *servicesMenu = [NSApp servicesMenu];
265
266 if (servicesMenu != nil) {
267 servicesTitle = [servicesMenu title];
268 if (servicesTitle == nil) {
269 ICLog(@"Can't get service menu title");
270 servicesTitle = @"Services";
271 }
272 } else {
273 servicesTitle = [[NSBundle bundleWithIdentifier: @"com.apple.AppKit"] localizedStringForKey: @"Services" value: nil table: @"ServicesMenu"];
274 if (servicesTitle == nil) {
275 ICLog(@"Can't get localized text for 'Services' in AppKit.framework");
276 servicesTitle = @"Services";
277 }
[66]278 }
279 servicesMenu = [[NSMenu alloc] initWithTitle: servicesTitle];
280 servicesItem = [[NSMenuItem alloc] initWithTitle: servicesTitle action:nil keyEquivalent:@""];
[182]281 ICCF_SetServicesMenu(servicesMenu);
[66]282 [servicesItem setSubmenu: servicesMenu];
283 [servicesItem setRepresentedObject: ICCF_SERVICES_ITEM];
284 [servicesMenu release];
[139]285 return [servicesItem autorelease];
[66]286}
287
[139]288static const unichar UNICHAR_BLACK_RIGHT_POINTING_SMALL_TRIANGLE = 0x25b8;
289
290// returns YES if menu contains useful items, NO otherwise
[320]291static BOOL ICCF_ConsolidateServicesMenu(NSMenu *menu, NSDictionary *serviceOptions, NSDictionary *serviceInfo) {
[139]292 [menu update]; // doesn't propagate to submenus, so we need to do this first
293 NSEnumerator *enumerator = [[menu itemArray] objectEnumerator];
294 NSMenuItem *menuItem;
295 NSMenu *submenu;
[319]296 NSDictionary *itemOptions = nil, *itemInfo = nil;
[139]297 BOOL shouldKeepItem = NO, shouldKeepMenu = NO;
298
299 while ( (menuItem = [enumerator nextObject]) != nil) {
[142]300 if (serviceOptions != nil)
301 itemOptions = [serviceOptions objectForKey: [menuItem title]];
[319]302 if (serviceInfo != nil)
303 itemInfo = [serviceInfo objectForKey: [menuItem title]];
[142]304 if ([[itemOptions objectForKey: (NSString *)kICServiceHidden] boolValue]) {
305 shouldKeepItem = NO;
306 } else if ( (submenu = [menuItem submenu]) != nil) {
[319]307 // XXX don't rely on nil-sending working
[320]308 shouldKeepItem = ICCF_ConsolidateServicesMenu(submenu, [itemOptions objectForKey: (NSString *)kICServiceSubmenu], [itemInfo objectForKey: (NSString *)kICServiceSubmenu]);
[139]309 if (shouldKeepItem && [submenu numberOfItems] == 1) { // consolidate
310 NSMenuItem *serviceItem = [[submenu itemAtIndex: 0] retain];
311 [serviceItem setTitle:
312 [NSString stringWithFormat: @"%@ %@ %@", [menuItem title], [NSString stringWithCharacters: &UNICHAR_BLACK_RIGHT_POINTING_SMALL_TRIANGLE length: 1], [serviceItem title]]];
[319]313
[139]314 int serviceIndex = [menu indexOfItem: menuItem];
315 [submenu removeItemAtIndex: 0]; // can't have item in two menus
316 [menu removeItemAtIndex: serviceIndex];
317 [menu insertItem: serviceItem atIndex: serviceIndex];
318 [serviceItem release];
[319]319 menuItem = serviceItem;
[139]320 }
321 } else {
[182]322 [menuItem setKeyEquivalent: @""];
[139]323 shouldKeepItem = [menuItem isEnabled];
324 }
[319]325 if (!shouldKeepItem) {
[139]326 [menu removeItem: menuItem];
[319]327 continue;
[139]328 }
[319]329 shouldKeepMenu = YES;
330
331 if (itemInfo == nil) continue;
332 NSString *bundlePath = (NSString *)[itemInfo objectForKey: (NSString *)kICServiceBundlePath];
333 if (bundlePath == NULL) continue;
334 IconRef serviceIcon = ICCF_CopyIconRefForPath(bundlePath);
335 if (serviceIcon == NULL) continue;
336 [menuItem _setIconRef: serviceIcon];
337 ReleaseIconRef(serviceIcon);
[139]338 }
339
340 return shouldKeepMenu;
341}
342
343NSMenuItem *ICCF_ContextualServicesMenuItem() {
344 NSMenuItem *servicesItem = ICCF_ServicesMenuItem();
[319]345 NSDictionary *servicesInfo = ICCF_GetServicesInfo(); // XXX cache/retain
346 if (ICCF_ConsolidateServicesMenu([servicesItem submenu], (NSDictionary *)ICCF_prefs.serviceOptions, servicesInfo))
[139]347 return servicesItem;
348 else
349 return nil;
350}
351
[74]352void ICCF_AddRemoveServicesMenu() {
353 // needed because:
354 // (a) we get called before the runloop has properly started and will crash if we don't delay on app startup
355 // (b) the APE message handler calls us from another thread and nothing happens if we try to add a menu on it
356 [ICeCoffEE performSelectorOnMainThread: @selector(IC_addRemoveServicesMenu) withObject: nil waitUntilDone: NO];
[66]357}
358
[167]359NSMenu *ICCF_MenuForEvent(NSView *self, NSMenu *contextMenu, NSEvent *e) {
[66]360 if (contextMenu != nil && [e type] == NSRightMouseDown || ([e type] == NSLeftMouseDown && [e modifierFlags] & NSControlKeyMask)) {
361 int servicesItemIndex = [contextMenu indexOfItemWithRepresentedObject: ICCF_SERVICES_ITEM];
[139]362 // always regenerate: make sure menu reflects context
363 if (servicesItemIndex != -1) {
[74]364 [contextMenu removeItemAtIndex: servicesItemIndex];
365 [contextMenu removeItemAtIndex: servicesItemIndex - 1];
[66]366 }
[139]367 if (ICCF_prefs.servicesInContextualMenu) {
368 NSMenuItem *contextualServicesItem = ICCF_ContextualServicesMenuItem();
369 if (contextualServicesItem != nil) {
370 [contextMenu addItem: [NSMenuItem separatorItem]];
371 [contextMenu addItem: contextualServicesItem];
372 }
373 }
[66]374 }
375 return contextMenu;
376}
377
[183]378static NSEvent *ICCF_MouseDownEventWithModifierFlags(NSEvent *e, BOOL inheritModifierFlags) {
379 return [NSEvent mouseEventWithType: NSLeftMouseDown
380 location: [e locationInWindow]
381 modifierFlags: (inheritModifierFlags ? [e modifierFlags] : 0)
382 timestamp: [e timestamp]
383 windowNumber: [e windowNumber]
384 context: [e context]
385 eventNumber: [e eventNumber]
386 clickCount: 1
387 pressure: 0];
388}
[182]389
[183]390
[74]391@implementation ICeCoffEE
392
393+ (void)IC_addRemoveServicesMenu;
[66]394{
395 NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
[74]396 static NSMenuItem *servicesItem = nil;
397
398 if (servicesItem == nil && ICCF_prefs.servicesInMenuBar) {
399 servicesItem = [ICCF_ServicesMenuItem() retain];
[66]400
[74]401 int insertLoc = [mainMenu indexOfItemWithSubmenu: [NSApp windowsMenu]];
402 if (insertLoc == -1)
403 insertLoc = [mainMenu numberOfItems];
[66]404
[74]405 [mainMenu insertItem: servicesItem atIndex: insertLoc];
406 } else if (servicesItem != nil && !ICCF_prefs.servicesInMenuBar) {
407 [mainMenu removeItem: servicesItem];
408 [servicesItem release];
409 servicesItem = nil;
410 }
[66]411}
412
413// XXX localization?
414- (NSMenu *)menuForEvent:(NSEvent *)e;
415{
416 NSMenu *myMenu = [super menuForEvent: e];
417 return ICCF_MenuForEvent(self, myMenu, e);
418}
419
420- (void)mouseDown:(NSEvent *)e;
421{
422#if ICCF_DEBUG
423 static BOOL down = NO;
424 if (down) {
425 ICLog(@"recursive invocation!");
426 return;
427 }
428 down = YES;
429 ICLog(@"ICeCoffEE down: %@", e);
430#endif
[183]431 if (ICCF_sharedTrigger != nil) {
432 ICLog(@"%@ cancelling", ICCF_sharedTrigger);
433 [ICCF_sharedTrigger cancel];
434 }
[106]435 if (ICCF_enabled && ICCF_prefs.commandClickEnabled && ICCF_EventIsCommandMouseDown(e)) {
[183]436 BOOL inheritModifierFlags;
[182]437 if ([self respondsToSelector: @selector(selectedRanges)]) {
[183]438 // Command-multiple-click or -drag for discontiguous selection, Mac OS X 10.4 or later
439 inheritModifierFlags = YES;
[182]440 } else {
441 // don't want to trigger selection extension or anything else; pass through as a plain click
[183]442 // (on Mac OS X 10.3, command does not modify behavior)
443 inheritModifierFlags = NO;
[182]444 }
[183]445 [super mouseDown: ICCF_MouseDownEventWithModifierFlags(e, inheritModifierFlags)];
[106]446 // we don't actually get a mouseUp event, just wait for mouseDown to return
[66]447 NSEvent *upEvent = [[self window] currentEvent];
448 NSPoint downPt = [e locationInWindow];
449 NSPoint upPt = [upEvent locationInWindow];
450 ICLog(@"next: %@", upEvent);
451 NSAssert([upEvent type] == NSLeftMouseUp, @"NSTextView mouseDown: did not return with current event as mouse up!");
[74]452 if (abs(downPt.x - upPt.x) <= kICHysteresisPixels && abs(downPt.y - upPt.y) <= kICHysteresisPixels) {
[183]453 if (inheritModifierFlags) {
454 // Mac OS X 10.4 and later: make sure we don't have a command-double-click
455 [ICeCoffEETrigger setTriggerForEvent: e onTarget: self]; // gets stored in ICCF_sharedTrigger; the reason for this weird calling pattern is that we don't want to add methods to NSTextView, and we don't want to add a method call on every mouseDown
456 ICLog(@"%@ set", ICCF_sharedTrigger);
457 } else {
458 // Mac OS X 10.3
459 ICCF_LaunchURLFromTextView(self, e);
460 }
[66]461 }
[106]462 } else {
463 [super mouseDown: e];
[66]464 }
465#if ICCF_DEBUG
466 down = NO;
467#endif
468}
469
470@end
Note: See TracBrowser for help on using the repository browser.