3 * Copyright (c) 2007 - 2011, Blue Static <http://www.bluestatic.org>
5 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
6 * General Public License as published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public License along with this program; if not,
14 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
17 #import "BSSourceView.h"
19 #include "BSLineNumberRulerView.h"
21 @interface BSSourceView (Private)
23 - (void)errorHighlightingFile:(NSNotification*)notif;
24 - (void)setPlainTextStringFromFile:(NSString*)filePath;
25 - (void)computeLineIndex;
28 @implementation BSSourceView
30 @synthesize textView = textView_;
31 @synthesize scrollView = scrollView_;
32 @synthesize markers = markers_;
33 @synthesize markedLine;
38 * Initializes the source view with the path of a file
40 - (id)initWithFrame:(NSRect)frame
42 if (self = [super initWithFrame:frame])
45 [[NSNotificationCenter defaultCenter]
47 selector:@selector(errorHighlightingFile:)
48 name:NSFileHandleReadToEndOfFileCompletionNotification
62 [scrollView_ removeFromSuperview];
63 [textView_ removeFromSuperview];
69 * Sets the file name as well as the text of the source view
71 - (void)setFile:(NSString*)f
79 if (![[NSFileManager defaultManager] fileExistsAtPath:f])
81 [textView_ setString:@""];
87 // Attempt to use the PHP CLI to highlight the source file as HTML
88 NSPipe* outPipe = [NSPipe pipe];
89 NSPipe* errPipe = [NSPipe pipe];
90 NSTask* task = [[NSTask new] autorelease];
92 [task setLaunchPath:@"/usr/bin/php"]; // This is the path to the default Leopard PHP executable
93 [task setArguments:[NSArray arrayWithObjects:@"-s", f, nil]];
94 [task setStandardOutput:outPipe];
95 [task setStandardError:errPipe];
98 [[errPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
100 NSData* data = [[outPipe fileHandleForReading] readDataToEndOfFile];
101 NSAttributedString* source = [[NSAttributedString alloc] initWithHTML:data documentAttributes:NULL];
102 [[textView_ textStorage] setAttributedString:source];
105 @catch (NSException* exception)
107 // If the PHP executable is not available then the NSTask will throw an exception
108 [self setPlainTextStringFromFile:f];
111 [self computeLineIndex];
115 * Sets the contents of the SourceView via a string rather than loading from a path
117 - (void)setString:(NSString*)source asFile:(NSString*)path
119 // create the temp file
120 NSError* error = nil;
121 NSString* tmpPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"MacGDBpHighlighter"];
122 [source writeToFile:tmpPath atomically:NO encoding:NSUTF8StringEncoding error:&error];
125 [textView_ setString:source];
129 // highlight the temporary file
130 [self setFile:tmpPath];
132 // delete the temp file
133 [[NSFileManager defaultManager] removeItemAtPath:tmpPath error:NULL];
135 // plop in our fake path so nobody knows the difference
142 [self computeLineIndex];
146 * If an error occurs in reading the highlighted PHP source, this will merely set the string
148 - (void)errorHighlightingFile:(NSNotification*)notif
150 NSData* data = [[notif userInfo] objectForKey:NSFileHandleNotificationDataItem];
151 if ([data length] > 0) // there's something on stderr, so the PHP CLI failed
152 [self setPlainTextStringFromFile:file];
156 * Flip the coordinates
164 * Tells the text view to scroll to a certain line
166 - (void)scrollToLine:(int)line
168 if ([[textView_ textStorage] length] == 0)
171 // go through the document until we find the NSRange for the line we want
173 for (int i = 0; i < line; i++)
175 rangeIndex = NSMaxRange([[textView_ string] lineRangeForRange:NSMakeRange(rangeIndex, 0)]);
178 // now get the true start/end markers for it
179 unsigned lineStart, lineEnd;
180 [[textView_ string] getLineStart:&lineStart end:NULL contentsEnd:&lineEnd forRange:NSMakeRange(rangeIndex - 1, 0)];
181 [textView_ scrollRangeToVisible:[[textView_ string] lineRangeForRange:NSMakeRange(lineStart, lineEnd - lineStart)]];
185 * Setup all the subviews for the source metaview
189 // Create the scroll view.
190 scrollView_ = [[[NSScrollView alloc] initWithFrame:[self bounds]] autorelease];
191 [scrollView_ setHasHorizontalScroller:YES];
192 [scrollView_ setHasVerticalScroller:YES];
193 [scrollView_ setAutohidesScrollers:YES];
194 [scrollView_ setBorderType:NSBezelBorder];
195 [scrollView_ setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
196 [[scrollView_ contentView] setAutoresizesSubviews:YES];
197 [self addSubview:scrollView_];
200 BSLineNumberRulerView* lineNumberView =
201 [[[BSLineNumberRulerView alloc] initWithScrollView:scrollView_] autorelease];
202 [scrollView_ setVerticalRulerView:lineNumberView];
203 [scrollView_ setHasHorizontalRuler:NO];
204 [scrollView_ setHasVerticalRuler:YES];
205 [scrollView_ setRulersVisible:YES];
207 // add the text view to the scroll view
209 textFrame.origin = NSMakePoint(0.0, 0.0);
210 textFrame.size = [scrollView_ contentSize];
211 textView_ = [[[NSTextView alloc] initWithFrame:textFrame] autorelease];
212 [textView_ setEditable:NO];
213 [textView_ setFont:[NSFont fontWithName:@"Monaco" size:10.0]];
214 [textView_ setHorizontallyResizable:YES];
215 [textView_ setVerticallyResizable:YES];
216 [textView_ setMinSize:textFrame.size];
217 [textView_ setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
218 [[textView_ textContainer] setContainerSize:NSMakeSize(FLT_MAX, FLT_MAX)];
219 [[textView_ textContainer] setWidthTracksTextView:NO];
220 [[textView_ textContainer] setHeightTracksTextView:NO];
221 [textView_ setAutoresizingMask:NSViewNotSizable];
222 [scrollView_ setDocumentView:textView_];
224 NSArray* types = [NSArray arrayWithObject:NSFilenamesPboardType];
225 [self registerForDraggedTypes:types];
229 * Gets the plain-text representation of the file at |filePath| and sets the
230 * contents in the source view.
232 - (void)setPlainTextStringFromFile:(NSString*)filePath
235 NSString* contents = [NSString stringWithContentsOfFile:filePath
236 encoding:NSUTF8StringEncoding
239 NSLog(@"Error reading file at %@: %@", filePath, error);
242 [textView_ setString:contents];
246 * Iterates over the text storage system and computes a map of line numbers to
247 * first character index for a line's frame rectangle.
249 - (void)computeLineIndex
253 NSString* text = [textView_ string];
254 NSUInteger stringLength = [text length];
255 NSUInteger index = 0;
257 while (index < stringLength) {
258 lineIndex_.push_back(index);
259 index = NSMaxRange([text lineRangeForRange:NSMakeRange(index, 0)]);
262 NSUInteger lineEnd, contentEnd;
263 [text getLineStart:NULL
265 contentsEnd:&contentEnd
266 forRange:NSMakeRange(lineIndex_.back(), 0)];
267 if (contentEnd < lineEnd)
268 lineIndex_.push_back(index);
270 NSLog(@"line count = %d", lineIndex_.size());
273 // Drag Handlers ///////////////////////////////////////////////////////////////
276 * Validates an initiated drag operation.
278 - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender
280 if ([delegate respondsToSelector:@selector(sourceView:acceptsDropOfFile:)])
281 return NSDragOperationCopy;
282 return NSDragOperationNone;
286 * Performs a dragging operation of files to set the contents of the file.
288 - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender
290 NSPasteboard* pboard = [sender draggingPasteboard];
291 if ([[pboard types] containsObject:NSFilenamesPboardType]) {
292 NSArray* files = [pboard propertyListForType:NSFilenamesPboardType];
294 NSString* filename = [files objectAtIndex:0];
295 if ([delegate respondsToSelector:@selector(sourceView:acceptsDropOfFile:)] &&
296 [delegate sourceView:self acceptsDropOfFile:filename]) {
297 [self setFile:filename];