Merge branch 'master' of https://github.com/konsolebox/geany into konsolebox-master
[geany-mirror.git] / scintilla / src / PositionCache.cxx
blob997a4bfae38471bd3eb1b05cfea20e1ef21c2c9f
1 // Scintilla source code edit control
2 /** @file PositionCache.cxx
3 ** Classes for caching layout information.
4 **/
5 // Copyright 1998-2007 by Neil Hodgson <neilh@scintilla.org>
6 // The License.txt file describes the conditions under which this software may be distributed.
8 #include <stdlib.h>
9 #include <string.h>
10 #include <stdio.h>
11 #include <ctype.h>
13 #include <stdexcept>
14 #include <string>
15 #include <vector>
16 #include <map>
17 #include <algorithm>
19 #include "Platform.h"
21 #include "ILexer.h"
22 #include "Scintilla.h"
24 #include "Position.h"
25 #include "SplitVector.h"
26 #include "Partitioning.h"
27 #include "RunStyles.h"
28 #include "ContractionState.h"
29 #include "CellBuffer.h"
30 #include "KeyMap.h"
31 #include "Indicator.h"
32 #include "XPM.h"
33 #include "LineMarker.h"
34 #include "Style.h"
35 #include "ViewStyle.h"
36 #include "CharClassify.h"
37 #include "Decoration.h"
38 #include "CaseFolder.h"
39 #include "Document.h"
40 #include "UniConversion.h"
41 #include "Selection.h"
42 #include "PositionCache.h"
44 #ifdef SCI_NAMESPACE
45 using namespace Scintilla;
46 #endif
48 LineLayout::LineLayout(int maxLineLength_) :
49 lineStarts(0),
50 lenLineStarts(0),
51 lineNumber(-1),
52 inCache(false),
53 maxLineLength(-1),
54 numCharsInLine(0),
55 numCharsBeforeEOL(0),
56 validity(llInvalid),
57 xHighlightGuide(0),
58 highlightColumn(0),
59 containsCaret(false),
60 edgeColumn(0),
61 chars(0),
62 styles(0),
63 positions(0),
64 hotspot(0,0),
65 widthLine(wrapWidthInfinite),
66 lines(1),
67 wrapIndent(0) {
68 bracePreviousStyles[0] = 0;
69 bracePreviousStyles[1] = 0;
70 Resize(maxLineLength_);
73 LineLayout::~LineLayout() {
74 Free();
77 void LineLayout::Resize(int maxLineLength_) {
78 if (maxLineLength_ > maxLineLength) {
79 Free();
80 chars = new char[maxLineLength_ + 1];
81 styles = new unsigned char[maxLineLength_ + 1];
82 // Extra position allocated as sometimes the Windows
83 // GetTextExtentExPoint API writes an extra element.
84 positions = new XYPOSITION[maxLineLength_ + 1 + 1];
85 maxLineLength = maxLineLength_;
89 void LineLayout::Free() {
90 delete []chars;
91 chars = 0;
92 delete []styles;
93 styles = 0;
94 delete []positions;
95 positions = 0;
96 delete []lineStarts;
97 lineStarts = 0;
100 void LineLayout::Invalidate(validLevel validity_) {
101 if (validity > validity_)
102 validity = validity_;
105 int LineLayout::LineStart(int line) const {
106 if (line <= 0) {
107 return 0;
108 } else if ((line >= lines) || !lineStarts) {
109 return numCharsInLine;
110 } else {
111 return lineStarts[line];
115 int LineLayout::LineLastVisible(int line) const {
116 if (line < 0) {
117 return 0;
118 } else if ((line >= lines-1) || !lineStarts) {
119 return numCharsBeforeEOL;
120 } else {
121 return lineStarts[line+1];
125 Range LineLayout::SubLineRange(int subLine) const {
126 return Range(LineStart(subLine), LineLastVisible(subLine));
129 bool LineLayout::InLine(int offset, int line) const {
130 return ((offset >= LineStart(line)) && (offset < LineStart(line + 1))) ||
131 ((offset == numCharsInLine) && (line == (lines-1)));
134 void LineLayout::SetLineStart(int line, int start) {
135 if ((line >= lenLineStarts) && (line != 0)) {
136 int newMaxLines = line + 20;
137 int *newLineStarts = new int[newMaxLines];
138 for (int i = 0; i < newMaxLines; i++) {
139 if (i < lenLineStarts)
140 newLineStarts[i] = lineStarts[i];
141 else
142 newLineStarts[i] = 0;
144 delete []lineStarts;
145 lineStarts = newLineStarts;
146 lenLineStarts = newMaxLines;
148 lineStarts[line] = start;
151 void LineLayout::SetBracesHighlight(Range rangeLine, const Position braces[],
152 char bracesMatchStyle, int xHighlight, bool ignoreStyle) {
153 if (!ignoreStyle && rangeLine.ContainsCharacter(braces[0])) {
154 int braceOffset = braces[0] - rangeLine.start;
155 if (braceOffset < numCharsInLine) {
156 bracePreviousStyles[0] = styles[braceOffset];
157 styles[braceOffset] = bracesMatchStyle;
160 if (!ignoreStyle && rangeLine.ContainsCharacter(braces[1])) {
161 int braceOffset = braces[1] - rangeLine.start;
162 if (braceOffset < numCharsInLine) {
163 bracePreviousStyles[1] = styles[braceOffset];
164 styles[braceOffset] = bracesMatchStyle;
167 if ((braces[0] >= rangeLine.start && braces[1] <= rangeLine.end) ||
168 (braces[1] >= rangeLine.start && braces[0] <= rangeLine.end)) {
169 xHighlightGuide = xHighlight;
173 void LineLayout::RestoreBracesHighlight(Range rangeLine, const Position braces[], bool ignoreStyle) {
174 if (!ignoreStyle && rangeLine.ContainsCharacter(braces[0])) {
175 int braceOffset = braces[0] - rangeLine.start;
176 if (braceOffset < numCharsInLine) {
177 styles[braceOffset] = bracePreviousStyles[0];
180 if (!ignoreStyle && rangeLine.ContainsCharacter(braces[1])) {
181 int braceOffset = braces[1] - rangeLine.start;
182 if (braceOffset < numCharsInLine) {
183 styles[braceOffset] = bracePreviousStyles[1];
186 xHighlightGuide = 0;
189 int LineLayout::FindBefore(XYPOSITION x, int lower, int upper) const {
190 do {
191 int middle = (upper + lower + 1) / 2; // Round high
192 XYPOSITION posMiddle = positions[middle];
193 if (x < posMiddle) {
194 upper = middle - 1;
195 } else {
196 lower = middle;
198 } while (lower < upper);
199 return lower;
203 int LineLayout::FindPositionFromX(XYPOSITION x, Range range, bool charPosition) const {
204 int pos = FindBefore(x, range.start, range.end);
205 while (pos < range.end) {
206 if (charPosition) {
207 if (x < (positions[pos + 1])) {
208 return pos;
210 } else {
211 if (x < ((positions[pos] + positions[pos + 1]) / 2)) {
212 return pos;
215 pos++;
217 return range.end;
220 Point LineLayout::PointFromPosition(int posInLine, int lineHeight) const {
221 Point pt;
222 // In case of very long line put x at arbitrary large position
223 if (posInLine > maxLineLength) {
224 pt.x = positions[maxLineLength] - positions[LineStart(lines)];
227 for (int subLine = 0; subLine < lines; subLine++) {
228 const Range rangeSubLine = SubLineRange(subLine);
229 if (posInLine >= rangeSubLine.start) {
230 pt.y = static_cast<XYPOSITION>(subLine*lineHeight);
231 if (posInLine <= rangeSubLine.end) {
232 pt.x = positions[posInLine] - positions[rangeSubLine.start];
233 if (rangeSubLine.start != 0) // Wrapped lines may be indented
234 pt.x += wrapIndent;
236 } else {
237 break;
240 return pt;
243 int LineLayout::EndLineStyle() const {
244 return styles[numCharsBeforeEOL > 0 ? numCharsBeforeEOL-1 : 0];
247 LineLayoutCache::LineLayoutCache() :
248 level(0),
249 allInvalidated(false), styleClock(-1), useCount(0) {
250 Allocate(0);
253 LineLayoutCache::~LineLayoutCache() {
254 Deallocate();
257 void LineLayoutCache::Allocate(size_t length_) {
258 PLATFORM_ASSERT(cache.empty());
259 allInvalidated = false;
260 cache.resize(length_);
263 void LineLayoutCache::AllocateForLevel(int linesOnScreen, int linesInDoc) {
264 PLATFORM_ASSERT(useCount == 0);
265 size_t lengthForLevel = 0;
266 if (level == llcCaret) {
267 lengthForLevel = 1;
268 } else if (level == llcPage) {
269 lengthForLevel = linesOnScreen + 1;
270 } else if (level == llcDocument) {
271 lengthForLevel = linesInDoc;
273 if (lengthForLevel > cache.size()) {
274 Deallocate();
275 Allocate(lengthForLevel);
276 } else {
277 if (lengthForLevel < cache.size()) {
278 for (size_t i = lengthForLevel; i < cache.size(); i++) {
279 delete cache[i];
280 cache[i] = 0;
283 cache.resize(lengthForLevel);
285 PLATFORM_ASSERT(cache.size() == lengthForLevel);
288 void LineLayoutCache::Deallocate() {
289 PLATFORM_ASSERT(useCount == 0);
290 for (size_t i = 0; i < cache.size(); i++)
291 delete cache[i];
292 cache.clear();
295 void LineLayoutCache::Invalidate(LineLayout::validLevel validity_) {
296 if (!cache.empty() && !allInvalidated) {
297 for (size_t i = 0; i < cache.size(); i++) {
298 if (cache[i]) {
299 cache[i]->Invalidate(validity_);
302 if (validity_ == LineLayout::llInvalid) {
303 allInvalidated = true;
308 void LineLayoutCache::SetLevel(int level_) {
309 allInvalidated = false;
310 if ((level_ != -1) && (level != level_)) {
311 level = level_;
312 Deallocate();
316 LineLayout *LineLayoutCache::Retrieve(int lineNumber, int lineCaret, int maxChars, int styleClock_,
317 int linesOnScreen, int linesInDoc) {
318 AllocateForLevel(linesOnScreen, linesInDoc);
319 if (styleClock != styleClock_) {
320 Invalidate(LineLayout::llCheckTextAndStyle);
321 styleClock = styleClock_;
323 allInvalidated = false;
324 int pos = -1;
325 LineLayout *ret = 0;
326 if (level == llcCaret) {
327 pos = 0;
328 } else if (level == llcPage) {
329 if (lineNumber == lineCaret) {
330 pos = 0;
331 } else if (cache.size() > 1) {
332 pos = 1 + (lineNumber % (cache.size() - 1));
334 } else if (level == llcDocument) {
335 pos = lineNumber;
337 if (pos >= 0) {
338 PLATFORM_ASSERT(useCount == 0);
339 if (!cache.empty() && (pos < static_cast<int>(cache.size()))) {
340 if (cache[pos]) {
341 if ((cache[pos]->lineNumber != lineNumber) ||
342 (cache[pos]->maxLineLength < maxChars)) {
343 delete cache[pos];
344 cache[pos] = 0;
347 if (!cache[pos]) {
348 cache[pos] = new LineLayout(maxChars);
350 cache[pos]->lineNumber = lineNumber;
351 cache[pos]->inCache = true;
352 ret = cache[pos];
353 useCount++;
357 if (!ret) {
358 ret = new LineLayout(maxChars);
359 ret->lineNumber = lineNumber;
362 return ret;
365 void LineLayoutCache::Dispose(LineLayout *ll) {
366 allInvalidated = false;
367 if (ll) {
368 if (!ll->inCache) {
369 delete ll;
370 } else {
371 useCount--;
376 // Simply pack the (maximum 4) character bytes into an int
377 static inline int KeyFromString(const char *charBytes, size_t len) {
378 PLATFORM_ASSERT(len <= 4);
379 int k=0;
380 for (size_t i=0; i<len && charBytes[i]; i++) {
381 k = k * 0x100;
382 k += static_cast<unsigned char>(charBytes[i]);
384 return k;
387 SpecialRepresentations::SpecialRepresentations() {
388 std::fill(startByteHasReprs, startByteHasReprs+0x100, 0);
391 void SpecialRepresentations::SetRepresentation(const char *charBytes, const char *value) {
392 MapRepresentation::iterator it = mapReprs.find(KeyFromString(charBytes, UTF8MaxBytes));
393 if (it == mapReprs.end()) {
394 // New entry so increment for first byte
395 startByteHasReprs[static_cast<unsigned char>(charBytes[0])]++;
397 mapReprs[KeyFromString(charBytes, UTF8MaxBytes)] = Representation(value);
400 void SpecialRepresentations::ClearRepresentation(const char *charBytes) {
401 MapRepresentation::iterator it = mapReprs.find(KeyFromString(charBytes, UTF8MaxBytes));
402 if (it != mapReprs.end()) {
403 mapReprs.erase(it);
404 startByteHasReprs[static_cast<unsigned char>(charBytes[0])]--;
408 const Representation *SpecialRepresentations::RepresentationFromCharacter(const char *charBytes, size_t len) const {
409 PLATFORM_ASSERT(len <= 4);
410 if (!startByteHasReprs[static_cast<unsigned char>(charBytes[0])])
411 return 0;
412 MapRepresentation::const_iterator it = mapReprs.find(KeyFromString(charBytes, len));
413 if (it != mapReprs.end()) {
414 return &(it->second);
416 return 0;
419 bool SpecialRepresentations::Contains(const char *charBytes, size_t len) const {
420 PLATFORM_ASSERT(len <= 4);
421 if (!startByteHasReprs[static_cast<unsigned char>(charBytes[0])])
422 return false;
423 MapRepresentation::const_iterator it = mapReprs.find(KeyFromString(charBytes, len));
424 return it != mapReprs.end();
427 void SpecialRepresentations::Clear() {
428 mapReprs.clear();
429 std::fill(startByteHasReprs, startByteHasReprs+0x100, 0);
432 void BreakFinder::Insert(int val) {
433 if (val > nextBreak) {
434 const std::vector<int>::iterator it = std::lower_bound(selAndEdge.begin(), selAndEdge.end(), val);
435 if (it == selAndEdge.end()) {
436 selAndEdge.push_back(val);
437 } else if (*it != val) {
438 selAndEdge.insert(it, 1, val);
443 BreakFinder::BreakFinder(const LineLayout *ll_, const Selection *psel, Range lineRange_, int posLineStart_,
444 int xStart, bool breakForSelection, const Document *pdoc_, const SpecialRepresentations *preprs_, const ViewStyle *pvsDraw) :
445 ll(ll_),
446 lineRange(lineRange_),
447 posLineStart(posLineStart_),
448 nextBreak(lineRange_.start),
449 saeCurrentPos(0),
450 saeNext(0),
451 subBreak(-1),
452 pdoc(pdoc_),
453 encodingFamily(pdoc_->CodePageFamily()),
454 preprs(preprs_) {
456 // Search for first visible break
457 // First find the first visible character
458 if (xStart > 0.0f)
459 nextBreak = ll->FindBefore(static_cast<XYPOSITION>(xStart), lineRange.start, lineRange.end);
460 // Now back to a style break
461 while ((nextBreak > lineRange.start) && (ll->styles[nextBreak] == ll->styles[nextBreak - 1])) {
462 nextBreak--;
465 if (breakForSelection) {
466 SelectionPosition posStart(posLineStart);
467 SelectionPosition posEnd(posLineStart + lineRange.end);
468 SelectionSegment segmentLine(posStart, posEnd);
469 for (size_t r=0; r<psel->Count(); r++) {
470 SelectionSegment portion = psel->Range(r).Intersect(segmentLine);
471 if (!(portion.start == portion.end)) {
472 if (portion.start.IsValid())
473 Insert(portion.start.Position() - posLineStart);
474 if (portion.end.IsValid())
475 Insert(portion.end.Position() - posLineStart);
479 if (pvsDraw && pvsDraw->indicatorsSetFore > 0) {
480 for (Decoration *deco = pdoc->decorations.root; deco; deco = deco->next) {
481 if (pvsDraw->indicators[deco->indicator].OverridesTextFore()) {
482 int startPos = deco->rs.EndRun(posLineStart);
483 while (startPos < (posLineStart + lineRange.end)) {
484 Insert(startPos - posLineStart);
485 startPos = deco->rs.EndRun(startPos);
490 Insert(ll->edgeColumn);
491 Insert(lineRange.end);
492 saeNext = (!selAndEdge.empty()) ? selAndEdge[0] : -1;
495 BreakFinder::~BreakFinder() {
498 TextSegment BreakFinder::Next() {
499 if (subBreak == -1) {
500 int prev = nextBreak;
501 while (nextBreak < lineRange.end) {
502 int charWidth = 1;
503 if (encodingFamily == efUnicode)
504 charWidth = UTF8DrawBytes(reinterpret_cast<unsigned char *>(ll->chars) + nextBreak, lineRange.end - nextBreak);
505 else if (encodingFamily == efDBCS)
506 charWidth = pdoc->IsDBCSLeadByte(ll->chars[nextBreak]) ? 2 : 1;
507 const Representation *repr = preprs->RepresentationFromCharacter(ll->chars + nextBreak, charWidth);
508 if (((nextBreak > 0) && (ll->styles[nextBreak] != ll->styles[nextBreak - 1])) ||
509 repr ||
510 (nextBreak == saeNext)) {
511 while ((nextBreak >= saeNext) && (saeNext < lineRange.end)) {
512 saeCurrentPos++;
513 saeNext = (saeCurrentPos < selAndEdge.size()) ? selAndEdge[saeCurrentPos] : lineRange.end;
515 if ((nextBreak > prev) || repr) {
516 // Have a segment to report
517 if (nextBreak == prev) {
518 nextBreak += charWidth;
519 } else {
520 repr = 0; // Optimize -> should remember repr
522 if ((nextBreak - prev) < lengthStartSubdivision) {
523 return TextSegment(prev, nextBreak - prev, repr);
524 } else {
525 break;
529 nextBreak += charWidth;
531 if ((nextBreak - prev) < lengthStartSubdivision) {
532 return TextSegment(prev, nextBreak - prev);
534 subBreak = prev;
536 // Splitting up a long run from prev to nextBreak in lots of approximately lengthEachSubdivision.
537 // For very long runs add extra breaks after spaces or if no spaces before low punctuation.
538 int startSegment = subBreak;
539 if ((nextBreak - subBreak) <= lengthEachSubdivision) {
540 subBreak = -1;
541 return TextSegment(startSegment, nextBreak - startSegment);
542 } else {
543 subBreak += pdoc->SafeSegment(ll->chars + subBreak, nextBreak-subBreak, lengthEachSubdivision);
544 if (subBreak >= nextBreak) {
545 subBreak = -1;
546 return TextSegment(startSegment, nextBreak - startSegment);
547 } else {
548 return TextSegment(startSegment, subBreak - startSegment);
553 bool BreakFinder::More() const {
554 return (subBreak >= 0) || (nextBreak < lineRange.end);
557 PositionCacheEntry::PositionCacheEntry() :
558 styleNumber(0), len(0), clock(0), positions(0) {
561 void PositionCacheEntry::Set(unsigned int styleNumber_, const char *s_,
562 unsigned int len_, XYPOSITION *positions_, unsigned int clock_) {
563 Clear();
564 styleNumber = styleNumber_;
565 len = len_;
566 clock = clock_;
567 if (s_ && positions_) {
568 positions = new XYPOSITION[len + (len / 4) + 1];
569 for (unsigned int i=0; i<len; i++) {
570 positions[i] = positions_[i];
572 memcpy(reinterpret_cast<char *>(reinterpret_cast<void *>(positions + len)), s_, len);
576 PositionCacheEntry::~PositionCacheEntry() {
577 Clear();
580 void PositionCacheEntry::Clear() {
581 delete []positions;
582 positions = 0;
583 styleNumber = 0;
584 len = 0;
585 clock = 0;
588 bool PositionCacheEntry::Retrieve(unsigned int styleNumber_, const char *s_,
589 unsigned int len_, XYPOSITION *positions_) const {
590 if ((styleNumber == styleNumber_) && (len == len_) &&
591 (memcmp(reinterpret_cast<char *>(reinterpret_cast<void *>(positions + len)), s_, len)== 0)) {
592 for (unsigned int i=0; i<len; i++) {
593 positions_[i] = positions[i];
595 return true;
596 } else {
597 return false;
601 unsigned int PositionCacheEntry::Hash(unsigned int styleNumber_, const char *s, unsigned int len_) {
602 unsigned int ret = s[0] << 7;
603 for (unsigned int i=0; i<len_; i++) {
604 ret *= 1000003;
605 ret ^= s[i];
607 ret *= 1000003;
608 ret ^= len_;
609 ret *= 1000003;
610 ret ^= styleNumber_;
611 return ret;
614 bool PositionCacheEntry::NewerThan(const PositionCacheEntry &other) const {
615 return clock > other.clock;
618 void PositionCacheEntry::ResetClock() {
619 if (clock > 0) {
620 clock = 1;
624 PositionCache::PositionCache() {
625 clock = 1;
626 pces.resize(0x400);
627 allClear = true;
630 PositionCache::~PositionCache() {
631 Clear();
634 void PositionCache::Clear() {
635 if (!allClear) {
636 for (size_t i=0; i<pces.size(); i++) {
637 pces[i].Clear();
640 clock = 1;
641 allClear = true;
644 void PositionCache::SetSize(size_t size_) {
645 Clear();
646 pces.resize(size_);
649 void PositionCache::MeasureWidths(Surface *surface, const ViewStyle &vstyle, unsigned int styleNumber,
650 const char *s, unsigned int len, XYPOSITION *positions, Document *pdoc) {
652 allClear = false;
653 size_t probe = pces.size(); // Out of bounds
654 if ((!pces.empty()) && (len < 30)) {
655 // Only store short strings in the cache so it doesn't churn with
656 // long comments with only a single comment.
658 // Two way associative: try two probe positions.
659 unsigned int hashValue = PositionCacheEntry::Hash(styleNumber, s, len);
660 probe = hashValue % pces.size();
661 if (pces[probe].Retrieve(styleNumber, s, len, positions)) {
662 return;
664 unsigned int probe2 = (hashValue * 37) % pces.size();
665 if (pces[probe2].Retrieve(styleNumber, s, len, positions)) {
666 return;
668 // Not found. Choose the oldest of the two slots to replace
669 if (pces[probe].NewerThan(pces[probe2])) {
670 probe = probe2;
673 if (len > BreakFinder::lengthStartSubdivision) {
674 // Break up into segments
675 unsigned int startSegment = 0;
676 XYPOSITION xStartSegment = 0;
677 while (startSegment < len) {
678 unsigned int lenSegment = pdoc->SafeSegment(s + startSegment, len - startSegment, BreakFinder::lengthEachSubdivision);
679 FontAlias fontStyle = vstyle.styles[styleNumber].font;
680 surface->MeasureWidths(fontStyle, s + startSegment, lenSegment, positions + startSegment);
681 for (unsigned int inSeg = 0; inSeg < lenSegment; inSeg++) {
682 positions[startSegment + inSeg] += xStartSegment;
684 xStartSegment = positions[startSegment + lenSegment - 1];
685 startSegment += lenSegment;
687 } else {
688 FontAlias fontStyle = vstyle.styles[styleNumber].font;
689 surface->MeasureWidths(fontStyle, s, len, positions);
691 if (probe < pces.size()) {
692 // Store into cache
693 clock++;
694 if (clock > 60000) {
695 // Since there are only 16 bits for the clock, wrap it round and
696 // reset all cache entries so none get stuck with a high clock.
697 for (size_t i=0; i<pces.size(); i++) {
698 pces[i].ResetClock();
700 clock = 2;
702 pces[probe].Set(styleNumber, s, len, positions, clock);