TextLayout.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. #include "TextLayout.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <filesystem>
  6. #include <ft2build.h>
  7. #include FT_FREETYPE_H
  8. #include FT_GLYPH_H
  9. #include FT_OUTLINE_H
  10. #include <hb-ft.h>
  11. #include <hb.h>
  12. #include <msdfgen.h>
  13. #include "WallpaperEngine/Logging/Log.h"
  14. using namespace WallpaperEngine::Render::Objects;
  15. namespace {
  16. constexpr char32_t kEllipsis = U'…';
  17. constexpr int kMaxAtlasSize = 4096;
  18. // the whitespace set wallpaper64.exe breaks lines at and trims (bit mask 0x100002200: tab, CR, space)
  19. bool isBreakSpace (char32_t c) { return c == U'\t' || c == U'\r' || c == U' '; }
  20. std::u32string decodeUtf8 (const std::string& text) {
  21. std::u32string codepoints;
  22. size_t i = 0;
  23. while (i < text.size ()) {
  24. const auto lead = static_cast<unsigned char> (text[i]);
  25. size_t extraBytes;
  26. char32_t codepoint;
  27. if ((lead & 0x80) == 0x00) {
  28. codepoint = lead;
  29. extraBytes = 0;
  30. } else if ((lead & 0xE0) == 0xC0) {
  31. codepoint = lead & 0x1F;
  32. extraBytes = 1;
  33. } else if ((lead & 0xF0) == 0xE0) {
  34. codepoint = lead & 0x0F;
  35. extraBytes = 2;
  36. } else if ((lead & 0xF8) == 0xF0) {
  37. codepoint = lead & 0x07;
  38. extraBytes = 3;
  39. } else {
  40. i++;
  41. continue;
  42. }
  43. if (i + extraBytes >= text.size ()) {
  44. break;
  45. }
  46. bool valid = true;
  47. for (size_t k = 1; k <= extraBytes; k++) {
  48. const auto cont = static_cast<unsigned char> (text[i + k]);
  49. if ((cont & 0xC0) != 0x80) {
  50. valid = false;
  51. break;
  52. }
  53. codepoint = (codepoint << 6) | (cont & 0x3F);
  54. }
  55. if (!valid) {
  56. i++;
  57. continue;
  58. }
  59. codepoints.push_back (codepoint);
  60. i += extraBytes + 1;
  61. }
  62. return codepoints;
  63. }
  64. void trimTrailingSpaces (std::u32string& line) {
  65. while (!line.empty () && isBreakSpace (line.back ())) {
  66. line.pop_back ();
  67. }
  68. }
  69. // sub_1401B0360: what the last line kept by the row limit gets
  70. void finishLastRow (std::u32string& line, bool ellipsis) {
  71. trimTrailingSpaces (line);
  72. if (ellipsis && (line.empty () || line.back () != kEllipsis)) {
  73. line.push_back (kEllipsis);
  74. }
  75. }
  76. uint64_t glyphKey (size_t face, uint32_t glyph) { return (static_cast<uint64_t> (face) << 32) | glyph; }
  77. // WE falls back to a fixed list of Windows fonts for characters the wallpaper's font lacks, ask fontconfig for any
  78. // installed outline font that has the character instead
  79. std::string fontForCodepoint (char32_t codepoint) {
  80. // every text object asks for the same characters, fc-match is only run once per character
  81. static std::unordered_map<char32_t, std::string> cache;
  82. if (const auto it = cache.find (codepoint); it != cache.end ()) {
  83. return it->second;
  84. }
  85. char pattern[64];
  86. std::snprintf (pattern, sizeof (pattern), "sans-serif:scalable=true:charset=%x", static_cast<unsigned> (codepoint));
  87. const std::string command = std::string ("fc-match -f '%{file}' '") + pattern + "' 2>/dev/null";
  88. FILE* pipe = popen (command.c_str (), "r");
  89. if (pipe == nullptr) {
  90. return {};
  91. }
  92. std::string path;
  93. char buffer[512];
  94. while (fgets (buffer, sizeof (buffer), pipe) != nullptr) {
  95. path += buffer;
  96. }
  97. pclose (pipe);
  98. if (path.empty () || !std::filesystem::exists (path)) {
  99. path.clear ();
  100. }
  101. return cache.emplace (codepoint, path).first->second;
  102. }
  103. struct OutlineContext {
  104. msdfgen::Shape* shape;
  105. msdfgen::Contour* contour = nullptr;
  106. msdfgen::Point2 position;
  107. };
  108. // FT_Outline_Decompose into a msdfgen shape at 1/64 scale (26.6 -> pixels), like wallpaper64.exe's callbacks
  109. msdfgen::Point2 outlinePoint (const FT_Vector* vector) { return { vector->x / 64.0, vector->y / 64.0 }; }
  110. int outlineMoveTo (const FT_Vector* to, void* user) {
  111. auto* context = static_cast<OutlineContext*> (user);
  112. if (!(context->contour != nullptr && context->contour->edges.empty ())) {
  113. context->contour = &context->shape->addContour ();
  114. }
  115. context->position = outlinePoint (to);
  116. return 0;
  117. }
  118. int outlineLineTo (const FT_Vector* to, void* user) {
  119. auto* context = static_cast<OutlineContext*> (user);
  120. const msdfgen::Point2 endpoint = outlinePoint (to);
  121. if (context->contour != nullptr && endpoint != context->position) {
  122. context->contour->addEdge (msdfgen::EdgeHolder (context->position, endpoint));
  123. context->position = endpoint;
  124. }
  125. return 0;
  126. }
  127. int outlineConicTo (const FT_Vector* control, const FT_Vector* to, void* user) {
  128. auto* context = static_cast<OutlineContext*> (user);
  129. if (context->contour != nullptr) {
  130. const msdfgen::Point2 endpoint = outlinePoint (to);
  131. context->contour->addEdge (msdfgen::EdgeHolder (context->position, outlinePoint (control), endpoint));
  132. context->position = endpoint;
  133. }
  134. return 0;
  135. }
  136. int outlineCubicTo (const FT_Vector* control1, const FT_Vector* control2, const FT_Vector* to, void* user) {
  137. auto* context = static_cast<OutlineContext*> (user);
  138. if (context->contour != nullptr) {
  139. const msdfgen::Point2 endpoint = outlinePoint (to);
  140. context->contour->addEdge (
  141. msdfgen::EdgeHolder (context->position, outlinePoint (control1), outlinePoint (control2), endpoint)
  142. );
  143. context->position = endpoint;
  144. }
  145. return 0;
  146. }
  147. constexpr float kDistanceInfinity = 1e20f;
  148. // sub_1401AC130: Felzenszwalb's 1D squared distance transform of f in place (float, like WE's)
  149. void distanceTransform1D (std::vector<float>& f, std::vector<float>& d, std::vector<int>& v, std::vector<float>& z) {
  150. const int n = static_cast<int> (f.size ());
  151. if (n <= 0) {
  152. return;
  153. }
  154. int k = 0;
  155. v[0] = 0;
  156. z[0] = -kDistanceInfinity;
  157. z[1] = kDistanceInfinity;
  158. for (int q = 1; q < n; q++) {
  159. const float fq = static_cast<float> (q) * static_cast<float> (q) + f[q];
  160. float s = (fq - (static_cast<float> (v[k]) * static_cast<float> (v[k]) + f[v[k]]))
  161. / static_cast<float> (2 * (q - v[k]));
  162. while (s <= z[k]) {
  163. k--;
  164. s = (fq - (static_cast<float> (v[k]) * static_cast<float> (v[k]) + f[v[k]]))
  165. / static_cast<float> (2 * (q - v[k]));
  166. }
  167. k++;
  168. v[k] = q;
  169. z[k] = s;
  170. z[k + 1] = kDistanceInfinity;
  171. }
  172. k = 0;
  173. for (int q = 0; q < n; q++) {
  174. while (static_cast<float> (q) > z[k + 1]) {
  175. k++;
  176. }
  177. d[q] = static_cast<float> ((q - v[k]) * (q - v[k])) + f[v[k]];
  178. }
  179. f = d;
  180. }
  181. // sub_1401AC3B0: squared distances to the nearest 0 cell, columns first, then rows
  182. void distanceTransform2D (std::vector<float>& grid, int width, int height) {
  183. const int longest = std::max (width, height);
  184. std::vector<float> line;
  185. std::vector<float> scratch (longest);
  186. std::vector<int> v (longest);
  187. std::vector<float> z (longest + 1);
  188. for (int x = 0; x < width; x++) {
  189. line.resize (height);
  190. scratch.resize (height);
  191. for (int y = 0; y < height; y++) {
  192. line[y] = grid[x + y * width];
  193. }
  194. distanceTransform1D (line, scratch, v, z);
  195. for (int y = 0; y < height; y++) {
  196. grid[x + y * width] = line[y];
  197. }
  198. }
  199. for (int y = 0; y < height; y++) {
  200. line.assign (grid.begin () + static_cast<long> (y) * width, grid.begin () + static_cast<long> (y + 1) * width);
  201. scratch.resize (width);
  202. distanceTransform1D (line, scratch, v, z);
  203. std::ranges::copy (line, grid.begin () + static_cast<long> (y) * width);
  204. }
  205. }
  206. // sub_1401AC4E0: bilinear sample of a BGRA bitmap at pixel coordinates, RGBA out, transparent outside it
  207. void sampleBitmapBGRA (const FT_Bitmap& bitmap, float x, float y, uint8_t* out) {
  208. const int maxX = static_cast<int> (bitmap.width) - 1;
  209. const int maxY = static_cast<int> (bitmap.rows) - 1;
  210. if (x < 0.0f || x > static_cast<float> (maxX) || y < 0.0f || y > static_cast<float> (maxY)) {
  211. out[0] = out[1] = out[2] = out[3] = 0;
  212. return;
  213. }
  214. const float floorX = std::floor (x);
  215. const float floorY = std::floor (y);
  216. const float fx = x - floorX;
  217. const float fy = y - floorY;
  218. const int x0 = static_cast<int> (floorX);
  219. const int y0 = static_cast<int> (floorY);
  220. const int x1 = std::min (x0 + 1, maxX);
  221. const int y1 = std::min (y0 + 1, maxY);
  222. const uint8_t* row0 = bitmap.buffer + static_cast<long> (y0) * bitmap.pitch;
  223. const uint8_t* row1 = bitmap.buffer + static_cast<long> (y1) * bitmap.pitch;
  224. uint8_t texel[4];
  225. for (int channel = 0; channel < 4; channel++) {
  226. const float value = static_cast<float> (row0[x1 * 4 + channel]) * ((1.0f - fy) * fx)
  227. + static_cast<float> (row0[x0 * 4 + channel]) * ((1.0f - fy) * (1.0f - fx))
  228. + static_cast<float> (row1[x0 * 4 + channel]) * ((1.0f - fx) * fy)
  229. + static_cast<float> (row1[x1 * 4 + channel]) * (fy * fx);
  230. texel[channel] = static_cast<uint8_t> (std::clamp (static_cast<int> (value + 0.5f), 0, 255));
  231. }
  232. out[0] = texel[2];
  233. out[1] = texel[1];
  234. out[2] = texel[0];
  235. out[3] = texel[3];
  236. }
  237. } // namespace
  238. TextLayout::TextLayout () {
  239. if (FT_Init_FreeType (&m_library) != 0) {
  240. m_library = nullptr;
  241. sLog.error ("TextLayout: FT_Init_FreeType failed");
  242. }
  243. m_colorAtlas.channels = 4;
  244. this->resetAtlases ();
  245. }
  246. TextLayout::~TextLayout () {
  247. this->clearFaces ();
  248. if (m_library != nullptr) {
  249. FT_Done_FreeType (m_library);
  250. }
  251. }
  252. void TextLayout::clearFaces () {
  253. for (const auto& face : m_faces) {
  254. if (face->font != nullptr) {
  255. hb_font_destroy (face->font);
  256. }
  257. if (face->face != nullptr) {
  258. FT_Done_Face (face->face);
  259. }
  260. }
  261. m_faces.clear ();
  262. m_fallbacksLoaded = false;
  263. m_fallbackTried.clear ();
  264. m_boxes.clear ();
  265. m_glyphs.clear ();
  266. this->resetAtlases ();
  267. }
  268. bool TextLayout::setPrimaryFont (std::vector<uint8_t> data, const std::string& path) {
  269. this->clearFaces ();
  270. return this->addFace (
  271. data.empty () ? nullptr : std::make_shared<const std::vector<uint8_t>> (std::move (data)), path
  272. );
  273. }
  274. void TextLayout::setFallbackFonts (std::vector<TextFontSource> fonts) {
  275. m_fallbackSources = std::move (fonts);
  276. }
  277. bool TextLayout::addFace (std::shared_ptr<const std::vector<uint8_t>> data, const std::string& path) {
  278. if (m_library == nullptr) {
  279. return false;
  280. }
  281. auto face = std::make_unique<Face> ();
  282. face->data = std::move (data);
  283. face->path = path;
  284. const FT_Error error = face->data == nullptr
  285. ? FT_New_Face (m_library, path.c_str (), 0, &face->face)
  286. : FT_New_Memory_Face (
  287. m_library, face->data->data (), static_cast<FT_Long> (face->data->size ()), 0, &face->face
  288. );
  289. if (error != 0) {
  290. sLog.error ("TextLayout: cannot load font '", path, "' (FreeType error ", error, ")");
  291. return false;
  292. }
  293. // bitmap-only fonts (colour emoji strikes) can't be sized to an arbitrary raster size
  294. if (!FT_IS_SCALABLE (face->face)) {
  295. FT_Done_Face (face->face);
  296. return false;
  297. }
  298. FT_Select_Charmap (face->face, FT_ENCODING_UNICODE);
  299. face->color = FT_HAS_COLOR (face->face);
  300. if (m_size > 0.0f) {
  301. FT_Set_Char_Size (face->face, 0, static_cast<FT_F26Dot6> (m_size * 64.0f), 300, 300);
  302. }
  303. face->font = hb_ft_font_create (face->face, nullptr);
  304. m_faces.push_back (std::move (face));
  305. return true;
  306. }
  307. void TextLayout::applySize (float size) {
  308. if (size == m_size) {
  309. return;
  310. }
  311. m_size = size;
  312. for (const auto& face : m_faces) {
  313. FT_Set_Char_Size (face->face, 0, static_cast<FT_F26Dot6> (size * 64.0f), 300, 300);
  314. hb_ft_font_changed (face->font);
  315. }
  316. m_boxes.clear ();
  317. m_glyphs.clear ();
  318. this->resetAtlases ();
  319. }
  320. int TextLayout::faceFor (char32_t codepoint) {
  321. const auto findLoaded = [this, codepoint] () {
  322. for (size_t i = 0; i < m_faces.size (); i++) {
  323. if (FT_Get_Char_Index (m_faces[i]->face, codepoint) != 0) {
  324. return static_cast<int> (i);
  325. }
  326. }
  327. return -1;
  328. };
  329. if (const int face = findLoaded (); face >= 0) {
  330. return face;
  331. }
  332. if (codepoint < 0x20) {
  333. return -1;
  334. }
  335. // WE's fixed fallback list (sub_1401AD670) comes right after the primary font, fontconfig's picks after that
  336. if (!m_fallbacksLoaded) {
  337. m_fallbacksLoaded = true;
  338. for (const auto& source : m_fallbackSources) {
  339. this->addFace (source.data, source.path);
  340. }
  341. if (const int face = findLoaded (); face >= 0) {
  342. return face;
  343. }
  344. }
  345. if (!m_fallbackTried.insert (codepoint).second) {
  346. return -1;
  347. }
  348. const std::string path = fontForCodepoint (codepoint);
  349. if (path.empty ()) {
  350. return -1;
  351. }
  352. for (const auto& face : m_faces) {
  353. if (face->path == path) {
  354. return -1;
  355. }
  356. }
  357. if (!this->addFace ({}, path) || FT_Get_Char_Index (m_faces.back ()->face, codepoint) == 0) {
  358. return -1;
  359. }
  360. return static_cast<int> (m_faces.size () - 1);
  361. }
  362. // sub_1401AD670: one run per stretch of text a single face covers, zero width joiners and whitespace stay in the
  363. // current run
  364. std::vector<TextLayout::Run> TextLayout::itemize (const std::u32string& line) {
  365. std::vector<Run> runs;
  366. for (size_t i = 0; i < line.size (); i++) {
  367. const char32_t c = line[i];
  368. const bool keepsRun = c == 0x200D || c == U'\t' || c == U'\n' || c == U'\r' || c == U' ';
  369. if (keepsRun && !runs.empty ()) {
  370. runs.back ().text.push_back (c);
  371. continue;
  372. }
  373. int face = this->faceFor (c);
  374. if (face < 0) {
  375. face = runs.empty () ? 0 : static_cast<int> (runs.back ().face);
  376. }
  377. if (runs.empty () || runs.back ().face != static_cast<size_t> (face)) {
  378. runs.push_back ({ static_cast<size_t> (face), i, {} });
  379. }
  380. runs.back ().text.push_back (c);
  381. }
  382. return runs;
  383. }
  384. std::vector<TextLayout::ShapedGlyph> TextLayout::shape (const std::u32string& line, const TextLayoutParams& params) {
  385. std::vector<ShapedGlyph> glyphs;
  386. for (const auto& run : this->itemize (line)) {
  387. const Face& face = *m_faces[run.face];
  388. hb_buffer_t* buffer = hb_buffer_create ();
  389. hb_buffer_add_utf32 (
  390. buffer, reinterpret_cast<const uint32_t*> (run.text.data ()), static_cast<int> (run.text.size ()), 0, -1
  391. );
  392. hb_buffer_guess_segment_properties (buffer);
  393. hb_shape (face.font, buffer, nullptr, 0);
  394. unsigned int count = 0;
  395. const hb_glyph_info_t* infos = hb_buffer_get_glyph_infos (buffer, &count);
  396. const hb_glyph_position_t* positions = hb_buffer_get_glyph_positions (buffer, nullptr);
  397. const float pad = params.msdf
  398. ? static_cast<float> (std::max<int> (face.face->size->metrics.y_ppem, 1)) * 12.0f * 0.03125f
  399. : 0.0f;
  400. for (unsigned int i = 0; i < count; i++) {
  401. const uint32_t glyph = infos[i].codepoint;
  402. // WE's glyph fetch fails on .notdef, which leaves the character out without advancing the pen
  403. const AtlasGlyph* entry = glyph == 0 ? nullptr : this->atlasGlyph (run.face, glyph);
  404. if (entry == nullptr) {
  405. continue;
  406. }
  407. // the quad comes from the outline's box (sub_1401ADDB0, loaded without bitmaps). Segoe UI Emoji, the colour
  408. // font WE finds first on Windows, has monochrome outlines under its colour layers, Twemoji (the fallback left
  409. // on Linux) has none, which would give its emoji an empty quad: their bitmap's box stands in there
  410. const GlyphBox* box = this->glyphBox (run.face, glyph);
  411. GlyphBox bounds = box != nullptr ? *box : GlyphBox {};
  412. if (entry->color && bounds.x0 == bounds.x1 && bounds.y0 == bounds.y1) {
  413. bounds = entry->bitmapBox;
  414. }
  415. const int xOffset = positions[i].x_offset >> 6;
  416. const int yOffset = positions[i].y_offset >> 6;
  417. const uint32_t cluster = infos[i].cluster + static_cast<uint32_t> (run.start);
  418. glyphs.push_back (
  419. {
  420. .key = glyphKey (run.face, glyph),
  421. .cluster = cluster,
  422. .codepoint = cluster < line.size () ? line[cluster] : 0,
  423. .advance = static_cast<float> (positions[i].x_advance >> 6) + params.spacing.x,
  424. .yAdvance = static_cast<float> (positions[i].y_advance >> 6),
  425. .x0 = static_cast<float> (xOffset + bounds.x0),
  426. .y0 = static_cast<float> (yOffset + bounds.y0),
  427. .x1 = static_cast<float> (xOffset + bounds.x1),
  428. .y1 = static_cast<float> (yOffset + bounds.y1),
  429. .pad = pad,
  430. .color = entry->color,
  431. }
  432. );
  433. }
  434. hb_buffer_destroy (buffer);
  435. }
  436. return glyphs;
  437. }
  438. float TextLayout::measureRight (const std::u32string& line) {
  439. float pen = 0.0f;
  440. float right = 0.0f;
  441. for (const auto& run : this->itemize (line)) {
  442. hb_buffer_t* buffer = hb_buffer_create ();
  443. hb_buffer_add_utf32 (
  444. buffer, reinterpret_cast<const uint32_t*> (run.text.data ()), static_cast<int> (run.text.size ()), 0, -1
  445. );
  446. hb_buffer_guess_segment_properties (buffer);
  447. hb_shape (m_faces[run.face]->font, buffer, nullptr, 0);
  448. unsigned int count = 0;
  449. const hb_glyph_info_t* infos = hb_buffer_get_glyph_infos (buffer, &count);
  450. const hb_glyph_position_t* positions = hb_buffer_get_glyph_positions (buffer, nullptr);
  451. for (unsigned int i = 0; i < count; i++) {
  452. if (const GlyphBox* box = this->glyphBox (run.face, infos[i].codepoint); box != nullptr) {
  453. right = static_cast<float> (positions[i].x_offset >> 6) + pen + static_cast<float> (box->x1);
  454. pen += static_cast<float> (positions[i].x_advance >> 6);
  455. }
  456. }
  457. hb_buffer_destroy (buffer);
  458. }
  459. return right;
  460. }
  461. // sub_1401ADDB0: the outline's pixel grid fitted control box, loaded without bitmaps
  462. const TextLayout::GlyphBox* TextLayout::glyphBox (size_t face, uint32_t glyph) {
  463. const uint64_t key = glyphKey (face, glyph);
  464. if (const auto it = m_boxes.find (key); it != m_boxes.end ()) {
  465. return &it->second;
  466. }
  467. FT_Face ftFace = m_faces[face]->face;
  468. FT_Glyph ftGlyph = nullptr;
  469. if (FT_Load_Glyph (ftFace, glyph, FT_LOAD_NO_BITMAP) != 0 || FT_Get_Glyph (ftFace->glyph, &ftGlyph) != 0) {
  470. return nullptr;
  471. }
  472. FT_BBox bbox;
  473. FT_Glyph_Get_CBox (ftGlyph, FT_GLYPH_BBOX_PIXELS, &bbox);
  474. FT_Done_Glyph (ftGlyph);
  475. return &m_boxes
  476. .emplace (
  477. key,
  478. GlyphBox { static_cast<int> (bbox.xMin), static_cast<int> (bbox.yMin), static_cast<int> (bbox.xMax),
  479. static_cast<int> (bbox.yMax) }
  480. )
  481. .first->second;
  482. }
  483. TextLayout::AtlasGlyph* TextLayout::atlasGlyph (size_t face, uint32_t glyph) {
  484. const uint64_t key = glyphKey (face, glyph);
  485. if (const auto it = m_glyphs.find (key); it != m_glyphs.end ()) {
  486. return &it->second;
  487. }
  488. AtlasGlyph entry;
  489. const Face& source = *m_faces[face];
  490. // sub_1401AE080: plain glyphs are rendered with FT_LOAD_RENDER | FT_LOAD_COLOR, in MSDF mode fonts with colour
  491. // glyphs are too (their BGRA bitmaps become distance fields), the rest are outlines
  492. bool rendered;
  493. if (!m_msdf) {
  494. rendered = this->renderPlainGlyph (source.face, glyph, entry);
  495. } else if (source.color) {
  496. rendered = this->renderColorMsdfGlyph (source.face, glyph, entry);
  497. } else {
  498. rendered = this->renderMsdfGlyph (source.face, glyph, entry);
  499. }
  500. if (!rendered) {
  501. return nullptr;
  502. }
  503. auto& stored = m_glyphs.emplace (key, std::move (entry)).first->second;
  504. if (!this->pack (stored.color ? m_colorAtlas : m_atlas, key, stored)) {
  505. m_atlasFull = true;
  506. }
  507. return &stored;
  508. }
  509. bool TextLayout::renderPlainGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out) {
  510. if (FT_Load_Glyph (face, glyph, FT_LOAD_RENDER | FT_LOAD_COLOR) != 0) {
  511. return false;
  512. }
  513. const FT_GlyphSlot slot = face->glyph;
  514. const FT_Bitmap& bitmap = slot->bitmap;
  515. out.width = static_cast<int> (bitmap.width);
  516. out.height = static_cast<int> (bitmap.rows);
  517. // colour bitmaps go to the RGBA atlas as they are, premultiplied, with red and blue swapped
  518. if (bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
  519. out.color = true;
  520. out.bitmapBox = { slot->bitmap_left, slot->bitmap_top - out.height, slot->bitmap_left + out.width,
  521. slot->bitmap_top };
  522. out.pixels.assign (static_cast<size_t> (out.width) * out.height * 4, 0);
  523. for (int row = 0; row < out.height; row++) {
  524. const uint8_t* src = bitmap.buffer + static_cast<long> (row) * bitmap.pitch;
  525. uint8_t* dst = &out.pixels[static_cast<size_t> (row) * out.width * 4];
  526. for (int col = 0; col < out.width; col++) {
  527. dst[col * 4 + 0] = src[col * 4 + 2];
  528. dst[col * 4 + 1] = src[col * 4 + 1];
  529. dst[col * 4 + 2] = src[col * 4 + 0];
  530. dst[col * 4 + 3] = src[col * 4 + 3];
  531. }
  532. }
  533. return true;
  534. }
  535. out.pixels.assign (static_cast<size_t> (out.width) * out.height, 0);
  536. if (bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) {
  537. for (int row = 0; row < out.height; row++) {
  538. std::copy_n (bitmap.buffer + row * bitmap.pitch, out.width, out.pixels.begin () + row * out.width);
  539. }
  540. }
  541. return true;
  542. }
  543. // sub_1401AE080 for a colour glyph in MSDF mode: the bitmap's alpha (inside from 128 on) becomes a signed distance
  544. // field laid out like the MSDF glyphs (32 px per em, 12 px of range around it), stored in all four channels, and the
  545. // colours are resampled at the colour atlas' scale into its colour texture
  546. bool TextLayout::renderColorMsdfGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out) {
  547. if (FT_Load_Glyph (face, glyph, FT_LOAD_RENDER | FT_LOAD_COLOR) != 0) {
  548. return false;
  549. }
  550. const FT_GlyphSlot slot = face->glyph;
  551. const FT_Bitmap& bitmap = slot->bitmap;
  552. // a glyph of a colour font without colour layers: WE copies its grey bitmap into the RGBA atlas as if it had one
  553. // byte per pixel, which leaves the glyph's own cell empty
  554. if (bitmap.pixel_mode != FT_PIXEL_MODE_BGRA) {
  555. out.width = static_cast<int> (bitmap.width);
  556. out.height = static_cast<int> (bitmap.rows);
  557. out.pixels.assign (static_cast<size_t> (out.width) * out.height * 4, 0);
  558. return true;
  559. }
  560. const int bitmapWidth = static_cast<int> (bitmap.width);
  561. const int bitmapHeight = static_cast<int> (bitmap.rows);
  562. // FT_Glyph_Get_CBox of a bitmap glyph in pixels
  563. const int boxX0 = slot->bitmap_left;
  564. const int boxY0 = slot->bitmap_top - bitmapHeight;
  565. const int boxWidth = bitmapWidth;
  566. const int boxHeight = bitmapHeight;
  567. int width = 0;
  568. int height = 0;
  569. out.color = true;
  570. out.bitmapBox = { boxX0, boxY0, boxX0 + boxWidth, boxY0 + boxHeight };
  571. // sub_1401ADF30: the first colour glyph picks the colour texture's scale for the whole font set
  572. if (m_colorAtlas.colorScale == 0) {
  573. m_colorAtlas.colorScale = std::max (1, (std::max (boxWidth, boxHeight) + 31) / 32);
  574. m_colorAtlas.colorPixels.assign (
  575. static_cast<size_t> (m_colorAtlas.size) * m_colorAtlas.colorScale * m_colorAtlas.size
  576. * m_colorAtlas.colorScale * 4,
  577. 0
  578. );
  579. }
  580. if (boxWidth > 0 && boxHeight > 0) {
  581. const float toAtlas = 32.0f / static_cast<float> (std::max<int> (face->size->metrics.y_ppem, 1));
  582. width = std::max (1, static_cast<int> (static_cast<float> (boxWidth) * toAtlas));
  583. height = std::max (1, static_cast<int> (static_cast<float> (boxHeight) * toAtlas));
  584. }
  585. out.width = width + 24;
  586. out.height = height + 24;
  587. out.pixels.assign (static_cast<size_t> (out.width) * out.height * 4, 0);
  588. const int colorScale = m_colorAtlas.colorScale;
  589. out.colorPixels.assign (static_cast<size_t> (out.width) * colorScale * out.height * colorScale * 4, 0);
  590. if (width <= 0 || height <= 0 || bitmap.buffer == nullptr) {
  591. return true;
  592. }
  593. const float scale = static_cast<float> (std::max (width, height))
  594. / std::max (static_cast<float> (boxHeight), static_cast<float> (boxWidth));
  595. const float range = 24.0f / scale;
  596. const double translateX = static_cast<double> (12.0f / scale - static_cast<float> (boxX0));
  597. const double translateY = static_cast<double> (12.0f / scale - static_cast<float> (boxY0));
  598. // sub_1401AB9C0: squared distances to the nearest inside and outside texels, signed distance at texel centers
  599. std::vector<float> toInside (static_cast<size_t> (bitmapWidth) * bitmapHeight);
  600. std::vector<float> toOutside (toInside.size ());
  601. for (int y = 0; y < bitmapHeight; y++) {
  602. for (int x = 0; x < bitmapWidth; x++) {
  603. const bool inside = bitmap.buffer[static_cast<long> (y) * bitmap.pitch + x * 4 + 3] >= 0x80;
  604. toInside[x + y * bitmapWidth] = inside ? 0.0f : kDistanceInfinity;
  605. toOutside[x + y * bitmapWidth] = inside ? kDistanceInfinity : 0.0f;
  606. }
  607. }
  608. distanceTransform2D (toInside, bitmapWidth, bitmapHeight);
  609. distanceTransform2D (toOutside, bitmapWidth, bitmapHeight);
  610. std::vector<float> field (toInside.size ());
  611. for (int y = 0; y < bitmapHeight; y++) {
  612. for (int x = 0; x < bitmapWidth; x++) {
  613. const size_t i = x + y * bitmapWidth;
  614. const bool inside = bitmap.buffer[static_cast<long> (y) * bitmap.pitch + x * 4 + 3] >= 0x80;
  615. field[i] = inside ? std::sqrt (toOutside[i]) - 0.5f : 0.5f - std::sqrt (toInside[i]);
  616. }
  617. }
  618. const float inverseRange = 1.0f / range;
  619. const auto toByte = [] (float value) {
  620. return static_cast<uint8_t> (std::clamp (static_cast<int> (value * 256.0f), 0, 255));
  621. };
  622. for (int y = 0; y < out.height; y++) {
  623. const float glyphY = static_cast<float> ((static_cast<float> (y) + 0.5) / scale - translateY);
  624. const float bitmapY = static_cast<float> (slot->bitmap_top) - glyphY;
  625. for (int x = 0; x < out.width; x++) {
  626. const float glyphX = static_cast<float> ((static_cast<float> (x) + 0.5) / scale - translateX);
  627. const float bitmapX = glyphX - static_cast<float> (slot->bitmap_left);
  628. // outside the bitmap the distance to its edge adds on
  629. const float clampedX = bitmapX >= static_cast<float> (bitmapWidth - 1)
  630. ? static_cast<float> (bitmapWidth - 1)
  631. : (bitmapX <= 0.0f ? 0.0f : bitmapX);
  632. const float clampedY = bitmapY >= static_cast<float> (bitmapHeight - 1)
  633. ? static_cast<float> (bitmapHeight - 1)
  634. : (bitmapY <= 0.0f ? 0.0f : bitmapY);
  635. const float dx = bitmapX - clampedX;
  636. const float dy = bitmapY - clampedY;
  637. const float outside = std::sqrt (dy * dy + dx * dx);
  638. const float floorX = std::floor (clampedX);
  639. const float floorY = std::floor (clampedY);
  640. const float fx = clampedX - floorX;
  641. const float fy = clampedY - floorY;
  642. const int x0 = static_cast<int> (floorX);
  643. const int y0 = static_cast<int> (floorY);
  644. const int x1 = std::min (x0 + 1, bitmapWidth - 1);
  645. const int y1 = std::min (y0 + 1, bitmapHeight - 1);
  646. const float top = (1.0f - fx) * field[x0 + y0 * bitmapWidth] + fx * field[x1 + y0 * bitmapWidth];
  647. const float bottom = (1.0f - fx) * field[x0 + y1 * bitmapWidth] + fx * field[x1 + y1 * bitmapWidth];
  648. const float value = ((top * (1.0f - fy) + bottom * fy) - outside) * inverseRange + 0.5f;
  649. // rows go bottom up here, the atlas is stored top down
  650. uint8_t* dst = &out.pixels[(static_cast<size_t> (out.height - y - 1) * out.width + x) * 4];
  651. dst[0] = dst[1] = dst[2] = dst[3] = toByte (value);
  652. }
  653. }
  654. const int colorWidth = out.width * colorScale;
  655. const int colorHeight = out.height * colorScale;
  656. const double colorToGlyph = static_cast<double> (static_cast<float> (colorScale) * scale);
  657. for (int row = 0; row < colorHeight; row++) {
  658. const float glyphY
  659. = static_cast<float> ((static_cast<float> (colorHeight - row - 1) + 0.5) / colorToGlyph - translateY);
  660. const float bitmapY = static_cast<float> (slot->bitmap_top) - glyphY;
  661. for (int col = 0; col < colorWidth; col++) {
  662. const float glyphX = static_cast<float> ((static_cast<float> (col) + 0.5) / colorToGlyph - translateX);
  663. sampleBitmapBGRA (
  664. bitmap, glyphX - static_cast<float> (slot->bitmap_left), bitmapY,
  665. &out.colorPixels[(static_cast<size_t> (row) * colorWidth + col) * 4]
  666. );
  667. }
  668. }
  669. return true;
  670. }
  671. // sub_1401AE080: an MSDF of the glyph at 32 pixels per em with 12 pixels of distance range around it
  672. bool TextLayout::renderMsdfGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out) {
  673. FT_Glyph ftGlyph = nullptr;
  674. if (FT_Load_Glyph (face, glyph, FT_LOAD_NO_BITMAP) != 0 || face->glyph->format != FT_GLYPH_FORMAT_OUTLINE
  675. || FT_Get_Glyph (face->glyph, &ftGlyph) != 0) {
  676. return false;
  677. }
  678. FT_BBox bbox;
  679. FT_Glyph_Get_CBox (ftGlyph, FT_GLYPH_BBOX_PIXELS, &bbox);
  680. FT_Done_Glyph (ftGlyph);
  681. const int boxWidth = static_cast<int> (bbox.xMax - bbox.xMin);
  682. const int boxHeight = static_cast<int> (bbox.yMax - bbox.yMin);
  683. int width = 0;
  684. int height = 0;
  685. if (boxWidth > 0 && boxHeight > 0) {
  686. const float toAtlas = 32.0f / static_cast<float> (std::max<int> (face->size->metrics.y_ppem, 1));
  687. width = std::max (1, static_cast<int> (static_cast<float> (boxWidth) * toAtlas));
  688. height = std::max (1, static_cast<int> (static_cast<float> (boxHeight) * toAtlas));
  689. }
  690. out.width = width + 24;
  691. out.height = height + 24;
  692. out.pixels.assign (static_cast<size_t> (out.width) * out.height * 4, 0);
  693. if (width <= 0 || height <= 0) {
  694. return true;
  695. }
  696. msdfgen::Shape shape;
  697. OutlineContext context { &shape };
  698. FT_Outline_Funcs funcs {
  699. .move_to = outlineMoveTo,
  700. .line_to = outlineLineTo,
  701. .conic_to = outlineConicTo,
  702. .cubic_to = outlineCubicTo,
  703. .shift = 0,
  704. .delta = 0,
  705. };
  706. if (FT_Outline_Decompose (&face->glyph->outline, &funcs, &context) != 0) {
  707. return true;
  708. }
  709. if (!shape.contours.empty () && shape.contours.back ().edges.empty ()) {
  710. shape.contours.pop_back ();
  711. }
  712. if (shape.contours.empty ()) {
  713. return true;
  714. }
  715. shape.normalize ();
  716. shape.orientContours ();
  717. // WE's seed argument is whatever the previous call left in the register, msdfgen's default is used here
  718. msdfgen::edgeColoringSimple (shape, 3.0);
  719. const float scale = static_cast<float> (std::max (width, height))
  720. / std::max (static_cast<float> (boxHeight), static_cast<float> (boxWidth));
  721. const float range = 24.0f / scale;
  722. const msdfgen::Projection projection (
  723. msdfgen::Vector2 (scale),
  724. msdfgen::Vector2 (
  725. 12.0f / scale - static_cast<float> (bbox.xMin), 12.0f / scale - static_cast<float> (bbox.yMin)
  726. )
  727. );
  728. const msdfgen::SDFTransformation transformation (projection, msdfgen::DistanceMapping (msdfgen::Range (range)));
  729. msdfgen::Bitmap<float, 3> msdf (out.width, out.height);
  730. msdfgen::MSDFGeneratorConfig generatorConfig (
  731. true, msdfgen::ErrorCorrectionConfig (msdfgen::ErrorCorrectionConfig::DISABLED)
  732. );
  733. msdfgen::generateMSDF (msdf, shape, transformation, generatorConfig);
  734. const msdfgen::MSDFGeneratorConfig correctionConfig (
  735. true,
  736. msdfgen::ErrorCorrectionConfig (
  737. msdfgen::ErrorCorrectionConfig::EDGE_PRIORITY, msdfgen::ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE,
  738. 1.1111111111111112, 1.1111111111111112
  739. )
  740. );
  741. msdfgen::msdfErrorCorrection (msdf, shape, transformation, correctionConfig);
  742. const auto toByte = [] (float value) {
  743. const int scaled = static_cast<int> (value * 256.0f);
  744. return static_cast<uint8_t> (std::clamp (scaled, 0, 255));
  745. };
  746. // msdfgen's rows go bottom up, the atlas is stored top down
  747. for (int row = 0; row < out.height; row++) {
  748. for (int col = 0; col < out.width; col++) {
  749. const float* texel = msdf (col, out.height - row - 1);
  750. uint8_t* dst = &out.pixels[(static_cast<size_t> (row) * out.width + col) * 4];
  751. dst[0] = toByte (texel[0]);
  752. dst[1] = toByte (texel[1]);
  753. dst[2] = toByte (texel[2]);
  754. dst[3] = 255;
  755. }
  756. }
  757. return true;
  758. }
  759. void TextLayout::resetAtlases () {
  760. for (Atlas* atlas : { &m_atlas, &m_colorAtlas }) {
  761. atlas->size = 512;
  762. atlas->pixels.assign (static_cast<size_t> (atlas->size) * atlas->size * atlas->channels, 0);
  763. atlas->colorScale = 0;
  764. atlas->colorPixels.clear ();
  765. atlas->packOrder.clear ();
  766. atlas->shelfX = atlas->shelfY = atlas->shelfHeight = 0;
  767. atlas->changed = true;
  768. }
  769. m_atlasFull = false;
  770. }
  771. bool TextLayout::pack (Atlas& atlas, uint64_t key, AtlasGlyph& glyph) {
  772. // one pixel between glyphs so linear filtering never picks up a neighbour
  773. const int width = glyph.width + 1;
  774. const int height = glyph.height + 1;
  775. while (true) {
  776. if (atlas.shelfX + width > atlas.size) {
  777. atlas.shelfY += atlas.shelfHeight;
  778. atlas.shelfX = 0;
  779. atlas.shelfHeight = 0;
  780. }
  781. if (width <= atlas.size && atlas.shelfY + height <= atlas.size) {
  782. break;
  783. }
  784. // the atlas doubles up to 4096 like WE's
  785. if (atlas.size >= kMaxAtlasSize) {
  786. return false;
  787. }
  788. this->repackAtlas (atlas, atlas.size * 2);
  789. }
  790. glyph.x = atlas.shelfX;
  791. glyph.y = atlas.shelfY;
  792. atlas.shelfX += width;
  793. atlas.shelfHeight = std::max (atlas.shelfHeight, height);
  794. const int channels = atlas.channels;
  795. for (int row = 0; row < glyph.height; row++) {
  796. std::copy_n (
  797. glyph.pixels.begin () + static_cast<long> (row) * glyph.width * channels, glyph.width * channels,
  798. atlas.pixels.begin () + (static_cast<long> (glyph.y + row) * atlas.size + glyph.x) * channels
  799. );
  800. }
  801. // the colour texture holds the same cell at colorScale times the resolution
  802. if (atlas.colorScale > 0 && !glyph.colorPixels.empty ()) {
  803. const int scale = atlas.colorScale;
  804. const int rowLength = glyph.width * scale * 4;
  805. const long stride = static_cast<long> (atlas.size) * scale * 4;
  806. for (int row = 0; row < glyph.height * scale; row++) {
  807. std::copy_n (
  808. glyph.colorPixels.begin () + static_cast<long> (row) * rowLength, rowLength,
  809. atlas.colorPixels.begin () + (static_cast<long> (glyph.y) * scale + row) * stride
  810. + static_cast<long> (glyph.x) * scale * 4
  811. );
  812. }
  813. }
  814. atlas.packOrder.push_back (key);
  815. atlas.changed = true;
  816. return true;
  817. }
  818. void TextLayout::repackAtlas (Atlas& atlas, int size) {
  819. const std::vector<uint64_t> order = std::move (atlas.packOrder);
  820. atlas.size = size;
  821. atlas.pixels.assign (static_cast<size_t> (size) * size * atlas.channels, 0);
  822. if (atlas.colorScale > 0) {
  823. atlas.colorPixels.assign (
  824. static_cast<size_t> (size) * atlas.colorScale * size * atlas.colorScale * 4, 0
  825. );
  826. }
  827. atlas.packOrder.clear ();
  828. atlas.shelfX = atlas.shelfY = atlas.shelfHeight = 0;
  829. for (const uint64_t key : order) {
  830. if (auto it = m_glyphs.find (key); it != m_glyphs.end ()) {
  831. this->pack (atlas, key, it->second);
  832. }
  833. }
  834. }
  835. bool TextLayout::takeAtlasChanged () {
  836. const bool changed = m_atlas.changed;
  837. m_atlas.changed = false;
  838. return changed;
  839. }
  840. bool TextLayout::takeColorAtlasChanged () {
  841. const bool changed = m_colorAtlas.changed;
  842. m_colorAtlas.changed = false;
  843. return changed;
  844. }
  845. TextLayoutResult TextLayout::layout (const std::string& utf8, const TextLayoutParams& params) {
  846. TextLayoutResult result;
  847. if (m_faces.empty ()) {
  848. return result;
  849. }
  850. if (params.msdf != m_msdf) {
  851. m_msdf = params.msdf;
  852. m_atlas.channels = m_msdf ? 4 : 1;
  853. m_glyphs.clear ();
  854. this->resetAtlases ();
  855. }
  856. this->applySize (params.size);
  857. const std::u32string text = decodeUtf8 (utf8);
  858. // WE flushes a full atlas and lays the text out again with only what it needs
  859. for (int attempt = 0; attempt < 2; attempt++) {
  860. m_atlasFull = false;
  861. std::vector<std::u32string> lines;
  862. for (size_t start = 0; start < text.size ();) {
  863. const size_t newline = text.find (U'\n', start);
  864. if (params.maxRows > 0 && lines.size () >= static_cast<size_t> (params.maxRows)) {
  865. finishLastRow (lines.back (), params.ellipsis);
  866. break;
  867. }
  868. lines.push_back (text.substr (start, newline == std::u32string::npos ? newline : newline - start));
  869. if (newline == std::u32string::npos) {
  870. break;
  871. }
  872. start = newline + 1;
  873. }
  874. std::vector<bool> wrapped (lines.size (), false);
  875. struct Line {
  876. std::vector<ShapedGlyph> glyphs;
  877. float width;
  878. };
  879. std::vector<Line> finished;
  880. size_t glyphCount = 0;
  881. float minX = 0.0f;
  882. float maxX = 0.0f;
  883. float minY = 0.0f;
  884. float maxY = 0.0f;
  885. float widest = 0.0f;
  886. const FT_Size_Metrics& metrics = m_faces.front ()->face->size->metrics;
  887. const float pitch = static_cast<float> (metrics.height >> 6) + params.spacing.y;
  888. for (size_t i = 0; i < lines.size ();) {
  889. const std::vector<ShapedGlyph> glyphs = this->shape (lines[i], params);
  890. std::vector<ShapedGlyph> kept;
  891. float pen = 0.0f;
  892. int64_t previousCluster = -1;
  893. bool reshape = false;
  894. bool lastLine = false;
  895. for (const auto& glyph : glyphs) {
  896. const bool overflows = params.maxWidth > 0.0f && !kept.empty () && !isBreakSpace (glyph.codepoint)
  897. && static_cast<int64_t> (glyph.cluster) != previousCluster && pen + glyph.x1 > params.maxWidth;
  898. if (!overflows) {
  899. kept.push_back (glyph);
  900. pen += glyph.advance;
  901. previousCluster = glyph.cluster;
  902. continue;
  903. }
  904. std::u32string& line = lines[i];
  905. if (params.maxRows <= 0 || finished.size () + 1 < static_cast<size_t> (params.maxRows)) {
  906. // back to the last whitespace before the overflowing character, or break inside the word
  907. size_t breakAt = glyph.cluster;
  908. while (breakAt > 1 && isBreakSpace (line[breakAt])) {
  909. breakAt--;
  910. }
  911. for (size_t j = breakAt; j-- > 0;) {
  912. if (isBreakSpace (line[j])) {
  913. breakAt = j;
  914. break;
  915. }
  916. }
  917. std::u32string rest = line.substr (breakAt);
  918. rest.erase (0, std::min (rest.size (), rest.find_first_not_of (U"\t\r ")));
  919. line.resize (breakAt);
  920. trimTrailingSpaces (line);
  921. wrapped[i] = true;
  922. std::erase_if (kept, [breakAt] (const ShapedGlyph& g) { return g.cluster >= breakAt; });
  923. lines.insert (lines.begin () + static_cast<long> (i) + 1, std::move (rest));
  924. wrapped.insert (wrapped.begin () + static_cast<long> (i) + 1, false);
  925. } else {
  926. wrapped[i] = false;
  927. lines.resize (i + 1);
  928. wrapped.resize (i + 1);
  929. if (params.ellipsis) {
  930. // the longest start of the line that still fits with the ellipsis after it
  931. size_t length = glyph.cluster;
  932. while (true) {
  933. std::u32string candidate = line.substr (0, std::min (length, line.size ()));
  934. candidate.push_back (kEllipsis);
  935. if (this->measureRight (candidate) <= params.maxWidth || length == 0) {
  936. break;
  937. }
  938. length--;
  939. }
  940. line.resize (std::min (length, line.size ()));
  941. if (line.empty () || line.back () != kEllipsis) {
  942. trimTrailingSpaces (line);
  943. line.push_back (kEllipsis);
  944. }
  945. reshape = true;
  946. } else {
  947. finishLastRow (line, false);
  948. lastLine = true;
  949. }
  950. }
  951. break;
  952. }
  953. if (reshape) {
  954. continue;
  955. }
  956. float lineMinX = 0.0f;
  957. float lineMinY = 0.0f;
  958. float lineMaxX = 0.0f;
  959. float lineMaxY = 0.0f;
  960. float penX = 0.0f;
  961. float penY = 0.0f;
  962. for (const auto& glyph : kept) {
  963. lineMinX = std::min (lineMinX, penX + glyph.x0);
  964. lineMinY = std::min (lineMinY, penY + glyph.y0);
  965. lineMaxX = std::max (lineMaxX, penX + glyph.x1);
  966. lineMaxY = std::max (lineMaxY, penY + glyph.y1);
  967. penX += glyph.advance;
  968. penY += glyph.yAdvance;
  969. }
  970. // blockalign stretches the spaces of wrapped lines until they fill maxwidth
  971. if (params.blockAlign && wrapped[i]) {
  972. const auto spaces = std::ranges::count_if (lines[i], isBreakSpace);
  973. if (spaces > 0) {
  974. const float extra = (params.maxWidth - (lineMaxX - lineMinX)) / static_cast<float> (spaces);
  975. for (auto& glyph : kept) {
  976. if (isBreakSpace (glyph.codepoint)) {
  977. glyph.advance += extra;
  978. }
  979. }
  980. lineMaxX = lineMinX + params.maxWidth;
  981. }
  982. }
  983. const float width = lineMaxX - lineMinX;
  984. const float lineY = static_cast<float> (finished.size ()) * -pitch;
  985. minY = std::min (minY, lineY + lineMinY);
  986. maxY = std::max (maxY, lineY + lineMaxY);
  987. minX = std::min (lineMinX, minX);
  988. maxX = std::max (lineMaxX, maxX);
  989. widest = std::max (width, widest);
  990. glyphCount += kept.size ();
  991. finished.push_back ({ std::move (kept), width });
  992. if (lastLine) {
  993. break;
  994. }
  995. i++;
  996. }
  997. if (m_atlasFull && attempt == 0) {
  998. m_glyphs.clear ();
  999. this->resetAtlases ();
  1000. continue;
  1001. }
  1002. if (finished.empty () || glyphCount == 0) {
  1003. return result;
  1004. }
  1005. const float ascender = static_cast<float> (metrics.ascender >> 6);
  1006. result.minX = minX;
  1007. result.maxX = maxX;
  1008. result.top = std::max (ascender, maxY);
  1009. result.bottom = std::min (ascender - static_cast<float> (finished.size ()) * pitch, minY);
  1010. result.pitch = pitch;
  1011. result.lines = static_cast<int> (finished.size ());
  1012. result.ascender = ascender;
  1013. result.descender = static_cast<float> (metrics.descender >> 6);
  1014. float lineY = 0.0f;
  1015. for (const auto& line : finished) {
  1016. float shift = 0.0f;
  1017. if (params.align == TextAlign::Center) {
  1018. shift = (widest - line.width) * 0.5f;
  1019. } else if (params.align == TextAlign::Right) {
  1020. shift = widest - line.width;
  1021. }
  1022. float pen = 0.0f;
  1023. for (const auto& glyph : line.glyphs) {
  1024. const auto it = m_glyphs.find (glyph.key);
  1025. if (it != m_glyphs.end () && it->second.x >= 0) {
  1026. const AtlasGlyph& entry = it->second;
  1027. // sub_1401B0410 puts colour glyphs into a vertex buffer of their own
  1028. const float atlasSize = static_cast<float> (entry.color ? m_colorAtlas.size : m_atlas.size);
  1029. (entry.color ? result.colorQuads : result.quads).push_back (
  1030. {
  1031. .rect = { pen + glyph.x0 - glyph.pad + shift, lineY + glyph.y0 - glyph.pad,
  1032. pen + glyph.x1 + glyph.pad + shift, lineY + glyph.y1 + glyph.pad },
  1033. .uv = { static_cast<float> (entry.x) / atlasSize, static_cast<float> (entry.y) / atlasSize,
  1034. static_cast<float> (entry.x + entry.width) / atlasSize,
  1035. static_cast<float> (entry.y + entry.height) / atlasSize },
  1036. }
  1037. );
  1038. }
  1039. pen += glyph.advance;
  1040. }
  1041. lineY -= pitch;
  1042. }
  1043. result.valid = true;
  1044. break;
  1045. }
  1046. return result;
  1047. }