text method

int text(
  1. int x,
  2. int y,
  3. String s,
  4. int pen,
)

Draws s at (x, y) with pen; returns the columns it advanced (0 when the row is clipped out). Tabs draw as one blank, controls and lone combining marks are dropped.

The string is drawn in stored order, whatever its script: for marks, digits and box glyphs. Text a user supplies goes through a TextPainter, which draws a right-to-left string as it reads in visual order (TextOrder.visual), as a Text does.

Implementation

int text(int x, int y, String s, int pen) {
  final ay = y + _oy;
  if (ay < _cy0 || ay >= _cy1 || s.isEmpty) {
    return 0;
  }
  var ax = x + _ox;
  final startX = ax;
  _begin(ay, pen);
  final scan = _scan;
  final seg = segmenter;
  final len = s.length;
  final graphemes = seg.mode == TextMode.graphemes;
  for (var i = 0; i < len;) {
    if (ax >= _cx1) {
      break;
    }
    final cu = s.codeUnitAt(i);
    // ---- run of printable ASCII: written in one tight loop ----------------
    if (cu >= 0x20 && cu < 0x7F) {
      final room = _cx1 - ax;
      final lim = len - i < room ? len : i + room;
      var j = i + 1;
      while (j < lim) {
        final c = s.codeUnitAt(j);
        if (c < 0x20 || c >= 0x7F) {
          break;
        }
        j++;
      }
      // the last one may take a combining mark: leave it to the scanner
      if (j < len && s.codeUnitAt(j) >= 0x300) {
        j--;
      }
      if (j > i) {
        _asciiRun(s, i, j, ax);
        ax += j - i;
        i = j;
        continue;
      }
    } else if (cu >= 0x80 && (cu < 0xD800 || cu > 0xDFFF)) {
      // ---- one BMP code point that can't join its neighbour --------
      final single = graphemes
          ? _standsAloneG(s, i, cu)
          : _standsAloneL(s, i, cu);
      if (single) {
        final w = codePointWidth(cu, seg.ambiguousWidth);
        i++;
        if (w == 0) {
          continue;
        }
        _place(ax, w, codePointUncertain(cu) ? cu | kUncertain : cu);
        ax += w;
        continue;
      }
    }
    final start = i;
    seg.scan(s, i, scan);
    i = scan.end;
    var w = scan.width;
    int glyph;
    if (w == 0) {
      if (scan.first != 0x09) {
        continue;
      }
      w = 1;
      glyph = kBlank;
    } else if (graphemes && isLeadingMark(scan.first)) {
      // a mark with no base: drop it, re-segment what follows
      i = start + (scan.first > 0xFFFF ? 2 : 1);
      continue;
    } else {
      glyph = scan.length == 1 ? scan.first : glyphs.intern(s, start, i);
    }
    if (scan.uncertain || scan.joinsNext) {
      glyph |= kUncertain;
    }
    _place(ax, w, glyph);
    ax += w;
  }
  _end();
  return ax - startX;
}