source: trunk/ICeCoffEE/ICeCoffEE/ICeCoffEE.m

Last change on this file was 495, checked in by Nicholas Riley, 15 years ago

English.proj/APEInfo.rtfd: Updated for 1.5b5.

English.lproj/InfoPlist.strings: Updated copyright date.

English.lproj/Localizable.strings: Don't report an error in WebKit if
there's nothing to launch ("Sorry, ICeCoffEE was unable to find
anything to select").

ICeCoffEE/ICeCoffEE.m: Don't trigger exception with Command-click
outside text range (introduced in 10.5.x?).

ICeCoffEE/ICeCoffEEWebKit.m: Update for WebFrame changes (r39145).

VERSION.xcconfig: Updated for 1.5b5.

File size: 19.0 KB
Line 
1// ICeCoffEE - Internet Config Carbon/Cocoa Editor Extension
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"
8#import "ICeCoffEEServices.h"
9#import "ICeCoffEETextViewTrigger.h"
10#import "ICeCoffEEParser.h"
11
12iccfPrefRec ICCF_prefs;
13
14NSString *ICCF_ErrString(OSStatus err, NSString *context) {
15 if (err == noErr || err == userCanceledErr) return nil;
16
17 NSString *errNum = [NSString stringWithFormat: @"%ld", err];
18 NSString *errDesc = ICCF_LocalizedString(errNum);
19
20 if (errDesc == NULL || errDesc == errNum)
21 errDesc = [NSString stringWithFormat: ICCF_LocalizedString(@"An unknown error occurred in %@"), context];
22
23 return [NSString stringWithFormat: @"%@ (%d)", errDesc, (int)err];
24}
25
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
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
53BOOL ICCF_EventIsCommandMouseDown(NSEvent *e) {
54 return ([e type] == NSLeftMouseDown && ([e modifierFlags] & NSCommandKeyMask) != 0 && [e clickCount] == 1);
55}
56
57iccfURLAction ICCF_KeyboardAction(NSEvent *e) {
58 unsigned int modifierFlags = [e modifierFlags];
59 iccfURLAction action;
60 action.presentMenu = (modifierFlags & NSAlternateKeyMask) != 0;
61 action.launchInBackground = (modifierFlags & NSShiftKeyMask) != 0;
62 return action;
63}
64
65// RFC-ordained max URL length, just to avoid passing IC/LS multi-megabyte documents
66#if ICCF_DEBUG
67const long ICCF_MAX_URL_LEN = 1024; // XXX change later
68#else
69const long ICCF_MAX_URL_LEN = 1024;
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
77ConstStringPtr ICCF_GetHint(ICInstance inst, const char *urlData, Size length, long *selStart, long *selEnd, Boolean *needsSlashes) {
78 Handle h = NewHandle(0);
79 OSStatus err;
80
81 if (h == NULL) return NULL;
82
83 // parse the URL providing a bogus protocol, to get rid of escaped forms
84 err = ICParseURL(inst, "\p*", urlData, length, selStart, selEnd, h);
85 if (err != noErr) return NULL;
86
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;
90
91 const char *urlParsed = *h;
92 long i = 0;
93 Boolean sawAt = false;
94 if (hSize >= 2 && urlParsed[0] == '*' && urlParsed[1] == ':') {
95 // this is an IC-inserted protocol; skip over it
96 i = 2;
97 *needsSlashes = (hSize < i + 2 || urlParsed[i] != '/' || urlParsed[i + 1] != '/');
98 } else *needsSlashes = false;
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);
110 if (sawAt) {
111 *needsSlashes = false;
112 return "\pmailto";
113 }
114 return "\phttp";
115}
116
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);
126
127 // if *h begins with '<hint>:', then copy the slashes after it
128 if (sizeBefore > hintLength + 1 && strncmp((const char *)&hint[1], copy, hintLength) == 0 && copy[hintLength] == ':') {
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 }
136
137 free(copy);
138 ICLog(@"ICCF_AddSlashes after: |%s|\n", *h);
139}
140
141BOOL ICCF_LaunchURL(NSString *string, iccfURLAction action) {
142 OSStatus err = noErr;
143 long selStart, selEnd;
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];
152
153 Handle h = NULL;
154
155 @try {
156 h = NewHandle(len);
157 if (h == NULL)
158 ICCF_OSErrCAssert(MemError(), @"NewHandle");
159
160 if (CFStringGetBytes((CFStringRef)urlString, CFRangeMake(0, len), kCFStringEncodingASCII, '\0', false, (UInt8 *)*h, len, NULL) != len)
161 ICCF_OSErrCAssert(kTECNoConversionPathErr, @"CFStringGetBytes");
162
163 selStart = 0; selEnd = len;
164
165 Boolean needsSlashes;
166 ConstStringPtr hint = ICCF_GetHint(ICCF_GetInst(), *h, len, &selStart, &selEnd, &needsSlashes);
167 NSCAssert(hint != NULL, @"Internal error: can't get protocol hint for URL");
168
169 if (needsSlashes) {
170 ICCF_AddSlashes(h, hint);
171 len = selEnd = GetHandleSize(h);
172 }
173
174 err = ICCF_DoURLAction(ICCF_GetInst(), hint, *h, selStart, selEnd, action);
175 ICCF_OSErrCAssert(err, @"ICCF_DoURLAction");
176 } @finally {
177 DisposeHandle(h);
178 [urlString release];
179 }
180
181 return (err == noErr);
182}
183
184// XXX not sure what to do if there's already a selection; BBEdit and MLTE extend it, Tex-Edit Plus doesn't.
185Boolean ICCF_enabled = true;
186
187BOOL ICCF_HandleException(NSException *e, NSEvent *event) {
188 if ([e reason] == nil || [[e reason] length] == 0)
189 return NO;
190
191 if (ICCF_prefs.errorSoundEnabled) NSBeep();
192 if (!ICCF_prefs.errorDialogEnabled) return YES;
193
194 [[NSApplication sharedApplication] activateIgnoringOtherApps: YES];
195 [[event window] makeKeyAndOrderFront: nil];
196
197 int result = NSRunAlertPanel(ICCF_LocalizedString(@"AlertTitle"), ICCF_LocalizedString(@"AlertMessage%@"), nil, nil, ICCF_LocalizedString(@"AlertDisableButton"), e);
198 if (result != NSAlertDefaultReturn) {
199 result = NSRunAlertPanel(ICCF_LocalizedString(@"DisableAlertTitle"), ICCF_LocalizedString(@"DisableAlertMessage%@"), ICCF_LocalizedString(@"DisableAlertDisableButton"), ICCF_LocalizedString(@"DisableAlertDontDisableButton"), nil,
200 [(NSString *)ICCF_CopyAppName() autorelease]);
201 if (result == NSAlertDefaultReturn)
202 ICCF_enabled = NO;
203 }
204 return YES;
205}
206
207void ICCF_LaunchURLFromTextView(NSTextView *self, NSEvent *triggeringEvent) {
208 BOOL isEditable = [self isEditable];
209
210 @try {
211 NSString *s = [[self textStorage] string]; // according to the class documentation, sending 'string' is guaranteed to be O(1)
212 unsigned length = [s length];
213 NSCAssert(s != nil, ICCF_LocalizedString(@"Sorry, ICeCoffEE is unable to locate the insertion point or selection"));
214 NSCAssert(length != 0, ICCF_LocalizedString(@"No text was found"));
215
216 ICCF_StartIC();
217
218 NSRange range = [self selectedRange];
219 NSCAssert(range.location != NSNotFound, ICCF_LocalizedString(@"There is no insertion point or selection in the text field where you clicked"));
220 NSString *url = nil;
221
222 if (range.location == length)
223 range.location--; // Leopard text storage complains "out of range"
224
225 if ([[self textStorage] attribute: NSLinkAttributeName atIndex: range.location
226 effectiveRange: NULL] != nil) {
227 NSRange linkRange;
228 id link = [[self textStorage] attribute: NSLinkAttributeName atIndex: range.location longestEffectiveRange: &linkRange inRange: NSMakeRange(0, length)];
229 if (NSMaxRange(range) <= NSMaxRange(linkRange)) {
230 // selection is entirely within link range
231 url = [link isKindOfClass: [NSURL class]] ? [link absoluteString] : link;
232 range = linkRange;
233 [self setSelectedRange: range affinity: NSSelectionAffinityDownstream stillSelecting: NO];
234 }
235 }
236 if (url == nil) {
237 if (range.length == 0) {
238 if (range.location == length) range.location--;
239 range.length = 1;
240 range = ICCF_URLEnclosingRange(s, range);
241 [self setSelectedRange: range affinity: NSSelectionAffinityDownstream stillSelecting: NO];
242 }
243
244 url = [s substringWithRange: range];
245 }
246
247 if (ICCF_LaunchURL(url, ICCF_KeyboardAction(triggeringEvent)) && ICCF_prefs.textBlinkEnabled) {
248 if (isEditable)
249 [self setEditable: NO];
250
251 for (unsigned i = 0 ; i < ICCF_prefs.textBlinkCount ; i++) {
252 NSRange emptyRange = {range.location, 0};
253 [self setSelectedRange: emptyRange affinity: NSSelectionAffinityDownstream stillSelecting: YES];
254 [self display];
255 usleep(kICBlinkDelayUsecs);
256 [self setSelectedRange: range affinity: NSSelectionAffinityDownstream stillSelecting: YES];
257 [self display];
258 usleep(kICBlinkDelayUsecs);
259 }
260 }
261 } @catch (NSException *e) {
262 ICCF_HandleException(e, triggeringEvent);
263 }
264
265 ICCF_StopIC();
266 if (isEditable)
267 [self setEditable: YES];
268}
269
270NSString * const ICCF_SERVICES_ITEM = @"ICeCoffEE Services Item";
271
272NSMenuItem *ICCF_ServicesMenuItem() {
273 NSMenuItem *servicesItem;
274 NSString *servicesTitle = nil;
275 NSMenu *servicesMenu = [NSApp servicesMenu];
276
277 if (servicesMenu != nil) {
278 servicesTitle = [servicesMenu title];
279 if (servicesTitle == nil) {
280 ICLog(@"Can't get service menu title");
281 servicesTitle = @"Services";
282 }
283 } else {
284 servicesTitle = [[NSBundle bundleWithIdentifier: @"com.apple.AppKit"] localizedStringForKey: @"Services" value: nil table: @"ServicesMenu"];
285 if (servicesTitle == nil) {
286 ICLog(@"Can't get localized text for 'Services' in AppKit.framework");
287 servicesTitle = @"Services";
288 }
289 }
290 servicesMenu = [[NSMenu alloc] initWithTitle: servicesTitle];
291 servicesItem = [[NSMenuItem alloc] initWithTitle: servicesTitle action:nil keyEquivalent:@""];
292 ICCF_SetServicesMenu(servicesMenu);
293 [servicesItem setSubmenu: servicesMenu];
294 [servicesItem setRepresentedObject: ICCF_SERVICES_ITEM];
295 [servicesMenu release];
296 return [servicesItem autorelease];
297}
298
299static const unichar UNICHAR_BLACK_RIGHT_POINTING_SMALL_TRIANGLE = 0x25b8;
300
301// returns YES if menu contains useful items, NO otherwise
302static BOOL ICCF_ConsolidateServicesMenu(NSMenu *menu, NSDictionary *serviceOptions, NSDictionary *serviceInfo) {
303 [menu update]; // doesn't propagate to submenus, so we need to do this first
304 NSEnumerator *enumerator = [[menu itemArray] objectEnumerator];
305 NSMenuItem *menuItem;
306 NSMenu *submenu;
307 NSDictionary *itemOptions = nil, *itemInfo = nil;
308 BOOL shouldKeepItem = NO, shouldKeepMenu = NO;
309
310 while ( (menuItem = [enumerator nextObject]) != nil) {
311 if (serviceOptions != nil)
312 itemOptions = [serviceOptions objectForKey: [menuItem title]];
313 if (serviceInfo != nil)
314 itemInfo = [serviceInfo objectForKey: [menuItem title]];
315 if ([[itemOptions objectForKey: (NSString *)kICServiceHidden] boolValue]) {
316 shouldKeepItem = NO;
317 } else if ( (submenu = [menuItem submenu]) != nil) {
318 // XXX don't rely on nil-sending working
319 shouldKeepItem = ICCF_ConsolidateServicesMenu(submenu, [itemOptions objectForKey: (NSString *)kICServiceSubmenu], [itemInfo objectForKey: (NSString *)kICServiceSubmenu]);
320 if (shouldKeepItem && [submenu numberOfItems] == 1) { // consolidate
321 NSMenuItem *serviceItem = [[submenu itemAtIndex: 0] retain];
322 [serviceItem setTitle:
323 [NSString stringWithFormat: @"%@ %@ %@", [menuItem title], [NSString stringWithCharacters: &UNICHAR_BLACK_RIGHT_POINTING_SMALL_TRIANGLE length: 1], [serviceItem title]]];
324
325 int serviceIndex = [menu indexOfItem: menuItem];
326 [submenu removeItemAtIndex: 0]; // can't have item in two menus
327 [menu removeItemAtIndex: serviceIndex];
328 [menu insertItem: serviceItem atIndex: serviceIndex];
329 [serviceItem release];
330 menuItem = serviceItem;
331 }
332 } else {
333 [menuItem setKeyEquivalent: @""];
334 shouldKeepItem = [menuItem isEnabled];
335 }
336 if (!shouldKeepItem) {
337 [menu removeItem: menuItem];
338 continue;
339 }
340 shouldKeepMenu = YES;
341
342 if (itemInfo == nil) continue;
343 NSString *bundlePath = (NSString *)[itemInfo objectForKey: (NSString *)kICServiceBundlePath];
344 if (bundlePath == NULL) continue;
345 IconRef serviceIcon = ICCF_CopyIconRefForPath(bundlePath);
346 if (serviceIcon == NULL) continue;
347 [menuItem _setIconRef: serviceIcon];
348 ReleaseIconRef(serviceIcon);
349 }
350
351 return shouldKeepMenu;
352}
353
354NSMenuItem *ICCF_ContextualServicesMenuItem() {
355 // user key equivalents get populated in 10.4, not in 10.5
356 BOOL usesUserKeyEquivalents = [NSMenuItem usesUserKeyEquivalents];
357 if (usesUserKeyEquivalents) {
358 ICCF_SetServicesMenu([NSApp servicesMenu]); // populate menubar menu with key equivalents
359 [NSMenuItem setUsesUserKeyEquivalents: NO];
360 }
361
362 NSMenuItem *servicesItem = ICCF_ServicesMenuItem();
363
364 if (usesUserKeyEquivalents)
365 [NSMenuItem setUsesUserKeyEquivalents: YES];
366
367 NSDictionary *servicesInfo = ICCF_GetServicesInfo(); // XXX cache/retain
368 if (ICCF_ConsolidateServicesMenu([servicesItem submenu], (NSDictionary *)ICCF_prefs.serviceOptions, servicesInfo))
369 return servicesItem;
370 else
371 return nil;
372}
373
374void ICCF_AddRemoveServicesMenu() {
375 // needed because:
376 // (a) we get called before the runloop has properly started and will crash if we don't delay on app startup
377 // (b) the APE message handler calls us from another thread and nothing happens if we try to add a menu on it
378 [ICeCoffEE performSelectorOnMainThread: @selector(IC_addRemoveServicesMenu) withObject: nil waitUntilDone: NO];
379}
380
381NSMenu *ICCF_MenuForEvent(NSView *self, NSMenu *contextMenu, NSEvent *e) {
382 if (contextMenu != nil && [e type] == NSRightMouseDown || ([e type] == NSLeftMouseDown && [e modifierFlags] & NSControlKeyMask)) {
383 int servicesItemIndex = [contextMenu indexOfItemWithRepresentedObject: ICCF_SERVICES_ITEM];
384 // always regenerate: make sure menu reflects context
385 if (servicesItemIndex != -1) {
386 [contextMenu removeItemAtIndex: servicesItemIndex];
387 [contextMenu removeItemAtIndex: servicesItemIndex - 1];
388 }
389 if (ICCF_prefs.servicesInContextualMenu) {
390 NSMenuItem *contextualServicesItem = ICCF_ContextualServicesMenuItem();
391 if (contextualServicesItem != nil) {
392 [contextMenu addItem: [NSMenuItem separatorItem]];
393 [contextMenu addItem: contextualServicesItem];
394 }
395 }
396 }
397 return contextMenu;
398}
399
400static NSEvent *ICCF_MouseDownEventWithModifierFlags(NSEvent *e, BOOL inheritModifierFlags) {
401 return [NSEvent mouseEventWithType: NSLeftMouseDown
402 location: [e locationInWindow]
403 modifierFlags: (inheritModifierFlags ? [e modifierFlags] : 0)
404 timestamp: [e timestamp]
405 windowNumber: [e windowNumber]
406 context: [e context]
407 eventNumber: [e eventNumber]
408 clickCount: 1
409 pressure: 0];
410}
411
412@implementation ICeCoffEE
413
414+ (void)IC_addRemoveServicesMenu;
415{
416 NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
417 static NSMenuItem *servicesItem = nil;
418
419 if (servicesItem == nil && ICCF_prefs.servicesInMenuBar) {
420 servicesItem = [ICCF_ServicesMenuItem() retain];
421
422 int insertLoc = [mainMenu indexOfItemWithSubmenu: [NSApp windowsMenu]];
423 if (insertLoc == -1)
424 insertLoc = [mainMenu numberOfItems];
425
426 [mainMenu insertItem: servicesItem atIndex: insertLoc];
427 } else if (servicesItem != nil && !ICCF_prefs.servicesInMenuBar) {
428 [mainMenu removeItem: servicesItem];
429 [servicesItem release];
430 servicesItem = nil;
431 }
432}
433
434// XXX localization?
435- (NSMenu *)menuForEvent:(NSEvent *)e;
436{
437 NSMenu *myMenu = [super menuForEvent: e];
438 return ICCF_MenuForEvent(self, myMenu, e);
439}
440
441static BOOL ICCF_inMouseDown;
442
443- (void)clickedOnLink:(id)link atIndex:(unsigned)charIndex;
444{
445 if (!ICCF_inMouseDown)
446 [super clickedOnLink: link atIndex: charIndex];
447}
448
449- (void)mouseDown:(NSEvent *)downEvent;
450{
451#if ICCF_DEBUG
452 static BOOL down = NO;
453 if (down) {
454 ICLog(@"recursive invocation!");
455 return;
456 }
457 down = YES;
458 ICLog(@"ICeCoffEE down: %@", downEvent);
459#endif
460 [ICeCoffEETrigger cancel];
461
462 if (ICCF_enabled && ICCF_prefs.commandClickEnabled && ICCF_EventIsCommandMouseDown(downEvent)) {
463 ICCF_inMouseDown = YES;
464 @try {
465 [super mouseDown: ICCF_MouseDownEventWithModifierFlags(downEvent, YES)];
466 } @finally {
467 ICCF_inMouseDown = NO;
468 }
469 // we don't actually get a mouseUp event, just wait for mouseDown to return
470 NSEvent *upEvent = [[self window] currentEvent];
471 NSPoint downPt = [downEvent locationInWindow];
472 NSPoint upPt = [upEvent locationInWindow];
473 ICLog(@"next: %@", upEvent);
474 NSAssert([upEvent type] == NSLeftMouseUp, @"NSTextView mouseDown: did not return with current event as mouse up!");
475 if (abs(downPt.x - upPt.x) <= kICHysteresisPixels && abs(downPt.y - upPt.y) <= kICHysteresisPixels) {
476 // make sure we don't have a Command-double-click
477 [ICeCoffEETextViewTrigger setTriggerForEvent: downEvent 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
478 }
479 } else {
480 [super mouseDown: downEvent];
481 }
482#if ICCF_DEBUG
483 down = NO;
484#endif
485}
486
487@end
Note: See TracBrowser for help on using the repository browser.