Class: DynamicCursesInput::ColorWindow

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamic_curses_input/color_window.rb

Overview

Class for creating a colored window

Instance Method Summary collapse

Constructor Details

#initialize(echo, x, y) ⇒ ColorWindow

Initialize instance variables and setup curses



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/dynamic_curses_input/color_window.rb', line 12

def initialize(echo, x, y) # rubocop:disable Metrics/MethodLength, Naming/MethodParameterName
  @echo = echo # Determines whether input should be echoed to the screen
  setup_curses_color # Setup curses
  @x = x
  @y = y
  # Define color pairs
  Curses.init_pair(1, Curses::COLOR_BLACK, Curses::COLOR_BLACK)
  Curses.init_pair(2, Curses::COLOR_BLUE, Curses::COLOR_BLACK)
  Curses.init_pair(3, Curses::COLOR_GREEN, Curses::COLOR_BLACK)
  Curses.init_pair(4, Curses::COLOR_CYAN, Curses::COLOR_BLACK)
  Curses.init_pair(5, Curses::COLOR_RED, Curses::COLOR_BLACK)
  Curses.init_pair(6, Curses::COLOR_MAGENTA, Curses::COLOR_BLACK)
  Curses.init_pair(7, Curses::COLOR_YELLOW, Curses::COLOR_BLACK) # Brown is usually represented as yellow
  Curses.init_pair(8, Curses::COLOR_WHITE, Curses::COLOR_BLACK)
end

Instance Method Details

#add_color_window(color, text, x, y, input: nil, echo: true) ⇒ Object

Method that adds colored text to the window



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/dynamic_curses_input/color_window.rb', line 29

def add_color_window(color, text, x, y, input: nil, echo: true) # rubocop:disable Metrics/MethodLength, Metrics/ParameterLists, Naming/MethodParameterName
  # Map color names to color pair numbers
  color_map = {
    'black' => 1,
    'blue' => 2,
    'green' => 3,
    'cyan' => 4,
    'red' => 5,
    'magenta' => 6,
    'brown' => 7, # Brown is usually represented as yellow in terminal colors
    'white' => 8
  }

  # Get the color pair number for the specified color
  color_pair = color_map[color.downcase]

  # Set the cursor position if both x and y are specified
  if x && y
    set_position(y, x)
  elsif x.nil? && y.nil?
    # If both x and y are not specified, raise an ArgumentError
    raise ArgumentError, 'Both x and y coordinates must be specified for printing the color window.'
  end

  # Print the text in the specified color
  Curses.attron(Curses.color_pair(color_pair))
  Curses.addstr(text)
  Curses.attroff(Curses.color_pair(color_pair))

  # If an input is specified, take input from the user
  InputHandler.catch_input(echo) if input

  Curses.refresh
end