Module: RubyTUI::ColorMode

Defined in:
lib/rubytui/color_mode.rb

Overview

Detects and manages terminal color capabilities.

Examples:

ColorMode.force(ColorMode::COLOR256)
ColorMode.downgrade(Color.rgb(255, 128, 0))  # => Color.indexed(214)

Constant Summary collapse

BASIC16 =

Basic 16-color ANSI palette.

:basic16
COLOR256 =

256-color indexed palette.

:color256
TRUECOLOR =

24-bit RGB truecolor.

:truecolor

Class Method Summary collapse

Class Method Details

.detect ⇒ Symbol

Detect terminal color capability from environment variables.

Returns TRUECOLOR when COLORTERM is truecolor or 24bit, TERM contains 24bit or truecolor, or TERM_PROGRAM is one of iterm.app, hyper, wezterm, alacritty, kitty; COLOR256 when TERM contains 256color or COLORTERM is 256; otherwise BASIC16. All comparisons are case-insensitive. The result is cached until reset!, and force overrides it.

Returns:

  • (Symbol) —

    the detected (or forced) color mode



28
29
30
31
32
# File 'lib/rubytui/color_mode.rb', line 28

def detect
  return @detected if defined?(@detected)

  @detected = detect_from_env
end

.downgrade(color, mode = detect) ⇒ Color?

Downgrade a Color to fit the current terminal capability.

TRUECOLOR (or an unrecognized mode) returns color unchanged. COLOR256 maps RGB colors to the nearest indexed color. BASIC16 maps RGB and indexed colors to the nearest named color. Colors that already fit the mode are returned unchanged.

Parameters:

  • color (Color, nil) —

    color to convert

  • mode (Symbol) (defaults to: detect) —

    target color mode (default: detect)

Returns:

  • (Color, nil) —

    the converted color, or nil if color is nil



62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rubytui/color_mode.rb', line 62

def downgrade(color, mode = detect)
  return color if color.nil?

  case mode
  when TRUECOLOR
    color  # no downgrade needed
  when COLOR256
    downgrade_to_256(color)
  when BASIC16
    downgrade_to_16(color)
  else
    color
  end
end

.force(mode) ⇒ Symbol

Force a specific color mode

Replaces the cached value returned by detect until reset!.

Parameters:

Returns:

  • (Symbol) —

    mode



48
49
50
# File 'lib/rubytui/color_mode.rb', line 48

def force(mode)
  @detected = mode
end

.reset! ⇒ void

This method returns an undefined value.

Reset cached detection (for testing)



37
38
39
# File 'lib/rubytui/color_mode.rb', line 37

def reset!
  remove_instance_variable(:@detected) if defined?(@detected)
end