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/>.
22 import iv
.nanovg
.oui
.blendish
;
29 version(laytest
) import iv
.encoding
;
30 version(aliced
) {} else private alias usize
= size_t
;
32 private int lrintf (float f
) { pragma(inline
, true); return cast(int)(f
+0.5); }
34 import core
.stdc
.math
: lrintf
;
37 // ////////////////////////////////////////////////////////////////////////// //
38 abstract class LayObject
{
39 abstract int width ();
40 abstract int spacewidth ();
41 abstract int height ();
42 abstract int ascent (); // should be positive
43 abstract int descent (); // should be negative
44 abstract bool canbreak ();
45 abstract bool spaced ();
47 abstract void draw (NVGContext ctx
, float x
, float y
);
51 // ////////////////////////////////////////////////////////////////////////// //
52 // this needs such fonts in stash:
56 // textz -- italic and bold
60 // monoz -- italic and bold
61 final class LayFontStash
{
64 // list of known font faces, should be filled by caller when this object created
66 int[string
] fontfaces
;
67 string
[int] fontfaceids
;
71 bool fontWasSet
; // to ensure that first call to `setFont()` will do it's work
72 LayFontStyle lastStyle
;
76 // create new fontstash
77 FONSparams fontParams
;
78 fontParams
.width
= 1024/*NVG_INIT_FONTIMAGE_SIZE*/;
79 fontParams
.height
= 1024/*NVG_INIT_FONTIMAGE_SIZE*/;
80 fontParams
.flags
= FONS_ZERO_TOPLEFT
;
81 fs
= fonsCreateInternal(&fontParams
);
82 if (fs
is null) throw new Exception("error creating font stash");
84 fs
.fonsResetAtlas(1024, 1024);
85 fonsSetSpacing(fs
, 0);
87 fonsSetAlign(fs
, NVGTextAlign(NVGTextAlign
.H
.Left
, NVGTextAlign
.V
.Baseline
));
90 ~this () { freeFontStash(); }
92 void freeFontStash () {
93 if (killFontStash
&& fs
!is null) {
94 fs
.fonsDeleteInternal();
96 killFontStash
= false;
100 void addFont(T
: const(char)[], TP
: const(char)[]) (T name
, TP path
) {
101 static if (is(T
== typeof(null))) {
102 throw new Exception("invalid font face name");
104 if (name
.length
== 0) throw new Exception("invalid font face name");
105 if (name
in fontfaces
) throw new Exception("duplicate font '"~name
.idup
~"'");
106 int fid
= fs
.fonsAddFont(name
, path
);
107 if (fid
< 0) throw new Exception("font '"~name
~"' is not found at '"~path
.idup
~"'");
108 static if (is(T
== string
)) {
109 fontfaces
[name
] = fid
;
110 fontfaceids
[fid
] = name
;
112 string n
= name
.idup
;
114 fontfaceids
[fid
] = n
;
119 // returns "font id" which can be used in `fontFace()`
120 @property int fontFaceId (const(char)[] name
) {
121 if (auto fid
= name
in fontfaces
) return *fid
;
125 @property string
fontFace (int fid
) {
126 if (auto ff
= fid
in fontfaceids
) return *ff
;
130 void setFont() (in auto ref LayFontStyle style
) {
131 int fsz
= style
.fontsize
;
132 if (fsz
< 1) fsz
= 1;
133 if (!fontWasSet || fsz
!= lastStyle
.fontsize || style
.fontface
!= lastStyle
.fontface
) {
134 if (style
.fontface
!= lastStyle
.fontface
) fonsSetFont(fs
, style
.fontface
);
135 if (fsz
!= lastStyle
.fontsize
) fonsSetSize(fs
, fsz
);
137 lastStyle
.fontsize
= fsz
;
141 int textWidth(T
) (const(T
)[] str) if (is(T
== char) ||
is(T
== dchar)) {
142 import std
.algorithm
: max
;
144 float adv
= fs
.fonsTextBounds(0, 0, str, b
[]);
146 return lrintf(max(adv
, w
));
149 int spacesWidth (int count
) {
150 if (count
< 1) return 0;
151 auto it
= FonsTextBoundsIterator(fs
, 0, 0);
153 return lrintf(it
.advance
*count
);
156 // this returns "width", "width with trailing whitespace", and "width with trailing hypen"
157 // all `*` args can be omited
158 void textWidth2(T
) (const(T
)[] str, int* w
=null, int* wsp
=null, int* whyph
=null) if (is(T
== char) ||
is(T
== dchar)) {
159 import std
.algorithm
: max
;
160 if (w
is null && wsp
is null && whyph
is null) return;
162 auto it
= FonsTextBoundsIterator(fs
, 0, 0);
165 it
.getHBounds(minx
, maxx
);
166 *w
= lrintf(max(it
.advance
, maxx
-minx
));
168 if (wsp
!is null && whyph
is null) {
170 it
.getHBounds(minx
, maxx
);
171 *wsp
= lrintf(max(it
.advance
, maxx
-minx
));
172 } else if (wsp
is null && whyph
!is null) {
173 it
.put(cast(dchar)45);
174 it
.getHBounds(minx
, maxx
);
175 *whyph
= lrintf(max(it
.advance
, maxx
-minx
));
176 } else if (wsp
!is null && whyph
!is null) {
179 it
.getHBounds(minx
, maxx
);
180 *wsp
= lrintf(max(it
.advance
, maxx
-minx
));
181 sit
.put(cast(dchar)45);
182 sit
.getHBounds(minx
, maxx
);
183 *whyph
= lrintf(max(sit
.advance
, maxx
-minx
));
188 // use line bounds for height
189 float y0
= void, y1
= void;
190 fs
.fonsLineBounds(0, &y0
, &y1
);
191 return lrintf(y1
-y0
);
194 void textMetrics (int* asc
, int* desc
, int* lineh
) {
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
{
214 Href
= 1<<5, // this is cross-reference (not actually a style flag, but it somewhat fits here)
216 ubyte flags
; // see above
217 int fontface
= -1; // i can't use strings here, as this struct inside LayWord will not be GC-scanned
219 uint color
= 0xff000000; // AABBGGRR; AA usually ignored by renderer, but i'll keep it anyway
220 string
toString () const {
221 import std
.format
: format
;
222 string res
= "font:%s;size:%s;color:0x%08X".format(fontface
, fontsize
, color
);
223 if (flags
&Flag
.Italic
) res
~= ";italic";
224 if (flags
&Flag
.Bold
) res
~= ";bold";
225 if (flags
&Flag
.Strike
) res
~= ";strike";
226 if (flags
&Flag
.Underline
) res
~= ";under";
227 if (flags
&Flag
.Overline
) res
~= ";over";
231 import std
.conv
: to
;
232 import std
.ascii
: toLower
;
234 foreach (string s
; __traits(allMembers
, Flag
)) {
236 res
~= "@property bool "~s
[0].toLower
~s
[1..$]~" () const pure nothrow @safe @nogc { pragma(inline, true); return ((flags&Flag."~s
~") != 0); }\n";
237 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";
241 void resetAttrs () pure nothrow @safe @nogc { pragma(inline
, true); flags
= 0; }
242 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
); }
246 // ////////////////////////////////////////////////////////////////////////// //
248 align(1) struct LayLineStyle
{
250 enum Justify
: ubyte {
256 Justify mode
= Justify
.Left
;
257 short lpad
, rpad
, tpad
, bpad
; // paddings; left and right can be negative
258 ubyte paraIndent
; // in spaces
259 string
toString () const {
260 import std
.format
: format
;
262 final switch (mode
) {
263 case Justify
.Left
: res
= "left"; break;
264 case Justify
.Right
: res
= "right"; break;
265 case Justify
.Center
: res
= "center"; break;
266 case Justify
.Justify
: res
= "justify"; break;
268 if (lpad
) res
~= ";lpad:%s".format(lpad
);
269 if (rpad
) res
~= ";rpad:%s".format(rpad
);
270 if (tpad
) res
~= ";tpad:%s".format(tpad
);
271 if (bpad
) res
~= ";bpad:%s".format(bpad
);
275 import std
.conv
: to
;
276 import std
.ascii
: toLower
;
278 foreach (string s
; __traits(allMembers
, Justify
)) {
280 res
~= "@property bool "~s
[0].toLower
~s
[1..$]~" () const pure nothrow @safe @nogc { pragma(inline, true); return (mode == Justify."~s
~"); }\n";
281 res
~= "ref LayLineStyle set"~s
~" () pure nothrow @safe @nogc { mode = Justify."~s
~"; return this; }\n";
285 //bool opEquals() (in auto ref LayLineStyle s) const pure nothrow @safe @nogc { pragma(inline, true); return (mode == s.mode && lpad == s.lpad); }
286 @property pure nothrow @safe @nogc {
287 int leftpad () const { pragma(inline
, true); return lpad
; }
288 void leftpad (int v
) { pragma(inline
, true); lpad
= (v
< short.min ?
short.min
: v
> short.max ?
short.max
: cast(short)v
); }
289 int rightpad () const { pragma(inline
, true); return rpad
; }
290 void rightpad (int v
) { pragma(inline
, true); rpad
= (v
< short.min ?
short.min
: v
> short.max ?
short.max
: cast(short)v
); }
291 int toppad () const { pragma(inline
, true); return tpad
; }
292 void toppad (int v
) { pragma(inline
, true); tpad
= (v
< 0 ?
0 : v
> short.max ?
short.max
: cast(short)v
); }
293 int bottompad () const { pragma(inline
, true); return bpad
; }
294 void bottompad (int v
) { pragma(inline
, true); bpad
= (v
< 0 ?
0 : v
> short.max ?
short.max
: cast(short)v
); }
299 // ////////////////////////////////////////////////////////////////////////// //
300 // layouted text word
301 align(1) struct LayWord
{
303 static align(1) struct Props
{
306 CanBreak
= 1<<0, // can i break line at this word?
307 Spaced
= 1<<1, // should this word be whitespaced at the end?
308 Hypen
= 1<<2, // if i'll break at this word, should i add hyphen mark?
309 LineEnd
= 1<<3, // this word ends current line
310 ParaEnd
= 1<<4, // this word ends current paragraph (and, implicitly, line)
311 Object
= 1<<5, // wstart is actually object index in object array
313 // note that if word is softhyphen candidate, i have hyphen mark at [wend]
314 // if props.hyphen is set, wend is including that mark, otherwise it isn't
315 ubyte flags
; // see above
316 @property pure nothrow @safe @nogc:
317 bool canbreak () const { pragma(inline
, true); return ((flags
&Flag
.CanBreak
) != 0); }
318 void canbreak (bool v
) { pragma(inline
, true); if (v
) flags |
= Flag
.CanBreak
; else flags
&= ~Flag
.CanBreak
; }
319 bool spaced () const { pragma(inline
, true); return ((flags
&Flag
.Spaced
) != 0); }
320 void spaced (bool v
) { pragma(inline
, true); if (v
) flags |
= Flag
.Spaced
; else flags
&= ~Flag
.Spaced
; }
321 bool hyphen () const { pragma(inline
, true); return ((flags
&Flag
.Hypen
) != 0); }
322 void hyphen (bool v
) { pragma(inline
, true); if (v
) flags |
= Flag
.Hypen
; else flags
&= ~Flag
.Hypen
; }
323 bool lineend () const { pragma(inline
, true); return ((flags
&Flag
.LineEnd
) != 0); }
324 void lineend (bool v
) { pragma(inline
, true); if (v
) flags |
= Flag
.LineEnd
; else flags
&= ~Flag
.LineEnd
; }
325 bool paraend () const { pragma(inline
, true); return ((flags
&Flag
.ParaEnd
) != 0); }
326 void paraend (bool v
) { pragma(inline
, true); if (v
) flags |
= Flag
.ParaEnd
; else flags
&= ~Flag
.ParaEnd
; }
327 bool someend () const { pragma(inline
, true); return ((flags
&(Flag
.ParaEnd|Flag
.LineEnd
)) != 0); }
328 bool object () const { pragma(inline
, true); return ((flags
&Flag
.Object
) != 0); }
329 void object (bool v
) { pragma(inline
, true); if (v
) flags |
= Flag
.Object
; else flags
&= ~Flag
.Object
; }
331 uint wstart
, wend
; // in LayText text buffer
332 LayFontStyle style
; // font style
333 uint wordNum
; // word number (index in LayText word array)
334 Props propsOrig
; // original properties, used for relayouting
336 Props props
; // effective props after layouting
337 short x
; // horizontal word position in line
338 short h
; // word height (full)
339 short asc
; // ascent (positive)
340 short desc
; // descent (negative)
341 short w
; // word width, without hyphen and spacing
342 short wsp
; // word width with spacing (i.e. with space added at the end)
343 short whyph
; // word width with hyphen (i.e. with hyphen mark added at the end)
344 @property short width () const pure nothrow @safe @nogc { pragma(inline
, true); return (props
.hyphen ? whyph
: w
); }
345 // width with spacing/hyphen
346 @property short fullwidth () const pure nothrow @safe @nogc { pragma(inline
, true); return (props
.hyphen ? whyph
: props
.spaced ? wsp
: w
); }
347 // space width based on original props
348 @property short spacewidth () const pure nothrow @safe @nogc { pragma(inline
, true); return cast(short)(propsOrig
.spaced ? wsp
-w
: 0); }
349 //FIXME: find better place for this! keep that in separate pool, or something, and look there with word index
351 short paraPad
; // to not recalcuate it on each relayouting; set to -1 to recalculate ;-)
352 @property int objectIdx () const pure nothrow @safe @nogc { pragma(inline
, true); return (propsOrig
.object ? wstart
: -1); }
357 // ////////////////////////////////////////////////////////////////////////// //
358 // layouted text line
360 uint wstart
, wend
; // indicies in word array
361 LayLineStyle just
; // line style
362 // calculated properties
363 int x
, y
, w
; // starting x and y positions, width
364 // on finish, layouter will calculate minimal ('cause it is negative) descent
365 int h
, desc
; // height, descent (negative)
366 @property int wordCount () const pure nothrow @safe @nogc { pragma(inline
, true); return cast(int)(wend
-wstart
); }
370 // ////////////////////////////////////////////////////////////////////////// //
371 alias LayText
= LayTextImpl
!char;
374 final class LayTextImpl(TBT
=char) if (is(TBT
== char) ||
is(TBT
== dchar)) {
376 // special control characters
377 enum dchar EndLineCh
= 0x2028; // 0x0085 is treated like whitespace
378 enum dchar EndParaCh
= 0x2029;
381 void ensurePool(ubyte pow2
, bool clear
, T
) (uint want
, ref T
* ptr
, ref uint used
, ref uint alloced
) {
382 if (want
== 0) return;
383 static assert(pow2
< 24, "wtf?!");
384 uint cursz
= used
*cast(uint)T
.sizeof
;
385 if (cursz
>= int.max
/2) throw new Exception("pool overflow");
386 auto lsz
= cast(ulong)want
*T
.sizeof
;
387 if (lsz
>= int.max
/2 || lsz
+cursz
>= int.max
/2) throw new Exception("pool overflow");
388 want
= cast(uint)lsz
;
389 uint cural
= alloced
*cast(uint)T
.sizeof
;
390 if (cursz
+want
> cural
) {
391 import core
.stdc
.stdlib
: realloc
;
393 uint newsz
= ((cursz
+want
)|
((1<<pow2
)-1))+1;
394 if (newsz
>= int.max
/2) throw new Exception("pool overflow");
395 auto np
= cast(T
*)realloc(ptr
, newsz
);
396 if (np
is null) throw new Exception("out of memory for pool");
398 import core
.stdc
.string
: memset
;
399 memset(np
+used
, 0, newsz
-cursz
);
402 alloced
= newsz
/cast(uint)T
.sizeof
;
407 uint charsUsed
, charsAllocated
;
409 static if (is(TBT
== char)) {
410 void putChars (const(dchar)[] str...) {
411 import core
.stdc
.string
: memcpy
;
412 //if (str.length >= int.max/2) throw new Exception("string too long");
414 foreach (dchar ch
; str[]) {
415 //auto len = utf8Encode(buf[], ch);
416 //if (len < 0) { buf.ptr[0] = '?'; len = 1; }
417 if (!Utf8Decoder
.isValidDC(ch
)) ch
= Utf8Decoder
.replacement
;
420 ensurePool
!(16, false)(1, ltext
, charsUsed
, charsAllocated
);
421 ltext
[charsUsed
++] = cast(char)ch
;
425 buf
.ptr
[0] = cast(char)(0xC0|
(ch
>>6));
426 buf
.ptr
[1] = cast(char)(0x80|
(ch
&0x3F));
428 } else if (ch
<= 0xFFFF) {
429 buf
.ptr
[0] = cast(char)(0xE0|
(ch
>>12));
430 buf
.ptr
[1] = cast(char)(0x80|
((ch
>>6)&0x3F));
431 buf
.ptr
[2] = cast(char)(0x80|
(ch
&0x3F));
433 } else if (ch
<= 0x10FFFF) {
434 buf
.ptr
[0] = cast(char)(0xF0|
(ch
>>18));
435 buf
.ptr
[1] = cast(char)(0x80|
((ch
>>12)&0x3F));
436 buf
.ptr
[2] = cast(char)(0x80|
((ch
>>6)&0x3F));
437 buf
.ptr
[3] = cast(char)(0x80|
(ch
&0x3F));
442 ensurePool
!(16, false)(len
, ltext
, charsUsed
, charsAllocated
);
443 memcpy(ltext
+charsUsed
, buf
.ptr
, len
);
450 void putChars (const(dchar)[] str...) {
451 import core
.stdc
.string
: memcpy
;
452 if (str.length
== 0) return;
453 if (str.length
>= int.max
/2/dchar.sizeof
) throw new Exception("string too long");
454 ensurePool
!(16, false)(cast(uint)str.length
, ltext
, charsUsed
, charsAllocated
);
455 memcpy(ltext
+charsUsed
, str.ptr
, cast(uint)str.length
*dchar.sizeof
);
456 charsUsed
+= cast(uint)str.length
;
461 uint wordsUsed
, wordsAllocated
;
463 LayWord
* allocWord(bool clear
=false) () {
464 ensurePool
!(16, true)(1, words
, wordsUsed
, wordsAllocated
);
465 auto res
= words
+wordsUsed
;
467 import core
.stdc
.string
: memset
;
468 memset(res
, 0, (*res
).sizeof
);
470 res
.wordNum
= wordsUsed
++;
471 //res.userTag = wordTag;
476 uint linesUsed
, linesAllocated
;
478 LayLine
* allocLine(bool clear
=false) () {
479 ensurePool
!(16, true)(1, lines
, linesUsed
, linesAllocated
);
481 import core
.stdc
.string
: memset
;
482 auto res
= lines
+(linesUsed
++);
483 memset(res
, 0, (*res
).sizeof
);
486 return lines
+(linesUsed
++);
490 LayLine
* lastLine () { pragma(inline
, true); return (linesUsed
> 0 ? lines
+linesUsed
-1 : null); }
492 bool lastLineHasWords () { pragma(inline
, true); return (linesUsed
> 0 ?
(lines
[linesUsed
-1].wend
> lines
[linesUsed
-1].wstart
) : false); }
494 // should not be called when there are no lines, or no words in last line
495 LayWord
* lastLineLastWord () { pragma(inline
, true); return words
+lastLine
.wend
-1; }
497 static struct StyleStackItem
{
501 StyleStackItem
* styleStack
;
502 uint ststackUsed
, ststackAllocated
;
504 public void pushStyles () {
505 ensurePool
!(4, false)(1, styleStack
, ststackUsed
, ststackAllocated
);
506 auto si
= styleStack
+(ststackUsed
++);
511 public void popStyles () {
512 if (ststackUsed
== 0) throw new Exception("style stack underflow");
513 auto si
= styleStack
+(--ststackUsed
);
519 bool firstParaLine
= true;
520 uint lastWordStart
; // in fulltext
521 uint firstWordNotFlushed
;
523 @property bool hasWordChars () const pure nothrow @safe @nogc { pragma(inline
, true); return (lastWordStart
< charsUsed
); }
526 // current attributes
527 LayLineStyle just
; // for current paragraph
529 // user can change this alot, so don't apply that immediately
530 LayFontStyle newStyle
;
531 LayLineStyle newJust
;
536 bool lastWasSoftHypen
;
537 int maxWidth
; // maximum text width
541 int textHeight
= 0; // total text height
542 int textWidth
= 0; // maximum text width
545 // compare function should return (roughly): key-l
546 alias CmpFn
= int delegate (LayLine
* l
) nothrow @nogc;
548 int findLineBinary (scope CmpFn cmpfn
) {
549 if (linesUsed
== 0) return -1;
550 int bot
= 0, i
= cast(int)linesUsed
-1;
552 int mid
= i
-(i
-bot
)/2;
553 int cmp = cmpfn(lines
+mid
);
554 if (cmp < 0) i
= mid
-1;
555 else if (cmp > 0) bot
= mid
;
558 return (cmpfn(lines
+i
) == 0 ? i
: -1);
561 // find line with this word index
562 int findLineWithWord (uint idx
) {
563 return findLineBinary((LayLine
* l
) {
564 if (idx
< l
.wstart
) return -1;
565 if (idx
>= l
.wend
) return 1;
570 // find line which contains this coordinate
571 int findLineAtY (int y
) {
572 if (linesUsed
== 0) return 0;
574 if (y
>= textHeight
) return cast(int)linesUsed
-1;
575 auto res
= findLineBinary((LayLine
* l
) {
576 if (y
< l
.y
) return -1;
577 if (y
>= l
.y
+l
.h
) return 1;
584 // find word at given coordinate in the given line
585 int findWordAtX (LayLine
* ln
, int x
) {
586 int wcmp (int wnum
) {
587 auto w
= words
+ln
.wstart
+wnum
;
588 if (x
< w
.x
) return -1;
589 return (x
>= (wnum
+1 < ln
.wordCount ? w
[1].x
: w
.x
+w
.w
) ?
1 : 0);
591 if (ln
is null || ln
.wordCount
== 0) return -1;
592 int bot
= 0, i
= ln
.wordCount
-1;
594 int mid
= i
-(i
-bot
)/2;
596 case -1: i
= mid
-1; break;
597 case 1: bot
= mid
; break;
598 default: return ln
.wstart
+mid
;
601 return (wcmp(i
) == 0 ? ln
.wstart
+i
: -1);
604 // find word at the given coordinates
605 int wordAtXY (int x
, int y
) {
606 auto lidx
= findLineAtY(y
);
607 if (lidx
< 0) return -1;
608 auto ln
= lines
+lidx
;
609 if (y
< ln
.y || y
>= ln
.y
+ln
.h || ln
.wordCount
== 0) return -1;
610 return findWordAtX(ln
, x
);
613 LayWord
* wordByIndex (uint idx
) pure nothrow @trusted @nogc { pragma(inline
, true); return (idx
< wordsUsed ? words
+idx
: null); }
615 @property const(TBT
)[] wordText (in ref LayWord w
) const pure nothrow @trusted @nogc { pragma(inline
, true); return (w
.wstart
<= w
.wend ? ltext
[w
.wstart
..w
.wend
] : null); }
617 @property int lineCount () const pure nothrow @safe @nogc { pragma(inline
, true); return cast(int)linesUsed
; }
620 @property auto lineWords (int lidx
) {
621 static struct Range
{
624 int wordsLeft
; // not including current
625 nothrow @trusted @nogc:
627 this(LT
) (LT lay
, int lidx
) {
628 if (lidx
>= 0 && lidx
< lay
.linesUsed
) {
629 auto ln
= lay
.lines
+lidx
;
630 if (ln
.wend
> ln
.wstart
) {
631 w
= lay
.words
+ln
.wstart
;
632 wordsLeft
= ln
.wend
-ln
.wstart
-1;
637 @property bool empty () const pure { pragma(inline
, true); return (w
is null); }
638 @property ref LayWord
front () pure { pragma(inline
, true); assert(w
!is null); return *w
; }
639 void popFront () { if (wordsLeft
) { ++w
; --wordsLeft
; } else w
= null; }
640 Range
save () { Range res
= void; res
.w
= w
; res
.wordsLeft
= wordsLeft
; return res
; }
641 @property int length () const pure { pragma(inline
, true); return (w
!is null ? wordsLeft
+1 : 0); }
642 alias opDollar
= length
;
643 @property LayWord
[] opSlice () { return (w
!is null ? w
[0..wordsLeft
+1] : null); }
644 @property LayWord
[] opSlice (int lo
, int hi
) {
646 if (w
is null || hi
<= lo || lo
> wordsLeft
) return null;
647 if (hi
> wordsLeft
+1) hi
= wordsLeft
+1;
651 return Range(this, lidx
);
654 LayLine
* line (int lidx
) { pragma(inline
, true); return (lidx
>= 0 && lidx
< linesUsed ? lines
+lidx
: null); }
660 this (LayFontStash alaf
, int awidth
) {
661 if (alaf
is null) assert(0, "no layout fonts");
662 if (awidth
< 1) awidth
= 1;
667 ~this () { freeMemory(); }
670 import core
.stdc
.stdlib
: free
;
671 if (lines
!is null) { free(lines
); lines
= null; }
672 if (words
!is null) { free(words
); words
= null; }
673 if (ltext
!is null) { free(ltext
); ltext
= null; }
674 wordsUsed
= wordsAllocated
= linesUsed
= linesAllocated
= charsUsed
= charsAllocated
= 0;
677 @property int width () const pure nothrow @safe @nogc { pragma(inline
, true); return maxWidth
; }
679 // last flushed word index
680 @property uint lastWordIndex () const pure nothrow @safe @nogc { pragma(inline
, true); return (wordsUsed ? wordsUsed
-1 : 0); }
682 // current word index
683 @property uint nextWordIndex () const pure nothrow @safe @nogc { pragma(inline
, true); return wordsUsed
+hasWordChars
; }
685 // use those to change current style. font style will take an effect on next char, line style on next line
686 @property ref LayFontStyle
fontStyle () pure nothrow @safe @nogc { pragma(inline
, true); return newStyle
; }
687 @property ref LayLineStyle
lineStyle () pure nothrow @safe @nogc { pragma(inline
, true); return newJust
; }
689 // return "font id" for the given font face
690 @property int fontFaceId (const(char)[] name
) {
692 int fid
= laf
.fontFaceId(name
);
693 if (fid
>= 0) return fid
;
695 throw new Exception("unknown font face '"~name
.idup
~"'");
698 // return font face for the given "font id"
699 @property string
fontFace (int fid
) { pragma(inline
, true); return (laf
!is null ? laf
.fontFace(fid
) : null); }
702 void endLine () { put(EndLineCh
); }
703 // end current paragraph
704 void endPara () { put(EndParaCh
); }
706 // add "object" into text -- special thing that knows it's dimensions
707 void putObject (LayObject obj
) {
708 import std
.algorithm
: max
, min
;
710 lastWasSoftHypen
= false;
711 if (obj
is null) return;
712 if (objects
.length
>= int.max
/2) throw new Exception("too many objects");
714 // create special word
715 auto w
= allocWord();
716 w
.wstart
= cast(dchar)objects
.length
; // store object index
720 w
.propsOrig
.object
= true;
721 w
.propsOrig
.spaced
= obj
.spaced
;
722 w
.propsOrig
.canbreak
= obj
.canbreak
;
723 w
.props
= w
.propsOrig
;
724 w
.w
= cast(short)min(max(0, obj
.width
), short.max
);
725 w
.whyph
= w
.wsp
= cast(short)min(w
.w
+max(0, obj
.spacewidth
), short.max
);
726 w
.h
= cast(short)min(max(0, obj
.height
), short.max
);
727 w
.asc
= cast(short)min(max(0, obj
.ascent
), short.max
);
728 if (w
.asc
< 0) throw new Exception("object ascent should be positive");
729 w
.desc
= cast(short)min(max(0, obj
.descent
), short.max
);
730 if (w
.desc
> 0) throw new Exception("object descent should be negative");
735 // add text to layouter; it is ok to mix (valid) utf-8 and dchars here
736 void put(T
) (const(T
)[] str...) if (is(T
== char) ||
is(T
== dchar)) {
737 if (str.length
== 0) return;
739 dchar curCh
; // 0: no more chars
742 static if (is(T
== char)) {
744 if (!lastWasUtf
) { lastWasUtf
= true; dec.reset
; }
745 void skipCh () @trusted {
746 while (stpos
< str.length
) {
747 curCh
= dec.decode(cast(ubyte)str.ptr
[stpos
++]);
748 if (curCh
<= dchar.max
) return;
756 void skipCh () @trusted {
757 if (stpos
< str.length
) {
758 curCh
= str.ptr
[stpos
++];
759 if (curCh
> dchar.max
) curCh
= '?';
767 if (!dec.complete
) curCh
= '?'; else skipCh();
773 // process stream dchars
774 if (curCh
== 0) return;
775 if (!hasWordChars
) style
= newStyle
;
776 if (wordsUsed
== 0 || words
[wordsUsed
-1].propsOrig
.someend
) just
= newJust
;
781 if (ch
== EndLineCh || ch
== EndParaCh
) {
782 // ignore leading empty lines
783 if (hasWordChars
) flushWord(); // has some word data, flush it now
784 lastWasSoftHypen
= false; // word flusher is using this flag
785 auto lw
= (wordsUsed ? words
+wordsUsed
-1 : createEmptyWord());
786 // do i need to add empty word for attrs?
787 if (lw
.propsOrig
.someend
) lw
= createEmptyWord();
788 // fix word properties
789 lw
.propsOrig
.canbreak
= true;
790 lw
.propsOrig
.spaced
= false;
791 lw
.propsOrig
.hyphen
= false;
792 lw
.propsOrig
.lineend
= (ch
== EndLineCh
);
793 lw
.propsOrig
.paraend
= (ch
== EndParaCh
);
796 firstParaLine
= (ch
== EndParaCh
);
797 } else if (ch
== 0x00a0) {
798 // non-breaking space
799 lastWasSoftHypen
= false;
800 if (hasWordChars
&& style
!= newStyle
) flushWord();
802 } else if (ch
== 0x0ad) {
804 if (!lastWasSoftHypen
&& hasWordChars
) {
806 lastWasSoftHypen
= true; // word flusher is using this flag
809 lastWasSoftHypen
= true;
810 } else if (ch
<= ' ' ||
isWhite(ch
)) {
813 auto lw
= words
+wordsUsed
-1;
814 lw
.propsOrig
.canbreak
= true;
815 lw
.propsOrig
.spaced
= true;
819 lastWasSoftHypen
= false;
821 lastWasSoftHypen
= false;
822 if (ch
> dchar.max || ch
.isSurrogate || ch
.isPrivateUse || ch
.isNonCharacter || ch
.isMark || ch
.isFormat || ch
.isControl
) ch
= '?';
823 if (hasWordChars
&& style
!= newStyle
) flushWord();
825 if (isDash(ch
) && charsUsed
-lastWordStart
> 1 && !isDash(ltext
[charsUsed
-2])) flushWord();
830 // "finalize" layout: calculate lines, layout words...
831 // call this after you done feeding text to this
834 lastWasSoftHypen
= false;
835 relayout(maxWidth
, true);
838 // relayout everything using the existing words
839 void relayout (int newWidth
, bool forced
) {
840 if (newWidth
< 1) newWidth
= 1;
841 if (!forced
&& newWidth
== maxWidth
) return;
844 if (linesAllocated
> 0) {
845 import core
.stdc
.string
: memset
;
846 memset(lines
, 0, linesAllocated
*lines
[0].sizeof
);
852 firstParaLine
= true;
853 scope(exit
) firstWordNotFlushed
= wu
;
857 auto w
= words
+(lend
++);
858 if (w
.propsOrig
.someend
) break;
860 flushLines(widx
, lend
);
862 firstParaLine
= words
[widx
-1].propsOrig
.paraend
;
868 void save (VFile fl
) {
869 fl
.rawWriteExact("XLL0");
870 fl
.rawWriteExact(ltext
[0..charsUsed
]);
871 fl
.rawWriteExact(words
[0..wordsUsed
]);
876 void dump (VFile fl
) const {
877 fl
.writeln("LINES: ", linesUsed
);
878 foreach (immutable idx
, const ref ln
; lines
[0..linesUsed
]) {
879 fl
.writeln("LINE #", idx
, ": ", ln
.wordCount
, " words; just=", ln
.just
.toString
, "; jlpad=", ln
.just
.leftpad
, "; y=", ln
.y
, "; h=", ln
.h
, "; desc=", ln
.desc
);
880 foreach (immutable widx
, const ref w
; words
[ln
.wstart
..ln
.wend
]) {
881 fl
.writeln(" WORD #", widx
, "(", w
.wordNum
, ")[", w
.wstart
, "..", w
.wend
, "]: ", wordText(w
));
882 fl
.writeln(" wbreak=", w
.props
.canbreak
, "; wspaced=", w
.props
.spaced
, "; whyphen=", w
.props
.hyphen
, "; style=", w
.style
.toString
);
883 fl
.writeln(" x=", w
.x
, "; w=", w
.w
, "; h=", w
.h
, "; asc=", w
.asc
, "; desc=", w
.desc
);
889 static bool isDash (dchar ch
) {
890 pragma(inline
, true);
891 return (ch
== '-' ||
(ch
>= 0x2013 && ch
== 0x2015) || ch
== 0x2212);
894 LayWord
* createEmptyWord () {
895 assert(!hasWordChars
);
896 auto w
= allocWord();
898 w
.props
= w
.propsOrig
;
899 // set word dimensions
900 if (w
.style
.fontface
< 0) throw new Exception("invalid font face in word style");
901 laf
.setFont(w
.style
);
902 w
.w
= w
.wsp
= w
.whyph
= 0;
903 // calculate ascent, descent and height
906 laf
.textMetrics(&a
, &d
, &h
);
907 w
.asc
= cast(short)a
;
908 w
.desc
= cast(short)d
;
919 auto w
= allocWord();
920 w
.wstart
= lastWordStart
;
922 //{ import iv.encoding, std.conv : to; writeln("adding word: [", wordText(*w).to!string.recodeToKOI8, "]"); }
923 w
.propsOrig
.hyphen
= lastWasSoftHypen
;
924 if (lastWasSoftHypen
) {
925 w
.propsOrig
.canbreak
= true;
926 w
.propsOrig
.spaced
= false;
927 --w
.wend
; // remove hyphen mark (for now)
930 w
.props
= w
.propsOrig
;
931 w
.props
.hyphen
= false;
932 // set word dimensions
933 if (w
.style
.fontface
< 0) throw new Exception("invalid font face in word style");
934 laf
.setFont(w
.style
);
935 // i may need spacing later, and anyway most words should be with spacing, so calc it unconditionally
936 if (w
.wend
> w
.wstart
) {
937 auto t
= wordText(*w
);
939 laf
.textWidth2(t
, &ww
, &wsp
, (w
.propsOrig
.hyphen ?
&whyph
: null));
941 w
.wsp
= cast(short)wsp
;
942 if (!w
.propsOrig
.hyphen
) w
.whyph
= w
.w
; else w
.whyph
= cast(short)whyph
;
943 if (isDash(t
[$-1])) { w
.propsOrig
.canbreak
= true; w
.props
.canbreak
= true; }
945 w
.w
= w
.wsp
= w
.whyph
= 0;
947 // calculate ascent, descent and height
950 laf
.textMetrics(&a
, &d
, &h
);
951 w
.asc
= cast(short)a
;
952 w
.desc
= cast(short)d
;
957 lastWordStart
= charsUsed
;
963 void flushLines (uint curw
, uint endw
) {
965 debug(xlay_line_flush
) writeln("flushing ", endw
-curw
, " words");
966 uint stline
= linesUsed
; // reformat from this
968 foreach (ref LayWord w
; words
[curw
..endw
]) {
969 if (w
.props
.hyphen
) --w
.wend
; // remove hyphen mark
970 w
.props
= w
.propsOrig
;
971 w
.props
.hyphen
= false;
974 LayWord
* w
= words
+curw
;
975 while (curw
< endw
) {
976 debug(xlay_line_flush
) writeln(" ", endw
-curw
, " words left");
978 // add line to work with
980 ln
.wstart
= ln
.wend
= curw
;
982 ln
.w
= w
.just
.leftpad
+w
.just
.rightpad
;
983 // indent first line of paragraph
985 firstParaLine
= false;
986 // left-side or justified lines has paragraph indent
987 if (ln
.just
.paraIndent
> 0 && (w
.just
.left || w
.just
.justify
)) {
988 auto ind
= w
.paraPad
;
990 laf
.setFont(w
.style
);
991 ind
= cast(short)laf
.spacesWidth(ln
.just
.paraIndent
);
995 ln
.just
.leftpad
= ln
.just
.leftpad
+ind
;
1000 //writeln("new line; maxWidth=", maxWidth, "; starting line width=", ln.w);
1001 //writeln("* maxWidth=", maxWidth, "; ln.w=", ln.w, "; leftpad=", ln.just.leftpad, "; rightpad=", ln.just.rightpad);
1003 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))));
1004 // add words until i hit breaking point
1005 // if it will end beyond maximum width, and this line
1006 // has some words, flush the line and start new one
1007 uint startIndex
= curw
;
1008 int curwdt
= ln
.w
, lastwsp
= 0;
1009 while (curw
< endw
) {
1010 // add word width with spacing (i will compensate for that after loop)
1011 lastwsp
= (w
.propsOrig
.spaced ? w
.wsp
-w
.w
: 0);
1012 curwdt
+= w
.w
+lastwsp
;
1013 ++curw
; // advance counter here...
1014 if (w
.props
.canbreak
) break; // done with this span
1015 ++w
; // ...and word pointer here (skipping one inc at the end ;-)
1017 debug(xlay_line_flush
) writeln(" ", curw
-startIndex
, " words processed");
1018 // can i add the span? if this is first span in line, add it unconditionally
1019 if (ln
.wordCount
== 0 || curwdt
-lastwsp
<= maxWidth
) {
1023 ++w
; // advance to curw
1024 debug(xlay_line_flush
) writeln("curwdt=", curwdt
, "; maxWidth=", maxWidth
, "; wc=", ln
.wordCount
, "(", ln
.wend
-ln
.wstart
, ")");
1026 // nope, start new line here
1027 debug(xlay_line_flush
) writeln("added line with ", ln
.wordCount
, " words");
1028 // last word in the line should not be spaced
1029 auto ww
= words
+ln
.wend
-1;
1030 // compensate for spacing at last word
1031 ln
.w
-= (ww
.props
.spaced ? ww
.wsp
-ww
.w
: 0);
1032 ww
.props
.spaced
= false;
1033 // and should have hyphen mark if it is necessary
1034 if (ww
.propsOrig
.hyphen
) {
1035 assert(!ww
.props
.hyphen
);
1036 ww
.props
.hyphen
= true;
1038 // fix line width (word layouter will use that)
1039 ln
.w
+= ww
.whyph
-ww
.w
;
1046 debug(xlay_line_flush
) writeln("added line with ", ln
.wordCount
, " words; new lines range: [", stline
, "..", linesUsed
, "]");
1047 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))));
1048 // last line should not be justified
1049 if (ln
.just
.justify
) ln
.just
.setLeft
;
1050 // do real word layouting and fix line metrics
1051 debug(xlay_line_flush
) writeln("added ", linesUsed
-stline
, " lines");
1052 foreach (uint lidx
; stline
..linesUsed
) {
1053 debug(xlay_line_flush
) writeln(": lidx=", lidx
, "; wc=", lines
[lidx
].wordCount
);
1059 // do word layouting and fix line metrics
1060 void layoutLine (uint lidx
) {
1061 import std
.algorithm
: max
, min
;
1062 assert(lidx
< linesUsed
);
1063 auto ln
= lines
+lidx
;
1064 //writeln("maxWidth=", maxWidth, "; ln.w=", ln.w, "; leftpad=", ln.just.leftpad, "; rightpad=", ln.just.rightpad);
1065 debug(xlay_line_layout
) writeln("lidx=", lidx
, "; wc=", ln
.wordCount
);
1067 ln
.y
= (lidx ? ln
[-1].y
+ln
[-1].h
: 0);
1068 auto lwords
= lineWords(lidx
);
1069 assert(!lwords
.empty
); // i should have at least one word in each line
1070 // line width is calculated for us by `flushLines()`
1071 // calculate line metrics and number of words with spacing
1072 int lineH
, lineDesc
, wspCount
;
1073 foreach (ref LayWord w
; lwords
.save
) {
1074 lineH
= max(lineH
, w
.h
);
1075 lineDesc
= min(lineDesc
, w
.desc
);
1076 if (w
.props
.spaced
) ++wspCount
;
1078 // vertical padding; clamp it, as i can't have line over line (it will break too many things)
1079 lineH
+= ln
.just
.toppad
+ln
.just
.bottompad
;
1082 if (ln
.w
>= maxWidth
) {
1083 //writeln("*** ln.w=", ln.w, "; maxWidth=", maxWidth);
1084 // way too long; (almost) easy deal
1085 // calculate free space to spare in case i'll need to compensate hyphen mark
1086 int x
= ln
.just
.leftpad
, spc
= 0;
1087 foreach (ref LayWord w
; lwords
.save
) {
1090 if (w
.props
.spaced
) spc
+= w
.wsp
-w
.w
;
1092 // if last word ends with hyphen, try to compensate it
1093 if (words
[ln
.wend
-1].props
.hyphen
) {
1094 int needspc
= ln
.w
-maxWidth
;
1095 // no more than 8 pix or 2/3 of free space
1096 if (needspc
<= 8 && needspc
<= spc
/3*2) {
1097 // compensate (i can do fractional math here, but meh...)
1098 while (needspc
> 0) {
1099 // excellence in coding!
1100 foreach_reverse (immutable widx
; ln
.wstart
..ln
.wend
) {
1101 if (words
[widx
].props
.spaced
) {
1103 foreach (immutable c
; widx
+1..ln
.wend
) words
[c
].x
-= 1;
1104 if (--needspc
== 0) break;
1110 } else if (ln
.just
.justify
&& wspCount
> 0) {
1111 // fill the whole line
1112 int spc
= maxWidth
-ln
.w
; // space left to distribute
1113 int xadvsp
= spc
/wspCount
;
1114 int frac
= spc
-xadvsp
*wspCount
;
1115 int x
= ln
.just
.leftpad
;
1116 // no need to save range here, i'll do it in one pass
1117 foreach (ref LayWord w
; lwords
) {
1120 if (w
.props
.spaced
) {
1129 //if (x != maxWidth-ln.just.rightpad) writeln("x=", x, "; but it should be ", maxWidth-ln.just.rightpad, "; spcleft=", spc, "; ln.w=", ln.w, "; maxWidth=", maxWidth-ln.w);
1130 //assert(x == maxWidth-ln.just.rightpad);
1133 if (ln
.just
.left || ln
.just
.justify
) x
= ln
.just
.leftpad
;
1134 else if (ln
.just
.right
) x
= maxWidth
-ln
.w
+ln
.just
.leftpad
;
1135 else if (ln
.just
.center
) x
= (maxWidth
-(ln
.w
-ln
.just
.leftpad
-ln
.just
.rightpad
))/2;
1136 else assert(0, "wtf?!");
1137 // no need to save range here, i'll do it in one pass
1138 foreach (ref LayWord w
; lwords
) {
1143 if (ln
.h
< 1) ln
.h
= 1;
1144 textWidth
= max(textWidth
, ln
.w
);
1145 textHeight
= ln
.y
+ln
.h
;
1146 debug(xlay_line_layout
) writeln("lidx=", lidx
, "; wc=", ln
.wordCount
);