well_of_text/src/typesetting.nim

63 lines
1.8 KiB
Nim

# SPDX-FileCopyrightText: ☭ Emery Hemingway
# SPDX-License-Identifier: Unlicense
import std/[sequtils]
import pixie
proc newFont*(typeface: Typeface, size: float32): Font =
result = newFont(typeface)
result.size = size
func height(arr: Arrangement): float =
if arr.positions.len > 0: result = arr.positions[arr.positions.high].y
proc add(result: var Arrangement; other: sink Arrangement) =
if result.lines.len == 0:
result = other
else:
let runeOff = result.runes.len
add(result.lines, map(other.lines,
proc (x: (int, int)): (int, int) = (x[0]+runeOff, x[1]+runeOff)))
add(result.spans, map(other.spans,
proc (x: (int, int)): (int, int) = (x[0]+runeOff, x[1]+runeOff)))
add(result.fonts, other.fonts)
add(result.runes, other.runes)
let yOff = result.positions[result.positions.high].y
add(result.positions,
map(other.positions,
proc(pos: Vec2): Vec2 = vec2(pos.x, pos.y + yOff)))
add(result.selectionRects,
map(other.selectionRects,
proc(rect: Rect): Rect = rect(rect.x, rect.y + yOff, rect.w, rect.h)))
proc render*(font: Font; text: string): Image =
# TODO: render by font size, not by wh
var wh = layoutBounds(font, "X")
echo "bounds of X are ", wh
wh.x = wh.x * 80
wh.y = wh.y * 50
let margin = wh / 9.0
var
printSpace = wh * (7.0 / 9.0)
pages = @[Arrangement()]
proc pageEnd(): float =
let
pi = pages.high
li = pages[pi].lines.high
ci = pages[pi].lines[li][1]
pages[pi].positions[ci].y
proc append(span: Span) =
var arr = typeset(@[span], printSpace)
if pages[pages.high].height + arr.height < printSpace.y:
pages[pages.high].add arr
else:
discard
append(newSpan(text, font))
result = newImage(int wh.x, int wh.y)
fill(result, rgba(255, 255, 255, 255))
fillText(result, pages[0], translate(margin))