source: trunk/ICeCoffEE/ICeCoffEE/ICeCoffEEParser.m @ 436

Last change on this file since 436 was 436, checked in by Nicholas Riley, 12 years ago

Use @try/@catch/@finally rather than macro-based exceptions

File size: 10.1 KB
Line 
1//
2//  ICeCoffEEParser.m
3//  ICeCoffEE
4//
5//  Created by Nicholas Riley on 6/21/07.
6//  Copyright 2007 Nicholas Riley. All rights reserved.
7//
8
9#import "ICeCoffEEParser.h"
10#import "ICeCoffEE.h"
11
12void ICCF_Delimiters(NSCharacterSet **leftPtr, NSCharacterSet **rightPtr) {
13    static NSCharacterSet *urlLeftDelimiters = nil, *urlRightDelimiters = nil;
14   
15    if (urlLeftDelimiters == nil || urlRightDelimiters == nil) {
16        NSMutableCharacterSet *set = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];
17        NSMutableCharacterSet *tmpSet;
18        [urlLeftDelimiters release];
19        [urlRightDelimiters release];
20       
21        [set autorelease];
22        [set formUnionWithCharacterSet: [[NSCharacterSet characterSetWithRange: NSMakeRange(0x21, 0x5e)] invertedSet]]; // nonprintable and non-ASCII characters
23        [set formUnionWithCharacterSet: [NSCharacterSet punctuationCharacterSet]];
24        // XXX obsoleted by RFC 3986 now... use §2.1, 2.2, 2.3
25        [set removeCharactersInString: @";/?:@&=+$,-_.!~*'(){}[]%#"]; // RFC 2396 §2.2, 2.3, 2.4, plus % and # from "delims" set and {}, []
26       
27        tmpSet = [[set mutableCopy] autorelease];
28        [tmpSet formUnionWithCharacterSet: [NSCharacterSet characterSetWithCharactersInString: @"<(["]];
29        urlLeftDelimiters = [tmpSet copy]; // make immutable again - for efficiency
30       
31        tmpSet = [[set mutableCopy] autorelease];
32        [tmpSet formUnionWithCharacterSet: [NSCharacterSet characterSetWithCharactersInString: @">)]"]];
33        urlRightDelimiters = [tmpSet copy]; // make immutable again - for efficiency
34    }
35   
36    *leftPtr = urlLeftDelimiters; *rightPtr = urlRightDelimiters;
37}
38
39static ICInstance ICCF_icInst = NULL;
40
41void ICCF_StartIC() {
42    OSStatus err;
43   
44    if (ICCF_icInst != NULL) {
45        ICLog(@"ICCF_StartIC: Internet Config is already running!");
46        ICCF_StopIC();
47    }
48    err = ICStart(&ICCF_icInst, kICCFCreator);
49    NSCAssert1(err == noErr, ICCF_LocalizedString(@"Unable to start Internet Config (error %d)"), err);
50}
51
52void ICCF_StopIC() {
53    if (ICCF_icInst == NULL) {
54        ICLog(@"ICCF_StopIC: Internet Config is not running!");
55    } else {
56        ICStop(ICCF_icInst);
57        ICCF_icInst = NULL;
58    }
59}
60
61ICInstance ICCF_GetInst() {
62    NSCAssert(ICCF_icInst != NULL, @"Internal error: Called ICCF_GetInst without ICCF_StartIC");
63    return ICCF_icInst;
64}
65
66// input/output 'range' is the range of source document which contains 'string'
67void ICCF_ParseURL(NSString *string, NSRange *range) {
68    OSStatus err;
69    Handle h;
70    long selStart = 0, selEnd = range->length; // local offsets within 'string'
71    char *urlData = NULL;
72   
73    NSCAssert(selEnd == [string length], @"Internal error: URL string is wrong length");
74   
75    @try {
76        if ([[NSCharacterSet characterSetWithCharactersInString: @";,."] characterIsMember:
77            [string characterAtIndex: selEnd - 1]]) {
78            selEnd--;
79        }
80        NSCharacterSet *alphanumericCharacterSet = [NSCharacterSet alphanumericCharacterSet];
81        while (![alphanumericCharacterSet characterIsMember: [string characterAtIndex: selStart]]) {
82            selStart++;
83            NSCAssert(selStart < selEnd, @"No URL is selected");
84        }
85       
86        string = [string substringWithRange: NSMakeRange(selStart, selEnd - selStart)];
87       
88        ICLog(@"Parsing URL |%@|", string);
89       
90        NSCAssert([string canBeConvertedToEncoding: NSASCIIStringEncoding], @"No URL is selected");
91       
92        urlData = (char *)malloc( (range->length + 1) * sizeof(char));
93        NSCAssert(urlData != NULL, @"Internal error: can't allocate memory for URL string");
94       
95        // 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.
96        [string getCString: urlData];
97       
98        h = NewHandle(0);
99        NSCAssert(h != NULL, @"Internal error: can't allocate URL handle");
100       
101        err = ICParseURL(ICCF_GetInst(), "\pmailto", urlData, range->length, &selStart, &selEnd, h);
102        DisposeHandle(h);
103       
104        ICCF_OSErrCAssert(err, @"ICParseURL");
105       
106        range->length = selEnd - selStart;
107        range->location += selStart;
108    } @finally {
109        free(urlData);
110    }
111}
112
113static BOOL ICCF_StringIncludesCharacter(NSString *s, unichar character, NSRange range) {
114    NSRange result = [s rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString:
115                                         [NSString stringWithCharacters: &character length: 1]]
116                                        options: NSLiteralSearch range: range];
117    return (result.location != NSNotFound);
118}
119
120static BOOL ICCF_IsLikelyURI(NSString *s, NSRange range) {
121    return ([s rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @":/.@"]
122                               options: NSLiteralSearch range: range].location != NSNotFound);
123}
124
125static BOOL ICCF_IsLikelyIPv6Address(NSString *s, NSRange range) {
126    return ([s rangeOfCharacterFromSet:
127             [[NSCharacterSet characterSetWithCharactersInString: @"ABCDEFabcdef0123456789:"] invertedSet]
128                               options: NSLiteralSearch range: range].location == NSNotFound);
129}
130
131NSRange ICCF_URLEnclosingRange(NSString *s, NSRange range) {
132    NSCharacterSet *urlLeftDelimiters = nil, *urlRightDelimiters = nil;
133    NSRange delimiterRange;
134    unsigned extraLen;
135    BOOL multiLine = NO;
136   
137    ICCF_CheckRange(range);
138   
139    ICCF_Delimiters(&urlLeftDelimiters, &urlRightDelimiters);
140   
141    // right delimiter selected?  Yes, this can break with ...)URL(....  Oh well.
142    if (range.location > 0 && [urlRightDelimiters characterIsMember: [s characterAtIndex: range.location]]) {
143        --range.location;
144        ++range.length;
145        ICLog(@"expanding past initial %c, now |%@|", [s characterAtIndex: range.location + 1],
146              [s substringWithRange: range]);
147    }
148       
149expandFront:
150    // XXX instead of 0, make this stop at the max URL length to prevent protracted searches
151    // XXX backport to ICeCoffEETerminal
152    // add 1 to range to trap delimiters that are on the edge of the selection (i.e., <...)
153    delimiterRange = [s rangeOfCharacterFromSet: urlLeftDelimiters
154                                        options: NSLiteralSearch | NSBackwardsSearch
155                                          range: NSMakeRange(0, range.location + (range.location != [s length]))];
156    if (delimiterRange.location == NSNotFound) {
157        // extend to beginning of string
158        range.length += range.location;
159        range.location = 0;
160    } else {
161        NSCAssert(delimiterRange.length == 1, @"Internal error: delimiter matched range is not of length 1");
162        if ([s characterAtIndex: delimiterRange.location] == '<') { // XXX move to expandBoth to handle clicking in middle
163            multiLine = YES;
164            urlRightDelimiters = [NSCharacterSet characterSetWithCharactersInString: @">"];
165        }
166        range.length += range.location - delimiterRange.location - 1;
167        range.location = delimiterRange.location + 1;
168    }
169   
170
171expandBack:
172    // XXX instead of length of string, make this stop at the max URL length to prevent protracted searches
173    // add 1 to range to trap delimiters that are on the edge of the selection (i.e., ...>)
174    extraLen = [s length] - range.location - range.length;
175    delimiterRange = [s rangeOfCharacterFromSet: urlRightDelimiters
176                                        options: NSLiteralSearch
177                                          range: NSMakeRange(range.location + range.length - (range.length != 0),
178                                                             extraLen + (range.length != 0))];
179    if (delimiterRange.location == NSNotFound) {
180        // extend to end of string
181        range.length += extraLen;
182        extraLen = 0;
183    } else {
184        NSCAssert(delimiterRange.length == 1, @"Internal error: delimiter matched range is not of length 1");
185        range.length += delimiterRange.location - range.location - range.length;
186        extraLen = [s length] - NSMaxRange(range);
187
188        unichar opening, closing = [s characterAtIndex: delimiterRange.location];
189        if (closing == '>' && !multiLine && ICCF_StringIncludesCharacter(s, '<', NSMakeRange(0, range.location))) {
190            urlLeftDelimiters = [NSCharacterSet characterSetWithCharactersInString: @"<"];
191            goto expandFront; // XXX move to expandBoth to handle clicking in middle
192        }
193        // grow URL past closing paren/brace/bracket if we've seen an open paren/brace/bracket
194        if (closing == ')') opening = '(';
195        else if (closing == '}') opening = '{';
196        else if (closing == ']') opening = '[';
197        else goto expandBoth;
198        if (!ICCF_StringIncludesCharacter(s, opening, range))
199            goto expandBoth;
200       
201        if (extraLen == 1) {
202            range.length += 1;
203            --extraLen;
204            ICLog(@"expanding past %c, now |%@|", closing, [s substringWithRange: range]);
205        } else {
206            range.length += 2;
207            ICLog(@"expanding past %c, now |%@|", closing, [s substringWithRange: range]);
208            goto expandBack;
209        }
210    }
211   
212expandBoth:
213    if (range.location <= 1)
214        goto checkRange; // nowhere to expand
215    unichar opening = [s characterAtIndex: range.location - 1], closing;
216    if (opening == '(') closing = ')';
217    else if (opening == '{') closing = '}';
218    else if (opening == '[') closing = ']';
219    else goto checkRange;
220
221    ICLog(@"extraLen = %d", extraLen);
222    // check if we're inside a partial delimited URL: not foolproof, but handles (foo), {UUID} and [IPv6]
223    if (delimiterRange.location != NSNotFound && [s characterAtIndex: delimiterRange.location] == closing &&
224        ((opening == '[' && ICCF_IsLikelyIPv6Address(s, range)) || !ICCF_IsLikelyURI(s, range))) {
225        ICLog(@"expanding past %c...%c, was |%@|", opening, closing, [s substringWithRange: range]);
226        range.location -= 2;
227        if (extraLen > 1)
228            range.length += 4;
229        else
230            range.length += 2 + extraLen;
231        ICLog(@"expanding past %c...%c, now |%@|", opening, closing, [s substringWithRange: range]);
232        goto expandFront;
233    }
234
235    if (ICCF_StringIncludesCharacter(s, closing, range) &&
236        ((opening == '[' &&
237          ICCF_IsLikelyIPv6Address(s, NSMakeRange(range.location,
238                                                  [s rangeOfString: @"]"].location - range.location)))
239         || !ICCF_IsLikelyURI(s, range))) {
240        range.location -= 2;
241        range.length += 2;
242        ICLog(@"expanding past %c, now |%@|", opening, [s substringWithRange: range]);
243        goto expandFront;
244    }
245
246checkRange:
247    ICCF_CheckRange(range);
248   
249    ICCF_ParseURL([s substringWithRange: range], &range);
250   
251    return range;
252}
Note: See TracBrowser for help on using the repository browser.