diff --git a/.gitmodules b/.gitmodules index d633757..87938ad 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ -[submodule "addons/godot_xterm_native/godot-cpp"] - path = addons/godot_xterm_native/godot-cpp +[submodule "addons/godot_xterm/godot-cpp"] + path = addons/godot_xterm/godot-cpp url = https://github.com/lihop/godot-cpp -[submodule "addons/godot_xterm_native/libtsm"] - path = addons/godot_xterm_native/libtsm +[submodule "addons/godot_xterm/libtsm"] + path = addons/godot_xterm/libtsm url = https://github.com/Aetf/libtsm diff --git a/.travis.yml b/.travis.yml index 5527a51..722f934 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,13 +5,11 @@ services: jobs: include: - - name: "Run tests" - env: SERVICE=tests - - name: "Build native on Arch Linux" + - name: "Build on Arch Linux" env: SERVICE=build-archlinux - - name: "Build native on NixOS" + - name: "Build on NixOS" env: SERVICE=build-nixos - - name: "Build native on Ubuntu" + - name: "Build on Ubuntu" env: SERVICE=build-ubuntu script: docker-compose run $SERVICE diff --git a/README.md b/README.md index 87e17d5..77fd191 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ Native implementation of Godot Xterm using GDNative with [libtsm](https://github.com/Aetf/libtsm). +Terminal emulator for Godot using GDNative and [libtsm](https://github.com/Aetf/libtsm). + +**Note**: If you are looking for the purely gdscript version of this plugin it was too buggy and slow so is no longer being developed or maintained but can found [here](https://github.com/lihop/godot-xterm/tree/gdscript-unmaintained). + ## Demo Click the thumbnail to watch a demo video on youtube: @@ -22,4 +26,4 @@ You are also implicitly verifying that all code is your original work, or unorig Copyright (c) 2020 Leroy Hopson (MIT License) The fonts used in this project are published under a seperate license. -See: [addons/godot_xterm_native/fonts/LICENSE.txt](addons/godot_xterm_native/fonts/LICENSE.txt). +See: [addons/godot_xterm/fonts/LICENSE.txt](addons/godot_xterm/fonts/LICENSE.txt). diff --git a/addons/godot_xterm_native/.gitignore b/addons/godot_xterm/.gitignore similarity index 100% rename from addons/godot_xterm_native/.gitignore rename to addons/godot_xterm/.gitignore diff --git a/addons/godot_xterm/Constants.gd b/addons/godot_xterm/Constants.gd deleted file mode 100644 index 210c4b8..0000000 --- a/addons/godot_xterm/Constants.gd +++ /dev/null @@ -1,23 +0,0 @@ -extends Reference - -# font flags -enum { - FONT_NORMAL = 0, - FONT_BOLD = 1 << 0 - FONT_ITALIC = 1 << 1, - FONT_UNDERLINED = 1 << 2 - FONT_BLINK = 1 << 3 - FONT_INVERSE = 1 << 4 - FONT_IVSIBILE = 1 << 5 - FONT_STRIKETHROUGH = 1 << 6 -} - -# colors -const COLOR_BLACK = Color(0.0, 0.0, 0.0) # 0 -const COLOR_RED = Color(1.0, 0.0, 0.0) # 1 -const COLOR_GREEN = Color(0.0, 1.0, 0.0) # 2 -const COLOR_YELLOW = Color(1.0, 1.0, 0.0) # 3 -const COLOR_BLUE = Color(0.0, 0.0, 1.0) # 4 -const COLOR_MAGENTA = Color(1.0, 0.0, 1.0) # 5 -const COLOR_CYAN = Color(0.0, 1.0, 1.0) # 6 -const COLOR_WHITE = Color(1.0, 1.0, 1.0) # 7 diff --git a/addons/godot_xterm_native/Dockerfile b/addons/godot_xterm/Dockerfile similarity index 100% rename from addons/godot_xterm_native/Dockerfile rename to addons/godot_xterm/Dockerfile diff --git a/addons/godot_xterm_native/LICENSE b/addons/godot_xterm/LICENSE similarity index 100% rename from addons/godot_xterm_native/LICENSE rename to addons/godot_xterm/LICENSE diff --git a/addons/godot_xterm_native/SConstruct b/addons/godot_xterm/SConstruct similarity index 100% rename from addons/godot_xterm_native/SConstruct rename to addons/godot_xterm/SConstruct diff --git a/addons/godot_xterm_native/bin/.gitignore b/addons/godot_xterm/bin/.gitignore similarity index 100% rename from addons/godot_xterm_native/bin/.gitignore rename to addons/godot_xterm/bin/.gitignore diff --git a/addons/godot_xterm/buffer/attribute_data.gd b/addons/godot_xterm/buffer/attribute_data.gd deleted file mode 100644 index 5198725..0000000 --- a/addons/godot_xterm/buffer/attribute_data.gd +++ /dev/null @@ -1,168 +0,0 @@ -# Copyright (c) 2018 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -const Constants = preload("res://addons/godot_xterm/buffer/constants.gd") -const Attributes = Constants.Attributes -const FgFlags = Constants.FgFlags -const BgFlags = Constants.BgFlags -const UnderlineStyle = Constants.UnderlineStyle - -var fg = 0 -var bg = 0 -var extended = ExtendedAttrs.new() - - -static func to_color_rgb(value: int) -> Color: - # Create color from RGB format. - return Color("%02x%02x%02x" % [value >> Attributes.RED_SHIFT & 255, - value >> Attributes.GREEN_SHIFT & 255, value & 255]) - - -# flags -func is_inverse() -> int: - return fg & FgFlags.INVERSE -func is_bold() -> int: - return fg & FgFlags.BOLD -func is_underline() -> int: - return fg & FgFlags.UNDERLINE -func is_blink() -> int: - return fg & FgFlags.BLINK -func is_invisible() -> int: - return fg & FgFlags.INVISIBLE -func is_italic() -> int: - return bg & BgFlags.ITALIC -func is_dim() -> int: - return fg & BgFlags.DIM - - -# color modes -func get_fg_color_mode() -> int: - return fg & Attributes.CM_MASK -func get_bg_color_mode() -> int: - return bg & Attributes.CM_MASK -func is_fg_rgb() -> bool: - return (fg & Attributes.CM_MASK) == Attributes.CM_RGB -func is_bg_rgb() -> bool: - return (bg & Attributes.CM_MASK) == Attributes.CM_RGB -func is_fg_palette() -> bool: - return (fg & Attributes.CM_MASK) == Attributes.CM_P16 or (fg & Attributes.CM_MASK) == Attributes.CM_P256 -func is_bg_palette() -> bool: - return (bg & Attributes.CM_MASK) == Attributes.CM_P16 or (bg & Attributes.CM_MASK) == Attributes.CM_P256 -func is_fg_default() -> bool: - return (fg & Attributes.CM_MASK) == 0 -func is_bg_default() -> bool: - return (bg & Attributes.CM_MASK) == 0 -func is_attribute_default() -> bool: - return fg == 0 && bg == 0 - - -func get_fg_color() -> int: - match fg & Attributes.CM_MASK: - Attributes.CM_P16, Attributes.CM_P256: - return fg & Attributes.PCOLOR_MASK - Attributes.CM_RGB: - return fg & Attributes.RGB_MASK - _: - return -1 # CM_DEFAULT defaults to -1 - - -func get_bg_color() -> int: - match bg & Attributes.CM_MASK: - Attributes.CM_P16, Attributes.CM_P256: - return bg & Attributes.PCOLOR_MASK - Attributes.CM_RGB: - return bg & Attributes.RGB_MASK - _: - return -1 # CM_DEFAULT defaults to -1 - - -func has_extended_attrs() -> int: - return bg & BgFlags.HAS_EXTENDED - - -func update_extended() -> void: - if extended.is_empty(): - bg &= ~BgFlags.HAS_EXTENDED - else: - bg |= BgFlags.HAS_EXTENDED - - -func get_underline_color() -> int: - if bg & BgFlags.HAS_EXTENDED and ~extended.underline_color: - match extended.underline_color & Attributes.CM_MASK: - Attributes.CM_P16, Attributes.CM_P256: - return extended.underline_color & Attributes.PCOLOR_MASK - Attributes.CM_RGB: - return extended.underline_color & Attributes.RGB_MASK - _: - return get_fg_color() - else: - return get_fg_color() - - -func get_underline_color_mode() -> int: - if bg & BgFlags.HAS_EXTENDED and ~extended.underline_color: - return extended.underline_color & Attributes.CM_MASK - else: - return get_fg_color_mode() - - -func is_underline_color_rgb() -> bool: - if bg & BgFlags.HAS_EXTENDED and ~extended.underline_color: - return extended.underline_color & Attributes.CM_MASK == Attributes.CM_RGB - else: - return is_fg_rgb() - - -func is_underline_color_palette() -> bool: - if bg & BgFlags.HAS_EXTENDED and ~extended.underline_color: - return extended.underline_color & Attributes.CM_MASK == Attributes.CM_P16 \ - or extended.underline_color & Attributes.CM_MASK == Attributes.CM_P256 - else: - return is_fg_palette() - - -func is_underline_color_default() -> bool: - if bg & BgFlags.HAS_EXTENDED and ~extended.underline_color: - return extended.underline_color & Attributes.CM_MASK == 0 - else: - return is_fg_default() - - -func get_underline_style(): - if fg & FgFlags.UNDERLINE: - return extended.underline_style if bg & BgFlags.HAS_EXTENDED else UnderlineStyle.SINGLE - else: - return UnderlineStyle.NONE - - -class ExtendedAttrs: - extends Reference - # Extended attributes for a cell. - # Holds information about different underline styles and color. - - - var underline_style = UnderlineStyle.NONE - var underline_color: int = -1 - - - func _init(): - underline_style - - - func duplicate(): - # Workaround as per: https://github.com/godotengine/godot/issues/19345#issuecomment-471218401 - var AttributeData = load("res://addons/godot_xterm/buffer/attribute_data.gd") - var clone = AttributeData.ExtendedAttrs.new() - clone.underline_style = underline_style - clone.underline_color = underline_color - return clone - - - # Convenient method to indicate whether the object holds no additional information, - # that needs to be persistant in the buffer. - func is_empty(): - return underline_style == UnderlineStyle.NONE diff --git a/addons/godot_xterm/buffer/buffer.gd b/addons/godot_xterm/buffer/buffer.gd deleted file mode 100644 index 3c7ce4f..0000000 --- a/addons/godot_xterm/buffer/buffer.gd +++ /dev/null @@ -1,430 +0,0 @@ -# Copyright (c) 2017 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -const BufferLine = preload("res://addons/godot_xterm/buffer/buffer_line.gd") -const CellData = preload("res://addons/godot_xterm/buffer/cell_data.gd") -const Charsets = preload("res://addons/godot_xterm/data/charsets.gd") -const Constants = preload("res://addons/godot_xterm/buffer/constants.gd") -const CircularList = preload("res://addons/godot_xterm/circular_list.gd") -const AttributeData = preload("res://addons/godot_xterm/buffer/attribute_data.gd") -const BufferReflow = preload("res://addons/godot_xterm/buffer/buffer_reflow.gd") - -const MAX_BUFFER_SIZE = 4294967295 # 2^32 - 1 - -var lines -var ydisp: int = 0 -var ybase: int = 0 -var y: int = 0 -var x: int = 0 -var scroll_bottom: int -var scroll_top: int -var tabs = {} -var saved_y: int = 0 -var saved_x: int = 0 -var saved_cur_attr_data = AttributeData.new() -var saved_charset = Charsets.DEFAULT_CHARSET -var markers: Array = [] - -var _null_cell = CellData.from_char_data([0, Constants.NULL_CELL_CHAR, - Constants.NULL_CELL_WIDTH, Constants.NULL_CELL_CODE]) -var _whitespace_cell = CellData.from_char_data([0, Constants.WHITESPACE_CELL_CHAR, - Constants.WHITESPACE_CELL_WIDTH, Constants.WHITESPACE_CELL_CODE]) -var _cols: int -var _rows: int -var _has_scrollback -var _options_service -var _buffer_service - - -func _init(has_scrollback: bool, options_service, buffer_service): - _has_scrollback = has_scrollback - _options_service = options_service - _buffer_service = buffer_service - _cols = buffer_service.cols - _rows = buffer_service.rows - lines = CircularList.new(_get_correct_buffer_length(_rows)) - scroll_top = 0 - scroll_bottom = _rows - 1 - setup_tab_stops() - - -# Resizes the buffer, adjusting its data accordingly. -# @param new_cols The new number of columns. -# @param new_rows The new number of rows. -func resize(new_cols: int, new_rows: int) -> void: - # store reference to null cell with default attrs - var null_cell = get_null_cell(AttributeData.new()) - - # Increase max length if needed before adjustments to allow space to fill - # as required. - var new_max_length = _get_correct_buffer_length(new_rows) - if new_max_length > lines.max_length: - lines.max_length = new_max_length - - # The following adjustments should only happen if the buffer has been - # initialized/filled. - if lines.length > 0: - # Deal with columns increasing (reducing needs to happen after reflow) - if _cols < new_cols: - for i in range(lines.length): - lines.get_line(i).resize(new_cols, null_cell) - - # Resize rows in both directions as needed - var add_to_y = 0 - if _rows < new_rows: - for y in range(_rows, new_rows): - if lines.length < new_rows + ybase: - if _options_service.options.windows_mode: - # Just add the new missing rows on Windows as conpty reprints the screen with it's - # view of the world. Once a line enters scrollback for conpty it remains there - lines.push(BufferLine.new(new_cols, null_cell)) - else: - if ybase > 0 and lines.length <= ybase + y + add_to_y + 1: - # There is room above the buffer and there are no empty elements below the line, - # scroll up - ybase -= 1 - add_to_y += 1 - if ydisp > 0: - # Viewport is at the top of the buffer, must increase downwards - ydisp -= 1 - else: - # Add a blank line if tere is no buffer left at the top to srcoll to, or if there - # are blank lines after the cursor - lines.push(BufferLine.new(new_cols, null_cell)) - else: # _rows >= new_rows - for _y in range(_rows, new_rows, -1): - if lines.length > new_rows + ybase: - if lines.length > ybase + y + 1: - # The line is blank line below the cursor, remove it - lines.pop() - else: - # The line is the cursor, scroll down - ybase += 1 - ydisp += 1 - - # Reduce max length if needed after adjustments, this is done after as it - # would otherwise cut data from the bottom of the buffer. - if new_max_length < lines.max_length: - # Trim from the top of th ebuffer and adjust ybase and ydisp. - var amount_to_trim = lines.length - new_max_length - if amount_to_trim > 0: - lines.trim_start(amount_to_trim) - ybase = max(ybase - amount_to_trim, 0) - ydisp = max(ydisp - amount_to_trim, 0) - saved_y = max(saved_y - amount_to_trim, 0) - lines.max_length = new_max_length - - # Make sure that the cursor stays on screen - x = min(x, new_cols - 1) - y = min(y, new_rows - 1) - if add_to_y: - y += add_to_y - saved_x = min(saved_x, new_cols -1) - - scroll_top = 0 - - scroll_bottom = new_rows - 1 - - if _is_reflow_enabled(): - _reflow(new_cols, new_rows) - - # Trim the end of the line off if cols shrunk - if _cols > new_cols: - for i in range(lines.length): - lines.get_line(i).resize(new_cols, null_cell) - - _cols = new_cols - _rows = new_rows - - -func _is_reflow_enabled() -> bool: - return _has_scrollback and not _options_service.options.windows_mode - - -func _reflow(new_cols: int, new_rows: int) -> void: - if _cols == new_cols: - return - - # Iterate through rows, ignore the last one as it cannot be wrapped - if new_cols > _cols: - _reflow_larger(new_cols, new_rows) - else: - _reflow_smaller(new_cols, new_rows) - - -func _reflow_larger(new_cols: int, new_rows: int) -> void: - var to_remove: PoolIntArray = BufferReflow.reflow_larger_get_lines_to_remove(lines, - _cols, new_cols, ybase + y, get_null_cell(AttributeData.new())) - if not to_remove.empty(): - var new_layout_result = BufferReflow.reflow_larger_create_new_layout(lines, to_remove) - BufferReflow.reflow_larger_apply_new_layout(lines, new_layout_result.layout) - _reflow_larger_adjust_viewport(new_cols, new_rows, new_layout_result.count_removed) - - -func _reflow_larger_adjust_viewport(new_cols: int, new_rows: int, count_removed: int) -> void: - var null_cell = get_null_cell(AttributeData.new()) - # Adjust viewport based on number of items removed - var viewport_adjustments = count_removed - while viewport_adjustments > 0: - viewport_adjustments -= 1 - if ybase == 0: - if y > 0: - y -= 1 - if lines.length < new_rows: - # Add an extra row at the bottom of the viewport - lines.push(BufferLine.new(new_cols, null_cell)) - else: - if ydisp == ybase: - ydisp -= 1 - ybase -= 1 - - saved_y = max(saved_y - count_removed, 0) - - -func _reflow_smaller(new_cols: int, new_rows: int) -> void: - var null_cell = get_null_cell(AttributeData.new()) - # Gather all BufferLines that need to be inserted into the Buffer here so that they can be - # batched up and only commited once - var to_insert = [] - var count_to_insert = 0 - # Go backwards as many lines may be trimmed and this will avoid considering them - var i = lines.length - 1 - while i >= 0: - # Check wether this line is a problem - var next_line = lines.get_line(i) - if not next_line or not next_line.is_wrapped and next_line.get_trimmed_length() <= new_cols: - i -= 1 - continue - - # Gather wrapped lines and adjust y to be the starting line - var wrapped_lines = [next_line] - while next_line.is_wrapped and i > 0: - i -= 1 - next_line = lines.get_line(i) - wrapped_lines.push_front(next_line) - - # If these lines contain the cursor don't touch them, the program will handle fixing up - # wrapped lines with the cursor - var absolute_y = ybase + y - if absolute_y >= i and absolute_y < i + wrapped_lines.size(): - i -= 1 - continue - - var last_line_length = wrapped_lines[wrapped_lines.size() - 1].get_trimmed_length() - var dest_line_lengths = BufferReflow.reflow_smaller_get_new_line_lengths(wrapped_lines, _cols, new_cols) - var lines_to_add = dest_line_lengths.size() - wrapped_lines.size() - var trimmed_lines: int - if ybase == 0 and y != lines.length - 1: - # If the top section of the buffer is not yet filled - trimmed_lines = max(0, y - lines.max_length + lines_to_add) - else: - trimmed_lines = max(0, lines.length - lines.max_length + lines_to_add) - - # Add the new lines - var new_lines = [] - for j in range(lines_to_add): - var new_line = get_blank_line(AttributeData.new(), true) - new_lines.append(new_line) - if not new_lines.empty(): - to_insert.append({"start": i + wrapped_lines.size() + count_to_insert, - "new_lines": new_lines}) - count_to_insert += new_lines.size() - wrapped_lines += new_lines - - # Copy buffer data to new locations, this needs to happen backwards to do in-place - var dest_line_index = dest_line_lengths.size() - 1 # floor(cells_needed / new_cols) - var dest_col = dest_line_lengths[dest_line_index] # cells_needed % new_cols - if dest_col == 0: - dest_line_index -= 1 - dest_col = dest_line_lengths[dest_line_index] - var src_line_index = wrapped_lines.size() - lines_to_add - 1 - var src_col = last_line_length - while src_line_index >= 0: - var cells_to_copy = min(src_col, dest_col) - wrapped_lines[dest_line_index].copy_cells_from(wrapped_lines[src_line_index], - src_col - cells_to_copy, dest_col - cells_to_copy, cells_to_copy, true) - dest_col -= cells_to_copy - if dest_col == 0: - dest_line_index -= 1 - dest_col = dest_line_lengths[dest_line_index] - src_col -= cells_to_copy - if src_col == 0: - src_line_index -= 1 - var wrapped_lines_index = max(src_line_index, 0) - src_col = BufferReflow.get_wrapped_line_trimmed_length(wrapped_lines, wrapped_lines_index, _cols) - - # Null out the end of the line ends if a wide character wrapped to the following line - for j in range(wrapped_lines.size()): - if dest_line_lengths[j] < new_cols: - wrapped_lines[j].set_cell(dest_line_lengths[j], null_cell) - - # Adjust viewport as needed - var viewport_adjustments = lines_to_add - trimmed_lines - while viewport_adjustments > 0: - if ybase == 0: - if y < new_rows - 1: - y += 1 - lines.pop() - else: - ybase += 1 - ydisp += 1 - else: - # Ensure ybase does not exceed its maximum value - if ybase < min(lines.max_length, (lines.length + count_to_insert) - new_rows): - if ybase == ydisp: - ydisp += 1 - ybase += 1 - viewport_adjustments -= 1 - saved_y = min(saved_y + lines_to_add, ybase + new_rows - 1) - i -= 1 - - # Rearrange lines in the buffer if there are any insertions, this is done at the end rather - # than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many - # costly calls to CircularList.splice. - if not to_insert.empty(): - # Record buffer insert events and then play them backwards so that the indexes are - # correct - var insert_events = [] - - # Record original lines so they don't get overridden when we rearrange the list - var original_lines = [] - for j in range(lines.length): - original_lines.append(lines.get_line(j)) - var original_lines_length = lines.length - - var original_line_index = original_lines_length - 1 - var next_to_insert_index = 0 - var next_to_insert = to_insert[next_to_insert_index] - lines.length = min(lines.max_length, lines.length + count_to_insert) - var count_inserted_so_far = 0 - var j = min(lines.max_length - 1, original_lines_length + count_to_insert - 1) - while j >= 0: - if next_to_insert and next_to_insert.start > original_line_index + count_inserted_so_far: - # Insert extra lines here, adjusting i as needed - for next_i in range(next_to_insert.new_lines.size() - 1, -1, -1): - lines.set_line(j, next_to_insert.new_lines[next_i]) - j -= 1 - j += 1 - - # Create insert events for later - insert_events.append({"index": original_line_index + 1, - "amount": next_to_insert.new_lines.size()}) - count_inserted_so_far += next_to_insert.new_lines.size() - next_to_insert_index += 1 - next_to_insert = to_insert[next_to_insert_index] if to_insert.size() > next_to_insert_index else null - else: - lines.set_line(j, original_lines[original_line_index]) - original_line_index -= 1 - j -= 1 - - # Update markers - var insert_count_emitted = 0 - for k in range(insert_events.size() - 1, -1, -1): - insert_events[k].index += insert_count_emitted - lines.emit_signal("inserted", insert_events[k]) - insert_count_emitted += insert_events[k].amount - var amount_to_trim = max(0, original_lines_length + count_to_insert - lines.max_length) - if amount_to_trim > 0: - lines.emit_signal("trimmed", amount_to_trim) - - -func get_null_cell(attr = null): - if attr: - _null_cell.fg = attr.fg - _null_cell.bg = attr.bg - _null_cell.extended = attr.extended - else: - _null_cell.fg = 0 - _null_cell.bg = 0 - _null_cell.extended = AttributeData.ExtendedAttrs.new() - return _null_cell - - -func get_blank_line(attr, is_wrapped: bool = false): - return BufferLine.new(_buffer_service.cols, get_null_cell(attr), is_wrapped) - - -func _get_correct_buffer_length(rows: int) -> int: - if not _has_scrollback: - return rows - else: - var correct_buffer_length = rows + _options_service.options.scrollback - return correct_buffer_length if correct_buffer_length < MAX_BUFFER_SIZE else MAX_BUFFER_SIZE - - -# Fills the viewport with blank lines. -func fill_viewport_rows(fill_attr = null) -> void: - if lines.length == 0: - if not fill_attr: - fill_attr = AttributeData.new() - var i = _rows - while i: - lines.push(get_blank_line(fill_attr)) - i -= 1 - - - -# Clears the buffer to it's initial state, discarding all previous data. -func clear() -> void: - ydisp = 0 - ybase = 0 - y = 0 - x = 0 - lines = CircularList.new(_get_correct_buffer_length(_rows)) - scroll_top = 0 - scroll_bottom = _rows - 1 - setup_tab_stops() - - -func get_wrapped_range_for_line(y: int) -> Dictionary: - var first = y - var last = y - # Scan upwards for wrapped lines - while first > 0 and lines.get_el(first).is_wrapped: - first -= 1 - # Scan downwards for wrapped lines - while last + 1 < lines.length and lines.get_el(last + 1).is_wrapped: - last += 1 - return {"first": first, "last": last} - - -# Setup the tab stops. -# @param i The index to start setting up tab stops from. -func setup_tab_stops(i = null) -> void: - if i != null: - if not tabs.get(i): - i = prev_stop(i) - else: - tabs = {} - i = 0 - - while i < _cols: - tabs[i] = true - i += max(_options_service.options.tab_stop_width, 1) - - -# Move the cursor to the previous tab stop from the given position (default is current). -# @param x The position to move the cursor to the previous tab stop. -func prev_stop(x: int) -> int: - if x == null: - x = self.x - - while not tabs.get(x - 1, false) and x - 1 > 0: - x - 1 - - return _cols - 1 if x > _cols else 0 if x < 0 else x - -# Move the cursor one tab stop forward from the given position (default is current). -# @param x The position to move the cursor one tab stop forward. -func next_stop(x = null) -> int: - if x == null: - x = self.x - - x += 1 - while not tabs.get(x) and x < _cols: - x += 1 - - return _cols - 1 if x >= _cols else 0 if x < 0 else x diff --git a/addons/godot_xterm/buffer/buffer_line.gd b/addons/godot_xterm/buffer/buffer_line.gd deleted file mode 100644 index b7d49ac..0000000 --- a/addons/godot_xterm/buffer/buffer_line.gd +++ /dev/null @@ -1,291 +0,0 @@ -# Copyright (c) 2018 The xterm.js authors. All rights reserved -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -const AttributeData = preload("res://addons/godot_xterm/buffer/attribute_data.gd") -const CellData = preload("res://addons/godot_xterm/buffer/cell_data.gd") -const Constants = preload("res://addons/godot_xterm/buffer/constants.gd") -const Content = Constants.Content -const BgFlags = Constants.BgFlags - -const CELL_SIZE = 3 - -enum Cell { - CONTENT - FG - BG -} - -var _data: Array -var _combined: Dictionary = {} -var _extended_attrs: Dictionary = {} - -var length: int -var is_wrapped - -func _init(cols: int, fill_cell_data = null, is_wrapped: bool = false): - self.is_wrapped = is_wrapped - _data = [] - _data.resize(cols * CELL_SIZE) - var cell = fill_cell_data if fill_cell_data \ - else CellData.from_char_data([0, Constants.NULL_CELL_CHAR, Constants.NULL_CELL_WIDTH, Constants.NULL_CELL_CODE]) - for i in range(cols): - set_cell(i, cell) - length = cols - - -func get_cell(index: int): - return _data[index * CELL_SIZE + Cell.CONTENT] - - -func get_width(index: int) -> int: - if (index * CELL_SIZE + Cell.CONTENT) < _data.size(): - return _data[index * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT - else: - return 0 - - -func has_content(index: int) -> int: - return _data[index * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK - - -# Get codepoint of the cell. -# To be in line with `code` in CharData this either returns -# a single UTF32 codepoint or the last codepoint of a combined string. -func get_codepoint(index: int) -> int: - var content = _data[index * CELL_SIZE + Cell.CONTENT] - if content & Content.IS_COMBINED_MASK: - return _combined[index].ord_at(_combined[index].length() - 1) - else: - return content & Content.CODEPOINT_MASK - - -func load_cell(index: int, cell): - var start_index = index * CELL_SIZE - cell.content = _data[start_index + Cell.CONTENT] - cell.fg = _data[start_index + Cell.FG] - cell.bg = _data[start_index + Cell.BG] - if cell.content and cell.content & Content.IS_COMBINED_MASK: - cell.combined_data = _combined[index] - if cell.bg & BgFlags.HAS_EXTENDED: - cell.extended = _extended_attrs[index] - return cell - - -func set_cell(index: int, cell) -> void: - if cell.content & Content.IS_COMBINED_MASK: - _combined[index] = cell.combined_data - if cell.bg & BgFlags.HAS_EXTENDED: - _extended_attrs[index] = cell.extended - _data[index * CELL_SIZE + Cell.CONTENT] = cell.content - _data[index * CELL_SIZE + Cell.FG] = cell.fg - _data[index * CELL_SIZE + Cell.BG] = cell.bg - - -func set_cell_from_codepoint(index: int, codepoint: int, width: int, fg: int, bg: int, e_attrs) -> void: - if bg & BgFlags.HAS_EXTENDED: - _extended_attrs[index] = e_attrs - _data[index * CELL_SIZE + Cell.CONTENT] = codepoint | (width << Content.WIDTH_SHIFT) - _data[index * CELL_SIZE + Cell.FG] = fg - _data[index * CELL_SIZE + Cell.BG] = bg - - -# Add a codepoint to a cell from input handler -# During input stage combining chars with a width of 0 follow and stack -# onto a leading char. Since we already set the attrs -# by the previous `set_data_from_code_pont` call, we can omit it here. -func add_codepoint_to_cell(index: int, codepoint: int) -> void: - var content = _data[index * CELL_SIZE + Cell.CONTENT] - if content & Content.IS_COMBINED_MASK: - # we already have a combined string, simply add - _combined[index] += char(codepoint) - else: - if content & Content.CODEPOINT_MASK: - # normal case for combining chars: - # - move current leading char + new one into combined string - # - set combined flag - _combined[index] = char(content & Content.CODEPOINT_MASK) + char(codepoint) - content &= ~Content.CODEPOINT_MASK # set codepoint in buffer to 0 - content |= Content.IS_COMBINED_MASK - else: - # should not happen - we actually have no data in the cell yet - # simply set the data in the cell buffer with a width of 1 - content = codepoint | (1 << Content.WIDTH_SHIFT) - _data[index * CELL_SIZE + Cell.CONTENT] = content - - -func insert_cells(pos: int, n: int, fill_cell_data, erase_attr = null) -> void: - pos %= length - - # handle fullwidth at pos: reset cell one to the left if pos is second cell of a wide char - var fg = erase_attr.fg if erase_attr and erase_attr.fg else 0 - var bg = erase_attr.bg if erase_attr and erase_attr.bg else 0 - var extended = erase_attr.extended if erase_attr and erase_attr.extended else AttributeData.ExtendedAttrs.new() - if pos and get_width(pos - 1) == 2: - set_cell_from_codepoint(pos - 1, 0, 1, fg, bg, extended) - - if n < length - pos: - var cell = CellData.new() - var i = length - pos - n - 1 - while i >= 0: - set_cell(pos + n + i, load_cell(pos + i, cell)) - i -= 1 - for j in range(n): - set_cell(pos + j, fill_cell_data) - else: - for i in range(pos, length): - set_cell(i, fill_cell_data) - - # handle fullwidth at line end: reset last cell if it is first cell of a wide char - if get_width(length - 1) == 2: - set_cell_from_codepoint(length - 1, 0, 1, fg, bg, extended) - - -func delete_cells(pos: int, n: int, fill_cell_data, erase_attr = null) -> void: - pos %= length - if n < length - pos: - var cell = CellData.new() - for i in range(length - pos - n): - set_cell(pos + i, load_cell(pos + n + i, cell)) - for i in range(length - n, length): - set_cell(i, fill_cell_data) - else: - for i in range(pos, length): - set_cell(i, fill_cell_data) - - # handle fullwidth at pos: - # - reset pos-1 if wide char - # - reset pos if width==0 (previous second cell of a wide char) - var fg = erase_attr.fg if erase_attr and erase_attr.fg else 0 - var bg = erase_attr.bg if erase_attr and erase_attr.bg else 0 - var extended = erase_attr.extended if erase_attr and erase_attr.extended else AttributeData.ExtendedAttrs.new() - if pos and get_width(pos - 1) == 2: - set_cell_from_codepoint(pos - 1, 0, 1, fg, bg, extended) - if get_width(pos) == 0 and not has_content(pos): - set_cell_from_codepoint(pos, 0, 1, fg, bg, extended) - - -func replace_cells(start: int, end: int, fill_cell_data, erase_attr = null) -> void: - var fg = erase_attr.fg if erase_attr and erase_attr.fg else 0 - var bg = erase_attr.bg if erase_attr and erase_attr.bg else 0 - var extended = erase_attr.extended if erase_attr and erase_attr.extended else AttributeData.ExtendedAttrs.new() - - # handle fullwidth at start: reset cell one to left if start is second cell of a wide char - if start and get_width(start - 1) == 2: - set_cell_from_codepoint(start - 1, 0, 1, fg, bg, extended) - # handle fullwidth at last cell + 1: reset to empty cell if it is second part of a wide char - if end < length and get_width(end - 1) == 2: - set_cell_from_codepoint(end, 0, 1, fg, bg, extended) - - while start < end and start < length: - set_cell(start, fill_cell_data) - start += 1 - - -func resize(cols: int, fill_cell_data) -> void: - if cols == length: - return - if cols > length: - var data = [] - if length: - if cols * CELL_SIZE < _data.size(): - data = _data.slice(0, cols * CELL_SIZE - 1) - else: - data = _data.duplicate() - data.resize(cols * CELL_SIZE) - _data = data - var i = length - while i < cols: - set_cell(i, fill_cell_data) - i += 1 - else: - if cols: - var data = [] - data = _data.slice(0, cols * CELL_SIZE - 1) - data.resize(cols * CELL_SIZE) - _data = data - # Remove any cut off combined data, FIXME: repeat this for extended attrs - for key in _combined.keys(): - if key as int > cols: - _combined.erase(key) - else: - _data = [] - _combined = {} - length = cols - - -# Fill a line with `fill_cell_data`. -func fill(fill_cell_data) -> void: - _combined = {} - _extended_attrs = {} - for i in range(length): - set_cell(i, fill_cell_data) - - -# alter to a full copy of line -func copy_from(line) -> void: - _data = line._data.duplicate() - length = line.length - _combined = {} - for k in line._combined.keys(): - _combined[k] = line._combined[k] - is_wrapped = line.is_wrapped - - -func get_trimmed_length() -> int: - for i in range(length - 1, -1, -1): - if _data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK: - return i + (_data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT) - return 0 - - -func copy_cells_from(src, src_col: int, dest_col: int, length: int, apply_in_reverse: bool) -> void: - var src_data = src._data - - if apply_in_reverse: - for cell in range(length - 1, -1, -1): - for i in range(CELL_SIZE): - _data[(dest_col + cell) * CELL_SIZE + i] = src_data[(src_col + cell) * CELL_SIZE + i] - else: - for cell in range(length): - for i in range(CELL_SIZE): - _data[(dest_col + cell) * CELL_SIZE + i] = src_data[(src_col + cell) * CELL_SIZE + i] - - # Move any combined data over as needed, FIXME: repeat for extended attrs - var src_combined_keys = src._combined.keys() - for i in range(src_combined_keys.size()): - var key = int(src_combined_keys[i]) - if key >= src_col: - _combined[key + src_col + dest_col] = src._combined[key] - - -func translate_to_string(trim_right: bool = false, start_col: int = 0, end_col: int = -1) -> String: - if end_col == -1: - end_col = length - if trim_right: - end_col = min(end_col, get_trimmed_length()) - var result = "" - while start_col < end_col: - var content = _data[start_col * CELL_SIZE + Cell.CONTENT] - var cp = content & Content.CODEPOINT_MASK - if content & Content.IS_COMBINED_MASK: - result += _combined[start_col] - elif cp: - result += char(cp) - else: - result += Constants.WHITESPACE_CELL_CHAR - start_col += max(content >> Content.WIDTH_SHIFT, 1) # always advance by 1 - return result - - -func duplicate(): - # Workaround as per: https://github.com/godotengine/godot/issues/19345#issuecomment-471218401 - var duplicant = load("res://addons/godot_xterm/buffer/buffer_line.gd").new(length) - duplicant._data = _data.duplicate(true) - duplicant._combined = _combined.duplicate(true) - duplicant._extended_attrs = _extended_attrs.duplicate(true) - duplicant.length = length - duplicant.is_wrapped = is_wrapped - return duplicant diff --git a/addons/godot_xterm/buffer/buffer_reflow.gd b/addons/godot_xterm/buffer/buffer_reflow.gd deleted file mode 100644 index 1a55143..0000000 --- a/addons/godot_xterm/buffer/buffer_reflow.gd +++ /dev/null @@ -1,198 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Object - - -# Evaluates and returns indexes to be removed after a reflow larger occurs. Lines will be removed -# when a wrapped line unwraps. -# @param lines The buffer lines. -# @param newCols The columns after resize. -static func reflow_larger_get_lines_to_remove(lines, old_cols: int, new_cols: int, - buffer_absolute_y: int, null_cell) -> PoolIntArray: - # Gather all BufferLines that need to be removed from the Buffer here so that they can be - # batched up and only committed once - var to_remove = PoolIntArray([]) - - var y = 0 - while y < lines.length - 1: - # Check if this row is wrapped - var i = y - i += 1 - var next_line = lines.get_line(i) - if not next_line.is_wrapped: - y += 1 - continue - - # Check how many lines it's wrapped for - var wrapped_lines = [lines.get_line(y)] - while i < lines.length and next_line.is_wrapped: - wrapped_lines.append(next_line) - i += 1 - next_line = lines.get_line(i) - - # If these lines contain the cursor don't touch them, the program will handle fixing up wrapped - # lines with the cursor - if buffer_absolute_y >= y and buffer_absolute_y < i: - y += wrapped_lines.size() - 1 - y += 1 - continue - - # Copy buffer data to new locations - var dest_line_index = 0 - var dest_col = get_wrapped_line_trimmed_length(wrapped_lines, dest_line_index, old_cols) - var src_line_index = 1 - var src_col = 0 - while src_line_index < wrapped_lines.size(): - var src_trimmed_line_length = get_wrapped_line_trimmed_length(wrapped_lines, src_line_index, old_cols) - var src_remaining_cells = src_trimmed_line_length - src_col - var dest_remaining_cells = new_cols - dest_col - var cells_to_copy = min(src_remaining_cells, dest_remaining_cells) - - wrapped_lines[dest_line_index].copy_cells_from(wrapped_lines[src_line_index], src_col, dest_col, cells_to_copy, false) - - dest_col += cells_to_copy - if dest_col == new_cols: - dest_line_index += 1 - dest_col = 0 - - src_col += cells_to_copy - if src_col == src_trimmed_line_length: - src_line_index += 1 - src_col = 0 - - # Make sure the last cell isn't wide, if it is copy it to the current dest - if dest_col == 0 and dest_line_index != 0: - if wrapped_lines[dest_line_index - 1].get_width(new_cols - 1) == 2: - wrapped_lines[dest_line_index].copy_cells_from(wrapped_lines[dest_line_index - 1], new_cols - 1, dest_col, 1, false) - dest_col += 1 - # Null out the end of the last row - wrapped_lines[dest_line_index - 1].set_cell(new_cols - 1, null_cell) - - # Clear out remaining cells or fragments could remain; - var replaced = wrapped_lines[dest_line_index].translate_to_string() - wrapped_lines[dest_line_index].replace_cells(dest_col, new_cols, null_cell) - - # Work backwards and remove any rows at the end that only contain null cells - var count_to_remove = 0 - for j in range(wrapped_lines.size() - 1, 0, -1): - if j > dest_line_index or wrapped_lines[j].get_trimmed_length() == 0: - count_to_remove += 1 - else: - break - - if count_to_remove > 0: - to_remove.append(y + wrapped_lines.size() - count_to_remove) # index - to_remove.append(count_to_remove) - - y += wrapped_lines.size() - 1 - y += 1 - - return to_remove - - -# Creates and return the new layout for lines given an array of indexes to be removed. -# @param lines The buffer lines. -# @param to_remove The indexes to remove. -static func reflow_larger_create_new_layout(lines, to_remove: PoolIntArray): - var layout = PoolIntArray([]) - # First iterate through the list and get the actual indexes to use for rows - var next_to_remove_index = 0 - var next_to_remove_start = to_remove[next_to_remove_index] - var count_removed_so_far = 0 - var i = 0 - while i < lines.length: - if next_to_remove_start == i: - next_to_remove_index += 1 - var count_to_remove = to_remove[next_to_remove_index] - - # Tell markers that there was a deletion - lines.emit_signal("deleted", i - count_removed_so_far, count_to_remove) - - i += count_to_remove - 1 - count_removed_so_far += count_to_remove - next_to_remove_index += 1 - next_to_remove_start = to_remove[next_to_remove_index] if next_to_remove_index < to_remove.size() else null - else: - layout.append(i) - - i += 1 - - return { "layout": layout, "count_removed": count_removed_so_far } - - -# Applies a new layout to the buffer. This essentially does the same as many splice calls but it's -# done all at once in a single iteration through the list since splice is very expensive. -# @param lines The buffer lines. -# @param new_layout The new layout to apply. -static func reflow_larger_apply_new_layout(lines, new_layout: PoolIntArray) -> void: - # Record original lines so they don't get overridden when we rearrange the list - var new_layout_lines = [] - for i in range(new_layout.size()): - new_layout_lines.append(lines.get_line(new_layout[i])) - - # Rearrange the list - for i in range(new_layout_lines.size()): - lines.set_line(i, new_layout_lines[i]) - lines.length = new_layout.size() - - -# Gets the new line lengths for a given wrapped line. The purpose of this function it to pre- -# compute the wrapping points since wide characters may need to be wrapped onto the following line. -# This function will return an array of numbers of where each line wraps to, the resulting array -# will only contain the values `newCols` (when the line does not end with a wide character) and -# `new_cols - 1` (when the line does end with a wide character), except for the last value which -# will contain the remaining items to fill the line. -# -# Calling this with a `new_cols` value of `1` will lock up. -# -# @param wrapped_lines The wrapped lines to evaluate. -# @param old_cols The columns before resize. -# @param new_cols The columns after resize. -static func reflow_smaller_get_new_line_lengths(wrapped_lines: Array, old_cols: int, new_cols: int) -> PoolIntArray: - var new_line_lengths = PoolIntArray([]) - var cells_needed: int - for i in range(wrapped_lines.size()): - cells_needed += get_wrapped_line_trimmed_length(wrapped_lines, i, old_cols) - - # Use src_col and scr_line to find the new wrapping point, use that to get the cells_available and - # lines_needed - var src_col = 0 - var src_line = 0 - var cells_available = 0 - while cells_available < cells_needed: - if cells_needed - cells_available < new_cols: - # Add the final line and exit the loop - new_line_lengths.append(cells_needed - cells_available) - break - - src_col += new_cols - var old_trimmed_length = get_wrapped_line_trimmed_length(wrapped_lines, src_line, old_cols) - if src_col > old_trimmed_length: - src_col -= old_trimmed_length - src_line += 1 - - var ends_with_wide = wrapped_lines[src_line].get_width(src_col - 1) == 2 - if ends_with_wide: - src_col -= 1 - - var line_length = new_cols - 1 if ends_with_wide else new_cols - new_line_lengths.append(line_length) - cells_available += line_length - - return new_line_lengths - - -static func get_wrapped_line_trimmed_length(lines: Array, i: int, cols: int) -> int: - # If this is the last row in the wrapped line, get the actual trimmed length - if i == lines.size() - 1: - return lines[i].get_trimmed_length() - - # Detect whether the following line starts with a wide character and the end of the current line - # is null, if so then we can be pretty sure the null character should be excluded from the line - # length - var ends_in_null = not (lines[i].has_content(cols - 1)) and lines[i].get_width(cols - 1) == 1 - var following_line_starts_with_wide = lines[i + 1].get_width(0) == 2 - if ends_in_null and following_line_starts_with_wide: - return cols - 1 - return cols diff --git a/addons/godot_xterm/buffer/buffer_set.gd b/addons/godot_xterm/buffer/buffer_set.gd deleted file mode 100644 index 63f0cdf..0000000 --- a/addons/godot_xterm/buffer/buffer_set.gd +++ /dev/null @@ -1,69 +0,0 @@ -# Copyright (c) 2017 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - -const Buffer = preload("res://addons/godot_xterm/buffer/buffer.gd") - -signal buffer_activated(active_buffer, inactive_buffer) - -var normal -var alt -var active - - -func _init(options_service, buffer_service): - normal = Buffer.new(true, options_service, buffer_service) - normal.fill_viewport_rows() - - # The alt buffer should never have scrollback. - # See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer - alt = Buffer.new(false, options_service, buffer_service) - active = normal - - setup_tab_stops() - - -# Sets the normal Bufer of the BufferSet as its currently active Buffer. -func activate_normal_buffer() -> void: - if active == normal: - return - - normal.x = alt.x - normal.y = alt.y - - # The alt buffer should always be cleared when we switch to the normal - # buffer. This frees up memory since the alt buffer should always be new - # when activated. - alt.clear() - active = normal - emit_signal("buffer_activated", normal, alt) - - -# Sets the alt Buffer of the BufferSet as its currently active Buffer. -func activate_alt_buffer(fill_attr = null) -> void: - if active == alt: - return - - # Since the alt buffer is always cleared when the normal buffer is - # activated, we want to fill it when switching to it. - alt.fill_viewport_rows(fill_attr) - alt.x = normal.x - alt.y = normal.y - active = alt - emit_signal("buffer_activated", alt, normal) - - -# Resizes both normal and alt buffers, adjusting their data accordingly. -# @param new_cols The new number of columns. -# @param new_rows The new number of rows. -func resize(new_cols: int, new_rows: int) -> void: - normal.resize(new_cols, new_rows) - alt.resize(new_cols, new_rows) - - -# Setup the tab stops. -# @param i The index to start setting up tab stops from. -func setup_tab_stops(i = null) -> void: - normal.setup_tab_stops(i) - alt.setup_tab_stops(i) diff --git a/addons/godot_xterm/buffer/cell_data.gd b/addons/godot_xterm/buffer/cell_data.gd deleted file mode 100644 index b2ec880..0000000 --- a/addons/godot_xterm/buffer/cell_data.gd +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (c) 2018 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends "res://addons/godot_xterm/buffer/attribute_data.gd" -# CellData - represents a single cell in the terminal buffer. - - -const Decoder = preload("res://addons/godot_xterm/input/text_decoder.gd") - -const Content = Constants.Content - -# Helper to create CellData from CharData -static func from_char_data(value): - # Workaround as per: https://github.com/godotengine/godot/issues/19345#issuecomment-471218401 - var char_data = load("res://addons/godot_xterm/buffer/cell_data.gd").new() - char_data.set_from_char_data(value) - return char_data - - -# Primitives from terminal buffer -var content = 0 -var combined_data = '' - - -# Whether cell contains a combined string -func is_combined() -> int: - return content & Content.IS_COMBINED_MASK - - -func get_width() -> int: - return content >> Content.WIDTH_SHIFT - - -func get_chars() -> String: - if content & Content.IS_COMBINED_MASK: - return combined_data - elif content & Content.CODEPOINT_MASK: - return char(content & Content.CODEPOINT_MASK) - else: - return Constants.NULL_CELL_CHAR - -func get_code() -> int: - if is_combined(): - return combined_data.ord_at(combined_data.length() - 1) - else: - return content & Content.CODEPOINT_MASK - - -func set_from_char_data(value) -> void: - var attr: int = value[Constants.CHAR_DATA_ATTR_INDEX] - var character: String = value[Constants.CHAR_DATA_CHAR_INDEX] - var width: int = value[Constants.CHAR_DATA_WIDTH_INDEX] - var code: int = value[Constants.CHAR_DATA_CODE_INDEX] - - fg = attr - bg = 0 - # combined strings need special treatment. Javascript uses utf16 for strings - # whereas Godot uses utf8, therefore we don't need any of the special - # handling of surrogates in the original xterm.js code. - if character.length() >= 2: - combined_data = character - content = Content.IS_COMBINED_MASK | (width << Content.WIDTH_SHIFT) - else: - content = (character.ord_at(0) if character.length() else 0) | (width << Content.WIDTH_SHIFT) - - -func get_as_char_data(): - return [fg, get_chars(), get_width(), get_code()] diff --git a/addons/godot_xterm/buffer/constants.gd b/addons/godot_xterm/buffer/constants.gd deleted file mode 100644 index 00fc648..0000000 --- a/addons/godot_xterm/buffer/constants.gd +++ /dev/null @@ -1,106 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -const DEFAULT_COLOR = 256 -const DEFAULT_ATTR = (0 << 18) | (DEFAULT_COLOR << 9) | (256 << 0) - -const CHAR_DATA_ATTR_INDEX = 0 -const CHAR_DATA_CHAR_INDEX = 1 -const CHAR_DATA_WIDTH_INDEX = 2 -const CHAR_DATA_CODE_INDEX = 3 - -# Null cell - a real empty cell (containing nothing). -# Note that code should always be 0 for a null cell as -# several test condition of the buffer line rely on this. -const NULL_CELL_CHAR = '' -const NULL_CELL_WIDTH = 1 -const NULL_CELL_CODE = 0 - - -# Whitespace cell. -# This is meant as a replacement for empty cells when needed -# during rendering lines to preserve correct alignment. -const WHITESPACE_CELL_CHAR = ' ' -const WHITESPACE_CELL_WIDTH = 1 -const WHITESPACE_CELL_CODE = 32 - - -# Bitmasks for accessing data in `content`. -enum Content { - CODEPOINT_MASK = 0x1FFFFF - IS_COMBINED_MASK = 0x200000 - HAS_CONTENT_MASK = 0x3FFFFF - WIDTH_MASK = 0xC00000 - WIDTH_SHIFT = 22 -} - - -enum Attributes { - # bit 1..8 blue in RGB, color in P256 and P16 - BLUE_MASK = 0xFF - BLUE_SHIFT = 0 - PCOLOR_MASK = 0xFF - PCOLOR_SHIFT = 0 - - # bit 9..16 green in RGB - GREEN_MASK = 0xFF00 - GREEN_SHIFT = 8 - - # bit 17..24 red in RGB - RED_MASK = 0xFF0000 - RED_SHIFT = 16 - - # bit 25..26 color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3) - CM_MASK = 0x3000000 - CM_DEFAULT = 0 - CM_P16 = 0x1000000 - CM_P256 = 0x2000000 - CM_RGB = 0x3000000 - - # bit 1..24 RGB room - RGB_MASK = 0xFFFFFF -} - - -enum FgFlags { - # bit 27..31 (32th bit unused) - INVERSE = 0x4000000 - BOLD = 0x8000000 - UNDERLINE = 0x10000000 - BLINK = 0x20000000 - INVISIBLE = 0x40000000 -} - - -enum BgFlags { - # bit 27..32 (upper 3 unused) - ITALIC = 0x4000000 - DIM = 0x8000000 - HAS_EXTENDED = 0x10000000 -} - - -enum UnderlineStyle { - NONE - SINGLE - DOUBLE - CURLY - DOTTED - DASHED -} - -enum CursorStyle { - BLOCK - UNDERLINE - BAR -} - -enum BellStyle { - NONE - VISUAL - SOUND - BOTH -} diff --git a/addons/godot_xterm_native/build.sh b/addons/godot_xterm/build.sh similarity index 87% rename from addons/godot_xterm_native/build.sh rename to addons/godot_xterm/build.sh index 07275d3..d51ba09 100755 --- a/addons/godot_xterm_native/build.sh +++ b/addons/godot_xterm/build.sh @@ -1,7 +1,7 @@ #! /usr/bin/env nix-shell #! nix-shell -i bash --pure -p binutils.bintools cmake scons -# Make sure we are in the addons/godot_xterm_native directory +# Make sure we are in the addons/godot_xterm directory cd ${BASH_SOURCE%/*} # Initialize godot-cpp diff --git a/addons/godot_xterm/char_data.gd b/addons/godot_xterm/char_data.gd deleted file mode 100644 index d65d8a7..0000000 --- a/addons/godot_xterm/char_data.gd +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2020 The GodotXterm authors. All rights reserved. -# License MIT -extends Reference - -var ch # character -var fg = Color(1.0, 1.0, 1.0) # foreground color -var bg = Color(0.0, 0.0, 0.0) # background color -var ff = 0 # font flags - -func _init( - character: String, - background_color: Color = bg, - foreground_color: Color = fg, - font_flags = ff # Does this work or will it cause problems (this assignement technique) - ): - ch = character - bg = background_color - fg = foreground_color - ff = font_flags diff --git a/addons/godot_xterm/circular_list.gd b/addons/godot_xterm/circular_list.gd deleted file mode 100644 index 4f6f191..0000000 --- a/addons/godot_xterm/circular_list.gd +++ /dev/null @@ -1,185 +0,0 @@ -# Copyright (c) 2016 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference -# Represents a circular list; a list with a maximum size that wraps around when push is called, -# overriding values at the start of the list. - - -signal deleted(index, amount) -signal inserted -signal trimmed - -var _array -var _start_index: int -var length: int = 0 setget _set_length,_get_length -var max_length: int setget _set_max_length,_get_max_length -var is_full: bool setget ,_get_is_full - - -func _set_length(new_length: int): - if new_length > length: - for i in range(length, new_length): - _array[i] = null - length = new_length - - -func _get_length(): - return length - - -func _set_max_length(new_max_length): - if max_length == new_max_length: - return - - # Reconstruct array, starting at index 0. - # Only transfer values from the indexes 0 to length. - var new_array = [] - new_array.resize(new_max_length) - for i in range(0, min(new_max_length, length)): - new_array[i] = _array[_get_cyclic_index(i)] - _array = new_array - max_length = new_max_length - _start_index = 0 - - -func _get_max_length(): - return max_length - - -# Ringbuffer is at max length. -func _get_is_full() -> bool: - return length == max_length - - -func _init(max_length = 0): - self.max_length = max_length - _array = [] - _array.resize(max_length) - _start_index = 0 - - -func get_el(index: int): - return _array[_get_cyclic_index(index)] - - -# Alias for `get_al`. -func get_line(index: int): - return get_el(index) - - -func set_el(index: int, value) -> void: - _array[_get_cyclic_index(index)] = value - - -# Alias for `set_el`. -func set_line(index: int, value) -> void: - set_el(index, value) - - -# Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0 -# if the maximum length is reached. -# @param value The value to push onto the list. -func push(value) -> void: - _array[_get_cyclic_index(length)] = value - if length == max_length: - _start_index += 1 - _start_index %= max_length - emit_signal("trimmed", 1) - else: - length += 1 - - -# Advance ringbuffer index and return current element for recycling. -# Note: The buffer must be full for this method to work. -# @throws When the buffer is not full. -func recycle(): - if length != max_length: - push_error("Can only recycle when the buffer is full") - _start_index = (_start_index + 1) % max_length - emit_signal("trimmed", 1) - return _array[_get_cyclic_index(length - 1)] - - -# Removes and returns the last value on the list. -# @return The popped value. -func pop(): - var last = _array[_get_cyclic_index(length - 1)] - length -= 1 - return last - - -# Deletes and/or inserts items at a particular index (in that order). Unlike -# Array.prototype.splice, this operation does not return the deleted items as a new array in -# order to save creating a new array. Note that this operation may shift all values in the list -# in the worst case. -# @param start The index to delete and/or insert. -# @param deleteCount The number of elements to delete. -# @param items The items to insert. -func splice(start: int, delete_count: int, items: Array = []) -> void: - # Delete items - if delete_count: - for i in range(start, length - delete_count): - _array[_get_cyclic_index(i)] = _array[_get_cyclic_index(i + delete_count)] - length -= delete_count - - # Add items - var i = length - 1 - while i >= start: - _array[_get_cyclic_index(i + items.size())] = _array[_get_cyclic_index(i)] - i -= 1 - for j in range(items.size()): - _array[_get_cyclic_index(start + j)] = items[j] - - # Adjust length as needed - if length + items.size() > max_length: - var count_to_trim = (length + items.size()) - max_length - _start_index += count_to_trim - length = max_length - emit_signal("trimmed", count_to_trim) - else: - length += items.size() - - -# Trims a number of items from the start of the list. -# @param count The number of items to remove. -func trim_start(count: int) -> void: - if count > length: - count = length - _start_index += count - length -= count - emit_signal("trimmed", count) - - -func shift_elements(start: int, count: int, offset: int) -> void: - if count <= 0: - return - if start < 0 or start >= length: - self.push_error("start argument out of range") - if start + offset < 0: - self.push_error("cannot shift elements in list beyond index 0") - - if offset > 0: - for i in range(count - 1, -1, -1): - set_el(start + i + offset, get_el(start + i)) - - var expand_list_by = (start + count + offset) - length - - if expand_list_by > 0: - length += expand_list_by - while length > max_length: - length -= 1 - _start_index += 1 - emit_signal("trimmed", 1) - else: - for i in range(0, count): - set_el(start + i + offset, get_el(start + i)) - - -func _get_cyclic_index(index: int) -> int: - return (_start_index + index) % max_length - - -# Wrapper for `push_error` so we can test for calls to this built-in function. -func push_error(message): - push_error(message) diff --git a/addons/godot_xterm/color_manager.gd b/addons/godot_xterm/color_manager.gd deleted file mode 100644 index 8e2ceb9..0000000 --- a/addons/godot_xterm/color_manager.gd +++ /dev/null @@ -1,108 +0,0 @@ -# Copyright (c) 2017 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference -# Xterm.js stores colors in both css and rgba formats. In this case we only need -# to store the colors in godots RGBA Color format. - - -static func _generate_default_ansi_colors() -> PoolColorArray: - var colors = PoolColorArray([ - # dark: - Color('#2e3436'), - Color('#cc0000'), - Color('#4e9a06'), - Color('#c4a000'), - Color('#3465a4'), - Color('#75507b'), - Color('#06989a'), - Color('#d3d7cf'), - # bright: - Color('#555753'), - Color('#ef2929'), - Color('#8ae234'), - Color('#fce94f'), - Color('#729fcf'), - Color('#ad7fa8'), - Color('#34e2e2'), - Color('#eeeeec'), - ]) - - # Fill in the remaining 240 ANSI colors. - # Generate colors (16-231) - var v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff] - for i in range(0, 216): - var r = v[(i / 36) % 6 | 0] - var g = v[(i / 6) % 6 | 0] - var b = v[i % 6] - colors.append(Color("%02x%02x%02x" % [r, g, b])) - - # Generate greys (232-255) - for i in range(0, 24): - var c = 8 + i * 10 - colors.append(Color("%02x%02x%02x" % [c, c, c])) - - return colors - - -const DEFAULT_FOREGROUND = Color('#ffffff') -const DEFAULT_BACKGROUND = Color('#000000') -const DEFAULT_CURSOR = Color('#ffffff') -const DEFAULT_CURSOR_ACCENT = Color('#000000') -const DEFAULT_SELECTION = Color(1, 1, 1, 0.3) -var DEFAULT_ANSI_COLORS = _generate_default_ansi_colors() - -var colors -var _litmus_color: Gradient = Gradient.new() -var _contrast_cache: Dictionary = {} - - -func _init(): - colors = { - 'foreground': DEFAULT_FOREGROUND, - 'background': DEFAULT_BACKGROUND, - 'cursor': DEFAULT_CURSOR, - 'cursor_accent': DEFAULT_CURSOR_ACCENT, - 'selection': DEFAULT_SELECTION, - 'selection_opaque': DEFAULT_BACKGROUND.blend(DEFAULT_SELECTION), - 'ansi': DEFAULT_ANSI_COLORS, - 'contrast_cache': _contrast_cache, - } - - -func on_options_change(key: String) -> void: - if key == 'minimum_contrast_ratio': - _contrast_cache.clear() - - -# Sets the terminal's theme. -# If a partial theme is provided then default -# colors will be used where colors are not defined. -func set_theme(theme: Dictionary = {}) -> void: - colors['foreground'] = theme.get('foreground', DEFAULT_FOREGROUND) - colors['bakcground'] = theme.get('background', DEFAULT_BACKGROUND) - colors['cursor'] = theme.get('cursor', DEFAULT_CURSOR) - colors['cursor_accent'] = theme.get('cursor_accent', DEFAULT_CURSOR_ACCENT) - colors['selection'] = theme.get('selection', DEFAULT_SELECTION) - colors['selection_opaque'] = theme.get('selection_opaque', colors['selection_opaque']) - colors['ansi'][0] = theme.get('black', DEFAULT_ANSI_COLORS[0]) - colors['ansi'][1] = theme.get('red', DEFAULT_ANSI_COLORS[1]) - colors['ansi'][2] = theme.get('green', DEFAULT_ANSI_COLORS[2]) - colors['ansi'][3] = theme.get('yellow', DEFAULT_ANSI_COLORS[3]) - colors['ansi'][4] = theme.get('blue', DEFAULT_ANSI_COLORS[4]) - colors['ansi'][5] = theme.get('magenta', DEFAULT_ANSI_COLORS[5]) - colors['ansi'][6] = theme.get('cyan', DEFAULT_ANSI_COLORS[6]) - colors['ansi'][7] = theme.get('white', DEFAULT_ANSI_COLORS[7]) - colors['ansi'][8] = theme.get('bright_black', DEFAULT_ANSI_COLORS[8]) - colors['ansi'][9] = theme.get('bright_red', DEFAULT_ANSI_COLORS[9]) - colors['ansi'][10] = theme.get('bright_green', DEFAULT_ANSI_COLORS[10]) - colors['ansi'][11] = theme.get('bright_yellow', DEFAULT_ANSI_COLORS[11]) - colors['ansi'][12] = theme.get('bright_blue', DEFAULT_ANSI_COLORS[12]) - colors['ansi'][13] = theme.get('bright_magenta', DEFAULT_ANSI_COLORS[13]) - colors['ansi'][14] = theme.get('bright_cyan', DEFAULT_ANSI_COLORS[14]) - colors['ansi'][15] = theme.get('bright_white', DEFAULT_ANSI_COLORS[15]) - - _contrast_cache.clear() - - - diff --git a/addons/godot_xterm/data/charsets.gd b/addons/godot_xterm/data/charsets.gd deleted file mode 100644 index a429cb7..0000000 --- a/addons/godot_xterm/data/charsets.gd +++ /dev/null @@ -1,256 +0,0 @@ -# Copyrigth (c) 2016 The xterm.js authors. All rights reserved -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference -# The character sets supported by the terminal. These enable several languages -# to be represented within the terminal with only 8-bit encoding. See ISO 2022 -# for a discussion on character sets. Only VT100 character sets are supported. - -const CHARSETS = { - # DEC Special Character and Line Drawing Set. - # Reference: http:#vt100.net/docs/vt102-ug/table5-13.html - # A lot of curses apps use this if they see TERM=xterm. - # testing: echo -e "\e(0a\e(B" - # The xterm output sometimes seems to conflict with the - # reference above. xterm seems in line with the reference - # when running vttest however. - # The table below now uses xterm"s output from vttest. - "0": { - "`": "\u25c6", # "◆" - "a": "\u2592", # "▒" - "b": "\u2409", # "␉" (HT) - "c": "\u240c", # "␌" (FF) - "d": "\u240d", # "␍" (CR) - "e": "\u240a", # "␊" (LF) - "f": "\u00b0", # "°" - "g": "\u00b1", # "±" - "h": "\u2424", # "␤" (NL) - "i": "\u240b", # "␋" (VT) - "j": "\u2518", # "┘" - "k": "\u2510", # "┐" - "l": "\u250c", # "┌" - "m": "\u2514", # "└" - "n": "\u253c", # "┼" - "o": "\u23ba", # "⎺" - "p": "\u23bb", # "⎻" - "q": "\u2500", # "─" - "r": "\u23bc", # "⎼" - "s": "\u23bd", # "⎽" - "t": "\u251c", # "├" - "u": "\u2524", # "┤" - "v": "\u2534", # "┴" - "w": "\u252c", # "┬" - "x": "\u2502", # "│" - "y": "\u2264", # "≤" - "z": "\u2265", # "≥" - "{": "\u03c0", # "π" - "|": "\u2260", # "≠" - "}": "\u00a3", # "£" - "~": "\u00b7" # "·" - }, - - # British character set - # ESC (A - # Reference: http:#vt100.net/docs/vt220-rm/table2-5.html - "A": { - "#": "£" - }, - - # United States character set - # ESC (B - "B": null, - - # Dutch character set - # ESC (4 - # Reference: http:#vt100.net/docs/vt220-rm/table2-6.html - "4": { - "#": "£", - "@": "¾", - "[": "ij", - "\\": "½", - "]": "|", - "{": "¨", - "|": "f", - "}": "¼", - "~": "´" - }, - - # Finnish character set - # ESC (C or ESC (5 - # Reference: http:#vt100.net/docs/vt220-rm/table2-7.html - "C": { - "[": "Ä", - "\\": "Ö", - "]": "Å", - "^": "Ü", - "`": "é", - "{": "ä", - "|": "ö", - "}": "å", - "~": "ü" - }, - "5": { - "[": "Ä", - "\\": "Ö", - "]": "Å", - "^": "Ü", - "`": "é", - "{": "ä", - "|": "ö", - "}": "å", - "~": "ü" - }, - - # French character set - # ESC (R - # Reference: http:#vt100.net/docs/vt220-rm/table2-8.html - "R": { - "#": "£", - "@": "à", - "[": "°", - "\\": "ç", - "]": "§", - "{": "é", - "|": "ù", - "}": "è", - "~": "¨" - }, - - # French Canadian character set - # ESC (Q - # Reference: http:#vt100.net/docs/vt220-rm/table2-9.html - "Q": { - "@": "à", - "[": "â", - "\\": "ç", - "]": "ê", - "^": "î", - "`": "ô", - "{": "é", - "|": "ù", - "}": "è", - "~": "û" - }, - - # German character set - # ESC (K - # Reference: http:#vt100.net/docs/vt220-rm/table2-10.html - "K": { - "@": "§", - "[": "Ä", - "\\": "Ö", - "]": "Ü", - "{": "ä", - "|": "ö", - "}": "ü", - "~": "ß" - }, - - # Italian character set - # ESC (Y - # Reference: http:#vt100.net/docs/vt220-rm/table2-11.html - "Y": { - "#": "£", - "@": "§", - "[": "°", - "\\": "ç", - "]": "é", - "`": "ù", - "{": "à", - "|": "ò", - "}": "è", - "~": "ì" - }, - - # Norwegian/Danish character set - # ESC (E or ESC (6 - # Reference: http:#vt100.net/docs/vt220-rm/table2-12.html - "E": { - "@": "Ä", - "[": "Æ", - "\\": "Ø", - "]": "Å", - "^": "Ü", - "`": "ä", - "{": "æ", - "|": "ø", - "}": "å", - "~": "ü" - }, - "6": { - "@": "Ä", - "[": "Æ", - "\\": "Ø", - "]": "Å", - "^": "Ü", - "`": "ä", - "{": "æ", - "|": "ø", - "}": "å", - "~": "ü" - }, - - # Spanish character set - # ESC (Z - # Reference: http:#vt100.net/docs/vt220-rm/table2-13.html - "Z": { - "#": "£", - "@": "§", - "[": "¡", - "\\": "Ñ", - "]": "¿", - "{": "°", - "|": "ñ", - "}": "ç" - }, - - # Swedish character set - # ESC (H or ESC (7 - # Reference: http:#vt100.net/docs/vt220-rm/table2-14.html - "H": { - "@": "É", - "[": "Ä", - "\\": "Ö", - "]": "Å", - "^": "Ü", - "`": "é", - "{": "ä", - "|": "ö", - "}": "å", - "~": "ü" - }, - "7": { - "@": "É", - "[": "Ä", - "\\": "Ö", - "]": "Å", - "^": "Ü", - "`": "é", - "{": "ä", - "|": "ö", - "}": "å", - "~": "ü" - }, - - # Swiss character set - # ESC (= - # Reference: http:#vt100.net/docs/vt220-rm/table2-15.html - #/ - "=": { - "#": "ù", - "@": "à", - "[": "é", - "\\": "ç", - "]": "ê", - "^": "î", - "_": "è", - "`": "ô", - "{": "ä", - "|": "ö", - "}": "ü", - "~": "û" - }, -} - -# The default character set, US. -const DEFAULT_CHARSET = CHARSETS["B"] diff --git a/addons/godot_xterm_native/fonts/Cousine-Bold.ttf b/addons/godot_xterm/fonts/Cousine-Bold.ttf similarity index 100% rename from addons/godot_xterm_native/fonts/Cousine-Bold.ttf rename to addons/godot_xterm/fonts/Cousine-Bold.ttf diff --git a/addons/godot_xterm_native/fonts/Cousine-BoldItalic.ttf b/addons/godot_xterm/fonts/Cousine-BoldItalic.ttf similarity index 100% rename from addons/godot_xterm_native/fonts/Cousine-BoldItalic.ttf rename to addons/godot_xterm/fonts/Cousine-BoldItalic.ttf diff --git a/addons/godot_xterm_native/fonts/Cousine-Italic.ttf b/addons/godot_xterm/fonts/Cousine-Italic.ttf similarity index 100% rename from addons/godot_xterm_native/fonts/Cousine-Italic.ttf rename to addons/godot_xterm/fonts/Cousine-Italic.ttf diff --git a/addons/godot_xterm_native/fonts/Cousine-Regular.ttf b/addons/godot_xterm/fonts/Cousine-Regular.ttf similarity index 100% rename from addons/godot_xterm_native/fonts/Cousine-Regular.ttf rename to addons/godot_xterm/fonts/Cousine-Regular.ttf diff --git a/addons/godot_xterm_native/fonts/LICENSE.txt b/addons/godot_xterm/fonts/LICENSE.txt similarity index 100% rename from addons/godot_xterm_native/fonts/LICENSE.txt rename to addons/godot_xterm/fonts/LICENSE.txt diff --git a/addons/godot_xterm/fonts/source_code_pro/OFL.txt b/addons/godot_xterm/fonts/source_code_pro/OFL.txt deleted file mode 100644 index 6f4c937..0000000 --- a/addons/godot_xterm/fonts/source_code_pro/OFL.txt +++ /dev/null @@ -1,93 +0,0 @@ -Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. - -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL - - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.tres b/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.tres deleted file mode 100644 index 6a95e02..0000000 --- a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.tres +++ /dev/null @@ -1,6 +0,0 @@ -[gd_resource type="DynamicFont" load_steps=2 format=2] - -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.ttf" type="DynamicFontData" id=1] - -[resource] -font_data = ExtResource( 1 ) diff --git a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.ttf b/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.ttf deleted file mode 100644 index c790e04..0000000 Binary files a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.ttf and /dev/null differ diff --git a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.tres b/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.tres deleted file mode 100644 index 41d8f3d..0000000 --- a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.tres +++ /dev/null @@ -1,6 +0,0 @@ -[gd_resource type="DynamicFont" load_steps=2 format=2] - -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.ttf" type="DynamicFontData" id=1] - -[resource] -font_data = ExtResource( 1 ) diff --git a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.ttf b/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.ttf deleted file mode 100644 index 0878199..0000000 Binary files a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.ttf and /dev/null differ diff --git a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.tres b/addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.tres deleted file mode 100644 index 033a34e..0000000 --- a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.tres +++ /dev/null @@ -1,6 +0,0 @@ -[gd_resource type="DynamicFont" load_steps=2 format=2] - -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.ttf" type="DynamicFontData" id=1] - -[resource] -font_data = ExtResource( 1 ) diff --git a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.ttf b/addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.ttf deleted file mode 100644 index 91a2a44..0000000 Binary files a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.ttf and /dev/null differ diff --git a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.tres b/addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.tres deleted file mode 100644 index 22109c0..0000000 --- a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.tres +++ /dev/null @@ -1,6 +0,0 @@ -[gd_resource type="DynamicFont" load_steps=2 format=2] - -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.ttf" type="DynamicFontData" id=1] - -[resource] -font_data = ExtResource( 1 ) diff --git a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.ttf b/addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.ttf deleted file mode 100644 index 3563e73..0000000 Binary files a/addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.ttf and /dev/null differ diff --git a/addons/godot_xterm/fonts/vt323/OFL.txt b/addons/godot_xterm/fonts/vt323/OFL.txt deleted file mode 100644 index 24e8149..0000000 --- a/addons/godot_xterm/fonts/vt323/OFL.txt +++ /dev/null @@ -1,93 +0,0 @@ -Copyright 2011, The VT323 Project Authors (peter.hull@oikoi.com) - -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL - - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/addons/godot_xterm/fonts/vt323/vt323_regular.tres b/addons/godot_xterm/fonts/vt323/vt323_regular.tres deleted file mode 100644 index a389a10..0000000 --- a/addons/godot_xterm/fonts/vt323/vt323_regular.tres +++ /dev/null @@ -1,3 +0,0 @@ -[gd_resource type="DynamicFont" format=2] - -[resource] diff --git a/addons/godot_xterm/fonts/vt323/vt323_regular.ttf b/addons/godot_xterm/fonts/vt323/vt323_regular.ttf deleted file mode 100644 index e838581..0000000 Binary files a/addons/godot_xterm/fonts/vt323/vt323_regular.ttf and /dev/null differ diff --git a/addons/godot_xterm_native/godot-cpp b/addons/godot_xterm/godot-cpp similarity index 100% rename from addons/godot_xterm_native/godot-cpp rename to addons/godot_xterm/godot-cpp diff --git a/addons/godot_xterm/godotxtermnative.gdnlib b/addons/godot_xterm/godotxtermnative.gdnlib new file mode 100644 index 0000000..2b32ce5 --- /dev/null +++ b/addons/godot_xterm/godotxtermnative.gdnlib @@ -0,0 +1,16 @@ +[general] + +singleton=false +load_once=true +symbol_prefix="godot_" +reloadable=true + +[entry] + +X11.64="res://addons/godot_xterm/bin/x11/libgodotxtermnative.so" +Server.64="res://addons/godot_xterm/bin/x11/libgodotxtermnative.so" + +[dependencies] + +X11.64=[ ] +Server.64=[ ] diff --git a/addons/godot_xterm/icon.svg b/addons/godot_xterm/icon.svg deleted file mode 100644 index 0f58b26..0000000 --- a/addons/godot_xterm/icon.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - diff --git a/addons/godot_xterm/input/text_decoder.gd b/addons/godot_xterm/input/text_decoder.gd deleted file mode 100644 index 6ea7155..0000000 --- a/addons/godot_xterm/input/text_decoder.gd +++ /dev/null @@ -1,266 +0,0 @@ -# Copyright (c) 2020 The GodotXterm authors. -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# License MIT -extends Reference - -# Convert a given to a utf8 PoolByteArray. -# The code for this function is based on the stackoverflow -# answer by user Schwern https://stackoverflow.com/a/42013984. -static func utf32_to_utf8(codepoint: int): - var utf8 = PoolByteArray([]) - - if codepoint <= 0x007F: - utf8.append(codepoint) - elif codepoint <= 0x07FF: - utf8.append(0b11000000 | codepoint >> 6 & 0b00011111) - utf8.append(0b10000000 | codepoint & 0b00111111) - elif codepoint <= 0xFFFF: - utf8.append(0b11100000 | codepoint >> 12 & 0b00001111) - utf8.append(0b10000000 | codepoint >> 6 & 0b00111111) - utf8.append(0b10000000 | codepoint & 0b00111111) - elif codepoint <= 0x10FFFF: - utf8.append(0b11110000 | codepoint >> 18 & 0b00000111) - utf8.append(0b10000000 | codepoint >> 12 & 0b00111111) - utf8.append(0b10000000 | codepoint >> 6 & 0b00111111) - utf8.append(0b10000000 | codepoint & 0b00111111) - else: - push_warning("Codepoint " + String(codepoint) + " is out of UTF-8 range") - - return utf8 - - -# Covert UTF32 char codes into a String. -# Basically the same as `char` but for multiple codepoints -# in a loop (which is a lot faster). -static func utf32_to_string(data: Array, start: int = 0, end: int = -1): - if end == -1: - end = data.size() - var result = '' - for i in range(start, end): - result += char(data[i]) - return result - - -# Utf8Decoder - decodes UTF8 byte sequences into UTF32 codepoints. -class Utf8ToUtf32: - var interim = PoolByteArray() - - func _init(): - interim.resize(3) - - # Clears interim bytes and resets decoder to clean state. - func clear(): - for i in interim.size(): - interim[i] = 0 - - # Decodes UTF8 byte sequences in `input` to UTF32 codepoints in `target`. - # The methods assumes stream input and will store partly transmitted bytes - # and decode them with the next data chunk. - # Note: The method does no bound checks for target, therefore make sure - # the provided data chunk does not exceed the size of `target`. - # Returns the number of written codepoints in `target`. - func decode(input: PoolByteArray, target: Array): - var length = input.size() - - if !length: - return 0 - - if length > target.size(): - target.resize(length) - - var size = 0 - var byte1: int - var byte2: int - var byte3: int - var byte4: int - var codepoint = 0 - var start_pos = 0 - - # handle leftover bytes - if interim[0]: - var discard_interim = false - var cp = interim[0] - cp &= 0x1F if (cp & 0xE0) == 0xC0 else 0x0F if (cp & 0xF0) == 0xE0 else 0x07 - var pos = 1 - var tmp = interim[pos] & 0x3F - while tmp && pos < 4: - cp <<= 6 - cp |= tmp - pos += 1 - tmp = interim[pos] & 0x3F if interim.size() < pos else 0 - # missing bytes - read from input - var type = 2 if (interim[0] & 0xE0) == 0xC0 else 3 if (interim[0] & 0xF0) == 0xE0 else 4 - var missing = type - pos - while start_pos < missing: - if start_pos >= length: - return 0 - tmp = input[start_pos] - start_pos += 1 - if (tmp & 0xC0) != 0x80: - # wrong continuation, discard interim bytes completely - start_pos -= 1 - discard_interim = true - break - else: - # need to save so we can continue short inputs in next call - interim[pos + 1] = tmp - pos += 1 - cp <<= 6 - cp |= tmp & 0x3F - if not discard_interim: - # final test is type dependent - match type: - 2: - if cp < 0x80: - # wrong starter byte - start_pos -= 1 - else: - target[size] = cp - size += 1 - 3: - if cp < 0x0800 or (cp >= 0xD800 and cp <= 0xDFFF): - # illegal codepoint - pass - else: - target[size] = cp - size += 1 - _: - if cp < 0x10000 or cp > 0x10FFFF: - # illegal codepoint - pass - else: - target[size] = cp - size += 1 - clear() - - # loop through input - var four_stop = length - 4 - var i = start_pos - while i < length: - # ASCII shortcut with loop unrolled to 4 consecutive ASCII chars. - # This is a compromise between speed gain for ASCII - # and penalty for non ASCII: - # For best ASCII performance the char should be stored directly into target, - # but even a single attempt to write to target and compare afterwards - # penalizes non ASCII really bad (-50%), thus we load the char into byteX first, - # which reduces ASCII performance by ~15%. - # This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible - # compared to the gains. - # Note that this optimization only takes place for 4 consecutive ASCII chars, - # for any shorter it bails out. Worst case - all 4 bytes being read but - # thrown away due to the last being a non ASCII char (-10% performance). - while i < four_stop: - byte1 = input[i] - byte2 = input[i + 1] - byte3 = input[i + 2] - byte4 = input[i + 3] - if not (byte1 & 0x80) | (byte2 & 0x80) | (byte3 & 0x80) | (byte4 & 0x80): - target[size] = byte1 - target[size+1] = byte2 - target[size+2] = byte3 - target[size+3] = byte4 - size += 4 - i += 4 - else: - break - - # reread byte1 - byte1 = input[i] - i += 1 - - # 1 byte - if byte1 < 0x80: - target[size] = byte1 - size += 1 - - # 2 bytes - elif (byte1 & 0xE0) == 0xC0: - if i >= length: - interim[0] = byte1 - return size - byte2 = input[i] - i+=1 - if (byte2 & 0xC0) != 0x80: - # wrong continuation - i-=1 - continue - codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F) - if (codepoint < 0x80): - # wrong starter byte - i-=1 - continue - target[size] = codepoint - size+=1 - - # 3 bytes - elif (byte1 & 0xF0) == 0xE0: - if i >= length: - interim[0] = byte1 - return size - byte2 = input[i] - i+=1 - if (byte2 & 0xC0) != 0x80: - # wrong continuation - i-=1 - continue - if i >= length: - interim[0] = byte1 - interim[1] = byte2 - return size - byte3 = input[i] - i+=1 - if (byte3 & 0xC0) != 0x80: - # wrong continuation - i-=1 - continue - codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F) - if codepoint < 0x0800 or (codepoint >=0xD800 and codepoint <= 0xDFFF): - # illegal codepoint, no i-- here - continue - target[size] = codepoint - size+=1 - - # 4 bytes - elif (byte1 & 0xF8) == 0xF0: - if i >= length: - interim[0] = byte1 - return size - byte2 = input[i] - i += 1 - if (byte2 & 0xC0) != 0x80: - # wrong continuation - i -= 1 - continue - if i >= length: - interim[0] = byte1 - interim[1] = byte2 - return size - byte3 = input[i] - i += 1 - if (byte3 & 0xC0) != 0x80: - # wrong continuation - i -= 1 - continue - if i >= length: - interim[0] = byte1 - interim[1] = byte2 - interim[2] = byte3 - return size - byte4 = input[i] - i += 1 - if (byte4 & 0xC0) != 0x80: - # wrong continuation - i -= 1 - continue - codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F) - if codepoint < 0x010000 or codepoint > 0x10FFFF: - # illegal codepoint, no i-- here - continue - target[size] = codepoint - size += 1 - else: - # illegal byte, just skip - pass - - target.resize(size) - return size diff --git a/addons/godot_xterm/input_handler.gd b/addons/godot_xterm/input_handler.gd deleted file mode 100644 index 11caaeb..0000000 --- a/addons/godot_xterm/input_handler.gd +++ /dev/null @@ -1,1491 +0,0 @@ -# Copyright (c) 2014 The xterm.js authors. All rights reserved. -# Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference -# The terminal's InputHandler, this handles all input from the Parser. -# -# Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand -# each function's header comment. - - -const Constants = preload("res://addons/godot_xterm/parser/constants.gd") -const BufferConstants = preload("res://addons/godot_xterm/buffer/constants.gd") -const Decoder = preload("res://addons/godot_xterm/input/text_decoder.gd") -const CellData = preload("res://addons/godot_xterm/buffer/cell_data.gd") -const AttributeData = preload("res://addons/godot_xterm/buffer/attribute_data.gd") -const EscapeSequenceParser = preload("res://addons/godot_xterm/parser/escape_sequence_parser.gd") -const Charsets = preload("res://addons/godot_xterm/data/charsets.gd") - -const Attributes = BufferConstants.Attributes -const C0 = Constants.C0 -const C1 = Constants.C1 -const FgFlags = BufferConstants.FgFlags -const BgFlags = BufferConstants.BgFlags -const UnderlineStyle = BufferConstants.UnderlineStyle -const CursorStyle = BufferConstants.CursorStyle -const CHARSETS = Charsets.CHARSETS -const Content = BufferConstants.Content - -const GLEVEL = {'(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2} -const MAX_PARSEBUFFER_LENGTH = 131072 -const STACK_LIMIT = 10 -var DEFAULT_ATTRIBUTE_DATA = AttributeData.new() - -signal line_fed -signal cursor_moved -signal bell_requested -signal refresh_rows_requested(start_row, end_row) -signal reset_requested -signal scroll_requested -signal windows_options_report_requested -signal scrollbar_sync_requested - -var _buffer_service -var _core_service -var _charset_service -var _options_service -var _parser - -var _parse_buffer: Array = [] -var _utf8_decoder = Decoder.Utf8ToUtf32.new() -var _cur_attr_data = AttributeData.new() -var _erase_attr_data_internal = AttributeData.new() -var _work_cell = CellData.new() -var _parse_thread: Thread = Thread.new() - -var _buffer setget ,_get_buffer -var buffer setget _set_buffer,_get_buffer - - -func _set_buffer(buffer) -> void: - buffer = buffer - - -func _get_buffer(): - return _buffer_service.buffer - - -func _init(buffer_service, core_service, charset_service, options_service, - parser = EscapeSequenceParser.new()): - _buffer_service = buffer_service - _core_service = core_service - _charset_service = charset_service - _options_service = options_service - _parser = parser - - buffer = _buffer_service.buffer - _buffer_service.connect("buffer_activated", self, "_set_buffer") - - # Print handler - _parser.set_print_handler(self, "print") - - # CSI handler - _parser.set_csi_handler({"final": "@"}, self, "insert_chars") - _parser.set_csi_handler({"intermediates": " ", "final": "@"}, self, "scroll_left") - _parser.set_csi_handler({"final": "A"}, self, "cursor_up") - _parser.set_csi_handler({"intermediates": " ", "final": "A"}, self, "scroll_right") - _parser.set_csi_handler({"final": "B"}, self, "cursor_down") - _parser.set_csi_handler({"final": "C"}, self, "cursor_forward") - _parser.set_csi_handler({"final": "D"}, self, "cursor_backward") - _parser.set_csi_handler({"final": "E"}, self, "cursor_nextLine") - _parser.set_csi_handler({"final": "F"}, self, "cursor_precedingLine") - _parser.set_csi_handler({"final": "G"}, self, "cursor_char_absolute") - _parser.set_csi_handler({"final": "H"}, self, "cursor_position") - _parser.set_csi_handler({"final": "I"}, self, "cursor_forward_tab") - _parser.set_csi_handler({"final": "J"}, self, "erase_in_display") - _parser.set_csi_handler({"prefix": "?", "final": "J"}, self, "erase_in_display") - _parser.set_csi_handler({"final": "K"}, self, "erase_in_line") - _parser.set_csi_handler({"prefix": "?", "final": "K"}, self, "erase_in_line") - _parser.set_csi_handler({"final": "L"}, self, "insert_lines") - _parser.set_csi_handler({"final": "M"}, self, "delete_lines") - _parser.set_csi_handler({"final": "P"}, self, "delete_chars") - _parser.set_csi_handler({"final": "S"}, self, "scroll_up") - _parser.set_csi_handler({"final": "T"}, self, "scroll_down") - _parser.set_csi_handler({"final": "X"}, self, "erase_chars") - _parser.set_csi_handler({"final": "Z"}, self, "cursor_backward_tab") - _parser.set_csi_handler({"final": "`"}, self, "char_pos_absolute") - _parser.set_csi_handler({"final": "a"}, self, "h_position_relative") - _parser.set_csi_handler({"final": "b"}, self, "repeat_preceding_character") - _parser.set_csi_handler({"final": "c"}, self, "send_device_attributes_primary") - _parser.set_csi_handler({"prefix": ">", "final": "c"}, self, "send_device_attributes_secondary") - _parser.set_csi_handler({"final": "d"}, self, "line_pos_absolute") - _parser.set_csi_handler({"final": "e"}, self, "v_position_relative") - _parser.set_csi_handler({"final": "f"}, self, "h_v_position") - _parser.set_csi_handler({"final": "g"}, self, "tab_clear") - _parser.set_csi_handler({"final": "h"}, self, "set_mode") - _parser.set_csi_handler({"prefix": "?", "final": "h"}, self, "set_mode_private") - _parser.set_csi_handler({"final": "l"}, self, "reset_mode") - _parser.set_csi_handler({"prefix": "?", "final": "l"}, self, "reset_mode_private") - _parser.set_csi_handler({"final": "m"}, self, "char_attributes") - _parser.set_csi_handler({"final": "n"}, self, "device_status") - _parser.set_csi_handler({"prefix": "?", "final": "n"}, self, "device_status_private") - _parser.set_csi_handler({"intermediates": "!", "final": "p"}, self, "soft_reset") - _parser.set_csi_handler({"intermediates": " ", "final": "q"}, self, "set_cursor_style") - _parser.set_csi_handler({"final": "r"}, self, "set_scroll_region") - _parser.set_csi_handler({"final": "s"}, self, "save_cursor") - _parser.set_csi_handler({"final": "t"}, self, "window_options") - _parser.set_csi_handler({"final": "u"}, self, "restore_cursor") - _parser.set_csi_handler({"intermediates": "\"", "final": "}"}, self, "insert_columns") - _parser.set_csi_handler({"intermediates": "\"", "final": "~"}, self, "delete_columns") - - # execute handler - _parser.set_execute_handler(C0.BEL, self, "bell") - _parser.set_execute_handler(C0.LF, self, "line_feed") - _parser.set_execute_handler(C0.VT, self, "line_feed") - _parser.set_execute_handler(C0.FF, self, "line_feed") - _parser.set_execute_handler(C0.CR, self, "carriage_return") - _parser.set_execute_handler(C0.BS, self, "backspace") - _parser.set_execute_handler(C0.HT, self, "tab"); - _parser.set_execute_handler(C0.SO, self, "shift_out") - _parser.set_execute_handler(C0.SI, self, "shift_in") - # FIXME: What to do with missing? Old code just added those to print - - _parser.set_execute_handler(C1.IND, self, "index") - _parser.set_execute_handler(C1.NEL, self, "next_line") - _parser.set_execute_handler(C1.HTS, self, "tab_set") - - # ESC handlers - _parser.set_esc_handler({"final": "7"}, self, "save_cursor") - _parser.set_esc_handler({"final": "8"}, self, "restore_cursor") - _parser.set_esc_handler({"final": "D"}, self, "index") - _parser.set_esc_handler({"final": "E"}, self, "next_line") - _parser.set_esc_handler({"final": "H"}, self, "tab_set") - _parser.set_esc_handler({"final": "M"}, self, "reverse_index") - _parser.set_esc_handler({"final": "="}, self, "keypad_application_mode") - _parser.set_esc_handler({"final": ">"}, self, "keypad_numeric_mode") - _parser.set_esc_handler({"final": "c"}, self, "full_reset") - _parser.set_esc_handler({"final": "n"}, self, "set_glevel", 2) - _parser.set_esc_handler({"final": "o"}, self, "set_glevel", 3) - _parser.set_esc_handler({"final": "|"}, self, "set_glevel", 3) - _parser.set_esc_handler({"final": "}"}, self, "set_glevel", 2) - _parser.set_esc_handler({"final": "~"}, self, "set_glevel", 1) - _parser.set_esc_handler({"intermediates": "%", "final": "@"}, self, "select_default_charset") - _parser.set_esc_handler({"intermediates": "%", "final": "G"}, self, "select_default_charset") - for flag in CHARSETS.keys(): - _parser.set_esc_handler({"intermediates": "(", "final": flag}, self, "select_charset", "(" + flag) - _parser.set_esc_handler({"intermediates": ")", "final": flag}, self, "select_charset", ")" + flag) - _parser.set_esc_handler({"intermediates": "*", "final": flag}, self, "select_charset", "*" + flag) - _parser.set_esc_handler({"intermediates": "+", "final": flag}, self, "select_charset", "+" + flag) - _parser.set_esc_handler({"intermediates": "-", "final": flag}, self, "select_charset", "-" + flag) - _parser.set_esc_handler({"intermediates": ".", "final": flag}, self, "select_charset", "." + flag) - _parser.set_esc_handler({"intermediates": "/", "final": flag}, self, "select_charset", "/" + flag) # TODO: supported? - _parser.set_esc_handler({"intermediates": "#", "final": "8"}, self, "screen_alignment_pattern") - - -#func parse(data) -> void: -# if _parse_thread.is_active(): -# _parse_thread.wait_to_finish() -# _parse_thread.start(self, "_parse_async", data) - - -func parse(data) -> void: - var buffer = _buffer_service.buffer - var cursor_start_x = buffer.x - var cursor_start_y = buffer.y - - var data_length = data.length() if typeof(data) == TYPE_STRING else data.size() - - # resize input buffer if needed - if _parse_buffer.size() < data_length and _parse_buffer.size() < MAX_PARSEBUFFER_LENGTH: - _parse_buffer.resize(min(data_length, MAX_PARSEBUFFER_LENGTH)) - - # process big data in smaller chunks - if data_length > MAX_PARSEBUFFER_LENGTH: - var i = 0 - while i < data_length: - var end = i + MAX_PARSEBUFFER_LENGTH if i + MAX_PARSEBUFFER_LENGTH < data_length else data_length - var length - match typeof(data): - TYPE_STRING: - length = _utf8_decoder.decode(data.to_utf8(), _parse_buffer) - TYPE_RAW_ARRAY: - length = _utf8_decoder.decode(data, _parse_buffer) - TYPE_ARRAY: - length = data.size() - _parse_buffer = data.duplicate() - _parser.parse(_parse_buffer, length) - i += MAX_PARSEBUFFER_LENGTH - else: - var length - match typeof(data): - TYPE_STRING: - length = _utf8_decoder.decode(data.to_utf8(), _parse_buffer) - TYPE_RAW_ARRAY: - length = _utf8_decoder.decode(data, _parse_buffer) - TYPE_ARRAY: - length = data.size() - _parse_buffer = data.duplicate() - _parser.parse(_parse_buffer, length) - - buffer = _buffer_service.buffer - if (buffer.x != cursor_start_x or buffer.y != cursor_start_y): - emit_signal("cursor_moved") - - # Refresh all rows. - emit_signal("refresh_rows_requested") - # TODO: Refresh only dirty rows accumulated as part of parsing. - - -func _exit_tree(): - _parse_thread.wait_to_finish() - - -func print(data: Array, start: int, end: int) -> void: - var code: int - var ch_width: int - var buffer = _buffer_service.buffer - var charset = _charset_service.charset - var screen_reader_mode = _options_service.options.screen_reader_mode - var cols = _buffer_service.cols - var wraparound_mode = true #TODO _core_service.modes.wraparound - var insert_mode = false # TODO FIXME! _core_service.modes.insert_mode - var cur_attr = _cur_attr_data - var buffer_row = buffer.lines.get_el(buffer.ybase + buffer.y) - - # TODO: dirtyRowService stuff - - # handle wide chars: reset start_cell-1 if we would overwrite the second cell of a wide char - if buffer.x and end - start > 0 and buffer_row.get_width(buffer.x - 1) == 2: - buffer_row.set_cell_from_codepoint(buffer.x - 1, 0, 1, cur_attr.fg, cur_attr.bg, cur_attr.extended) - - for pos in range(start, end): - code = data[pos] - - # calculate print space - # expensive call, therefore we save width in line buffer - ch_width = char(code).length() # FIXME - - # get charset replacement character - # charset is only defined for ASCII, therefore we only - # search for an replacement char if code < 127 - if code < 127 and charset: - var ch = charset.get(char(code)) - if ch: - code = ch.ord_at(0) - - if screen_reader_mode: - pass - # TODO: Handle A11y - - # insert combining char at last cursor position - # buffer.x should never be 0 for a combining char - # since they always follow a cell consuming char - # therefore we can test for buffer.x to avoid oveflow left - if (not ch_width) and buffer.x: - if not buffer_row.get_width(buffer.x - 1): - # found empty cell after full_width, need to go 2 cells back - # it is save to step 2 cells back here - # since an empty cell is only set by full_width chars - buffer_row.add_codepoint_to_cell(buffer.x - 2, code) - else: - buffer_row.add_codepoint_to_cell(buffer.x - 1, code) - continue - - # goto next line if ch would overflow - # NOTE: To avoid costly width checks here, - # the terminal does not allow a cols < 2 - if buffer.x + ch_width - 1 >= cols: - # autowrap - DECAWM - # automatically wraps to the beginning of the next line - if wraparound_mode: - while buffer.x < cols: - buffer_row.set_cell_from_codepoint(buffer.x, 0, 1, cur_attr.fg, cur_attr.bg, cur_attr.extended) - buffer.x += 1 - buffer.x = 0 - buffer.y += 1 - if buffer.y == buffer.scroll_bottom + 1: - buffer.y -= 1 - emit_signal("scroll_requested", _erase_attr_data(), true) - else: - if buffer.y >= _buffer_service.rows: - buffer.y = _buffer_service.rows - 1 - # The line already exists (e.g. the initial viewport), mark it as a - # wrapped line - buffer.lines.get_el(buffer.ybase + buffer.y).is_wrapped = true - # row changed, get it again - buffer_row = buffer.lines.get_el(buffer.ybase + buffer.y) - else: - buffer.x = cols - 1 - if ch_width == 2: - # FIXME: check for xterm behavior - # What to do here? We got a wide char that does not fit into last cell - continue - - # insert mode: move characters to right - if insert_mode: - # right shift cells according to the width - buffer_row.insert_cells(buffer.x, ch_width, buffer.get_null_cell(cur_attr), cur_attr) - # test last cell - since the last cell has only room for - # a halfwidth char any fullwidth shifted there is lost - # and will be set to empty cell - if buffer_row.get_width(cols - 1) == 2: - buffer_row.set_cell_from_codepoint(cols - 1, Constants.NULL_CELL_CODE, Constants.NULL_CELL_WIDTH, cur_attr.fg, cur_attr.bg, cur_attr.extended) - - # write current char to buffer and advance cursor - buffer_row.set_cell_from_codepoint(buffer.x, code, ch_width, cur_attr.fg, cur_attr.bg, cur_attr.extended) - buffer.x += 1 - - # fullwidth char - also set next cell to placeholder stub and advance cursor - # for graphemes bigger than fullwidth we can simply loop to zero - # we already made sure above, that buffer.x + ch_width will not overflow right - if ch_width > 0: - ch_width -= 1 - while ch_width: - # other than a regular empty cell a cell following a wide char has no width - buffer_row.set_cell_from_codepoint(buffer.x, 0, 0, cur_attr.fg, cur_attr.bg, cur_attr.extended) - buffer.x += 1 - ch_width -= 1 - - # Store last char in Parser.preceding_codepoint for REP to work correctly - # This needs to check whether: - # - fullwidth + surrogates: reset - # - combining: only base char gets carried on (bug in xterm?) - if end - start > 0: - buffer_row.load_cell(buffer.x - 1, _work_cell) - if _work_cell.get_width() == 2 or _work_cell.get_code() > 0xFFFF: - _parser.preceding_codepoint = 0 - elif _work_cell.is_combined(): - _parser.preceding_codepoint = _work_cell.get_chars().ord_at(0) - else: - _parser.preceding_codepoint = _work_cell.content - - # handle wide chars: reset cell to the right if it is second cell of a wide char - if buffer.x < cols and end - start > 0 and buffer_row.get_width(buffer.x) == 0 and not buffer_row.has_content(buffer.x): - buffer_row.set_cell_from_codepoint(buffer.x, 0, 1, cur_attr.fg, cur_attr.bg, cur_attr.extended) - - # TODO dirty row stuff - # _dirty_row_service.mark_dirty(buffer.y) - - -func bell(): - emit_signal("bell_requested") - - -func line_feed(): - var buffer = _buffer_service.buffer - - if _options_service.options.convert_eol: - buffer.x = 0 - buffer.y += 1 - if buffer.y == buffer.scroll_bottom + 1: - buffer.y -= 1 - emit_signal("scroll_requested", _erase_attr_data()) - elif buffer.y >= _buffer_service.rows: - buffer.y = _buffer_service.rows - 1 - # If the end of the line is hit, prevent this action from wrapping around to the next line. - if buffer.x >= _buffer_service.cols: - buffer.x -= 1 - - emit_signal("line_fed") - - -func carriage_return(): - _buffer_service.buffer.x = 0 - - -func backspace(): - var buffer = _buffer_service.buffer - - # reverse wrap-around is disabled - if not _core_service.dec_private_modes.reverse_wraparound: - _restrict_cursor() - if buffer.x > 0: - buffer.x -= 1 - return - - # reverse wrap-around is enabled - # other than for normal operation mode, reverse wrap-around allows the cursor - # to be at x=cols to be able to address the last cell of a row by BS - _restrict_cursor(_buffer_service.cols) - - if buffer.x > 0: - buffer.x -= 1 - else: - # reverse wrap-around handling: - # Our implementation deviates from xterm on purpose. Details: - # - only previous soft NLs can be reversed (is_wrapped=true) - # - only works within scrollborders (top/bottom, left/right not yet supported) - # - cannot peek into scrollbuffer - # - any cursor movement sequence keeps working as expected - if buffer.x == 0 \ - and buffer.y > buffer.scroll_top \ - and buffer.y <= buffer.scroll_bottom \ - and buffer.lines.get_el(buffer.ybase + buffer.y).is_wrapped: - buffer.lines.get_el(buffer.ybase + buffer.y).is_wrapped = false - buffer.y -= 1 - buffer.x = _buffer_service.cols - 1 - # find last taken cell - last can have 3 different states: - # - has_content(true) + has_width(1): narrow char - we are done - # - has_width(0): second part of a wide char - we are done - # - has_content(false) + has_width(1): empty cell due to early wrapping wide char, go one cell further back - var line = buffer.lines.get_el(buffer.ybase + buffer.y) - if line.has_width(buffer.x) and line.has_content(buffer.x): - buffer.x -= 1 - # We do this only once, since width=1 + has_content= false currently happens only once before - # early wrapping of a wide char. - # This needs to be fixed once we support graphemes taking more than 2 cells. - _restrict_cursor() - - -func tab(): - if _buffer_service.buffer.x >= _buffer_service.cols: - return - var original_x = _buffer_service.buffer.x - _buffer_service.buffer.x = _buffer_service.buffer.next_stop() - # TODO A11y - - -# SO -# Shift Out (Ctrl-N) -> Switch to Alternate Character Set. This invokes the -# G1 character set. -# -# @vt: #P[Only limited ISO-2022 charset support.] C0 SO "Shift Out" "\x0E" "Switch to an alternative character set." -func shift_out(): - _charset_service.set_glevel(1) - - -# SI -# Shift In (Ctrl-O) -> Switch to Standard Character Set. This invokes the G0 -# character set (the default). -# -# @vt: #Y C0 SI "Shift In" "\x0F" "Return to regular character set after Shift Out." -func shift_in(): - _charset_service.set_glevel(0) - - -func _restrict_cursor(max_col: int = _buffer_service.cols - 1) -> void: - var buffer = _buffer_service.buffer - - self._buffer.x = min(max_col, max(0, self._buffer.x)) - if _core_service.dec_private_modes.origin: - self._buffer.y = min(self._buffer.scroll_bottom, max(self._buffer.scroll_top, self._buffer.y)) - else: - self._buffer.y = min(_buffer_service.rows - 1, max(0, self._buffer.y)) - - # _dirty_row_service.mark_dirty(_buffer_service.buffer.y) - - -# Set absolute cursor position. -func _set_cursor(x: int, y: int) -> void: - # _dirty_row_service.mark_dirty(self._buffer.y) - if _core_service.dec_private_modes.origin: - self._buffer.x = x - self._buffer.y = self._buffer.scroll_top + y - else: - self._buffer.x = x - self._buffer.y = y - - -# Set relative cursor position. -func _move_cursor(x: int, y: int) -> void: - # for relative changes we have to make sure we are within 0 .. cols/rows - 1 - # before calculating the new position - _restrict_cursor() - _set_cursor(self._buffer.y + x, self._buffer.y + y) - - -# ESC D -# C1.IND -# DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html) -# Moves the cursor down one line in the same column. -# -# @vt: #Y C1 IND "Index" "\x84" "Move the cursor one line down scrolling if needed." -# @vt: #Y ESC IND "Index" "ESC D" "Move the cursor one line down scrolling if needed." -func index() -> void: - _restrict_cursor() - buffer.y += 1 - if buffer.y == buffer.scroll_bottom + 1: - buffer.y -= 1 - emit_signal("scroll_requested", _erase_attr_data()) - elif buffer.y >= _buffer_service.rows: - buffer.y = _buffer_service.rows - 1 - _restrict_cursor() - - -# ESC E -# C1.NEL -# DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL) -# Moves cursor to first position on next line. -# -# @vt: #Y C1 NEL "Next Line" "\x85" "Move the cursor to the beginning of the next row." -# @vt: #Y ESC NEL "Next Line" "ESC E" "Move the cursor to the beginning of the next row." -func next_line() -> void: - buffer.x = 0 - index() - - -# ESC = -# DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html) -# Enables the numeric keypad to send application sequences to the host. -func keypad_application_mode() -> void: - _core_service.dec_private_modes.application_keypad = true - emit_signal("scrollbar_sync_requested") - - -# ESC > -# DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html) -# Enables the keypad to send numeric characters to the host. -func keypad_numeric_mode() -> void: - _core_service.dec_private_modes.application_keypad = false - emit_signal("scrollbar_sync_requested") - - -# ESC % @ -# ESC % G -# Select default character set. UTF-8 is not supported (string are unicode anyways) -# therefore ESC % G does the same. -func select_default_charset() -> void: - _charset_service.set_glevel(0) - _charset_service.set_gcharset(0, Charsets.DEFAULT_CHARSET) # US (default) - - -# ESC ( C -# Designate G0 Character Set, VT100, ISO 2022. -# ESC ) C -# Designate G1 Character Set (ISO 2022, VT100). -# ESC * C -# Designate G2 Character Set (ISO 2022, VT220). -# ESC + C -# Designate G3 Character Set (ISO 2022, VT220). -# ESC - C -# Designate G1 Character Set (VT300). -# ESC . C -# Designate G2 Character Set (VT300). -# ESC / C -# Designate G3 Character Set (VT300). C = A -> ISO Latin-1 Supplemental. - Supported? -func select_charset(collect_and_flag: String) -> void: - if collect_and_flag.length() != 2: - select_default_charset() - return - - if collect_and_flag.substr(0, 1) == "/": - return # TODO: Is this supported? - - var g = GLEVEL[collect_and_flag.substr(0, 1)] - var charset = CHARSETS[collect_and_flag.substr(1, 1)] - _charset_service.set_gcharset(g, charset) - - -# ESC H -# C1.HTS -# DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html) -# Sets a horizontal tab stop at the column position indicated by -# the value of the active column when the terminal receives an HTS. -# -# @vt: #Y C1 HTS "Horizontal Tabulation Set" "\x88" "Places a tab stop at the current cursor position." -# @vt: #Y ESC HTS "Horizontal Tabulation Set" "ESC H" "Places a tab stop at the current cursor position." -func tab_set(): - buffer.tabs[buffer.x] = true - - -# CSI Ps @ -# Insert Ps (Blank) Character(s) (default = 1) (ICH). -# -# @vt: #Y CSI ICH "Insert Characters" "CSI Ps @" "Insert `Ps` (blank) characters (default = 1)." -# The ICH sequence inserts `Ps` blank characters. The cursor remains at the beginning of the blank characters. -# Text between the cursor and right margin moves to the right. Characters moved past the right margin are lost. -# -# -# FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual) -func insert_chars(params) -> void: - _restrict_cursor() - var line = buffer.lines.get_el(buffer.ybase + buffer.y) - if line: - line.insert_cells(buffer.x, params.get_param(0, 1), - buffer.get_null_cell(_erase_attr_data()), _erase_attr_data()) - - -# CSI Ps SP @ Scroll left Ps columns (default = 1) (SL) ECMA-48 -# -# Notation: (Pn) -# Representation: CSI Pn 02/00 04/00 -# Parameter default value: Pn = 1 -# SL causes the data in the presentation component to be moved by n character positions -# if the line orientation is horizontal, or by n line positions if the line orientation -# is vertical, such that the data appear to move to the left; where n equals the value of Pn. -# The active presentation position is not affected by this control function. -# -# Supported: -# - always left shift (no line orientation setting respected) -# -# @vt: #Y CSI SL "Scroll Left" "CSI Ps SP @" "Scroll viewport `Ps` times to the left." -# SL moves the content of all lines within the scroll margins `Ps` times to the left. -# SL has no effect outside of the scroll margins. -func scroll_left(params) -> void: - if buffer.y > buffer.scroll_bottom or buffer.y < buffer.scroll_top: - return - var param = params.get_param(0, 1) - for y in range(buffer.scroll_top, buffer.scroll_bottom + 1): - var line = buffer.lines.get_el(buffer.ybase + y) - line.delete_cells(0, param, buffer.get_null_cell(_erase_attr_data()), - _erase_attr_data()) - line.is_wrapped = false - - -func cursor_up(params) -> void: - # stop at scroll_top - var diff_to_top = self._buffer.y - self._buffer.scroll_top - if diff_to_top >= 0: - _move_cursor(0, -min(diff_to_top, params.get_param(0, 1))) - else: - _move_cursor(0, -params.get_param(0, 1)) - - -# CSI Ps SP A Scroll right Ps columns (default = 1) (SR) ECMA-48 -# -# Notation: (Pn) -# Representation: CSI Pn 02/00 04/01 -# Parameter default value: Pn = 1 -# SR causes the data in the presentation component to be moved by n character positions -# if the line orientation is horizontal, or by n line positions if the line orientation -# is vertical, such that the data appear to move to the right; where n equals the value of Pn. -# The active presentation position is not affected by this control function. -# -# Supported: -# - always right shift (no line orientation setting respected) -# -# @vt: #Y CSI SR "Scroll Right" "CSI Ps SP A" "Scroll viewport `Ps` times to the right." -# SL moves the content of all lines within the scroll margins `Ps` times to the right. -# Content at the right margin is lost. -# SL has no effect outside of the scroll margins. -func scroll_right(params) -> void: - if buffer.y > buffer.scroll_bottom or buffer.y < buffer.scroll_top: - return - var param = params.get_param(0, 1) - for y in range(buffer.scroll_top, buffer.scroll_bottom + 1): - var line = buffer.lines.get_el(buffer.ybase + y) - line.insert_cells(0, param, buffer.get_null_cell(_erase_attr_data()), - _erase_attr_data()) - line.is_wrapped = false - - -func cursor_down(params): - # stop at scroll_bottom - var diff_to_bottom = self._buffer.scroll_bottom - self._buffer.y - if diff_to_bottom >= 0: - _move_cursor(0, min(diff_to_bottom, params.get_param(0,1))) - else: - _move_cursor(0, params.get_param(0, 1)) - - -func cursor_forward(params): - _move_cursor(params.get_param(0, 1), 0) - - -func cursor_backward(params): - _move_cursor(-params.get_param(0, 1), 0) - - -func cursor_next_line(params): - cursor_down(params) - self._buffer.x = 0 - - -func cursor_preceding_line(params): - cursor_up(params) - self._buffer.x = 0 - - -func cursor_char_absolute(params): - _set_cursor(params.get_param(0, 1) - 1, self._buffer.y) - - -func cursor_position(params): - _set_cursor( - # col - (params.get_param(1, 1)) - 1 if params.length >= 2 else 0, - # row - (params.get_param(0, 1)) - 1 - ) - - -func char_pos_absolute(params) -> void: - _set_cursor(params.get_param(0, 1) - 1, self._buffer.y) - - -func h_position_relative(params): - _move_cursor(params.get_param(0, 1), 0) - - -func line_pos_absolute(params): - _set_cursor(self._buffer.x, params.get_param(0, 1) - 1) - - -func v_position_relative(params): - _move_cursor(0, params.get_param(0, 1)) - - -func h_v_position(params): - cursor_position(params) - - -# CSI Ps g Tab Clear (TBC). -# Ps = 0 -> Clear Current Column (default). -# Ps = 3 -> Clear All. -# Potentially: -# Ps = 2 -> Clear Stops on Line. -# http://vt100.net/annarbor/aaa-ug/section6.html -# -# @vt: #Y CSI TBC "Tab Clear" "CSI Ps g" "Clear tab stops at current position (0) or all (3) (default=0)." -# Clearing tabstops off the active row (Ps = 2, VT100) is currently not supported. -func tab_clear(params) -> void: - match params.get_param(0): - 3: - self._buffer.tabs = {} - 0, _: - self._buffer.tabs.erase(self._buffer.x) - - -# CSI Ps I -# Cursor Forward Tabulation Ps tab stops (default = 1) (CHT). -# -# @vt: #Y CSI CHT "Cursor Horizontal Tabulation" "CSI Ps I" "Move cursor `Ps` times tabs forward (default=1)." -func cursor_forward_tab(params) -> void: - if self._buffer.x >= self._buffer.cols: - return - var param = params.get_param(0, 1) - while param: - self._buffer.x = self._buffer.next_stop() - param -= 1 - - -func cursor_backward_tab(params) -> void: - if self._buffer.x >= _buffer_service.cols: - return - var param = params.get_param(0, 1) - while param: - self._buffer.x = self._buffer.buffer.prev_stop() - param -= 1 - - -# Helper method to erase cells in a terminal row. -# The cell gets replaced with the eraseChar of the terminal. -# params: -# - `y` row index -# - `start` first cell index to be erased -# - `end` end - 1 is last erased cell -func _erase_in_buffer_line(y: int, start: int, end: int, clear_wrap: bool = false) -> void: - var line = self._buffer.lines.get_el(self._buffer.ybase + y) - line.replace_cells(start, end, self._buffer.get_null_cell(_erase_attr_data()), - _erase_attr_data()) - if clear_wrap: - line.is_wrapped = false - - -# Helper method to reset cells in a terminal row. -# The cell gets replaced with the eraseChar of the terminal and the isWrapped property is set to false. -# @param y row index -func _reset_buffer_line(y: int) -> void: - var line = buffer.lines.get_line(buffer.ybase + y) - line.fill(buffer.get_null_cell(_erase_attr_data())) - line.is_wrapped = false - - -func erase_in_display(params) -> void: - _restrict_cursor() - var j - match params.get_param(0): - 0: - j = buffer.y - # _dirty_row_service.mark_dirty(j) - _erase_in_buffer_line(j, buffer.x, _buffer_service.cols, buffer.x == 0) - j += 1 - while j < _buffer_service.rows: - _reset_buffer_line(j) - j += 1 - # _dirty_row_service.mark_dirty(j) - 1: - j = buffer.y - # _dirty_row_service.mark_dirty(j) - # Deleted front part of line and everything before. This line will no longer be wrapped. - _erase_in_buffer_line(j, 0, buffer.x + 1, true) - if buffer.x + 1 >= _buffer_service.cols: - # Deleted entire previous line. This next line can no longer be wrapped. - buffer.lines.get_el(j + 1).is_wrapped = false - while j > 0: - j -= 1 - _reset_buffer_line(j) - # _dirty_row_service.mark_dirty(0) - 2: - j = _buffer_service.rows - # _dirty_row_service.mark_dirty(j - 1) - while j > 0: - j -= 1 - _reset_buffer_line(j) - # _dirty_row_sevice.mark_dirty(0) - 3: - # Clear scrollback (everything not in viewport) - var scrollback_size = self._buffer.lines.length - _buffer_service.rows - if scrollback_size > 0: - self._buffer.lines.trim_start(scrollback_size) - self._buffer.ybase = max(self._buffer.ybase - scrollback_size, 0) - self._buffer.ydisp = max(self._buffer.ydisp - scrollback_size, 0) - # Force a scroll to refresh viewport - emit_signal("scroll_requested", 0) - - -func erase_in_line(params): - _restrict_cursor() - match params.get_param(0): - 0: - _erase_in_buffer_line(buffer.y, buffer.x, _buffer_service.cols) - 1: - _erase_in_buffer_line(buffer.y, 0, buffer.x + 1) - 2: - _erase_in_buffer_line(buffer.y, 0, _buffer_service.cols) - - -# CSI Ps L -# Insert Ps Line(s) (default = 1) (IL). -# -# @vt: #Y CSI IL "Insert Line" "CSI Ps L" "Insert `Ps` blank lines at active row (default=1)." -# For every inserted line at the scroll top one line at the scroll bottom gets removed. -# The cursor is set to the first column. -# IL has no effect if the cursor is outside the scroll margins. -func insert_lines(params) -> void: - _restrict_cursor() - var param = params.get_param(0, 1) - - if buffer.y > buffer.scroll_bottom or buffer.y < buffer.scroll_top: - return - - var row: int = buffer.ybase + buffer.y - var scroll_bottom_row_offset = _buffer_service.rows - 1 - buffer.scroll_bottom - var scroll_bottom_absolute = _buffer_service.rows - 1 + buffer.ybase - scroll_bottom_row_offset + 1 - - while param: - # test: echo -e '\e[44m\e[1L\e[0m' - # blank_line(true) - xterm/linux behavior - buffer.lines.splice(scroll_bottom_absolute - 1, 1) - buffer.lines.splice(row, 0, [buffer.get_blank_line(_erase_attr_data())]) - param -= 1 - - buffer.x = 0 # see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only? - - -# CSI Ps M -# Delete Ps Line(s) (default = 1) (DL). -# -# @vt: #Y CSI DL "Delete Line" "CSI Ps M" "Delete `Ps` lines at active row (default=1)." -# For every deleted line at the scroll top one blank line at the scroll bottom gets appended. -# The cursor is set to the first column. -# DL has no effect if the cursor is outside the scroll margins. -func delete_lines(params) -> void: - _restrict_cursor() - var param = params.get_param(0, 1) - - if buffer.y > buffer.scroll_bottom or buffer.y < buffer.scroll_top: - return - - var row: int = buffer.ybase + buffer.y - - var j: int - j = _buffer_service.rows - 1 - buffer.scroll_bottom - j = _buffer_service.rows - 1 + buffer.ybase - j - - while param: - # test echo -e '\e[44m\e[1M\e[0m' - # blank_line(true) - xterm/linux behavior - buffer.lines.splice(row, 1) - buffer.lines.splice(j, 0, [buffer.get_blank_line(_erase_attr_data())]) - param -= 1 - - -# CSI Ps P -# Delete Ps Character(s) (default = 1) (DCH). -# -# @vt: #Y CSI DCH "Delete Character" "CSI Ps P" "Delete `Ps` characters (default=1)." -# As characters are deleted, the remaining characters between the cursor and right margin move to the left. -# Character attributes move with the characters. The terminal adds blank characters at the right margin. -# -# -# FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual) -func delete_chars(params) -> void: - _restrict_cursor() - var line = buffer.lines.get_el(buffer.ybase + buffer.y) - if line: - line.delete_cells(buffer.x, params.get_param(0, 1), - buffer.get_null_cell(_erase_attr_data()), _erase_attr_data()) - #_dirty_row_service.markDirty(buffer.y) - - -# CSI Ps S Scroll up Ps lines (default = 1) (SU). -# -# @vt: #Y CSI SU "Scroll Up" "CSI Ps S" "Scroll `Ps` lines up (default=1)." -# -# -# FIXME: scrolled out lines at top = 1 should add to scrollback (xterm) -func scroll_up(params) -> void: - var param = params.get_param(0, 1) - while param: - buffer.lines.splice(buffer.ybase + buffer.scroll_top, 1) - buffer.lines.splice(buffer.ybase + buffer.scroll_bottom, 0, - [buffer.get_blank_line(_erase_attr_data())]) - param -= 1 - - -# CSI Ps T Scroll down Ps lines (default = 1) (SD). -# -# @vt: #Y CSI SD "Scroll Down" "CSI Ps T" "Scroll `Ps` lines down (default=1)." -func scroll_down(params) -> void: - var param = params.get_param(0, 1) - while param: - buffer.lines.splice(buffer.ybase + buffer.scroll_bottom, 1) - buffer.lines.splice(buffer.ybase + buffer.scroll_top, 0, - buffer.get_blank_line(DEFAULT_ATTRIBUTE_DATA)) - param -= 1 - - -func erase_chars(params) -> void: - _restrict_cursor() - var line = buffer.lines.get_el(buffer.ybase + buffer.y) - if line: - line.replace_cells(buffer.x, buffer.x + params.get_param(0, 1), - buffer.get_null_cell(_erase_attr_data()), _erase_attr_data()) - #this._dirtyRowService.markDirty(this._bufferService.buffer.y) - - -func repeat_preceding_character(params) -> void: - if not _parser.preceding_codepoint: - return - # call print to insert the chars and handle correct wrapping - var length = params.get_param(0, 1) - var data = [] - for _i in range(length): - data.append(_parser.preceding_codepoint) - self.print(data, 0, length) - - -func send_device_attributes_primary(params): - # TODO - pass - - -func send_device_attributes_secondary(params): - # TODO - pass - - -func set_mode(params): - # TODO - pass - - -func reset_mode(params) -> void: - for param in params.params: - match param: - 4: - _core_service.modes.insert_mode = false - 20: - #this._t.convertEol = false - pass - - -func char_attributes(params): - # Optimize a single SGR0 - if params.length == 1 and params.get_param(0) == 0: - _cur_attr_data.fg = AttributeData.new().fg - _cur_attr_data.bg = AttributeData.new().bg - return - - var attr = _cur_attr_data - - for i in range(params.length): - var p = params.get_param(i) - if p >= 30 and p <= 37: - # fg color 8 - attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK) - attr.fg |= Attributes.CM_P16 | (p - 30) - elif p >= 40 and p <= 47: - # bg color 8 - attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK) - attr.bg |= Attributes.CM_P16 | (p - 40) - elif p >= 90 and p <= 97: - # fg color 16 - attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK) - attr.fg |= Attributes.CM_P16 | (p - 90) | 8 - elif p >= 100 and p <= 107: - # bg color 16 - attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK) - attr.bg |= Attributes.CM_P16 | (p - 100) | 8 - elif p == 0: - # default - attr.fg = DEFAULT_ATTRIBUTE_DATA.fg - attr.bg = DEFAULT_ATTRIBUTE_DATA.bg - elif p == 1: - # bold text - attr.fg |= FgFlags.BOLD - elif p == 3: - # italic text - attr.bg |= BgFlags.ITALIC - elif p == 4: - # underlined text - attr.fg |= FgFlags.UNDERLINE - _process_underline(params.get_sub_params(i)[0] if params.has_sub_params(i) else UnderlineStyle.SINGLE, attr) - elif p == 5: - # blink - # test with: echo -e '\e[5mblink\e[m' - attr.fg |= FgFlags.BLINK - elif p == 7: - # inverse and positive - # test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m' - attr.fg |= FgFlags.INVERSE - elif p == 8: - # invisible - attr.fg |= FgFlags.INVISIBLE - elif p == 2: - # dimmed text - attr.bg |= BgFlags.DIM - elif p == 21: - # double underline - _process_underline(UnderlineStyle.DOUBLE, attr) - elif p == 22: - # not bold nor faint - attr.fg &= ~FgFlags.BOLD - attr.bg &= ~BgFlags.DIM - elif p == 23: - # not italic - attr.bg &= ~BgFlags.ITALIC - elif p == 24: - # not underlined - attr.fg &= ~FgFlags.UNDERLINE - elif p == 25: - # not blink - attr.fg &= ~FgFlags.BLINK - elif p == 27: - # not inverse - attr.fg &= ~FgFlags.INVERSE - elif p == 28: - # not invisible - attr.fg &= ~FgFlags.INVISIBLE - elif p == 39: - # reset fg - attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK) - attr.fg |= AttributeData.new().fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK) - elif p == 49: - # reset bg - attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK) - attr.bg |= AttributeData.new().bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK) - elif p == 38 or p == 48 or p == 58: - # fg color 256 and RGB - i += _extract_color(params, i, attr) - elif p == 59: - attr.extended = attr.extended.duplicate() - attr.extended.underline_color = -1 - attr.update_extended() - elif p == 100: # FIXME: dead branch, p=100 already handled above! - # TODO reset fg/bg - pass - - -func device_status(params): - # TODO - pass - - -func device_status_private(params): - # TODO - pass - - -# CSI ! p Soft terminal reset (DECSTR). -# http://vt100.net/docs/vt220-rm/table4-10.html -# -# @vt: #Y CSI DECSTR "Soft Terminal Reset" "CSI ! p" "Reset several terminal attributes to initial state." -# There are two terminal reset sequences - RIS and DECSTR. While RIS performs almost a full terminal bootstrap, -# DECSTR only resets certain attributes. For most needs DECSTR should be sufficient. -# -# The following terminal attributes are reset to default values: -# - IRM is reset (dafault = false) -# - scroll margins are reset (default = viewport size) -# - erase attributes are reset to default -# - charsets are reset -# - DECSC data is reset to initial values -# - DECOM is reset to absolute mode -# -# -# FIXME: there are several more attributes missing (see VT520 manual) -func soft_reset(params): - _core_service.is_cursor_hidden = false - emit_signal("scrollbar_sync_requested") - buffer.scroll_top = 0 - buffer.scroll_bottom = _buffer_service.rows - 1 - _cur_attr_data = DEFAULT_ATTRIBUTE_DATA - _core_service.reset() - _charset_service.reset() - - # reset DECSC data - buffer.saved_x = 0 - buffer.saved_y = buffer.ybase - buffer.saved_cur_attr_data.fg = _cur_attr_data.fg - buffer.saved_cur_attr_data.bg = _cur_attr_data.bg - buffer.saved_charset = _charset_service.charset - - # reset DECOM - _core_service.dec_private_modes.origin = false - - -# CSI Ps SP q Set cursor style (DECSCUSR, VT520). -# Ps = 0 -> blinking block. -# Ps = 1 -> blinking block (default). -# Ps = 2 -> steady block. -# Ps = 3 -> blinking underline. -# Ps = 4 -> steady underline. -# Ps = 5 -> blinking bar (xterm). -# Ps = 6 -> steady bar (xterm). -# -# @vt: #Y CSI DECSCUSR "Set Cursor Style" "CSI Ps SP q" "Set cursor style." -# Supported cursor styles: -# - empty, 0 or 1: steady block -# - 2: blink block -# - 3: steady underline -# - 4: blink underline -# - 5: steady bar -# - 6: blink bar -func set_cursor_style(params) -> void: - var param = params.get_param(0, 1) - - match param: - 1, 2: - _options_service.options.cursor_style = CursorStyle.BLOCK - 3, 4: - _options_service.options.cursor_style = CursorStyle.UNDERLINE - 5, 6: - _options_service.options.cursor_style = CursorStyle.BAR - - var is_blinking = param % 2 == 1 - _options_service.options.cursor_blink = is_blinking - - -func set_scroll_region(params) -> void: - var top = params.get_param(0, 1) - var bottom = params.get_param(1, 0) - - if bottom > _buffer_service.rows or bottom == 0: - bottom = _buffer_service.rows - - if bottom > top: - buffer.scroll_top = top - 1 - buffer.scroll_bottom = bottom - 1 - _set_cursor(0, 0) - - -func save_cursor(params = null): - self._buffer.saved_x = self._buffer.x - self._buffer.saved_y = self._buffer.ybase + self._buffer.y - self._buffer.saved_cur_attr_data.fg = _cur_attr_data.fg - self._buffer.saved_cur_attr_data.bg = _cur_attr_data.bg - self._buffer.saved_charset = _charset_service.charset - - -func window_options(params): - var second = params.get_param(1, 0) - match params.get_param(0): - 14: - pass - 16: - pass - 18: - pass - 22: - pass - 23: - pass - - -# CSI Pm ' } -# Insert Ps Column(s) (default = 1) (DECIC), VT420 and up. -# -# @vt: #Y CSI DECIC "Insert Columns" "CSI Ps ' }" "Insert `Ps` columns at cursor position." -# DECIC inserts `Ps` times blank columns at the cursor position for all lines with the scroll margins, -# moving content to the right. Content at the right margin is lost. -# DECIC has no effect outside the scrolling margins. -func insert_columns(params): - if buffer.y > buffer.scroll_bottom or buffer.y < buffer.scroll_top: - return - - var param = params.get_param(0, 1) - - for y in range(buffer.scroll_top, buffer.scroll_bottom + 1): - var line = buffer.lines.get_el(buffer.ybase + y) - line.insert_cells(buffer.x, param, buffer.get_null_cells(_erase_attr_data()), - _erase_attr_data()) - line.is_wrapped = false - - -# CSI Pm ' ~ -# Delete Ps Column(s) (default = 1) (DECDC), VT420 and up. -# -# @vt: #Y CSI DECDC "Delete Columns" "CSI Ps ' ~" "Delete `Ps` columns at cursor position." -# DECDC deletes `Ps` times columns at the cursor position for all lines with the scroll margins, -# moving content to the left. Blank columns are added at the right margin. -# DECDC has no effect outside the scrolling margins. -func delete_columns(params): - if buffer.y > buffer.scroll_bottom or buffer.y < buffer.scroll_top: - return - - var param = params.get_param(0, 1) - - for y in range(buffer.scroll_top, buffer.scroll_bottom + 1): - var line = buffer.lines.get_el(buffer.ybase + y) - line.delete_cells(buffer.x, param, buffer.get_null_cells(_erase_attr_data()), - _erase_attr_data()) - line.is_wrapped = false - - -func set_mode_private(params) -> void: - for param in params.params: - match param: - 1: - _core_service.dec_private_modes.application_cursor_keys = true - 2: - _charset_service.set_gcharset(0, Charsets.DEFAULT_CHARSET) - _charset_service.set_gcharset(1, Charsets.DEFAULT_CHARSET) - _charset_service.set_gcharset(2, Charsets.DEFAULT_CHARSET) - _charset_service.set_gcharset(3, Charsets.DEFAULT_CHARSET) - # set VT100 mode here - 3: - # DECCOLM - 132 column mode. - # This is only active if 'set_win_lines' (24) is enabled - # through `options.window_options`. - if _options_service.options.window_options.set_win_lines: - _buffer_service.resize(132, _buffer_service.rows) - emit_signal("reset_requested") - 6: - _core_service.dec_private_modes.origin = true - _set_cursor(0, 0) - 7: - _core_service.dec_private_modes.wraparound = true - 12: - # cursor_blink = true - # TODO handle cursor blink - pass - 45: - _core_service.dec_private_modes.reverse_wraparound = true - 66: - _core_service.dec_private_modes.application_keypad = true - emit_signal("scrollbar_sync_requested") - 9: # X10 Mouse - # no release, no motion, no wheel, no modifiers. - # _core_mouse_service.active_protocal = 'X10' - # TODO - pass - 1000: # vt200 mouse - pass - 1002: # button event mouse - pass - 1003: # any event mouse - pass - 1004: # send focusin/focusout events - # focusin: ^[[I - # focusout: ^[[O - _core_service.dec_private_modes.send_focus = true - 1005: # utf8 ext mode mouse - removed in # 2507 - pass - 1006: # sgr ext mode mouse - pass - 1015: - pass - 25: # show cursor - _core_service.is_cursor_hidden = false - 1048: # alt screen cursor - save_cursor() - 1049: # alt screen buffer cursor - save_cursor() - continue - 47, 1047, 1049: # alt screen buffer - _buffer_service.buffers.activate_alt_buffer(_erase_attr_data()) - _core_service.is_cursor_initialized = true - emit_signal("refresh_rows_requested", 0, _buffer_service.rows - 1) - emit_signal("scrollbar_sync_requested") - 2004: # bracketed paste mode (https://cirw.in/blog/bracketed-paste) - _core_service.dec_private_modes.bracketed_paste_mode = true - - -func reset_mode_private(params): - for param in params.to_array(): - match param: - 1: - _core_service.dec_private_modes.application_cursor_keys = false - 3: - # DECCOLM - 80 column mode. - # This is only active if 'set_win_lines' (24) is enabled - # through `options.windows_options`. - if _options_service.options.window_options.get("set_win_lines", false): - _buffer_service.resize(80, _buffer_service.rows) - emit_signal("reset_requested") - 6: - _core_service.dec_private_modes.origin = false - _set_cursor(0, 0) - 7: - _core_service.dec_private_modes.wraparound = false - 12: - # cursor_blink = false - # TODO: Handle cursor_blink - pass - 45: - _core_service.dec_private_modes.reverse_wraparound = false - 66: - _core_service.dec_private_modes.application_keypad = false - emit_signal("scrollbar_sync_requested") - 9, 1000, 1002, 1003: - # X10 Mouse, vt200 mouse, button event mouse and any event mouse respectively. - # TODO: Core mouse service - # _core_mouse_service.active_protocal = "NONE" - pass - 1004: # send focusin/focusout events - _core_service.dec_private_modes.send_focus = false - 1005: # utf8 ext mode mouse - removed in #2507 - pass - 1006: # sgr ext mode mouse - # TODO - pass - 1015: # urxvt ext mode mouse - removed in #2507 - pass - 25: # hide cursor - _core_service.is_cursor_hidden = true - pass - 1048: # alt screen cursor - restore_cursor() - 1049, 47, 1047: - # Ensure the selection manager has the correct buffer. - _buffer_service.buffers.activate_normal_buffer() - if param == 1049: - restore_cursor() - _core_service.is_cursor_initialized = true - emit_signal("refresh_rows_requested", 0, _buffer_service.rows - 1) - emit_signal("scrollbar_sync_requested") - 2004: # bracketed paste mode (https://cirw.in/blog/bracketed-paste) - _core_service.dec_private_modes.bracketed_paste_mode = false - - -# Helper to write color information packed with color mode. -func _update_attr_color(color: int, mode: int, c1: int, c2: int, c3: int) -> int: - if mode == 2: - color |= Attributes.CM_RGB - color &= ~Attributes.RGB_MASK - color |= AttributeData.from_color_rgb([c1, c2, c3]) - elif mode == 5: - color &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK) - color |= Attributes.CM_P256 | (c1 & 0xff) - return color - - -# Helper to extract and apply color params/subparams. -# Returns advance for params index. -func _extract_color(params, pos: int, attr) -> int: - # normalize params - # meaning: [target, CM, ign, val, val, val] - # RGB : [ 38/34, 2, ign, r, g, b] - # P256 : [ 38/34, 5, ign, v, ign, ign] - var accu = [0, 0, -1, 0, 0, 0] - - # alignment placeholder for non color space sequences - var c_space = 0 - - # return advance we took in params - var advance = -1 - - while advance + pos < params.length and advance + c_space < accu.size(): - accu[advance + c_space] = params.get_param(pos + advance) - advance += 1 - # TODO FIX and FINISH me - return advance - - -func restore_cursor(params = null) -> void: - self._buffer.x = self._buffer.saved_x if self._buffer.saved_x else 0 - self._buffer.y = max(self._buffer.saved_y - self._buffer.ybase, 0) - _cur_attr_data.fg = self._buffer.saved_cur_attr_data.fg - _cur_attr_data.bg = self._buffer.saved_cur_attr_data.bg - # FIXME _charset_service.charset = _saved_charset - if self._buffer.saved_charset: - _charset_service.charset = self._buffer.saved_charset - _restrict_cursor() - - -# ESC M -# C1.RI -# DEC mnemonic: HTS -# Moves the cursor up one line in the same column. If the cursor is at the top margin, -# the page scrolls down. -# -# @vt: #Y ESC IR "Reverse Index" "ESC M" "Move the cursor one line up scrolling if needed." -# -func reverse_index() -> void: - _restrict_cursor() - if buffer.y == buffer.scroll_top: - # possibly move the code below to term.reverse_srcoll() - # test: echo -ne '\e[1;1H\e[44m\eM\e[0m' - # blank_line(true) is xterm/linux behavior - var scroll_region_height = buffer.scroll_bottom - buffer.scroll_top - buffer.lines.shift_elements(buffer.ybase + buffer.y, scroll_region_height, 1) - buffer.lines.set_line(buffer.ybase + buffer.y, buffer.get_blank_line(_erase_attr_data())) - else: - buffer.y -= 1 - _restrict_cursor() # quickfix to not run out of bounds - - -# ESC c -# DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html) -# Reset to initial state. -func full_reset() -> void: - _parser.reset() - emit_signal("reset_requested") - - -func reset() -> void: - _cur_attr_data = DEFAULT_ATTRIBUTE_DATA - _erase_attr_data_internal = DEFAULT_ATTRIBUTE_DATA - - -func _process_underline(style: int, attr) -> void: - # treat extended attrs as immutable, thus always clone from old one - # this is needed since the buffer only holds references to it - attr.extended = attr.extended.duplicate() - - # default to 1 == single underline - if not ~style or style > 5: - style = 1 - attr.extended.underline_style = style - attr.fg |= FgFlags.UNDERLINE - - # 0 deactivates underline - if style == 0: - attr.fg &= ~FgFlags.UNDERLINE - - # update HAS_EXTENDED in BG - attr.update_extended() - - - -# back_color_erase feature for xterm. -func _erase_attr_data(): - _erase_attr_data_internal.bg &= ~(Attributes.CM_MASK | 0xFFFFFF) - _erase_attr_data_internal.bg |= _cur_attr_data.bg & ~0xFC000000 - return _erase_attr_data_internal - - -# ESC # 8 -# DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html) -# This control function fills the complete screen area with -# a test pattern (E) used for adjusting screen alignment. -# -# @vt: #Y ESC DECALN "Screen Alignment Pattern" "ESC # 8" "Fill viewport with a test pattern (E)." -func screen_alignment_pattern() -> void: - # prepare cell data - var cell = CellData.new() - cell.content = 1 << Content.WIDTH_SHIFT | 'E'.ord_at(0) - cell.fg = _cur_attr_data.fg - cell.bg = _cur_attr_data.bg - - _set_cursor(0, 0) - - for y_offset in range(0, _buffer_service.rows): - var row = buffer.ybase + buffer.y + y_offset - var line = buffer.lines.get_line(row) - if line: - line.fill(cell) - line.is_wrapped = false - _set_cursor(0, 0) diff --git a/addons/godot_xterm_native/libtsm b/addons/godot_xterm/libtsm similarity index 100% rename from addons/godot_xterm_native/libtsm rename to addons/godot_xterm/libtsm diff --git a/addons/godot_xterm/parser/constants.gd b/addons/godot_xterm/parser/constants.gd deleted file mode 100644 index 6ef558c..0000000 --- a/addons/godot_xterm/parser/constants.gd +++ /dev/null @@ -1,131 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - -# Psuedo-character placeholder for non-ascii characters (unicode). -const NON_ASCII_PRINTABLE = 0xa0 - -# Payload limit for OSC and DCS. -const PAYLOAD_LIMIT = 10000000 - -# Internal states of EscapeSequenceParser. -enum ParserState { - GROUND - ESCAPE - ESCAPE_INTERMEDIATE - CSI_ENTRY - CSI_PARAM - CSI_INTERMEDIATE - CSI_IGNORE - SOS_PM_APC_STRING - OSC_STRING - DCS_ENTRY - DCS_PARAM - DCS_IGNORE - DCS_INTERMEDIATE - DCS_PASSTHROUGH -} - -# Internal actions of EscapeSequenceParser. -enum ParserAction { - IGNORE - ERROR - PRINT - EXECUTE - OSC_START - OSC_PUT - OSC_END - CSI_DISPATCH - PARAM - COLLECT - ESC_DISPATCH - CLEAR - DCS_HOOK - DCS_PUT - DCS_UNHOOK -} - - # Internal states of OscParser. -enum OscState { - START - ID - PAYLOAD - ABORT -} - -# C0 control codes -# See: https://en.wikipedia.org/wiki/C0_and_C1_control_codes#C0_controls -enum C0 { - NUL - SOH - STX - ETX - EOT - ENQ - ACK - BEL - BS - HT - LF - VT - FF - CR - SO - SI - DLE - DC1 - DC2 - DC3 - DC4 - NAK - SYN - ETB - CAN - EM - SUB - ESC - FS - GS - RS - US - SP - DEL = 0x7f -} - -# C1 control codes -# See: https://en.wikipedia.org/wiki/C0_and_C1_control_codes#C1_controls -enum C1 { - PAD = 0x80 - HOP = 0x81 - BPH = 0x82 - NBH = 0x83 - IND = 0x84 - NEL = 0x85 - SSA = 0x86 - ESA = 0x87 - HTS = 0x88 - HTJ = 0x89 - VTS = 0x8a - PLD = 0x8b - PLU = 0x8c - RI = 0x8d - SS2 = 0x8e - SS3 = 0x8f - DCS = 0x90 - PU1 = 0x91 - PU2 = 0x92 - STS = 0x93 - CCH = 0x94 - MW = 0x95 - SPA = 0x96 - EPA = 0x97 - SOS = 0x98 - SGCI = 0x99 - SCI = 0x9a - CSI = 0x9b - ST = 0x9c - OSC = 0x9d - PM = 0x9e - APC = 0x9f -} diff --git a/addons/godot_xterm/parser/dcs_parser.gd b/addons/godot_xterm/parser/dcs_parser.gd deleted file mode 100644 index 5746d55..0000000 --- a/addons/godot_xterm/parser/dcs_parser.gd +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -const Decoder = preload("res://addons/godot_xterm/input/text_decoder.gd") - - -const EMPTY_HANDLERS = [] - - -var _handlers: Dictionary = {} -var _active: Array = EMPTY_HANDLERS -var _ident: int = 0 -var _handler_fb: Dictionary - - -func _init(): - pass - - -func set_handler(ident: int, handler): - _handlers[ident] = [handler] - - -func clear_handler(ident: int): - _handlers.erase(ident) - - -func set_handler_fallback(target, method): - _handler_fb = {'target': target, 'method': method} - - -func reset(): - if _active.size(): - unhook(false) - _active = EMPTY_HANDLERS - _ident = 0 - - -func hook(ident: int, params): - # always reset leftover handlers - reset() - _ident = ident - _active = _handlers[ident] if _handlers.has(ident) else EMPTY_HANDLERS - if _active.empty(): - _handler_fb['target'].call(_handler_fb['method'], _ident, 'HOOK', params) - else: - _active.invert() - for handler in _active: - handler.hook(params) - _active.invert() - - -func put(data: Array, start: int, end: int): - if _active.empty(): - _handler_fb['target'].call(_handler_fb['method'], _ident, 'PUT', - Decoder.utf32_to_string(data, start, end)) - else: - _active.invert() - for handler in _active: - handler.put(data, start, end) - _active.invert() - - -func unhook(success: bool): - if _active.empty(): - _handler_fb['target'].call(_handler_fb['method'], _ident, 'UNHOOK', success) - else: - _active.invert() - for handler in _active: - if handler.unhook(success) != false: - success = false # will cleanup left over handlers - _active.invert() - _active = EMPTY_HANDLERS - _ident = 0 diff --git a/addons/godot_xterm/parser/escape_sequence_parser.gd b/addons/godot_xterm/parser/escape_sequence_parser.gd deleted file mode 100644 index ee5c155..0000000 --- a/addons/godot_xterm/parser/escape_sequence_parser.gd +++ /dev/null @@ -1,337 +0,0 @@ -# Copyright (c) 2018 The xterm.js authers. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - -const Constants = preload("res://addons/godot_xterm/parser/constants.gd") -const TransitionTable = preload("res://addons/godot_xterm/parser/transition_table.gd") -const VT500TransitionTable = preload("res://addons/godot_xterm/parser/vt500_transition_table.gd") -const DcsParser = preload("res://addons/godot_xterm/parser/dcs_parser.gd") -const Params = preload("res://addons/godot_xterm/parser/params.gd") - -const TableAccess = TransitionTable.TableAccess -const NON_ASCII_PRINTABLE = Constants.NON_ASCII_PRINTABLE -const ParserState = Constants.ParserState -const ParserAction = Constants.ParserAction - -var initial_state -var current_state -var preceding_codepoint - -var _transitions - -# buffers over several parse calls -var _params -var _collect - -# handler lookup containers -var _print_handler -var _execute_handlers -var _csi_handlers -var _esc_handlers -var _osc_parser -var _dcs_parser -var _error_handler - -# fallback handlers -var _print_handler_fb -var _execute_handler_fb -var _csi_handler_fb -var _esc_handler_fb -var _error_handler_fb - - -# Default do noting fallback handler. -# Allows a variable number of arguments from 0 - 7. -func noop(a = null, b = null, c = null, d = null, e = null, f = null, g = null): - pass - - -func _init(transitions = VT500TransitionTable.new().table): - initial_state = ParserState.GROUND - current_state = initial_state - _transitions = transitions - _params = Params.new() # Defaults to 32 storable params/subparams - _params.add_param(0) # ZDM (Zero Default Mode - _collect = 0 - preceding_codepoint = 0 - - # set default fallback handlers and handler lookup containers - var noop = {'target': self, 'method': 'noop'} - _print_handler_fb = noop - _execute_handler_fb = noop - _csi_handler_fb = noop - _esc_handler_fb = noop - _error_handler_fb = noop - _print_handler = _print_handler_fb - _execute_handlers = {} - _csi_handlers = {} - _esc_handlers = {} - _osc_parser = null # TODO OscParser.new() - _dcs_parser = DcsParser.new() - _error_handler = _error_handler_fb - - # swallow 7bit ST (ESC+\) - set_esc_handler({'final': '\\'}, self, 'noop') - - -static func identifier(id: Dictionary, final_range: Array = [0x40, 0x7e]): - var res = 0 - - var prefix = id.get('prefix') - var intermediates = id.get('intermediates') - var final = id.get('final') - - if prefix: - if prefix.length() > 1: - push_error("only one byte prefix supported") - res = prefix.to_ascii()[0] - if res and 0x3c > res or res > 0x3f: - push_error("prefix must be in the range 0x3c-0x3f") - - if intermediates: - if intermediates.length() > 2: - push_error("only two bytes as intermediates are supported") - for intermediate in intermediates: - var im = intermediate.to_ascii()[0] - if 0x20 > im or im > 0x2f: - push_error("intermediate must be in the range 0x20-0x2f") - res = res << 8 - res = res | im - - if final.length() != 1: - push_error("final must be a single byte") - var final_code = final.to_ascii()[0] - if final_range[0] > final_code or final_code > final_range[1]: - push_error("final must be in the range " + String(final_range[0]) + "-" + String(final_range[1])) - res = res << 8 - res = res | final_code - - return res - -static func ident_to_string(ident: int): - var res = PoolStringArray([]) - while ident: - res.append(PoolByteArray([ident & 0xFF]).get_string_from_ascii()) - ident >>= 8 - res.invert() - return res.join('') - -func set_print_handler(target: Object, method: String): - _print_handler = { 'target': target, 'method': method } - - -func add_esc_handler(id, target, method): - var ident = identifier(id, [0x30, 0x7e]) - if not _esc_handlers.has(ident): - _esc_handlers[ident] = [] - var handler_list = _esc_handlers[ident] - handler_list.append({'target': target, 'method': method}) - - -func set_csi_handler(id: Dictionary, target: Object, method: String): - _csi_handlers[identifier(id)] = [{ 'target': target, 'method': method }] - - -func set_csi_handler_fallback(target, method): - _csi_handler_fb = { 'target': target, 'method': method } - - -func set_execute_handler(flag: int, target: Object, method: String): - _execute_handlers[flag] = { 'target': target, 'method': method } - - -func set_execute_handler_fallback(target: Object, method: String): - _execute_handler_fb = { 'target': target, 'method': method } - - -func set_esc_handler(id, target, method, arg = null): - _esc_handlers[identifier(id, [0x30, 0x7e])] = [{'target': target, - 'method': method, 'arg': arg}] - - -func set_esc_handler_fallback(target: Object, method: String): - _esc_handler_fb = {'target': target, 'method': method} - - -func add_dcs_handler(id, target, method): - pass - # TODO!!! - -func set_dcs_handler(id, target: Object, method: String): - _dcs_parser.set_handler(id, {'target': target, 'method': method}) - -func set_dcs_handler_fallback(target: Object, method: String): - _dcs_parser.set_handler_fallback(target, method) - -func reset(): - current_state = initial_state - _params.reset() - _params.add_param(0) # ZDM - _collect = 0 - preceding_codepoint = 0 - -func parse(data: Array, length: int): - var code = 0 - var transition = 0 - var _current_state = current_state - var dcs = _dcs_parser - var collect = _collect - var params = _params - - #print("table", table) - - #print("parse -> data: ", data, " length: ", length) - - # Process input string. - var i = 0 - while i < length: - #print("i: ", i) - code = data[i] - - #print("code: ", code) - - # Normal transition and action lookup. - transition = _transitions[_current_state << TableAccess.INDEX_STATE_SHIFT | code if code < 0xa0 else NON_ASCII_PRINTABLE] - - #print ("transition: ", transition) - #print("current state: ", current_state) - - match transition >> TableAccess.TRANSITION_ACTION_SHIFT: - ParserAction.PRINT: - # read ahead with loop unrolling -# # Note: 0x20 (SP) is included, 0x7F (DEL) is excluded - var j = i + 1 - while true: - code = data[j] if j < data.size() else 0 - if j >= length or code < 0x20 or (code > 0x7e and code < NON_ASCII_PRINTABLE): - _print_handler['target'].call(_print_handler['method'], data, i, j) - i = j - 1 - break - j += 1 - code = data[j] if j < data.size() else 0 - if j >= length or code < 0x20 or (code > 0x7e and code < NON_ASCII_PRINTABLE): - _print_handler['target'].call(_print_handler['method'], data, i, j) - i = j - 1 - break - j += 1 - code = data[j] if j < data.size() else 0 - if j >= length or code < 0x20 or (code > 0x7e and code < NON_ASCII_PRINTABLE): - _print_handler['target'].call(_print_handler['method'], data, i, j) - i = j - 1 - break - j += 1 - code = data[j] if j < data.size() else 0 - if j >= length or code < 0x20 or (code > 0x7e and code < NON_ASCII_PRINTABLE): - _print_handler['target'].call(_print_handler['method'], data, i, j) - i = j - 1 - break - j += 1 - ParserAction.EXECUTE: - var handler = _execute_handlers.get(code) - if handler: - print("EXEC: ", handler['method']) - handler['target'].call(handler['method']) - elif _execute_handler_fb: - _execute_handler_fb['target'].call(_execute_handler_fb['method'], code) - preceding_codepoint = 0 - ParserAction.IGNORE: - pass - ParserAction.ERROR: - print("Parser error!") - - ParserAction.CSI_DISPATCH: - # Trigger CSI Handler - var handlers = _csi_handlers.get((collect << 8 | code), []) - handlers.invert() - for handler in handlers: - print("CSI: ", handler['method']) - # undefined or true means success and to stop bubbling - if handler['target'].call(handler['method'], params): - continue - handlers.invert() - if handlers.empty(): - _csi_handler_fb['target'].call(_csi_handler_fb['method'], collect << 8 | code, params.to_array()) - preceding_codepoint = 0 - - - ParserAction.PARAM: - # Inner loop digits (0x30 - 0x39) and ; (0x3b) and : (0x3a) - var do = true - while do: - match code: - 0x3b: - params.add_param(0) - 0x3a: - params.add_sub_param(-1) - _: - params.add_digit(code - 48) - i += 1 - code = data[i] if i < data.size() else 0 - do = i < length and code > 0x2f and code < 0x3c - i-=1 - - ParserAction.COLLECT: - collect <<= 8 - collect |= code - - ParserAction.ESC_DISPATCH: - var handlers = _esc_handlers.get((collect << 8 | code), []) - handlers.invert() - for handler in handlers: - # undefined or true means success and to stop bubbling - print("ESC: ", handler['method']) - if handler['arg']: - if handler['target'].call(handler['method'], handler['arg']) != false: - continue - else: - if handler['target'].call(handler['method']) != false: - continue - handlers.invert() - if handlers.empty(): - _esc_handler_fb['target'].call(_esc_handler_fb['method'], collect << 8 | code) - preceding_codepoint = 0 - - ParserAction.CLEAR: - params.reset() - params.add_param(0) # ZDM - collect = 0 - - ParserAction.DCS_HOOK: - dcs.hook(collect << 8 | code, params.to_array()) - - ParserAction.DCS_PUT: - # inner loop - exit DCS_PUT: 0x18, 0x1a, 0x1b, 0x7f, 0x80 - 0x9f - # unhook triggered by: 0x1b, 0x9c (success) and 0x18, 0x1a (abort) - for j in range(i + 1, length + 1): - code = data[j] - if code == 0x18 or code == 0x1a or code == 0x1b or (code > 0x7f and code < NON_ASCII_PRINTABLE): - dcs.put(data, i, j) - i = j - 1 - break - break - ParserAction.DCS_UNHOOK: - _dcs_parser.unhook(code != 0x18 and code != 0x1a) - if code == 0x1b: - transition |= ParserState.ESCAPE - params.reset() - params.add_param(0) # ZDM - collect = 0; - preceding_codepoint = 0 - ParserAction.OSC_START: - pass - - ParserAction.OSC_PUT: - pass - - ParserAction.OSC_END: - pass - - _current_state = transition & TableAccess.TRANSITION_STATE_MASK - i += 1 - - # save collected intermediates - _collect = collect - - # save state - current_state = _current_state diff --git a/addons/godot_xterm/parser/params.gd b/addons/godot_xterm/parser/params.gd deleted file mode 100644 index 49bf95a..0000000 --- a/addons/godot_xterm/parser/params.gd +++ /dev/null @@ -1,136 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -# Max value supported for a single param/subparam (clamped to positive int32 range). -const MAX_VALUE = 0x7FFFFFFF; -# Max allowed subparams for a single sequence (hardcoded limitation). -const MAX_SUBPARAMS = 256; - -var params = [] -var length = 0 - -var sub_params = [] -var sub_params_length = 0 -var _max_length -var _max_sub_params_length -var sub_params_idx = [] -var _reject_digits = false -var _reject_sub_digits = false -var digit_is_sub = false - - -static func from_array(values: Array): - # Workaround as per: https://github.com/godotengine/godot/issues/19345#issuecomment-471218401 - var params = load("res://addons/godot_xterm/parser/params.gd").new() - if values.empty(): - return params - # skip leading sub params - for i in range(values.size()): - var value = values[i] - if typeof(value) == TYPE_ARRAY: - if i == 0: - # skip leading sub params - continue - else: - for sub_param in value: - params.add_sub_param(sub_param) - else: - params.add_param(value) - return params - - -func _init(max_length: int = 32, max_sub_params_length: int = 32): - _max_length = max_length - _max_sub_params_length = max_sub_params_length - - if (max_sub_params_length > MAX_SUBPARAMS): - push_error("max_sub_params_length must not be greater than 256") - - params.resize(max_length) - sub_params.resize(max_sub_params_length) - sub_params_idx.resize(max_length) - - -# Gets param at `index` from param if it exists and is non-zero. -# Otherwise returns `default` (which is zero anyway due to zero default -# mode (ZDM), but allows the caller to specify a non-zero default value). -func get_param(index: int, default = 0) -> int: - if index < params.size() and params[index]: - return params[index] - else: - return default - - -func add_param(value: int): - digit_is_sub = false - if length >= _max_length: - _reject_digits = true - return - if value < -1: - push_error('values lesser than -1 are not allowed') - sub_params_idx[length] = sub_params_length << 8 | sub_params_length - params[length] = MAX_VALUE if value > MAX_VALUE else value - length += 1 - - -# Add a sub parameter value. -# The sub parameter is automatically associated with the last parameter value. -# Thus it is not possible to add a subparameter without any parameter added yet. -# `Params` only stores up to `subParamsLength` sub parameters, any later -# sub parameter will be ignored. -func add_sub_param(value: int): - digit_is_sub = true - if !length: - return - if _reject_digits or sub_params_length >= _max_sub_params_length: - _reject_sub_digits = true - return - if value < -1: - push_error('values lesser than -1 are not allowed') - sub_params[sub_params_length] = MAX_VALUE if value > MAX_VALUE else value - sub_params_length += 1 - sub_params_idx[length - 1] += 1 - - -# Whether parameter at index `idx` has sub parameters. -func has_sub_params(idx: int) -> bool: - return (sub_params_idx[idx] & 0xFF) - (sub_params_idx[idx] >> 8) > 0 - - -func get_sub_params(idx: int): - var start = sub_params_idx[idx] >> 8 - var end = sub_params_idx[idx] & 0xFF - if end - start > 0: - return sub_params.slice(start, end - 1) - else: - return null - - -func add_digit(value: int): - var _length = sub_params_length if digit_is_sub else length - if _reject_digits or (not _length) or (digit_is_sub and _reject_sub_digits): - return - var store = sub_params if digit_is_sub else params - var cur = store[_length - 1] - store[_length - 1] = min(cur * 10 + value, MAX_VALUE) if ~cur else value - - -func to_array(): - var res = [] - for i in range(length): - res.append(params[i]) - var start = sub_params_idx[i] >> 8 - var end = sub_params_idx[i] & 0xff - if end - start > 0: - res.append(sub_params.slice(start, end - 1)) - return res - -func reset(): - length = 0 - sub_params_length = 0 - _reject_digits = false - _reject_sub_digits = false - digit_is_sub = false diff --git a/addons/godot_xterm/parser/transition_table.gd b/addons/godot_xterm/parser/transition_table.gd deleted file mode 100644 index 860c452..0000000 --- a/addons/godot_xterm/parser/transition_table.gd +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - -enum TableAccess { - TRANSITION_ACTION_SHIFT = 4, - TRANSITION_STATE_MASK = 15, - INDEX_STATE_SHIFT = 8 -} - -var table: PoolByteArray = PoolByteArray() - -func _init(length: int): - table.resize(length) - -func setDefault(action: int, next: int): - for i in range(table.size()): - table[i] = action << TableAccess.TRANSITION_ACTION_SHIFT | next - -func add(code: int, state: int, action: int, next: int): - table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next - -func addMany(codes: Array, state: int, action: int, next: int): - for code in codes: - add(code, state, action, next) diff --git a/addons/godot_xterm/parser/vt500_transition_table.gd b/addons/godot_xterm/parser/vt500_transition_table.gd deleted file mode 100644 index 09993a1..0000000 --- a/addons/godot_xterm/parser/vt500_transition_table.gd +++ /dev/null @@ -1,123 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends "res://addons/godot_xterm/parser/transition_table.gd" - -const Constants = preload("res://addons/godot_xterm/parser/constants.gd") -const ParserState = Constants.ParserState -const ParserAction = Constants.ParserAction -const NON_ASCII_PRINTABLE = Constants.NON_ASCII_PRINTABLE - -var PRINTABLES = Array(range(0x20, 0x7f)) # 0x20 (SP) included, 0x7f (DEL) excluded. -var EXECUTABLES = Array(range(0x00, 0x18)) + [0x19] + Array(range(0x1c, 0x20)) - -func _init().(4096): - # Set default transition. - setDefault(ParserAction.ERROR, ParserState.GROUND) - - # Printables. - addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND) - - # Global anywhere rules. - for state in ParserState.values(): - addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND) - addMany(range(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND) - addMany(range(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND) - add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND) # ST as terminator - add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE) # ESC - add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING) # OSC - addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING) - add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY) # CSI - add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY) # DCS - - # Rules for executables and 7f. - addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND) - addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE) - add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE) - addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING) - addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY) - add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY) - addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM) - add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM); - addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE) - addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE) - add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE) - addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE) - add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE); - - # OSC. - add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING) - addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING) - add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING) - addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND) - addMany(range(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING) - - # SOS/PM/APC does nothing. - addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING) - addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING) - addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING) - add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND) - add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING) - # csi entries - add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY) - addMany(range(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND) - addMany(range(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM) - addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM) - addMany(range(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM) - addMany(range(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND) - addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE) - addMany(range(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE) - add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE) - addMany(range(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND) - addMany(range(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE) - addMany(range(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE) - addMany(range(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE) - addMany(range(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND) - addMany(range(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE) - # esc_intermediate - addMany(range(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE) - addMany(range(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE) - addMany(range(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND) - addMany(range(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND) - addMany(range(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND) - addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND) - addMany(range(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND); - - # dcs entry - add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY) - addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY) - add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY) - addMany(range(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY) - addMany(range(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE) - addMany(range(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM) - addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM) - addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE) - addMany(range(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE) - addMany(range(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE) - addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM) - add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM) - addMany(range(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM) - addMany(range(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM) - addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE) - addMany(range(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE) - addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE) - add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE) - addMany(range(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE) - addMany(range(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE) - addMany(range(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE) - addMany(range(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH) - addMany(range(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH) - addMany(range(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH) - addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH) - addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH) - add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH) - addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND); - - # special handling of unicode chars - add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND) - add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING) - add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE) - add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE) - add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH) - - return table diff --git a/addons/godot_xterm/plugin.cfg b/addons/godot_xterm/plugin.cfg index ff9fc59..4c733ed 100644 --- a/addons/godot_xterm/plugin.cfg +++ b/addons/godot_xterm/plugin.cfg @@ -1,7 +1,7 @@ [plugin] name="GodotXterm" -description="Xterm.js for Godot" -author="Leroy Hopson" +description="" +author="The GodotXterm authors" version="0.1.0" script="plugin.gd" diff --git a/addons/godot_xterm/plugin.gd b/addons/godot_xterm/plugin.gd index 173102b..48f5e24 100644 --- a/addons/godot_xterm/plugin.gd +++ b/addons/godot_xterm/plugin.gd @@ -1,16 +1,17 @@ -# Copyright (c) 2020 The GodotXterm authors. All rights reserved. -# License MIT tool extends EditorPlugin func _enter_tree(): - var script = preload("res://addons/godot_xterm/terminal.gd") - var texture = preload("res://addons/godot_xterm/icon.svg") - add_custom_type("Terminal", "Control", script, texture) - pass + var terminal_script = preload("res://addons/godot_xterm/terminal.gdns") + var terminal_icon = preload("res://addons/godot_xterm/terminal_icon.svg") + add_custom_type("Terminal", "Control", terminal_script, terminal_icon) + + var pseudoterminal_script = preload("res://addons/godot_xterm/pseudoterminal.gdns") + var pseudoterminal_icon = preload("res://addons/godot_xterm/pseudoterminal_icon.svg") + add_custom_type("Pseudoterminal", "Node", pseudoterminal_script, pseudoterminal_icon) func _exit_tree(): remove_custom_type("Terminal") - pass + remove_custom_type("Psuedoterminal") diff --git a/addons/godot_xterm_native/pseudoterminal.gdns b/addons/godot_xterm/pseudoterminal.gdns similarity index 59% rename from addons/godot_xterm_native/pseudoterminal.gdns rename to addons/godot_xterm/pseudoterminal.gdns index db30774..19c7ba2 100644 --- a/addons/godot_xterm_native/pseudoterminal.gdns +++ b/addons/godot_xterm/pseudoterminal.gdns @@ -1,6 +1,6 @@ [gd_resource type="NativeScript" load_steps=2 format=2] -[ext_resource path="res://addons/godot_xterm_native/godotxtermnative.gdnlib" type="GDNativeLibrary" id=1] +[ext_resource path="res://addons/godot_xterm/godotxtermnative.gdnlib" type="GDNativeLibrary" id=1] [resource] resource_name = "Terminal" diff --git a/addons/godot_xterm_native/pseudoterminal_icon.svg b/addons/godot_xterm/pseudoterminal_icon.svg similarity index 100% rename from addons/godot_xterm_native/pseudoterminal_icon.svg rename to addons/godot_xterm/pseudoterminal_icon.svg diff --git a/addons/godot_xterm/icon.svg.import b/addons/godot_xterm/pseudoterminal_icon.svg.import similarity index 66% rename from addons/godot_xterm/icon.svg.import rename to addons/godot_xterm/pseudoterminal_icon.svg.import index a4fb527..d351d90 100644 --- a/addons/godot_xterm/icon.svg.import +++ b/addons/godot_xterm/pseudoterminal_icon.svg.import @@ -2,15 +2,15 @@ importer="texture" type="StreamTexture" -path="res://.import/icon.svg-b0b594198f5f4040e8f0e39a8a353265.stex" +path="res://.import/pseudoterminal_icon.svg-50ba2514dae785a6b48b0da604cf3a09.stex" metadata={ "vram_texture": false } [deps] -source_file="res://addons/godot_xterm/icon.svg" -dest_files=[ "res://.import/icon.svg-b0b594198f5f4040e8f0e39a8a353265.stex" ] +source_file="res://addons/godot_xterm/pseudoterminal_icon.svg" +dest_files=[ "res://.import/pseudoterminal_icon.svg-50ba2514dae785a6b48b0da604cf3a09.stex" ] [params] diff --git a/addons/godot_xterm/renderer/canvas_rendering_context_2d.gd b/addons/godot_xterm/renderer/canvas_rendering_context_2d.gd deleted file mode 100644 index 3e14e6e..0000000 --- a/addons/godot_xterm/renderer/canvas_rendering_context_2d.gd +++ /dev/null @@ -1,74 +0,0 @@ -# Copyright (c) 2020 The GodotXterm authors. All rights reserved. -# License MIT -extends Node2D -class_name CanvasRenderingContext2D -# This is a shim for the CavasRenderingContext2D interface of HTML5's Canvas API, -# which the xterm.js renderer code uses heavily. It extends Node2D to take -# advantage of the z_index property and also uses many methods of CanvasItem -# which Node2D inherits. - - -var fill_style -var font = preload("res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.tres") -var _saved -var _draw_buffer = [] - - -# Called when the node enters the scene tree for the first time. -func _ready(): - pass # Replace with function body. - - -func draw_rect_deferred(rect: Rect2, color: Color): - _draw_buffer.append({"method": "draw_rect", "args": [rect, color]}) - update() - - -func clear_rect(rect: Rect2): - draw_rect_deferred(rect, Color(0, 0, 0, 0)) - - -func fill_rect(rect: Rect2): - draw_rect_deferred(rect, fill_style) - - -func fill_text(text: String, x: int, y: int): - _draw_buffer.append({"method": "_draw_text", "args": [font, Vector2(x, y), text, fill_style]}) - update() - -func _draw_text(font: Font, pos: Vector2, text: String, color) -> void: - for i in text.length(): - var c = text[i] - var next_char = text[i + 1] if i + 1 < text.length() else '' - var advance = draw_char(font, pos, c, next_char, color) - pos.x += advance - - -func _draw(): - for command in _draw_buffer: - self.callv(command.method, command.args) - _draw_buffer.resize(0) - - -func save(): - _saved = { - 'fill_style': fill_style, - 'font': font, - } - - -func restore(): - fill_style = _saved['fill_style'] - font = _saved['font'] - - -func measure_text(text: String): - var text_metrics = TextMetrics.new() - text_metrics.width = font.get_string_size(text).x - return text_metrics - -class TextMetrics: - extends Reference - # https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics - - var width diff --git a/addons/godot_xterm/renderer/character_joiner_registry.gd b/addons/godot_xterm/renderer/character_joiner_registry.gd deleted file mode 100644 index c6d86a7..0000000 --- a/addons/godot_xterm/renderer/character_joiner_registry.gd +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright (c) 2018 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -const CellData = preload("res://addons/godot_xterm/buffer/cell_data.gd") - - -class JoinedCellData extends "res://addons/godot_xterm/buffer/attribute_data.gd": - - - var _width: int = 0 - var content: int = 0 - var combined_data: String = '' - - - func _init(first_cell, chars: String, width: int): - fg = first_cell.fg - bg = first_cell.bg - combined_data = chars - _width = width - - -var _character_joiners: Array = [] -var _next_character_joiner_id = 0 -var _work_cell = CellData.new() -var _buffer_service - - -func _init(buffer_service): - _buffer_service = buffer_service - - -func get_joined_characters(row: int) -> Array: - if _character_joiners.empty(): - return [] - - var line = _buffer_service.buffer.lines.get_el(row) - if not line or line.length == 0: - return [] - - var ranges = [] - var line_str = line.translate_to_string(true) - - return ranges diff --git a/addons/godot_xterm/services/buffer_service.gd b/addons/godot_xterm/services/buffer_service.gd deleted file mode 100644 index 62d7124..0000000 --- a/addons/godot_xterm/services/buffer_service.gd +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - -signal buffer_activated(active_buffer, inactive_buffer) -signal resized(cols, rows) - -const BufferSet = preload("res://addons/godot_xterm/buffer/buffer_set.gd") - -const MINIMUM_COLS = 2 # Less than 2 can mess with wide chars -const MINIMUM_ROWS = 1 - -var service_brand - -var cols: int -var rows: int -var buffers -# Whether the user is scrolling (locks the scroll position) -var is_user_scrolling: bool = false -var _options_service - -var buffer setget ,_get_buffer - - -func _get_buffer(): - return buffers.active if buffers else null - - -func _init(options_service): - _options_service = options_service - _options_service.connect("option_changed", self, "_option_changed") - cols = max(_options_service.options.cols, MINIMUM_COLS) - rows = max(_options_service.options.rows, MINIMUM_ROWS) - buffers = BufferSet.new(_options_service, self) - buffers.connect("buffer_activated", self, "_buffer_activated") - - -func resize(cols: int, rows: int) -> void: - self.cols = cols - self.rows = rows - buffers.resize(cols, rows) - #buffers.setup_tab_stops(cols) - emit_signal("resized", cols, rows) - - -func _buffer_activated(active_buffer, inactive_buffer): - emit_signal("buffer_activated", active_buffer, inactive_buffer) - - -func _option_changed(option: String) -> void: - if option == "cols" or option == "rows": - resize(_options_service.options.cols, _options_service.options.rows) diff --git a/addons/godot_xterm/services/charset_service.gd b/addons/godot_xterm/services/charset_service.gd deleted file mode 100644 index 8e098f0..0000000 --- a/addons/godot_xterm/services/charset_service.gd +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -var service_brand -var charset = null -var glevel: int = 0 - -var _charsets = [] - - -func reset() -> void: - charset = null - _charsets = [] - glevel = 0 - - -func set_glevel(g: int) -> void: - glevel = g - charset = _charsets[g] - - -func set_gcharset(g: int, charset = null) -> void: - if _charsets.size() < g + 1: - _charsets.resize(g + 1) - _charsets[g] = charset - if glevel == g: - charset = charset diff --git a/addons/godot_xterm/services/core_service.gd b/addons/godot_xterm/services/core_service.gd deleted file mode 100644 index 9d7b0df..0000000 --- a/addons/godot_xterm/services/core_service.gd +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -var DEFAULT_MODES = { - "insert_mode": false, -} - -var DEFAULT_DEC_PRIVATE_MODES = { - "application_cursor_keys": false, - "application_keypad": false, - "bracketed_paste_mode": false, - "origin": false, - "reverse_wraparound": false, # defaults: xterm -true, vt100 - false -} - -var modes = DEFAULT_MODES.duplicate() -var dec_private_modes = DEFAULT_DEC_PRIVATE_MODES.duplicate() -var is_cursor_hidden = false -var is_cursor_initialized = true - - -func reset(): - modes = DEFAULT_MODES.duplicate() - dec_private_modes.duplicate() diff --git a/addons/godot_xterm/services/options_service.gd b/addons/godot_xterm/services/options_service.gd deleted file mode 100644 index f056729..0000000 --- a/addons/godot_xterm/services/options_service.gd +++ /dev/null @@ -1,104 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends Reference - - -const Constants = preload("res://addons/godot_xterm/buffer/constants.gd") - -const CursorStyle = Constants.CursorStyle -const UnderlineStyle = Constants.UnderlineStyle -const BellStyle = Constants.BellStyle - - -class TerminalOptions: - extends Reference - - - var cols: int = 80 - var rows: int = 24 - var cursor_blink: bool = false - var cursor_style = CursorStyle.BLOCK -# var cursor_width: int = 1 -# var bell_sound: AudioStream = null -# var bell_style = BellStyle.NONE -# var draw_bold_text_in_bright_colors: bool = true -# var fast_scroll_modifier = "alt" -# var fast_scroll_sensitivity: int = 5 - var font_family: Dictionary = { - # TODO - } - var font_size: int = 15 -# var font_weight: String # TODO: Remove -# var font_weight_bold: String # TODO: Remove - var line_height: float = 1.0 -# var link_tooltip_hover_duration: int # TODO: Remove - var letter_spacing: float = 0 -# var log_level # TODO: implement - var scrollback: int = 1000 -# var scroll_sensitivity: int = 1 - var screen_reader_mode: bool = false -# var mac_option_is_meta: bool = false -# var mac_option_click_forces_selection: bool = false -# var minimum_contrast_ratio: float = 1 -# var disable_stdin: bool = false -# var allow_proposed_api: bool = true - var allow_transparency: bool = false - var tab_stop_width: int = 8 -# var colors: Dictionary = { -# 'black': Color(0, 0, 0) -# } -# var right_click_selects_word = "isMac" # TODO? -# var renderer_type = "canvas" # Remove? - var window_options: Dictionary = { - 'set_win_lines': false, - } - var windows_mode: bool = false -# var word_separator: String = " ()[]{}',\"" - var convert_eol: bool = true -# var term_name: String = "xterm" -# var cancel_events: bool = false - - - # Copies options from an `object` to itself. - func copy_from(object: Object): - for property in get_property_list(): - if property.usage == PROPERTY_USAGE_SCRIPT_VARIABLE: - var p = object.get(property.name) - if p: - set(property.name, p) - - -var DEFAULT_OPTIONS = TerminalOptions.new() - -signal option_changed - -var options - - -func _init(options): - self.options = options - - # Set the font size based on the font_size option - _resize_fonts() - - -func set_option(key: String, value) -> void: - # TODO: sanitize and validate options. - - # Don't fire an option change event if they didn't change - if options[key] == value: - return - - options[key] = value - emit_signal("option_changed", key) - - # Update other options accordingly. - match key: - "font_size": - _resize_fonts() - - -func _resize_fonts(): - for font in options.font_family.values(): - font.size = options.font_size diff --git a/addons/godot_xterm_native/src/libgodotxtermnative.cpp b/addons/godot_xterm/src/libgodotxtermnative.cpp similarity index 100% rename from addons/godot_xterm_native/src/libgodotxtermnative.cpp rename to addons/godot_xterm/src/libgodotxtermnative.cpp diff --git a/addons/godot_xterm_native/src/pseudoterminal.cpp b/addons/godot_xterm/src/pseudoterminal.cpp similarity index 100% rename from addons/godot_xterm_native/src/pseudoterminal.cpp rename to addons/godot_xterm/src/pseudoterminal.cpp diff --git a/addons/godot_xterm_native/src/pseudoterminal.h b/addons/godot_xterm/src/pseudoterminal.h similarity index 100% rename from addons/godot_xterm_native/src/pseudoterminal.h rename to addons/godot_xterm/src/pseudoterminal.h diff --git a/addons/godot_xterm_native/src/terminal.cpp b/addons/godot_xterm/src/terminal.cpp similarity index 100% rename from addons/godot_xterm_native/src/terminal.cpp rename to addons/godot_xterm/src/terminal.cpp diff --git a/addons/godot_xterm_native/src/terminal.h b/addons/godot_xterm/src/terminal.h similarity index 100% rename from addons/godot_xterm_native/src/terminal.h rename to addons/godot_xterm/src/terminal.h diff --git a/addons/godot_xterm/terminal.gd b/addons/godot_xterm/terminal.gd deleted file mode 100644 index fd7fbd8..0000000 --- a/addons/godot_xterm/terminal.gd +++ /dev/null @@ -1,390 +0,0 @@ -# Copyright (c) 2020 The GodotXterm authors. All rights reserved. -# Copyright (c) 2014-2020 The xterm.js authors. All rights reserved. -# Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) -# Ported to GDScript by the GodotXterm authors. -# Licese MIT -# -# Originally forked from (with the author's permission): -# Fabrice Bellard's javascript vt100 for jslinux: -# http://bellard.org/jslinux/ -# Copyright (c) 2011 Fabrice Bellard -# The original design remains. The terminal itself -# has been extended to include xterm CSI codes, among -# other features. -# -# Terminal Emulation References: -# http://vt100.net/ -# http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt -# http://invisible-island.net/xterm/ctlseqs/ctlseqs.html -# http://invisible-island.net/vttest/ -# http://www.inwap.com/pdp10/ansicode.txt -# http://linux.die.net/man/4/console_codes -# http://linux.die.net/man/7/urxvt -tool -extends Control - - -const BufferService = preload("res://addons/godot_xterm/services/buffer_service.gd") -const CoreService = preload("res://addons/godot_xterm/services/core_service.gd") -const OptionsService = preload("res://addons/godot_xterm/services/options_service.gd") -const CharsetService = preload("res://addons/godot_xterm/services/charset_service.gd") -const InputHandler = preload("res://addons/godot_xterm/input_handler.gd") -const Const = preload("res://addons/godot_xterm/Constants.gd") -const Constants = preload("res://addons/godot_xterm/parser/constants.gd") -const Parser = preload("res://addons/godot_xterm/parser/escape_sequence_parser.gd") -const Decoder = preload("res://addons/godot_xterm/input/text_decoder.gd") -const ColorManager = preload("res://addons/godot_xterm/color_manager.gd") -const CellData = preload("res://addons/godot_xterm/buffer/cell_data.gd") -const AttributeData = preload("res://addons/godot_xterm/buffer/attribute_data.gd") - -const SourceCodeProRegular = preload("res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.tres") -const SourceCodeProBold = preload("res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.tres") -const SourceCodeProItalic = preload("res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.tres") -const SourceCodeProBoldItalic = preload("res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.tres") - -const C0 = Constants.C0 -const C1 = Constants.C1 -const ESCAPE = 27 -const BACKSPACE = 8 -const BEEP = 7 -const SPACE = 32 -const LEFT_BRACKET = 91 -const ENTER = 10 -const BACKSPACE_ALT = 127 - -const BLINK_INTERVAL = 0.6 # 600ms. The time between blinks. - -# TODO: Move me somewhere else. -enum BellStyle { - NONE -} - -signal output(data) -signal scrolled(ydisp) - -export var cols = 80 -export var rows = 24 -# If set, terminals rows and cols will be automatically calculated based on the -# control's rect size and font_size. -export var auto_resize = false -export var cursor_blink = false -export var cursor_style = 'block' -export var cursor_width = 1 -export var bell_sound: AudioStream = null # TODO Bell sound -export(BellStyle) var bell_style = BellStyle.NONE -export var draw_bold_text_in_bright_colors = true -export var fast_scroll_modifier = 'alt' # TODO Use scancode? -export var fast_scroll_sensitivity = 5 -export var font_family: Dictionary = { - "regular": SourceCodeProRegular, - "bold": SourceCodeProBold, - "italic": SourceCodeProItalic, - "bold_italic": SourceCodeProBoldItalic, -} -export var font_size: int = 15 -export var line_height = 1.0 -export var link_tooltip_hover_duration = 500 # Not relevant? -export var letter_spacing = 0 -export var log_level = 'info' # Not relevant? -export var scrollback = 1000 -export var scroll_sensitivity = 1 -export var screen_reader_mode: bool = false -export var mac_option_is_meta = false -export var mac_option_click_forces_selection = false -export var minimum_contrast_ratio = 1 -export var disable_stdin = false -export var allow_proposed_api = true -export var allow_transparency = false -export var tab_stop_width = 8 -export var colors: Dictionary = { - "black": Color("#2e3436"), - "red": Color("#cc0000"), - "green": Color("#4e9a06"), - "yellow": Color("#c4a000"), - "blue": Color("#3465a4"), - "magenta": Color("#75507b"), - "cyan": Color("#06989a"), - "white": Color("#d3d7cf"), - "bright_black": Color("#555753"), - "bright_red": Color("#ef2929"), - "bright_green": Color("#8ae234"), - "bright_yellow": Color("#fce94f"), - "bright_blue": Color("#729fcf"), - "bright_magenta": Color("#ad7fa8"), - "bright_cyan": Color("#34e2e2"), - "bright_white": Color("#eeeeec"), -} -export var right_click_selects_word = 'isMac' # TODO -export var renderer_type = 'canvas' # Relevant? -export var window_options = { - 'set_win_lines': false -} -export var windows_mode = false -export var word_separator = " ()[]{}',\"`" -export var convert_eol = true -export var term_name = 'xterm' -export var cancel_events = false - -var options_service -var decoder -var parser -var _buffer_service -var _core_service -var _charset_service -var _input_handler -var _render_service -var _color_manager -var _scaled_char_width -var _scaled_char_height -var _scaled_cell_width -var _scaled_cell_height -var _scaled_char_top -var _scaled_char_left -var _work_cell = CellData.new() -var _blink_on = false -var _time_since_last_blink = 0 - -func _ready(): - var options = OptionsService.TerminalOptions.new() - options.copy_from(self) - options_service = OptionsService.new(options) - - _buffer_service = BufferService.new(options_service) - _core_service = CoreService.new() - _charset_service = CharsetService.new() - - - # Register input handler and connect signals. - _input_handler = InputHandler.new(_buffer_service, _core_service, _charset_service, options_service) - _input_handler.connect("bell_requested", self, "bell") - _input_handler.connect("refresh_rows_requested", self, "_refresh_rows") - _input_handler.connect("reset_requested", self, "reset") - _input_handler.connect("scroll_requested", self, "scroll") - _input_handler.connect("windows_options_report_requested", self, "report_windows_options") - - _color_manager = ColorManager.new() - _color_manager.set_theme(colors) - - if auto_resize: - connect("resized", self, "_update_dimensions") - - _update_dimensions() - - - -func _refresh_rows(start_row = 0, end_row = 0): - # Not optimized, just draw - update() - - -func _input(event): - if event is InputEventKey and event.pressed: - var data = PoolByteArray([]) - accept_event() - - # TODO: Handle more of these. - if (event.control and event.scancode == KEY_C): - data.append(3) - elif event.unicode: - data.append(event.unicode) - elif event.scancode == KEY_ENTER: - data.append(ENTER) - elif event.scancode == KEY_BACKSPACE: - data.append(BACKSPACE_ALT) - elif event.scancode == KEY_ESCAPE: - data.append(27) - elif event.scancode == KEY_TAB: - data.append(9) - elif OS.get_scancode_string(event.scancode) == "Shift": - pass - elif OS.get_scancode_string(event.scancode) == "Control": - pass - else: - pass - #push_warning('Unhandled input. scancode: ' + str(OS.get_scancode_string(event.scancode))) - emit_signal("output", data) - - -func write(data, callback_target = null, callback_method: String = ''): - _input_handler.parse(data) - if callback_target and callback_method: - callback_target.call(callback_method) - - -func refresh(start = null, end = null) -> void: - pass - - -# Recalculates the character and canvas dimensions. -func _update_dimensions(): - var char_width = 0 - var char_height = 0 - - for font in options_service.options.font_family.values(): - var size = font.get_string_size("W") - char_width = max(char_width, size.x) - char_height = max(char_height, size.y) - - _scaled_char_width = char_width - _scaled_char_height = char_height - - # Calculate the scaled cell height, if line_height is not 1 then the value - # will be floored because since line_height can never be lower then 1, there - # is a guarantee that the scaled line height will always be larger than - # scaled char height. - _scaled_cell_height = floor(_scaled_char_height * options_service.options.line_height) - - # Calculate the y coordinate within a cell that text should draw from in - # order to draw in the center of a cell. - _scaled_char_top = 0 if options_service.options.line_height == 1 else \ - round((_scaled_cell_height - _scaled_char_height) / 2) - - # Calculate the scaled cell width, taking the letter_spacing into account. - _scaled_cell_width = _scaled_char_width + round(options_service.options.letter_spacing) - - # Calculate the x coordinate with a cell that text should draw from in - # order to draw in the center of a cell. - _scaled_char_left = floor(options_service.options.letter_spacing / 2) - - if auto_resize: - # Calculate cols and rows based on cell size - var rect: Rect2 = get_rect() - var cols = max(2, floor(rect.size.x / _scaled_cell_width)) - var rows = max(1, floor(rect.size.y / _scaled_cell_height)) - - self.cols = cols - self.rows = rows - - options_service.set_option("rows", rows) - options_service.set_option("cols", cols) - - -# Scroll the terminal down 1 row, creating a blank line. -# @param is_wrapped Whether the new line is wrapped from the previous line. -func scroll(erase_attr, is_wrapped: bool = false) -> void: - var buffer = _buffer_service.buffer - var new_line = buffer.get_blank_line(erase_attr, is_wrapped) - - var top_row = buffer.ybase + buffer.scroll_top - var bottom_row = buffer.ybase + buffer.scroll_bottom - - if buffer.scroll_top == 0: - # Determine whether the buffer is going to be trimmed after insertion. - var will_buffer_be_trimmed = buffer.lines.is_full - - # Insert the line using the fastest method - if bottom_row == buffer.lines.length - 1: - if will_buffer_be_trimmed: - buffer.lines.recycle().copy_from(new_line.duplicate()) - else: - buffer.lines.push(new_line.duplicate()) - else: - buffer.lines.splice(bottom_row + 1, 0, [new_line.duplicate()]) - - # Only adjust ybase and ydisp when the buffer is not trimmed - if not will_buffer_be_trimmed: - buffer.ybase += 1 - # Only scroll the ydisp with ybase if the user has not scrolled up - if not _buffer_service.is_user_scrolling: - buffer.ydisp += 1 - else: - # When the buffer is full and the user has scrolled up, keep the text - # stable unless ydisp is right at the top - if _buffer_service.is_user_scrolling: - buffer.ydisp = max(buffer.ydisp - 1, 0) - else: - # scroll_top is non-zero which means no line will be going to the - # scrollback, instead we can just shift them in-place. - var scroll_region_height = bottom_row - top_row + 1 # as it's zero based - buffer.lines.shift_elements(top_row + 1, scroll_region_height - 1, -1) - buffer.lines.set_line(bottom_row, new_line.duplicate()) - - # Move the viewport to the bottom of the buffer unless the user is scrolling. - if not _buffer_service.is_user_scrolling: - buffer.ydisp = buffer.ybase - - # Flag rows that need updating - # TODO - - emit_signal("scrolled", buffer.ydisp) - - -func _process(delta): - _time_since_last_blink += delta - if _time_since_last_blink > BLINK_INTERVAL: - _blink_on = not _blink_on - _time_since_last_blink = 0 - update() - - -func _draw(): - # Draw the background and foreground - if _buffer_service == null: - return - - var buffer = _buffer_service.buffer - var rows = _buffer_service.rows - - for y in range(0, rows): - var row = y + buffer.ydisp - var line = buffer.lines.get_line(row) - for x in line.length: - line.load_cell(x, _work_cell) - - # Background - - # Get the background color - # TODO: handle inverse - var bg_color - if _work_cell.is_bg_rgb(): - bg_color = AttributeData.to_color_rgb(_work_cell.get_bg_color()) - elif _work_cell.is_bg_palette(): - bg_color = _color_manager.colors.ansi[_work_cell.get_bg_color()] - else: - bg_color = _color_manager.colors.background - - draw_rect(Rect2(x * _scaled_cell_width, y * _scaled_cell_height, - (cols - x) * _scaled_cell_width, 1 * _scaled_cell_height), - bg_color) - - # Foreground - # Don't draw if cell is invisible - if _work_cell.is_invisible(): - continue - - # Don't draw if cell is blink and blink is off - if _work_cell.is_blink() and not _blink_on: - continue - - # Get the foreground color - # TODO: handle inverse min contrast and draw bold in bright colors - # dim and maybe more! - var fg_color - if _work_cell.is_fg_default(): - fg_color = _color_manager.colors.foreground - if _work_cell.is_fg_rgb(): - fg_color = AttributeData.to_color_rgb(_work_cell.get_fg_color()) - else: - fg_color = _color_manager.colors.ansi[_work_cell.get_fg_color()] - - # Get font - var font: DynamicFont = options_service.options.font_family.regular - var is_bold = _work_cell.is_bold() - var is_italic = _work_cell.is_italic() - - if is_bold and is_italic: - font = options_service.options.font_family.bold_italic - elif is_bold: - font = options_service.options.font_family.bold - elif is_italic: - font = options_service.options.font_family.italic - - # TODO: set this once initially - font.size = options_service.options.font_size - - draw_char(font, - Vector2(x * _scaled_cell_width + _scaled_char_left, - y * _scaled_cell_height + _scaled_char_top + _scaled_char_height / 2), - _work_cell.get_chars() if _work_cell.get_chars() else ' ', "", fg_color) - # Draw the cursor - # Draw selection diff --git a/addons/godot_xterm_native/terminal.gdns b/addons/godot_xterm/terminal.gdns similarity index 58% rename from addons/godot_xterm_native/terminal.gdns rename to addons/godot_xterm/terminal.gdns index 4a21b9f..334e2d6 100644 --- a/addons/godot_xterm_native/terminal.gdns +++ b/addons/godot_xterm/terminal.gdns @@ -1,6 +1,6 @@ [gd_resource type="NativeScript" load_steps=2 format=2] -[ext_resource path="res://addons/godot_xterm_native/godotxtermnative.gdnlib" type="GDNativeLibrary" id=1] +[ext_resource path="res://addons/godot_xterm/godotxtermnative.gdnlib" type="GDNativeLibrary" id=1] [resource] resource_name = "Terminal" diff --git a/addons/godot_xterm_native/terminal_icon.svg b/addons/godot_xterm/terminal_icon.svg similarity index 100% rename from addons/godot_xterm_native/terminal_icon.svg rename to addons/godot_xterm/terminal_icon.svg diff --git a/addons/gut/icon.png.import b/addons/godot_xterm/terminal_icon.svg.import similarity index 67% rename from addons/gut/icon.png.import rename to addons/godot_xterm/terminal_icon.svg.import index 848473e..d8ea732 100644 --- a/addons/gut/icon.png.import +++ b/addons/godot_xterm/terminal_icon.svg.import @@ -2,15 +2,15 @@ importer="texture" type="StreamTexture" -path="res://.import/icon.png-91b084043b8aaf2f1c906e7b9fa92969.stex" +path="res://.import/terminal_icon.svg-33ee6ad8b86db2f37e5d8d61a6b1b8db.stex" metadata={ "vram_texture": false } [deps] -source_file="res://addons/gut/icon.png" -dest_files=[ "res://.import/icon.png-91b084043b8aaf2f1c906e7b9fa92969.stex" ] +source_file="res://addons/godot_xterm/terminal_icon.svg" +dest_files=[ "res://.import/terminal_icon.svg-33ee6ad8b86db2f37e5d8d61a6b1b8db.stex" ] [params] diff --git a/addons/godot_xterm/themes/default.theme b/addons/godot_xterm/themes/default.theme new file mode 100644 index 0000000..6f200ea Binary files /dev/null and b/addons/godot_xterm/themes/default.theme differ diff --git a/addons/godot_xterm_native/godotxtermnative.gdnlib b/addons/godot_xterm_native/godotxtermnative.gdnlib deleted file mode 100644 index d5b1abf..0000000 --- a/addons/godot_xterm_native/godotxtermnative.gdnlib +++ /dev/null @@ -1,16 +0,0 @@ -[general] - -singleton=false -load_once=true -symbol_prefix="godot_" -reloadable=true - -[entry] - -X11.64="res://addons/godot_xterm_native/bin/x11/libgodotxtermnative.so" -Server.64="res://addons/godot_xterm_native/bin/x11/libgodotxtermnative.so" - -[dependencies] - -X11.64=[ ] -Server.64=[ ] diff --git a/addons/godot_xterm_native/plugin.cfg b/addons/godot_xterm_native/plugin.cfg deleted file mode 100644 index e9d179b..0000000 --- a/addons/godot_xterm_native/plugin.cfg +++ /dev/null @@ -1,7 +0,0 @@ -[plugin] - -name="Godot Xterm Native" -description="" -author="Leroy Hopson" -version="0.1" -script="plugin.gd" diff --git a/addons/godot_xterm_native/plugin.gd b/addons/godot_xterm_native/plugin.gd deleted file mode 100644 index 155bb98..0000000 --- a/addons/godot_xterm_native/plugin.gd +++ /dev/null @@ -1,17 +0,0 @@ -tool -extends EditorPlugin - - -func _enter_tree(): - var terminal_script = preload("res://addons/godot_xterm_native/terminal.gdns") - var terminal_icon = preload("res://addons/godot_xterm_native/terminal_icon.svg") - add_custom_type("Terminal", "Control", terminal_script, terminal_icon) - - var pseudoterminal_script = preload("res://addons/godot_xterm_native/pseudoterminal.gdns") - var pseudoterminal_icon = preload("res://addons/godot_xterm_native/pseudoterminal_icon.svg") - add_custom_type("Pseudoterminal", "Node", pseudoterminal_script, pseudoterminal_icon) - - -func _exit_tree(): - remove_custom_type("Terminal") - remove_custom_type("Psuedoterminal") diff --git a/addons/godot_xterm_native/pseudoterminal_icon.svg.import b/addons/godot_xterm_native/pseudoterminal_icon.svg.import deleted file mode 100644 index f440542..0000000 --- a/addons/godot_xterm_native/pseudoterminal_icon.svg.import +++ /dev/null @@ -1,34 +0,0 @@ -[remap] - -importer="texture" -type="StreamTexture" -path="res://.import/pseudoterminal_icon.svg-11c935c96560f4f752005a829ae0b2b7.stex" -metadata={ -"vram_texture": false -} - -[deps] - -source_file="res://addons/godot_xterm_native/pseudoterminal_icon.svg" -dest_files=[ "res://.import/pseudoterminal_icon.svg-11c935c96560f4f752005a829ae0b2b7.stex" ] - -[params] - -compress/mode=0 -compress/lossy_quality=0.7 -compress/hdr_mode=0 -compress/bptc_ldr=0 -compress/normal_map=0 -flags/repeat=0 -flags/filter=true -flags/mipmaps=false -flags/anisotropic=false -flags/srgb=2 -process/fix_alpha_border=true -process/premult_alpha=false -process/HDR_as_SRGB=false -process/invert_color=false -stream=false -size_limit=0 -detect_3d=true -svg/scale=1.0 diff --git a/addons/godot_xterm_native/terminal_icon.svg.import b/addons/godot_xterm_native/terminal_icon.svg.import deleted file mode 100644 index 2650939..0000000 --- a/addons/godot_xterm_native/terminal_icon.svg.import +++ /dev/null @@ -1,34 +0,0 @@ -[remap] - -importer="texture" -type="StreamTexture" -path="res://.import/terminal_icon.svg-ab79ba4c14608847c16f36c424b01cf4.stex" -metadata={ -"vram_texture": false -} - -[deps] - -source_file="res://addons/godot_xterm_native/terminal_icon.svg" -dest_files=[ "res://.import/terminal_icon.svg-ab79ba4c14608847c16f36c424b01cf4.stex" ] - -[params] - -compress/mode=0 -compress/lossy_quality=0.7 -compress/hdr_mode=0 -compress/bptc_ldr=0 -compress/normal_map=0 -flags/repeat=0 -flags/filter=true -flags/mipmaps=false -flags/anisotropic=false -flags/srgb=2 -process/fix_alpha_border=true -process/premult_alpha=false -process/HDR_as_SRGB=false -process/invert_color=false -stream=false -size_limit=0 -detect_3d=true -svg/scale=1.0 diff --git a/addons/godot_xterm_native/themes/default.theme b/addons/godot_xterm_native/themes/default.theme deleted file mode 100644 index 2121696..0000000 Binary files a/addons/godot_xterm_native/themes/default.theme and /dev/null differ diff --git a/addons/gut/GutScene.gd b/addons/gut/GutScene.gd deleted file mode 100644 index 4139dd4..0000000 --- a/addons/gut/GutScene.gd +++ /dev/null @@ -1,347 +0,0 @@ -extends Panel - -onready var _script_list = $ScriptsList -onready var _nav = { - prev = $Navigation/Previous, - next = $Navigation/Next, - run = $Navigation/Run, - current_script = $Navigation/CurrentScript, - show_scripts = $Navigation/ShowScripts -} -onready var _progress = { - script = $ScriptProgress, - test = $TestProgress -} -onready var _summary = { - failing = $Summary/Failing, - passing = $Summary/Passing -} - -onready var _extras = $ExtraOptions -onready var _ignore_pauses = $ExtraOptions/IgnorePause -onready var _continue_button = $Continue/Continue -onready var _text_box = $TextDisplay/RichTextLabel - -onready var _titlebar = { - bar = $TitleBar, - time = $TitleBar/Time, - label = $TitleBar/Title -} - -var _mouse = { - down = false, - in_title = false, - down_pos = null, - in_handle = false -} -var _is_running = false -var _start_time = 0.0 -var _time = 0.0 - -const DEFAULT_TITLE = 'Gut: The Godot Unit Testing tool.' -var _utils = load('res://addons/gut/utils.gd').new() -var _text_box_blocker_enabled = true -var _pre_maximize_size = null - -signal end_pause -signal ignore_pause -signal log_level_changed -signal run_script -signal run_single_script - -func _ready(): - _pre_maximize_size = rect_size - _hide_scripts() - _update_controls() - _nav.current_script.set_text("No scripts available") - set_title() - clear_summary() - $TitleBar/Time.set_text("") - $ExtraOptions/DisableBlocker.pressed = !_text_box_blocker_enabled - _extras.visible = false - update() - -func _process(_delta): - if(_is_running): - _time = OS.get_unix_time() - _start_time - var disp_time = round(_time * 100)/100 - $TitleBar/Time.set_text(str(disp_time)) - -func _draw(): # needs get_size() - # Draw the lines in the corner to show where you can - # drag to resize the dialog - var grab_margin = 3 - var line_space = 3 - var grab_line_color = Color(.4, .4, .4) - for i in range(1, 10): - var x = rect_size - Vector2(i * line_space, grab_margin) - var y = rect_size - Vector2(grab_margin, i * line_space) - draw_line(x, y, grab_line_color, 1, true) - -func _on_Maximize_draw(): - # draw the maximize square thing. - var btn = $TitleBar/Maximize - btn.set_text('') - var w = btn.get_size().x - var h = btn.get_size().y - btn.draw_rect(Rect2(0, 0, w, h), Color(0, 0, 0, 1)) - btn.draw_rect(Rect2(2, 4, w - 4, h - 6), Color(1,1,1,1)) - -func _on_ShowExtras_draw(): - var btn = $Continue/ShowExtras - btn.set_text('') - var start_x = 20 - var start_y = 15 - var pad = 5 - var color = Color(.1, .1, .1, 1) - var width = 2 - for i in range(3): - var y = start_y + pad * i - btn.draw_line(Vector2(start_x, y), Vector2(btn.get_size().x - start_x, y), color, width, true) - -# #################### -# GUI Events -# #################### -func _on_Run_pressed(): - _run_mode() - emit_signal('run_script', get_selected_index()) - -func _on_CurrentScript_pressed(): - _run_mode() - emit_signal('run_single_script', get_selected_index()) - -func _on_Previous_pressed(): - _select_script(get_selected_index() - 1) - -func _on_Next_pressed(): - _select_script(get_selected_index() + 1) - -func _on_LogLevelSlider_value_changed(_value): - emit_signal('log_level_changed', $LogLevelSlider.value) - -func _on_Continue_pressed(): - _continue_button.disabled = true - emit_signal('end_pause') - -func _on_IgnorePause_pressed(): - var checked = _ignore_pauses.is_pressed() - emit_signal('ignore_pause', checked) - if(checked): - emit_signal('end_pause') - _continue_button.disabled = true - -func _on_ShowScripts_pressed(): - _toggle_scripts() - -func _on_ScriptsList_item_selected(index): - _select_script(index) - -func _on_TitleBar_mouse_entered(): - _mouse.in_title = true - -func _on_TitleBar_mouse_exited(): - _mouse.in_title = false - -func _input(event): - if(event is InputEventMouseButton): - if(event.button_index == 1): - _mouse.down = event.pressed - if(_mouse.down): - _mouse.down_pos = event.position - - if(_mouse.in_title): - if(event is InputEventMouseMotion and _mouse.down): - set_position(get_position() + (event.position - _mouse.down_pos)) - _mouse.down_pos = event.position - - if(_mouse.in_handle): - if(event is InputEventMouseMotion and _mouse.down): - var new_size = rect_size + event.position - _mouse.down_pos - var new_mouse_down_pos = event.position - rect_size = new_size - _mouse.down_pos = new_mouse_down_pos - _pre_maximize_size = rect_size - -func _on_ResizeHandle_mouse_entered(): - _mouse.in_handle = true - -func _on_ResizeHandle_mouse_exited(): - _mouse.in_handle = false - -# Send scroll type events through to the text box -func _on_FocusBlocker_gui_input(ev): - if(_text_box_blocker_enabled): - if(ev is InputEventPanGesture): - get_text_box()._gui_input(ev) - # convert a drag into a pan gesture so it scrolls. - elif(ev is InputEventScreenDrag): - var converted = InputEventPanGesture.new() - converted.delta = Vector2(0, ev.relative.y) - converted.position = Vector2(0, 0) - get_text_box()._gui_input(converted) - elif(ev is InputEventMouseButton and (ev.button_index == BUTTON_WHEEL_DOWN or ev.button_index == BUTTON_WHEEL_UP)): - get_text_box()._gui_input(ev) - else: - get_text_box()._gui_input(ev) - print(ev) - -func _on_RichTextLabel_gui_input(ev): - pass - # leaving this b/c it is wired up and might have to send - # more signals through - print(ev) - -func _on_Copy_pressed(): - _text_box.select_all() - _text_box.copy() - _text_box.deselect() - -func _on_DisableBlocker_toggled(button_pressed): - _text_box_blocker_enabled = !button_pressed - -func _on_ShowExtras_toggled(button_pressed): - _extras.visible = button_pressed - -func _on_Maximize_pressed(): - if(rect_size == _pre_maximize_size): - maximize() - else: - rect_size = _pre_maximize_size -# #################### -# Private -# #################### -func _run_mode(is_running=true): - if(is_running): - _start_time = OS.get_unix_time() - _time = _start_time - _summary.failing.set_text("0") - _summary.passing.set_text("0") - _is_running = is_running - - _hide_scripts() - var ctrls = $Navigation.get_children() - for i in range(ctrls.size()): - ctrls[i].disabled = is_running - -func _select_script(index): - $Navigation/CurrentScript.set_text(_script_list.get_item_text(index)) - _script_list.select(index) - _update_controls() - -func _toggle_scripts(): - if(_script_list.visible): - _hide_scripts() - else: - _show_scripts() - -func _show_scripts(): - _script_list.show() - -func _hide_scripts(): - _script_list.hide() - -func _update_controls(): - var is_empty = _script_list.get_selected_items().size() == 0 - if(is_empty): - _nav.next.disabled = true - _nav.prev.disabled = true - else: - var index = get_selected_index() - _nav.prev.disabled = index <= 0 - _nav.next.disabled = index >= _script_list.get_item_count() - 1 - - _nav.run.disabled = is_empty - _nav.current_script.disabled = is_empty - _nav.show_scripts.disabled = is_empty - - -# #################### -# Public -# #################### -func run_mode(is_running=true): - _run_mode(is_running) - -func set_scripts(scripts): - _script_list.clear() - for i in range(scripts.size()): - _script_list.add_item(scripts[i]) - _select_script(0) - _update_controls() - -func select_script(index): - _select_script(index) - -func get_selected_index(): - return _script_list.get_selected_items()[0] - -func get_log_level(): - return $LogLevelSlider.value - -func set_log_level(value): - $LogLevelSlider.value = _utils.nvl(value, 0) - -func set_ignore_pause(should): - _ignore_pauses.pressed = should - -func get_ignore_pause(): - return _ignore_pauses.pressed - -func get_text_box(): - return $TextDisplay/RichTextLabel - -func end_run(): - _run_mode(false) - _update_controls() - -func set_progress_script_max(value): - _progress.script.set_max(max(value, 1)) - -func set_progress_script_value(value): - _progress.script.set_value(value) - -func set_progress_test_max(value): - _progress.test.set_max(max(value, 1)) - -func set_progress_test_value(value): - _progress.test.set_value(value) - -func clear_progress(): - _progress.test.set_value(0) - _progress.script.set_value(0) - -func pause(): - print('we got here') - _continue_button.disabled = false - -func set_title(title=null): - if(title == null): - $TitleBar/Title.set_text(DEFAULT_TITLE) - else: - $TitleBar/Title.set_text(title) - -func get_run_duration(): - return $TitleBar/Time.text.to_float() - -func add_passing(amount=1): - if(!_summary): - return - _summary.passing.set_text(str(_summary.passing.get_text().to_int() + amount)) - $Summary.show() - -func add_failing(amount=1): - if(!_summary): - return - _summary.failing.set_text(str(_summary.failing.get_text().to_int() + amount)) - $Summary.show() - -func clear_summary(): - _summary.passing.set_text("0") - _summary.failing.set_text("0") - $Summary.hide() - -func maximize(): - if(is_inside_tree()): - var vp_size_offset = get_viewport().size - rect_size = vp_size_offset / get_scale() - set_position(Vector2(0, 0)) - diff --git a/addons/gut/GutScene.tscn b/addons/gut/GutScene.tscn deleted file mode 100644 index 8d56a4b..0000000 --- a/addons/gut/GutScene.tscn +++ /dev/null @@ -1,299 +0,0 @@ -[gd_scene load_steps=5 format=2] - -[ext_resource path="res://addons/gut/GutScene.gd" type="Script" id=1] - -[sub_resource type="StyleBoxFlat" id=1] -bg_color = Color( 0.193863, 0.205501, 0.214844, 1 ) -corner_radius_top_left = 20 -corner_radius_top_right = 20 - -[sub_resource type="StyleBoxFlat" id=2] -bg_color = Color( 1, 1, 1, 1 ) -border_color = Color( 0, 0, 0, 1 ) -corner_radius_top_left = 5 -corner_radius_top_right = 5 - -[sub_resource type="Theme" id=3] -resource_local_to_scene = true -Panel/styles/panel = SubResource( 2 ) -Panel/styles/panelf = null -Panel/styles/panelnc = null - -[node name="Gut" type="Panel"] -margin_right = 740.0 -margin_bottom = 320.0 -rect_min_size = Vector2( 740, 250 ) -custom_styles/panel = SubResource( 1 ) -script = ExtResource( 1 ) - -[node name="TitleBar" type="Panel" parent="."] -anchor_right = 1.0 -margin_bottom = 40.0 -theme = SubResource( 3 ) - -[node name="Title" type="Label" parent="TitleBar"] -anchor_right = 1.0 -margin_bottom = 40.0 -custom_colors/font_color = Color( 0, 0, 0, 1 ) -text = "Gut" -align = 1 -valign = 1 - -[node name="Time" type="Label" parent="TitleBar"] -anchor_left = 1.0 -anchor_right = 1.0 -margin_left = -114.0 -margin_right = -53.0 -margin_bottom = 40.0 -custom_colors/font_color = Color( 0, 0, 0, 1 ) -text = "9999.99" -valign = 1 - -[node name="Maximize" type="Button" parent="TitleBar"] -anchor_left = 1.0 -anchor_right = 1.0 -margin_left = -30.0 -margin_top = 10.0 -margin_right = -6.0 -margin_bottom = 30.0 -custom_colors/font_color = Color( 0, 0, 0, 1 ) -text = "M" -flat = true - -[node name="ScriptProgress" type="ProgressBar" parent="."] -anchor_top = 1.0 -anchor_bottom = 1.0 -margin_left = 70.0 -margin_top = -100.0 -margin_right = 180.0 -margin_bottom = -70.0 -step = 1.0 - -[node name="Label" type="Label" parent="ScriptProgress"] -margin_left = -70.0 -margin_right = -10.0 -margin_bottom = 24.0 -text = "Scripts" -align = 1 -valign = 1 - -[node name="TestProgress" type="ProgressBar" parent="."] -anchor_top = 1.0 -anchor_bottom = 1.0 -margin_left = 70.0 -margin_top = -70.0 -margin_right = 180.0 -margin_bottom = -40.0 -step = 1.0 - -[node name="Label" type="Label" parent="TestProgress"] -margin_left = -70.0 -margin_right = -10.0 -margin_bottom = 24.0 -text = "Tests" -align = 1 -valign = 1 - -[node name="TextDisplay" type="Panel" parent="."] -anchor_right = 1.0 -anchor_bottom = 1.0 -margin_top = 40.0 -margin_bottom = -107.0 -__meta__ = { -"_edit_group_": true -} - -[node name="RichTextLabel" type="TextEdit" parent="TextDisplay"] -anchor_right = 1.0 -anchor_bottom = 1.0 -mouse_default_cursor_shape = 0 -readonly = true -syntax_highlighting = true -smooth_scrolling = true - -[node name="FocusBlocker" type="Panel" parent="TextDisplay"] -self_modulate = Color( 1, 1, 1, 0 ) -anchor_right = 1.0 -anchor_bottom = 1.0 -margin_right = -10.0 - -[node name="Navigation" type="Panel" parent="."] -self_modulate = Color( 1, 1, 1, 0 ) -anchor_top = 1.0 -anchor_bottom = 1.0 -margin_left = 220.0 -margin_top = -100.0 -margin_right = 580.0 - -[node name="Previous" type="Button" parent="Navigation"] -margin_left = -30.0 -margin_right = 50.0 -margin_bottom = 40.0 -text = "<" - -[node name="Next" type="Button" parent="Navigation"] -margin_left = 230.0 -margin_right = 310.0 -margin_bottom = 40.0 -text = ">" - -[node name="Run" type="Button" parent="Navigation"] -margin_left = 60.0 -margin_right = 220.0 -margin_bottom = 40.0 -text = "Run" - -[node name="CurrentScript" type="Button" parent="Navigation"] -margin_left = -30.0 -margin_top = 50.0 -margin_right = 310.0 -margin_bottom = 90.0 -text = "res://test/unit/test_gut.gd" -clip_text = true - -[node name="ShowScripts" type="Button" parent="Navigation"] -margin_left = 320.0 -margin_top = 50.0 -margin_right = 360.0 -margin_bottom = 90.0 -text = "..." - -[node name="LogLevelSlider" type="HSlider" parent="."] -anchor_top = 1.0 -anchor_bottom = 1.0 -margin_left = 80.0 -margin_top = -40.0 -margin_right = 130.0 -margin_bottom = -20.0 -rect_scale = Vector2( 2, 2 ) -max_value = 2.0 -tick_count = 3 -ticks_on_borders = true - -[node name="Label" type="Label" parent="LogLevelSlider"] -margin_left = -35.0 -margin_top = 5.0 -margin_right = 25.0 -margin_bottom = 25.0 -rect_scale = Vector2( 0.5, 0.5 ) -text = "Log Level" -align = 1 -valign = 1 - -[node name="ScriptsList" type="ItemList" parent="."] -anchor_bottom = 1.0 -margin_left = 180.0 -margin_top = 40.0 -margin_right = 620.0 -margin_bottom = -108.0 -allow_reselect = true - -[node name="ExtraOptions" type="Panel" parent="."] -anchor_left = 1.0 -anchor_top = 1.0 -anchor_right = 1.0 -anchor_bottom = 1.0 -margin_left = -210.0 -margin_top = -246.0 -margin_bottom = -106.0 -custom_styles/panel = SubResource( 1 ) - -[node name="IgnorePause" type="CheckBox" parent="ExtraOptions"] -margin_left = 10.0 -margin_top = 10.0 -margin_right = 128.0 -margin_bottom = 34.0 -rect_scale = Vector2( 1.5, 1.5 ) -text = "Ignore Pauses" - -[node name="DisableBlocker" type="CheckBox" parent="ExtraOptions"] -margin_left = 10.0 -margin_top = 50.0 -margin_right = 130.0 -margin_bottom = 74.0 -rect_scale = Vector2( 1.5, 1.5 ) -text = "Selectable" - -[node name="Copy" type="Button" parent="ExtraOptions"] -margin_left = 20.0 -margin_top = 90.0 -margin_right = 200.0 -margin_bottom = 130.0 -text = "Copy" - -[node name="ResizeHandle" type="Control" parent="."] -anchor_left = 1.0 -anchor_top = 1.0 -anchor_right = 1.0 -anchor_bottom = 1.0 -margin_left = -40.0 -margin_top = -40.0 - -[node name="Continue" type="Panel" parent="."] -self_modulate = Color( 1, 1, 1, 0 ) -anchor_left = 1.0 -anchor_top = 1.0 -anchor_right = 1.0 -anchor_bottom = 1.0 -margin_left = -150.0 -margin_top = -100.0 -margin_right = -30.0 -margin_bottom = -10.0 - -[node name="Continue" type="Button" parent="Continue"] -margin_top = 50.0 -margin_right = 119.0 -margin_bottom = 90.0 -disabled = true -text = "Continue" - -[node name="ShowExtras" type="Button" parent="Continue"] -margin_left = 50.0 -margin_right = 120.0 -margin_bottom = 40.0 -rect_pivot_offset = Vector2( 35, 20 ) -toggle_mode = true -text = "_" - -[node name="Summary" type="Node2D" parent="."] -position = Vector2( 0, 3 ) - -[node name="Passing" type="Label" parent="Summary"] -margin_top = 10.0 -margin_right = 40.0 -margin_bottom = 24.0 -custom_colors/font_color = Color( 0, 0, 0, 1 ) -text = "0" -align = 1 -valign = 1 - -[node name="Failing" type="Label" parent="Summary"] -margin_left = 40.0 -margin_top = 10.0 -margin_right = 80.0 -margin_bottom = 24.0 -custom_colors/font_color = Color( 0, 0, 0, 1 ) -text = "0" -align = 1 -valign = 1 -[connection signal="mouse_entered" from="TitleBar" to="." method="_on_TitleBar_mouse_entered"] -[connection signal="mouse_exited" from="TitleBar" to="." method="_on_TitleBar_mouse_exited"] -[connection signal="draw" from="TitleBar/Maximize" to="." method="_on_Maximize_draw"] -[connection signal="pressed" from="TitleBar/Maximize" to="." method="_on_Maximize_pressed"] -[connection signal="gui_input" from="TextDisplay/RichTextLabel" to="." method="_on_RichTextLabel_gui_input"] -[connection signal="gui_input" from="TextDisplay/FocusBlocker" to="." method="_on_FocusBlocker_gui_input"] -[connection signal="pressed" from="Navigation/Previous" to="." method="_on_Previous_pressed"] -[connection signal="pressed" from="Navigation/Next" to="." method="_on_Next_pressed"] -[connection signal="pressed" from="Navigation/Run" to="." method="_on_Run_pressed"] -[connection signal="pressed" from="Navigation/CurrentScript" to="." method="_on_CurrentScript_pressed"] -[connection signal="pressed" from="Navigation/ShowScripts" to="." method="_on_ShowScripts_pressed"] -[connection signal="value_changed" from="LogLevelSlider" to="." method="_on_LogLevelSlider_value_changed"] -[connection signal="item_selected" from="ScriptsList" to="." method="_on_ScriptsList_item_selected"] -[connection signal="pressed" from="ExtraOptions/IgnorePause" to="." method="_on_IgnorePause_pressed"] -[connection signal="toggled" from="ExtraOptions/DisableBlocker" to="." method="_on_DisableBlocker_toggled"] -[connection signal="pressed" from="ExtraOptions/Copy" to="." method="_on_Copy_pressed"] -[connection signal="mouse_entered" from="ResizeHandle" to="." method="_on_ResizeHandle_mouse_entered"] -[connection signal="mouse_exited" from="ResizeHandle" to="." method="_on_ResizeHandle_mouse_exited"] -[connection signal="pressed" from="Continue/Continue" to="." method="_on_Continue_pressed"] -[connection signal="draw" from="Continue/ShowExtras" to="." method="_on_ShowExtras_draw"] -[connection signal="toggled" from="Continue/ShowExtras" to="." method="_on_ShowExtras_toggled"] diff --git a/addons/gut/LICENSE.md b/addons/gut/LICENSE.md deleted file mode 100644 index a38ac23..0000000 --- a/addons/gut/LICENSE.md +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2018 Tom "Butch" Wesley - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/addons/gut/double_templates/function_template.gd b/addons/gut/double_templates/function_template.gd deleted file mode 100644 index 666952e..0000000 --- a/addons/gut/double_templates/function_template.gd +++ /dev/null @@ -1,6 +0,0 @@ -{func_decleration} - __gut_spy('{method_name}', {param_array}) - if(__gut_should_call_super('{method_name}', {param_array})): - return {super_call} - else: - return __gut_get_stubbed_return('{method_name}', {param_array}) diff --git a/addons/gut/double_templates/script_template.gd b/addons/gut/double_templates/script_template.gd deleted file mode 100644 index 4766a30..0000000 --- a/addons/gut/double_templates/script_template.gd +++ /dev/null @@ -1,36 +0,0 @@ -{extends} - -var __gut_metadata_ = { - path = '{path}', - subpath = '{subpath}', - stubber = __gut_instance_from_id({stubber_id}), - spy = __gut_instance_from_id({spy_id}), -} - -func __gut_instance_from_id(inst_id): - if(inst_id == -1): - return null - else: - return instance_from_id(inst_id) - -func __gut_should_call_super(method_name, called_with): - if(__gut_metadata_.stubber != null): - return __gut_metadata_.stubber.should_call_super(self, method_name, called_with) - else: - return false - -var __gut_utils_ = load('res://addons/gut/utils.gd').new() - -func __gut_spy(method_name, called_with): - if(__gut_metadata_.spy != null): - __gut_metadata_.spy.add_call(self, method_name, called_with) - -func __gut_get_stubbed_return(method_name, called_with): - if(__gut_metadata_.stubber != null): - return __gut_metadata_.stubber.get_return(self, method_name, called_with) - else: - return null - -# ------------------------------------------------------------------------------ -# Methods start here -# ------------------------------------------------------------------------------ diff --git a/addons/gut/doubler.gd b/addons/gut/doubler.gd deleted file mode 100644 index 790e566..0000000 --- a/addons/gut/doubler.gd +++ /dev/null @@ -1,525 +0,0 @@ -# ------------------------------------------------------------------------------ -# Utility class to hold the local and built in methods separately. Add all local -# methods FIRST, then add built ins. -# ------------------------------------------------------------------------------ -class ScriptMethods: - # List of methods that should not be overloaded when they are not defined - # in the class being doubled. These either break things if they are - # overloaded or do not have a "super" equivalent so we can't just pass - # through. - var _blacklist = [ - 'has_method', - 'get_script', - 'get', - '_notification', - 'get_path', - '_enter_tree', - '_exit_tree', - '_process', - '_draw', - '_physics_process', - '_input', - '_unhandled_input', - '_unhandled_key_input', - '_set', - '_get', # probably - 'emit_signal', # can't handle extra parameters to be sent with signal. - 'draw_mesh', # issue with one parameter, value is `Null((..), (..), (..))`` - '_to_string', # nonexistant function ._to_string - '_get_minimum_size', # Nonexistent function _get_minimum_size - ] - - var built_ins = [] - var local_methods = [] - var _method_names = [] - - func is_blacklisted(method_meta): - return _blacklist.find(method_meta.name) != -1 - - func _add_name_if_does_not_have(method_name): - var should_add = _method_names.find(method_name) == -1 - if(should_add): - _method_names.append(method_name) - return should_add - - func add_built_in_method(method_meta): - var did_add = _add_name_if_does_not_have(method_meta.name) - if(did_add and !is_blacklisted(method_meta)): - built_ins.append(method_meta) - - func add_local_method(method_meta): - var did_add = _add_name_if_does_not_have(method_meta.name) - if(did_add): - local_methods.append(method_meta) - - func to_s(): - var text = "Locals\n" - for i in range(local_methods.size()): - text += str(" ", local_methods[i].name, "\n") - text += "Built-Ins\n" - for i in range(built_ins.size()): - text += str(" ", built_ins[i].name, "\n") - return text - -# ------------------------------------------------------------------------------ -# Helper class to deal with objects and inner classes. -# ------------------------------------------------------------------------------ -class ObjectInfo: - var _path = null - var _subpaths = [] - var _utils = load('res://addons/gut/utils.gd').new() - var _method_strategy = null - var make_partial_double = false - var scene_path = null - var _native_class = null - var _native_class_instance = null - - func _init(path, subpath=null): - _path = path - if(subpath != null): - _subpaths = _utils.split_string(subpath, '/') - - # Returns an instance of the class/inner class - func instantiate(): - var to_return = null - if(is_native()): - to_return = _native_class.new() - else: - to_return = get_loaded_class().new() - return to_return - - # Can't call it get_class because that is reserved so it gets this ugly name. - # Loads up the class and then any inner classes to give back a reference to - # the desired Inner class (if there is any) - func get_loaded_class(): - var LoadedClass = load(_path) - for i in range(_subpaths.size()): - LoadedClass = LoadedClass.get(_subpaths[i]) - return LoadedClass - - func to_s(): - return str(_path, '[', get_subpath(), ']') - - func get_path(): - return _path - - func get_subpath(): - return _utils.join_array(_subpaths, '/') - - func has_subpath(): - return _subpaths.size() != 0 - - func get_extends_text(): - var extend = null - if(is_native()): - extend = str("extends ", get_native_class_name()) - else: - extend = str("extends '", get_path(), "'") - - if(has_subpath()): - extend += str('.', get_subpath().replace('/', '.')) - - return extend - - func get_method_strategy(): - return _method_strategy - - func set_method_strategy(method_strategy): - _method_strategy = method_strategy - - func is_native(): - return _native_class != null - - func set_native_class(native_class): - _native_class = native_class - _native_class_instance = native_class.new() - _path = _native_class_instance.get_class() - - func get_native_class_name(): - return _native_class_instance.get_class() - -# ------------------------------------------------------------------------------ -# Allows for interacting with a file but only creating a string. This was done -# to ease the transition from files being created for doubles to loading -# doubles from a string. This allows the files to be created for debugging -# purposes since reading a file is easier than reading a dumped out string. -# ------------------------------------------------------------------------------ -class FileOrString: - extends File - - var _do_file = false - var _contents = '' - var _path = null - - func open(path, mode): - _path = path - if(_do_file): - return .open(path, mode) - else: - return OK - - func close(): - if(_do_file): - return .close() - - func store_string(s): - if(_do_file): - .store_string(s) - _contents += s - - func get_contents(): - return _contents - - func get_path(): - return _path - - func load_it(): - if(_contents != ''): - var script = GDScript.new() - script.set_source_code(get_contents()) - script.reload() - return script - else: - return load(_path) - -# ------------------------------------------------------------------------------ -# A stroke of genius if I do say so. This allows for doubling a scene without -# having to write any files. By overloading instance we can make whatever -# we want. -# ------------------------------------------------------------------------------ -class PackedSceneDouble: - extends PackedScene - var _script = null - var _scene = null - - func set_script_obj(obj): - _script = obj - - func instance(edit_state=0): - var inst = _scene.instance(edit_state) - if(_script != null): - inst.set_script(_script) - return inst - - func load_scene(path): - _scene = load(path) - - - - -# ------------------------------------------------------------------------------ -# START Doubler -# ------------------------------------------------------------------------------ -var _utils = load('res://addons/gut/utils.gd').new() - -var _ignored_methods = _utils.OneToMany.new() -var _stubber = _utils.Stubber.new() -var _lgr = _utils.get_logger() -var _method_maker = _utils.MethodMaker.new() - -var _output_dir = 'user://gut_temp_directory' -var _double_count = 0 # used in making files names unique -var _spy = null -var _strategy = null -var _base_script_text = _utils.get_file_as_text('res://addons/gut/double_templates/script_template.gd') -var _make_files = false - -# These methods all call super implicitly. Stubbing them to call super causes -# super to be called twice. -var _non_super_methods = [ - "_init", - "_ready", - "_notification", - "_enter_world", - "_exit_world", - "_process", - "_physics_process", - "_exit_tree", - "_gui_input ", -] - -func _init(strategy=_utils.DOUBLE_STRATEGY.PARTIAL): - set_logger(_utils.get_logger()) - _strategy = strategy - -# ############### -# Private -# ############### -func _get_indented_line(indents, text): - var to_return = '' - for _i in range(indents): - to_return += "\t" - return str(to_return, text, "\n") - - -func _stub_to_call_super(obj_info, method_name): - if(_non_super_methods.has(method_name)): - return - var path = obj_info.get_path() - if(obj_info.scene_path != null): - path = obj_info.scene_path - var params = _utils.StubParams.new(path, method_name, obj_info.get_subpath()) - params.to_call_super() - _stubber.add_stub(params) - -func _get_base_script_text(obj_info, override_path): - var path = obj_info.get_path() - if(override_path != null): - path = override_path - - var stubber_id = -1 - if(_stubber != null): - stubber_id = _stubber.get_instance_id() - - var spy_id = -1 - if(_spy != null): - spy_id = _spy.get_instance_id() - - var values = { - "path":path, - "subpath":obj_info.get_subpath(), - "stubber_id":stubber_id, - "spy_id":spy_id, - "extends":obj_info.get_extends_text() - } - return _base_script_text.format(values) - -func _write_file(obj_info, dest_path, override_path=null): - var base_script = _get_base_script_text(obj_info, override_path) - var script_methods = _get_methods(obj_info) - - var f = FileOrString.new() - f._do_file = _make_files - var f_result = f.open(dest_path, f.WRITE) - - if(f_result != OK): - _lgr.error(str('Error creating file ', dest_path)) - _lgr.error(str('Could not create double for :', obj_info.to_s())) - return - - f.store_string(base_script) - - for i in range(script_methods.local_methods.size()): - if(obj_info.make_partial_double): - _stub_to_call_super(obj_info, script_methods.local_methods[i].name) - f.store_string(_get_func_text(script_methods.local_methods[i])) - - for i in range(script_methods.built_ins.size()): - _stub_to_call_super(obj_info, script_methods.built_ins[i].name) - f.store_string(_get_func_text(script_methods.built_ins[i])) - - f.close() - return f - -func _double_scene_and_script(scene_info): - var to_return = PackedSceneDouble.new() - to_return.load_scene(scene_info.get_path()) - - var inst = load(scene_info.get_path()).instance() - var script_path = null - if(inst.get_script()): - script_path = inst.get_script().get_path() - inst.free() - - if(script_path): - var oi = ObjectInfo.new(script_path) - oi.set_method_strategy(scene_info.get_method_strategy()) - oi.make_partial_double = scene_info.make_partial_double - oi.scene_path = scene_info.get_path() - to_return.set_script_obj(_double(oi, scene_info.get_path()).load_it()) - - return to_return - -func _get_methods(object_info): - var obj = object_info.instantiate() - # any method in the script or super script - var script_methods = ScriptMethods.new() - var methods = obj.get_method_list() - - # first pass is for local methods only - for i in range(methods.size()): - # 65 is a magic number for methods in script, though documentation - # says 64. This picks up local overloads of base class methods too. - if(methods[i].flags == 65 and !_ignored_methods.has(object_info.get_path(), methods[i]['name'])): - script_methods.add_local_method(methods[i]) - - - if(object_info.get_method_strategy() == _utils.DOUBLE_STRATEGY.FULL): - # second pass is for anything not local - for i in range(methods.size()): - # 65 is a magic number for methods in script, though documentation - # says 64. This picks up local overloads of base class methods too. - if(methods[i].flags != 65 and !_ignored_methods.has(object_info.get_path(), methods[i]['name'])): - script_methods.add_built_in_method(methods[i]) - - return script_methods - -func _get_inst_id_ref_str(inst): - var ref_str = 'null' - if(inst): - ref_str = str('instance_from_id(', inst.get_instance_id(),')') - return ref_str - -func _get_func_text(method_hash): - return _method_maker.get_function_text(method_hash) + "\n" - -# returns the path to write the double file to -func _get_temp_path(object_info): - var file_name = null - var extension = null - if(object_info.is_native()): - file_name = object_info.get_native_class_name() - extension = 'gd' - else: - file_name = object_info.get_path().get_file().get_basename() - extension = object_info.get_path().get_extension() - - if(object_info.has_subpath()): - file_name += '__' + object_info.get_subpath().replace('/', '__') - - file_name += str('__dbl', _double_count, '__.', extension) - - var to_return = _output_dir.plus_file(file_name) - return to_return - -func _load_double(fileOrString): - return fileOrString.load_it() - -func _double(obj_info, override_path=null): - var temp_path = _get_temp_path(obj_info) - var result = _write_file(obj_info, temp_path, override_path) - _double_count += 1 - return result - -func _double_script(path, make_partial, strategy): - var oi = ObjectInfo.new(path) - oi.make_partial_double = make_partial - oi.set_method_strategy(strategy) - return _double(oi).load_it() - -func _double_inner(path, subpath, make_partial, strategy): - var oi = ObjectInfo.new(path, subpath) - oi.set_method_strategy(strategy) - oi.make_partial_double = make_partial - return _double(oi).load_it() - -func _double_scene(path, make_partial, strategy): - var oi = ObjectInfo.new(path) - oi.set_method_strategy(strategy) - oi.make_partial_double = make_partial - return _double_scene_and_script(oi) - -func _double_gdnative(native_class, make_partial, strategy): - var oi = ObjectInfo.new(null) - oi.set_native_class(native_class) - oi.set_method_strategy(strategy) - oi.make_partial_double = make_partial - return _double(oi).load_it() - -# ############### -# Public -# ############### -func get_output_dir(): - return _output_dir - -func set_output_dir(output_dir): - if(output_dir != null): - _output_dir = output_dir - if(_make_files): - var d = Directory.new() - d.make_dir_recursive(output_dir) - -func get_spy(): - return _spy - -func set_spy(spy): - _spy = spy - -func get_stubber(): - return _stubber - -func set_stubber(stubber): - _stubber = stubber - -func get_logger(): - return _lgr - -func set_logger(logger): - _lgr = logger - _method_maker.set_logger(logger) - -func get_strategy(): - return _strategy - -func set_strategy(strategy): - _strategy = strategy - -func partial_double_scene(path, strategy=_strategy): - return _double_scene(path, true, strategy) - -# double a scene -func double_scene(path, strategy=_strategy): - return _double_scene(path, false, strategy) - -# double a script/object -func double(path, strategy=_strategy): - return _double_script(path, false, strategy) - -func partial_double(path, strategy=_strategy): - return _double_script(path, true, strategy) - -func partial_double_inner(path, subpath, strategy=_strategy): - return _double_inner(path, subpath, true, strategy) - -# double an inner class in a script -func double_inner(path, subpath, strategy=_strategy): - return _double_inner(path, subpath, false, strategy) - -# must always use FULL strategy since this is a native class and you won't get -# any methods if you don't use FULL -func double_gdnative(native_class): - return _double_gdnative(native_class, false, _utils.DOUBLE_STRATEGY.FULL) - -# must always use FULL strategy since this is a native class and you won't get -# any methods if you don't use FULL -func partial_double_gdnative(native_class): - return _double_gdnative(native_class, true, _utils.DOUBLE_STRATEGY.FULL) - -func clear_output_directory(): - if(!_make_files): - return false - - var did = false - if(_output_dir.find('user://') == 0): - var d = Directory.new() - var result = d.open(_output_dir) - # BIG GOTCHA HERE. If it cannot open the dir w/ erro 31, then the - # directory becomes res:// and things go on normally and gut clears out - # out res:// which is SUPER BAD. - if(result == OK): - d.list_dir_begin(true) - var f = d.get_next() - while(f != ''): - d.remove(f) - f = d.get_next() - did = true - return did - -func delete_output_directory(): - var did = clear_output_directory() - if(did): - var d = Directory.new() - d.remove(_output_dir) - -func add_ignored_method(path, method_name): - _ignored_methods.add(path, method_name) - -func get_ignored_methods(): - return _ignored_methods - -func get_make_files(): - return _make_files - -func set_make_files(make_files): - _make_files = make_files - set_output_dir(_output_dir) diff --git a/addons/gut/gut.gd b/addons/gut/gut.gd deleted file mode 100644 index 34f18c7..0000000 --- a/addons/gut/gut.gd +++ /dev/null @@ -1,1343 +0,0 @@ -################################################################################ -#(G)odot (U)nit (T)est class -# -################################################################################ -#The MIT License (MIT) -#===================== -# -#Copyright (c) 2019 Tom "Butch" Wesley -# -#Permission is hereby granted, free of charge, to any person obtaining a copy -#of this software and associated documentation files (the "Software"), to deal -#in the Software without restriction, including without limitation the rights -#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -#copies of the Software, and to permit persons to whom the Software is -#furnished to do so, subject to the following conditions: -# -#The above copyright notice and this permission notice shall be included in -#all copies or substantial portions of the Software. -# -#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -#THE SOFTWARE. -# -################################################################################ -# View readme for usage details. -# -# Version 6.8.2 -################################################################################ -#extends "res://addons/gut/gut_gui.gd" -tool -extends Control -var _version = '6.8.2' - -var _utils = load('res://addons/gut/utils.gd').new() -var _lgr = _utils.get_logger() -# Used to prevent multiple messages for deprecated setup/teardown messages -var _deprecated_tracker = _utils.ThingCounter.new() - -# ########################### -# Editor Variables -# ########################### -export(String) var _select_script = '' -export(String) var _tests_like = '' -export(String) var _inner_class_name = '' - -export var _run_on_load = false -export var _should_maximize = false setget set_should_maximize, get_should_maximize - -export var _should_print_to_console = true setget set_should_print_to_console, get_should_print_to_console -export(int, 'Failures only', 'Tests and failures', 'Everything') var _log_level = 1 setget set_log_level, get_log_level -# This var is JUST used to expose this setting in the editor -# the var that is used is in the _yield_between hash. -export var _yield_between_tests = true setget set_yield_between_tests, get_yield_between_tests -export var _disable_strict_datatype_checks = false setget disable_strict_datatype_checks, is_strict_datatype_checks_disabled -# The prefix used to get tests. -export var _test_prefix = 'test_' -export var _file_prefix = 'test_' -export var _file_extension = '.gd' -export var _inner_class_prefix = 'Test' - -export(String) var _temp_directory = 'user://gut_temp_directory' -export(String) var _export_path = '' setget set_export_path, get_export_path - -export var _include_subdirectories = false setget set_include_subdirectories, get_include_subdirectories -# Allow user to add test directories via editor. This is done with strings -# instead of an array because the interface for editing arrays is really -# cumbersome and complicates testing because arrays set through the editor -# apply to ALL instances. This also allows the user to use the built in -# dialog to pick a directory. -export(String, DIR) var _directory1 = '' -export(String, DIR) var _directory2 = '' -export(String, DIR) var _directory3 = '' -export(String, DIR) var _directory4 = '' -export(String, DIR) var _directory5 = '' -export(String, DIR) var _directory6 = '' -export(int, 'FULL', 'PARTIAL') var _double_strategy = _utils.DOUBLE_STRATEGY.PARTIAL setget set_double_strategy, get_double_strategy -export(String, FILE) var _pre_run_script = '' setget set_pre_run_script, get_pre_run_script -export(String, FILE) var _post_run_script = '' setget set_post_run_script, get_post_run_script -export(bool) var _color_output = false setget set_color_output, get_color_output - -# The instance that is created from _pre_run_script. Accessible from -# get_pre_run_script_instance. -var _pre_run_script_instance = null -var _post_run_script_instance = null # This is not used except in tests. - -# ########################### -# Other Vars -# ########################### -const LOG_LEVEL_FAIL_ONLY = 0 -const LOG_LEVEL_TEST_AND_FAILURES = 1 -const LOG_LEVEL_ALL_ASSERTS = 2 -const WAITING_MESSAGE = '/# waiting #/' -const PAUSE_MESSAGE = '/# Pausing. Press continue button...#/' - -var _script_name = null -var _test_collector = _utils.TestCollector.new() - -# The instanced scripts. This is populated as the scripts are run. -var _test_script_objects = [] - -var _waiting = false -var _done = false -var _is_running = false - -var _current_test = null -var _log_text = "" - -var _pause_before_teardown = false -# when true _pause_before_teardown will be ignored. useful -# when batch processing and you don't want to watch. -var _ignore_pause_before_teardown = false -var _wait_timer = Timer.new() - -var _yield_between = { - should = false, - timer = Timer.new(), - after_x_tests = 5, - tests_since_last_yield = 0 -} - -var _was_yield_method_called = false -# used when yielding to gut instead of some other -# signal. Start with set_yield_time() -var _yield_timer = Timer.new() - -var _unit_test_name = '' -var _new_summary = null - -var _yielding_to = { - obj = null, - signal_name = '' -} - -var _stubber = _utils.Stubber.new() -var _doubler = _utils.Doubler.new() -var _spy = _utils.Spy.new() -var _gui = null - -const SIGNAL_TESTS_FINISHED = 'tests_finished' -const SIGNAL_STOP_YIELD_BEFORE_TEARDOWN = 'stop_yield_before_teardown' - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func _init(): - # This min size has to be what the min size of the GutScene's min size is - # but it has to be set here and not inferred i think. - rect_min_size =Vector2(740, 250) - - add_user_signal(SIGNAL_TESTS_FINISHED) - add_user_signal(SIGNAL_STOP_YIELD_BEFORE_TEARDOWN) - add_user_signal('timeout') - add_user_signal('done_waiting') - _doubler.set_output_dir(_temp_directory) - _doubler.set_stubber(_stubber) - _doubler.set_spy(_spy) - - _lgr.set_gut(self) - _doubler.set_logger(_lgr) - _spy.set_logger(_lgr) - - - _stubber.set_logger(_lgr) - _test_collector.set_logger(_lgr) - _gui = load('res://addons/gut/GutScene.tscn').instance() - -# ------------------------------------------------------------------------------ -# Initialize controls -# ------------------------------------------------------------------------------ -func _ready(): - _lgr.info(str('using [', OS.get_user_data_dir(), '] for temporary output.')) - - set_process_input(true) - - add_child(_wait_timer) - _wait_timer.set_wait_time(1) - _wait_timer.set_one_shot(true) - - add_child(_yield_between.timer) - _wait_timer.set_one_shot(true) - - add_child(_yield_timer) - _yield_timer.set_one_shot(true) - _yield_timer.connect('timeout', self, '_yielding_callback') - - _setup_gui() - - add_directory(_directory1) - add_directory(_directory2) - add_directory(_directory3) - add_directory(_directory4) - add_directory(_directory5) - add_directory(_directory6) - - if(_select_script != null): - select_script(_select_script) - - if(_tests_like != null): - set_unit_test_name(_tests_like) - - if(_run_on_load): - test_scripts(_select_script == null) - - if(_should_maximize): - maximize() - - # hide the panel that IS gut so that only the GUI is seen - self.self_modulate = Color(1,1,1,0) - show() - var v_info = Engine.get_version_info() - p(str('Godot version: ', v_info.major, '.', v_info.minor, '.', v_info.patch)) - p(str('GUT version: ', get_version())) - - -################################################################################ -# -# GUI Events and setup -# -################################################################################ -func _setup_gui(): - # This is how we get the size of the control to translate to the gui when - # the scene is run. This is also another reason why the min_rect_size - # must match between both gut and the gui. - _gui.rect_size = self.rect_size - add_child(_gui) - _gui.set_anchor(MARGIN_RIGHT, ANCHOR_END) - _gui.set_anchor(MARGIN_BOTTOM, ANCHOR_END) - _gui.connect('run_single_script', self, '_on_run_one') - _gui.connect('run_script', self, '_on_new_gui_run_script') - _gui.connect('end_pause', self, '_on_new_gui_end_pause') - _gui.connect('ignore_pause', self, '_on_new_gui_ignore_pause') - _gui.connect('log_level_changed', self, '_on_log_level_changed') - var _foo = connect('tests_finished', _gui, 'end_run') - -func _add_scripts_to_gui(): - var scripts = [] - for i in range(_test_collector.scripts.size()): - var s = _test_collector.scripts[i] - var txt = '' - if(s.has_inner_class()): - txt = str(' - ', s.inner_class_name, ' (', s.tests.size(), ')') - else: - txt = str(s.get_full_name(), ' (', s.tests.size(), ')') - scripts.append(txt) - _gui.set_scripts(scripts) - -func _on_run_one(index): - clear_text() - var indexes = [index] - if(!_test_collector.scripts[index].has_inner_class()): - indexes = _get_indexes_matching_path(_test_collector.scripts[index].path) - _test_the_scripts(indexes) - -func _on_new_gui_run_script(index): - var indexes = [] - clear_text() - for i in range(index, _test_collector.scripts.size()): - indexes.append(i) - _test_the_scripts(indexes) - -func _on_new_gui_end_pause(): - _pause_before_teardown = false - emit_signal(SIGNAL_STOP_YIELD_BEFORE_TEARDOWN) - -func _on_new_gui_ignore_pause(should): - _ignore_pause_before_teardown = should - -func _on_log_level_changed(value): - _log_level = value - -##################### -# -# Events -# -##################### - -# ------------------------------------------------------------------------------ -# Timeout for the built in timer. emits the timeout signal. Start timer -# with set_yield_time() -# ------------------------------------------------------------------------------ -func _yielding_callback(from_obj=false): - if(_yielding_to.obj): - _yielding_to.obj.call_deferred( - "disconnect", - _yielding_to.signal_name, self, - '_yielding_callback') - _yielding_to.obj = null - _yielding_to.signal_name = '' - - if(from_obj): - # we must yiled for a little longer after the signal is emitted so that - # the signal can propagate to other objects. This was discovered trying - # to assert that obj/signal_name was emitted. Without this extra delay - # the yield returns and processing finishes before the rest of the - # objects can get the signal. This works b/c the timer will timeout - # and come back into this method but from_obj will be false. - _yield_timer.set_wait_time(.1) - _yield_timer.start() - else: - emit_signal('timeout') - -# ------------------------------------------------------------------------------ -# completed signal for GDScriptFucntionState returned from a test script that -# has yielded -# ------------------------------------------------------------------------------ -func _on_test_script_yield_completed(): - _waiting = false - -##################### -# -# Private -# -##################### - -# ------------------------------------------------------------------------------ -# Convert the _summary dictionary into text -# ------------------------------------------------------------------------------ -func _get_summary_text(): - var to_return = "\n\n*****************\nRun Summary\n*****************" - - to_return += "\n" + _new_summary.get_summary_text() + "\n" - - var logger_text = '' - if(_lgr.get_errors().size() > 0): - logger_text += str("\n * ", _lgr.get_errors().size(), ' Errors.') - if(_lgr.get_warnings().size() > 0): - logger_text += str("\n * ", _lgr.get_warnings().size(), ' Warnings.') - if(_lgr.get_deprecated().size() > 0): - logger_text += str("\n * ", _lgr.get_deprecated().size(), ' Deprecated calls.') - if(logger_text != ''): - logger_text = "\nWarnings/Errors:" + logger_text + "\n\n" - to_return += logger_text - - if(_new_summary.get_totals().tests > 0): - to_return += '+++ ' + str(_new_summary.get_totals().passing) + ' passed ' + str(_new_summary.get_totals().failing) + ' failed. ' + \ - "Tests finished in: " + str(_gui.get_run_duration()) + ' +++' - var c = Color(0, 1, 0) - if(_new_summary.get_totals().failing > 0): - c = Color(1, 0, 0) - elif(_new_summary.get_totals().pending > 0): - c = Color(1, 1, .8) - - _gui.get_text_box().add_color_region('+++', '+++', c) - else: - to_return += '+++ No tests ran +++' - _gui.get_text_box().add_color_region('+++', '+++', Color(1, 0, 0)) - - return to_return - -func _validate_hook_script(path): - var result = { - valid = true, - instance = null - } - - # empty path is valid but will have a null instance - if(path == ''): - return result - - var f = File.new() - if(f.file_exists(path)): - var inst = load(path).new() - if(inst and inst is _utils.HookScript): - result.instance = inst - result.valid = true - else: - result.valid = false - _lgr.error('The hook script [' + path + '] does not extend res://addons/gut/hook_script.gd') - else: - result.valid = false - _lgr.error('The hook script [' + path + '] does not exist.') - - return result - - -# ------------------------------------------------------------------------------ -# Runs a hook script. Script must exist, and must extend -# res://addons/gut/hook_script.gd -# ------------------------------------------------------------------------------ -func _run_hook_script(inst): - if(inst != null): - inst.gut = self - inst.run() - return inst - -# ------------------------------------------------------------------------------ -# Initialize variables for each run of a single test script. -# ------------------------------------------------------------------------------ -func _init_run(): - var valid = true - _test_collector.set_test_class_prefix(_inner_class_prefix) - _test_script_objects = [] - _new_summary = _utils.Summary.new() - - _log_text = "" - - _current_test = null - - _is_running = true - - _yield_between.tests_since_last_yield = 0 - - _gui.get_text_box().clear_colors() - _gui.get_text_box().add_keyword_color("PASSED", Color(0, 1, 0)) - _gui.get_text_box().add_keyword_color("FAILED", Color(1, 0, 0)) - _gui.get_text_box().add_color_region('/#', '#/', Color(.9, .6, 0)) - _gui.get_text_box().add_color_region('/-', '-/', Color(1, 1, 0)) - _gui.get_text_box().add_color_region('/*', '*/', Color(.5, .5, 1)) - - var pre_hook_result = _validate_hook_script(_pre_run_script) - _pre_run_script_instance = pre_hook_result.instance - var post_hook_result = _validate_hook_script(_post_run_script) - _post_run_script_instance = post_hook_result.instance - - valid = pre_hook_result.valid and post_hook_result.valid - - return valid - - - - -# ------------------------------------------------------------------------------ -# Print out run information and close out the run. -# ------------------------------------------------------------------------------ -func _end_run(): - p(_get_summary_text(), 0) - p("\n") - if(!_utils.is_null_or_empty(_select_script)): - p('Ran Scripts matching ' + _select_script) - if(!_utils.is_null_or_empty(_unit_test_name)): - p('Ran Tests matching ' + _unit_test_name) - if(!_utils.is_null_or_empty(_inner_class_name)): - p('Ran Inner Classes matching ' + _inner_class_name) - - # For some reason the text edit control isn't scrolling to the bottom after - # the summary is printed. As a workaround, yield for a short time and - # then move the cursor. I found this workaround through trial and error. - _yield_between.timer.set_wait_time(0.1) - _yield_between.timer.start() - yield(_yield_between.timer, 'timeout') - _gui.get_text_box().cursor_set_line(_gui.get_text_box().get_line_count()) - - _is_running = false - update() - _run_hook_script(_post_run_script_instance) - emit_signal(SIGNAL_TESTS_FINISHED) - _gui.set_title("Finished. " + str(get_fail_count()) + " failures.") - - -# ------------------------------------------------------------------------------ -# Checks the passed in thing to see if it is a "function state" object that gets -# returned when a function yields. -# ------------------------------------------------------------------------------ -func _is_function_state(script_result): - return script_result != null and \ - typeof(script_result) == TYPE_OBJECT and \ - script_result is GDScriptFunctionState - -# ------------------------------------------------------------------------------ -# Print out the heading for a new script -# ------------------------------------------------------------------------------ -func _print_script_heading(script): - if(_does_class_name_match(_inner_class_name, script.inner_class_name)): - p("\n/-----------------------------------------") - if(script.inner_class_name == null): - p("Running Script " + script.path, 0) - else: - p("Running Class [" + script.inner_class_name + "] in " + script.path, 0) - - if(!_utils.is_null_or_empty(_inner_class_name) and _does_class_name_match(_inner_class_name, script.inner_class_name)): - p(str(' [',script.inner_class_name, '] matches [', _inner_class_name, ']')) - - if(!_utils.is_null_or_empty(_unit_test_name)): - p(' Only running tests like: "' + _unit_test_name + '"') - - p("-----------------------------------------/") - -# ------------------------------------------------------------------------------ -# Just gets more logic out of _test_the_scripts. Decides if we should yield after -# this test based on flags and counters. -# ------------------------------------------------------------------------------ -func _should_yield_now(): - var should = _yield_between.should and \ - _yield_between.tests_since_last_yield == _yield_between.after_x_tests - if(should): - _yield_between.tests_since_last_yield = 0 - else: - _yield_between.tests_since_last_yield += 1 - return should - -# ------------------------------------------------------------------------------ -# Yes if the class name is null or the script's class name includes class_name -# ------------------------------------------------------------------------------ -func _does_class_name_match(the_class_name, script_class_name): - return (the_class_name == null or the_class_name == '') or (script_class_name != null and script_class_name.find(the_class_name) != -1) - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func _setup_script(test_script): - test_script.gut = self - test_script.set_logger(_lgr) - add_child(test_script) - _test_script_objects.append(test_script) - - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func _do_yield_between(time): - _yield_between.timer.set_wait_time(time) - _yield_between.timer.start() - return _yield_between.timer - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func _wait_for_done(result): - var iter_counter = 0 - var print_after = 3 - - # sets waiting to false. - result.connect('completed', self, '_on_test_script_yield_completed') - - if(!_was_yield_method_called): - p('/# Yield detected, waiting #/') - - _was_yield_method_called = false - _waiting = true - _wait_timer.set_wait_time(0.25) - - while(_waiting): - iter_counter += 1 - if(iter_counter > print_after): - p(WAITING_MESSAGE, 2) - iter_counter = 0 - _wait_timer.start() - yield(_wait_timer, 'timeout') - - emit_signal('done_waiting') - -# ------------------------------------------------------------------------------ -# returns self so it can be integrated into the yield call. -# ------------------------------------------------------------------------------ -func _wait_for_continue_button(): - p(PAUSE_MESSAGE, 0) - _waiting = true - return self - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func _call_deprecated_script_method(script, method, alt): - if(script.has_method(method)): - var txt = str(script, '-', method) - if(!_deprecated_tracker.has(txt)): - # Removing the deprecated line. I think it's still too early to - # start bothering people with this. Left everything here though - # because I don't want to remember how I did this last time. - #_lgr.deprecated(str('The method ', method, ' has been deprecated, use ', alt, ' instead.')) - _deprecated_tracker.add(txt) - script.call(method) - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func _get_indexes_matching_script_name(name): - var indexes = [] # empty runs all - for i in range(_test_collector.scripts.size()): - if(_test_collector.scripts[i].get_filename().find(name) != -1): - indexes.append(i) - return indexes - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func _get_indexes_matching_path(path): - var indexes = [] - for i in range(_test_collector.scripts.size()): - if(_test_collector.scripts[i].path == path): - indexes.append(i) - return indexes - -# ------------------------------------------------------------------------------ -# Run all tests in a script. This is the core logic for running tests. -# -# Note, this has to stay as a giant monstrosity of a method because of the -# yields. -# ------------------------------------------------------------------------------ -func _test_the_scripts(indexes=[]): - var is_valid = _init_run() - if(!is_valid): - _lgr.error('Something went wrong and the run was aborted.') - return - - _run_hook_script(_pre_run_script_instance) - if(_pre_run_script_instance!= null and _pre_run_script_instance.should_abort()): - _lgr.error('pre-run abort') - emit_signal(SIGNAL_TESTS_FINISHED) - return - - _gui.run_mode() - - var indexes_to_run = [] - if(indexes.size()==0): - for i in range(_test_collector.scripts.size()): - indexes_to_run.append(i) - else: - indexes_to_run = indexes - - _gui.set_progress_script_max(indexes_to_run.size()) # New way - _gui.set_progress_script_value(0) - - if(_doubler.get_strategy() == _utils.DOUBLE_STRATEGY.FULL): - _lgr.info("Using Double Strategy FULL as default strategy. Keep an eye out for weirdness, this is still experimental.") - - # loop through scripts - for test_indexes in range(indexes_to_run.size()): - var the_script = _test_collector.scripts[indexes_to_run[test_indexes]] - - if(the_script.tests.size() > 0): - _gui.set_title('Running: ' + the_script.get_full_name()) - _print_script_heading(the_script) - _new_summary.add_script(the_script.get_full_name()) - - var test_script = the_script.get_new() - var script_result = null - _setup_script(test_script) - _doubler.set_strategy(_double_strategy) - - # yield between test scripts so things paint - if(_yield_between.should): - yield(_do_yield_between(0.01), 'timeout') - - # !!! - # Hack so there isn't another indent to this monster of a method. if - # inner class is set and we do not have a match then empty the tests - # for the current test. - # !!! - if(!_does_class_name_match(_inner_class_name, the_script.inner_class_name)): - the_script.tests = [] - else: - # call both pre-all-tests methods until prerun_setup is removed - _call_deprecated_script_method(test_script, 'prerun_setup', 'before_all') - test_script.before_all() - - _gui.set_progress_test_max(the_script.tests.size()) # New way - - # Each test in the script - for i in range(the_script.tests.size()): - _stubber.clear() - _spy.clear() - _doubler.clear_output_directory() - _current_test = the_script.tests[i] - - if((_unit_test_name != '' and _current_test.name.find(_unit_test_name) > -1) or - (_unit_test_name == '')): - p(_current_test.name, 1) - _new_summary.add_test(_current_test.name) - - # yield so things paint - if(_should_yield_now()): - yield(_do_yield_between(0.001), 'timeout') - - _call_deprecated_script_method(test_script, 'setup', 'before_each') - test_script.before_each() - - - #When the script yields it will return a GDScriptFunctionState object - script_result = test_script.call(_current_test.name) - if(_is_function_state(script_result)): - _wait_for_done(script_result) - yield(self, 'done_waiting') - - #if the test called pause_before_teardown then yield until - #the continue button is pressed. - if(_pause_before_teardown and !_ignore_pause_before_teardown): - _gui.pause() - yield(_wait_for_continue_button(), SIGNAL_STOP_YIELD_BEFORE_TEARDOWN) - - test_script.clear_signal_watcher() - - # call each post-each-test method until teardown is removed. - _call_deprecated_script_method(test_script, 'teardown', 'after_each') - test_script.after_each() - - if(_current_test.passed): - _gui.get_text_box().add_keyword_color(_current_test.name, Color(0, 1, 0)) - else: - _gui.get_text_box().add_keyword_color(_current_test.name, Color(1, 0, 0)) - - _gui.set_progress_test_value(i + 1) - _doubler.get_ignored_methods().clear() - - # call both post-all-tests methods until postrun_teardown is removed. - if(_does_class_name_match(_inner_class_name, the_script.inner_class_name)): - _call_deprecated_script_method(test_script, 'postrun_teardown', 'after_all') - test_script.after_all() - - # This might end up being very resource intensive if the scripts - # don't clean up after themselves. Might have to consolidate output - # into some other structure and kill the script objects with - # test_script.free() instead of remove child. - remove_child(test_script) - #END TESTS IN SCRIPT LOOP - _current_test = null - _gui.set_progress_script_value(test_indexes + 1) # new way - #END TEST SCRIPT LOOP - - _end_run() - -func _pass(text=''): - _gui.add_passing() - if(_current_test): - _new_summary.add_pass(_current_test.name, text) - -func _fail(text=''): - _gui.add_failing() - if(_current_test != null): - var line_text = ' at line ' + str(_extractLineNumber( _current_test)) - p(line_text, LOG_LEVEL_FAIL_ONLY) - # format for summary - line_text = "\n " + line_text - - _new_summary.add_fail(_current_test.name, text + line_text) - _current_test.passed = false - -# Extracts the line number from curren stacktrace by matching the test case name -func _extractLineNumber(current_test): - var line_number = current_test.line_number - # if stack trace available than extraxt the test case line number - var stackTrace = get_stack() - if(stackTrace!=null): - for index in stackTrace.size(): - var line = stackTrace[index] - var function = line.get("function") - if function == current_test.name: - line_number = line.get("line") - return line_number - -func _pending(text=''): - if(_current_test): - _new_summary.add_pending(_current_test.name, text) - -# Gets all the files in a directory and all subdirectories if get_include_subdirectories -# is true. The files returned are all sorted by name. -func _get_files(path, prefix, suffix): - var files = [] - var directories = [] - - var d = Directory.new() - d.open(path) - # true parameter tells list_dir_begin not to include "." and ".." directories. - d.list_dir_begin(true) - - # Traversing a directory is kinda odd. You have to start the process of listing - # the contents of a directory with list_dir_begin then use get_next until it - # returns an empty string. Then I guess you should end it. - var fs_item = d.get_next() - var full_path = '' - while(fs_item != ''): - full_path = path.plus_file(fs_item) - - #file_exists returns fasle for directories - if(d.file_exists(full_path)): - if(fs_item.begins_with(prefix) and fs_item.ends_with(suffix)): - files.append(full_path) - elif(get_include_subdirectories() and d.dir_exists(full_path)): - directories.append(full_path) - - fs_item = d.get_next() - d.list_dir_end() - - for dir in range(directories.size()): - var dir_files = _get_files(directories[dir], prefix, suffix) - for i in range(dir_files.size()): - files.append(dir_files[i]) - - files.sort() - return files -######################### -# -# public -# -######################### - -# ------------------------------------------------------------------------------ -# Conditionally prints the text to the console/results variable based on the -# current log level and what level is passed in. Whenever currently in a test, -# the text will be indented under the test. It can be further indented if -# desired. -# -# The first time output is generated when in a test, the test name will be -# printed. -# ------------------------------------------------------------------------------ -func p(text, level=0, indent=0): - var str_text = str(text) - var to_print = "" - var printing_test_name = false - - if(level <= _utils.nvl(_log_level, 0)): - if(_current_test != null): - # make sure everything printed during the execution - # of a test is at least indented once under the test - if(indent == 0): - indent = 1 - - # Print the name of the current test if we haven't - # printed it already. - if(!_current_test.has_printed_name): - to_print = "* " + _current_test.name - _current_test.has_printed_name = true - printing_test_name = str_text == _current_test.name - - if(!printing_test_name): - if(to_print != ""): - to_print += "\n" - # Make the indent - var pad = "" - for _i in range(0, indent): - pad += " " - to_print += pad + str_text - to_print = to_print.replace("\n", "\n" + pad) - - if(_should_print_to_console): - var formatted = to_print - if(_color_output): - formatted = _utils.colorize_text(to_print) - print(formatted) - - _log_text += to_print + "\n" - - _gui.get_text_box().insert_text_at_cursor(to_print + "\n") - -################ -# -# RUN TESTS/ADD SCRIPTS -# -################ -func get_minimum_size(): - return Vector2(810, 380) - -# ------------------------------------------------------------------------------ -# Runs all the scripts that were added using add_script -# ------------------------------------------------------------------------------ -func test_scripts(run_rest=false): - clear_text() - - if(_script_name != null and _script_name != ''): - var indexes = _get_indexes_matching_script_name(_script_name) - if(indexes == []): - _lgr.error('Could not find script matching ' + _script_name) - else: - _test_the_scripts(indexes) - else: - _test_the_scripts([]) - - -# ------------------------------------------------------------------------------ -# Runs a single script passed in. -# ------------------------------------------------------------------------------ -func test_script(script): - _test_collector.set_test_class_prefix(_inner_class_prefix) - _test_collector.clear() - _test_collector.add_script(script) - _test_the_scripts() - -# ------------------------------------------------------------------------------ -# Adds a script to be run when test_scripts called -# -# No longer supports selecting a script via this method. -# ------------------------------------------------------------------------------ -func add_script(script, was_select_this_one=null): - if(was_select_this_one != null): - _lgr.error('The option to select a script when using add_script has been removed. Calling add_script with 2 parameters will be removed in a later release.') - - if(!Engine.is_editor_hint()): - _test_collector.set_test_class_prefix(_inner_class_prefix) - _test_collector.add_script(script) - _add_scripts_to_gui() - -# ------------------------------------------------------------------------------ -# Add all scripts in the specified directory that start with the prefix and end -# with the suffix. Does not look in sub directories. Can be called multiple -# times. -# ------------------------------------------------------------------------------ -func add_directory(path, prefix=_file_prefix, suffix=_file_extension): - var d = Directory.new() - # check for '' b/c the calls to addin the exported directories 1-6 will pass - # '' if the field has not been populated. This will cause res:// to be - # processed which will include all files if include_subdirectories is true. - if(path == '' or !d.dir_exists(path)): - if(path != ''): - _lgr.error(str('The path [', path, '] does not exist.')) - return - - var files = _get_files(path, prefix, suffix) - for i in range(files.size()): - add_script(files[i]) - -# ------------------------------------------------------------------------------ -# This will try to find a script in the list of scripts to test that contains -# the specified script name. It does not have to be a full match. It will -# select the first matching occurrence so that this script will run when run_tests -# is called. Works the same as the select_this_one option of add_script. -# -# returns whether it found a match or not -# ------------------------------------------------------------------------------ -func select_script(script_name): - _script_name = script_name - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func export_tests(path=_export_path): - if(path == null): - _lgr.error('You must pass a path or set the export_path before calling export_tests') - else: - var result = _test_collector.export_tests(path) - if(result): - p(_test_collector.to_s()) - p("Exported to " + path) - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func import_tests(path=_export_path): - if(!_utils.file_exists(path)): - _lgr.error(str('Cannot import tests: the path [', path, '] does not exist.')) - else: - _test_collector.clear() - var result = _test_collector.import_tests(path) - if(result): - p(_test_collector.to_s()) - p("Imported from " + path) - _add_scripts_to_gui() - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func import_tests_if_none_found(): - if(_test_collector.scripts.size() == 0): - import_tests() - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func export_if_tests_found(): - if(_test_collector.scripts.size() > 0): - export_tests() -################ -# -# MISC -# -################ - -# ------------------------------------------------------------------------------ -# Maximize test runner window to fit the viewport. -# ------------------------------------------------------------------------------ -func set_should_maximize(should): - _should_maximize = should - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_should_maximize(): - return _should_maximize - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func maximize(): - _gui.maximize() - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func disable_strict_datatype_checks(should): - _disable_strict_datatype_checks = should - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func is_strict_datatype_checks_disabled(): - return _disable_strict_datatype_checks - -# ------------------------------------------------------------------------------ -# Pauses the test and waits for you to press a confirmation button. Useful when -# you want to watch a test play out onscreen or inspect results. -# ------------------------------------------------------------------------------ -func end_yielded_test(): - _lgr.deprecated('end_yielded_test is no longer necessary, you can remove it.') - -# ------------------------------------------------------------------------------ -# Clears the text of the text box. This resets all counters. -# ------------------------------------------------------------------------------ -func clear_text(): - _gui.get_text_box().set_text("") - _gui.get_text_box().clear_colors() - update() - -# ------------------------------------------------------------------------------ -# Get the number of tests that were ran -# ------------------------------------------------------------------------------ -func get_test_count(): - return _new_summary.get_totals().tests - -# ------------------------------------------------------------------------------ -# Get the number of assertions that were made -# ------------------------------------------------------------------------------ -func get_assert_count(): - var t = _new_summary.get_totals() - return t.passing + t.failing - -# ------------------------------------------------------------------------------ -# Get the number of assertions that passed -# ------------------------------------------------------------------------------ -func get_pass_count(): - return _new_summary.get_totals().passing - -# ------------------------------------------------------------------------------ -# Get the number of assertions that failed -# ------------------------------------------------------------------------------ -func get_fail_count(): - return _new_summary.get_totals().failing - -# ------------------------------------------------------------------------------ -# Get the number of tests flagged as pending -# ------------------------------------------------------------------------------ -func get_pending_count(): - return _new_summary.get_totals().pending - -# ------------------------------------------------------------------------------ -# Set whether it should print to console or not. Default is yes. -# ------------------------------------------------------------------------------ -func set_should_print_to_console(should): - _should_print_to_console = should - -# ------------------------------------------------------------------------------ -# Get whether it is printing to the console -# ------------------------------------------------------------------------------ -func get_should_print_to_console(): - return _should_print_to_console - -# ------------------------------------------------------------------------------ -# Get the results of all tests ran as text. This string is the same as is -# displayed in the text box, and similar to what is printed to the console. -# ------------------------------------------------------------------------------ -func get_result_text(): - return _log_text - -# ------------------------------------------------------------------------------ -# Set the log level. Use one of the various LOG_LEVEL_* constants. -# ------------------------------------------------------------------------------ -func set_log_level(level): - _log_level = level - if(!Engine.is_editor_hint()): - _gui.set_log_level(level) - -# ------------------------------------------------------------------------------ -# Get the current log level. -# ------------------------------------------------------------------------------ -func get_log_level(): - return _log_level - -# ------------------------------------------------------------------------------ -# Call this method to make the test pause before teardown so that you can inspect -# anything that you have rendered to the screen. -# ------------------------------------------------------------------------------ -func pause_before_teardown(): - _pause_before_teardown = true; - -# ------------------------------------------------------------------------------ -# For batch processing purposes, you may want to ignore any calls to -# pause_before_teardown that you forgot to remove. -# ------------------------------------------------------------------------------ -func set_ignore_pause_before_teardown(should_ignore): - _ignore_pause_before_teardown = should_ignore - _gui.set_ignore_pause(should_ignore) - -func get_ignore_pause_before_teardown(): - return _ignore_pause_before_teardown - -# ------------------------------------------------------------------------------ -# Set to true so that painting of the screen will occur between tests. Allows you -# to see the output as tests occur. Especially useful with long running tests that -# make it appear as though it has humg. -# -# NOTE: not compatible with 1.0 so this is disabled by default. This will -# change in future releases. -# ------------------------------------------------------------------------------ -func set_yield_between_tests(should): - _yield_between.should = should - -func get_yield_between_tests(): - return _yield_between.should - -# ------------------------------------------------------------------------------ -# Call _process or _fixed_process, if they exist, on obj and all it's children -# and their children and so and so forth. Delta will be passed through to all -# the _process or _fixed_process methods. -# ------------------------------------------------------------------------------ -func simulate(obj, times, delta): - for _i in range(times): - if(obj.has_method("_process")): - obj._process(delta) - if(obj.has_method("_physics_process")): - obj._physics_process(delta) - - for kid in obj.get_children(): - simulate(kid, 1, delta) - -# ------------------------------------------------------------------------------ -# Starts an internal timer with a timeout of the passed in time. A 'timeout' -# signal will be sent when the timer ends. Returns itself so that it can be -# used in a call to yield...cutting down on lines of code. -# -# Example, yield to the Gut object for 10 seconds: -# yield(gut.set_yield_time(10), 'timeout') -# ------------------------------------------------------------------------------ -func set_yield_time(time, text=''): - _yield_timer.set_wait_time(time) - _yield_timer.start() - var msg = '/# Yielding (' + str(time) + 's)' - if(text == ''): - msg += ' #/' - else: - msg += ': ' + text + ' #/' - p(msg, 1) - _was_yield_method_called = true - return self - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func set_yield_signal_or_time(obj, signal_name, max_wait, text=''): - obj.connect(signal_name, self, '_yielding_callback', [true]) - _yielding_to.obj = obj - _yielding_to.signal_name = signal_name - - _yield_timer.set_wait_time(max_wait) - _yield_timer.start() - _was_yield_method_called = true - p(str('/# Yielding to signal "', signal_name, '" or for ', max_wait, ' seconds #/ ', text)) - return self - -# ------------------------------------------------------------------------------ -# get the specific unit test that should be run -# ------------------------------------------------------------------------------ -func get_unit_test_name(): - return _unit_test_name - -# ------------------------------------------------------------------------------ -# set the specific unit test that should be run. -# ------------------------------------------------------------------------------ -func set_unit_test_name(test_name): - _unit_test_name = test_name - -# ------------------------------------------------------------------------------ -# Creates an empty file at the specified path -# ------------------------------------------------------------------------------ -func file_touch(path): - var f = File.new() - f.open(path, f.WRITE) - f.close() - -# ------------------------------------------------------------------------------ -# deletes the file at the specified path -# ------------------------------------------------------------------------------ -func file_delete(path): - var d = Directory.new() - var result = d.open(path.get_base_dir()) - if(result == OK): - d.remove(path) - -# ------------------------------------------------------------------------------ -# Checks to see if the passed in file has any data in it. -# ------------------------------------------------------------------------------ -func is_file_empty(path): - var f = File.new() - f.open(path, f.READ) - var empty = f.get_len() == 0 - f.close() - return empty - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_file_as_text(path): - return _utils.get_file_as_text(path) - -# ------------------------------------------------------------------------------ -# deletes all files in a given directory -# ------------------------------------------------------------------------------ -func directory_delete_files(path): - var d = Directory.new() - var result = d.open(path) - - # SHORTCIRCUIT - if(result != OK): - return - - # Traversing a directory is kinda odd. You have to start the process of listing - # the contents of a directory with list_dir_begin then use get_next until it - # returns an empty string. Then I guess you should end it. - d.list_dir_begin() - var thing = d.get_next() # could be a dir or a file or something else maybe? - var full_path = '' - while(thing != ''): - full_path = path + "/" + thing - #file_exists returns fasle for directories - if(d.file_exists(full_path)): - d.remove(full_path) - thing = d.get_next() - d.list_dir_end() - -# ------------------------------------------------------------------------------ -# Returns the instantiated script object that is currently being run. -# ------------------------------------------------------------------------------ -func get_current_script_object(): - var to_return = null - if(_test_script_objects.size() > 0): - to_return = _test_script_objects[-1] - return to_return - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_current_test_object(): - return _current_test - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_stubber(): - return _stubber - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_doubler(): - return _doubler - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_spy(): - return _spy - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_temp_directory(): - return _temp_directory - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func set_temp_directory(temp_directory): - _temp_directory = temp_directory - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_inner_class_name(): - return _inner_class_name - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func set_inner_class_name(inner_class_name): - _inner_class_name = inner_class_name - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_summary(): - return _new_summary - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_double_strategy(): - return _double_strategy - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func set_double_strategy(double_strategy): - _double_strategy = double_strategy - _doubler.set_strategy(double_strategy) - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_include_subdirectories(): - return _include_subdirectories - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_logger(): - return _lgr - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func set_logger(logger): - _lgr = logger - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func set_include_subdirectories(include_subdirectories): - _include_subdirectories = include_subdirectories - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_test_collector(): - return _test_collector - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_export_path(): - return _export_path - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func set_export_path(export_path): - _export_path = export_path - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_version(): - return _version - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_pre_run_script(): - return _pre_run_script - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func set_pre_run_script(pre_run_script): - _pre_run_script = pre_run_script - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_post_run_script(): - return _post_run_script - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func set_post_run_script(post_run_script): - _post_run_script = post_run_script - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_pre_run_script_instance(): - return _pre_run_script_instance - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_post_run_script_instance(): - return _post_run_script_instance - -func get_color_output(): - return _color_output - -func set_color_output(color_output): - _color_output = color_output diff --git a/addons/gut/gut_cmdln.gd b/addons/gut/gut_cmdln.gd deleted file mode 100644 index ef89144..0000000 --- a/addons/gut/gut_cmdln.gd +++ /dev/null @@ -1,366 +0,0 @@ -################################################################################ -#(G)odot (U)nit (T)est class -# -################################################################################ -#The MIT License (MIT) -#===================== -# -#Copyright (c) 2019 Tom "Butch" Wesley -# -#Permission is hereby granted, free of charge, to any person obtaining a copy -#of this software and associated documentation files (the "Software"), to deal -#in the Software without restriction, including without limitation the rights -#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -#copies of the Software, and to permit persons to whom the Software is -#furnished to do so, subject to the following conditions: -# -#The above copyright notice and this permission notice shall be included in -#all copies or substantial portions of the Software. -# -#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -#THE SOFTWARE. -# -################################################################################ -# Description -# ----------- -# Command line interface for the GUT unit testing tool. Allows you to run tests -# from the command line instead of running a scene. Place this script along with -# gut.gd into your scripts directory at the root of your project. Once there you -# can run this script (from the root of your project) using the following command: -# godot -s -d test/gut/gut_cmdln.gd -# -# See the readme for a list of options and examples. You can also use the -gh -# option to get more information about how to use the command line interface. -# -# Version 6.8.2 -################################################################################ -extends SceneTree - - -var Optparse = load('res://addons/gut/optparse.gd') -var Gut = load('res://addons/gut/gut.gd') - -#------------------------------------------------------------------------------- -# Helper class to resolve the various different places where an option can -# be set. Using the get_value method will enforce the order of precedence of: -# 1. command line value -# 2. config file value -# 3. default value -# -# The idea is that you set the base_opts. That will get you a copies of the -# hash with null values for the other types of values. Lower precedented hashes -# will punch through null values of higher precedented hashes. -#------------------------------------------------------------------------------- -class OptionResolver: - var base_opts = null - var cmd_opts = null - var config_opts = null - - - func get_value(key): - return _nvl(cmd_opts[key], _nvl(config_opts[key], base_opts[key])) - - func set_base_opts(opts): - base_opts = opts - cmd_opts = _null_copy(opts) - config_opts = _null_copy(opts) - - # creates a copy of a hash with all values null. - func _null_copy(h): - var new_hash = {} - for key in h: - new_hash[key] = null - return new_hash - - func _nvl(a, b): - if(a == null): - return b - else: - return a - func _string_it(h): - var to_return = '' - for key in h: - to_return += str('(',key, ':', _nvl(h[key], 'NULL'), ')') - return to_return - - func to_s(): - return str("base:\n", _string_it(base_opts), "\n", \ - "config:\n", _string_it(config_opts), "\n", \ - "cmd:\n", _string_it(cmd_opts), "\n", \ - "resolved:\n", _string_it(get_resolved_values())) - - func get_resolved_values(): - var to_return = {} - for key in base_opts: - to_return[key] = get_value(key) - return to_return - - func to_s_verbose(): - var to_return = '' - var resolved = get_resolved_values() - for key in base_opts: - to_return += str(key, "\n") - to_return += str(' default: ', _nvl(base_opts[key], 'NULL'), "\n") - to_return += str(' config: ', _nvl(config_opts[key], ' --'), "\n") - to_return += str(' cmd: ', _nvl(cmd_opts[key], ' --'), "\n") - to_return += str(' final: ', _nvl(resolved[key], 'NULL'), "\n") - - return to_return - -#------------------------------------------------------------------------------- -# Here starts the actual script that uses the Options class to kick off Gut -# and run your tests. -#------------------------------------------------------------------------------- -var _utils = load('res://addons/gut/utils.gd').new() -# instance of gut -var _tester = null -# array of command line options specified -var _final_opts = [] -# Hash for easier access to the options in the code. Options will be -# extracted into this hash and then the hash will be used afterwards so -# that I don't make any dumb typos and get the neat code-sense when I -# type a dot. -var options = { - config_file = 'res://.gutconfig.json', - dirs = [], - disable_colors = false, - double_strategy = 'partial', - ignore_pause = false, - include_subdirs = false, - inner_class = '', - log_level = 1, - opacity = 100, - post_run_script = '', - pre_run_script = '', - prefix = 'test_', - selected = '', - should_exit = false, - should_exit_on_success = false, - should_maximize = false, - show_help = false, - suffix = '.gd', - tests = [], - unit_test_name = '', -} - -# flag to indicate if only a single script should be run. -var _run_single = false - -func setup_options(): - var opts = Optparse.new() - opts.set_banner(('This is the command line interface for the unit testing tool Gut. With this ' + - 'interface you can run one or more test scripts from the command line. In order ' + - 'for the Gut options to not clash with any other godot options, each option starts ' + - 'with a "g". Also, any option that requires a value will take the form of ' + - '"-g=". There cannot be any spaces between the option, the "=", or ' + - 'inside a specified value or godot will think you are trying to run a scene.')) - opts.add('-gtest', [], 'Comma delimited list of full paths to test scripts to run.') - opts.add('-gdir', [], 'Comma delimited list of directories to add tests from.') - opts.add('-gprefix', 'test_', 'Prefix used to find tests when specifying -gdir. Default "[default]"') - opts.add('-gsuffix', '.gd', 'Suffix used to find tests when specifying -gdir. Default "[default]"') - opts.add('-gmaximize', false, 'Maximizes test runner window to fit the viewport.') - opts.add('-gexit', false, 'Exit after running tests. If not specified you have to manually close the window.') - opts.add('-gexit_on_success', false, 'Only exit if all tests pass.') - opts.add('-glog', 1, 'Log level. Default [default]') - opts.add('-gignore_pause', false, 'Ignores any calls to gut.pause_before_teardown.') - opts.add('-gselect', '', ('Select a script to run initially. The first script that ' + - 'was loaded using -gtest or -gdir that contains the specified ' + - 'string will be executed. You may run others by interacting ' + - 'with the GUI.')) - opts.add('-gunit_test_name', '', ('Name of a test to run. Any test that contains the specified ' + - 'text will be run, all others will be skipped.')) - opts.add('-gh', false, 'Print this help, then quit') - opts.add('-gconfig', 'res://.gutconfig.json', 'A config file that contains configuration information. Default is res://.gutconfig.json') - opts.add('-ginner_class', '', 'Only run inner classes that contain this string') - opts.add('-gopacity', 100, 'Set opacity of test runner window. Use range 0 - 100. 0 = transparent, 100 = opaque.') - opts.add('-gpo', false, 'Print option values from all sources and the value used, then quit.') - opts.add('-ginclude_subdirs', false, 'Include subdirectories of -gdir.') - opts.add('-gdouble_strategy', 'partial', 'Default strategy to use when doubling. Valid values are [partial, full]. Default "[default]"') - opts.add('-gdisable_colors', false, 'Disable command line colors.') - opts.add('-gpre_run_script', '', 'pre-run hook script path') - opts.add('-gpost_run_script', '', 'post-run hook script path') - opts.add('-gprint_gutconfig_sample', false, 'Print out json that can be used to make a gutconfig file then quit.') - return opts - - -# Parses options, applying them to the _tester or setting values -# in the options struct. -func extract_command_line_options(from, to): - to.config_file = from.get_value('-gconfig') - to.dirs = from.get_value('-gdir') - to.disable_colors = from.get_value('-gdisable_colors') - to.double_strategy = from.get_value('-gdouble_strategy') - to.ignore_pause = from.get_value('-gignore_pause') - to.include_subdirs = from.get_value('-ginclude_subdirs') - to.inner_class = from.get_value('-ginner_class') - to.log_level = from.get_value('-glog') - to.opacity = from.get_value('-gopacity') - to.post_run_script = from.get_value('-gpost_run_script') - to.pre_run_script = from.get_value('-gpre_run_script') - to.prefix = from.get_value('-gprefix') - to.selected = from.get_value('-gselect') - to.should_exit = from.get_value('-gexit') - to.should_exit_on_success = from.get_value('-gexit_on_success') - to.should_maximize = from.get_value('-gmaximize') - to.suffix = from.get_value('-gsuffix') - to.tests = from.get_value('-gtest') - to.unit_test_name = from.get_value('-gunit_test_name') - - -func load_options_from_config_file(file_path, into): - # SHORTCIRCUIT - var f = File.new() - if(!f.file_exists(file_path)): - if(file_path != 'res://.gutconfig.json'): - print('ERROR: Config File "', file_path, '" does not exist.') - return -1 - else: - return 1 - - f.open(file_path, f.READ) - var json = f.get_as_text() - f.close() - - var results = JSON.parse(json) - # SHORTCIRCUIT - if(results.error != OK): - print("\n\n",'!! ERROR parsing file: ', file_path) - print(' at line ', results.error_line, ':') - print(' ', results.error_string) - return -1 - - # Get all the options out of the config file using the option name. The - # options hash is now the default source of truth for the name of an option. - for key in into: - if(results.result.has(key)): - into[key] = results.result[key] - - return 1 - -# Apply all the options specified to _tester. This is where the rubber meets -# the road. -func apply_options(opts): - _tester = Gut.new() - get_root().add_child(_tester) - _tester.connect('tests_finished', self, '_on_tests_finished', [opts.should_exit, opts.should_exit_on_success]) - _tester.set_yield_between_tests(true) - _tester.set_modulate(Color(1.0, 1.0, 1.0, min(1.0, float(opts.opacity) / 100))) - _tester.show() - - _tester.set_include_subdirectories(opts.include_subdirs) - - if(opts.should_maximize): - _tester.maximize() - - if(opts.inner_class != ''): - _tester.set_inner_class_name(opts.inner_class) - _tester.set_log_level(opts.log_level) - _tester.set_ignore_pause_before_teardown(opts.ignore_pause) - - for i in range(opts.dirs.size()): - _tester.add_directory(opts.dirs[i], opts.prefix, opts.suffix) - - for i in range(opts.tests.size()): - _tester.add_script(opts.tests[i]) - - if(opts.selected != ''): - _tester.select_script(opts.selected) - _run_single = true - - if(opts.double_strategy == 'full'): - _tester.set_double_strategy(_utils.DOUBLE_STRATEGY.FULL) - elif(opts.double_strategy == 'partial'): - _tester.set_double_strategy(_utils.DOUBLE_STRATEGY.PARTIAL) - - _tester.set_unit_test_name(opts.unit_test_name) - _tester.set_pre_run_script(opts.pre_run_script) - _tester.set_post_run_script(opts.post_run_script) - _tester.set_color_output(!opts.disable_colors) - -func _print_gutconfigs(values): - var header = """Here is a sample of a full .gutconfig.json file. -You do not need to specify all values in your own file. The values supplied in -this sample are what would be used if you ran gut w/o the -gprint_gutconfig_sample -option (the resolved values where default < .gutconfig < command line).""" - print("\n", header.replace("\n", ' '), "\n\n") - var resolved = values - - # remove some options that don't make sense to be in config - resolved.erase("config_file") - resolved.erase("show_help") - - print("Here's a config with all the properties set based off of your current command and config.") - var text = JSON.print(resolved) - print(text.replace(',', ",\n")) - - for key in resolved: - resolved[key] = null - - print("\n\nAnd here's an empty config for you fill in what you want.") - text = JSON.print(resolved) - print(text.replace(',', ",\n")) - - -# parse options and run Gut -func _init(): - var opt_resolver = OptionResolver.new() - opt_resolver.set_base_opts(options) - - print("\n\n", ' --- Gut ---') - var o = setup_options() - - var all_options_valid = o.parse() - extract_command_line_options(o, opt_resolver.cmd_opts) - var load_result = \ - load_options_from_config_file(opt_resolver.get_value('config_file'), opt_resolver.config_opts) - - if(load_result == -1): # -1 indicates json parse error - quit() - else: - if(!all_options_valid): - quit() - elif(o.get_value('-gh')): - var v_info = Engine.get_version_info() - print(str('Godot version: ', v_info.major, '.', v_info.minor, '.', v_info.patch)) - print(str('GUT version: ', Gut.new().get_version())) - - o.print_help() - quit() - elif(o.get_value('-gpo')): - print('All command line options and where they are specified. ' + - 'The "final" value shows which value will actually be used ' + - 'based on order of precedence (default < .gutconfig < cmd line).' + "\n") - print(opt_resolver.to_s_verbose()) - quit() - elif(o.get_value('-gprint_gutconfig_sample')): - _print_gutconfigs(opt_resolver.get_resolved_values()) - quit() - else: - _final_opts = opt_resolver.get_resolved_values(); - apply_options(_final_opts) - _tester.test_scripts(!_run_single) - -# exit if option is set. -func _on_tests_finished(should_exit, should_exit_on_success): - if(_final_opts.dirs.size() == 0): - if(_tester.get_summary().get_totals().scripts == 0): - var lgr = _tester.get_logger() - lgr.error('No directories configured. Add directories with options or a .gutconfig.json file. Use the -gh option for more information.') - - if(_tester.get_fail_count()): - OS.exit_code = 1 - - # Overwrite the exit code with the post_script - var post_inst = _tester.get_post_run_script_instance() - if(post_inst != null and post_inst.get_exit_code() != null): - OS.exit_code = post_inst.get_exit_code() - - if(should_exit or (should_exit_on_success and _tester.get_fail_count() == 0)): - quit() - else: - print("Tests finished, exit manually") diff --git a/addons/gut/gut_plugin.gd b/addons/gut/gut_plugin.gd deleted file mode 100644 index 0517c1c..0000000 --- a/addons/gut/gut_plugin.gd +++ /dev/null @@ -1,12 +0,0 @@ -tool -extends EditorPlugin - -func _enter_tree(): - # Initialization of the plugin goes here - # Add the new type with a name, a parent type, a script and an icon - add_custom_type("Gut", "Control", preload("gut.gd"), preload("icon.png")) - -func _exit_tree(): - # Clean-up of the plugin goes here - # Always remember to remove it from the engine when deactivated - remove_custom_type("Gut") diff --git a/addons/gut/hook_script.gd b/addons/gut/hook_script.gd deleted file mode 100644 index 10a5e12..0000000 --- a/addons/gut/hook_script.gd +++ /dev/null @@ -1,35 +0,0 @@ -# ------------------------------------------------------------------------------ -# This script is the base for custom scripts to be used in pre and post -# run hooks. -# ------------------------------------------------------------------------------ - -# This is the instance of GUT that is running the tests. You can get -# information about the run from this object. This is set by GUT when the -# script is instantiated. -var gut = null - -# the exit code to be used by gut_cmdln. See set method. -var _exit_code = null - -var _should_abort = false -# Virtual method that will be called by GUT after instantiating -# this script. -func run(): - pass - -# Set the exit code when running from the command line. If not set then the -# default exit code will be returned (0 when no tests fail, 1 when any tests -# fail). -func set_exit_code(code): - _exit_code = code - -func get_exit_code(): - return _exit_code - -# Usable by pre-run script to cause the run to end AFTER the run() method -# finishes. post-run script will not be ran. -func abort(): - _should_abort = true - -func should_abort(): - return _should_abort diff --git a/addons/gut/icon.png b/addons/gut/icon.png deleted file mode 100644 index 7c58987..0000000 Binary files a/addons/gut/icon.png and /dev/null differ diff --git a/addons/gut/logger.gd b/addons/gut/logger.gd deleted file mode 100644 index c7cd458..0000000 --- a/addons/gut/logger.gd +++ /dev/null @@ -1,105 +0,0 @@ -extends Node2D - -var _gut = null - -var types = { - warn = 'WARNING', - error = 'ERROR', - info = 'INFO', - debug = 'DEBUG', - deprecated = 'DEPRECATED' -} - -var _logs = { - types.warn: [], - types.error: [], - types.info: [], - types.debug: [], - types.deprecated: [] -} - -var _suppress_output = false - -func _gut_log_level_for_type(log_type): - if(log_type == types.warn or log_type == types.error or log_type == types.deprecated): - return 0 - else: - return 2 - -func _log(type, text): - _logs[type].append(text) - var formatted = str('[', type, '] ', text) - if(!_suppress_output): - if(_gut): - # this will keep the text indented under test for readability - _gut.p(formatted, _gut_log_level_for_type(type)) - # IDEA! We could store the current script and test that generated - # this output, which could be useful later if we printed out a summary. - else: - print(formatted) - return formatted - -# --------------- -# Get Methods -# --------------- -func get_warnings(): - return get_log_entries(types.warn) - -func get_errors(): - return get_log_entries(types.error) - -func get_infos(): - return get_log_entries(types.info) - -func get_debugs(): - return get_log_entries(types.debug) - -func get_deprecated(): - return get_log_entries(types.deprecated) - -func get_count(log_type=null): - var count = 0 - if(log_type == null): - for key in _logs: - count += _logs[key].size() - else: - count = _logs[log_type].size() - return count - -func get_log_entries(log_type): - return _logs[log_type] - -# --------------- -# Log methods -# --------------- -func warn(text): - return _log(types.warn, text) - -func error(text): - return _log(types.error, text) - -func info(text): - return _log(types.info, text) - -func debug(text): - return _log(types.debug, text) - -# supply some text or the name of the deprecated method and the replacement. -func deprecated(text, alt_method=null): - var msg = text - if(alt_method): - msg = str('The method ', text, ' is deprecated, use ', alt_method , ' instead.') - return _log(types.deprecated, msg) - -# --------------- -# Misc -# --------------- -func get_gut(): - return _gut - -func set_gut(gut): - _gut = gut - -func clear(): - for key in _logs: - _logs[key].clear() diff --git a/addons/gut/method_maker.gd b/addons/gut/method_maker.gd deleted file mode 100644 index 80503e4..0000000 --- a/addons/gut/method_maker.gd +++ /dev/null @@ -1,211 +0,0 @@ -# This class will generate method declaration lines based on method meta -# data. It will create defaults that match the method data. -# -# -------------------- -# function meta data -# -------------------- -# name: -# flags: -# args: [{ -# (class_name:), -# (hint:0), -# (hint_string:), -# (name:), -# (type:4), -# (usage:7) -# }] -# default_args [] - -var _utils = load('res://addons/gut/utils.gd').new() -var _lgr = _utils.get_logger() -const PARAM_PREFIX = 'p_' - -# ------------------------------------------------------ -# _supported_defaults -# -# This array contains all the data types that are supported for default values. -# If a value is supported it will contain either an empty string or a prefix -# that should be used when setting the parameter default value. -# For example int, real, bool do not need anything func(p1=1, p2=2.2, p3=false) -# but things like Vectors and Colors do since only the parameters to create a -# new Vector or Color are included in the metadata. -# ------------------------------------------------------ - # TYPE_NIL = 0 — Variable is of type nil (only applied for null). - # TYPE_BOOL = 1 — Variable is of type bool. - # TYPE_INT = 2 — Variable is of type int. - # TYPE_REAL = 3 — Variable is of type float/real. - # TYPE_STRING = 4 — Variable is of type String. - # TYPE_VECTOR2 = 5 — Variable is of type Vector2. - # TYPE_RECT2 = 6 — Variable is of type Rect2. - # TYPE_VECTOR3 = 7 — Variable is of type Vector3. - # TYPE_COLOR = 14 — Variable is of type Color. - # TYPE_OBJECT = 17 — Variable is of type Object. - # TYPE_DICTIONARY = 18 — Variable is of type Dictionary. - # TYPE_ARRAY = 19 — Variable is of type Array. - # TYPE_VECTOR2_ARRAY = 24 — Variable is of type PoolVector2Array. - - - -# TYPE_TRANSFORM2D = 8 — Variable is of type Transform2D. -# TYPE_PLANE = 9 — Variable is of type Plane. -# TYPE_QUAT = 10 — Variable is of type Quat. -# TYPE_AABB = 11 — Variable is of type AABB. -# TYPE_BASIS = 12 — Variable is of type Basis. -# TYPE_TRANSFORM = 13 — Variable is of type Transform. -# TYPE_NODE_PATH = 15 — Variable is of type NodePath. -# TYPE_RID = 16 — Variable is of type RID. -# TYPE_RAW_ARRAY = 20 — Variable is of type PoolByteArray. -# TYPE_INT_ARRAY = 21 — Variable is of type PoolIntArray. -# TYPE_REAL_ARRAY = 22 — Variable is of type PoolRealArray. -# TYPE_STRING_ARRAY = 23 — Variable is of type PoolStringArray. -# TYPE_VECTOR3_ARRAY = 25 — Variable is of type PoolVector3Array. -# TYPE_COLOR_ARRAY = 26 — Variable is of type PoolColorArray. -# TYPE_MAX = 27 — Marker for end of type constants. -# ------------------------------------------------------ -var _supported_defaults = [] - -func _init(): - for _i in range(TYPE_MAX): - _supported_defaults.append(null) - - # These types do not require a prefix for defaults - _supported_defaults[TYPE_NIL] = '' - _supported_defaults[TYPE_BOOL] = '' - _supported_defaults[TYPE_INT] = '' - _supported_defaults[TYPE_REAL] = '' - _supported_defaults[TYPE_OBJECT] = '' - _supported_defaults[TYPE_ARRAY] = '' - _supported_defaults[TYPE_STRING] = '' - _supported_defaults[TYPE_DICTIONARY] = '' - _supported_defaults[TYPE_VECTOR2_ARRAY] = '' - - # These require a prefix for whatever default is provided - _supported_defaults[TYPE_VECTOR2] = 'Vector2' - _supported_defaults[TYPE_RECT2] = 'Rect2' - _supported_defaults[TYPE_VECTOR3] = 'Vector3' - _supported_defaults[TYPE_COLOR] = 'Color' - -# ############### -# Private -# ############### -var _func_text = _utils.get_file_as_text('res://addons/gut/double_templates/function_template.gd') - -func _is_supported_default(type_flag): - return type_flag >= 0 and type_flag < _supported_defaults.size() and [type_flag] != null - -# Creates a list of parameters with defaults of null unless a default value is -# found in the metadata. If a default is found in the meta then it is used if -# it is one we know how support. -# -# If a default is found that we don't know how to handle then this method will -# return null. -func _get_arg_text(method_meta): - var text = '' - var args = method_meta.args - var defaults = [] - var has_unsupported_defaults = false - - # fill up the defaults with null defaults for everything that doesn't have - # a default in the meta data. default_args is an array of default values - # for the last n parameters where n is the size of default_args so we only - # add nulls for everything up to the first parameter with a default. - for _i in range(args.size() - method_meta.default_args.size()): - defaults.append('null') - - # Add meta-data defaults. - for i in range(method_meta.default_args.size()): - var t = args[defaults.size()]['type'] - var value = '' - if(_is_supported_default(t)): - # strings are special, they need quotes around the value - if(t == TYPE_STRING): - value = str("'", str(method_meta.default_args[i]), "'") - # Colors need the parens but things like Vector2 and Rect2 don't - elif(t == TYPE_COLOR): - value = str(_supported_defaults[t], '(', str(method_meta.default_args[i]), ')') - elif(t == TYPE_OBJECT): - if(str(method_meta.default_args[i]) == "[Object:null]"): - value = str(_supported_defaults[t], 'null') - else: - value = str(_supported_defaults[t], str(method_meta.default_args[i]).to_lower()) - - # Everything else puts the prefix (if one is there) form _supported_defaults - # in front. The to_lower is used b/c for some reason the defaults for - # null, true, false are all "Null", "True", "False". - else: - value = str(_supported_defaults[t], str(method_meta.default_args[i]).to_lower()) - else: - _lgr.warn(str( - 'Unsupported default param type: ',method_meta.name, '-', args[defaults.size()].name, ' ', t, ' = ', method_meta.default_args[i])) - value = str('unsupported=',t) - has_unsupported_defaults = true - - defaults.append(value) - - # construct the string of parameters - for i in range(args.size()): - text += str(PARAM_PREFIX, args[i].name, '=', defaults[i]) - if(i != args.size() -1): - text += ', ' - - # if we don't know how to make a default then we have to return null b/c - # it will cause a runtime error and it's one thing we could return to let - # callers know it didn't work. - if(has_unsupported_defaults): - text = null - - return text - -# ############### -# Public -# ############### - -# Creates a delceration for a function based off of function metadata. All -# types whose defaults are supported will have their values. If a datatype -# is not supported and the parameter has a default, a warning message will be -# printed and the declaration will return null. -func get_function_text(meta): - var method_params = _get_arg_text(meta) - var text = null - - var param_array = get_spy_call_parameters_text(meta) - if(param_array == 'null'): - param_array = '[]' - - if(method_params != null): - var decleration = str('func ', meta.name, '(', method_params, '):') - text = _func_text.format({ - "func_decleration":decleration, - "method_name":meta.name, - "param_array":param_array, - "super_call":get_super_call_text(meta) - }) - return text - -# creates a call to the function in meta in the super's class. -func get_super_call_text(meta): - var params = '' - - for i in range(meta.args.size()): - params += PARAM_PREFIX + meta.args[i].name - if(meta.args.size() > 1 and i != meta.args.size() -1): - params += ', ' - - return str('.', meta.name, '(', params, ')') - -func get_spy_call_parameters_text(meta): - var called_with = 'null' - if(meta.args.size() > 0): - called_with = '[' - for i in range(meta.args.size()): - called_with += str(PARAM_PREFIX, meta.args[i].name) - if(i < meta.args.size() - 1): - called_with += ', ' - called_with += ']' - return called_with - -func get_logger(): - return _lgr - -func set_logger(logger): - _lgr = logger diff --git a/addons/gut/one_to_many.gd b/addons/gut/one_to_many.gd deleted file mode 100644 index 6a0f818..0000000 --- a/addons/gut/one_to_many.gd +++ /dev/null @@ -1,38 +0,0 @@ -# ------------------------------------------------------------------------------ -# This datastructure represents a simple one-to-many relationship. It manages -# a dictionary of value/array pairs. It ignores duplicates of both the "one" -# and the "many". -# ------------------------------------------------------------------------------ -var _items = {} - -# return the size of _items or the size of an element in _items if "one" was -# specified. -func size(one=null): - var to_return = 0 - if(one == null): - to_return = _items.size() - elif(_items.has(one)): - to_return = _items[one].size() - return to_return - -# Add an element to "one" if it does not already exist -func add(one, many_item): - if(_items.has(one) and !_items[one].has(many_item)): - _items[one].append(many_item) - else: - _items[one] = [many_item] - -func clear(): - _items.clear() - -func has(one, many_item): - var to_return = false - if(_items.has(one)): - to_return = _items[one].has(many_item) - return to_return - -func to_s(): - var to_return = '' - for key in _items: - to_return += str(key, ": ", _items[key], "\n") - return to_return diff --git a/addons/gut/optparse.gd b/addons/gut/optparse.gd deleted file mode 100644 index 0f6ccf5..0000000 --- a/addons/gut/optparse.gd +++ /dev/null @@ -1,250 +0,0 @@ -################################################################################ -#(G)odot (U)nit (T)est class -# -################################################################################ -#The MIT License (MIT) -#===================== -# -#Copyright (c) 2019 Tom "Butch" Wesley -# -#Permission is hereby granted, free of charge, to any person obtaining a copy -#of this software and associated documentation files (the "Software"), to deal -#in the Software without restriction, including without limitation the rights -#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -#copies of the Software, and to permit persons to whom the Software is -#furnished to do so, subject to the following conditions: -# -#The above copyright notice and this permission notice shall be included in -#all copies or substantial portions of the Software. -# -#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -#THE SOFTWARE. -# -################################################################################ -# Description -# ----------- -# Command line interface for the GUT unit testing tool. Allows you to run tests -# from the command line instead of running a scene. Place this script along with -# gut.gd into your scripts directory at the root of your project. Once there you -# can run this script (from the root of your project) using the following command: -# godot -s -d test/gut/gut_cmdln.gd -# -# See the readme for a list of options and examples. You can also use the -gh -# option to get more information about how to use the command line interface. -# -# Version 6.8.2 -################################################################################ - -#------------------------------------------------------------------------------- -# Parses the command line arguments supplied into an array that can then be -# examined and parsed based on how the gut options work. -#------------------------------------------------------------------------------- -class CmdLineParser: - var _used_options = [] - # an array of arrays. Each element in this array will contain an option - # name and if that option contains a value then it will have a sedond - # element. For example: - # [[-gselect, test.gd], [-gexit]] - var _opts = [] - - func _init(): - for i in range(OS.get_cmdline_args().size()): - var opt_val = OS.get_cmdline_args()[i].split('=') - _opts.append(opt_val) - - # Parse out multiple comma delimited values from a command line - # option. Values are separated from option name with "=" and - # additional values are comma separated. - func _parse_array_value(full_option): - var value = _parse_option_value(full_option) - var split = value.split(',') - return split - - # Parse out the value of an option. Values are separated from - # the option name with "=" - func _parse_option_value(full_option): - if(full_option.size() > 1): - return full_option[1] - else: - return null - - # Search _opts for an element that starts with the option name - # specified. - func find_option(name): - var found = false - var idx = 0 - - while(idx < _opts.size() and !found): - if(_opts[idx][0] == name): - found = true - else: - idx += 1 - - if(found): - return idx - else: - return -1 - - func get_array_value(option): - _used_options.append(option) - var to_return = [] - var opt_loc = find_option(option) - if(opt_loc != -1): - to_return = _parse_array_value(_opts[opt_loc]) - _opts.remove(opt_loc) - - return to_return - - # returns the value of an option if it was specified, null otherwise. This - # used to return the default but that became problemnatic when trying to - # punch through the different places where values could be specified. - func get_value(option): - _used_options.append(option) - var to_return = null - var opt_loc = find_option(option) - if(opt_loc != -1): - to_return = _parse_option_value(_opts[opt_loc]) - _opts.remove(opt_loc) - - return to_return - - # returns true if it finds the option, false if not. - func was_specified(option): - _used_options.append(option) - return find_option(option) != -1 - - # Returns any unused command line options. I found that only the -s and - # script name come through from godot, all other options that godot uses - # are not sent through OS.get_cmdline_args(). - # - # This is a onetime thing b/c i kill all items in _used_options - func get_unused_options(): - var to_return = [] - for i in range(_opts.size()): - to_return.append(_opts[i][0]) - - var script_option = to_return.find('-s') - if script_option != -1: - to_return.remove(script_option + 1) - to_return.remove(script_option) - - while(_used_options.size() > 0): - var index = to_return.find(_used_options[0].split("=")[0]) - if(index != -1): - to_return.remove(index) - _used_options.remove(0) - - return to_return - -#------------------------------------------------------------------------------- -# Simple class to hold a command line option -#------------------------------------------------------------------------------- -class Option: - var value = null - var option_name = '' - var default = null - var description = '' - - func _init(name, default_value, desc=''): - option_name = name - default = default_value - description = desc - value = null#default_value - - func pad(to_pad, size, pad_with=' '): - var to_return = to_pad - for _i in range(to_pad.length(), size): - to_return += pad_with - - return to_return - - func to_s(min_space=0): - var subbed_desc = description - if(subbed_desc.find('[default]') != -1): - subbed_desc = subbed_desc.replace('[default]', str(default)) - return pad(option_name, min_space) + subbed_desc - -#------------------------------------------------------------------------------- -# The high level interface between this script and the command line options -# supplied. Uses Option class and CmdLineParser to extract information from -# the command line and make it easily accessible. -#------------------------------------------------------------------------------- -var options = [] -var _opts = [] -var _banner = '' - -func add(name, default, desc): - options.append(Option.new(name, default, desc)) - -func get_value(name): - var found = false - var idx = 0 - - while(idx < options.size() and !found): - if(options[idx].option_name == name): - found = true - else: - idx += 1 - - if(found): - return options[idx].value - else: - print("COULD NOT FIND OPTION " + name) - return null - -func set_banner(banner): - _banner = banner - -func print_help(): - var longest = 0 - for i in range(options.size()): - if(options[i].option_name.length() > longest): - longest = options[i].option_name.length() - - print('---------------------------------------------------------') - print(_banner) - - print("\nOptions\n-------") - for i in range(options.size()): - print(' ' + options[i].to_s(longest + 2)) - print('---------------------------------------------------------') - -func print_options(): - for i in range(options.size()): - print(options[i].option_name + '=' + str(options[i].value)) - -func parse(): - var parser = CmdLineParser.new() - - for i in range(options.size()): - var t = typeof(options[i].default) - # only set values that were specified at the command line so that - # we can punch through default and config values correctly later. - # Without this check, you can't tell the difference between the - # defaults and what was specified, so you can't punch through - # higher level options. - if(parser.was_specified(options[i].option_name)): - if(t == TYPE_INT): - options[i].value = int(parser.get_value(options[i].option_name)) - elif(t == TYPE_STRING): - options[i].value = parser.get_value(options[i].option_name) - elif(t == TYPE_ARRAY): - options[i].value = parser.get_array_value(options[i].option_name) - elif(t == TYPE_BOOL): - options[i].value = parser.was_specified(options[i].option_name) - elif(t == TYPE_NIL): - print(options[i].option_name + ' cannot be processed, it has a nil datatype') - else: - print(options[i].option_name + ' cannot be processed, it has unknown datatype:' + str(t)) - - var unused = parser.get_unused_options() - if(unused.size() > 0): - print("Unrecognized options: ", unused) - return false - - return true diff --git a/addons/gut/plugin.cfg b/addons/gut/plugin.cfg deleted file mode 100644 index 31fd316..0000000 --- a/addons/gut/plugin.cfg +++ /dev/null @@ -1,7 +0,0 @@ -[plugin] - -name="Gut" -description="Unit Testing tool for Godot." -author="Butch Wesley" -version="6.8.2" -script="gut_plugin.gd" diff --git a/addons/gut/signal_watcher.gd b/addons/gut/signal_watcher.gd deleted file mode 100644 index 5fae3fe..0000000 --- a/addons/gut/signal_watcher.gd +++ /dev/null @@ -1,166 +0,0 @@ -################################################################################ -#The MIT License (MIT) -#===================== -# -#Copyright (c) 2019 Tom "Butch" Wesley -# -#Permission is hereby granted, free of charge, to any person obtaining a copy -#of this software and associated documentation files (the "Software"), to deal -#in the Software without restriction, including without limitation the rights -#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -#copies of the Software, and to permit persons to whom the Software is -#furnished to do so, subject to the following conditions: -# -#The above copyright notice and this permission notice shall be included in -#all copies or substantial portions of the Software. -# -#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -#THE SOFTWARE. -# -################################################################################ - -# Some arbitrary string that should never show up by accident. If it does, then -# shame on you. -const ARG_NOT_SET = '_*_argument_*_is_*_not_set_*_' - -# This hash holds the objects that are being watched, the signals that are being -# watched, and an array of arrays that contains arguments that were passed -# each time the signal was emitted. -# -# For example: -# _watched_signals => { -# ref1 => { -# 'signal1' => [[], [], []], -# 'signal2' => [[p1, p2]], -# 'signal3' => [[p1]] -# }, -# ref2 => { -# 'some_signal' => [], -# 'other_signal' => [[p1, p2, p3], [p1, p2, p3], [p1, p2, p3]] -# } -# } -# -# In this sample: -# - signal1 on the ref1 object was emitted 3 times and each time, zero -# parameters were passed. -# - signal3 on ref1 was emitted once and passed a single parameter -# - some_signal on ref2 was never emitted. -# - other_signal on ref2 was emitted 3 times, each time with 3 parameters. -var _watched_signals = {} -var _utils = load('res://addons/gut/utils.gd').new() - -func _add_watched_signal(obj, name): - # SHORTCIRCUIT - ignore dupes - if(_watched_signals.has(obj) and _watched_signals[obj].has(name)): - return - - if(!_watched_signals.has(obj)): - _watched_signals[obj] = {name:[]} - else: - _watched_signals[obj][name] = [] - obj.connect(name, self, '_on_watched_signal', [obj, name]) - -# This handles all the signals that are watched. It supports up to 9 parameters -# which could be emitted by the signal and the two parameters used when it is -# connected via watch_signal. I chose 9 since you can only specify up to 9 -# parameters when dynamically calling a method via call (per the Godot -# documentation, i.e. some_object.call('some_method', 1, 2, 3...)). -# -# Based on the documentation of emit_signal, it appears you can only pass up -# to 4 parameters when firing a signal. I haven't verified this, but this should -# future proof this some if the value ever grows. -func _on_watched_signal(arg1=ARG_NOT_SET, arg2=ARG_NOT_SET, arg3=ARG_NOT_SET, \ - arg4=ARG_NOT_SET, arg5=ARG_NOT_SET, arg6=ARG_NOT_SET, \ - arg7=ARG_NOT_SET, arg8=ARG_NOT_SET, arg9=ARG_NOT_SET, \ - arg10=ARG_NOT_SET, arg11=ARG_NOT_SET): - var args = [arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11] - - # strip off any unused vars. - var idx = args.size() -1 - while(str(args[idx]) == ARG_NOT_SET): - args.remove(idx) - idx -= 1 - - # retrieve object and signal name from the array and remove them. These - # will always be at the end since they are added when the connect happens. - var signal_name = args[args.size() -1] - args.pop_back() - var object = args[args.size() -1] - args.pop_back() - - _watched_signals[object][signal_name].append(args) - -func does_object_have_signal(object, signal_name): - var signals = object.get_signal_list() - for i in range(signals.size()): - if(signals[i]['name'] == signal_name): - return true - return false - -func watch_signals(object): - var signals = object.get_signal_list() - for i in range(signals.size()): - _add_watched_signal(object, signals[i]['name']) - -func watch_signal(object, signal_name): - var did = false - if(does_object_have_signal(object, signal_name)): - _add_watched_signal(object, signal_name) - did = true - return did - -func get_emit_count(object, signal_name): - var to_return = -1 - if(is_watching(object, signal_name)): - to_return = _watched_signals[object][signal_name].size() - return to_return - -func did_emit(object, signal_name): - var did = false - if(is_watching(object, signal_name)): - did = get_emit_count(object, signal_name) != 0 - return did - -func print_object_signals(object): - var list = object.get_signal_list() - for i in range(list.size()): - print(list[i].name, "\n ", list[i]) - -func get_signal_parameters(object, signal_name, index=-1): - var params = null - if(is_watching(object, signal_name)): - var all_params = _watched_signals[object][signal_name] - if(all_params.size() > 0): - if(index == -1): - index = all_params.size() -1 - params = all_params[index] - return params - -func is_watching_object(object): - return _watched_signals.has(object) - -func is_watching(object, signal_name): - return _watched_signals.has(object) and _watched_signals[object].has(signal_name) - -func clear(): - for obj in _watched_signals: - for signal_name in _watched_signals[obj]: - if(_utils.is_not_freed(obj)): - obj.disconnect(signal_name, self, '_on_watched_signal') - _watched_signals.clear() - -# Returns a list of all the signal names that were emitted by the object. -# If the object is not being watched then an empty list is returned. -func get_signals_emitted(obj): - var emitted = [] - if(is_watching_object(obj)): - for signal_name in _watched_signals[obj]: - if(_watched_signals[obj][signal_name].size() > 0): - emitted.append(signal_name) - - return emitted diff --git a/addons/gut/source_code_pro.fnt b/addons/gut/source_code_pro.fnt deleted file mode 100644 index 3367650..0000000 Binary files a/addons/gut/source_code_pro.fnt and /dev/null differ diff --git a/addons/gut/spy.gd b/addons/gut/spy.gd deleted file mode 100644 index 32ae414..0000000 --- a/addons/gut/spy.gd +++ /dev/null @@ -1,96 +0,0 @@ -# { -# instance_id_or_path1:{ -# method1:[ [p1, p2], [p1, p2] ], -# method2:[ [p1, p2], [p1, p2] ] -# }, -# instance_id_or_path1:{ -# method1:[ [p1, p2], [p1, p2] ], -# method2:[ [p1, p2], [p1, p2] ] -# }, -# } -var _calls = {} -var _utils = load('res://addons/gut/utils.gd').new() -var _lgr = _utils.get_logger() - -func _get_params_as_string(params): - var to_return = '' - if(params == null): - return '' - - for i in range(params.size()): - if(params[i] == null): - to_return += 'null' - else: - if(typeof(params[i]) == TYPE_STRING): - to_return += str('"', params[i], '"') - else: - to_return += str(params[i]) - if(i != params.size() -1): - to_return += ', ' - return to_return - -func add_call(variant, method_name, parameters=null): - if(!_calls.has(variant)): - _calls[variant] = {} - - if(!_calls[variant].has(method_name)): - _calls[variant][method_name] = [] - - _calls[variant][method_name].append(parameters) - -func was_called(variant, method_name, parameters=null): - var to_return = false - if(_calls.has(variant) and _calls[variant].has(method_name)): - if(parameters): - to_return = _calls[variant][method_name].has(parameters) - else: - to_return = true - return to_return - -func get_call_parameters(variant, method_name, index=-1): - var to_return = null - var get_index = -1 - - if(_calls.has(variant) and _calls[variant].has(method_name)): - var call_size = _calls[variant][method_name].size() - if(index == -1): - # get the most recent call by default - get_index = call_size -1 - else: - get_index = index - - if(get_index < call_size): - to_return = _calls[variant][method_name][get_index] - else: - _lgr.error(str('Specified index ', index, ' is outside range of the number of registered calls: ', call_size)) - - return to_return - -func call_count(instance, method_name, parameters=null): - var to_return = 0 - - if(was_called(instance, method_name)): - if(parameters): - for i in range(_calls[instance][method_name].size()): - if(_calls[instance][method_name][i] == parameters): - to_return += 1 - else: - to_return = _calls[instance][method_name].size() - return to_return - -func clear(): - _calls = {} - -func get_call_list_as_string(instance): - var to_return = '' - if(_calls.has(instance)): - for method in _calls[instance]: - for i in range(_calls[instance][method].size()): - to_return += str(method, '(', _get_params_as_string(_calls[instance][method][i]), ")\n") - return to_return - -func get_logger(): - return _lgr - -func set_logger(logger): - _lgr = logger diff --git a/addons/gut/stub_params.gd b/addons/gut/stub_params.gd deleted file mode 100644 index 8a749f4..0000000 --- a/addons/gut/stub_params.gd +++ /dev/null @@ -1,43 +0,0 @@ -var return_val = null -var stub_target = null -var target_subpath = null -var parameters = null -var stub_method = null -var call_super = false - -const NOT_SET = '|_1_this_is_not_set_1_|' - -func _init(target=null, method=null, subpath=null): - stub_target = target - stub_method = method - target_subpath = subpath - -func to_return(val): - return_val = val - call_super = false - return self - -func to_do_nothing(): - return to_return(null) - -func to_call_super(): - call_super = true - return self - -func when_passed(p1=NOT_SET,p2=NOT_SET,p3=NOT_SET,p4=NOT_SET,p5=NOT_SET,p6=NOT_SET,p7=NOT_SET,p8=NOT_SET,p9=NOT_SET,p10=NOT_SET): - parameters = [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10] - var idx = 0 - while(idx < parameters.size()): - if(str(parameters[idx]) == NOT_SET): - parameters.remove(idx) - else: - idx += 1 - return self - -func to_s(): - var base_string = str(stub_target, '[', target_subpath, '].', stub_method) - if(call_super): - base_string += " to call SUPER" - else: - base_string += str(' with (', parameters, ') = ', return_val) - return base_string diff --git a/addons/gut/stubber.gd b/addons/gut/stubber.gd deleted file mode 100644 index c0e74ff..0000000 --- a/addons/gut/stubber.gd +++ /dev/null @@ -1,162 +0,0 @@ -# { -# inst_id_or_path1:{ -# method_name1: [StubParams, StubParams], -# method_name2: [StubParams, StubParams] -# }, -# inst_id_or_path2:{ -# method_name1: [StubParams, StubParams], -# method_name2: [StubParams, StubParams] -# } -# } -var returns = {} -var _utils = load('res://addons/gut/utils.gd').new() -var _lgr = _utils.get_logger() - -func _is_instance(obj): - return typeof(obj) == TYPE_OBJECT and !obj.has_method('new') - -func _make_key_from_metadata(doubled): - var to_return = doubled.__gut_metadata_.path - if(doubled.__gut_metadata_.subpath != ''): - to_return += str('-', doubled.__gut_metadata_.subpath) - return to_return - -# Creates they key for the returns hash based on the type of object passed in -# obj could be a string of a path to a script with an optional subpath or -# it could be an instance of a doubled object. -func _make_key_from_variant(obj, subpath=null): - var to_return = null - - match typeof(obj): - TYPE_STRING: - # this has to match what is done in _make_key_from_metadata - to_return = obj - if(subpath != null and subpath != ''): - to_return += str('-', subpath) - TYPE_OBJECT: - if(_is_instance(obj)): - to_return = _make_key_from_metadata(obj) - elif(_utils.is_native_class(obj)): - to_return = _utils.get_native_class_name(obj) - else: - to_return = obj.resource_path - return to_return - -func _add_obj_method(obj, method, subpath=null): - var key = _make_key_from_variant(obj, subpath) - if(_is_instance(obj)): - key = obj - - if(!returns.has(key)): - returns[key] = {} - if(!returns[key].has(method)): - returns[key][method] = [] - - return key - -# ############## -# Public -# ############## - -# TODO: This method is only used in tests and should be refactored out. It -# does not support inner classes and isn't helpful. -func set_return(obj, method, value, parameters=null): - var key = _add_obj_method(obj, method) - var sp = _utils.StubParams.new(key, method) - sp.parameters = parameters - sp.return_val = value - returns[key][method].append(sp) - -func add_stub(stub_params): - var key = _add_obj_method(stub_params.stub_target, stub_params.stub_method, stub_params.target_subpath) - returns[key][stub_params.stub_method].append(stub_params) - -# Searches returns for an entry that matches the instance or the class that -# passed in obj is. -# -# obj can be an instance, class, or a path. -func _find_stub(obj, method, parameters=null): - var key = _make_key_from_variant(obj) - var to_return = null - - if(_is_instance(obj)): - if(returns.has(obj) and returns[obj].has(method)): - key = obj - elif(obj.get('__gut_metadata_')): - key = _make_key_from_metadata(obj) - - if(returns.has(key) and returns[key].has(method)): - var param_idx = -1 - var null_idx = -1 - - for i in range(returns[key][method].size()): - if(returns[key][method][i].parameters == parameters): - param_idx = i - if(returns[key][method][i].parameters == null): - null_idx = i - - # We have matching parameter values so return the stub value for that - if(param_idx != -1): - to_return = returns[key][method][param_idx] - # We found a case where the parameters were not specified so return - # parameters for that - elif(null_idx != -1): - to_return = returns[key][method][null_idx] - else: - _lgr.warn(str('Call to [', method, '] was not stubbed for the supplied parameters ', parameters, '. Null was returned.')) - - return to_return - -# Gets a stubbed return value for the object and method passed in. If the -# instance was stubbed it will use that, otherwise it will use the path and -# subpath of the object to try to find a value. -# -# It will also use the optional list of parameter values to find a value. If -# the object was stubbed with no parameters than any parameters will match. -# If it was stubbed with specific parameter values then it will try to match. -# If the parameters do not match BUT there was also an empty parameter list stub -# then it will return those. -# If it cannot find anything that matches then null is returned.for -# -# Parameters -# obj: this should be an instance of a doubled object. -# method: the method called -# parameters: optional array of parameter vales to find a return value for. -func get_return(obj, method, parameters=null): - var stub_info = _find_stub(obj, method, parameters) - - if(stub_info != null): - return stub_info.return_val - else: - return null - -func should_call_super(obj, method, parameters=null): - var stub_info = _find_stub(obj, method, parameters) - if(stub_info != null): - return stub_info.call_super - else: - # this log message is here because of how the generated doubled scripts - # are structured. With this log msg here, you will only see one - # "unstubbed" info instead of multiple. - _lgr.info('Unstubbed call to ' + method + '::' + str(obj)) - return false - - -func clear(): - returns.clear() - -func get_logger(): - return _lgr - -func set_logger(logger): - _lgr = logger - -func to_s(): - var text = '' - for thing in returns: - text += str(thing) + "\n" - for method in returns[thing]: - text += str("\t", method, "\n") - for i in range(returns[thing][method].size()): - text += "\t\t" + returns[thing][method][i].to_s() + "\n" - return text diff --git a/addons/gut/summary.gd b/addons/gut/summary.gd deleted file mode 100644 index 1b26b53..0000000 --- a/addons/gut/summary.gd +++ /dev/null @@ -1,152 +0,0 @@ -# ------------------------------------------------------------------------------ -# Contains all the results of a single test. Allows for multiple asserts results -# and pending calls. -# ------------------------------------------------------------------------------ -class Test: - var pass_texts = [] - var fail_texts = [] - var pending_texts = [] - - func to_s(): - var pad = ' ' - var to_return = '' - for i in range(fail_texts.size()): - to_return += str(pad, 'FAILED: ', fail_texts[i], "\n") - for i in range(pending_texts.size()): - to_return += str(pad, 'PENDING: ', pending_texts[i], "\n") - return to_return - -# ------------------------------------------------------------------------------ -# Contains all the results for a single test-script/inner class. Persists the -# names of the tests and results and the order in which the tests were run. -# ------------------------------------------------------------------------------ -class TestScript: - var name = 'NOT_SET' - # - var _tests = {} - var _test_order = [] - - func _init(script_name): - name = script_name - - func get_pass_count(): - var count = 0 - for key in _tests: - count += _tests[key].pass_texts.size() - return count - - func get_fail_count(): - var count = 0 - for key in _tests: - count += _tests[key].fail_texts.size() - return count - - func get_pending_count(): - var count = 0 - for key in _tests: - count += _tests[key].pending_texts.size() - return count - - func get_test_obj(obj_name): - if(!_tests.has(obj_name)): - _tests[obj_name] = Test.new() - _test_order.append(obj_name) - return _tests[obj_name] - - func add_pass(test_name, reason): - var t = get_test_obj(test_name) - t.pass_texts.append(reason) - - func add_fail(test_name, reason): - var t = get_test_obj(test_name) - t.fail_texts.append(reason) - - func add_pending(test_name, reason): - var t = get_test_obj(test_name) - t.pending_texts.append(reason) - -# ------------------------------------------------------------------------------ -# Summary Class -# -# This class holds the results of all the test scripts and Inner Classes that -# were run. -# -------------------------------------------d----------------------------------- -var _scripts = [] - -func add_script(name): - _scripts.append(TestScript.new(name)) - -func get_scripts(): - return _scripts - -func get_current_script(): - return _scripts[_scripts.size() - 1] - -func add_test(test_name): - get_current_script().get_test_obj(test_name) - -func add_pass(test_name, reason = ''): - get_current_script().add_pass(test_name, reason) - -func add_fail(test_name, reason = ''): - get_current_script().add_fail(test_name, reason) - -func add_pending(test_name, reason = ''): - get_current_script().add_pending(test_name, reason) - -func get_test_text(test_name): - return test_name + "\n" + get_current_script().get_test_obj(test_name).to_s() - -# Gets the count of unique script names minus the . at the -# end. Used for displaying the number of scripts without including all the -# Inner Classes. -func get_non_inner_class_script_count(): - var unique_scripts = {} - for i in range(_scripts.size()): - var ext_loc = _scripts[i].name.find_last('.gd.') - if(ext_loc == -1): - unique_scripts[_scripts[i].name] = 1 - else: - unique_scripts[_scripts[i].name.substr(0, ext_loc + 3)] = 1 - return unique_scripts.keys().size() - -func get_totals(): - var totals = { - passing = 0, - pending = 0, - failing = 0, - tests = 0, - scripts = 0 - } - - for s in range(_scripts.size()): - totals.passing += _scripts[s].get_pass_count() - totals.pending += _scripts[s].get_pending_count() - totals.failing += _scripts[s].get_fail_count() - totals.tests += _scripts[s]._test_order.size() - - totals.scripts = get_non_inner_class_script_count() - - return totals - -func get_summary_text(): - var _totals = get_totals() - - var to_return = '' - for s in range(_scripts.size()): - if(_scripts[s].get_fail_count() > 0 or _scripts[s].get_pending_count() > 0): - to_return += _scripts[s].name + "\n" - for t in range(_scripts[s]._test_order.size()): - var tname = _scripts[s]._test_order[t] - var test = _scripts[s].get_test_obj(tname) - if(test.fail_texts.size() > 0 or test.pending_texts.size() > 0): - to_return += str(' - ', tname, "\n", test.to_s()) - - var header = "*** Totals ***\n" - header += str(' Scripts: ', get_non_inner_class_script_count(), "\n") - header += str(' Tests: ', _totals.tests, "\n") - header += str(' Passing asserts: ', _totals.passing, "\n") - header += str(' Failing asserts: ',_totals.failing, "\n") - header += str(' Pending: ', _totals.pending, "\n") - - return to_return + "\n" + header diff --git a/addons/gut/test.gd b/addons/gut/test.gd deleted file mode 100644 index 0be9b15..0000000 --- a/addons/gut/test.gd +++ /dev/null @@ -1,1173 +0,0 @@ -################################################################################ -#(G)odot (U)nit (T)est class -# -################################################################################ -#The MIT License (MIT) -#===================== -# -#Copyright (c) 2019 Tom "Butch" Wesley -# -#Permission is hereby granted, free of charge, to any person obtaining a copy -#of this software and associated documentation files (the "Software"), to deal -#in the Software without restriction, including without limitation the rights -#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -#copies of the Software, and to permit persons to whom the Software is -#furnished to do so, subject to the following conditions: -# -#The above copyright notice and this permission notice shall be included in -#all copies or substantial portions of the Software. -# -#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -#THE SOFTWARE. -# -################################################################################ -# View readme for usage details. -# -# Version - see gut.gd -################################################################################ -# Class that all test scripts must extend. -# -# This provides all the asserts and other testing features. Test scripts are -# run by the Gut class in gut.gd -################################################################################ -extends Node - -# ------------------------------------------------------------------------------ -# Helper class to hold info for objects to double. This extracts info and has -# some convenience methods. This is key in being able to make the "smart double" -# method which makes doubling much easier for the user. -# ------------------------------------------------------------------------------ -class DoubleInfo: - var path - var subpath - var strategy - var make_partial - var extension - var _utils = load('res://addons/gut/utils.gd').new() - var _is_native = false - - # Flexible init method. p2 can be subpath or stategy unless p3 is - # specified, then p2 must be subpath and p3 is strategy. - # - # Examples: - # (object_to_double) - # (object_to_double, subpath) - # (object_to_double, strategy) - # (object_to_double, subpath, strategy) - func _init(thing, p2=null, p3=null): - strategy = p2 - - if(typeof(p2) == TYPE_STRING): - strategy = p3 - subpath = p2 - - if(typeof(thing) == TYPE_OBJECT): - if(_utils.is_native_class(thing)): - path = thing - _is_native = true - extension = 'native_class_not_used' - else: - path = thing.resource_path - else: - path = thing - - if(!_is_native): - extension = path.get_extension() - - func is_scene(): - return extension == 'tscn' - - func is_script(): - return extension == 'gd' - - func is_native(): - return _is_native - -# ------------------------------------------------------------------------------ -# Begin test.gd -# ------------------------------------------------------------------------------ - -# constant for signal when calling yield_for -const YIELD = 'timeout' - -# Need a reference to the instance that is running the tests. This -# is set by the gut class when it runs the tests. This gets you -# access to the asserts in the tests you write. -var gut = null -var passed = false -var failed = false -var _disable_strict_datatype_checks = false -# Holds all the text for a test's fail/pass. This is used for testing purposes -# to see the text of a failed sub-test in test_test.gd -var _fail_pass_text = [] - -# Hash containing all the built in types in Godot. This provides an English -# name for the types that corosponds with the type constants defined in the -# engine. This is used for priting out messages when comparing types fails. -var types = {} - -func _init_types_dictionary(): - types[TYPE_NIL] = 'TYPE_NIL' - types[TYPE_BOOL] = 'Bool' - types[TYPE_INT] = 'Int' - types[TYPE_REAL] = 'Float/Real' - types[TYPE_STRING] = 'String' - types[TYPE_VECTOR2] = 'Vector2' - types[TYPE_RECT2] = 'Rect2' - types[TYPE_VECTOR3] = 'Vector3' - #types[8] = 'Matrix32' - types[TYPE_PLANE] = 'Plane' - types[TYPE_QUAT] = 'QUAT' - types[TYPE_AABB] = 'AABB' - #types[12] = 'Matrix3' - types[TYPE_TRANSFORM] = 'Transform' - types[TYPE_COLOR] = 'Color' - #types[15] = 'Image' - types[TYPE_NODE_PATH] = 'Node Path' - types[TYPE_RID] = 'RID' - types[TYPE_OBJECT] = 'TYPE_OBJECT' - #types[19] = 'TYPE_INPUT_EVENT' - types[TYPE_DICTIONARY] = 'Dictionary' - types[TYPE_ARRAY] = 'Array' - types[TYPE_RAW_ARRAY] = 'TYPE_RAW_ARRAY' - types[TYPE_INT_ARRAY] = 'TYPE_INT_ARRAY' - types[TYPE_REAL_ARRAY] = 'TYPE_REAL_ARRAY' - types[TYPE_STRING_ARRAY] = 'TYPE_STRING_ARRAY' - types[TYPE_VECTOR2_ARRAY] = 'TYPE_VECTOR2_ARRAY' - types[TYPE_VECTOR3_ARRAY] = 'TYPE_VECTOR3_ARRAY' - types[TYPE_COLOR_ARRAY] = 'TYPE_COLOR_ARRAY' - types[TYPE_MAX] = 'TYPE_MAX' - -const EDITOR_PROPERTY = PROPERTY_USAGE_SCRIPT_VARIABLE | PROPERTY_USAGE_DEFAULT -const VARIABLE_PROPERTY = PROPERTY_USAGE_SCRIPT_VARIABLE - -# Summary counts for the test. -var _summary = { - asserts = 0, - passed = 0, - failed = 0, - tests = 0, - pending = 0 -} - -# This is used to watch signals so we can make assertions about them. -var _signal_watcher = load('res://addons/gut/signal_watcher.gd').new() - -# Convenience copy of _utils.DOUBLE_STRATEGY -var DOUBLE_STRATEGY = null -var _utils = load('res://addons/gut/utils.gd').new() -var _lgr = _utils.get_logger() - -func _init(): - _init_types_dictionary() - DOUBLE_STRATEGY = _utils.DOUBLE_STRATEGY # yes, this is right - -# ------------------------------------------------------------------------------ -# Fail an assertion. Causes test and script to fail as well. -# ------------------------------------------------------------------------------ -func _fail(text): - _summary.asserts += 1 - _summary.failed += 1 - var msg = 'FAILED: ' + text - _fail_pass_text.append(msg) - if(gut): - gut.p(msg, gut.LOG_LEVEL_FAIL_ONLY) - gut._fail(text) - -# ------------------------------------------------------------------------------ -# Pass an assertion. -# ------------------------------------------------------------------------------ -func _pass(text): - _summary.asserts += 1 - _summary.passed += 1 - var msg = "PASSED: " + text - _fail_pass_text.append(msg) - if(gut): - gut.p(msg, gut.LOG_LEVEL_ALL_ASSERTS) - gut._pass(text) - -# ------------------------------------------------------------------------------ -# Checks if the datatypes passed in match. If they do not then this will cause -# a fail to occur. If they match then TRUE is returned, FALSE if not. This is -# used in all the assertions that compare values. -# ------------------------------------------------------------------------------ -func _do_datatypes_match__fail_if_not(got, expected, text): - var did_pass = true - - if(!_disable_strict_datatype_checks): - var got_type = typeof(got) - var expect_type = typeof(expected) - if(got_type != expect_type and got != null and expected != null): - # If we have a mismatch between float and int (types 2 and 3) then - # print out a warning but do not fail. - if([2, 3].has(got_type) and [2, 3].has(expect_type)): - _lgr.warn(str('Warn: Float/Int comparison. Got ', types[got_type], ' but expected ', types[expect_type])) - else: - _fail('Cannot compare ' + types[got_type] + '[' + str(got) + '] to ' + types[expect_type] + '[' + str(expected) + ']. ' + text) - did_pass = false - - return did_pass - -# ------------------------------------------------------------------------------ -# Create a string that lists all the methods that were called on an spied -# instance. -# ------------------------------------------------------------------------------ -func _get_desc_of_calls_to_instance(inst): - var BULLET = ' * ' - var calls = gut.get_spy().get_call_list_as_string(inst) - # indent all the calls - calls = BULLET + calls.replace("\n", "\n" + BULLET) - # remove trailing newline and bullet - calls = calls.substr(0, calls.length() - BULLET.length() - 1) - return "Calls made on " + str(inst) + "\n" + calls - -# ------------------------------------------------------------------------------ -# Signal assertion helper. Do not call directly, use _can_make_signal_assertions -# ------------------------------------------------------------------------------ -func _fail_if_does_not_have_signal(object, signal_name): - var did_fail = false - if(!_signal_watcher.does_object_have_signal(object, signal_name)): - _fail(str('Object ', object, ' does not have the signal [', signal_name, ']')) - did_fail = true - return did_fail -# ------------------------------------------------------------------------------ -# Signal assertion helper. Do not call directly, use _can_make_signal_assertions -# ------------------------------------------------------------------------------ -func _fail_if_not_watching(object): - var did_fail = false - if(!_signal_watcher.is_watching_object(object)): - _fail(str('Cannot make signal assertions because the object ', object, \ - ' is not being watched. Call watch_signals(some_object) to be able to make assertions about signals.')) - did_fail = true - return did_fail - -# ------------------------------------------------------------------------------ -# Returns text that contains original text and a list of all the signals that -# were emitted for the passed in object. -# ------------------------------------------------------------------------------ -func _get_fail_msg_including_emitted_signals(text, object): - return str(text," (Signals emitted: ", _signal_watcher.get_signals_emitted(object), ")") - -# ------------------------------------------------------------------------------ -# This validates that parameters is an array and generates a specific error -# and a failure with a specific message -# ------------------------------------------------------------------------------ -func _fail_if_parameters_not_array(parameters): - var invalid = parameters != null and typeof(parameters) != TYPE_ARRAY - if(invalid): - _lgr.error('The "parameters" parameter must be an array of expected parameter values.') - _fail('Cannot compare paramter values because an array was not passed.') - return invalid -# ####################### -# Virtual Methods -# ####################### - -# alias for prerun_setup -func before_all(): - pass - -# alias for setup -func before_each(): - pass - -# alias for postrun_teardown -func after_all(): - pass - -# alias for teardown -func after_each(): - pass - -# ####################### -# Public -# ####################### - -func get_logger(): - return _lgr - -func set_logger(logger): - _lgr = logger - - -# ####################### -# Asserts -# ####################### - -# ------------------------------------------------------------------------------ -# Asserts that the expected value equals the value got. -# ------------------------------------------------------------------------------ -func assert_eq(got, expected, text=""): - var disp = "[" + str(got) + "] expected to equal [" + str(expected) + "]: " + text - if(_do_datatypes_match__fail_if_not(got, expected, text)): - if(expected != got): - _fail(disp) - else: - _pass(disp) - -# ------------------------------------------------------------------------------ -# Asserts that the value got does not equal the "not expected" value. -# ------------------------------------------------------------------------------ -func assert_ne(got, not_expected, text=""): - var disp = "[" + str(got) + "] expected to be anything except [" + str(not_expected) + "]: " + text - if(_do_datatypes_match__fail_if_not(got, not_expected, text)): - if(got == not_expected): - _fail(disp) - else: - _pass(disp) - -# ------------------------------------------------------------------------------ -# Asserts that the expected value almost equals the value got. -# ------------------------------------------------------------------------------ -func assert_almost_eq(got, expected, error_interval, text=''): - var disp = "[" + str(got) + "] expected to equal [" + str(expected) + "] +/- [" + str(error_interval) + "]: " + text - if(_do_datatypes_match__fail_if_not(got, expected, text) and _do_datatypes_match__fail_if_not(got, error_interval, text)): - if(got < (expected - error_interval) or got > (expected + error_interval)): - _fail(disp) - else: - _pass(disp) - -# ------------------------------------------------------------------------------ -# Asserts that the expected value does not almost equal the value got. -# ------------------------------------------------------------------------------ -func assert_almost_ne(got, not_expected, error_interval, text=''): - var disp = "[" + str(got) + "] expected to not equal [" + str(not_expected) + "] +/- [" + str(error_interval) + "]: " + text - if(_do_datatypes_match__fail_if_not(got, not_expected, text) and _do_datatypes_match__fail_if_not(got, error_interval, text)): - if(got < (not_expected - error_interval) or got > (not_expected + error_interval)): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Asserts got is greater than expected -# ------------------------------------------------------------------------------ -func assert_gt(got, expected, text=""): - var disp = "[" + str(got) + "] expected to be > than [" + str(expected) + "]: " + text - if(_do_datatypes_match__fail_if_not(got, expected, text)): - if(got > expected): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Asserts got is less than expected -# ------------------------------------------------------------------------------ -func assert_lt(got, expected, text=""): - var disp = "[" + str(got) + "] expected to be < than [" + str(expected) + "]: " + text - if(_do_datatypes_match__fail_if_not(got, expected, text)): - if(got < expected): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# asserts that got is true -# ------------------------------------------------------------------------------ -func assert_true(got, text=""): - if(!got): - _fail(text) - else: - _pass(text) - -# ------------------------------------------------------------------------------ -# Asserts that got is false -# ------------------------------------------------------------------------------ -func assert_false(got, text=""): - if(got): - _fail(text) - else: - _pass(text) - -# ------------------------------------------------------------------------------ -# Asserts value is between (inclusive) the two expected values. -# ------------------------------------------------------------------------------ -func assert_between(got, expect_low, expect_high, text=""): - var disp = "[" + str(got) + "] expected to be between [" + str(expect_low) + "] and [" + str(expect_high) + "]: " + text - - if(_do_datatypes_match__fail_if_not(got, expect_low, text) and _do_datatypes_match__fail_if_not(got, expect_high, text)): - if(expect_low > expect_high): - disp = "INVALID range. [" + str(expect_low) + "] is not less than [" + str(expect_high) + "]" - _fail(disp) - else: - if(got < expect_low or got > expect_high): - _fail(disp) - else: - _pass(disp) - -# ------------------------------------------------------------------------------ -# Uses the 'has' method of the object passed in to determine if it contains -# the passed in element. -# ------------------------------------------------------------------------------ -func assert_has(obj, element, text=""): - var disp = str('Expected [', obj, '] to contain value: [', element, ']: ', text) - if(obj.has(element)): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func assert_does_not_have(obj, element, text=""): - var disp = str('Expected [', obj, '] to NOT contain value: [', element, ']: ', text) - if(obj.has(element)): - _fail(disp) - else: - _pass(disp) - -# ------------------------------------------------------------------------------ -# Asserts that a file exists -# ------------------------------------------------------------------------------ -func assert_file_exists(file_path): - var disp = 'expected [' + file_path + '] to exist.' - var f = File.new() - if(f.file_exists(file_path)): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Asserts that a file should not exist -# ------------------------------------------------------------------------------ -func assert_file_does_not_exist(file_path): - var disp = 'expected [' + file_path + '] to NOT exist' - var f = File.new() - if(!f.file_exists(file_path)): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Asserts the specified file is empty -# ------------------------------------------------------------------------------ -func assert_file_empty(file_path): - var disp = 'expected [' + file_path + '] to be empty' - var f = File.new() - if(f.file_exists(file_path) and gut.is_file_empty(file_path)): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Asserts the specified file is not empty -# ------------------------------------------------------------------------------ -func assert_file_not_empty(file_path): - var disp = 'expected [' + file_path + '] to contain data' - if(!gut.is_file_empty(file_path)): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Asserts the object has the specified method -# ------------------------------------------------------------------------------ -func assert_has_method(obj, method): - assert_true(obj.has_method(method), 'Should have method: ' + method) - -# Old deprecated method name -func assert_get_set_methods(obj, property, default, set_to): - _lgr.deprecated('assert_get_set_methods', 'assert_accessors') - assert_accessors(obj, property, default, set_to) - -# ------------------------------------------------------------------------------ -# Verifies the object has get and set methods for the property passed in. The -# property isn't tied to anything, just a name to be appended to the end of -# get_ and set_. Asserts the get_ and set_ methods exist, if not, it stops there. -# If they exist then it asserts get_ returns the expected default then calls -# set_ and asserts get_ has the value it was set to. -# ------------------------------------------------------------------------------ -func assert_accessors(obj, property, default, set_to): - var fail_count = _summary.failed - var get = 'get_' + property - var set = 'set_' + property - assert_has_method(obj, get) - assert_has_method(obj, set) - # SHORT CIRCUIT - if(_summary.failed > fail_count): - return - assert_eq(obj.call(get), default, 'It should have the expected default value.') - obj.call(set, set_to) - assert_eq(obj.call(get), set_to, 'The set value should have been returned.') - - -# --------------------------------------------------------------------------- -# Property search helper. Used to retrieve Dictionary of specified property -# from passed object. Returns null if not found. -# If provided, property_usage constrains the type of property returned by -# passing either: -# EDITOR_PROPERTY for properties defined as: export(int) var some_value -# VARIABLE_PROPERTY for properties defunded as: var another_value -# --------------------------------------------------------------------------- -func _find_object_property(obj, property_name, property_usage=null): - var result = null - var found = false - var properties = obj.get_property_list() - - while !found and !properties.empty(): - var property = properties.pop_back() - if property['name'] == property_name: - if property_usage == null or property['usage'] == property_usage: - result = property - found = true - return result - -# ------------------------------------------------------------------------------ -# Asserts a class exports a variable. -# ------------------------------------------------------------------------------ -func assert_exports(obj, property_name, type): - var disp = 'expected %s to have editor property [%s]' % [obj, property_name] - var property = _find_object_property(obj, property_name, EDITOR_PROPERTY) - if property != null: - disp += ' of type [%s]. Got type [%s].' % [types[type], types[property['type']]] - if property['type'] == type: - _pass(disp) - else: - _fail(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Signal assertion helper. -# -# Verifies that the object and signal are valid for making signal assertions. -# This will fail with specific messages that indicate why they are not valid. -# This returns true/false to indicate if the object and signal are valid. -# ------------------------------------------------------------------------------ -func _can_make_signal_assertions(object, signal_name): - return !(_fail_if_not_watching(object) or _fail_if_does_not_have_signal(object, signal_name)) - -# ------------------------------------------------------------------------------ -# Check if an object is connected to a signal on another object. Returns True -# if it is and false otherwise -# ------------------------------------------------------------------------------ -func _is_connected(signaler_obj, connect_to_obj, signal_name, method_name=""): - if(method_name != ""): - return signaler_obj.is_connected(signal_name, connect_to_obj, method_name) - else: - var connections = signaler_obj.get_signal_connection_list(signal_name) - for conn in connections: - if((conn.source == signaler_obj) and (conn.target == connect_to_obj)): - return true - return false -# ------------------------------------------------------------------------------ -# Watch the signals for an object. This must be called before you can make -# any assertions about the signals themselves. -# ------------------------------------------------------------------------------ -func watch_signals(object): - _signal_watcher.watch_signals(object) - -# ------------------------------------------------------------------------------ -# Asserts that an object is connected to a signal on another object -# -# This will fail with specific messages if the target object is not connected -# to the specified signal on the source object. -# ------------------------------------------------------------------------------ -func assert_connected(signaler_obj, connect_to_obj, signal_name, method_name=""): - pass - var method_disp = '' - if (method_name != ""): - method_disp = str(' using method: [', method_name, '] ') - var disp = str('Expected object ', signaler_obj,\ - ' to be connected to signal: [', signal_name, '] on ',\ - connect_to_obj, method_disp) - if(_is_connected(signaler_obj, connect_to_obj, signal_name, method_name)): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Asserts that an object is not connected to a signal on another object -# -# This will fail with specific messages if the target object is connected -# to the specified signal on the source object. -# ------------------------------------------------------------------------------ -func assert_not_connected(signaler_obj, connect_to_obj, signal_name, method_name=""): - var method_disp = '' - if (method_name != ""): - method_disp = str(' using method: [', method_name, '] ') - var disp = str('Expected object ', signaler_obj,\ - ' to not be connected to signal: [', signal_name, '] on ',\ - connect_to_obj, method_disp) - if(_is_connected(signaler_obj, connect_to_obj, signal_name, method_name)): - _fail(disp) - else: - _pass(disp) - -# ------------------------------------------------------------------------------ -# Asserts that a signal has been emitted at least once. -# -# This will fail with specific messages if the object is not being watched or -# the object does not have the specified signal -# ------------------------------------------------------------------------------ -func assert_signal_emitted(object, signal_name, text=""): - var disp = str('Expected object ', object, ' to have emitted signal [', signal_name, ']: ', text) - if(_can_make_signal_assertions(object, signal_name)): - if(_signal_watcher.did_emit(object, signal_name)): - _pass(disp) - else: - _fail(_get_fail_msg_including_emitted_signals(disp, object)) - -# ------------------------------------------------------------------------------ -# Asserts that a signal has not been emitted. -# -# This will fail with specific messages if the object is not being watched or -# the object does not have the specified signal -# ------------------------------------------------------------------------------ -func assert_signal_not_emitted(object, signal_name, text=""): - var disp = str('Expected object ', object, ' to NOT emit signal [', signal_name, ']: ', text) - if(_can_make_signal_assertions(object, signal_name)): - if(_signal_watcher.did_emit(object, signal_name)): - _fail(disp) - else: - _pass(disp) - -# ------------------------------------------------------------------------------ -# Asserts that a signal was fired with the specified parameters. The expected -# parameters should be passed in as an array. An optional index can be passed -# when a signal has fired more than once. The default is to retrieve the most -# recent emission of the signal. -# -# This will fail with specific messages if the object is not being watched or -# the object does not have the specified signal -# ------------------------------------------------------------------------------ -func assert_signal_emitted_with_parameters(object, signal_name, parameters, index=-1): - var disp = str('Expected object ', object, ' to emit signal [', signal_name, '] with parameters ', parameters, ', got ') - if(_can_make_signal_assertions(object, signal_name)): - if(_signal_watcher.did_emit(object, signal_name)): - var parms_got = _signal_watcher.get_signal_parameters(object, signal_name, index) - if(parameters == parms_got): - _pass(str(disp, parms_got)) - else: - _fail(str(disp, parms_got)) - else: - var text = str('Object ', object, ' did not emit signal [', signal_name, ']') - _fail(_get_fail_msg_including_emitted_signals(text, object)) - -# ------------------------------------------------------------------------------ -# Assert that a signal has been emitted a specific number of times. -# -# This will fail with specific messages if the object is not being watched or -# the object does not have the specified signal -# ------------------------------------------------------------------------------ -func assert_signal_emit_count(object, signal_name, times, text=""): - - if(_can_make_signal_assertions(object, signal_name)): - var count = _signal_watcher.get_emit_count(object, signal_name) - var disp = str('Expected the signal [', signal_name, '] emit count of [', count, '] to equal [', times, ']: ', text) - if(count== times): - _pass(disp) - else: - _fail(_get_fail_msg_including_emitted_signals(disp, object)) - -# ------------------------------------------------------------------------------ -# Assert that the passed in object has the specified signal -# ------------------------------------------------------------------------------ -func assert_has_signal(object, signal_name, text=""): - var disp = str('Expected object ', object, ' to have signal [', signal_name, ']: ', text) - if(_signal_watcher.does_object_have_signal(object, signal_name)): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Returns the number of times a signal was emitted. -1 returned if the object -# is not being watched. -# ------------------------------------------------------------------------------ -func get_signal_emit_count(object, signal_name): - return _signal_watcher.get_emit_count(object, signal_name) - -# ------------------------------------------------------------------------------ -# Get the parmaters of a fired signal. If the signal was not fired null is -# returned. You can specify an optional index (use get_signal_emit_count to -# determine the number of times it was emitted). The default index is the -# latest time the signal was fired (size() -1 insetead of 0). The parameters -# returned are in an array. -# ------------------------------------------------------------------------------ -func get_signal_parameters(object, signal_name, index=-1): - return _signal_watcher.get_signal_parameters(object, signal_name, index) - -# ------------------------------------------------------------------------------ -# Get the parameters for a method call to a doubled object. By default it will -# return the most recent call. You can optionally specify an index. -# -# Returns: -# * an array of parameter values if a call the method was found -# * null when a call to the method was not found or the index specified was -# invalid. -# ------------------------------------------------------------------------------ -func get_call_parameters(object, method_name, index=-1): - var to_return = null - if(_utils.is_double(object)): - to_return = gut.get_spy().get_call_parameters(object, method_name, index) - else: - _lgr.error('You must pass a doulbed object to get_call_parameters.') - - return to_return - -# ------------------------------------------------------------------------------ -# Assert that object is an instance of a_class -# ------------------------------------------------------------------------------ -func assert_extends(object, a_class, text=''): - _lgr.deprecated('assert_extends', 'assert_is') - assert_is(object, a_class, text) - -# Alias for assert_extends -func assert_is(object, a_class, text=''): - var disp = str('Expected [', object, '] to be type of [', a_class, ']: ', text) - var NATIVE_CLASS = 'GDScriptNativeClass' - var GDSCRIPT_CLASS = 'GDScript' - var bad_param_2 = 'Parameter 2 must be a Class (like Node2D or Label). You passed ' - - if(typeof(object) != TYPE_OBJECT): - _fail(str('Parameter 1 must be an instance of an object. You passed: ', types[typeof(object)])) - elif(typeof(a_class) != TYPE_OBJECT): - _fail(str(bad_param_2, types[typeof(a_class)])) - else: - disp = str('Expected [', object.get_class(), '] to extend [', a_class.get_class(), ']: ', text) - if(a_class.get_class() != NATIVE_CLASS and a_class.get_class() != GDSCRIPT_CLASS): - _fail(str(bad_param_2, a_class.get_class(), ' ', types[typeof(a_class)])) - else: - if(object is a_class): - _pass(disp) - else: - _fail(disp) - -func _get_typeof_string(the_type): - var to_return = "" - if(types.has(the_type)): - to_return += str(the_type, '(', types[the_type], ')') - else: - to_return += str(the_type) - return to_return - - # ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func assert_typeof(object, type, text=''): - var disp = str('Expected [typeof(', object, ') = ') - disp += _get_typeof_string(typeof(object)) - disp += '] to equal [' - disp += _get_typeof_string(type) + ']' - disp += '. ' + text - if(typeof(object) == type): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func assert_not_typeof(object, type, text=''): - var disp = str('Expected [typeof(', object, ') = ') - disp += _get_typeof_string(typeof(object)) - disp += '] to not equal [' - disp += _get_typeof_string(type) + ']' - disp += '. ' + text - if(typeof(object) != type): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Assert that text contains given search string. -# The match_case flag determines case sensitivity. -# ------------------------------------------------------------------------------ -func assert_string_contains(text, search, match_case=true): - var empty_search = 'Expected text and search strings to be non-empty. You passed \'%s\' and \'%s\'.' - var disp = 'Expected \'%s\' to contain \'%s\', match_case=%s' % [text, search, match_case] - if(text == '' or search == ''): - _fail(empty_search % [text, search]) - elif(match_case): - if(text.find(search) == -1): - _fail(disp) - else: - _pass(disp) - else: - if(text.to_lower().find(search.to_lower()) == -1): - _fail(disp) - else: - _pass(disp) - -# ------------------------------------------------------------------------------ -# Assert that text starts with given search string. -# match_case flag determines case sensitivity. -# ------------------------------------------------------------------------------ -func assert_string_starts_with(text, search, match_case=true): - var empty_search = 'Expected text and search strings to be non-empty. You passed \'%s\' and \'%s\'.' - var disp = 'Expected \'%s\' to start with \'%s\', match_case=%s' % [text, search, match_case] - if(text == '' or search == ''): - _fail(empty_search % [text, search]) - elif(match_case): - if(text.find(search) == 0): - _pass(disp) - else: - _fail(disp) - else: - if(text.to_lower().find(search.to_lower()) == 0): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Assert that text ends with given search string. -# match_case flag determines case sensitivity. -# ------------------------------------------------------------------------------ -func assert_string_ends_with(text, search, match_case=true): - var empty_search = 'Expected text and search strings to be non-empty. You passed \'%s\' and \'%s\'.' - var disp = 'Expected \'%s\' to end with \'%s\', match_case=%s' % [text, search, match_case] - var required_index = len(text) - len(search) - if(text == '' or search == ''): - _fail(empty_search % [text, search]) - elif(match_case): - if(text.find(search) == required_index): - _pass(disp) - else: - _fail(disp) - else: - if(text.to_lower().find(search.to_lower()) == required_index): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Assert that a method was called on an instance of a doubled class. If -# parameters are supplied then the params passed in when called must match. -# TODO make 3rd parameter "param_or_text" and add fourth parameter of "text" and -# then work some magic so this can have a "text" parameter without being -# annoying. -# ------------------------------------------------------------------------------ -func assert_called(inst, method_name, parameters=null): - var disp = str('Expected [',method_name,'] to have been called on ',inst) - - if(_fail_if_parameters_not_array(parameters)): - return - - if(!_utils.is_double(inst)): - _fail('You must pass a doubled instance to assert_called. Check the wiki for info on using double.') - else: - if(gut.get_spy().was_called(inst, method_name, parameters)): - _pass(disp) - else: - if(parameters != null): - disp += str(' with parameters ', parameters) - _fail(str(disp, "\n", _get_desc_of_calls_to_instance(inst))) - -# ------------------------------------------------------------------------------ -# Assert that a method was not called on an instance of a doubled class. If -# parameters are specified then this will only fail if it finds a call that was -# sent matching parameters. -# ------------------------------------------------------------------------------ -func assert_not_called(inst, method_name, parameters=null): - var disp = str('Expected [', method_name, '] to NOT have been called on ', inst) - - if(_fail_if_parameters_not_array(parameters)): - return - - if(!_utils.is_double(inst)): - _fail('You must pass a doubled instance to assert_not_called. Check the wiki for info on using double.') - else: - if(gut.get_spy().was_called(inst, method_name, parameters)): - if(parameters != null): - disp += str(' with parameters ', parameters) - _fail(str(disp, "\n", _get_desc_of_calls_to_instance(inst))) - else: - _pass(disp) - -# ------------------------------------------------------------------------------ -# Assert that a method on an instance of a doubled class was called a number -# of times. If parameters are specified then only calls with matching -# parameter values will be counted. -# ------------------------------------------------------------------------------ -func assert_call_count(inst, method_name, expected_count, parameters=null): - var count = gut.get_spy().call_count(inst, method_name, parameters) - - if(_fail_if_parameters_not_array(parameters)): - return - - var param_text = '' - if(parameters): - param_text = ' with parameters ' + str(parameters) - var disp = 'Expected [%s] on %s to be called [%s] times%s. It was called [%s] times.' - disp = disp % [method_name, inst, expected_count, param_text, count] - - if(!_utils.is_double(inst)): - _fail('You must pass a doubled instance to assert_call_count. Check the wiki for info on using double.') - else: - if(count == expected_count): - _pass(disp) - else: - _fail(str(disp, "\n", _get_desc_of_calls_to_instance(inst))) - -# ------------------------------------------------------------------------------ -# Asserts the passed in value is null -# ------------------------------------------------------------------------------ -func assert_null(got, text=''): - var disp = str('Expected [', got, '] to be NULL: ', text) - if(got == null): - _pass(disp) - else: - _fail(disp) - -# ------------------------------------------------------------------------------ -# Asserts the passed in value is null -# ------------------------------------------------------------------------------ -func assert_not_null(got, text=''): - var disp = str('Expected [', got, '] to be anything but NULL: ', text) - if(got == null): - _fail(disp) - else: - _pass(disp) - -# ----------------------------------------------------------------------------- -# Asserts object has been freed from memory -# We pass in a title (since if it is freed, we lost all identity data) -# ----------------------------------------------------------------------------- -func assert_freed(obj, title): - assert_true(not is_instance_valid(obj), "Object %s is freed" % title) - -# ------------------------------------------------------------------------------ -# Asserts Object has not been freed from memory -# ----------------------------------------------------------------------------- -func assert_not_freed(obj, title): - assert_true(is_instance_valid(obj), "Object %s is not freed" % title) - -# ------------------------------------------------------------------------------ -# Mark the current test as pending. -# ------------------------------------------------------------------------------ -func pending(text=""): - _summary.pending += 1 - if(gut): - if(text == ""): - gut.p("PENDING") - else: - gut.p("PENDING: " + text) - gut._pending(text) - -# ------------------------------------------------------------------------------ -# Returns the number of times a signal was emitted. -1 returned if the object -# is not being watched. -# ------------------------------------------------------------------------------ - -# ------------------------------------------------------------------------------ -# Yield for the time sent in. The optional message will be printed when -# Gut detects the yield. When the time expires the YIELD signal will be -# emitted. -# ------------------------------------------------------------------------------ -func yield_for(time, msg=''): - return gut.set_yield_time(time, msg) - -# ------------------------------------------------------------------------------ -# Yield to a signal or a maximum amount of time, whichever comes first. When -# the conditions are met the YIELD signal will be emitted. -# ------------------------------------------------------------------------------ -func yield_to(obj, signal_name, max_wait, msg=''): - watch_signals(obj) - gut.set_yield_signal_or_time(obj, signal_name, max_wait, msg) - - return gut - -# ------------------------------------------------------------------------------ -# Ends a test that had a yield in it. You only need to use this if you do -# not make assertions after a yield. -# ------------------------------------------------------------------------------ -func end_test(): - _lgr.deprecated('end_test is no longer necessary, you can remove it.') - #gut.end_yielded_test() - -func get_summary(): - return _summary - -func get_fail_count(): - return _summary.failed - -func get_pass_count(): - return _summary.passed - -func get_pending_count(): - return _summary.pending - -func get_assert_count(): - return _summary.asserts - -func clear_signal_watcher(): - _signal_watcher.clear() - -func get_double_strategy(): - return gut.get_doubler().get_strategy() - -func set_double_strategy(double_strategy): - gut.get_doubler().set_strategy(double_strategy) - -func pause_before_teardown(): - gut.pause_before_teardown() -# ------------------------------------------------------------------------------ -# Convert the _summary dictionary into text -# ------------------------------------------------------------------------------ -func get_summary_text(): - var to_return = get_script().get_path() + "\n" - to_return += str(' ', _summary.passed, ' of ', _summary.asserts, ' passed.') - if(_summary.pending > 0): - to_return += str("\n ", _summary.pending, ' pending') - if(_summary.failed > 0): - to_return += str("\n ", _summary.failed, ' failed.') - return to_return - -# ------------------------------------------------------------------------------ -# Double a script, inner class, or scene using a path or a loaded script/scene. -# -# -# ------------------------------------------------------------------------------ - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func _smart_double(double_info): - var override_strat = _utils.nvl(double_info.strategy, gut.get_doubler().get_strategy()) - var to_return = null - - if(double_info.is_scene()): - if(double_info.make_partial): - to_return = gut.get_doubler().partial_double_scene(double_info.path, override_strat) - else: - to_return = gut.get_doubler().double_scene(double_info.path, override_strat) - - elif(double_info.is_native()): - if(double_info.make_partial): - to_return = gut.get_doubler().partial_double_gdnative(double_info.path) - else: - to_return = gut.get_doubler().double_gdnative(double_info.path) - - elif(double_info.is_script()): - if(double_info.subpath == null): - if(double_info.make_partial): - to_return = gut.get_doubler().partial_double(double_info.path, override_strat) - else: - to_return = gut.get_doubler().double(double_info.path, override_strat) - else: - if(double_info.make_partial): - to_return = gut.get_doubler().partial_double_inner(double_info.path, double_info.subpath, override_strat) - else: - to_return = gut.get_doubler().double_inner(double_info.path, double_info.subpath, override_strat) - return to_return - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func double(thing, p2=null, p3=null): - var double_info = DoubleInfo.new(thing, p2, p3) - double_info.make_partial = false - - return _smart_double(double_info) - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func partial_double(thing, p2=null, p3=null): - var double_info = DoubleInfo.new(thing, p2, p3) - double_info.make_partial = true - - return _smart_double(double_info) - - -# ------------------------------------------------------------------------------ -# Specifically double a scene -# ------------------------------------------------------------------------------ -func double_scene(path, strategy=null): - var override_strat = _utils.nvl(strategy, gut.get_doubler().get_strategy()) - return gut.get_doubler().double_scene(path, override_strat) - -# ------------------------------------------------------------------------------ -# Specifically double a script -# ------------------------------------------------------------------------------ -func double_script(path, strategy=null): - var override_strat = _utils.nvl(strategy, gut.get_doubler().get_strategy()) - return gut.get_doubler().double(path, override_strat) - -# ------------------------------------------------------------------------------ -# Specifically double an Inner class in a a script -# ------------------------------------------------------------------------------ -func double_inner(path, subpath, strategy=null): - var override_strat = _utils.nvl(strategy, gut.get_doubler().get_strategy()) - return gut.get_doubler().double_inner(path, subpath, override_strat) - -# ------------------------------------------------------------------------------ -# Add a method that the doubler will ignore. You can pass this the path to a -# script or scene or a loaded script or scene. When running tests, these -# ignores are cleared after every test. -# ------------------------------------------------------------------------------ -func ignore_method_when_doubling(thing, method_name): - var double_info = DoubleInfo.new(thing) - var path = double_info.path - - if(double_info.is_scene()): - var inst = thing.instance() - if(inst.get_script()): - path = inst.get_script().get_path() - - gut.get_doubler().add_ignored_method(path, method_name) - -# ------------------------------------------------------------------------------ -# Stub something. -# -# Parameters -# 1: the thing to stub, a file path or a instance or a class -# 2: either an inner class subpath or the method name -# 3: the method name if an inner class subpath was specified -# NOTE: right now we cannot stub inner classes at the path level so this should -# only be called with two parameters. I did the work though so I'm going -# to leave it but not update the wiki. -# ------------------------------------------------------------------------------ -func stub(thing, p2, p3=null): - var method_name = p2 - var subpath = null - if(p3 != null): - subpath = p2 - method_name = p3 - var sp = _utils.StubParams.new(thing, method_name, subpath) - gut.get_stubber().add_stub(sp) - return sp - -# ------------------------------------------------------------------------------ -# convenience wrapper. -# ------------------------------------------------------------------------------ -func simulate(obj, times, delta): - gut.simulate(obj, times, delta) - -# ------------------------------------------------------------------------------ -# Replace the node at base_node.get_node(path) with with_this. All references -# to the node via $ and get_node(...) will now return with_this. with_this will -# get all the groups that the node that was replaced had. -# -# The node that was replaced is queued to be freed. -# -# TODO see replace_by method, this could simplify the logic here. -# ------------------------------------------------------------------------------ -func replace_node(base_node, path_or_node, with_this): - var path = path_or_node - - if(typeof(path_or_node) != TYPE_STRING): - # This will cause an engine error if it fails. It always returns a - # NodePath, even if it fails. Checking the name count is the only way - # I found to check if it found something or not (after it worked I - # didn't look any farther). - path = base_node.get_path_to(path_or_node) - if(path.get_name_count() == 0): - _lgr.error('You passed an object that base_node does not have. Cannot replace node.') - return - - if(!base_node.has_node(path)): - _lgr.error(str('Could not find node at path [', path, ']')) - return - - var to_replace = base_node.get_node(path) - var parent = to_replace.get_parent() - var replace_name = to_replace.get_name() - - parent.remove_child(to_replace) - parent.add_child(with_this) - with_this.set_name(replace_name) - with_this.set_owner(parent) - - var groups = to_replace.get_groups() - for i in range(groups.size()): - with_this.add_to_group(groups[i]) - - to_replace.queue_free() diff --git a/addons/gut/test_collector.gd b/addons/gut/test_collector.gd deleted file mode 100644 index 8d8264a..0000000 --- a/addons/gut/test_collector.gd +++ /dev/null @@ -1,241 +0,0 @@ -# ------------------------------------------------------------------------------ -# Used to keep track of info about each test ran. -# ------------------------------------------------------------------------------ -class Test: - # indicator if it passed or not. defaults to true since it takes only - # one failure to make it not pass. _fail in gut will set this. - var passed = true - # the name of the function - var name = "" - # flag to know if the name has been printed yet. - var has_printed_name = false - # the line number the test is on - var line_number = -1 - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -class TestScript: - var inner_class_name = null - var tests = [] - var path = null - var _utils = null - var _lgr = null - - func _init(utils=null, logger=null): - _utils = utils - _lgr = logger - - func to_s(): - var to_return = path - if(inner_class_name != null): - to_return += str('.', inner_class_name) - to_return += "\n" - for i in range(tests.size()): - to_return += str(' ', tests[i].name, "\n") - return to_return - - func get_new(): - var TheScript = load(path) - var inst = null - if(inner_class_name != null): - inst = TheScript.get(inner_class_name).new() - else: - inst = TheScript.new() - return inst - - func get_full_name(): - var to_return = path - if(inner_class_name != null): - to_return += '.' + inner_class_name - return to_return - - func get_filename(): - return path.get_file() - - func has_inner_class(): - return inner_class_name != null - - func export_to(config_file, section): - config_file.set_value(section, 'path', path) - config_file.set_value(section, 'inner_class', inner_class_name) - var names = [] - for i in range(tests.size()): - names.append(tests[i].name) - config_file.set_value(section, 'tests', names) - - func _remap_path(source_path): - var to_return = source_path - if(!_utils.file_exists(source_path)): - _lgr.debug('Checking for remap for: ' + source_path) - var remap_path = source_path.get_basename() + '.gd.remap' - if(_utils.file_exists(remap_path)): - var cf = ConfigFile.new() - cf.load(remap_path) - to_return = cf.get_value('remap', 'path') - else: - _lgr.warn('Could not find remap file ' + remap_path) - return to_return - - func import_from(config_file, section): - path = config_file.get_value(section, 'path') - path = _remap_path(path) - var test_names = config_file.get_value(section, 'tests') - for i in range(test_names.size()): - var t = Test.new() - t.name = test_names[i] - tests.append(t) - # Null is an acceptable value, but you can't pass null as a default to - # get_value since it thinks you didn't send a default...then it spits - # out red text. This works around that. - var inner_name = config_file.get_value(section, 'inner_class', 'Placeholder') - if(inner_name != 'Placeholder'): - inner_class_name = inner_name - else: # just being explicit - inner_class_name = null - - -# ------------------------------------------------------------------------------ -# start test_collector, I don't think I like the name. -# ------------------------------------------------------------------------------ -var scripts = [] -var _test_prefix = 'test_' -var _test_class_prefix = 'Test' - -var _utils = load('res://addons/gut/utils.gd').new() -var _lgr = _utils.get_logger() - -func _parse_script(script): - var file = File.new() - var line = "" - var line_count = 0 - var inner_classes = [] - var scripts_found = [] - - file.open(script.path, 1) - while(!file.eof_reached()): - line_count += 1 - line = file.get_line() - #Add a test - if(line.begins_with("func " + _test_prefix)): - var from = line.find(_test_prefix) - var line_len = line.find("(") - from - var new_test = Test.new() - new_test.name = line.substr(from, line_len) - new_test.line_number = line_count - script.tests.append(new_test) - - if(line.begins_with('class ')): - var iclass_name = line.replace('class ', '') - iclass_name = iclass_name.replace(':', '') - if(iclass_name.begins_with(_test_class_prefix)): - inner_classes.append(iclass_name) - - scripts_found.append(script.path) - - for i in range(inner_classes.size()): - var ts = TestScript.new(_utils, _lgr) - ts.path = script.path - ts.inner_class_name = inner_classes[i] - if(_parse_inner_class_tests(ts)): - scripts.append(ts) - scripts_found.append(script.path + '[' + inner_classes[i] +']') - - file.close() - return scripts_found - -func _parse_inner_class_tests(script): - var inst = script.get_new() - - if(!inst is _utils.Test): - _lgr.warn('Ignoring ' + script.inner_class_name + ' because it starts with "' + _test_class_prefix + '" but does not extend addons/gut/test.gd') - return false - - var methods = inst.get_method_list() - for i in range(methods.size()): - var name = methods[i]['name'] - if(name.begins_with(_test_prefix) and methods[i]['flags'] == 65): - var t = Test.new() - t.name = name - script.tests.append(t) - - return true -# ----------------- -# Public -# ----------------- -func add_script(path): - # SHORTCIRCUIT - if(has_script(path)): - return [] - - var f = File.new() - # SHORTCIRCUIT - if(!f.file_exists(path)): - _lgr.error('Could not find script: ' + path) - return - - var ts = TestScript.new(_utils, _lgr) - ts.path = path - scripts.append(ts) - return _parse_script(ts) - -func to_s(): - var to_return = '' - for i in range(scripts.size()): - to_return += scripts[i].to_s() + "\n" - return to_return -func get_logger(): - return _lgr - -func set_logger(logger): - _lgr = logger - -func get_test_prefix(): - return _test_prefix - -func set_test_prefix(test_prefix): - _test_prefix = test_prefix - -func get_test_class_prefix(): - return _test_class_prefix - -func set_test_class_prefix(test_class_prefix): - _test_class_prefix = test_class_prefix - -func clear(): - scripts.clear() - -func has_script(path): - var found = false - var idx = 0 - while(idx < scripts.size() and !found): - if(scripts[idx].path == path): - found = true - else: - idx += 1 - return found - -func export_tests(path): - var success = true - var f = ConfigFile.new() - for i in range(scripts.size()): - scripts[i].export_to(f, str('TestScript-', i)) - var result = f.save(path) - if(result != OK): - _lgr.error(str('Could not save exported tests to [', path, ']. Error code: ', result)) - success = false - return success - -func import_tests(path): - var success = false - var f = ConfigFile.new() - var result = f.load(path) - if(result != OK): - _lgr.error(str('Could not load exported tests from [', path, ']. Error code: ', result)) - else: - var sections = f.get_sections() - for key in sections: - var ts = TestScript.new(_utils, _lgr) - ts.import_from(f, key) - scripts.append(ts) - success = true - return success diff --git a/addons/gut/thing_counter.gd b/addons/gut/thing_counter.gd deleted file mode 100644 index a9b0b48..0000000 --- a/addons/gut/thing_counter.gd +++ /dev/null @@ -1,43 +0,0 @@ -var things = {} - -func get_unique_count(): - return things.size() - -func add(thing): - if(things.has(thing)): - things[thing] += 1 - else: - things[thing] = 1 - -func has(thing): - return things.has(thing) - -func get(thing): - var to_return = 0 - if(things.has(thing)): - to_return = things[thing] - return to_return - -func sum(): - var count = 0 - for key in things: - count += things[key] - return count - -func to_s(): - var to_return = "" - for key in things: - to_return += str(key, ": ", things[key], "\n") - to_return += str("sum: ", sum()) - return to_return - -func get_max_count(): - var max_val = null - for key in things: - if(max_val == null or things[key] > max_val): - max_val = things[key] - return max_val - -func add_array_items(array): - for i in range(array.size()): - add(array[i]) diff --git a/addons/gut/utils.gd b/addons/gut/utils.gd deleted file mode 100644 index 7f44f26..0000000 --- a/addons/gut/utils.gd +++ /dev/null @@ -1,160 +0,0 @@ -var _Logger = load('res://addons/gut/logger.gd') # everything should use get_logger - -var Doubler = load('res://addons/gut/doubler.gd') -var Gut = load('res://addons/gut/gut.gd') -var HookScript = load('res://addons/gut/hook_script.gd') -var MethodMaker = load('res://addons/gut/method_maker.gd') -var Spy = load('res://addons/gut/spy.gd') -var Stubber = load('res://addons/gut/stubber.gd') -var StubParams = load('res://addons/gut/stub_params.gd') -var Summary = load('res://addons/gut/summary.gd') -var Test = load('res://addons/gut/test.gd') -var TestCollector = load('res://addons/gut/test_collector.gd') -var ThingCounter = load('res://addons/gut/thing_counter.gd') -var OneToMany = load('res://addons/gut/one_to_many.gd') - -const GUT_METADATA = '__gut_metadata_' - -enum DOUBLE_STRATEGY{ - FULL, - PARTIAL -} - -var escape = PoolByteArray([0x1b]).get_string_from_ascii() -var CMD_COLORS = { - RED = escape + '[31m', - YELLOW = escape + '[33m', - DEFAULT = escape + '[0m', - GREEN = escape + '[32m', - UNDERLINE = escape + '[4m', - BOLD = escape + '[1m' -} - -func colorize_word(source, word, c): - var new_word = c + word + CMD_COLORS.DEFAULT - return source.replace(word, new_word) - -func colorize_text(text): - var t = colorize_word(text, 'FAILED', CMD_COLORS.RED) - t = colorize_word(t, 'PASSED', CMD_COLORS.GREEN) - t = colorize_word(t, 'PENDING', CMD_COLORS.YELLOW) - t = colorize_word(t, '[ERROR]', CMD_COLORS.RED) - t = colorize_word(t, '[WARNING]', CMD_COLORS.YELLOW) - t = colorize_word(t, '[DEBUG]', CMD_COLORS.BOLD) - t = colorize_word(t, '[DEPRECATED]', CMD_COLORS.BOLD) - t = colorize_word(t, '[INFO]', CMD_COLORS.BOLD) - return t - - -var _file_checker = File.new() - -func is_version_30(): - var info = Engine.get_version_info() - return info.major == 3 and info.minor == 0 - -func is_version_31(): - var info = Engine.get_version_info() - return info.major == 3 and info.minor == 1 - -# ------------------------------------------------------------------------------ -# Everything should get a logger through this. -# -# Eventually I want to make this get a single instance of a logger but I'm not -# sure how to do that without everything having to be in the tree which I -# DO NOT want to to do. I'm thinking of writings some instance ids to a file -# and loading them in the _init for this. -# ------------------------------------------------------------------------------ -func get_logger(): - return _Logger.new() - -# ------------------------------------------------------------------------------ -# Returns an array created by splitting the string by the delimiter -# ------------------------------------------------------------------------------ -func split_string(to_split, delim): - var to_return = [] - - var loc = to_split.find(delim) - while(loc != -1): - to_return.append(to_split.substr(0, loc)) - to_split = to_split.substr(loc + 1, to_split.length() - loc) - loc = to_split.find(delim) - to_return.append(to_split) - return to_return - -# ------------------------------------------------------------------------------ -# Returns a string containing all the elements in the array separated by delim -# ------------------------------------------------------------------------------ -func join_array(a, delim): - var to_return = '' - for i in range(a.size()): - to_return += str(a[i]) - if(i != a.size() -1): - to_return += str(delim) - return to_return - -# ------------------------------------------------------------------------------ -# return if_null if value is null otherwise return value -# ------------------------------------------------------------------------------ -func nvl(value, if_null): - if(value == null): - return if_null - else: - return value - -# ------------------------------------------------------------------------------ -# returns true if the object has been freed, false if not -# -# From what i've read, the weakref approach should work. It seems to work most -# of the time but sometimes it does not catch it. The str comparison seems to -# fill in the gaps. I've not seen any errors after adding that check. -# ------------------------------------------------------------------------------ -func is_freed(obj): - var wr = weakref(obj) - return !(wr.get_ref() and str(obj) != '[Deleted Object]') - -func is_not_freed(obj): - return !is_freed(obj) - -func is_double(obj): - return obj.get(GUT_METADATA) != null - -func extract_property_from_array(source, property): - var to_return = [] - for i in (source.size()): - to_return.append(source[i].get(property)) - return to_return - -func file_exists(path): - return _file_checker.file_exists(path) - -func write_file(path, content): - var f = File.new() - f.open(path, f.WRITE) - f.store_string(content) - f.close() - -func is_null_or_empty(text): - return text == null or text == '' - -func get_native_class_name(thing): - var to_return = null - if(is_native_class(thing)): - to_return = thing.new().get_class() - return to_return - -func is_native_class(thing): - var it_is = false - if(typeof(thing) == TYPE_OBJECT): - it_is = str(thing).begins_with("[GDScriptNativeClass:") - return it_is - -# ------------------------------------------------------------------------------ -# ------------------------------------------------------------------------------ -func get_file_as_text(path): - var to_return = '' - var f = File.new() - var result = f.open(path, f.READ) - if(result == OK): - to_return = f.get_as_text() - f.close() - return to_return diff --git a/demo.gif b/demo.gif deleted file mode 100644 index eb0ffb1..0000000 Binary files a/demo.gif and /dev/null differ diff --git a/docker-compose.yml b/docker-compose.yml index 5707d3b..e2312e6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,24 +1,17 @@ version: "3.3" services: - tests: - image: barichello/godot-ci:3.2.2 - environment: - - RUN_FULL_CODEPOINT_TESTS=true - volumes: - - .:/src - command: godot --path /src -s addons/gut/gut_cmdln.gd build-archlinux: build: context: . dockerfile: ./dockerfiles/archlinux - command: bash /src/addons/godot_xterm_native/build.sh + command: bash /src/addons/godot_xterm/build.sh build-nixos: build: context: . dockerfile: ./dockerfiles/nixos - command: /src/addons/godot_xterm_native/build.sh + command: /src/addons/godot_xterm/build.sh build-ubuntu: build: context: . dockerfile: ./dockerfiles/ubuntu - command: bash /src/addons/godot_xterm_native/build.sh + command: bash /src/addons/godot_xterm/build.sh diff --git a/examples/asciicast/demo.cast b/examples/asciicast/demo.cast new file mode 100644 index 0000000..afba5c6 --- /dev/null +++ b/examples/asciicast/demo.cast @@ -0,0 +1,61 @@ +{"version": 2, "width": 86, "height": 29, "timestamp": 1589772748, "env": {"SHELL": "/run/current-system/sw/bin/bash", "TERM": "xterm"}} +[0.082961, "o", "> "] +[0.798002, "o", "e"] +[0.893414, "o", "c"] +[0.956255, "o", "h"] +[1.008677, "o", "o"] +[1.089472, "o", " "] +[1.189602, "o", "h"] +[1.266892, "o", "e"] +[1.347483, "o", "l"] +[1.46568, "o", "l"] +[1.541039, "o", "o"] +[1.726772, "o", "\r\n"] +[1.727475, "o", "hello\r\n> "] +[2.060109, "o", "#"] +[2.179668, "o", " "] +[2.471941, "o", "T"] +[2.652735, "o", "h"] +[2.746515, "o", "i"] +[2.810578, "o", "s"] +[2.921342, "o", " "] +[2.98886, "o", "i"] +[3.069095, "o", "s"] +[3.31728, "o", " "] +[3.399615, "o", "a"] +[3.513605, "o", " "] +[3.72609, "o", "d"] +[3.811197, "o", "e"] +[3.94649, "o", "m"] +[4.047162, "o", "o"] +[4.225042, "o", "\r\n"] +[4.225402, "o", "> "] +[4.935288, "o", "t"] +[5.163552, "o", "o"] +[5.323205, "o", "i"] +[5.46746, "o", "l"] +[5.561098, "o", "et "] +[6.064937, "o", "-"] +[6.41563, "o", "-"] +[6.60443, "o", "g"] +[6.666621, "o", "a"] +[6.768317, "o", "y"] +[6.848917, "o", " "] +[7.076406, "o", "H"] +[7.250067, "o", "E"] +[7.410878, "o", "L"] +[7.537016, "o", "L"] +[7.604155, "o", "O"] +[7.888992, "o", " "] +[8.193437, "o", "W"] +[8.365871, "o", "O"] +[8.454678, "o", "R"] +[8.525163, "o", "L"] +[8.60286, "o", "D"] +[8.873053, "o", "!"] +[9.216434, "o", "\r\n"] +[9.251462, "o", " \r\n \u001b[0;1;31;91mm\u001b[0m \u001b[0;1;36;96mm\u001b[0m \u001b[0;1;34;94mmm\u001b[0;1;35;95mmm\u001b[0;1;31;91mmm\u001b[0m \u001b[0;1;33;93mm\u001b[0m \u001b[0;1;35;95mm\u001b[0m \u001b[0;1;36;96mmm\u001b[0;1;34;94mmm\u001b[0m \u001b[0;1;36;96mm\u001b[0m \u001b[0;1;31;91mm\u001b[0m \u001b[0;1;33;93mm\u001b[0;1;32;92mmm\u001b[0;1;36;96mm\u001b[0m \u001b[0;1;34;94mm\u001b[0;1;35;95mmm\u001b[0;1;31;91mmm\u001b[0m \u001b[0;1;32;92mm\u001b[0m \u001b[0;1;35;95mm\u001b[0;1;31;91mmm\u001b[0;1;33;93mm\u001b[0m \r\n \u001b[0;1;33;93m#\u001b[0m \u001b[0;1;34;94m#\u001b[0m \u001b[0;1;35;95m#\u001b[0m \u001b[0;1;32;92m#\u001b[0m \u001b[0;1;31;91m#\u001b[0m \u001b[0;1;36;96mm\u001b[0;1;34;94m\"\u001b[0m \u001b[0;1;35;95m\"\u001b[0;1;31;91mm\u001b[0m \u001b[0;1;34;94m#\u001b[0m \u001b[0;1;35;95m#\u001b[0m \u001b[0;1;33;93m#\u001b[0m \u001b[0;1;32;92mm\"\u001b[0m \u001b[0;1;34;94m\"m\u001b[0m \u001b[0;1;35;95m#\u001b[0m \u001b[0;1;33;93m\"\u001b[0;1;32;92m#\u001b[0m \u001b[0;1;36;96m#\u001b[0m \u001b[0;1;31;91m#\u001b[0m \u001b[0;1;32;92m\"\u001b[0;1;36;96mm\u001b[0m\r\n \u001b[0;1;32;92m#\u001b[0;1;36;96mmm\u001b[0;1;34;94mmm\u001b[0;1;35;95m#\u001b[0m \u001b[0;1;31;91m#m\u001b[0;1;33;93mmm\u001b[0;1;32;92mmm\u001b[0m \u001b[0;1;36;96m#\u001b[0m \u001b[0;1;33;93m#\u001b[0m \u001b[0;1;34;94m#\u001b"] +[9.251901, "o", "[0m \u001b[0;1;33;93m#\u001b[0m \u001b[0;1;35;95m\"\u001b[0m \u001b[0;1;31;91m#\"\u001b[0;1;33;93m#\u001b[0m \u001b[0;1;32;92m#\u001b[0m \u001b[0;1;36;96m#\u001b[0m \u001b[0;1;35;95m#\u001b[0m \u001b[0;1;31;91m#\u001b[0;1;33;93mmm\u001b[0;1;32;92mmm\u001b[0;1;36;96m\"\u001b[0m \u001b[0;1;34;94m#\u001b[0m \u001b[0;1;33;93m#\u001b[0m \u001b[0;1;34;94m#\u001b[0m\r\n \u001b[0;1;36;96m#\u001b[0m \u001b[0;1;31;91m#\u001b[0m \u001b[0;1;33;93m#\u001b[0m \u001b[0;1;34;94m#\u001b[0m \u001b[0;1;32;92m#\u001b[0m \u001b[0;1;35;95m#\u001b[0m \u001b[0;1;32;92m#\u001b[0m \u001b[0;1;31;91m#\u001b[0;1;33;93m#\u001b[0m \u001b[0;1;32;92m##\u001b[0;1;36;96m\"\u001b[0m \u001b[0;1;34;94m#\u001b[0m \u001b[0;1;31;91m#\u001b[0m \u001b[0;1;33;93m#\u001b[0m \u001b[0;1;36;96m\"\u001b[0;1;34;94mm\u001b[0m \u001b[0;1;35;95m#\u001b[0m \u001b[0;1;32;92m#\u001b[0m \u001b[0;1;35;95m#\u001b[0m\r\n \u001b[0;1;34;94m#\u001b[0m \u001b[0;1;33;93m#\u001b[0m \u001b[0;1;32;92m#m\u001b[0;1;36;96mmm\u001b[0;1;34;94mmm\u001b[0m \u001b[0;1;35;95m#\u001b[0;1;31;91mmm\u001b[0;1;33;93mmm\u001b[0;1;32;92mm\u001b[0m \u001b[0;1;36;96m#m\u001b[0;1;34;94mmm\u001b[0;1;35;95mmm\u001b[0m \u001b[0;1;33;93m#m\u001b[0;1;32;92mm#\u001b[0m \u001b[0;1;33;93m#\u001b[0m \u001b[0;1;36;96m#\u001b[0m \u001b[0;1;35;95m#\u001b[0;1;31;91mmm\u001b[0;1;33;93m#\u001b[0m \u001b[0;1;32;92m#\u001b[0m \u001b[0;1;35;95m\"\u001b[0m \u001b[0;1;31;91m#m\u001b[0;1;33;93mmm\u001b[0;1"] +[9.251944, "o", ";32;92mmm\u001b[0m \u001b[0;1;36;96m#\u001b[0;1;34;94mmm\u001b[0;1;35;95mm\"\u001b[0m \r\n \r\n \r\n \r\n \u001b[0;1;36;96mm\u001b[0m \r\n \u001b[0;1;34;94m#\u001b[0m \r\n \u001b[0;1;35;95m#\u001b[0m \r\n \u001b[0;1;31;91m\"\u001b[0m \r\n \u001b[0;1;33;93m#\u001b[0m \r\n \r\n \r\n"] +[9.252259, "o", "> "] +[12.56287, "o", "exit\r\n"] diff --git a/examples/terminal/Terminal.tscn b/examples/terminal/Terminal.tscn index 71be21b..42e0583 100644 --- a/examples/terminal/Terminal.tscn +++ b/examples/terminal/Terminal.tscn @@ -1,8 +1,8 @@ [gd_scene load_steps=5 format=2] -[ext_resource path="res://addons/godot_xterm_native/terminal.gdns" type="Script" id=1] -[ext_resource path="res://addons/godot_xterm_native/themes/default.theme" type="Theme" id=2] -[ext_resource path="res://addons/godot_xterm_native/pseudoterminal.gdns" type="Script" id=3] +[ext_resource path="res://addons/godot_xterm/terminal.gdns" type="Script" id=1] +[ext_resource path="res://addons/godot_xterm/themes/default.theme" type="Theme" id=2] +[ext_resource path="res://addons/godot_xterm/pseudoterminal.gdns" type="Script" id=3] [ext_resource path="res://examples/terminal/container.gd" type="Script" id=4] [node name="Container" type="Container"] diff --git a/project.godot b/project.godot index a0bada7..0a0e2db 100644 --- a/project.godot +++ b/project.godot @@ -15,13 +15,12 @@ _global_script_class_icons={ [application] -config/name="Godot Xterm Native" -run/main_scene="res://examples/terminal/Terminal.tscn" +config/name="Godot Xterm" config/icon="res://icon.png" [editor_plugins] -enabled=PoolStringArray( "godot_xterm_native" ) +enabled=PoolStringArray( "godot_xterm" ) [rendering] diff --git a/scenes/demo.gd b/scenes/demo.gd deleted file mode 100644 index 3dbb928..0000000 --- a/scenes/demo.gd +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright (c) 2020 The GodotTerm authors. All rights reserved. -# License MIT -extends Control - - -signal data_received(data) - -# The user must have these programs installed for this to work. -const dependencies = PoolStringArray(['which', 'socat', 'bash']) -const host = '127.0.0.1' -const port = 7154 - -# Enable recording of all data send to the psuedoterminal master. -# This is useful if you want to record a session if you are trying -# to make a showcase of the terminal ;-) -export var record: bool = false -export(String) var record_file_path = '/tmp/godot-xterm-record.json' - -var socat_pid = -1 -var stream_peer = StreamPeerTCP.new() -var record_file - - -func _ready(): - # First check that dependencies are installed and in $PATH. - var exit_code = OS.execute("which", dependencies) - if exit_code != 0: - OS.alert("Make sure the following programs are installed and in your $PATH: " + \ - dependencies.join(", ") + ".", "Misssing Dependencies!") - else: - # Start socat. - socat_pid = OS.execute("socat", - ["-d", "-d", "tcp-l:%d,bind=%s,reuseaddr,fork" % [port, host], - "exec:bash,pty,setsid,stderr,login,ctty"], false) - - # Create a StreamPeerTCP to connect to socat. - var err = stream_peer.connect_to_host(host, port) - if err != OK: - OS.alert("Couldn't connect to socat on %s:%d" % [host, port], "Connection Failed!") - - var status = stream_peer.get_status() - var connected = stream_peer.is_connected_to_host() - - # Set the TERM environment variable, so that the correct escape sequences - # are sent to Terminal. By default this is set to dumb, which lacks support - # for even simple commands such as clear and reset. - stream_peer.put_data("export TERM=xterm\n".to_ascii()) - stream_peer.put_data("clear\n".to_ascii()) - - # Connect the Terminal and StreamPeer. - $Terminal.connect('output', self, 'send_data') - connect("data_received", $Terminal, "write") - - connect("resized", self, "_resize_terminal") - _resize_terminal() - - -func _resize_terminal(): - $Terminal.rect_size = OS.window_size - - -func send_data(data: PoolByteArray): - if record: - # Save the data and timestamp to a file - record_file.write() - stream_peer.put_data(data) - - -func _process(delta): - if stream_peer.get_status() == StreamPeerTCP.STATUS_CONNECTED: - var res = stream_peer.get_data(stream_peer.get_available_bytes()) - var error = res[0] - var data = res[1] - if error != OK: - OS.alert("Something went wrong with the TCP connection to socat.", - "Connection Error!") - elif not data.empty(): - emit_signal("data_received", data) - - -func _exit_tree(): - if record: - record_file.close() - if socat_pid != -1: - OS.execute("kill", ["-9", socat_pid], false) diff --git a/scenes/demo.tscn b/scenes/demo.tscn deleted file mode 100644 index ac1a8f4..0000000 --- a/scenes/demo.tscn +++ /dev/null @@ -1,55 +0,0 @@ -[gd_scene load_steps=7 format=2] - -[ext_resource path="res://scenes/demo.gd" type="Script" id=1] -[ext_resource path="res://addons/godot_xterm/terminal.gd" type="Script" id=2] -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.tres" type="DynamicFont" id=3] -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.tres" type="DynamicFont" id=4] -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.tres" type="DynamicFont" id=5] -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.tres" type="DynamicFont" id=6] - -[node name="Demo" type="Control"] -show_behind_parent = true -anchor_right = 1.0 -anchor_bottom = 1.0 -script = ExtResource( 1 ) -__meta__ = { -"_edit_use_anchors_": false -} - -[node name="Terminal" type="Control" parent="."] -anchor_right = 1.0 -anchor_bottom = 1.0 -rect_min_size = Vector2( 600, 400 ) -script = ExtResource( 2 ) -__meta__ = { -"_edit_use_anchors_": false -} -auto_resize = true -font_family = { -"bold": ExtResource( 6 ), -"bold_italic": ExtResource( 5 ), -"italic": ExtResource( 4 ), -"regular": ExtResource( 3 ) -} -line_height = 1.15 -colors = { -"black": Color( 0.180392, 0.203922, 0.211765, 1 ), -"blue": Color( 0.203922, 0.396078, 0.643137, 1 ), -"bright_black": Color( 0.333333, 0.341176, 0.32549, 1 ), -"bright_blue": Color( 0.447059, 0.623529, 0.811765, 1 ), -"bright_cyan": Color( 0.203922, 0.886275, 0.886275, 1 ), -"bright_green": Color( 0.541176, 0.886275, 0.203922, 1 ), -"bright_magenta": Color( 0.678431, 0.498039, 0.658824, 1 ), -"bright_red": Color( 0.937255, 0.160784, 0.160784, 1 ), -"bright_white": Color( 0.933333, 0.933333, 0.92549, 1 ), -"bright_yellow": Color( 0.988235, 0.913725, 0.309804, 1 ), -"cyan": Color( 0.0235294, 0.596078, 0.603922, 1 ), -"green": Color( 0.305882, 0.603922, 0.0235294, 1 ), -"magenta": Color( 0.458824, 0.313726, 0.482353, 1 ), -"red": Color( 0.8, 0, 0, 1 ), -"white": Color( 0.827451, 0.843137, 0.811765, 1 ), -"yellow": Color( 0.768627, 0.627451, 0, 1 ) -} -window_options = { -"set_win_lines": false -} diff --git a/scenes/showcase.tscn b/scenes/showcase.tscn deleted file mode 100644 index 14aa48e..0000000 --- a/scenes/showcase.tscn +++ /dev/null @@ -1,39 +0,0 @@ -[gd_scene load_steps=7 format=2] - -[ext_resource path="res://scenes/demo.gd" type="Script" id=1] -[ext_resource path="res://addons/godot_xterm/terminal.gd" type="Script" id=2] -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.tres" type="DynamicFont" id=3] -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_italic.tres" type="DynamicFont" id=4] -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold_italic.tres" type="DynamicFont" id=5] -[ext_resource path="res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.tres" type="DynamicFont" id=6] - -[node name="Demo" type="Control"] -anchor_right = 1.0 -anchor_bottom = 1.0 -script = ExtResource( 1 ) -__meta__ = { -"_edit_use_anchors_": false -} - -[node name="Terminal" type="Control" parent="."] -margin_left = 163.651 -margin_top = 68.7974 -margin_right = 763.651 -margin_bottom = 468.797 -rect_min_size = Vector2( 600, 400 ) -script = ExtResource( 2 ) -__meta__ = { -"_edit_use_anchors_": false -} -font_family = { -"bold": ExtResource( 6 ), -"bold_italic": ExtResource( 5 ), -"italic": ExtResource( 4 ), -"regular": ExtResource( 3 ) -} -colors = { -"black": Color( 0.121569, 0.00784314, 0.00784314, 1 ) -} -window_options = { - -} diff --git a/test/integration/test_terminal.gd b/test/integration/test_terminal.gd deleted file mode 100644 index 9eca2b1..0000000 --- a/test/integration/test_terminal.gd +++ /dev/null @@ -1,102 +0,0 @@ -# Copyright (c) 2020 The GodotXterm authors. All rights reserved. -# License MIT -extends "res://addons/gut/test.gd" - -const Parser = preload("res://addons/godot_xterm/parser/escape_sequence_parser.gd") -const Terminal = preload("res://addons/godot_xterm/terminal.gd") -const Decoder = preload("res://addons/godot_xterm/input/text_decoder.gd") -const Constants = preload("res://addons/godot_xterm/parser/constants.gd") - -const C0 = Constants.C0 -const C1 = Constants.C1 - -class TestBuffer: - var calls = [] - var printed = '' - - func handle_print(data, start, end): - var string = Decoder.utf32_to_string(data.slice(start, end - 1)) - calls.append(['print', string]) - printed += string - - - func handle_exec(): - calls.append(['exec']) - - - func handle_csi(params): - calls.append(['csi', params.to_array()]) - - - func clear(): - printed = '' - calls.resize(0) - - -var parser -var buffer -var decoder - - -func parse(parser, string): - var container = [] - container.resize(string.length()) - var length = decoder.decode(string.to_utf8(), container) - parser.parse(container, length) - - -func before_all(): - buffer = TestBuffer.new() - decoder = Decoder.Utf8ToUtf32.new() - - -func before_each(): - parser = Parser.new() - parser.set_print_handler(buffer, 'handle_print') - buffer.clear() - - -func test_prints_printables(): - var string = 'bash-4.4# ' - var data = string.to_utf8() - var length = decoder.decode(data, data) - parser.parse(data, length) - assert_eq(buffer.calls, [['print', 'bash-4.4# ']]) - assert_eq(buffer.printed, 'bash-4.4# ') - - -func skip_test_c0(): - for code in C0.values(): - parser.set_execute_handler(code, buffer, 'handle_exec') - parse(parser, char(code)) - if code == 0x0 or code == 0x1b or code == 0x20 or code == 0x7f: - assert_eq(buffer.calls, []) - else: - assert_eq(buffer.calls, [['exec']], 'code: 0x%x' % code) - assert_eq(buffer.printed, '') - parser.reset() - buffer.clear() - - -func skip_test_c1(): - for code in C1.values(): - parser.set_execute_handler(code, buffer, 'handle_exec') - parse(parser, char(code)) - assert_eq(buffer.calls, [['exec']], 'code: 0x%x' % code) - assert_eq(buffer.printed, '') - parser.reset() - buffer.clear() - - -func test_print_csi_print(): - parser.set_csi_handler({'final': 'g'}, buffer, 'handle_csi') - parse(parser, 'a\u001b[gb') - assert_eq(buffer.calls, [['print', 'a'],['csi', [0]], ['print', 'b']]) - assert_eq(buffer.printed, 'ab') - - -func test_csi_position_cursor(): - parser.set_csi_handler({'final': 'H'}, buffer, 'handle_csi') - parse(parser, '\u001b[1;5H') - assert_eq(buffer.calls, [['csi', [1, 5]]]) - assert_eq(buffer.printed, '') diff --git a/test/test.tscn b/test/test.tscn deleted file mode 100644 index fe35273..0000000 --- a/test/test.tscn +++ /dev/null @@ -1,17 +0,0 @@ -[gd_scene load_steps=2 format=2] - -[ext_resource path="res://addons/gut/gut.gd" type="Script" id=1] - -[node name="Gut" type="Control"] -self_modulate = Color( 1, 1, 1, 0 ) -margin_right = 1031.0 -margin_bottom = 597.0 -rect_min_size = Vector2( 740, 250 ) -script = ExtResource( 1 ) -__meta__ = { -"_edit_use_anchors_": false -} -_yield_between_tests = false -_include_subdirectories = true -_directory1 = "res://test" -_double_strategy = 1 diff --git a/test/test_utils.gd b/test/test_utils.gd deleted file mode 100644 index a43614c..0000000 --- a/test/test_utils.gd +++ /dev/null @@ -1,66 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends "res://addons/gut/test.gd" - - -const Buffer = preload("res://addons/godot_xterm/buffer/buffer.gd") -const BufferSet = preload("res://addons/godot_xterm/buffer/buffer_set.gd") -const OptionsService = preload("res://addons/godot_xterm/services/options_service.gd") - - -class MockBufferService: - extends Reference - - - signal resized(cols, rows) - - var service_brand - var buffer setget ,_get_buffer - var buffers - var is_user_scrolling: bool = false - var cols - var rows - - - func _get_buffer(): - return buffers.active - - - func _init(cols: int, rows: int, options_service = MockOptionsService.new()): - self.cols = cols - self.rows = rows - buffers = BufferSet.new(options_service, self) - - - func resize(cols: int, rows: int) -> void: - self.cols = cols - self.rows = rows - - - func reset() -> void: - pass - - -class MockOptionsService: - extends Reference - - - signal option_changed - - var service_brand - var options = OptionsService.TerminalOptions.new() - - - func _init(test_options = null): - if test_options: - for key in test_options.keys(): - self.options.set(key, test_options[key]) - - - func set_option(key: String, value) -> void: - pass - - - func get_option(key: String): - pass diff --git a/test/unit/.test_input_handler.gd.swp b/test/unit/.test_input_handler.gd.swp deleted file mode 100644 index edf7547..0000000 Binary files a/test/unit/.test_input_handler.gd.swp and /dev/null differ diff --git a/test/unit/buffer/test_buffer.gd b/test/unit/buffer/test_buffer.gd deleted file mode 100644 index 7871dd8..0000000 --- a/test/unit/buffer/test_buffer.gd +++ /dev/null @@ -1,362 +0,0 @@ -# Copyright (c) 2017 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends "res://addons/gut/test.gd" - - -const Buffer = preload("res://addons/godot_xterm/buffer/buffer.gd") -const CircularList = preload("res://addons/godot_xterm/circular_list.gd") -const CellData = preload("res://addons/godot_xterm/buffer/cell_data.gd") -const AttributeData = preload("res://addons/godot_xterm/buffer/attribute_data.gd") -const TestUtils = preload("res://test/test_utils.gd") - - -class BaseBufferTest: - extends "res://addons/gut/test.gd" - - - const INIT_COLS = 80 - const INIT_ROWS = 24 - const INIT_SCROLLBACK = 1000 - - var options_service - var buffer_service - var buffer - - - func before_each(): - options_service = TestUtils.MockOptionsService.new({'scrollback': INIT_SCROLLBACK}) - buffer_service = TestUtils.MockBufferService.new(INIT_COLS, INIT_ROWS) - buffer = Buffer.new(true, options_service, buffer_service) - - -class TestInit: - extends BaseBufferTest - - - func test_buffer_lines(): - assert_eq(buffer.lines.get_script(), CircularList) - assert_eq(buffer.lines.max_length, buffer_service.rows + INIT_SCROLLBACK) - - - func test_buffer_scroll_bottom(): - assert_eq(buffer.scroll_bottom, buffer_service.rows - 1) - - - func test_fill_viewport_rows(): - # It should fill the buffer with blank lines based on the size of the viewport - var blank_line_char = buffer.get_blank_line(AttributeData.new()).load_cell(0, CellData.new()).get_as_char_data() - buffer.fill_viewport_rows() - assert_eq(buffer.lines.length, INIT_ROWS) - for y in range(INIT_ROWS): - assert_eq(buffer.lines.get_el(y).length, INIT_COLS) - for x in range(INIT_COLS): - assert_eq(buffer.lines.get_el(y).load_cell(x, CellData.new()).get_as_char_data(), blank_line_char) - - -class TestGetWrappedRangeForLine: - extends BaseBufferTest - - - func before_each(): - .before_each() - buffer.fill_viewport_rows() - - - func test_non_wrapped_returns_a_single_row_for_the_first_row(): - assert_eq(buffer.get_wrapped_range_for_line(0).first, 0) - assert_eq(buffer.get_wrapped_range_for_line(0).last, 0) - - - func test_non_wrapped_returns_a_single_row_for_a_middle_row(): - assert_eq(buffer.get_wrapped_range_for_line(12).first, 12) - assert_eq(buffer.get_wrapped_range_for_line(12).last, 12) - - - func test_non_wrapped_returns_a_single_row_for_the_last_row(): - assert_eq(buffer.get_wrapped_range_for_line(buffer.lines.length - 1).first, INIT_ROWS - 1) - assert_eq(buffer.get_wrapped_range_for_line(buffer.lines.length - 1).last, INIT_ROWS - 1) - - - func test_wrapped_returns_a_range_for_first_row(): - buffer.lines.get_el(1).is_wrapped = true - assert_eq(buffer.get_wrapped_range_for_line(0).first, 0) - assert_eq(buffer.get_wrapped_range_for_line(0).last, 1) - - - func test_wrapped_range_for_middle_row_wrapping_upwards(): - buffer.fill_viewport_rows() - buffer.lines.get_el(12).is_wrapped = true - assert_eq(buffer.get_wrapped_range_for_line(12).first, 11) - assert_eq(buffer.get_wrapped_range_for_line(12).last, 12) - - - func test_wrapped_range_for_middle_row_wrapping_downwards(): - buffer.lines.get_el(13).is_wrapped = true - assert_eq(buffer.get_wrapped_range_for_line(12).first, 12) - assert_eq(buffer.get_wrapped_range_for_line(12).last, 13) - - - func test_wrapped_range_for_middle_row_wrapping_both_ways(): - buffer.lines.get_el(11).is_wrapped = true - buffer.lines.get_el(12).is_wrapped = true - buffer.lines.get_el(13).is_wrapped = true - buffer.lines.get_el(14).is_wrapped = true - assert_eq(buffer.get_wrapped_range_for_line(12).first, 10) - assert_eq(buffer.get_wrapped_range_for_line(12).last, 14) - - - func test_wrapped_range_for_last_row(): - buffer.lines.get_el(INIT_ROWS - 1).is_wrapped = true - assert_eq(buffer.get_wrapped_range_for_line(buffer.lines.length - 1).first, INIT_ROWS - 2) - assert_eq(buffer.get_wrapped_range_for_line(buffer.lines.length - 1).last, INIT_ROWS - 1) - - - func test_wrapped_range_for_row_that_wraps_upward_to_first_row(): - buffer.lines.get_el(1).is_wrapped = true - assert_eq(buffer.get_wrapped_range_for_line(1).first, 0) - assert_eq(buffer.get_wrapped_range_for_line(1).last, 1) - - - func test_wrapped_range_for_row_that_wraps_downward_to_last_row(): - buffer.lines.get_el(buffer.lines.length - 1).is_wrapped = true - assert_eq(buffer.get_wrapped_range_for_line(buffer.lines.length - 2).first, INIT_ROWS - 2) - assert_eq(buffer.get_wrapped_range_for_line(buffer.lines.length - 2).last, INIT_ROWS - 1) - - -class TestResize: - extends BaseBufferTest - - - func before_each(): - .before_each() - buffer.fill_viewport_rows() - - - func test_column_size_reduction_trims_data_in_the_buffer(): - buffer.resize(INIT_COLS / 2, INIT_ROWS) - assert_eq(buffer.lines.length, INIT_ROWS) - for i in range(INIT_ROWS): - assert_eq(buffer.lines.get_line(i).length, INIT_COLS / 2) - - - func test_column_size_increase_adds_pad_columns(): - buffer.resize(INIT_COLS + 10, INIT_ROWS) - assert_eq(buffer.lines.length, INIT_ROWS) - for i in range(INIT_ROWS): - assert_eq(buffer.lines.get_line(i).length, INIT_COLS + 10) - - - func test_row_size_reduction_trims_blank_lines_from_the_end(): - buffer.resize(INIT_COLS, INIT_ROWS - 10) - assert_eq(buffer.lines.length, INIT_ROWS - 10) - - - func test_row_size_reduction_moves_viewport_down_when_it_is_at_the_end(): - # Set cursor y to have 5 blank lines below it - buffer.y = INIT_ROWS - 5 - 1 - buffer.resize(INIT_COLS, INIT_ROWS - 10) - # Trim 5 rows - assert_eq(buffer.lines.length, INIT_ROWS - 5) - # Shift the viewport down 5 rows - assert_eq(buffer.ydisp, 5) - assert_eq(buffer.ybase, 5) - - - func test_no_scrollback_trims_from_the_top_of_the_buffer_when_the_cursor_reaches_the_bottom(): - buffer = Buffer.new(true, TestUtils.MockOptionsService.new({"scrollback": 0}), buffer_service) - assert_eq(buffer.lines.max_length, INIT_ROWS) - buffer.y = INIT_ROWS - 1 - buffer.fill_viewport_rows() - var ch_data = buffer.lines.get_line(5).load_cell(0, CellData.new()).get_as_char_data() - ch_data[1] = "a" - buffer.lines.get_line(5).set_cell(0, CellData.from_char_data(ch_data)) - ch_data = buffer.lines.get_line(INIT_ROWS - 1).load_cell(0, CellData.new()).get_as_char_data() - ch_data[1] = "b" - buffer.lines.get_line(INIT_ROWS - 1).set_cell(0, CellData.from_char_data(ch_data)) - buffer.resize(INIT_COLS, INIT_ROWS - 5) - assert_eq(buffer.lines.get_line(0).load_cell(0, CellData.new()).get_as_char_data()[1], "a") - assert_eq(buffer.lines.get_line(INIT_ROWS - 1 - 5).load_cell(0, CellData.new()).get_as_char_data()[1], "b") - - - func test_row_size_increase_adds_blank_lines_to_empty_buffer(): - assert_eq(buffer.ydisp, 0) - buffer.resize(INIT_COLS, INIT_ROWS + 10) - assert_eq(buffer.ydisp, 0) - assert_eq(buffer.lines.length, INIT_ROWS + 10) - - func test_row_size_increase_shows_more_of_the_buffer_above(): - # Create 10 extra blank lines - for i in range(10): - buffer.lines.push(buffer.get_blank_line(AttributeData.new())) - # Set cursor to the bottom of the buffer - buffer.y = INIT_ROWS - 1 - # Scroll down 10 lines - buffer.ybase = 10 - buffer.ydisp = 10 - assert_eq(buffer.lines.length, INIT_ROWS + 10) - buffer.resize(INIT_COLS, INIT_ROWS + 5) - # Should be 5 more lines - assert_eq(buffer.ydisp, 5) - assert_eq(buffer.ybase, 5) - # Should not trim the buffer - assert_eq(buffer.lines.length, INIT_ROWS + 10) - - - func test_row_size_increase_shows_more_of_the_buffer_below_when_the_viewort_is_at_the_top_of_the_buffer(): - # Create 10 extra blank lines - for i in range(10): - buffer.lines.push(buffer.get_blank_line(AttributeData.new())) - # Set cursor to the bottom of the buffer - buffer.y = INIT_ROWS - 1 - # Scroll down 10 lines - buffer.ybase = 10 - buffer.ydisp = 0 - assert_eq(buffer.lines.length, INIT_ROWS + 10) - buffer.resize(INIT_COLS, INIT_ROWS + 5) - # The viewport should remain at the top - assert_eq(buffer.ydisp, 0) - # The buffer ybase should move up 5 lines - assert_eq(buffer.ybase, 5) - # Should not trim the buffer - assert_eq(buffer.lines.length, INIT_ROWS + 10) - - - func test_row_and_column_increase_resizes_properly(): - buffer.resize(INIT_COLS + 5, INIT_ROWS + 5) - assert_eq(buffer.lines.length, INIT_ROWS + 5) - buffer.resize(INIT_COLS - 5, INIT_ROWS) - assert_eq(buffer.lines.length, INIT_ROWS) - - - func test_reflow_does_not_wrap_empty_lines(): - assert_eq(buffer.lines.length, INIT_ROWS) - buffer.resize(INIT_COLS - 5, INIT_ROWS) - assert_eq(buffer.lines.length, INIT_ROWS) - - - func test_reflow_shrinks_row_length(): - buffer.resize(5, 10) - assert_eq(buffer.lines.length, 10) - for i in range(10): - assert_eq(buffer.lines.get_line(i).length, 5) - - - func test_reflow_wraps_and_unwraps_lines(): - buffer.resize(5, 10) - var first_line = buffer.lines.get_line(0) - for i in range(5): - var code = "a".ord_at(0) + i - var ch = char(code) - first_line.set_cell(i, CellData.from_char_data([0, ch, 1, code])) - buffer.y = 1 - assert_eq(buffer.lines.get_line(0).length, 5) - assert_eq(buffer.lines.get_line(0).translate_to_string(), "abcde") - buffer.resize(1, 10) - assert_eq(buffer.lines.length, 10) - assert_eq(buffer.lines.get_line(0).translate_to_string(), "a") - assert_eq(buffer.lines.get_line(1).translate_to_string(), "b") - assert_eq(buffer.lines.get_line(2).translate_to_string(), "c") - assert_eq(buffer.lines.get_line(3).translate_to_string(), "d") - assert_eq(buffer.lines.get_line(4).translate_to_string(), "e") - assert_eq(buffer.lines.get_line(5).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(6).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(7).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(8).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(9).translate_to_string(), " ") - buffer.resize(5, 10) - assert_eq(buffer.lines.length, 10) - assert_eq(buffer.lines.get_line(0).translate_to_string(), "abcde") - assert_eq(buffer.lines.get_line(1).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(2).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(3).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(4).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(5).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(6).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(7).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(8).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(9).translate_to_string(), " ") - - - func test_discards_parts_of_wrapped_lines_that_go_out_of_the_scrollback(): - options_service.options.scrollback = 1 - buffer.resize(10, 5) - var last_line = buffer.lines.get_line(3) - for i in range(10): - var code = "a".ord_at(0) + i - var ch = char(code) - last_line.set_cell(i, CellData.from_char_data([0, ch, 1, code])) - assert_eq(buffer.lines.length, 5) - buffer.y = 4 - buffer.resize(2, 5) - assert_eq(buffer.y, 4) - assert_eq(buffer.ybase, 1) - assert_eq(buffer.lines.get_line(0).translate_to_string(), "ab") - assert_eq(buffer.lines.get_line(1).translate_to_string(), "cd") - assert_eq(buffer.lines.get_line(2).translate_to_string(), "ef") - assert_eq(buffer.lines.get_line(3).translate_to_string(), "gh") - assert_eq(buffer.lines.get_line(4).translate_to_string(), "ij") - assert_eq(buffer.lines.get_line(5).translate_to_string(), " ") - buffer.resize(1, 5) - assert_eq(buffer.y, 4) - assert_eq(buffer.ybase, 1) - assert_eq(buffer.lines.length, 6) - assert_eq(buffer.lines.get_line(0).translate_to_string(), "f") - assert_eq(buffer.lines.get_line(1).translate_to_string(), "g") - assert_eq(buffer.lines.get_line(2).translate_to_string(), "h") - assert_eq(buffer.lines.get_line(3).translate_to_string(), "i") - assert_eq(buffer.lines.get_line(4).translate_to_string(), "j") - assert_eq(buffer.lines.get_line(5).translate_to_string(), " ") - buffer.resize(10, 5) - assert_eq(buffer.y, 1) - assert_eq(buffer.ybase, 0) - assert_eq(buffer.lines.length, 5) - assert_eq(buffer.lines.get_line(0).translate_to_string(), "fghij ") - assert_eq(buffer.lines.get_line(1).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(2).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(3).translate_to_string(), " ") - assert_eq(buffer.lines.get_line(4).translate_to_string(), " ") - - - func test_removes_the_correct_amount_of_rows_when_reflowing_larger(): - # This is a regression test to ensure that successive wrapped lines that are getting - # 3+ lines removed on a reflow actually remove the right lines - buffer.resize(10, 10) - buffer.y = 2 - var first_line = buffer.lines.get_line(0) - var second_line = buffer.lines.get_line(1) - for i in range(10): - var code = "a".ord_at(0) + i - var ch = char(code) - first_line.set_cell(i, CellData.from_char_data([0, ch, 1, code])) - for i in range(10): - var code = "0".ord_at(0) + i - var ch = char(code) - second_line.set_cell(i, CellData.from_char_data([0, ch, 1, code])) - assert_eq(buffer.lines.length, 10) - assert_eq(buffer.lines.get_line(0).translate_to_string(), "abcdefghij") - assert_eq(buffer.lines.get_line(1).translate_to_string(), "0123456789") - for i in range(2, 10): - assert_eq(buffer.lines.get_line(i).translate_to_string(), " ") - buffer.resize(2, 10) - assert_eq(buffer.ybase, 1) - assert_eq(buffer.lines.length, 11) - assert_eq(buffer.lines.get_line(0).translate_to_string(), "ab") - assert_eq(buffer.lines.get_line(1).translate_to_string(), "cd") - assert_eq(buffer.lines.get_line(2).translate_to_string(), "ef") - assert_eq(buffer.lines.get_line(3).translate_to_string(), "gh") - assert_eq(buffer.lines.get_line(4).translate_to_string(), "ij") - assert_eq(buffer.lines.get_line(5).translate_to_string(), "01") - assert_eq(buffer.lines.get_line(6).translate_to_string(), "23") - assert_eq(buffer.lines.get_line(7).translate_to_string(), "45") - assert_eq(buffer.lines.get_line(8).translate_to_string(), "67") - assert_eq(buffer.lines.get_line(9).translate_to_string(), "89") - assert_eq(buffer.lines.get_line(10).translate_to_string(), " ") - buffer.resize(10, 10) - assert_eq(buffer.ybase, 0) - assert_eq(buffer.lines.length, 10) - assert_eq(buffer.lines.get_line(0).translate_to_string(), "abcdefghij") - assert_eq(buffer.lines.get_line(1).translate_to_string(), "0123456789") - for i in range(2, 10): - assert_eq(buffer.lines.get_line(i).translate_to_string(), " ", - "line %d is incorrect" % i) diff --git a/test/unit/buffer/test_buffer_line.gd b/test/unit/buffer/test_buffer_line.gd deleted file mode 100644 index 4807ba8..0000000 --- a/test/unit/buffer/test_buffer_line.gd +++ /dev/null @@ -1,436 +0,0 @@ -# Copyright (c) 2018 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends "res://addons/gut/test.gd" - - -const BufferLine = preload("res://addons/godot_xterm/buffer/buffer_line.gd") -const AttributeData = preload("res://addons/godot_xterm/buffer/attribute_data.gd") -const CellData = preload("res://addons/godot_xterm/buffer/cell_data.gd") -const Decoder = preload("res://addons/godot_xterm/input/text_decoder.gd") -const Constants = preload("res://addons/godot_xterm/buffer/constants.gd") - -const BgFlags = Constants.BgFlags -const Attributes = Constants.Attributes -const UnderlineStyle = Constants.UnderlineStyle -const FgFlags = Constants.FgFlags -const Content = Constants.Content - - -class BufferLineTest: - extends BufferLine - - - func _init(cols: int, fill_cell_data = null, is_wrapped: bool = false).(cols, fill_cell_data, is_wrapped): - pass - - - func to_array(): - var result = [] - for i in range(length): - result.append(load_cell(i, CellData.new()).get_as_char_data()) - return result - - -class TestAttributeData: - extends "res://addons/gut/test.gd" - - - var attrs - - - func before_each(): - attrs = AttributeData.new() - - - func test_has_extended_attrs(): - assert_eq(attrs.has_extended_attrs() as bool, false) - attrs.bg |= BgFlags.HAS_EXTENDED - assert_eq(attrs.has_extended_attrs() as bool, true) - - - func test_get_underline_color_P256(): - # set a P256 color - attrs.extended.underline_color = Attributes.CM_P256 | 45 - - # should use FG color if BgFlags.HAS_EXTENDED is not set - assert_eq(attrs.get_underline_color(), -1) - - # should use underline_color is BgFlags.HAS_EXTENDED is set and underline_color holds a value - attrs.bg |= BgFlags.HAS_EXTENDED - assert_eq(attrs.get_underline_color(), 45) - - # should use FG color if underline_color holds no value - attrs.extended.underline_color = -1 - attrs.fg |= Attributes.CM_P256 | 123 - assert_eq(attrs.get_underline_color(), 123) - - - func test_get_underline_color_RGB(): - # set a P256 color - attrs.extended.underline_color = Attributes.CM_RGB | (1 << 16) | (2 << 8) | 3 - - # should use FG color if BgFlags.HAS_EXTENDED is not set - assert_eq(attrs.get_underline_color(), -1) - - # should use underline_color if BgFlags.HAS_EXTENDED is set and underline_color holds a value - attrs.bg |= BgFlags.HAS_EXTENDED - assert_eq(attrs.get_underline_color(), (1 << 16) | (2 << 8) | 3) - - # should use FG color if underline_color holds no value - attrs.extended.underline_color = -1 - attrs.fg |= Attributes.CM_P256 | 123 - assert_eq(attrs.get_underline_color(), 123) - - - func test_underline_attrs(): - # should always return color mode of fg - for mode in [Attributes.CM_DEFAULT, Attributes.CM_P16, Attributes.CM_P256, Attributes.CM_RGB]: - attrs.extended.underline_color = mode - assert_eq(attrs.get_underline_color_mode(), attrs.get_fg_color_mode()) - assert_eq(attrs.is_underline_color_default(), true) - - attrs.fg = Attributes.CM_RGB - - for mode in [Attributes.CM_DEFAULT, Attributes.CM_P16, Attributes.CM_P256, Attributes.CM_RGB]: - attrs.extended.underline_color = mode - assert_eq(attrs.get_underline_color_mode(), attrs.get_fg_color_mode()) - assert_eq(attrs.is_underline_color_default(), false) - assert_eq(attrs.is_underline_color_rgb(), true) - - # should return own mode - attrs.bg |= BgFlags.HAS_EXTENDED - attrs.extended.underline_color = Attributes.CM_DEFAULT - assert_eq(attrs.get_underline_color_mode(), Attributes.CM_DEFAULT) - attrs.extended.underline_color = Attributes.CM_P16 - assert_eq(attrs.get_underline_color_mode(), Attributes.CM_P16) - assert_eq(attrs.is_underline_color_palette(), true) - attrs.extended.underline_color = Attributes.CM_P256 - assert_eq(attrs.get_underline_color_mode(), Attributes.CM_P256) - assert_eq(attrs.is_underline_color_palette(), true) - attrs.extended.underline_color = Attributes.CM_RGB - assert_eq(attrs.get_underline_color_mode(), Attributes.CM_RGB) - assert_eq(attrs.is_underline_color_rgb(), true) - - - func test_get_underline_style(): - # defaults to no underline style - assert_eq(attrs.get_underline_style(), UnderlineStyle.NONE) - - # should return NONE if UNDERLINE is not set - attrs.extended.underline_style = UnderlineStyle.CURLY - assert_eq(attrs.get_underline_style(), UnderlineStyle.NONE) - - # should return SINGLE style if UNDERLINE is set and HAS_EXTENDED is false - attrs.fg |= FgFlags.UNDERLINE - assert_eq(attrs.get_underline_style(), UnderlineStyle.SINGLE) - - # shoud return correct style if both is set - attrs.bg |= BgFlags.HAS_EXTENDED - assert_eq(attrs.get_underline_style(), UnderlineStyle.CURLY) - - # should return NONE if UNDERLINE is not set, but HAS_EXTENDED is true - attrs.fg &= ~FgFlags.UNDERLINE - assert_eq(attrs.get_underline_style(), UnderlineStyle.NONE) - - -class TestCellData: - extends "res://addons/gut/test.gd" - - - var cell - var decoder = Decoder.Utf8ToUtf32.new() - - - func before_each(): - cell = CellData.new() - - - func test_char_data_cell_data_equality(): - # ASCII - cell.set_from_char_data([123, 'a', 1, 'a'.ord_at(0)]) - assert_eq(cell.get_as_char_data(), [123, 'a', 1, 'a'.ord_at(0)]) - assert_eq(cell.is_combined(), 0) - # combining - cell.set_from_char_data([123, 'e\u0301', 1, '\u0301'.ord_at(0)]) - assert_eq(cell.get_as_char_data(), [123, 'e\u0301', 1, '\u0301'.ord_at(0)]) - assert_eq(cell.is_combined(), Content.IS_COMBINED_MASK) - # surrogate - cell.set_from_char_data([123, '𝄞', 1, 0x1D11E]) - assert_eq(cell.get_as_char_data(), [123, '𝄞', 1, 0x1D11E]) - assert_eq(cell.is_combined(), 0) - # surrogate + combining - cell.set_from_char_data([123, '𓂀\u0301', 1, '𓂀\u0301'.ord_at(1)]) - assert_eq(cell.get_as_char_data(), [123, '𓂀\u0301', 1, '𓂀\u0301'.ord_at(1)]) - assert_eq(cell.is_combined(), Content.IS_COMBINED_MASK) - # wide char - cell.set_from_char_data([123, '1', 2, '1'.ord_at(0)]) - assert_eq(cell.get_as_char_data(), [123, '1', 2, '1'.ord_at(0)]) - assert_eq(cell.is_combined(), 0) - - -class TestBufferLine: - extends "res://addons/gut/test.gd" - - - func test_ctor(): - var line = BufferLineTest.new(0) - assert_eq(line.length, 0) - assert_eq(line.is_wrapped, false) - line = BufferLineTest.new(10) - assert_eq(line.length, 10) - assert_eq(line.load_cell(0, CellData.new()).get_as_char_data(), - [0, Constants.NULL_CELL_CHAR, Constants.NULL_CELL_WIDTH, - Constants.NULL_CELL_CODE]) - assert_eq(line.is_wrapped, false) - line = BufferLineTest.new(10, null, true) - assert_eq(line.length, 10) - assert_eq(line.load_cell(0, CellData.new()).get_as_char_data(), - [0, Constants.NULL_CELL_CHAR, Constants.NULL_CELL_WIDTH, - Constants.NULL_CELL_CODE]) - assert_eq(line.is_wrapped, true) - var char_data = [123, 'a', 456, 'a'.ord_at(0)] - line = BufferLineTest.new(10, CellData.from_char_data(char_data), true) - assert_eq(line.length, 10) - assert_eq(line.load_cell(0, CellData.new()).get_as_char_data(), char_data) - assert_eq(line.is_wrapped, true) - - - func test_insert_cells() -> void: - var line = BufferLineTest.new(3) - line.set_cell(0, CellData.from_char_data([1, 'a', 0, 'a'.ord_at(0)])) - line.set_cell(1, CellData.from_char_data([2, 'b', 0, 'b'.ord_at(0)])) - line.set_cell(2, CellData.from_char_data([3, 'c', 0, 'c'.ord_at(0)])) - line.insert_cells(1, 3, CellData.from_char_data([4, 'd', 0, 'd'.ord_at(0)])) - assert_eq(line.to_array(), [ - [1, 'a', 0, 'a'.ord_at(0)], - [4, 'd', 0, 'd'.ord_at(0)], - [4, 'd', 0, 'd'.ord_at(0)] - ]) - - - func test_delete_cells() -> void: - var line = BufferLineTest.new(5) - line.set_cell(0, CellData.from_char_data([1, 'a', 0, 'a'.ord_at(0)])) - line.set_cell(1, CellData.from_char_data([2, 'b', 0, 'b'.ord_at(0)])) - line.set_cell(2, CellData.from_char_data([3, 'c', 0, 'c'.ord_at(0)])) - line.set_cell(3, CellData.from_char_data([4, 'd', 0, 'd'.ord_at(0)])) - line.set_cell(4, CellData.from_char_data([5, 'e', 0, 'e'.ord_at(0)])) - line.delete_cells(1, 2, CellData.from_char_data([6, 'f', 0, 'f'.ord_at(0)])) - assert_eq(line.to_array(), [ - [1, 'a', 0, 'a'.ord_at(0)], - [4, 'd', 0, 'd'.ord_at(0)], - [5, 'e', 0, 'e'.ord_at(0)], - [6, 'f', 0, 'f'.ord_at(0)], - [6, 'f', 0, 'f'.ord_at(0)] - ]) - - - func test_replace_cells(): - var line = BufferLineTest.new(5) - line.set_cell(0, CellData.from_char_data([1, 'a', 0, 'a'.ord_at(0)])) - line.set_cell(1, CellData.from_char_data([2, 'b', 0, 'b'.ord_at(0)])) - line.set_cell(2, CellData.from_char_data([3, 'c', 0, 'c'.ord_at(0)])) - line.set_cell(3, CellData.from_char_data([4, 'd', 0, 'd'.ord_at(0)])) - line.set_cell(4, CellData.from_char_data([5, 'e', 0, 'e'.ord_at(0)])) - line.replace_cells(2, 4, CellData.from_char_data([6, 'f', 0, 'f'.ord_at(0)])) - assert_eq(line.to_array(), [ - [1, 'a', 0, 'a'.ord_at(0)], - [2, 'b', 0, 'b'.ord_at(0)], - [6, 'f', 0, 'f'.ord_at(0)], - [6, 'f', 0, 'f'.ord_at(0)], - [5, 'e', 0, 'e'.ord_at(0)], - ]) - - - func test_copy_from(): - var line = BufferLineTest.new(5) - line.set_cell(0, CellData.from_char_data([1, 'a', 0, 'a'.ord_at(0)])) - line.set_cell(0, CellData.from_char_data([2, 'b', 0, 'b'.ord_at(0)])) - line.set_cell(0, CellData.from_char_data([3, 'c', 0, 'c'.ord_at(0)])) - line.set_cell(0, CellData.from_char_data([4, 'd', 0, 'd'.ord_at(0)])) - line.set_cell(0, CellData.from_char_data([5, 'e', 0, 'e'.ord_at(0)])) - var line2 = BufferLineTest.new(5, CellData.from_char_data([1, 'a', 0, 'a'.ord_at(0)]), true) - line2.copy_from(line) - assert_eq(line2.to_array(), line.to_array()) - assert_eq(line2.length, line.length) - assert_eq(line2.is_wrapped, line.is_wrapped) - - -class TestResize: - extends "res://addons/gut/test.gd" - - - var CHAR_DATA = [1, 'a', 0, 'a'.ord_at(0)] - var line - - func repeat(el, times: int) -> Array: - var result = [] - result.resize(times) - for i in range(times): - result[i] = el - return result - - - func test_enlarge(): - line = BufferLineTest.new(5, CellData.from_char_data(CHAR_DATA), false) - line.resize(10, CellData.from_char_data(CHAR_DATA)) - assert_eq(line.to_array(), repeat(CHAR_DATA, 10)) - - - func test_shrink(): - line = BufferLineTest.new(10, CellData.from_char_data(CHAR_DATA), false) - line.resize(5, CellData.from_char_data(CHAR_DATA)) - assert_eq(line.to_array(), repeat(CHAR_DATA, 5)) - - - func test_shrink_to_0_length(): - line = BufferLineTest.new(10, CellData.from_char_data(CHAR_DATA), false) - line.resize(0, CellData.from_char_data(CHAR_DATA)) - assert_eq(line.to_array(), repeat(CHAR_DATA, 0)) - - func shrink_then_enlarge(): - line = BufferLineTest.new(10, CellData.from_char_data(CHAR_DATA), false); - line.set_cell(2, CellData.from_char_data([0, '😁', 1, '😁'.ord_at(0)])) - line.set_cell(9, CellData.from_char_data([0, '😁', 1, '😁'.ord_at(0)])) - assert_eq(line.translate_to_string(), 'aa😁aaaaaa😁') - line.resize(5, CellData.from_char_data(CHAR_DATA)) - assert_eq(line.translate_to_string(), 'aa😁aa') - line.resize(10, CellData.from_char_data(CHAR_DATA)) - assert_eq(line.translate_to_string(), 'aa😁aaaaaaa') - - -class TestTrimLength: - extends "res://addons/gut/test.gd" - - - var line - - - func before_each(): - line = BufferLineTest.new(3, CellData.from_char_data([Constants.DEFAULT_ATTR, - Constants.NULL_CELL_CHAR, Constants.NULL_CELL_WIDTH, Constants.NULL_CELL_CODE])) - - - func test_empty_line(): - assert_eq(line.get_trimmed_length(), 0) - - - func test_ascii(): - line.set_cell(0, CellData.from_char_data([1, "a", 1, "a".ord_at(0)])) - line.set_cell(2, CellData.from_char_data([1, "a", 1, "a".ord_at(0)])) - assert_eq(line.get_trimmed_length(), 3) - - - func test_unicode(): - line.set_cell(0, CellData.from_char_data([1, "\u1f914", 1, "\u1f914".ord_at(0)])) - line.set_cell(2, CellData.from_char_data([1, "\u1f914", 1, "\u1f914".ord_at(0)])) - assert_eq(line.get_trimmed_length(), 3) - - - func test_one_cell(): - line.set_cell(0, CellData.from_char_data([1, "a", 1, "a".ord_at(0)])) - assert_eq(line.get_trimmed_length(), 1) - - -class TestAddCharToCell: - extends "res://addons/gut/test.gd" - - - var line - var cell - - - func before_each(): - line = BufferLineTest.new(3, CellData.from_char_data([Constants.DEFAULT_ATTR, - Constants.NULL_CELL_CHAR, Constants.NULL_CELL_WIDTH, Constants.NULL_CELL_CODE])) - cell = line.load_cell(0, CellData.new()) - - - func test_sets_width_to_1_for_empty_cell(): - line.add_codepoint_to_cell(0, "\u0301".ord_at(0)) - cell = line.load_cell(0, CellData.new()) - # chars contains single combining char - # width is set to 1 - assert_eq(cell.get_as_char_data(), [Constants.DEFAULT_ATTR, '\u0301', 1, 0x0301]) - # do not account a single combining char as combined - assert_eq(cell.is_combined(), 0) - - - func test_add_char_to_combining_string_in_cell(): - cell.set_from_char_data([123, "e\u0301", 1, "e\u0301".ord_at(1)]) - line.set_cell(0, cell) - line.add_codepoint_to_cell(0, "\u0301".ord_at(0)) - line.load_cell(0, cell) - # char contains 3 chars - # width is set to 1 - assert_eq(cell.get_as_char_data(), [123, "e\u0301\u0301", 1, 0x0301]) - # do not account a single combining char as combined - assert_eq(cell.is_combined(), Content.IS_COMBINED_MASK) - - - func test_create_combining_string_on_taken_cell(): - cell.set_from_char_data([123, "e", 1, "e".ord_at(1)]) - line.set_cell(0, cell) - line.add_codepoint_to_cell(0, "\u0301".ord_at(0)) - line.load_cell(0, cell) - # chars contains 2 chars - # width is set to 1 - assert_eq(cell.get_as_char_data(), [123, "e\u0301", 1, 0x0301]) - # do not account a single combining char as combined - assert_eq(cell.is_combined(), Content.IS_COMBINED_MASK) - - -class TestTranslateToString: - extends "res://addons/gut/test.gd" - - - var line - - - func before_each(): - line = BufferLineTest.new(10, CellData.from_char_data([Constants.DEFAULT_ATTR, - Constants.NULL_CELL_CHAR, Constants.NULL_CELL_WIDTH, Constants.NULL_CELL_CODE]), false) - - - func test_empty_line(): - assert_eq(line.translate_to_string(false), ' ') - assert_eq(line.translate_to_string(true), '') - - - func test_ASCII(): - line.set_cell(0, CellData.from_char_data([1, 'a', 1, 'a'.ord_at(0)])) - line.set_cell(2, CellData.from_char_data([1, 'a', 1, 'a'.ord_at(0)])) - line.set_cell(4, CellData.from_char_data([1, 'a', 1, 'a'.ord_at(0)])) - line.set_cell(5, CellData.from_char_data([1, 'a', 1, 'a'.ord_at(0)])) - assert_eq(line.translate_to_string(false), 'a a aa ') - assert_eq(line.translate_to_string(true), 'a a aa') - assert_eq(line.translate_to_string(false, 0, 5), 'a a a') - assert_eq(line.translate_to_string(false, 0, 4), 'a a ') - assert_eq(line.translate_to_string(false, 0, 3), 'a a') - assert_eq(line.translate_to_string(true, 0, 5), 'a a a') - assert_eq(line.translate_to_string(true, 0, 4), 'a a ') - assert_eq(line.translate_to_string(true, 0, 3), 'a a') - - - func test_space_at_end(): - line.set_cell(0, CellData.from_char_data([1, 'a', 1, 'a'.ord_at(0)])) - line.set_cell(2, CellData.from_char_data([1, 'a', 1, 'a'.ord_at(0)])) - line.set_cell(4, CellData.from_char_data([1, 'a', 1, 'a'.ord_at(0)])) - line.set_cell(5, CellData.from_char_data([1, 'a', 1, 'a'.ord_at(0)])) - line.set_cell(6, CellData.from_char_data([1, ' ', 1, ' '.ord_at(0)])) - assert_eq(line.translate_to_string(false), 'a a aa ') - assert_eq(line.translate_to_string(true), 'a a aa ') - - - func test_always_returns_some_sane_value(): - # sanity check - broken line with invalid out of bound null width cells - # this can atm happen with deleting/inserting chars in inputhandler by "breaking" - # fullwidth pairs --> needs to be fixed after settling BufferLine impl - assert_eq(line.translate_to_string(false), ' ') - assert_eq(line.translate_to_string(true), '') - - - func test_works_with_end_col_0(): - line.set_cell(0, CellData.from_char_data([1, 'a', 1, 'a'.ord_at(0)])) - assert_eq(line.translate_to_string(true, 0, 0), '') diff --git a/test/unit/input/test_text_decoder.gd b/test/unit/input/test_text_decoder.gd deleted file mode 100644 index 65b5686..0000000 --- a/test/unit/input/test_text_decoder.gd +++ /dev/null @@ -1,113 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends 'res://addons/gut/test.gd' - -const Decoder = preload("res://addons/godot_xterm/input/text_decoder.gd") - -# Note: There might be some invisible characters (such as emoji) depending -# on your editor and font settings. -const TEST_STRINGS = [ - "Лорем ипсум долор сит амет, ех сеа аццусам диссентиет. Ан еос стет еирмод витуперата. Иус дицерет урбанитас ет. Ан при алтера долорес сплендиде, цу яуо интегре денияуе, игнота волуптариа инструцтиор цу вим.", - "ლორემ იფსუმ დოლორ სით ამეთ, ფაცერ მუციუს ცონსეთეთურ ყუო იდ, ფერ ვივენდუმ ყუაერენდუმ ეა, ესთ ამეთ მოვეთ სუავითათე ცუ. ვითაე სენსიბუს ან ვიხ. ეხერცი დეთერრუისსეთ უთ ყუი. ვოცენთ დებითის ადიფისცი ეთ ფერ. ნეც ან ფეუგაით ფორენსიბუს ინთერესსეთ. იდ დიცო რიდენს იუს. დისსენთიეთ ცონსეყუუნთურ სედ ნე, ნოვუმ მუნერე ეუმ ათ, ნე ეუმ ნიჰილ ირაცუნდია ურბანითას.", - "अधिकांश अमितकुमार प्रोत्साहित मुख्य जाने प्रसारन विश्लेषण विश्व दारी अनुवादक अधिकांश नवंबर विषय गटकउसि गोपनीयता विकास जनित परस्पर गटकउसि अन्तरराष्ट्रीयकरन होसके मानव पुर्णता कम्प्युटर यन्त्रालय प्रति साधन", - "覧六子当聞社計文護行情投身斗来。増落世的況上席備界先関権能万。本物挙歯乳全事携供板栃果以。頭月患端撤競見界記引去法条公泊候。決海備駆取品目芸方用朝示上用報。講申務紙約週堂出応理田流団幸稿。起保帯吉対阜庭支肯豪彰属本躍。量抑熊事府募動極都掲仮読岸。自続工就断庫指北速配鳴約事新住米信中験。婚浜袋著金市生交保他取情距。", - "八メル務問へふらく博辞説いわょ読全タヨムケ東校どっ知壁テケ禁去フミ人過を装5階がねぜ法逆はじ端40落ミ予竹マヘナセ任1悪た。省ぜりせ製暇ょへそけ風井イ劣手はぼまず郵富法く作断タオイ取座ゅょが出作ホシ月給26島ツチ皇面ユトクイ暮犯リワナヤ断連こうでつ蔭柔薄とレにの。演めけふぱ損田転10得観びトげぎ王物鉄夜がまけ理惜くち牡提づ車惑参ヘカユモ長臓超漫ぼドかわ。", - "모든 국민은 행위시의 법률에 의하여 범죄를 구성하지 아니하는 행위로 소추되지 아니하며. 전직대통령의 신분과 예우에 관하여는 법률로 정한다, 국회는 헌법 또는 법률에 특별한 규정이 없는 한 재적의원 과반수의 출석과 출석의원 과반수의 찬성으로 의결한다. 군인·군무원·경찰공무원 기타 법률이 정하는 자가 전투·훈련등 직무집행과 관련하여 받은 손해에 대하여는 법률이 정하는 보상외에 국가 또는 공공단체에 공무원의 직무상 불법행위로 인한 배상은 청구할 수 없다.", - "كان فشكّل الشرقي مع, واحدة للمجهود تزامناً بعض بل. وتم جنوب للصين غينيا لم, ان وبدون وكسبت الأمور ذلك, أسر الخاسر الانجليزية هو. نفس لغزو مواقعها هو. الجو علاقة الصعداء انه أي, كما مع بمباركة للإتحاد الوزراء. ترتيب الأولى أن حدى, الشتوية باستحداث مدن بل, كان قد أوسع عملية. الأوضاع بالمطالبة كل قام, دون إذ شمال الربيع،. هُزم الخاصّة ٣٠ أما, مايو الصينية مع قبل.", - "או סדר החול מיזמי קרימינולוגיה. קהילה בגרסה לויקיפדים אל היא, של צעד ציור ואלקטרוניקה. מדע מה ברית המזנון ארכיאולוגיה, אל טבלאות מבוקשים כלל. מאמרשיחהצפה העריכהגירסאות שכל אל, כתב עיצוב מושגי של. קבלו קלאסיים ב מתן. נבחרים אווירונאוטיקה אם מלא, לוח למנוע ארכיאולוגיה מה. ארץ לערוך בקרבת מונחונים או, עזרה רקטות לויקיפדים אחר גם.", - "Лорем ლორემ अधिकांश 覧六子 八メル 모든 בקרבת äggg 123€ .", -] - - -func test_utf32_to_utf8(): - # 1 byte utf8 character - assert_eq( - Decoder.utf32_to_utf8(0x00000061), - PoolByteArray([0x61]) - ) - # 2 byte utf8 character - assert_eq( - Decoder.utf32_to_utf8(0x00000761), - PoolByteArray([0xdd, 0xa1]) - ) - # 3 byte utf8 character - assert_eq( - Decoder.utf32_to_utf8(0x00002621), - PoolByteArray([0xe2, 0x98, 0xa1]) - ) - # 4 byte utf8 character - assert_eq( - Decoder.utf32_to_utf8(0x00010144), - PoolByteArray([0xf0, 0x90, 0x85, 0x84]) - ) - assert_eq( - Decoder.utf32_to_utf8(0x0001f427) as Array, - PoolByteArray([0xf0, 0x9f, 0x90, 0xa7]) as Array - ) - - -func test_utf32_to_string(): - assert_eq( - Decoder.utf32_to_string([49, 50, 51, 0x1d11e, 49, 50, 51]), - '123𝄞123' - ) - -class TestUtf8ToUtf32Decoder: - extends 'res://addons/gut/test.gd' - - var decoder = Decoder.Utf8ToUtf32.new() - var target = [] - - # Full codepoint tests take a long time to run, so skip them unless this - # environment variable is set. - var skip_full_codepoint_tests = not OS.get_environment("RUN_FULL_CODEPOINT_TESTS") - - - func before_each(): - decoder.clear() - target.clear() - target.resize(5) - - func test_lol(): - var target = [0, 0, 0, 0] - decoder.decode(''.substr(0, 1).to_utf8(), target) - assert_eq(target, []) - - - func test_full_code_point_0_to_65535(): # 1/2/3 byte sequences - if skip_full_codepoint_tests: - print("Skipping full codepoint test") - return - for i in range(65536): - # skip surrogate pairs - if i >= 0xD800 and i <= 0xDFFF: - continue - # FIXME: Skip 0xfeff (zero width no-break space) - # which fails for some reason - if i == 0xfeff: - continue - var utf8_data = Decoder.utf32_to_utf8(i) - var length = decoder.decode(utf8_data, target) - assert_eq(length, 1) - assert_eq(char(target[0]), utf8_data.get_string_from_utf8(), - "Wrong string for codepoint 0x%x" % target[0]) - decoder.clear() - - func test_full_codepoint_65536_to_0x10FFFF(): # 4 byte sequences - if skip_full_codepoint_tests: - print("Skipping full codepoint test") - return - for i in range(65536, 0x10FFFF): - var utf8_data = Decoder.utf32_to_utf8(i) - var length = decoder.decode(utf8_data, target) - assert_eq(length, 1) - assert_eq(target[0], i) - - func test_test_strings(): - target.resize(500) - for string in TEST_STRINGS: - var utf8_data = string.to_utf8() - var length = decoder.decode(utf8_data, target) - assert_eq(Decoder.utf32_to_string(target, 0, length), string) - decoder.clear() diff --git a/test/unit/parser/test_dcs_parser.gd b/test/unit/parser/test_dcs_parser.gd deleted file mode 100644 index cbe6459..0000000 --- a/test/unit/parser/test_dcs_parser.gd +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright (c) 2020 The GodotXterm authors. -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# License MIT -extends "res://addons/gut/test.gd" - -const DcsParser = preload("res://addons/godot_xterm/parser/dcs_parser.gd") -const Parser = preload("res://addons/godot_xterm/parser/escape_sequence_parser.gd") -const Params = preload("res://addons/godot_xterm/parser/params.gd") -const Decoder = preload("res://addons/godot_xterm/input/text_decoder.gd") - -class Handler: - extends Reference - - - var _output - var _msg - var _return_false - - - func _init(output: Array, msg: String, return_false: bool = false): - _output = output - _msg = msg - _return_false = return_false - - - func hook(params): - _output.append([_msg, 'HOOK', params.to_array()]) - - - func put(data: Array, start: int, end: int): - _output.append([_msg, 'PUT', Decoder.utf32_to_string(data, start, end)]) - - - func unhook(success: bool): - _output.append([_msg, 'UNHOOK', success]) - if _return_false: - return false - - -var parser: DcsParser -var reports: Array - - -func to_utf32(s: String): - var utf32 = [] - utf32.resize(s.length()) - var decoder = Decoder.Utf8ToUtf32.new() - var length = decoder.decode(s.to_utf8(), utf32) - assert_eq(length, s.length()) - return utf32.slice(0, length - 1) - - -func handler_fallback(id, action, data): - if action == 'HOOK': - data = data.to_array() - reports.append([id, action, data]) - - -func before_each(): - parser = DcsParser.new() - parser.set_handler_fallback(self, 'handler_fallback') - reports = [] - - -func test_set_dcs_handler(): - parser.set_handler(Parser.identifier({'intermediates': '+', 'final': 'p'}), - Handler.new(reports, 'th')) - parser.hook(Parser.identifier({'intermediates': '+', 'final': 'p'}), - Params.from_array([1, 2, 3])) - var data = to_utf32('Here comes') - parser.put(data, 0, data.size()) - data = to_utf32('the mouse!') - parser.put(data, 0, data.size()) - parser.unhook(true) - assert_eq(reports, [ - # messages from Handler - ['th', 'HOOK', [1, 2, 3]], - ['th', 'PUT', 'Here comes'], - ['th', 'PUT', 'the mouse!'], - ['th', 'UNHOOK', true], - ]) - - -func test_clear_dcs_handler(): - var ident = Parser.identifier({'intermediates': '+', 'final': 'p'}) - parser.set_handler(ident, Handler.new(reports, 'th')) - parser.clear_handler(ident) - parser.hook(ident, Params.from_array([1, 2, 3])) - var data = to_utf32('Here comes') - parser.put(data, 0, data.size()) - data = to_utf32('the mouse!') - parser.put(data, 0, data.size()) - parser.unhook(true) - assert_eq(reports, [ - # messages from fallback handler - [ident, 'HOOK', [1, 2, 3]], - [ident, 'PUT', 'Here comes'], - [ident, 'PUT', 'the mouse!'], - [ident, 'UNHOOK', true], - ]) diff --git a/test/unit/parser/test_escape_sequence_parser.gd b/test/unit/parser/test_escape_sequence_parser.gd deleted file mode 100644 index c2fc64f..0000000 --- a/test/unit/parser/test_escape_sequence_parser.gd +++ /dev/null @@ -1,411 +0,0 @@ -# Copyright (c) 2020 The GodotXterm authors. -# Copyright (c) 2018 The xterm.js authors. All rights reserved. -# License MIT -extends 'res://addons/gut/test.gd' - -const Parser = preload("res://addons/godot_xterm/parser/escape_sequence_parser.gd") -const Params = preload("res://addons/godot_xterm/parser/params.gd") -const Decoder = preload("res://addons/godot_xterm/input/text_decoder.gd") -const Constants = preload("res://addons/godot_xterm/parser/constants.gd") -const ParserState = Constants.ParserState - -class TestTerminal: - var calls = [] - - func clear(): - calls = [] - - - func handle_print(data, start, end): - var string = Decoder.utf32_to_string(data, start, end) - calls.append(['print', string]) - - - func handle_csi(ident, params): - var id = Parser.ident_to_string(ident) - var collect = id.substr(0, id.length() - 1) - var flag = id.substr(id.length() - 1, 1) - calls.append(['csi', collect, params, flag]) - - - func handle_esc(ident: int): - var id = Parser.ident_to_string(ident) - var collect = id.substr(0, id.length() - 1) - var flag = id.substr(id.length() - 1, 1) - calls.append(['esc', collect, flag]) - - - func handle_execute(code: int): - var flag = char(code) - calls.append(['exe', flag]) - - - func handle_dcs(collect_and_flag, action, payload): - match action: - 'HOOK': - calls.append(['dcs hook', payload.to_array()]) - 'PUT': - calls.append(['dcs put', payload]) - 'UNHOOK': - calls.append(['dcs unhook', payload]) - - -# derived parser with access to internal states -class TestParser: - extends Parser - - var params setget _set_params,_get_params - var collect setget _set_collect,_get_collect - - - func _init(): - pass - - - func _set_params(value): - _params = Params.from_array(value) - - - func _get_params(): - return _params.to_array() - - - func _set_collect(value: String): - _collect = 0 - for c in value.to_ascii(): - _collect <<= 8 - _collect |= c - - - func _get_collect() -> String: - return ident_to_string(_collect) - - - func real_params(): - return _params - -# translate string based parse calls into typed array based -func parse(parser: TestParser, data): - if data == '': # handle the 0x00 codepoint - data = PoolByteArray([0]) - else: - data = data.to_utf8() - var container = [] - var decoder = Decoder.Utf8ToUtf32.new() - decoder.clear() - var length = decoder.decode(data, container) - parser.parse(container, length) - - -var parser -var test_terminal - - -func before_all(): - parser = TestParser.new() - test_terminal = TestTerminal.new() - - parser.set_print_handler(test_terminal, 'handle_print') - parser.set_csi_handler_fallback(test_terminal, 'handle_csi') - parser.set_esc_handler_fallback(test_terminal, 'handle_esc') - parser.set_execute_handler_fallback(test_terminal, "handle_execute") - parser.set_dcs_handler_fallback(test_terminal, "handle_dcs") - - -func before_each(): - parser.reset() - test_terminal.clear() - - -func test_initial_states(): - assert_eq(parser.initial_state, ParserState.GROUND) - assert_eq(parser.current_state, ParserState.GROUND) - assert_eq(parser._params.to_array(), [0]) - -func test_reset_states(): - var params = Params.new() - params.add_param(123) - parser.current_state = 124 - parser._params = params - parser.reset() - assert_eq(parser.current_state, ParserState.GROUND) - assert_eq(parser._params.to_array(), [0]) - -# state transitions and actions - -func test_state_GROUND_execute_action(): - var exes = range(0x00, 0x18) + [0x19] + range(0x1c, 0x20) - for exe in exes: - parser.current_state = ParserState.GROUND - parse(parser, char(exe)) - assert_eq(parser.current_state, ParserState.GROUND) - parser.reset() - -func test_state_GROUND_print_action(): - var printables = range(0x20, 0x7f) # NOTE: DEL excluded - for printable in printables: - var string = char(printable) - parser.current_state = ParserState.GROUND - parse(parser, string) - assert_eq(parser.current_state, ParserState.GROUND) - assert_eq(test_terminal.calls, [['print', string]]) - parser.reset() - test_terminal.clear() - -func test_trans_ANYWHERE_to_GROUND_with_actions(): - var exes = [ - '\u0018', '\u001a', - '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u0085', '\u0086', '\u0087', '\u0088', - '\u0089', '\u008a', '\u008b', '\u008c', '\u008d', '\u008e', '\u008f', - '\u0091', '\u0092', '\u0093', '\u0094', '\u0095', '\u0096', '\u0097', '\u0099', '\u009a' - ] - var exceptions = { - 8: { '\u0018': [], '\u001a': [] }, # abort OSC_STRING - 13: { '\u0018': [['dcs unhook', false]], '\u001a': [['dcs unhook', false]] } # abort DCS_PASSTHROUGH - } - for state in ParserState.values(): - for exe in exes: - if exe != '\u0018' and exe != '\u001a': - continue - parser.current_state = state - parse(parser, exe) - assert_eq(parser.current_state, ParserState.GROUND) - assert_eq( - test_terminal.calls, - exceptions[state][exe] if exceptions.has(state) and exceptions[state].has(exe) else [['exe', exe]], - 'state: %s exe: %x' % [ParserState.keys()[state], exe.to_utf8()[0]] - ) - parser.reset() - test_terminal.clear() - parse(parser, '\u009c') - assert_eq(parser.current_state, ParserState.GROUND) - assert_eq(test_terminal.calls, []) - parser.reset() - test_terminal.clear() - - -func skip_test_trans_ANYWHERE_to_ESCAPE_with_clear(): - for state in ParserState.values(): - var state_name = ParserState.keys()[state] - parser.current_state = state - parser.params = [23] - parser.collect = '#' - parse(parser, '\u001b') - assert_eq(parser.current_state, ParserState.ESCAPE, - 'wrong current_state. start state: %s' % state_name) - assert_eq(parser.params, [0], - 'wrong params. start state: %s' % state_name) - assert_eq(parser.collect, '', - 'wrong collect. start state: %s' % state_name) - parser.reset() - - -func test_state_ESCAPE_execute_rules(): - var exes = range(0x00, 0x18) + [0x19] + range(0x1c, 0x20) - for exe in exes: - parser.current_state = ParserState.ESCAPE - var data = char(exe) - parse(parser, data) - assert_eq(parser.current_state, ParserState.ESCAPE, 'exe: %x' % exe) - assert_eq(test_terminal.calls, [['exe', data]], 'exe: %x' % exe) - parser.reset() - test_terminal.clear() - - -func test_state_ESCAPE_ignore(): - parser.current_state = ParserState.ESCAPE - parse(parser, '\u007f') - assert_eq(parser.current_state, ParserState.ESCAPE) - assert_eq(test_terminal.calls, []) - -func test_trans_ESCAPE_to_GROUND_with_esc_dispatch_action(): - var dispatches = range(0x30, 0x50) + range(0x51, 0x58) + [0x59, 0x5a] + range(0x60, 0x7f) - for dispatch in dispatches: - parser.current_state = ParserState.ESCAPE - var data = char(dispatch) - parse(parser, data) - assert_eq(parser.current_state, ParserState.GROUND, - 'wrong state: %s, dispatch: %x' % [ParserState.keys()[parser.current_state], dispatch]) - assert_eq(test_terminal.calls, [['esc', '', data]], - 'wrong call. dispatch: %x' % dispatch) - parser.reset() - test_terminal.clear() - - -func test_trans_ESCAPE_to_ESCAPE_INTERMEDIATE_with_collect_action(): - var collect = range(0x20, 0x30) - for c in collect: - parser.current_state = ParserState.ESCAPE - var data = char(c) - parse(parser, data) - assert_eq(parser.current_state, ParserState.ESCAPE_INTERMEDIATE) - assert_eq(parser.collect, data) - parser.reset() - - -func test_state_ESCAPE_INTERMEDIATE_execute_rules(): - var exes = range(0x00, 0x18) + [0x19] + range(0x1c, 0x20) - for exe in exes: - var data = char(exe) - parser.current_state = ParserState.ESCAPE_INTERMEDIATE - parse(parser, data) - assert_eq(parser.current_state, ParserState.ESCAPE_INTERMEDIATE) - assert_eq(test_terminal.calls, [['exe', data]]) - parser.reset() - test_terminal.clear() - - -func test_state_ESCAPE_INTERMEDIATE_ignore(): - parser.current_state = ParserState.ESCAPE_INTERMEDIATE - parse(parser, '\u007f') - assert_eq(parser.current_state, ParserState.ESCAPE_INTERMEDIATE) - assert_eq(test_terminal.calls, []) - - -func test_state_ESCAPE_INTERMEDIATE_collect_action(): - var collect = range(0x20, 0x30) - for c in collect: - var data = char(c) - parser.current_state = ParserState.ESCAPE_INTERMEDIATE - parse(parser, data) - assert_eq(parser.current_state, ParserState.ESCAPE_INTERMEDIATE) - assert_eq(parser.collect, data) - parser.reset() - - -func test_trans_ESCAPE_INTERMEDIATE_to_GROUND_with_esc_dispatch_action(): - var collect = range(0x30, 0x7f) - for c in collect: - var data = char(c) - parser.current_state = ParserState.ESCAPE_INTERMEDIATE - parse(parser, data) - assert_eq(parser.current_state, ParserState.GROUND) - # '\u005c' --> ESC + \ (7bit ST) parser does not expose this as it already got handled - assert_eq(test_terminal.calls, [] if c == 0x5c else [['esc', '', data]], 'c: 0x%x' % c) - parser.reset() - test_terminal.clear() - -func test_ANYWHERE_or_ESCAPE_to_CSI_ENTRY_with_clear(): - # C0 - parser.current_state = ParserState.ESCAPE - parser.params = [123] - parser.collect = '#' - parse(parser, '[') - assert_eq(parser.current_state, ParserState.CSI_ENTRY) - assert_eq(parser.params, [0]) - assert_eq(parser.collect, '') - parser.reset() - # C1 - for state in ParserState.values(): - parser.current_state = state - parser.params = [123] - parser.collect = '#' - parse(parser, '\u009b') - assert_eq(parser.current_state, ParserState.CSI_ENTRY) - assert_eq(parser.collect, '') - parser.reset() - - -func test_CSI_ENTRY_execute_rules(): - var exes = range(0x00, 0x18) + [0x19] + range(0x1c, 0x20) - for exe in exes: - var data = char(exe) - parser.current_state = ParserState.CSI_ENTRY - parse(parser, data) - assert_eq(parser.current_state, ParserState.CSI_ENTRY) - assert_eq(test_terminal.calls, [['exe', data]]) - parser.reset() - test_terminal.clear() - - -func test_state_CSI_ENTRY_ignore(): - parser.current_state = ParserState.CSI_ENTRY - parse(parser, '\u007f') - assert_eq(parser.current_state, ParserState.CSI_ENTRY) - assert_eq(test_terminal.calls, []) - - -func test_trans_CSI_ENTRY_to_GROUND_with_csi_dispatch_action(): - var dispatches = range(0x40, 0x7f) - for dispatch in dispatches: - var data = char(dispatch) - parser.current_state = ParserState.CSI_ENTRY - parse(parser, data) - assert_eq(parser.current_state, ParserState.GROUND) - assert_eq(test_terminal.calls, [['csi', '', [0], data]]) - parser.reset() - test_terminal.clear() - - -func test_trans_CSI_ENTRY_to_CSI_PARAMS_with_param_or_collect_action(): - var params = range(0x30, 0x3a) - var collect = ['\u003c', '\u003d', '\u003e', '\u003f'] - for param in params: - parser.current_state = ParserState.CSI_ENTRY - parse(parser, char(param)) - assert_eq(parser.current_state, ParserState.CSI_PARAM) - assert_eq(parser.params, [param - 48], 'param: 0x%x' % param) - parser.reset() - parser.current_state = ParserState.CSI_ENTRY - parse(parser, '\u003b') - assert_eq(parser.current_state, ParserState.CSI_PARAM) - assert_eq(parser.params, [0, 0]) - parser.reset() - for c in collect: - parser.current_state = ParserState.CSI_ENTRY - parse(parser, c) - assert_eq(parser.current_state, ParserState.CSI_PARAM) - assert_eq(parser.collect, c) - parser.reset() - - -func test_state_CSI_PARAM_execute_rules(): - var exes = range(0x00, 0x018) + [0x19] + range(0x1c, 0x20) - for exe in exes: - var data = char(exe) - parser.current_state = ParserState.CSI_PARAM - parse(parser, data) - assert_eq(parser.current_state, ParserState.CSI_PARAM) - assert_eq(test_terminal.calls, [['exe', data]]) - parser.reset() - test_terminal.clear() - - -func test_state_CSI_PARAM_param_action(): - var params = range(0x30, 0x3a) - for param in params: - parser.current_state = ParserState.CSI_PARAM - parse(parser, char(param)) - assert_eq(parser.current_state, ParserState.CSI_PARAM) - assert_eq(parser.params, [param - 48], 'param: 0x%x' % param) - parser.reset() - - -func test_state_CSI_PARAM_ignore(): - parser.current_state = ParserState.CSI_PARAM - parse(parser, '\u007f') - assert_eq(parser.current_state, ParserState.CSI_PARAM) - assert_eq(test_terminal.calls, []) - - -func test_trans_CSI_PARAM_to_GROUND_with_csi_dispatch_action(): - var dispatches = range(0x40, 0x7f) - for dispatch in dispatches: - var data = char(dispatch) - parser.current_state = ParserState.CSI_PARAM - parser.params = [0, 1] - parse(parser, data) - assert_eq(parser.current_state, ParserState.GROUND) - assert_eq(test_terminal.calls, [['csi', '', [0, 1], data]]) - parser.reset() - test_terminal.clear() - - -func test_trans_CSI_ENTRY_to_CSI_INTERMEDIATE_with_collect_action(): - for collect in range(0x20, 0x30): - var data = char(collect) - parser.current_state = ParserState.CSI_ENTRY - parse(parser, data) - assert_eq(parser.current_state, ParserState.CSI_INTERMEDIATE) - assert_eq(parser.collect, data) - parser.reset() diff --git a/test/unit/parser/test_parser.gd b/test/unit/parser/test_parser.gd deleted file mode 100644 index c3987cc..0000000 --- a/test/unit/parser/test_parser.gd +++ /dev/null @@ -1,202 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends 'res://addons/gut/test.gd' - -const Params = preload("res://addons/godot_xterm/parser/params.gd") - -class TestParams: - extends 'res://addons/gut/test.gd' - - var params - - func before_each(): - params = Params.new() - - func test_respects_ctor_args(): - params = Params.new(12, 23) - assert_eq(params.params.size(), 12) - assert_eq(params.sub_params.size(), 23) - assert_eq(params.to_array(), []) - - func test_add_param(): - params.add_param(1) - assert_eq(params.length, 1) - assert_eq(params.params.slice(0, params.length - 1), [1]) - assert_eq(params.to_array(), [1]) - params.add_param(23) - assert_eq(params.length, 2) - assert_eq(params.params.slice(0, params.length - 1), [1, 23]) - assert_eq(params.to_array(), [1, 23]) - assert_eq(params.sub_params_length, 0) - - func test_add_sub_param(): - params.add_param(1) - params.add_sub_param(2) - params.add_sub_param(3) - assert_eq(params.length, 1) - assert_eq(params.sub_params_length, 2) - assert_eq(params.to_array(), [1, [2, 3]]) - params.add_param(12345) - params.add_sub_param(-1) - assert_eq(params.length, 2) - assert_eq(params.sub_params_length, 3) - assert_eq(params.to_array(), [1, [2,3], 12345, [-1]]) - - func test_should_not_add_sub_params_without_previous_param(): - params.add_sub_param(2) - params.add_sub_param(3) - assert_eq(params.length, 0) - assert_eq(params.sub_params_length, 0) - assert_eq(params.to_array(), []) - params.add_param(1) - params.add_sub_param(2) - params.add_sub_param(3) - assert_eq(params.length, 1) - assert_eq(params.sub_params_length, 2) - assert_eq(params.to_array(), [1, [2, 3]]) - - func test_reset(): - params.add_param(1) - params.add_sub_param(2) - params.add_sub_param(3) - params.add_param(12345) - params.reset() - assert_eq(params.length, 0) - assert_eq(params.sub_params_length, 0) - assert_eq(params.to_array(), []) - params.add_param(1) - params.add_sub_param(2) - params.add_sub_param(3) - params.add_param(12345) - params.add_sub_param(-1) - assert_eq(params.length, 2) - assert_eq(params.sub_params_length, 3) - assert_eq(params.to_array(), [1, [2, 3], 12345, [-1]]) - - - func test_from_array_to_array(): - var data = [] - assert_eq(params.from_array(data).to_array(), data) - data = [1, [2, 3], 12345, [-1]] - assert_eq(params.from_array(data).to_array(), data) - data = [38, 2, 50, 100, 150] - assert_eq(params.from_array(data).to_array(), data) - data = [38, 2, 50, 100, [150]] - assert_eq(params.from_array(data).to_array(), data) - data = [38, [2, 50, 100, 150]] - assert_eq(params.from_array(data).to_array(), data) - # strip empty sub params - data = [38, [2, 50, 100, 150], 5, [], 6] - assert_eq(Params.from_array(data).to_array(), [38, [2, 50, 100, 150], 5, 6]) - # ignore leading sub params - data = [[1,2], 12345, [-1]] - assert_eq(Params.from_array(data).to_array(), [12345, [-1]]) - - -class TestParse: - extends 'res://addons/gut/test.gd' - - var params - - func parse(params, s): - params.reset() - params.add_param(0) - if typeof(s) == TYPE_STRING: - s = [s] - for chunk in s: - var i = 0 - while i < chunk.length(): - # Start for - var code = chunk.to_ascii()[i] - var do = true - while do: - match code: - 0x3b: - params.add_param(0) - 0x3a: - params.add_sub_param(-1) - _: - params.add_digit(code - 48) - code = chunk.to_ascii()[i] if i < chunk.length() else 0 - i+=1 - do = i < s.size() and code > 0x2f and code < 0x3c - i-=1 - # End for - i+=1 - - func before_each(): - params = Params.new() - - func test_param_defaults_to_0(): # ZDM (Zero Default Mode) - parse(params, '') - assert_eq(params.to_array(), [0]) - - func test_sub_param_defaults_to_neg_1(): - parse(params, ':') - assert_eq(params.to_array(), [0, [-1]]) - - func test_reset_on_new_sequence(): - parse(params, '1;2;3') - assert_eq(params.to_array(), [1, 2, 3]) - parse(params, '4') - assert_eq(params.to_array(), [4]) - parse(params, '4::123:5;6;7') - assert_eq(params.to_array(), [4, [-1, 123, 5], 6, 7]) - parse(params, '') - assert_eq(params.to_array(), [0]) - - func test_should_handle_length_restrictions_correctly(): - params = Params.new(3, 3) - parse(params, '1;2;3') - assert_eq(params.to_array(), [1, 2, 3]) - parse(params, '4') - assert_eq(params.to_array(), [4]) - parse(params, '4::123:5;6;7') - assert_eq(params.to_array(), [4, [-1, 123, 5], 6, 7]) - parse(params, '') - assert_eq(params.to_array(), [0]) - # overlong params - parse(params, '4;38:2::50:100:150;48:5:22') - assert_eq(params.to_array(), [4, 38, [2, -1, 50], 48]) - # overlong sub params - parse(params, '4;38:2::50:100:150;48:5:22') - assert_eq(params.to_array(), [4, 38, [2, -1, 50], 48]) - - func test_typical_sequences(): - # SGR with semicolon syntax - parse(params, '0;4;38;2;50;100;150;48;5;22') - assert_eq(params.to_array(), [0, 4, 38, 2, 50, 100, 150, 48, 5, 22]) - # SGR mixed style (partly wrong) - parse(params, '0;4;38;2;50:100:150;48;5:22') - assert_eq(params.to_array(), [0, 4, 38, 2, 50, [100, 150], 48, 5, [22]]) - # SGR colon style - parse(params, '0;4;38:2::50:100:150;48:5:22') - assert_eq(params.to_array(), [0, 4, 38, [2, -1, 50, 100, 150], 48, [5, 22]]) - - func test_clamp_parsed_params(): - parse(params, '2147483648') - assert_eq(params.to_array(), [0x7FFFFFFF]) - - func test_clamp_parsed_sub_params(): - parse(params, ':2147483648') - assert_eq(params.to_array(), [0, [0x7FFFFFFF]]) - - func test_should_cancel_subdigits_if_beyond_params_limit(): - parse(params, ';;;;;;;;;10;;;;;;;;;;20;;;;;;;;;;30;31;32;33;34;35::::::::') - assert_eq(params.to_array(), [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 31, 32 - ]) - -# func test_should_carry_forward_is_sub_state(): -# parse(params, ['1:22:33', '44']) -# assert_eq(params.to_array(), [1, [22, 3344]]) - - - - - - - diff --git a/test/unit/renderer/test_canvas_rendering_context_2d.gd b/test/unit/renderer/test_canvas_rendering_context_2d.gd deleted file mode 100644 index b4862a1..0000000 --- a/test/unit/renderer/test_canvas_rendering_context_2d.gd +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2020 The GodotXterm authors. All rights reserved. -# License MIT -extends "res://addons/gut/test.gd" - - -const CanvasRenderingContext2D = preload("res://addons/godot_xterm/renderer/canvas_rendering_context_2d.gd") -const RegularFont = preload("res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_regular.tres") -const BoldFont = preload("res://addons/godot_xterm/fonts/source_code_pro/source_code_pro_bold.tres") - -var ctx - - -func before_each(): - ctx = CanvasRenderingContext2D.new() - - -func test_measure_text(): - assert_eq(ctx.measure_text("a").width, RegularFont.get_string_size("a").x) - - -func test_save_and_restore(): - # fill_style - ctx.fill_style = Color.red - ctx.save() - ctx.fill_style = Color.blue - assert_eq(ctx.fill_style, Color.blue) - ctx.restore() - assert_eq(ctx.fill_style, Color.red) - # font - ctx.font = RegularFont - ctx.save() - ctx.font = BoldFont - assert_eq(ctx.font, BoldFont) - ctx.restore() - assert_eq(ctx.font, RegularFont) diff --git a/test/unit/renderer/test_character_joiner_registry.gd b/test/unit/renderer/test_character_joiner_registry.gd deleted file mode 100644 index be21289..0000000 --- a/test/unit/renderer/test_character_joiner_registry.gd +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright (c) 2018 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends "res://addons/gut/test.gd" - - -const CharacterJoinerRegistry = preload("res://addons/godot_xterm/renderer/character_joiner_registry.gd") -const Buffer = preload("res://addons/godot_xterm/buffer/buffer.gd") -const BufferLine = preload("res://addons/godot_xterm/buffer/buffer_line.gd") -const CircularList = preload("res://addons/godot_xterm/circular_list.gd") -const CellData = preload("res://addons/godot_xterm/buffer/cell_data.gd") -const AttributeData = preload("res://addons/godot_xterm/buffer/attribute_data.gd") -const TestUtils = preload("res://test/test_utils.gd") - -var registry - - -func line_data(data): - var tline = BufferLine.new(0) - for d in data: - var line = d[0] - var attr = d[1] if d.size() > 1 else 0 - var offset = tline.length - tline.resize(tline.length + line.split('').size(), CellData.from_char_data([0, '', 0, 0])) - - -func before_each(): - var buffer_service = TestUtils.MockBufferService.new(16, 10) - var lines = buffer_service.buffer.lines - lines.set_el(0, line_data([['a -> b -> c -> d']])) - lines.set_el(1, line_data([['a -> b => c -> d']])) - lines.set_el(2, line_data([['a -> b -', 0xFFFFFFFF], ['> c -> d', 0]])) - - registry = CharacterJoinerRegistry.new(buffer_service) - - -func test_has_no_joiners_upon_creation(): - assert_eq(registry.get_joined_characters(0), []) diff --git a/test/unit/test_circular_list.gd b/test/unit/test_circular_list.gd deleted file mode 100644 index ccca6bd..0000000 --- a/test/unit/test_circular_list.gd +++ /dev/null @@ -1,201 +0,0 @@ -# Copyright (c) 2016 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends "res://addons/gut/test.gd" - - -const CIRCULAR_LIST_PATH = "res://addons/godot_xterm/circular_list.gd" -const CircularList = preload(CIRCULAR_LIST_PATH) - -var list - - -func before_each(): - list = CircularList.new(5) - - -func test_push(): - list.push("1") - list.push("2") - list.push("3") - list.push("4") - list.push("5") - assert_eq(list.get_line(0), "1") - assert_eq(list.get_line(1), "2") - assert_eq(list.get_line(2), "3") - assert_eq(list.get_line(3), "4") - assert_eq(list.get_line(4), "5") - - -func test_splice_deletes_items(): - list = CircularList.new(2) - list.push("1") - list.push("2") - list.splice(0, 1) - assert_eq(list.length, 1) - assert_eq(list.get_el(0), "2") - list.push("3") - list.splice(1, 1) - assert_eq(list.length, 1) - assert_eq(list.get_el(0), "2") - - -func test_splice_inserts_items(): - list = CircularList.new(2) - list.push("1") - list.splice(0, 0, ["2"]) - assert_eq(list.length, 2) - assert_eq(list.get_el(0), "2") - assert_eq(list.get_el(1), "1") - list.splice(1, 0, ["3"]) - assert_eq(list.length, 2) - assert_eq(list.get_el(0), "3") - assert_eq(list.get_el(1), "1") - - -func test_splice_deletes_items_then_inserts_items(): - list = CircularList.new(3) - list.push("1") - list.push("2") - list.splice(0, 1, ["3", "4"]) - assert_eq(list.length, 3) - assert_eq(list.get_el(0), "3") - assert_eq(list.get_el(1), "4") - assert_eq(list.get_el(2), "2") - - -func test_splice_wraps_the_array_correctly_when_more_items_are_inserted_than_deleted(): - list = CircularList.new(3) - list.push("1") - list.push("2") - list.splice(1, 0, ["3", "4"]) - assert_eq(list.length, 3) - assert_eq(list.get_el(0), "3") - assert_eq(list.get_el(1), "4") - assert_eq(list.get_el(2), "2") - - -class TestShiftElements: - extends "res://addons/gut/test.gd" - - - var list - - - func before_each(): - list = CircularList.new(5) - - - func test_does_not_mutate_the_list_when_count_is_0(): - list.push(1) - list.push(2) - list.shift_elements(0, 0, 1) - assert_eq(list.length, 2) - assert_eq(list.get_el(0), 1) - assert_eq(list.get_el(1), 2) - - - func test_pushes_errors_for_invalid_args(): - list = partial_double(CIRCULAR_LIST_PATH).new() - list.max_length = 5 - list.push(1) - list.shift_elements(-1, 1, 1) - assert_called(list, "push_error", ["start argument out of range"]) - list.shift_elements(1, 1, 1) - assert_called(list, "push_error", ["start argument out of range"]) - list.shift_elements(0, 1, -1) - assert_called(list, "push_error", ["cannot shift elements in list beyond index 0"]) - - - func test_trim_start_removes_items_from_the_beginning_of_the_list(): - list.push("1") - list.push("2") - list.push("3") - list.push("4") - list.push("5") - list.trim_start(1) - assert_eq(list.length, 4) - assert_eq(list.get_el(0), "2") - assert_eq(list.get_el(1), "3") - assert_eq(list.get_el(2), "4") - assert_eq(list.get_el(3), "5") - list.trim_start(2) - assert_eq(list.length, 2) - assert_eq(list.get_el(0), "4") - assert_eq(list.get_el(1), "5") - - - func test_trim_start_removes_all_items_if_the_requested_trim_amount_is_larger_than_the_lists_length(): - list.push("1") - list.trim_start(2) - assert_eq(list.length, 0) - - - func test_shifts_an_element_forward(): - list.push(1) - list.push(2) - list.shift_elements(0, 1, 1) - assert_eq(list.length, 2) - assert_eq(list.get_el(0), 1) - assert_eq(list.get_el(1), 1) - - - func test_shifts_elements_forward(): - list.push(1) - list.push(2) - list.push(3) - list.push(4) - list.shift_elements(0, 2, 2) - assert_eq(list.length, 4) - assert_eq(list.get_el(0), 1) - assert_eq(list.get_el(1), 2) - assert_eq(list.get_el(2), 1) - assert_eq(list.get_el(3), 2) - - - func test_shifts_elements_forward_expanding_the_list_if_needed(): - list.push(1) - list.push(2) - list.shift_elements(0, 2, 2) - assert_eq(list.length, 4) - assert_eq(list.get_el(0), 1) - assert_eq(list.get_el(1), 2) - assert_eq(list.get_el(2), 1) - assert_eq(list.get_el(3), 2) - - - func test_shifts_elements_forward_wrapping_the_list_if_needed(): - list.push(1) - list.push(2) - list.push(3) - list.push(4) - list.push(5) - list.shift_elements(2, 2, 3) - assert_eq(list.length, 5) - assert_eq(list.get_el(0), 3) - assert_eq(list.get_el(1), 4) - assert_eq(list.get_el(2), 5) - assert_eq(list.get_el(3), 3) - assert_eq(list.get_el(4), 4) - - - func test_shifts_an_element_backwards(): - list.push(1) - list.push(2) - list.shift_elements(1, 1, -1) - assert_eq(list.length, 2) - assert_eq(list.get_el(0), 2) - assert_eq(list.get_el(1), 2) - - - func test_shiftS_elements_backwards(): - list.push(1) - list.push(2) - list.push(3) - list.push(4) - list.shift_elements(2, 2, -2) - assert_eq(list.length, 4) - assert_eq(list.get_el(0), 3) - assert_eq(list.get_el(1), 4) - assert_eq(list.get_el(2), 3) - assert_eq(list.get_el(3), 4) diff --git a/test/unit/test_input_handler.gd b/test/unit/test_input_handler.gd deleted file mode 100644 index a6b3183..0000000 --- a/test/unit/test_input_handler.gd +++ /dev/null @@ -1,288 +0,0 @@ -# Copyright (c) 2017 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends "res://addons/gut/test.gd" - - -const TestUtils = preload("res://test/test_utils.gd") -const InputHandler = preload("res://addons/godot_xterm/input_handler.gd") -const CharsetService = preload("res://addons/godot_xterm/services/charset_service.gd") -const Params = preload("res://addons/godot_xterm/parser/params.gd") -const CoreService = preload("res://addons/godot_xterm/services/core_service.gd") -const Constants = preload("res://addons/godot_xterm/buffer/constants.gd") -const OptionsService = preload("res://addons/godot_xterm/services/options_service.gd") - -const CursorStyle = Constants.CursorStyle - -var options_service -var buffer_service -var charset_service -var core_service -var input_handler - - -func get_lines(buffer_service, limit: int) -> Array: - var res = [] - if not limit: - limit = buffer_service.rows - for i in range(limit): - var line = buffer_service.buffer.lines.get_el(i) - if line: - res.append(line.translate_to_string(true)) - return res - - -func repeat(string: String, times: int) -> String: - var s = "" - for i in range(times): - s += string - return s - - -func term_content(buffer_service, trim: bool) -> PoolStringArray: - var result = PoolStringArray([]) - - for i in buffer_service.rows: - result.append(buffer_service.buffer.lines.get_el(i).translate_to_string(trim)) - return result; - - -func before_each(): - options_service = TestUtils.MockOptionsService.new() - buffer_service = TestUtils.MockBufferService.new(80, 30, options_service) - charset_service = CharsetService.new() - core_service = CoreService.new() - input_handler = InputHandler.new(buffer_service, core_service, charset_service, options_service) - - -func test_save_and_restore_cursor(): - buffer_service.buffer.x = 1 - buffer_service.buffer.y = 2 - buffer_service.buffer.ybase = 0 - input_handler._cur_attr_data.fg = 3 - # Save cursor position - input_handler.save_cursor() - assert_eq(buffer_service.buffer.x, 1) - assert_eq(buffer_service.buffer.y, 2) - assert_eq(input_handler._cur_attr_data.fg, 3) - # Change the cursor position - buffer_service.buffer.x = 10 - buffer_service.buffer.y = 20 - input_handler._cur_attr_data.fg = 30 - # Restore cursor position - input_handler.restore_cursor() - assert_eq(buffer_service.buffer.x, 1) - assert_eq(buffer_service.buffer.y, 2) - assert_eq(input_handler._cur_attr_data.fg, 3) - - -func test_set_cursor_style(): - input_handler.set_cursor_style(Params.from_array([0])) - assert_eq(options_service.options.cursor_style, CursorStyle.BLOCK) - assert_eq(options_service.options.cursor_blink, true) - - options_service.options = OptionsService.TerminalOptions.new() - input_handler.set_cursor_style(Params.from_array([1])) - assert_eq(options_service.options.cursor_style, CursorStyle.BLOCK) - assert_eq(options_service.options.cursor_blink, true) - - options_service.options = OptionsService.TerminalOptions.new() - input_handler.set_cursor_style(Params.from_array([2])) - assert_eq(options_service.options.cursor_style, CursorStyle.BLOCK) - assert_eq(options_service.options.cursor_blink, false) - - options_service.options = OptionsService.TerminalOptions.new() - input_handler.set_cursor_style(Params.from_array([3])) - assert_eq(options_service.options.cursor_style, CursorStyle.UNDERLINE) - assert_eq(options_service.options.cursor_blink, true) - - options_service.options = OptionsService.TerminalOptions.new() - input_handler.set_cursor_style(Params.from_array([4])) - assert_eq(options_service.options.cursor_style, CursorStyle.UNDERLINE) - assert_eq(options_service.options.cursor_blink, false) - - options_service.options = OptionsService.TerminalOptions.new() - input_handler.set_cursor_style(Params.from_array([5])) - assert_eq(options_service.options.cursor_style, CursorStyle.BAR) - assert_eq(options_service.options.cursor_blink, true) - - options_service.options = OptionsService.TerminalOptions.new() - input_handler.set_cursor_style(Params.from_array([6])) - assert_eq(options_service.options.cursor_style, CursorStyle.BAR) - assert_eq(options_service.options.cursor_blink, false) - - -func test_set_mode_toggles_bracketed_paste_mode(): - # Set bracketed paste mode - input_handler.set_mode_private(Params.from_array([2004])) - assert_true(core_service.dec_private_modes.bracketed_paste_mode) - # Reset bracketed paste mode - input_handler.reset_mode_private(Params.from_array([2004])) - assert_false(core_service.dec_private_modes.bracketed_paste_mode) - - -func test_erase_in_line(): - buffer_service = TestUtils.MockBufferService.new(80, 30, options_service) - input_handler = InputHandler.new(buffer_service, core_service, charset_service, options_service) - - # fill 6 lines to test 3 different states - input_handler.parse(repeat("a", buffer_service.cols)) - input_handler.parse(repeat("a", buffer_service.cols)) - input_handler.parse(repeat("a", buffer_service.cols)) - - - # params[0] - right erase - buffer_service.buffer.y = 0 - buffer_service.buffer.x = 70 - input_handler.erase_in_line(Params.from_array([0])) - assert_eq(buffer_service.buffer.lines.get_line(0).translate_to_string(false), - repeat("a", 70) + " ") - - # params[1] - left erase - buffer_service.buffer.y = 1 - buffer_service.buffer.x = 70 - input_handler.erase_in_line(Params.from_array([1])) - assert_eq(buffer_service.buffer.lines.get_line(1).translate_to_string(false), - repeat(" ", 70) + " aaaaaaaaa") - - # params[1] - left erase - buffer_service.buffer.y = 2 - buffer_service.buffer.x = 70 - input_handler.erase_in_line(Params.from_array([2])) - assert_eq(buffer_service.buffer.lines.get_line(2).translate_to_string(false), - repeat(" ", buffer_service.cols)) - - -func test_erase_in_display(): - buffer_service = TestUtils.MockBufferService.new(80, 7, options_service) - input_handler = InputHandler.new(buffer_service, core_service, charset_service, options_service) - - # fill display with a's - for _i in range(buffer_service.rows): - input_handler.parse(repeat("a", buffer_service.cols)) - - # params [0] - right and below erase - buffer_service.buffer.y = 5 - buffer_service.buffer.x = 40 - input_handler.erase_in_display(Params.from_array([0])) - assert_eq(term_content(buffer_service, false), PoolStringArray([ - repeat("a", buffer_service.cols), - repeat("a", buffer_service.cols), - repeat("a", buffer_service.cols), - repeat("a", buffer_service.cols), - repeat("a", buffer_service.cols), - repeat("a", 40) + repeat(" ", buffer_service.cols - 40), - repeat(" ", buffer_service.cols), - ])) - assert_eq(term_content(buffer_service, true), PoolStringArray([ - repeat("a", buffer_service.cols), - repeat("a", buffer_service.cols), - repeat("a", buffer_service.cols), - repeat("a", buffer_service.cols), - repeat("a", buffer_service.cols), - repeat("a", 40), - "" - ])) - - # reset - for _i in range(buffer_service.rows): - input_handler.parse(repeat("a", buffer_service.cols)) - - # params [1] - left and above - buffer_service.buffer.y = 5; - buffer_service.buffer.x = 40; - input_handler.erase_in_display(Params.from_array([1])) - assert_eq(term_content(buffer_service, false), PoolStringArray([ - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - repeat(" ", 41) + repeat("a", buffer_service.cols - 41), - repeat("a", buffer_service.cols), - ])) - assert_eq(term_content(buffer_service, true), PoolStringArray([ - "", - "", - "", - "", - "", - repeat(" ", 41) + repeat("a", buffer_service.cols - 41), - repeat("a", buffer_service.cols), - ])) - - # reset - for _i in range(buffer_service.rows): - input_handler.parse(repeat("a", buffer_service.cols)) - - # params [2] - whole screen - buffer_service.buffer.y = 5; - buffer_service.buffer.x = 40; - input_handler.erase_in_display(Params.from_array([2])); - assert_eq(term_content(buffer_service, false), PoolStringArray([ - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - repeat(" ", buffer_service.cols), - ])) - assert_eq(term_content(buffer_service, true), PoolStringArray([ - "", - "", - "", - "", - "", - "", - "", - ])) - - # reset and add a wrapped line - buffer_service.buffer.y = 0; - buffer_service.buffer.x = 0; - input_handler.parse(repeat("a", buffer_service.cols)) # line 0 - input_handler.parse(repeat("a", buffer_service.cols + 9)) # line 1 and 2 - for i in range(3, buffer_service.rows): - input_handler.parse(repeat("a", buffer_service.cols)) - - # params[1] left and above with wrap - # confirm precondition that line 2 is wrapped - assert_true(buffer_service.buffer.lines.get_line(2).is_wrapped) - buffer_service.buffer.y = 2 - buffer_service.buffer.x = 40 - input_handler.erase_in_display(Params.from_array([1])) - assert_false(buffer_service.buffer.lines.get_line(2).is_wrapped) - - # reset and add a wrapped line - buffer_service.buffer.y = 0 - buffer_service.buffer.x = 0 - input_handler.parse(repeat("a", buffer_service.cols)) # line 0 - input_handler.parse(repeat("a", buffer_service.cols + 9)) # line 1 and 2 - for i in range(3, buffer_service.rows): - input_handler.parse(repeat("a", buffer_service.cols)) - - # params[1] left and above with wrap - # confirm precondition that line 2 is wrapped - assert_true(buffer_service.buffer.lines.get_line(2).is_wrapped) - buffer_service.buffer.y = 1 - buffer_service.buffer.x = 90 # Cursor is beyond last column - input_handler.erase_in_display(Params.from_array([1])); - assert_false(buffer_service.buffer.lines.get_line(2).is_wrapped) - - -func test_print_does_not_cause_an_infinite_loop(): - var container = [] - container.resize(10) - container[0] = 0x200B - input_handler.print(container, 0, 1) - - -# FIXME -func skip_test_clear_cells_to_the_right_on_early_wrap_around(): - buffer_service.resize(5, 5) - options_service.options.scrollback = 1 - input_handler.parse('12345') - buffer_service.buffer.x = 0 - input_handler.parse("¥¥¥") - assert_eq(get_lines(buffer_service, 2), PoolStringArray(["¥¥", "¥"])) diff --git a/test/unit/test_params.gd b/test/unit/test_params.gd deleted file mode 100644 index d80cf6b..0000000 --- a/test/unit/test_params.gd +++ /dev/null @@ -1,222 +0,0 @@ -# Copyright (c) 2019 The xterm.js authors. All rights reserved. -# Ported to GDScript by the GodotXterm authors. -# License MIT -extends 'res://addons/gut/test.gd' - - -const Params = preload("res://addons/godot_xterm/parser/params.gd") - - -class TestParams: - extends 'res://addons/gut/test.gd' - - var params - - - func before_each(): - params = Params.new() - - - func test_respects_ctor_args(): - params = Params.new(12, 23) - assert_eq(params.params.size(), 12) - assert_eq(params.sub_params.size(), 23) - assert_eq(params.to_array(), []) - - - func test_add_param(): - params.add_param(1) - assert_eq(params.length, 1) - assert_eq(params.params.slice(0, params.length - 1), [1]) - assert_eq(params.to_array(), [1]) - params.add_param(23) - assert_eq(params.length, 2) - assert_eq(params.params.slice(0, params.length - 1), [1, 23]) - assert_eq(params.to_array(), [1, 23]) - assert_eq(params.sub_params_length, 0) - - - func test_add_sub_param(): - params.add_param(1) - params.add_sub_param(2) - params.add_sub_param(3) - assert_eq(params.length, 1) - assert_eq(params.sub_params_length, 2) - assert_eq(params.to_array(), [1, [2, 3]]) - params.add_param(12345) - params.add_sub_param(-1) - assert_eq(params.length, 2) - assert_eq(params.sub_params_length, 3) - assert_eq(params.to_array(), [1, [2,3], 12345, [-1]]) - - - func test_should_not_add_sub_params_without_previous_param(): - params.add_sub_param(2) - params.add_sub_param(3) - assert_eq(params.length, 0) - assert_eq(params.sub_params_length, 0) - assert_eq(params.to_array(), []) - params.add_param(1) - params.add_sub_param(2) - params.add_sub_param(3) - assert_eq(params.length, 1) - assert_eq(params.sub_params_length, 2) - assert_eq(params.to_array(), [1, [2, 3]]) - - - func test_reset(): - params.add_param(1) - params.add_sub_param(2) - params.add_sub_param(3) - params.add_param(12345) - params.reset() - assert_eq(params.length, 0) - assert_eq(params.sub_params_length, 0) - assert_eq(params.to_array(), []) - params.add_param(1) - params.add_sub_param(2) - params.add_sub_param(3) - params.add_param(12345) - params.add_sub_param(-1) - assert_eq(params.length, 2) - assert_eq(params.sub_params_length, 3) - assert_eq(params.to_array(), [1, [2, 3], 12345, [-1]]) - - - func test_from_array_to_array(): - var data = [] - assert_eq(params.from_array(data).to_array(), data) - data = [1, [2, 3], 12345, [-1]] - assert_eq(params.from_array(data).to_array(), data) - data = [38, 2, 50, 100, 150] - assert_eq(params.from_array(data).to_array(), data) - data = [38, 2, 50, 100, [150]] - assert_eq(params.from_array(data).to_array(), data) - data = [38, [2, 50, 100, 150]] - assert_eq(params.from_array(data).to_array(), data) - # strip empty sub params - data = [38, [2, 50, 100, 150], 5, [], 6] - assert_eq(Params.from_array(data).to_array(), [38, [2, 50, 100, 150], 5, 6]) - # ignore leading sub params - data = [[1,2], 12345, [-1]] - assert_eq(Params.from_array(data).to_array(), [12345, [-1]]) - - - func test_has_sub_params_get_sub_params(): - params = Params.from_array([38, [2, 50, 100, 150], 5, [], 6]) - assert_eq(params.has_sub_params(0), true) - assert_eq(params.get_sub_params(0), [2, 50, 100, 150]) - assert_eq(params.has_sub_params(1), false) - assert_eq(params.get_sub_params(1), null) - assert_eq(params.has_sub_params(2), false) - assert_eq(params.get_sub_params(2), null) - - -class TestParse: - extends 'res://addons/gut/test.gd' - - - var params - - - func parse(params, s): - params.reset() - params.add_param(0) - if typeof(s) == TYPE_STRING: - s = [s] - for chunk in s: - var i = 0 - while i < chunk.length(): - # Start for - var code = chunk.to_ascii()[i] - var do = true - while do: - match code: - 0x3b: - params.add_param(0) - 0x3a: - params.add_sub_param(-1) - _: - params.add_digit(code - 48) - code = chunk.to_ascii()[i] if i < chunk.length() else 0 - i+=1 - do = i < s.size() and code > 0x2f and code < 0x3c - i-=1 - # End for - i+=1 - - - func before_each(): - params = Params.new() - - - func test_param_defaults_to_0(): # ZDM (Zero Default Mode) - parse(params, '') - assert_eq(params.to_array(), [0]) - - - func test_sub_param_defaults_to_neg_1(): - parse(params, ':') - assert_eq(params.to_array(), [0, [-1]]) - - - func test_reset_on_new_sequence(): - parse(params, '1;2;3') - assert_eq(params.to_array(), [1, 2, 3]) - parse(params, '4') - assert_eq(params.to_array(), [4]) - parse(params, '4::123:5;6;7') - assert_eq(params.to_array(), [4, [-1, 123, 5], 6, 7]) - parse(params, '') - assert_eq(params.to_array(), [0]) - - - func test_should_handle_length_restrictions_correctly(): - params = Params.new(3, 3) - parse(params, '1;2;3') - assert_eq(params.to_array(), [1, 2, 3]) - parse(params, '4') - assert_eq(params.to_array(), [4]) - parse(params, '4::123:5;6;7') - assert_eq(params.to_array(), [4, [-1, 123, 5], 6, 7]) - parse(params, '') - assert_eq(params.to_array(), [0]) - # overlong params - parse(params, '4;38:2::50:100:150;48:5:22') - assert_eq(params.to_array(), [4, 38, [2, -1, 50], 48]) - # overlong sub params - parse(params, '4;38:2::50:100:150;48:5:22') - assert_eq(params.to_array(), [4, 38, [2, -1, 50], 48]) - - - func test_typical_sequences(): - # SGR with semicolon syntax - parse(params, '0;4;38;2;50;100;150;48;5;22') - assert_eq(params.to_array(), [0, 4, 38, 2, 50, 100, 150, 48, 5, 22]) - # SGR mixed style (partly wrong) - parse(params, '0;4;38;2;50:100:150;48;5:22') - assert_eq(params.to_array(), [0, 4, 38, 2, 50, [100, 150], 48, 5, [22]]) - # SGR colon style - parse(params, '0;4;38:2::50:100:150;48:5:22') - assert_eq(params.to_array(), [0, 4, 38, [2, -1, 50, 100, 150], 48, [5, 22]]) - - - func test_clamp_parsed_params(): - parse(params, '2147483648') - assert_eq(params.to_array(), [0x7FFFFFFF]) - - - func test_clamp_parsed_sub_params(): - parse(params, ':2147483648') - assert_eq(params.to_array(), [0, [0x7FFFFFFF]]) - - - func test_should_cancel_subdigits_if_beyond_params_limit(): - parse(params, ';;;;;;;;;10;;;;;;;;;;20;;;;;;;;;;30;31;32;33;34;35::::::::') - assert_eq(params.to_array(), [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 31, 32 - ]) - -