#!/usr/bin/perl
# xls: an XMLterm wrapper for the UNIX "ls" command
# Usage: xls  [-c|--cols] [-h|help] [-t||--text] <files>

use Cwd;
use Getopt::Long;

Getopt::Long::config('bundling');

&GetOptions("cols|c=i", "help|h!", "text|t!");

if ($opt_help) {
    print "Usage: xls [-c|--cols] [-t||--text] [<files>]\n";
    exit;
}

# Icon details
#my $imgdir="chrome://xmlterm/skin/default/images"
my $imgdir = "file:///usr/share/pixmaps/mc";

my %img;
($img{'directory'}, $img{'executable'}, $img{'plainfile'}, $img{'urlfile'}) =
    ('i-directory.png', 'i-executable.png', 'i-regular.png', 'i-regular.png');

my $ncols = 5;
$ncols = $opt_cols if ($opt_cols);

my $dir = cwd();
my $rowimg = "";
my $rowtxt = "";
my $nfile = 0;

my $filelist;

if (@ARGV) {
    if ((@ARGV == 1) && (-d $ARGV[0])) {
        @filelist = glob("$ARGV[0]/*");    # specified directory
    } else {
        @filelist = @ARGV;                 # specified file(s)
    }
} else {
    @filelist = glob("*");                 # all files in current directory
}

my $cookie = $ENV{LTERM_COOKIE};           # XMLTerm cookie
print "\e{S$cookie\a";                     # HTML stream escape sequence
print "<TABLE FRAME=none BORDER=0>";
print "<COLGROUP COLSPAN=$ncols WIDTH=1*>";

foreach $file (@filelist) {        # for each file in the list
    $file =~ m%\A(.*?) (\.[^/.]*)?\Z%x # Deconstruct file name
        or die "xls: Internal error; unable to deconstruct file name\n";

    my ($filename, $extension) = ($1, $2);

    my ($filetype, $fileimg, $sendcmd, $sendtxt1, $sendtxt2);

    $sendtxt1  = $file;
    if ($dir eq "/") {
        $sendtxt2  = "/";
    } else {
        $sendtxt2  = "$dir/";
    }

    if (-d $file) {                     # directory
        $filetype = "directory";
        $fileimg  = "$imgdir/$img{$filetype}";
        $sendcmd  = "cdxls";

    } elsif (-x $file) {                # executable
        $filetype = "executable";
        $fileimg  = "$imgdir/$img{$filetype}";
        $sendcmd  = "exec";

    } elsif (($extension eq ".gif") ||
             ($extension eq ".png") ||
             ($extension eq ".jpg")) {  # image
        $filetype = "imagefile";
        $fileimg  = "file://$dir/$file";
        $sendcmd  = "xcat";

    } elsif ($extension eq ".ps") {     # postscript
        $filetype = "plainfile";
        $fileimg  = "$imgdir/$img{$filetype}";
        $sendcmd  = "xcat";

    } elsif ($extension eq ".url") {  # URL
        open INFILE, $file or next;
        $_ = <INFILE>;
        close INFILE;

        # Extract content URL and the icon URL (if any)
        my @urlvals;
        my $nurl = 0;
        while ( m%\b                              # URL word boundary
                 (http|file|mailto):              # protocol
                 (?=/)                            # lookahead
                 (?://                            # slashpair
                   (?:([\w.]+)@)?                 # username
                   ([\w\-]+(?:\.[\w\-]+)*)?       # host
                   (?::(\d+))?                    # port
                 )?
                 (/|/[^/\s]\S*?)?                 # pathname
                 (?=>|\"|\'|\s|[.,!](?:\s|\Z)|\Z) # URL terminator (look ahead)
                 %x ) {
            $urlvals[$nurl] = $&;
            s%$&%%;
            $nurl++;
        }
        s%\A\s*(\S.*?)?\s*\Z%$1%;                 # trim leading/trailing space

        if ($nurl >= 1) {
            my $urldesc = $_;
            my $urlstr = $urlvals[0];
            $urldesc = $urlstr if !$urldesc;

            $sendcmd = "textlink";               # override send command
            $sendtxt1 = "$urlstr";
            $sendtxt2 = "$urlstr";
            
            $filetype = "urlfile";
            if ($nurl >= 2) {
                $fileimg  = "$urlvals[1]";       # use icon URL
            } else {
                $fileimg  = "$imgdir/$img{$filetype}";  #default URL icon
            }
        } else {
            $filetype = "plainfile";
            $fileimg  = "$imgdir/$img{$filetype}";
            $sendcmd  = "xcat";
        }

    } else {                            # plain file
        $filetype = "plainfile";
        $fileimg  = "$imgdir/$img{$filetype}";
        $sendcmd  = "xcat";
    }

    my @comps = split(m./.,$file);
    my $tail = $comps[$#comps];            # file name

    my $clickcmd =
     qq%onClick="return HandleEvent(event,'click','$sendcmd',-\#,'$sendtxt1','$sendtxt2')"%;

    $rowimg .= "<TD><IMG HEIGHT=48 WIDTH=48 SRC='$fileimg' $clickcmd>";
    $rowtxt .= "<TD><SPAN CLASS='$filetype' $clickcmd>";
    $rowtxt .= "$tail</SPAN>";
    $nfile++;

    if (($nfile % $ncols) == 0) {       # print complete table row
        print "<TR CLASS='icons'>$rowimg" unless $opt_text;
        print "<TR>$rowtxt";
        $rowimg = "";
        $rowtxt = "";
    }

}

if ($rowtxt) {
    print "<TR CLASS='icons'>$rowimg" unless $opt_text;
    print "<TR>$rowtxt";
}

print "</TABLE>";
print "<div class='beginner'>";
print "Double-click on file/directory name to execute file/open directory.";
print "<span class='noicons'><br>Set <b>Icons</b> setting to <em>on</em> to enable icon display.</span>";
print "<span class='icons'><br>Set <b>Icons</b> setting to <em>off</em> to disable icon display.</span>";
print "</div>";
print "\000";                           # Terminate HTML stream

