module AnsiToIrc
Constants
- ANSI_PATTERN
- FG_256_PATTERN
- FG_RGB_PATTERN
- RESET_PATTERN
Public Instance Methods
Source
# File lib/ansi_to_irc.rb, line 84 def ansi216_rgb(index) idx = index - 16 r = (idx / 36) * 51 g = ((idx % 36) / 6) * 51 b = (idx % 6) * 51 [r, g, b] end
Source
# File lib/ansi_to_irc.rb, line 70 def ansi256_to_extended(index) idx = index.to_i.clamp(0, 255) if idx < 16 idx elsif idx < 232 r, g, b = ansi216_rgb(idx) nearest_code(r, g, b) else grey = 8 + (idx - 232) * 10 nearest_code(grey, grey, grey) end end
Source
# File lib/ansi_to_irc.rb, line 18 def convert(text) value = text.to_s return value if value.empty? out = +"" pos = 0 value.scan(ANSI_PATTERN) do match = Regexp.last_match out << value[pos...match.begin(0)] out << irc_code_for_sequence(match[0]) pos = match.end(0) end out << value[pos..] out end
Source
# File lib/ansi_to_irc.rb, line 53 def irc_code_for_sequence(seq) if (match = seq.match(FG_256_PATTERN)) code = ansi256_to_extended(match[1].to_i) return IrcFormat.color(code) end if (match = seq.match(FG_RGB_PATTERN)) code = nearest_code(match[1].to_i, match[2].to_i, match[3].to_i) return IrcFormat.color(code) end return IrcFormat::RESET if seq.match?(RESET_PATTERN) "" end
Source
# File lib/ansi_to_irc.rb, line 102 def load_extended_colors! require_relative "irc_extended_colors" unless defined?(IrcExtendedColors) end
Source
# File lib/ansi_to_irc.rb, line 38 def nearest_code(r, g, b) load_extended_colors! hex = format("%02x%02x%02x", r.to_i.clamp(0, 255), g.to_i.clamp(0, 255), b.to_i.clamp(0, 255)) best_code = 16 best_dist = Float::INFINITY IrcExtendedColors::RGB.each do |code, rgb_hex| dist = rgb_distance(hex, rgb_hex) next unless dist < best_dist best_dist = dist best_code = code end best_code end
Source
# File lib/ansi_to_irc.rb, line 93 def rgb_distance(hex_a, hex_b) a = hex_a.to_s.ljust(6, "0")[0, 6] b = hex_b.to_s.ljust(6, "0")[0, 6] ar, ag, ab = [a[0, 2], a[2, 2], a[4, 2]].map { |x| x.to_i(16) } br, bg, bb = [b[0, 2], b[2, 2], b[4, 2]].map { |x| x.to_i(16) } ((ar - br)**2) + ((ag - bg)**2) + ((ab - bb)**2) end
Source
# File lib/ansi_to_irc.rb, line 34 def strip_irc_codes(text) text.to_s.gsub(/\x03(?:\d{2}(?:,\d{2})?)?/, "") end