Class: Hackmac::Graph::Display

Inherits:
Object
  • Object
show all
Defined in:
lib/hackmac/graph/display.rb,
lib/hackmac/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 = Hackmac::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) ⇒ 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



30
31
32
33
34
# File 'lib/hackmac/graph/display.rb', line 30

def initialize(lines, columns)
  @lines_range   = 1..lines
  @columns_range = 1..columns
  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



154
155
156
# File 'lib/hackmac/graph/display.rb', line 154

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



163
164
165
# File 'lib/hackmac/graph/display.rb', line 163

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



112
113
114
115
116
117
118
119
120
121
122
# File 'lib/hackmac/graph/display.rb', line 112

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) ⇒ Hackmac::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



234
235
236
237
238
239
240
241
# File 'lib/hackmac/graph/display.rb', line 234

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



480
481
482
483
# File 'lib/hackmac/graph/display.rb', line 480

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



462
463
464
# File 'lib/hackmac/graph/display.rb', line 462

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

#bottomHackmac::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:



310
311
312
# File 'lib/hackmac/graph/display.rb', line 310

def bottom
  at(lines, x)
end

#centeredHackmac::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:



349
350
351
# File 'lib/hackmac/graph/display.rb', line 349

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

#clearHackmac::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:



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/hackmac/graph/display.rb', line 47

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

#color(color) ⇒ Hackmac::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



396
397
398
399
# File 'lib/hackmac/graph/display.rb', line 396

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



184
185
186
# File 'lib/hackmac/graph/display.rb', line 184

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



196
197
198
# File 'lib/hackmac/graph/display.rb', line 196

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



88
89
90
91
92
93
94
95
96
# File 'lib/hackmac/graph/display.rb', line 88

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

#getHackmac::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:



378
379
380
# File 'lib/hackmac/graph/display.rb', line 378

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>”



143
144
145
# File 'lib/hackmac/graph/display.rb', line 143

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

#leftHackmac::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:



323
324
325
# File 'lib/hackmac/graph/display.rb', line 323

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



172
173
174
# File 'lib/hackmac/graph/display.rb', line 172

def lines
  @lines_range.end
end

#on_color(on_color) ⇒ Hackmac::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



416
417
418
419
# File 'lib/hackmac/graph/display.rb', line 416

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

#put(char) ⇒ Hackmac::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



256
257
258
259
260
261
# File 'lib/hackmac/graph/display.rb', line 256

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

#resetHackmac::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:



72
73
74
75
76
77
# File 'lib/hackmac/graph/display.rb', line 72

def reset
  @color    = 15
  @on_color = 0
  @styles   = []
  self
end

#rightHackmac::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:



336
337
338
# File 'lib/hackmac/graph/display.rb', line 336

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



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/hackmac/graph/display.rb', line 434

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

#styled(*s) ⇒ Hackmac::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



212
213
214
215
216
217
218
# File 'lib/hackmac/graph/display.rb', line 212

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



131
132
133
134
135
# File 'lib/hackmac/graph/display.rb', line 131

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

#topHackmac::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:



297
298
299
# File 'lib/hackmac/graph/display.rb', line 297

def top
  at(1, x)
end

#write(string) ⇒ Hackmac::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:



275
276
277
278
279
280
281
282
283
284
285
# File 'lib/hackmac/graph/display.rb', line 275

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) ⇒ Hackmac::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:



366
367
368
# File 'lib/hackmac/graph/display.rb', line 366

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