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

Last change on this file since 271 was 264, checked in by Nicholas Riley, 18 years ago

Use blue-tec Localization Suite; strip whitespace from URLs before launching.

File size: 23.7 KB
Line 
1// ICeCoffEE - Internet Config Carbon/Cocoa Editor Extension
2// Nicholas Riley <mailto:icecoffee@sabi.net>
3
4/* To do/think about:
5
6- TXNClick - MLTE has its own (lousy) support in Jaguar, seems improved in Panther, good enough to leave?
7
8*/
9
10#import "ICeCoffEE.h"
11#import <Carbon/Carbon.h>
12#include <unistd.h>
13#import "ICeCoffEESuper.h"
14#import "ICeCoffEESetServicesMenu.h"
15#import "ICeCoffEETrigger.h"
16
17iccfPrefRec ICCF_prefs;
18
19NSString *ICCF_ErrString(OSStatus err, NSString *context) {
20 if (err == noErr || err == userCanceledErr) return nil;
21
22 NSString *errNum = [NSString stringWithFormat: @"%ld", err];
23 NSString *errDesc = ICCF_LocalizedString(errNum);
24
25 if (errDesc == NULL || errDesc == errNum)
26 errDesc = [NSString stringWithFormat: ICCF_LocalizedString(@"An unknown error occurred in %@"), context];
27
28 return [NSString stringWithFormat: @"%@ (%d)", errDesc, (int)err];
29}
30
31CFStringRef ICCF_CopyErrString(OSStatus err, CFStringRef context) {
32 if (err == noErr || err == userCanceledErr) return NULL;
33
34 CFStringRef errNum = CFStringCreateWithFormat(NULL, NULL, CFSTR("%ld"), err);
35 CFStringRef errDesc = ICCF_CopyLocalizedString(errNum);
36
37 if (errDesc == NULL || errDesc == errNum) {
38 CFStringRef errDescFormat = ICCF_CopyLocalizedString(CFSTR("An unknown error occurred in %@"));
39 if (errDesc != NULL) CFRelease(errDesc);
40 errDesc = CFStringCreateWithFormat(NULL, NULL, errDescFormat, context);
41 }
42
43 CFStringRef errStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%d)"), errDesc, (int)err);
44
45 if (errNum != NULL) CFRelease(errNum);
46 if (errDesc != NULL) CFRelease(errDesc);
47 return errStr;
48}
49
50CFStringRef ICCF_CopyAppName() {
51 ProcessSerialNumber psn = {0, kCurrentProcess};
52 CFStringRef appName = NULL;
53 CopyProcessName(&psn, &appName);
54 if (appName == NULL) return CFSTR("(unknown)");
55 return appName;
56}
57
58BOOL ICCF_EventIsCommandMouseDown(NSEvent *e) {
59 return ([e type] == NSLeftMouseDown && ([e modifierFlags] & NSCommandKeyMask) != 0 && [e clickCount] == 1);
60}
61
62iccfURLAction ICCF_KeyboardAction(NSEvent *e) {
63 unsigned int modifierFlags = [e modifierFlags];
64 iccfURLAction action;
65 action.presentMenu = (modifierFlags & NSAlternateKeyMask) != 0;
66 action.launchInBackground = (modifierFlags & NSShiftKeyMask) != 0;
67 return action;
68}
69
70void ICCF_CheckRange(NSRange range) {
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);
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 characterSetWithRange: NSMakeRange(0x21, 0x5e)] invertedSet]]; // nonprintable and non-ASCII characters
86 [set formUnionWithCharacterSet: [NSCharacterSet punctuationCharacterSet]];
87 [set removeCharactersInString: @";/?:@&=+$,-_.!~*'()%#"]; // RFC 2396 ¤2.2, 2.3, 2.4, plus % and # from "delims" set
88
89 tmpSet = [[set mutableCopy] autorelease];
90 [tmpSet formUnionWithCharacterSet: [NSCharacterSet characterSetWithCharactersInString: @"><("]];
91 urlLeftDelimiters = [tmpSet copy]; // make immutable again - for efficiency
92
93 tmpSet = [[set mutableCopy] autorelease];
94 [tmpSet formUnionWithCharacterSet: [NSCharacterSet characterSetWithCharactersInString: @"><)"]];
95 urlRightDelimiters = [tmpSet copy]; // make immutable again - for efficiency
96 }
97
98 *leftPtr = urlLeftDelimiters; *rightPtr = urlRightDelimiters;
99}
100
101static ICInstance ICCF_icInst = NULL;
102
103void ICCF_StartIC() {
104 OSStatus err;
105
106 if (ICCF_icInst != NULL) {
107 ICLog(@"ICCF_StartIC: Internet Config is already running!");
108 ICCF_StopIC();
109 }
110 err = ICStart(&ICCF_icInst, kICCFCreator);
111 NSCAssert1(err == noErr, ICCF_LocalizedString(@"Unable to start Internet Config (error %d)"), err);
112}
113
114void ICCF_StopIC() {
115 if (ICCF_icInst == NULL) {
116 ICLog(@"ICCF_StopIC: Internet Config is not running!");
117 } else {
118 ICStop(ICCF_icInst);
119 ICCF_icInst = NULL;
120 }
121}
122
123ICInstance ICCF_GetInst() {
124 NSCAssert(ICCF_icInst != NULL, @"Internal error: Called ICCF_GetInst without ICCF_StartIC");
125 return ICCF_icInst;
126}
127
128ConstStringPtr ICCF_GetHint(ICInstance inst, const char *urlData, Size length, long *selStart, long *selEnd, Boolean *needsSlashes) {
129 Handle h = NewHandle(0);
130 OSStatus err;
131
132 if (h == NULL) return NULL;
133
134 // parse the URL providing a bogus protocol, to get rid of escaped forms
135 err = ICParseURL(inst, "\p*", urlData, length, selStart, selEnd, h);
136 if (err != noErr) return NULL;
137
138 // scan through the parsed URL looking for characters not found in email addresses
139 Size hSize = GetHandleSize(h);
140 if (hSize == 0) return NULL;
141
142 const char *urlParsed = *h;
143 long i = 0;
144 Boolean sawAt = false;
145 if (hSize >= 2 && urlParsed[0] == '*' && urlParsed[1] == ':') {
146 // this is an IC-inserted protocol; skip over it
147 i = 2;
148 *needsSlashes = (hSize < i + 2 || urlParsed[i] != '/' || urlParsed[i + 1] != '/');
149 } else *needsSlashes = false;
150 for ( ; i < hSize ; i++) {
151 char c = urlParsed[i];
152 if (c == '@') {
153 sawAt = true;
154 } else if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
155 (c == '+' || c == '-' || c == '_' || c == '!' || c == '.'))) {
156 DisposeHandle(h);
157 return "\phttp";
158 }
159 }
160 DisposeHandle(h);
161 if (sawAt) {
162 *needsSlashes = false;
163 return "\pmailto";
164 }
165 return "\phttp";
166}
167
168static const char *kICSlashes = "//";
169
170void ICCF_AddSlashes(Handle h, ConstStringPtr hint) {
171 Size sizeBefore = GetHandleSize(h);
172 unsigned char hintLength = StrLength(hint);
173 char *copy = (char *)malloc(sizeBefore);
174 memcpy(copy, *h, sizeBefore);
175 ICLog(@"ICCF_AddSlashes before: |%s|\n", *h);
176 ReallocateHandle(h, sizeBefore + 2);
177
178 // if *h begins with '<hint>:', then copy the slashes after it
179 if (sizeBefore > hintLength + 1 && strncmp((const char *)&hint[1], copy, hintLength) == 0 && copy[hintLength] == ':') {
180 memcpy(*h, copy, hintLength + 1);
181 memcpy(*h + hintLength + 1, kICSlashes, 2);
182 memcpy(*h + hintLength + 3, &copy[hintLength + 1], sizeBefore - hintLength - 1);
183 } else {
184 memcpy(*h, kICSlashes, 2);
185 memcpy(*h + 2, copy, sizeBefore);
186 }
187
188 free(copy);
189 ICLog(@"ICCF_AddSlashes after: |%s|\n", *h);
190}
191
192// input/output 'range' is the range of source document which contains 'string'
193void ICCF_ParseURL(NSString *string, NSRange *range) {
194 OSStatus err;
195 Handle h;
196 long selStart = 0, selEnd = range->length; // local offsets within 'string'
197 char *urlData = NULL;
198
199 NSCAssert(selEnd == [string length], @"Internal error: URL string is wrong length");
200
201 NS_DURING
202 if ([[NSCharacterSet characterSetWithCharactersInString: @";,."] characterIsMember:
203 [string characterAtIndex: selEnd - 1]]) {
204 selEnd--;
205 }
206 NSCharacterSet *alphanumericCharacterSet = [NSCharacterSet alphanumericCharacterSet];
207 while (![alphanumericCharacterSet characterIsMember: [string characterAtIndex: selStart]]) {
208 selStart++;
209 NSCAssert(selStart < selEnd, @"No URL is selected");
210 }
211
212 string = [string substringWithRange: NSMakeRange(selStart, selEnd - selStart)];
213
214 ICLog(@"Parsing URL |%@|", string);
215
216 NSCAssert([string canBeConvertedToEncoding: NSASCIIStringEncoding], @"No URL is selected");
217
218 urlData = (char *)malloc( (range->length + 1) * sizeof(char));
219 NSCAssert(urlData != NULL, @"Internal error: can't allocate memory for URL string");
220
221 // XXX getCString: is deprecated in 10.4, but this is safe and shouldn't assert because we've already verified the string can be converted to ASCII, which should be a subset of any possible system encoding. The replacement (getCString:maxLength:encoding:) is not available until 10.4, so we leave this until we dump Internet Config and gain IDN friendliness.
222 [string getCString: urlData];
223
224 h = NewHandle(0);
225 NSCAssert(h != NULL, @"Internal error: can't allocate URL handle");
226
227 err = ICParseURL(ICCF_GetInst(), "\pmailto", urlData, range->length, &selStart, &selEnd, h);
228 DisposeHandle(h);
229
230 ICCF_OSErrCAssert(err, @"ICParseURL");
231
232 range->length = selEnd - selStart;
233 range->location += selStart;
234 NS_HANDLER
235 free(urlData);
236 [localException raise];
237 NS_ENDHANDLER
238
239 free(urlData);
240}
241
242BOOL ICCF_LaunchURL(NSString *string, iccfURLAction action) {
243 OSStatus err = noErr;
244 long selStart, selEnd;
245 string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
246 unsigned len = [string length];
247
248 Handle h = NULL;
249
250 NS_DURING
251 h = NewHandle(len);
252 if (h == NULL)
253 ICCF_OSErrCAssert(MemError(), @"NewHandle");
254
255 if (CFStringGetBytes((CFStringRef)string, CFRangeMake(0, len), kCFStringEncodingASCII, '\0', false, (UInt8 *)*h, len, NULL) != len)
256 ICCF_OSErrCAssert(kTECNoConversionPathErr, @"CFStringGetBytes");
257
258 selStart = 0; selEnd = len;
259
260 Boolean needsSlashes;
261 ConstStringPtr hint = ICCF_GetHint(ICCF_GetInst(), *h, len, &selStart, &selEnd, &needsSlashes);
262 NSCAssert(hint != NULL, @"Internal error: can't get protocol hint for URL");
263
264 if (needsSlashes) {
265 ICCF_AddSlashes(h, hint);
266 len = selEnd = GetHandleSize(h);
267 }
268
269 err = ICCF_DoURLAction(ICCF_GetInst(), hint, *h, selStart, selEnd, action);
270 ICCF_OSErrCAssert(err, @"ICCF_DoURLAction");
271
272 NS_HANDLER
273 DisposeHandle(h);
274 [localException raise];
275 NS_ENDHANDLER
276
277 DisposeHandle(h);
278
279 return (err == noErr);
280}
281
282// XXX not sure what to do if there's already a selection; BBEdit and MLTE extend it, Tex-Edit Plus doesn't.
283// RFC-ordained max URL length, just to avoid passing IC/LS multi-megabyte documents
284#if ICCF_DEBUG
285const long ICCF_MAX_URL_LEN = 60; // XXX change later
286#else
287const long ICCF_MAX_URL_LEN = 1024;
288#endif
289
290Boolean ICCF_enabled = true;
291
292BOOL ICCF_HandleException(NSException *e) {
293 if ([e reason] == nil || [[e reason] length] == 0)
294 return NO;
295
296 if (ICCF_prefs.errorSoundEnabled) NSBeep();
297 if (!ICCF_prefs.errorDialogEnabled) return YES;
298
299 int result = NSRunAlertPanel(ICCF_LocalizedString(@"AlertTitle"), ICCF_LocalizedString(@"AlertMessage%@"), nil, nil, ICCF_LocalizedString(@"AlertDisableButton"), e);
300 if (result != NSAlertDefaultReturn) {
301 result = NSRunAlertPanel(ICCF_LocalizedString(@"DisableAlertTitle"), ICCF_LocalizedString(@"DisableAlertMessage%@"), ICCF_LocalizedString(@"DisableAlertDisableButton"), ICCF_LocalizedString(@"DisableAlertDontDisableButton"), nil,
302 [(NSString *)ICCF_CopyAppName() autorelease]);
303 if (result == NSAlertDefaultReturn)
304 ICCF_enabled = NO;
305 }
306 return YES;
307}
308
309void ICCF_LaunchURLFromTextView(NSTextView *self, NSEvent *triggeringEvent) {
310 NSCharacterSet *urlLeftDelimiters = nil, *urlRightDelimiters = nil;
311 NSRange range = [self selectedRange], delimiterRange;
312 NSColor *insertionPointColor = [self insertionPointColor];
313 NSString *s = [[self textStorage] string]; // according to the class documentation, sending 'string' is guaranteed to be O(1)
314 unsigned extraLen;
315 int i;
316
317 NS_DURING
318
319 NSCAssert(range.location != NSNotFound, ICCF_LocalizedString(@"There is no insertion point or selection in the text field where you clicked"));
320 NSCAssert(s != nil, ICCF_LocalizedString(@"Sorry, ICeCoffEE is unable to locate the insertion point or selection"));
321
322 ICCF_StartIC();
323
324 NSCAssert([s length] != 0, ICCF_LocalizedString(@"No text was found"));
325
326 if (range.location == [s length]) range.location--; // work around bug in selectionRangeForProposedRange (r. 2845418)
327
328 range = [self selectionRangeForProposedRange: range granularity: NSSelectByWord];
329
330 // However, NSSelectByWord does not capture even the approximate boundaries of a URL
331 // (text to a space/line ending character); it'll stop at a period in the middle of a hostname.
332 // So, we expand it as follows:
333
334 ICCF_CheckRange(range);
335
336 ICCF_Delimiters(&urlLeftDelimiters, &urlRightDelimiters);
337
338 // XXX instead of 0, make this stop at the max URL length to prevent protracted searches
339 // add 1 to range to trap delimiters that are on the edge of the selection (i.e., <...)
340 delimiterRange = [s rangeOfCharacterFromSet: urlLeftDelimiters
341 options: NSLiteralSearch | NSBackwardsSearch
342 range: NSMakeRange(0, range.location + (range.location != [s length]))];
343 if (delimiterRange.location == NSNotFound) {
344 // extend to beginning of string
345 range.length += range.location;
346 range.location = 0;
347 } else {
348 NSCAssert(delimiterRange.length == 1, @"Internal error: delimiter matched range is not of length 1");
349 range.length += range.location - delimiterRange.location - 1;
350 range.location = delimiterRange.location + 1;
351 }
352
353 ICCF_CheckRange(range);
354
355 // XXX instead of length of string, make this stop at the max URL length to prevent protracted searches
356 // add 1 to range to trap delimiters that are on the edge of the selection (i.e., ...>)
357 extraLen = [s length] - range.location - range.length;
358 delimiterRange = [s rangeOfCharacterFromSet: urlRightDelimiters
359 options: NSLiteralSearch
360 range: NSMakeRange(range.location + range.length - (range.length != 0),
361 extraLen + (range.length != 0))];
362 if (delimiterRange.location == NSNotFound) {
363 // extend to end of string
364 range.length += extraLen;
365 } else {
366 NSCAssert(delimiterRange.length == 1, @"Internal error: delimiter matched range is not of length 1");
367 range.length += delimiterRange.location - range.location - range.length;
368 }
369
370 ICCF_CheckRange(range);
371
372 ICCF_ParseURL([s substringWithRange: range], &range);
373
374 [self setSelectedRange: range affinity: NSSelectionAffinityDownstream stillSelecting: NO];
375 [self display];
376
377 if (ICCF_LaunchURL([s substringWithRange: range], ICCF_KeyboardAction(triggeringEvent)) && ICCF_prefs.textBlinkEnabled) {
378 for (i = 0 ; i < ICCF_prefs.textBlinkCount ; i++) {
379 NSRange emptyRange = {range.location, 0};
380 [self setSelectedRange: emptyRange affinity: NSSelectionAffinityDownstream stillSelecting: YES];
381 [self display];
382 usleep(kICBlinkDelayUsecs);
383 [self setInsertionPointColor: [self backgroundColor]];
384 [self setSelectedRange: range affinity: NSSelectionAffinityDownstream stillSelecting: YES];
385 [self display];
386 usleep(kICBlinkDelayUsecs);
387 }
388 }
389
390 NS_HANDLER
391 ICCF_HandleException(localException);
392 NS_ENDHANDLER
393
394 ICCF_StopIC();
395 [self setInsertionPointColor: insertionPointColor];
396}
397
398NSString * const ICCF_SERVICES_ITEM = @"ICeCoffEE Services Item";
399
400NSMenuItem *ICCF_ServicesMenuItem() {
401 NSMenuItem *servicesItem;
402 NSString *servicesTitle = nil;
403 NSMenu *servicesMenu = [NSApp servicesMenu];
404
405 if (servicesMenu != nil) {
406 servicesTitle = [servicesMenu title];
407 if (servicesTitle == nil) {
408 ICLog(@"Can't get service menu title");
409 servicesTitle = @"Services";
410 }
411 } else {
412 servicesTitle = [[NSBundle bundleWithIdentifier: @"com.apple.AppKit"] localizedStringForKey: @"Services" value: nil table: @"ServicesMenu"];
413 if (servicesTitle == nil) {
414 ICLog(@"Can't get localized text for 'Services' in AppKit.framework");
415 servicesTitle = @"Services";
416 }
417 }
418 servicesMenu = [[NSMenu alloc] initWithTitle: servicesTitle];
419 servicesItem = [[NSMenuItem alloc] initWithTitle: servicesTitle action:nil keyEquivalent:@""];
420 ICCF_SetServicesMenu(servicesMenu);
421 [servicesItem setSubmenu: servicesMenu];
422 [servicesItem setRepresentedObject: ICCF_SERVICES_ITEM];
423 [servicesMenu release];
424 return [servicesItem autorelease];
425}
426
427static const unichar UNICHAR_BLACK_RIGHT_POINTING_SMALL_TRIANGLE = 0x25b8;
428
429// returns YES if menu contains useful items, NO otherwise
430BOOL ICCF_ConsolidateServicesMenu(NSMenu *menu, NSDictionary *serviceOptions) {
431 [menu update]; // doesn't propagate to submenus, so we need to do this first
432 NSEnumerator *enumerator = [[menu itemArray] objectEnumerator];
433 NSMenuItem *menuItem;
434 NSMenu *submenu;
435 NSDictionary *itemOptions = nil;
436 BOOL shouldKeepItem = NO, shouldKeepMenu = NO;
437
438 while ( (menuItem = [enumerator nextObject]) != nil) {
439 if (serviceOptions != nil)
440 itemOptions = [serviceOptions objectForKey: [menuItem title]];
441 if ([[itemOptions objectForKey: (NSString *)kICServiceHidden] boolValue]) {
442 shouldKeepItem = NO;
443 } else if ( (submenu = [menuItem submenu]) != nil) {
444 shouldKeepItem = ICCF_ConsolidateServicesMenu(submenu, [itemOptions objectForKey: (NSString *)kICServiceSubmenu]);
445 if (shouldKeepItem && [submenu numberOfItems] == 1) { // consolidate
446 NSMenuItem *serviceItem = [[submenu itemAtIndex: 0] retain];
447 [serviceItem setTitle:
448 [NSString stringWithFormat: @"%@ %@ %@", [menuItem title], [NSString stringWithCharacters: &UNICHAR_BLACK_RIGHT_POINTING_SMALL_TRIANGLE length: 1], [serviceItem title]]];
449
450 int serviceIndex = [menu indexOfItem: menuItem];
451 [submenu removeItemAtIndex: 0]; // can't have item in two menus
452 [menu removeItemAtIndex: serviceIndex];
453 [menu insertItem: serviceItem atIndex: serviceIndex];
454 [serviceItem release];
455 }
456 } else {
457 [menuItem setKeyEquivalent: @""];
458 shouldKeepItem = [menuItem isEnabled];
459 }
460 if (shouldKeepItem) {
461 shouldKeepMenu = YES;
462 } else {
463 [menu removeItem: menuItem];
464 }
465 }
466
467 return shouldKeepMenu;
468}
469
470NSMenuItem *ICCF_ContextualServicesMenuItem() {
471 NSMenuItem *servicesItem = ICCF_ServicesMenuItem();
472 if (ICCF_ConsolidateServicesMenu([servicesItem submenu], (NSDictionary *)ICCF_prefs.serviceOptions))
473 return servicesItem;
474 else
475 return nil;
476}
477
478void ICCF_AddRemoveServicesMenu() {
479 // needed because:
480 // (a) we get called before the runloop has properly started and will crash if we don't delay on app startup
481 // (b) the APE message handler calls us from another thread and nothing happens if we try to add a menu on it
482 [ICeCoffEE performSelectorOnMainThread: @selector(IC_addRemoveServicesMenu) withObject: nil waitUntilDone: NO];
483}
484
485NSMenu *ICCF_MenuForEvent(NSView *self, NSMenu *contextMenu, NSEvent *e) {
486 if (contextMenu != nil && [e type] == NSRightMouseDown || ([e type] == NSLeftMouseDown && [e modifierFlags] & NSControlKeyMask)) {
487 int servicesItemIndex = [contextMenu indexOfItemWithRepresentedObject: ICCF_SERVICES_ITEM];
488 // always regenerate: make sure menu reflects context
489 if (servicesItemIndex != -1) {
490 [contextMenu removeItemAtIndex: servicesItemIndex];
491 [contextMenu removeItemAtIndex: servicesItemIndex - 1];
492 }
493 if (ICCF_prefs.servicesInContextualMenu) {
494 NSMenuItem *contextualServicesItem = ICCF_ContextualServicesMenuItem();
495 if (contextualServicesItem != nil) {
496 [contextMenu addItem: [NSMenuItem separatorItem]];
497 [contextMenu addItem: contextualServicesItem];
498 }
499 }
500 }
501 return contextMenu;
502}
503
504static NSEvent *ICCF_MouseDownEventWithModifierFlags(NSEvent *e, BOOL inheritModifierFlags) {
505 return [NSEvent mouseEventWithType: NSLeftMouseDown
506 location: [e locationInWindow]
507 modifierFlags: (inheritModifierFlags ? [e modifierFlags] : 0)
508 timestamp: [e timestamp]
509 windowNumber: [e windowNumber]
510 context: [e context]
511 eventNumber: [e eventNumber]
512 clickCount: 1
513 pressure: 0];
514}
515
516
517@interface NSTextView (IC_NSSharing)
518// only in Mac OS X 10.4 and later
519- (NSArray *)selectedRanges;
520@end
521
522@implementation ICeCoffEE
523
524+ (void)IC_addRemoveServicesMenu;
525{
526 NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
527 static NSMenuItem *servicesItem = nil;
528
529 if (servicesItem == nil && ICCF_prefs.servicesInMenuBar) {
530 servicesItem = [ICCF_ServicesMenuItem() retain];
531
532 int insertLoc = [mainMenu indexOfItemWithSubmenu: [NSApp windowsMenu]];
533 if (insertLoc == -1)
534 insertLoc = [mainMenu numberOfItems];
535
536 [mainMenu insertItem: servicesItem atIndex: insertLoc];
537 } else if (servicesItem != nil && !ICCF_prefs.servicesInMenuBar) {
538 [mainMenu removeItem: servicesItem];
539 [servicesItem release];
540 servicesItem = nil;
541 }
542 if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_3) {
543 [[NSApp servicesMenu] update]; // enable keyboard equivalents in Mac OS X 10.3
544 }
545}
546
547// XXX localization?
548- (NSMenu *)menuForEvent:(NSEvent *)e;
549{
550 NSMenu *myMenu = [super menuForEvent: e];
551 return ICCF_MenuForEvent(self, myMenu, e);
552}
553
554- (void)mouseDown:(NSEvent *)e;
555{
556#if ICCF_DEBUG
557 static BOOL down = NO;
558 if (down) {
559 ICLog(@"recursive invocation!");
560 return;
561 }
562 down = YES;
563 ICLog(@"ICeCoffEE down: %@", e);
564#endif
565 if (ICCF_sharedTrigger != nil) {
566 ICLog(@"%@ cancelling", ICCF_sharedTrigger);
567 [ICCF_sharedTrigger cancel];
568 }
569 if (ICCF_enabled && ICCF_prefs.commandClickEnabled && ICCF_EventIsCommandMouseDown(e)) {
570 BOOL inheritModifierFlags;
571 if ([self respondsToSelector: @selector(selectedRanges)]) {
572 // Command-multiple-click or -drag for discontiguous selection, Mac OS X 10.4 or later
573 inheritModifierFlags = YES;
574 } else {
575 // don't want to trigger selection extension or anything else; pass through as a plain click
576 // (on Mac OS X 10.3, command does not modify behavior)
577 inheritModifierFlags = NO;
578 }
579 [super mouseDown: ICCF_MouseDownEventWithModifierFlags(e, inheritModifierFlags)];
580 // we don't actually get a mouseUp event, just wait for mouseDown to return
581 NSEvent *upEvent = [[self window] currentEvent];
582 NSPoint downPt = [e locationInWindow];
583 NSPoint upPt = [upEvent locationInWindow];
584 ICLog(@"next: %@", upEvent);
585 NSAssert([upEvent type] == NSLeftMouseUp, @"NSTextView mouseDown: did not return with current event as mouse up!");
586 if (abs(downPt.x - upPt.x) <= kICHysteresisPixels && abs(downPt.y - upPt.y) <= kICHysteresisPixels) {
587 if (inheritModifierFlags) {
588 // Mac OS X 10.4 and later: make sure we don't have a command-double-click
589 [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
590 ICLog(@"%@ set", ICCF_sharedTrigger);
591 } else {
592 // Mac OS X 10.3
593 ICCF_LaunchURLFromTextView(self, e);
594 }
595 }
596 } else {
597 [super mouseDown: e];
598 }
599#if ICCF_DEBUG
600 down = NO;
601#endif
602}
603
604@end
Note: See TracBrowser for help on using the repository browser.