#!/usr/bin/perl
# Use, modification and redistribution of this software is hereby granted, 
# provided that this entire copyright notice is included on any copies of 
# this software and applications and derivations thereof.
# 
# This software is provided on an "as is" basis, without warranty of any
# kind, either expressed or implied, as to any matter including, but not
# limited to warranty of fitness of purpose, or merchantability, or
# results obtained from use of this software.
#
# (C) 2003-2004 Mark A. Hillebrand <mah at cs.uni-sb.de>
#
# TODO should each line padded to line-width because of background coloring (cf. mutt)?
# TODO ISO-8859-1 output option
# TODO add support for non-@style formatting
# Setup resource strings for xterm as follows:
# echo 'XTerm*printerCommand: /path/to/xterm-html-printer' | xrdb -merge
# echo 'XTerm*printAttributes: 2' | xrdb -merge
use File::Temp qw(tempfile);
use HTML::Entities;
# TODO produce this dynamically from "appres XTerm | grep -i 'color[0-9]\+'" and rgb.txt
my %FG_COLORS = (
	# these colors come from /usr/X11/lib/X11/app-defaults/XTerm-color and
	# were transformed using /usr/X11/lib/X11/rgb.txt
	0 => '#000000',
	1 => '#cd0000',
	2 => '#00cd00',
	3 => '#cdcd00',
	4 => '#1e90ff',
	5 => '#cd00cd',
	6 => '#00cdcd',
	7 => '#e5e5e5',
);
# TODO this is hack, try to obtain these G[0123] charsets from ISO 2022
my %LINEDRAWINGS = (
	l => '┌',
	q => '─',
	k => '┐',
	x => '│',
	m => '└',
	j => '┘',
);
# TODO number sequentially
my ($fh, $filename) = tempfile("xterm-XXXXXX", SUFFIX => '.html', DIR => $ENV{HOME} );

# TODO add switch for filtering capabilities instead of tempfile-naming
#use FileHandle;
#$fh = new FileHandle;
#$fh->open(">&STDOUT");

my $background = '#FFFFFF';
my $foreground = '#000000';

# TODO add an option for the background color, cannot be detected
print $fh qq[<html>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<body>\n<table style="border-style:solid"><tr><td style="background:$background"><pre>\n];
# note: xterm seems to supply unicode

sub linedraw {
	my $s = shift;
	$s =~ s/(\e\[.*?[a-zA-Z]|.)/
		if( substr($1,0,1) eq "\e" ) {
			$1;
		} else {
			$LINEDRAWINGS{$1};
		}
	/gex;
	return $s;
}
while( <> ) {
	s/^\e#5//;	# delete common line start
	s/\r$//;
	chomp;
	# substitute those nasty line drawing characters to unicode
	s/\016(.*?)\017/linedraw($1)/ge;
	
	#@attr = ();	# auto-reset at EOL
	#s/\r$//;	# delete common line end
	# print encode_entities($in);
	for( m/(\e\[.*?[a-zA-Z]|[^\e]*)/g ) {
		if( (substr $_, 0, 1) eq "\e" ) {
			if( (substr $_, -1) eq 'm' ) {
				# set attributes
				#warn substr($_,2,length($_)-3);
				for $a (split ';', substr($_,2,length($_)-3)) {
					#warn $a;
					if( $a == 0 ) {	# reset
						@attr = ();	# clear attribute array
					} elsif( $a == 1 ) {	# bold
						push @attr, "font-weight:bold";
					} elsif( substr($a,0,1) eq '3' ) {
						die "?color not defined" if not exists $FG_COLORS{substr($a,1,1)};
						push @attr, "color:$FG_COLORS{substr($a,1,1)}";
					} elsif( substr($a,0,1) eq '4' ) {
						if( length $a == 1 ) {
							# underline
							push @attr, "font-decoration:underline";
						} else {
							die "?color not defined" if not exists $FG_COLORS{substr($a,1,1)};
							push @attr, "background:$FG_COLORS{substr($a,1,1)}";
						}
					} elsif( substr($a,0,1) == 7 ) { # invert
						print '<!-- warning: inversion with non-empty attribute stack-->' if $#attr > 0;
						push @attr, "background:$foreground";
						push @attr, "color:$background";
					} else {
					}
				}

			}
		} else {
			# (xterm seems to supply unicode)
			if( @attr ) {
				print $fh 
					'<font style="' .
					join('; ', @attr) .
					'">' .
					encode_entities($_,'<>&"') .
					'</font>';
			} else {
				print $fh encode_entities($_,'<>&"');
			}
		}
	}
	print $fh "\n";
}
print $fh "</pre></td></tr></table>\n</body>\n</html>\n";
