package receipt import ( "fmt" "strconv" "strings" "uberbringer/internal/pkg/escpos" ) // Room a box needs around its title and footer, and a rule or divider // around its label: corners, fills of at least one (title, footer) or two // (labels) characters, and a space on each side of the text. const ( inlineTitleRoom = 6 // ┌─ Title ─┐ cappedTitleRoom = 8 // ╔═╡ Title ╞═╗ footerRoom = 7 // └─ footer ──┘ labelRoom = 6 // ── Label ── minBoxWidth = 3 // kvMinWidth fits a one-character key, a space, a two-character // leader, a space and a one-character value. kvMinWidth = 6 ) // layout lays out blocks in one code page. It normalizes their text as it // goes and counts the characters that print as '?'. type layout struct { cp escpos.CodePage unknown int } func (lo *layout) text(s string) string { s, n := normalize(s, lo.cp) lo.unknown += n return expandTabs(s, 0) } func (lo *layout) line(s string) string { s, n := normalizeLine(s, lo.cp) lo.unknown += n return s } // centre places lines of width cells in the middle of cols cells. func centre(lines []blockLine, width, cols int) []blockLine { margin := (cols - width) / 2 if margin <= 0 { return lines } for i, l := range lines { lines[i] = append(blockLine{plain(spaces(margin))}, l...) } return lines } // blockWidth is the width of a block with the given columns field on a // line of cols cells. func blockWidth(columns, cols int) int { if columns > 0 { return min(columns, cols) } return cols } // Kinds of item in a box body. const ( itemText = iota itemFeed itemDivider itemKV itemList ) // boxItem is one part of a box body, with its text already normalized. type boxItem struct { kind int // itemText. text string style textStyle align escpos.Justification wrap bool // itemFeed. lines int // itemDivider: label, style and alignment, and the weight of the line. double bool // itemKV. pairs []kvRow leader string // itemList. list []listRow } // kvRow is a Pair with its text normalized. type kvRow struct { key, value string bold bool } // box lays out a box on a line of cols cells. Every line it returns, apart // from the centring margin, is exactly the box width. func (lo *layout) box(el Element, spec boxSpec, cols int) []blockLine { set := bordersFor(spec.style, lo.cp) items := lo.boxItems(el, spec) title, footer := lo.line(el.Title), lo.line(el.Footer) titleRoom := inlineTitleRoom if spec.capped { titleRoom = cappedTitleRoom } width := blockWidth(spec.columns, cols) padding := spec.padding if spec.fit { need := minBoxWidth + 2*padding if title != "" { need = max(need, runeLen(title)+titleRoom) } if footer != "" { need = max(need, runeLen(footer)+footerRoom) } for _, it := range items { if it.kind == itemDivider { if it.text != "" { // The label needs its room inside the two junctions. need = max(need, runeLen(it.text)+labelRoom+2) } continue } need = max(need, it.naturalWidth(width-2-2*padding)+2+2*padding) } width = min(width, need) } // Narrow boxes give up padding before they give up content. width = max(width, minBoxWidth) padding = min(padding, (width-minBoxWidth)/2) content := width - 2 - 2*padding lines := []blockLine{set.top(title, spec.title, spec.capped, width)} for _, it := range items { if it.kind == itemDivider { lines = append(lines, lo.divider(set, it, width)) continue } for _, row := range it.contentLines(content) { line := blockLine{plain(string(set.vertical) + spaces(padding))} line = append(line, row...) line = append(line, plain(spaces(padding)+string(set.vertical))) lines = append(lines, line) } } lines = append(lines, set.bottom(footer, width)) return centre(lines, width, cols) } // boxItems turns the body of a box, its text or its children, into items. // The job has been validated, so the children's specs parse; their errors // are not checked again here. func (lo *layout) boxItems(el Element, spec boxSpec) []boxItem { if len(el.Children) == 0 { return []boxItem{{kind: itemText, text: lo.text(el.Text), style: spec.text, align: spec.align, wrap: true}} } var items []boxItem for _, child := range el.Children { switch child.Type { case TypeText: ts, _ := child.textSpec() align := ts.align if child.Align == "" { align = spec.align } items = append(items, boxItem{ kind: itemText, text: lo.text(child.Text), style: textStyle{bold: ts.bold, underline: ts.underline, invert: ts.invert}, align: align, wrap: ts.wrap, }) case TypeFeed: n, _ := child.feedLines() items = append(items, boxItem{kind: itemFeed, lines: int(n)}) case TypeRule: rs, _ := child.ruleSpec(true) items = append(items, boxItem{ kind: itemDivider, text: lo.line(child.Text), style: textStyle{bold: rs.bold}, align: rs.align, double: rs.style == ruleDouble, }) case TypeKV: ks, _ := child.kvSpec() items = append(items, boxItem{kind: itemKV, pairs: lo.kvRows(child.Pairs), leader: leaderFor(ks.leader, lo.cp)}) case TypeList: ls, _ := child.listSpec() items = append(items, boxItem{kind: itemList, list: lo.listRows(child, ls)}) } } return items } // naturalWidth is the content width a text or kv item needs, given at most // limit cells; fit boxes shrink to the widest item. func (it boxItem) naturalWidth(limit int) int { limit = max(limit, 1) switch it.kind { case itemText: widest := 0 for _, row := range it.rows(limit) { widest = max(widest, runeLen(row)) } return widest case itemKV: widest := 0 for _, p := range it.pairs { widest = max(widest, runeLen(p.key)+4+runeLen(p.value)) } return min(widest, limit) case itemList: widest := 0 for _, row := range it.list { bullet := runeLen(row.bullet) room := max(limit-bullet, 1) for _, text := range wrap(row.text, room, room) { widest = max(widest, bullet+runeLen(text)) } } return min(widest, limit) } return 0 } // rows splits a text item into lines of at most width runes. func (it boxItem) rows(width int) []string { if it.wrap { return wrap(it.text, width, width) } var rows []string for _, para := range strings.Split(it.text, "\n") { r := []rune(para) for len(r) > width { rows = append(rows, string(r[:width])) r = r[width:] } rows = append(rows, string(r)) } return rows } // contentLines lays out a text, feed, kv or list item at exactly width // cells. func (it boxItem) contentLines(width int) []blockLine { switch it.kind { case itemFeed: lines := make([]blockLine, it.lines) for i := range lines { lines[i] = blockLine{plain(spaces(width))} } return lines case itemKV: return kvLines(it.pairs, it.leader, width) case itemList: return listLines(it.list, width) } var lines []blockLine for _, row := range it.rows(width) { n := runeLen(row) left := 0 switch it.align { case escpos.JustifyCenter: left = (width - n) / 2 case escpos.JustifyRight: left = width - n } lines = append(lines, blockLine{ plain(spaces(left)), {text: row, style: it.style}, plain(spaces(width - n - left)), }) } return lines } // top draws the top border, with the title set into it in style. func (b borders) top(title string, style textStyle, capped bool, width int) blockLine { h := string(b.horizontal) inner := width - 2 room := inlineTitleRoom if capped { room = cappedTitleRoom } title = truncate(title, width-room) if title == "" { return blockLine{plain(string(b.topLeft) + fill(h, inner) + string(b.topRight))} } head := string(b.topLeft) + h + " " tail := " " if capped { head = string(b.topLeft) + h + string(b.capLeft) + " " tail = " " + string(b.capRight) } rest := width - runeLen(head) - runeLen(title) - runeLen(tail) - 1 return blockLine{ plain(head), {text: title, style: style}, plain(tail + fill(h, rest) + string(b.topRight)), } } // bottom draws the bottom border, with the footer set into it on the right. func (b borders) bottom(footer string, width int) blockLine { h := string(b.horizontal) footer = truncate(footer, width-footerRoom) if footer == "" { return blockLine{plain(string(b.bottomLeft) + fill(h, width-2) + string(b.bottomRight))} } rest := width - runeLen(footer) - 6 return blockLine{ plain(string(b.bottomLeft) + fill(h, rest) + " "), plain(footer), plain(" " + fill(h, 2) + string(b.bottomRight)), } } // divider draws a rule inside a box, joined to its borders. func (lo *layout) divider(b borders, it boxItem, width int) blockLine { left, h, right := b.divider(it.double, lo.cp) line := blockLine{plain(string(left))} line = append(line, labelled(string(h), it.text, it.style, it.align, width-2)...) return append(line, plain(string(right))) } // labelled draws a line of pattern, width cells long, with label set into // it at align. func labelled(pattern, label string, style textStyle, align escpos.Justification, width int) blockLine { label = truncate(label, width-labelRoom) if label == "" { return blockLine{plain(fill(pattern, width))} } rest := width - runeLen(label) - 2 var left int switch align { case escpos.JustifyLeft: left = 2 case escpos.JustifyRight: left = rest - 2 default: left = rest / 2 } return blockLine{ plain(fillTowards(pattern, left, true) + " "), {text: label, style: style}, plain(" " + fillTowards(pattern, rest-left, false)), } } // rule lays out a rule on a line of cols cells. func (lo *layout) rule(el Element, spec ruleSpec, cols int) []blockLine { width := blockWidth(spec.columns, cols) line := labelled(rulePattern(spec.style, lo.cp), lo.line(el.Text), textStyle{bold: spec.bold}, spec.align, width) return centre([]blockLine{line}, width, cols) } // kv lays out a kv block on a line of cols cells. func (lo *layout) kv(el Element, spec kvSpec, cols int) []blockLine { width := blockWidth(spec.columns, cols) lines := kvLines(lo.kvRows(el.Pairs), leaderFor(spec.leader, lo.cp), width) return centre(lines, width, cols) } func (lo *layout) kvRows(pairs []Pair) []kvRow { rows := make([]kvRow, len(pairs)) for i, p := range pairs { rows[i] = kvRow{key: lo.line(p.Key), value: lo.text(p.Value), bold: p.Bold} } return rows } // kvLines lays out rows at exactly width cells: the key, a space, a leader // of at least two, a space and the value. A value too long for the line // wraps to the room after the key, and its further lines are right-aligned. func kvLines(rows []kvRow, leader string, width int) []blockLine { if width < kvMinWidth { return narrowKVLines(rows, width) } var lines []blockLine for _, row := range rows { style := textStyle{bold: row.bold} key := truncate(row.key, max(width-8, 1)) room := max(width-runeLen(key)-4, 1) values := wrap(row.value, room, room) first := values[0] dots := width - runeLen(key) - 2 - runeLen(first) tail := blockLine{plain(" "), {text: first, style: style}} if first == "" { dots++ tail = nil } line := blockLine{{text: key, style: style}, plain(" " + fill(leader, dots))} lines = append(lines, append(line, tail...)) for _, v := range values[1:] { lines = append(lines, blockLine{plain(spaces(width - runeLen(v))), {text: v, style: style}}) } } return lines } // list lays out a list block on a line of cols cells. func (lo *layout) list(el Element, spec listSpec, cols int) []blockLine { width := blockWidth(spec.columns, cols) return centre(listLines(lo.listRows(el, spec), width), width, cols) } // listRow is one list item: its bullet, with the space after it, and its // text, normalized. type listRow struct { bullet, text string } // listRows gives each item of a list its bullet: "· ", "- ", a number // right-aligned to the widest, or a checkbox, ticked for the done items. func (lo *layout) listRows(el Element, spec listSpec) []listRow { done := make(map[int]bool, len(el.Done)) for _, index := range el.Done { done[index] = true } digits := len(strconv.Itoa(len(el.Items))) rows := make([]listRow, len(el.Items)) for i, item := range el.Items { var bullet string switch spec.bullet { case bulletDash: bullet = "- " case bulletNumber: bullet = fmt.Sprintf("%*d. ", digits, i+1) case bulletCheckbox: bullet = "[ ] " if done[i] { bullet = "[" + checkMark(lo.cp) + "] " } default: bullet = listDot(lo.cp) + " " } rows[i] = listRow{bullet: bullet, text: lo.text(item)} } return rows } // listLines lays out rows at exactly width cells: each bullet, then the // item's text wrapped to the room after it, its further lines indented to // line up with the first. On a line too narrow for the whole bullet, the // bullet is cut so that one cell is left for the text. func listLines(rows []listRow, width int) []blockLine { width = max(width, 1) var lines []blockLine for _, row := range rows { bullet := []rune(row.bullet) indent := min(len(bullet), width-1) room := width - indent for i, text := range wrap(row.text, room, room) { lead := spaces(indent) if i == 0 { lead = string(bullet[:indent]) } lines = append(lines, blockLine{plain(lead + text + spaces(room-runeLen(text)))}) } } return lines } // narrowKVLines lays out rows on lines too narrow for a key, a leader and a // value side by side: the key on a line of its own, then the value, // right-aligned. func narrowKVLines(rows []kvRow, width int) []blockLine { width = max(width, 1) var lines []blockLine for _, row := range rows { style := textStyle{bold: row.bold} key := truncate(row.key, width) lines = append(lines, blockLine{{text: key, style: style}, plain(spaces(width - runeLen(key)))}) for _, v := range wrap(row.value, width, width) { lines = append(lines, blockLine{plain(spaces(width - runeLen(v))), {text: v, style: style}}) } } return lines }