File: GSSimpleLayoutManager.m

package info (click to toggle)
gnustep-gui 0.7.6-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 16,464 kB
  • ctags: 7,163
  • sloc: objc: 84,669; ansic: 14,192; yacc: 290; makefile: 196; cpp: 87; sh: 21
file content (1235 lines) | stat: -rw-r--r-- 33,499 bytes parent folder | download
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
/*
   GSSimpleLayoutManager.m

   First GNUstep layout manager, extracted from NSText

   Copyright (C) 2000 Free Software Foundation, Inc.

   Author:  Scott Christley <scottc@net-community.com>
   Date: 1996
   Author:  Felipe A. Rodriguez <far@ix.netcom.com>
   Date: July 1998
   Author:  Daniel Bhringer <boehring@biomed.ruhr-uni-bochum.de>
   Date: August 1998
   Author: Fred Kiefer <FredKiefer@gmx.de>
   Date: September 2000
   Extracted from NSText, reorganised to specification

   This file is part of the GNUstep GUI Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; see the file COPYING.LIB.
   If not, write to the Free Software Foundation,
   59 Temple Place - Suite 330, Boston, MA 02111 - 1307, USA.
*/

#include <Foundation/NSRange.h>
#include <Foundation/NSGeometry.h>
#include <Foundation/NSArray.h>
#include <Foundation/NSString.h>
#include <Foundation/NSScanner.h>
#include <Foundation/NSCharacterSet.h>

#include <AppKit/NSGraphics.h>
#include <AppKit/NSColor.h>
#include <AppKit/NSText.h>
#include <AppKit/NSTextView.h>
#include <AppKit/NSTextStorage.h>
#include <AppKit/NSTextContainer.h>
#include <AppKit/NSStringDrawing.h>

#include "GSSimpleLayoutManager.h"

#define HUGE 1e7

static NSCharacterSet *newlines;
static NSCharacterSet *selectionWordGranularitySet;
static NSCharacterSet *invSelectionWordGranularitySet;

@interface _GNULineLayoutInfo: NSObject
{
@public
  NSRange	glyphRange;
  NSRect	lineFragmentRect;
  NSRect	usedRect;
}


+ (id) lineLayoutWithRange: (NSRange)aRange
		      rect: (NSRect)aRect
		  usedRect: (NSRect)charRect;


- (NSRange) glyphRange;
- (NSRect) lineFragmentRect;

- (NSString*) description;
@end

@implementation _GNULineLayoutInfo

+ (_GNULineLayoutInfo *) lineLayoutWithRange: (NSRange)aRange
					rect: (NSRect)aRect
				    usedRect: (NSRect)charRect
{
  _GNULineLayoutInfo *ret = AUTORELEASE([_GNULineLayoutInfo new]);

  ret->glyphRange = aRange;
  ret->lineFragmentRect = aRect;
  ret->usedRect = charRect;
  return ret;
}

- (NSRange) glyphRange
{
  return glyphRange;
}

- (NSRect) lineFragmentRect
{
  return lineFragmentRect;
}

- (NSString*) description
{
  return [NSString stringWithFormat: @"_GNULineLayoutInfo with glyphRange: %@, lineFragmentRect: %@, usedRect: %@",
		   NSStringFromRange (glyphRange), 		   
		   NSStringFromRect (lineFragmentRect),
		   NSStringFromRect (usedRect)];
}

@end
// end: _GNULineLayoutInfo------------------------------------------------------


@interface GSSimpleLayoutManager (Private)

- (NSRect) rectForCharacterIndex: (unsigned) index;
- (NSRange) lineRangeForRect: (NSRect) aRect;
- (NSSize) _sizeOfRange: (NSRange) range;

// return value is identical to the real line number
- (int) lineLayoutIndexForGlyphIndex: (unsigned) anIndex;
// returns the full glyph range for a line range
- (NSRange) glyphRangeForLineLayoutRange: (NSRange) aRange;
- (unsigned) lineLayoutIndexForPoint: (NSPoint)point;

- (void) setNeedsDisplayForLineRange: (NSRange) redrawLineRange
		     inTextContainer:(NSTextContainer *)aTextContainer;
// override for special layout of text
- (NSRange) rebuildForRange: (NSRange)aRange
		  delta: (int)insertionDelta
	    inTextContainer:(NSTextContainer *)aTextContainer;
// low level, override but never invoke (use setNeedsDisplayForLineRange:)
- (void) drawLinesInLineRange: (NSRange)aRange;
- (void) drawSelectionAsRangeNoCaret: (NSRange)aRange;
@end

@implementation GSSimpleLayoutManager

+ (void) initialize
{
  if (self == [GSSimpleLayoutManager class])
    {
      NSMutableCharacterSet	*ms;
      
      ASSIGN (selectionWordGranularitySet, 
	      [NSCharacterSet whitespaceCharacterSet]);
      ASSIGN (invSelectionWordGranularitySet, 
	      [selectionWordGranularitySet invertedSet]);
      
      ms = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];
      [ms formIntersectionWithCharacterSet: invSelectionWordGranularitySet];
      newlines = [ms copy];
      RELEASE(ms);
    }
}

- (id) init
{
  self = [super init];

  _lineLayoutInformation = [[NSMutableArray alloc] init];
  return self;
}

- (void) dealloc
{
  RELEASE(_lineLayoutInformation);

  [super dealloc];
}

- (void) setTextStorage: (NSTextStorage*)aTextStorage
{
  [_lineLayoutInformation removeAllObjects];

  [super setTextStorage: aTextStorage];
}

// Returns the currently used bounds for all the text
- (NSRect)usedRectForTextContainer:(NSTextContainer *)aTextContainer
{
  if ([_lineLayoutInformation count])
    {
      NSEnumerator *lineEnum;
      _GNULineLayoutInfo *currentInfo;
      NSRect retRect = NSMakeRect (0, 0, 0, 0);

      for ((lineEnum = [_lineLayoutInformation objectEnumerator]);
	   (currentInfo = [lineEnum nextObject]);)
	{
	  retRect = NSUnionRect (retRect, currentInfo->usedRect);
	}
      return retRect;
    }
  else
    return NSZeroRect;
}

- (unsigned) glyphIndexForPoint: (NSPoint)point
		inTextContainer: (NSTextContainer*)aTextContainer
 fractionOfDistanceThroughGlyph: (float*)partialFraction
{
  _GNULineLayoutInfo *currentInfo = [_lineLayoutInformation 
				      objectAtIndex: 
					[self lineLayoutIndexForPoint: point]];
  NSRect rect = currentInfo->usedRect;
  NSRange range = currentInfo->glyphRange;
  int i;
  int min = range.location;
  int max = NSMaxRange(range);
  float x = point.x;
  float fmin = rect.origin.x;
  float fmax = NSMaxX(rect);
  float w1, w2;

  if (partialFraction != NULL)
    {
      *partialFraction = 0.0;
    }
  if (x <= fmin)
    {
      return MAX(0, min - 1);
    }
  if (x >= fmax)
    {
      return MAX(0, max);
    }
  if (range.length == 1)
    {
      return min;
    }

  // this should give a good starting index for binary search
  i = (int)((max - min) * (x - fmin) / (fmax - fmin)) + min;
  while (min < max)
    {
      w1 = [self _sizeOfRange:
		  NSMakeRange (range.location,
			       i - range.location)].width + fmin;
      if (i > range.location)
	w2 = [self _sizeOfRange:
		     NSMakeRange (range.location,
				  i-1 - range.location)].width + fmin;
      else
	w2 = fmin;

      if (w1 < x)
	{
	  min = i + 1;
	  i = (max + min) / 2;
	  continue;
	}
      if (w2 > x)
	{
	  max = i - 1;
	  i = (max + min) / 2;
	  continue;
	}
      if (w1 > x)
	{
	  if (partialFraction != NULL)
	    {
	      *partialFraction = 1.0 - (w1 - x)/(w1 - w2); 
	    }
	}
      return MAX(0, i-1);
    }
  return MAX(0, min - 1);
}

- (NSRect)lineFragmentRectForGlyphAtIndex: (unsigned)index 
			   effectiveRange: (NSRange *)lineFragmentRange
{
  _GNULineLayoutInfo *currentInfo;
  
  if (![_textStorage length] || ![_lineLayoutInformation count])
    {
      return NSMakeRect(0, 0, 0, 12);
    }
  
  currentInfo = [_lineLayoutInformation 
		  objectAtIndex: [self lineLayoutIndexForGlyphIndex: 
					 index]];

  if (lineFragmentRange)
    {
      *lineFragmentRange = currentInfo->glyphRange;
    }

  return currentInfo->lineFragmentRect;
}

- (NSPoint)locationForGlyphAtIndex:(unsigned)index
{
  float x;
  unsigned start;
  _GNULineLayoutInfo *currentInfo;
  
  if (![_textStorage length] || ![_lineLayoutInformation count])
    {
      return NSMakePoint(0, 0);
    }
    
  currentInfo = [_lineLayoutInformation 
		    objectAtIndex: [self lineLayoutIndexForGlyphIndex: 
					     index]];
  if (index >= NSMaxRange (currentInfo->glyphRange))
    {
      return NSMakePoint (NSMaxX (currentInfo->usedRect), 0);
    }
  
  start = currentInfo->glyphRange.location;
  x = [self _sizeOfRange: (NSMakeRange (start, index - start))].width;

  /* NB: As per specs, we return the location relative to the glyph's
     line fragment rectangle */
  return NSMakePoint(x, 0);
}

- (NSRect)boundingRectForGlyphRange:(NSRange)aRange 
		    inTextContainer:(NSTextContainer *)aTextContainer;
{
  _GNULineLayoutInfo *currentInfo;
  unsigned i1, i2;
  NSRect rect1;

  if (![_textStorage length] || ![_lineLayoutInformation count])
    {
      return NSMakeRect(0, 0, 0, 12);
    }

  i1 = [self lineLayoutIndexForGlyphIndex: aRange.location];
  i2 = [self lineLayoutIndexForGlyphIndex: NSMaxRange(aRange)];

  // This is not exacty what we need, but should be correct enough
  currentInfo = [_lineLayoutInformation objectAtIndex: i1];
  rect1 = currentInfo->lineFragmentRect;

  if (i1 != i2)
    {
      currentInfo = [_lineLayoutInformation objectAtIndex: i2];
      rect1 = NSUnionRect(rect1, currentInfo->lineFragmentRect);
    }
  else
    {
      //float width = [aTextContainer containerSize].width;
      // FIXME: When we are on one line we may need only part of it
    }

  return rect1;
}

- (NSRange)glyphRangeForBoundingRect:(NSRect)aRect 
		     inTextContainer:(NSTextContainer *)aTextContainer
{
  NSRange aRange = [self lineRangeForRect: aRect];

  return [self glyphRangeForLineLayoutRange: aRange];    
}

- (NSRect*) rectArrayForCharacterRange:(NSRange)aRange 
	  withinSelectedCharacterRange:(NSRange)selCharRange
		       inTextContainer:(NSTextContainer *)aTextContainer 
			     rectCount:(unsigned *)rectCount;
{
  //FIXME: This currently ignores most of its arguments

  if (!rectCount)
      return _rects;

  if (aRange.length)
    {
      NSRect startRect = [self rectForCharacterIndex: aRange.location];
      NSRect endRect = [self rectForCharacterIndex: NSMaxRange (aRange)];
      float width = 0;
      if (aTextContainer)
	width = [aTextContainer containerSize].width;

      if (startRect.origin.y  == endRect.origin.y)
	{
	  // single line selection
	  _rects[0] = NSMakeRect (startRect.origin.x, startRect.origin.y,
				  endRect.origin.x - startRect.origin.x,
				  startRect.size.height);
	  *rectCount = 1;
	}
      else if (startRect.origin.y == endRect.origin.y - endRect.size.height)
	{
	  // two line selection

	  // first line
	  _rects[0] = NSMakeRect (startRect.origin.x, startRect.origin.y,
				  width - startRect.origin.x,
				  startRect.size.height);
	  // second line
	  _rects[1] = NSMakeRect (0, endRect.origin.y, endRect.origin.x,
				  endRect.size.height);
	  *rectCount = 2;
	}
      else
	{
	  //   3 Rects: multiline selection

	  // first line
	  _rects[0] = NSMakeRect (startRect.origin.x, startRect.origin.y,
				  width - startRect.origin.x,
				  startRect.size.height);
	  // intermediate lines
	  _rects[1] = NSMakeRect (0, NSMaxY(startRect),
				  width,
				  endRect.origin.y - NSMaxY (startRect));
	  // last line
	  _rects[2] = NSMakeRect (0, endRect.origin.y, endRect.origin.x,
				  endRect.size.height);
	  *rectCount = 3;
	}
    }
  else 
    *rectCount = 0;

  return _rects;
}

- (NSRange)glyphRangeForTextContainer: (NSTextContainer*)aContainer
{
  return NSMakeRange(0, [_textStorage length]);
}

- (void) setTextContainer: (NSTextContainer*)aTextContainer
	    forGlyphRange: (NSRange)glyphRange
{
}

- (void) invalidateLayoutForCharacterRange: (NSRange)aRange
				    isSoft: (BOOL)flag
		      actualCharacterRange: (NSRange*)actualRange
{
  NSRange lineRange;
  NSTextContainer *aTextContainer = [self textContainerForGlyphAtIndex: aRange.location
					  effectiveRange: NULL];

  lineRange = [self rebuildForRange: aRange 
		    delta: 0
		    inTextContainer: aTextContainer];
  [[aTextContainer textView] sizeToFit];
  [[aTextContainer textView] invalidateTextContainerOrigin];

  if (actualRange)
    *actualRange = [self glyphRangeForLineLayoutRange: lineRange];
}

- (void)textStorage:(NSTextStorage *)aTextStorage
	     edited:(unsigned int)mask
	      range:(NSRange)aRange
     changeInLength:(int)delta
   invalidatedRange:(NSRange)invalidatedCharRange;
{
  NSRange lineRange;
  NSTextContainer *aTextContainer;

  // No editing
  if (!mask)
    {
      return;
    }
  
  [self invalidateGlyphsForCharacterRange: invalidatedCharRange
	changeInLength: delta
	actualCharacterRange: NULL];

  aTextContainer = [self textContainerForGlyphAtIndex: aRange.location
			 effectiveRange: NULL];
  lineRange = [self rebuildForRange: aRange
		    delta: delta
		    inTextContainer: aTextContainer];
  [[aTextContainer textView] sizeToFit];
  [[aTextContainer textView] invalidateTextContainerOrigin];

  /* FIXME - it was reported that at this point lineRange is no longer
   * correct ...  looks like sizeToFit / invalidateTextContainerOrigin
   * migth cause additional relayout.  */
  [self setNeedsDisplayForLineRange: lineRange
	inTextContainer: aTextContainer];
}

- (void)drawGlyphsForGlyphRange: (NSRange)glyphRange 
			atPoint: (NSPoint)containerOrigin
{
  NSRange newRange;
  NSRange selectedRange = [[self firstTextView] selectedRange];
  unsigned start = [self lineLayoutIndexForGlyphIndex: glyphRange.location];
  unsigned end = [self lineLayoutIndexForGlyphIndex: NSMaxRange(glyphRange)];
  NSRange lineRange = NSMakeRange(start, end + 1 - start);

  [self drawLinesInLineRange: lineRange];

  // We have to redraw the part of the selection that is inside
  // the redrawn lines
  newRange = NSIntersectionRange(selectedRange, glyphRange);
  // Was there any overlapping with the selection?
  if ((selectedRange.length &&
       NSLocationInRange(newRange.location, selectedRange)))
    {
      [self drawSelectionAsRangeNoCaret: newRange];
    }
}

- (void) setLineFragmentRect: (NSRect)fragmentRect
	       forGlyphRange: (NSRange)glyphRange
		    usedRect: (NSRect)usedRect
{
  [_lineLayoutInformation addObject:
      [_GNULineLayoutInfo
	  lineLayoutWithRange: glyphRange
	  rect: fragmentRect
	  usedRect: usedRect]];
}

- (void) setLocation: (NSPoint)aPoint
forStartOfGlyphRange: (NSRange)glyphRange
{
}

@end

@implementation GSSimpleLayoutManager (Private)

- (NSSize) _sizeOfRange: (NSRange)aRange
{
  if (aRange.length == 0  
      ||  _textStorage == nil 
      ||  NSMaxRange(aRange) > [_textStorage length])
    {
      return NSZeroSize;
    }
  
  return [_textStorage sizeRange: aRange];
}

- (unsigned) lineLayoutIndexForPoint: (NSPoint)point
{
  int i;
  int min = 0;
  int max = MAX(0, [_lineLayoutInformation count] - 1);
  float y = point.y;
  float fmin = NSMinY([[_lineLayoutInformation objectAtIndex: 0] lineFragmentRect]);
  float fmax = NSMaxY([[_lineLayoutInformation lastObject] lineFragmentRect]);
  NSRect rect;

  if (y >= fmax)
    return max;

  if (y <= fmin)
    return min;

  // this should give a good starting index for binary search
  i = (int)((max - min) * (y - fmin) / (fmax - fmin)) + min;
  while (min < max)
    {
      _GNULineLayoutInfo *ci = [_lineLayoutInformation objectAtIndex: i];

      rect = ci->lineFragmentRect;

      if (NSMaxY(rect) < y)
	{
	  min = i + 1;
	  i = (max + min) / 2;
	  continue;
	}
      if (NSMinY(rect) > y)
	{
	  max = i - 1;
	  i = (max + min) / 2;
	  continue;
	}

      return i;
    }
  return min;
}

- (int) lineLayoutIndexForGlyphIndex: (unsigned)anIndex
{
  int i;
  int min = 0;
  int max = MAX(0, (int)[_lineLayoutInformation count] - 1);
  unsigned y = anIndex;
  unsigned fmin;
  unsigned fmax;
  NSRange range;

  if (!max)
    return 0;

  fmin = [[_lineLayoutInformation objectAtIndex: 0] glyphRange].location;
  fmax = NSMaxRange([[_lineLayoutInformation lastObject] glyphRange]);

  if (y >= fmax)
    return max;

  if (y <= fmin)
    return min;

  // this should give a good starting index for binary search
  i = (int)((max - min) * (y - fmin) / (fmax - fmin)) + min;
  while (min < max)
    {
      _GNULineLayoutInfo *ci = [_lineLayoutInformation objectAtIndex: i];

      range = ci->glyphRange;

      if (NSMaxRange(range) <= y)
	{
	  min = i + 1;
	  i = (max + min) / 2;
	  continue;
	}
      if (range.location > y)
	{
	  max = i - 1;
	  i = (max + min) / 2;
	  continue;
	}
      // Do we need a special treatment for paragraph infos?
      return i;
    }
  return min;
}

- (NSRange) glyphRangeForLineLayoutRange: (NSRange)aRange;
{
  _GNULineLayoutInfo	*currentInfo;
  unsigned startLine = aRange.location;
  unsigned endLine = NSMaxRange(aRange);
  unsigned startIndex;
  unsigned endIndex;

  if (startLine >= [_lineLayoutInformation count])
    currentInfo = [_lineLayoutInformation lastObject];
  else
    currentInfo = [_lineLayoutInformation objectAtIndex: startLine];
  startIndex = currentInfo->glyphRange.location;

  if (endLine >= [_lineLayoutInformation count])
    currentInfo = [_lineLayoutInformation lastObject];
  else
    currentInfo = [_lineLayoutInformation objectAtIndex: endLine];
  endIndex = NSMaxRange(currentInfo->glyphRange);

  return NSMakeRange(startIndex, endIndex - startIndex);
}

// rect to the end of line
- (NSRect) rectForCharacterIndex: (unsigned)index
{
  float width = 0;
  id container;
  _GNULineLayoutInfo *currentInfo;
  unsigned start;
  NSRect rect;
  float x;

  container = [self textContainerForGlyphAtIndex: index effectiveRange: NULL];
  if (container)
    width = [container containerSize].width;
  if (![_textStorage length] || ![_lineLayoutInformation count])
    {
      return NSMakeRect(0, 0, width, 12);
    }

  currentInfo = [_lineLayoutInformation lastObject];
  if (index >= NSMaxRange(currentInfo->glyphRange))
    {
      NSRect rect = currentInfo->lineFragmentRect;

      return NSMakeRect(NSMaxX (rect), rect.origin.y,
			width - NSMaxX (rect),
			rect.size.height);
    }


  currentInfo = [_lineLayoutInformation 
		  objectAtIndex: [self lineLayoutIndexForGlyphIndex: 
					 index]];
  start = currentInfo->glyphRange.location;
  rect = currentInfo->lineFragmentRect;
  x = rect.origin.x + [self _sizeOfRange: NSMakeRange(start, index-start)].width;
     
  return NSMakeRect(x, rect.origin.y, NSMaxX (rect) - x,
		    rect.size.height);
}

- (void) drawSelectionAsRangeNoCaret: (NSRange)aRange
{
  unsigned i, count;
  NSTextContainer *aTextContainer;
  NSRect *rects;

  aTextContainer = [self textContainerForGlyphAtIndex: aRange.location
			 effectiveRange: NULL];
  rects = [self rectArrayForCharacterRange: aRange 
		withinSelectedCharacterRange: aRange
		inTextContainer: aTextContainer
		rectCount: &count];

  for (i = 0; i < count; i++)
    {
	NSHighlightRect (rects[i]);
    }
}

- (NSRange) lineRangeForRect: (NSRect)rect
{
  NSPoint upperLeftPoint = rect.origin;
  NSPoint lowerRightPoint = NSMakePoint (NSMaxX (rect), NSMaxY (rect));
  unsigned startLine, endLine;

  startLine = [self lineLayoutIndexForPoint: upperLeftPoint];
  endLine = [self lineLayoutIndexForPoint: lowerRightPoint];
  if (++endLine > [_lineLayoutInformation count])
    endLine = [_lineLayoutInformation count];

  return NSMakeRange(startLine, endLine - startLine);
}

// relies on _lineLayoutInformation
- (void) drawLinesInLineRange: (NSRange)aRange;
{
  NSArray *linesToDraw = [_lineLayoutInformation subarrayWithRange: aRange];
  NSEnumerator *lineEnum;
  _GNULineLayoutInfo *currentInfo;

  for ((lineEnum = [linesToDraw objectEnumerator]);
       (currentInfo = [lineEnum nextObject]);)
    {
      [_textStorage drawRange: currentInfo->glyphRange
		    inRect: currentInfo->lineFragmentRect];
    }
}

- (void) setNeedsDisplayForLineRange: (NSRange)redrawLineRange
		     inTextContainer: (NSTextContainer *)aTextContainer 
{
  if ([_lineLayoutInformation count]
      && NSMaxRange (redrawLineRange) < [_lineLayoutInformation count]
      && redrawLineRange.length)
    {
      _GNULineLayoutInfo *firstInfo
	= [_lineLayoutInformation objectAtIndex: redrawLineRange.location];
      NSRect displayRect = firstInfo->lineFragmentRect;
      float width = 0;
      if (aTextContainer)
	width = [aTextContainer containerSize].width;

      if (redrawLineRange.length > 1)
	  displayRect = NSUnionRect(displayRect,
				    [[_lineLayoutInformation
					 objectAtIndex: 
					     (int)NSMaxRange(redrawLineRange) - 1] lineFragmentRect]);

      displayRect.size.width = width - displayRect.origin.x;
      [[aTextContainer textView] setNeedsDisplayInRect: displayRect];
    }
}

- (BOOL) _relocLayoutArray: (NSMutableArray*)ghostArray
		    offset: (int)relocOffset
		floatTrift: (float*)yDisplacement
{
  _GNULineLayoutInfo *lastInfo = [_lineLayoutInformation lastObject];
  // The start character in the ghostArray
  unsigned nextChar = NSMaxRange(lastInfo->glyphRange) - relocOffset;
  NSEnumerator *relocEnum;
  _GNULineLayoutInfo *currReloc = nil;
  float yReloc;

  while ([ghostArray count])
    {
      unsigned firstChar;
      
      currReloc = [ghostArray objectAtIndex: 0];
      firstChar =  currReloc->glyphRange.location;
NSDebugLog(@"Reloc %@ to %d", NSStringFromRange(currReloc->glyphRange), nextChar);
      if (firstChar == nextChar)
	break;
      else if (firstChar > nextChar)
	return NO;
      else
	[ghostArray removeObjectAtIndex: 0];
    }

  if (![ghostArray count])
    return NO;

  relocEnum = [ghostArray objectEnumerator];
  yReloc = NSMaxY(lastInfo->lineFragmentRect) - currReloc->lineFragmentRect.origin.y;
  if (yDisplacement)
    *yDisplacement = yReloc;

  while ((currReloc = [relocEnum nextObject]) != nil)
    {
      currReloc->glyphRange.location += relocOffset;
      if (yReloc)
	{
	  currReloc->lineFragmentRect.origin.y += yReloc;
	  currReloc->usedRect.origin.y += yReloc;
	}
      [_lineLayoutInformation addObject:  currReloc];
    }

  return YES;
}

/*
 * A little utility function to determine the range of characters in a scanner
 * that are present in a specified character set.
 */
static inline NSRange
scanRange(NSScanner *scanner, NSCharacterSet* aSet)
{
  unsigned	start = [scanner scanLocation];
  unsigned	end = start;

  if ([scanner scanCharactersFromSet: aSet intoString: 0] == YES)
    {
      end = [scanner scanLocation];
    }
  return NSMakeRange(start, end - start);
}

// returns range of lines actually updated
- (NSRange) rebuildForRange: (NSRange)aRange
		      delta: (int)insertionDelta
	    inTextContainer:(NSTextContainer *)aTextContainer 
{
  NSPoint drawingPoint = NSZeroPoint;
  float padding = [aTextContainer lineFragmentPadding];
  unsigned startingIndex = 0;
  unsigned currentLineIndex;
  NSString *allText = [_textStorage string];
  unsigned length = [allText length];
  unsigned paraPos;
  int maxLines = [_lineLayoutInformation count];
  int aLine = 0;
  // for optimization detection
  NSMutableArray *ghostArray = nil;

  if (maxLines)
    {
      int insertionLineIndex = [self lineLayoutIndexForGlyphIndex:
				       aRange.location];
      int nextLine = [self lineLayoutIndexForGlyphIndex: 
			     NSMaxRange(aRange) - insertionDelta] + 1;
      
      if (nextLine < maxLines)
	{
	  // remember old array for optimization purposes
	  ghostArray = AUTORELEASE([[_lineLayoutInformation
				      subarrayWithRange:
					NSMakeRange (nextLine, 
						     maxLines - nextLine)]
				     mutableCopy]);
	}
      
      aLine = MAX(0, insertionLineIndex - 1);
      if (aLine)
	{
	  _GNULineLayoutInfo *lastValidLineInfo = [_lineLayoutInformation 
						    objectAtIndex: aLine - 1];
	  NSRect aRect = lastValidLineInfo->lineFragmentRect;
	  
	  startingIndex = NSMaxRange(lastValidLineInfo->glyphRange);
	  drawingPoint = aRect.origin;
	  drawingPoint.y += aRect.size.height;
	}
      
      [_lineLayoutInformation removeObjectsInRange:
				NSMakeRange (aLine, maxLines - aLine)];
    }
  
  if (!length)
    {
      float width = 0;
      if (aTextContainer)
        width = [aTextContainer containerSize].width;

      // FIXME: This should be done via extra line fragment
      // If there is no text add one empty box
      [_lineLayoutInformation
	  addObject: [_GNULineLayoutInfo
			 lineLayoutWithRange: NSMakeRange (0, 0)
			 rect: NSMakeRect (0, 0, width, 12)
			 usedRect: NSMakeRect (0, 0, 1, 12)]];
      return NSMakeRange(0,1);
    }
      
  currentLineIndex = aLine;
  paraPos = startingIndex;

  while (paraPos < length)
    {
      NSRange	para;		// Range of current paragraph.
      NSRange	eol;		// Range of newline character.
      NSScanner	*lScanner;
      unsigned	startingLineCharIndex = paraPos;
      BOOL	isBuckled = NO;
      NSString *paragraph;
      unsigned	position;	// Position in NSString.
      NSRect remainingRect = NSZeroRect;

      /* Determine the range of the next paragraph of text (in 'para')
	 and set 'paraPos' to point after the terminating newline
	 character (if any).  */
      para = NSMakeRange (paraPos, length - paraPos);
      eol = [allText rangeOfCharacterFromSet: newlines
		     options: NSLiteralSearch
		     range: para];

      if (eol.location == NSNotFound)
	{
	  eol.location = length;
	  eol.length = 0;
	}
      else
	{
	  para.length = eol.location - para.location;
	}
      paraPos = NSMaxRange(eol);
      position = para.location;

      paragraph = [allText substringWithRange: para];

      lScanner = [NSScanner scannerWithString: paragraph];
      [lScanner setCharactersToBeSkipped: nil];

      // Process a paragraph
      do
	{
	  // Temporary added a autorelease pool, as the current layout
	  // mechanism uses up much memory space, that should be freed
	  // as soon as possible.
	  CREATE_AUTORELEASE_POOL(pool);
	  NSRect fragmentRect;
	  NSRect usedLineRect;
	  float width;
	  NSRange lineGlyphRange;
	  // starts with zero, do not confuse with startingLineCharIndex
	  unsigned localLineStartIndex = [lScanner scanLocation];
	  unsigned scannerPosition = localLineStartIndex;

	  if (NSIsEmptyRect(remainingRect))
	    {
	      fragmentRect = NSMakeRect (0, drawingPoint.y, HUGE, HUGE);
	    }
	  else 
	    {
	      fragmentRect = remainingRect;
	    }
	  
	  fragmentRect = [aTextContainer 
			   lineFragmentRectForProposedRect: fragmentRect
			   sweepDirection: NSLineSweepRight
			   movementDirection: NSLineMoveDown
			   remainingRect: &remainingRect];
	  if (NSIsEmptyRect(fragmentRect))
 	    {
	      // No more space in the text container, give up doing the layout
	      int a = MAX (1, [_lineLayoutInformation count] - aLine);
	      return NSMakeRange(aLine, a);
	    }

	  width = fragmentRect.size.width - 2 * padding;
	  usedLineRect = fragmentRect;
	  usedLineRect.origin.x += padding;
	  usedLineRect.size = NSZeroSize;
	  
	  // scan the individual words to the end of the line
	  while (![lScanner isAtEnd]) 
	    {
	      NSRange	currentStringRange, trailingSpacesRange;
	      NSRange	leadingSpacesRange;
	      NSSize advanceSize;

	      // snack next word
	      // leading spaces: only first time
	      leadingSpacesRange
		= scanRange(lScanner, selectionWordGranularitySet);
	      currentStringRange
		= scanRange(lScanner, invSelectionWordGranularitySet);
	      trailingSpacesRange
		= scanRange(lScanner, selectionWordGranularitySet);

	      if (leadingSpacesRange.length)
		{
		  currentStringRange = NSUnionRange(leadingSpacesRange,
						    currentStringRange);
		}
	      if (trailingSpacesRange.length)
		{
		  currentStringRange = NSUnionRange(trailingSpacesRange,
						    currentStringRange);
		}
	      
	      // evaluate size of current word
	      advanceSize = [self _sizeOfRange:
				    NSMakeRange (currentStringRange.location + position,
						 currentStringRange.length)];

	      // handle case where single word is broader than width
	      // (buckle word)
	      if (advanceSize.width > width)
		{
		  if (isBuckled)
		    {
		      NSSize currentSize = NSMakeSize (HUGE, 0);
		      unsigned lastVisibleCharIndex;

		      for (lastVisibleCharIndex  =  currentStringRange.length;
			   currentSize.width >= width && lastVisibleCharIndex;
			   lastVisibleCharIndex--)
			{
			  currentSize = [self _sizeOfRange: NSMakeRange(
			      startingLineCharIndex, lastVisibleCharIndex)];
			}
		      isBuckled = NO;
		      usedLineRect.size = currentSize;
		      scannerPosition = localLineStartIndex + lastVisibleCharIndex +1;
		      [lScanner setScanLocation: scannerPosition];
		      break;
		    }
		  else
		    {
		      // undo layout of extralarge word
		      // (will be done on the next line [see above])
		      isBuckled = YES;
		    }
		}
	      else 
		{
		  isBuckled = NO;
		}
	      
	      // line to long
	      if (usedLineRect.size.width + advanceSize.width > width 
		  || isBuckled)
	        {
		  // end of line -> word wrap
		  // undo layout of last word
		  [lScanner setScanLocation: scannerPosition];
		  break;
		}

	      // Add next word
	      usedLineRect = NSUnionRect (usedLineRect,
					     NSMakeRect (drawingPoint.x,
							 drawingPoint.y,
							 advanceSize.width,
							 advanceSize.height));
	      scannerPosition = [lScanner scanLocation];
	      drawingPoint.x += advanceSize.width;
	    }

	  if ([lScanner isAtEnd])
	    {
	      // newline - induced premature lineending: flush
	      if (eol.length)
	        {
		  // Add information for the line break
		  scannerPosition += eol.length;
		  usedLineRect.size.width += 1;
		  // FIXME: This should use the real font size!!
		  if (usedLineRect.size.height == 0)
		    {
		      usedLineRect.size.height = 12;
		    }
		}
	    }
	  
	  lineGlyphRange = NSMakeRange (startingLineCharIndex,
					scannerPosition - localLineStartIndex);
	  // Adjust the height of the line fragment rect, as this will
	  // the to big
	  fragmentRect.size.height = usedLineRect.size.height;
	  
	  // This range is to small, as there are more lines that fit
	  // into the container
	  [self setTextContainer: aTextContainer 
		forGlyphRange: lineGlyphRange];
	  
	  [self setLineFragmentRect: fragmentRect
		forGlyphRange: lineGlyphRange
		usedRect: usedLineRect];

	  // This range is too big, as there are different runs in the
	  // glyph range
	  [self setLocation: NSMakePoint(0.0, 0.0)
		forStartOfGlyphRange: lineGlyphRange];
	  
	  currentLineIndex++;
	  startingLineCharIndex = NSMaxRange(lineGlyphRange);
	  drawingPoint.y += usedLineRect.size.height;
	  drawingPoint.x = 0;
	  
	  RELEASE(pool);
	  
	  if (ghostArray != nil)
	    {
	      float yDisplacement = 0;
	      
	      // is it possible to simply patch layout changes into
	      // layout array instead of doing a time consuming re -
	      // layout of the whole doc?
	      if ([self _relocLayoutArray: ghostArray
			offset: insertionDelta
			floatTrift: &yDisplacement])
	        {
		  unsigned erg;
		  
		  // y displacement: redisplay all remaining lines
		  if (yDisplacement)
		    {
		      erg = [_lineLayoutInformation count] - aLine;
		    }
		  else 
		    {
		      // return 2: redisplay only this and previous line
		      erg = currentLineIndex - aLine;
		    }
	      
		  return NSMakeRange(aLine, MAX(1, erg));
		}
	    }
	}
      while ([lScanner isAtEnd] == NO);
    }

  /* Now test for the special case - there is a newline at the end of
     the text?  The last newline is not displayed by the previous
     engine, so we do it manually.  */
  if ([newlines characterIsMember: [allText characterAtIndex: (length - 1)]])
    {
      float width = 0;
      if (aTextContainer)
	width = [aTextContainer containerSize].width;

      [_lineLayoutInformation
	addObject: [_GNULineLayoutInfo
		     lineLayoutWithRange: NSMakeRange (length, 0)
		     rect: NSMakeRect (drawingPoint.x, drawingPoint.y, 
				       width, 12)
		     usedRect: NSMakeRect (drawingPoint.x, drawingPoint.y, 
					   1, 12)]];      
    }
  

  
  // lines actually updated (optimized drawing)
  return NSMakeRange(aLine, MAX(1, [_lineLayoutInformation count] - aLine));
}


/* Computing where the insertion point should be moved when the user
 * presses 'Up' or 'Down' is a task for the layout manager.  */

/* Insertion point has y coordinate `position'.  We'd like to put it
   one line up/down (up if upFlag == YES, down if upFlag == NO),
   horizontally at `wanted', or the nearest available place.  Return
   the char index for the new insertion point position.  */
- (unsigned) _charIndexForInsertionPointMovingFromY: (float)position
					      bestX: (float)wanted
						 up: (BOOL)upFlag
				      textContainer: (NSTextContainer *)tc
{
  NSPoint point;
  unsigned line;
  _GNULineLayoutInfo *lineInfo;
  NSRect rect;
  NSRange range;
  unsigned glyphIndex;
  
  /* Compute the line we were on */
  point.x = 0;
  point.y = position;
  
  line = [self lineLayoutIndexForPoint: point];
  
  if (upFlag == YES  &&  line == 0)
    {
      return 0;
    }
  else if (upFlag == NO  &&  line == ([_lineLayoutInformation count] - 1))
    {
      return [_textStorage length];
    }

  /* Get line info for previous/following line */
  if (upFlag)
    {
      line -= 1;
    }
  else
    {
      line += 1;
    }

  lineInfo = [_lineLayoutInformation objectAtIndex: line];
  
  rect  = lineInfo->usedRect;
  range = lineInfo->glyphRange;

  /* Check if we are outside the rect */
  if (wanted <= rect.origin.x)
    {
      glyphIndex = [self characterIndexForGlyphAtIndex: range.location];
    }
  
  else if (wanted >= NSMaxX (rect))
    {
      glyphIndex = [self characterIndexForGlyphAtIndex: 
			   (NSMaxRange (range) - 1)];
    }
  else
    {
      /* Else, we can simply move there ! */
      glyphIndex = [self glyphIndexForPoint: NSMakePoint (wanted, 
							  NSMidY (rect)) 
			 inTextContainer: tc
			 fractionOfDistanceThroughGlyph: NULL];
    }
  return [self characterIndexForGlyphAtIndex: glyphIndex];
}

@end