Draw the text and shorten it if required
507670
def _draw_text(self, coords, text, foreground, font):
        """"""
        if text is None:
            return None
        x1_r, _, x2_r, _ = coords
        while True:
            text_id = self._timeline.create_text(
                (0, 0), text=text,
                fill=foreground if foreground != "default" else self._marker_foreground,
                font=font if font != "default" else self._marker_font,
                tags=("marker",)
            )
            x1_t, _, x2_t, _ = self._timeline.bbox(text_id)
            if (x2_t - x1_t) < (x2_r - x1_r):
                break
            self._timeline.delete(text_id)
            text = text[:-4] + "..."
        x, y = TimeLine.calculate_text_coords(coords)
        self._timeline.coords(text_id, (x, y))
        return text_id
346373
def draw_help(self, surf):
    """"""
    if not self._help:
      return

    def write(loc, text):
      surf.write_screen(self._font_large, colors.black, loc, text)

    surf.surf.fill(colors.white * 0.8)
    write((1, 1), "Shortcuts:")

    max_len = max(len(s) for s, _ in self.shortcuts)
    for i, (hotkey, description) in enumerate(self.shortcuts, start=2):
      write((2, i), hotkey)
      write((3 + max_len * 0.7, i), description)
353290
def fill(self, text=""):
        ""
        self.f.write(self.line_marker + "    " * self._indent + text)
        self.line_marker = "\n"
682430
function drawRadialTitle(context, options) {
    if (!options.title) return;

    context.save();
    context.font = drawings.font(options, 'Title', context.max / 200);
    context.fillStyle = options.colorTitle;
    context.textAlign = 'center';
    context.fillText(options.title, 0, -context.max / 4.25, context.max * 0.8);
    context.restore();
}
358739
function drawLegend(obj) {
            if (obj.data) {

                svg.select('.donut-text')
                    .text(() => centeredTextFunction(obj.data))
                    .attr('dy', '.2em')
                    .attr('text-anchor', 'middle');

                svg.select('.donut-text').call(wrapText, legendWidth);
            }
        }
555908
def draw(self):
        

        logger.debug("*** draw")

        if not self.text:
            return

        canvas = self.canv
        style = self.style

        canvas.saveState()

        # Draw box arround paragraph for debugging
        if self.debug:
            bw = 0.5
            bc = Color(1, 1, 0)
            bg = Color(0.9, 0.9, 0.9)
            canvas.setStrokeColor(bc)
            canvas.setLineWidth(bw)
            canvas.setFillColor(bg)
            canvas.rect(
                style.leftIndent,
                0,
                self.width,
                self.height,
                fill=1,
                stroke=1)

        y = 0
        dy = self.height
        for line in self.text.lines:
            y += line.height
            for frag in line:

                # Box
                if hasattr(frag, "draw"):
                    frag.draw(canvas, dy - y)

                # Text
                if frag.get("text", ""):
                    canvas.setFont(frag["fontName"], frag["fontSize"])
                    canvas.setFillColor(frag.get("color", style["color"]))
                    canvas.drawString(frag["x"], dy - y + frag["y"], frag["text"])

                # XXX LINK
                link = frag.get("link", None)
                if link:
                    _scheme_re = re.compile('^[a-zA-Z][-+a-zA-Z0-9]+$')
                    x, y, w, h = frag["x"], dy - y, frag["width"], frag["fontSize"]
                    rect = (x, y, w, h)
                    if isinstance(link, six.text_type):
                        link = link.encode('utf8')
                    parts = link.split(':', 1)
                    scheme = len(parts) == 2 and parts[0].lower() or ''
                    if _scheme_re.match(scheme) and scheme != 'document':
                        kind = scheme.lower() == 'pdf' and 'GoToR' or 'URI'
                        if kind == 'GoToR':
                            link = parts[1]

                        canvas.linkURL(link, rect, relative=1, kind=kind)
                    else:
                        if link[0] == '#':
                            link = link[1:]
                            scheme = ''
                        canvas.linkRect("", scheme != 'document' and link or parts[1], rect, relative=1)

        canvas.restoreState()
232804
def draw_text(stdscr, text, color=0, fallback=None, title=None):
    
    if fallback is None:
        fallback = text
    y, x = stdscr.getmaxyx()
    if title:
        title = pad_to_size(title, x, 1)
        if "\n" in title.rstrip("\n"):
            # hack to get more spacing between title and body for figlet
            title += "\n" * 5
        text = title + "\n" + pad_to_size(text, x, len(text.split("\n")))
    lines = pad_to_size(text, x, y).rstrip("\n").split("\n")

    try:
        for i, line in enumerate(lines):
            stdscr.insstr(i, 0, line, curses.color_pair(color))
    except:
        lines = pad_to_size(fallback, x, y).rstrip("\n").split("\n")
        try:
            for i, line in enumerate(lines[:]):
                stdscr.insstr(i, 0, line, curses.color_pair(color))
        except:
            pass
    stdscr.refresh()
281348
public void drawString(String pString) {
        setupForText();
        graphics.drawString(pString, (float) getPenPosition().getX(), (float) getPenPosition().getY());
    }
146272
def fit_text(text, length):
    """"""
    text_length = wcswidth(text)

    if text_length > length:
        return trunc(text, length)

    if text_length < length:
        return pad(text, length)

    return text
415866
function drawLinearTitle(context, options) {
    if (!options.title) return ;

    let {isVertical, width, length, baseX, baseY, titleMargin} =
        context.barDimensions;
    let textHeight = options.fontTitleSize * width / 200;
    //noinspection JSUnresolvedFunction
    let textX = round(baseX + (isVertical ? width : length) / 2);
    //noinspection JSUnresolvedFunction
    let textY = round(baseY + titleMargin / 2 -
        (isVertical ? textHeight : textHeight / 2) -
        0.025 * (isVertical ? length : width));

    context.save();
    context.textAlign = 'center';
    context.fillStyle = options.colorTitle;
    context.font = drawings.font(options, 'Title', width / 200);
    context.lineWidth = 0;
    context.fillText(options.title, textX, textY, isVertical ? width : length);
}
748108
def draw_text(img, pos, text, color, font_scale=0.4):
    
    img = img.astype(np.uint8)
    x0, y0 = int(pos[0]), int(pos[1])
    # Compute text size.
    font = cv2.FONT_HERSHEY_SIMPLEX
    ((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, 1)
    # Place text background.
    if x0 + text_w > img.shape[1]:
        x0 = img.shape[1] - text_w
    if y0 - int(1.15 * text_h) < 0:
        y0 = int(1.15 * text_h)
    back_topleft = x0, y0 - int(1.3 * text_h)
    back_bottomright = x0 + text_w, y0
    cv2.rectangle(img, back_topleft, back_bottomright, color, -1)
    # Show text.
    text_bottomleft = x0, y0 - int(0.25 * text_h)
    cv2.putText(img, text, text_bottomleft, font, font_scale, (222, 222, 222), lineType=cv2.LINE_AA)
    return img
668330
function appendText(str, isPlainText) {
		let i = newTokens.length - 1,
			last = newTokens[i]

		if (isPlainText) {
			if (lastTextWasPlain && lastPlainTextWasSpaced) {
				// Remove preceding spaces, since the last plain text
				// ended in spaces
				str = str.trimLeft()
			}

			str = str.replace(/(\s)\s+/g, '$1')
			lastPlainTextWasSpaced = /^\s$/.test(str.substr(-1))
		}
		lastTextWasPlain = isPlainText

		if (typeof last === 'string') {
			newTokens[i] += str
		} else {
			newTokens.push(str)
		}
	}
1315423
function drawLinearUnits(context, options) {
    if (!options.units) return ;

    let {isVertical, width, length, baseX, baseY, unitsMargin} =
        context.barDimensions;
    let textHeight = options.fontUnitsSize * width / 200;
    //noinspection JSUnresolvedFunction
    let textX = round(baseX + (isVertical ? width : length) / 2);
    //noinspection JSUnresolvedFunction
    let textY = round(baseY + (isVertical ? length : width) +
        unitsMargin / 2 - textHeight / 2);

    context.save();
    context.textAlign = 'center';
    context.fillStyle = options.colorUnits;
    context.font = drawings.font(options, 'Units', width / 200);
    context.lineWidth = 0;
    context.fillText(options.units, textX, textY, isVertical ? width : length);
}
50665
function drawHorizontalExtendedLine() {
            baseLine = svg.select('.grid-lines-group')
                .selectAll('line.extended-x-line')
                .data([0])
                .enter()
                  .append('line')
                    .attr('class', 'extended-x-line')
                    .attr('x1', xAxisPadding.left)
                    .attr('x2', chartWidth)
                    .attr('y1', chartHeight)
                    .attr('y2', chartHeight);
        }
776190
@Override
    public void drawText(Graphics2D graphics, int width, int height) {
        if(StringUtils.isBlank(text) || StringUtils.isBlank(domainName)) {
            return ;
        }
        
        int x = 0, y = 0; 
        int fontsize = ((int)(width * textWidthPercent)) / domainName.length();
        if (fontsize < minFontSize) {
            return;
        }
        
        float fsize = (float)fontsize;
        Font font = domainFont.deriveFont(fsize);
        graphics.setFont(font);
        FontRenderContext context = graphics.getFontRenderContext();
        int sw = (int) font.getStringBounds(domainName, context).getWidth();

        x = width - sw - fontsize;
        y = height - fontsize;
        if(x <= 0 || y <= 0) {
            return ;
        }

        if (fontShadowColor != null) {
            graphics.setColor(fontShadowColor);
            graphics.drawString(domainName, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize));
        }
        graphics.setColor(fontColor);
        graphics.drawString(domainName, x, y);
        
        //draw company name
        fsize = (float)fontsize;
        font = defaultFont.deriveFont(fsize);
        graphics.setFont(font);
        context = graphics.getFontRenderContext();
        sw = (int) font.getStringBounds(text, context).getWidth();
        x = width - sw - fontsize;
        y = height - (int)(fontsize * 2.5);
        if(x <= 0 || y <= 0) {
            return ;
        }
        
        if (fontShadowColor != null) {
            graphics.setColor(fontShadowColor);
            graphics.drawString(text, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize));
        }
        graphics.setColor(fontColor);
        graphics.drawString(text, x, y);
    }
357488
def _draw_text(self, pos, text, font, **kw):
        
        self.drawables.append((pos, text, font, kw))
793278
function drawCaptions(node) {
      ctx.save();
      var x = node.offset.x;
      var y = node.offset.y;
      ctx.translate(x, y);

      var tm = node.textMetrics;
      var caption = node.getCaption();
      var font = node.text.font;

      // ctx.strokeStyle = "#CCC";
      // ctx.strokeRect(0, 0, tm.width, tm.height);

      ctx.font = font.style + " " + font.weight + " " + font.size
          + "px sans-serif";

      var captionX = tm.width / 2;
      var captionY = 0;
      if (node.isRoot()) {
        // TODO remove magic numbers
        captionX = 0;
        captionY = 20;

        // root box
        ctx.lineWidth = 5.0;
        ctx.strokeStyle = "orange";
        ctx.fillStyle = "white";
        mindmaps.CanvasDrawingUtil.roundedRect(ctx,
            0 - tm.width / 2 - 4, 20 - 4, tm.width + 8,
            tm.height + 8, 10);
      }

      ctx.strokeStyle = font.color;
      ctx.fillStyle = font.color;

      // TODO underline manually. canvas doesnt support it
      // TODO strike through manually

      function checkLength(str) {
        var ctm = ctx.measureText(str);
        return ctm.width <= tm.width;
      }

      // write node caption.

      if (checkLength(caption)) {
        // easy part only one line
        ctx.fillText(caption, captionX, captionY);
      } else {
        /**
         * caption consists of multiple lines. needs special handling
         * that imitates the line breaking algorithm "word-wrap:
         * break-word;"
         * 
         * <pre>
         * 1. break up string into words
         * 2. cut words that are too long into smaller pieces so they fit on a line
         * 3. construct lines: fit as many words as possible on a line
         * 4. print lines
         * </pre>
         */

        /**
         * step 1
         */
        // check all words and break words that are too long for a one
        // line
        // TODO not perfect yet
        // find words in string (special treatment for hyphens)
        // a hyphen breaks like a white-space does
        // var regex = /(\w+-+)|(\w+)|(-+)/gi;
        // var regex = /[^- ]+[- ]*/gi;
        // var regex = /[^ -]+-* *|[- ]+/gi;
        // for now just match for words and the trailing space
        // hyphenating has probably be done in step 2
        var regex = /[^ ]+ */gi;
        var words1 = caption.match(regex);
        console.log("words1", words1);

        /**
         * step 2
         */
        var words2 = [];
        words1.forEach(function(word) {
          if (!checkLength(word)) {
            var part = "";
            for ( var i = 0; i < word.length; i++) {
              var c = word.charAt(i);
              if (checkLength(part + c)) {
                part += c;
                continue;
              } else {
                words2.push(part);
                part = c;
              }
            }
            words2.push(part);
          } else {
            words2.push(word);
          }
        });

        console.log("words2", words2);

        /**
         * step 3
         */
        var wordWidth = function(str) {
          return ctx.measureText(str).width;
        };

        var lines = [];
        var line = "";
        var lineWidth = tm.width;

        // construct invidual lines
        words2.forEach(function(word) {
          if (line === "") {
            line = word;
          } else {
            if (wordWidth(line + " " + word) > lineWidth) {
              lines.push(line);
              line = word;
            } else {
              line += " " + word;
            }
          }
        });
        lines.push(line);
        console.log("lines", lines);

        /**
         * step 4
         */
        // print lines
        for ( var j = 0; j < lines.length; j++) {
          var line = lines[j];
          ctx.fillText(line, captionX, captionY + j * font.size);
        }
      }

      node.forEachChild(function(child) {
        drawCaptions(child);
      });

      ctx.restore();
    }