File: KDTextView.m

package info (click to toggle)
biococoa 2.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,172 kB
  • sloc: objc: 21,348; makefile: 18; ansic: 4
file content (547 lines) | stat: -rw-r--r-- 16,951 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//
//  KDTextView.m
//  LineNumbering
//
//  Created by Koen van der Drift on Sat May 01 2004.
//  Pimped by Alexander Griekspoor on Sat Mar 04 2006
//  Copyright (c) 2003-2009 The BioCocoa Project.
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions
//  are met:
//  1. Redistributions of source code must retain the above copyright
//  notice, this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright
//  notice, this list of conditions and the following disclaimer in the
//  documentation and/or other materials provided with the distribution.
//  3. The name of the author may not be used to endorse or promote products
//  derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
//  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
//  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
//  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

//  NSTextView subclass which adds:
//  - line numbering
//  - column spacing
//  - fancy overlays for mouse position and selections
//  - better information transmission on selections to the delegate

//  To be added in future versions:
//  - make columnwidth character based, instead of 90 points -> 10 chars
//  - calculate column width based on current font
//  - optimization by only redrawing dirty areas

#import "KDTextView.h"
#import "KDTextViewContainer.h"

// Available delegate methods
@protocol KDTextViewDelegate <NSObject>
- (void)copy:(id)sender;
- (void)didClickInTextView: (id)sender location: (NSPoint)thePoint character: (int)c;
- (void)didDragInTextView: (id)sender location: (NSPoint)thePoint character: (int)c;
- (void)didMoveInTextView: (id)sender location: (NSPoint)thePoint character: (int)c;
- (void)didDragSelectionInTextView: (id)sender range: (NSRange)aRange;
- (NSMenu *)menuForTextView: (id)sender;
@end

@implementation KDTextView

- (id)initWithCoder:(NSCoder *)aDecoder;
{
	if (self = [super initWithCoder:aDecoder])
	{
		[self initLineMargin: [self frame]];
		[self setUnit: @""];
	}
	
    return self;
}

-(id)initWithFrame:(NSRect)frame
{
    if (self = [super initWithFrame:frame])
    {
		[self initLineMargin: frame];
		[self setUnit: @""];
    }
	
    return self;
}

- (void) initLineMargin:(NSRect) frame
{
	NSSize				contentSize;
	KDTextViewContainer	*myContainer;
	
	// create a subclass of NSTextContainer that specifies the textdraw area. 
	// This will allow for a left margin for numbering.
	
	contentSize = [[self enclosingScrollView] contentSize];
	frame = NSMakeRect(0, 0, contentSize.width, contentSize.height);
	myContainer = [[KDTextViewContainer allocWithZone:[self zone]] 
			initWithContainerSize:NSMakeSize(frame.size.width, 100000)];
	
	[myContainer setWidthTracksTextView:YES];
	[myContainer setHeightTracksTextView:NO];
	
	// This controls the inset of our text away from the margin.
	[myContainer setLineFragmentPadding:7];
	
	[self replaceTextContainer:myContainer];
	[myContainer release];
	
	// set all the parameters for the text view - it's was created from scratch, so it doesn't use
	// the values from the Nib file.
	
	[self setMinSize:frame.size];
	[self setMaxSize:NSMakeSize(100000, 100000)];
	
	[self setHorizontallyResizable:NO];
	[self setVerticallyResizable:YES];
	
	[self setAutoresizingMask:NSViewWidthSizable];
	[self setAllowsUndo:YES];
	
	[self setFont:[NSFont fontWithName: @"Courier" size: 14]];
	
	// listen to updates from the window to force a redraw - eg when the window resizes.
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidUpdate:)
												 name:NSWindowDidUpdateNotification object:[self window]];
	
	marginAttributes = [[NSMutableDictionary alloc] init];
	
	[marginAttributes setObject:[NSFont boldSystemFontOfSize:8] forKey: NSFontAttributeName];
	[marginAttributes setObject:[NSColor darkGrayColor] forKey: NSForegroundColorAttributeName];
	
	selectionAttributes = [[NSMutableDictionary alloc] init];
	
	[selectionAttributes setObject:[NSFont boldSystemFontOfSize:9] forKey: NSFontAttributeName];
	[selectionAttributes setObject:[NSColor whiteColor] forKey: NSForegroundColorAttributeName];
	
	
	drawNumbersInMargin = YES;
	drawLineNumbers = NO;
	drawOverlay = YES;
}

- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [marginAttributes release];
	[selectionAttributes release];
	
	[unit release];
	
    [super dealloc];
}

- (BOOL)drawNumbersInMargin
{
	return drawNumbersInMargin;
}

- (void)setDrawNumbersInMargin:(BOOL)newDrawNumbersInMargin
{
	drawNumbersInMargin = newDrawNumbersInMargin;
}

- (BOOL)drawLineNumbers
{
	return drawLineNumbers;
}

- (void)setDrawLineNumbers:(BOOL)newDrawLineNumbers
{
	drawLineNumbers = newDrawLineNumbers;
}

- (BOOL)drawOverlay
{
	return drawOverlay;
}

- (void)setDrawOverlay:(BOOL)newDrawOverlay
{
	drawOverlay = newDrawOverlay;
}

// displayed in the selection marker, e.g. set to bp for DNA and aa for amino acids
// format: 187-195 (8 $UNIT)

- (NSString *)unit
{
	return unit;
}

- (void)setUnit:(NSString *)newUnit
{
	[newUnit retain];
	[unit release];
	unit = newUnit;
}


- (void)drawRect:(NSRect)aRect 
{
    [super drawRect:aRect];
	
    [self drawEmptyMargin: [self marginRect]];
    
	// line numbers
    if ( drawNumbersInMargin )
    {
        [self drawNumbersInMargin: [self marginRect]];
    }
	
	// overlays, not when printed.
	if ( drawOverlay && [[NSGraphicsContext currentContext] isDrawingToScreen])
	{
		[self drawSelectionOverlayInTextview: aRect];
		[self drawOverlayInTextview: aRect];
	}
	
}


- (void)windowDidUpdate:(NSNotification *)notification
{
    [self updateMargin];
}

- (void)updateLayout
{
    [self updateMargin];
}


-(void)updateMargin
{
    [self setNeedsDisplayInRect:[self marginRect] avoidAdditionalLayout:NO];
}


-(NSRect)marginRect
{
    NSRect  r;
    
    r = [self bounds];
    r.size.width = kLEFT_MARGIN_WIDTH;
	
    return r;
}

-(void)drawEmptyMargin:(NSRect)aRect
{
	/*
     These values control the color of our margin. Giving the rect the 'clear' 
     background color is accomplished using the windowBackgroundColor.  Change 
     the color here to anything you like to alter margin contents.
	 */
	if([[NSGraphicsContext currentContext] isDrawingToScreen]){
		[[NSColor controlHighlightColor] set];
		[NSBezierPath fillRect: aRect]; 
	}	
	// These points should be set to the left margin width.
    NSPoint top = NSMakePoint(aRect.size.width, [self bounds].size.height);
    NSPoint bottom = NSMakePoint(aRect.size.width, 0);
    
	// This draws the dark line separating the margin from the text area.
    [[NSColor grayColor] set];
    [NSBezierPath setDefaultLineWidth:0.75];
    [NSBezierPath strokeLineFromPoint:top toPoint:bottom];
}


-(void) drawNumbersInMargin:(NSRect)aRect;
{
	UInt32		index, lineNumber;
	NSRange		lineRange;
	NSRect		lineRect;
	
	NSLayoutManager* layoutManager = [self layoutManager];
	NSTextContainer* textContainer = [self textContainer];
	
	// Only get the visible part of the scroller view
	NSRect documentVisibleRect = [[self enclosingScrollView] documentVisibleRect];
	
	// Find the glyph range for the visible glyphs
	NSRange glyphRange = [layoutManager glyphRangeForBoundingRect: documentVisibleRect inTextContainer: textContainer];
	
	// Calculate the start and end indexes for the glyphs	
	unsigned start_index = glyphRange.location;
	unsigned end_index = glyphRange.location + glyphRange.length;
	
	if(![[NSGraphicsContext currentContext] isDrawingToScreen]){
		start_index = 0;
		end_index = [layoutManager numberOfGlyphs];
	}
	
	index = 0;
	lineNumber = 1;
	
	if([[NSGraphicsContext currentContext] isDrawingToScreen]){
		
		// Skip all lines that are visible at the top of the text view (if any)
		while (index < start_index)
		{
			lineRect = [layoutManager lineFragmentRectForGlyphAtIndex:index effectiveRange:&lineRange];
			index = NSMaxRange( lineRange );
			++lineNumber;
		}
	}
	
	for ( index = start_index; index < end_index; lineNumber++ )
	{
		lineRect  = [layoutManager lineFragmentRectForGlyphAtIndex:index effectiveRange:&lineRange];
		//NSLog(@"Rect: %f, %f, %f, %f", lineRect.origin.x, lineRect.origin.y, lineRect.size.width, lineRect.size.height);
		if ( drawLineNumbers && lineRect.origin.x == 30)
		{
			index = NSMaxRange( lineRange );
			[self drawOneNumberInMargin:lineNumber inRect:lineRect];
		}
		else if ( lineRect.origin.x == 30)   // draw character numbers
		{
			[self drawOneNumberInMargin:index+1 inRect:lineRect];
		}
		
		index = NSMaxRange( lineRange );
	}
	
    if ( drawLineNumbers )
    {
        lineRect = [layoutManager extraLineFragmentRect];
        [self drawOneNumberInMargin:lineNumber inRect:lineRect];
    }
	
}


-(void)drawOneNumberInMargin:(unsigned) aNumber inRect:(NSRect)r
{
    NSString    *s;
    NSSize      stringSize;
    
    s = [NSString stringWithFormat:@"%d", aNumber, nil];
    stringSize = [s sizeWithAttributes:marginAttributes];
	
	// Simple algorithm to center the line number next to the glyph.
    [s drawAtPoint: NSMakePoint( r.origin.x - stringSize.width - 1, 
								 r.origin.y + ((r.size.height / 2) - (stringSize.height / 2))) 
	withAttributes:marginAttributes];
}

-(void)drawSelectionOverlayInTextview: (NSRect)rect{
	
	// don't draw when margin is drawn
	if(NSWidth(rect) == 30) return;
	
	NSRange range = [self selectedRange];
	
	NSString    *s;
    NSSize      stringSize;
	NSRect		stringRect;
	NSBezierPath *stringPath;
	
	NSPoint p;
	
	if(range.length > 0){
		// calculate rect of 1st char of selection
		NSRect r = [[self layoutManager] boundingRectForGlyphRange: NSMakeRange(range.location, 1) 
												   inTextContainer: [self textContainer]];
		p = (NSPoint){r.origin.x, NSMaxY(r)};	
		
		// generate string
		if(range.length == 1)
			s = [NSString stringWithFormat:@"%d", range.location+1];
		else 
			s = [NSString stringWithFormat:@"%d-%d (%d%@)", range.location+1, range.location+range.length, range.length, [self unit]];

		stringSize = [s sizeWithAttributes:selectionAttributes];
		
		// position with respect to character
		stringRect.origin.x = p.x + 5.0;
		stringRect.origin.y = p.y - stringSize.height - 16.0;
		
		// if doesn't fit (to close to top), move to last char of selection
		if(stringRect.origin.y - 15.0 < rect.origin.y){			
			NSRect r = [[self layoutManager] boundingRectForGlyphRange: NSMakeRange(range.location + range.length - 1, 1) 
													   inTextContainer: [self textContainer]];
			
			stringRect.origin.x = NSMaxX(r) - stringSize.width;
			stringRect.origin.y = NSMaxY(r) + 2.0;
		}
		
		// if doesn't fit (to close to right edge), reposition
		if((stringRect.origin.x + stringSize.width + 10.0) > rect.origin.x + NSWidth(rect)) 
			stringRect.origin.x -= (stringRect.origin.x + stringSize.width + 10.0) - (rect.origin.x + NSWidth(rect));
	
		// if doesn't fit (to close to left edge), reposition
		// NOTE: HARDCODED MARGIN WIDTH + 5 -> room for more elegant solution here
		if(stringRect.origin.x < 35.0) stringRect.origin.x = 35.0;
		
		// draw overlay + text
		stringRect.size = stringSize;	
		
		stringPath = [NSBezierPath bezierPath];
		[stringPath moveToPoint: (NSPoint) {stringRect.origin.x, stringRect.origin.y + 7.0}];
		[stringPath lineToPoint: (NSPoint) {stringRect.origin.x + stringRect.size.width, stringRect.origin.y + 7.0}];
		[stringPath setLineCapStyle: NSRoundLineCapStyle];
		[[NSColor colorWithCalibratedWhite: 0.0 alpha: 0.6]set];
		[stringPath setLineWidth: stringSize.height];
		[stringPath stroke];
		
		[s drawAtPoint: stringRect.origin withAttributes:selectionAttributes];
	}
}

-(void)drawOverlayInTextview: (NSRect)rect{
	
	// where are we?
	NSPoint cursor = [self convertPoint: [[self window] mouseLocationOutsideOfEventStream] fromView: nil];
	
	// not in margin, not outside ourselves
	if(cursor.x < 30.0) return;
	if(!NSPointInRect(cursor, rect)) return;
	
	NSTextStorage* textStorage = [self textStorage];
	NSRange selectedRange = [self selectedRange];
	
	NSString    *s;
    NSSize      stringSize;
	NSRect		stringRect;
	NSBezierPath *stringPath;
	
	// don't draw if active selection
	if(selectedRange.length > 0){
		return;
		
	// what's the char under our mouse
	} else {
		float partial = 1.0;
		int c = (int) [[self layoutManager] glyphIndexForPoint: cursor inTextContainer: [self textContainer] fractionOfDistanceThroughGlyph: &partial];
		if(c > 0 && c < [textStorage length] - 1)
			s = [NSString stringWithFormat:@"%d", c+1];
		else return;
	}
	
    stringSize = [s sizeWithAttributes:selectionAttributes];
	
	// position with respect to char
	stringRect.origin.x = cursor.x + 8.0;
	stringRect.origin.y = cursor.y + stringSize.height + 2.0;
	
	// if doesn't fit (to close to right edge), reposition
	if((stringRect.origin.x + stringSize.width + 10.0) > rect.origin.x + NSWidth(rect)) 
		stringRect.origin.x -= (stringRect.origin.x + stringSize.width + 10.0) - (rect.origin.x + NSWidth(rect));
	
	// if doesn't fit (to close to bottom edge), reposition
	if((stringRect.origin.y + stringSize.height + 10.0) > rect.origin.y + NSHeight(rect)) 
		stringRect.origin.y -= (stringRect.origin.y + stringSize.height + 10.0) - (rect.origin.y + NSHeight(rect));
	
	// draw overlay + text
	stringRect.size = stringSize;	
	
	stringPath = [NSBezierPath bezierPath];
	[stringPath moveToPoint: (NSPoint) {stringRect.origin.x, stringRect.origin.y + 7.0}];
	[stringPath lineToPoint: (NSPoint) {stringRect.origin.x + stringRect.size.width, stringRect.origin.y + 7.0}];
	[stringPath setLineCapStyle: NSRoundLineCapStyle];
	[[NSColor colorWithCalibratedWhite: 0.0 alpha: 0.6]set];
	[stringPath setLineWidth: stringSize.height];
	[stringPath stroke];
	
    [s drawAtPoint: stringRect.origin withAttributes:selectionAttributes];
	
}

// Allows customization of contextual menu by delegate
-(NSMenu*)menuForEvent:(NSEvent*) evt { 
	id <KDTextViewDelegate> delegate = [self delegate];
    if ([delegate respondsToSelector:@selector(menuForTextView:)]) 
		return [delegate menuForTextView: self];
	return nil;
}

// Mouse methods that inform delegate
- (void)mouseDown:(NSEvent *)theEvent{
	id <KDTextViewDelegate> delegate = [self delegate];
	float partial = 0.5;
	NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
	
    if ([delegate respondsToSelector:@selector(didClickInTextView: location: character:)]){
		int c = (int) [[self layoutManager] glyphIndexForPoint: p inTextContainer: [self textContainer] fractionOfDistanceThroughGlyph: &partial];
        [delegate didClickInTextView: self location: p character: c];
	}
	
	// redraw to sync overlays
	[self setNeedsDisplay: YES];
	
	[super mouseDown: theEvent];

}  

- (void)mouseMoved:(NSEvent *)theEvent{
	float partial = 1.0;
	NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
	int c = (int) [[self layoutManager] glyphIndexForPoint: p inTextContainer: [self textContainer] fractionOfDistanceThroughGlyph: &partial];
	
	id <KDTextViewDelegate> delegate = [self delegate];
    if ([delegate respondsToSelector:@selector(didMoveInTextView: location: character:)]){
		
		[delegate didMoveInTextView: self location: p character: c];
	}
	
	// redraw to sync overlays
	[self setNeedsDisplay: YES];
	
	[super mouseMoved: theEvent];
	
}  

- (void)mouseEntered:(NSEvent *)theEvent{
	
	// redraw to sync overlays
	[self setNeedsDisplay: YES];
	
	[super mouseEntered: theEvent];
	
}  

- (void)mouseExited:(NSEvent *)theEvent{
	
	// redraw to sync overlays
	[self setNeedsDisplay: YES];
	
	[super mouseExited: theEvent];
	
}  

- (NSRange)selectionRangeForProposedRange:(NSRange)proposedCharRange granularity:(NSSelectionGranularity)granularity{
	// DRAGGING SELECTION, inform delegate
	id <KDTextViewDelegate> delegate = [self delegate];
    if ([delegate respondsToSelector:@selector(didDragSelectionInTextView:range:)]){
		
		[delegate didDragSelectionInTextView: self range: proposedCharRange];
	}
	
	// MAKE SURE THAT SELECTION IS REDRAWN DURING DRAG	
	[self setNeedsDisplay: YES];
	return [super selectionRangeForProposedRange:proposedCharRange granularity:granularity];
}

- (void)setSelectedRange:(NSRange)aRange{
	// MAKE SURE THAT SELECTION IS REDRAWN DURING DRAG	
	[self setNeedsDisplay: YES];
	[super setSelectedRange: aRange];
}

@end