Skip to content
Repos

DevPlaceApp

C++ 9.8 KB299 lines Opens in site

Directory Raw Download

#include "ui/TextLayout.hpp"

#include <algorithm>

#include "ui/TextEngine.hpp"

namespace dp::ui {

namespace {

struct Token {
  std::string text;
  const TextStyle* style = nullptr;
  float width = 0;
  bool spaceBefore = false;  // a break opportunity (whitespace) precedes this token
  bool hardBreak = false;    // newline
};

std::size_t cpLen(unsigned char c) {
  if (c < 0x80) return 1;
  if ((c >> 5) == 0x6) return 2;
  if ((c >> 4) == 0xE) return 3;
  if ((c >> 3) == 0x1E) return 4;
  return 1;
}

bool isCjk(const std::string& cp) {
  if (cp.size() != 3) return false;
  const unsigned char a = static_cast<unsigned char>(cp[0]);
  return a >= 0xE3 && a <= 0xED;  // CJK, Kana, Hangul blocks: break anywhere
}

std::vector<Token> tokenize(const std::vector<TextSpan>& spans) {
  std::vector<Token> out;
  auto& engine = TextEngine::instance();
  for (const TextSpan& span : spans) {
    std::string cur;
    bool pendingSpace = false;
    auto flush = [&] {
      if (cur.empty()) return;
      Token t;
      t.text = cur;
      t.style = &span.style;
      t.width = engine.width(span.style.font, cur);
      t.spaceBefore = pendingSpace;
      out.push_back(std::move(t));
      cur.clear();
      pendingSpace = false;
    };
    for (std::size_t i = 0; i < span.text.size();) {
      const char c = span.text[i];
      if (c == '\n') {
        flush();
        Token t;
        t.style = &span.style;
        t.hardBreak = true;
        out.push_back(t);
        pendingSpace = false;
        ++i;
      } else if (c == ' ' || c == '\t') {
        flush();
        pendingSpace = true;
        ++i;
      } else {
        const std::size_t n = std::min(cpLen(static_cast<unsigned char>(c)), span.text.size() - i);
        const std::string cp = span.text.substr(i, n);
        if (isCjk(cp)) {
          flush();
          Token t;
          t.text = cp;
          t.style = &span.style;
          t.width = engine.width(span.style.font, cp);
          t.spaceBefore = pendingSpace;
          out.push_back(std::move(t));
          pendingSpace = false;
        } else {
          cur += cp;
        }
        i += n;
      }
    }
    flush();
    // Whitespace at the end of a span carries into the next span's first token.
    if (pendingSpace && !out.empty() && &span != &spans.back()) {
      // mark by inserting an empty space token handled below
      Token t;
      t.style = &span.style;
      t.text = " ";
      t.width = engine.width(span.style.font, " ");
      t.spaceBefore = false;
      t.hardBreak = false;
      t.text.clear();  // zero-length marker: width only
      out.push_back(t);
      out.back().spaceBefore = true;
    }
  }
  return out;
}

float spaceWidth(const TextStyle& s) { return TextEngine::instance().width(s.font, " "); }

}  // namespace

std::vector<std::string> TextLayout::codepoints(const std::string& utf8) {
  std::vector<std::string> out;
  for (std::size_t i = 0; i < utf8.size();) {
    const std::size_t n = std::min(cpLen(static_cast<unsigned char>(utf8[i])), utf8.size() - i);
    out.push_back(utf8.substr(i, n));
    i += n;
  }
  return out;
}

float TextLayout::minWidth(const std::vector<TextSpan>& spans) {
  float best = 0;
  for (const Token& t : tokenize(spans)) best = std::max(best, t.width);
  return best;
}

TextBlock TextLayout::layout(const std::vector<TextSpan>& spans, float maxWidth, int lineLimit, TextAlign align,
                             float lineSpacing) {
  TextBlock block;
  const std::vector<Token> tokens = tokenize(spans);
  auto& engine = TextEngine::instance();
  TextLine line;
  float lineAscent = 0;
  float lineHeightMax = 0;
  const TextStyle* lastStyle = spans.empty() ? nullptr : &spans.front().style;

  auto fontMetrics = [&](const TextStyle& s) {
    const float lh = s.font.lineHeight();
    const float natural = engine.ascent(s.font) + engine.descent(s.font);
    const float baseline = (lh - natural) / 2 + engine.ascent(s.font);
    return std::pair<float, float>(lh, baseline);
  };
  auto emptyLineHeight = [&] {
    const TextStyle& s = lastStyle ? *lastStyle : TextStyle{};
    return fontMetrics(s);
  };
  auto closeLine = [&](bool force) {
    if (line.runs.empty() && !force) return;
    if (line.runs.empty()) {
      auto [lh, base] = emptyLineHeight();
      lineHeightMax = lh;
      lineAscent = base;
    }
    line.height = lineHeightMax;
    line.baseline = lineAscent;
    float w = 0;
    for (const TextRun& r : line.runs) w = std::max(w, r.x + r.width);
    line.width = w;
    block.lines.push_back(std::move(line));
    line = TextLine{};
    lineAscent = 0;
    lineHeightMax = 0;
  };
  auto place = [&](const Token& t, const std::string& text, float width, bool space) {
    float x = line.runs.empty() ? 0 : line.runs.back().x + line.runs.back().width;
    if (space && !line.runs.empty()) x += spaceWidth(*t.style);
    // merge into the previous run when the style matches and no space was inserted (kept per token for links)
    if (!line.runs.empty() && !space && line.runs.back().style == *t.style) {
      line.runs.back().text += text;
      line.runs.back().width += width;
    } else if (!line.runs.empty() && space && line.runs.back().style == *t.style) {
      line.runs.back().text += " " + text;
      line.runs.back().width = x + width - line.runs.back().x;
    } else {
      TextRun r;
      r.text = (space && !line.runs.empty() ? std::string() : std::string()) + text;
      r.style = *t.style;
      r.x = x;
      r.width = width;
      line.runs.push_back(std::move(r));
    }
    const auto [lh, base] = fontMetrics(*t.style);
    if (lh > lineHeightMax) {
      lineHeightMax = lh;
      lineAscent = base;
    }
  };

  bool carry = false;
  for (std::size_t i = 0; i < tokens.size(); ++i) {
    const Token& t = tokens[i];
    lastStyle = t.style;
    if (t.hardBreak) {
      closeLine(true);
      carry = false;
      continue;
    }
    if (t.text.empty()) {  // span-boundary whitespace marker: the space belongs before the next token
      carry = true;
      continue;
    }
    const bool space = (t.spaceBefore || carry) && !line.runs.empty();
    carry = false;
    const float used = line.runs.empty() ? 0 : line.runs.back().x + line.runs.back().width;
    const float need = used + (space ? spaceWidth(*t.style) : 0) + t.width;
    if (need <= maxWidth + 0.01f || line.runs.empty()) {
      if (t.width > maxWidth + 0.05f && line.runs.empty() && maxWidth < kInf / 2) {
        // Unbreakable token wider than the line: split by code points.
        std::string chunk;
        float cw = 0;
        for (const std::string& cp : TextLayout::codepoints(t.text)) {
          const float w = engine.width(t.style->font, cp);
          if (cw + w > maxWidth && !chunk.empty()) {
            place(t, chunk, cw, false);
            closeLine(false);
            chunk.clear();
            cw = 0;
          }
          chunk += cp;
          cw += w;
        }
        if (!chunk.empty()) place(t, chunk, engine.width(t.style->font, chunk), false);
      } else {
        place(t, t.text, t.width, space);
      }
    } else {
      closeLine(false);
      if (t.width > maxWidth + 0.05f && maxWidth < kInf / 2) {
        std::string chunk;
        float cw = 0;
        for (const std::string& cp : TextLayout::codepoints(t.text)) {
          const float w = engine.width(t.style->font, cp);
          if (cw + w > maxWidth && !chunk.empty()) {
            place(t, chunk, cw, false);
            closeLine(false);
            chunk.clear();
            cw = 0;
          }
          chunk += cp;
          cw += w;
        }
        if (!chunk.empty()) place(t, chunk, engine.width(t.style->font, chunk), false);
      } else {
        place(t, t.text, t.width, false);
      }
    }
  }
  closeLine(block.lines.empty());

  // Line limit with tail truncation.
  if (lineLimit > 0 && static_cast<int>(block.lines.size()) > lineLimit) {
    block.lines.resize(static_cast<std::size_t>(lineLimit));
    block.truncated = true;
    TextLine& last = block.lines.back();
    if (!last.runs.empty()) {
      const TextStyle style = last.runs.back().style;
      const float ell = engine.width(style.font, "\xE2\x80\xA6");
      while (!last.runs.empty()) {
        TextRun& r = last.runs.back();
        if (r.x + r.width + ell <= maxWidth || maxWidth >= kInf / 2) break;
        auto cps = TextLayout::codepoints(r.text);
        if (cps.empty()) {
          last.runs.pop_back();
          continue;
        }
        cps.pop_back();
        r.text.clear();
        for (const auto& cp : cps) r.text += cp;
        r.width = engine.width(r.style.font, r.text);
        if (r.text.empty()) last.runs.pop_back();
      }
      while (!last.runs.empty() && !last.runs.back().text.empty() && last.runs.back().text.back() == ' ') {
        last.runs.back().text.pop_back();
        last.runs.back().width = engine.width(last.runs.back().style.font, last.runs.back().text);
      }
      TextRun e;
      e.text = "\xE2\x80\xA6";
      e.style = style;
      e.x = last.runs.empty() ? 0 : last.runs.back().x + last.runs.back().width;
      e.width = ell;
      last.runs.push_back(std::move(e));
      last.width = last.runs.back().x + last.runs.back().width;
    }
  }

  // Vertical positions and size.
  float y = 0, widest = 0;
  for (std::size_t i = 0; i < block.lines.size(); ++i) {
    TextLine& l = block.lines[i];
    l.y = y;
    y += l.height + (i + 1 < block.lines.size() ? lineSpacing : 0);
    widest = std::max(widest, l.width);
  }
  block.size = {widest, y};
  // Alignment is applied against the proposed width (or the block width when unconstrained).
  const float boxW = maxWidth >= kInf / 2 ? widest : maxWidth;
  for (TextLine& l : block.lines) {
    float shift = 0;
    if (align == TextAlign::Center) shift = (boxW - l.width) / 2;
    else if (align == TextAlign::Trailing) shift = boxW - l.width;
    if (shift != 0) for (TextRun& r : l.runs) r.x += shift;
  }
  return block;
}

}  // namespace dp::ui
23.5ms