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/>.
24 import iv
.nanovg
.oui
.blendish
;
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 ();
45 abstract void draw (NVGContext ctx
, float x
, float y
);
49 // ////////////////////////////////////////////////////////////////////////// //
50 // this needs such fonts in stash:
54 // textz -- italic and bold
58 // monoz -- italic and bold
59 final class LayFontStash
{
62 // list of known font faces, should be filled by caller when this object created
64 int[string
] fontfaces
;
65 string
[int] fontfaceids
;
69 bool fontWasSet
; // to ensure that first call to `setFont()` will do it's work
70 LayFontStyle lastStyle
;
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");
82 fs
.fonsResetAtlas(1024, 1024);
83 fonsSetSpacing(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;
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");
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
;
110 string n
= name
.idup
;
112 fontfaceids
[fid
] = n
;
117 @property int fontFaceId (const(char)[] name
) {
118 if (auto fid
= name
in fontfaces
) return *fid
;
122 @property string
fontFace (int fid
) {
123 if (auto ff
= fid
in fontfaceids
) return *ff
;
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
);
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
;
142 float adv
= fs
.fonsTextBounds(0, 0, str, b
[]);
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);
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;
160 auto it
= FonsTextBoundsIterator(fs
, 0, 0);
163 it
.getHBounds(minx
, maxx
);
164 *w
= lrintf(max(it
.advance
, maxx
-minx
));
166 if (wsp
!is null && whyph
is null) {
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) {
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
));
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
{
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
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";
230 import std
.conv
: to
;
231 import std
.ascii
: toLower
;
233 foreach (string s
; __traits(allMembers
, Flag
)) {
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";
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 // ////////////////////////////////////////////////////////////////////////// //
247 align(1) struct LayLineStyle
{
249 enum Justify
: ubyte {
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
;
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
);
274 import std
.conv
: to
;
275 import std
.ascii
: toLower
;
277 foreach (string s
; __traits(allMembers
, Justify
)) {
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";
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
{
302 static align(1) struct Props
{
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
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
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
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 // ////////////////////////////////////////////////////////////////////////// //
369 final class LayText
{
371 // special control characters
372 enum dchar EndLineCh
= 0x2028; // 0x0085 is treated like whitespace
373 enum dchar EndParaCh
= 0x2029;
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
;
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");
393 import core
.stdc
.string
: memset
;
394 memset(np
+used
, 0, newsz
-cursz
);
397 alloced
= newsz
/cast(uint)T
.sizeof
;
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
;
414 uint wordsUsed
, wordsAllocated
;
416 LayWord
* allocWord(bool clear
=false) () {
417 ensurePool
!(16, true)(1, words
, wordsUsed
, wordsAllocated
);
418 auto res
= words
+wordsUsed
;
420 import core
.stdc
.string
: memset
;
421 memset(res
, 0, (*res
).sizeof
);
423 res
.wordNum
= wordsUsed
++;
428 uint linesUsed
, linesAllocated
;
430 LayLine
* allocLine(bool clear
=false) () {
431 ensurePool
!(16, true)(1, lines
, linesUsed
, linesAllocated
);
433 import core
.stdc
.string
: memset
;
434 auto res
= lines
+(linesUsed
++);
435 memset(res
, 0, (*res
).sizeof
);
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
{
453 StyleStackItem
* styleStack
;
454 uint ststackUsed
, ststackAllocated
;
456 public void pushStyles () {
457 ensurePool
!(4, false)(1, styleStack
, ststackUsed
, ststackAllocated
);
458 auto si
= styleStack
+(ststackUsed
++);
463 public void popStyles () {
464 if (ststackUsed
== 0) throw new Exception("style stack underflow");
465 auto si
= styleStack
+(--ststackUsed
);
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
); }
478 // current attributes
479 LayLineStyle just
; // for current paragraph
481 // user can change this alot, so don't apply that immediately
482 LayFontStyle newStyle
;
483 LayLineStyle newJust
;
488 bool lastWasSoftHypen
;
489 int maxWidth
; // maximum text width
493 int textHeight
= 0; // total text height
494 int textWidth
= 0; // maximum text width
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;
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
;
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;
522 // find line which contains this coordinate
523 int findLineWithY (int y
) {
524 if (linesUsed
== 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;
532 //if (res == -1) { import std.stdio; writeln("*** y=", y, "; th=", textHeight); }
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
; }
542 @property auto lineWords (int lidx
) {
543 static struct Range
{
546 int wordsLeft
; // not including current
547 nothrow @trusted @nogc:
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;
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
) {
569 if (w
is null || hi
<= lo || lo
> wordsLeft
) return null;
570 if (hi
> wordsLeft
+1) hi
= wordsLeft
+1;
574 return Range(this, lidx
);
577 LayLine
* line (int lidx
) { pragma(inline
, true); return (lidx
>= 0 && lidx
< linesUsed ? lines
+lidx
: null); }
583 this (LayFontStash alaf
, int awidth
) {
584 if (alaf
is null) assert(0, "no layout fonts");
585 if (awidth
< 1) awidth
= 1;
590 ~this () { 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
) {
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
) {
626 lastWasSoftHypen
= false;
627 if (obj
is null) return;
628 if (objects
.length
>= int.max
/2) throw new Exception("too many objects");
630 // create special word
631 auto w
= allocWord();
632 w
.wstart
= cast(dchar)objects
.length
; // store object index
636 w
.propsOrig
.object
= true;
637 w
.propsOrig
.spaced
= obj
.spaced
;
638 w
.propsOrig
.canbreak
= obj
.canbreak
;
639 w
.props
= w
.propsOrig
;
641 w
.whyph
= w
.wsp
= w
.w
+obj
.spacewidth
;
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");
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
658 static if (is(T
== char)) {
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;
672 void skipCh () @trusted {
673 if (stpos
< str.length
) {
674 curCh
= str.ptr
[stpos
++];
675 if (curCh
> dchar.max
) curCh
= '?';
683 if (!dec.complete
) curCh
= '?'; else skipCh();
689 // process stream dchars
690 if (curCh
== 0) return;
691 if (!hasWordChars
) style
= newStyle
;
692 if (firstWordNotFlushed
>= wordsUsed
) just
= newJust
;
697 if (ch
== EndLineCh || ch
== EndParaCh
) {
698 lastWasSoftHypen
= false;
699 // ignore leading empty lines
700 if (hasWordChars || linesUsed
) {
703 // has some word data, flush it now
705 lw
= words
+wordsUsed
-1;
706 } else if (wordsUsed
== 0) {
707 // create empty word to set attributes on it
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
);
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();
731 } else if (ch
== 0x0ad) {
733 if (!lastWasSoftHypen
&& hasWordChars
) {
735 lastWasSoftHypen
= true; // word flusher is using this flag
738 lastWasSoftHypen
= true;
739 } else if (ch
<= ' ' ||
isWhite(ch
)) {
740 lastWasSoftHypen
= false;
743 auto lw
= words
+wordsUsed
-1;
744 lw
.propsOrig
.canbreak
= true;
745 lw
.propsOrig
.spaced
= true;
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();
754 if (isDash(ch
) && charsUsed
-lastWordStart
> 1 && !isDash(ltext
[charsUsed
-2])) 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;
770 if (linesAllocated
> 0) {
771 import core
.stdc
.string
: memset
;
772 memset(lines
, 0, linesAllocated
*lines
[0].sizeof
);
778 firstParaLine
= true;
779 scope(exit
) firstWordNotFlushed
= wu
;
783 auto w
= words
+(lend
++);
784 if (w
.propsOrig
.lineend || w
.propsOrig
.paraend
) break;
786 flushLines(widx
, lend
);
787 //assert(wordsUsed == lend);
789 if (words
[widx
-1].propsOrig
.paraend
) firstParaLine
= true;
794 void save (VFile fl
) {
795 fl
.rawWriteExact("");
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
);
812 static bool isDash (dchar ch
) {
813 pragma(inline
, true);
814 return (ch
== '-' ||
(ch
>= 0x2013 && ch
== 0x2015) || ch
== 0x2212);
819 auto w
= allocWord();
820 w
.wstart
= lastWordStart
;
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)
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; }
842 w
.w
= w
.wsp
= w
.whyph
= 0;
844 // calculate ascent, descent and height
845 laf
.textMetrics(&w
.asc
, &w
.desc
, &w
.h
);
848 lastWordStart
= charsUsed
;
854 void flushLines (uint curw
, uint endw
) {
856 debug(xlay_line_flush
) writeln("flushing ", endw
-curw
, " words");
857 uint stline
= linesUsed
; // reformat from this
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;
865 LayWord
* w
= words
+curw
;
866 while (curw
< endw
) {
867 debug(xlay_line_flush
) writeln(" ", endw
-curw
, " words left");
869 // add line to work with
871 ln
.wstart
= ln
.wend
= curw
;
873 ln
.w
= just
.lpad
+just
.rpad
;
874 // indent first line of paragraph
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
);
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
) {
910 ++w
; // advance to curw
911 debug(xlay_line_flush
) writeln("curwdt=", curwdt
, "; maxWidth=", maxWidth
, "; wc=", ln
.wordCount
, "(", ln
.wend
-ln
.wstart
, ")");
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;
925 // fix line width (word layouter will use that)
926 ln
.w
+= ww
.whyph
-ww
.w
;
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
);
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
);
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
);
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
) {
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
) {
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
) {
1006 if (w
.props
.spaced
) {
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);
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
) {
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
);