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

Last change on this file since 124 was 106, checked in by Nicholas Riley, 21 years ago

ICeCoffEE 1.3.2b1

File size: 18.7 KB
RevLine 
[66]1// ICeCoffEE - Internet Config Cocoa Editor Extension
2// Nicholas Riley <mailto:icecoffee@sabi.net>
3
4/* To do/think about:
5
[74]6- TXNClick - MLTE has its own support in Jaguar and later, but it's lousy
[66]7
8Done:
9
[74]10- TEClick - TextEdit
[66]11- flash on success (like BBEdit)
12- display dialog on failure (decode OSStatus)
[74]13- adjust URL blinking
14- app exclusion list - make a pref pane (see AquaShade config)
[75]15- _LSCopyApplicationURLsForItemURL - list apps
[79]16- Menu on command-option-click: add bookmark, open with other helper, pass to configurable service, ...?
[66]17
18*/
19
20#import "ICeCoffEE.h"
21#import <Carbon/Carbon.h>
22#include <unistd.h>
23#import "ICeCoffEESuper.h"
24
[74]25iccfPrefRec ICCF_prefs;
[66]26
[74]27NSString *ICCF_ErrString(OSStatus err, NSString *context) {
28 if (err == noErr || err == userCanceledErr) return nil;
[66]29
[74]30 NSString *errNum = [NSString stringWithFormat: @"%ld", err];
31 NSString *errDesc = ICCF_LocalizedString(errNum);
[66]32
[74]33 if (errDesc == NULL || errDesc == errNum)
34 errDesc = [NSString stringWithFormat: ICCF_LocalizedString(@"An unknown error occurred in %@"), context];
35
[66]36 return [NSString stringWithFormat: @"%@ (%d)", errDesc, (int)err];
37}
38
[74]39CFStringRef ICCF_CopyErrString(OSStatus err, CFStringRef context) {
40 if (err == noErr || err == userCanceledErr) return NULL;
41
42 CFStringRef errNum = CFStringCreateWithFormat(NULL, NULL, CFSTR("%ld"), err);
43 CFStringRef errDesc = ICCF_CopyLocalizedString(errNum);
44
45 if (errDesc == NULL || errDesc == errNum) {
46 CFStringRef errDescFormat = ICCF_CopyLocalizedString(CFSTR("An unknown error occurred in %@"));
47 if (errDesc != NULL) CFRelease(errDesc);
48 errDesc = CFStringCreateWithFormat(NULL, NULL, errDescFormat, context);
49 }
50
51 CFStringRef errStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%d)"), errDesc, (int)err);
52
53 if (errNum != NULL) CFRelease(errNum);
54 if (errDesc != NULL) CFRelease(errDesc);
55 return errStr;
56}
57
[66]58BOOL ICCF_EventIsCommandMouseDown(NSEvent *e) {
[106]59 return ([e type] == NSLeftMouseDown && ([e modifierFlags] & NSCommandKeyMask) != 0 && [e clickCount] == 1);
[66]60}
61
[106]62iccfURLAction ICCF_KeyboardAction() {
[74]63 unsigned int modifierFlags = [[NSApp currentEvent] modifierFlags];
[106]64 iccfURLAction action;
65 action.presentMenu = (modifierFlags & NSAlternateKeyMask) != 0;
66 action.launchInBackground = (modifierFlags & NSShiftKeyMask) != 0;
67 return action;
[74]68}
69
[66]70void ICCF_CheckRange(NSRange range) {
[74]71 NSCAssert(range.length > 0, ICCF_LocalizedString(@"No URL is selected"));
72 NSCAssert1(range.length <= ICCF_MAX_URL_LEN, ICCF_LocalizedString(@"The potential URL is longer than %lu characters"), ICCF_MAX_URL_LEN);
[66]73}
74
75void ICCF_Delimiters(NSCharacterSet **leftPtr, NSCharacterSet **rightPtr) {
76 static NSCharacterSet *urlLeftDelimiters = nil, *urlRightDelimiters = nil;
77
78 if (urlLeftDelimiters == nil || urlRightDelimiters == nil) {
79 NSMutableCharacterSet *set = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];
80 NSMutableCharacterSet *tmpSet;
81 [urlLeftDelimiters release];
82 [urlRightDelimiters release];
83
84 [set autorelease];
85 [set formUnionWithCharacterSet: [NSCharacterSet punctuationCharacterSet]];
86 [set removeCharactersInString: @";/?:@&=+$,-_.!~*'()%#"]; // RFC 2396 ¤2.2, 2.3, 2.4, plus #
87
88 tmpSet = [[set mutableCopy] autorelease];
89 [tmpSet formUnionWithCharacterSet: [NSCharacterSet characterSetWithCharactersInString: @"><("]];
90 urlLeftDelimiters = [tmpSet copy]; // make immutable again - for efficiency
91
92 tmpSet = [[set mutableCopy] autorelease];
93 [tmpSet formUnionWithCharacterSet: [NSCharacterSet characterSetWithCharactersInString: @"><)"]];
94 urlRightDelimiters = [tmpSet copy]; // make immutable again - for efficiency
95 }
96
97 *leftPtr = urlLeftDelimiters; *rightPtr = urlRightDelimiters;
98}
99
100static ICInstance ICCF_icInst = NULL;
101
102void ICCF_StartIC() {
103 OSStatus err;
104
105 if (ICCF_icInst != NULL) {
106 ICLog(@"ICCF_StartIC: Internet Config is already running!");
107 ICCF_StopIC();
108 }
[74]109 err = ICStart(&ICCF_icInst, kICCFCreator);
110 NSCAssert1(err == noErr, ICCF_LocalizedString(@"Unable to start Internet Config (error %d)"), err);
[66]111}
112
113void ICCF_StopIC() {
114 if (ICCF_icInst == NULL) {
115 ICLog(@"ICCF_StopIC: Internet Config is not running!");
116 } else {
117 ICStop(ICCF_icInst);
118 ICCF_icInst = NULL;
119 }
120}
121
122ICInstance ICCF_GetInst() {
123 NSCAssert(ICCF_icInst != NULL, @"Internal error: Called ICCF_GetInst without ICCF_StartIC");
124 return ICCF_icInst;
125}
126
[79]127ConstStringPtr ICCF_GetHint(ICInstance inst, const char *urlData, Size length, long *selStart, long *selEnd, Boolean *needsSlashes) {
[74]128 Handle h = NewHandle(0);
129 OSStatus err;
[79]130
[74]131 if (h == NULL) return NULL;
132
133 // parse the URL providing a bogus protocol, to get rid of escaped forms
[79]134 err = ICParseURL(inst, "\p*", urlData, length, selStart, selEnd, h);
[74]135 if (err != noErr) return NULL;
136
137 // scan through the parsed URL looking for characters not found in email addresses
138 Size hSize = GetHandleSize(h);
139 if (hSize == 0) return NULL;
140
141 const char *urlParsed = *h;
142 long i = 0;
143 Boolean sawAt = false;
[79]144 if (hSize >= 2 && urlParsed[0] == '*' && urlParsed[1] == ':') {
[74]145 // this is an IC-inserted protocol; skip over it
146 i = 2;
[79]147 *needsSlashes = (hSize < i + 2 || urlParsed[i] != '/' || urlParsed[i + 1] != '/');
148 } else *needsSlashes = false;
[74]149 for ( ; i < hSize ; i++) {
150 char c = urlParsed[i];
151 if (c == '@') {
152 sawAt = true;
153 } else if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
154 (c == '+' || c == '-' || c == '_' || c == '!' || c == '.'))) {
155 DisposeHandle(h);
156 return "\phttp";
157 }
158 }
159 DisposeHandle(h);
[79]160 if (sawAt) {
161 *needsSlashes = false;
162 return "\pmailto";
163 }
164 return "\phttp";
[74]165}
166
[79]167static const char *kICSlashes = "//";
168
169void ICCF_AddSlashes(Handle h, ConstStringPtr hint) {
170 Size sizeBefore = GetHandleSize(h);
171 unsigned char hintLength = StrLength(hint);
172 char *copy = (char *)malloc(sizeBefore);
173 memcpy(copy, *h, sizeBefore);
174 ICLog(@"ICCF_AddSlashes before: |%s|\n", *h);
175 ReallocateHandle(h, sizeBefore + 2);
176
177 // if *h begins with '<hint>:', then copy the slashes after it
178 if (sizeBefore > hintLength + 1 && strncmp(&hint[1], copy, hintLength) == 0 && copy[hintLength] == ':') {
179 memcpy(*h, copy, hintLength + 1);
180 memcpy(*h + hintLength + 1, kICSlashes, 2);
181 memcpy(*h + hintLength + 3, &copy[hintLength + 1], sizeBefore - hintLength - 1);
182 } else {
183 memcpy(*h, kICSlashes, 2);
184 memcpy(*h + 2, copy, sizeBefore);
185 }
186
187 free(copy);
188 ICLog(@"ICCF_AddSlashes after: |%s|\n", *h);
189}
190
[66]191void ICCF_ParseURL(NSString *string, NSRange *range) {
192 OSStatus err;
193 Handle h;
194 long selStart, selEnd;
195 char *urlData = NULL;
196
197 NSCAssert(range->length == [string length], @"Internal error: URL string is wrong length");
198
199 NS_DURING
200 if ([[NSCharacterSet characterSetWithCharactersInString: @";,."] characterIsMember:
201 [string characterAtIndex: range->length - 1]]) {
202 range->length--;
203 }
204
205 string = [string substringToIndex: range->length];
206
207 ICLog(@"Parsing URL |%@|", string);
208
209 urlData = (char *)malloc( (range->length + 1) * sizeof(char));
[74]210 NSCAssert(urlData != NULL, @"Internal error: canÕt allocate memory for URL string");
[66]211
212 selStart = 0; selEnd = range->length;
213
214 [string getCString: urlData];
215
216 h = NewHandle(0);
[74]217 NSCAssert(h != NULL, @"Internal error: canÕt allocate URL handle");
218
[66]219 err = ICParseURL(ICCF_GetInst(), "\pmailto", urlData, range->length, &selStart, &selEnd, h);
[74]220 DisposeHandle(h);
221
[66]222 ICCF_OSErrCAssert(err, @"ICParseURL");
223
[74]224 range->length = selEnd - selStart;
[66]225 range->location += selStart;
226 NS_HANDLER
227 free(urlData);
228 [localException raise];
229 NS_ENDHANDLER
230
231 free(urlData);
232}
233
[106]234void ICCF_LaunchURL(NSString *string, iccfURLAction action) {
[66]235 OSStatus err;
236 long selStart, selEnd;
237 unsigned len = [string length];
238
[79]239 Handle h = NULL;
[66]240
241 NS_DURING
[79]242 h = NewHandle(len);
243 if (h == NULL)
244 ICCF_OSErrCAssert(MemError(), @"NewHandle");
[66]245
[79]246 if (CFStringGetBytes((CFStringRef)string, CFRangeMake(0, len), kCFStringEncodingASCII, '\0', false, *h, len, NULL) != len)
247 ICCF_OSErrCAssert(kTECNoConversionPathErr, @"CFStringGetBytes");
[66]248
249 selStart = 0; selEnd = len;
250
[79]251 Boolean needsSlashes;
252 ConstStringPtr hint = ICCF_GetHint(ICCF_GetInst(), *h, len, &selStart, &selEnd, &needsSlashes);
[74]253 NSCAssert(hint != NULL, @"Internal error: canÕt get protocol hint for URL");
254
[79]255 if (needsSlashes) {
256 ICCF_AddSlashes(h, hint);
257 len = selEnd = GetHandleSize(h);
258 }
259
[106]260 err = ICCF_DoURLAction(ICCF_GetInst(), hint, *h, selStart, selEnd, action);
261 ICCF_OSErrCAssert(err, @"ICCF_DoURLAction");
[66]262
263 NS_HANDLER
[79]264 DisposeHandle(h);
[66]265 [localException raise];
266 NS_ENDHANDLER
267
[79]268 DisposeHandle(h);
[66]269}
270
[74]271// XXX not sure what to do if there's already a selection; BBEdit and MLTE extend it, Tex-Edit Plus doesn't.
[106]272// RFC-ordained max URL length, just to avoid passing IC/LS multi-megabyte documents
[66]273#if ICCF_DEBUG
[106]274const long ICCF_MAX_URL_LEN = 60; // XXX change later
[66]275#else
276const long ICCF_MAX_URL_LEN = 1024;
277#endif
278
[74]279Boolean ICCF_enabled = true;
[66]280
[74]281BOOL ICCF_HandleException(NSException *e) {
282 if ([e reason] == nil || [[e reason] length] == 0)
283 return NO;
284
285 if (ICCF_prefs.errorSoundEnabled) NSBeep();
286 if (!ICCF_prefs.errorDialogEnabled) return YES;
287
288 int result = NSRunAlertPanel(ICCF_LocalizedString(@"AlertTitle"), ICCF_LocalizedString(@"AlertMessage%@"), nil, nil, ICCF_LocalizedString(@"AlertDisableButton"), e);
[66]289 if (result != NSAlertDefaultReturn) {
[74]290 result = NSRunAlertPanel(ICCF_LocalizedString(@"DisableAlertTitle"), ICCF_LocalizedString(@"DisableAlertMessage"), ICCF_LocalizedString(@"DisableAlertDisableButton"), ICCF_LocalizedString(@"DisableAlertDontDisableButton"), nil);
[66]291 if (result == NSAlertDefaultReturn)
292 ICCF_enabled = NO;
293 }
[74]294 return YES;
[66]295}
296
297void ICCF_LaunchURLFromTextView(NSTextView *self) {
298 NSCharacterSet *urlLeftDelimiters = nil, *urlRightDelimiters = nil;
299 NSRange range = [self selectedRange], delimiterRange;
300 NSColor *insertionPointColor = [self insertionPointColor];
301 NSString *s = [[self textStorage] string]; // according to the class documentation, sending 'string' is guaranteed to be O(1)
302 unsigned extraLen;
303 int i;
304
305 NS_DURING
306
[74]307 NSCAssert(range.location != NSNotFound, ICCF_LocalizedString(@"There is no insertion point or selection in the text field where you clicked"));
308 NSCAssert(s != nil, ICCF_LocalizedString(@"Sorry, ICeCoffEE is unable to locate the insertion point or selection"));
[66]309
310 ICCF_StartIC();
311
[74]312 NSCAssert([s length] != 0, ICCF_LocalizedString(@"No text was found"));
[66]313
314 if (range.location == [s length]) range.location--; // work around bug in selectionRangeForProposedRange (r. 2845418)
315
316 range = [self selectionRangeForProposedRange: range granularity: NSSelectByWord];
317
318 // However, NSSelectByWord does not capture even the approximate boundaries of a URL
319 // (text to a space/line ending character); it'll stop at a period in the middle of a hostname.
320 // So, we expand it as follows:
321
322 ICCF_CheckRange(range);
323
324 ICCF_Delimiters(&urlLeftDelimiters, &urlRightDelimiters);
325
326 // XXX instead of 0, make this stop at the max URL length to prevent protracted searches
327 // add 1 to range to trap delimiters that are on the edge of the selection (i.e., <...)
328 delimiterRange = [s rangeOfCharacterFromSet: urlLeftDelimiters
329 options: NSLiteralSearch | NSBackwardsSearch
330 range: NSMakeRange(0, range.location + (range.location != [s length]))];
331 if (delimiterRange.location == NSNotFound) {
332 // extend to beginning of string
333 range.length += range.location;
334 range.location = 0;
335 } else {
336 NSCAssert(delimiterRange.length == 1, @"Internal error: delimiter matched range is not of length 1");
337 range.length += range.location - delimiterRange.location - 1;
338 range.location = delimiterRange.location + 1;
339 }
340
341 ICCF_CheckRange(range);
342
343 // XXX instead of length of string, make this stop at the max URL length to prevent protracted searches
344 // add 1 to range to trap delimiters that are on the edge of the selection (i.e., ...>)
345 extraLen = [s length] - range.location - range.length;
346 delimiterRange = [s rangeOfCharacterFromSet: urlRightDelimiters
347 options: NSLiteralSearch
348 range: NSMakeRange(range.location + range.length - (range.length != 0),
349 extraLen + (range.length != 0))];
350 if (delimiterRange.location == NSNotFound) {
351 // extend to end of string
352 range.length += extraLen;
353 } else {
354 NSCAssert(delimiterRange.length == 1, @"Internal error: delimiter matched range is not of length 1");
355 range.length += delimiterRange.location - range.location - range.length;
356 }
357
358 ICCF_CheckRange(range);
359
360 ICCF_ParseURL([s substringWithRange: range], &range);
361
362 [self setSelectedRange: range affinity: NSSelectionAffinityDownstream stillSelecting: NO];
363 [self display];
364
[106]365 ICCF_LaunchURL([s substringWithRange: range], ICCF_KeyboardAction());
[66]366
[74]367 if (ICCF_prefs.textBlinkEnabled) {
368 for (i = 0 ; i < ICCF_prefs.textBlinkCount ; i++) {
369 NSRange emptyRange = {range.location, 0};
370 [self setSelectedRange: emptyRange affinity: NSSelectionAffinityDownstream stillSelecting: YES];
371 [self display];
372 usleep(kICBlinkDelayUsecs);
373 [self setInsertionPointColor: [self backgroundColor]];
374 [self setSelectedRange: range affinity: NSSelectionAffinityDownstream stillSelecting: YES];
375 [self display];
376 usleep(kICBlinkDelayUsecs);
377 }
378 }
379
[66]380 NS_HANDLER
381 ICCF_HandleException(localException);
382 NS_ENDHANDLER
383
384 ICCF_StopIC();
385 [self setInsertionPointColor: insertionPointColor];
386}
387
388NSString * const ICCF_SERVICES_ITEM = @"ICeCoffEE Services Item";
389
390NSMenuItem *ICCF_ServicesMenuItem() {
391 NSMenuItem *servicesItem;
392 NSMenu *servicesMenu;
393 // XXX better to just use [[NSApp servicesMenu] title]? That grabs the title from the existing Services submenu.
394 NSString *servicesTitle = [[NSBundle bundleWithIdentifier: @"com.apple.AppKit"] localizedStringForKey: @"Services" value: nil table: @"ServicesMenu"];
395 if (servicesTitle == nil) {
396 ICLog(@"CanÕt get localized text for ÒServicesÓ in AppKit.framework");
397 servicesTitle = @"Services";
398 }
399 servicesMenu = [[NSMenu alloc] initWithTitle: servicesTitle];
400 servicesItem = [[NSMenuItem alloc] initWithTitle: servicesTitle action:nil keyEquivalent:@""];
401 [[NSApplication sharedApplication] setServicesMenu: servicesMenu];
402 [servicesItem setSubmenu: servicesMenu];
403 [servicesItem setRepresentedObject: ICCF_SERVICES_ITEM];
404 [servicesMenu release];
405 return servicesItem;
406}
407
[74]408void ICCF_AddRemoveServicesMenu() {
409 // needed because:
410 // (a) we get called before the runloop has properly started and will crash if we don't delay on app startup
411 // (b) the APE message handler calls us from another thread and nothing happens if we try to add a menu on it
412 [ICeCoffEE performSelectorOnMainThread: @selector(IC_addRemoveServicesMenu) withObject: nil waitUntilDone: NO];
[66]413}
414
415NSMenu *ICCF_MenuForEvent(NSTextView *self, NSMenu *contextMenu, NSEvent *e) {
416 if (contextMenu != nil && [e type] == NSRightMouseDown || ([e type] == NSLeftMouseDown && [e modifierFlags] & NSControlKeyMask)) {
417 int servicesItemIndex = [contextMenu indexOfItemWithRepresentedObject: ICCF_SERVICES_ITEM];
[74]418 if (servicesItemIndex == -1 && ICCF_prefs.servicesInContextualMenu) {
[66]419 [contextMenu addItem: [NSMenuItem separatorItem]];
420 [contextMenu addItem: ICCF_ServicesMenuItem()];
[74]421 } else if (servicesItemIndex != -1 && !ICCF_prefs.servicesInContextualMenu) {
422 [contextMenu removeItemAtIndex: servicesItemIndex];
423 [contextMenu removeItemAtIndex: servicesItemIndex - 1];
[66]424 }
425 }
426 return contextMenu;
427}
428
[74]429@implementation ICeCoffEE
430
431+ (void)IC_addRemoveServicesMenu;
[66]432{
433 NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
[74]434 static NSMenuItem *servicesItem = nil;
435
436 if (servicesItem == nil && ICCF_prefs.servicesInMenuBar) {
437 servicesItem = [ICCF_ServicesMenuItem() retain];
[66]438
[74]439 int insertLoc = [mainMenu indexOfItemWithSubmenu: [NSApp windowsMenu]];
440 if (insertLoc == -1)
441 insertLoc = [mainMenu numberOfItems];
[66]442
[74]443 [mainMenu insertItem: servicesItem atIndex: insertLoc];
444 } else if (servicesItem != nil && !ICCF_prefs.servicesInMenuBar) {
445 [mainMenu removeItem: servicesItem];
446 [servicesItem release];
447 servicesItem = nil;
448 }
[66]449}
450
451// XXX localization?
452- (NSMenu *)menuForEvent:(NSEvent *)e;
453{
454 NSMenu *myMenu = [super menuForEvent: e];
455 return ICCF_MenuForEvent(self, myMenu, e);
456}
457
458- (void)mouseDown:(NSEvent *)e;
459{
460#if ICCF_DEBUG
461 static BOOL down = NO;
462 if (down) {
463 ICLog(@"recursive invocation!");
464 return;
465 }
466 down = YES;
467 ICLog(@"ICeCoffEE down: %@", e);
468#endif
[106]469 if (ICCF_enabled && ICCF_prefs.commandClickEnabled && ICCF_EventIsCommandMouseDown(e)) {
470 // don't want to trigger selection extension or anything else; pass through as a plain click
471 [super mouseDown: [NSEvent mouseEventWithType: NSLeftMouseDown location: [e locationInWindow] modifierFlags: 0 timestamp: [e timestamp] windowNumber: [e windowNumber] context: [e context] eventNumber: [e eventNumber] clickCount: 1 pressure: 0]];
472 // we don't actually get a mouseUp event, just wait for mouseDown to return
[66]473 NSEvent *upEvent = [[self window] currentEvent];
474 NSPoint downPt = [e locationInWindow];
475 NSPoint upPt = [upEvent locationInWindow];
476 ICLog(@"next: %@", upEvent);
477 NSAssert([upEvent type] == NSLeftMouseUp, @"NSTextView mouseDown: did not return with current event as mouse up!");
[74]478 if (abs(downPt.x - upPt.x) <= kICHysteresisPixels && abs(downPt.y - upPt.y) <= kICHysteresisPixels) {
[66]479 ICCF_LaunchURLFromTextView(self);
480 }
[106]481 } else {
482 [super mouseDown: e];
[66]483 }
484#if ICCF_DEBUG
485 down = NO;
486#endif
487}
488
489@end
Note: See TracBrowser for help on using the repository browser.