#!/usr/bin/perl

# Copyright (c) 2002-2009 Mikhael Goikhman
#
# 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, see: <http://www.gnu.org/licenses/>

# Filter this script to pod2man to get a man page:
#   pod2man -c "Fvwm Utilities" fvwm-perllib | nroff -man | less -e

#use strict;  # comment to make it faster

BEGIN {
#	use vars qw($prefix $datarootdir $datadir $perllibdir);
	$prefix = "/usr";
	$datarootdir = "/usr/share";
	$datadir = "/usr/share";
	$perllibdir = "/usr/share/fvwm3/perllib";

	# try to do it as fast as possible
	if ($ARGV[0] eq 'dir') {
		print $perllibdir;
		exit(0);
	}
}

use Getopt::Long;
use lib $perllibdir;
use General::FileSystem '-die';

my $version = "1.1.2";
my $version_info = "released";

my $pager = $ENV{PAGER} || "less -e";
my $do_man = 0;
my $do_cat = 0;
my $do_raw = 0;

GetOptions(
	"help|h|?"    => \&show_help,
	"version|v|V" => \&show_version,
	"man"         => \$do_man,
	"cat"         => \$do_cat,
	"raw"         => \$do_raw,
	"dir"         => sub { print $perllibdir; exit(0); },
) || wrong_usage();

if ($ARGV[0] eq 'man') {
	$do_man = 1;
	shift;
} elsif ($ARGV[0] eq 'cat') {
	$do_cat = 1;
	shift;
} elsif ($ARGV[0] eq 'raw') {
	$do_raw = 1;
	shift;
}

wrong_usage() if !$do_man && !$do_cat && !$do_raw || @ARGV > 1;

my $man_or_cat_str = $do_man || $do_raw ? "man" : "cat";
my $internal_pods = {};

$internal_pods->{index} = qq{
	:head1 NAME

	index - lists all available help topics

	:head1 DESCRIPTION

	Recent I<fvwm> versions install the Perl library that makes creating
	fvwm modules in Perl possible and easy.

	You may read the Perl library documentation locally by running:

	    % fvwm-perllib $man_or_cat_str <topic>

	Available topics:

	    index
	    tutorial
	    events
	    {{CLASS_NAMES}}

	For example:

	    % fvwm-perllib $man_or_cat_str FVWM::Module

	:head1 AUTHOR

	Mikhael Goikhman <migo\@homemail.com>.
};

$internal_pods->{tutorial} = q{
	:head1 NAME

	tutorial - common techniques for writting fvwm modules

	:head1 TUTORIAL

	:head2 What is a window manager

	A window manager is a program that runs on top of the X Window
	System and manages windows, menus, key and mouse bindings, virtual
	desktops and pages, draws window decorations using defined colors or
	images, title-bar buttons and fonts. The window manager defines
	window placement and focus policies. It may also manage such things
	as root background, mouse cursors, sounds, run applications and
	do other nice things.

	:head2 What is a module

	In the unix traditions, different functionality may be implemented
	by separate programs to reduce a bloat. A module is an optional
	program that is intended to extend the window manager using a defined
	module protocol.

	Fvwm modules are spawned by the main I<fvwm> executable. They
	usually listen to the window manager events, do some useful work and
	send back commands for execution. There are transient modules that
	exit immediately or shortly, and persistent modules that exit
	together with a window manager or when a user requests.  Some
	modules may control windows or other modules. Some modules may supply
	a GUI, others may be non interactive.

	:head2 Creating a simple module

	Let's create a module that shows a flash window for one second when
	you change pages. We will use I<xmessage> with nifty options for our
	flash purposes, but you may use your fantasy to do this better.

	First, we should understand when our module works. Usually a module
	does nothing (sleeps) and is awaken when something interesting
	happens. This is achieved using events. A module defines events that
	it is interesting to receive and set-ups event handlers (perl
	functions) to be called when the event happens. Then a module enters
	the event loop where it sleeps all the time until one or another
	event happens. Most of the module work is done in the event
	handlers. When an event is processed, the module enters the event
	loop again.

	In our case, we should listen to an fvwm event I<M_NEW_PAGE>. The list
	of all events may be found in man page "events". When we receive
	the event we want to get new page coordinates and display them
	using our special xmessage window.

	Now, from theory to practice. The header of all modules written in
	Perl is pretty standard:

	    #!/usr/bin/perl -w

	    use lib `fvwm-perllib dir`;
	    use FVWM::Module;

	Then create the actual module object:

	    my $module = new FVWM::Module(
	        Mask => M_NEW_PAGE | M_NEW_DESK,
	        Debug => 1,
	    );

	The B<Debug> option tells to print the event names that a module
	receives to help writing a module, it also echoes all sent commands.
	The B<Mask> option tells which events a module wants to receive, in
	our case these are events generated on the page and desk changes.

	To handle events, event handlers that are perl functions, should be
	defined. It is ok not to define any event handler for I<M_NEW_DESK>
	and to define two event handlers for I<M_NEW_PAGE>. But for our
	purposes one I<M_NEW_PAGE> would be more than enough:

	    $module->add_handler(M_NEW_PAGE, \&got_new_page);

	It is a time to implement our C<got_new_page> function that will be
	called every time the desktop page is changed.

	    sub got_new_page {
	        my ($module, $event) = @_;

	        my $width  = $event->_vp_width;
	        my $height = $event->_vp_height;

	        if (!$width || !$height) {
	            # this may happen when doing DeskTopSize 1x1 on page 2 2
	            return;
	        }
	        my $page_nx = int($event->_vp_x / $width);
	        my $page_ny = int($event->_vp_y / $height);

	        # actually show the flash
	        $module->send("Exec xmessage -name FlashWindow \
	            -bg cyan -fg white -center -timeout 1 -button '' \
	            -xrm '*cursorName: none' -xrm '*borderWidth: 2' \
	            -xrm '*borderColor: yellow' -xrm '*Margin: 12' \
	            '($page_nx, $page_ny)'");
	    }

	All event handlers are called with 2 parameters, a module and an
	event objects. The arguments for all events are defined in
	L<FVWM::EventNames>. Each event type has its own arguments. Our
	I<M_NEW_PAGE> has 5 arguments: vp_x vp_y desk vp_width vp_height.
	We should do some calculations to get the page numbers from viewport
	coordinates.

	The B<send> method passes the command to I<fvwm> for execution.
	It would be better to set-up the FlashWindow specially:

	    $module->send("Style FlashWindow StaysOnTop, NoTitle, NoHandles, \
		BorderWidth 10, WindowListSkip, NeverFocus, UsePPosition");

	Finally, all persistent modules should enter the event loop:

	    $module->event_loop;

	The full module source that we just wrote is available at
	ftp://ftp.fvwm.org/pub/fvwm/devel/sources/tests/perl/module-flash .
	To run it execute this fvwm command:

	    Module /path/to/module-flash

	To kill the module, execute:

	    KillModule /path/to/module-flash

	:head2 Using event trackers

	In fact, the task of calculating page coordinates, or managing
	information about all windows, or gathering colorset, module or
	global information is so often, that there are existing
	implentation in the form of event trackers. Tracker is an instance
	of L<FVWM::Tracker> superclass. Currently these tracker classes are
	available (see their man pages):

	    FVWM::Tracker::Colorsets
	    FVWM::Tracker::GlobalConfig
	    FVWM::Tracker::ModuleConfig
	    FVWM::Tracker::PageInfo
	    FVWM::Tracker::Scheduler
	    FVWM::Tracker::WindowList

	Using a tracker is easy, something along lines:

	    my $tracker = $module->track("WindowList");
	    my $colorset_tracker = $module->track("Colorsets");

	Our module that we wrote above may be reduced if we use:

	    my $viewport = $module->track("PageInfo");

	    my $page_nx = $viewport->data("page_nx");
	    my $page_ny = $viewport->data("page_ny");

	Note that the tracker continues to work and maintain the up-to-date
	information about the current page and desk (or up-to-date windows
	or colorsets depending on the tracker type) at any given moment.

	Internally, trackers listen to appropriate events using the same
	event handler mechanism, so there is no speed advantage. However
	it is a good idea to reuse the existing verified code and reduce
	the number of events needed to be trapped manually. There is
	usually no problem if the developer and the tracker define
	handlers for the same events (besides the handler order maybe).

	:head2 On the module masks

	In our example above we explicitly defined Mask in constructor.
	This is not really needed. If not specified, the event mask is
	managed automatically (it is updated every time a new event handler
	is added).

	Note, there are actually two event masks, called "mask" and
	"xmask" (extended mask). If you are interested in the details,
	refer to the fvwm documentation or perllib sources.

	When trackers are added or removed, the module mask (and xmask)
	are automatically tweaked underhand. In short, there is often no
	reason to worry about the module masks. However, in rare cases
	you may want to define SyncMask (or SyncXMask), so that fvwm is
	synchronized with the module on certain events.

	:head2 Creating a more functional module

	Let's extend our new-page-flash example above and add a way to stop
	our module and to define another string format. This would be
	possible using the following I<fvwm> commands:

	    SendToModule /path/to/module-flash stop
	    SendToModule /path/to/module-flash format '[%d %d]'

	To handle such commands, we should define I<M_STRING> event handler.

	    use General::Parse;
	    my $format = "(%d, %d)";  # the default format

	    $module->mask($module->mask | M_STRING);
	    $module->add_handler(M_STRING, sub {
	        my ($module, $event) = @_;
	        my $line = $event->_text;
	        my ($action, @args) = get_tokens($line);

	        if ($action eq "stop") {
	            $module->terminate;
	        } elsif ($action eq "format") {
	            $format = $args[0];
	        }
	    });

	:head1 EXAMPLES

	Currently see I<ftp://ftp.fvwm.org/pub/fvwm/devel/sources/tests/perl/>
	for examples.

	Learning the sources of B<FvwmPerl>, B<FvwmDebug>
	modules may help too.

	:head1 SEE ALSO

	See L<FVWM::Module> for the module API.

	:head1 AUTHOR

	Mikhael Goikhman <migo@homemail.com>.
};

$internal_pods->{events} = q{
	:head1 NAME

	events - list of all fvwm events with arguments

	:head1 DESCRIPTION

	This list is automatically generated from L<FVWM::EventNames> package.

	Given L<FVWM::Event> object of certain event type, say I<M_STRING>,
	here is the syntax to get value of its I<win_id> argument:

	    $win_id = $event->_win_id;

	There are several more ways to access arguments, like:

	    $win_id = $event->arg_values->[0];
	    $text = $event->args->{text};

	:head1 EVENTS WITH ARGUMENTS

	{{EVENT_NAMES}}

	:head1 ARGUMENT TYPE LEGEND

	Here is a mapping of fvwm argument types to perl native types:

	    number - integer
	    bool   - boolean, true or false
	    window - X window id in decimal, use sprintf("0x%07x", $wid)
	    pixel  - "rgb:" . join('/', sprintf("%06lx", $val) =~ /(..)(..)(..)/)
	    string - string (scalar)
	    wflags - window flags in binary string
	    looped - loop of zero or more fixed argument bunches

	Run L<FvwmDebug> to browse events.

	:head1 SEE ALSO

	See "tutorial", L<FVWM::Event>, L<FVWM::EventNames> and L<FvwmDebug>.

	:head1 AUTHOR

	Mikhael Goikhman <migo@homemail.com>.
};

my $topic = $ARGV[0] || "index";
my $file = "-";
my $text = "";
if (exists $internal_pods->{$topic}) {
	$text = $internal_pods->{$topic};
	$text =~ s/^\t//mg;
	$text =~ s/^:/=/mg;

	if ($topic eq 'index') {
		my @class_names = sort @{list_filenames($perllibdir, 1)};
		@class_names = map { s!\.pm$!!; s!/!::!g; $_ } @class_names;
		$text =~ s/\{\{CLASS_NAMES\}\}/join("\n    ", @class_names)/seg;
	}

	if ($topic eq 'eventslass_names-e

#u    s

	In ,0iol Goiklx", s = map { ass_na

#u    s,insteadvwm modules inis a mappsible and easy.

	You ma None
duce aname:
    s/hidthemh',
     nis a mapk)
	ame:
    T  h~ /%(-?\d+)?(\*kemh',
 T  h~ /%(});

	:head1 EXe:
     event t a mappsible as defau;

	:head1 EXe:
     event t a mappsible as defau;

	:head1in events.
= map { ass_
     T  h-con  relea(ally (tgin/sh}.
'-' means,	:headon co}Process took " +DrCAin_id =  module mask (and xmaskdule /path/to =  module mur moduB
@ @--------------- reRed HowcoTHOR

	Mikhael GoiwcoTHOR

in rit(0); }s
	you may wancsto
define SyncMask rit(0); }s
	zs-A
I&a @MPFIR        \') 'rftied.

	   ""
# alonp('+ "$[gt.Rf*{.Eds->{$ wrote u
in rirote ueives to het mask iom -R' \\
    -t( /(\s+)/, $line, 5 );

    # Also, conditional comma2 2
	 o so based on
   "+
4 -"v",2
	 o so /$fname" ->{rguments	:head1 EVE>Tformat ARGUMENTS
	{{EVENT_NAMES{o"linkc_9

in rit(0); }s
e
	recei};

	:head,ts)-,,	:h,ew_menuli-\W_PAG8
	Not_9

iNot_9

iNotename) a3 not avas kes eve gument8(,vent happens. The.
};

$_na

   size    e in 

   >_te;
		$t       my ($action, @args) = get_tokens($li8
	Not\n !Bn the tPame) az>#&+",($li8
	No&    title> icon ]
[ B<--iconNegati_bd)		  A      	               > with wind ls
	title'\n";
	n!-file n as pu (c) 19/withwport-<e should undeowidththwpor an
{
		$sin namebjecen
{e}.BE  ;

	my $i]i")file = "bje B<T       $format = $aR

	Mi LSO

	See "6?
7;'0); . 
D    {{CL)\
7;or our    sual clasaur    M_WI/"        por an
{
		$sin clasaur  ok " =/usr/libexec/f 	:headrtfunctionPCan
{
		$clude or none
my le mur modue u
y #Ysitivpxnu $na preferences, e  #>.plit(/,+/, $1));. This0%, $1# Changn clasa1));. Targum($file   de_sys when d de_sys or_cat_str = $do_ needed en d de_sys &% module

	Ined enB o basedned enB anothsion    %, $1# Ch in ced enB   A @$/\\\$\$/}	    Kill,,,,,,,1w_!x
# whether show  en d de_ else-_menus, C Swidt%, $1 module wheted enB o b_WM_STAT in('/', o        TerminE_BELOWo    _NELntrt
	handl,,,,1ca)is islf):
   o     0  oE_Ba)is i  _NLw  en d d [user_men _NELntrt_NELntrtcoyspt.

=item B  stdn\>{$tontrt_NEENMAi}?AHBdional g;
	$tef.filen.      it is updatey0.!
r_caENMAi}?AHBdiona      ^LMRL     $tef.fi]n	       ef.fi]n	        e.fi]nn	  _tokens(e file lif.fi]n	  (.KNeffe:
   lvwmD$1 mo(-?\d+)?(\*kemh)le lif.fonal g;
	$teng_usag.      it is updatey0.!
r_caENMAi}?AHBdiona      ^LMRL     $tef.fi]n	       ef.fi]n	        e.fi]nn	  _tokens(e file lif.fi]n	  (.KNeffe:
   lvwmD$1 mo(-?\d+)?(\*kemh)le lif.fonal g;
	$teng_usag.      it is updatey0.!
r_caENMAi}?AHBdiy #Ysitivpxnu  xlock's nu  xont ? "%$fi]n	        B 9]n	      /0esktoxist,3 not axlock's mD$1 mfiame, B 9]n	 $tef(vwm3/pery0.!
r_caie =~ s/\\/\\\\/g;-.7so!
r_caead "fvw_f)fs s/ire?tory -d '$een 0 "tysly
creatAME

fvwm-" modurgmfvw_f)fs   # count perllieen 0 Ns heto acc00017165 
	pri-"w_ffy($action eq ult forma
};

$   if fillerma
 ""
# alonp('+$file_.Rf*{.Eds->{er ==3misc1, $m$[   	   07x", alonp(/d.

	    urces of B<FvwmPe. Targum($fi    urces of B% moPe. Targibed in B           Adden fils"/usr/share";
	,ath)
    ,A& used :GlobalC commant,  2 - dirs =~ /%[dD]/o 10  wlo;  # char	 o so /A PARTIC->{rguments	:he(d,c  2 - dir0  wlo; MRL     dToMenu

defidden islf):
aeadenu

defid -c "Fvwmore functional 2 - $parent_&s(e       if.fi]n	  (.KNeffe:
m_strarent_&s   tos  stri#Ysits ok not taR