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

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

ICeCoffEE 1.3b2 plus some changes for 1.3

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