adapted to new nanovg API
[xreader.git] / xlayouter.d
blobcfeb0d54fbc3da2fb24d4632d6e091059907d2db
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 abstract class LayObject {
37 abstract int width ();
38 abstract int spacewidth ();
39 abstract int height ();
40 abstract int ascent (); // should be positive
41 abstract int descent (); // should be negative
42 abstract bool canbreak ();
43 abstract bool spaced ();
44 // y is at baseline
45 abstract void draw (NVGContext ctx, float x, float y);
49 // ////////////////////////////////////////////////////////////////////////// //
50 // this needs such fonts in stash:
51 // text -- normal
52 // texti -- italic
53 // textb -- bold
54 // textz -- italic and bold
55 // mono -- normal
56 // monoi -- italic
57 // monob -- bold
58 // monoz -- italic and bold
59 final class LayFontStash {
60 public:
61 FONScontext* fs;
62 // list of known font faces, should be filled by caller when this object created
63 // DO NOT MODIFY!
64 int[string] fontfaces;
65 string[int] fontfaceids;
67 private:
68 bool killFontStash;
69 bool fontWasSet; // to ensure that first call to `setFont()` will do it's work
70 LayFontStyle lastStyle;
72 public:
73 this () {
74 // create new fontstash
75 FONSparams fontParams;
76 fontParams.width = 1024/*NVG_INIT_FONTIMAGE_SIZE*/;
77 fontParams.height = 1024/*NVG_INIT_FONTIMAGE_SIZE*/;
78 fontParams.flags = FONS_ZERO_TOPLEFT;
79 fs = fonsCreateInternal(&fontParams);
80 if (fs is null) throw new Exception("error creating font stash");
81 killFontStash = true;
82 fs.fonsResetAtlas(1024, 1024);
83 fonsSetSpacing(fs, 0);
84 fonsSetBlur(fs, 0);
85 fonsSetAlign(fs, NVGAlign.Left|NVGAlign.Baseline);
88 ~this () { freeFontStash(); }
90 void freeFontStash () {
91 if (killFontStash && fs !is null) {
92 fs.fonsDeleteInternal();
94 killFontStash = false;
95 fs = null;
98 void addFont(T : const(char)[], TP : const(char)[]) (T name, TP path) {
99 static if (is(T == typeof(null))) {
100 throw new Exception("invalid font face name");
101 } else {
102 if (name.length == 0) throw new Exception("invalid font face name");
103 if (name in fontfaces) throw new Exception("duplicate font '"~name.idup~"'");
104 int fid = fs.fonsAddFont(name, path);
105 if (fid < 0) throw new Exception("font '"~name~"' is not found at '"~path.idup~"'");
106 static if (is(T == string)) {
107 fontfaces[name] = fid;
108 fontfaceids[fid] = name;
109 } else {
110 string n = name.idup;
111 fontfaces[n] = fid;
112 fontfaceids[fid] = n;
117 @property int fontFaceId (const(char)[] name) {
118 if (auto fid = name in fontfaces) return *fid;
119 return -1;
122 @property string fontFace (int fid) {
123 if (auto ff = fid in fontfaceids) return *ff;
124 return null;
127 void setFont() (in auto ref LayFontStyle style) {
128 int fsz = style.fontsize;
129 if (fsz < 1) fsz = 1;
130 if (!fontWasSet || fsz != lastStyle.fontsize || style.fontface != lastStyle.fontface) {
131 if (style.fontface != lastStyle.fontface) fonsSetFont(fs, style.fontface);
132 if (fsz != lastStyle.fontsize) fonsSetSize(fs, fsz);
133 lastStyle = style;
134 lastStyle.fontsize = fsz;
138 int textWidth(T) (const(T)[] str) if (is(T == char) || is(T == dchar)) {
139 import std.algorithm : max;
140 import core.stdc.math : lrintf;
141 float[4] b = void;
142 float adv = fs.fonsTextBounds(0, 0, str, b[]);
143 float w = b[2]-b[0];
144 return lrintf(max(adv, w));
147 int spacesWidth (int count) {
148 import core.stdc.math : lrintf;
149 if (count < 1) return 0;
150 auto it = FonsTextBoundsIterator(fs, 0, 0);
151 it.put(' ');
152 return lrintf(it.advance*count);
155 void textWidth2(T) (const(T)[] str, int* w=null, int* wsp=null, int* whyph=null) if (is(T == char) || is(T == dchar)) {
156 import core.stdc.math : lrintf;
157 import std.algorithm : max;
158 if (w is null && wsp is null && whyph is null) return;
159 float minx, maxx;
160 auto it = FonsTextBoundsIterator(fs, 0, 0);
161 it.put(str);
162 if (w !is null) {
163 it.getHBounds(minx, maxx);
164 *w = lrintf(max(it.advance, maxx-minx));
166 if (wsp !is null && whyph is null) {
167 it.put(" ");
168 it.getHBounds(minx, maxx);
169 *wsp = lrintf(max(it.advance, maxx-minx));
170 } else if (wsp is null && whyph !is null) {
171 it.put(cast(dchar)45);
172 it.getHBounds(minx, maxx);
173 *whyph = lrintf(max(it.advance, maxx-minx));
174 } else if (wsp !is null && whyph !is null) {
175 auto sit = it;
176 it.put(" ");
177 it.getHBounds(minx, maxx);
178 *wsp = lrintf(max(it.advance, maxx-minx));
179 sit.put(cast(dchar)45);
180 sit.getHBounds(minx, maxx);
181 *whyph = lrintf(max(sit.advance, maxx-minx));
185 int textHeight () {
186 import core.stdc.math : lrintf;
187 // use line bounds for height
188 float y0 = void, y1 = void;
189 fs.fonsLineBounds(0, &y0, &y1);
190 return lrintf(y1-y0);
193 void textMetrics (int* asc, int* desc, int* lineh) {
194 import core.stdc.math : lrintf;
195 float a = void, d = void, h = void;
196 fs.fonsVertMetrics(&a, &d, &h);
197 if (asc !is null) *asc = lrintf(a);
198 if (desc !is null) *desc = lrintf(d);
199 if (lineh !is null) *lineh = lrintf(h);
204 // ////////////////////////////////////////////////////////////////////////// //
205 // generic text style
206 align(1) struct LayFontStyle {
207 align(1):
208 enum Flag : uint {
209 Italic = 1<<0,
210 Bold = 1<<1,
211 Strike = 1<<2,
212 Underline = 1<<3,
213 Overline = 1<<4,
215 ubyte flags; // see above
216 int fontface = -1; // i can't use strings here, as this struct inside LayWord will not be GC-scanned
217 int fontsize;
218 uint color = 0xff000000; // AABBGGRR; AA usually ignored by renderer, but i'll keep it anyway
219 string toString () const {
220 import std.format : format;
221 string res = "font:%s;size:%s;color:0x%08X".format(fontface, fontsize, color);
222 if (flags&Flag.Italic) res ~= ";italic";
223 if (flags&Flag.Bold) res ~= ";bold";
224 if (flags&Flag.Strike) res ~= ";strike";
225 if (flags&Flag.Underline) res ~= ";under";
226 if (flags&Flag.Overline) res ~= ";over";
227 return res;
229 mixin({
230 import std.conv : to;
231 import std.ascii : toLower;
232 string res;
233 foreach (string s; __traits(allMembers, Flag)) {
234 //pragma(msg, s);
235 res ~= "@property bool "~s[0].toLower~s[1..$]~" () const pure nothrow @safe @nogc { pragma(inline, true); return ((flags&Flag."~s~") != 0); }\n";
236 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";
238 return res;
239 }());
240 void resetAttrs () pure nothrow @safe @nogc { pragma(inline, true); flags = 0; }
241 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); }
245 // ////////////////////////////////////////////////////////////////////////// //
246 // line align style
247 align(1) struct LayLineStyle {
248 align(1):
249 enum Justify : ubyte {
250 Left,
251 Right,
252 Center,
253 Justify,
255 Justify mode = Justify.Left;
256 short lpad, rpad, tpad, bpad;
257 ubyte paraIndent; // in spaces
258 string toString () const {
259 import std.format : format;
260 string res;
261 final switch (mode) {
262 case Justify.Left: res = "left"; break;
263 case Justify.Right: res = "right"; break;
264 case Justify.Center: res = "center"; break;
265 case Justify.Justify: res = "justify"; break;
267 if (lpad) res ~= ";lpad:%s".format(lpad);
268 if (rpad) res ~= ";rpad:%s".format(rpad);
269 if (tpad) res ~= ";tpad:%s".format(tpad);
270 if (bpad) res ~= ";bpad:%s".format(bpad);
271 return res;
273 mixin({
274 import std.conv : to;
275 import std.ascii : toLower;
276 string res;
277 foreach (string s; __traits(allMembers, Justify)) {
278 //pragma(msg, s);
279 res ~= "@property bool "~s[0].toLower~s[1..$]~" () const pure nothrow @safe @nogc { pragma(inline, true); return (mode == Justify."~s~"); }\n";
280 res ~= "ref LayLineStyle set"~s~" () pure nothrow @safe @nogc { mode = Justify."~s~"; return this; }\n";
282 return res;
283 }());
284 bool opEquals() (in auto ref LayLineStyle s) const pure nothrow @safe @nogc { pragma(inline, true); return (mode == s.mode && lpad == s.lpad); }
285 @property pure nothrow @safe @nogc {
286 int leftpad () const { pragma(inline, true); return lpad; }
287 void leftpad (int v) { pragma(inline, true); lpad = (v < short.min ? short.min : v > short.max ? short.max : cast(short)v); }
288 int rightpad () const { pragma(inline, true); return rpad; }
289 void rightpad (int v) { pragma(inline, true); rpad = (v < short.min ? short.min : v > short.max ? short.max : cast(short)v); }
290 int toppad () const { pragma(inline, true); return tpad; }
291 void toppad (int v) { pragma(inline, true); tpad = (v < 0 ? 0 : v > short.max ? short.max : cast(short)v); }
292 int bottompad () const { pragma(inline, true); return bpad; }
293 void bottompad (int v) { pragma(inline, true); bpad = (v < 0 ? 0 : v > short.max ? short.max : cast(short)v); }
298 // ////////////////////////////////////////////////////////////////////////// //
299 // layouted text word
300 align(1) struct LayWord {
301 align(1):
302 static align(1) struct Props {
303 align(1):
304 enum Flag : uint {
305 CanBreak = 1<<0, // can i break line at this word?
306 Spaced = 1<<1, // should this word be whitespaced at the end?
307 Hypen = 1<<2, // if i'll break at this word, should i add hyphen mark?
308 LineEnd = 1<<3, // this word ends current line
309 ParaEnd = 1<<4, // this word ends current paragraph (and, implicitly, line)
310 Object = 1<<5, // dchar at wstart is actually object index in object array
312 ubyte flags; // see above
313 @property pure nothrow @safe @nogc:
314 bool canbreak () const { pragma(inline, true); return ((flags&Flag.CanBreak) != 0); }
315 void canbreak (bool v) { pragma(inline, true); if (v) flags |= Flag.CanBreak; else flags &= ~Flag.CanBreak; }
316 bool spaced () const { pragma(inline, true); return ((flags&Flag.Spaced) != 0); }
317 void spaced (bool v) { pragma(inline, true); if (v) flags |= Flag.Spaced; else flags &= ~Flag.Spaced; }
318 bool hyphen () const { pragma(inline, true); return ((flags&Flag.Hypen) != 0); }
319 void hyphen (bool v) { pragma(inline, true); if (v) flags |= Flag.Hypen; else flags &= ~Flag.Hypen; }
320 bool lineend () const { pragma(inline, true); return ((flags&Flag.LineEnd) != 0); }
321 void lineend (bool v) { pragma(inline, true); if (v) flags |= Flag.LineEnd; else flags &= ~Flag.LineEnd; }
322 bool paraend () const { pragma(inline, true); return ((flags&Flag.ParaEnd) != 0); }
323 void paraend (bool v) { pragma(inline, true); if (v) flags |= Flag.ParaEnd; else flags &= ~Flag.ParaEnd; }
324 // note that if word is softhyphen candidate, i have hyphen mark at [wend]
325 // if props.hyphen is set, wend is including that mark, otherwise it isn't
326 bool object () const { pragma(inline, true); return ((flags&Flag.Object) != 0); }
327 void object (bool v) { pragma(inline, true); if (v) flags |= Flag.Object; else flags &= ~Flag.Object; }
329 uint wstart, wend; // in LayText text buffer
330 LayFontStyle style; // font style
331 uint wordNum; // word number (index in LayText word array)
332 Props propsOrig; // original properties, used for relayouting
333 // calculated values
334 Props props; // effective props after layouting
335 int x; // horizontal word position in line
336 int h; // word height (full)
337 int asc; // ascent (positive)
338 int desc; // descent (negative)
339 int w; // word width, without hyphen and spacing
340 int wsp; // word width with spacing (i.e. with space added at the end)
341 int whyph; // word width with hyphen (i.e. with hyphen mark added at the end)
342 @property int width () const pure nothrow @safe @nogc { pragma(inline, true); return (props.hyphen ? whyph : w); }
343 // width with spacing/hyphen
344 @property int fullwidth () const pure nothrow @safe @nogc { pragma(inline, true); return (props.hyphen ? whyph : props.spaced ? wsp : w); }
345 // space width based on original props
346 @property int spacewidth () const pure nothrow @safe @nogc { pragma(inline, true); return (propsOrig.spaced ? wsp-w : 0); }
347 //FIXME: find better place for this! keep that in separate pool, or something, and look there with word index
348 LayLineStyle just;
349 int paraPad; // to not recalcuate it on each relayouting; set to -1 to recalculate ;-)
350 @property int objectIdx () const pure nothrow @safe @nogc { pragma(inline, true); return (propsOrig.object ? wstart : -1); }
354 // ////////////////////////////////////////////////////////////////////////// //
355 // layouted text line
356 struct LayLine {
357 uint wstart, wend; // indicies in word array
358 LayLineStyle just; // line style
359 // calculated properties
360 int x, y, w; // starting x and y positions, width
361 // on finish, layouter will calculate minimal ('cause it is negative) descent
362 int h, desc; // height, descent (negative)
363 @property int wordCount () const pure nothrow @safe @nogc { pragma(inline, true); return cast(int)(wend-wstart); }
367 // ////////////////////////////////////////////////////////////////////////// //
368 // layouted text
369 final class LayText {
370 public:
371 // special control characters
372 enum dchar EndLineCh = 0x2028; // 0x0085 is treated like whitespace
373 enum dchar EndParaCh = 0x2029;
375 private:
376 void ensurePool(ubyte pow2, bool clear, T) (uint want, ref T* ptr, ref uint used, ref uint alloced) {
377 if (want == 0) return;
378 static assert(pow2 < 24, "wtf?!");
379 uint cursz = used*cast(uint)T.sizeof;
380 if (cursz >= int.max/2) throw new Exception("pool overflow");
381 auto lsz = cast(ulong)want*T.sizeof;
382 if (lsz >= int.max/2 || lsz+cursz >= int.max/2) throw new Exception("pool overflow");
383 want = cast(uint)lsz;
384 uint cural = alloced*cast(uint)T.sizeof;
385 if (cursz+want > cural) {
386 import core.stdc.stdlib : realloc;
387 // grow it
388 uint newsz = ((cursz+want)|((1<<pow2)-1))+1;
389 if (newsz >= int.max/2) throw new Exception("pool overflow");
390 auto np = cast(T*)realloc(ptr, newsz);
391 if (np is null) throw new Exception("out of memory for pool");
392 static if (clear) {
393 import core.stdc.string : memset;
394 memset(np+used, 0, newsz-cursz);
396 ptr = np;
397 alloced = newsz/cast(uint)T.sizeof;
401 dchar* ltext;
402 uint charsUsed, charsAllocated;
404 void putChars (const(dchar)[] str...) {
405 import core.stdc.string : memcpy;
406 if (str.length == 0) return;
407 if (str.length > int.max/2) throw new Exception("text too big");
408 ensurePool!(16, false)(str.length, ltext, charsUsed, charsAllocated);
409 memcpy(ltext+charsUsed, str.ptr, cast(uint)str.length*cast(uint)ltext[0].sizeof);
410 charsUsed += cast(uint)str.length;
413 LayWord* words;
414 uint wordsUsed, wordsAllocated;
416 LayWord* allocWord(bool clear=false) () {
417 ensurePool!(16, true)(1, words, wordsUsed, wordsAllocated);
418 auto res = words+wordsUsed;
419 static if (clear) {
420 import core.stdc.string : memset;
421 memset(res, 0, (*res).sizeof);
423 res.wordNum = wordsUsed++;
424 return res;
427 LayLine* lines;
428 uint linesUsed, linesAllocated;
430 LayLine* allocLine(bool clear=false) () {
431 ensurePool!(16, true)(1, lines, linesUsed, linesAllocated);
432 static if (clear) {
433 import core.stdc.string : memset;
434 auto res = lines+(linesUsed++);
435 memset(res, 0, (*res).sizeof);
436 return res;
437 } else {
438 return lines+(linesUsed++);
442 LayLine* lastLine () { pragma(inline, true); return (linesUsed > 0 ? lines+linesUsed-1 : null); }
444 bool lastLineHasWords () { pragma(inline, true); return (linesUsed > 0 ? (lines[linesUsed-1].wend > lines[linesUsed-1].wstart) : false); }
446 // should not be called when there are no lines, or no words in last line
447 LayWord* lastLineLastWord () { pragma(inline, true); return words+lastLine.wend-1; }
449 static struct StyleStackItem {
450 LayFontStyle fs;
451 LayLineStyle ls;
453 StyleStackItem* styleStack;
454 uint ststackUsed, ststackAllocated;
456 public void pushStyles () {
457 ensurePool!(4, false)(1, styleStack, ststackUsed, ststackAllocated);
458 auto si = styleStack+(ststackUsed++);
459 si.fs = newStyle;
460 si.ls = newJust;
463 public void popStyles () {
464 if (ststackUsed == 0) throw new Exception("style stack underflow");
465 auto si = styleStack+(--ststackUsed);
466 newStyle = si.fs;
467 newJust = si.ls;
470 private:
471 bool firstParaLine = true;
472 uint lastWordStart; // in fulltext
473 uint firstWordNotFlushed;
475 @property bool hasWordChars () const pure nothrow @safe @nogc { pragma(inline, true); return (lastWordStart < charsUsed); }
477 private:
478 // current attributes
479 LayLineStyle just; // for current paragraph
480 LayFontStyle style;
481 // user can change this alot, so don't apply that immediately
482 LayFontStyle newStyle;
483 LayLineStyle newJust;
485 private:
486 Utf8Decoder dec;
487 bool lastWasUtf;
488 bool lastWasSoftHypen;
489 int maxWidth; // maximum text width
490 LayFontStash laf;
492 public:
493 int textHeight = 0; // total text height
494 int textWidth = 0; // maximum text width
496 public:
497 // compare function should return (roughly): key-l
498 alias CmpFn = int delegate (LayLine* l) nothrow @nogc;
500 int findLineBinary (scope CmpFn cmpfn) {
501 if (linesUsed == 0) return -1;
502 int bot = 0, i = cast(int)linesUsed-1;
503 while (bot != i) {
504 int mid = i-(i-bot)/2;
505 int cmp = cmpfn(lines+mid);
506 if (cmp < 0) i = mid-1;
507 else if (cmp > 0) bot = mid;
508 else return mid;
510 return (cmpfn(lines+i) == 0 ? i : -1);
513 // find line with this word index
514 int findLineWithWord (uint idx) {
515 return findLineBinary((LayLine* l) {
516 if (idx < l.wstart) return -1;
517 if (idx >= l.wend) return 1;
518 return 0;
522 // find line which contains this coordinate
523 int findLineWithY (int y) {
524 if (linesUsed == 0) return 0;
525 if (y < 0) return 0;
526 if (y >= textHeight) return cast(int)linesUsed-1;
527 auto res = findLineBinary((LayLine* l) {
528 if (y < l.y) return -1;
529 if (y >= l.y+l.h) return 1;
530 return 0;
532 //if (res == -1) { import std.stdio; writeln("*** y=", y, "; th=", textHeight); }
533 assert(res != -1);
534 return res;
537 @property const(dchar)[] wordText (in ref LayWord w) const pure nothrow @trusted @nogc { pragma(inline, true); return ltext[w.wstart..w.wend]; }
539 @property int lineCount () const pure nothrow @safe @nogc { pragma(inline, true); return cast(int)linesUsed; }
541 // word iterator
542 @property auto lineWords (int lidx) {
543 static struct Range {
544 private:
545 LayWord* w;
546 int wordsLeft; // not including current
547 nothrow @trusted @nogc:
548 private:
549 this (LayText lay, int lidx) {
550 if (lidx >= 0 && lidx < lay.linesUsed) {
551 auto ln = lay.lines+lidx;
552 if (ln.wend > ln.wstart) {
553 w = lay.words+ln.wstart;
554 wordsLeft = ln.wend-ln.wstart-1;
558 public:
559 @property bool empty () const pure { pragma(inline, true); return (w is null); }
560 //@property ref LayWord front () pure { pragma(inline, true); assert(w !is null); return *w; }
561 @property ref LayWord front () pure { pragma(inline, true); assert(w !is null); return *w; }
562 void popFront () { if (wordsLeft) { ++w; --wordsLeft; } else w = null; }
563 Range save () { Range res = void; res.w = w; res.wordsLeft = wordsLeft; return res; }
564 @property int length () const pure { pragma(inline, true); return (w !is null ? wordsLeft+1 : 0); }
565 alias opDollar = length;
566 @property LayWord[] opSlice () { return (w !is null ? w[0..wordsLeft+1] : null); }
567 @property LayWord[] opSlice (int lo, int hi) {
568 if (lo < 0) lo = 0;
569 if (w is null || hi <= lo || lo > wordsLeft) return null;
570 if (hi > wordsLeft+1) hi = wordsLeft+1;
571 return w[lo..hi];
574 return Range(this, lidx);
577 LayLine* line (int lidx) { pragma(inline, true); return (lidx >= 0 && lidx < linesUsed ? lines+lidx : null); }
579 public:
580 LayObject[] objects;
582 public:
583 this (LayFontStash alaf, int awidth) {
584 if (alaf is null) assert(0, "no layout fonts");
585 if (awidth < 1) awidth = 1;
586 laf = alaf;
587 maxWidth = awidth;
590 ~this () { freeMemory(); }
592 void freeMemory () {
593 import core.stdc.stdlib : free;
594 if (lines !is null) { free(lines); lines = null; }
595 if (words !is null) { free(words); words = null; }
596 if (ltext !is null) { free(ltext); ltext = null; }
597 wordsUsed = wordsAllocated = linesUsed = linesAllocated = charsUsed = charsAllocated = 0;
600 @property int width () const pure nothrow @safe @nogc { pragma(inline, true); return maxWidth; }
602 // last flushed word index
603 @property uint lastWordIndex () const pure nothrow @safe @nogc { pragma(inline, true); return (wordsUsed ? wordsUsed-1 : 0); }
605 // current word index
606 @property uint nextWordIndex () const pure nothrow @safe @nogc { pragma(inline, true); return wordsUsed; }
608 @property ref LayFontStyle fontStyle () pure nothrow @safe @nogc { pragma(inline, true); return newStyle; }
609 @property ref LayLineStyle lineStyle () pure nothrow @safe @nogc { pragma(inline, true); return newJust; }
611 @property int fontFaceId (const(char)[] name) {
612 if (laf !is null) {
613 int fid = laf.fontFaceId(name);
614 if (fid >= 0) return fid;
616 throw new Exception("unknown font face '"~name.idup~"'");
619 @property string fontFace (int fid) { pragma(inline, true); return (laf !is null ? laf.fontFace(fid) : null); }
621 void endLine () { put(EndLineCh); }
622 void endPara () { put(EndParaCh); }
624 void putObject (LayObject obj) {
625 flushWord();
626 lastWasSoftHypen = false;
627 if (obj is null) return;
628 if (objects.length >= int.max/2) throw new Exception("too many objects");
629 just = newJust;
630 // create special word
631 auto w = allocWord();
632 w.wstart = cast(dchar)objects.length; // store object index
633 w.wend = 0;
634 objects ~= obj;
635 w.style = style;
636 w.propsOrig.object = true;
637 w.propsOrig.spaced = obj.spaced;
638 w.propsOrig.canbreak = obj.canbreak;
639 w.props = w.propsOrig;
640 w.w = obj.width;
641 w.whyph = w.wsp = w.w+obj.spacewidth;
642 w.h = obj.height;
643 w.asc = obj.ascent;
644 if (w.asc < 0) throw new Exception("object ascent should be positive");
645 w.desc = obj.descent;
646 if (w.desc > 0) throw new Exception("object descent should be negative");
647 w.just = just;
648 w.paraPad = -1;
651 // add text to layouter
652 void put(T) (const(T)[] str...) if (is(T == char) || is(T == dchar)) {
653 if (str.length == 0) return;
655 dchar curCh; // 0: no more chars
656 usize stpos;
658 static if (is(T == char)) {
659 // utf-8 stream
660 if (!lastWasUtf) { lastWasUtf = true; dec.reset; }
661 void skipCh () @trusted {
662 while (stpos < str.length) {
663 curCh = dec.decode(cast(ubyte)str.ptr[stpos++]);
664 if (curCh <= dchar.max) return;
666 curCh = 0;
668 // load first char
669 skipCh();
670 } else {
671 // dchar stream
672 void skipCh () @trusted {
673 if (stpos < str.length) {
674 curCh = str.ptr[stpos++];
675 if (curCh > dchar.max) curCh = '?';
676 } else {
677 curCh = 0;
680 // load first char
681 if (lastWasUtf) {
682 lastWasUtf = false;
683 if (!dec.complete) curCh = '?'; else skipCh();
684 } else {
685 skipCh();
689 // process stream dchars
690 if (curCh == 0) return;
691 if (!hasWordChars) style = newStyle;
692 if (firstWordNotFlushed >= wordsUsed) just = newJust;
693 while (curCh) {
694 import std.uni;
695 dchar ch = curCh;
696 skipCh();
697 if (ch == EndLineCh || ch == EndParaCh) {
698 lastWasSoftHypen = false;
699 // ignore leading empty lines
700 if (hasWordChars || linesUsed) {
701 LayWord* lw;
702 if (hasWordChars) {
703 // has some word data, flush it now
704 flushWord();
705 lw = words+wordsUsed-1;
706 } else if (wordsUsed == 0) {
707 // create empty word to set attributes on it
708 lw = allocWord();
709 } else {
710 lw = words+wordsUsed-1;
711 // do i need to add empty word for attrs?
712 if (lw.propsOrig.lineend || lw.propsOrig.paraend) lw = allocWord();
714 // fix word properties
715 lw.propsOrig.canbreak = true;
716 lw.propsOrig.spaced = false;
717 lw.propsOrig.hyphen = false;
718 lw.propsOrig.lineend = (ch == EndLineCh);
719 lw.propsOrig.paraend = (ch == EndParaCh);
720 // build layout part
721 flushLines(firstWordNotFlushed, wordsUsed);
722 firstWordNotFlushed = wordsUsed;
724 /*if (ch == EndParaCh)*/ just = newJust;
725 firstParaLine = (ch == EndParaCh);
726 } else if (ch == 0x00a0) {
727 // non-breaking space
728 lastWasSoftHypen = false;
729 if (hasWordChars && style != newStyle) flushWord();
730 putChars(' ');
731 } else if (ch == 0x0ad) {
732 // soft hyphen
733 if (!lastWasSoftHypen && hasWordChars) {
734 putChars('-');
735 lastWasSoftHypen = true; // word flusher is using this flag
736 flushWord();
738 lastWasSoftHypen = true;
739 } else if (ch <= ' ' || isWhite(ch)) {
740 lastWasSoftHypen = false;
741 if (hasWordChars) {
742 flushWord();
743 auto lw = words+wordsUsed-1;
744 lw.propsOrig.canbreak = true;
745 lw.propsOrig.spaced = true;
746 } else {
747 style = newStyle;
749 } else {
750 lastWasSoftHypen = false;
751 if (ch > dchar.max || ch.isSurrogate || ch.isPrivateUse || ch.isNonCharacter || ch.isMark || ch.isFormat || ch.isControl) ch = '?';
752 if (hasWordChars && style != newStyle) flushWord();
753 putChars(ch);
754 if (isDash(ch) && charsUsed-lastWordStart > 1 && !isDash(ltext[charsUsed-2])) flushWord();
759 void finalize () {
760 flushWord();
761 flushLines(firstWordNotFlushed, wordsUsed);
762 firstWordNotFlushed = wordsUsed;
765 void relayout (int newWidth, bool forced) {
766 if (newWidth < 1) newWidth = 1;
767 if (!forced && newWidth == maxWidth) return;
768 maxWidth = newWidth;
769 linesUsed = 0;
770 if (linesAllocated > 0) {
771 import core.stdc.string : memset;
772 memset(lines, 0, linesAllocated*lines[0].sizeof);
774 uint widx = 0;
775 uint wu = wordsUsed;
776 textWidth = 0;
777 textHeight = 0;
778 firstParaLine = true;
779 scope(exit) firstWordNotFlushed = wu;
780 while (widx < wu) {
781 uint lend = widx;
782 while (lend < wu) {
783 auto w = words+(lend++);
784 if (w.propsOrig.lineend || w.propsOrig.paraend) break;
786 flushLines(widx, lend);
787 //assert(wordsUsed == lend);
788 widx = lend;
789 if (words[widx-1].propsOrig.paraend) firstParaLine = true;
793 public:
794 void save (VFile fl) {
795 fl.rawWriteExact("");
798 public:
799 void dump (VFile fl) const {
800 fl.writeln("LINES: ", linesUsed);
801 foreach (immutable idx, const ref ln; lines[0..linesUsed]) {
802 fl.writeln("LINE #", idx, ": ", ln.wordCount, " words; just=", ln.just.toString, "; jlpad=", ln.just.lpad, "; y=", ln.y, "; h=", ln.h, "; desc=", ln.desc);
803 foreach (immutable widx, const ref w; words[ln.wstart..ln.wend]) {
804 fl.writeln(" WORD #", widx, "(", w.wordNum, ")[", w.wstart, "..", w.wend, "]: ", wordText(w));
805 fl.writeln(" wbreak=", w.props.canbreak, "; wspaced=", w.props.spaced, "; whyphen=", w.props.hyphen, "; style=", w.style.toString);
806 fl.writeln(" x=", w.x, "; w=", w.w, "; h=", w.h, "; asc=", w.asc, "; desc=", w.desc);
811 private:
812 static bool isDash (dchar ch) {
813 pragma(inline, true);
814 return (ch == '-' || (ch >= 0x2013 && ch == 0x2015) || ch == 0x2212);
817 void flushWord () {
818 if (hasWordChars) {
819 auto w = allocWord();
820 w.wstart = lastWordStart;
821 w.wend = charsUsed;
822 //{ import iv.encoding, std.conv : to; writeln("adding word: [", wordText(*w).to!string.recodeToKOI8, "]"); }
823 w.propsOrig.hyphen = lastWasSoftHypen;
824 if (lastWasSoftHypen) {
825 w.propsOrig.canbreak = true;
826 w.propsOrig.spaced = false;
827 --w.wend; // remove hyphen mark (for now)
829 w.style = style;
830 w.props = w.propsOrig;
831 w.props.hyphen = false;
832 // set word dimensions
833 if (w.style.fontface < 0) throw new Exception("invalid font face in word style");
834 laf.setFont(w.style);
835 // i may need spacing later, and anyway most words should be with spacing, so calc it unconditionally
836 if (w.wend > w.wstart) {
837 auto t = wordText(*w);
838 laf.textWidth2(t, &w.w, &w.wsp, (w.propsOrig.hyphen ? &w.whyph : null));
839 if (!w.propsOrig.hyphen) w.whyph = w.w;
840 if (isDash(t[$-1])) { w.propsOrig.canbreak = true; w.props.canbreak = true; }
841 } else {
842 w.w = w.wsp = w.whyph = 0;
844 // calculate ascent, descent and height
845 laf.textMetrics(&w.asc, &w.desc, &w.h);
846 w.just = just;
847 w.paraPad = -1;
848 lastWordStart = charsUsed;
850 style = newStyle;
853 // [curw..endw)"
854 void flushLines (uint curw, uint endw) {
855 if (curw < endw) {
856 debug(xlay_line_flush) writeln("flushing ", endw-curw, " words");
857 uint stline = linesUsed; // reformat from this
858 // fix word styles
859 foreach (ref LayWord w; words[curw..endw]) {
860 if (w.props.hyphen) --w.wend; // remove hyphen mark
861 w.props = w.propsOrig;
862 w.props.hyphen = false;
864 LayLine* ln;
865 LayWord* w = words+curw;
866 while (curw < endw) {
867 debug(xlay_line_flush) writeln(" ", endw-curw, " words left");
868 if (ln is null) {
869 // add line to work with
870 ln = allocLine();
871 ln.wstart = ln.wend = curw;
872 ln.just = w.just;
873 ln.w = just.lpad+just.rpad;
874 // indent first line of paragraph
875 if (firstParaLine) {
876 firstParaLine = false;
877 // left-side or justified lines has paragraph indent
878 if (ln.just.paraIndent > 0 && (just.left || just.justify)) {
879 laf.setFont(w.style);
880 int ind = (w.paraPad < 0 ? laf.spacesWidth(ln.just.paraIndent) : w.paraPad);
881 ln.w += ind;
882 ln.just.lpad += ind;
883 w.paraPad = ind;
884 } else {
885 w.paraPad = 0;
888 //writeln("new line; maxWidth=", maxWidth, "; starting line width=", ln.w);
890 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))));
891 // add words until i hit breaking point
892 // if it will end beyond maximum width, and this line
893 // has some words, flush the line and start new one
894 uint startIndex = curw;
895 int curwdt = ln.w, lastwsp = 0;
896 while (curw < endw) {
897 // add word width with spacing (i will compensate for that after loop)
898 lastwsp = (w.propsOrig.spaced ? w.wsp-w.w : 0);
899 curwdt += w.w+lastwsp;
900 ++curw; // advance counter here...
901 if (w.props.canbreak) break; // done with this span
902 ++w; // ...and word pointer here (skipping one inc at the end ;-)
904 debug(xlay_line_flush) writeln(" ", curw-startIndex, " words processed");
905 // can i add the span? if this is first span in line, add it unconditionally
906 if (ln.wordCount == 0 || curwdt-lastwsp <= maxWidth) {
907 // yay, i can!
908 ln.wend = curw;
909 ln.w = curwdt;
910 ++w; // advance to curw
911 debug(xlay_line_flush) writeln("curwdt=", curwdt, "; maxWidth=", maxWidth, "; wc=", ln.wordCount, "(", ln.wend-ln.wstart, ")");
912 } else {
913 // nope, start new line here
914 debug(xlay_line_flush) writeln("added line with ", ln.wordCount, " words");
915 // last word in the line should not be spaced
916 auto ww = words+ln.wend-1;
917 // compensate for spacing at last word
918 ln.w -= (ww.props.spaced ? ww.wsp-ww.w : 0);
919 ww.props.spaced = false;
920 // and should have hyphen mark if it is necessary
921 if (ww.propsOrig.hyphen) {
922 assert(!ww.props.hyphen);
923 ww.props.hyphen = true;
924 ++ww.wend;
925 // fix line width (word layouter will use that)
926 ln.w += ww.whyph-ww.w;
928 ln = null;
929 curw = startIndex;
930 w = words+curw;
933 debug(xlay_line_flush) writeln("added line with ", ln.wordCount, " words; new lines range: [", stline, "..", linesUsed, "]");
934 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))));
935 // last line should not be justified
936 if (ln.just.justify) ln.just.setLeft;
937 // do real word layouting and fix line metrics
938 debug(xlay_line_flush) writeln("added ", linesUsed-stline, " lines");
939 foreach (uint lidx; stline..linesUsed) {
940 debug(xlay_line_flush) writeln(": lidx=", lidx, "; wc=", lines[lidx].wordCount);
941 layoutLine(lidx);
946 // do word layouting and fix line metrics
947 void layoutLine (uint lidx) {
948 import std.algorithm : max, min;
949 assert(lidx < linesUsed);
950 auto ln = lines+lidx;
951 debug(xlay_line_layout) writeln("lidx=", lidx, "; wc=", ln.wordCount);
952 // y position
953 ln.y = (lidx ? ln[-1].y+ln[-1].h : 0);
954 auto lwords = lineWords(lidx);
955 assert(!lwords.empty); // i should have at least one word in each line
956 // line width is calculated for us by `flushLines()`
957 // calculate line metrics and number of words with spacing
958 int lineH, lineDesc, wspCount;
959 foreach (ref LayWord w; lwords.save) {
960 lineH = max(lineH, w.h);
961 lineDesc = min(lineDesc, w.desc);
962 if (w.props.spaced) ++wspCount;
964 // vertical padding; clamp it, as i can't have line over line (it will break too many things)
965 lineH += max(0, ln.just.tpad)+max(0, ln.just.bpad);
966 ln.h = lineH;
967 ln.desc = lineDesc;
968 if (ln.w >= maxWidth) {
969 //writeln("*** ln.w=", ln.w, "; maxWidth=", maxWidth);
970 // way too long; (almost) easy deal
971 // calculate free space to spare in case i'll need to compensate hyphen mark
972 int x = ln.just.lpad, spc = 0;
973 foreach (ref LayWord w; lwords.save) {
974 w.x = x;
975 x += w.fullwidth;
976 if (w.props.spaced) spc += w.wsp-w.w;
978 // if last word ends with hyphen, try to compensate it
979 if (words[ln.wend-1].props.hyphen) {
980 int needspc = ln.w-maxWidth;
981 // no more than 8 pix or 2/3 of free space
982 if (needspc <= 8 && needspc <= spc/3*2) {
983 // compensate (i can do fractional math here, but meh...)
984 while (needspc > 0) {
985 // excellence in coding!
986 foreach_reverse (immutable widx; ln.wstart..ln.wend) {
987 if (words[widx].props.spaced) {
988 --ln.w;
989 foreach (immutable c; widx+1..ln.wend) words[c].x -= 1;
990 if (--needspc == 0) break;
996 } else if (ln.just.justify && wspCount > 0) {
997 // fill the whole line
998 int spc = maxWidth-ln.w; // space left to distribute
999 int xadvsp = spc/wspCount;
1000 int frac = spc-xadvsp*wspCount;
1001 int x = ln.just.lpad;
1002 // no need to save range here, i'll do it in one pass
1003 foreach (ref LayWord w; lwords) {
1004 w.x = x;
1005 x += w.fullwidth;
1006 if (w.props.spaced) {
1007 x += xadvsp;
1008 //spc -= xadvsp;
1009 if (frac-- > 0) {
1010 ++x;
1011 //--spc;
1015 //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);
1016 //assert(x == maxWidth-ln.just.rpad);
1017 } else {
1018 int x;
1019 if (ln.just.left || ln.just.justify) x = ln.just.lpad;
1020 else if (ln.just.right) x = maxWidth-ln.w+ln.just.lpad;
1021 else if (ln.just.center) x = (maxWidth-(ln.w-ln.just.lpad-ln.just.rpad))/2;
1022 else assert(0, "wtf?!");
1023 // no need to save range here, i'll do it in one pass
1024 foreach (ref LayWord w; lwords) {
1025 w.x = x;
1026 x += w.fullwidth;
1029 if (ln.h < 1) ln.h = 1;
1030 textWidth = max(textWidth, ln.w);
1031 textHeight = ln.y+ln.h;
1032 debug(xlay_line_layout) writeln("lidx=", lidx, "; wc=", ln.wordCount);