3 Commits

Author SHA1 Message Date
Alexander Heldt
6aa9cc28de Use StringTree to store the rendered layout
And print the entire layout at once
2025-12-02 21:12:54 +01:00
Alexander Heldt
3d7287902f Move render_layout to layout module 2025-12-02 21:11:50 +01:00
Alexander Heldt
deaa0fcf89 Don't prefix internal modules 2025-12-02 21:11:45 +01:00
5 changed files with 44 additions and 472 deletions

View File

@@ -146,7 +146,6 @@ fn update_playback_time_loop(
interval_ms: Int,
) {
process.sleep(interval_ms)
// TODO only update if state is playing
update_playback_time(mpv, ui)
update_playback_time_loop(mpv, ui, interval_ms)

View File

@@ -1,105 +1,41 @@
import gleam/dict
import gleam/float
import gleam/int
import gleam/list
import gleam/string
import gleam/string_tree
import gleam/string_tree.{type StringTree}
import musicplayer/logging/logging
import musicplayer/ui/internal
pub type Section {
Section(String)
pub type Layout {
Layout(width: Int, height: Int, nodes: dict.Dict(Section, Node))
}
pub type Section {
Root
Header
Search
PlaybackTime
}
pub type NodeType {
Container
Row
Cell
}
/// A Nodes width and height is in percentage (of the available width/height of its parent Node)
pub type Node {
Node(
t: NodeType,
content: String,
width_percent: Int,
height_percent: Int,
children: List(Section),
)
}
pub type Layout {
Layout(width: Int, height: Int, nodes: dict.Dict(Section, Node))
Node(content: String, x: Int, y: Int, children: List(Section))
}
pub fn new() -> Layout {
let nodes =
dict.from_list([
#(
Section("Root"),
Node(
t: Container,
content: "container",
width_percent: 100,
height_percent: 100,
children: [
Section("Row1"),
Section("Row2"),
],
),
),
#(
Section("Row1"),
Node(
t: Row,
content: "row 1",
width_percent: 100,
height_percent: 50,
children: [
Section("A"),
Section("A"),
],
),
),
#(
Section("A"),
Node(
t: Cell,
content: "cell 1",
width_percent: 50,
height_percent: 100,
children: [],
),
),
#(
Section("B"),
Node(
t: Cell,
content: "cell 2",
width_percent: 50,
height_percent: 100,
children: [],
),
),
#(
Section("Row2"),
Node(
t: Row,
content: "row 1",
width_percent: 100,
height_percent: 50,
children: [],
),
Root,
Node(content: "", x: 0, y: 0, children: [
Header,
Search,
PlaybackTime,
]),
),
#(Header, Node(content: "Music Player", x: 1, y: 1, children: [])),
#(Search, Node(content: "", x: 30, y: 1, children: [])),
#(PlaybackTime, Node(content: "00:00", x: 1, y: 2, children: [])),
])
Layout(width: 0, height: 0, nodes: nodes)
Layout(0, 0, nodes: nodes)
}
pub fn update_section(
@@ -125,161 +61,30 @@ pub fn update_dimensions(layout: Layout, width: Int, height: Int) -> Layout {
Layout(..layout, width:, height:)
}
pub fn render(layout: Layout) -> Nil {
internal.clear_screen()
[layout.width, layout.height]
|> list.map(int.to_string)
|> string.join(" ")
|> string.append("layout - render: ", _)
|> logging.log
let container_width = int.to_float(layout.width)
let container_height = int.to_float(layout.height)
let container_top_left_x = 1
let container_top_left_y = 1
let ansi_ops =
RenderOps(
draw_box: fn(tree, x, y, w, h) {
string_tree.append(tree, draw_box(x, y, w, h))
},
draw_text: fn(tree, text, x, y) {
string_tree.append(tree, internal.chars_at(text, x, y))
},
)
pub fn render(layout: Layout, from: Section) -> Nil {
string_tree.new()
|> render_generic(
layout,
container_width,
container_height,
container_top_left_x,
container_top_left_y,
0,
Section("Root"),
_,
ansi_ops,
)
|> render_loop(layout, from, _)
|> string_tree.to_string
|> internal.print
}
pub type RenderOps(ctx) {
RenderOps(
draw_box: fn(ctx, Int, Int, Int, Int) -> ctx,
draw_text: fn(ctx, String, Int, Int) -> ctx,
)
}
pub fn render_generic(
pub fn render_loop(
layout: Layout,
// Dimensions
container_width: Float,
container_height: Float,
container_tl_x: Int,
container_tl_y: Int,
// State
index: Int,
from: Section,
current_ctx: ctx,
// <--- Generic State
ops: RenderOps(ctx),
// <--- The Strategy
) -> ctx {
into: StringTree,
) -> StringTree {
case dict.get(layout.nodes, from) {
Error(_) -> current_ctx
Error(_) -> into
Ok(node) -> {
// --- 1. MATH (Shared Logic) ---
let margin = 2.0
let width =
container_width *. { int.to_float(node.width_percent) /. 100.0 }
|> float.floor
|> float.truncate
let height =
container_height *. { int.to_float(node.height_percent) /. 100.0 }
|> float.floor
|> float.truncate
let #(cx, cy) = case node.t {
Container -> #(container_tl_x, container_tl_y)
Row -> #(container_tl_x, container_tl_y + { index * height })
Cell -> #(container_tl_x + { index * width }, container_tl_y)
}
// --- 2. RENDER PARENT (Using Generic Ops) ---
// We modify the context using the provided functions
let ctx_with_parent =
current_ctx
|> ops.draw_box(cx, cy, width, height)
|> ops.draw_text(node.content, cx, cy)
// --- 3. RECURSE CHILDREN ---
list.index_map(node.children, fn(child, i) { #(i, child) })
|> list.fold(ctx_with_parent, fn(acc_ctx, ic) {
let #(i, child) = ic
let cw =
container_width
*. { int.to_float(node.width_percent) /. 100.0 }
-. margin
|> float.floor
let ch =
container_height
*. { int.to_float(node.height_percent) /. 100.0 }
-. margin
|> float.floor
let child_origin_x = container_tl_x + 1
let child_origin_y = container_tl_y + 1
render_generic(
layout,
cw,
ch,
child_origin_x,
child_origin_y,
i,
child,
acc_ctx,
ops,
let parent =
string_tree.append(
into,
internal.chars_at(node.content, node.x, node.y),
)
list.fold(node.children, parent, fn(into_acc, child) {
render_loop(layout, child, into_acc)
})
}
}
}
fn draw_box(x: Int, y: Int, width: Int, height: Int) -> String {
let box_chars = #("", "", "", "", "", "")
let #(tl, tr, bl, br, h, v) = box_chars
// Add top of box
let tree =
string_tree.new()
|> string_tree.append(internal.chars_at(
tl <> string.repeat(h, width - 2) <> tr,
x,
y,
))
// Add sides of box
let tree_with_sides =
list.range(1, height - 2)
|> list.map(fn(row) {
tree
|> string_tree.append(internal.chars_at(v, x, y + row))
|> string_tree.append(internal.chars_at(v, x + width - 1, y + row))
})
|> string_tree.concat
// Add bottom of box
tree_with_sides
|> string_tree.append(internal.chars_at(
bl <> string.repeat(h, width - 2) <> br,
x,
y + height - 1,
))
|> string_tree.to_string
}

View File

@@ -1,3 +0,0 @@
pub fn main() {
echo "hello"
}

View File

@@ -38,7 +38,7 @@ pub fn new() -> Result(Subject(Control), String) {
internal.clear_screen()
internal.hide_cursor()
redraw_loop(redraw)
redraw_on_update_loop(redraw)
})
Ok(ui)
@@ -63,18 +63,21 @@ fn handle_message(
|> string.append("ui - updating dimensions: ", _)
|> logging.log
let layout = layout.update_dimensions(state.layout, width, height)
process.send(state.redraw, layout)
actor.continue(State(..state, layout:))
actor.continue(
State(
..state,
layout: layout.update_dimensions(state.layout, width, height),
),
)
}
}
}
control.UpdateState(section, content) -> {
let layout = layout.update_section(state.layout, section, content)
let state = State(..state, layout:)
actor.send(state.redraw, layout)
actor.continue(State(..state, layout:))
actor.continue(state)
}
control.Exit(reply_to) -> {
@@ -85,11 +88,13 @@ fn handle_message(
}
}
fn redraw_loop(redraw: Subject(Layout)) -> Nil {
process.receive_forever(redraw)
|> layout.render
fn redraw_on_update_loop(redraw: Subject(Layout)) -> Nil {
let layout = process.receive_forever(redraw)
redraw_loop(redraw)
internal.clear_screen()
layout.render(layout, layout.Root)
redraw_on_update_loop(redraw)
}
fn update_dimensions_on_interval(ui: Subject(Control), interval_ms: Int) {

View File

@@ -1,234 +0,0 @@
import gleam/dict
import gleam/float
import gleam/int
import gleam/list
import gleam/string
import gleeunit
import musicplayer/ui/layout.{
type Layout, type Section, Layout, Node, RenderOps, Section,
}
pub fn main() -> Nil {
gleeunit.main()
}
pub fn foo_test() {
let layout =
Layout(
width: 80,
height: 20,
nodes: dict.from_list([
#(
Section("Root"),
Node(
t: layout.Container,
content: "container",
width_percent: 100,
height_percent: 100,
children: [
Section("Row1"),
Section("Row2"),
],
),
),
#(
Section("Row1"),
Node(
t: layout.Row,
content: "row 1",
width_percent: 100,
height_percent: 50,
children: [
Section("A"),
Section("B"),
],
),
),
#(
Section("A"),
Node(
t: layout.Cell,
content: "cell 1",
width_percent: 50,
height_percent: 100,
children: [],
),
),
#(
Section("B"),
Node(
t: layout.Cell,
content: "cell 2",
width_percent: 50,
height_percent: 100,
children: [],
),
),
#(
Section("Row2"),
Node(
t: layout.Row,
content: "row 1",
width_percent: 100,
height_percent: 50,
children: [],
),
),
]),
)
let expected =
"
container──────────────────────────────────────────────────────────────────────┐
│row 1────────────────────────────────────────────────────────────────────────┐│
││cell 1───────────────────────────────┐cell 2───────────────────────────────┐││
│││ ││ │││
│││ ││ │││
│││ ││ │││
│││ ││ │││
│││ ││ │││
││└────────────────────────────────────┘└────────────────────────────────────┘││
│└────────────────────────────────────────────────────────────────────────────┘│
│row 1────────────────────────────────────────────────────────────────────────┐│
││ ││
││ ││
││ ││
││ ││
││ ││
││ ││
││ ││
│└────────────────────────────────────────────────────────────────────────────┘│
└──────────────────────────────────────────────────────────────────────────────┘
"
let visual = render_to_visual(layout, Section("Root"), 80, 20)
assert visual == string.trim(expected)
}
pub type Screen =
dict.Dict(#(Int, Int), String)
pub fn render_to_visual(
layout: Layout,
root: Section,
width: Int,
height: Int,
) -> String {
// 1. Define the Strategy: How to draw on a Dict
let test_ops =
RenderOps(
draw_box: fn(screen, x, y, w, h) { plot_box(screen, x, y, w, h) },
draw_text: fn(screen, text, x, y) { plot_text(screen, text, x, y) },
)
// 2. Run the generic logic (reusing the exact math from your real app)
let final_screen =
layout.render_generic(
layout,
int.to_float(width),
int.to_float(height),
1,
// Start X (1-based for ANSI compatibility)
1,
// Start Y
0,
// Root index
root,
dict.new(),
// Initial Context
test_ops,
)
// 3. Convert the Grid to a Visual String
screen_to_string(final_screen)
}
// ----------------------------------------------------------------------------
// Plotting Primitives (The "Graphics Engine" for Tests)
// ----------------------------------------------------------------------------
fn plot_text(screen: Screen, text: String, start_x: Int, y: Int) -> Screen {
// We use to_graphemes to ensure Unicode characters (like emoji or box lines)
// are treated as single visual units.
text
|> string.to_graphemes
|> list.index_fold(screen, fn(acc, char, i) {
dict.insert(acc, #(start_x + i, y), char)
})
}
fn plot_box(screen: Screen, x: Int, y: Int, w: Int, h: Int) -> Screen {
let box_chars = #("", "", "", "", "", "")
let #(tl, tr, bl, br, hor, ver) = box_chars
// Don't draw impossible boxes
case w < 2 || h < 2 {
True -> screen
False -> {
screen
// 1. Corners
|> dict.insert(#(x, y), tl)
|> dict.insert(#(x + w - 1, y), tr)
|> dict.insert(#(x, y + h - 1), bl)
|> dict.insert(#(x + w - 1, y + h - 1), br)
// 2. Top and Bottom edges
|> plot_line_hor(x + 1, y, w - 2, hor)
|> plot_line_hor(x + 1, y + h - 1, w - 2, hor)
// 3. Side edges
|> plot_line_ver(x, y + 1, h - 2, ver)
|> plot_line_ver(x + w - 1, y + 1, h - 2, ver)
}
}
}
fn plot_line_hor(
screen: Screen,
x: Int,
y: Int,
len: Int,
char: String,
) -> Screen {
list.range(0, len - 1)
|> list.fold(screen, fn(acc, i) { dict.insert(acc, #(x + i, y), char) })
}
fn plot_line_ver(
screen: Screen,
x: Int,
y: Int,
len: Int,
char: String,
) -> Screen {
list.range(0, len - 1)
|> list.fold(screen, fn(acc, i) { dict.insert(acc, #(x, y + i), char) })
}
// ----------------------------------------------------------------------------
// Output Formatting
// ----------------------------------------------------------------------------
fn screen_to_string(screen: Screen) -> String {
let keys = dict.keys(screen)
// Find the bounding box of the drawing
let max_x = list.fold(keys, 0, fn(m, k) { int.max(m, k.0) })
let max_y = list.fold(keys, 0, fn(m, k) { int.max(m, k.1) })
// We start from 1 because ANSI is 1-based
let min_y = list.fold(keys, 1000, fn(m, k) { int.min(m, k.1) })
list.range(min_y, max_y)
|> list.map(fn(y) {
list.range(1, max_x)
|> list.map(fn(x) {
case dict.get(screen, #(x, y)) {
Ok(char) -> char
Error(_) -> " "
// Fill gaps with space
}
})
|> string.join("")
})
|> string.join("\n")
}