# Shared layout for screen and print exports. Titles and sources start at the
# sheet margin. The plot reserves space separately for row names and values.
chart_heading <- function(title, subtitle, source) {
  left <- .012
  width <- par("fin")[1L] - .3
  add_line <- function(text, side, line, cex, color, font = 1) {
    text_width <- strwidth(text, units = "inches", cex = cex, font = font)
    fit <- min(1, width / max(text_width, .01))
    mtext(text, side = side, line = line, outer = TRUE, at = left, adj = 0,
          cex = cex * fit, col = color, font = font)
  }
  if (par("fin")[1L] < 6) {
    title_lines <- strwrap(title, width = 40)
    subtitle_lines <- strwrap(subtitle, width = 62)
    source_lines <- strwrap(source, width = 73)
    for (i in seq_along(title_lines)) add_line(title_lines[i], 3, 5.3 - 1.33 * (i - 1), 1.68, navy, 2)
    for (i in seq_along(subtitle_lines)) add_line(subtitle_lines[i], 3, 2.5 - (i - 1), 1.04, muted)
    for (i in seq_along(source_lines)) add_line(source_lines[i], 1, 1 + .98 * (i - 1), .91, muted)
  } else {
    add_line(title, 3, 2.85, 1.56, navy, 2)
    add_line(subtitle, 3, 1.11, 1, muted)
    add_line(source, 1, .77, .83, muted)
  }
}

row_chart <- function(values, labels, title, subtitle, source, xlab,
                      label_format = as.character, tick_format = label_format,
                      colors = rep(teal, length(labels)), errors = NULL,
                      min_value = 0, kind = "bar", sort_rows = TRUE) {
  if (is.null(dim(values))) values <- matrix(values, nrow = 1L)
  keep <- which(colSums(is.finite(values)) == nrow(values))
  stopifnot(length(keep) > 0L)
  if (sort_rows) keep <- keep[order(values[1, keep], decreasing = TRUE)]
  values <- values[, keep, drop = FALSE]
  labels <- labels[keep]
  if (is.matrix(colors)) {
    colors <- colors[, keep, drop = FALSE]
  } else {
    colors <- matrix(colors[keep], nrow = 1L)
  }
  if (is.null(errors)) errors <- rep(0, length(keep)) else errors <- errors[keep]

  mobile <- par("fin")[1L] < 6
  if (mobile) labels <- vapply(labels, function(label) paste(strwrap(label, width = 24), collapse = "\n"), "")
  row_margin <- max(strwidth(labels, units = "inches", cex = .94)) / par("csi") + 1.35
  par(mar = c(3.5, max(4, row_margin), .4, .9))
  shown <- matrix(label_format(as.numeric(values)), nrow = nrow(values))
  high <- max(sweep(values, 2L, errors, "+"))
  axis_range <- high - min_value
  stopifnot(axis_range > 0)
  gap <- axis_range * .022
  fractions <- matrix(strwidth(shown, units = "inches", cex = .89), nrow = nrow(values)) / par("pin")[1L]
  label_x <- sweep(values, 2L, errors, "+") + gap
  stopifnot(max(fractions) < .5)
  max_value <- max(min_value + axis_range * 1.12, min_value + (label_x - min_value) / (1 - fractions - .025))
  ticks <- pretty(c(min_value, high), n = if (mobile) 4 else 5)
  ticks <- ticks[ticks >= min_value & ticks <= max_value - .02 * axis_range]

  centers <- rev(seq_along(labels))
  offsets <- if (nrow(values) == 1L) 0 else seq(-.18, .18, length.out = nrow(values))
  plotted_y <- outer(offsets, centers, "+")
  plot.new()
  plot.window(xlim = c(min_value, max_value), ylim = c(.45, length(labels) + .55), yaxs = "i")
  abline(v = ticks, col = grid)
  axis(1, at = ticks, labels = tick_format(ticks), cex.axis = .86, col = grid)
  axis(2, at = centers, labels = labels, tick = FALSE, cex.axis = .94)
  if (kind == "dot") {
    points(values, plotted_y, pch = 19, cex = 1.16, col = colors)
  } else {
    half <- if (nrow(values) == 1L) .30 else .14
    rect(min_value, plotted_y - half, values, plotted_y + half, col = colors, border = NA)
  }
  if (any(errors > 0)) {
    arrows(pmax(values - errors, min_value), plotted_y, values + errors, plotted_y,
           code = 3, angle = 90, length = .035, lwd = 1.15, col = navy)
  }
  text(label_x, plotted_y, labels = shown, adj = 0, cex = .89, col = navy)
  mtext(xlab, side = 1, line = 2.2, adj = 0, cex = .9, col = muted)
  chart_heading(title, subtitle, source)
}
