#if OS == .WINDOWS { #load "windows.jai"; } else #if (OS == .LINUX) || (OS == .MACOS) { #load "unix.jai"; } else { #assert(false, "Unsupported OS."); } #import "Basic"; #import "String"; #import "Thread"; Drawings :: struct { CornerBR :: "\x6A"; CornerTR :: "\x6B"; CornerTL :: "\x6C"; CornerBL :: "\x6D"; Cross :: "\x6E"; LineH :: "\x71"; TeeL :: "\x74"; TeeR :: "\x75"; TeeB :: "\x76"; TeeT :: "\x77"; LineV :: "\x78"; Blank :: "\x5F"; Diamond :: "\x60"; Checkerboard :: "\x61"; PlusMinus :: "\x67"; LessThanOrEqual :: "\x79"; GreaterThanOrEqual :: "\x7A"; Pi :: "\x7B"; NotEqual :: "\x7C"; CenteredDot :: "\x7E"; } Commands :: struct { EnterAlternateBuffer :: "\e[?1049h"; EnterMainBuffer :: "\e[?1049l"; EnterDrawingMode :: "\e(0"; EnterNormalMode :: "\e(B"; ClearScreen :: "\e[2J"; ClearLine :: "\e[2K"; RefreshWindow :: "\e[7t"; // TODO Not yet tested. SetUTF8 :: "\e%G"; // TODO TEST ME PLEASE // Cursor Position SetCursorPosition :: "\e[%;%H"; // Cursor Visibility ShowCursor :: "\e[?25h"; HideCursor :: "\e[?25l"; StartBlinking :: "\e[?25h]"; StopBlinking :: "\e[?25l]"; SaveCursorPosition :: "\e7"; RestoreCursorPosition :: "\e8"; // Cursor Shape DefaultShape :: "\e[0 q"; BlinkingBlockShape :: "\e[1 q"; SteadyBlockShape :: "\e[2 q"; BlinkingUnderlineShape :: "\e[3 q"; SteadyUnderlineShape :: "\e[4 q"; BlinkingBarShape :: "\e[5 q"; SteadyBarShape :: "\e[6 q"; // Input Mode KeypadAppMode :: "\e="; KeypadNumMode :: "\e>"; CursorAppMode :: "\e[?1h"; CursorNormalMode :: "\e[?1l"; // Query State QueryCursorPosition :: "\e[6n"; // Emits the cursor position as: "ESC [ ; R" Where = row and = column. QueryDeviceAttributes :: "\e[0c"; QueryWindowSizeInChars :: "\e[18t"; // Emits the window size as: "ESC [ 8 ; t" Where = row and = column. TODO Does not work on windows. } // TODO Maybe make the OS_* procedures as inline?! initialized := false; input_buffer : [64] u8; input_string : string; Key :: u8; // TODO To be improved. Keys :: enum u8 { None :: 0; Resize :: 1; //410; // TODO Why?! } dam :: (msg: string) { print(msg, to_standard_error = true); } push_key :: (key: Key) { // TODO } get_key :: (timeout_milliseconds: s32 = -1) -> Key { if OS_was_terminal_resized() return xx Keys.Resize; if input_string.count > 0 { defer advance(*input_string, 1); return input_string[0]; } is_input_available := OS_wait_for_input(timeout_milliseconds); if OS_was_terminal_resized() return xx Keys.Resize; if is_input_available { bytes_read := OS_read_input(input_buffer.data, input_buffer.count); // TODO Does not check for read errors. if bytes_read > 0 { input_string.data = input_buffer.data; input_string.count = bytes_read; defer advance(*input_string, 1); return input_string[0]; } } return xx Keys.None; } get_str :: (str_limit: int = -1, allocator: Allocator = temp) -> string { assert(allocator.proc != null, "Argument 'allocator.proc' has invalid null value."); if str_limit < 0 { builder: String_Builder(); builder.allocator = allocator; init_string_builder(*builder); while(1) { buffer := get_current_buffer(*builder); buffer_data := get_buffer_data(buffer); buffer.count = OS_read_input(buffer_data, buffer.allocated); // TODO Does not check for read errors. if buffer.count < buffer.allocated break; expand(*builder); } return builder_to_string(*builder, allocator); } else { buffer := alloc_string(str_limit, allocator); buffer.count = OS_read_input(buffer.data, str_limit); return buffer; } } start :: () { if initialized == true return; write_strings(Commands.HideCursor, Commands.SaveCursorPosition, Commands.EnterAlternateBuffer, Commands.SetUTF8); OS_prepare_terminal(); was_resized = false; init(*resize_mutex, "resize_mutex"); input_string.data = input_buffer.data; input_string.count = 0; initialized = true; set_handler(); // TODO Move to beter place. } stop :: () { if initialized == false return; initialized = false; restore_handler(); // TODO Move to beter place. OS_reset_terminal(); write_strings(Commands.EnterMainBuffer, Commands.RestoreCursorPosition, Commands.ShowCursor); } flush_input :: () { // TODO } draw_box :: (x: int, y: int, width: int, height: int) { // TODO Check if using a String_Builder improves performance (measure it)! // TODO Validate input parameters against the terminal size. assert(x > 0 && y > 0 && width > 1 && height > 1, "Invalid arguments."); auto_release_temp(); tmp_string: string; tmp_string = tprint(Commands.SetCursorPosition, y, x); write_strings( Commands.EnterDrawingMode, tmp_string, Drawings.CornerTL ); for 1..width-2 { write_string(Drawings.LineH); } write_string(Drawings.CornerTR); for idx: y+1..y+height-2 { tmpL := tprint(Commands.SetCursorPosition, idx, x); tmpR := tprint(Commands.SetCursorPosition, idx, x+width-1); write_strings( tmpL, Drawings.LineV, tmpR, Drawings.LineV); } tmpBL := tprint(Commands.SetCursorPosition, y+height-1, x); write_strings( tmpBL, Drawings.CornerBL); for 1..width-2 { write_string(Drawings.LineH); } write_string(Drawings.CornerBR); write_string(Commands.EnterNormalMode); } // TODO Maybe rename to "clear()" clear_terminal :: inline () { assert(initialized, "TUI is not ready."); write_string(Commands.ClearScreen); } // TODO Maybe rename to "get_size()" get_terminal_size :: () -> rows: int, columns: int { assert(initialized, "TUI is not ready."); rows, columns: int = ---; #if OS == .WINDOWS { rows, columns = OS_get_terminal_size(); } else { auto_release_temp(); flush_input(); write_string(Commands.QueryWindowSizeInChars); input := get_str(64); // Expected message format: [8;;t // where is the number of rows and of columns. assert( input[0] == #char "\e" && input[1] == #char "[" && input[2] == #char "8", //input[input.count-1] == #char "t", "Query window size in chars returned invalid response."); parts := split(input, ";"); rows = parse_int(*parts[1]); columns = parse_int(*parts[2]); } return rows, columns; } set_cursor_position :: (row: int, column: int) { auto_release_temp(); tmp_string := tprint(Commands.SetCursorPosition, row, column); write_string(tmp_string); } get_cursor_position :: () -> row: int, column: int { assert(initialized, "TUI is not ready."); // TODO Should I use this inside each and every procedure? auto_release_temp(); flush_input(); write_string(Commands.QueryCursorPosition); input := get_str(64); // Expected message format: \e[;R // where is the number of rows and of columns. assert( input[0] == #char "\e" && input[1] == #char "[" && input[input.count-1] == #char "R", "Query cursor position returned invalid response."); advance(*input, 2); parts := split(input, ";"); row := parse_int(*parts[0]); column := parse_int(*parts[1]); return row, column; } #if OS == .WINDOWS { // Prototyping zone... keep clear! } else #if OS == .LINUX || OS == .MACOS { // Prototyping zone... keep clear! OS_wait_for_input :: (timeout_milliseconds: s32) -> is_input_available: bool { fds := pollfd.[ .{ fd = STDIN_FILENO, events = POLLIN, revents = 0 } ]; nfds := fds.count; poll_return := poll(fds.data, xx nfds, xx timeout_milliseconds); // TODO Wait for input using poll syscall. This breaks and throws '-1 | 4 | Interrupted system call' when we resize the window while polling. error_code, error_message := get_error_value_and_string(); return ifx poll_return > 0 then true else false; } resize_mutex : Mutex; was_resized : bool; OS_was_terminal_resized :: () -> bool { lock(*resize_mutex); defer unlock(*resize_mutex); defer was_resized = false; return was_resized; } process_resize :: (signal_code : s32) #c_call { new_context : Context; push_context new_context { print("SIGNAL:%", signal_code); if signal_code != SIGWINCH then return; if was_resized == true then return; print("RESIZE\n"); lock(*resize_mutex); defer unlock(*resize_mutex); was_resized = true; } } // TODO Rename this procedure. set_handler :: () { sa : sigaction_t; sa.sa_handler = process_resize; sigemptyset(*(sa.sa_mask)); sa.sa_flags = SA_RESTART; sigaction(SIGWINCH, *sa, null); } // TODO Rename this procedure. restore_handler :: () { sa : sigaction_t; sa.sa_handler = SIG_DFL; sigaction(SIGWINCH, null, *sa); } }