Text.hx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. package h2d;
  2. /**
  3. `Text` alignment rules.
  4. **/
  5. enum Align {
  6. /**
  7. Aligns the text to the left edge.
  8. **/
  9. Left;
  10. /**
  11. Aligns the text to the right edge.
  12. When `Text.maxWidth` is set and/or Text size is constrained (see `Object.constraintSize`), right edge is considered the smallest of the two.
  13. Otherwise edge is at the `0` coordinate of the Text instance.
  14. See Text sample for showcase.
  15. **/
  16. Right;
  17. /**
  18. Centers the text alignment.
  19. When `Text.maxWidth` is set and/or Text size is constrained (see `Object.constraintSize`), center is calculated from 0 to the smallest of the two.
  20. Otherwise text is centered around `0` coordinate of the Text instance.
  21. See Text sample for showcase.
  22. **/
  23. Center;
  24. /**
  25. With respect to Text constraints, aligns the text to the right edge of the longest line width.
  26. When `Text.maxWidth` is set and/or Text size is constrained (see `Object.constraintSize`),
  27. right edge is calculated as the smallest value of the `maxWidth`, constrained width and longest line width (after word-wrap from constraints).
  28. Otherwise uses longest line width as the right edge.
  29. See Text sample for showcase.
  30. **/
  31. MultilineRight;
  32. /**
  33. Centers the text with respect to Text constraints with the longest line width.
  34. When `Text.maxWidth` is set and/or Text size is constrained (see `Object.constraintSize`),
  35. center is calculated from the to the smallest value of the `maxWidth`, constrained width and longest line width (after word-wrap from constraints).
  36. Otherwise calculates center from 0 to the longest line width.
  37. See Text sample for showcase.
  38. **/
  39. MultilineCenter;
  40. }
  41. /**
  42. A basic text renderer with multiline support.
  43. See [Text](https://github.com/HeapsIO/heaps/wiki/Text) section of the manual for more details.
  44. **/
  45. class Text extends Drawable {
  46. /**
  47. The font used to render text.
  48. **/
  49. public var font(default, set) : Font;
  50. /**
  51. Current rendered text.
  52. **/
  53. public var text(default, set) : String;
  54. /**
  55. Text RGB color. Alpha value is ignored.
  56. **/
  57. public var textColor(default, set) : Int;
  58. /**
  59. When set, limits maximum line width and causes word-wrap.
  60. Affects positioning of the text depending on `textAlign` value.
  61. When Text is affected by size constraints (see `Object.constraintSize`), smallest of the two is used for word-wrap.
  62. **/
  63. public var maxWidth(default, set) : Null<Float>;
  64. /**
  65. Adds simple drop shadow to the Text with specified offset, color and alpha.
  66. Causes text to be rendered twice (first drop shadow and then the text itself).
  67. **/
  68. public var dropShadow : { dx : Float, dy : Float, color : Int, alpha : Float };
  69. /**
  70. Calculated text width. Can exceed maxWidth in certain cases.
  71. **/
  72. public var textWidth(get, null) : Float;
  73. /**
  74. Calculated text height.
  75. Not a completely precise text metric and increments in the `Font.lineHeight` steps.
  76. In `HtmlText`, can be increased by various values depending on the active line font and `HtmlText.lineHeightMode` value.
  77. **/
  78. public var textHeight(get, null) : Float;
  79. /**
  80. Text align rules dictate how the text lines are positioned.
  81. See `Align` for specific details on each alignment mode.
  82. **/
  83. public var textAlign(default, set) : Align;
  84. /**
  85. Extra letter spacing in pixels.
  86. **/
  87. public var letterSpacing(default, set) : Float = 0;
  88. /**
  89. Extra line spacing in pixels.
  90. **/
  91. public var lineSpacing(default,set) : Float = 0;
  92. /**
  93. Allow line break.
  94. **/
  95. public var lineBreak(default,set) : Bool = true;
  96. var glyphs : TileGroup;
  97. var needsRebuild : Bool;
  98. var currentText : String;
  99. var textChanged : Bool;
  100. var calcDone:Bool;
  101. var calcXMin:Float;
  102. var calcYMin:Float;
  103. var calcWidth:Float;
  104. var calcHeight:Float;
  105. var calcSizeHeight:Float;
  106. var constraintWidth:Float = -1;
  107. var realMaxWidth:Float = -1;
  108. var sdfShader : h3d.shader.SignedDistanceField;
  109. /**
  110. Creates a new Text instance.
  111. @param font The font used to render the Text.
  112. @param parent An optional parent `h2d.Object` instance to which Text adds itself if set.
  113. **/
  114. public function new( font : Font, ?parent : h2d.Object ) {
  115. super(parent);
  116. this.font = font;
  117. textAlign = Left;
  118. text = "";
  119. currentText = "";
  120. textColor = 0xFFFFFF;
  121. }
  122. function set_font(font) {
  123. if( this.font == font ) return font;
  124. this.font = font;
  125. if ( font != null ) {
  126. switch( font.type ) {
  127. case BitmapFont:
  128. if ( sdfShader != null ) {
  129. removeShader(sdfShader);
  130. sdfShader = null;
  131. }
  132. case SignedDistanceField(channel, alphaCutoff, smoothing):
  133. if ( sdfShader == null ) {
  134. sdfShader = new h3d.shader.SignedDistanceField();
  135. addShader(sdfShader);
  136. }
  137. // Automatically use linear sampling if not designated otherwise.
  138. if (smooth == null) smooth = true;
  139. sdfShader.alphaCutoff = alphaCutoff;
  140. sdfShader.smoothing = smoothing;
  141. sdfShader.channel = channel;
  142. sdfShader.autoSmoothing = smoothing == -1;
  143. }
  144. }
  145. if( glyphs != null ) glyphs.remove();
  146. glyphs = new TileGroup(font == null ? null : font.tile, this);
  147. glyphs.visible = false;
  148. rebuild();
  149. return font;
  150. }
  151. function set_textAlign(a) {
  152. if( textAlign == a ) return a;
  153. textAlign = a;
  154. rebuild();
  155. return a;
  156. }
  157. function set_letterSpacing(s) {
  158. if( letterSpacing == s ) return s;
  159. letterSpacing = s;
  160. rebuild();
  161. return s;
  162. }
  163. function set_lineSpacing(s) {
  164. if( lineSpacing == s ) return s;
  165. lineSpacing = s;
  166. rebuild();
  167. return s;
  168. }
  169. function set_lineBreak(b) {
  170. if( lineBreak == b ) return b;
  171. lineBreak = b;
  172. rebuild();
  173. return b;
  174. }
  175. override function constraintSize(width:Float, height:Float) {
  176. constraintWidth = width;
  177. updateConstraint();
  178. }
  179. override function onAdd() {
  180. super.onAdd();
  181. rebuild();
  182. }
  183. inline function checkText() {
  184. if ( textChanged && text != currentText ) {
  185. textChanged = false;
  186. currentText = text;
  187. calcDone = false;
  188. needsRebuild = true;
  189. }
  190. }
  191. override function sync(ctx:RenderContext) {
  192. super.sync(ctx);
  193. checkText();
  194. if ( needsRebuild ) initGlyphs(currentText);
  195. }
  196. override function draw(ctx:RenderContext) {
  197. if( glyphs == null ) {
  198. emitTile(ctx, h2d.Tile.fromColor(0xFF00FF, 16, 16));
  199. return;
  200. }
  201. checkText();
  202. if ( needsRebuild ) initGlyphs(currentText);
  203. if( dropShadow != null ) {
  204. var oldX = absX, oldY = absY;
  205. absX += dropShadow.dx * matA + dropShadow.dy * matC;
  206. absY += dropShadow.dx * matB + dropShadow.dy * matD;
  207. var oldR = color.r;
  208. var oldG = color.g;
  209. var oldB = color.b;
  210. var oldA = color.a;
  211. color.setColor(dropShadow.color);
  212. color.a = dropShadow.alpha * oldA;
  213. glyphs.drawWith(ctx, this);
  214. absX = oldX;
  215. absY = oldY;
  216. color.set(oldR, oldG, oldB, oldA);
  217. }
  218. glyphs.drawWith(ctx,this);
  219. }
  220. function set_text(t : String) {
  221. var t = t == null ? "null" : t;
  222. if( t == this.text ) return t;
  223. this.text = t;
  224. textChanged = true;
  225. validateText();
  226. onContentChanged();
  227. return t;
  228. }
  229. /**
  230. Extra validation of the `text` variable when it's changed. Override to add custom validation.
  231. Only validation of the text is allowed, and attempting to change the text value will lead to undefined behavior.
  232. **/
  233. @:dox(show)
  234. function validateText() {
  235. }
  236. function rebuild() {
  237. calcDone = false;
  238. needsRebuild = true;
  239. onContentChanged();
  240. }
  241. /**
  242. Calculates and returns width of the provided `text` with settings this Text instance.
  243. **/
  244. public function calcTextWidth( text : String ) {
  245. if( calcDone ) {
  246. var ow = calcWidth, oh = calcHeight, osh = calcSizeHeight, ox = calcXMin, oy = calcYMin;
  247. initGlyphs(text, false);
  248. var w = calcWidth;
  249. calcWidth = ow;
  250. calcHeight = oh;
  251. calcSizeHeight = osh;
  252. calcXMin = ox;
  253. calcYMin = oy;
  254. return w;
  255. } else {
  256. initGlyphs(text, false);
  257. calcDone = false;
  258. return calcWidth;
  259. }
  260. }
  261. /**
  262. Perform a word-wrap of the `text` based on this Text settings.
  263. **/
  264. public function splitText( text : String ) {
  265. return splitRawText(text,0,0);
  266. }
  267. /**
  268. <span class="label">Advanced usage</span>
  269. Perform a word-wrap of the text based on this Text settings.
  270. @param text String to word-wrap.
  271. @param leftMargin Starting x offset of the first line.
  272. @param afterData Minimum remaining space required at the end of the line.
  273. @param font Optional overriding font to use instead of currently set.
  274. @param sizes Optional line width array. Will be populated with sizes of split lines if present. Sizes will include both `leftMargin` in it's first line entry.
  275. @param prevChar Optional character code for concatenation purposes (proper kernings).
  276. **/
  277. @:dox(show)
  278. function splitRawText( text : String, leftMargin = 0., afterData = 0., ?font : Font, ?sizes:Array<Float>, ?prevChar:Int = -1 ) {
  279. var maxWidth = realMaxWidth;
  280. if( maxWidth < 0 ) {
  281. if ( sizes == null )
  282. return text;
  283. else
  284. maxWidth = Math.POSITIVE_INFINITY;
  285. }
  286. if ( font == null ) font = this.font;
  287. var lines = [], restPos = 0;
  288. var x = leftMargin;
  289. for( i in 0...text.length ) {
  290. var cc = text.charCodeAt(i);
  291. var e = font.getChar(cc);
  292. var newline = cc == '\n'.code;
  293. var esize = e.width + e.getKerningOffset(prevChar);
  294. var nc = text.charCodeAt(i+1);
  295. if( font.charset.isBreakChar(cc) && (nc == null || !font.charset.isComplementChar(nc)) ) {
  296. if( lines.length == 0 && leftMargin > 0 && x > maxWidth ) {
  297. lines.push("");
  298. if ( sizes != null ) sizes.push(leftMargin);
  299. x -= leftMargin;
  300. }
  301. var size = x + esize + letterSpacing; /* TODO : no letter spacing */
  302. var k = i + 1, max = text.length;
  303. var prevChar = prevChar;
  304. var breakFound = false;
  305. while( size <= maxWidth && k < max ) {
  306. var cc = text.charCodeAt(k++);
  307. if( lineBreak && (font.charset.isSpace(cc) || cc == '\n'.code ) ) {
  308. breakFound = true;
  309. break;
  310. }
  311. var e = font.getChar(cc);
  312. size += e.width + letterSpacing + e.getKerningOffset(prevChar);
  313. prevChar = cc;
  314. var nc = text.charCodeAt(k+1);
  315. if( font.charset.isBreakChar(cc) && (nc == null || !font.charset.isComplementChar(nc)) ) break;
  316. }
  317. if( lineBreak && (size > maxWidth || (!breakFound && size + afterData > maxWidth)) ) {
  318. newline = true;
  319. if( font.charset.isSpace(cc) ){
  320. lines.push(text.substr(restPos, i - restPos));
  321. e = null;
  322. }else{
  323. lines.push(text.substr(restPos, i + 1 - restPos));
  324. }
  325. restPos = i + 1;
  326. }
  327. }
  328. if( e != null && cc != '\n'.code )
  329. x += esize + letterSpacing;
  330. if( newline ) {
  331. if ( sizes != null ) sizes.push(x);
  332. x = 0;
  333. prevChar = -1;
  334. } else
  335. prevChar = cc;
  336. }
  337. if( restPos < text.length ) {
  338. if( lines.length == 0 && leftMargin > 0 && x + afterData - letterSpacing > maxWidth ) {
  339. lines.push("");
  340. if ( sizes != null ) sizes.push(leftMargin);
  341. x -= leftMargin;
  342. }
  343. lines.push(text.substr(restPos, text.length - restPos));
  344. if ( sizes != null ) sizes.push(x);
  345. }
  346. return lines.join("\n");
  347. }
  348. /**
  349. Returns cut `text` based on `progress` percentile.
  350. Can be used to gradually show appearing text. (Especially useful when using `HtmlText`)
  351. **/
  352. public function getTextProgress( text : String, progress : Float ) {
  353. if( progress >= text.length ) return text;
  354. return text.substr(0, Std.int(progress));
  355. }
  356. function initGlyphs( text : String, rebuild = true ) : Void {
  357. if( rebuild ) glyphs.clear();
  358. var x = 0., y = 0., xMax = 0., xMin = 0., yMin = 0., prevChar = -1, linei = 0;
  359. var align = textAlign;
  360. var lines = new Array<Float>();
  361. var dl = font.lineHeight + lineSpacing;
  362. var t = splitRawText(text, 0, 0, lines);
  363. for ( lw in lines ) {
  364. if ( lw > x ) x = lw;
  365. }
  366. calcWidth = x;
  367. switch( align ) {
  368. case Center, Right, MultilineCenter, MultilineRight:
  369. var max = if( align == MultilineCenter || align == MultilineRight ) hxd.Math.ceil(calcWidth) else realMaxWidth < 0 ? 0 : hxd.Math.ceil(realMaxWidth);
  370. var k = align == Center || align == MultilineCenter ? 0.5 : 1;
  371. for( i in 0...lines.length )
  372. lines[i] = Math.ffloor((max - lines[i]) * k);
  373. x = lines[0];
  374. xMin = x;
  375. case Left:
  376. x = 0;
  377. }
  378. for( i in 0...t.length ) {
  379. var cc = t.charCodeAt(i);
  380. var e = font.getChar(cc);
  381. var offs = e.getKerningOffset(prevChar);
  382. var esize = e.width + offs;
  383. // if the next word goes past the max width, change it into a newline
  384. if( cc == '\n'.code ) {
  385. if( x > xMax ) xMax = x;
  386. switch( align ) {
  387. case Left:
  388. x = 0;
  389. case Right, Center, MultilineCenter, MultilineRight:
  390. x = lines[++linei];
  391. if( x < xMin ) xMin = x;
  392. }
  393. y += dl;
  394. prevChar = -1;
  395. } else {
  396. if( e != null ) {
  397. if( rebuild ) glyphs.add(x + offs, y, e.t);
  398. if( y == 0 && e.t.dy < yMin ) yMin = e.t.dy;
  399. x += esize + letterSpacing;
  400. }
  401. prevChar = cc;
  402. }
  403. }
  404. if( x > xMax ) xMax = x;
  405. calcXMin = xMin;
  406. calcYMin = yMin;
  407. calcWidth = xMax - xMin;
  408. calcHeight = y + font.lineHeight;
  409. calcSizeHeight = y + (font.baseLine > 0 ? font.baseLine : font.lineHeight);
  410. calcDone = true;
  411. if ( rebuild ) needsRebuild = false;
  412. }
  413. inline function updateSize() {
  414. checkText();
  415. if ( !calcDone ) initGlyphs(text, needsRebuild);
  416. }
  417. function get_textHeight() {
  418. updateSize();
  419. return calcHeight;
  420. }
  421. function get_textWidth() {
  422. updateSize();
  423. return calcWidth;
  424. }
  425. function set_maxWidth(w) {
  426. if( maxWidth == w ) return w;
  427. maxWidth = w;
  428. updateConstraint();
  429. return w;
  430. }
  431. function updateConstraint() {
  432. var old = realMaxWidth;
  433. if( maxWidth == null )
  434. realMaxWidth = constraintWidth;
  435. else if( constraintWidth < 0 )
  436. realMaxWidth = maxWidth;
  437. else
  438. realMaxWidth = hxd.Math.min(maxWidth, constraintWidth);
  439. if( realMaxWidth != old )
  440. rebuild();
  441. }
  442. function set_textColor(c) {
  443. if( this.textColor == c ) return c;
  444. this.textColor = c;
  445. var a = color.w;
  446. color.setColor(c);
  447. color.w = a;
  448. return c;
  449. }
  450. override function getBoundsRec( relativeTo : Object, out : h2d.col.Bounds, forSize : Bool ) {
  451. super.getBoundsRec(relativeTo, out, forSize);
  452. updateSize();
  453. var x, y, w : Float, h;
  454. if ( forSize ) {
  455. x = calcXMin; // TODO: Should be 0 as well for consistency, but currently causes problems with Flows
  456. y = 0.;
  457. w = calcWidth;
  458. h = calcSizeHeight;
  459. } else {
  460. x = calcXMin;
  461. y = calcYMin;
  462. w = calcWidth;
  463. h = calcHeight - calcYMin;
  464. }
  465. addBounds(relativeTo, out, x, y, w, h);
  466. }
  467. }