| 1 | package IRC::FromANSI::Tiny; | ||
| 2 | # ABSTRACT: Convert ANSI color codes to IRC | ||
| 3 | our $AUTHORITY = 'cpan:ARODLAND'; # AUTHORITY | ||
| 4 | our $VERSION = '0.01'; # VERSION | ||
| 5 | |||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | use Parse::ANSIColor::Tiny; | ||
| 9 | |||
| 10 | my %irccolors = ( | ||
| 11 | black => 1, | ||
| 12 | red => 5, | ||
| 13 | green => 3, | ||
| 14 | yellow => 7, | ||
| 15 | blue => 2, | ||
| 16 | magenta => 6, | ||
| 17 | cyan => 10, | ||
| 18 | white => 14, | ||
| 19 | bright_black => 15, | ||
| 20 | bright_red => 4, | ||
| 21 | bright_green => 9, | ||
| 22 | bright_yellow => 8, | ||
| 23 | bright_blue => 12, | ||
| 24 | bright_magenta => 13, | ||
| 25 | bright_cyan => 11, | ||
| 26 | bright_white => 0, | ||
| 27 | ); | ||
| 28 | |||
| 29 | sub convert { | ||
| 30 | my ($text) = @_; | ||
| 31 | my $ret = ""; | ||
| 32 | |||
| 33 | my $ansi = Parse::ANSIColor::Tiny->new; | ||
| 34 | my $data = $ansi->parse($text); | ||
| 35 | my (%foregrounds, %backgrounds); | ||
| 36 | $foregrounds{$_} = 1 for $ansi->foreground_colors; | ||
| 37 | $backgrounds{$_} = 1 for $ansi->background_colors; | ||
| 38 | my ($foreground, $background, $underline, $bold) = (undef, undef, 0, 0); | ||
| 39 | |||
| 40 | for my $chunk (@$data) { | ||
| 41 | my ($attrs, $text) = @$chunk; | ||
| 42 | my ($fg) = grep $foregrounds{$_}, @$attrs; | ||
| 43 | my ($bg) = grep $backgrounds{$_}, @$attrs; | ||
| 44 | my $bb = (grep $_ eq 'bold', @$attrs) ? 1 : 0; | ||
| 45 | my $u = (grep $_ eq 'underline', @$attrs) ? 1 : 0; | ||
| 46 | |||
| 47 | my $set_color; | ||
| 48 | if ($fg) { | ||
| 49 | $foreground = ($b ? 'bright_' : '') . $fg; | ||
| 50 | $set_color = "\cC$irccolors{$foreground}"; | ||
| 51 | $bb = 0; | ||
| 52 | } | ||
| 53 | if ($bg) { | ||
| 54 | $background = $bg; | ||
| 55 | $set_color = "\cC" . $irccolors{$foreground || "black"} . ",$irccolors{$background}"; | ||
| 56 | } | ||
| 57 | if (!$fg && !$bg && ($foreground || $background)) { | ||
| 58 | undef $foreground; | ||
| 59 | undef $background; | ||
| 60 | if ($text =~ /^\d/) { | ||
| 61 | # Use "reset all" to clear color to avoid a following number | ||
| 62 | # being interpreted as a color code | ||
| 63 | $set_color = "\cO"; | ||
| 64 | undef $underline; | ||
| 65 | undef $bold; | ||
| 66 | } else { | ||
| 67 | $set_color = "\cC"; | ||
| 68 | } | ||
| 69 | } | ||
| 70 | $ret .= $set_color if length $set_color; | ||
| 71 | if ($bb ^ $bold) { | ||
| 72 | $bold = $bb; | ||
| 73 | $ret .= "\cB"; | ||
| 74 | } | ||
| 75 | if ($u ^ $underline) { | ||
| 76 | $underline = $u; | ||
| 77 | $ret .= "\c_"; | ||
| 78 | } | ||
| 79 | $ret .= $text; | ||
| 80 | } | ||
| 81 | return $ret; | ||
| 82 | } | ||
| 83 | |||
| 84 | 1; | ||
| 85 | |||
| 86 | __END__ |