13 Commits

Author SHA1 Message Date
Alexander Heldt
89ef014c98 wip 2025-12-02 20:48:34 +01:00
Alexander Heldt
0025772177 wip 2025-11-30 21:45:55 +01:00
Alexander Heldt
033beb6b1f wip 2025-11-30 21:41:21 +01:00
Alexander Heldt
3589d94c29 wip 2025-11-30 21:29:43 +01:00
Alexander Heldt
59429d7721 wip 2025-11-30 18:22:15 +01:00
Alexander Heldt
7212df3abb wip-before-change-of-order 2025-11-30 16:27:31 +01:00
Alexander Heldt
1732b12fbe use-string-trees 2025-11-30 15:38:52 +01:00
Alexander Heldt
50c053a42a wip-working 2025-11-30 13:29:52 +01:00
Alexander Heldt
2332710235 working-but-not-columnwise 2025-11-30 11:55:02 +01:00
Alexander Heldt
18c4793872 wip-working-ish 2025-11-30 11:53:27 +01:00
Alexander Heldt
4752ce418b Move render_layout to layout module 2025-11-30 11:53:27 +01:00
Alexander Heldt
df9160b932 Don't prefix internal modules 2025-11-30 11:53:25 +01:00
Alexander Heldt
f9d7b573ac Simplify logging
To avoid having to pass around a `Subject`
2025-11-30 11:50:46 +01:00
12 changed files with 545 additions and 186 deletions

View File

@@ -8,15 +8,14 @@ import musicplayer/musicplayer
import musicplayer/ui/ui import musicplayer/ui/ui
pub fn main() -> Nil { pub fn main() -> Nil {
let assert Ok(logger) = logging.new("/tmp/musicplayer.log") let assert Ok(_) = logging.initialize()
let input_keys_name: Name(Key) = process.new_name("input_keys") let input_keys_name: Name(Key) = process.new_name("input_keys")
input.new(input_keys_name) input.new(input_keys_name)
let assert Ok(ui) = ui.new(logger) let assert Ok(ui) = ui.new()
let assert Ok(mpv) = mpv.new() let assert Ok(mpv) = mpv.new()
let assert Ok(musicplayer_pid) = let assert Ok(musicplayer_pid) = musicplayer.new(ui, mpv, input_keys_name)
musicplayer.new(logger, ui, mpv, input_keys_name)
let monitor = process.monitor(musicplayer_pid) let monitor = process.monitor(musicplayer_pid)
process.new_selector() process.new_selector()

View File

@@ -1,7 +1,5 @@
import gleam/erlang/process.{type Subject}
pub type Control { pub type Control {
Write(String) Write(String)
Exit(reply_to: Subject(Nil)) Exit
} }

View File

@@ -1,58 +1,30 @@
import gleam/erlang/process.{type Subject}
import gleam/otp/actor
import gleam/result import gleam/result
import gleam/string import gleam/string
import gleam/time/calendar import gleam/time/calendar
import gleam/time/timestamp import gleam/time/timestamp
import simplifile import simplifile
import musicplayer/logging/control.{type Control} const filepath = "/tmp/musicplayer.log"
type State { pub fn initialize() -> Result(Nil, String) {
State(filepath: String) case simplifile.is_file(filepath) {
} Ok(True) -> Ok(Nil)
_ -> simplifile.create_file(filepath)
pub fn new(filepath: String) -> Result(Subject(Control), String) {
use _ <- result.try(
case simplifile.is_file(filepath) {
Ok(True) -> Ok(Nil)
_ -> simplifile.create_file(filepath)
}
|> result.map_error(fn(e) {
"Could not access or create log file: " <> string.inspect(e)
}),
)
actor.new(State(filepath:))
|> actor.on_message(handle_message)
|> actor.start
|> result.map_error(fn(start_error) {
"Could not start logger: " <> string.inspect(start_error)
})
|> result.map(fn(started) { started.data })
}
fn handle_message(state: State, control: Control) -> actor.Next(State, Control) {
case control {
control.Write(content) -> {
let log_line =
timestamp.system_time()
|> timestamp.to_rfc3339(calendar.utc_offset)
<> ": "
<> content
<> "\n"
// Ignore any logging errors
let _ = simplifile.append(state.filepath, log_line)
actor.continue(state)
}
control.Exit(reply_to) -> {
process.send(reply_to, Nil)
actor.stop()
}
} }
|> result.map_error(fn(e) {
"Could not access or create log file: " <> string.inspect(e)
})
} }
pub fn log(logger: Subject(Control), content: String) -> Nil { pub fn log(content: String) -> Nil {
process.send(logger, control.Write(content)) let log_line =
timestamp.system_time()
|> timestamp.to_rfc3339(calendar.utc_offset)
<> ": "
<> content
<> "\n"
// Ignore any logging errors
let _ = simplifile.append(filepath, log_line)
Nil
} }

View File

@@ -5,7 +5,6 @@ import gleam/string
import musicplayer/control.{type Control} import musicplayer/control.{type Control}
import musicplayer/input/key.{type Key} import musicplayer/input/key.{type Key}
import musicplayer/logging/control as logging_control
import musicplayer/logging/logging import musicplayer/logging/logging
import musicplayer/mpv/control as mpv_control import musicplayer/mpv/control as mpv_control
import musicplayer/time/time import musicplayer/time/time
@@ -25,14 +24,12 @@ type State {
State( State(
mode: Mode, mode: Mode,
input: Input, input: Input,
logger: Subject(logging_control.Control),
ui: Subject(ui_control.Control), ui: Subject(ui_control.Control),
mpv: Subject(mpv_control.Control), mpv: Subject(mpv_control.Control),
) )
} }
pub fn new( pub fn new(
logger: Subject(logging_control.Control),
ui: Subject(ui_control.Control), ui: Subject(ui_control.Control),
mpv: Subject(mpv_control.Control), mpv: Subject(mpv_control.Control),
input_keys_name: Name(Key), input_keys_name: Name(Key),
@@ -42,14 +39,14 @@ pub fn new(
let input = Input(False, "") let input = Input(False, "")
case case
actor.new(State(Idle, input, logger, ui, mpv)) actor.new(State(Idle, input, ui, mpv))
|> actor.on_message(handle_message) |> actor.on_message(handle_message)
|> actor.start |> actor.start
{ {
Error(start_error) -> Error(start_error) ->
Error("Could not start actor: " <> string.inspect(start_error)) Error("Could not start actor: " <> string.inspect(start_error))
Ok(actor.Started(pid:, data: musicplayer)) -> { Ok(actor.Started(pid:, data: musicplayer)) -> {
logging.log(logger, "musicplayer - started") logging.log("musicplayer - started")
process.spawn(fn() { process.spawn(fn() {
let assert Ok(_) = process.register(process.self(), input_keys_name) let assert Ok(_) = process.register(process.self(), input_keys_name)
handle_key(musicplayer, input_keys) handle_key(musicplayer, input_keys)
@@ -65,7 +62,7 @@ pub fn new(
fn handle_message(state: State, control: Control) -> actor.Next(State, Control) { fn handle_message(state: State, control: Control) -> actor.Next(State, Control) {
case control { case control {
control.Search -> { control.Search -> {
logging.log(state.logger, "musicplayer - initiating search") logging.log("musicplayer - initiating search")
update_search(state.ui, "searching: ") update_search(state.ui, "searching: ")
@@ -79,7 +76,7 @@ fn handle_message(state: State, control: Control) -> actor.Next(State, Control)
} }
control.Raw(content) -> { control.Raw(content) -> {
logging.log(state.logger, "musicplayer - recieved raw input: " <> content) logging.log("musicplayer - recieved raw input: " <> content)
let content = case state.mode { let content = case state.mode {
Idle -> state.input.content Idle -> state.input.content
@@ -93,7 +90,7 @@ fn handle_message(state: State, control: Control) -> actor.Next(State, Control)
actor.continue(State(..state, input: Input(..state.input, content:))) actor.continue(State(..state, input: Input(..state.input, content:)))
} }
control.Backspace -> { control.Backspace -> {
logging.log(state.logger, "musicplayer - recieved backspace") logging.log("musicplayer - recieved backspace")
let content = case state.mode { let content = case state.mode {
Idle -> state.input.content Idle -> state.input.content
@@ -103,11 +100,10 @@ fn handle_message(state: State, control: Control) -> actor.Next(State, Control)
} }
control.Return -> { control.Return -> {
logging.log( logging.log(
state.logger,
"musicplayer - recieved return. `input.capture`: " "musicplayer - recieved return. `input.capture`: "
<> "'" <> "'"
<> state.input.content <> state.input.content
<> "'", <> "'",
) )
// Note: state.input.content is now the final input, use it // Note: state.input.content is now the final input, use it
@@ -123,26 +119,21 @@ fn handle_message(state: State, control: Control) -> actor.Next(State, Control)
} }
control.TogglePlayPause -> { control.TogglePlayPause -> {
logging.log(state.logger, "musicplayer - toggling play/pause") logging.log("musicplayer - toggling play/pause")
process.send(state.mpv, mpv_control.TogglePlayPause) process.send(state.mpv, mpv_control.TogglePlayPause)
update_playback_time(state.mpv, state.ui) update_playback_time(state.mpv, state.ui)
actor.continue(state) actor.continue(state)
} }
control.Exit -> { control.Exit -> {
logging.log(state.logger, "musicplayer - initiating musicplayer shutdown") logging.log("musicplayer - initiating musicplayer shutdown")
// Close `mpv` socket // Close `mpv` socket
process.call(state.mpv, 1000, fn(reply_to) { mpv_control.Exit(reply_to) }) process.call(state.mpv, 1000, fn(reply_to) { mpv_control.Exit(reply_to) })
// Reset terminal state (show cursor etc.) // Reset terminal state (show cursor etc.)
process.call(state.ui, 1000, fn(reply_to) { ui_control.Exit(reply_to) }) process.call(state.ui, 1000, fn(reply_to) { ui_control.Exit(reply_to) })
logging.log(state.logger, "musicplayer - stopped") logging.log("musicplayer - stopped")
// Close logger (NOOP)
process.call(state.logger, 1000, fn(reply_to) {
logging_control.Exit(reply_to)
})
actor.stop() actor.stop()
} }

View File

@@ -0,0 +1,42 @@
import gleam/list
import gleam/string
import gleam/string_tree
import musicplayer/ui/internal
pub fn text(chars: String, x: Int, y: Int) {
internal.chars_at(chars, x, y)
}
pub fn 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

@@ -7,9 +7,13 @@ pub fn clear_screen() -> Nil {
io.print("\u{001B}[2J\u{001B}[H") io.print("\u{001B}[2J\u{001B}[H")
} }
pub fn print_at(text: String, x: Int, y: Int) -> Nil { pub fn chars_at(chars: String, x: Int, y: Int) -> String {
let seq = "\u{001B}[" <> int.to_string(y) <> ";" <> int.to_string(x) <> "H" let seq = "\u{001B}[" <> int.to_string(y) <> ";" <> int.to_string(x) <> "H"
io.print(seq <> text) seq <> chars
}
pub fn print(chars: String) -> Nil {
io.print(chars)
} }
pub fn hide_cursor() -> Nil { pub fn hide_cursor() -> Nil {

View File

@@ -1,28 +1,33 @@
import gleam/dict import gleam/dict
import gleam/erlang/process.{type Subject}
import gleam/float import gleam/float
import gleam/int import gleam/int
import gleam/list import gleam/list
import gleam/string import gleam/string
import gleam/string_tree
import musicplayer/logging/control as logging_control
import musicplayer/logging/logging import musicplayer/logging/logging
import musicplayer/ui/ansi
import musicplayer/ui/internal import musicplayer/ui/internal
pub type Layout {
Layout(width: Int, height: Int, nodes: dict.Dict(Section, Node))
}
pub type Section { pub type Section {
Section(String)
Root Root
Header Header
Search Search
PlaybackTime PlaybackTime
} }
pub type NodeType {
Container
Row
Cell
}
/// A Nodes width and height is in percentage (of the available width/height of its parent Node) /// A Nodes width and height is in percentage (of the available width/height of its parent Node)
pub type Node { pub type Node {
Node( Node(
t: NodeType,
content: String, content: String,
width_percent: Int, width_percent: Int,
height_percent: Int, height_percent: Int,
@@ -30,34 +35,55 @@ pub type Node {
) )
} }
pub type Layout {
Layout(width: Int, height: Int, nodes: dict.Dict(Section, Node))
}
pub fn new() -> Layout { pub fn new() -> Layout {
let nodes = let nodes =
dict.from_list([ dict.from_list([
#( #(
Root, Root,
Node(content: "", width_percent: 100, height_percent: 100, children: [ Node(
// Header, t: Container,
// Search, content: "Music Player",
PlaybackTime, width_percent: 100,
]), height_percent: 100,
children: [Header, Search, PlaybackTime],
),
),
#(
Header,
Node(
t: Row,
content: "Foo (1) | Bar (2) | Baz (3)",
width_percent: 100,
height_percent: 33,
children: [],
),
),
#(
Search,
Node(
t: Row,
content: "",
width_percent: 100,
height_percent: 33,
children: [],
),
), ),
// #(
// Header,
// Node(content: "Music Player", width: 50, height: 10, children: []),
// ),
// #(Search, Node(content: "", width: 50, height: 10, children: [])),
#( #(
PlaybackTime, PlaybackTime,
Node( Node(
t: Row,
content: "00:00", content: "00:00",
width_percent: 50, width_percent: 100,
height_percent: 100, height_percent: 33,
children: [], children: [],
), ),
), ),
]) ])
Layout(width: 0, height: 0, nodes: nodes)
Layout(0, 0, nodes: nodes)
} }
pub fn update_section( pub fn update_section(
@@ -83,45 +109,96 @@ pub fn update_dimensions(layout: Layout, width: Int, height: Int) -> Layout {
Layout(..layout, width:, height:) Layout(..layout, width:, height:)
} }
pub fn render(logger: Subject(logging_control.Control), layout: Layout) -> Nil { pub fn render(layout: Layout) -> Nil {
internal.clear_screen() internal.clear_screen()
[layout.width, layout.height] [layout.width, layout.height]
|> list.map(int.to_string) |> list.map(int.to_string)
|> string.join(" ") |> string.join(" ")
|> string.append("layout - render: ", _) |> string.append("layout - render: ", _)
|> logging.log(logger, _) |> logging.log
let container_width = int.to_float(layout.width) let container_width = int.to_float(layout.width)
let container_height = int.to_float(layout.height) let container_height = int.to_float(layout.height)
let container_top_left_x = 1 let container_top_left_x = 1
let container_top_left_y = 1 let container_top_left_y = 1
render_loop( let ansi_renders =
Renders(
box: fn(tree, x, y, w, h) {
string_tree.append(tree, ansi.box(x, y, w, h))
},
text: fn(tree, chars, x, y) {
string_tree.append(tree, ansi.text(chars, x, y))
},
)
string_tree.new()
|> render_generic(
layout, layout,
container_width, container_width,
container_height, container_height,
container_top_left_x, container_top_left_x,
container_top_left_y, container_top_left_y,
0,
Root, Root,
logger, _,
ansi_renders,
)
|> string_tree.to_string
|> internal.print
}
pub type Renders(into) {
Renders(
text: fn(into, String, Int, Int) -> into,
box: fn(into, Int, Int, Int, Int) -> into,
) )
} }
pub fn render_loop( pub fn render_generic(
layout: Layout, layout: Layout,
// Dimensions
container_width: Float, container_width: Float,
container_height: Float, container_height: Float,
container_top_left_x: Int, container_tl_x: Int,
container_top_left_y: Int, container_tl_y: Int,
// State
index: Int,
from: Section, from: Section,
logger: Subject(logging_control.Control), render_into: into,
) -> Nil { renders: Renders(into),
let margin = 2.0 ) -> into {
case dict.get(layout.nodes, from) { case dict.get(layout.nodes, from) {
Error(_) -> Nil Error(_) -> render_into
Ok(node) -> { Ok(node) -> {
list.each(node.children, fn(child) { 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)
}
let parent =
render_into
|> renders.box(cx, cy, width, height)
// + 2 for header margin
|> renders.text(node.content, cx + 2, cy)
list.index_map(node.children, fn(child, i) { #(i, child) })
|> list.fold(parent, fn(acc_into, ic) {
let #(i, child) = ic
let cw = let cw =
container_width container_width
*. { int.to_float(node.width_percent) /. 100.0 } *. { int.to_float(node.width_percent) /. 100.0 }
@@ -134,59 +211,21 @@ pub fn render_loop(
-. margin -. margin
|> float.floor |> float.floor
let cx = container_top_left_x + 1 let child_origin_x = container_tl_x + 1
let cy = container_top_left_y + 1 let child_origin_y = container_tl_y + 1
render_loop(layout, cw, ch, cx, cy, child, logger) render_generic(
layout,
cw,
ch,
child_origin_x,
child_origin_y,
i,
child,
acc_into,
renders,
)
}) })
logging.log(logger, "section: " <> string.inspect(from))
logging.log(
logger,
"container width: " <> float.to_string(container_width),
)
logging.log(
logger,
"container height: " <> float.to_string(container_height),
)
let width =
container_width
*. { int.to_float(node.width_percent) /. int.to_float(100) }
|> float.floor
|> float.truncate
let height =
container_height
*. { int.to_float(node.height_percent) /. int.to_float(100) }
|> float.floor
|> float.truncate
logging.log(logger, "width: " <> int.to_string(width))
logging.log(logger, "height: " <> int.to_string(height))
let cx = container_top_left_x
let cy = container_top_left_y
logging.log(logger, "cx: " <> int.to_string(cx))
logging.log(logger, "cy: " <> int.to_string(cy))
draw_box(cx, cy, width, height)
// Box heading
internal.print_at(node.content, cx, cy)
} }
} }
} }
fn draw_box(x: Int, y: Int, width: Int, height: Int) -> Nil {
let box_chars = #("", "", "", "", "", "")
let #(tl, tr, bl, br, h, v) = box_chars
internal.print_at(tl <> string.repeat(h, width - 2) <> tr, x, y)
list.range(1, height - 2)
|> list.each(fn(row) {
internal.print_at(v, x, y + row)
internal.print_at(v, x + width - 1, y + row)
})
internal.print_at(bl <> string.repeat(h, width - 2) <> br, x, y + height - 1)
}

View File

@@ -0,0 +1,82 @@
import gleam/dict
import musicplayer/ui/internal
import musicplayer/ui/layout.{Container, Layout, Node, Section}
import musicplayer/ui/layout_examples/wait_for_input.{wait_for_input}
pub fn main() {
let assert Ok(width) = internal.io_get_columns()
let assert Ok(height) = internal.io_get_rows()
two_rows_with_cells(width, height)
|> layout.render
wait_for_input()
}
/// Two rows:
/// First row has two cells
/// Second row has no cells
fn two_rows_with_cells(width: Int, height: Int) -> layout.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: layout.Row,
content: "row 1",
width_percent: 100,
height_percent: 50,
children: [
Section("A"),
Section("A"),
],
),
),
#(
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 2",
width_percent: 100,
height_percent: 50,
children: [],
),
),
])
Layout(width:, height:, nodes: nodes)
}

View File

@@ -0,0 +1,15 @@
import gleam/erlang/process.{type Name}
import musicplayer/input/input
import musicplayer/input/key.{type Key}
pub fn wait_for_input() {
let input_keys_name: Name(Key) = process.new_name("input_keys")
let assert Ok(_) = process.register(process.self(), input_keys_name)
input.new(input_keys_name)
process.new_selector()
|> process.select(process.named_subject(input_keys_name))
|> process.selector_receive_forever
}

View File

@@ -4,30 +4,23 @@ import gleam/list
import gleam/otp/actor import gleam/otp/actor
import gleam/string import gleam/string
import musicplayer/logging/control as logging_control
import musicplayer/logging/logging import musicplayer/logging/logging
import musicplayer/ui/control.{type Control} import musicplayer/ui/control.{type Control}
import musicplayer/ui/internal import musicplayer/ui/internal
import musicplayer/ui/layout.{type Layout} import musicplayer/ui/layout.{type Layout}
pub type State(redraw, content) { pub type State(redraw, content) {
State( State(redraw: Subject(Layout), layout: Layout)
logger: Subject(logging_control.Control),
redraw: Subject(Layout),
layout: Layout,
)
} }
pub fn new( pub fn new() -> Result(Subject(Control), String) {
logger: Subject(logging_control.Control),
) -> Result(Subject(Control), String) {
let redraw_name = process.new_name("redraw") let redraw_name = process.new_name("redraw")
let redraw: Subject(Layout) = process.named_subject(redraw_name) let redraw: Subject(Layout) = process.named_subject(redraw_name)
let layout = layout.new() let layout = layout.new()
case case
actor.new(State(logger, redraw, layout)) actor.new(State(redraw, layout))
|> actor.on_message(handle_message) |> actor.on_message(handle_message)
|> actor.start |> actor.start
{ {
@@ -36,7 +29,7 @@ pub fn new(
Ok(actor.Started(data: ui, ..)) -> { Ok(actor.Started(data: ui, ..)) -> {
process.spawn(fn() { process.spawn(fn() {
let update_dimensions_interval_ms = 300 let update_dimensions_interval_ms = 300
update_dimensions_on_interval(logger, ui, update_dimensions_interval_ms) update_dimensions_on_interval(ui, update_dimensions_interval_ms)
}) })
process.spawn(fn() { process.spawn(fn() {
@@ -45,7 +38,7 @@ pub fn new(
internal.clear_screen() internal.clear_screen()
internal.hide_cursor() internal.hide_cursor()
redraw_loop(logger, redraw) redraw_loop(redraw)
}) })
Ok(ui) Ok(ui)
@@ -68,7 +61,7 @@ fn handle_message(
|> list.map(int.to_string) |> list.map(int.to_string)
|> string.join(" ") |> string.join(" ")
|> string.append("ui - updating dimensions: ", _) |> string.append("ui - updating dimensions: ", _)
|> logging.log(state.logger, _) |> logging.log
let layout = layout.update_dimensions(state.layout, width, height) let layout = layout.update_dimensions(state.layout, width, height)
@@ -92,28 +85,21 @@ fn handle_message(
} }
} }
fn redraw_loop( fn redraw_loop(redraw: Subject(Layout)) -> Nil {
logger: Subject(logging_control.Control),
redraw: Subject(Layout),
) -> Nil {
process.receive_forever(redraw) process.receive_forever(redraw)
|> layout.render(logger, _) |> layout.render
redraw_loop(logger, redraw) redraw_loop(redraw)
} }
fn update_dimensions_on_interval( fn update_dimensions_on_interval(ui: Subject(Control), interval_ms: Int) {
logger: Subject(logging_control.Control),
ui: Subject(Control),
interval_ms: Int,
) {
case internal.io_get_columns(), internal.io_get_rows() { case internal.io_get_columns(), internal.io_get_rows() {
Ok(width), Ok(height) -> { Ok(width), Ok(height) -> {
process.send(ui, control.UpdateDimensions(width, height)) process.send(ui, control.UpdateDimensions(width, height))
} }
_, _ -> logging.log(logger, "ui - failed to update dimensions") _, _ -> logging.log("ui - failed to update dimensions")
} }
process.sleep(interval_ms) process.sleep(interval_ms)
update_dimensions_on_interval(logger, ui, interval_ms) update_dimensions_on_interval(ui, interval_ms)
} }

View File

@@ -0,0 +1,118 @@
import gleam/dict
import gleam/io
import gleam/string
import gleeunit
import gleeunit/should
import musicplayer/ui/virtual_ansi
import musicplayer/ui/layout.{Layout, Node, 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 =
virtual_ansi.render(layout, Section("Root"), layout.width, layout.height)
case visual == string.trim(expected) {
True -> Nil
False -> {
io.println("Test failed")
io.println("Expected:")
io.println(string.trim(expected))
io.println("Got:")
io.println(visual)
should.equal(visual, expected)
}
}
}

View File

@@ -0,0 +1,113 @@
import gleam/dict
import gleam/int
import gleam/list
import gleam/string
import musicplayer/ui/layout.{type Layout, type Section, Renders}
pub type Screen =
dict.Dict(#(Int, Int), String)
pub fn render(layout: Layout, root: Section, width: Int, height: Int) -> String {
let test_renders =
Renders(
box: fn(screen, x, y, w, h) { box(screen, x, y, w, h) },
text: fn(screen, chars, x, y) { text(screen, chars, x, y) },
)
let screen =
layout.render_generic(
layout,
int.to_float(width),
int.to_float(height),
1,
1,
0,
root,
dict.new(),
test_renders,
)
screen_to_string(screen)
}
pub 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")
}
pub fn 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)
})
}
pub fn 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
|> horizontal_line(x + 1, y, w - 2, hor)
|> horizontal_line(x + 1, y + h - 1, w - 2, hor)
// 3. Side edges
|> vertical_line(x, y + 1, h - 2, ver)
|> vertical_line(x + w - 1, y + 1, h - 2, ver)
}
}
}
fn horizontal_line(
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 vertical_line(
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) })
}