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

Last change on this file since 75 was 75, checked in by Nicholas Riley, 19 years ago

Fixed bugs, added final set of features for 1.3b3.

File size: 17.7 KB
Line 
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
10- Menu on command-option-click: add bookmark, open with other helper, pass to configurable service, ...?
11- TXNClick - MLTE has its own support in Jaguar and later, but it's lousy
12
13Done:
14
15- TEClick - TextEdit
16- flash on success (like BBEdit)
17- display dialog on failure (decode OSStatus)
18- adjust URL blinking
19- app exclusion list - make a pref pane (see AquaShade config)
20- _LSCopyApplicationURLsForItemURL - list apps
21
22*/
23
24#import "ICeCoffEE.h"
25#import <Carbon/Carbon.h>
26#include <unistd.h>
27#import "ICeCoffEESuper.h"
28#import "ICeCoffEEActionMenu.h"
29
30iccfPrefRec ICCF_prefs;
31
32NSString *ICCF_ErrString(OSStatus err, NSString *context) {
33 if (err == noErr || err == userCanceledErr) return nil;
34
35 NSString *errNum = [NSString stringWithFormat: @"%ld", err];
36 NSString *errDesc = ICCF_LocalizedString(errNum);
37
38 if (errDesc == NULL || errDesc == errNum)
39 errDesc = [NSString stringWithFormat: ICCF_LocalizedString(@"An unknown error occurred in %@"), context];
40
41 return [NSString stringWithFormat: @"%@ (%d)", errDesc, (int)err];
42}
43
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
63BOOL ICCF_EventIsCommandMouseDown(NSEvent *e) {
64 unsigned int modifierFlags = [e modifierFlags];
65 return ([e type] == NSLeftMouseDown &&
66 (modifierFlags == NSCommandKeyMask || modifierFlags == (NSCommandKeyMask | NSAlternateKeyMask))
67 && [e clickCount] == 1);
68}
69
70BOOL ICCF_OptionKeyIsDown() {
71 unsigned int modifierFlags = [[NSApp currentEvent] modifierFlags];
72 return (modifierFlags & NSAlternateKeyMask) != 0;
73}
74
75void ICCF_CheckRange(NSRange range) {
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);
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 }
114 err = ICStart(&ICCF_icInst, kICCFCreator);
115 NSCAssert1(err == noErr, ICCF_LocalizedString(@"Unable to start Internet Config (error %d)"), err);
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
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
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));
188 NSCAssert(urlData != NULL, @"Internal error: canÕt allocate memory for URL string");
189
190 selStart = 0; selEnd = range->length;
191
192 [string getCString: urlData];
193
194 h = NewHandle(0);
195 NSCAssert(h != NULL, @"Internal error: canÕt allocate URL handle");
196
197 err = ICParseURL(ICCF_GetInst(), "\pmailto", urlData, range->length, &selStart, &selEnd, h);
198 DisposeHandle(h);
199
200 ICCF_OSErrCAssert(err, @"ICParseURL");
201
202 range->length = selEnd - selStart;
203 range->location += selStart;
204 NS_HANDLER
205 free(urlData);
206 [localException raise];
207 NS_ENDHANDLER
208
209 free(urlData);
210}
211
212void ICCF_LaunchURL(NSString *string, BOOL chooseApp) {
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));
221 NSCAssert(urlData != NULL, @"Internal error: canÕt allocate memory for URL string");
222
223 [string getCString: urlData];
224
225 selStart = 0; selEnd = len;
226
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_DoURLActionMenu(ICCF_GetInst(), hint, urlData, selStart, selEnd);
232 ICCF_OSErrCAssert(err, @"ICCF_DoURLActionMenu");
233 } else {
234 err = ICLaunchURL(ICCF_GetInst(), hint, urlData, len, &selStart, &selEnd);
235 ICCF_OSErrCAssert(err, @"ICLaunchURL");
236 }
237
238 NS_HANDLER
239 free(urlData);
240 [localException raise];
241 NS_ENDHANDLER
242
243 free(urlData);
244}
245
246// XXX not sure what to do if there's already a selection; BBEdit and MLTE extend it, Tex-Edit Plus doesn't.
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
254Boolean ICCF_enabled = true;
255
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);
264 if (result != NSAlertDefaultReturn) {
265 result = NSRunAlertPanel(ICCF_LocalizedString(@"DisableAlertTitle"), ICCF_LocalizedString(@"DisableAlertMessage"), ICCF_LocalizedString(@"DisableAlertDisableButton"), ICCF_LocalizedString(@"DisableAlertDontDisableButton"), nil);
266 if (result == NSAlertDefaultReturn)
267 ICCF_enabled = NO;
268 }
269 return YES;
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
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"));
284
285 ICCF_StartIC();
286
287 NSCAssert([s length] != 0, ICCF_LocalizedString(@"No text was found"));
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
340 ICCF_LaunchURL([s substringWithRange: range], ICCF_OptionKeyIsDown());
341
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
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
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];
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];
393 if (servicesItemIndex == -1 && ICCF_prefs.servicesInContextualMenu) {
394 [contextMenu addItem: [NSMenuItem separatorItem]];
395 [contextMenu addItem: ICCF_ServicesMenuItem()];
396 } else if (servicesItemIndex != -1 && !ICCF_prefs.servicesInContextualMenu) {
397 [contextMenu removeItemAtIndex: servicesItemIndex];
398 [contextMenu removeItemAtIndex: servicesItemIndex - 1];
399 }
400 }
401 return contextMenu;
402}
403
404@implementation ICeCoffEE
405
406+ (NSString *)IC_version;
407{
408 // XXX get from bundle if possible: centralize
409 return [NSString stringWithCString: ICCF_VERSION];
410}
411
412+ (void)IC_addRemoveServicesMenu;
413{
414 NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
415 static NSMenuItem *servicesItem = nil;
416
417 if (servicesItem == nil && ICCF_prefs.servicesInMenuBar) {
418 servicesItem = [ICCF_ServicesMenuItem() retain];
419
420 int insertLoc = [mainMenu indexOfItemWithSubmenu: [NSApp windowsMenu]];
421 if (insertLoc == -1)
422 insertLoc = [mainMenu numberOfItems];
423
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 }
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];
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
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!");
465 if (abs(downPt.x - upPt.x) <= kICHysteresisPixels && abs(downPt.y - upPt.y) <= kICHysteresisPixels) {
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.