Class: Graphina::Graph::Display

Inherits:
Object
  • Object
show all
Defined in:
lib/graphina/graph/display.rb,
lib/graphina/graph/display/cell.rb

Overview

A terminal display class that manages a grid of colored cells with ANSI styling support

The Display class provides functionality for creating and managing terminal-based visual displays It handles cell-level rendering with support for colors, background colors, and text styles The class maintains internal state for cursor position and formatting attributes while providing methods to manipulate individual cells and render complete display grids to the terminal

Examples:

display = Graphina::Graph::Display.new(24, 80)
# Creates a 24x80 character display grid for terminal rendering

Defined Under Namespace

Classes: Cell

Constant Summary collapse

ANSI =

Shortcut for Term::ANSIColor module.

Term::ANSIColor

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lines, columns, color: :white, on_color: :black) ⇒ Display

The initialize method sets up a Display instance by configuring its grid dimensions and initializing internal state

This method creates a display grid with the specified number of lines and columns, establishing the boundaries for cell positioning. It initializes the internal ranges for lines and columns and performs an initial clear operation to set up the display buffer with default values

Parameters:

  • lines (Integer)

    the number of lines (rows) in the display grid

  • columns (Integer)

    the number of columns (characters per line) in the display grid

  • color (Symbol) (defaults to: :white)

    the default text color for the display

  • on_color (Symbol) (defaults to: :black)

    the default background color for the display



32
33
34
35
36
37
38
# File 'lib/graphina/graph/display.rb', line 32

def initialize(lines, columns, color: :white, on_color: :black)
  @lines_range   = 1..lines
  @columns_range = 1..columns
  @orig_color    = color
  @orig_on_color = on_color
  clear
end

Instance Attribute Details

#xInteger (readonly)

The x reader method provides access to the x attribute that was set during object initialization.

This method returns the value of the x instance variable, which typically represents the horizontal coordinate or position within the display grid.

Returns:

  • (Integer)

    the x coordinate value stored in the instance variable



158
159
160
# File 'lib/graphina/graph/display.rb', line 158

def x
  @x
end

#yInteger (readonly)

The y reader method provides access to the y attribute that was set during object initialization.

This method returns the value of the y instance variable, which typically represents the vertical coordinate or position within the display grid.

Returns:

  • (Integer)

    the y coordinate value stored in the instance variable



167
168
169
# File 'lib/graphina/graph/display.rb', line 167

def y
  @y
end

Instance Method Details

#-(old) ⇒ String

The - method calculates the difference between two display states by comparing their cells and returns a string of ANSI escape sequences that represent only the changes

This method takes another Display instance and compares it with the current display state to identify which cells have changed. It generates a minimal set of ANSI cursor movement and character output commands to redraw only the portions of the display that have changed, making terminal updates more efficient

Parameters:

Returns:

  • (String)

    a string containing ANSI escape sequences for rendering only the changed cells



116
117
118
119
120
121
122
123
124
125
126
# File 'lib/graphina/graph/display.rb', line 116

def -(old)
  dimensions != old.dimensions and raise ArgumentError,
    "old dimensions #{old.dimensions.inspect} don't match #{dimensions.inspect}"
  result = +''
  each.zip(old.each) do |(my, mx, me), (_, _, old)|
    if me != old
      result << ANSI.move_to(my, mx) << me.to_s
    end
  end
  result
end

#at(y, x) ⇒ Graphina::Graph::Display

The at method sets the cursor position within the display grid

This method updates the internal y and x coordinates to the specified position, validating that the coordinates fall within the defined grid boundaries before making the change. It enables subsequent character output operations to occur at the designated location.

Parameters:

  • y (Integer)

    the vertical coordinate to move the cursor to

  • x (Integer)

    the horizontal coordinate to move the cursor to

Returns:

Raises:

  • (ArgumentError)

    raised when the y coordinate is outside the valid lines range

  • (ArgumentError)

    raised when the x coordinate is outside the valid columns range



238
239
240
241
242
243
244
245
# File 'lib/graphina/graph/display.rb', line 238

def at(y, x)
  @lines_range.include?(y) or
    raise ArgumentError, "y #{y} out of lines range #@lines_range"
  @columns_range.include?(x) or
    raise ArgumentError, "x #{x} out of columns range #@columns_range"
  @y, @x = y, x
  self
end

#attribute!(a) ⇒ Object (private)

The attribute! method validates a given value against known ANSI color attributes and raises an error if invalid

This method serves as a validation wrapper around the attribute? method, ensuring that a provided value is a recognized ANSI color attribute. If the validation fails, it raises an ArgumentError with a descriptive message indicating which value was not accepted

Parameters:

  • a (Object)

    the value to validate as an ANSI color attribute

Returns:

  • (Object)

    returns the validated attribute if it passes validation

Raises:

  • (ArgumentError)

    raised when the provided value is not recognized as a valid ANSI color attribute



484
485
486
487
# File 'lib/graphina/graph/display.rb', line 484

def attribute!(a)
  attribute?(a) or
    raise ArgumentError, "#{a.inspect} is not a color attribute"
end

#attribute?(a) ⇒ Object? (private)

The attribute? method checks if a given value is a valid ANSI color attribute

This method validates whether the provided input corresponds to a recognized ANSI color attribute within the Term::ANSIColor::Attribute namespace

Parameters:

  • a (Object)

    the value to check against valid ANSI attributes

Returns:

  • (Object, nil)

    the attribute if valid, nil otherwise



466
467
468
# File 'lib/graphina/graph/display.rb', line 466

def attribute?(a)
  Term::ANSIColor::Attribute[a]
end

#bottomGraphina::Graph::Display

The bottom method moves the cursor position to the last line of the current column

This method sets the vertical cursor coordinate to the last line while preserving the current horizontal position. It is useful for positioning text at the bottom of the current column in terminal displays.

Returns:



314
315
316
# File 'lib/graphina/graph/display.rb', line 314

def bottom
  at(lines, x)
end

#centeredGraphina::Graph::Display

The centered method moves the cursor position to the center of the display grid

This method calculates the midpoint coordinates of the terminal display grid and positions the cursor at that location, making it convenient for centering text or other content within the available terminal space

Returns:



353
354
355
# File 'lib/graphina/graph/display.rb', line 353

def centered
  at(lines / 2, columns / 2)
end

#clearGraphina::Graph::Display

The clear method resets the display state by initializing cursor position, color attributes, and cell contents to their default values

This method prepares the terminal display for a fresh rendering by resetting internal tracking variables such as cursor coordinates, color settings, and text styles. It also reinitializes the two-dimensional array of Cell objects that represent the display grid, filling each cell with a space character and default styling attributes

Returns:



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/graphina/graph/display.rb', line 51

def clear
  @x        = 1
  @y        = 1
  @color    = @orig_color
  @on_color = @orig_on_color
  @styles   = []
  @cells    =
    Array.new(lines) {
      Array.new(columns) {
        Cell.new(' ', @color, @on_color, @styles)
      }
    }
  reset
end

#color(color) ⇒ Graphina::Graph::Display

The color method sets the text color attribute for subsequent character output

This method configures the color that will be applied to characters written to the display by updating the internal color tracking variable with a validated color attribute value

Parameters:

  • color (Integer)

    the color index to set for subsequent text output

Returns:

Raises:

  • (ArgumentError)

    raised when the provided color value is not a valid color attribute



400
401
402
403
# File 'lib/graphina/graph/display.rb', line 400

def color(color)
  @color = attribute!(color)
  self
end

#columnsInteger

The columns method returns the number of columns in the display

This method provides access to the horizontal dimension of the graphical display by returning the total number of columns available for rendering content

Returns:

  • (Integer)

    the number of columns (characters per line) in the display object



188
189
190
# File 'lib/graphina/graph/display.rb', line 188

def columns
  @columns_range.end
end

#dimensionsArray<Integer>

The dimensions method returns the size dimensions of the display grid

This method provides access to the display’s rectangular dimensions by returning an array containing the number of lines (height) and columns (width) that define the terminal display area

Returns:

  • (Array<Integer>)

    an array where the first element is the number of lines and the second element is the number of columns in the display grid



200
201
202
# File 'lib/graphina/graph/display.rb', line 200

def dimensions
  [ lines, columns ]
end

#each {|y, x, cell| ... } ⇒ Enumerator

The each method iterates over all cells in the display grid

This method provides an iterator interface for accessing each cell in the terminal display grid by yielding the row, column, and cell object for each position in the grid

Yields:

  • (y, x, cell)

    yields the row coordinate, column coordinate, and cell object

Returns:

  • (Enumerator)

    an enumerator that allows iteration over all cells in the grid



92
93
94
95
96
97
98
99
100
# File 'lib/graphina/graph/display.rb', line 92

def each(&block)
  Enumerator.new do |enum|
    @lines_range.each do |y|
      @columns_range.each do |x|
        enum.yield y, x, @cells[y - 1][x - 1]
      end
    end
  end.each(&block)
end

#getGraphina::Graph::Display::Cell

The get method retrieves the cell object at the current cursor position

This method accesses the internal two-dimensional array of Cell objects using the current vertical and horizontal cursor coordinates to return the specific cell that is currently pointed to by the cursor

Returns:



382
383
384
# File 'lib/graphina/graph/display.rb', line 382

def get
  @cells[@y - 1][@x - 1]
end

#inspectString

The inspect method returns a string representation of the display object that includes its class name along with the dimensions of the display grid

Returns:

  • (String)

    a formatted string containing the class name and display dimensions in the format “#<ClassName: columns×lines>”



147
148
149
# File 'lib/graphina/graph/display.rb', line 147

def inspect
  "#<#{self.class}: #{columns}×#{lines}>"
end

#leftGraphina::Graph::Display

The left method moves the cursor position to the first column of the current line

This method sets the horizontal cursor coordinate to the first column while preserving the current vertical position. It is useful for positioning text at the beginning of the current line in terminal displays

Returns:



327
328
329
# File 'lib/graphina/graph/display.rb', line 327

def left
  at(y, 1)
end

#linesInteger

The lines method returns the number of lines in the display

This method provides access to the vertical dimension of the graphical display by returning the total number of rows available for rendering content

Returns:

  • (Integer)

    the number of lines (rows) in the display object



176
177
178
# File 'lib/graphina/graph/display.rb', line 176

def lines
  @lines_range.end
end

#on_color(on_color) ⇒ Graphina::Graph::Display

The on_color method sets the background color attribute for subsequent character output

This method configures the background color that will be applied to characters written to the display by updating the internal on_color tracking variable with a validated color attribute value

Parameters:

  • on_color (Integer)

    the background color index to set for subsequent text output

Returns:

Raises:

  • (ArgumentError)

    raised when the provided color value is not a valid color attribute



420
421
422
423
# File 'lib/graphina/graph/display.rb', line 420

def on_color(on_color)
  @on_color = attribute!(on_color)
  self
end

#put(char) ⇒ Graphina::Graph::Display

The put method assigns a character to the current cursor position in the display grid

This method stores a character cell at the current vertical and horizontal coordinates within the terminal display grid. It validates that the input is a single character before assigning it, ensuring that only valid characters are placed in the grid.

Parameters:

  • char (String)

    the single character to be placed at the current cursor position

Returns:

Raises:

  • (ArgumentError)

    raised when the provided character is not a single character



260
261
262
263
264
265
# File 'lib/graphina/graph/display.rb', line 260

def put(char)
  char.size == 1 or
    raise ArgumentError, "#{char} is not single character"
  @cells[@y - 1][@x - 1] = Cell.new(char, @color, @on_color, @styles)
  self
end

#resetGraphina::Graph::Display

The reset method resets the display’s color and style attributes to their default values

This method reinitializes the internal color tracking variables to their default state, clearing any active styling and resetting the text color to white (15) and background color to black (0). It also clears all active text styles.

Returns:



76
77
78
79
80
81
# File 'lib/graphina/graph/display.rb', line 76

def reset
  @color    = @orig_color
  @on_color = @orig_on_color
  @styles   = []
  self
end

#rightGraphina::Graph::Display

The right method moves the cursor position to the last column of the current line

This method sets the horizontal cursor coordinate to the final column while maintaining the current vertical position. It is useful for positioning text at the end of the current line in terminal displays

Returns:



340
341
342
# File 'lib/graphina/graph/display.rb', line 340

def right
  at(y, columns)
end

#style?(s) ⇒ Boolean (private)

The style? method checks whether a given symbol is a valid text styling attribute

This method verifies if the provided symbol corresponds to one of the supported text styles that can be applied to terminal output, such as bold, italic, underline, and other formatting options

Parameters:

  • s (Symbol)

    the symbol to check against the list of valid styles

Returns:

  • (Boolean)

    true if the symbol is a recognized text style, false otherwise



438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/graphina/graph/display.rb', line 438

def style?(s)
  [
    :bold,
    :dark,
    :faint,
    :italic,
    :underline,
    :underscore,
    :blink,
    :rapid_blink,
    :reverse,
    :negative,
    :concealed,
    :conceal,
    :strikethrough,
  ].member?(s)
end

#styled(*s) ⇒ Graphina::Graph::Display

The styled method sets the text styles for subsequent character output

This method configures the styling attributes that will be applied to characters written to the display, such as bold, italic, underline, and other text formatting options. It validates that all provided style names are recognized before applying them.

Parameters:

  • s (Array<Symbol>)

    an array of style symbols to apply

Returns:

Raises:

  • (ArgumentError)

    raised when any of the provided style symbols is not recognized



216
217
218
219
220
221
222
# File 'lib/graphina/graph/display.rb', line 216

def styled(*s)
  if nope = s.find { !style?(_1) }
    raise ArgumentError, "#{nope} is not a style"
  end
  @styles = s
  self
end

#to_sString

The to_s method generates a string representation of the display by iterating over all cells and constructing a formatted terminal output with ANSI escape sequences for positioning and styling

Returns:

  • (String)

    a complete terminal display string with all cells rendered using their visual attributes and positioned according to their coordinates in the grid



135
136
137
138
139
# File 'lib/graphina/graph/display.rb', line 135

def to_s
  each.inject(ANSI.clear_screen)  do |s, (y, x, c)|
    s << ANSI.move_to(y, x) << c.to_s
  end
end

#topGraphina::Graph::Display

The top method moves the cursor position to the first line of the current column

This method sets the vertical cursor coordinate to the first line while preserving the current horizontal position It is useful for positioning text at the top of the current column in terminal displays

Returns:



301
302
303
# File 'lib/graphina/graph/display.rb', line 301

def top
  at(1, x)
end

#write(string) ⇒ Graphina::Graph::Display

The write method outputs a string character by character within the display grid

This method takes a string and writes it to the current cursor position in the terminal display, advancing the cursor position after each character is written. It handles line wrapping by stopping when reaching the end of the row.

Parameters:

  • string (String)

    the string to be written to the display

Returns:



279
280
281
282
283
284
285
286
287
288
289
# File 'lib/graphina/graph/display.rb', line 279

def write(string)
  string.each_char do |char|
    put(char)
    if x < columns - 1
      at(y, x + 1)
    else
      break
    end
  end
  self
end

#write_centered(string) ⇒ Graphina::Graph::Display

The write_centered method positions the cursor at the horizontal center of the display grid and writes a string there

This method calculates the starting column position needed to center the given string within the current display width, moves the cursor to that position, and then writes the string character by character. It is useful for creating centered text output in terminal displays.

Parameters:

  • string (String)

    the text string to be written and centered on the current line

Returns:



370
371
372
# File 'lib/graphina/graph/display.rb', line 370

def write_centered(string)
  at(@y, (columns - string.size) / 2).write(string)
end