removed some debug code
[xreader.git] / xlayouter.d
blobea97ac2f0fde989bc2f42943de08e2e01eb9bbb9
1 /* Written by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
2 * Understanding is not required. Only obedience.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 module xlayouter;
19 import arsd.color;
20 import arsd.png;
21 import arsd.jpeg;
23 import iv.nanovg;
24 import iv.nanovg.oui.blendish;
25 import iv.utfutil;
26 import iv.vfs;
27 import iv.vfs.io;
29 import booktext;
31 version(laytest) import iv.encoding;
32 version(aliced) {} else private alias usize = size_t;
35 // ////////////////////////////////////////////////////////////////////////// //
36 // this needs such fonts in stash:
37 // text -- normal
38 // texti -- italic
39 // textb -- bold
40 // textz -- italic and bold
41 // mono -- normal
42 // monoi -- italic
43 // monob -- bold
44 // monoz -- italic and bold
45 final class LayFontStash {
46 public:
47 FONScontext* fs;
48 // list of known font faces, should be filled by caller when this object created
49 // DO NOT MODIFY!
50 int[string] fontfaces;
51 string[int] fontfaceids;
53 private:
54 bool killFontStash;
55 bool fontWasSet; // to ensure that first call to `setFont()` will do it's work
56 LayFontStyle lastStyle;
58 public:
59 this () {
60 // create new fontstash
61 FONSparams fontParams;
62 fontParams.width = 1024/*NVG_INIT_FONTIMAGE_SIZE*/;
63 fontParams.height = 1024/*NVG_INIT_FONTIMAGE_SIZE*/;
64 fontParams.flags = FONS_ZERO_TOPLEFT;
65 fs = fonsCreateInternal(&fontParams);
66 if (fs is null) throw new Exception("error creating font stash");
67 killFontStash = true;
68 fs.fonsResetAtlas(1024, 1024);
69 fonsSetSpacing(fs, 0);
70 fonsSetBlur(fs, 0);
71 fonsSetAlign(fs, NVGAlign.Left|NVGAlign.Baseline);
74 ~this () { freeFontStash(); }
76 void freeFontStash () {
77 if (killFontStash && fs !is null) {
78 fs.fonsDeleteInternal();
80 killFontStash = false;
81 fs = null;
84 void addFont(T : const(char)[], TP : const(char)[]) (T name, TP path) {
85 static if (is(T == typeof(null))) {
86 throw new Exception("invalid font face name");
87 } else {
88 if (name.length == 0) throw new Exception("invalid font face name");
89 if (name in fontfaces) throw new Exception("duplicate font '"~name.idup~"'");
90 int fid = fs.fonsAddFont(name, path);
91 if (fid < 0) throw new Exception("font '"~name~"' is not found at '"~path.idup~"'");
92 static if (is(T == string)) {
93 fontfaces[name] = fid;
94 fontfaceids[fid] = name;
95 } else {
96 string n = name.idup;
97 fontfaces[n] = fid;
98 fontfaceids[fid] = n;
103 @property int fontFaceId (const(char)[] name) {
104 if (auto fid = name in fontfaces) return *fid;
105 return -1;
108 @property string fontFace (int fid) {
109 if (auto ff = fid in fontfaceids) return *ff;
110 return null;
113 void setFont() (in auto ref LayFontStyle style) {
114 int fsz = style.fontsize;
115 if (fsz < 1) fsz = 1;
116 if (!fontWasSet || fsz != lastStyle.fontsize || style.fontface != lastStyle.fontface) {
117 if (style.fontface != lastStyle.fontface) fonsSetFont(fs, style.fontface);
118 if (fsz != lastStyle.fontsize) fonsSetSize(fs, fsz);
119 lastStyle = style;
120 lastStyle.fontsize = fsz;
124 int textWidth(T) (const(T)[] str) if (is(T == char) || is(T == dchar)) {
125 import std.algorithm : max;
126 import core.stdc.math : lrintf;
127 float[4] b = void;
128 float adv = fs.fonsTextBounds(0, 0, str, b[]);
129 float w = b[2]-b[0];
130 return lrintf(max(adv, w));
133 int spacesWidth (int count) {
134 import core.stdc.math : lrintf;
135 if (count < 1) return 0;
136 auto it = FonsTextBoundsIterator(fs, 0, 0);
137 it.put(' ');
138 return lrintf(it.advance*count);
141 void textWidth2(T) (const(T)[] str, int* w=null, int* wsp=null, int* whyph=null) if (is(T == char) || is(T == dchar)) {
142 import core.stdc.math : lrintf;
143 import std.algorithm : max;
144 if (w is null && wsp is null && whyph is null) return;
145 float minx, maxx;
146 auto it = FonsTextBoundsIterator(fs, 0, 0);
147 it.put(str);
148 if (w !is null) {
149 it.getHBounds(minx, maxx);
150 *w = lrintf(max(it.advance, maxx-minx));
152 if (wsp !is null && whyph is null) {
153 it.put(" ");
154 it.getHBounds(minx, maxx);
155 *wsp = lrintf(max(it.advance, maxx-minx));
156 } else if (wsp is null && whyph !is null) {
157 it.put(cast(dchar)45);
158 it.getHBounds(minx, maxx);
159 *whyph = lrintf(max(it.advance, maxx-minx));
160 } else if (wsp !is null && whyph !is null) {
161 auto sit = it;
162 it.put(" ");
163 it.getHBounds(minx, maxx);
164 *wsp = lrintf(max(it.advance, maxx-minx));
165 sit.put(cast(dchar)45);
166 sit.getHBounds(minx, maxx);
167 *whyph = lrintf(max(sit.advance, maxx-minx));
171 int textHeight () {
172 import core.stdc.math : lrintf;
173 // use line bounds for height
174 float y0 = void, y1 = void;
175 fs.fonsLineBounds(0, &y0, &y1);
176 return lrintf(y1-y0);
179 void textMetrics (int* asc, int* desc, int* lineh) {
180 import core.stdc.math : lrintf;
181 float a = void, d = void, h = void;
182 fs.fonsVertMetrics(&a, &d, &h);
183 if (asc !is null) *asc = lrintf(a);
184 if (desc !is null) *desc = lrintf(d);
185 if (lineh !is null) *lineh = lrintf(h);
190 // ////////////////////////////////////////////////////////////////////////// //
191 // generic text style
192 align(1) struct LayFontStyle {
193 align(1):
194 enum Flag : uint {
195 Italic = 1<<0,
196 Bold = 1<<1,
197 Strike = 1<<2,
198 Underline = 1<<3,
199 Overline = 1<<4,
201 ubyte flags; // see above
202 int fontface = -1; // i can't use strings here, as this struct inside LayWord will not be GC-scanned
203 int fontsize;
204 uint color = 0xff000000; // AABBGGRR; AA usually ignored by renderer, but i'll keep it anyway
205 string toString () const {
206 import std.format : format;
207 string res = "font:%s;size:%s;color:0x%08X".format(fontface, fontsize, color);
208 if (flags&Flag.Italic) res ~= ";italic";
209 if (flags&Flag.Bold) res ~= ";bold";
210 if (flags&Flag.Strike) res ~= ";strike";
211 if (flags&Flag.Underline) res ~= ";under";
212 if (flags&Flag.Overline) res ~= ";over";
213 return res;
215 mixin({
216 import std.conv : to;
217 import std.ascii : toLower;
218 string res;
219 foreach (string s; __traits(allMembers, Flag)) {
220 //pragma(msg, s);
221 res ~= "@property bool "~s[0].toLower~s[1..$]~" () const pure nothrow @safe @nogc { pragma(inline, true); return ((flags&Flag."~s~") != 0); }\n";
222 res ~= "@property void "~s[0].toLower~s[1..$]~" (bool v) pure nothrow @safe @nogc { pragma(inline, true); if (v) flags |= Flag."~s~"; else flags &= ~Flag."~s~"; }\n";
224 return res;
225 }());
226 bool opEquals() (in auto ref LayFontStyle s) const pure nothrow @safe @nogc { pragma(inline, true); return (flags == s.flags && fontface == s.fontface && color == s.color && fontsize == s.fontsize); }
230 // ////////////////////////////////////////////////////////////////////////// //
231 // line align style
232 align(1) struct LayLineStyle {
233 align(1):
234 enum Justify : ubyte {
235 Left,
236 Right,
237 Center,
238 Justify,
240 Justify mode = Justify.Left;
241 short lpad, rpad, tpad, bpad;
242 ubyte paraIndent; // in spaces
243 string toString () const {
244 import std.format : format;
245 string res;
246 final switch (mode) {
247 case Justify.Left: res = "left"; break;
248 case Justify.Right: res = "right"; break;
249 case Justify.Center: res = "center"; break;
250 case Justify.Justify: res = "justify"; break;
252 if (lpad) res ~= ";lpad:%s".format(lpad);
253 if (rpad) res ~= ";rpad:%s".format(rpad);
254 if (tpad) res ~= ";tpad:%s".format(tpad);
255 if (bpad) res ~= ";bpad:%s".format(bpad);
256 return res;
258 mixin({
259 import std.conv : to;
260 import std.ascii : toLower;
261 string res;
262 foreach (string s; __traits(allMembers, Justify)) {
263 //pragma(msg, s);
264 res ~= "@property bool "~s[0].toLower~s[1..$]~" () const pure nothrow @safe @nogc { pragma(inline, true); return (mode == Justify."~s~"); }\n";
265 res ~= "ref LayLineStyle set"~s~" () pure nothrow @safe @nogc { mode = Justify."~s~"; return this; }\n";
267 return res;
268 }());
269 bool opEquals() (in auto ref LayLineStyle s) const pure nothrow @safe @nogc { pragma(inline, true); return (mode == s.mode && lpad == s.lpad); }
270 @property pure nothrow @safe @nogc {
271 int leftpad () const { pragma(inline, true); return lpad; }
272 void leftpad (int v) { pragma(inline, true); lpad = (v < short.min ? short.min : v > short.max ? short.max : cast(short)v); }
273 int rightpad () const { pragma(inline, true); return rpad; }
274 void rightpad (int v) { pragma(inline, true); rpad = (v < short.min ? short.min : v > short.max ? short.max : cast(short)v); }
275 int toppad () const { pragma(inline, true); return tpad; }
276 void toppad (int v) { pragma(inline, true); tpad = (v < 0 ? 0 : v > short.max ? short.max : cast(short)v); }
277 int bottompad () const { pragma(inline, true); return bpad; }
278 void bottompad (int v) { pragma(inline, true); bpad = (v < 0 ? 0 : v > short.max ? short.max : cast(short)v); }
283 // ////////////////////////////////////////////////////////////////////////// //
284 // layouted text word
285 align(1) struct LayWord {
286 align(1):
287 static align(1) struct Props {
288 align(1):
289 enum Flag : uint {
290 CanBreak = 1<<0, // can i break line at this word?
291 Spaced = 1<<1, // should this word be whitespaced at the end?
292 Hypen = 1<<2, // if i'll break at this word, should i add hyphen mark?
293 LineEnd = 1<<3, // this word ends current line
294 ParaEnd = 1<<4, // this word ends current paragraph (and, implicitly, line)
296 ubyte flags; // see above
297 @property pure nothrow @safe @nogc:
298 bool canbreak () const { pragma(inline, true); return ((flags&Flag.CanBreak) != 0); }
299 void canbreak (bool v) { pragma(inline, true); if (v) flags |= Flag.CanBreak; else flags &= ~Flag.CanBreak; }
300 bool spaced () const { pragma(inline, true); return ((flags&Flag.Spaced) != 0); }
301 void spaced (bool v) { pragma(inline, true); if (v) flags |= Flag.Spaced; else flags &= ~Flag.Spaced; }
302 bool hyphen () const { pragma(inline, true); return ((flags&Flag.Hypen) != 0); }
303 void hyphen (bool v) { pragma(inline, true); if (v) flags |= Flag.Hypen; else flags &= ~Flag.Hypen; }
304 bool lineend () const { pragma(inline, true); return ((flags&Flag.LineEnd) != 0); }
305 void lineend (bool v) { pragma(inline, true); if (v) flags |= Flag.LineEnd; else flags &= ~Flag.LineEnd; }
306 bool paraend () const { pragma(inline, true); return ((flags&Flag.ParaEnd) != 0); }
307 void paraend (bool v) { pragma(inline, true); if (v) flags |= Flag.ParaEnd; else flags &= ~Flag.ParaEnd; }
308 // note that if word is softhyphen candidate, i have hyphen mark at [wend]
309 // if props.hyphen is set, wend is including that mark, otherwise it isn't
311 uint wstart, wend; // in LayText text buffer
312 LayFontStyle style; // font style
313 uint wordNum; // word number (index in LayText word array)
314 Props propsOrig; // original properties, used for relayouting
315 // calculated values
316 Props props; // effective props after layouting
317 int x; // horizontal word position in line
318 int h; // word height (full)
319 int asc; // ascent (positive)
320 int desc; // descent (negative)
321 int w; // word width, without hyphen and spacing
322 int wsp; // word width with spacing (i.e. with space added at the end)
323 int whyph; // word width with hyphen (i.e. with hyphen mark added at the end)
324 @property int width () const pure nothrow @safe @nogc { pragma(inline, true); return (props.hyphen ? whyph : w); }
325 // width with spacing/hyphen
326 @property int fullwidth () const pure nothrow @safe @nogc { pragma(inline, true); return (props.hyphen ? whyph : props.spaced ? wsp : w); }
327 // space width based on original props
328 @property int spacewidth () const pure nothrow @safe @nogc { pragma(inline, true); return (propsOrig.spaced ? wsp-w : 0); }
329 //FIXME: find better place for this! keep that in separate pool, or something, and look there with word index
330 LayLineStyle just;
331 int paraPad; // to not recalcuate it on each relayouting; set to -1 to recalculate ;-)
335 // ////////////////////////////////////////////////////////////////////////// //
336 // layouted text line
337 struct LayLine {
338 uint wstart, wend; // indicies in word array
339 LayLineStyle just; // line style
340 // calculated properties
341 int x, y, w; // starting x and y positions, width
342 // on finish, layouter will calculate minimal ('cause it is negative) descent
343 int h, desc; // height, descent (negative)
344 @property int wordCount () const pure nothrow @safe @nogc { pragma(inline, true); return cast(int)(wend-wstart); }
348 // ////////////////////////////////////////////////////////////////////////// //
349 // layouted text
350 final class LayText {
351 public:
352 // special control characters
353 enum dchar EndLineCh = 0x2028; // 0x0085 is treated like whitespace
354 enum dchar EndParaCh = 0x2029;
356 private:
357 void ensurePool(ubyte pow2, bool clear, T) (uint want, ref T* ptr, ref uint used, ref uint alloced) {
358 if (want == 0) return;
359 static assert(pow2 < 24, "wtf?!");
360 uint cursz = used*cast(uint)T.sizeof;
361 if (cursz >= int.max/2) throw new Exception("pool overflow");
362 auto lsz = cast(ulong)want*T.sizeof;
363 if (lsz >= int.max/2 || lsz+cursz >= int.max/2) throw new Exception("pool overflow");
364 want = cast(uint)lsz;
365 uint cural = alloced*cast(uint)T.sizeof;
366 if (cursz+want > cural) {
367 import core.stdc.stdlib : realloc;
368 // grow it
369 uint newsz = ((cursz+want)|((1<<pow2)-1))+1;
370 if (newsz >= int.max/2) throw new Exception("pool overflow");
371 auto np = cast(T*)realloc(ptr, newsz);
372 if (np is null) throw new Exception("out of memory for pool");
373 static if (clear) {
374 import core.stdc.string : memset;
375 memset(np+used, 0, newsz-cursz);
377 ptr = np;
378 alloced = newsz/cast(uint)T.sizeof;
382 dchar* ltext;
383 uint charsUsed, charsAllocated;
385 void putChars (const(dchar)[] str...) {
386 import core.stdc.string : memcpy;
387 if (str.length == 0) return;
388 if (str.length > int.max/2) throw new Exception("text too big");
389 ensurePool!(16, false)(str.length, ltext, charsUsed, charsAllocated);
390 memcpy(ltext+charsUsed, str.ptr, cast(uint)str.length*cast(uint)ltext[0].sizeof);
391 charsUsed += cast(uint)str.length;
394 LayWord* words;
395 uint wordsUsed, wordsAllocated;
397 LayWord* allocWord(bool clear=false) () {
398 ensurePool!(16, true)(1, words, wordsUsed, wordsAllocated);
399 auto res = words+wordsUsed;
400 static if (clear) {
401 import core.stdc.string : memset;
402 memset(res, 0, (*res).sizeof);
404 res.wordNum = wordsUsed++;
405 return res;
408 LayLine* lines;
409 uint linesUsed, linesAllocated;
411 LayLine* allocLine(bool clear=false) () {
412 ensurePool!(16, true)(1, lines, linesUsed, linesAllocated);
413 static if (clear) {
414 import core.stdc.string : memset;
415 auto res = lines+(linesUsed++);
416 memset(res, 0, (*res).sizeof);
417 return res;
418 } else {
419 return lines+(linesUsed++);
423 LayLine* lastLine () { pragma(inline, true); return (linesUsed > 0 ? lines+linesUsed-1 : null); }
425 bool lastLineHasWords () { pragma(inline, true); return (linesUsed > 0 ? (lines[linesUsed-1].wend > lines[linesUsed-1].wstart) : false); }
427 // should not be called when there are no lines, or no words in last line
428 LayWord* lastLineLastWord () { pragma(inline, true); return words+lastLine.wend-1; }
430 static struct StyleStackItem {
431 LayFontStyle fs;
432 LayLineStyle ls;
434 StyleStackItem* styleStack;
435 uint ststackUsed, ststackAllocated;
437 public void pushStyles () {
438 ensurePool!(4, false)(1, styleStack, ststackUsed, ststackAllocated);
439 auto si = styleStack+(ststackUsed++);
440 si.fs = newStyle;
441 si.ls = newJust;
444 public void popStyles () {
445 if (ststackUsed == 0) throw new Exception("style stack underflow");
446 auto si = styleStack+(--ststackUsed);
447 newStyle = si.fs;
448 newJust = si.ls;
451 private:
452 bool firstParaLine = true;
453 uint lastWordStart; // in fulltext
454 uint firstWordNotFlushed;
456 @property bool hasWordChars () const pure nothrow @safe @nogc { pragma(inline, true); return (lastWordStart < charsUsed); }
458 private:
459 // current attributes
460 LayLineStyle just; // for current paragraph
461 LayFontStyle style;
462 // user can change this alot, so don't apply that immediately
463 LayFontStyle newStyle;
464 LayLineStyle newJust;
466 private:
467 Utf8Decoder dec;
468 bool lastWasUtf;
469 bool lastWasSoftHypen;
470 int maxWidth; // maximum text width
471 LayFontStash laf;
473 public:
474 int textHeight = 0; // total text height
475 int textWidth = 0; // maximum text width
477 public:
478 // compare function should return (roughly): key-l
479 alias CmpFn = int delegate (LayLine* l) nothrow @nogc;
481 int findLineBinary (scope CmpFn cmpfn) {
482 if (linesUsed == 0) return -1;
483 int bot = 0, i = cast(int)linesUsed-1;
484 while (bot != i) {
485 int mid = i-(i-bot)/2;
486 int cmp = cmpfn(lines+mid);
487 if (cmp < 0) i = mid-1;
488 else if (cmp > 0) bot = mid;
489 else return mid;
491 return (cmpfn(lines+i) == 0 ? i : -1);
494 // find line with this word index
495 int findLineWithWord (uint idx) {
496 return findLineBinary((LayLine* l) {
497 if (idx < l.wstart) return -1;
498 if (idx >= l.wend) return 1;
499 return 0;
503 // find line which contains this coordinate
504 int findLineWithY (int y) {
505 if (linesUsed == 0) return 0;
506 if (y < 0) return 0;
507 if (y >= textHeight) return cast(int)linesUsed-1;
508 auto res = findLineBinary((LayLine* l) {
509 if (y < l.y) return -1;
510 if (y >= l.y+l.h) return 1;
511 return 0;
513 //if (res == -1) { import std.stdio; writeln("*** y=", y, "; th=", textHeight); }
514 assert(res != -1);
515 return res;
518 @property const(dchar)[] wordText (in ref LayWord w) const pure nothrow @trusted @nogc { pragma(inline, true); return ltext[w.wstart..w.wend]; }
520 @property int lineCount () const pure nothrow @safe @nogc { pragma(inline, true); return cast(int)linesUsed; }
522 // word iterator
523 @property auto lineWords (int lidx) {
524 static struct Range {
525 private:
526 LayWord* w;
527 int wordsLeft; // not including current
528 nothrow @trusted @nogc:
529 private:
530 this (LayText lay, int lidx) {
531 if (lidx >= 0 && lidx < lay.linesUsed) {
532 auto ln = lay.lines+lidx;
533 if (ln.wend > ln.wstart) {
534 w = lay.words+ln.wstart;
535 wordsLeft = ln.wend-ln.wstart-1;
539 public:
540 @property bool empty () const pure { pragma(inline, true); return (w is null); }
541 //@property ref LayWord front () pure { pragma(inline, true); assert(w !is null); return *w; }
542 @property ref LayWord front () pure { pragma(inline, true); assert(w !is null); return *w; }
543 void popFront () { if (wordsLeft) { ++w; --wordsLeft; } else w = null; }
544 Range save () { Range res = void; res.w = w; res.wordsLeft = wordsLeft; return res; }
545 @property int length () const pure { pragma(inline, true); return (w !is null ? wordsLeft+1 : 0); }
546 alias opDollar = length;
547 @property LayWord[] opSlice () { return (w !is null ? w[0..wordsLeft+1] : null); }
548 @property LayWord[] opSlice (int lo, int hi) {
549 if (lo < 0) lo = 0;
550 if (w is null || hi <= lo || lo > wordsLeft) return null;
551 if (hi > wordsLeft+1) hi = wordsLeft+1;
552 return w[lo..hi];
555 return Range(this, lidx);
558 LayLine* line (int lidx) { pragma(inline, true); return (lidx >= 0 && lidx < linesUsed ? lines+lidx : null); }
560 public:
561 this (LayFontStash alaf, int awidth) {
562 if (alaf is null) assert(0, "no layout fonts");
563 if (awidth < 1) awidth = 1;
564 laf = alaf;
565 maxWidth = awidth;
568 ~this () { freeMemory(); }
570 void freeMemory () {
571 import core.stdc.stdlib : free;
572 if (lines !is null) { free(lines); lines = null; }
573 if (words !is null) { free(words); words = null; }
574 if (ltext !is null) { free(ltext); ltext = null; }
575 wordsUsed = wordsAllocated = linesUsed = linesAllocated = charsUsed = charsAllocated = 0;
578 @property int width () const pure nothrow @safe @nogc { pragma(inline, true); return maxWidth; }
580 // last flushed word index
581 @property uint lastWordIndex () const pure nothrow @safe @nogc { pragma(inline, true); return (wordsUsed ? wordsUsed-1 : 0); }
583 // current word index
584 @property uint nextWordIndex () const pure nothrow @safe @nogc { pragma(inline, true); return wordsUsed; }
586 @property ref LayFontStyle fontStyle () pure nothrow @safe @nogc { pragma(inline, true); return newStyle; }
587 @property ref LayLineStyle lineStyle () pure nothrow @safe @nogc { pragma(inline, true); return newJust; }
589 @property int fontFaceId (const(char)[] name) {
590 if (laf !is null) {
591 int fid = laf.fontFaceId(name);
592 if (fid >= 0) return fid;
594 throw new Exception("unknown font face '"~name.idup~"'");
597 @property string fontFace (int fid) { pragma(inline, true); return (laf !is null ? laf.fontFace(fid) : null); }
599 void endLine () { put(EndLineCh); }
600 void endPara () { put(EndParaCh); }
602 // add text to layouter
603 void put(T) (const(T)[] str...) if (is(T == char) || is(T == dchar)) {
604 if (str.length == 0) return;
606 dchar curCh; // 0: no more chars
607 usize stpos;
609 static if (is(T == char)) {
610 // utf-8 stream
611 if (!lastWasUtf) { lastWasUtf = true; dec.reset; }
612 void skipCh () @trusted {
613 while (stpos < str.length) {
614 curCh = dec.decode(cast(ubyte)str.ptr[stpos++]);
615 if (curCh <= dchar.max) return;
617 curCh = 0;
619 // load first char
620 skipCh();
621 } else {
622 // dchar stream
623 void skipCh () @trusted {
624 if (stpos < str.length) {
625 curCh = str.ptr[stpos++];
626 if (curCh > dchar.max) curCh = '?';
627 } else {
628 curCh = 0;
631 // load first char
632 if (lastWasUtf) {
633 lastWasUtf = false;
634 if (!dec.complete) curCh = '?'; else skipCh();
635 } else {
636 skipCh();
640 // process stream dchars
641 if (curCh == 0) return;
642 if (!hasWordChars) style = newStyle;
643 if (firstWordNotFlushed >= wordsUsed) just = newJust;
644 while (curCh) {
645 import std.uni;
646 dchar ch = curCh;
647 skipCh();
648 if (ch == EndLineCh || ch == EndParaCh) {
649 lastWasSoftHypen = false;
650 // ignore leading empty lines
651 if (hasWordChars || linesUsed) {
652 LayWord* lw;
653 if (hasWordChars) {
654 // has some word data, flush it now
655 flushWord();
656 lw = words+wordsUsed-1;
657 } else if (wordsUsed == 0) {
658 // create empty word to set attributes on it
659 lw = allocWord();
660 } else {
661 lw = words+wordsUsed-1;
662 // do i need to add empty word for attrs?
663 if (lw.propsOrig.lineend || lw.propsOrig.paraend) lw = allocWord();
665 // fix word properties
666 lw.propsOrig.canbreak = true;
667 lw.propsOrig.spaced = false;
668 lw.propsOrig.hyphen = false;
669 lw.propsOrig.lineend = (ch == EndLineCh);
670 lw.propsOrig.paraend = (ch == EndParaCh);
671 // build layout part
672 flushLines(firstWordNotFlushed, wordsUsed);
673 firstWordNotFlushed = wordsUsed;
675 if (ch == EndParaCh) just = newJust;
676 firstParaLine = (ch == EndParaCh);
677 } else if (ch == 0x00a0) {
678 // non-breaking space
679 lastWasSoftHypen = false;
680 if (hasWordChars && style != newStyle) flushWord();
681 putChars(' ');
682 } else if (ch == 0x0ad) {
683 // soft hyphen
684 if (!lastWasSoftHypen && hasWordChars) {
685 putChars('-');
686 lastWasSoftHypen = true; // word flusher is using this flag
687 flushWord();
689 lastWasSoftHypen = true;
690 } else if (ch <= ' ' || isWhite(ch)) {
691 lastWasSoftHypen = false;
692 if (hasWordChars) {
693 flushWord();
694 auto lw = words+wordsUsed-1;
695 lw.propsOrig.canbreak = true;
696 lw.propsOrig.spaced = true;
697 } else {
698 style = newStyle;
700 } else {
701 lastWasSoftHypen = false;
702 if (ch > dchar.max || ch.isSurrogate || ch.isPrivateUse || ch.isNonCharacter || ch.isMark || ch.isFormat || ch.isControl) ch = '?';
703 if (hasWordChars && style != newStyle) flushWord();
704 putChars(ch);
705 if (isDash(ch) && charsUsed-lastWordStart > 1 && !isDash(ltext[charsUsed-2])) flushWord();
710 void finalize () {
711 flushWord();
712 flushLines(firstWordNotFlushed, wordsUsed);
713 firstWordNotFlushed = wordsUsed;
716 void relayout (int newWidth, bool forced) {
717 if (newWidth < 1) newWidth = 1;
718 if (!forced && newWidth == maxWidth) return;
719 maxWidth = newWidth;
720 linesUsed = 0;
721 if (linesAllocated > 0) {
722 import core.stdc.string : memset;
723 memset(lines, 0, linesAllocated*lines[0].sizeof);
725 uint widx = 0;
726 uint wu = wordsUsed;
727 textWidth = 0;
728 textHeight = 0;
729 firstParaLine = true;
730 scope(exit) firstWordNotFlushed = wu;
731 while (widx < wu) {
732 uint lend = widx;
733 while (lend < wu) {
734 auto w = words+(lend++);
735 if (w.propsOrig.lineend || w.propsOrig.paraend) break;
737 flushLines(widx, lend);
738 //assert(wordsUsed == lend);
739 widx = lend;
740 if (words[widx-1].propsOrig.paraend) firstParaLine = true;
744 public:
745 void save (VFile fl) {
746 fl.rawWriteExact("");
749 public:
750 void dump (VFile fl) const {
751 fl.writeln("LINES: ", linesUsed);
752 foreach (immutable idx, const ref ln; lines[0..linesUsed]) {
753 fl.writeln("LINE #", idx, ": ", ln.wordCount, " words; just=", ln.just.toString, "; jlpad=", ln.just.lpad, "; y=", ln.y, "; h=", ln.h, "; desc=", ln.desc);
754 foreach (immutable widx, const ref w; words[ln.wstart..ln.wend]) {
755 fl.writeln(" WORD #", widx, "(", w.wordNum, ")[", w.wstart, "..", w.wend, "]: ", wordText(w));
756 fl.writeln(" wbreak=", w.props.canbreak, "; wspaced=", w.props.spaced, "; whyphen=", w.props.hyphen, "; style=", w.style.toString);
757 fl.writeln(" x=", w.x, "; w=", w.w, "; h=", w.h, "; asc=", w.asc, "; desc=", w.desc);
762 private:
763 static bool isDash (dchar ch) {
764 pragma(inline, true);
765 return (ch == '-' || (ch >= 0x2013 && ch == 0x2015) || ch == 0x2212);
768 void flushWord () {
769 if (hasWordChars) {
770 auto w = allocWord();
771 w.wstart = lastWordStart;
772 w.wend = charsUsed;
773 //{ import iv.encoding, std.conv : to; writeln("adding word: [", wordText(*w).to!string.recodeToKOI8, "]"); }
774 w.propsOrig.hyphen = lastWasSoftHypen;
775 if (lastWasSoftHypen) {
776 w.propsOrig.canbreak = true;
777 w.propsOrig.spaced = false;
778 --w.wend; // remove hyphen mark (for now)
780 w.style = style;
781 w.props = w.propsOrig;
782 w.props.hyphen = false;
783 // set word dimensions
784 if (w.style.fontface < 0) throw new Exception("invalid font face in word style");
785 laf.setFont(w.style);
786 // i may need spacing later, and anyway most words should be with spacing, so calc it unconditionally
787 if (w.wend > w.wstart) {
788 auto t = wordText(*w);
789 laf.textWidth2(t, &w.w, &w.wsp, (w.propsOrig.hyphen ? &w.whyph : null));
790 if (!w.propsOrig.hyphen) w.whyph = w.w;
791 if (isDash(t[$-1])) { w.propsOrig.canbreak = true; w.props.canbreak = true; }
792 } else {
793 w.w = w.wsp = w.whyph = 0;
795 // calculate ascent, descent and height
796 laf.textMetrics(&w.asc, &w.desc, &w.h);
797 w.just = just;
798 w.paraPad = -1;
799 lastWordStart = charsUsed;
801 style = newStyle;
804 // [curw..endw)"
805 void flushLines (uint curw, uint endw) {
806 if (curw < endw) {
807 debug(xlay_line_flush) writeln("flushing ", endw-curw, " words");
808 uint stline = linesUsed; // reformat from this
809 // fix word styles
810 foreach (ref LayWord w; words[curw..endw]) {
811 if (w.props.hyphen) --w.wend; // remove hyphen mark
812 w.props = w.propsOrig;
813 w.props.hyphen = false;
815 LayLine* ln;
816 LayWord* w = words+curw;
817 while (curw < endw) {
818 debug(xlay_line_flush) writeln(" ", endw-curw, " words left");
819 if (ln is null) {
820 // add line to work with
821 ln = allocLine();
822 ln.wstart = ln.wend = curw;
823 ln.just = w.just;
824 ln.w = just.lpad+just.rpad;
825 // indent first line of paragraph
826 if (firstParaLine) {
827 firstParaLine = false;
828 // left-side or justified lines has paragraph indent
829 if (ln.just.paraIndent > 0 && (just.left || just.justify)) {
830 laf.setFont(w.style);
831 int ind = (w.paraPad < 0 ? laf.spacesWidth(ln.just.paraIndent) : w.paraPad);
832 ln.w += ind;
833 ln.just.lpad += ind;
834 w.paraPad = ind;
835 } else {
836 w.paraPad = 0;
839 //writeln("new line; maxWidth=", maxWidth, "; starting line width=", ln.w);
841 debug(xlay_line_flush) writefln(" (%s:0x%04x) 0x%08x : 0x%08x : 0x%08x : %s", LayLine.sizeof, LayLine.sizeof, cast(uint)lines, cast(uint)ln, cast(uint)(lines+linesUsed-1), cast(int)(ln-((lines+linesUsed-1))));
842 // add words until i hit breaking point
843 // if it will end beyond maximum width, and this line
844 // has some words, flush the line and start new one
845 uint startIndex = curw;
846 int curwdt = ln.w, lastwsp = 0;
847 while (curw < endw) {
848 // add word width with spacing (i will compensate for that after loop)
849 lastwsp = (w.propsOrig.spaced ? w.wsp-w.w : 0);
850 curwdt += w.w+lastwsp;
851 ++curw; // advance counter here...
852 if (w.props.canbreak) break; // done with this span
853 ++w; // ...and word pointer here (skipping one inc at the end ;-)
855 debug(xlay_line_flush) writeln(" ", curw-startIndex, " words processed");
856 // can i add the span? if this is first span in line, add it unconditionally
857 if (ln.wordCount == 0 || curwdt-lastwsp <= maxWidth) {
858 // yay, i can!
859 ln.wend = curw;
860 ln.w = curwdt;
861 ++w; // advance to curw
862 debug(xlay_line_flush) writeln("curwdt=", curwdt, "; maxWidth=", maxWidth, "; wc=", ln.wordCount, "(", ln.wend-ln.wstart, ")");
863 } else {
864 // nope, start new line here
865 debug(xlay_line_flush) writeln("added line with ", ln.wordCount, " words");
866 // last word in the line should not be spaced
867 auto ww = words+ln.wend-1;
868 // compensate for spacing at last word
869 ln.w -= (ww.props.spaced ? ww.wsp-ww.w : 0);
870 ww.props.spaced = false;
871 // and should have hyphen mark if it is necessary
872 if (ww.propsOrig.hyphen) {
873 assert(!ww.props.hyphen);
874 ww.props.hyphen = true;
875 ++ww.wend;
876 // fix line width (word layouter will use that)
877 ln.w += ww.whyph-ww.w;
879 ln = null;
880 curw = startIndex;
881 w = words+curw;
884 debug(xlay_line_flush) writeln("added line with ", ln.wordCount, " words; new lines range: [", stline, "..", linesUsed, "]");
885 debug(xlay_line_flush) writefln("(%s:0x%04x) 0x%08x : 0x%08x : 0x%08x : %s", LayLine.sizeof, LayLine.sizeof, cast(uint)lines, cast(uint)ln, cast(uint)(lines+linesUsed-1), cast(int)(ln-((lines+linesUsed-1))));
886 // last line should not be justified
887 if (ln.just.justify) ln.just.setLeft;
888 // do real word layouting and fix line metrics
889 debug(xlay_line_flush) writeln("added ", linesUsed-stline, " lines");
890 foreach (uint lidx; stline..linesUsed) {
891 debug(xlay_line_flush) writeln(": lidx=", lidx, "; wc=", lines[lidx].wordCount);
892 layoutLine(lidx);
897 // do word layouting and fix line metrics
898 void layoutLine (uint lidx) {
899 import std.algorithm : max, min;
900 assert(lidx < linesUsed);
901 auto ln = lines+lidx;
902 debug(xlay_line_layout) writeln("lidx=", lidx, "; wc=", ln.wordCount);
903 // y position
904 ln.y = (lidx ? ln[-1].y+ln[-1].h : 0);
905 auto lwords = lineWords(lidx);
906 assert(!lwords.empty); // i should have at least one word in each line
907 // line width is calculated for us by `flushLines()`
908 // calculate line metrics and number of words with spacing
909 int lineH, lineDesc, wspCount;
910 foreach (ref LayWord w; lwords.save) {
911 lineH = max(lineH, w.h);
912 lineDesc = min(lineDesc, w.desc);
913 if (w.props.spaced) ++wspCount;
915 // vertical padding; clamp it, as i can't have line over line (it will break too many things)
916 lineH += max(0, ln.just.tpad)+max(0, ln.just.bpad);
917 ln.h = lineH;
918 ln.desc = lineDesc;
919 if (ln.w >= maxWidth) {
920 //writeln("*** ln.w=", ln.w, "; maxWidth=", maxWidth);
921 // way too long; (almost) easy deal
922 // calculate free space to spare in case i'll need to compensate hyphen mark
923 int x = ln.just.lpad, spc = 0;
924 foreach (ref LayWord w; lwords.save) {
925 w.x = x;
926 x += w.fullwidth;
927 if (w.props.spaced) spc += w.wsp-w.w;
929 // if last word ends with hyphen, try to compensate it
930 if (words[ln.wend-1].props.hyphen) {
931 int needspc = ln.w-maxWidth;
932 // no more than 8 pix or 2/3 of free space
933 if (needspc <= 8 && needspc <= spc/3*2) {
934 // compensate (i can do fractional math here, but meh...)
935 while (needspc > 0) {
936 // excellence in coding!
937 foreach_reverse (immutable widx; ln.wstart..ln.wend) {
938 if (words[widx].props.spaced) {
939 --ln.w;
940 foreach (immutable c; widx+1..ln.wend) words[c].x -= 1;
941 if (--needspc == 0) break;
947 } else if (ln.just.justify && wspCount > 0) {
948 // fill the whole line
949 int spc = maxWidth-ln.w; // space left to distribute
950 int xadvsp = spc/wspCount;
951 int frac = spc-xadvsp*wspCount;
952 int x = ln.just.lpad;
953 // no need to save range here, i'll do it in one pass
954 foreach (ref LayWord w; lwords) {
955 w.x = x;
956 x += w.fullwidth;
957 if (w.props.spaced) {
958 x += xadvsp;
959 //spc -= xadvsp;
960 if (frac-- > 0) {
961 ++x;
962 //--spc;
966 //if (x != maxWidth-ln.just.rpad) writeln("x=", x, "; but it should be ", maxWidth-ln.just.rpad, "; spcleft=", spc, "; ln.w=", ln.w, "; maxWidth=", maxWidth-ln.w);
967 //assert(x == maxWidth-ln.just.rpad);
968 } else {
969 int x;
970 if (ln.just.left || ln.just.justify) x = ln.just.lpad;
971 else if (ln.just.right) x = maxWidth-ln.w+ln.just.lpad;
972 else if (ln.just.center) x = (maxWidth-(ln.w-ln.just.lpad-ln.just.rpad))/2;
973 else assert(0, "wtf?!");
974 // no need to save range here, i'll do it in one pass
975 foreach (ref LayWord w; lwords) {
976 w.x = x;
977 x += w.fullwidth;
980 if (ln.h < 1) ln.h = 1;
981 textWidth = max(textWidth, ln.w);
982 textHeight = ln.y+ln.h;
983 debug(xlay_line_layout) writeln("lidx=", lidx, "; wc=", ln.wordCount);