#!/usr/bin/env perl
use warnings;
use strict;
use IPC::Open2;

my $proglist = `wmiir namespace|tr -d "\n"` . "/.proglist";
open2 my $procout, my $procin, "wimenu", "-c";

sub quote(_) {
    local ($_) = @_;
    return $_ unless m/[\[\](){}\$'^#~!&;*?|<>\s]/;
    s/'/''/g;
    "'$_'";
}

my $oldoffset;
sub update(&;$) {
    my ($choices, $offset) = @_;
    if(not defined $offset or $offset != $oldoffset) {
        $oldoffset = $offset || 0;
        print $procin $offset, "\n" if defined $offset;
        print $procin $choices->(), "\n\n";
    }
}

sub readout(@) {
    my ($mode, $expr, @rest) = @_;
    open(my $fd, $mode, $expr, @rest);
    join "\n", map {chomp; quote} <$fd>
}

update {readout "<", $proglist};

while(local $_ = <$procout>) {
    chomp;
    unless(<$procout>) {
        print;
        exit;
    }
    if(not /.*\s/) {
        update {readout "<", $proglist} 0;
    } else {
        my $offset = length $&;
        $_ = substr $_, $offset;
        my @args = m{(/|^)\.[^/]*$} && ("-A") || ();
        $offset += length $& if m{.*/};
        s,/.*?$,,;
        update {readout "-|", "ls", @args, $_ || "."} $offset;
    }
}

# vim:se sts=4 sw=4 et:

