summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorLogan Hunt <loganhunt@simponic.xyz>2023-01-13 17:02:31 -0700
committerGitHub <noreply@github.com>2023-01-13 17:02:31 -0700
commitb1b62f154ab5f74a9217dbf5a6422640ac929df3 (patch)
tree6fa3b6e8d7e9219decda28948bf3f02c3cf2dab2 /lib
parentfdc22875284b78f9fb98993cbe44ce893c0de413 (diff)
parent3a6c603b0b12964d8a04ae4f78fb61bc094adf12 (diff)
downloadchessh-b1b62f154ab5f74a9217dbf5a6422640ac929df3.tar.gz
chessh-b1b62f154ab5f74a9217dbf5a6422640ac929df3.zip
Merge pull request #3 from Simponic/draw_board
Draw board
Diffstat (limited to 'lib')
-rw-r--r--lib/chessh/ssh/client.ex123
-rw-r--r--lib/chessh/ssh/client/board/board.ex123
-rw-r--r--lib/chessh/ssh/client/board/renderer.ex252
-rw-r--r--lib/chessh/ssh/client/board/server.ex19
-rw-r--r--lib/chessh/ssh/client/client.ex147
-rw-r--r--lib/chessh/ssh/client/menu.ex90
-rw-r--r--lib/chessh/ssh/client/screen.ex18
-rw-r--r--lib/chessh/ssh/screens/board.ex31
-rw-r--r--lib/chessh/ssh/screens/menu.ex105
-rw-r--r--lib/chessh/ssh/screens/screen.ex22
-rw-r--r--lib/chessh/ssh/tui.ex36
-rw-r--r--lib/chessh/utils.ex24
12 files changed, 690 insertions, 300 deletions
diff --git a/lib/chessh/ssh/client.ex b/lib/chessh/ssh/client.ex
deleted file mode 100644
index 4ed2fd1..0000000
--- a/lib/chessh/ssh/client.ex
+++ /dev/null
@@ -1,123 +0,0 @@
-defmodule Chessh.SSH.Client do
- alias IO.ANSI
- alias Chessh.SSH.Client.Menu
- require Logger
-
- use GenServer
-
- @clear_codes [
- ANSI.clear(),
- ANSI.reset(),
- ANSI.home()
- ]
-
- @min_terminal_width 64
- @min_terminal_height 31
- @max_terminal_width 255
- @max_terminal_height 127
-
- @terminal_bad_dim_msg [
- @clear_codes | "The dimensions of your terminal are not within in the valid range"
- ]
-
- defmodule State do
- defstruct tui_pid: nil,
- width: 0,
- height: 0,
- player_session: nil,
- buffer: [],
- state_stack: [{Menu, %Menu.State{}}]
- end
-
- @impl true
- def init([%State{tui_pid: tui_pid} = state]) do
- send(tui_pid, {:send_data, render(state)})
- {:ok, state}
- end
-
- @impl true
- def handle_info(:quit, %State{} = state) do
- {:stop, :normal, state}
- end
-
- @impl true
- def handle_info(msg, state) do
- [burst_ms, burst_rate] =
- Application.get_env(:chessh, RateLimits)
- |> Keyword.take([:player_session_message_burst_ms, :player_session_message_burst_rate])
- |> Keyword.values()
-
- case Hammer.check_rate_inc(
- "player-session-#{state.player_session.id}-burst-message-rate",
- burst_ms,
- burst_rate,
- 1
- ) do
- {:allow, _count} ->
- handle(msg, state)
-
- {:deny, _limit} ->
- {:noreply, state}
- end
- end
-
- def handle(
- {:data, data},
- %State{tui_pid: tui_pid, state_stack: [{module, _screen_state} | _tail]} = state
- ) do
- action = keymap(data)
-
- if action == :quit do
- {:stop, :normal, state}
- else
- new_state = module.handle_input(action, state)
-
- send(tui_pid, {:send_data, render(new_state)})
-
- {:noreply, new_state}
- end
- end
-
- def handle({:resize, {width, height}}, %State{tui_pid: tui_pid} = state) do
- new_state = %State{state | width: width, height: height}
-
- if height <= @max_terminal_height || width <= @max_terminal_width do
- send(tui_pid, {:send_data, render(new_state)})
- end
-
- {:noreply, new_state}
- end
-
- def keymap(key) do
- case key do
- # Exit keys - C-c and C-d
- <<3>> -> :quit
- <<4>> -> :quit
- # Arrow keys
- "\e[A" -> :up
- "\e[B" -> :down
- "\e[D" -> :left
- "\e[C" -> :right
- "\r" -> :return
- x -> x
- end
- end
-
- def terminal_size_allowed(width, height) do
- Enum.member?(@min_terminal_width..@max_terminal_width, width) &&
- Enum.member?(@min_terminal_height..@max_terminal_height, height)
- end
-
- def render(
- %State{width: width, height: height, state_stack: [{module, _screen_state} | _]} = state
- ) do
- if terminal_size_allowed(width, height) do
- [
- @clear_codes ++
- module.render(state)
- ]
- else
- @terminal_bad_dim_msg
- end
- end
-end
diff --git a/lib/chessh/ssh/client/board/board.ex b/lib/chessh/ssh/client/board/board.ex
new file mode 100644
index 0000000..cbbade5
--- /dev/null
+++ b/lib/chessh/ssh/client/board/board.ex
@@ -0,0 +1,123 @@
+defmodule Chessh.SSH.Client.Board do
+ require Logger
+ alias Chessh.Utils
+ alias Chessh.SSH.Client.Board.Renderer
+
+ defmodule State do
+ defstruct cursor: %{x: 7, y: 7},
+ highlighted: %{},
+ move_from: nil,
+ game_id: nil,
+ client_pid: nil,
+ binbo_pid: nil,
+ width: 0,
+ height: 0,
+ flipped: false
+ end
+
+ use Chessh.SSH.Client.Screen
+
+ def init([%State{client_pid: client_pid, game_id: game_id} = state | _]) do
+ :syn.add_node_to_scopes([:games])
+ :ok = :syn.join(:games, {:game, game_id}, self())
+
+ :binbo.start()
+ {:ok, binbo_pid} = :binbo.new_server()
+ :binbo.new_game(binbo_pid)
+
+ send(client_pid, {:send_to_ssh, Utils.clear_codes()})
+
+ {:ok, %State{state | binbo_pid: binbo_pid}}
+ end
+
+ def handle_info({:new_move, move}, %State{binbo_pid: binbo_pid, client_pid: client_pid} = state) do
+ case :binbo.move(binbo_pid, move) do
+ {:ok, :continue} ->
+ send(client_pid, {:send_to_ssh, render_state(state)})
+
+ _ ->
+ nil
+ end
+
+ {:noreply, state}
+ end
+
+ def input(
+ width,
+ height,
+ action,
+ %State{
+ move_from: move_from,
+ game_id: game_id,
+ cursor: %{x: cursor_x, y: cursor_y} = cursor,
+ client_pid: client_pid,
+ flipped: flipped
+ } = state
+ ) do
+ new_cursor =
+ case action do
+ :left -> %{y: cursor_y, x: Utils.wrap_around(cursor_x, -1, Renderer.chess_board_width())}
+ :right -> %{y: cursor_y, x: Utils.wrap_around(cursor_x, 1, Renderer.chess_board_width())}
+ :down -> %{y: Utils.wrap_around(cursor_y, 1, Renderer.chess_board_height()), x: cursor_x}
+ :up -> %{y: Utils.wrap_around(cursor_y, -1, Renderer.chess_board_height()), x: cursor_x}
+ _ -> cursor
+ end
+
+ {new_move_from, move_to} =
+ if action == :return do
+ coords = {new_cursor.y, new_cursor.x}
+
+ case move_from do
+ nil -> {coords, nil}
+ _ -> {nil, coords}
+ end
+ else
+ {move_from, nil}
+ end
+
+ # TODO: Check move here, then publish new move, subscribers get from DB instead
+ if move_from && move_to do
+ attempted_move =
+ if flipped,
+ do:
+ "#{Renderer.to_chess_coord(flip(move_from))}#{Renderer.to_chess_coord(flip(move_to))}",
+ else: "#{Renderer.to_chess_coord(move_from)}#{Renderer.to_chess_coord(move_to)}"
+
+ :syn.publish(:games, {:game, game_id}, {:new_move, attempted_move})
+ end
+
+ new_state = %State{
+ state
+ | cursor: new_cursor,
+ move_from: new_move_from,
+ highlighted: %{
+ {new_cursor.y, new_cursor.x} => Renderer.to_select_background(),
+ new_move_from => Renderer.from_select_background()
+ },
+ width: width,
+ height: height,
+ flipped: if(action == "f", do: !flipped, else: flipped)
+ }
+
+ send(client_pid, {:send_to_ssh, render_state(new_state)})
+ new_state
+ end
+
+ def render(width, height, %State{client_pid: client_pid} = state) do
+ send(client_pid, {:send_to_ssh, render_state(state)})
+ %State{state | width: width, height: height}
+ end
+
+ def flip({y, x}),
+ do: {Renderer.chess_board_height() - 1 - y, Renderer.chess_board_width() - 1 - x}
+
+ defp render_state(
+ %State{
+ binbo_pid: binbo_pid
+ } = state
+ ) do
+ {:ok, fen} = :binbo.get_fen(binbo_pid)
+
+ Renderer.render_board_state(fen, state)
+ end
+end
diff --git a/lib/chessh/ssh/client/board/renderer.ex b/lib/chessh/ssh/client/board/renderer.ex
new file mode 100644
index 0000000..fa8648f
--- /dev/null
+++ b/lib/chessh/ssh/client/board/renderer.ex
@@ -0,0 +1,252 @@
+defmodule Chessh.SSH.Client.Board.Renderer do
+ alias IO.ANSI
+ alias Chessh.Utils
+ alias Chessh.SSH.Client.Board
+ require Logger
+
+ @chess_board_height 8
+ @chess_board_width 8
+
+ @tile_width 7
+ @tile_height 4
+
+ @from_select_background ANSI.light_blue_background()
+ @to_select_background ANSI.blue_background()
+ @dark_piece_color ANSI.light_red()
+ @light_piece_color ANSI.light_magenta()
+
+ def chess_board_height(), do: @chess_board_height
+ def chess_board_width(), do: @chess_board_width
+ def to_select_background(), do: @to_select_background
+ def from_select_background(), do: @from_select_background
+
+ def to_chess_coord({y, x})
+ when x >= 0 and x < @chess_board_width and y >= 0 and y < @chess_board_height do
+ "#{List.to_string([?a + x])}#{@chess_board_height - y}"
+ end
+
+ def render_board_state(fen, %Board.State{
+ width: _width,
+ height: _height,
+ highlighted: highlighted,
+ flipped: flipped
+ }) do
+ board =
+ draw_board(
+ fen,
+ {@tile_width, @tile_height},
+ highlighted,
+ flipped
+ )
+
+ [ANSI.home()] ++
+ Enum.map(
+ Enum.zip(1..length(board), board),
+ fn {i, line} ->
+ [ANSI.cursor(i, 0), line]
+ end
+ )
+ end
+
+ defp tileIsLight(row, col) do
+ rem(row, 2) == rem(col, 2)
+ end
+
+ defp piece_type(char) do
+ case String.capitalize(char) do
+ "P" -> "pawn"
+ "N" -> "knight"
+ "R" -> "rook"
+ "B" -> "bishop"
+ "K" -> "king"
+ "Q" -> "queen"
+ _ -> nil
+ end
+ end
+
+ defp skip_cols_or_place_piece_reduce(char, {curr_column, data}, rowI) do
+ case Integer.parse(char) do
+ {skip, ""} ->
+ {curr_column + skip, data}
+
+ _ ->
+ case piece_type(char) do
+ nil ->
+ {curr_column, data}
+
+ type ->
+ shade = if(char == String.capitalize(char), do: "light", else: "dark")
+
+ {curr_column + 1,
+ Map.put(
+ data,
+ "#{rowI}, #{curr_column}",
+ {shade, type}
+ )}
+ end
+ end
+ end
+
+ defp make_coordinate_to_piece_art_map(fen) do
+ rows =
+ String.split(fen, " ")
+ |> List.first()
+ |> String.split("/")
+
+ Enum.zip(rows, 0..(length(rows) - 1))
+ |> Enum.map(fn {row, rowI} ->
+ {@chess_board_height, pieces_per_row} =
+ Enum.reduce(
+ String.split(row, ""),
+ {0, %{}},
+ &skip_cols_or_place_piece_reduce(&1, &2, rowI)
+ )
+
+ pieces_per_row
+ end)
+ |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc ->
+ Map.merge(acc, pieces_map_for_this_row)
+ end)
+ end
+
+ defp draw_board(
+ fen,
+ {tile_width, tile_height} = tile_dims,
+ highlights,
+ flipped
+ ) do
+ coordinate_to_piece = make_coordinate_to_piece_art_map(fen)
+ board = make_board(tile_dims)
+
+ (Enum.zip_with([board, 0..(length(board) - 1)], fn [row_str, row] ->
+ curr_y = div(row, tile_height)
+
+ %{row_chars: row_chars} =
+ Enum.reduce(
+ Enum.zip(String.graphemes(row_str), 0..(String.length(row_str) - 1)),
+ %{current_color: ANSI.black(), row_chars: []},
+ fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state ->
+ curr_x = div(col, tile_width)
+
+ key =
+ "#{if !flipped, do: curr_y, else: @chess_board_height - curr_y - 1}, #{if !flipped, do: curr_x, else: @chess_board_width - curr_x - 1}"
+
+ relative_to_tile_col = col - curr_x * tile_width
+
+ prefix =
+ if relative_to_tile_col == 0 do
+ case Map.fetch(highlights, {curr_y, curr_x}) do
+ {:ok, color} ->
+ color
+
+ _ ->
+ ANSI.default_background()
+ end
+ end
+
+ {color, row_chars} =
+ case Map.fetch(coordinate_to_piece, key) do
+ {:ok, {shade, type}} ->
+ piece = Utils.ascii_chars()["pieces"][shade][type]
+ piece_line = Enum.at(piece, row - curr_y * tile_height)
+ pad_left_right = div(tile_width - String.length(piece_line), 2)
+
+ if relative_to_tile_col >= pad_left_right &&
+ relative_to_tile_col < tile_width - pad_left_right do
+ piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right)
+ new_char = if piece_char == " ", do: char, else: piece_char
+
+ color =
+ if piece_char == " ",
+ do: ANSI.default_color(),
+ else:
+ if(shade == "dark", do: @dark_piece_color, else: @light_piece_color)
+
+ if color != current_color do
+ {color, row_chars ++ [prefix, color, new_char]}
+ else
+ {current_color, row_chars ++ [prefix, new_char]}
+ end
+ else
+ {ANSI.default_color(), row_chars ++ [prefix, ANSI.default_color(), char]}
+ end
+
+ _ ->
+ if ANSI.default_color() != current_color do
+ {ANSI.default_color(), row_chars ++ [prefix, ANSI.default_color(), char]}
+ else
+ {current_color, row_chars ++ [prefix, char]}
+ end
+ end
+
+ %{
+ row_state
+ | current_color: color,
+ row_chars: row_chars
+ }
+ end
+ )
+
+ curr_num =
+ Utils.ascii_chars()["numbers"][
+ Integer.to_string(if flipped, do: curr_y + 1, else: @chess_board_height - curr_y)
+ ]
+
+ curr_num_line_no = rem(row, @tile_height)
+
+ Enum.join(
+ [
+ String.pad_trailing(
+ if(curr_num_line_no < length(curr_num),
+ do: Enum.at(curr_num, curr_num_line_no),
+ else: ""
+ ),
+ @tile_width
+ )
+ ] ++ row_chars,
+ ""
+ )
+ end) ++ column_coords(flipped))
+ |> Enum.map(fn row_line -> "#{ANSI.default_background()}#{row_line}" end)
+ end
+
+ defp column_coords(flipped) do
+ Enum.map(0..(@tile_height - 1), fn row ->
+ String.duplicate(" ", @tile_width) <>
+ (Enum.map(
+ if(!flipped, do: 0..(@chess_board_width - 1), else: (@chess_board_width - 1)..0),
+ fn col ->
+ curr_letter = Utils.ascii_chars()["letters"][List.to_string([?a + col])]
+ curr_letter_line_no = rem(row, @tile_height)
+
+ curr_line =
+ if(curr_letter_line_no < length(curr_letter),
+ do: Enum.at(curr_letter, curr_letter_line_no),
+ else: ""
+ )
+
+ center_prefix_len = div(@tile_width - String.length(curr_line), 2)
+
+ String.pad_trailing(
+ String.duplicate(" ", center_prefix_len) <> curr_line,
+ @tile_width
+ )
+ end
+ )
+ |> Enum.join(""))
+ end)
+ end
+
+ defp make_board({tile_width, tile_height}) do
+ rows =
+ Enum.map(0..(@chess_board_height - 1), fn row ->
+ Enum.map(0..(@chess_board_width - 1), fn col ->
+ if(tileIsLight(row, col), do: '▊', else: ' ')
+ |> List.duplicate(tile_width)
+ end)
+ |> Enum.join("")
+ end)
+
+ Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end)
+ end
+end
diff --git a/lib/chessh/ssh/client/board/server.ex b/lib/chessh/ssh/client/board/server.ex
new file mode 100644
index 0000000..2e480e7
--- /dev/null
+++ b/lib/chessh/ssh/client/board/server.ex
@@ -0,0 +1,19 @@
+# defmodule Chessh.SSH.Client.Board.Server do
+# use GenServer
+#
+# defmodule State do
+# defstruct game_id: nil,
+# binbo_pid: nil
+# end
+#
+# def init([%State{game_id: game_id} = state]) do
+# {:ok, binbo_pid} = GenServer.start_link(:binbo, [])
+#
+# :syn.join(:games, {:game, game_id})
+# {:ok, state}
+# end
+#
+# def handle_cast({:new_move, attempted_move}, %State{game_id: game_id} = state) do
+# {:no_reply, state}
+# end
+# end
diff --git a/lib/chessh/ssh/client/client.ex b/lib/chessh/ssh/client/client.ex
new file mode 100644
index 0000000..10dd3b2
--- /dev/null
+++ b/lib/chessh/ssh/client/client.ex
@@ -0,0 +1,147 @@
+defmodule Chessh.SSH.Client do
+ alias IO.ANSI
+ require Logger
+
+ use GenServer
+
+ @clear_codes [
+ ANSI.clear(),
+ ANSI.home()
+ ]
+
+ @min_terminal_width 64
+ @min_terminal_height 38
+ @max_terminal_width 220
+ @max_terminal_height 100
+
+ defmodule State do
+ defstruct tui_pid: nil,
+ width: 0,
+ height: 0,
+ player_session: nil,
+ screen_processes: []
+ end
+
+ @impl true
+ def init([%State{} = state]) do
+ {:ok, screen_pid} =
+ GenServer.start_link(Chessh.SSH.Client.Board, [
+ %Chessh.SSH.Client.Board.State{client_pid: self()}
+ ])
+
+ {:ok, %{state | screen_processes: [screen_pid]}}
+ end
+
+ @impl true
+ def handle_info(:quit, %State{} = state) do
+ {:stop, :normal, state}
+ end
+
+ @impl true
+ def handle_info(msg, state) do
+ [burst_ms, burst_rate] =
+ Application.get_env(:chessh, RateLimits)
+ |> Keyword.take([:player_session_message_burst_ms, :player_session_message_burst_rate])
+ |> Keyword.values()
+
+ case Hammer.check_rate_inc(
+ "player-session-#{state.player_session.id}-burst-message-rate",
+ burst_ms,
+ burst_rate,
+ 1
+ ) do
+ {:allow, _count} ->
+ handle(msg, state)
+
+ {:deny, _limit} ->
+ {:noreply, state}
+ end
+ end
+
+ def handle(
+ {:data, data},
+ %State{width: width, height: height, screen_processes: [screen_pid | _]} = state
+ ) do
+ action = keymap(data)
+
+ if action == :quit do
+ {:stop, :normal, state}
+ else
+ send(screen_pid, {:input, width, height, action})
+ {:noreply, state}
+ end
+ end
+
+ def handle(
+ :refresh,
+ %State{} = state
+ ) do
+ render(state)
+ {:noreply, state}
+ end
+
+ def handle(
+ {:send_to_ssh, data},
+ %State{width: width, height: height, tui_pid: tui_pid} = state
+ ) do
+ case get_terminal_dim_msg(width, height) do
+ {true, msg} -> send(tui_pid, {:send_data, msg})
+ {false, _} -> send(tui_pid, {:send_data, data})
+ end
+
+ {:noreply, state}
+ end
+
+ def handle(
+ {:resize, {width, height}},
+ %State{tui_pid: tui_pid, screen_processes: [screen_pid | _]} = state
+ ) do
+ case get_terminal_dim_msg(width, height) do
+ {true, msg} -> send(tui_pid, {:send_data, msg})
+ {false, _} -> send(screen_pid, {:render, width, height})
+ end
+
+ {:noreply, %State{state | width: width, height: height}}
+ end
+
+ def keymap(key) do
+ case key do
+ # Exit keys - C-c and C-d
+ <<3>> -> :quit
+ <<4>> -> :quit
+ # Arrow keys
+ "\e[A" -> :up
+ "\e[B" -> :down
+ "\e[D" -> :left
+ "\e[C" -> :right
+ "\r" -> :return
+ x -> x
+ end
+ end
+
+ defp get_terminal_dim_msg(width, height) do
+ case {height > @max_terminal_height, height < @min_terminal_height,
+ width > @max_terminal_width, width < @min_terminal_width} do
+ {true, _, _, _} -> {true, @clear_codes ++ ["The terminal height is too large."]}
+ {_, true, _, _} -> {true, @clear_codes ++ ["The terminal height is too small."]}
+ {_, _, true, _} -> {true, @clear_codes ++ ["The terminal width is too large"]}
+ {_, _, _, true} -> {true, @clear_codes ++ ["The terminal width is too small."]}
+ {false, false, false, false} -> {false, nil}
+ end
+ end
+
+ defp render(%State{
+ tui_pid: tui_pid,
+ width: width,
+ height: height,
+ screen_processes: [screen_pid | _]
+ }) do
+ {out_of_range, msg} = get_terminal_dim_msg(width, height)
+
+ if out_of_range && msg do
+ send(tui_pid, {:send_data, msg})
+ else
+ send(screen_pid, {:render, width, height})
+ end
+ end
+end
diff --git a/lib/chessh/ssh/client/menu.ex b/lib/chessh/ssh/client/menu.ex
new file mode 100644
index 0000000..c207872
--- /dev/null
+++ b/lib/chessh/ssh/client/menu.ex
@@ -0,0 +1,90 @@
+defmodule Chessh.SSH.Client.Menu do
+ alias Chessh.Utils
+ alias IO.ANSI
+
+ require Logger
+
+ defmodule State do
+ defstruct client_pid: nil,
+ selected: 0
+ end
+
+ @logo " Simponic's
+ dP MP\"\"\"\"\"\"`MM MP\"\"\"\"\"\"`MM M\"\"MMMMM\"\"MM
+ 88 M mmmmm..M M mmmmm..M M MMMMM MM
+.d8888b. 88d888b. .d8888b. M. `YM M. `YM M `M
+88' `\"\" 88' `88 88ooood8 MMMMMMM. M MMMMMMM. M M MMMMM MM
+88. ... 88 88 88. ... M. .MMM' M M. .MMM' M M MMMMM MM
+`88888P' dP dP `88888P' Mb. .dM Mb. .dM M MMMMM MM
+ MMMMMMMMMMM MMMMMMMMMMM MMMMMMMMMMMM"
+ use Chessh.SSH.Client.Screen
+
+ def init([%State{} = state | _]) do
+ {:ok, state}
+ end
+
+ @options [
+ {"Option 1", {}},
+ {"Option 2", {}},
+ {"Option 3", {}}
+ ]
+
+ def input(width, height, action, %State{client_pid: client_pid, selected: selected} = state) do
+ new_state =
+ case(action) do
+ :up ->
+ %State{
+ state
+ | selected: Utils.wrap_around(selected, -1, length(@options))
+ }
+
+ :down ->
+ %State{state | selected: Utils.wrap_around(selected, 1, length(@options))}
+
+ # :return ->
+ # {_, new_state} = Enum.at(@options, selected)
+ # new_state
+
+ _ ->
+ state
+ end
+
+ send(client_pid, {:send_to_ssh, render_state(width, height, new_state)})
+ new_state
+ end
+
+ def render(width, height, %State{client_pid: client_pid} = state) do
+ send(client_pid, {:send_to_ssh, render_state(width, height, state)})
+ state
+ end
+
+ defp render_state(
+ width,
+ height,
+ %State{selected: selected}
+ ) do
+ logo_lines = String.split(@logo, "\n")
+ {logo_width, logo_height} = Utils.text_dim(@logo)
+ {y, x} = Utils.center_rect({logo_width, logo_height + length(logo_lines)}, {width, height})
+
+ [ANSI.clear()] ++
+ Enum.flat_map(
+ Enum.zip(1..length(logo_lines), logo_lines),
+ fn {i, line} ->
+ [
+ ANSI.cursor(y + i, x),
+ line
+ ]
+ end
+ ) ++
+ Enum.flat_map(
+ Enum.zip(0..(length(@options) - 1), @options),
+ fn {i, {option, _}} ->
+ [
+ ANSI.cursor(y + length(logo_lines) + i + 1, x),
+ if(i == selected, do: ANSI.format([:bright, :light_cyan, "+ #{option}"]), else: option)
+ ]
+ end
+ ) ++ [ANSI.home()]
+ end
+end
diff --git a/lib/chessh/ssh/client/screen.ex b/lib/chessh/ssh/client/screen.ex
new file mode 100644
index 0000000..0437b23
--- /dev/null
+++ b/lib/chessh/ssh/client/screen.ex
@@ -0,0 +1,18 @@
+defmodule Chessh.SSH.Client.Screen do
+ @callback render(width :: integer(), height :: integer(), state :: any()) :: any()
+ @callback input(width :: integer(), height :: integer(), action :: any(), state :: any()) ::
+ any()
+
+ defmacro __using__(_) do
+ quote do
+ @behaviour Chessh.SSH.Client.Screen
+ use GenServer
+
+ def handle_info({:render, width, height}, state),
+ do: {:noreply, render(width, height, state)}
+
+ def handle_info({:input, width, height, action}, state),
+ do: {:noreply, input(width, height, action, state)}
+ end
+ end
+end
diff --git a/lib/chessh/ssh/screens/board.ex b/lib/chessh/ssh/screens/board.ex
deleted file mode 100644
index c95049f..0000000
--- a/lib/chessh/ssh/screens/board.ex
+++ /dev/null
@@ -1,31 +0,0 @@
-defmodule Chessh.SSH.Client.Board do
- alias Chessh.SSH.Client
- alias IO.ANSI
-
- require Logger
-
- defmodule State do
- defstruct cursor_x: 0,
- cursor_y: 0
- end
-
- use Chessh.SSH.Client.Screen
-
- def render(%Client.State{} = _state) do
- knight = @ascii_chars["pieces"]["white"]["knight"]
-
- [ANSI.home()] ++
- Enum.map(
- Enum.zip(0..(length(knight) - 1), knight),
- fn {i, line} ->
- [ANSI.cursor(i, 0), line]
- end
- )
- end
-
- def handle_input(action, %Client.State{} = state) do
- case action do
- _ -> state
- end
- end
-end
diff --git a/lib/chessh/ssh/screens/menu.ex b/lib/chessh/ssh/screens/menu.ex
deleted file mode 100644
index f89670f..0000000
--- a/lib/chessh/ssh/screens/menu.ex
+++ /dev/null
@@ -1,105 +0,0 @@
-defmodule Chessh.SSH.Client.Menu do
- alias Chessh.SSH.Client
- alias Chessh.Utils
- alias IO.ANSI
-
- require Logger
-
- defmodule State do
- defstruct y: 0,
- x: 0,
- selected: 0
- end
-
- use Chessh.SSH.Client.Screen
-
- @logo " Simponic's
- dP MP\"\"\"\"\"\"`MM MP\"\"\"\"\"\"`MM M\"\"MMMMM\"\"MM
- 88 M mmmmm..M M mmmmm..M M MMMMM MM
-.d8888b. 88d888b. .d8888b. M. `YM M. `YM M `M
-88' `\"\" 88' `88 88ooood8 MMMMMMM. M MMMMMMM. M M MMMMM MM
-88. ... 88 88 88. ... M. .MMM' M M. .MMM' M M MMMMM MM
-`88888P' dP dP `88888P' Mb. .dM Mb. .dM M MMMMM MM
- MMMMMMMMMMM MMMMMMMMMMM MMMMMMMMMMMM"
-
- @options [
- {"Option 1", {Chessh.SSH.Client.Board, %{}}},
- {"Option 2", {Chessh.SSH.Client.Board, %{}}},
- {"Option 3", {Chessh.SSH.Client.Board, %{}}}
- ]
-
- def render(%Client.State{
- width: width,
- height: height,
- state_stack: [{_this_module, %State{selected: selected, y: dy, x: dx}} | _tail]
- }) do
- text = String.split(@logo, "\n")
- {logo_width, logo_height} = Utils.text_dim(@logo)
- {y, x} = center_rect({logo_width, logo_height + length(text)}, {width, height})
-
- Enum.flat_map(
- Enum.zip(0..(length(text) - 1), text),
- fn {i, line} ->
- [
- ANSI.cursor(y + i + dy, x + dx),
- line
- ]
- end
- ) ++
- Enum.flat_map(
- Enum.zip(0..(length(@options) - 1), @options),
- fn {i, {option, _}} ->
- [
- ANSI.cursor(y + length(text) + i + dy, x + dx),
- if(i == selected, do: ANSI.format([:light_cyan, "* #{option}"]), else: option)
- ]
- end
- ) ++ [ANSI.home()]
- end
-
- def wrap_around(index, delta, length) do
- calc = index + delta
- if(calc < 0, do: length, else: 0) + rem(calc, length)
- end
-
- def handle_input(
- data,
- %Client.State{
- state_stack:
- [{this_module, %State{selected: selected} = screen_state} | tail] = state_stack
- } = state
- ) do
- case(data) do
- :up ->
- %Client.State{
- state
- | state_stack: [
- {this_module,
- %State{screen_state | selected: wrap_around(selected, -1, length(@options))}}
- | tail
- ]
- }
-
- :down ->
- %Client.State{
- state
- | state_stack: [
- {this_module,
- %State{screen_state | selected: wrap_around(selected, 1, length(@options))}}
- | tail
- ]
- }
-
- :return ->
- {_, new_state} = Enum.at(@options, selected)
-
- %Client.State{
- state
- | state_stack: [new_state] ++ state_stack
- }
-
- _ ->
- state
- end
- end
-end
diff --git a/lib/chessh/ssh/screens/screen.ex b/lib/chessh/ssh/screens/screen.ex
deleted file mode 100644
index 3d9e9ec..0000000
--- a/lib/chessh/ssh/screens/screen.ex
+++ /dev/null
@@ -1,22 +0,0 @@
-defmodule Chessh.SSH.Client.Screen do
- @callback render(state :: Chessh.SSH.Client.State.t() | any()) :: any()
- @callback handle_input(action :: any(), state :: Chessh.SSH.Client.State.t()) ::
- Chessh.SSH.Client.State.t()
-
- defmacro __using__(_) do
- quote do
- @behaviour Chessh.SSH.Client.Screen
-
- @ascii_chars Application.compile_env!(:chessh, :ascii_chars_json_file)
- |> File.read!()
- |> Jason.decode!()
-
- def center_rect({rect_width, rect_height}, {parent_width, parent_height}) do
- {
- div(parent_height - rect_height, 2),
- div(parent_width - rect_width, 2)
- }
- end
- end
- end
-end
diff --git a/lib/chessh/ssh/tui.ex b/lib/chessh/ssh/tui.ex
index d76986f..1838fb8 100644
--- a/lib/chessh/ssh/tui.ex
+++ b/lib/chessh/ssh/tui.ex
@@ -26,7 +26,7 @@ defmodule Chessh.SSH.Tui do
{:ok, init_state}
end
- def handle_msg({:ssh_channel_up, channel_id, connection_ref}, state) do
+ def handle_msg({:ssh_channel_up, channel_id, connection_ref}, %State{} = state) do
Logger.debug("SSH channel up #{inspect(:ssh.connection_info(connection_ref))}")
connected_player =
@@ -54,7 +54,7 @@ defmodule Chessh.SSH.Tui do
:syn.join(:player_sessions, {:session, session.id}, self())
{:ok,
- %{
+ %State{
state
| channel_id: channel_id,
connection_ref: connection_ref,
@@ -66,7 +66,7 @@ defmodule Chessh.SSH.Tui do
def handle_msg(
{:EXIT, client_pid, _reason},
- %{client_pid: client_pid, channel_id: channel_id} = state
+ %State{client_pid: client_pid, channel_id: channel_id} = state
) do
send(client_pid, :quit)
{:stop, channel_id, state}
@@ -74,16 +74,15 @@ defmodule Chessh.SSH.Tui do
def handle_msg(
{:send_data, data},
- %{connection_ref: connection_ref, channel_id: channel_id} = state
+ %State{connection_ref: connection_ref, channel_id: channel_id} = state
) do
- Logger.debug("Data was sent to TUI process #{inspect(data)}")
:ssh_connection.send(connection_ref, channel_id, data)
{:ok, state}
end
def handle_msg(
:session_closed,
- %{connection_ref: connection_ref, channel_id: channel_id} = state
+ %State{connection_ref: connection_ref, channel_id: channel_id} = state
) do
:ssh_connection.send(connection_ref, channel_id, @session_closed_message)
{:stop, channel_id, state}
@@ -95,9 +94,8 @@ defmodule Chessh.SSH.Tui do
def handle_ssh_msg(
{:ssh_cm, _connection_handler, {:data, _channel_id, _type, data}},
- state
+ %State{} = state
) do
- Logger.debug("DATA #{inspect(data)}")
send(state.client_pid, {:data, data})
{:ok, state}
end
@@ -105,7 +103,7 @@ defmodule Chessh.SSH.Tui do
def handle_ssh_msg(
{:ssh_cm, connection_handler,
{:pty, channel_id, want_reply?, {_term, width, height, _pixwidth, _pixheight, _opts}}},
- state
+ %State{} = state
) do
Logger.debug("#{inspect(state.player_session)} has requested a PTY")
:ssh_connection.reply_request(connection_handler, want_reply?, :success, channel_id)
@@ -130,13 +128,12 @@ defmodule Chessh.SSH.Tui do
def handle_ssh_msg(
{:ssh_cm, _connection_handler,
{:window_change, _channel_id, width, height, _pixwidth, _pixheight}},
- %{client_pid: client_pid} = state
+ %State{client_pid: client_pid} = state
) do
- Logger.debug("WINDOW CHANGE")
send(client_pid, {:resize, {width, height}})
{:ok,
- %{
+ %State{
state
| width: width,
height: height
@@ -160,12 +157,13 @@ defmodule Chessh.SSH.Tui do
}
])
- {:ok, %{state | client_pid: client_pid}}
+ send(client_pid, :refresh)
+ {:ok, %State{state | client_pid: client_pid}}
end
def handle_ssh_msg(
{:ssh_cm, connection_handler, {:exec, channel_id, want_reply?, cmd}},
- state
+ %State{} = state
) do
:ssh_connection.reply_request(connection_handler, want_reply?, :success, channel_id)
Logger.debug("EXEC #{cmd}")
@@ -174,7 +172,7 @@ defmodule Chessh.SSH.Tui do
def handle_ssh_msg(
{:ssh_cm, _connection_handler, {:eof, _channel_id}},
- state
+ %State{} = state
) do
Logger.debug("EOF")
{:ok, state}
@@ -182,7 +180,7 @@ defmodule Chessh.SSH.Tui do
def handle_ssh_msg(
{:ssh_cm, _connection_handler, {:signal, _channel_id, signal}},
- state
+ %State{} = state
) do
Logger.debug("SIGNAL #{signal}")
{:ok, state}
@@ -190,7 +188,7 @@ defmodule Chessh.SSH.Tui do
def handle_ssh_msg(
{:ssh_cm, _connection_handler, {:exit_signal, channel_id, signal, err, lang}},
- state
+ %State{} = state
) do
Logger.debug("EXIT SIGNAL #{signal} #{err} #{lang}")
{:stop, channel_id, state}
@@ -198,7 +196,7 @@ defmodule Chessh.SSH.Tui do
def handle_ssh_msg(
{:ssh_cm, _connection_handler, {:exit_STATUS, channel_id, status}},
- state
+ %State{} = state
) do
Logger.debug("EXIT STATUS #{status}")
{:stop, channel_id, state}
@@ -206,7 +204,7 @@ defmodule Chessh.SSH.Tui do
def handle_ssh_msg(
msg,
- %{channel_id: channel_id} = state
+ %State{channel_id: channel_id} = state
) do
Logger.debug("UNKOWN MESSAGE #{inspect(msg)}")
{:stop, channel_id, state}
diff --git a/lib/chessh/utils.ex b/lib/chessh/utils.ex
index 3e83d5e..20a8b96 100644
--- a/lib/chessh/utils.ex
+++ b/lib/chessh/utils.ex
@@ -1,4 +1,23 @@
defmodule Chessh.Utils do
+ @ascii_chars Application.compile_env!(:chessh, :ascii_chars_json_file)
+ |> File.read!()
+ |> Jason.decode!()
+
+ @clear_codes [
+ IO.ANSI.clear(),
+ IO.ANSI.home()
+ ]
+
+ def ascii_chars(), do: @ascii_chars
+ def clear_codes(), do: @clear_codes
+
+ def center_rect({rect_width, rect_height}, {parent_width, parent_height}) do
+ {
+ div(parent_height - rect_height, 2),
+ div(parent_width - rect_width, 2)
+ }
+ end
+
def pid_to_str(pid) do
pid
|> :erlang.pid_to_list()
@@ -11,4 +30,9 @@ defmodule Chessh.Utils do
split = String.split(text, "\n")
{Enum.reduce(split, 0, fn x, acc -> max(acc, String.length(x)) end), length(split)}
end
+
+ def wrap_around(index, delta, length) do
+ calc = index + delta
+ if(calc < 0, do: length, else: 0) + rem(calc, length)
+ end
end