#!/usr/bin/perl -w

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# Filter this script to pod2man to get a man page:
#   pod2man -c "FVWM Module" FvwmPerl | nroff -man | less -e

require 5.004;
use strict;

BEGIN {
	use vars qw($prefix $datadir);
	$prefix = "/usr/X11R6";
	$datadir = "${prefix}/share";
}

use lib "${datadir}/fvwm/perllib";
use FVWM::Module;
use General::FileSystem "-quiet";
use General::Parse;
use Getopt::Long;

# ----------------------------------------------------------------------------
# variables

my $lineToEval = undef;
my $fileToLoad = undef;
my $preprocess = 0;
# whether continue running after --eval, --load or --preprocess, default is no
my $stay = 0;
my $nolock = 0;
my $debug = 0;
my $detached = 0;
my $ppArgs = {};
my $ppFileCount = 0;

my $preprocessOptions = {
	"c|command"    => \$ppArgs->{command},
	"q|quote=s"    => \$ppArgs->{quote},
	"nosend"       => \$ppArgs->{nosend},
	"noremove"     => \$ppArgs->{noremove},
};

my $options = {
	"e|eval=s"     => \$lineToEval,
	"l|load=s"     => \$fileToLoad,
	"p|preprocess" => \$preprocess,
	"s|stay!"      => \$stay,
	"nolock"       => \$nolock,
	"debug=i"      => \$debug,
	%$preprocessOptions,
};

my $module = new FVWM::Module(
	Name          => "FvwmPerl",
	Mask          => M_STRING,
	SyncMask      => M_STRING,
	EnableOptions => $options,
	EnableAlias   => 1,
	Debug         => \$debug,  # $debug is not really ready yet
);

sub printActionError ($$) {
	my $action = shift;
	my $errMsg = shift;
	return if $errMsg =~ /^!/;
	$errMsg =~ s/\s+$//s;
	print STDERR "[", $module->name, "][$action]: $errMsg\n";
}

# ----------------------------------------------------------------------------
# prepare the environment that may be used in the sent perl commands

my $version = "2.5.3";

my ($a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $k, $l, $m, $n, $o, $p)
	= ("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
my (@a, @b, @c, @d, @e, @f, @g, @h, @i, @j, @k, @l, @m, @n, @o, @p);
my (%a, %b, %c, %d, %e, %f, %g, %h, %i, %j, %k, %l, %m, %n, %o, %p);

sub command ($) {
	my $command = shift;
	$module->send($command);
}

sub stop () {
	# send a signal to the event loop to terminate the module
	$module->terminate;
}

sub skip () {
	# send a signal to the event loop to terminate the current event handler
	$module->terminate("continue");
}

sub unlock () {
	# enable asynchronous evaluation
	$module->sendUnlock;
}

sub detach () {
	my $pid = fork();

	# main process skips the remaining evaluation
	skip() unless defined $pid && $pid == 0;

	# child process will exit after evaluation
	$detached = 1;
}

sub load ($) {
	my $filename = shift;
	my $contents = loadFile($filename);
	if (!defined $contents) {
		printActionError("load", "Can't find and read $filename: $!");
		return;
	}
	eval $$contents;
	printActionError("load", "$@") if $@;
}

sub doEval ($) {
	my $string = shift;
	eval $string;
	printActionError("eval", "$@") if $@;
	if ($detached) {
		# let's hope we should not clean-up anything
		exit(0);
	}
}

sub preprocessDirectives ($;$) {
	my $textRef = shift;
	my $depth = shift || 0;

	my $quote = $PreprocessNamespace::PPP_QUOTE1;
	my $processedText = "";

	my $errorSub = sub ($) {
		printActionError("preprocess", "$_[0], preprocessing failed");
	};
	my ($start, $directive, $params, $end);

	while ($$textRef =~ m{\A(.*?)^$quote(\w+)[ \t]*(.*?)\n(.*)\z}ms) {
		($start, $directive, $params, $end) = ($1, $2, $3, $4);
		$$textRef = "";
		#print "\t$depth $directive $params\n";

		if (eqi($directive, "End")) {
			if ($depth == 0) {
				$errorSub->("Unexpected ${quote}End");
				return undef;
			}
			$$textRef = $processedText . $start;
			return $end;
		}

		my $subtext = $end;

		if (eqi($directive, "Repeat")) {
			my $count = getToken($params);
			unless (defined $count && $count =~ /^\d+$/) {
				$errorSub->("Usage: ${quote}Repeat count");
				return undef;
			}
			$end = &preprocessDirectives(\$subtext, $depth + 1);
			return undef unless defined $end;
			$start .= $subtext x $count;
			next;
		}
		my $prefix = undef;
		if (eqi($directive, "ModuleConfig")) {
			my ($moduleName, $destroy) = getTokens($params, 2);
			unless (defined $moduleName) {
				$errorSub->("Usage: ${quote}ModuleConfig module-name");
				return undef;
			}
			if (defined $destroy && eqi($destroy, "destroy")) {
				$start .= "DestroyModuleConfig $moduleName: *\n";
			};
			$prefix = "*$moduleName: ";
		}
		if (defined $prefix || eqi($directive, "Prefix")) {
			$prefix = getToken($params) unless defined $prefix;
			unless (defined $prefix) {
				$errorSub->("Usage: ${quote}Prefix prefix");
				return undef;
			}
			$end = &preprocessDirectives(\$subtext, $depth + 1);
			return undef unless defined $end;
			foreach (split(/\n/s, $subtext)) {
				$start .= "$prefix$_\n" unless /^\s*$/;
			}
			next;
		}
	} continue {
		$processedText .= $start;
		$$textRef = $end;
	}

	if ($depth == 0) {
		$$textRef = $processedText . $$textRef if $processedText ne "";
		return "";
	}
	$errorSub->("No corresponding ${quote}End found");
	return undef;
}

sub preprocess ($;$) {
	my $args = shift;
	my $data = shift;

	unlock();

	my $depth = $args->{depth};
	$depth ||= 0;
	if ($depth > 20) {
		printActionError("preprocess", "Too deep include depth=$depth");
		return;
	}

	my $nosend   = $args->{nosend};
	my $noremove = $args->{noremove};
	my $command  = $args->{command};
	my $quote    = $args->{quote} || '%';
	my ($quote1, $quote2) = split(//, $quote, 2);
	$quote2 ||= $quote1;

	my $textRef = $command? \$data: loadFile($data);
	unless (defined $textRef) {
		printActionError("preprocess", "No file to preprocess ($data)");
		return;
	}

	# there should be another way without running external programs
	my @dimentions = `xdpyinfo | grep dimensions` =~ /(\d+)x(\d+)/;

	{
		package PreprocessNamespace;
		no strict "vars";
		# OR-ing is a work around for "used once" warning

		$PPP_DEPTH    = $depth;
		$PPP_QUOTE    = $quote;
		$PPP_QUOTE1   = $quote1;
		$PPP_QUOTE2   = $PPP_QUOTE2 || $quote2;
		$PPP_NOSEND   = $nosend;
		$PPP_NOREMOVE = $noremove;
		$USER    = $USER    || $ENV{USER};
		$DISPLAY = $DISPLAY || $ENV{DISPLAY};
		$WIDTH   = $WIDTH   || $dimentions[0];
		$HEIGHT  = $HEIGHT  || $dimentions[1];
		$FVWM_VERSION = $FVWM_VERSION || $version;
		$FVWM_MODULEDIR = $FVWM_MODULEDIR || $ENV{FVWM_MODULEDIR};
		$FVWM_DATADIR = $FVWM_DATADIR || $module->siteDataDir;
		$FVWM_USERDIR = $FVWM_USERDIR || $module->userDataDir;
	}

	# perl code substitution first
	$$textRef =~ s/\Q$quote1\E { ( .*? ) } \Q$quote2\E/
		my $result = eval "
			no strict;
			package PreprocessNamespace;
			$1
		";
		if ($@) {
			printActionError("preprocess", $@);
			$result = "";
		}
		$result;
	/sgex;

	# line based directives
	preprocessDirectives($textRef);

	my $tempFileName = $module->userDataDir . "/.FvwmPerl-preprocess-$$";
	$tempFileName .= "-" . (++$ppFileCount);
	saveFile($tempFileName, $textRef);

	unless ($nosend) {
		$module->send("Read $tempFileName");
		$module->send("Exec rm -f '$tempFileName'")
			unless $noremove;
	}
}

sub PreprocessNamespace::include ($) {
	my $file = shift;
	::preprocess({
		depth    => $PreprocessNamespace::PPP_DEPTH + 1,
		quote    => $PreprocessNamespace::PPP_QUOTE,
		nosend   => $PreprocessNamespace::PPP_NOSEND,
		noremove => $PreprocessNamespace::PPP_NOREMOVE,
	}, $file);
	return "";
}

# ----------------------------------------------------------------------------
# event handlers

sub processMessage ($$$$$$) {
	my $self = $_[0];
	my $string = $_[5];

	$string =~ s/^\s+//;
	return if $string eq "";
	my ($action, $rest) = split(/\s+/, $string, 2);
	$action = lc($action);

	if ($action eq "eval") {
		return unless defined $rest;
		doEval($rest);
	}

	elsif ($action eq "load") {
		return unless defined $rest;
		load(getToken($rest));
	}

	elsif ($action eq "preprocess") {
		$ppArgs = {};
		@ARGV = getTokens($rest);
		GetOptions(%$preprocessOptions) || return;

		preprocess($ppArgs, join(" ", @ARGV));
	}

	elsif ($action eq "stop") {
		stop();
	}

	elsif ($action eq "dump") {
		# will dump non-void variables in the future
	}

	else {
		printActionError("processMessage", "Unknown action ($action)");
	}
}

$module->addHandler(M_STRING, \&processMessage);

# ----------------------------------------------------------------------------
# execution

# unlock fvwm earlier if requested
$module->sendReady if $nolock;

if (defined $lineToEval) {
	doEval($lineToEval);
	exit(0) unless $stay;
}

if (defined $fileToLoad) {
	load($fileToLoad);
	exit(0) unless $stay;
}

if ($preprocess) {
	preprocess($ppArgs, join(" ", @ARGV));
	exit(0) unless $stay;
}

$module->eventLoop;

__END__

# ----------------------------------------------------------------------------
# man page

=head1 NAME

FvwmPerl - the FVWM perl manipulator

=head1 SYNOPSIS

FvwmPerl is spawned by fvwm(1), so no command line invocation will work.

=head1 DESCRIPTION

This module is intended to extend fvwm commands with the perl scripting
power.  It enables to embed perl expressions in the fvwmrc files and
construct fvwm commands.

=head1 INVOCATION

FvwmPerl may be invoked from a fvwmrc file.  If you want to invoke
the unique and persistent instanse of FvwmPerl, it is suggested to
do this from the I<StartFunction>.  Calling it from the top is also
possible, but has several issues not discussed here.

    AddToFunc StartFunction I Module FvwmPerl

There are several command line switches:

B<FvwmPerl>
[ B<--eval> line ]
[ B<--load> file ]
[ B<--preprocess> [ B<--quote> char ] [ B<--command> ]
[ B<--nosend> ] [ B<--noremove> ] [ line | file ] ]
[ B<--stay> ] [ --nolock ]
[ alias ]

Long switches may be abbreviated to short one-letter switches.

B<-e>|B<--eval> line - evaluate the given perl code

B<-l>|B<--load> file - evaluate perl code in the given file

B<-p>|B<--preprocess> file - preprocess the given fvwmrc file

B<-c>|B<--command> line - an FVWM command to be preprocessed instead of file

B<-q>|B<--quote> char - changes the default '%' quote

B<--nosend> - do not send the preprocessed file to I<fvwm> for B<Read>ing,
the default is send. Useful for preprocessing non fvwmrc files.

B<--noremove> - do not remove the preprocessed file after sending
it to I<fvwm> for B<Read>ing, the default is remove. Useful for debugging.

B<-s>|B<--stay> - continues an execution after B<--eval>, B<--load> or
B<--preprocess> are processed.  By default, the module is not persistent
in this case, i.e. B<--nostay> is assumed.

B<--nolock> - when one of the 3 action options is given, this option causes
unlocking I<fvwm> immediately. By default the requested action is executed
synchronously; this only makes difference when invoked like:

  ModuleSynchronous FvwmPerl --preprocess someconfig.ppp

If B<--nolock> is added here, B<ModuleSynchronous> returns immediately.
Note that B<Module> returns immediately regardless of this option.

=head1 ACTIONS

There are several actions that FvwmPerl may perform:

=over 4

=item B<eval> perl-code

Evaluate a line of perl code.

A special function B<command(>"command"B<)> may be used in perl code to send
commands back to fvwm.

If perl code contains an error, it is printed to the standard error stream
with the I<[FvwmPerl][eval]:> header prepended.

=item B<load> file-name

Load a file of perl code.
If the file is not fully qualified, it is searched in the user
directory $FVWM_USERDIR (usually ~/.fvwm) and the system wide
data directory $FVWM_DATADIR.

A special function B<command(>"command"B<)> may be used in perl code to send
commands back to fvwm.

If perl code contains an error, it is printed to the standard error stream
with the I<[FvwmPerl][load]:> header prepended.

=item B<preprocess> [-q|--quote char] [-c|--command] [I<line> | I<file>]

Preprocess fvwmrc I<file> or (if --command is given) I<line>.
This file contains lines that are not touched (usually FVWM commands)
and specially preformatted perl code that is processed and replaced.
Text enclosed in B<%{> ... B<}%> delimiters, that may start anywhere
on the line and end anywhere on the same or an other line, is perl code.

The I<quote> parameter changes perl code delimiters.  If a single char
is given, like '@', the delimiters are B<@{> ... B<}@>.
If the given quote is 2 chars, like B<E<lt>E<gt>>, the quotes are
B<E<lt>{> ... B<}E<gt>>

The perl code is substituted for the result of its evaluation.
I.e. %{$a = "c"; ++$a}% is replaced with "d".

The evaluation is unlike B<eval> and B<load> is done under the
package PreprocessNamespace and without I<use strict>, so you are
free to use any variable names without fear of conflicts. Just don't
use uninitialized variables to mean undef or empty list (they may be in fact
initialized by the previous preprocess action), and do a clean-up if needed.
The variables and function in the I<main> package are still available,
like ::command() or ::skip(), but it is just not a good idea to access them
while preprocessing.

There is a special function B<include>(I<file>) that loads a file,
preprocesses it and returns the preprocessed result. Avoid recursion.

If any embedded perl code contains an error, it is printed to the standard
error stream and prepended with the I<[FvwmPerl][preprocess]:> header.
The result of substitution is empty in this case.

The following variables may be used in the perl code:

$USER,
$DISPLAY,
$WIDTH,
$HEIGHT,
$FVWM_VERSION,
$FVWM_MODULEDIR,
$FVWM_DATADIR,
$FVWM_USERDIR

The following line based directives are recognized when preprocessing.
They are processed after the perl code (if any) is substituted.

=over 4

=item %B<Repeat> I<count>

Causes the following lines to be repeated I<count> times.

=item %B<ModuleConfig> I<module-name> [ destroy ]

Causes the following lines to be interpreted as the given module configuration.
If "destroy" is specified the previous module configuration is destroyed first.

=item %B<Prefix> I<prefix>

Prefixes the following lines with the quoted I<prefix>.

=item %B<End> any-optional-comment

Ends any of the directives described above, may be nested.

=back

Examples:

  %Prefix "AddToFunc SwitchToWindow I"
    Iconify off
    WindowShade off
    Raise
    WrapToWindow 50 50
  %End

  %ModuleConfig FvwmPager destroy
    Colorset 0
    Font lucidasans-10
    DeskTopScale 28
    MiniIcons
  %End ModuleConfig FvwmPager

  %Prefix "All (MyWindowToAnimate) ResizeMove "
  100 100 %{($WIDTH - 100) / 2}% %{($HEIGHT - 100) / 2}%
  %Repeat %{$count}%
  br w+2c w+2c w-1c w-1c
  %End
  %Repeat %{$count}%
  br w-2c w-2c w+1c w+1c
  %End
  %End Prefix

Additional preprocess parameters --nosend and --noremove may be given too.
See their description at the top.

=back

These 3 actions may be requested in one of 3 ways: 1) in the command line when
FvwmPerl is invoked (in this case FvwmPerl is short-lived unless B<--stay>
is also given), 2) by sending the corresponding message in fvwmrc using
SendToModule, 3) by calling the corresponding perl function in perl code.

=head1 FUNCTIONS

There are several functions that perl code may call:

=over 4

=item B<command(>I<$fvwmCommand>B<)>

In case of B<eval> or B<load> - send back to fvwm a string I<$fvwmCommand>.
In case of B<preprocess> - append a string I<$fvwmCommand> to the output of
the embedded perl code.

=item B<doEval(>I<$perlCode>B<)>

This function is equivalent to the B<eval> functionality
on the string I<$perlCode>, described above.

=item B<load(>$fileNameB<)>

This function is equivalent to the B<load> functionality
on the file $fileName, described above.

=item B<preprocess(>I<@params, ["-c $command"] [$fileName]>B<)>

This function is equivalent to the B<preprocess> functionality
with the given parameters and the file $fileName described above.

=back

=head1 VARIABLES

There are several global variables in the I<main> namespace that may be used
in the perl code:

    $a, $b, ... $h
    @a, @b, ... @h
    %a, %b, ... %h

They all are initialized to the empty value and may be used to store a state
between different calls to FvwmPerl actions (B<eval> and B<load>).

If you need more readable variable names, either write "no strict 'vars';"
at the start of every perl code or use a hash for this, like:

    $h{id} = $h{firstName} . " " . $h{secondName}

or use a package name, like:

    @MyMenu::terminals = qw( xterm rxvt );
    $MyMenu::itemNum = @MyMenu::terminals;

There may be a configuration option to turn strictness on and off.

=head1 MESSAGES

FvwmPerl may receive messages using the fvwm command SendToModule.
The names, meanings and parameters of the messages are the same as the
corresponding actions, described above.

Additionally, a message B<stop> causes a module to quit.
A message B<dump> dumps the contents of the changed variables.

=head1 EXAMPLES

A simple test:

    SendToModule FvwmPerl eval $h{dir} = $ENV{HOME}
    SendToModule FvwmPerl eval load($h{dir} . "/test.fpl")
    SendToModule FvwmPerl load $[HOME]/test.fpl
    SendToModule FvwmPerl preprocess fvwmrc.ppp
    SendToModule FvwmPerl eval dump(\%h, @a);
    SendToModule FvwmPerl stop

The following example handles root backgrounds in fvwmrc.
All these commands may be added to StartFunction.

    Module FvwmPerl

    # find all background pixmaps for a later use
    SendToModule FvwmPerl eval $a = $ENV{HOME} . "/bg"; \
      opendir DIR, $a; @b = grep { /xpm$/ } readdir(DIR); closedir DIR

    # build a menu of background pixmaps
    AddToMenu MyBackgrounds "My Backgrounds" Title
    SendToModule FvwmPerl eval foreach $b (@b) \
      { command("AddToMenu MyBackgrounds '$b' Exec fvwm-root $a/$b") }

    # choose a random background to load on start-up
    SendToModule FvwmPerl eval command("AddToFunc \
      InitFunction + I Exec exec fvwm-root $a/" . $b[int(random(@b))])

=head1 ESCAPING

B<SendToModule> just like any other fvwm commands expands several dollar
prefixed variables.  This may clash with the dollars perl uses.
You may avoid this by prefixing SendToModule with a leading dash.
The following 2 lines in each pair are equivalent:

    SendToModule FvwmPerl eval $$d = "$[DISPLAY]"
    -SendToModule FvwmPerl eval $d = "$ENV{DISPLAY}"

    SendToModule FvwmPerl eval \
        command("Echo desk=$d, display=$$d")
    SendToModule FvwmPerl preprocess -c \
        Echo desk=%("$d")%, display=%{$$d}%

Another solution to avoid escaping of special symbols like dollars
and backslashes is to create a perl file in ~/.fvwm and then load it:

    SendToModule FvwmPerl load build-menus.fpl

If you need to preprocess one command starting with a dash, you should
precede it using "--".

    # this prints the current desk, i.e. "0"
    SendToModule FvwmPerl preprocess -c Echo "$%{$a = "c"; ++$a}%"
    # this prints "$d"
    SendToModule FvwmPerl preprocess -c -- -Echo "$%{"d"}%"
    # this prints "$d" (SendToModule expands $$ to $)
    SendToModule FvwmPerl preprocess -c -- -Echo "$$%{"d"}%"
    # this prints "$$d"
    -SendToModule FvwmPerl preprocess -c -- -Echo "$$%{"d"}%"

Again, it is suggested to put your command(s) into file and preprocess
the file instead.

=head1 CAVEATS

FvwmPerl being written in perl and dealing with perl, follows the famous
perl motto: "There's more than one way to do it", so the choice is yours.

Here are more pairs of equivalent lines:

    Module FvwmPerl --load "my.fpl" --stay
    Module FvwmPerl -e 'load("my.fpl")' -s

    SendToModule FvwmPerl preprocess --quote '@' my.ppp
    SendToModule FvwmPerl eval preprocess({quote => '@'}, "my.ppp");

Warning, you may affect the way FvwmPerl works by evaluating appropriate
perl code, this is considered a feature not a bug.  But please don't do this,
write your own FVWM module in perl instead.

=head1 SEE ALSO

The fvwm(1) man page describes all available commands.

Basically, in your perl code you may use any function or class method from
the perl library installed with FVWM, see the man pages of perl packages
B<General::FileSystem>, B<General::Parse> and B<FVWM::Module>.

=head1 AUTHOR

Mikhael Goikhman <migo@homemail.com>.

=cut
