diff options
author | berkeviktor@aol.com <berkeviktor@aol.com> | 2011-02-24 04:14:30 +0100 |
---|---|---|
committer | berkeviktor@aol.com <berkeviktor@aol.com> | 2011-02-24 04:14:30 +0100 |
commit | 4a6ceffb98a0b785494f680d3776c4bfc4052f9e (patch) | |
tree | 850703c1c841ccd99f58d0b06084615aaebe782c /plugins | |
parent | f16af8be941b596dedac3bf4e371ee2d21f4b598 (diff) |
add xchat r1489
Diffstat (limited to 'plugins')
35 files changed, 15851 insertions, 0 deletions
diff --git a/plugins/Make.plugin b/plugins/Make.plugin new file mode 100644 index 00000000..4a4c56fd --- /dev/null +++ b/plugins/Make.plugin @@ -0,0 +1,38 @@ +# Makefile stub for creating standalone plugin distributions. + +plugin_dist: pg_dist pg_dist/config.status + pgi=`cd $(srcdir)/.. && pwd`; cd pg_dist; \ + $(MAKE) $(AM_MAKEFLAGS) PLUGIN_INCLUDES=-I$$pgi distcheck dist + +pg_dist: pg_distdir pg_dist/configure.in pg_dist/install-sh + cd pg_dist \ + && libtoolize --copy --force --automake \ + && automake --copy --add-missing --foreign \ + && autoconf -l ../$(top_srcdir) + +pg_distdir: $(DISTFILES) + test -d pg_dist || mkdir pg_dist + for dfile in $(DISTFILES); do \ + test -f $$dfile && cp $$dfile pg_dist \ + || test -f $(srcdir)/$$dfile && cp $(srcdir)/$$dfile pg_dist; done + sed '/Make.plugin/d' < $(srcdir)/Makefile.am > pg_dist/Makefile.am + +pg_dist/configure.in: $(srcdir)/../plugin-conf.in + rm -f pg_dist/configure.in + test -f $(srcdir)/config.stub \ + && cat $(srcdir)/config.stub > pg_dist/configure.in || true + cat $(srcdir)/../plugin-conf.in | \ + sed 's%@PLUGIN_VERSION@%$(PLUGIN_VERSION)%; \ + s%@PLUGIN@%$(PLUGIN)%' >> pg_dist/configure.in + +pg_dist/install-sh: pg_distdir + cp $(top_srcdir)/install-sh pg_dist + +pg_dist/config.status: pg_dist/configure + cd pg_dist \ + && test -f config.status && $(SHELL) ./config.status --recheck \ + || $(SHELL) ./configure --enable-maintainer-mode + +DISTCLEANFILES = pg_dist/* pg_dist + +# diff --git a/plugins/Makefile.am b/plugins/Makefile.am new file mode 100644 index 00000000..d90f813a --- /dev/null +++ b/plugins/Makefile.am @@ -0,0 +1,21 @@ +# temp. solution while mailcheck & xdcc arn't in SUBDIRS +EXTRA_DIST = plugin20.html Make.plugin plugin-conf.in \ + xdcc/xdcc.c \ + xdcc/Makefile.am + +noinst_HEADERS = xchat-plugin.h + +if DO_PYTHON +pythondir = python +endif + +if DO_PERL +perldir = perl +endif + +if DO_TCL +tcldir = tcl +endif + +#SUBDIRS = . $(pythondir) $(perldir) mailcheck xdcc +SUBDIRS = . $(pythondir) $(perldir) $(tcldir) diff --git a/plugins/mailcheck/Makefile.am b/plugins/mailcheck/Makefile.am new file mode 100644 index 00000000..bda04229 --- /dev/null +++ b/plugins/mailcheck/Makefile.am @@ -0,0 +1,25 @@ +## Process with automake to produce Makefile.in + +# To create a standalone tarball of your plugin run the plugin_dist +# target. Note: you must configure the main source tree with +# --enable-maintainer-mode + +# These two must be defined. +PLUGIN=mailcheck +PLUGIN_VERSION=0.1 + +# This file must be in the form PLUGIN-config.h.in, it can be empty but +# must exist +EXTRA_DIST = mailcheck-config.h.in + +# Remember to include this line in your Makefile.am +include @top_srcdir@/plugins/Make.plugin + +libdir = $(xchatdir)/plugins + +lib_LTLIBRARIES = mailcheck.la +mailcheck_la_SOURCES = mailcheck.c +mailcheck_la_LDFLAGS = -avoid-version -module +INCLUDES = $(COMMON_CFLAGS) $(PLUGIN_INCLUDES) + +DISTCLEANFILES = pg_dir/* diff --git a/plugins/mailcheck/mailcheck.c b/plugins/mailcheck/mailcheck.c new file mode 100644 index 00000000..19011ab3 --- /dev/null +++ b/plugins/mailcheck/mailcheck.c @@ -0,0 +1,94 @@ +/* XCHAT 2.0 PLUGIN: Mail checker */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <unistd.h> + +#include "xchat-plugin.h" + + +static xchat_plugin *ph; /* plugin handle */ + +static int +mail_items(char *file) +{ + FILE *fp; + int items; + char buf[512]; + + fp = fopen(file, "r"); + if(!fp) + return 1; + + items = 0; + while(fgets(buf, sizeof buf, fp)) + { + if(!strncmp(buf, "From ", 5)) + items++; + } + fclose(fp); + + return items; +} + +static void +xchat_mail_check (void) +{ + static int last_size = -1; + int size; + struct stat st; + char buf[512]; + char *maildir; + + maildir = getenv("MAIL"); + if(!maildir) + { + snprintf (buf, sizeof(buf), "/var/spool/mail/%s", getenv("USER")); + maildir = buf; + } + + if(stat(maildir, &st) < 0) + return; + + size = st.st_size; + + if(last_size == -1) + { + last_size = size; + return; + } + + if(size > last_size) + { + xchat_printf(ph, + "-\0033-\0039-\017\tYou have new mail (%d messages, %d bytes total).", + mail_items(maildir), size); + } + + last_size = size; +} + +static int timeout_cb(void *userdata) +{ + xchat_mail_check(); + + return 1; +} + +int xchat_plugin_init(xchat_plugin *plugin_handle, + char **plugin_name, char **plugin_desc, char **plugin_version, + char *arg) +{ + ph = plugin_handle; + + *plugin_name = "MailCheck"; + *plugin_desc = "Checks your mailbox every 30 seconds"; + *plugin_version = "0.1"; + + xchat_hook_timer(ph, 30000, timeout_cb, 0); + + return 1; +} diff --git a/plugins/perl/Makefile.am b/plugins/perl/Makefile.am new file mode 100644 index 00000000..816ae67c --- /dev/null +++ b/plugins/perl/Makefile.am @@ -0,0 +1,20 @@ + +EXTRA_DIST=alt_completion.pl xchat2-perldocs.html xchat2-perl.html \ + generate_header lib/Xchat.pm lib/Xchat/Embed.pm lib/Xchat/List/Network.pm \ + lib/Xchat/List/Network/Entry.pm lib/Xchat/List/Network/AutoJoin.pm \ + lib/IRC.pm + +libdir = $(xchatlibdir)/plugins + +lib_LTLIBRARIES = perl.la +perl_la_SOURCES = perl.c +perl_la_LDFLAGS = -avoid-version -module +perl_la_LIBADD = $(PERL_LDFLAGS) +BUILT_SOURCES = xchat.pm.h irc.pm.h +#CFLAGS = @CFLAGS@ -Wno-unused +INCLUDES = $(PERL_CFLAGS) $(COMMON_CFLAGS) -I$(srcdir)/.. +CLEANFILES = xchat.pm.h irc.pm.h +xchat.pm.h irc.pm.h: lib/Xchat.pm lib/Xchat/Embed.pm \ + lib/Xchat/List/Network.pm lib/Xchat/List/Network/Entry.pm \ + lib/Xchat/List/Network/AutoJoin.pm lib/IRC.pm + perl generate_header diff --git a/plugins/perl/alt_completion.pl b/plugins/perl/alt_completion.pl new file mode 100644 index 00000000..2572fb81 --- /dev/null +++ b/plugins/perl/alt_completion.pl @@ -0,0 +1,507 @@ +use strict; +use warnings; +use Xchat (); +use File::Spec (); +use File::Basename qw(fileparse); + +# if the last time you addressed someone was greater than this many minutes +# ago, ignore it +# this avoids having people you have talked to a long time ago coming up too +# early in the completion list +# Setting this to 0 will disable the check which is effectively the same as +# setting it to infinity +my $last_use_threshold = 10; # 10 minutes + +# added to the front of a completion the same way as a suffix, only if +# the word is at the beginning of the line +my $prefix = ''; + +# ignore leading non-alphanumeric characters: -[\]^_`{|} +# Assuming you have the following nicks in a channel: +# [SomeNick] _SomeNick_ `SomeNick SomeNick SomeOtherNick +# when $ignore_leading_non_alnum is set to 0 +# s<tab> will cycle through SomeNick and SomeOtherNick +# when $ignore_leading_non_alnum is set to 1 +# s<tab> will cycle through [SomeNick] _SomeNick_ `SomeNick SomeNick +# SomeOtherNick +my $ignore_leading_non_alnum = 0; + +# enable path completion +my $path_completion = 1; +my $base_path = ''; + +Xchat::register( + "Tab Completion", "1.0401", "Alternative tab completion behavior" +); +Xchat::hook_print( "Key Press", \&complete ); +Xchat::hook_print( "Close Context", \&close_context ); +Xchat::hook_print( "Focus Tab", \&focus_tab ); +Xchat::hook_print( "Part", \&clean_selected ); +Xchat::hook_print( "Part with Reason", \&clean_selected ); +Xchat::hook_command( "", \&track_selected ); + +sub SHIFT() { 1 } +sub CTRL() { 4 } +sub ALT() { 8 } + +sub TAB() { 0xFF09 } +sub LEFT_TAB() { 0xFE20 } + +my %completions; +my %last_visit; +my %selected; +my %escape_map = ( + '[' => qr![\[{]!, + '{' => qr![\[{]!, + '}' => qr![\]}]!, + ']' => qr![\]}]!, + '\\' => qr![\\\|]!, + '|' => qr![\\\|]!, + '.' => qr!\.!, + '^' => qr!\^!, + '$' => qr!\$!, + '*' => qr!\*!, + '+' => qr!\+!, + '?' => qr!\?!, + '(' => qr!\(!, + ')' => qr!\)!, + '-' => qr!\-!, +); + +my $escapes = join "", keys %escape_map; +$escapes = qr/[\Q$escapes\E]/; + +# used to determine if a word is the start of a path +my $path_pattern = qr{^(?:~|/|[[:alpha:]]:\\)}; + +sub complete { + my ($key, $modifiers) = @{$_[0]}; + # if $_[0][0] contains the value of the key pressed + # $_[0][1] contains modifiers + # the value for tab is 0xFF09 + # the value for shift-tab(Left Tab) is 0xFE20 + # we don't care about other keys + + # the key must be a tab and left tab + return Xchat::EAT_NONE unless $key == TAB || $key == LEFT_TAB; + + # if it is a tab then it must not have any modifiers + return Xchat::EAT_NONE if $key == TAB && $modifiers & (CTRL|ALT|SHIFT); + + # loop backwards for shift+tab/left tab + my $delta = $modifiers & SHIFT ? -1 : 1; + my $context = Xchat::get_context; + $completions{$context} ||= {}; + + my $completions = $completions{$context}; + $completions->{pos} ||= -1; + + my $suffix = Xchat::get_prefs( "completion_suffix" ); + $suffix =~ s/^\s+//; + + my $input = Xchat::get_info( "inputbox" ); + my $cursor_pos = Xchat::get_info( "state_cursor" ); + my $left = substr( $input, 0, $cursor_pos ); + my $right = substr( $input, $cursor_pos ); + my $length = length $left; + + # trim spaces from the end of $left to avoid grabbing the wrong word + # this is mainly needed for completion at the very beginning where a space + # is added after the completion + $left =~ s/\s+$//; + + # always add one to the index because + # 1) if a space is found we want the position after it + # 2) if a space isn't found then we get back -1 + my $word_start = rindex( $left, " " ) + 1; + my $word = substr( $left, $word_start ); + $left = substr( $left, 0, -length $word ); + + if( $cursor_pos == $completions->{pos} ) { + my $previous_word = $completions->{completed}; + my $new_left = $input; + substr( $new_left, $cursor_pos ) = ""; + + if( $previous_word and $new_left =~ s/(\Q$previous_word\E)$// ) { + $word = $1; + $word_start = length( $new_left ); + $left = $new_left; + } + } + + my $command_char = Xchat::get_prefs( "input_command_char" ); + # ignore commands + if( ($word !~ m{^[${command_char}]}) + or ( $word =~ m{^[${command_char}]} and $word_start != 0 ) ) { + + if( $cursor_pos == length $input # end of input box + # not a valid nick char + && $input =~ /(?<![\x41-\x5A\x61-\x7A\x30-\x39\x5B-\x60\x7B-\x7D-])$/ + && $cursor_pos != $completions->{pos} # not continuing a completion + && $word !~ m{^(?:[&#/~]|[[:alpha:]]:\\)} # not a channel or path + ) { + # check for path completion + unless( $path_completion and $word =~ $path_pattern ) { + $word_start = $cursor_pos; + $left = $input; + $length = length $length; + $right = ""; + $word = ""; + } + } + + if( $word_start == 0 && $prefix && $word =~ /^\Q$prefix/ ) { + $word =~ s/^\Q$prefix//; + } + + my $completed; # this is going to be the "completed" word + + # for parital completions and channel names so a : isn't added + #$completions->{skip_suffix} = ($word =~ /^[&#]/) ? 1 : 0; + + # continuing from a previous completion + if( + exists $completions->{matches} && @{$completions->{matches}} + && $cursor_pos == $completions->{pos} + && $word =~ /^\Q$completions->{matches}[$completions->{index}]/ + ) { + $completions->{index} += $delta; + + if( $completions->{index} < 0 ) { + $completions->{index} += @{$completions->{matches}}; + } else { + $completions->{index} %= @{$completions->{matches}}; + } + + } else { + + if( $word =~ /^[&#]/ ) { + # channel name completion + $completions->{matches} = [ matching_channels( $word ) ]; + $completions->{skip_suffix} = 0; + } elsif( $path_completion and $word =~ $path_pattern ) { + # file name completion + $completions->{matches} = [ matching_files( $word ) ]; + $completions->{skip_suffix} = 1; + } else { + # nick completion + # fix $word so { equals [, ] equals }, \ equals | + # and escape regex metacharacters + $word =~ s/($escapes)/$escape_map{$1}/g; + + $completions->{matches} = [ matching_nicks( $word ) ]; + $completions->{skip_suffix} = 0; + } + $completions->{index} = 0; + + } + $completed = $completions->{matches}[ $completions->{index} ]; + $completions->{completed} = $completed; + + my $completion_amount = Xchat::get_prefs( "completion_amount" ); + + # don't cycle if the number of possible completions is greater than + # completion_amount + if( + @{$completions->{matches}} > $completion_amount + && @{$completions->{matches}} != 1 + ) { + # don't print if we tabbed in the beginning and the list of possible + # completions includes all nicks in the channel + my $context_type = Xchat::context_info->{type}; + if( $context_type != 2 # not a channel + or @{$completions->{matches}} < Xchat::get_list("users") + ) { + Xchat::print( join " ", @{$completions->{matches}}, "\n" ); + } + + $completed = lcs( $completions->{matches} ); + $completions->{skip_suffix} = 1; + } + + if( $completed ) { + + if( $word_start == 0 && !$completions->{skip_suffix} ) { + # at the start of the line append completion suffix + Xchat::command( "settext $prefix$completed$suffix$right"); + $completions->{pos} = length( "$prefix$completed$suffix" ); + } else { + Xchat::command( "settext $left$completed$right" ); + $completions->{pos} = length( "$left$completed" ); + } + + Xchat::command( "setcursor $completions->{pos}" ); + } + +=begin +# debugging stuff + local $, = " "; + my $input_length = length $input; + Xchat::print [ + qq{input[$input]}, + qq{input_length[$input_length]}, + qq{cursor[$cursor_pos]}, + qq{start[$word_start]}, + qq{length[$length]}, + qq{left[$left]}, + qq{word[$word]}, qq{right[$right]}, + qq{completed[}. ($completed||""). qq{]}, + qq{pos[$completions->{pos}]}, + ]; + use Data::Dumper; + local $Data::Dumper::Indent = 0; + Xchat::print Dumper $completions->{matches}; +=cut + + return Xchat::EAT_ALL; + } else { + return Xchat::EAT_NONE; + } +} + + +# all channels starting with $word +sub matching_channels { + my $word = shift; + + # for use in compare_channels(); + our $current_chan; + local $current_chan = Xchat::get_info( "channel" ); + + my $conn_id = Xchat::get_info( "id" ); + $word =~ s/^[&#]+//; + + return + map { $_->[1]->{channel} } + sort compare_channels map { + my $chan = $_->{channel}; + $chan =~ s/^[#&]+//; + + # comparisons will be done based only on the name + # matching name, same connection, only channels + $chan =~ /^$word/i && $_->{id} == $conn_id ? + [ $chan, $_ ] : + () + } channels(); +} + +sub channels { + return grep { $_->{type} == 2 } Xchat::get_list( "channels" ); +} + +sub compare_channels { + # package variable, value set in matching_channels() + our $current_chan; + + # turn off warnings generated from channels that have not yet been visited + # since the script was loaded + no warnings "uninitialized"; + + # the current channel is always first, then ordered by most recently visited + return + $a->[1]{channel} eq $current_chan ? -1 : + $b->[1]{channel} eq $current_chan ? 1 : + $last_visit{ $b->[1]{context} } <=> $last_visit{ $a->[1]{context} } + || $a->[1]{channel} cmp $b->[1]{channel}; + +} + +sub matching_nicks { + my $word_re = shift; + + # for use in compare_nicks() + our ($my_nick, $selections, $now); + local $my_nick = Xchat::get_info( "nick" ); + local $selections = $selected{ Xchat::get_context() }; + local $now = time; + + my $pattern = $ignore_leading_non_alnum ? + qr/^[\-\[\]^_`{|}\\]*$word_re/i : qr/^$word_re/i; + return + map { $_->{nick} } + sort compare_nicks grep { + $_->{nick} =~ $pattern; + } Xchat::get_list( "users" ) + +} + +sub max { + return unless @_; + my $max = shift; + for(@_) { + $max = $_ if $_ > $max; + } + return $max; +} + +sub compare_times { + # package variables set in matching_nicks() + our $selections; + our $now; + + for my $nick ( $a->{nick}, $b->{nick} ) { + # turn off the warnings that get generated from users who have yet + # to speak since the script was loaded + no warnings "uninitialized"; + + if( $last_use_threshold + && (( $now - $selections->{$nick}) > ($last_use_threshold * 60)) ) { + delete $selections->{ $nick } + } + } + my $a_time = $selections->{ $a->{nick} } || 0 ; + my $b_time = $selections->{ $b->{nick} } || 0 ; + + if( $a_time || $b_time ) { + return $b_time <=> $a_time; + } elsif( !$a_time && !$b_time ) { + return $b->{lasttalk} <=> $a->{lasttalk}; + } + +} + +sub compare_nicks { + # more package variables, value set in matching_nicks() + our $my_nick; + + # our own nick is always last, then ordered by the people we spoke to most + # recently and the people who were speaking most recently + return + $a->{nick} eq $my_nick ? 1 : + $b->{nick} eq $my_nick ? -1 : + compare_times() + || Xchat::nickcmp( $a->{nick}, $b->{nick} ); + +# $selections->{ $b->{nick} } <=> $selections->{ $a->{nick} } +# || $b->{lasttalk} <=> $a->{lasttalk} + +} + +sub matching_files { + my $word = shift; + + my ($file, $input_dir) = fileparse( $word ); + + my $dir = expand_tilde( $input_dir ); + + if( opendir my $dir_handle, $dir ) { + my @files; + + if( $file ) { + @files = grep { + #Xchat::print( $_ ); + /^\Q$file/ } readdir $dir_handle; + } else { + @files = readdir $dir_handle; + } + + return map { + File::Spec->catfile( $input_dir, $_ ); + } sort + grep { !/^[.]{1,2}$/ } @files; + } else { + return (); + } +} + +# Remove completion related data for tabs that are closed +sub close_context { + my $context = Xchat::get_context; + delete $completions{$context}; + delete $last_visit{$context}; + return Xchat::EAT_NONE; +} + +# track visit times +sub focus_tab { + $last_visit{Xchat::get_context()} = time(); + return Xchat::EAT_NONE; +} + +# keep track of the last time a message was addressed to someone +# a message is considered addressed to someone if their nick is used followed +# by the completion suffix +sub track_selected { + my $input = $_[1][0]; + return Xchat::EAT_NONE unless defined $input; + + my $suffix = Xchat::get_prefs( "completion_suffix" ); + for( grep defined, $input =~ /^(.+)\Q$suffix/, $_[0][0] ) { + if( in_channel( $_ ) ) { + $selected{Xchat::get_context()}{$_} = time(); + last; + } + } + + return Xchat::EAT_NONE; +} + +# if a user is in the current channel +# user_info() can also be used instead of the loop +sub in_channel { + my $target = shift; + for my $nick ( nicks() ) { + if( $nick eq $target ) { + return 1; + } + } + + return 0; +} + +# list of nicks in the current channel +sub nicks { + return map { $_->{nick} } Xchat::get_list( "users" ); +} + +# remove people from the selected list when they leave the channel +sub clean_selected { + delete $selected{ Xchat::get_context() }{$_[0][0]}; + return Xchat::EAT_NONE; +} + +# Longest common substring +# Used for partial completion when using non-cycling completion +sub lcs { + my @nicks = @{+shift}; + return "" if @nicks == 0; + return $nicks[0] if @nicks == 1; + + my $substring = shift @nicks; + + while(@nicks) { + $substring = common_string( $substring, shift @nicks ); + } + + return $substring; +} + +sub common_string { + my ($nick1, $nick2) = @_; + my $index = 0; + + $index++ while( + ($index < length $nick1) && ($index < length $nick2) && + lc(substr( $nick1, $index, 1 )) eq lc(substr( $nick2, $index, 1 )) + ); + + + return substr( $nick1, 0, $index ); +} + +sub expand_tilde { + my $file = shift; + + $file =~ s/^~/home_dir()/e; + return $file; +} + +sub home_dir { + return $base_path if $base_path; + + if ( $^O eq "MSWin32" ) { + return $ENV{USERPROFILE}; + } else { + return ((getpwuid($>))[7] || $ENV{HOME} || $ENV{LOGDIR}); + } +} diff --git a/plugins/perl/char_count.pl b/plugins/perl/char_count.pl new file mode 100644 index 00000000..418046f4 --- /dev/null +++ b/plugins/perl/char_count.pl @@ -0,0 +1,101 @@ + +use strict; +use warnings; +use Xchat qw(:all); +use Glib qw(TRUE FALSE); +use Gtk2 -init; + +sub get_inputbox { + my $widget = Glib::Object->new_from_pointer( get_info( "win_ptr" ), 0 ); + my $input_box; + + my @containers = ($widget); + + while( @containers ) { + my $container = shift @containers; + + for my $child ( $container->get_children ) { + if( $child->get( "name" ) eq 'xchat-inputbox' ) { + $input_box = $child; + last; + } elsif( $child->isa( "Gtk2::Container" ) ) { + push @containers, $child; + } + } + } + return $input_box; +} + +sub get_hbox { + my $widget = shift; + my $hbox; + + while( $widget->parent ) { + if( $widget->parent->isa( "Gtk2::HBox" ) ) { + return $widget->parent; + } + $widget = $widget->parent; + } + +} + +my $input_box = get_inputbox(); + +if( $input_box ) { + my $hbox = get_hbox( $input_box ); + if( $hbox ) { + my $label = Gtk2::Label->new(); + $label->set_alignment( 0.5, ($label->get_alignment)[1] ); + $hbox->pack_end( $label, 0, 0, 5 ); + $label->show(); + + my $update_label = sub { + my $ctx_type = context_info->{"type"}; + hook_timer( 0, sub { + if( $ctx_type == 2 || $ctx_type == 3 ) { + my $count = length get_info "inputbox"; + $label->set_text( $count ? $count : "" ); + } else { + $label->set_text( "" ); + } + return REMOVE; + }); + return EAT_NONE; + }; + + hook_print( "Key Press", $update_label ); + hook_print( "Focus Tab", $update_label ); + hook_print( "Focus Window", $update_label ); + hook_command( "", + sub { + $label->set_text( "" ); + return EAT_NONE; + } + ); + + my @handlers; + my $buffer = $input_box->get_buffer; + my $handler = sub { $update_label->(); return TRUE }; + + if( $buffer->isa( "Gtk2::TextBuffer" ) ) { + push @handlers, $buffer->signal_connect( "changed", $handler ); + } elsif( $buffer->isa( "Gtk2::EntryBuffer" ) ) { + push @handlers, + $buffer->signal_connect( "deleted-text", $handler ); + $buffer->signal_connect( "inserted-text", $handler ); + } + + register( "Character Counter", "1.0.0", + "Display the number of characters in the inputbox", + sub { + $hbox->remove( $label ); + $buffer->signal_handler_disconnect( $_ ) for @handlers; + } + ); + } else { + prnt "Counldn't find hbox"; + } + +} else { + prnt "Couldn't fint input box"; +} diff --git a/plugins/perl/generate_header b/plugins/perl/generate_header new file mode 100644 index 00000000..d6c8a65f --- /dev/null +++ b/plugins/perl/generate_header @@ -0,0 +1,50 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +sub header { + my $file = shift; + open my $input, "<", $file or die "Couldn't open '$file':$!"; + my @file = <$input>; + close $file; + return toc(@file); +} + +sub toc { + my @lines = @_; + for( @lines ) { + if( /^\s*$/s ) { $_ = qq{"\\n"\n}; next; } + if( /^\s*#/ ) { $_ = qq{"\\n"\n}; next; } + s/\\/\\\\/g; # double the number of \'s + s/"/\\"/g; + s/^\s*/"/; + s/\n/\\n"\n/; + } + return @lines; +} + +for my $files ( + [ "xchat.pm.h", # output file + "lib/Xchat.pm", # input files + "lib/Xchat/Embed.pm", + "lib/Xchat/List/Network.pm", + "lib/Xchat/List/Network/Entry.pm", + "lib/Xchat/List/Network/AutoJoin.pm", + ], + [ "irc.pm.h", # output file + "lib/IRC.pm" # input file + ] +) { + my ($output,@inputs) = @$files; + + open my $header, ">", $output or die "Couldn't open '$output': $!"; + + for my $input ( @inputs ) { + print $header qq["{\\n"\n]; + print $header qq{"#line 1 \\"$input\\"\\n"\n}; + print $header header( $input ); + print $header qq["}\\n"\n]; + } + close $header; +} diff --git a/plugins/perl/generate_html b/plugins/perl/generate_html new file mode 100644 index 00000000..c144ce7e --- /dev/null +++ b/plugins/perl/generate_html @@ -0,0 +1,27 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use File::Basename qw(dirname); + +sub __DIR__ { + return dirname +(caller 0)[1]; +} + +# this must go before use Pod::Html to use our private copy +use lib __DIR__ . '/lib'; +use Pod::Html; + +chdir( __DIR__ ) or die $!; +pod2html( +# "pod2html", + "--header", + "--infile=lib/Xchat.pod", + "--outfile=xchat2-perl.html", +); + +#system( qw(tidy -m -i -xml -utf8 -quiet xchat2-perl.html) ); +unlink( "pod2htmd.tmp" ); +unlink( "pod2htmi.tmp" ); + +exec( "./syntax_highlight", "xchat2-perl.html" ) + or die $!; diff --git a/plugins/perl/lib/IRC.pm b/plugins/perl/lib/IRC.pm new file mode 100644 index 00000000..c22a8e73 --- /dev/null +++ b/plugins/perl/lib/IRC.pm @@ -0,0 +1,257 @@ + +package IRC; +sub IRC::register { + my ($script_name, $version, $callback) = @_; + my $package = caller; + $callback = Xchat::Embed::fix_callback( $package, $callback) if $callback; + Xchat::register( $script_name, $version, undef, $callback ); +} + + +sub IRC::add_command_handler { + my ($command, $callback) = @_; + my $package = caller; + + $callback = Xchat::Embed::fix_callback( $package, $callback ); + + # starting index for word_eol array + # this is for compatibility with '' as the command + my $start_index = $command ? 1 : 0; + + Xchat::hook_command( $command, + sub { + no strict 'refs'; + return &{$callback}($_[1][$start_index]); + } + ); + return; +} + +sub IRC::add_message_handler { + my ($message, $callback) = @_; + my $package = caller; + $callback = Xchat::Embed::fix_callback( $package, $callback ); + + Xchat::hook_server( $message, + sub { + no strict 'refs'; + return &{$callback}( $_[1][0] ); + } + ); + return; +} + +sub IRC::add_print_handler { + my ($event, $callback) = @_; + my $package = caller; + $callback = Xchat::Embed::fix_callback( $package, $callback ); + Xchat::hook_print( $event, + sub { + my @word = @{$_[0]}; + no strict 'refs'; + return &{$callback}( join( ' ', @word[0..3] ), @word ); + } + ); + return; +} + +sub IRC::add_timeout_handler { + my ($timeout, $callback) = @_; + my $package = caller; + $callback = Xchat::Embed::fix_callback( $package, $callback ); + Xchat::hook_timer( $timeout, + sub { + no strict 'refs'; + &{$callback}; + return 0; + } + ); + return; +} + +sub IRC::command { + my $command = shift; + if( $command =~ m{^/} ) { + $command =~ s{^/}{}; + Xchat::command( $command ); + } else { + Xchat::command( qq[say $command] ); + } +} + +sub IRC::command_with_channel { + my ($command, $channel, $server) = @_; + my $old_ctx = Xchat::get_context; + my $ctx = Xchat::find_context( $channel, $server ); + + if( $ctx ) { + Xchat::set_context( $ctx ); + IRC::command( $command ); + Xchat::set_context( $ctx ); + } +} + +sub IRC::command_with_server { + my ($command, $server) = @_; + my $old_ctx = Xchat::get_context; + my $ctx = Xchat::find_context( undef, $server ); + + if( $ctx ) { + Xchat::set_context( $ctx ); + IRC::command( $command ); + Xchat::set_context( $ctx ); + } +} + +sub IRC::dcc_list { + my @dccs; + for my $dcc ( Xchat::get_list( 'dcc' ) ) { + push @dccs, $dcc->{nick}; + push @dccs, $dcc->{file} ? $dcc->{file} : ''; + push @dccs, @{$dcc}{qw(type status cps size)}; + push @dccs, $dcc->{type} == 0 ? $dcc->{pos} : $dcc->{resume}; + push @dccs, $dcc->{address32}; + push @dccs, $dcc->{destfile} ? $dcc->{destfile} : ''; + } + return @dccs; +} + +sub IRC::channel_list { + my @channels; + for my $channel ( Xchat::get_list( 'channels' ) ) { + push @channels, @{$channel}{qw(channel server)}, + Xchat::context_info( $channel->{context} )->{nick}; + } + return @channels; +} + +sub IRC::get_info { + my $id = shift; + my @ids = qw(version nick channel server xchatdir away network host topic); + + if( $id >= 0 && $id <= 8 && $id != 5 ) { + my $info = Xchat::get_info($ids[$id]); + return defined $info ? $info : ''; + } else { + if( $id == 5 ) { + return Xchat::get_info( 'away' ) ? 1 : 0; + } else { + return 'Error2'; + } + } +} + +sub IRC::get_prefs { + return 'Unknown variable' unless defined $_[0]; + my $result = Xchat::get_prefs(shift); + return defined $result ? $result : 'Unknown variable'; +} + +sub IRC::ignore_list { + my @ignores; + for my $ignore ( Xchat::get_list( 'ignore' ) ) { + push @ignores, $ignore->{mask}; + my $flags = $ignore->{flags}; + push @ignores, $flags & 1, $flags & 2, $flags & 4, $flags & 8, $flags & 16, + $flags & 32, ':'; + } + return @ignores; +} + +sub IRC::print { + Xchat::print( $_ ) for @_; + return; +} + +sub IRC::print_with_channel { + Xchat::print( @_ ); +} + +sub IRC::send_raw { + Xchat::commandf( qq[quote %s], shift ); +} + +sub IRC::server_list { + my @servers; + for my $channel ( Xchat::get_list( 'channels' ) ) { + push @servers, $channel->{server} if $channel->{server}; + } + return @servers; +} + +sub IRC::user_info { + my $user; + if( @_ > 0 ) { + $user = Xchat::user_info( shift ); + } else { + $user = Xchat::user_info(); + } + + my @info; + if( $user ) { + push @info, $user->{nick}; + if( $user->{host} ) { + push @info, $user->{host}; + } else { + push @info, 'FETCHING'; + } + push @info, $user->{prefix} eq '@' ? 1 : 0; + push @info, $user->{prefix} eq '+' ? 1 : 0; + } + return @info; +} + +sub IRC::user_list { + my ($channel, $server) = @_; + my $ctx = Xchat::find_context( $channel, $server ); + my $old_ctx = Xchat::get_context; + + if( $ctx ) { + Xchat::set_context( $ctx ); + my @users; + for my $user ( Xchat::get_list( 'users' ) ) { + push @users, $user->{nick}; + if( $user->{host} ) { + push @users, $user->{host}; + } else { + push @users, 'FETCHING'; + } + push @users, $user->{prefix} eq '@' ? 1 : 0; + push @users, $user->{prefix} eq '+' ? 1 : 0; + push @users, ':'; + } + Xchat::set_context( $old_ctx ); + return @users; + } else { + return; + } +} + +sub IRC::user_list_short { + my ($channel, $server) = @_; + my $ctx = Xchat::find_context( $channel, $server ); + my $old_ctx = Xchat::get_context; + + if( $ctx ) { + Xchat::set_context( $ctx ); + my @users; + for my $user ( Xchat::get_list( 'users' ) ) { + my $nick = $user->{nick}; + my $host = $user->{host} || 'FETCHING'; + push @users, $nick, $host; + } + Xchat::set_context( $old_ctx ); + return @users; + } else { + return; + } + +} + +sub IRC::add_user_list {} +sub IRC::sub_user_list {} +sub IRC::clear_user_list {} +sub IRC::notify_list {} +sub IRC::perl_script_list {} + +1 diff --git a/plugins/perl/lib/Pod/Html.pm b/plugins/perl/lib/Pod/Html.pm new file mode 100644 index 00000000..3695564b --- /dev/null +++ b/plugins/perl/lib/Pod/Html.pm @@ -0,0 +1,2399 @@ +package Pod::Html; +use strict; +require Exporter; + +use vars qw($VERSION @ISA @EXPORT @EXPORT_OK); +$VERSION = 1.08; +@ISA = qw(Exporter); +@EXPORT = qw(pod2html htmlify); +@EXPORT_OK = qw(anchorify); + +use Carp; +use Config; +use Cwd; +use File::Spec; +use File::Spec::Unix; +use Getopt::Long; + +use locale; # make \w work right in non-ASCII lands + +=head1 NAME + +Pod::Html - module to convert pod files to HTML + +=head1 SYNOPSIS + + use Pod::Html; + pod2html([options]); + +=head1 DESCRIPTION + +Converts files from pod format (see L<perlpod>) to HTML format. It +can automatically generate indexes and cross-references, and it keeps +a cache of things it knows how to cross-reference. + +=head1 FUNCTIONS + +=head2 pod2html + + pod2html("pod2html", + "--podpath=lib:ext:pod:vms", + "--podroot=/usr/src/perl", + "--htmlroot=/perl/nmanual", + "--libpods=perlfunc:perlguts:perlvar:perlrun:perlop", + "--recurse", + "--infile=foo.pod", + "--outfile=/perl/nmanual/foo.html"); + +pod2html takes the following arguments: + +=over 4 + +=item backlink + + --backlink="Back to Top" + +Adds "Back to Top" links in front of every C<head1> heading (except for +the first). By default, no backlinks are generated. + +=item cachedir + + --cachedir=name + +Creates the item and directory caches in the given directory. + +=item css + + --css=stylesheet + +Specify the URL of a cascading style sheet. Also disables all HTML/CSS +C<style> attributes that are output by default (to avoid conflicts). + +=item flush + + --flush + +Flushes the item and directory caches. + +=item header + + --header + --noheader + +Creates header and footer blocks containing the text of the C<NAME> +section. By default, no headers are generated. + +=item help + + --help + +Displays the usage message. + +=item hiddendirs + + --hiddendirs + --nohiddendirs + +Include hidden directories in the search for POD's in podpath if recurse +is set. +The default is not to traverse any directory whose name begins with C<.>. +See L</"podpath"> and L</"recurse">. + +[This option is for backward compatibility only. +It's hard to imagine that one would usefully create a module with a +name component beginning with C<.>.] + +=item htmldir + + --htmldir=name + +Sets the directory in which the resulting HTML file is placed. This +is used to generate relative links to other files. Not passing this +causes all links to be absolute, since this is the value that tells +Pod::Html the root of the documentation tree. + +=item htmlroot + + --htmlroot=name + +Sets the base URL for the HTML files. When cross-references are made, +the HTML root is prepended to the URL. + +=item index + + --index + --noindex + +Generate an index at the top of the HTML file. This is the default +behaviour. + +=item infile + + --infile=name + +Specify the pod file to convert. Input is taken from STDIN if no +infile is specified. + +=item libpods + + --libpods=name:...:name + +List of page names (eg, "perlfunc") which contain linkable C<=item>s. + +=item netscape + + --netscape + --nonetscape + +B<Deprecated>, has no effect. For backwards compatibility only. + +=item outfile + + --outfile=name + +Specify the HTML file to create. Output goes to STDOUT if no outfile +is specified. + +=item podpath + + --podpath=name:...:name + +Specify which subdirectories of the podroot contain pod files whose +HTML converted forms can be linked to in cross references. + +=item podroot + + --podroot=name + +Specify the base directory for finding library pods. + +=item quiet + + --quiet + --noquiet + +Don't display I<mostly harmless> warning messages. These messages +will be displayed by default. But this is not the same as C<verbose> +mode. + +=item recurse + + --recurse + --norecurse + +Recurse into subdirectories specified in podpath (default behaviour). + +=item title + + --title=title + +Specify the title of the resulting HTML file. + +=item verbose + + --verbose + --noverbose + +Display progress messages. By default, they won't be displayed. + +=back + +=head2 htmlify + + htmlify($heading); + +Converts a pod section specification to a suitable section specification +for HTML. Note that we keep spaces and special characters except +C<", ?> (Netscape problem) and the hyphen (writer's problem...). + +=head2 anchorify + + anchorify(@heading); + +Similar to C<htmlify()>, but turns non-alphanumerics into underscores. Note +that C<anchorify()> is not exported by default. + +=head1 ENVIRONMENT + +Uses C<$Config{pod2html}> to setup default options. + +=head1 AUTHOR + +Tom Christiansen, E<lt>tchrist@perl.comE<gt>. + +=head1 SEE ALSO + +L<perlpod> + +=head1 COPYRIGHT + +This program is distributed under the Artistic License. + +=cut + +my ($Cachedir); +my ( $Dircache, $Itemcache ); +my @Begin_Stack; +my @Libpods; +my ( $Htmlroot, $Htmldir, $Htmlfile, $Htmlfileurl ); +my ( $Podfile, @Podpath, $Podroot ); +my $Css; + +my $Recurse; +my $Quiet; +my $HiddenDirs; +my $Verbose; +my $Doindex; + +my $Backlink; +my ( $Listlevel, @Listend ); +my $After_Lpar; +use vars qw($Ignore); # need to localize it later. + +my ( %Items_Named, @Items_Seen ); +my ( $Title, $Header ); + +my $Top; +my $Paragraph; + +my %Sections; + +# Caches +my %Pages = (); # associative array used to find the location + # of pages referenced by L<> links. +my %Items = (); # associative array used to find the location + # of =item directives referenced by C<> links + +my %Local_Items; +my $Is83; + +my $Curdir = File::Spec->curdir; + +init_globals(); + +sub init_globals { + $Cachedir = "."; # The directory to which item and directory + # caches will be written. + + $Dircache = "pod2htmd.tmp"; + $Itemcache = "pod2htmi.tmp"; + + @Begin_Stack = (); # begin/end stack + + @Libpods = (); # files to search for links from C<> directives + $Htmlroot = "/"; # http-server base directory from which all + # relative paths in $podpath stem. + $Htmldir = ""; # The directory to which the html pages + # will (eventually) be written. + $Htmlfile = ""; # write to stdout by default + $Htmlfileurl = ""; # The url that other files would use to + # refer to this file. This is only used + # to make relative urls that point to + # other files. + + $Podfile = ""; # read from stdin by default + @Podpath = (); # list of directories containing library pods. + $Podroot = $Curdir; # filesystem base directory from which all + # relative paths in $podpath stem. + $Css = ''; # Cascading style sheet + $Recurse = 1; # recurse on subdirectories in $podpath. + $Quiet = 0; # not quiet by default + $Verbose = 0; # not verbose by default + $Doindex = 1; # non-zero if we should generate an index + $Backlink = ''; # text for "back to top" links + $Listlevel = 0; # current list depth + @Listend = (); # the text to use to end the list. + $After_Lpar = 0; # set to true after a par in an =item + $Ignore = 1; # whether or not to format text. we don't + # format text until we hit our first pod + # directive. + + @Items_Seen = (); # for multiples of the same item in perlfunc + %Items_Named = (); + $Header = 0; # produce block header/footer + $Title = ''; # title to give the pod(s) + $Top = 1; # true if we are at the top of the doc. used + # to prevent the first <hr /> directive. + $Paragraph = ''; # which paragraph we're processing (used + # for error messages) + %Sections = (); # sections within this page + + %Local_Items = (); + $Is83 = $^O eq 'dos'; # Is it an 8.3 filesystem? +} + +# +# clean_data: global clean-up of pod data +# +sub clean_data($) { + my ($dataref) = @_; + for my $i ( 0 .. $#{$dataref} ) { + ${$dataref}[$i] =~ s/\s+\Z//; + + # have a look for all-space lines + if ( ${$dataref}[$i] =~ /^\s+$/m and $dataref->[$i] !~ /^\s/ ) { + my @chunks = split( /^\s+$/m, ${$dataref}[$i] ); + splice( @$dataref, $i, 1, @chunks ); + } + } +} + +sub pod2html { + local (@ARGV) = @_; + local ($/); + local $_; + + init_globals(); + + $Is83 = 0 if ( defined(&Dos::UseLFN) && Dos::UseLFN() ); + + # cache of %Pages and %Items from last time we ran pod2html + + #undef $opt_help if defined $opt_help; + + # parse the command-line parameters + parse_command_line(); + + # escape the backlink argument (same goes for title but is done later...) + $Backlink = html_escape($Backlink) if defined $Backlink; + + # set some variables to their default values if necessary + local *POD; + unless ( @ARGV && $ARGV[0] ) { + $Podfile = "-" unless $Podfile; # stdin + open( POD, "<$Podfile" ) + || die "$0: cannot open $Podfile file for input: $!\n"; + } else { + $Podfile = $ARGV[0]; # XXX: might be more filenames + *POD = *ARGV; + } + $Htmlfile = "-" unless $Htmlfile; # stdout + $Htmlroot = "" if $Htmlroot eq "/"; # so we don't get a // + $Htmldir =~ s#/\z##; # so we don't get a // + if ( $Htmlroot eq '' + && defined($Htmldir) + && $Htmldir ne '' + && substr( $Htmlfile, 0, length($Htmldir) ) eq $Htmldir ) + { + + # Set the 'base' url for this file, so that we can use it + # as the location from which to calculate relative links + # to other files. If this is '', then absolute links will + # be used throughout. + $Htmlfileurl = "$Htmldir/" . substr( $Htmlfile, length($Htmldir) + 1 ); + } + + # read the pod a paragraph at a time + warn "Scanning for sections in input file(s)\n" if $Verbose; + $/ = ""; + my @poddata = <POD>; + close(POD); + + # be eol agnostic + for (@poddata) { + if (/\r/) { + if (/\r\n/) { + @poddata = map { + s/\r\n/\n/g; + /\n\n/ + ? map { "$_\n\n" } split /\n\n/ + : $_ + } @poddata; + } else { + @poddata = map { + s/\r/\n/g; + /\n\n/ + ? map { "$_\n\n" } split /\n\n/ + : $_ + } @poddata; + } + last; + } + } + + clean_data( \@poddata ); + + # scan the pod for =head[1-6] directives and build an index + my $index = scan_headings( \%Sections, @poddata ); + + unless ($index) { + warn "No headings in $Podfile\n" if $Verbose; + } + + # open the output file + open( HTML, ">$Htmlfile" ) + || die "$0: cannot open $Htmlfile file for output: $!\n"; + + # put a title in the HTML file if one wasn't specified + if ( $Title eq '' ) { + TITLE_SEARCH: { + for ( my $i = 0 ; $i < @poddata ; $i++ ) { + if ( $poddata[$i] =~ /^=head1\s*NAME\b/m ) { + for my $para ( @poddata[ $i, $i + 1 ] ) { + last TITLE_SEARCH + if ($Title) = $para =~ /(\S+\s+-+.*\S)/s; + } + } + + } + } + } + if ( !$Title and $Podfile =~ /\.pod\z/ ) { + + # probably a split pod so take first =head[12] as title + for ( my $i = 0 ; $i < @poddata ; $i++ ) { + last if ($Title) = $poddata[$i] =~ /^=head[12]\s*(.*)/; + } + warn "adopted '$Title' as title for $Podfile\n" + if $Verbose and $Title; + } + if ($Title) { + $Title =~ s/\s*\(.*\)//; + } else { + warn "$0: no title for $Podfile.\n" unless $Quiet; + $Podfile =~ /^(.*)(\.[^.\/]+)?\z/s; + $Title = ( $Podfile eq "-" ? 'No Title' : $1 ); + warn "using $Title" if $Verbose; + } + $Title = html_escape($Title); + + my $csslink = ''; + my $bodystyle = ' style="background-color: white"'; + my $tdstyle = ' style="background-color: #cccccc"'; + + if ($Css) { + $csslink = qq(\n<link rel="stylesheet" href="$Css" type="text/css" />); + $csslink =~ s,\\,/,g; + $csslink =~ s,(/.):,$1|,; + $bodystyle = ''; + $tdstyle = ''; + } + + my $block = $Header ? <<END_OF_BLOCK : ''; +<table border="0" width="100%" cellspacing="0" cellpadding="3"> +<tr><td class="block"$tdstyle valign="middle"> +<big><strong><span class="block"> $Title</span></strong></big> +</td></tr> +</table> +END_OF_BLOCK + + print HTML <<END_OF_HEAD; +<?xml version="1.0" ?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<title>$Title</title>$csslink +<meta http-equiv="content-type" content="text/html; charset=utf-8" /> +<link rev="made" href="mailto:$Config{perladmin}" /> +<style type="text/css"> + .branch { + list-style: none; + } + + li code { + padding-right: 0.5em; + } + + .example { + width: 98%; + padding: 0.5em; + float: left; + font-family: monospace; + } + + .example .line_number { + float: left; + text-align: right; + margin-right: 10px; + padding-right: 5px; + border-right: 1px solid white; + } + + .example .content { + float: left; + } + + .example .content pre { + margin: 0; + } + + td > table { + margin: 0.5em; + border-collapse: collapse; + } + + td > table td { + border: 1px solid black; + } + + .synComment { + color: rgb(135,206,235); + } + .synPreProc { + color: rgb(205,92,92); + } + .synError { + } + .synConstant { + color: #ffa0a0; + } + .synSpecial { + color: rgb(255,222,173); + } + .synIgnore { + color: rgb(102,102,102); + } + .synNormal { + color: rgb(255,255,255); + background-color: rgb(51,51,51); + } + .synType { + color: rgb(189,183,107); + } + .synIdentifier { + color: rgb(152,251,152); + } + .synTodo { + color: rgb(255,69,0); + background-color: rgb(238,238,0); + } + .synStatement { + color: rgb(240,230,140); + } + +</style> +</head> + +<body$bodystyle> +$block +END_OF_HEAD + + # load/reload/validate/cache %Pages and %Items + get_cache( $Dircache, $Itemcache, \@Podpath, $Podroot, $Recurse ); + + # scan the pod for =item directives + scan_items( \%Local_Items, "", @poddata ); + + # put an index at the top of the file. note, if $Doindex is 0 we + # still generate an index, but surround it with an html comment. + # that way some other program can extract it if desired. + $index =~ s/--+/-/g; + + my $hr = ( $Doindex and $index ) ? qq(<hr />) : ""; + + unless ($Doindex) { + $index = qq(<!--\n$index\n-->\n); + } + + print HTML << "END_OF_INDEX"; + +<!-- INDEX BEGIN --> +<div> +<p><a name=\"__index__\"></a></p> +$index +$hr +</div> +<!-- INDEX END --> + +END_OF_INDEX + + # now convert this file + my $after_item; # set to true after an =item + my $need_dd = 0; + warn "Converting input file $Podfile\n" if $Verbose; + foreach my $i ( 0 .. $#poddata ) { + $_ = $poddata[$i]; + $Paragraph = $i + 1; + if (/^(=.*)/s) { # is it a pod directive? + $Ignore = 0; + $after_item = 0; + $need_dd = 0; + $_ = $1; + if (/^=begin\s+(\S+)\s*(.*)/si) { # =begin + process_begin( $1, $2 ); + } elsif (/^=end\s+(\S+)\s*(.*)/si) { # =end + process_end( $1, $2 ); + } elsif (/^=cut/) { # =cut + process_cut(); + } elsif (/^=pod/) { # =pod + process_pod(); + } else { + next if @Begin_Stack && $Begin_Stack[-1] ne 'html'; + + if (/^=(head[1-6])\s+(.*\S)/s) { # =head[1-6] heading + process_head( $1, $2, $Doindex && $index ); + } elsif (/^=item\s*(.*\S)?/sm) { # =item text + $need_dd = process_item($1); + $after_item = 1; + } elsif (/^=over\s*(.*)/) { # =over N + process_over(); + } elsif (/^=back/) { # =back + process_back($need_dd); + } elsif (/^=for\s+(\S+)\s*(.*)/si) { # =for + process_for( $1, $2 ); + } else { + /^=(\S*)\s*/; + warn "$0: $Podfile: unknown pod directive '$1' in " + . "paragraph $Paragraph. ignoring.\n" + unless $Quiet; + } + } + $Top = 0; + } else { + next if $Ignore; + next if @Begin_Stack && $Begin_Stack[-1] ne 'html'; + print HTML and next if @Begin_Stack && $Begin_Stack[-1] eq 'html'; + print HTML "<dd>\n" if $need_dd; + my $text = $_; + if ( $text =~ /\A\s+/ ) { + process_pre( \$text ); + print HTML "<pre>\n$text</pre>\n"; + + } else { + process_text( \$text ); + + # experimental: check for a paragraph where all lines + # have some ...\t...\t...\n pattern + if ( $text =~ /\t/ ) { + my @lines = split( "\n", $text ); + if ( @lines > 1 ) { + my $all = 2; + foreach my $line (@lines) { + if ( $line =~ /\S/ && $line !~ /\t/ ) { + $all--; + last if $all == 0; + } + } + if ( $all > 0 ) { + $text =~ s/\t+/<td>/g; + $text =~ s/^/<tr><td>/gm; + $text = + '<table cellspacing="0" cellpadding="0">' + . $text + . '</table>'; + } + } + } + ## end of experimental + + if ($after_item) { + $After_Lpar = 1; + } + print HTML "<p>$text</p>\n"; + } + print HTML "</dd>\n" if $need_dd; + $after_item = 0; + } + } + + # finish off any pending directives + finish_list(); + + # link to page index + print HTML "<p><a href=\"#__index__\"><small>$Backlink</small></a></p>\n" + if $Doindex + and $index + and $Backlink; + + print HTML <<END_OF_TAIL; +$block +</body> + +</html> +END_OF_TAIL + + # close the html file + close(HTML); + + warn "Finished\n" if $Verbose; +} + +############################################################################## + +sub usage { + my $podfile = shift; + warn "$0: $podfile: @_\n" if @_; + die <<END_OF_USAGE; +Usage: $0 --help --htmlroot=<name> --infile=<name> --outfile=<name> + --podpath=<name>:...:<name> --podroot=<name> + --libpods=<name>:...:<name> --recurse --verbose --index + --netscape --norecurse --noindex --cachedir=<name> + + --backlink - set text for "back to top" links (default: none). + --cachedir - directory for the item and directory cache files. + --css - stylesheet URL + --flush - flushes the item and directory caches. + --[no]header - produce block header/footer (default is no headers). + --help - prints this message. + --hiddendirs - search hidden directories in podpath + --htmldir - directory for resulting HTML files. + --htmlroot - http-server base directory from which all relative paths + in podpath stem (default is /). + --[no]index - generate an index at the top of the resulting html + (default behaviour). + --infile - filename for the pod to convert (input taken from stdin + by default). + --libpods - colon-separated list of pages to search for =item pod + directives in as targets of C<> and implicit links (empty + by default). note, these are not filenames, but rather + page names like those that appear in L<> links. + --outfile - filename for the resulting html file (output sent to + stdout by default). + --podpath - colon-separated list of directories containing library + pods (empty by default). + --podroot - filesystem base directory from which all relative paths + in podpath stem (default is .). + --[no]quiet - suppress some benign warning messages (default is off). + --[no]recurse - recurse on those subdirectories listed in podpath + (default behaviour). + --title - title that will appear in resulting html file. + --[no]verbose - self-explanatory (off by default). + --[no]netscape - deprecated, has no effect. for backwards compatibility only. + +END_OF_USAGE + +} + +sub parse_command_line { + my ( + $opt_backlink, $opt_cachedir, $opt_css, $opt_flush, + $opt_header, $opt_help, $opt_htmldir, $opt_htmlroot, + $opt_index, $opt_infile, $opt_libpods, $opt_netscape, + $opt_outfile, $opt_podpath, $opt_podroot, $opt_quiet, + $opt_recurse, $opt_title, $opt_verbose, $opt_hiddendirs + ); + + unshift @ARGV, split ' ', $Config{pod2html} if $Config{pod2html}; + my $result = GetOptions( + 'backlink=s' => \$opt_backlink, + 'cachedir=s' => \$opt_cachedir, + 'css=s' => \$opt_css, + 'flush' => \$opt_flush, + 'header!' => \$opt_header, + 'help' => \$opt_help, + 'hiddendirs!' => \$opt_hiddendirs, + 'htmldir=s' => \$opt_htmldir, + 'htmlroot=s' => \$opt_htmlroot, + 'index!' => \$opt_index, + 'infile=s' => \$opt_infile, + 'libpods=s' => \$opt_libpods, + 'netscape!' => \$opt_netscape, + 'outfile=s' => \$opt_outfile, + 'podpath=s' => \$opt_podpath, + 'podroot=s' => \$opt_podroot, + 'quiet!' => \$opt_quiet, + 'recurse!' => \$opt_recurse, + 'title=s' => \$opt_title, + 'verbose!' => \$opt_verbose, + ); + usage( "-", "invalid parameters" ) if not $result; + + usage("-") if defined $opt_help; # see if the user asked for help + $opt_help = ""; # just to make -w shut-up. + + @Podpath = split( ":", $opt_podpath ) if defined $opt_podpath; + @Libpods = split( ":", $opt_libpods ) if defined $opt_libpods; + + $Backlink = $opt_backlink if defined $opt_backlink; + $Cachedir = $opt_cachedir if defined $opt_cachedir; + $Css = $opt_css if defined $opt_css; + $Header = $opt_header if defined $opt_header; + $Htmldir = $opt_htmldir if defined $opt_htmldir; + $Htmlroot = $opt_htmlroot if defined $opt_htmlroot; + $Doindex = $opt_index if defined $opt_index; + $Podfile = $opt_infile if defined $opt_infile; + $HiddenDirs = $opt_hiddendirs if defined $opt_hiddendirs; + $Htmlfile = $opt_outfile if defined $opt_outfile; + $Podroot = $opt_podroot if defined $opt_podroot; + $Quiet = $opt_quiet if defined $opt_quiet; + $Recurse = $opt_recurse if defined $opt_recurse; + $Title = $opt_title if defined $opt_title; + $Verbose = $opt_verbose if defined $opt_verbose; + + warn "Flushing item and directory caches\n" + if $opt_verbose && defined $opt_flush; + $Dircache = "$Cachedir/pod2htmd.tmp"; + $Itemcache = "$Cachedir/pod2htmi.tmp"; + if ( defined $opt_flush ) { + 1 while unlink( $Dircache, $Itemcache ); + } +} + +my $Saved_Cache_Key; + +sub get_cache { + my ( $dircache, $itemcache, $podpath, $podroot, $recurse ) = @_; + my @cache_key_args = @_; + + # A first-level cache: + # Don't bother reading the cache files if they still apply + # and haven't changed since we last read them. + + my $this_cache_key = cache_key(@cache_key_args); + + return if $Saved_Cache_Key and $this_cache_key eq $Saved_Cache_Key; + + # load the cache of %Pages and %Items if possible. $tests will be + # non-zero if successful. + my $tests = 0; + if ( -f $dircache && -f $itemcache ) { + warn "scanning for item cache\n" if $Verbose; + $tests = load_cache( $dircache, $itemcache, $podpath, $podroot ); + } + + # if we didn't succeed in loading the cache then we must (re)build + # %Pages and %Items. + if ( !$tests ) { + warn "scanning directories in pod-path\n" if $Verbose; + scan_podpath( $podroot, $recurse, 0 ); + } + $Saved_Cache_Key = cache_key(@cache_key_args); +} + +sub cache_key { + my ( $dircache, $itemcache, $podpath, $podroot, $recurse ) = @_; + return join( '!', + $dircache, $itemcache, $recurse, @$podpath, $podroot, stat($dircache), + stat($itemcache) ); +} + +# +# load_cache - tries to find if the caches stored in $dircache and $itemcache +# are valid caches of %Pages and %Items. if they are valid then it loads +# them and returns a non-zero value. +# +sub load_cache { + my ( $dircache, $itemcache, $podpath, $podroot ) = @_; + my ($tests); + local $_; + + $tests = 0; + + open( CACHE, "<$itemcache" ) + || die "$0: error opening $itemcache for reading: $!\n"; + $/ = "\n"; + + # is it the same podpath? + $_ = <CACHE>; + chomp($_); + $tests++ if ( join( ":", @$podpath ) eq $_ ); + + # is it the same podroot? + $_ = <CACHE>; + chomp($_); + $tests++ if ( $podroot eq $_ ); + + # load the cache if its good + if ( $tests != 2 ) { + close(CACHE); + return 0; + } + + warn "loading item cache\n" if $Verbose; + while (<CACHE>) { + /(.*?) (.*)$/; + $Items{$1} = $2; + } + close(CACHE); + + warn "scanning for directory cache\n" if $Verbose; + open( CACHE, "<$dircache" ) + || die "$0: error opening $dircache for reading: $!\n"; + $/ = "\n"; + $tests = 0; + + # is it the same podpath? + $_ = <CACHE>; + chomp($_); + $tests++ if ( join( ":", @$podpath ) eq $_ ); + + # is it the same podroot? + $_ = <CACHE>; + chomp($_); + $tests++ if ( $podroot eq $_ ); + + # load the cache if its good + if ( $tests != 2 ) { + close(CACHE); + return 0; + } + + warn "loading directory cache\n" if $Verbose; + while (<CACHE>) { + /(.*?) (.*)$/; + $Pages{$1} = $2; + } + + close(CACHE); + + return 1; +} + +# +# scan_podpath - scans the directories specified in @podpath for directories, +# .pod files, and .pm files. it also scans the pod files specified in +# @Libpods for =item directives. +# +sub scan_podpath { + my ( $podroot, $recurse, $append ) = @_; + my ( $pwd, $dir ); + my ( $libpod, $dirname, $pod, @files, @poddata ); + + unless ($append) { + %Items = (); + %Pages = (); + } + + # scan each directory listed in @Podpath + $pwd = getcwd(); + chdir($podroot) + || die "$0: error changing to directory $podroot: $!\n"; + foreach $dir (@Podpath) { + scan_dir( $dir, $recurse ); + } + + # scan the pods listed in @Libpods for =item directives + foreach $libpod (@Libpods) { + + # if the page isn't defined then we won't know where to find it + # on the system. + next unless defined $Pages{$libpod} && $Pages{$libpod}; + + # if there is a directory then use the .pod and .pm files within it. + # NOTE: Only finds the first so-named directory in the tree. + # if ($Pages{$libpod} =~ /([^:]*[^(\.pod|\.pm)]):/) { + if ( $Pages{$libpod} =~ /([^:]*(?<!\.pod)(?<!\.pm)):/ ) { + + # find all the .pod and .pm files within the directory + $dirname = $1; + opendir( DIR, $dirname ) + || die "$0: error opening directory $dirname: $!\n"; + @files = grep( /(\.pod|\.pm)\z/ && !-d $_, readdir(DIR) ); + closedir(DIR); + + # scan each .pod and .pm file for =item directives + foreach $pod (@files) { + open( POD, "<$dirname/$pod" ) + || die "$0: error opening $dirname/$pod for input: $!\n"; + @poddata = <POD>; + close(POD); + clean_data( \@poddata ); + + scan_items( \%Items, "$dirname/$pod", @poddata ); + } + + # use the names of files as =item directives too. +### Don't think this should be done this way - confuses issues.(WL) +### foreach $pod (@files) { +### $pod =~ /^(.*)(\.pod|\.pm)$/; +### $Items{$1} = "$dirname/$1.html" if $1; +### } + } elsif ( $Pages{$libpod} =~ /([^:]*\.pod):/ + || $Pages{$libpod} =~ /([^:]*\.pm):/ ) + { + + # scan the .pod or .pm file for =item directives + $pod = $1; + open( POD, "<$pod" ) + || die "$0: error opening $pod for input: $!\n"; + @poddata = <POD>; + close(POD); + clean_data( \@poddata ); + + scan_items( \%Items, "$pod", @poddata ); + } else { + warn "$0: shouldn't be here (line " . __LINE__ . "\n" unless $Quiet; + } + } + @poddata = (); # clean-up a bit + + chdir($pwd) + || die "$0: error changing to directory $pwd: $!\n"; + + # cache the item list for later use + warn "caching items for later use\n" if $Verbose; + open( CACHE, ">$Itemcache" ) + || die "$0: error open $Itemcache for writing: $!\n"; + + print CACHE join( ":", @Podpath ) . "\n$podroot\n"; + foreach my $key ( keys %Items ) { + print CACHE "$key $Items{$key}\n"; + } + + close(CACHE); + + # cache the directory list for later use + warn "caching directories for later use\n" if $Verbose; + open( CACHE, ">$Dircache" ) + || die "$0: error open $Dircache for writing: $!\n"; + + print CACHE join( ":", @Podpath ) . "\n$podroot\n"; + foreach my $key ( keys %Pages ) { + print CACHE "$key $Pages{$key}\n"; + } + + close(CACHE); +} + +# +# scan_dir - scans the directory specified in $dir for subdirectories, .pod +# files, and .pm files. notes those that it finds. this information will +# be used later in order to figure out where the pages specified in L<> +# links are on the filesystem. +# +sub scan_dir { + my ( $dir, $recurse ) = @_; + my ( $t, @subdirs, @pods, $pod, $dirname, @dirs ); + local $_; + + @subdirs = (); + @pods = (); + + opendir( DIR, $dir ) + || die "$0: error opening directory $dir: $!\n"; + while ( defined( $_ = readdir(DIR) ) ) { + if ( -d "$dir/$_" + && $_ ne "." + && $_ ne ".." + && ( $HiddenDirs || !/^\./ ) ) + { # directory + $Pages{$_} = "" unless defined $Pages{$_}; + $Pages{$_} .= "$dir/$_:"; + push( @subdirs, $_ ); + } elsif (/\.pod\z/) { # .pod + s/\.pod\z//; + $Pages{$_} = "" unless defined $Pages{$_}; + $Pages{$_} .= "$dir/$_.pod:"; + push( @pods, "$dir/$_.pod" ); + } elsif (/\.html\z/) { # .html + s/\.html\z//; + $Pages{$_} = "" unless defined $Pages{$_}; + $Pages{$_} .= "$dir/$_.pod:"; + } elsif (/\.pm\z/) { # .pm + s/\.pm\z//; + $Pages{$_} = "" unless defined $Pages{$_}; + $Pages{$_} .= "$dir/$_.pm:"; + push( @pods, "$dir/$_.pm" ); + } elsif ( -T "$dir/$_" ) { # script(?) + local *F; + if ( open( F, "$dir/$_" ) ) { + my $line; + while ( defined( $line = <F> ) ) { + if ( $line =~ /^=(?:pod|head1)/ ) { + $Pages{$_} = "" unless defined $Pages{$_}; + $Pages{$_} .= "$dir/$_.pod:"; + last; + } + } + close(F); + } + } + } + closedir(DIR); + + # recurse on the subdirectories if necessary + if ($recurse) { + foreach my $subdir (@subdirs) { + scan_dir( "$dir/$subdir", $recurse ); + } + } +} + +# +# scan_headings - scan a pod file for head[1-6] tags, note the tags, and +# build an index. +# +sub scan_headings { + my ( $sections, @data ) = @_; + my ( $tag, $which_head, $otitle, $listdepth, $index ); + + local $Ignore = 0; + + $listdepth = 0; + $index = ""; + + # scan for =head directives, note their name, and build an index + # pointing to each of them. + foreach my $line (@data) { + if ( $line =~ /^=(head)([1-6])\s+(.*)/ ) { + ( $tag, $which_head, $otitle ) = ( $1, $2, $3 ); + + my $title = depod($otitle); + my $name = anchorify($title); + $$sections{$name} = 1; + $title = process_text( \$otitle ); + + while ( $which_head != $listdepth ) { + if ( $which_head > $listdepth ) { + $index .= "\n" + . ( "\t" x ($listdepth) ) + . ( $listdepth > 0 ? qq{<li class="branch">\n} + . "\t"x($listdepth + 1): "" ) + . "<ul>"; + $listdepth++; + } elsif ( $which_head < $listdepth ) { + $listdepth--; + $index .= "\n" + . ( "\t" x $listdepth ) + . ( $listdepth > 0 ? "\t" : "" ) + . "</ul>" + . ( $listdepth >= 0 ? "\n" . ("\t"x$listdepth) + . "</li>" : "" ) + . "\n"; + } + } + + $index .= "\n" + . ( "\t" x $listdepth ) . "<li>" + . "<a href=\"#" + . $name . "\">" + . $title + . "</a></li>"; + } + } + + # finish off the lists + while ( $listdepth-- ) { + $index .= "\n" . ( "\t" x $listdepth ) + . ($listdepth > 0 ? "\t" : "") + ."</ul>\n" + . ($listdepth > 0 ? ("\t" x $listdepth) . "</li>" : "" ); + } + + # get rid of bogus lists + $index =~ s,\t*<ul>\s*</ul>\n,,g; + + return $index; +} + +# +# scan_items - scans the pod specified by $pod for =item directives. we +# will use this information later on in resolving C<> links. +# +sub scan_items { + my ( $itemref, $pod, @poddata ) = @_; + my ( $i, $item ); + local $_; + + $pod =~ s/\.pod\z//; + $pod .= ".html" if $pod; + + foreach $i ( 0 .. $#poddata ) { + my $txt = depod( $poddata[$i] ); + + # figure out what kind of item it is. + # Build string for referencing this item. + if ( $txt =~ /\A=item\s+\*\s*(.*)\Z/s ) { # bullet + next unless $1; + $item = $1; + } elsif ( $txt =~ /\A=item\s+(?>\d+\.?)\s*(.*)\Z/s ) { # numbered list + $item = $1; + } elsif ( $txt =~ /\A=item\s+(.*)\Z/s ) { # plain item + $item = $1; + } else { + next; + } + my $fid = fragment_id($item); + $$itemref{$fid} = "$pod" if $fid; + } +} + +# +# process_head - convert a pod head[1-6] tag and convert it to HTML format. +# +sub process_head { + my ( $tag, $heading, $hasindex ) = @_; + + # figure out the level of the =head + $tag =~ /head([1-6])/; + my $level = $1; + + if ($Listlevel) { + warn +"$0: $Podfile: unterminated list at =head in paragraph $Paragraph. ignoring.\n" + unless $Quiet; + while ($Listlevel) { + process_back(); + } + } + + print HTML "<p>\n"; + if ( $level == 1 && !$Top ) { + print HTML "<a href=\"#__index__\"><small>$Backlink</small></a>\n" + if $hasindex and $Backlink; + print HTML "</p>\n<hr />\n"; + } else { + print HTML "</p>\n"; + } + + my $name = anchorify( depod($heading) ); + my $convert = process_text( \$heading ); + $convert =~ s{</?a[^>]+>}{}g; + print HTML "<h$level><a name=\"$name\" />$convert</h$level>\n"; +} + +# +# emit_item_tag - print an =item's text +# Note: The global $EmittedItem is used for inhibiting self-references. +# +my $EmittedItem; + +sub emit_item_tag($$$) { + my ( $otext, $text, $compact ) = @_; + my $item = fragment_id( depod($text), -generate ); + Carp::confess( "Undefined fragment '$text' (" + . depod($text) + . ") from fragment_id() in emit_item_tag() in $Podfile" ) + if !defined $item; + $EmittedItem = $item; + ### print STDERR "emit_item_tag=$item ($text)\n"; + + print HTML '<strong>'; + if ( $Items_Named{$item}++ ) { + print HTML process_text( \$otext ); + } else { + my $name = $item; + $name = anchorify($name); + print HTML +#qq{<a name="$name" class="item">}, + process_text( \$otext ), + # '</a>' + ; + } + print HTML "</strong>\n"; + undef($EmittedItem); +} + +sub emit_li { + my ($tag) = @_; + if ( $Items_Seen[$Listlevel]++ == 0 ) { + push( @Listend, "</$tag>" ); + print HTML "<$tag>\n"; + } + my $emitted = $tag eq 'dl' ? 'dt' : 'li'; + print HTML "<$emitted>"; + return $emitted; +} + +# +# process_item - convert a pod item tag and convert it to HTML format. +# +sub process_item { + my ($otext) = @_; + my $need_dd = 0; # set to 1 if we need a <dd></dd> after an item + + # lots of documents start a list without doing an =over. this is + # bad! but, the proper thing to do seems to be to just assume + # they did do an =over. so warn them once and then continue. + if ( $Listlevel == 0 ) { + warn +"$0: $Podfile: unexpected =item directive in paragraph $Paragraph. ignoring.\n" + unless $Quiet; + process_over(); + } + + # formatting: insert a paragraph if preceding item has >1 paragraph + if ($After_Lpar) { + print HTML $need_dd ? "</dd>\n" : "</li>\n" if $After_Lpar; + $After_Lpar = 0; + } + + # remove formatting instructions from the text + my $text = depod($otext); + + my $emitted; # the tag actually emitted, used for closing + + # all the list variants: + if ( $text =~ /\A\*/ ) { # bullet + $emitted = emit_li('ul'); + if ( $text =~ /\A\*\s+(\S.*)\Z/s ) { # with additional text + my $tag = $1; + $otext =~ s/\A\*\s+//; + emit_item_tag( $otext, $tag, 1 ); + } + print HTML "</li>" + } elsif ( $text =~ /\A\d+/ ) { # numbered list + $emitted = emit_li('ol'); + if ( $text =~ /\A(?>\d+\.?)\s*(\S.*)\Z/s ) { # with additional text + my $tag = $1; + $otext =~ s/\A\d+\.?\s*//; + emit_item_tag( $otext, $tag, 1 ); + } + print HTML "</li>"; + } else { # definition list + $emitted = emit_li('dl'); + if ( $text =~ /\A(.+)\Z/s ) { # should have text + emit_item_tag( $otext, $text, 1 ); + } + $need_dd = 1; + } + print HTML "\n"; + return $need_dd; +} + +# +# process_over - process a pod over tag and start a corresponding HTML list. +# +sub process_over { + + # start a new list + $Listlevel++; + push( @Items_Seen, 0 ); + $After_Lpar = 0; +} + +# +# process_back - process a pod back tag and convert it to HTML format. +# +sub process_back { + my $need_dd = shift; + if ( $Listlevel == 0 ) { + warn +"$0: $Podfile: unexpected =back directive in paragraph $Paragraph. ignoring.\n" + unless $Quiet; + return; + } + + # close off the list. note, I check to see if $Listend[$Listlevel] is + # defined because an =item directive may have never appeared and thus + # $Listend[$Listlevel] may have never been initialized. + $Listlevel--; + if ( defined $Listend[$Listlevel] ) { + print HTML $need_dd ? "</dd>\n" : "</li>\n" if $After_Lpar; + print HTML $Listend[$Listlevel]; + print HTML "\n"; + pop(@Listend); + } + $After_Lpar = 0; + + # clean up item count + pop(@Items_Seen); +} + +# +# process_cut - process a pod cut tag, thus start ignoring pod directives. +# +sub process_cut { + $Ignore = 1; +} + +# +# process_pod - process a pod tag, thus stop ignoring pod directives +# until we see a corresponding cut. +# +sub process_pod { + + # no need to set $Ignore to 0 cause the main loop did it +} + +# +# process_for - process a =for pod tag. if it's for html, spit +# it out verbatim, if illustration, center it, otherwise ignore it. +# +sub process_for { + my ( $whom, $text ) = @_; + if ( $whom =~ /^(pod2)?html$/i ) { + print HTML $text; + } elsif ( $whom =~ /^illustration$/i ) { + 1 while chomp $text; + for my $ext (qw[.png .gif .jpeg .jpg .tga .pcl .bmp]) { + $text .= $ext, last if -r "$text$ext"; + } + print HTML +qq{<p align="center"><img src="$text" alt="$text illustration" /></p>}; + } +} + +# +# process_begin - process a =begin pod tag. this pushes +# whom we're beginning on the begin stack. if there's a +# begin stack, we only print if it us. +# +sub process_begin { + my ( $whom, $text ) = @_; + $whom = lc($whom); + push( @Begin_Stack, $whom ); + if ( $whom =~ /^(pod2)?html$/ ) { + print HTML $text if $text; + } +} + +# +# process_end - process a =end pod tag. pop the +# begin stack. die if we're mismatched. +# +sub process_end { + my ( $whom, $text ) = @_; + $whom = lc($whom); + if ( !defined $Begin_Stack[-1] or $Begin_Stack[-1] ne $whom ) { + Carp::confess( + "Unmatched begin/end at chunk $Paragraph in pod $Podfile\n"); + } + pop(@Begin_Stack); +} + +# +# process_pre - indented paragraph, made into <pre></pre> +# +sub process_pre { + my ($text) = @_; + my ($rest); + return if $Ignore; + + $rest = $$text; + + # insert spaces in place of tabs + $rest =~ s#(.+)# + my $line = $1; + 1 while $line =~ s/(\t+)/' ' x ((length($1) * 8) - $-[0] % 8)/e; + $line; + #eg; + + # convert some special chars to HTML escapes + $rest = html_escape($rest); + + # try and create links for all occurrences of perl.* within + # the preformatted text. + $rest =~ s{ + (\s*)(perl\w+) + }{ + if ( defined $Pages{$2} ){ # is a link + qq($1<a href="$Htmlroot/$Pages{$2}">$2</a>); + } elsif (defined $Pages{dosify($2)}) { # is a link + qq($1<a href="$Htmlroot/$Pages{dosify($2)}">$2</a>); + } else { + "$1$2"; + } + }xeg; + $rest =~ s{ + (<a\ href="?) ([^>:]*:)? ([^>:]*) \.pod: ([^>:]*:)? + }{ + my $url ; + if ( $Htmlfileurl ne '' ){ + # Here, we take advantage of the knowledge + # that $Htmlfileurl ne '' implies $Htmlroot eq ''. + # Since $Htmlroot eq '', we need to prepend $Htmldir + # on the fron of the link to get the absolute path + # of the link's target. We check for a leading '/' + # to avoid corrupting links that are #, file:, etc. + my $old_url = $3 ; + $old_url = "$Htmldir$old_url" if $old_url =~ m{^\/}; + $url = relativize_url( "$old_url.html", $Htmlfileurl ); + } else { + $url = "$3.html" ; + } + "$1$url" ; + }xeg; + + # Look for embedded URLs and make them into links. We don't + # relativize them since they are best left as the author intended. + + my $urls = '(' . join( + '|', qw{ + http + telnet + mailto + news + gopher + file + wais + ftp + } + ) . ')'; + + my $ltrs = '\w'; + my $gunk = '/#~:.?+=&%@!\-'; + my $punc = '.:!?\-;'; + my $any = "${ltrs}${gunk}${punc}"; + + $rest =~ s{ + \b # start at word boundary + ( # begin $1 { + $urls : # need resource and a colon + (?!:) # Ignore File::, among others. + [$any] +? # followed by one or more of any valid + # character, but be conservative and + # take only what you need to.... + ) # end $1 } + (?= + " > # maybe pre-quoted '<a href="...">' + | # or: + [$punc]* # 0 or more punctuation + (?: # followed + [^$any] # by a non-url char + | # or + $ # end of the string + ) # + | # or else + $ # then end of the string + ) + }{<a href="$1">$1</a>}igox; + + # text should be as it is (verbatim) + $$text = $rest; +} + +# +# pure text processing +# +# pure_text/inIS_text: differ with respect to automatic C<> recognition. +# we don't want this to happen within IS +# +sub pure_text($) { + my $text = shift(); + process_puretext( $text, 1 ); +} + +sub inIS_text($) { + my $text = shift(); + process_puretext( $text, 0 ); +} + +# +# process_puretext - process pure text (without pod-escapes) converting +# double-quotes and handling implicit C<> links. +# +sub process_puretext { + my ( $text, $notinIS ) = @_; + + ## Guessing at func() or [\$\@%&]*var references in plain text is destined + ## to produce some strange looking ref's. uncomment to disable: + ## $notinIS = 0; + + my ( @words, $lead, $trail ); + + # keep track of leading and trailing white-space + $lead = ( $text =~ s/\A(\s+)//s ? $1 : "" ); + $trail = ( $text =~ s/(\s+)\Z//s ? $1 : "" ); + + # split at space/non-space boundaries + @words = split( /(?<=\s)(?=\S)|(?<=\S)(?=\s)/, $text ); + + # process each word individually + foreach my $word (@words) { + + # skip space runs + next if $word =~ /^\s*$/; + + # see if we can infer a link or a function call + # + # NOTE: This is a word based search, it won't automatically + # mark "substr($var, 1, 2)" because the 1st word would be "substr($var" + # User has to enclose those with proper C<> + + if ( + $notinIS + && $word =~ m/ + ^([a-z_]{2,}) # The function name + \( + ([0-9][a-z]* # Manual page(1) or page(1M) + |[^)]*[\$\@\%][^)]+ # ($foo), (1, @foo), (%hash) + | # () + ) + \) + ([.,;]?)$ # a possible punctuation follows + /xi + ) + { + + # has parenthesis so should have been a C<> ref + ## try for a pagename (perlXXX(1))? + my ( $func, $args, $rest ) = ( $1, $2, $3 || '' ); + if ( $args =~ /^\d+$/ ) { + my $url = page_sect( $word, '' ); + if ( defined $url ) { + $word = +qq(<a href="$url" class="man">the $word manpage</a>$rest); + next; + } + } + ## try function name for a link, append tt'ed argument list + $word = emit_C( $func, '', "($args)" ) . $rest; + +#### disabled. either all (including $\W, $\w+{.*} etc.) or nothing. +## } elsif( $notinIS && $word =~ /^[\$\@%&*]+\w+$/) { +## # perl variables, should be a C<> ref +## $word = emit_C( $word ); + + } elsif ( $word =~ m,^\w+://\w, ) { + + # looks like a URL + # Don't relativize it: leave it as the author intended + $word = qq(<a href="$word">$word</a>); + } elsif ( $word =~ /[\w.-]+\@[\w-]+\.\w/ ) { + + # looks like an e-mail address + my ( $w1, $w2, $w3 ) = ( "", $word, "" ); + ( $w1, $w2, $w3 ) = ( "(", $1, ")$2" ) if $word =~ /^\((.*?)\)(,?)/; + ( $w1, $w2, $w3 ) = ( "<", $1, ">$2" ) + if $word =~ /^<(.*?)>(,?)/; + $word = qq($w1<a href="mailto:$w2">$w2</a>$w3); + } else { + $word = html_escape($word) if $word =~ /["&<>]/; + } + } + + # put everything back together + return $lead . join( '', @words ) . $trail; +} + +# +# process_text - handles plaintext that appears in the input pod file. +# there may be pod commands embedded within the text so those must be +# converted to html commands. +# + +sub process_text1($$;$$); +sub pattern ($) { $_[0] ? '\s+' . ( '>' x ( $_[0] + 1 ) ) : '>' } +sub closing ($) { local ($_) = shift; ( defined && s/\s+\z// ) ? length : 0 } + +sub process_text { + return if $Ignore; + my ($tref) = @_; + my $res = process_text1( 0, $tref ); + $res =~ s/\s+$//s; + $$tref = $res; +} + +sub process_text_rfc_links { + my $text = shift; + + # For every "RFCnnnn" or "RFC nnn", link it to the authoritative + # ource. Do not use the /i modifier here. Require "RFC" to be written in + # in capital letters. + + $text =~ s{ + (?<=[^<>[:alpha:]]) # Make sure this is not an URL already + (RFC\s*([0-9]{1,5}))(?![0-9]) # max 5 digits + } + {<a href="http://www.ietf.org/rfc/rfc$2.txt" class="rfc">$1</a>}gx; + + $text; +} + +sub process_text1($$;$$) { + my ( $lev, $rstr, $func, $closing ) = @_; + my $res = ''; + + unless ( defined $func ) { + $func = ''; + $lev++; + } + + if ( $func eq 'B' ) { + + # B<text> - boldface + $res = '<strong>' . process_text1( $lev, $rstr ) . '</strong>'; + + } elsif ( $func eq 'C' ) { + + # C<code> - can be a ref or <code></code> + # need to extract text + my $par = go_ahead( $rstr, 'C', $closing ); + + ## clean-up of the link target + my $text = depod($par); + + ### my $x = $par =~ /[BI]</ ? 'yes' : 'no' ; + ### print STDERR "-->call emit_C($par) lev=$lev, par with BI=$x\n"; + + $res = emit_C( $text, $lev > 1 || ( $par =~ /[BI]</ ) ); + + } elsif ( $func eq 'E' ) { + + # E<x> - convert to character + $$rstr =~ s/^([^>]*)>//; + my $escape = $1; + $escape =~ s/^(\d+|X[\dA-F]+)$/#$1/i; + $res = "&$escape;"; + + } elsif ( $func eq 'F' ) { + + # F<filename> - italicize + $res = '<em class="file">' . process_text1( $lev, $rstr ) . '</em>'; + + } elsif ( $func eq 'I' ) { + + # I<text> - italicize + $res = '<em>' . process_text1( $lev, $rstr ) . '</em>'; + + } elsif ( $func eq 'L' ) { + + # L<link> - link + ## L<text|cross-ref> => produce text, use cross-ref for linking + ## L<cross-ref> => make text from cross-ref + ## need to extract text + my $par = go_ahead( $rstr, 'L', $closing ); + + # some L<>'s that shouldn't be: + # a) full-blown URL's are emitted as-is + if ( $par =~ m{^\w+://}s ) { + return make_URL_href($par); + } + + # b) C<...> is stripped and treated as C<> + if ( $par =~ /^C<(.*)>$/ ) { + my $text = depod($1); + return emit_C( $text, $lev > 1 || ( $par =~ /[BI]</ ) ); + } + + # analyze the contents + $par =~ s/\n/ /g; # undo word-wrapped tags + my $opar = $par; + my $linktext; + if ( $par =~ s{^([^|]+)\|}{} ) { + $linktext = $1; + } + + if( $par =~ m{^\w+://}s ) { + return make_URL_href( $par, $linktext ); + } + + # make sure sections start with a / + $par =~ s{^"}{/"}; + + my ( $page, $section, $ident ); + + # check for link patterns + if ( $par =~ m{^([^/]+?)/(?!")(.*?)$} ) { # name/ident + # we've got a name/ident (no quotes) + if ( length $2 ) { + ( $page, $ident ) = ( $1, $2 ); + } else { + ( $page, $section ) = ( $1, $2 ); + } + ### print STDERR "--> L<$par> to page $page, ident $ident\n"; + + } elsif ( $par =~ m{^(.*?)/"?(.*?)"?$} ) { # [name]/"section" + # even though this should be a "section", we go for ident first + ( $page, $ident ) = ( $1, $2 ); + ### print STDERR "--> L<$par> to page $page, section $section\n"; + + } elsif ( $par =~ /\s/ ) { # this must be a section with missing quotes + ( $page, $section ) = ( '', $par ); + ### print STDERR "--> L<$par> to void page, section $section\n"; + + } else { + ( $page, $section ) = ( $par, '' ); + ### print STDERR "--> L<$par> to page $par, void section\n"; + } + + # now, either $section or $ident is defined. the convoluted logic + # below tries to resolve L<> according to what the user specified. + # failing this, we try to find the next best thing... + my ( $url, $ltext, $fid ); + + RESOLVE: { + if ( defined $ident ) { + ## try to resolve $ident as an item + ( $url, $fid ) = coderef( $page, $ident ); + if ($url) { + if ( !defined($linktext) ) { + $linktext = $ident; + $linktext .= " in " if $ident && $page; + $linktext .= "the $page manpage" if $page; + } + ### print STDERR "got coderef url=$url\n"; + last RESOLVE; + } + ## no luck: go for a section (auto-quoting!) + $section = $ident; + } + ## now go for a section + my $htmlsection = htmlify($section); + $url = page_sect( $page, $htmlsection ); + if ($url) { + if ( !defined($linktext) ) { + $linktext = $section; + $linktext .= " in " if $section && $page; + $linktext .= "the $page manpage" if $page; + } + ### print STDERR "got page/section url=$url\n"; + last RESOLVE; + } + ## no luck: go for an ident + if ($section) { + $ident = $section; + } else { + $ident = $page; + $page = undef(); + } + ( $url, $fid ) = coderef( $page, $ident ); + if ($url) { + if ( !defined($linktext) ) { + $linktext = $ident; + $linktext .= " in " if $ident && $page; + $linktext .= "the $page manpage" if $page; + } + ### print STDERR "got section=>coderef url=$url\n"; + last RESOLVE; + } + + # warning; show some text. + $linktext = $opar unless defined $linktext; + warn +"$0: $Podfile: cannot resolve L<$opar> in paragraph $Paragraph.\n" + unless $Quiet; + } + + # now we have a URL or just plain code + $$rstr = $linktext . '>' . $$rstr; + if ( defined($url) ) { + $res = "<a href=\"$url\">" . process_text1( $lev, $rstr ) . '</a>'; + } else { + $res = '<em>' . process_text1( $lev, $rstr ) . '</em>'; + } + + } elsif ( $func eq 'S' ) { + + # S<text> - non-breaking spaces + $res = process_text1( $lev, $rstr ); + $res =~ s/ / /g; + + } elsif ( $func eq 'X' ) { + + # X<> - ignore + warn "$0: $Podfile: invalid X<> in paragraph $Paragraph.\n" + unless $$rstr =~ s/^[^>]*>// + or $Quiet; + } elsif ( $func eq 'Z' ) { + + # Z<> - empty + warn "$0: $Podfile: invalid Z<> in paragraph $Paragraph.\n" + unless $$rstr =~ s/^>// + or $Quiet; + + } else { + my $term = pattern $closing; + while ( $$rstr =~ s/\A(.*?)(([BCEFILSXZ])<(<+[^\S\n]+)?|$term)//s ) { + + # all others: either recurse into new function or + # terminate at closing angle bracket(s) + my $pt = $1; + $pt .= $2 if !$3 && $lev == 1; + $res .= $lev == 1 ? pure_text($pt) : inIS_text($pt); + return $res if !$3 && $lev > 1; + if ($3) { + $res .= process_text1( $lev, $rstr, $3, closing $4 ); + } + } + if ( $lev == 1 ) { + $res .= pure_text($$rstr); + } elsif ( !$Quiet ) { + my $snippet = substr( $$rstr, 0, 60 ); + warn +"$0: $Podfile: undelimited $func<> in paragraph $Paragraph: '$snippet'.\n" + + } + $res = process_text_rfc_links($res); + } + return $res; +} + +# +# go_ahead: extract text of an IS (can be nested) +# +sub go_ahead($$$) { + my ( $rstr, $func, $closing ) = @_; + my $res = ''; + my @closing = ($closing); + while ( $$rstr =~ + s/\A(.*?)(([BCEFILSXZ])<(<+\s+)?|@{[pattern $closing[0]]})//s ) + { + $res .= $1; + unless ($3) { + shift @closing; + return $res unless @closing; + } else { + unshift @closing, closing $4; + } + $res .= $2; + } + unless ($Quiet) { + my $snippet = substr( $$rstr, 0, 60 ); + warn +"$0: $Podfile: undelimited $func<> in paragraph $Paragraph (go_ahead): '$snippet'.\n"; + } + return $res; +} + +# +# emit_C - output result of C<text> +# $text is the depod-ed text +# +sub emit_C($;$$) { + my ( $text, $nocode, $args ) = @_; + $args = '' unless defined $args; + my $res; + my ( $url, $fid ) = coderef( undef(), $text ); + + # need HTML-safe text + my $linktext = html_escape("$text$args"); + + if ( $text !~ /^[\$@%]/ + && defined($url) + && ( !defined($EmittedItem) || $EmittedItem ne $fid ) ) + { + $res = "<a href=\"$url\"><code>$linktext</code></a>"; + } elsif ( 0 && $nocode ) { + $res = $linktext; + } else { + $res = "<code>$linktext</code>"; + } + return $res; +} + +# +# html_escape: make text safe for HTML +# +sub html_escape { + my $rest = $_[0]; + $rest =~ s/&/&/g; + $rest =~ s/</</g; + $rest =~ s/>/>/g; + $rest =~ s/"/"/g; + + # ' is only in XHTML, not HTML4. Be conservative + #$rest =~ s/'/'/g; + return $rest; +} + +# +# dosify - convert filenames to 8.3 +# +sub dosify { + my ($str) = @_; + return lc($str) if $^O eq 'VMS'; # VMS just needs casing + if ($Is83) { + $str = lc $str; + $str =~ s/(\.\w+)/substr ($1,0,4)/ge; + $str =~ s/(\w+)/substr ($1,0,8)/ge; + } + return $str; +} + +# +# page_sect - make a URL from the text of a L<> +# +sub page_sect($$) { + my ( $page, $section ) = @_; + my ( $linktext, $page83, $link ); # work strings + + # check if we know that this is a section in this page + if ( !defined $Pages{$page} && defined $Sections{$page} ) { + $section = $page; + $page = ""; + ### print STDERR "reset page='', section=$section\n"; + } + + $page83 = dosify($page); + $page = $page83 if ( defined $Pages{$page83} ); + if ( $page eq "" ) { + $link = "#" . anchorify($section); + } elsif ( $page =~ /::/ ) { + $page =~ s,::,/,g; + + # Search page cache for an entry keyed under the html page name, + # then look to see what directory that page might be in. NOTE: + # this will only find one page. A better solution might be to produce + # an intermediate page that is an index to all such pages. + my $page_name = $page; + $page_name =~ s,^.*/,,s; + if ( defined( $Pages{$page_name} ) + && $Pages{$page_name} =~ /([^:]*$page)\.(?:pod|pm):/ ) + { + $page = $1; + } else { + + # NOTE: This branch assumes that all A::B pages are located in + # $Htmlroot/A/B.html . This is often incorrect, since they are + # often in $Htmlroot/lib/A/B.html or such like. Perhaps we could + # analyze the contents of %Pages and figure out where any + # cousins of A::B are, then assume that. So, if A::B isn't found, + # but A::C is found in lib/A/C.pm, then A::B is assumed to be in + # lib/A/B.pm. This is also limited, but it's an improvement. + # Maybe a hints file so that the links point to the correct places + # nonetheless? + + } + $link = "$Htmlroot/$page.html"; + $link .= "#" . anchorify($section) if ($section); + } elsif ( !defined $Pages{$page} ) { + $link = ""; + } else { + $section = anchorify($section) if $section ne ""; + ### print STDERR "...section=$section\n"; + + # if there is a directory by the name of the page, then assume that an + # appropriate section will exist in the subdirectory + # if ($section ne "" && $Pages{$page} =~ /([^:]*[^(\.pod|\.pm)]):/) { + if ( $section ne "" && $Pages{$page} =~ /([^:]*(?<!\.pod)(?<!\.pm)):/ ) + { + $link = "$Htmlroot/$1/$section.html"; + ### print STDERR "...link=$link\n"; + + # since there is no directory by the name of the page, the section will + # have to exist within a .html of the same name. thus, make sure there + # is a .pod or .pm that might become that .html + } else { + $section = "#$section" if $section; + ### print STDERR "...section=$section\n"; + + # check if there is a .pod with the page name. + # for L<Foo>, Foo.(pod|pm) is preferred to A/Foo.(pod|pm) + if ( $Pages{$page} =~ /([^:]*)\.(?:pod|pm):/ ) { + $link = "$Htmlroot/$1.html$section"; + } else { + $link = ""; + } + } + } + + if ($link) { + + # Here, we take advantage of the knowledge that $Htmlfileurl ne '' + # implies $Htmlroot eq ''. This means that the link in question + # needs a prefix of $Htmldir if it begins with '/'. The test for + # the initial '/' is done to avoid '#'-only links, and to allow + # for other kinds of links, like file:, ftp:, etc. + my $url; + if ( $Htmlfileurl ne '' ) { + $link = "$Htmldir$link" if $link =~ m{^/}s; + $url = relativize_url( $link, $Htmlfileurl ); + + # print( " b: [$link,$Htmlfileurl,$url]\n" ); + } else { + $url = $link; + } + return $url; + + } else { + return undef(); + } +} + +# +# relativize_url - convert an absolute URL to one relative to a base URL. +# Assumes both end in a filename. +# +sub relativize_url { + my ( $dest, $source ) = @_; + + my ( $dest_volume, $dest_directory, $dest_file ) = + File::Spec::Unix->splitpath($dest); + $dest = File::Spec::Unix->catpath( $dest_volume, $dest_directory, '' ); + + my ( $source_volume, $source_directory, $source_file ) = + File::Spec::Unix->splitpath($source); + $source = + File::Spec::Unix->catpath( $source_volume, $source_directory, '' ); + + my $rel_path = ''; + if ( $dest ne '' ) { + $rel_path = File::Spec::Unix->abs2rel( $dest, $source ); + } + + if ( $rel_path ne '' + && substr( $rel_path, -1 ) ne '/' + && substr( $dest_file, 0, 1 ) ne '#' ) + { + $rel_path .= "/$dest_file"; + } else { + $rel_path .= "$dest_file"; + } + + return $rel_path; +} + +# +# coderef - make URL from the text of a C<> +# +sub coderef($$) { + my ( $page, $item ) = @_; + my ($url); + + my $fid = fragment_id($item); + + if ( defined($page) && $page ne "" ) { + + # we have been given a $page... + $page =~ s{::}{/}g; + + Carp::confess( +"Undefined fragment '$item' from fragment_id() in coderef() in $Podfile" + ) if !defined $fid; + + # Do we take it? Item could be a section! + my $base = $Items{$fid} || ""; + $base =~ s{[^/]*/}{}; + if ( $base ne "$page.html" ) { + ### print STDERR "coderef( $page, $item ): items{$fid} = $Items{$fid} = $base => discard page!\n"; + $page = undef(); + } + + } else { + + # no page - local items precede cached items + if ( defined($fid) ) { + if ( exists $Local_Items{$fid} ) { + $page = $Local_Items{$fid}; + } else { + $page = $Items{$fid}; + } + } + } + + # if there was a pod file that we found earlier with an appropriate + # =item directive, then create a link to that page. + if ( defined $page ) { + if ($page) { + if ( exists $Pages{$page} and $Pages{$page} =~ /([^:.]*)\.[^:]*:/ ) + { + $page = $1 . '.html'; + } + my $link = "$Htmlroot/$page#" . anchorify($fid); + + # Here, we take advantage of the knowledge that $Htmlfileurl + # ne '' implies $Htmlroot eq ''. + if ( $Htmlfileurl ne '' ) { + $link = "$Htmldir$link"; + $url = relativize_url( $link, $Htmlfileurl ); + } else { + $url = $link; + } + } else { + $url = "#" . anchorify($fid); + } + + confess "url has space: $url" if $url =~ /"[^"]*\s[^"]*"/; + } + return ( $url, $fid ); +} + +# +# Adapted from Nick Ing-Simmons' PodToHtml package. +sub relative_url { + my $source_file = shift; + my $destination_file = shift; + + my $source = URI::file->new_abs($source_file); + my $uo = URI::file->new( $destination_file, $source )->abs; + return $uo->rel->as_string; +} + +# +# finish_list - finish off any pending HTML lists. this should be called +# after the entire pod file has been read and converted. +# +sub finish_list { + while ( $Listlevel > 0 ) { + print HTML "</dl>\n"; + $Listlevel--; + } +} + +# +# htmlify - converts a pod section specification to a suitable section +# specification for HTML. Note that we keep spaces and special characters +# except ", ? (Netscape problem) and the hyphen (writer's problem...). +# +sub htmlify { + my ($heading) = @_; + $heading =~ s/(\s+)/ /g; + $heading =~ s/\s+\Z//; + $heading =~ s/\A\s+//; + + # The hyphen is a disgrace to the English language. + # $heading =~ s/[-"?]//g; + $heading =~ s/["?]//g; + $heading = lc($heading); + return $heading; +} + +# +# similar to htmlify, but turns non-alphanumerics into underscores +# +sub anchorify { + my ($anchor) = @_; + $anchor =~ s/\([^)]*\)//; + $anchor = htmlify($anchor); + $anchor =~ s/\W/_/g; + $anchor =~ tr/_/_/s; + return $anchor; +} + +# +# depod - convert text by eliminating all interior sequences +# Note: can be called with copy or modify semantics +# +my %E2c; +$E2c{lt} = '<'; +$E2c{gt} = '>'; +$E2c{sol} = '/'; +$E2c{verbar} = '|'; +$E2c{amp} = '&'; # in Tk's pods + +sub depod1($;$$); + +sub depod($) { + my $string; + if ( ref( $_[0] ) ) { + $string = ${ $_[0] }; + ${ $_[0] } = depod1( \$string ); + } else { + $string = $_[0]; + depod1( \$string ); + } +} + +sub depod1($;$$) { + my ( $rstr, $func, $closing ) = @_; + my $res = ''; + return $res unless defined $$rstr; + if ( !defined($func) ) { + + # skip to next begin of an interior sequence + while ( $$rstr =~ s/\A(.*?)([BCEFILSXZ])<(<+[^\S\n]+)?//s ) { + + # recurse into its text + $res .= $1 . depod1( $rstr, $2, closing $3); + } + $res .= $$rstr; + } elsif ( $func eq 'E' ) { + + # E<x> - convert to character + $$rstr =~ s/^([^>]*)>//; + $res .= $E2c{$1} || ""; + } elsif ( $func eq 'X' ) { + + # X<> - ignore + $$rstr =~ s/^[^>]*>//; + } elsif ( $func eq 'Z' ) { + + # Z<> - empty + $$rstr =~ s/^>//; + } else { + + # all others: either recurse into new function or + # terminate at closing angle bracket + my $term = pattern $closing; + while ( $$rstr =~ s/\A(.*?)(([BCEFILSXZ])<(<+[^\S\n]+)?|$term)//s ) { + $res .= $1; + last unless $3; + $res .= depod1( $rstr, $3, closing $4 ); + } + ## If we're here and $2 ne '>': undelimited interior sequence. + ## Ignored, as this is called without proper indication of where we are. + ## Rely on process_text to produce diagnostics. + } + return $res; +} + +{ + my %seen; # static fragment record hash + + sub fragment_id_readable { + my $text = shift; + my $generate = shift; # optional flag + + my $orig = $text; + + # leave the words for the fragment identifier, + # change everything else to underbars. + $text =~ + s/[^A-Za-z0-9_]+/_/g; # do not use \W to avoid locale dependency. + $text =~ s/_{2,}/_/g; + $text =~ s/\A_//; + $text =~ s/_\Z//; + + unless ($text) { + + # Nothing left after removing punctuation, so leave it as is + # E.g. if option is named: "=item -#" + + $text = $orig; + } + + if ($generate) { + if ( exists $seen{$text} ) { + + # This already exists, make it unique + $seen{$text}++; + $text = $text . $seen{$text}; + } else { + $seen{$text} = 1; # first time seen this fragment + } + } + + $text; + } +} + +my @HC; + +sub fragment_id_obfuscated { # This was the old "_2d_2d__" + my $text = shift; + my $generate = shift; # optional flag + + # text? Normalize by obfuscating the fragment id to make it unique + $text =~ s/\s+/_/sg; + + $text =~ s{(\W)}{ + defined( $HC[ord($1)] ) ? $HC[ord($1)] + : ( $HC[ord($1)] = sprintf( "%%%02X", ord($1) ) ) }gxe; + $text = substr( $text, 0, 50 ); + + $text; +} + +# +# fragment_id - construct a fragment identifier from: +# a) =item text +# b) contents of C<...> +# + +sub fragment_id { + my $text = shift; + my $generate = shift; # optional flag + + $text =~ s/\s+\Z//s; + if ($text) { + + # a method or function? + return $1 if $text =~ /(\w+)\s*\(/; + return $1 if $text =~ /->\s*(\w+)\s*\(?/; + + # a variable name? + return $1 if $text =~ /^([\$\@%*]\S+)/; + + # some pattern matching operator? + return $1 if $text =~ m|^(\w+/).*/\w*$|; + + # fancy stuff... like "do { }" + return $1 if $text =~ m|^(\w+)\s*{.*}$|; + + # honour the perlfunc manpage: func [PAR[,[ ]PAR]...] + # and some funnies with ... Module ... + return $1 if $text =~ m{^([a-z\d_]+)(\s+[A-Z,/& ][A-Z\d,/& ]*)?$}; + return $1 if $text =~ m{^([a-z\d]+)\s+Module(\s+[A-Z\d,/& ]+)?$}; + + return fragment_id_readable( $text, $generate ); + } else { + return; + } +} + +# +# make_URL_href - generate HTML href from URL +# Special treatment for CGI queries. +# +sub make_URL_href($;$) { + my ($url) = shift; + my $linktext = shift || $url; + if ( $url !~ s{^(http:[-\w/#~:.+=&%@!]+)(\?.*)$}{<a href="$1$2">$1</a>}i ) { + $url = "<a href=\"$url\">$linktext</a>"; + } + return $url; +} + +1; diff --git a/plugins/perl/lib/Xchat.pm b/plugins/perl/lib/Xchat.pm new file mode 100644 index 00000000..74914882 --- /dev/null +++ b/plugins/perl/lib/Xchat.pm @@ -0,0 +1,506 @@ +BEGIN { + $INC{'Xchat.pm'} = 'DUMMY'; +} + +$SIG{__WARN__} = sub { + my $message = shift @_; + my ($package) = caller; + + # redirect Gtk/Glib errors and warnings back to STDERR + my $message_levels = qr/ERROR|CRITICAL|WARNING|MESSAGE|INFO|DEBUG/i; + if( $message =~ /^(?:Gtk|GLib|Gdk)(?:-\w+)?-$message_levels/i ) { + print STDERR $message; + } else { + + if( defined &Xchat::Internal::print ) { + Xchat::print( $message ); + } else { + warn $message; + } + } +}; + +use File::Spec (); +use File::Basename (); +use File::Glob (); +use List::Util (); +use Symbol(); +use Time::HiRes (); +use Carp (); + +package Xchat; +use base qw(Exporter); +use strict; +use warnings; + +sub PRI_HIGHEST (); +sub PRI_HIGH (); +sub PRI_NORM (); +sub PRI_LOW (); +sub PRI_LOWEST (); + +sub EAT_NONE (); +sub EAT_XCHAT (); +sub EAT_PLUIN (); +sub EAT_ALL (); + +sub KEEP (); +sub REMOVE (); +sub FD_READ (); +sub FD_WRITE (); +sub FD_EXCEPTION (); +sub FD_NOTSOCKET (); + +sub get_context; +sub Xchat::Internal::context_info; +sub Xchat::Internal::print; + +our %EXPORT_TAGS = ( + constants => [ + qw(PRI_HIGHEST PRI_HIGH PRI_NORM PRI_LOW PRI_LOWEST), # priorities + qw(EAT_NONE EAT_XCHAT EAT_PLUGIN EAT_ALL), # callback return values + qw(FD_READ FD_WRITE FD_EXCEPTION FD_NOTSOCKET), # fd flags + qw(KEEP REMOVE), # timers + ], + hooks => [ + qw(hook_server hook_command hook_print hook_timer hook_fd unhook), + ], + util => [ + qw(register nickcmp strip_code send_modes), # misc + qw(print prnt printf prntf command commandf emit_print), # output + qw(find_context get_context set_context), # context + qw(get_info get_prefs get_list context_info user_info), # input + ], +); + +$EXPORT_TAGS{all} = [ map { @{$_} } @EXPORT_TAGS{qw(constants hooks util)}]; +our @EXPORT = @{$EXPORT_TAGS{constants}}; +our @EXPORT_OK = @{$EXPORT_TAGS{all}}; + +sub register { + my $package = Xchat::Embed::find_pkg(); + my $pkg_info = Xchat::Embed::pkg_info( $package ); + my $filename = $pkg_info->{filename}; + my ($name, $version, $description, $callback) = @_; + + if( defined $pkg_info->{gui_entry} ) { + Xchat::print( "Xchat::register called more than once in " + . $pkg_info->{filename} ); + return (); + } + + $description = "" unless defined $description; + $pkg_info->{shutdown} = $callback; + unless( $name && $name =~ /[[:print:]\w]/ ) { + $name = "Not supplied"; + } + unless( $version && $version =~ /\d+(?:\.\d+)?/ ) { + $version = "NaN"; + } + $pkg_info->{gui_entry} = + Xchat::Internal::register( $name, $version, $description, $filename ); + # keep with old behavior + return (); +} + +sub _process_hook_options { + my ($options, $keys, $store) = @_; + + unless( @$keys == @$store ) { + die 'Number of keys must match the size of the store'; + } + + my @results; + + if( ref( $options ) eq 'HASH' ) { + for my $index ( 0 .. @$keys - 1 ) { + my $key = $keys->[$index]; + if( exists( $options->{ $key } ) && defined( $options->{ $key } ) ) { + ${$store->[$index]} = $options->{ $key }; + } + } + } + +} + +sub hook_server { + return undef unless @_ >= 2; + my $message = shift; + my $callback = shift; + my $options = shift; + my $package = Xchat::Embed::find_pkg(); + + $callback = Xchat::Embed::fix_callback( $package, $callback ); + + my ($priority, $data) = ( Xchat::PRI_NORM, undef ); + _process_hook_options( + $options, + [qw(priority data)], + [\($priority, $data)], + ); + + my $pkg_info = Xchat::Embed::pkg_info( $package ); + my $hook = Xchat::Internal::hook_server( + $message, $priority, $callback, $data + ); + push @{$pkg_info->{hooks}}, $hook if defined $hook; + return $hook; +} + +sub hook_command { + return undef unless @_ >= 2; + my $command = shift; + my $callback = shift; + my $options = shift; + my $package = Xchat::Embed::find_pkg(); + + $callback = Xchat::Embed::fix_callback( $package, $callback ); + + my ($priority, $help_text, $data) = ( Xchat::PRI_NORM, undef, undef ); + _process_hook_options( + $options, + [qw(priority help_text data)], + [\($priority, $help_text, $data)], + ); + + my $pkg_info = Xchat::Embed::pkg_info( $package ); + my $hook = Xchat::Internal::hook_command( + $command, $priority, $callback, $help_text, $data + ); + push @{$pkg_info->{hooks}}, $hook if defined $hook; + return $hook; +} + +sub hook_print { + return undef unless @_ >= 2; + my $event = shift; + my $callback = shift; + my $options = shift; + my $package = Xchat::Embed::find_pkg(); + + $callback = Xchat::Embed::fix_callback( $package, $callback ); + + my ($priority, $run_after, $filter, $data) = ( Xchat::PRI_NORM, 0, 0, undef ); + _process_hook_options( + $options, + [qw(priority run_after_event filter data)], + [\($priority, $run_after, $filter, $data)], + ); + + if( $run_after and $filter ) { + Carp::carp( "Xchat::hook_print's run_after_event and filter options are mutually exclusive, you can only use of them at a time per hook" ); + return; + } + + if( $run_after ) { + my $cb = $callback; + $callback = sub { + my @args = @_; + hook_timer( 0, sub { + $cb->( @args ); + + if( ref $run_after eq 'CODE' ) { + $run_after->( @args ); + } + return REMOVE; + }); + return EAT_NONE; + }; + } + + if( $filter ) { + my $cb = $callback; + $callback = sub { + my @args = @{$_[0]}; + my $last_arg = @args - 1; + + my @new = $cb->( \@args, $_[1], $event ); + + # a filter can either return the new results or it can modify + # @_ in place. + if( @new ) { + emit_print( $event, @new[ 0 .. $last_arg ] ); + return EAT_ALL; + } elsif( + join( "\0", @{$_[0]} ) ne join( "\0", @args[ 0 .. $last_arg ] ) + ) { + emit_print( $event, @args[ 0 .. $last_arg ] ); + return EAT_ALL; + } + + return EAT_NONE; + }; + + } + + my $pkg_info = Xchat::Embed::pkg_info( $package ); + my $hook = Xchat::Internal::hook_print( + $event, $priority, $callback, $data + ); + push @{$pkg_info->{hooks}}, $hook if defined $hook; + return $hook; +} + +sub hook_timer { + return undef unless @_ >= 2; + my ($timeout, $callback, $data) = @_; + my $package = Xchat::Embed::find_pkg(); + + $callback = Xchat::Embed::fix_callback( $package, $callback ); + + if( + ref( $data ) eq 'HASH' && exists( $data->{data} ) + && defined( $data->{data} ) + ) { + $data = $data->{data}; + } + + my $pkg_info = Xchat::Embed::pkg_info( $package ); + my $hook = Xchat::Internal::hook_timer( $timeout, $callback, $data, $package ); + push @{$pkg_info->{hooks}}, $hook if defined $hook; + return $hook; +} + +sub hook_fd { + return undef unless @_ >= 2; + my ($fd, $callback, $options) = @_; + return undef unless defined $fd && defined $callback; + + my $fileno = fileno $fd; + return undef unless defined $fileno; # no underlying fd for this handle + + my ($package) = Xchat::Embed::find_pkg(); + $callback = Xchat::Embed::fix_callback( $package, $callback ); + + my ($flags, $data) = (Xchat::FD_READ, undef); + _process_hook_options( + $options, + [qw(flags data)], + [\($flags, $data)], + ); + + my $cb = sub { + my $userdata = shift; + return $userdata->{CB}->( + $userdata->{FD}, $userdata->{FLAGS}, $userdata->{DATA}, + ); + }; + + my $pkg_info = Xchat::Embed::pkg_info( $package ); + my $hook = Xchat::Internal::hook_fd( + $fileno, $cb, $flags, { + DATA => $data, FD => $fd, CB => $callback, FLAGS => $flags, + } + ); + push @{$pkg_info->{hooks}}, $hook if defined $hook; + return $hook; +} + +sub unhook { + my $hook = shift @_; + my $package = shift @_; + ($package) = caller unless $package; + my $pkg_info = Xchat::Embed::pkg_info( $package ); + + if( defined( $hook ) + && $hook =~ /^\d+$/ + && grep { $_ == $hook } @{$pkg_info->{hooks}} ) { + $pkg_info->{hooks} = [grep { $_ != $hook } @{$pkg_info->{hooks}}]; + return Xchat::Internal::unhook( $hook ); + } + return (); +} + +sub _do_for_each { + my ($cb, $channels, $servers) = @_; + + # not specifying any channels or servers is not the same as specifying + # undef for both + # - not specifying either results in calling the callback inthe current ctx + # - specifying undef for for both results in calling the callback in the + # front/currently selected tab + if( @_ == 3 && !($channels || $servers) ) { + $channels = [ undef ]; + $servers = [ undef ]; + } elsif( !($channels || $servers) ) { + $cb->(); + return 1; + } + + $channels = [ $channels ] unless ref( $channels ) eq 'ARRAY'; + + if( $servers ) { + $servers = [ $servers ] unless ref( $servers ) eq 'ARRAY'; + } else { + $servers = [ undef ]; + } + + my $num_done = 0; + my $old_ctx = Xchat::get_context(); + for my $server ( @$servers ) { + for my $channel ( @$channels ) { + if( Xchat::set_context( $channel, $server ) ) { + $cb->(); + $num_done++ + } + } + } + Xchat::set_context( $old_ctx ); + return $num_done; +} + +sub print { + my $text = shift @_; + return "" unless defined $text; + if( ref( $text ) eq 'ARRAY' ) { + if( $, ) { + $text = join $, , @$text; + } else { + $text = join "", @$text; + } + } + + return _do_for_each( + sub { Xchat::Internal::print( $text ); }, + @_ + ); +} + +sub printf { + my $format = shift; + Xchat::print( sprintf( $format, @_ ) ); +} + +# make Xchat::prnt() and Xchat::prntf() as aliases for Xchat::print() and +# Xchat::printf(), mainly useful when these functions are exported +sub prnt { + goto &Xchat::print; +} + +sub prntf { + goto &Xchat::printf; +} + +sub command { + my $command = shift; + return "" unless defined $command; + my @commands; + + if( ref( $command ) eq 'ARRAY' ) { + @commands = @$command; + } else { + @commands = ($command); + } + + return _do_for_each( + sub { Xchat::Internal::command( $_ ) foreach @commands }, + @_ + ); +} + +sub commandf { + my $format = shift; + Xchat::command( sprintf( $format, @_ ) ); +} + +sub set_context { + my $context; + if( @_ == 2 ) { + my ($channel, $server) = @_; + $context = Xchat::find_context( $channel, $server ); + } elsif( @_ == 1 ) { + if( defined $_[0] && $_[0] =~ /^\d+$/ ) { + $context = $_[0]; + } else { + $context = Xchat::find_context( $_[0] ); + } + } elsif( @_ == 0 ) { + $context = Xchat::find_context(); + } + return $context ? Xchat::Internal::set_context( $context ) : 0; +} + +sub get_info { + my $id = shift; + my $info; + + if( defined( $id ) ) { + if( grep { $id eq $_ } qw(state_cursor id) ) { + $info = Xchat::get_prefs( $id ); + } else { + $info = Xchat::Internal::get_info( $id ); + } + } + return $info; +} + +sub user_info { + my $nick = Xchat::strip_code(shift @_ || Xchat::get_info( "nick" )); + my $user; + for (Xchat::get_list( "users" ) ) { + if ( Xchat::nickcmp( $_->{nick}, $nick ) == 0 ) { + $user = $_; + last; + } + } + return $user; +} + +sub context_info { + my $ctx = shift @_ || Xchat::get_context; + my $old_ctx = Xchat::get_context; + my @fields = ( + qw(away channel charset host id inputbox libdirfs modes network), + qw(nick nickserv server topic version win_ptr win_status), + qw(xchatdir xchatdirfs state_cursor), + ); + + if( Xchat::set_context( $ctx ) ) { + my %info; + for my $field ( @fields ) { + $info{$field} = Xchat::get_info( $field ); + } + + my $ctx_info = Xchat::Internal::context_info; + @info{keys %$ctx_info} = values %$ctx_info; + + Xchat::set_context( $old_ctx ); + return %info if wantarray; + return \%info; + } else { + return undef; + } +} + +sub get_list { + unless( grep { $_[0] eq $_ } qw(channels dcc ignore notify users networks) ) { + Carp::carp( "'$_[0]' does not appear to be a valid list name" ); + } + if( $_[0] eq 'networks' ) { + return Xchat::List::Network->get(); + } else { + return Xchat::Internal::get_list( $_[0] ); + } +} + +sub strip_code { + my $pattern = qr< + \cB| #Bold + \cC\d{0,2}(?:,\d{1,2})?| #Color + \e\[(?:\d{1,2}(?:;\d{1,2})*)?m| # ANSI color code + \cG| #Beep + \cO| #Reset + \cV| #Reverse + \c_ #Underline + >x; + + if( defined wantarray ) { + my $msg = shift; + $msg =~ s/$pattern//g; + return $msg; + } else { + $_[0] =~ s/$pattern//g if defined $_[0]; + } +} + +1 diff --git a/plugins/perl/lib/Xchat.pod b/plugins/perl/lib/Xchat.pod new file mode 100644 index 00000000..a55a9bce --- /dev/null +++ b/plugins/perl/lib/Xchat.pod @@ -0,0 +1,1326 @@ +=head1 X-Chat 2 Perl Interface + +=head2 Introduction + +This is the new Perl interface for X-Chat 2. However, due to changes in +xchat's plugin code you will need xchat 2.0.8 or above to load this. Scripts +written using the old interface will continue to work. If there are any +problems, questions, comments or suggestions please email them to the address +on the bottom of this page. + +=head2 Constants + +=head3 Priorities + +=over 3 + +=item * +C<Xchat::PRI_HIGHEST> + +=item * +C<Xchat::PRI_HIGH> + +=item * +C<Xchat::PRI_NORM> + +=item * +C<Xchat::PRI_LOW> + +=item * +C<Xchat::PRI_LOWEST> + +=back + +=head3 Return values + +=over 3 + +=item * +C<Xchat::EAT_NONE> - pass the event along + +=item * +C<Xchat::EAT_XCHAT> - don't let xchat see this event + +=item * +C<Xchat::EAT_PLUGIN> - don't let other scripts and plugins see this event but xchat will still see it + +=item * +C<Xchat::EAT_ALL> - don't let anything else see this event + +=back + +=head4 Timer and fd hooks + +=over 3 + +=item * +C<Xchat::KEEP> - keep the timer going or hook watching the handle + +=item * +C<Xchat::REMOVE> - remove the timer or hook watching the handle + +=back + +=head3 hook_fd flags + +=over 3 + +=item * +C<Xchat::FD_READ> - invoke the callback when the handle is ready for reading + +=item * +C<Xchat::FD_WRITE> - invoke the callback when the handle is ready for writing + +=item * +C<Xchat::FD_EXCEPTION> - invoke the callback if an exception occurs + +=item * +C<Xchat::FD_NOTSOCKET> - indicate that the handle being hooked is not a socket + +=back + +=head2 Functions + +=head3 C<Xchat::register( $name, $version, [$description,[$callback]] )> + +=over 3 + +=item * +C<$name> - The name of this script + +=item * +C<$version> - This script's version + +=item * +C<$description> - A description for this script + +=item * +C<$callback> - This is a function that will be called when the is script + unloaded. This can be either a reference to a + function or an anonymous sub reference. + +=back + +This is the first thing to call in every script. + +=head3 C<Xchat::hook_server( $message, $callback, [\%options] )> + +=head3 C<Xchat::hook_command( $command, $callback, [\%options] )> + +=head3 C<Xchat::hook_print( $event,$callback, [\%options] )> + +=head3 C<Xchat::hook_timer( $timeout,$callback, [\%options | $data] )> + +=head3 C<Xchat::hook_fd( $handle, $callback, [ \%options ] )> + +These functions can be to intercept various events. +hook_server can be used to intercept any incoming message from the IRC server. +hook_command can be used to intercept any command, if the command doesn't currently exist then a new one is created. +hook_print can be used to intercept any of the events listed in Setttings-E<gt>Advanced-E<gt>Text Events +hook_timer can be used to create a new timer + + +=over 3 + +=item * +C<$message> - server message to hook such as PRIVMSG + +=item * +C<$command> - command to intercept, without the leading / + +=item * +C<$event> - one of the events listed in Settings-E<gt>Advanced-E<gt>Text Events + +=item * +C<$timeout> - timeout in milliseconds + +=item * +C<$handle> - the I/O handle you want to monitor with hook_fd. This must be something that has a fileno. See perldoc -f fileno or L<fileno|http://perldoc.perl.org/functions/fileno.html> + +=item * +C<$callback> - callback function, this is called whenever + the hooked event is trigged, the following are + the conditions that will trigger the different hooks. + This can be either a reference to a + function or an anonymous sub reference. + +=item * +\%options - a hash reference containing addional options for the hooks + +=back + +Valid keys for \%options: + +=begin html + +<table border="1"> + + <tr> + <td>data</td> <td>Additional data that is to be associated with the<br /> + hook. For timer hooks this value can be provided either as<br /> + <code>Xchat::hook_timer( $timeout, $cb,{data=>$data})</code><br /> + or <code>Xchat::hook_timer( $timeout, $cb, $data )</code>.<br /> + However, this means that hook_timer cannot be provided<br /> + with a hash reference containing data as a key.<br /> + + example:<br /> + my $options = { data => [@arrayOfStuff] };<br /> + Xchat::hook_timer( $timeout, $cb, $options );<br /> + <br /> + In this example, the timer's data will be<br /> + [@arrayOfStuff] and not { data => [@arrayOfStuff] }<br /> + <br /> + This key is valid for all of the hook functions.<br /> + <br /> + Default is undef.<br /> + </td> + </tr> + + <tr> + <td>priority</td> <td>Sets the priority for the hook.<br /> + It can be set to one of the + <code>Xchat::PRI_*</code> constants.<br /> + <br /> + This key only applies to server, command + and print hooks.<br /> + <br /> + Default is <code>Xchat::PRI_NORM</code>. + </td> + + </tr> + + <tr> + <td>help_text</td> <td>Text displayed for /help $command.<br /> + <br /> + This key only applies to command hooks.<br /> + <br /> + Default is "". + </td> + </tr> + + <tr> + <td>flags</td> <td>Specify the flags for a fd hook.<br /> + <br /> + See <a href="#hook_fd_flags">hook fd flags</a> section for valid values.<br /> + <br /> + On Windows if the handle is a pipe you specify<br /> + Xchat::FD_NOTSOCKET in addition to any other flags you might be using.<br /> + <br /> + This key only applies to fd hooks.<br /> + Default is Xchat::FD_READ + </td> + </tr> + +</table> + +=end html + +=head4 When callbacks are invoked + +Each of the hooks will be triggered at different times depending on the type +of hook. + +=begin html + +<table border="1"> + + <tr style="background-color: #dddddd"> + <td>Hook Type</td> <td>When the callback will be invoked</td> + </tr> + + <tr> + <td>server hooks</td> <td>a <code>$message</code> message is + received from the server + </td> + </tr> + + <tr> + <td>command hooks</td> <td>the <code>$command</code> command is + executed, either by the user or from a script + </td> + </tr> + + <tr> + <td>print hooks</td> <td>X-Chat is about to print the message for the + <code>$event</code> event + </td> + </tr> + + <tr> + <td>timer hooks</td> <td>called every <code>$timeout</code> milliseconds + (1000 millisecond is 1 second)<br /> + the callback will be executed in the same context where + the hook_timer was called, if the context no longer exists + then it will execute in a random context + </td> + </tr> + + <tr> + <td>fd hooks</td> <td>depends on the flags that were passed to hook_fd<br /> + See <a href="#hook_fd_flags">hook_fd flags</a> section. + </td> + </tr> +</table> + +=end html + + +The value return from these hook functions can be passed to C<Xchat::unhook> +to remove the hook. + +=head4 Callback Arguments + +All callback functions will receive their arguments in C<@_> like every +other Perl subroutine. + +=begin html + +<p> +Server and command callbacks<br /> +<br /> +<code>$_[0]</code> - array reference containing the IRC message or command and +arguments broken into words<br /> +example:<br /> +/command arg1 arg2 arg3<br /> +<code>$_[0][0]</code> - command<br /> +<code>$_[0][1]</code> - arg1<br /> +<code>$_[0][2]</code> - arg2<br /> +<code>$_[0][3]</code> - arg3<br /> +<br /> +<code>$_[1]</code> - array reference containing the Nth word to the last word<br /> +example:<br /> +/command arg1 arg2 arg3<br /> +<code>$_[1][0]</code> - command arg1 arg2 arg3<br /> +<code>$_[1][1]</code> - arg1 arg2 arg3<br /> +<code>$_[1][2]</code> - arg2 arg3<br /> +<code>$_[1][3]</code> - arg3<br /> +<br /> +<code>$_[2]</code> - the data that was passed to the hook function<br /> +<br /> +Print callbacks<br /> +<br /> +<code>$_[0]</code> - array reference containing the values for the + text event see Settings->Advanced->Text Events<br /> +<code>$_[1]</code> - the data that was passed to the hook function<br /> +<br /> +Timer callbacks<br /> +<br /> +<code>$_[0]</code> - the data that was passed to the hook function<br /> +<br /> + +fd callbacks<br /> +<br /> +<code>$_[0]</code> - the handle that was passed to hook_fd<br /> +<code>$_[1]</code> - flags indicating why the callback was called<br /> +<code>$_[2]</code> - the data that was passed to the hook function<br /> +</p> + +=end html + +=head4 Callback return values + +All server, command and print callbacks should return one of +the C<Xchat::EAT_*> constants. +Timer callbacks can return Xchat::REMOVE to remove +the timer or Xchat::KEEP to keep it going + +=head4 Miscellaneous Hook Related Information + +For server hooks, if C<$message> is "RAW LINE" then C<$cb> will be called for +every IRC message than X-Chat receives. + +For command hooks if C<$command> is "" then C<$cb> will be called for +messages entered by the user that is not a command. + +For print hooks besides those events listed in +Settings-E<gt>Advanced-E<gt>Text Events, these additional events can be used. + +=begin html + +<table border="1"> + + <tr style="background-color: #dddddd"> + <td>Event</td> <td>Description</td> + </tr> + + <tr> + <td>"Open Context"</td> <td>a new context is created</td> + </tr> + + <tr> + <td>"Close Context"</td> <td>a context has been close</td> + </tr> + + <tr> + <td>"Focus Tab"</td> <td>when a tab is brought to the front</td> + </tr> + + <tr> + <td>"Focus Window"</td> <td>when a top level window is focused or the + main tab window is focused by the window manager + </td> + </tr> + + <tr> + <td>"DCC Chat Text"</td> <td>when text from a DCC Chat arrives. + <code>$_[0]</code> will have these values<br /> + <br /> + <code>$_[0][0]</code> - Address<br /> + <code>$_[0][1]</code> - Port<br /> + <code>$_[0][2]</code> - Nick<br /> + <code>$_[0][3]</code> - Message<br /> + </td> + </tr> + + <tr> + <td>"Key Press"</td> <td>used for intercepting key presses<br /> + $_[0][0] - key value<br /> + $_[0][1] - state bitfield, 1 - shift, 4 - control, 8 - alt<br /> + $_[0][2] - string version of the key which might be empty for unprintable keys<br /> + $_[0][3] - length of the string in $_[0][2]<br /> + </td> + </tr> +</table> + +=end html + +=head3 C<Xchat::unhook( $hook )> + +=over 3 + +=item * +C<$hook> - the hook that was previously returned by one of the C<Xchat::hook_*> functions + +=back + + +This function is used to removed a hook previously added with one of +the C<Xchat::hook_*> functions + +It returns the data that was passed to the C<Xchat::hook_*> function when +the hook was added + + +=head3 C<Xchat::print( $text | \@lines, [$channel,[$server]] )> + +=over 3 + +=item * +C<$text> - the text to print + +=item * +C<\@lines> - array reference containing lines of text to be printed + all the elements will be joined together before printing + +=item * +C<$channel> - channel or tab with the given name where C<$text> + will be printed + +=item * +C<$server> - specifies that the text will be printed in a channel or tab + that is associated with C<$server> + +=back + +The first argument can either be a string or an array reference of strings. +Either or both of C<$channel> and C<$server> can be undef. + +If called as C<Xchat::print( $text )>, it will always return true. +If called with either the channel or the channel and the server +specified then it will return true if a context is found and +false otherwise. The text will not be printed if the context +is not found. The meaning of setting C<$channel> or C<$server> to +undef is the same as +L<find_context|xchat_find_context>. + + +=head3 C<Xchat::printf( $format, LIST )> + +=over 3 + +=item * +C<$format> - a format string, see "perldoc -f L<sprintf|http://perldoc.perl.org/functions/sprintf.html>" for further detail + +=item * +LIST - list of values for the format fields + +=back + +=head3 C<Xchat::command( $command | \@commands, [$channel,[$server]] )> + +=over 3 + +=item * +C<$command> - the command to execute, without the leading / + +=item * +C<\@commands> - array reference containing a list of commands to execute + +=item * +C<$channel> - channel or tab with the given name where C<$command> will be executed + +=item * +C<$server> - specifies that the command will be executed in a channel or tab that is associated with C<$server> + +=back + +The first argument can either be a string or an array reference of strings. +Either or both of C<$channel> and C<$server> can be undef. + +If called as C<Xchat::command( $command )>, it will always return true. +If called with either the channel or the channel and the server +specified then it will return true if a context is found and false +otherwise. The command will not be executed if the context is not found. +The meaning of setting C<$channel> or C<$server> to undef is the same +as find_context. + + +=head3 C<Xchat::commandf( $format, LIST )> + +=over 3 + +=item * +C<$format> - a format string, see "perldoc -f L<sprintf|http://perldoc.perl.org/functions/sprintf.html>" for further detail + +=item * +LIST - list of values for the format fields + +=back + +=head3 C<Xchat::find_context( [$channel, [$server]] )> + +=over 3 + +=item * +C<$channel> - name of a channel + +=item * +C<$server> - name of a server + +=back + +Either or both of C<$channel> and $server can be undef. Calling +C<Xchat::find_context()> is the same as calling +C<Xchat::find_context( undef, undef)> and +C<Xchat::find_context( $channel )> is +the same as C<Xchat::find_context( $channel, undef )>. + +If C<$server> is undef, find any channel named $channel. +If C<$channel> is undef, find the front most window +or tab named C<$server>.If both $channel and +C<$server> are undef, find the currently focused tab or window. + +Return the context found for one of the above situations or undef if such +a context cannot be found. + + +=head3 C<Xchat::get_context()> + +=over 3 + +=back + +Returns the current context. + +=head3 C<Xchat::set_context( $context | $channel,[$server] )> + +=over 3 + +=item * +C<$context> - context value as returned from L<get_context|xchat_get_context>,L<find_context|xchat_find_context> or one + of the fields in the list of hashrefs returned by list_get + +=item * +C<$channel> - name of a channel you want to switch context to + +=item * +C<$server> - name of a server you want to switch context to + +=back + +See L<find_context|xchat_find_context> for more details on C<$channel> and C<$server>. + +Returns true on success, false on failure + +=head3 C<Xchat::get_info( $id )> + +=over 3 + +=item * +C<$id> - one of the following case sensitive values + +=back + +=begin html + +<table border="1"> + + <tr style="background-color: #dddddd"> + <td>ID</td> <td>Return value</td> + </tr> + + <tr> + <td>away</td> <td>away reason or undef if you are not away</td> + </tr> + + <tr> + <td>channel</td> <td>current channel name</td> + </tr> + + <tr> + <td>charset</td> <td>character-set used in the current context</td> + </tr> + + <tr> + <td>event_text <Event Name></td> <td>text event format string for <Event name><br /> + Example: + <div class="example"> + my $channel_msg_format = Xchat::get_info( "event_text Channel Message" ); + </div> + </td> +</tr> +<tr> + <td>host</td> <td>real hostname of the current server</td> +</tr> + +<tr> + <td>id</td> <td>connection id</td> +</tr> + +<tr> + <td>inputbox</td> <td>contents of the inputbox</td> +</tr> + +<tr> + <td>libdirfs</td> + <td>the system wide directory where xchat will look for plugins. + this string is in the same encoding as the local file system</td> +</tr> + +<tr> + <td>modes</td> <td>the current channels modes or undef if not known</td> +</tr> + +<tr> + <td>network</td> <td>current network name or undef</td> +</tr> + +<tr> + <td>nick</td> <td>current nick</td> +</tr> + +<tr> + <td>nickserv</td> <td>nickserv password for this network or undef</td> +</tr> + +<tr> + <td>server</td> <td>current server name <br /> + (what the server claims to be) undef if not connected + </td> +</tr> + +<tr> + <td>state_cursor</td> + <td>current inputbox cursor position in characters</td> +</tr> + +<tr> + <td>topic</td> <td>current channel topic</td> +</tr> + +<tr> + <td>version</td> <td>xchat version number</td> +</tr> + +<tr> + <td>win_status</td> + <td>status of the xchat window, possible values are "active", "hidden" + and "normal"</td> +</tr> + +<tr> + <td>win_ptr</td> <td>native window pointer, GtkWindow * on Unix, HWND on Win32.<br /> + On Unix if you have the Glib module installed you can use my $window = Glib::Object->new_from_pointer( Xchat::get_info( "win_ptr" ) ); to get a Gtk2::Window object.<br /> + Additionally when you have detached tabs, each of the windows will return a different win_ptr for the different Gtk2::Window objects.<br /> + See <a href="http://xchat.cvs.sourceforge.net/viewvc/xchat/xchat2/plugins/perl/char_count.pl?view=markup">char_count.pl</a> for a longer example of a script that uses this to show how many characters you currently have in your input box. + </td> +</tr> +<tr> + <td>xchatdir</td> <td>xchat config directory encoded in UTF-8<br /> + examples:<br /> + /home/user/.xchat2<br /> + C:\Documents and Settings\user\Application Data\X-Chat 2 + </td> +</tr> + +<tr> + <td>xchatdirfs</td> <td>same as xchatdir except encoded in the locale file system encoding</td> +</tr> +</table> + +<p>This function is used to retrieve certain information about the current +context.</p> + +=end html + +=head3 C<Xchat::get_prefs( $name )> + +=over 3 + +=item * +C<$name> - name of a X-Chat setting (available through the /set command) + +=back + +This function provides a way to retrieve X-Chat's setting information. + +Returns C<undef> if there is no setting called called C<$name>. + + +=head3 C<Xchat::emit_print( $event, LIST )> + +=over 3 + +=item * +C<$event> - name from the Event column in Settings-E<gt>Advanced-E<gt>Text Events + +=item * +LIST - this depends on the Description column on the bottom of Settings-E<gt>Advanced-E<gt>Text Events + +=back + +This functions is used to generate one of the events listed under +Settings-E<gt>Advanced-E<gt>Text Events + +Note: when using this function you MUST return Xchat::EAT_ALL otherwise you will end up with duplicate events. +One is the original and the second is the one you emit. + +Returns true on success, false on failure + +=head3 C<Xchat::send_modes( $target | \@targets, $sign, $mode, [ $modes_per_line ] )> + +=over 3 + +=item * +C<$target> - a single nick to set the mode on + +=item * +C<\@targets> - an array reference of the nicks to set the mode on + +=item * +C<$sign> - the mode sign, either '+' or '-' + +=item * +C<$mode> - the mode character such as 'o' and 'v', this can only be one character long + +=item * +C<$modes_per_line> - an optional argument maximum number of modes to send per at once, pass 0 use the current server's maximum (default) + +=back + +Send multiple mode changes for the current channel. It may send multiple MODE lines if the request doesn't fit on one. + +Example: + +=begin html +<<div class="example"> +<code> +use strict; +use warning; +use Xchat qw(:all); + +hook_command( "MODES", sub { + my (undef, $who, $sign, $mode) = @{$_[0]}; + + my @targets = split /,/, $who; + if( @targets > 1 ) { + send_modes( \@targets, $sign, $mode, 1 ); + } else { + send_modes( $who, $sign, $mode ); + } + + return EAT_XCHAT; +}); + +</code> +</div> + +=end html + +=head3 C<Xchat::nickcmp( $nick1, $nick2 )> + +=over 3 + +=item * +C<$nick1, $nick2> - the two nicks or channel names that are to be compared + +=back + +The comparsion is based on the current server. Either a RFC1459 compliant +string compare or plain ascii will be using depending on the server. The +comparison is case insensitive. + +Returns a number less than, equal to or greater than zero if +C<$nick1> is +found respectively, to be less than, to match, or be greater than +C<$nick2>. + + +=head3 C<Xchat::get_list( $name )> + +=over 3 + +=item * +C<$name> - name of the list, one of the following: +"channels", "dcc", "ignore", "notify", "users" + +=back + +This function will return a list of hash references. The hash references +will have different keys depend on the list. An empty list is returned +if there is no such list. + +=begin html + +<p>"channels" - list of channels, querys and their server</p> + +<table border="1"> + + <tr style="background-color: #dddddd"> + <td>Key</td> <td>Description</td> + </tr> + + <tr> + <td>channel</td> <td>tab name</td> + </tr> + + <tr> + <td>chantypes</td> + <td>channel types supported by the server, typically "#&"</td> + </tr> + + <tr> + <td>context</td> <td>can be used with set_context</td> + </tr> + + <tr> + <td>flags</td> <td>Server Bits:<br /> + 0 - Connected<br /> + 1 - Connecting<br /> + 2 - Away<br /> + 3 - EndOfMotd(Login complete)<br /> + 4 - Has WHOX<br /> + 5 - Has IDMSG (FreeNode)<br /> + <br /> + <p>The following correspond to the /chanopt command</p> + 6 - Hide Join/Part Message (text_hidejoinpart)<br /> + 7 - unused (was for color paste)<br /> + 8 - Beep on message (alert_beep)<br /> + 9 - Blink Tray (alert_tray)<br /> + 10 - Blink Task Bar (alert_taskbar)<br /> +<p>Example of checking if the current context has Hide Join/Part messages set:</p> +<div class="example"> +<code> +if( Xchat::context_info->{flags} & (1 << 6) ) { + Xchat::print( "Hide Join/Part messages is enabled" ); +} +</code> +</div> + + </td> + </tr> + + <tr> + <td>id</td> <td>Unique server ID </td> + </tr> + + <tr> + <td>lag</td> + <td>lag in milliseconds</td> + </tr> + + <tr> + <td>maxmodes</td> <td>Maximum modes per line</td> + </tr> + + <tr> + <td>network</td> <td>network name to which this channel belongs</td> + </tr> + + <tr> + <td>nickprefixes</td> <td>Nickname prefixes e.g. "+@"</td> + </tr> + + <tr> + <td>nickmodes</td> <td>Nickname mode chars e.g. "vo"</td> + </tr> + + <tr> + <td>queue</td> + <td>number of bytes in the send queue</td> + </tr> + + <tr> + <td>server</td> <td>server name to which this channel belongs</td> + </tr> + + <tr> + <td>type</td> <td>the type of this context<br /> + 1 - server<br /> + 2 - channel<br /> + 3 - dialog<br /> + </td> + </tr> + + <tr> + <td>users</td> <td>Number of users in this channel</td> + </tr> +</table> + +<p>"dcc" - list of DCC file transfers</p> +<table border="1"> + + <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> + + <tr> + <td>address32</td> <td>address of the remote user(ipv4 address)</td> + </tr> + + <tr> + <td>cps</td> <td>bytes per second(speed)</td> + </tr> + + <tr> + <td>destfile</td> <td>destination full pathname</td> + </tr> + + <tr> + <td>file</td> <td>file name</td> + </tr> + + <tr> + <td>nick</td> + <td>nick of the person this DCC connection is connected to</td> + </tr> + + <tr> + <td>port</td> <td>TCP port number</td> + </tr> + + <tr> + <td>pos</td> <td>bytes sent/received</td> + </tr> + + <tr> + <td>poshigh</td> <td>bytes sent/received, high order 32 bits</td> + </tr> + + <tr> + <td>resume</td> <td>point at which this file was resumed<br /> + (zero if it was not resumed) + </td> + </tr> + + <tr> + <td>resumehigh</td> <td>point at which this file was resumed, high order 32 bits<br /> + </td> + </tr> + + <tr> + <td>size</td> <td>file size in bytes low order 32 bits</td> + </tr> + + <tr> + <td>sizehigh</td> <td>file size in bytes, high order 32 bits (when the files is > 4GB)</td> + </tr> + <tr> + <td>status</td> <td>DCC Status:<br /> + 0 - queued<br /> + 1 - active<br /> + 2 - failed<br /> + 3 - done<br /> + 4 - connecting<br /> + 5 - aborted + </td> + </tr> + + <tr> + <td>type</td> <td>DCC Type:<br /> + 0 - send<br /> + 1 - receive<br /> + 2 - chatrecv<br /> + 3 - chatsend + </td> + </tr> + +</table> + +<p>"ignore" - current ignore list</p> +<table border="1"> + + <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> + + <tr> + <td>mask</td> <td>ignore mask. e.g: *!*@*.aol.com</td> + </tr> + + <tr> + <td>flags</td> <td>Bit field of flags.<br /> + 0 - private<br /> + 1 - notice<br /> + 2 - channel<br /> + 3 - ctcp<br /> + 4 - invite<br /> + 5 - unignore<br /> + 6 - nosave<br /> + 7 - dcc<br /> + </td> + </tr> + +</table> + +<p>"notify" - list of people on notify</p> +<table border="1"> + <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> + + <tr> + <td>networks</td> + <td>comma separated list of networks where you will be notfified about this user's online/offline status or undef if you will be notificed on every network you are connected to</td> + </tr> + + <tr> + <td>nick</td> <td>nickname</td> + </tr> + + <tr> + <td>flags</td> <td>0 = is online</td> + </tr> + + <tr> + <td>on</td> <td>time when user came online</td> + </tr> + + <tr> + <td>off</td> <td>time when user went offline</td> + </tr> + + <tr> + <td>seen</td> <td>time when user was last verified still online</td> + </tr> +</table> + +<p>the values indexed by on, off and seen can be passed to localtime +and gmtime, see perldoc -f <a href="http://perldoc.perl.org/functions/localtime.html">localtime</a> and perldoc -f <a href="http://perldoc.perl.org/functions/gmtime.html">gmtime</a> for more +detail</p> + +<p>"users" - list of users in the current channel</p> +<table border="1"> + + <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> + + <tr> + <td>away</td> <td>away status(boolean)</td> + </tr> + + <tr> + <td>lasttalk</td> + <td>last time a user was seen talking, this is the an epoch time(number of seconds since a certain date, that date depends on the OS)</td> + </tr> + + <tr> + <td>nick</td> <td>nick name</td> + </tr> + + <tr> + <td>host</td> + <td>host name in the form: user@host or undef if not known</td> + </tr> + + <tr> + <td>prefix</td> <td>prefix character, .e.g: @ or +</td> + </tr> + + <tr> + <td>realname</td> + <td>Real name or undef</td> + </tr> + + <tr> + <td>selected</td> + <td>selected status in the user list, only works when retrieving the user list of the focused tab. You can use the /USELECT command to select the nicks</td> + </tr> +</table> + +<p>"networks" - list of networks and the associated settings from network list</p> +<table border="1"> + + <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> + + <tr> + <td>autojoins</td> <td>An object with the following methods:<br /> + <table> + <tr> + <td>Method</td> + <td>Description</td> + </tr> + + <tr> + <td>channels()</td> + <td>returns a list of this networks' autojoin channels in list context, a count of the number autojoin channels in scalar context</td> + </tr> + + <tr> + <td>keys()</td> + <td>returns a list of the keys to go with the channels, the order is the same as the channels, if a channel doesn't have a key, '' will be returned in it's place</td> + </tr> + + <tr> + <td>pairs()</td> + <td>a combination of channels() and keys(), returns a list of (channels, keys) pairs. This can be assigned to a hash for a mapping from channel to key.</td> + </tr> + + <tr> + <td>as_hash()</td> + <td>return the pairs as a hash reference</td> + </tr> + + <tr> + <td>as_string()</td> + <td>the original string that was used to construct this autojoin object, this can be used with the JOIN command to join all the channels in the autojoin list</td> + </tr> + + <tr> + <td>as_array()</td> + <td>return an array reference of hash references consisting of the keys "channel" and "key"</td> + </tr> + + <tr> + <td>as_bool()</td> + <td>returns true if the network has autojoins and false otherwise</td> + </tr> + </table> + </td> + </tr> + + <tr> + <td>connect_commands</td> <td>An array reference containing the connect commands for a network. An empty array if there aren't any</td> + </tr> + + <tr> + <td>encoding</td> <td>the encoding for the network</td> + </tr> + + + <tr> + <td>flags</td> + <td> + a hash reference corresponding to the checkboxes in the network edit window + <table> + <tr> + <td>allow_invalid</td> + <td>true if "Accept invalid SSL certificate" is checked</td> + </tr> + + <tr> + <td>autoconnect</td> + <td>true if "Auto connect to this network at startup" is checked</td> + </tr> + + <tr> + <td>cycle</td> + <td>true if "Connect to selected server only" is <strong>NOT</strong> checked</td> + </tr> + + <tr> + <td>use_global</td> + <td>true if "Use global user information" is checked</td> + </tr> + + <tr> + <td>use_proxy</td> + <td>true if "Bypass proxy server" is <strong>NOT</strong> checked</td> + </tr> + + <tr> + <td>use_ssl</td> + <td>true if "Use SSL for all the servers on this network" is checked</td> + </tr> + </table> + </td> + </tr> + + + <tr> + <td>irc_nick1</td> + <td>Corresponds with the "Nick name" field in the network edit window</td> + </tr> + + <tr> + <td>irc_nick2</td> + <td>Corresponds with the "Second choice" field in the network edit window</td> + </tr> + + <tr> + <td>irc_real_name</td> + <td>Corresponds with the "Real name" field in the network edit window</td> + </tr> + + + <tr> + <td>irc_user_name</td> + <td>Corresponds with the "User name" field in the network edit window</td> + </tr> + + + <tr> + <td>network</td> + <td>Name of the network</td> + </tr> + + <tr> + <td>nickserv_password</td> + <td>Corresponds with the "Nickserv password" field in the network edit window</td> + </tr> + + <tr> + <td>selected</td> + <td>Index into the list of servers in the "servers" key, this is used if the "cycle" flag is false</td> + </tr> + + <tr> + <td>server_password</td> + <td>Corresponds with the "Server password" field in the network edit window</td> + </tr> + + <tr> + <td>servers</td> + <td>An array reference of hash references with a "host" and "port" key. If a port is not specified then 6667 will be used.</td> + </tr> +</table> + +=end html + +=head3 C<Xchat::user_info( [$nick] )> + +=over 3 + +=item * +C<$nick> - the nick to look for, if this is not given your own nick will be + used as default + +=back + +This function is mainly intended to be used as a shortcut for when you need +to retrieve some information about only one user in a channel. Otherwise it +is better to use L<get_list|xchat_get_list>. +If C<$nick> is found a hash reference containing the same keys as those in the +"users" list of L<get_list|xchat_get_list> is returned otherwise undef is returned. +Since it relies on L<get_list|xchat_get_list> this function can only be used in a +channel context. + +=head3 C<Xchat::context_info( [$context] )> + +=over 3 + +=item * +C<$context> - context returned from L<get_context|xchat_get_context>, L<find_context|xchat_find_context> and L<get_list|xchat_get_list>, this is the context that you want infomation about. If this is omitted, it will default to current context. + +=back + +This function will return the information normally retrieved with L<get_info|xchat_get_info>, except this is for the context that is passed in. The information will be returned in the form of a hash. The keys of the hash are the C<$id> you would normally supply to L<get_info|xchat_get_info> as well as all the keys that are valid for the items in the "channels" list from L<get_list|xchat_get_list>. Use of this function is more efficient than calling get_list( "channels" ) and searching through the result. + +=begin html + +<p>Example:</p> +<div class="example"> +use strict; +use warnings; +use Xchat qw(:all); # imports all the functions documented on this page + +register( "User Count", "0.1", + "Print out the number of users on the current channel" ); + +hook_command( "UCOUNT", \&display_count ); + +sub display_count { + prnt "There are " . context_info()->{users} . " users in this channel."; + return EAT_XCHAT; +} +</div> + +=end html + +=head3 C<Xchat::strip_code( $string )> + +=over 3 + +=item * +C<$string> - string to remove codes from + +=back + +This function will remove bold, color, beep, reset, reverse and underline codes from C<$string>. It will also remove ANSI escape codes which might get used by certain terminal based clients. If it is called in void context C<$string> will be modified otherwise a modified copy of C<$string> is returned. + +=head2 Examples + +=head3 Asynchronous DNS resolution with hook_fd + +=begin html + +<div class="example"> +<code> +use strict; +use warnings; +use Xchat qw(:all); +use Net::DNS; + +hook_command( "BGDNS", sub { + my $host = $_[0][1]; + my $resolver = Net::DNS::Resolver->new; + my $sock = $resolver->bgsend( $host ); + + hook_fd( $sock, sub { + my $ready_sock = $_[0]; + my $packet = $resolver->bgread( $ready_sock ); + + if( $packet->authority && (my @answers = $packet->answer ) ) { + + if( @answers ) { + prnt "$host:"; + my $padding = " " x (length( $host ) + 2); + for my $answer ( @answers ) { + prnt $padding . $answer->rdatastr . ' ' . $answer->type; + } + } + } else { + prnt "Unable to resolve $host"; + } + + return REMOVE; + }, + { + flags => FD_READ, + }); + + return EAT_XCHAT; +}); +</code> +</div> + +=end html + +=head2 Contact Information + +Contact Lian Wan Situ at E<lt>atmcmnky [at] yahoo.comE<gt> for questions, comments and +corrections about this page or the Perl plugin itself. You can also find me +in #xchat on FreeNode under the nick Khisanth. diff --git a/plugins/perl/lib/Xchat/Embed.pm b/plugins/perl/lib/Xchat/Embed.pm new file mode 100644 index 00000000..dffbaf5e --- /dev/null +++ b/plugins/perl/lib/Xchat/Embed.pm @@ -0,0 +1,253 @@ +package Xchat::Embed; +use strict; +use warnings; +# list of loaded scripts keyed by their package names +our %scripts; + +sub load { + my $file = expand_homedir( shift @_ ); + my $package = file2pkg( $file ); + + if( exists $scripts{$package} ) { + my $pkg_info = pkg_info( $package ); + my $filename = File::Basename::basename( $pkg_info->{filename} ); + Xchat::printf( + qq{'%s' already loaded from '%s'.\n}, + $filename, $pkg_info->{filename} + ); + Xchat::print( + 'If this is a different script then it rename and try '. + 'loading it again.' + ); + return 2; + } + + if( open my $source_handle, $file ) { + my $source = do {local $/; <$source_handle>}; + close $source_handle; + # we shouldn't care about things after __END__ + $source =~ s/^__END__.*//ms; + + if( + my @replacements = $source =~ + m/^\s*package ((?:[^\W:]+(?:::)?)+)\s*?;/mg + ) { + + if ( @replacements > 1 ) { + Xchat::print( + "Too many package defintions, only 1 is allowed\n" + ); + return 1; + } + + my $original_package = shift @replacements; + + # remove original package declaration + $source =~ s/^(package $original_package\s*;)/#$1/m; + + # fixes things up for code calling subs with fully qualified names + $source =~ s/${original_package}:://g; + } + + # this must come before the eval or the filename will not be found in + # Xchat::register + $scripts{$package}{filename} = $file; + $scripts{$package}{loaded_at} = Time::HiRes::time(); + + my $full_path = File::Spec->rel2abs( $file ); + $source =~ s/^/#line 1 "$full_path"\n\x7Bpackage $package;/; + + # make sure we add the closing } even if the last line is a comment + if( $source =~ /^#.*\Z/m ) { + $source =~ s/^(?=#.*\Z)/\x7D/m; + } else { + $source =~ s/\Z/\x7D/; + } + + _do_eval( $source ); + + unless( exists $scripts{$package}{gui_entry} ) { + $scripts{$package}{gui_entry} = + Xchat::Internal::register( + "", "unknown", "", $file + ); + } + + if( $@ ) { + # something went wrong + $@ =~ s/\(eval \d+\)/$file/g; + Xchat::print( "Error loading '$file':\n$@\n" ); + # make sure the script list doesn't contain false information + unload( $scripts{$package}{filename} ); + return 1; + } + } else { + Xchat::print( "Error opening '$file': $!\n" ); + return 2; + } + + return 0; +} + +sub _do_eval { + no strict; + no warnings; + eval $_[0]; +} + +sub unload { + my $file = shift @_; + my $package = file2pkg( $file ); + my $pkg_info = pkg_info( $package ); + + if( $pkg_info ) { + # take care of the shutdown callback + if( exists $pkg_info->{shutdown} ) { + # allow incorrectly written scripts to be unloaded + eval { + if( ref $pkg_info->{shutdown} eq 'CODE' ) { + $pkg_info->{shutdown}->(); + } elsif ( $pkg_info->{shutdown} ) { + no strict 'refs'; + &{$pkg_info->{shutdown}}; + } + }; + } + + if( exists $pkg_info->{hooks} ) { + for my $hook ( @{$pkg_info->{hooks}} ) { + Xchat::unhook( $hook, $package ); + } + } + + + if( exists $pkg_info->{gui_entry} ) { + plugingui_remove( $pkg_info->{gui_entry} ); + } + + Symbol::delete_package( $package ); + delete $scripts{$package}; + return Xchat::EAT_ALL; + } else { + Xchat::print( qq{"$file" is not loaded.\n} ); + return Xchat::EAT_NONE; + } +} + +sub unload_all { + for my $package ( keys %scripts ) { + unload( $scripts{$package}->{filename} ); + } + + return Xchat::EAT_ALL; +} + +sub reload { + my $file = shift @_; + my $package = file2pkg( $file ); + my $pkg_info = pkg_info( $package ); + my $fullpath = $file; + + if( $pkg_info ) { + $fullpath = $pkg_info->{filename}; + unload( $file ); + } + + load( $fullpath ); + return Xchat::EAT_ALL; +} + +sub reload_all { + my @dirs = Xchat::get_info( "xchatdirfs" ) || Xchat::get_info( "xchatdir" ); + push @dirs, File::Spec->catdir( $dirs[0], "plugins" ); + for my $dir ( @dirs ) { + my $auto_load_glob = File::Spec->catfile( $dir, "*.pl" ); + my @scripts = map { $_->{filename} } + sort { $a->{loaded_at} <=> $b->{loaded_at} } values %scripts; + push @scripts, File::Glob::bsd_glob( $auto_load_glob ); + + my %seen; + @scripts = grep { !$seen{ $_ }++ } @scripts; + + unload_all(); + for my $script ( @scripts ) { + if( !pkg_info( file2pkg( $script ) ) ) { + load( $script ); + } + } + } +} + +sub expand_homedir { + my $file = shift @_; + + if ( $^O eq "MSWin32" ) { + $file =~ s/^~/$ENV{USERPROFILE}/; + } else { + $file =~ s{^~}{ + (getpwuid($>))[7] || $ENV{HOME} || $ENV{LOGDIR} + }ex; + } + return $file; +} + +sub file2pkg { + my $string = File::Basename::basename( shift @_ ); + $string =~ s/\.pl$//i; + $string =~ s|([^A-Za-z0-9/])|'_'.unpack("H*",$1)|eg; + return "Xchat::Script::" . $string; +} + +sub pkg_info { + my $package = shift @_; + return $scripts{$package}; +} + +sub find_external_pkg { + my $level = 1; + + while( my @frame = caller( $level ) ) { + return @frame if $frame[0] !~ /^Xchat/; + $level++; + } + +} + +sub find_pkg { + my $level = 1; + + while( my ($package, $file, $line) = caller( $level ) ) { + return $package if $package =~ /^Xchat::Script::/; + $level++; + } + + my @frame = find_external_pkg(); + my $location; + + if( $frame[0] or $frame[1] ) { + $location = $frame[1] ? $frame[1] : "package $frame[0]"; + $location .= " line $frame[2]"; + } else { + $location = "unknown location"; + } + + die "Unable to determine which script this hook belongs to. at $location\n"; + +} + +sub fix_callback { + my ($package, $callback) = @_; + + unless( ref $callback ) { + # change the package to the correct one in case it was hardcoded + $callback =~ s/^.*:://; + $callback = qq[${package}::$callback]; + + no strict 'subs'; + $callback = \&{$callback}; + } + + return $callback; +} + +1 diff --git a/plugins/perl/lib/Xchat/List/Network.pm b/plugins/perl/lib/Xchat/List/Network.pm new file mode 100644 index 00000000..da2f52dd --- /dev/null +++ b/plugins/perl/lib/Xchat/List/Network.pm @@ -0,0 +1,32 @@ +package Xchat::List::Network; +use strict; +use warnings; +use Storable qw(dclone); +my $last_modified; +my @servers; + +sub get { + my $server_file = Xchat::get_info( "xchatdirfs" ) . "/servlist_.conf"; + + # recreate the list only if the server list file has changed + if( -f $server_file && + (!defined $last_modified || $last_modified != -M $server_file ) ) { + $last_modified = -M _; + + if( open my $fh, "<", $server_file ) { + local $/ = "\n\n"; + while( my $record = <$fh> ) { + chomp $record; + next if $record =~ /^v=/; # skip the version line + push @servers, Xchat::List::Network::Entry::parse( $record ); + } + } else { + warn "Unable to open '$server_file': $!"; + } + } + + my $clone = dclone( \@servers ); + return @$clone; +} + +1 diff --git a/plugins/perl/lib/Xchat/List/Network/AutoJoin.pm b/plugins/perl/lib/Xchat/List/Network/AutoJoin.pm new file mode 100644 index 00000000..16036a9d --- /dev/null +++ b/plugins/perl/lib/Xchat/List/Network/AutoJoin.pm @@ -0,0 +1,82 @@ +package Xchat::List::Network::AutoJoin; +use strict; +use warnings; + +use overload +# '%{}' => \&as_hash, +# '@{}' => \&as_array, + '""' => 'as_string', + '0+' => 'as_bool'; + +sub new { + my $class = shift; + my $line = shift; + + my @autojoins; + + if ( $line ) { + my ( $channels, $keys ) = split / /, $line, 2; + my @channels = split /,/, $channels; + my @keys = split /,/, ($keys || ''); + + for my $channel ( @channels ) { + my $key = shift @keys; + $key = '' unless defined $key; + + push @autojoins, { + channel => $channel, + key => $key, + }; + } + } + return bless \@autojoins, $class; +} + +sub channels { + my $self = shift; + + if( wantarray ) { + return map { $_->{channel} } @$self; + } else { + return scalar @$self; + } +} + +sub keys { + my $self = shift; + return map { $_->{key} } @$self ; + +} + +sub pairs { + my $self = shift; + + my @channels = $self->channels; + my @keys = $self->keys; + + my @pairs = map { $_ => shift @keys } @channels; +} + +sub as_hash { + my $self = shift; + return +{ $self->pairs }; +} + +sub as_string { + my $self = shift; + return join " ", + join( ",", $self->channels ), + join( ",", $self->keys ); +} + +sub as_array { + my $self = shift; + return [ map { \%$_ } @$self ]; +} + +sub as_bool { + my $self = shift; + return $self->channels ? 1 : ""; +} + +1 diff --git a/plugins/perl/lib/Xchat/List/Network/Entry.pm b/plugins/perl/lib/Xchat/List/Network/Entry.pm new file mode 100644 index 00000000..e40b48bd --- /dev/null +++ b/plugins/perl/lib/Xchat/List/Network/Entry.pm @@ -0,0 +1,105 @@ +package Xchat::List::Network::Entry; +use strict; +use warnings; + +my %key_for = ( + I => "irc_nick1", + i => "irc_nick2", + U => "irc_user_name", + R => "irc_real_name", + P => "server_password", + B => "nickserv_password", + N => "network", + D => "selected", + E => "encoding", +); +my $letter_key_re = join "|", keys %key_for; + +sub parse { + my $data = shift; + my $entry = { + irc_nick1 => undef, + irc_nick2 => undef, + irc_user_name => undef, + irc_real_name => undef, + server_password => undef, + + # the order of the channels need to be maintained + # list of { channel => .., key => ... } + autojoins => Xchat::List::Network::AutoJoin->new( '' ), + connect_commands => [], + flags => {}, + selected => undef, + encoding => undef, + servers => [], + nickserv_password => undef, + network => undef, + }; + + my @fields = split /\n/, $data; + chomp @fields; + + for my $field ( @fields ) { + SWITCH: for ( $field ) { + /^($letter_key_re)=(.*)/ && do { + $entry->{ $key_for{ $1 } } = $2; + last SWITCH; + }; + + /^J.(.*)/ && do { + $entry->{ autojoins } = + Xchat::List::Network::AutoJoin->new( $1 ); + }; + + /^F.(.*)/ && do { + $entry->{ flags } = parse_flags( $1 ); + }; + + /^S.(.+)/ && do { + push @{$entry->{servers}}, parse_server( $1 ); + }; + + /^C.(.+)/ && do { + push @{$entry->{connect_commands}}, $1; + }; + } + } + +# $entry->{ autojoins } = $entry->{ autojoin_channels }; + return $entry; +} + +sub parse_flags { + my $value = shift || 0; + my %flags; + + $flags{ "cycle" } = $value & 1 ? 1 : 0; + $flags{ "use_global" } = $value & 2 ? 1 : 0; + $flags{ "use_ssl" } = $value & 4 ? 1 : 0; + $flags{ "autoconnect" } = $value & 8 ? 1 : 0; + $flags{ "use_proxy" } = $value & 16 ? 1 : 0; + $flags{ "allow_invalid" } = $value & 32 ? 1 : 0; + + return \%flags; +} + +sub parse_server { + my $data = shift; + if( $data ) { + my ($host, $port) = split /\//, $data; + unless( $port ) { + my @parts = split /:/, $host; + + # if more than 2 then we are probably dealing with a IPv6 address + # if less than 2 then no port was specified + if( @parts == 2 ) { + $port = $parts[1]; + } + } + + $port ||= 6667; + return { host => $host, port => $port }; + } +} + +1 diff --git a/plugins/perl/perl.c b/plugins/perl/perl.c new file mode 100644 index 00000000..a29ce65a --- /dev/null +++ b/plugins/perl/perl.c @@ -0,0 +1,1522 @@ +/* X-Chat 2.0 PERL Plugin + * Copyright (C) 1998-2002 Peter Zelezny. + * + * 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 + */ + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <dirent.h> +#ifdef ENABLE_NLS +#include <locale.h> +#endif +#ifdef WIN32 +#include <windows.h> +#endif + +#undef PACKAGE +#include "../../config.h" /* for #define OLD_PERL */ +#include "xchat-plugin.h" + +static xchat_plugin *ph; /* plugin handle */ + +static int perl_load_file (char *script_name); + +#ifdef WIN32 +/* STRINGIFY is from perl's CORE/config.h */ +#ifndef PERL_REQUIRED_VERSION + #define PERL_REQUIRED_VERSION STRINGIFY(PERL_REVISION) "." STRINGIFY(PERL_VERSION) +#endif + +#ifndef PERL_DLL + #define PERL_DLL "perl" STRINGIFY(PERL_REVISION) STRINGIFY(PERL_VERSION) ".dll" +#endif + +static DWORD +child (char *str) +{ + MessageBoxA (0, str, "Perl DLL Error", + MB_OK | MB_ICONHAND | MB_SETFOREGROUND | MB_TASKMODAL); + return 0; +} + +static void +thread_mbox (char *str) +{ + DWORD tid; + + CloseHandle (CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) child, + str, 0, &tid)); +} + +#endif + +/* leave this before XSUB.h, to avoid readdir() being redefined */ + +static void +perl_auto_load_from_path (const char *path) +{ + DIR *dir; + struct dirent *ent; + + dir = opendir (path); + if (dir) { + while ((ent = readdir (dir))) { + int len = strlen (ent->d_name); + if (len > 3 && strcasecmp (".pl", ent->d_name + len - 3) == 0) { + char *file = malloc (len + strlen (path) + 2); + sprintf (file, "%s/%s", path, ent->d_name); + perl_load_file (file); + free (file); + } + } + closedir (dir); + } +} + +static int +perl_auto_load (void *unused) +{ + const char *xdir; + char *sub_dir; +#ifdef WIN32 + int copied = 0; + char *slash = NULL; +#endif + + /* get the dir in local filesystem encoding (what opendir() expects!) */ + xdir = xchat_get_info (ph, "xchatdirfs"); + if (!xdir) /* xchatdirfs is new for 2.0.9, will fail on older */ + xdir = xchat_get_info (ph, "xchatdir"); + + /* autoload from ~/.xchat2/ or ${APPDATA}\X-Chat 2\ on win32 */ + perl_auto_load_from_path (xdir); + + sub_dir = malloc (strlen (xdir) + 9); + strcpy (sub_dir, xdir); + strcat (sub_dir, "/plugins"); + perl_auto_load_from_path (sub_dir); + free (sub_dir); + +#ifdef WIN32 + /* autoload from C:\program files\xchat\plugins\ */ + sub_dir = malloc (1025 + 9); + copied = GetModuleFileName( 0, sub_dir, 1024 ); + sub_dir[copied] = '\0'; + slash = strrchr( sub_dir, '\\' ); + if( slash != NULL ) { + *slash = '\0'; + } + perl_auto_load_from_path ( strncat (sub_dir, "\\plugins", 9)); + free (sub_dir); +#endif + return 0; +} + +#include <EXTERN.h> +#define WIN32IOP_H +#include <perl.h> +#include <XSUB.h> + +typedef struct +{ + SV *callback; + SV *userdata; + xchat_hook *hook; /* required for timers */ + xchat_context *ctx; /* allow timers to remember their context */ + SV *package; /* need to track the package name when removing hooks + by returning REMOVE + */ + unsigned int depth; +} HookData; + +static PerlInterpreter *my_perl = NULL; +extern void boot_DynaLoader (pTHX_ CV * cv); + +/* + this is used for autoload and shutdown callbacks +*/ +static int +execute_perl (SV * function, char *args) +{ + + int count, ret_value = 1; + + dSP; + ENTER; + SAVETMPS; + + PUSHMARK (SP); + XPUSHs (sv_2mortal (newSVpv (args, 0))); + PUTBACK; + + count = call_sv (function, G_EVAL | G_SCALAR); + SPAGAIN; + if (SvTRUE (ERRSV)) { + xchat_printf(ph, "Perl error: %s\n", SvPV_nolen (ERRSV)); + if (!SvOK (POPs)) {} /* remove undef from the top of the stack */ + } else if (count != 1) { + xchat_printf (ph, "Perl error: expected 1 value from %s, " + "got: %d\n", SvPV_nolen (function), count); + } else { + ret_value = POPi; + } + PUTBACK; + FREETMPS; + LEAVE; + + return ret_value; +} + +static char * +get_filename (char *word[], char *word_eol[]) +{ + int len; + char *file; + + len = strlen (word[2]); + + /* if called as /load "filename.pl" the only difference between word and + * word_eol will be the two quotes + */ + + if (strchr (word[2], ' ') != NULL + || (strlen (word_eol[2]) - strlen(word[2])) == 2 ) + { + file = word[2]; + } else { + file = word_eol[2]; + } + + len = strlen (file); + + if (len > 3 && strncasecmp (".pl", file + len - 3, 3) == 0) { + return file; + } + + return NULL; +} + +static SV * +list_item_to_sv ( xchat_list *list, const char *const *fields ) +{ + HV *hash = newHV(); + SV *field_value; + const char *field; + int field_index = 0; + const char *field_name; + int name_len; + + while (fields[field_index] != NULL) { + field_name = fields[field_index] + 1; + name_len = strlen (field_name); + + switch (fields[field_index][0]) { + case 's': + field = xchat_list_str (ph, list, field_name); + if (field != NULL) { + field_value = newSVpvn (field, strlen (field)); + } else { + field_value = &PL_sv_undef; + } + break; + case 'p': + field_value = newSViv (PTR2IV (xchat_list_str (ph, list, + field_name))); + break; + case 'i': + field_value = newSVuv (xchat_list_int (ph, list, field_name)); + break; + case 't': + field_value = newSVnv (xchat_list_time (ph, list, field_name)); + break; + default: + field_value = &PL_sv_undef; + } + hv_store (hash, field_name, name_len, field_value, 0); + field_index++; + } + return sv_2mortal (newRV_noinc ((SV *) hash)); +} + +static AV * +array2av (char *array[]) +{ + int count = 0; + SV *temp = NULL; + AV *av = newAV(); + sv_2mortal ((SV *)av); + + for ( + count = 1; + count < 32 && array[count] != NULL && array[count][0] != 0; + count++ + ) { + temp = newSVpv (array[count], 0); + SvUTF8_on (temp); + av_push (av, temp); + } + + return av; +} + +static int +fd_cb (int fd, int flags, void *userdata) +{ + HookData *data = (HookData *) userdata; + int retVal = 0; + int count = 0; + + dSP; + ENTER; + SAVETMPS; + + PUSHMARK (SP); + XPUSHs (data->userdata); + PUTBACK; + + count = call_sv (data->callback, G_EVAL); + SPAGAIN; + + if (SvTRUE (ERRSV)) { + xchat_printf (ph, "Error in fd callback %s", SvPV_nolen (ERRSV)); + if (!SvOK (POPs)) {} /* remove undef from the top of the stack */ + retVal = XCHAT_EAT_ALL; + } else { + if (count != 1) { + xchat_print (ph, "Fd handler should only return 1 value."); + retVal = XCHAT_EAT_NONE; + } else { + retVal = POPi; + if (retVal == 0) { + /* if 0 is returned, the fd is going to get unhooked */ + PUSHMARK (SP); + XPUSHs (sv_2mortal (newSViv (PTR2IV (data->hook)))); + PUTBACK; + + call_pv ("Xchat::unhook", G_EVAL); + SPAGAIN; + + SvREFCNT_dec (data->callback); + + if (data->userdata) { + SvREFCNT_dec (data->userdata); + } + free (data); + } + } + + } + + PUTBACK; + FREETMPS; + LEAVE; + + return retVal; +} + +static int +timer_cb (void *userdata) +{ + HookData *data = (HookData *) userdata; + int retVal = 0; + int count = 0; + + dSP; + ENTER; + SAVETMPS; + + PUSHMARK (SP); + XPUSHs (data->userdata); + PUTBACK; + + if (data->ctx) { + xchat_set_context (ph, data->ctx); + } + count = call_sv (data->callback, G_EVAL); + SPAGAIN; + + if (SvTRUE (ERRSV)) { + xchat_printf (ph, "Error in timer callback %s", SvPV_nolen (ERRSV)); + if (!SvOK (POPs)) {} /* remove undef from the top of the stack */ + retVal = XCHAT_EAT_ALL; + } else { + if (count != 1) { + xchat_print (ph, "Timer handler should only return 1 value."); + retVal = XCHAT_EAT_NONE; + } else { + retVal = POPi; + if (retVal == 0) { + /* if 0 is return the timer is going to get unhooked */ + PUSHMARK (SP); + XPUSHs (sv_2mortal (newSViv (PTR2IV (data->hook)))); + XPUSHs (sv_mortalcopy (data->package)); + PUTBACK; + + call_pv ("Xchat::unhook", G_EVAL); + SPAGAIN; + } + } + + } + + PUTBACK; + FREETMPS; + LEAVE; + + return retVal; +} + +static int +server_cb (char *word[], char *word_eol[], void *userdata) +{ + HookData *data = (HookData *) userdata; + int retVal = 0; + int count = 0; + + dSP; + ENTER; + SAVETMPS; + + if (data->depth) + return XCHAT_EAT_NONE; + + /* xchat_printf (ph, */ + /* "Recieved %d words in server callback", av_len (wd)); */ + PUSHMARK (SP); + XPUSHs (newRV_noinc ((SV *) array2av (word))); + XPUSHs (newRV_noinc ((SV *) array2av (word_eol))); + XPUSHs (data->userdata); + PUTBACK; + + data->depth++; + count = call_sv (data->callback, G_EVAL); + data->depth--; + SPAGAIN; + if (SvTRUE (ERRSV)) { + xchat_printf (ph, "Error in server callback %s", SvPV_nolen (ERRSV)); + if (!SvOK (POPs)) {} /* remove undef from the top of the stack */ + retVal = XCHAT_EAT_NONE; + } else { + if (count != 1) { + xchat_print (ph, "Server handler should only return 1 value."); + retVal = XCHAT_EAT_NONE; + } else { + retVal = POPi; + } + + } + + PUTBACK; + FREETMPS; + LEAVE; + + return retVal; +} + +static int +command_cb (char *word[], char *word_eol[], void *userdata) +{ + HookData *data = (HookData *) userdata; + int retVal = 0; + int count = 0; + + dSP; + ENTER; + SAVETMPS; + + if (data->depth) + return XCHAT_EAT_NONE; + + /* xchat_printf (ph, "Recieved %d words in command callback", */ + /* av_len (wd)); */ + PUSHMARK (SP); + XPUSHs (newRV_noinc ((SV *) array2av (word))); + XPUSHs (newRV_noinc ((SV *) array2av (word_eol))); + XPUSHs (data->userdata); + PUTBACK; + + data->depth++; + count = call_sv (data->callback, G_EVAL); + data->depth--; + SPAGAIN; + if (SvTRUE (ERRSV)) { + xchat_printf (ph, "Error in command callback %s", SvPV_nolen (ERRSV)); + if (!SvOK (POPs)) {} /* remove undef from the top of the stack */ + retVal = XCHAT_EAT_XCHAT; + } else { + if (count != 1) { + xchat_print (ph, "Command handler should only return 1 value."); + retVal = XCHAT_EAT_NONE; + } else { + retVal = POPi; + } + + } + + PUTBACK; + FREETMPS; + LEAVE; + + return retVal; +} + +static int +print_cb (char *word[], void *userdata) +{ + + HookData *data = (HookData *) userdata; + SV *temp = NULL; + int retVal = 0; + int count = 1; + int last_index = 31; + /* must be initialized after SAVETMPS */ + AV *wd = NULL; + + dSP; + ENTER; + SAVETMPS; + + if (data->depth) + return XCHAT_EAT_NONE; + + wd = newAV (); + sv_2mortal ((SV *) wd); + + /* need to scan backwards to find the index of the last element since some + events such as "DCC Timeout" can have NULL elements in between non NULL + elements */ + + while (last_index >= 0 + && (word[last_index] == NULL || word[last_index][0] == 0)) { + last_index--; + } + + for (count = 1; count <= last_index; count++) { + if (word[count] == NULL) { + av_push (wd, &PL_sv_undef); + } else if (word[count][0] == 0) { + av_push (wd, newSVpvn ("",0)); + } else { + temp = newSVpv (word[count], 0); + SvUTF8_on (temp); + av_push (wd, temp); + } + } + + /*xchat_printf (ph, "Recieved %d words in print callback", av_len (wd)+1); */ + PUSHMARK (SP); + XPUSHs (newRV_noinc ((SV *) wd)); + XPUSHs (data->userdata); + PUTBACK; + + data->depth++; + count = call_sv (data->callback, G_EVAL); + data->depth--; + SPAGAIN; + if (SvTRUE (ERRSV)) { + xchat_printf (ph, "Error in print callback %s", SvPV_nolen (ERRSV)); + if (!SvOK (POPs)) {} /* remove undef from the top of the stack */ + retVal = XCHAT_EAT_NONE; + } else { + if (count != 1) { + xchat_print (ph, "Print handler should only return 1 value."); + retVal = XCHAT_EAT_NONE; + } else { + retVal = POPi; + } + + } + + PUTBACK; + FREETMPS; + LEAVE; + + return retVal; +} + +/* custom IRC perl functions for scripting */ + +/* Xchat::Internal::register (scriptname, version, desc, shutdowncallback, filename) + * + */ + +static +XS (XS_Xchat_register) +{ + char *name, *version, *desc, *filename; + void *gui_entry; + dXSARGS; + if (items != 4) { + xchat_printf (ph, + "Usage: Xchat::Internal::register(scriptname, version, desc, filename)"); + } else { + name = SvPV_nolen (ST (0)); + version = SvPV_nolen (ST (1)); + desc = SvPV_nolen (ST (2)); + filename = SvPV_nolen (ST (3)); + + gui_entry = xchat_plugingui_add (ph, filename, name, + desc, version, NULL); + + XSRETURN_IV (PTR2IV (gui_entry)); + + } +} + + +/* Xchat::print(output) */ +static +XS (XS_Xchat_print) +{ + + char *text = NULL; + + dXSARGS; + if (items != 1) { + xchat_print (ph, "Usage: Xchat::Internal::print(text)"); + } else { + text = SvPV_nolen (ST (0)); + xchat_print (ph, text); + } + XSRETURN_EMPTY; +} + +static +XS (XS_Xchat_emit_print) +{ + char *event_name; + int RETVAL; + int count; + + dXSARGS; + if (items < 1) { + xchat_print (ph, "Usage: Xchat::emit_print(event_name, ...)"); + } else { + event_name = (char *) SvPV_nolen (ST (0)); + RETVAL = 0; + + /* we need to figure out the number of defined values passed in */ + for (count = 0; count < items; count++) { + if (!SvOK (ST (count))) { + break; + } + } + + switch (count) { + case 1: + RETVAL = xchat_emit_print (ph, event_name, NULL); + break; + case 2: + RETVAL = xchat_emit_print (ph, event_name, + SvPV_nolen (ST (1)), NULL); + break; + case 3: + RETVAL = xchat_emit_print (ph, event_name, + SvPV_nolen (ST (1)), + SvPV_nolen (ST (2)), NULL); + break; + case 4: + RETVAL = xchat_emit_print (ph, event_name, + SvPV_nolen (ST (1)), + SvPV_nolen (ST (2)), + SvPV_nolen (ST (3)), NULL); + break; + case 5: + RETVAL = xchat_emit_print (ph, event_name, + SvPV_nolen (ST (1)), + SvPV_nolen (ST (2)), + SvPV_nolen (ST (3)), + SvPV_nolen (ST (4)), NULL); + break; + + } + + XSRETURN_IV (RETVAL); + } +} + +static +XS (XS_Xchat_send_modes) +{ + AV *p_targets = NULL; + int modes_per_line = 0; + char sign; + char mode; + int i = 0; + const char **targets; + int target_count = 0; + SV **elem; + + dXSARGS; + if (items < 3 || items > 4) { + xchat_print (ph, + "Usage: Xchat::send_modes( targets, sign, mode, modes_per_line)" + ); + } else { + if (SvROK (ST (0))) { + p_targets = (AV*) SvRV (ST (0)); + target_count = av_len (p_targets) + 1; + targets = malloc (target_count * sizeof (char *)); + for (i = 0; i < target_count; i++ ) { + elem = av_fetch (p_targets, i, 0); + + if (elem != NULL) { + targets[i] = SvPV_nolen (*elem); + } else { + targets[i] = ""; + } + } + } else{ + targets = malloc (sizeof (char *)); + targets[0] = SvPV_nolen (ST (0)); + target_count = 1; + } + + if (target_count == 0) { + XSRETURN_EMPTY; + } + + sign = (SvPV_nolen (ST (1)))[0]; + mode = (SvPV_nolen (ST (2)))[0]; + + if (items == 4 ) { + modes_per_line = (int) SvIV (ST (3)); + } + + xchat_send_modes (ph, targets, target_count, modes_per_line, sign, mode); + free (targets); + } +} +static +XS (XS_Xchat_get_info) +{ + SV *temp = NULL; + dXSARGS; + if (items != 1) { + xchat_print (ph, "Usage: Xchat::get_info(id)"); + } else { + SV *id = ST (0); + const char *RETVAL; + + RETVAL = xchat_get_info (ph, SvPV_nolen (id)); + if (RETVAL == NULL) { + XSRETURN_UNDEF; + } + + if (!strncmp ("win_ptr", SvPV_nolen (id), 7) + || !strncmp ("gtkwin_ptr", SvPV_nolen (id), 10)) + { + XSRETURN_IV (PTR2IV (RETVAL)); + } else { + + if ( + !strncmp ("libdirfs", SvPV_nolen (id), 8) || + !strncmp ("xchatdirfs", SvPV_nolen (id), 10) + ) { + XSRETURN_PV (RETVAL); + } else { + temp = newSVpv (RETVAL, 0); + SvUTF8_on (temp); + PUSHMARK (SP); + XPUSHs (sv_2mortal (temp)); + PUTBACK; + } + } + } +} + +static +XS (XS_Xchat_context_info) +{ + const char *const *fields; + dXSARGS; + + if (items > 0 ) { + xchat_print (ph, "Usage: Xchat::Internal::context_info()"); + } + fields = xchat_list_fields (ph, "channels" ); + XPUSHs (list_item_to_sv (NULL, fields)); + XSRETURN (1); +} + +static +XS (XS_Xchat_get_prefs) +{ + const char *str; + int integer; + SV *temp = NULL; + dXSARGS; + if (items != 1) { + xchat_print (ph, "Usage: Xchat::get_prefs(name)"); + } else { + + + switch (xchat_get_prefs (ph, SvPV_nolen (ST (0)), &str, &integer)) { + case 0: + XSRETURN_UNDEF; + break; + case 1: + temp = newSVpv (str, 0); + SvUTF8_on (temp); + SP -= items; + sp = mark; + XPUSHs (sv_2mortal (temp)); + PUTBACK; + break; + case 2: + XSRETURN_IV (integer); + break; + case 3: + if (integer) { + XSRETURN_YES; + } else { + XSRETURN_NO; + } + } + } +} + +/* Xchat::Internal::hook_server(name, priority, callback, userdata) */ +static +XS (XS_Xchat_hook_server) +{ + + char *name; + int pri; + SV *callback; + SV *userdata; + xchat_hook *hook; + HookData *data; + + dXSARGS; + + if (items != 4) { + xchat_print (ph, + "Usage: Xchat::Internal::hook_server(name, priority, callback, userdata)"); + } else { + name = SvPV_nolen (ST (0)); + pri = (int) SvIV (ST (1)); + callback = ST (2); + userdata = ST (3); + data = NULL; + data = malloc (sizeof (HookData)); + if (data == NULL) { + XSRETURN_UNDEF; + } + + data->callback = sv_mortalcopy (callback); + SvREFCNT_inc (data->callback); + data->userdata = sv_mortalcopy (userdata); + SvREFCNT_inc (data->userdata); + data->depth = 0; + data->package = NULL; + hook = xchat_hook_server (ph, name, pri, server_cb, data); + + XSRETURN_IV (PTR2IV (hook)); + } +} + +/* Xchat::Internal::hook_command(name, priority, callback, help_text, userdata) */ +static +XS (XS_Xchat_hook_command) +{ + char *name; + int pri; + SV *callback; + char *help_text = NULL; + SV *userdata; + xchat_hook *hook; + HookData *data; + + dXSARGS; + + if (items != 5) { + xchat_print (ph, + "Usage: Xchat::Internal::hook_command(name, priority, callback, help_text, userdata)"); + } else { + name = SvPV_nolen (ST (0)); + pri = (int) SvIV (ST (1)); + callback = ST (2); + + /* leave the help text has NULL if the help text is undefined to avoid + * overriding the default help message for builtin commands */ + if (SvOK(ST (3))) { + help_text = SvPV_nolen (ST (3)); + } + + userdata = ST (4); + data = NULL; + + data = malloc (sizeof (HookData)); + if (data == NULL) { + XSRETURN_UNDEF; + } + + data->callback = sv_mortalcopy (callback); + SvREFCNT_inc (data->callback); + data->userdata = sv_mortalcopy (userdata); + SvREFCNT_inc (data->userdata); + data->depth = 0; + data->package = NULL; + hook = xchat_hook_command (ph, name, pri, command_cb, help_text, data); + + XSRETURN_IV (PTR2IV (hook)); + } + +} + +/* Xchat::Internal::hook_print(name, priority, callback, [userdata]) */ +static +XS (XS_Xchat_hook_print) +{ + + char *name; + int pri; + SV *callback; + SV *userdata; + xchat_hook *hook; + HookData *data; + dXSARGS; + if (items != 4) { + xchat_print (ph, + "Usage: Xchat::Internal::hook_print(name, priority, callback, userdata)"); + } else { + name = SvPV_nolen (ST (0)); + pri = (int) SvIV (ST (1)); + callback = ST (2); + data = NULL; + userdata = ST (3); + + data = malloc (sizeof (HookData)); + if (data == NULL) { + XSRETURN_UNDEF; + } + + data->callback = sv_mortalcopy (callback); + SvREFCNT_inc (data->callback); + data->userdata = sv_mortalcopy (userdata); + SvREFCNT_inc (data->userdata); + data->depth = 0; + data->package = NULL; + hook = xchat_hook_print (ph, name, pri, print_cb, data); + + XSRETURN_IV (PTR2IV (hook)); + } +} + +/* Xchat::Internal::hook_timer(timeout, callback, userdata) */ +static +XS (XS_Xchat_hook_timer) +{ + int timeout; + SV *callback; + SV *userdata; + xchat_hook *hook; + SV *package; + HookData *data; + + dXSARGS; + + if (items != 4) { + xchat_print (ph, + "Usage: Xchat::Internal::hook_timer(timeout, callback, userdata, package)"); + } else { + timeout = (int) SvIV (ST (0)); + callback = ST (1); + data = NULL; + userdata = ST (2); + package = ST (3); + + data = malloc (sizeof (HookData)); + if (data == NULL) { + XSRETURN_UNDEF; + } + + data->callback = sv_mortalcopy (callback); + SvREFCNT_inc (data->callback); + data->userdata = sv_mortalcopy (userdata); + SvREFCNT_inc (data->userdata); + data->ctx = xchat_get_context (ph); + data->package = sv_mortalcopy (package); + SvREFCNT_inc (data->package); + hook = xchat_hook_timer (ph, timeout, timer_cb, data); + data->hook = hook; + + XSRETURN_IV (PTR2IV (hook)); + } +} + +/* Xchat::Internal::hook_fd(fd, callback, flags, userdata) */ +static +XS (XS_Xchat_hook_fd) +{ + int fd; + SV *callback; + int flags; + SV *userdata; + xchat_hook *hook; + HookData *data; + + dXSARGS; + + if (items != 4) { + xchat_print (ph, + "Usage: Xchat::Internal::hook_fd(fd, callback, flags, userdata)"); + } else { + fd = (int) SvIV (ST (0)); + callback = ST (1); + flags = (int) SvIV (ST (2)); + userdata = ST (3); + data = NULL; + +#ifdef WIN32 + if ((flags & XCHAT_FD_NOTSOCKET) == 0) { + /* this _get_osfhandle if from win32iop.h in the perl distribution, + * not the one provided by Windows + */ + fd = _get_osfhandle(fd); + if (fd < 0) { + xchat_print(ph, "Invalid file descriptor"); + XSRETURN_UNDEF; + } + } +#endif + + data = malloc (sizeof (HookData)); + if (data == NULL) { + XSRETURN_UNDEF; + } + + data->callback = sv_mortalcopy (callback); + SvREFCNT_inc (data->callback); + data->userdata = sv_mortalcopy (userdata); + SvREFCNT_inc (data->userdata); + data->package = NULL; + hook = xchat_hook_fd (ph, fd, flags, fd_cb, data); + data->hook = hook; + + XSRETURN_IV (PTR2IV (hook)); + } +} + +static +XS (XS_Xchat_unhook) +{ + xchat_hook *hook; + HookData *userdata; + int retCount = 0; + dXSARGS; + if (items != 1) { + xchat_print (ph, "Usage: Xchat::unhook(hook)"); + } else { + hook = INT2PTR (xchat_hook *, SvUV (ST (0))); + userdata = (HookData *) xchat_unhook (ph, hook); + + if (userdata != NULL) { + if (userdata->callback != NULL) { + SvREFCNT_dec (userdata->callback); + } + + if (userdata->userdata != NULL) { + XPUSHs (sv_mortalcopy (userdata->userdata)); + SvREFCNT_dec (userdata->userdata); + retCount = 1; + } + + if (userdata->package != NULL) { + SvREFCNT_dec (userdata->package); + } + free (userdata); + } + XSRETURN (retCount); + } + XSRETURN_EMPTY; +} + +/* Xchat::Internal::command(command) */ +static +XS (XS_Xchat_command) +{ + char *cmd = NULL; + + dXSARGS; + if (items != 1) { + xchat_print (ph, "Usage: Xchat::Internal::command(command)"); + } else { + cmd = SvPV_nolen (ST (0)); + xchat_command (ph, cmd); + + } + XSRETURN_EMPTY; +} + +static +XS (XS_Xchat_find_context) +{ + char *server = NULL; + char *chan = NULL; + xchat_context *RETVAL; + + dXSARGS; + if (items > 2) + xchat_print (ph, "Usage: Xchat::find_context ([channel, [server]])"); + { + + switch (items) { + case 0: /* no server name and no channel name */ + /* nothing to do, server and chan are already NULL */ + break; + case 1: /* channel name only */ + /* change channel value only if it is true or 0 */ + /* otherwise leave it as null */ + if (SvTRUE (ST (0)) || SvNIOK (ST (0))) { + chan = SvPV_nolen (ST (0)); + /* xchat_printf( ph, "XSUB - find_context( %s, NULL )", chan ); */ + } + /* else { xchat_print( ph, "XSUB - find_context( NULL, NULL )" ); } */ + /* chan is already NULL */ + break; + case 2: /* server and channel */ + /* change channel value only if it is true or 0 */ + /* otherwise leave it as NULL */ + if (SvTRUE (ST (0)) || SvNIOK (ST (0))) { + chan = SvPV_nolen (ST (0)); + /* xchat_printf( ph, "XSUB - find_context( %s, NULL )", SvPV_nolen(ST(0) )); */ + } + + /* else { xchat_print( ph, "XSUB - 2 arg NULL chan" ); } */ + /* change server value only if it is true or 0 */ + /* otherwise leave it as NULL */ + if (SvTRUE (ST (1)) || SvNIOK (ST (1))) { + server = SvPV_nolen (ST (1)); + /* xchat_printf( ph, "XSUB - find_context( NULL, %s )", SvPV_nolen(ST(1) )); */ + } + /* else { xchat_print( ph, "XSUB - 2 arg NULL server" ); } */ + break; + } + + RETVAL = xchat_find_context (ph, server, chan); + if (RETVAL != NULL) { + /* xchat_print (ph, "XSUB - context found"); */ + XSRETURN_IV (PTR2IV (RETVAL)); + } else { + /* xchat_print (ph, "XSUB - context not found"); */ + XSRETURN_UNDEF; + } + } +} + +static +XS (XS_Xchat_get_context) +{ + dXSARGS; + if (items != 0) { + xchat_print (ph, "Usage: Xchat::get_context()"); + } else { + XSRETURN_IV (PTR2IV (xchat_get_context (ph))); + } +} + +static +XS (XS_Xchat_set_context) +{ + xchat_context *ctx; + dXSARGS; + if (items != 1) { + xchat_print (ph, "Usage: Xchat::set_context(ctx)"); + } else { + ctx = INT2PTR (xchat_context *, SvUV (ST (0))); + XSRETURN_IV ((IV) xchat_set_context (ph, ctx)); + } +} + +static +XS (XS_Xchat_nickcmp) +{ + dXSARGS; + if (items != 2) { + xchat_print (ph, "Usage: Xchat::nickcmp(s1, s2)"); + } else { + XSRETURN_IV ((IV) xchat_nickcmp (ph, SvPV_nolen (ST (0)), + SvPV_nolen (ST (1)))); + } +} + +static +XS (XS_Xchat_get_list) +{ + SV *name; + xchat_list *list; + const char *const *fields; + int count = 0; /* return value for scalar context */ + dXSARGS; + + if (items != 1) { + xchat_print (ph, "Usage: Xchat::get_list(name)"); + } else { + SP -= items; /*remove the argument list from the stack */ + + name = ST (0); + + list = xchat_list_get (ph, SvPV_nolen (name)); + + if (list == NULL) { + XSRETURN_EMPTY; + } + + if (GIMME_V == G_SCALAR) { + while (xchat_list_next (ph, list)) { + count++; + } + xchat_list_free (ph, list); + XSRETURN_IV ((IV) count); + } + + fields = xchat_list_fields (ph, SvPV_nolen (name)); + while (xchat_list_next (ph, list)) { + XPUSHs (list_item_to_sv (list, fields)); + } + xchat_list_free (ph, list); + + PUTBACK; + return; + } +} + +static +XS (XS_Xchat_Embed_plugingui_remove) +{ + void *gui_entry; + dXSARGS; + if (items != 1) { + xchat_print (ph, "Usage: Xchat::Embed::plugingui_remove(handle)"); + } else { + gui_entry = INT2PTR (void *, SvUV (ST (0))); + xchat_plugingui_remove (ph, gui_entry); + } + XSRETURN_EMPTY; +} + +/* xs_init is the second argument perl_parse. As the name hints, it + initializes XS subroutines (see the perlembed manpage) */ +static void +xs_init (pTHX) +{ + HV *stash; + SV *version; + /* This one allows dynamic loading of perl modules in perl + scripts by the 'use perlmod;' construction */ + newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, __FILE__); + /* load up all the custom IRC perl functions */ + newXS ("Xchat::Internal::register", XS_Xchat_register, __FILE__); + newXS ("Xchat::Internal::hook_server", XS_Xchat_hook_server, __FILE__); + newXS ("Xchat::Internal::hook_command", XS_Xchat_hook_command, __FILE__); + newXS ("Xchat::Internal::hook_print", XS_Xchat_hook_print, __FILE__); + newXS ("Xchat::Internal::hook_timer", XS_Xchat_hook_timer, __FILE__); + newXS ("Xchat::Internal::hook_fd", XS_Xchat_hook_fd, __FILE__); + newXS ("Xchat::Internal::unhook", XS_Xchat_unhook, __FILE__); + newXS ("Xchat::Internal::print", XS_Xchat_print, __FILE__); + newXS ("Xchat::Internal::command", XS_Xchat_command, __FILE__); + newXS ("Xchat::Internal::set_context", XS_Xchat_set_context, __FILE__); + newXS ("Xchat::Internal::get_info", XS_Xchat_get_info, __FILE__); + newXS ("Xchat::Internal::context_info", XS_Xchat_context_info, __FILE__); + newXS ("Xchat::Internal::get_list", XS_Xchat_get_list, __FILE__); + + newXS ("Xchat::find_context", XS_Xchat_find_context, __FILE__); + newXS ("Xchat::get_context", XS_Xchat_get_context, __FILE__); + newXS ("Xchat::get_prefs", XS_Xchat_get_prefs, __FILE__); + newXS ("Xchat::emit_print", XS_Xchat_emit_print, __FILE__); + newXS ("Xchat::send_modes", XS_Xchat_send_modes, __FILE__); + newXS ("Xchat::nickcmp", XS_Xchat_nickcmp, __FILE__); + + newXS ("Xchat::Embed::plugingui_remove", XS_Xchat_Embed_plugingui_remove, + __FILE__); + + stash = get_hv ("Xchat::", TRUE); + if (stash == NULL) { + exit (1); + } + + newCONSTSUB (stash, "PRI_HIGHEST", newSViv (XCHAT_PRI_HIGHEST)); + newCONSTSUB (stash, "PRI_HIGH", newSViv (XCHAT_PRI_HIGH)); + newCONSTSUB (stash, "PRI_NORM", newSViv (XCHAT_PRI_NORM)); + newCONSTSUB (stash, "PRI_LOW", newSViv (XCHAT_PRI_LOW)); + newCONSTSUB (stash, "PRI_LOWEST", newSViv (XCHAT_PRI_LOWEST)); + + newCONSTSUB (stash, "EAT_NONE", newSViv (XCHAT_EAT_NONE)); + newCONSTSUB (stash, "EAT_XCHAT", newSViv (XCHAT_EAT_XCHAT)); + newCONSTSUB (stash, "EAT_PLUGIN", newSViv (XCHAT_EAT_PLUGIN)); + newCONSTSUB (stash, "EAT_ALL", newSViv (XCHAT_EAT_ALL)); + newCONSTSUB (stash, "FD_READ", newSViv (XCHAT_FD_READ)); + newCONSTSUB (stash, "FD_WRITE", newSViv (XCHAT_FD_WRITE)); + newCONSTSUB (stash, "FD_EXCEPTION", newSViv (XCHAT_FD_EXCEPTION)); + newCONSTSUB (stash, "FD_NOTSOCKET", newSViv (XCHAT_FD_NOTSOCKET)); + newCONSTSUB (stash, "KEEP", newSViv (1)); + newCONSTSUB (stash, "REMOVE", newSViv (0)); + + version = get_sv( "Xchat::VERSION", 1 ); + sv_setpv( version, PACKAGE_VERSION ); +} + +static void +perl_init (void) +{ + int warn; + int arg_count; + char *perl_args[] = { "", "-e", "0", "-w" }; + char *env[] = { "" }; + static const char xchat_definitions[] = { + /* Redefine the $SIG{__WARN__} handler to have XChat + printing warnings in the main window. (TheHobbit) */ +#include "xchat.pm.h" + }; +#ifdef OLD_PERL + static const char irc_definitions[] = { +#include "irc.pm.h" + }; +#endif +#ifdef ENABLE_NLS + + /* Problem is, dynamicaly loaded modules check out the $] + var. It appears that in the embedded interpreter we get + 5,00503 as soon as the LC_NUMERIC locale calls for a comma + instead of a point in separating integer and decimal + parts. I realy can't understant why... The following + appears to be an awful workaround... But it'll do until I + (or someone else :)) found the "right way" to solve this + nasty problem. (TheHobbit <thehobbit@altern.org>) */ + + setlocale (LC_NUMERIC, "C"); + +#endif + + warn = 0; + xchat_get_prefs (ph, "perl_warnings", NULL, &warn); + arg_count = warn ? 4 : 3; + + PERL_SYS_INIT3 (&arg_count, (char ***)&perl_args, (char ***)&env); + my_perl = perl_alloc (); + perl_construct (my_perl); + PL_exit_flags |= PERL_EXIT_DESTRUCT_END; + perl_parse (my_perl, xs_init, arg_count, perl_args, (char **)NULL); + + /* + Now initialising the perl interpreter by loading the + perl_definition array. + */ + + eval_pv (xchat_definitions, TRUE); +#ifdef OLD_PERL + eval_pv (irc_definitions, TRUE); +#endif + +} + + +static int +perl_load_file (char *filename) +{ +#ifdef WIN32 + static HMODULE lib = NULL; + + if (!lib) { + lib = LoadLibraryA (PERL_DLL); + if (!lib) { + if (GetLastError () == ERROR_BAD_EXE_FORMAT) + /* http://forum.xchat.org/viewtopic.php?t=3277 */ + thread_mbox ("Cannot use this " PERL_DLL "\n\n" + "32-bit ActivePerl is required."); + else { + /* a lot of people install this old version */ + lib = LoadLibraryA ("perl56.dll"); + if (lib) { + FreeLibrary (lib); + lib = NULL; + thread_mbox ("Cannot open " PERL_DLL "\n\n" + "You must have ActivePerl " PERL_REQUIRED_VERSION " installed in order to\n" + "run perl scripts.\n\n" + "I have found Perl 5.6, but that is too old."); + } else { + thread_mbox ("Cannot open " PERL_DLL "\n\n" + "You must have ActivePerl " PERL_REQUIRED_VERSION " installed in order to\n" + "run perl scripts.\n\n" + "http://www.activestate.com/ActivePerl/\n\n" + "Make sure perl's bin directory is in your PATH."); + } + } + /* failure */ + return FALSE; + } + + /* success */ + FreeLibrary (lib); + } +#endif + + if (my_perl == NULL) { + perl_init (); + } + + return execute_perl (sv_2mortal (newSVpv ("Xchat::Embed::load", 0)), + filename); + +} + +static void +perl_end (void) +{ + + if (my_perl != NULL) { + execute_perl (sv_2mortal (newSVpv ("Xchat::Embed::unload_all", 0)), ""); + PL_perl_destruct_level = 1; + perl_destruct (my_perl); + perl_free (my_perl); + PERL_SYS_TERM(); + my_perl = NULL; + } + +} + +static int +perl_command_unloadall (char *word[], char *word_eol[], void *userdata) +{ + if (my_perl != NULL) { + execute_perl (sv_2mortal (newSVpv ("Xchat::Embed::unload_all", 0)), ""); + return XCHAT_EAT_XCHAT; + } + + return XCHAT_EAT_XCHAT; +} + +static int +perl_command_reloadall (char *word[], char *word_eol[], void *userdata) +{ + if (my_perl != NULL) { + execute_perl (sv_2mortal (newSVpv ("Xchat::Embed::reload_all", 0)), ""); + + return XCHAT_EAT_XCHAT; + } else { + perl_auto_load( NULL ); + } + return XCHAT_EAT_XCHAT; +} + +static int +perl_command_load (char *word[], char *word_eol[], void *userdata) +{ + char *file = get_filename (word, word_eol); + + if (file != NULL ) + { + perl_load_file (file); + return XCHAT_EAT_XCHAT; + } + + return XCHAT_EAT_NONE; +} + +static int +perl_command_unload (char *word[], char *word_eol[], void *userdata) +{ + char *file = get_filename (word, word_eol); + + if (my_perl != NULL && file != NULL) { + execute_perl (sv_2mortal (newSVpv ("Xchat::Embed::unload", 0)), file); + return XCHAT_EAT_XCHAT; + } + + return XCHAT_EAT_NONE; +} + +static int +perl_command_reload (char *word[], char *word_eol[], void *userdata) +{ + char *file = get_filename (word, word_eol); + + if (my_perl != NULL && file != NULL) { + execute_perl (sv_2mortal (newSVpv ("Xchat::Embed::reload", 0)), file); + return XCHAT_EAT_XCHAT; + } + + return XCHAT_EAT_XCHAT; +} + +void +xchat_plugin_get_info (char **name, char **desc, char **version, + void **reserved) +{ + *name = "Perl"; + *desc = "Perl scripting interface"; + *version = PACKAGE_VERSION; + if (reserved) + *reserved = NULL; +} + + +/* Reinit safeguard */ + +static int initialized = 0; + +int +xchat_plugin_init (xchat_plugin * plugin_handle, char **plugin_name, + char **plugin_desc, char **plugin_version, char *arg) +{ + if (initialized != 0) { + xchat_print (plugin_handle, "Perl interface already loaded\n"); + return 0; + } + + ph = plugin_handle; + initialized = 1; + + *plugin_name = "Perl"; + *plugin_desc = "Perl scripting interface"; + *plugin_version = PACKAGE_VERSION; + + xchat_hook_command (ph, "load", XCHAT_PRI_NORM, perl_command_load, 0, 0); + xchat_hook_command (ph, "unload", XCHAT_PRI_NORM, perl_command_unload, 0, + 0); + xchat_hook_command (ph, "reload", XCHAT_PRI_NORM, perl_command_reload, 0, + 0); + xchat_hook_command (ph, "pl_reload", XCHAT_PRI_NORM, perl_command_reload, 0, + 0); + xchat_hook_command (ph, "unloadall", XCHAT_PRI_NORM, + perl_command_unloadall, 0, 0); + xchat_hook_command (ph, "reloadall", XCHAT_PRI_NORM, + perl_command_reloadall, 0, 0); + + /*perl_init (); */ + xchat_hook_timer (ph, 0, perl_auto_load, NULL ); + + xchat_print (ph, "Perl interface loaded\n"); + + return 1; +} + +int +xchat_plugin_deinit (xchat_plugin * plugin_handle) +{ + perl_end (); + + initialized = 0; + xchat_print (plugin_handle, "Perl interface unloaded\n"); + + return 1; +} diff --git a/plugins/perl/perl.def b/plugins/perl/perl.def new file mode 100644 index 00000000..a2ec6566 --- /dev/null +++ b/plugins/perl/perl.def @@ -0,0 +1,4 @@ +EXPORTS + xchat_plugin_init + xchat_plugin_deinit + xchat_plugin_get_info \ No newline at end of file diff --git a/plugins/perl/syntax_highlight b/plugins/perl/syntax_highlight new file mode 100644 index 00000000..96d57003 --- /dev/null +++ b/plugins/perl/syntax_highlight @@ -0,0 +1,69 @@ +#!/usr/bin/env perl +use 5.010; +use strict; +use warnings; +use Text::VimColor; +use HTML::TokeParser::Simple; +use HTML::Entities qw(decode_entities); +use Path::Class; + +my $html_file = shift; +my $reader = file( $html_file )->openr; +unlink $html_file; +my $writer = file( $html_file )->openw; + +my $parser = HTML::TokeParser::Simple->new( $reader ); + +while( my $token = $parser->get_token ) { + + my $class_name = $token->get_attr( "class" ); + + if( $token->is_start_tag( "div" ) + && ( $class_name && $class_name =~ qr/\bexample\b/ ) + ) { + my $start_tag = $token; + $start_tag->set_attr( class => $class_name . " synNormal" ); + my @content; + my $end_tag; + + EXAMPLE: + while( $token = $parser->get_token ) { + if( $token->is_end_tag( "div" ) ) { + $end_tag = $token; + last EXAMPLE; + } + + if( $token->is_text ) { + push @content, decode_entities( $token->as_is ); + } + } + + my $code = join "", @content; +# say $code; + my $vim = Text::VimColor->new( + string => $code, + filetype => "perl", + vim_options => [qw( -RXZ -i NONE -u NONE -N -n)], + ); + my $html = $vim->html; + $html =~ s/^\s+//; + $html =~ s/\s+$//; + + print $writer $start_tag->as_is; + + my $lines = $html =~ tr/\n/\n/; + + say $writer "<div class='line_number'>"; + for my $line ( 0 .. $lines ) { + say $writer "<div>",1 + $line,"</div>"; + } + say $writer "</div>"; + + print $writer "<div class='content'><pre>"; + say $writer $html; + say $writer "</pre></div>"; + print $writer $end_tag->as_is; + } else { + print $writer $token->as_is; + } +} diff --git a/plugins/perl/xchat2-perl.html b/plugins/perl/xchat2-perl.html new file mode 100644 index 00000000..38dd3912 --- /dev/null +++ b/plugins/perl/xchat2-perl.html @@ -0,0 +1,1166 @@ +<?xml version="1.0" ?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<title>X-Chat 2 Perl Interface</title> +<meta http-equiv="content-type" content="text/html; charset=utf-8" /> +<link rev="made" href="mailto:khisanth@miyu.hopto.org" /> +<style type="text/css"> + .branch { + list-style: none; + } + + li code { + padding-right: 0.5em; + } + + .example { + width: 98%; + padding: 0.5em; + float: left; + font-family: monospace; + } + + .example .line_number { + float: left; + text-align: right; + margin-right: 10px; + padding-right: 5px; + border-right: 1px solid white; + } + + .example .content { + float: left; + } + + .example .content pre { + margin: 0; + } + + td > table { + margin: 0.5em; + border-collapse: collapse; + } + + td > table td { + border: 1px solid black; + } + + .synComment { + color: rgb(135,206,235); + } + .synPreProc { + color: rgb(205,92,92); + } + .synError { + } + .synConstant { + color: #ffa0a0; + } + .synSpecial { + color: rgb(255,222,173); + } + .synIgnore { + color: rgb(102,102,102); + } + .synNormal { + color: rgb(255,255,255); + background-color: rgb(51,51,51); + } + .synType { + color: rgb(189,183,107); + } + .synIdentifier { + color: rgb(152,251,152); + } + .synTodo { + color: rgb(255,69,0); + background-color: rgb(238,238,0); + } + .synStatement { + color: rgb(240,230,140); + } + +</style> +</head> + +<body style="background-color: white"> +<table border="0" width="100%" cellspacing="0" cellpadding="3"> +<tr><td class="block" style="background-color: #cccccc" valign="middle"> +<big><strong><span class="block"> X-Chat 2 Perl Interface</span></strong></big> +</td></tr> +</table> + + +<!-- INDEX BEGIN --> +<div> +<p><a name="__index__"></a></p> + +<ul> + <li><a href="#x_chat_2_perl_interface">X-Chat 2 Perl Interface</a></li> + <li class="branch"> + <ul> + <li><a href="#introduction">Introduction</a></li> + <li><a href="#constants">Constants</a></li> + <li class="branch"> + <ul> + <li><a href="#priorities">Priorities</a></li> + <li><a href="#return_values">Return values</a></li> + <li class="branch"> + <ul> + <li><a href="#timer_and_fd_hooks">Timer and fd hooks</a></li> + </ul> + </li> + + <li><a href="#hook_fd_flags">hook_fd flags</a></li> + </ul> + </li> + + <li><a href="#functions">Functions</a></li> + <li class="branch"> + <ul> + <li><a href="#xchat_register"><code>Xchat::register( $name, $version, [$description,[$callback]] )</code></a></li> + <li><a href="#xchat_hook_server"><code>Xchat::hook_server( $message, $callback, [\%options] )</code></a></li> + <li><a href="#xchat_hook_command"><code>Xchat::hook_command( $command, $callback, [\%options] )</code></a></li> + <li><a href="#xchat_hook_print"><code>Xchat::hook_print( $event,$callback, [\%options] )</code></a></li> + <li><a href="#xchat_hook_timer"><code>Xchat::hook_timer( $timeout,$callback, [\%options | $data] )</code></a></li> + <li><a href="#xchat_hook_fd"><code>Xchat::hook_fd( $handle, $callback, [ \%options ] )</code></a></li> + <li class="branch"> + <ul> + <li><a href="#when_callbacks_are_invoked">When callbacks are invoked</a></li> + <li><a href="#callback_arguments">Callback Arguments</a></li> + <li><a href="#callback_return_values">Callback return values</a></li> + <li><a href="#miscellaneous_hook_related_information">Miscellaneous Hook Related Information</a></li> + </ul> + </li> + + <li><a href="#xchat_unhook"><code>Xchat::unhook( $hook )</code></a></li> + <li><a href="#xchat_print"><code>Xchat::print( $text | \@lines, [$channel,[$server]] )</code></a></li> + <li><a href="#xchat_printf"><code>Xchat::printf( $format, LIST )</code></a></li> + <li><a href="#xchat_command"><code>Xchat::command( $command | \@commands, [$channel,[$server]] )</code></a></li> + <li><a href="#xchat_commandf"><code>Xchat::commandf( $format, LIST )</code></a></li> + <li><a href="#xchat_find_context"><code>Xchat::find_context( [$channel, [$server]] )</code></a></li> + <li><a href="#xchat_get_context"><code>Xchat::get_context()</code></a></li> + <li><a href="#xchat_set_context"><code>Xchat::set_context( $context | $channel,[$server] )</code></a></li> + <li><a href="#xchat_get_info"><code>Xchat::get_info( $id )</code></a></li> + <li><a href="#xchat_get_prefs"><code>Xchat::get_prefs( $name )</code></a></li> + <li><a href="#xchat_emit_print"><code>Xchat::emit_print( $event, LIST )</code></a></li> + <li><a href="#xchat_send_modes"><code>Xchat::send_modes( $target | \@targets, $sign, $mode, [ $modes_per_line ] )</code></a></li> + <li><a href="#xchat_nickcmp"><code>Xchat::nickcmp( $nick1, $nick2 )</code></a></li> + <li><a href="#xchat_get_list"><code>Xchat::get_list( $name )</code></a></li> + <li><a href="#xchat_user_info"><code>Xchat::user_info( [$nick] )</code></a></li> + <li><a href="#xchat_context_info"><code>Xchat::context_info( [$context] )</code></a></li> + <li><a href="#xchat_strip_code"><code>Xchat::strip_code( $string )</code></a></li> + </ul> + </li> + + <li><a href="#examples">Examples</a></li> + <li class="branch"> + <ul> + <li><a href="#asynchronous_dns_resolution_with_hook_fd">Asynchronous DNS resolution with hook_fd</a></li> + </ul> + </li> + + <li><a href="#contact_information">Contact Information</a></li> + </ul> + </li> +</ul> + +<hr /> +</div> +<!-- INDEX END --> + +<p> +</p> +<h1><a name="x_chat_2_perl_interface" />X-Chat 2 Perl Interface</h1> +<p> +</p> +<h2><a name="introduction" />Introduction</h2> +<p>This is the new Perl interface for X-Chat 2. However, due to changes in +xchat's plugin code you will need xchat 2.0.8 or above to load this. Scripts +written using the old interface will continue to work. If there are any +problems, questions, comments or suggestions please email them to the address +on the bottom of this page.</p> +<p> +</p> +<h2><a name="constants" />Constants</h2> +<p> +</p> +<h3><a name="priorities" />Priorities</h3> +<ul> +<li><strong><code>Xchat::PRI_HIGHEST</code></strong> +</li> +<li><strong><code>Xchat::PRI_HIGH</code></strong> +</li> +<li><strong><code>Xchat::PRI_NORM</code></strong> +</li> +<li><strong><code>Xchat::PRI_LOW</code></strong> +</li> +<li><strong><code>Xchat::PRI_LOWEST</code></strong> +</li> +</ul> +<p> +</p> +<h3><a name="return_values" />Return values</h3> +<ul> +<li><strong><code>Xchat::EAT_NONE</code> - pass the event along</strong> +</li> +<li><strong><code>Xchat::EAT_XCHAT</code> - don't let xchat see this event</strong> +</li> +<li><strong><code>Xchat::EAT_PLUGIN</code> - don't let other scripts and plugins see this event but xchat will still see it</strong> +</li> +<li><strong><code>Xchat::EAT_ALL</code> - don't let anything else see this event</strong> +</li> +</ul> +<p> +</p> +<h4><a name="timer_and_fd_hooks" />Timer and fd hooks</h4> +<ul> +<li><strong><code>Xchat::KEEP</code> - keep the timer going or hook watching the handle</strong> +</li> +<li><strong><code>Xchat::REMOVE</code> - remove the timer or hook watching the handle</strong> +</li> +</ul> +<p> +</p> +<h3><a name="hook_fd_flags" />hook_fd flags</h3> +<ul> +<li><strong><code>Xchat::FD_READ</code> - invoke the callback when the handle is ready for reading</strong> +</li> +<li><strong><code>Xchat::FD_WRITE</code> - invoke the callback when the handle is ready for writing</strong> +</li> +<li><strong><code>Xchat::FD_EXCEPTION</code> - invoke the callback if an exception occurs</strong> +</li> +<li><strong><code>Xchat::FD_NOTSOCKET</code> - indicate that the handle being hooked is not a socket</strong> +</li> +</ul> +<p> +</p> +<h2><a name="functions" />Functions</h2> +<p> +</p> +<h3><a name="xchat_register" /><code>Xchat::register( $name, $version, [$description,[$callback]] )</code></h3> +<ul> +<li><strong><code>$name</code> - The name of this script</strong> +</li> +<li><strong><code>$version</code> - This script's version</strong> +</li> +<li><strong><code>$description</code> - A description for this script</strong> +</li> +<li><strong><code>$callback</code> - This is a function that will be called when the is script + unloaded. This can be either a reference to a + function or an anonymous sub reference.</strong> +</li> +</ul> +<p>This is the first thing to call in every script.</p> +<p> +</p> +<h3><a name="xchat_hook_server" /><code>Xchat::hook_server( $message, $callback, [\%options] )</code></h3> +<p> +</p> +<h3><a name="xchat_hook_command" /><code>Xchat::hook_command( $command, $callback, [\%options] )</code></h3> +<p> +</p> +<h3><a name="xchat_hook_print" /><code>Xchat::hook_print( $event,$callback, [\%options] )</code></h3> +<p> +</p> +<h3><a name="xchat_hook_timer" /><code>Xchat::hook_timer( $timeout,$callback, [\%options | $data] )</code></h3> +<p> +</p> +<h3><a name="xchat_hook_fd" /><code>Xchat::hook_fd( $handle, $callback, [ \%options ] )</code></h3> +<p>These functions can be to intercept various events. +hook_server can be used to intercept any incoming message from the IRC server. +hook_command can be used to intercept any command, if the command doesn't currently exist then a new one is created. +hook_print can be used to intercept any of the events listed in Setttings->Advanced->Text Events +hook_timer can be used to create a new timer</p> +<ul> +<li><strong><code>$message</code> - server message to hook such as PRIVMSG</strong> +</li> +<li><strong><code>$command</code> - command to intercept, without the leading /</strong> +</li> +<li><strong><code>$event</code> - one of the events listed in Settings->Advanced->Text Events</strong> +</li> +<li><strong><code>$timeout</code> - timeout in milliseconds</strong> +</li> +<li><strong><code>$handle</code> - the I/O handle you want to monitor with hook_fd. This must be something that has a fileno. See perldoc -f fileno or <a href="http://perldoc.perl.org/functions/fileno.html">fileno</a></strong> +</li> +<li><strong><code>$callback</code> - callback function, this is called whenever + the hooked event is trigged, the following are + the conditions that will trigger the different hooks. + This can be either a reference to a + function or an anonymous sub reference.</strong> +</li> +<li><strong>\%options - a hash reference containing addional options for the hooks</strong> +</li> +</ul> +<p>Valid keys for \%options:</p> +<table border="1"> <tr> + <td>data</td> <td>Additional data that is to be associated with the<br /> + hook. For timer hooks this value can be provided either as<br /> + <code>Xchat::hook_timer( $timeout, $cb,{data=>$data})</code><br /> + or <code>Xchat::hook_timer( $timeout, $cb, $data )</code>.<br /> + However, this means that hook_timer cannot be provided<br /> + with a hash reference containing data as a key.<br /> example:<br /> + my $options = { data => [@arrayOfStuff] };<br /> + Xchat::hook_timer( $timeout, $cb, $options );<br /> + <br /> + In this example, the timer's data will be<br /> + [@arrayOfStuff] and not { data => [@arrayOfStuff] }<br /> + <br /> + This key is valid for all of the hook functions.<br /> + <br /> + Default is undef.<br /> + </td> + </tr> <tr> + <td>priority</td> <td>Sets the priority for the hook.<br /> + It can be set to one of the + <code>Xchat::PRI_*</code> constants.<br /> + <br /> + This key only applies to server, command + and print hooks.<br /> + <br /> + Default is <code>Xchat::PRI_NORM</code>. + </td> </tr> <tr> + <td>help_text</td> <td>Text displayed for /help $command.<br /> + <br /> + This key only applies to command hooks.<br /> + <br /> + Default is "". + </td> + </tr> <tr> + <td>flags</td> <td>Specify the flags for a fd hook.<br /> + <br /> + See <a href="#hook_fd_flags">hook fd flags</a> section for valid values.<br /> + <br /> + On Windows if the handle is a pipe you specify<br /> + Xchat::FD_NOTSOCKET in addition to any other flags you might be using.<br /> + <br /> + This key only applies to fd hooks.<br /> + Default is Xchat::FD_READ + </td> + </tr></table><p> +</p> +<h4><a name="when_callbacks_are_invoked" />When callbacks are invoked</h4> +<p>Each of the hooks will be triggered at different times depending on the type +of hook.</p> +<table border="1"> <tr style="background-color: #dddddd"> + <td>Hook Type</td> <td>When the callback will be invoked</td> + </tr> <tr> + <td>server hooks</td> <td>a <code>$message</code> message is + received from the server + </td> + </tr> <tr> + <td>command hooks</td> <td>the <code>$command</code> command is + executed, either by the user or from a script + </td> + </tr> <tr> + <td>print hooks</td> <td>X-Chat is about to print the message for the + <code>$event</code> event + </td> + </tr> <tr> + <td>timer hooks</td> <td>called every <code>$timeout</code> milliseconds + (1000 millisecond is 1 second)<br /> + the callback will be executed in the same context where + the hook_timer was called, if the context no longer exists + then it will execute in a random context + </td> + </tr> <tr> + <td>fd hooks</td> <td>depends on the flags that were passed to hook_fd<br /> + See <a href="#hook_fd_flags">hook_fd flags</a> section. + </td> + </tr> +</table><p>The value return from these hook functions can be passed to <code>Xchat::unhook</code> +to remove the hook.</p> +<p> +</p> +<h4><a name="callback_arguments" />Callback Arguments</h4> +<p>All callback functions will receive their arguments in <code>@_</code> like every +other Perl subroutine.</p> +<p> +Server and command callbacks<br /> +<br /> +<code>$_[0]</code> - array reference containing the IRC message or command and +arguments broken into words<br /> +example:<br /> +/command arg1 arg2 arg3<br /> +<code>$_[0][0]</code> - command<br /> +<code>$_[0][1]</code> - arg1<br /> +<code>$_[0][2]</code> - arg2<br /> +<code>$_[0][3]</code> - arg3<br /> +<br /> +<code>$_[1]</code> - array reference containing the Nth word to the last word<br /> +example:<br /> +/command arg1 arg2 arg3<br /> +<code>$_[1][0]</code> - command arg1 arg2 arg3<br /> +<code>$_[1][1]</code> - arg1 arg2 arg3<br /> +<code>$_[1][2]</code> - arg2 arg3<br /> +<code>$_[1][3]</code> - arg3<br /> +<br /> +<code>$_[2]</code> - the data that was passed to the hook function<br /> +<br /> +Print callbacks<br /> +<br /> +<code>$_[0]</code> - array reference containing the values for the + text event see Settings->Advanced->Text Events<br /> +<code>$_[1]</code> - the data that was passed to the hook function<br /> +<br /> +Timer callbacks<br /> +<br /> +<code>$_[0]</code> - the data that was passed to the hook function<br /> +<br />fd callbacks<br /> +<br /> +<code>$_[0]</code> - the handle that was passed to hook_fd<br /> +<code>$_[1]</code> - flags indicating why the callback was called<br /> +<code>$_[2]</code> - the data that was passed to the hook function<br /> +</p><p> +</p> +<h4><a name="callback_return_values" />Callback return values</h4> +<p>All server, command and print callbacks should return one of +the <code>Xchat::EAT_*</code> constants. +Timer callbacks can return Xchat::REMOVE to remove +the timer or Xchat::KEEP to keep it going</p> +<p> +</p> +<h4><a name="miscellaneous_hook_related_information" />Miscellaneous Hook Related Information</h4> +<p>For server hooks, if <code>$message</code> is "RAW LINE" then <code>$cb</code> will be called for +every IRC message than X-Chat receives.</p> +<p>For command hooks if <code>$command</code> is "" then <code>$cb</code> will be called for +messages entered by the user that is not a command.</p> +<p>For print hooks besides those events listed in +Settings->Advanced->Text Events, these additional events can be used.</p> +<table border="1"> <tr style="background-color: #dddddd"> + <td>Event</td> <td>Description</td> + </tr> <tr> + <td>"Open Context"</td> <td>a new context is created</td> + </tr> <tr> + <td>"Close Context"</td> <td>a context has been close</td> + </tr> <tr> + <td>"Focus Tab"</td> <td>when a tab is brought to the front</td> + </tr> <tr> + <td>"Focus Window"</td> <td>when a top level window is focused or the + main tab window is focused by the window manager + </td> + </tr> <tr> + <td>"DCC Chat Text"</td> <td>when text from a DCC Chat arrives. + <code>$_[0]</code> will have these values<br /> + <br /> + <code>$_[0][0]</code> - Address<br /> + <code>$_[0][1]</code> - Port<br /> + <code>$_[0][2]</code> - Nick<br /> + <code>$_[0][3]</code> - Message<br /> + </td> + </tr> <tr> + <td>"Key Press"</td> <td>used for intercepting key presses<br /> + $_[0][0] - key value<br /> + $_[0][1] - state bitfield, 1 - shift, 4 - control, 8 - alt<br /> + $_[0][2] - string version of the key which might be empty for unprintable keys<br /> + $_[0][3] - length of the string in $_[0][2]<br /> + </td> + </tr> +</table><p> +</p> +<h3><a name="xchat_unhook" /><code>Xchat::unhook( $hook )</code></h3> +<ul> +<li><strong><code>$hook</code> - the hook that was previously returned by one of the <code>Xchat::hook_*</code> functions</strong> +</li> +</ul> +<p>This function is used to removed a hook previously added with one of +the <code>Xchat::hook_*</code> functions</p> +<p>It returns the data that was passed to the <code>Xchat::hook_*</code> function when +the hook was added</p> +<p> +</p> +<h3><a name="xchat_print" /><code>Xchat::print( $text | \@lines, [$channel,[$server]] )</code></h3> +<ul> +<li><strong><code>$text</code> - the text to print</strong> +</li> +<li><strong><code>\@lines</code> - array reference containing lines of text to be printed + all the elements will be joined together before printing</strong> +</li> +<li><strong><code>$channel</code> - channel or tab with the given name where <code>$text</code> + will be printed</strong> +</li> +<li><strong><code>$server</code> - specifies that the text will be printed in a channel or tab + that is associated with <code>$server</code></strong> +</li> +</ul> +<p>The first argument can either be a string or an array reference of strings. +Either or both of <code>$channel</code> and <code>$server</code> can be undef.</p> +<p>If called as <code>Xchat::print( $text )</code>, it will always return true. +If called with either the channel or the channel and the server +specified then it will return true if a context is found and +false otherwise. The text will not be printed if the context +is not found. The meaning of setting <code>$channel</code> or <code>$server</code> to +undef is the same as +<a href="#xchat_find_context">find_context</a>.</p> +<p> +</p> +<h3><a name="xchat_printf" /><code>Xchat::printf( $format, LIST )</code></h3> +<ul> +<li><strong><code>$format</code> - a format string, see "perldoc -f <a href="http://perldoc.perl.org/functions/sprintf.html">sprintf</a>" for further detail</strong> +</li> +<li><strong>LIST - list of values for the format fields</strong> +</li> +</ul> +<p> +</p> +<h3><a name="xchat_command" /><code>Xchat::command( $command | \@commands, [$channel,[$server]] )</code></h3> +<ul> +<li><strong><code>$command</code> - the command to execute, without the leading /</strong> +</li> +<li><strong><code>\@commands</code> - array reference containing a list of commands to execute</strong> +</li> +<li><strong><code>$channel</code> - channel or tab with the given name where <code>$command</code> will be executed</strong> +</li> +<li><strong><code>$server</code> - specifies that the command will be executed in a channel or tab that is associated with <code>$server</code></strong> +</li> +</ul> +<p>The first argument can either be a string or an array reference of strings. +Either or both of <code>$channel</code> and <code>$server</code> can be undef.</p> +<p>If called as <code>Xchat::command( $command )</code>, it will always return true. +If called with either the channel or the channel and the server +specified then it will return true if a context is found and false +otherwise. The command will not be executed if the context is not found. +The meaning of setting <code>$channel</code> or <code>$server</code> to undef is the same +as find_context.</p> +<p> +</p> +<h3><a name="xchat_commandf" /><code>Xchat::commandf( $format, LIST )</code></h3> +<ul> +<li><strong><code>$format</code> - a format string, see "perldoc -f <a href="http://perldoc.perl.org/functions/sprintf.html">sprintf</a>" for further detail</strong> +</li> +<li><strong>LIST - list of values for the format fields</strong> +</li> +</ul> +<p> +</p> +<h3><a name="xchat_find_context" /><code>Xchat::find_context( [$channel, [$server]] )</code></h3> +<ul> +<li><strong><code>$channel</code> - name of a channel</strong> +</li> +<li><strong><code>$server</code> - name of a server</strong> +</li> +</ul> +<p>Either or both of <code>$channel</code> and $server can be undef. Calling +<code>Xchat::find_context()</code> is the same as calling +<code>Xchat::find_context( undef, undef)</code> and +<code>Xchat::find_context( $channel )</code> is +the same as <code>Xchat::find_context( $channel, undef )</code>.</p> +<p>If <code>$server</code> is undef, find any channel named $channel. +If <code>$channel</code> is undef, find the front most window +or tab named <code>$server</code>.If both $channel and +<code>$server</code> are undef, find the currently focused tab or window.</p> +<p>Return the context found for one of the above situations or undef if such +a context cannot be found.</p> +<p> +</p> +<h3><a name="xchat_get_context" /><code>Xchat::get_context()</code></h3> +<p>Returns the current context.</p> +<p> +</p> +<h3><a name="xchat_set_context" /><code>Xchat::set_context( $context | $channel,[$server] )</code></h3> +<ul> +<li><strong><code>$context</code> - context value as returned from <a href="#xchat_get_context">get_context</a>,<a href="#xchat_find_context">find_context</a> or one + of the fields in the list of hashrefs returned by list_get</strong> +</li> +<li><strong><code>$channel</code> - name of a channel you want to switch context to</strong> +</li> +<li><strong><code>$server</code> - name of a server you want to switch context to</strong> +</li> +</ul> +<p>See <a href="#xchat_find_context">find_context</a> for more details on <code>$channel</code> and <code>$server</code>.</p> +<p>Returns true on success, false on failure</p> +<p> +</p> +<h3><a name="xchat_get_info" /><code>Xchat::get_info( $id )</code></h3> +<ul> +<li><strong><code>$id</code> - one of the following case sensitive values</strong> +</li> +</ul> +<table border="1"> <tr style="background-color: #dddddd"> + <td>ID</td> <td>Return value</td> + </tr> <tr> + <td>away</td> <td>away reason or undef if you are not away</td> + </tr> <tr> + <td>channel</td> <td>current channel name</td> + </tr> <tr> + <td>charset</td> <td>character-set used in the current context</td> + </tr> <tr> + <td>event_text <Event Name></td> <td>text event format string for <Event name><br /> + Example: + <div class="example synNormal"><div class='line_number'> +<div>1</div> +</div> +<div class='content'><pre><span class="synStatement">my</span> <span class="synIdentifier">$channel_msg_format</span> = Xchat::get_info( <span class="synStatement">"</span><span class="synConstant">event_text Channel Message</span><span class="synStatement">"</span> ); +</pre></div> +</div> + </td> +</tr> +<tr> + <td>host</td> <td>real hostname of the current server</td> +</tr><tr> + <td>id</td> <td>connection id</td> +</tr><tr> + <td>inputbox</td> <td>contents of the inputbox</td> +</tr><tr> + <td>libdirfs</td> + <td>the system wide directory where xchat will look for plugins. + this string is in the same encoding as the local file system</td> +</tr><tr> + <td>modes</td> <td>the current channels modes or undef if not known</td> +</tr><tr> + <td>network</td> <td>current network name or undef</td> +</tr><tr> + <td>nick</td> <td>current nick</td> +</tr><tr> + <td>nickserv</td> <td>nickserv password for this network or undef</td> +</tr><tr> + <td>server</td> <td>current server name <br /> + (what the server claims to be) undef if not connected + </td> +</tr><tr> + <td>state_cursor</td> + <td>current inputbox cursor position in characters</td> +</tr><tr> + <td>topic</td> <td>current channel topic</td> +</tr><tr> + <td>version</td> <td>xchat version number</td> +</tr><tr> + <td>win_status</td> + <td>status of the xchat window, possible values are "active", "hidden" + and "normal"</td> +</tr><tr> + <td>win_ptr</td> <td>native window pointer, GtkWindow * on Unix, HWND on Win32.<br /> + On Unix if you have the Glib module installed you can use my $window = Glib::Object->new_from_pointer( Xchat::get_info( "win_ptr" ) ); to get a Gtk2::Window object.<br /> + Additionally when you have detached tabs, each of the windows will return a different win_ptr for the different Gtk2::Window objects.<br /> + See <a href="http://xchat.cvs.sourceforge.net/viewvc/xchat/xchat2/plugins/perl/char_count.pl?view=markup">char_count.pl</a> for a longer example of a script that uses this to show how many characters you currently have in your input box. + </td> +</tr> +<tr> + <td>xchatdir</td> <td>xchat config directory encoded in UTF-8<br /> + examples:<br /> + /home/user/.xchat2<br /> + C:\Documents and Settings\user\Application Data\X-Chat 2 + </td> +</tr><tr> + <td>xchatdirfs</td> <td>same as xchatdir except encoded in the locale file system encoding</td> +</tr> +</table><p>This function is used to retrieve certain information about the current +context.</p><p> +</p> +<h3><a name="xchat_get_prefs" /><code>Xchat::get_prefs( $name )</code></h3> +<ul> +<li><strong><code>$name</code> - name of a X-Chat setting (available through the /set command)</strong> +</li> +</ul> +<p>This function provides a way to retrieve X-Chat's setting information.</p> +<p>Returns <code>undef</code> if there is no setting called called <code>$name</code>.</p> +<p> +</p> +<h3><a name="xchat_emit_print" /><code>Xchat::emit_print( $event, LIST )</code></h3> +<ul> +<li><strong><code>$event</code> - name from the Event column in Settings->Advanced->Text Events</strong> +</li> +<li><strong>LIST - this depends on the Description column on the bottom of Settings->Advanced->Text Events</strong> +</li> +</ul> +<p>This functions is used to generate one of the events listed under +Settings->Advanced->Text Events</p> +<p>Note: when using this function you MUST return Xchat::EAT_ALL otherwise you will end up with duplicate events. +One is the original and the second is the one you emit.</p> +<p>Returns true on success, false on failure</p> +<p> +</p> +<h3><a name="xchat_send_modes" /><code>Xchat::send_modes( $target | \@targets, $sign, $mode, [ $modes_per_line ] )</code></h3> +<ul> +<li><strong><code>$target</code> - a single nick to set the mode on</strong> +</li> +<li><strong><code>\@targets</code> - an array reference of the nicks to set the mode on</strong> +</li> +<li><strong><code>$sign</code> - the mode sign, either '+' or '-'</strong> +</li> +<li><strong><code>$mode</code> - the mode character such as 'o' and 'v', this can only be one character long</strong> +</li> +<li><strong><code>$modes_per_line</code> - an optional argument maximum number of modes to send per at once, pass 0 use the current server's maximum (default)</strong> +</li> +</ul> +<p>Send multiple mode changes for the current channel. It may send multiple MODE lines if the request doesn't fit on one.</p> +<p>Example:</p> +<<div class="example synNormal"><div class='line_number'> +<div>1</div> +<div>2</div> +<div>3</div> +<div>4</div> +<div>5</div> +<div>6</div> +<div>7</div> +<div>8</div> +<div>9</div> +<div>10</div> +<div>11</div> +<div>12</div> +<div>13</div> +<div>14</div> +</div> +<div class='content'><pre><span class="synStatement">use strict</span>; +<span class="synStatement">use </span>warning; +<span class="synStatement">use </span>Xchat <span class="synStatement">qw(</span><span class="synConstant">:all</span><span class="synStatement">)</span>; + +hook_command( <span class="synStatement">"</span><span class="synConstant">MODES</span><span class="synStatement">"</span>, <span class="synStatement">sub </span>{ + <span class="synStatement">my</span> (<span class="synStatement">undef</span>, <span class="synIdentifier">$who</span>, <span class="synIdentifier">$sign</span>, <span class="synIdentifier">$mode</span>) = <span class="synIdentifier">@{$_[</span><span class="synConstant">0</span><span class="synIdentifier">]}</span>; + <span class="synStatement">my</span> <span class="synIdentifier">@targets</span> = <span class="synStatement">split</span> <span class="synStatement">/</span><span class="synConstant">,</span><span class="synStatement">/</span>, <span class="synIdentifier">$who</span>; + <span class="synStatement">if</span>( <span class="synIdentifier">@targets</span> > <span class="synConstant">1</span> ) { + send_modes( \<span class="synIdentifier">@targets</span>, <span class="synIdentifier">$sign</span>, <span class="synIdentifier">$mode</span>, <span class="synConstant">1</span> ); + } <span class="synStatement">else</span> { + send_modes( <span class="synIdentifier">$who</span>, <span class="synIdentifier">$sign</span>, <span class="synIdentifier">$mode</span> ); + } + <span class="synStatement">return</span> EAT_XCHAT; +}); +</pre></div> +</div><p> +</p> +<h3><a name="xchat_nickcmp" /><code>Xchat::nickcmp( $nick1, $nick2 )</code></h3> +<ul> +<li><strong><code>$nick1, $nick2</code> - the two nicks or channel names that are to be compared</strong> +</li> +</ul> +<p>The comparsion is based on the current server. Either a <a href="http://www.ietf.org/rfc/rfc1459.txt" class="rfc">RFC1459</a> compliant +string compare or plain ascii will be using depending on the server. The +comparison is case insensitive.</p> +<p>Returns a number less than, equal to or greater than zero if +<code>$nick1</code> is +found respectively, to be less than, to match, or be greater than +<code>$nick2</code>.</p> +<p> +</p> +<h3><a name="xchat_get_list" /><code>Xchat::get_list( $name )</code></h3> +<ul> +<li><strong><code>$name</code> - name of the list, one of the following: +"channels", "dcc", "ignore", "notify", "users"</strong> +</li> +</ul> +<p>This function will return a list of hash references. The hash references +will have different keys depend on the list. An empty list is returned +if there is no such list.</p> +<p>"channels" - list of channels, querys and their server</p><table border="1"> <tr style="background-color: #dddddd"> + <td>Key</td> <td>Description</td> + </tr> <tr> + <td>channel</td> <td>tab name</td> + </tr> <tr> + <td>chantypes</td> + <td>channel types supported by the server, typically "#&"</td> + </tr> <tr> + <td>context</td> <td>can be used with set_context</td> + </tr> <tr> + <td>flags</td> <td>Server Bits:<br /> + 0 - Connected<br /> + 1 - Connecting<br /> + 2 - Away<br /> + 3 - EndOfMotd(Login complete)<br /> + 4 - Has WHOX<br /> + 5 - Has IDMSG (FreeNode)<br /> + <br /> + <p>The following correspond to the /chanopt command</p> + 6 - Hide Join/Part Message (text_hidejoinpart)<br /> + 7 - unused (was for color paste)<br /> + 8 - Beep on message (alert_beep)<br /> + 9 - Blink Tray (alert_tray)<br /> + 10 - Blink Task Bar (alert_taskbar)<br /> +<p>Example of checking if the current context has Hide Join/Part messages set:</p> +<div class="example synNormal"><div class='line_number'> +<div>1</div> +<div>2</div> +<div>3</div> +</div> +<div class='content'><pre><span class="synStatement">if</span>( Xchat::context_info->{flags} & (<span class="synConstant">1</span> << <span class="synConstant">6</span>) ) { + Xchat::<span class="synStatement">print</span>( <span class="synStatement">"</span><span class="synConstant">Hide Join/Part messages is enabled</span><span class="synStatement">"</span> ); +} +</pre></div> +</div> </td> + </tr> <tr> + <td>id</td> <td>Unique server ID </td> + </tr> + + <tr> + <td>lag</td> + <td>lag in milliseconds</td> + </tr> <tr> + <td>maxmodes</td> <td>Maximum modes per line</td> + </tr> <tr> + <td>network</td> <td>network name to which this channel belongs</td> + </tr> <tr> + <td>nickprefixes</td> <td>Nickname prefixes e.g. "+@"</td> + </tr> + + <tr> + <td>nickmodes</td> <td>Nickname mode chars e.g. "vo"</td> + </tr> <tr> + <td>queue</td> + <td>number of bytes in the send queue</td> + </tr> + + <tr> + <td>server</td> <td>server name to which this channel belongs</td> + </tr> <tr> + <td>type</td> <td>the type of this context<br /> + 1 - server<br /> + 2 - channel<br /> + 3 - dialog<br /> + </td> + </tr> <tr> + <td>users</td> <td>Number of users in this channel</td> + </tr> +</table><p>"dcc" - list of DCC file transfers</p> +<table border="1"> <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> <tr> + <td>address32</td> <td>address of the remote user(ipv4 address)</td> + </tr> <tr> + <td>cps</td> <td>bytes per second(speed)</td> + </tr> <tr> + <td>destfile</td> <td>destination full pathname</td> + </tr> <tr> + <td>file</td> <td>file name</td> + </tr> <tr> + <td>nick</td> + <td>nick of the person this DCC connection is connected to</td> + </tr> <tr> + <td>port</td> <td>TCP port number</td> + </tr> <tr> + <td>pos</td> <td>bytes sent/received</td> + </tr> <tr> + <td>poshigh</td> <td>bytes sent/received, high order 32 bits</td> + </tr> <tr> + <td>resume</td> <td>point at which this file was resumed<br /> + (zero if it was not resumed) + </td> + </tr> <tr> + <td>resumehigh</td> <td>point at which this file was resumed, high order 32 bits<br /> + </td> + </tr> <tr> + <td>size</td> <td>file size in bytes low order 32 bits</td> + </tr> <tr> + <td>sizehigh</td> <td>file size in bytes, high order 32 bits (when the files is > 4GB)</td> + </tr> + <tr> + <td>status</td> <td>DCC Status:<br /> + 0 - queued<br /> + 1 - active<br /> + 2 - failed<br /> + 3 - done<br /> + 4 - connecting<br /> + 5 - aborted + </td> + </tr> <tr> + <td>type</td> <td>DCC Type:<br /> + 0 - send<br /> + 1 - receive<br /> + 2 - chatrecv<br /> + 3 - chatsend + </td> + </tr></table><p>"ignore" - current ignore list</p> +<table border="1"> <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> <tr> + <td>mask</td> <td>ignore mask. e.g: *!*@*.aol.com</td> + </tr> <tr> + <td>flags</td> <td>Bit field of flags.<br /> + 0 - private<br /> + 1 - notice<br /> + 2 - channel<br /> + 3 - ctcp<br /> + 4 - invite<br /> + 5 - unignore<br /> + 6 - nosave<br /> + 7 - dcc<br /> + </td> + </tr></table><p>"notify" - list of people on notify</p> +<table border="1"> + <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> <tr> + <td>networks</td> + <td>comma separated list of networks where you will be notfified about this user's online/offline status or undef if you will be notificed on every network you are connected to</td> + </tr> <tr> + <td>nick</td> <td>nickname</td> + </tr> <tr> + <td>flags</td> <td>0 = is online</td> + </tr> <tr> + <td>on</td> <td>time when user came online</td> + </tr> <tr> + <td>off</td> <td>time when user went offline</td> + </tr> <tr> + <td>seen</td> <td>time when user was last verified still online</td> + </tr> +</table><p>the values indexed by on, off and seen can be passed to localtime +and gmtime, see perldoc -f <a href="http://perldoc.perl.org/functions/localtime.html">localtime</a> and perldoc -f <a href="http://perldoc.perl.org/functions/gmtime.html">gmtime</a> for more +detail</p><p>"users" - list of users in the current channel</p> +<table border="1"> <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> <tr> + <td>away</td> <td>away status(boolean)</td> + </tr> <tr> + <td>lasttalk</td> + <td>last time a user was seen talking, this is the an epoch time(number of seconds since a certain date, that date depends on the OS)</td> + </tr> <tr> + <td>nick</td> <td>nick name</td> + </tr> <tr> + <td>host</td> + <td>host name in the form: user@host or undef if not known</td> + </tr> <tr> + <td>prefix</td> <td>prefix character, .e.g: @ or +</td> + </tr> <tr> + <td>realname</td> + <td>Real name or undef</td> + </tr> <tr> + <td>selected</td> + <td>selected status in the user list, only works when retrieving the user list of the focused tab. You can use the /USELECT command to select the nicks</td> + </tr> +</table><p>"networks" - list of networks and the associated settings from network list</p> +<table border="1"> <tr style="background-color: #dddddd"> + <td>Key</td> <td>Value</td> + </tr> + + <tr> + <td>autojoins</td> <td>An object with the following methods:<br /> + <table> + <tr> + <td>Method</td> + <td>Description</td> + </tr> <tr> + <td>channels()</td> + <td>returns a list of this networks' autojoin channels in list context, a count of the number autojoin channels in scalar context</td> + </tr> <tr> + <td>keys()</td> + <td>returns a list of the keys to go with the channels, the order is the same as the channels, if a channel doesn't have a key, '' will be returned in it's place</td> + </tr> <tr> + <td>pairs()</td> + <td>a combination of channels() and keys(), returns a list of (channels, keys) pairs. This can be assigned to a hash for a mapping from channel to key.</td> + </tr> <tr> + <td>as_hash()</td> + <td>return the pairs as a hash reference</td> + </tr> <tr> + <td>as_string()</td> + <td>the original string that was used to construct this autojoin object, this can be used with the JOIN command to join all the channels in the autojoin list</td> + </tr> <tr> + <td>as_array()</td> + <td>return an array reference of hash references consisting of the keys "channel" and "key"</td> + </tr> <tr> + <td>as_bool()</td> + <td>returns true if the network has autojoins and false otherwise</td> + </tr> + </table> + </td> + </tr> + + <tr> + <td>connect_commands</td> <td>An array reference containing the connect commands for a network. An empty array if there aren't any</td> + </tr> <tr> + <td>encoding</td> <td>the encoding for the network</td> + </tr> <tr> + <td>flags</td> + <td> + a hash reference corresponding to the checkboxes in the network edit window + <table> + <tr> + <td>allow_invalid</td> + <td>true if "Accept invalid SSL certificate" is checked</td> + </tr> <tr> + <td>autoconnect</td> + <td>true if "Auto connect to this network at startup" is checked</td> + </tr> <tr> + <td>cycle</td> + <td>true if "Connect to selected server only" is <strong>NOT</strong> checked</td> + </tr> <tr> + <td>use_global</td> + <td>true if "Use global user information" is checked</td> + </tr> <tr> + <td>use_proxy</td> + <td>true if "Bypass proxy server" is <strong>NOT</strong> checked</td> + </tr> <tr> + <td>use_ssl</td> + <td>true if "Use SSL for all the servers on this network" is checked</td> + </tr> + </table> + </td> + </tr> <tr> + <td>irc_nick1</td> + <td>Corresponds with the "Nick name" field in the network edit window</td> + </tr> <tr> + <td>irc_nick2</td> + <td>Corresponds with the "Second choice" field in the network edit window</td> + </tr> <tr> + <td>irc_real_name</td> + <td>Corresponds with the "Real name" field in the network edit window</td> + </tr> <tr> + <td>irc_user_name</td> + <td>Corresponds with the "User name" field in the network edit window</td> + </tr> <tr> + <td>network</td> + <td>Name of the network</td> + </tr> <tr> + <td>nickserv_password</td> + <td>Corresponds with the "Nickserv password" field in the network edit window</td> + </tr> <tr> + <td>selected</td> + <td>Index into the list of servers in the "servers" key, this is used if the "cycle" flag is false</td> + </tr> <tr> + <td>server_password</td> + <td>Corresponds with the "Server password" field in the network edit window</td> + </tr> <tr> + <td>servers</td> + <td>An array reference of hash references with a "host" and "port" key. If a port is not specified then 6667 will be used.</td> + </tr> +</table><p> +</p> +<h3><a name="xchat_user_info" /><code>Xchat::user_info( [$nick] )</code></h3> +<ul> +<li><strong><code>$nick</code> - the nick to look for, if this is not given your own nick will be + used as default</strong> +</li> +</ul> +<p>This function is mainly intended to be used as a shortcut for when you need +to retrieve some information about only one user in a channel. Otherwise it +is better to use <a href="#xchat_get_list">get_list</a>. +If <code>$nick</code> is found a hash reference containing the same keys as those in the +"users" list of <a href="#xchat_get_list">get_list</a> is returned otherwise undef is returned. +Since it relies on <a href="#xchat_get_list">get_list</a> this function can only be used in a +channel context.</p> +<p> +</p> +<h3><a name="xchat_context_info" /><code>Xchat::context_info( [$context] )</code></h3> +<ul> +<li><strong><code>$context</code> - context returned from <a href="#xchat_get_context">get_context</a>, <a href="#xchat_find_context">find_context</a> and <a href="#xchat_get_list">get_list</a>, this is the context that you want infomation about. If this is omitted, it will default to current context.</strong> +</li> +</ul> +<p>This function will return the information normally retrieved with <a href="#xchat_get_info">get_info</a>, except this is for the context that is passed in. The information will be returned in the form of a hash. The keys of the hash are the <code>$id</code> you would normally supply to <a href="#xchat_get_info">get_info</a> as well as all the keys that are valid for the items in the "channels" list from <a href="#xchat_get_list">get_list</a>. Use of this function is more efficient than calling get_list( "channels" ) and searching through the result.</p> +<p>Example:</p> +<div class="example synNormal"><div class='line_number'> +<div>1</div> +<div>2</div> +<div>3</div> +<div>4</div> +<div>5</div> +<div>6</div> +<div>7</div> +<div>8</div> +<div>9</div> +<div>10</div> +<div>11</div> +</div> +<div class='content'><pre><span class="synStatement">use strict</span>; +<span class="synStatement">use warnings</span>; +<span class="synStatement">use </span>Xchat <span class="synStatement">qw(</span><span class="synConstant">:all</span><span class="synStatement">)</span>; <span class="synComment"># imports all the functions documented on this page</span> + +register( <span class="synStatement">"</span><span class="synConstant">User Count</span><span class="synStatement">"</span>, <span class="synStatement">"</span><span class="synConstant">0.1</span><span class="synStatement">"</span>, + <span class="synStatement">"</span><span class="synConstant">Print out the number of users on the current channel</span><span class="synStatement">"</span> ); +hook_command( <span class="synStatement">"</span><span class="synConstant">UCOUNT</span><span class="synStatement">"</span>, \<span class="synIdentifier">&display_count</span> ); +<span class="synStatement">sub </span><span class="synIdentifier">display_count </span>{ + prnt <span class="synStatement">"</span><span class="synConstant">There are </span><span class="synStatement">"</span> . context_info()->{users} . <span class="synStatement">"</span><span class="synConstant"> users in this channel.</span><span class="synStatement">"</span>; + <span class="synStatement">return</span> EAT_XCHAT; +} +</pre></div> +</div><p> +</p> +<h3><a name="xchat_strip_code" /><code>Xchat::strip_code( $string )</code></h3> +<ul> +<li><strong><code>$string</code> - string to remove codes from</strong> +</li> +</ul> +<p>This function will remove bold, color, beep, reset, reverse and underline codes from <code>$string</code>. It will also remove ANSI escape codes which might get used by certain terminal based clients. If it is called in void context <code>$string</code> will be modified otherwise a modified copy of <code>$string</code> is returned.</p> +<p> +</p> +<h2><a name="examples" />Examples</h2> +<p> +</p> +<h3><a name="asynchronous_dns_resolution_with_hook_fd" />Asynchronous DNS resolution with hook_fd</h3> +<div class="example synNormal"><div class='line_number'> +<div>1</div> +<div>2</div> +<div>3</div> +<div>4</div> +<div>5</div> +<div>6</div> +<div>7</div> +<div>8</div> +<div>9</div> +<div>10</div> +<div>11</div> +<div>12</div> +<div>13</div> +<div>14</div> +<div>15</div> +<div>16</div> +<div>17</div> +<div>18</div> +<div>19</div> +<div>20</div> +<div>21</div> +<div>22</div> +<div>23</div> +<div>24</div> +<div>25</div> +<div>26</div> +<div>27</div> +<div>28</div> +<div>29</div> +<div>30</div> +<div>31</div> +<div>32</div> +<div>33</div> +<div>34</div> +<div>35</div> +</div> +<div class='content'><pre><span class="synStatement">use strict</span>; +<span class="synStatement">use warnings</span>; +<span class="synStatement">use </span>Xchat <span class="synStatement">qw(</span><span class="synConstant">:all</span><span class="synStatement">)</span>; +<span class="synStatement">use </span>Net::DNS; + +hook_command( <span class="synStatement">"</span><span class="synConstant">BGDNS</span><span class="synStatement">"</span>, <span class="synStatement">sub </span>{ + <span class="synStatement">my</span> <span class="synIdentifier">$host</span> = <span class="synIdentifier">$_[</span><span class="synConstant">0</span><span class="synIdentifier">][</span><span class="synConstant">1</span><span class="synIdentifier">]</span>; + <span class="synStatement">my</span> <span class="synIdentifier">$resolver</span> = Net::DNS::Resolver->new; + <span class="synStatement">my</span> <span class="synIdentifier">$sock</span> = <span class="synIdentifier">$resolver->bgsend</span>( <span class="synIdentifier">$host</span> ); + + hook_fd( <span class="synIdentifier">$sock</span>, <span class="synStatement">sub </span>{ + <span class="synStatement">my</span> <span class="synIdentifier">$ready_sock</span> = <span class="synIdentifier">$_[</span><span class="synConstant">0</span><span class="synIdentifier">]</span>; + <span class="synStatement">my</span> <span class="synIdentifier">$packet</span> = <span class="synIdentifier">$resolver->bgread</span>( <span class="synIdentifier">$ready_sock</span> ); + + <span class="synStatement">if</span>( <span class="synIdentifier">$packet->authority</span> && (<span class="synStatement">my</span> <span class="synIdentifier">@answers</span> = <span class="synIdentifier">$packet->answer</span> ) ) { + + <span class="synStatement">if</span>( <span class="synIdentifier">@answers</span> ) { + prnt <span class="synStatement">"</span><span class="synIdentifier">$host</span><span class="synConstant">:</span><span class="synStatement">"</span>; + <span class="synStatement">my</span> <span class="synIdentifier">$padding</span> = <span class="synStatement">"</span><span class="synConstant"> </span><span class="synStatement">"</span> x (<span class="synStatement">length</span>( <span class="synIdentifier">$host</span> ) + <span class="synConstant">2</span>); + <span class="synStatement">for</span> <span class="synStatement">my</span> <span class="synIdentifier">$answer</span> ( <span class="synIdentifier">@answers</span> ) { + prnt <span class="synIdentifier">$padding</span> . <span class="synIdentifier">$answer->rdatastr</span> . <span class="synStatement">'</span><span class="synConstant"> </span><span class="synStatement">'</span> . <span class="synIdentifier">$answer->type</span>; + } + } + } <span class="synStatement">else</span> { + prnt <span class="synStatement">"</span><span class="synConstant">Unable to resolve </span><span class="synIdentifier">$host</span><span class="synStatement">"</span>; + } + + <span class="synStatement">return</span> REMOVE; + }, + { + <span class="synConstant">flags</span> => FD_READ, + }); + + <span class="synStatement">return</span> EAT_XCHAT; +}); +</pre></div> +</div> + +<p> +</p> +<h2><a name="contact_information" />Contact Information</h2> +<p>Contact Lian Wan Situ at <atmcmnky [at] yahoo.com> for questions, comments and +corrections about this page or the Perl plugin itself. You can also find me +in #xchat on FreeNode under the nick Khisanth.</p> +<table border="0" width="100%" cellspacing="0" cellpadding="3"> +<tr><td class="block" style="background-color: #cccccc" valign="middle"> +<big><strong><span class="block"> X-Chat 2 Perl Interface</span></strong></big> +</td></tr> +</table> + +</body> + +</html> diff --git a/plugins/perl/xchat2-perldocs.html b/plugins/perl/xchat2-perldocs.html new file mode 100644 index 00000000..10d8f314 --- /dev/null +++ b/plugins/perl/xchat2-perldocs.html @@ -0,0 +1,475 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>XChat - IRC (chat) client for UNIX</title> +<style type="text/css"> +body{font-family:sans-serif;background-color:#FFFBF0;} +:link{color:#00C;} +:visited{color:#609;} +:active{color:#C00;} +.date{background-color:#dddddd;font-family:terminal;font-size:small;} +th,td{font-family:sans-serif;} +h2{font-family:sans-serif;color:#990066;} +</style></head> + +<body> +<h1><center>This interface is deprecated</center></h1> +<table width="90%" cellpadding="0" cellspacing="0" border="0"> +<tbody><tr> + +<td align="left" valign="top"> +<blockquote> +<h2>Xchat Perl Docs</h2> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066"> +Introduction +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +<p>Good Hello!</p> +<p>The purpose of this page is to give people some quick documentation on the +things that they will encounter when they try to code scripts for X-Chat. +It is <strong>not</strong> meant to be a comprehensive programming tutorial, +by any means. If that's what you're looking for, then you can just keep on +looking.</p> +<p>If you're going to do any scripting with X-Chat at all, you will +need to know perl. It also won't hurt to have had experience writing tcl for +eggdrops or ircII scripts. Otherwise you're going to have to be very careful +to avoid creating conditions which could flood you offline or do other +not-so-optimal things. ;) Thankfully, it shouldn't take most intelligent +people more than a week (month on the outside) enough perl to do some nice +things in it. +<a HREF="http://www.perl.com">Perl</a> is a very flexible language.</p> +<p>You should probably also go read (or at least skim over and then carefully +bookmark this copy of the thing that defines how IRC works: <a HREF="http://www.irchelp.org/irchelp/rfc1459.html">RFC 1459</a>. +Other documents that scripters might find useful would be this +<a HREF="http://www.irchelp.org/irchelp/ircd/numerics.html">nice list of server +numerics</a>, and this list of <a HREF="http://www.irchelp.org/irchelp/ircd/hybrid6.html">changes +for Hybrid 6</a> which is something everyone on EFNet should read. In fact, I +<strong>strongly</strong> suggest saving copies of these documents to your local +hard drive, because you <i>will</i> be back to look at them again soon.</p> +<p>One last thing... While you may hear that RFC 1459 isn't being followed very +well, and this is partly true, do your absolute best to stick with RFC-compliant +behaviours anyway because otherwise there's a good chance that your script will +never interoperate properly with others, or at least just piss off a lot of other +people. <i>Pay special attention to section 2.2 of the RFC.</i></p> +</blockquote> + +<table ALIGN=CENTER WIDTH="75%" CELLPADDING=5 CELLSPACING=0> +<tr><td ALIGN=CENTER BGCOLOR="#FF7070"> +<font COLOR="#FFFFFF" FACE="Verdana, Helvetica, Arial, Sans"><b>Standard Disclaimer</b> +</font> +</td></tr><tr> <td BGCOLOR="#FFCECE" ALIGN=CENTER><font COLOR="#800000" FACE="Helvetica, Lucida, Arial, Sans"> +This documentation is provided on an "as-is" basis and comes with no warranty of accuracy or usefulness, either expressed or implied. It is subject to change without any notice, and may contain omissions or errors which could cause your genitalia to shrivel and fall off, or spontaneously combust. If you have any further questions,<br>please feel free to seek professional help.</font> +</td></tr></table> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066;"> +About Handlers +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +There are [currently] four basic ways to make things call the subroutines you write for X-Chat and they are: +<ul><li>message handlers - Triggered by messagse sent from the IRC server to your client</li> +<li>command handlers - triggered by / commands typed in by the user at the keyboard</li> +<li>timeout handlers - triggered by gtk+</li> +<li>print handlers - triggered just before xchat calls its built in print handlers for events</li></ul> +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066;"> +About Exit Codes +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +These are very important. Every time you set up a handler, it takes precedent over the built-in functions and commands of X-Chat. That is, whatever thing which triggered your subroutine will go to your code before it goes to X-Chat to be dealt with. In this way you can replace almost every built-in function that the client has with your own routines. The thing to remember is that if your code exits by hitting the end of your subroutine, or by a plain 'return' statement, processing of the event will go on to whatever other things have set up hooks for the event, and then (provided nothing else exits with a return value of 1) to X-Chat itself. There is only one problem with this, (which is solved by the brokering handler that I'll explain that later) and that is that you cannot really control what order the custom routines get called. Normally they will execute in order of which ones were installed first, but a single script has no real way of knowing this. Beware. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066;"> +About @_ +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +If you've never heard of @_ before, then you've obviously not coded in perl. When a message handler triggers, the raw line from the IRC server is passed to the subroutine you specify in @_. When a command handler is triggered, only the arguments are passed to the routine through @_ and they are not broken into a list, but left as one long string. You'll have to parse those yourself with split. (I advise using s/\s+/ /g to collapse the blank space to single space first.) When a timer handler is triggered, I *think* absolutely nothing is passed in @_, but it's not like anything terrifically important could be passed along anyway. Be especially careful when setting up message handlers for mode changes, since the modes are not broken up into individual events like they are with eggdrop. The upside of this is that X-Chat has no mode hooks of it's own, so you don't have to worry about it too much. (This is not the case with the brokering handler, however.) +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066;"> +About Context +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +There are some really nice things about coding for X-Chat, and the biggest one is that it's fairly good about determining the proper context for things. If a server sends something that triggers a message handler, then you can be sure that unless you specify otherwise, that your IRC::print or IRC::command function call will go back to that server and that server alone. If you really really need to know what the current context is, use the IRC::get_info function as detailed below. +</blockquote> + +<hr width="95%"> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066;"> +script initialization commands +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::register(scriptname, version, shutdownroutine, unused); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +<p>This is the first function your script should call, example:</p> +<blockquote><p>IRC::register ("my script", "1.0", "", "");</p></blockquote> +<p>The "shutdownroutine" arg is a function that will be called when X-Chat shuts down, so you get a chance to save config files etc. You can omit this arg, it is optional. The "unused" arg is reserved for future use, for now just provide "". This function also returns X-Chat's version number. </p> +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066;"> +Handler initialization commands +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::add_message_handler(message, subroutine_name); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +<p>This function allows you to set up hooks to subroutines so that when a particular message arrives from the IRC server that you are connected to, it can be passed to a subroutine to be dealt with appropriately. The message argument is essentially the second solid token from the raw line sent by the IRC server, and X-Chat doesn't know that some numeric messages have associated text messages, so for now set up a handler for both if you want to be sure odd servers don't screw up your expectations. (Read: fear IRCNet.) The entire line sent by the IRC server will be passed to your subroutine in @_. For the completely uninitiated, messages are things like 'PRIVMSG', 'NOTICE', '372', etc.</p> +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::add_command_handler(command, subroutine_name); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +<p>This function allows you to set up hooks for actual commands that the user can type into the text window. The arguments are passed to the subroutine via @_, and arrive as a single string. @_ will be null if no arguments are supplied. It's recommended that you be sure and collapse the excess whitespace with s/\s+/ /g before attempting to chop the line up with split. As mentioned earlier, exiting with an undefined return value will allow the command to be parsed by other handlers, while using a return value of 1 will signal the program that no further parsing needs to be done with this command.</p> +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::add_timeout_handler(interval, subroutine_name); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +<p>This function allows you to set up hooks for subroutines to be called at a particular interval. The interval is measured in milliseconds, so don't use a particularly small value unless you wish to drive the CPU load through the roof. 1000ms = 1 second. No values will be passed to the routine via @_ and return values don't affect anything either.</p> +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::add_print_handler(message, subroutine_name); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +<p>This function allows you to catch the system messages (those who generally start by three stars) and to execute a function each time an event appear. The events are those you can see in "Settings->Edit Events Texts". message is the name of the event (you can find it in the Edit Events box, "Events" column) , subroutine_name is the name of the function that will get messages. Be carrful: all the arguments are sent to function in $_[0] separated by spaces. </p> +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066;"> +Output commands +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::print(text); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This is a very simple routine. All it does is put the contents of the text string to the current window. The current window will be whichever window a command was typed into when called from a command handler, or in whichever window the message command is appropriate to if it is called from within a message handler. As with any perl program, newlines are not assumed, so don't forget to end the line with \n if you don't want things to look screwey. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::print_with_channel( text, channelname, servername ); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This routine does the same thing as IRC::Print does, except it allows you to direct the output to a specific window. It returns 1 on success, 0 on fail. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::command(text); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This routine allows you to execute commands in the current context. The text string containing the command will be parsed by everything that would normally parse a command, including your own command handlers, so be careful. Newlines are assumed, thankfully. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::command_with_server(text, servername); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This routine allows you to specify the context of the server for which the command will be executed. It's not particularly useful unless you're managing a connection manually, yet the command still exists for it's usefulness in doing things like managing a bnc connection, etc. Newlines are assumed here as well. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::send_raw(text); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This routine is very useful in that it allows you to send a string directly to the IRC server you are connected to. It is assumed that the server will be the one you first connected to if there is no clear context for the command, otherwise it will go to whatever server triggered the message handler or command handler window. You must specify newlines here always or you can be guaranteed that strange things will happen. The text message you specify should be a proper RAW IRC message, so don't play with it if you don't know how to do these. Additionally, while newlines are also not assumed here as with the IRC::print function, the RFC specifies that newlines are a CR+LF pair, even if most servers will accept a mere newline. It's best to play it safe and use \r\n instead of just \n. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066;"> +Information retrieval commands +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::get_info(integer); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This function returns a bit of selected information depending on what the value of the integer is. +Here's a list of the currently supported values: +<ul><li>0 - xchat version</li> +<li>1 - your nickname</li> +<li>2 - channel</li> +<li>3 - server</li> +<li>4 - xchatdir</li> +<li>5 - away status</li> +<li>6 - network name</li> +<li>7 - server hostname</li> +<li>8 - channel topic</li></ul> +<p>If you are requesting information that isn't available in the current context, then it will return null.</p> +<p>Any numbers other than the above will return an error message.</p> +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::get_prefs(var); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This command lets you read the preferences that are set in the xchat configuration file. Just look at the xchat.conf dir to see what variables are available to use with this command. Returns the value of the variable requested or "Unknown Variable" if the variable isn't available. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::user_info( nickname ); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +Returns a flat list of information on the nickname specified consisting of... nickname, nick host, and whether they have op or voice in the current context. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::channel_list( ); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This command returns a flat list which contains the current channel, server, and nickname for all channels the client is currently in. You'll have to break the list up into groups of three yourself. No arguments are necessary, or used [currently]. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::server_list( ); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This command returns a flat list of servers. (Note, it is incompatible with xchat 1.8 in that it also returns a list of servers you are NOT connected to as well.) +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::user_list(channel, server); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +<p>Works very much like the dcc_list command below, except that is returns information about the users on the channel provided as first argument. The second argument is the server and is optional.</p> +<p>NOTE: If a user has both op and voice, only the op flag will be set to 1 by this command in xchat2.</p> +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::user_list_short(channel, server); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +<p>A simpler version of IRC::user_list that returns pairs of nick & user@host suitable for assigning to a hash.</p> +<p>NOTE: If a user has both op and voice, only the op flag will be set to 1 by this command in xchat2.</p> +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::dcc_list( ); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This command does essentially the same thing as channel_list, giving you the details of each DCC connection currently in progress. I have no idea exactly what is returned because I haven't had a chance to poke at this one much, but suffice it to say that it's a flat list, and the first time you play with it the meaning of the returned values should be pretty obvious. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial"> +IRC::ignore_list( ); +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +This command returns a flat list of the contents of your ignore list. You'll have to play with it a little as I have not had a chance to yet. Works basically the same as the other list commands. +</blockquote> + +<table width="95%" cellpadding="0" cellspacing="3" border="0" align="center"> +<tbody><tr><td bgcolor="#000000"> +<table width="100%" cellpadding="2" cellspacing="1" border="0"><tbody><tr> +<td width="20%" align="left" bgcolor="#dddddd"> +<font face="Lucida, Helvetica, Arial" color="#990066;"> +Unimplemented commands that were available in xchat 1.8.x +</font></td> +</tr></tbody></table> +</td></tr></tbody></table> + +<blockquote> +add_user_list , sub_user_list , clear_user_list, notify_list were available in xchat 1.8.x but are not implemented in xchat 2 at this time. +</blockquote> + +</blockquote> +</td> +</tr> +</tbody></table> +<br><hr> +<font size="-10">This document originally written by Dagmar d'Surreal on March 26th, 1998 for xchat 1.4<br> +Updated on July 30th, 1999 by Peter Zelezny<br> +Updated on May 16th, 2003 by DaNumber8 to comply with the perl plugin for xchat2 version 2.0.3</font> +</body></html> diff --git a/plugins/perl/xcperl_build.bat b/plugins/perl/xcperl_build.bat new file mode 100644 index 00000000..6f569c47 --- /dev/null +++ b/plugins/perl/xcperl_build.bat @@ -0,0 +1,43 @@ +perl generate_header + +gcc -W -Os -DWIN32 -I "C:\MinGW\include" -I .. -I "C:\ActivePerl-5.8.9\perl\lib\CORE" -L "C:\ActivePerl-5.8.9\perl\bin" -c perl.c -o perl5.8.9.o + +dllwrap --def perl.def --dllname xcperl5.8.9.dll "C:\ActivePerl-5.8.9\perl\bin\perl58.dll" perl5.8.9.o + +strip xcperl5.8.9.dll + + + +gcc -W -Os -DWIN32 -I "C:\MinGW\include" -I .. -I "C:\Perl\lib\CORE" -L "C:\Perl\bin" -c perl.c -o perl5.10.0.o + +dllwrap --def perl.def --dllname xcperl5.10.0.dll "C:\Perl\bin\perl510.dll" perl5.10.0.o + +strip xcperl5.10.0.dll + + +gcc -W -Os -DWIN32 -I "C:\MinGW\include" -I .. -I "C:\ActivePerl-5.10.1\perl\lib\CORE" -L "C:\ActivePerl-5.10.1\perl\bin" -c perl.c -o perl5.10.1.o + +dllwrap --def perl.def --dllname xcperl5.10.1.dll "C:\ActivePerl-5.10.1\perl\bin\perl510.dll" perl5.10.1.o + +strip xcperl5.10.1.dll + + +gcc -W -Os -DWIN32 -I "C:\MinGW\include" -I .. -I "C:\ActivePerl-5.12.1\perl\lib\CORE" -L "C:\ActivePerl-5.12.1\perl\bin" -c perl.c -o perl5.12.1.o + +dllwrap --def perl.def --dllname xcperl5.12.1.dll "C:\ActivePerl-5.12.1\perl\bin\perl512.dll" perl5.12.1.o + +strip xcperl5.12.1.dll + +gcc -W -Os -DWIN32 -I "C:\MinGW\include" -I .. -I "C:\strawberry-perl-5.10.1.3\perl\lib\CORE" -L "C:\strawberry-perl-5.10.1.3\perl\bin" -c perl.c -o perl-strawberry5.10.1.o + +dllwrap --def perl.def --dllname xcperl-strawberry5.10.1.dll "C:\strawberry-perl-5.10.1.3\perl\bin\perl510.dll" perl5.10.1.o + +strip xcperl-strawberry5.10.1.dll + + +gcc -W -Os -DWIN32 -I "C:\MinGW\include" -I .. -I "C:\strawberry-perl-5.12.1.0-portable\perl\lib\CORE" -L "C:\strawberry-perl-5.12.1.0-portable\perl\bin" -c perl.c -o perl-strawberry5.12.1.o + +dllwrap --def perl.def --dllname xcperl-strawberry5.12.1.dll "C:\strawberry-perl-5.12.1.0-portable\perl\bin\perl512.dll" perl5.12.1.o + +strip xcperl-strawberry5.12.1.dll + diff --git a/plugins/plugin-conf.in b/plugins/plugin-conf.in new file mode 100644 index 00000000..d05792b1 --- /dev/null +++ b/plugins/plugin-conf.in @@ -0,0 +1,20 @@ + +AC_INIT(@PLUGIN@-config.h.in) +AM_CONFIG_HEADER(@PLUGIN@-config.h) +AM_INIT_AUTOMAKE(xchat-@PLUGIN@, @PLUGIN_VERSION@) +AM_MAINTAINER_MODE +AM_DISABLE_STATIC +AM_PROG_LIBTOOL + +AC_ARG_WITH(plugin-includes, +[ --with-plugin-includes directory containing xchat-plugin.h], + PLUGIN_INCLUDES=$enableval) + +AC_SUBST(PLUGIN_INCLUDES) + +xchatlibdir=${libdir}/xchat +AC_SUBST(xchatlibdir) + +AC_OUTPUT( +Makefile +) diff --git a/plugins/plugin20.html b/plugins/plugin20.html new file mode 100644 index 00000000..787c048b --- /dev/null +++ b/plugins/plugin20.html @@ -0,0 +1,1002 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<html> +<head> +<title>XChat 2.0 Plugin Interface</title> +<style type="text/css"> +<!-- +body { +font-family: sans-serif; +background-color: #FFFBF0; +} +.cmd { +background-color: #dddddd; +color: #990066 +} +.bbox { +font-family: monospace; +color: #fdfdfd; +background-color: #000; +border: 1px solid #00f; +padding: 4px; +text-align: left; +margin-left: 32px; +margin-right: 32px; +} +.box { +background-color: #ddddee; +border: 1px solid #000; +padding: 4px; +text-align: left; +margin-left: 32px; +margin-right: 32px; +} +--> +</style> +</head> +<body bgcolor="#FFFBF0" text="#000" link="#607060" vlink="#607060" alink="#607060"> + +<h1>XChat 2.0 Plugin Interface</h1> + +<small> +<font size="-12">plugin20.html revision 2.86</font> +<br>Latest version of this document is available at: <a href="http://xchat.org/docs/plugin20.html">http://xchat.org/docs/plugin20.html</a></small> + +<h2>1. Documentation:</h2> +<blockquote> +<a href="#intro">1.0 Introduction</a> +<br><a href="#sample">1.1 Sample plugin</a> +<br><a href="#word">1.2 What is word and word_eol?</a> +<br><a href="#lists">1.3 Lists and fields</a> +<br><a href="#win32">1.4 Plugins on Windows (Win32)</a> +<br><a href="#gui">1.5 Controlling the GUI</a> +<br> <a href="#gui">1.5.1 Basic Control</a> +<br> <a href="#menu">1.5.2 Custom Menu Items</a> +<br> <a href="#tray">1.5.3 System Tray</a> +<br><a href="#unicode">1.6 Handling UTF-8/Unicode strings</a> +</blockquote> + +<h2>2. Function reference:</h2> +<blockquote> +<a href="#xchat_hook_command">xchat_hook_command</a> +<br><a href="#xchat_hook_fd">xchat_hook_fd</a> +<br><a href="#xchat_hook_print">xchat_hook_print</a> +<br><a href="#xchat_hook_server">xchat_hook_server</a> +<br><a href="#xchat_hook_timer">xchat_hook_timer</a> +<br><a href="#xchat_unhook">xchat_unhook</a> +<br> +<br><a href="#xchat_command">xchat_command</a> +<br><a href="#xchat_commandf">xchat_commandf</a> +<br><a href="#xchat_print">xchat_print</a> +<br><a href="#xchat_printf">xchat_printf</a> +<br><a href="#xchat_emit_print">xchat_emit_print</a> +<br><a href="#xchat_send_modes">xchat_send_modes</a> +<br> +<br><a href="#xchat_find_context">xchat_find_context</a> +<br><a href="#xchat_get_context">xchat_get_context</a> +<br><a href="#xchat_get_info">xchat_get_info</a> +<br><a href="#xchat_get_prefs">xchat_get_prefs</a> +<br><a href="#xchat_set_context">xchat_set_context</a> +<br> +<br><a href="#xchat_nickcmp">xchat_nickcmp</a> +<br><a href="#xchat_strip">xchat_strip</a> +<br><a href="#xchat_free">xchat_free</a> +<br> +<br><a href="#lists">xchat_list_get</a> +<br><a href="#lists">xchat_list_free</a> +<br><a href="#lists">xchat_list_fields</a> (not documented yet) +<br><a href="#lists">xchat_list_next</a> +<br><a href="#lists">xchat_list_str</a> +<br><a href="#lists">xchat_list_int</a> +<br><a href="#lists">xchat_list_time</a> +<br> +<br><a href="#xchat_plugingui_add">xchat_plugingui_add</a> (not documented yet) +<br><a href="#xchat_plugingui_remove">xchat_plugingui_remove</a> (not documented yet) +</blockquote><br> + +<h3><a name=intro>Introduction</a></h3> +Plugins for XChat are written in C. The interface aims to keep 100% +binary compatability. This means that if you upgrade XChat, you will +not need to recompile your plugins, they'll continue to work. The +interface doesn't depend on any structures and offsets, so compiler +versions shouldn't have an impact either. The only real requirement of +an XChat plugin, is that it define a "xchat_plugin_init" symbol. This +is your entry point function, see the example below. You should make +all your global variables and functions <i>static</i>, so that a symbol +is not exported. There is no harm in exporting these symbols, but they +are not necessary and only pollute the name-space. Plugins are compiled as shared objects +(.so files), for example: +<br><br> +Most UNIX systems:<pre> + gcc -Wl,--export-dynamic -Wall -O1 -shared -fPIC myplugin.c -o myplugin.so +</pre> +MacOSX:<pre> + gcc -no-cpp-precomp -g -O2 -Wall -bundle -flat_namespace -undefined suppress -o myplugin.so myplugin.c +</pre> + +See the <a href="#win32">Windows section</a> on how to compile a plugin +using visual studio. +<p> +All strings passed to and from plugins are encoded in UTF-8, regardless +of locale. <a href="#unicode">What does this mean</a>? +</p><br> + +<h3><a name=sample>Sample plugin</a></h3> +This simple plugin autoOps anyone who joins a channel you're in. It also +adds a new command /AUTOOPTOGGLE, which can be used to turn the feature ON +or OFF. Every XChat plugin must define an xchat_plugin_init function, this +is the normal entry point. xchat_plugin_deinit is optional. +<br> +<div style="color: #ffffff; background-color: #111199;"> +<pre> + +<font color="#00ff00">#include </font><font color="#00ffff">"xchat-plugin.h"</font> + +<font color="#00ff00">#define PNAME </font><font color="#00ffff">"AutoOp"</font> +<font color="#00ff00">#define PDESC </font><font color="#00ffff">"Auto Ops anyone that joins"</font> +<font color="#00ff00">#define PVERSION </font><font color="#00ffff">"0.1"</font> + +<font color="#ffa500"><b>static</b></font> xchat_plugin *ph; <font color="#bebebe"><b>/*</b></font><font color="#bebebe"><b> plugin handle </b></font><font color="#bebebe"><b>*/</b></font> +<font color="#ffa500"><b>static</b></font> <font color="#ffa500"><b>int</b></font> enable = <font color="#00ffff">1</font>; + +<font color="#ffa500"><b>static</b></font> <font color="#ffa500"><b>int</b></font> join_cb(<font color="#ffa500"><b>char</b></font> *word[], <font color="#ffa500"><b>void</b></font> *userdata) +{ + <font color="#ffff00">if</font> (enable) + <font color="#bebebe"><b>/*</b></font><font color="#bebebe"><b> Op ANYONE who joins </b></font><font color="#bebebe"><b>*/</b></font> + xchat_commandf(ph, <font color="#00ffff">"OP </font><font color="#ff00ff">%s</font><font color="#00ffff">"</font>, word[<font color="#00ffff">1</font>]); + <font color="#bebebe"><b>/*</b></font><font color="#bebebe"><b> word[1] is the nickname, as in the Settings->Advanced->TextEvents window in xchat </b></font><font color="#bebebe"><b>*/</b></font> + + <font color="#ffff00">return</font> XCHAT_EAT_NONE; <font color="#bebebe"><b>/*</b></font><font color="#bebebe"><b> don't eat this event, xchat needs to see it! </b></font><font color="#bebebe"><b>*/</b></font> +} + +<font color="#ffa500"><b>static</b></font> <font color="#ffa500"><b>int</b></font> autooptoggle_cb(<font color="#ffa500"><b>char</b></font> *word[], <font color="#ffa500"><b>char</b></font> *word_eol[], <font color="#ffa500"><b>void</b></font> *userdata) +{ + <font color="#ffff00">if</font> (!enable) + { + enable = <font color="#00ffff">1</font>; + xchat_print(ph, <font color="#00ffff">"AutoOping now enabled!</font><font color="#ff00ff">\n</font><font color="#00ffff">"</font>); + } <font color="#ffff00">else</font> + { + enable = <font color="#00ffff">0</font>; + xchat_print(ph, <font color="#00ffff">"AutoOping now disabled!</font><font color="#ff00ff">\n</font><font color="#00ffff">"</font>); + } + + <font color="#ffff00">return</font> XCHAT_EAT_ALL; <font color="#bebebe"><b>/*</b></font><font color="#bebebe"><b> eat this command so xchat and other plugins can't process it </b></font><font color="#bebebe"><b>*/</b></font> +} + +<font color="#ffa500"><b>void</b></font> xchat_plugin_get_info(<font color="#ffa500"><b>char</b></font> **name, <font color="#ffa500"><b>char</b></font> **desc, <font color="#ffa500"><b>char</b></font> **version, <font color="#ffa500"><b>void</b></font> **reserved) +{ + *name = PNAME; + *desc = PDESC; + *version = PVERSION; +} + +<font color="#ffa500"><b>int</b></font> xchat_plugin_init(xchat_plugin *plugin_handle, + <font color="#ffa500"><b>char</b></font> **plugin_name, + <font color="#ffa500"><b>char</b></font> **plugin_desc, + <font color="#ffa500"><b>char</b></font> **plugin_version, + <font color="#ffa500"><b>char</b></font> *arg) +{ + <font color="#bebebe"><b>/*</b></font><font color="#bebebe"><b> we need to save this for use with any xchat_* functions </b></font><font color="#bebebe"><b>*/</b></font> + ph = plugin_handle; + + <font color="#bebebe"><b>/*</b></font><font color="#bebebe"><b> tell xchat our info </b></font><font color="#bebebe"><b>*/</b></font> + *plugin_name = PNAME; + *plugin_desc = PDESC; + *plugin_version = PVERSION; + + xchat_hook_command(ph, <font color="#00ffff">"AutoOpToggle"</font>, XCHAT_PRI_NORM, autooptoggle_cb, <font color="#00ffff">"Usage: AUTOOPTOGGLE, Turns OFF/ON Auto Oping"</font>, <font color="#00ffff">0</font>); + xchat_hook_print(ph, <font color="#00ffff">"Join"</font>, XCHAT_PRI_NORM, join_cb, <font color="#00ffff">0</font>); + + xchat_print(ph, <font color="#00ffff">"AutoOpPlugin loaded successfully!</font><font color="#ff00ff">\n</font><font color="#00ffff">"</font>); + + <font color="#ffff00">return</font> <font color="#00ffff">1</font>; <font color="#bebebe"><b>/*</b></font><font color="#bebebe"><b> return 1 for success </b></font><font color="#bebebe"><b>*/</b></font> +} + +</pre> +</div> + +<h3><a name=word>What's word and word_eol?</a></h3> + +They are arrays of strings. They contain the parameters the user entered +for the particular command. For example, if you executed: + +<pre> +/command NICK hi there + +word[1] is command +word[2] is NICK +word[3] is hi +word[4] is there + +word_eol[1] is command NICK hi there +word_eol[2] is NICK hi there +word_eol[3] is hi there +word_eol[4] is there +</pre> +These arrays are simply provided for your convenience. You are NOT allowed +to alter them. Both arrays are limited to 32 elements (index 31). word[0] and +word_eol[0] are reserved and should not be read. +<br><br><br> +<h3><a name=lists>Lists and Fields</a></h3> +Lists of information (DCCs, Channels, Userlist etc) can be retreived +with xchat_list_get. All fields are READ ONLY and must be copied if +needed for a long time after calling xchat_list_str. The types of lists and fields available are: +<blockquote> + +"channels" - list of channels, querys and their servers. +<blockquote><table border=1> +<tr bgcolor="#dddddd"><td>Name</td><td>Description</td><td>Type</td></tr> +<tr><td>channel</td><td>Channel or query name</td><td>string</td></tr> +<tr><td>chantypes</td><td>Channel types e.g. "#!&"<br><small>(Added in version 2.0.9. Older versions will return NULL)</small></td><td>string</td> +<tr><td>context</td><td>(xchat_context *) pointer. Can be used with xchat_set_context</td><td>string</td></tr> +<tr><td>flags</td><td>Server/Channel Bits:<br> +<table> +<tr><td>Bit #</td><td>Value</td><td>Description</td></tr> +<tr><td>0</td><td>1</td><td>Connected</td></tr> +<tr><td>1</td><td>2</td><td>Connecting in Progress</td></tr> +<tr><td>2</td><td>4</td><td>You are away</td></tr> +<tr><td>3</td><td>8</td><td>End of MOTD (Login complete)</td></tr> +<tr><td>4</td><td>16</td><td>Has WHOX (ircu)</td></tr> +<tr><td>5</td><td>32</td><td>Has IDMSG (FreeNode)</td></tr> +<tr><td>6</td><td>64</td><td>Hide Join/Part Messages</td></tr> +<tr><td>7</td><td>128</td><td>unused (was Color Paste in old versions)</td></tr> +<tr><td>8</td><td>256</td><td>Beep on Message</td></tr> +<tr><td>9</td><td>512</td><td>Blink Tray</td></tr> +<tr><td>10</td><td>1024</td><td>Blink Task Bar</td></tr> +</table> +<br><small>(Bits 0-5 added in 2.0.9. Bits 6-8 added in 2.6.6. Bit 9 added in 2.8.0. Bit 10 in 2.8.6)</small></td><td>int</td></tr> +<tr><td>id</td><td>Unique server ID<br><small>(Added in version 2.0.8. Older versions will return -1)</small></td><td>int</td></tr> +<tr><td>lag</td><td>Lag in milliseconds<br><small>(Added in version 2.6.8. Older versions will return -1)</small></td><td>int</td> +<tr><td>maxmodes</td><td>Maximum modes per line<br><small>(Added in version 2.0.9. Older versions will return -1)</small></td><td>int</td> +<tr><td>network</td><td>Network name to which this channel belongs<br><small>(Added in version 2.0.2. Older versions will return NULL)</small></td><td>string</td></tr> +<tr><td>nickprefixes</td><td>Nickname prefixes e.g. "@+"<br><small>(Added in version 2.0.9. Older versions will return NULL)</small></td><td>string</td> +<tr><td>nickmodes</td><td>Nickname mode chars e.g. "ov"<br><small>(Added in version 2.0.9. Older versions will return NULL)</small></td><td>string</td> +<tr><td>queue</td><td>Number of bytes in the send-queue<br><small>(Added in version 2.6.8. Older versions will return -1)</small></td><td>int</td> +<tr><td>server</td><td>Server name to which this channel belongs</td><td>string</td></tr> +<tr><td>type</td><td>Type of context this is: 1-Server 2-Channel 3-Dialog<br><small>(Added in version 2.0.2. Older versions will return -1)</small></td><td>int</td></tr> +<tr><td>users</td><td>Number of users in this channel<br><small>(Added in version 2.0.8. Older versions will return -1)</small></td><td>int</td></tr> +</table> +</blockquote> + +"dcc" - list of DCC file transfers. Fields: +<blockquote> <table border=1> +<tr bgcolor="#dddddd"><td>Name</td><td>Description</td><td>Type</td></tr> +<tr><td>address32</td><td>Address of the remote user (ipv4 address)</td><td>int</td></tr> +<tr><td>cps</td><td>Bytes per second (speed)</td><td>int</td></tr> +<tr><td>destfile</td><td>Destination full pathname</td><td>string</td></tr> +<tr><td>file</td><td>File name</td><td>string</td></tr> +<tr><td>nick</td><td>Nickname of person who the file is from/to</td><td>string</td></tr> +<tr><td>port</td><td>TCP port number</td><td>int</td></tr> +<tr><td>pos</td><td>Bytes sent/received</td><td>int</td></tr> +<tr><td>poshigh</td><td>Bytes sent/received, high order 32 bits</td><td>int</td></tr> +<tr><td>resume</td><td>Point at which this file was resumed (or zero if it was not resumed)</td><td>int</td></tr> +<tr><td>resumehigh</td><td>Point at which this file was resumed, high order 32 bits</td><td>int</td></tr> +<tr><td>size</td><td>File size in bytes, low order 32 bits (cast it to unsigned)</td><td>int</td></tr> +<tr><td>sizehigh</td><td>File size in bytes, high order 32 bits</td><td>int</td></tr> +<tr><td>status</td><td>DCC Status: 0-Queued 1-Active 2-Failed 3-Done 4-Connecting 5-Aborted</td><td>int</td></tr> +<tr><td>type</td><td>DCC Type: 0-Send 1-Receive 2-ChatRecv 3-ChatSend</td><td>int</td></tr> +</table> +</blockquote> + +"ignore" - current ignore list. +<blockquote> <table border=1> +<tr bgcolor="#dddddd"><td>Name</td><td>Description</td><td>Type</td></tr> +<tr><td>mask</td><td>Ignore mask. .e.g: *!*@*.aol.com</td><td>string</td></tr> +<tr><td>flags</td><td>Bit field of flags. 0=Private 1=Notice 2=Channel 3=Ctcp<br> +4=Invite 5=UnIgnore 6=NoSave 7=DCC</td><td>int</td></tr> +</table> +</blockquote> + +"notify" - list of people on notify. +<blockquote> <table border=1> +<tr bgcolor="#dddddd"><td>Name</td><td>Description</td><td>Type</td></tr> +<tr><td>networks</td><td>Networks to which this nick applies. Comma separated. May be NULL. +<br><small>(Added in version 2.6.8)</small></td><td>string</td></tr> +<tr><td>nick</td><td>Nickname</td><td>string</td></tr> +<tr><td>flags</td><td>Bit field of flags. 0=Is online.</td><td>int</td></tr> +<tr><td>on</td><td>Time when user came online.</td><td>time_t</td></tr> +<tr><td>off</td><td>Time when user went offline.</td><td>time_t</td></tr> +<tr><td>seen</td><td>Time when user the user was last verified still online.</td><td>time_t</td></tr> +</table> +<small>The entire "notify" list was added in xchat 2.0.8. Fields are +only valid for the context when xchat_list_get() was called +(i.e. you get information about the user ON THAT ONE SERVER ONLY). You +may cycle through the "channels" list to find notify information for every +server.</small> +</blockquote> + +"users" - list of users in the current channel. +<blockquote> <table border=1> +<tr bgcolor="#dddddd"><td>Name</td><td>Description</td><td>Type</td></tr> +<tr><td>away</td><td>Away status (boolean)<br><small>(Added in version 2.0.6. Older versions will return -1)</small></td><td>int</td></tr> +<tr><td>lasttalk</td><td>Last time the user was seen talking<br><small>(Added in version 2.4.2. Older versions will return -1)</small></td><td>time_t</td></tr> +<tr><td>nick</td><td>Nick name</td><td>string</td></tr> +<tr><td>host</td><td>Host name in the form: user@host (or NULL if not known).</td><td>string</td></tr> +<tr><td>prefix</td><td>Prefix character, .e.g: @ or +. Points to a single char.</td><td>string</td></tr> +<tr><td>realname</td><td>Real name or NULL<br><small>(Added in version 2.8.6)</small></td><td>string</td></tr> +<tr><td>selected</td><td>Selected status in the user list, only works for retrieving the user list of the focused tab<br><small>(Added in version 2.6.1. Older versions will return -1)</small></td><td>int</td></tr> +</table> +</blockquote> + +</blockquote> + +Example: +<br> +<pre> + list = xchat_list_get(ph, <font color="#f800f8">"dcc"</font>); + <font color="#a02828"><b>if</b></font>(list) + { + xchat_print(ph, <font color="#f800f8">"--- DCC LIST ------------------</font><font color="#6858c8">\n</font><font color="#f800f8">"</font> + <font color="#f800f8">"File To/From KB/s Position</font><font color="#6858c8">\n</font><font color="#f800f8">"</font>); + + <font color="#a02828"><b>while</b></font>(xchat_list_next(ph, list)) + { + xchat_printf(ph, <font color="#f800f8">"</font><font color="#6858c8">%6s</font><font color="#f800f8"> </font><font color="#6858c8">%10s</font><font color="#f800f8"> </font><font color="#6858c8">%.2f</font><font color="#f800f8"> </font><font color="#6858c8">%d</font><font color="#6858c8">\n</font><font color="#f800f8">"</font>, + xchat_list_str(ph, list, <font color="#f800f8">"file"</font>), + xchat_list_str(ph, list, <font color="#f800f8">"nick"</font>), + xchat_list_int(ph, list, <font color="#f800f8">"cps"</font>) / <font color="#f800f8">1024</font>, + xchat_list_int(ph, list, <font color="#f800f8">"pos"</font>)); + } + + xchat_list_free(ph, list); + } +</pre> + +<br> + +<h3><a name=win32>Plugins on Windows (Win32)</a></h3> +Yes, it can be done. All you need is either +<a href="http://msdn.microsoft.com/visualc/vctoolkit2003/">MSVC</a> (Visual Studio) or +<a href="http://www.mingw.org">MINGW</a>, both these compilers are free to download. +Simply compile your plugin as a DLL. You should have the following files: + +<ul> +<li><a href="http://xchat.org/docs/xchat-plugin.h">xchat-plugin.h</a> - Main Plugin header</li> +<li>plugin.c - Your plugin, you need to write this one :)</li> +<li>plugin.def - A simple text file containing the following:</li> +</ul> +<div class=box> +EXPORTS<br> + xchat_plugin_init<br> + xchat_plugin_deinit<br> + xchat_plugin_get_info<br> +</div> + +<br>Leave out <i>xchat_plugin_deinit</i> if you don't intend to define that +function. Then, to compile, type this at your command prompt:<br><br> +<div class=bbox> +<font color="#00FF00">MSVC</font> +<br> cl -O1 -MD -G5 -DWIN32 -c plugin.c<br> +<br> link /DLL /out:plugin.dll /SUBSYSTEM:WINDOWS plugin.obj /def:plugin.def /base:0x00d40000 +<br><br> +<font color="#00FF00">GCC (MINGW)</font> +<br> gcc -Wall -Os -DWIN32 -c plugin.c<br> +<br> dllwrap --def plugin.def --dllname plugin.dll plugin.o<br><br> +</div> +<br>For a complete example, have a look at the source code of the <a href="http://xchat.org/win32/testing/xcdns-src.zip">DNS Plugin</a>, which also contains a Makefile. +<br><br> +<font color=red>Caveat:</font> Plugins compiled on Win32 MUST have a +global variable called <b>ph</b>, which is the plugin_handle, much like +in the <a href="#sample">sample plugin</a> above. +<br><br> + +<h3><a name=gui>Controlling the GUI</a></h3> +<p> +A simple way to perform basic GUI functions is to use the /GUI command. +You can execute this command through the input-box, or by calling +xchat_command(ph, "GUI .....");. +</p> +<blockquote> + <table border=0 cellpadding=4> + <tr><td>GUI ATTACH</td><td>Same function as "Attach Window" in the XChat menu (new for 2.6.2).</td></tr> + <tr><td>GUI DETACH</td><td>Same function as "Detach Tab" in the XChat menu (new for 2.6.2).</td></tr> + <tr><td>GUI APPLY</td><td>Similar to clicking OK in the settings window. Execute this after /SET to activate GUI changes (new for 2.8.0)</td></tr> + <tr><td>GUI COLOR <i>n</i></td><td>Change the tab color of the current context, where n is a number from 0 to 3.</td></tr> + <tr><td>GUI FOCUS</td><td>Focus the current window or tab.</td></tr> + <tr><td>GUI FLASH</td><td>Flash the taskbar button. It will flash only if the window isn't focused and will stop when it is focused by the user.</td></tr> + <tr><td>GUI HIDE</td><td>Hide the main xchat window completely (this is used by the Systray plugin).</td></tr> + <tr><td>GUI ICONIFY</td><td>Iconify (minimize to taskbar) the current xchat window.</td></tr> + <tr><td>GUI MSGBOX <i>text</i></td><td>Displays a asynchronous message box with your text (new for 2.4.5).</td></tr> + <tr><td>GUI SHOW</td><td>Show the main xchat window (if currently hidden).</td></tr> + </table> +</blockquote> +<p> +Note, the FLASH, ICONIFY and COLOR args were added in xchat 2.0.8, they +will not work with previous versions. +</p> +<a name=menu>Starting from 2.4.5 you can add your own items to the menu bar. The menu command has this syntax</a>: +<pre> + MENU [-eX] [-i<ICONFILE>] [-k<mod>,<key>] [-m] [-pX] [-rX,group] [-tX] {ADD|DEL} <path> [command] [unselect command]</pre> +For example: +<pre> + MENU -p5 ADD FServe + MENU ADD "FServe/Show File List" "fs list" + MENU ADD FServe/- + MENU -k4,101 -t1 ADD "FServe/Enabled" "fs on" "fs off" + MENU -e0 ADD "FServe/Do Something" "fs action" +</pre> +In the example above, it would be recommended to execute "MENU DEL FServe" inside your xchat_plugin_deinit function. The special item with name "-" will add a separator line. +<br><br> +Parameters and flags: +<blockquote> +<table border=1 cellpadding=4 rules=all> +<tr><td>-eX</td><td>Set enable flag to X. -e0 for disable, -e1 for enable. This lets you create a disabled (shaded) item.</td></tr> +<tr><td>-iFILE</td><td>Use an icon filename FILE (new for 2.8.0). Not supported for toggles or radio items.</td></tr> +<tr><td>-k<mod>,<key></td><td>Specify a keyboard shortcut. "mod" is the modifier which is a bitwise OR of: 1-SHIFT 4-CTRL 8-ALT in decimal. "key" is the key value in decimal, e.g. -k5,101 would specify SHIFT-CTRL-E.</td></tr> +<tr><td>-m</td><td>Specify that this label should be treated as <a href="http://developer.gnome.org/doc/API/2.0/pango/PangoMarkupFormat.html">Pango Markup</a> language. Since forward slash ("/") is already used in menu paths, you should replace closing tags with an ASCII 003 instead e.g.: xchat_command(ph, "MENU -m ADD \"<b>Bold Menu<\003b>\""); (new for 2.6.6).</td></tr> +<tr><td>-pX</td><td>Specify a menu item's position number. e.g. -p5 will cause the item to be inserted in the 5th place. New for 2.8.0: If the position is a negative number, it will be used as an offset from the bottom/right-most item.</td></tr> +<tr><td>-rX,group</td><td>Specify a radio menu item, with initial state X and a group name (new for 2.8.0). The group name should be the exact label of another menu item (without the path) that this item will be grouped with. For radio items, only a select command will be executed (no unselect command).</td></tr> +<tr><td>-tX</td><td>Specify a toggle menu item with an initial state. -t0 for an "unticked" item and -t1 for a "ticked" item.</td></tr> +</table> +</blockquote> + +If you want to change an item's toggle state or enabled flag, +just ADD an item with exactly the same name and command and specify the -tX -eX parameters you need. +<br><br>It's also possible to add items to XChat's existing menus, for example:<br> +<pre> MENU ADD "Settings/Sub Menu" + MENU -t0 ADD "Settings/Sub Menu/My Setting" myseton mysetoff +</pre> +However, internal names and layouts of XChat's menu may change in the future, so use at own risk. +<br><br> +Here is an example of Radio items: +<pre> MENU ADD "Language" + MENU -r1,"English" ADD "Language/English" cmd1 + MENU -r0,"English" ADD "Language/Spanish" cmd2 + MENU -r0,"English" ADD "Language/German" cmd3</pre> +<br> +From 2.8.0, you can also change menus other than the main one (i.e popup menus). Currently they are: +<blockquote> +<table border=1 cellpadding=4 rules=all> +<tr bgcolor="#999999"><td>Root Name</td><td>Menu</td></tr> +<tr><td>$TAB</td><td>Tab menu (right click a channel/query tab or treeview row)</td></tr> +<tr><td>$TRAY</td><td>System Tray menu</td></tr> +<tr><td>$URL</td><td>URL link menu</td></tr> +<tr><td>$NICK</td><td>Userlist nick-name popup menu</td></tr> +<tr><td>$CHAN</td><td>Menu when clicking a channel in the text area (since 2.8.4)</td></tr> + +</table> +</blockquote> +<pre> + Example: MENU -p0 ADD "$TAB/Cycle Channel" cycle +</pre> + +<br> +<a name=tray>Starting from 2.8.0 you can manipulate XChat's system tray icon using the /TRAY command</a>: +<pre> + Usage: + TRAY -f <timeout> <file1> [<file2>] Flash tray between two icons. Leave off file2 to use default xchat icon. + TRAY -f <filename> Set tray to a fixed icon. + TRAY -i <number> Flash tray with an internal icon. + <small>2=Message 5=Highlight 8=Private 11=File</small> + TRAY -t <text> Set the tray tooltip. + TRAY -b <title> <text> Set the tray balloon. + <small>Supported on Windows from 2.8.1 and 2.8.2 on Linux (libnotify required on Linux).</small> +</pre> +Filenames can be ICO or PNG format. PNG format is supported on Linux/BSD and Windows XP (but requires installation of GDI+ on Windows 2000). Set a timeout of -1 to use XChat's default. +<br><br> + +<h3><a name=unicode>Handling UTF-8/Unicode strings</a></h3> +<p> +The XChat plugin API specifies that strings passed to and from xchat must be encoded in UTF-8. +<br><br> +What does this mean for the plugin programmer? You just have to be a little careful when +passing strings obtained from IRC to system calls. For example, if you're writing a file-server +bot, someone might message you a filename. Can you pass this filename directly to open()? Maybe! +If you're lazy... The correct thing to do is to convert the string to "system locale encoding", +otherwise your plugin will fail on non-ascii characters. +<br><br> +Here are examples on how to do this conversion on Unix and Windows. In this example, someone will +CTCP you the message "SHOWFILE <filename>". +<br><br> +</p> +<pre> +static int ctcp_cb(char *word[], char *word_eol[], void *userdata) +{ + if(strcmp(word[1], "SHOWFILE") == 0) + { + get_file_name(nick, word[2]); + } + + return XCHAT_EAT_XCHAT; +} + +static void get_file_name(char *nick, char *fname) +{ + char buf[256]; + FILE *fp; + +<font color="#777777"> /* the fname is in UTF-8, because it came from the xchat API */</font> +</pre><font color="#33aa44">#ifdef _WIN32</font><pre> + wchar_t wide_name[MAX_PATH]; + +<font color="#777777"> /* convert UTF-8 to WIDECHARs (aka UTF-16LE) */</font> + if (MultiByteToWideChar(CP_UTF8, 0, fname, -1, wide_name, MAX_PATH) < 1) + return; + +<font color="#777777"> /* now we have WIDECHARs, so we can _wopen() or CreateFileW(). */ + /* _wfopen actually requires NT4, Win2000, XP or newer. */</font> + fp = _wfopen(wide_name, "r"); +</pre><font color="#33aa44">#else</font><pre> + char *loc_name; + +<font color="#777777"> /* convert UTF-8 to System Encoding */</font> + loc_name = g_filename_from_utf8(fname, -1, 0, 0, 0); + if(!loc_name) + return; + +<font color="#777777"> /* now open using the system's encoding */</font> + fp = fopen(loc_name, "r"); + g_free(loc_name); +</pre><font color="#33aa44">#endif</font><pre> + if (fp) + { + while (fgets (buf, sizeof(buf), fp)) + { +<font color="#777777"> /* send every line to the user that requested it */</font> + xchat_commandf (ph, "QUOTE NOTICE %s :%s", nick, buf); + } + fclose (fp); + } +} +</pre> + + + +<br><br> + +<h1>Functions</h1> + +<h3><a class=cmd name="xchat_hook_command"> xchat_hook_command() </a></h3> +<b>Prototype:</b> xchat_hook *xchat_hook_command(xchat_plugin *ph, const char *name, int pri, xchat_cmd_cb *callb, const char *help_text, void *userdata); +<br> +<br><b>Description:</b> Adds a new /command. This allows your program to +handle commands entered at the input box. To capture text without a "/" at +the start (non-commands), you may hook a special name of "". i.e xchat_hook_command(ph, "", ...);. +<br> +Starting from version 2.6.8, commands hooked that begin with a period ('.') will be hidden in /HELP and /HELP -l. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>name:</b> Name of the command (without the forward slash). +<br><b>pri:</b> Priority of this command. Use XCHAT_PRI_NORM. +<br><b>callb:</b> Callback function. This will be called when the user executes the given command name. +<br><b>help_text:</b> String of text to display when the user executes /help for this command. May be NULL if you're lazy. +<br><b>userdata:</b> Pointer passed to the callback function.</blockquote> +<b>Returns:</b> Pointer to the hook. Can be passed to xchat_unhook. +<br> +<br><b>Example:</b> +<blockquote> +<pre> +static int onotice_cb(char *word[], char *word_eol[], void *userdata) +{ + if(word_eol[2][0] == 0) + { + xchat_printf(ph, "Second arg must be the message!\n"); + return XCHAT_EAT_ALL; + } + + xchat_commandf(ph, "NOTICE @%s :%s", xchat_get_info(ph, "channel"), word_eol[2]); + return XCHAT_EAT_ALL; +} + +xchat_hook_command(ph, "ONOTICE", XCHAT_PRI_NORM, onotice_cb, + "Usage: ONOTICE <message> Sends a notice to all ops", NULL); +</pre> +</blockquote> +<br> + +<h3><a class=cmd name="xchat_hook_fd"> xchat_hook_fd() </a></h3> +<b>Prototype:</b> xchat_hook *xchat_hook_fd(xchat_plugin *ph, int fd, int flags, xchat_fd_cb *callb, void *userdata); +<br> +<br><b>Description:</b> Hooks a socket or file descriptor. WIN32: Passing a pipe from MSVCR71, MSVCR80 or other variations is not supported at this time. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>fd:</b> The file descriptor or socket. +<br><b>flags:</b> One or more of XCHAT_FD_READ, XCHAT_FD_WRITE, XCHAT_FD_EXCEPTION, XCHAT_FD_NOTSOCKET. Use bitwise OR to combine them. +XCHAT_FD_NOTSOCKET tells xchat that the provided <b>fd</b> is not a socket, but a "MSVCRT.DLL" pipe. +<br><b>callb:</b> Callback function. This will be called when the socket is available for reading/writing or exception (depending on your chosen <b>flags</b>) +<br><b>userdata:</b> Pointer passed to the callback function.</blockquote> +<b>Returns:</b> Pointer to the hook. Can be passed to xchat_unhook. +<br><br><br> + +<h3><a class=cmd name="xchat_hook_print"> xchat_hook_print() </a></h3> +<b>Prototype:</b> <font color="#f8a400"><b>xchat_hook</b></font> *xchat_hook_print(<font color="#f8a400"><b>xchat_plugin</b></font> *ph, <font color="#f8a400"><b>const char</b></font> *name, <font color="#f8a400"><b>int</b></font> pri, <font color="#f8a400"><b>xchat_print_cb</b></font> *callb, <font color="#f8a400"><b>void</b></font> *userdata); +<br> +<br><b>Description:</b> Registers a function to trap any print events. +The event names may be any available in the "Advanced > Text Events" window. +There are also some extra "special" events you may hook using this function. +Currently they are:<blockquote> +"Open Context" - Called when a new xchat_context is created. +<br>"Close Context" - Called when a xchat_context pointer is closed. +<br>"Focus Tab" - Called when a tab is brought to front. +<br>"Focus Window" - Called a toplevel window is focused, or the main +tab-window is focused by the window manager. +<br>"DCC Chat Text" - Called when some text from a DCC Chat arrives. It provides these elements in the word[] array:<blockquote>word[1] Address +<br>word[2] Port +<br>word[3] Nick +<br>word[4] The Message +</blockquote> +"Key Press" - Called when some keys are pressed in the input-box (since 2.4.2). It provides these elements in the word[] array:<blockquote>word[1] Key Value +<br>word[2] State Bitfield (shift, capslock, alt) +<br>word[3] String version of the key +<br>word[4] Length of the string (may be 0 for unprintable keys) +</blockquote> +</blockquote> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>name:</b> Name of the print event (as in Edit Event Texts Window). +<br><b>pri:</b> Priority of this command. Use XCHAT_PRI_NORM. +<br><b>callb:</b> Callback function. This will be called when this event name is printed. +<br><b>userdata:</b> Pointer passed to the callback function.</blockquote> +<b>Returns:</b> Pointer to the hook. Can be passed to xchat_unhook. +<br> +<br><b>Example:</b> +<blockquote> +<pre> +static int youpart_cb(char *word[], void *userdata) +{ + xchat_printf(ph, "You have left channel %s\n", word[3]); + return XCHAT_EAT_XCHAT; /* dont let xchat do its normal printing */ +} + +xchat_hook_print(ph, "You Part", XCHAT_PRI_NORM, youpart_cb, NULL); +</pre> +</blockquote> +<br> + +<h3><a class=cmd name="xchat_hook_server"> xchat_hook_server() </a></h3> +<b>Prototype:</b> xchat_hook *xchat_hook_server(xchat_plugin *ph, const char *name, int pri, xchat_serv_cb *callb, void *userdata); +<br> +<br><b>Description:</b> Registers a function to be called when a certain server event occurs. You can +use this to trap PRIVMSG, NOTICE, PART, a server numeric etc... If you want to +hook every line that comes from the IRC server, you may use the special name of "RAW LINE". +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>name:</b> Name of the server event. +<br><b>pri:</b> Priority of this command. Use XCHAT_PRI_NORM. +<br><b>callb:</b> Callback function. This will be called when this event is received from the server. +<br><b>userdata:</b> Pointer passed to the callback function.</blockquote> +<b>Returns:</b> Pointer to the hook. Can be passed to xchat_unhook. +<br> +<br><b>Example:</b> +<blockquote> +<pre> +static int kick_cb(char *word[], char *word_eol[], void *userdata) +{ + xchat_printf(ph, "%s was kicked from %s (reason=%s)\n", word[4], word[3], word_eol[5]); + return XCHAT_EAT_NONE; /* don't eat this event, let other plugins and xchat see it too */ +} + +xchat_hook_server(ph, "KICK", XCHAT_PRI_NORM, kick_cb, NULL); +</pre> +</blockquote> +<br> + +<h3><a class=cmd name="xchat_hook_timer"> xchat_hook_timer() </a></h3> +<b>Prototype:</b> xchat_hook *xchat_hook_timer(xchat_plugin *ph, int timeout, xchat_timer_cb *callb, void *userdata); +<br> +<br><b>Description:</b> Registers a function to be called every "timeout" milliseconds. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>timeout:</b> Timeout in milliseconds (1000 is 1 second). +<br><b>callb:</b> Callback function. This will be called every "timeout" milliseconds. +<br><b>userdata:</b> Pointer passed to the callback function.</blockquote> +<b>Returns:</b> Pointer to the hook. Can be passed to xchat_unhook. +<br> +<br><b>Example:</b> +<blockquote> +<pre> +static xchat_hook *myhook; + +static int stop_cb(char *word[], char *word_eol[], void *userdata) +{ + if(myhook != NULL) + { + xchat_unhook(ph, myhook); + myhook = NULL; + xchat_print(ph, "Timeout removed!\n"); + } + + return XCHAT_EAT_ALL; +} + +static int timeout_cb(void *userdata) +{ + xchat_print(ph, "Annoying message every 5 seconds! Type /STOP to stop it.\n"); + return 1; /* return 1 to keep the timeout going */ +} + +myhook = xchat_hook_timer(ph, 5000, timeout_cb, NULL); +xchat_hook_command(ph, "STOP", XCHAT_PRI_NORM, stop_cb, NULL, NULL); +</pre><br> +</blockquote> + +<h3><a class=cmd name="xchat_unhook"> xchat_unhook() </a></h3> +<b>Prototype:</b> void *xchat_unhook(xchat_plugin *ph, xchat_hook *hook); +<br> +<br><b>Description:</b> Unhooks any hook registered with xchat_hook_print/server/timer/command. When plugins are unloaded, all of its hooks are automatically +removed, so you don't need to call this within your xchat_plugin_deinit() function. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>hook:</b> Pointer to the hook, as returned by xchat_hook_*. +<br></blockquote> +<b>Returns:</b> The userdata you originally gave to xchat_hook_*. +<br><br> + +<h3><a class=cmd name="xchat_command"> xchat_command() </a></h3> +<b>Prototype:</b> void xchat_command(xchat_plugin *ph, const char *command); +<br> +<br><b>Description:</b> Executes a command as if it were typed in xchat's input box. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>command:</b> Command to execute, without the forward slash "/". +<br><br> +</blockquote> + +<h3><a class=cmd name="xchat_commandf"> xchat_commandf() </a></h3> +<b>Prototype:</b> void xchat_commandf(xchat_plugin *ph, const char *format, ...); +<br> +<br><b>Description:</b> Executes a command as if it were typed in xchat's input box and provides string formating like printf. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>format:</b> The format string. +<br><br> +</blockquote> + +<h3><a class=cmd name="xchat_print"> xchat_print() </a></h3> +<b>Prototype:</b> void xchat_print(xchat_plugin *ph, const char *text); +<br> +<br><b>Description:</b> Prints some text to the current tab/window. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>text:</b> Text to print. May contain mIRC color codes. +<br><br> +</blockquote> + +<h3><a class=cmd name="xchat_printf"> xchat_printf() </a></h3> +<b>Prototype:</b> void xchat_printf(xchat_plugin *ph, const char *format, ...); +<br> +<br><b>Description:</b> Prints some text to the current tab/window and provides formating like printf. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>format:</b> The format string. +<br><br> +</blockquote> + +<h3><a class=cmd name="xchat_emit_print"> xchat_emit_print() </a></h3> +<b>Prototype:</b> int xchat_emit_print(xchat_plugin *ph, const char *event_name, ...); +<br> +<br><b>Description:</b> Generates a print event. This can be any +event found in the Preferences > Advanced > Text Events window. The vararg parameter list +MUST always be NULL terminated. Special care should be taken when calling this function +inside a print callback (from xchat_hook_print), as not to cause endless recursion. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>event_name:</b> Text event to print. +<br><br> +</blockquote> +<b>Returns:</b> 1-Success 0-Failure. +<br><br> +<b>Example:</b> +<pre> +xchat_emit_print(ph, "Channel Message", "John", "Hi there", "@", NULL); +</pre> +<br><br> + +<h3><a class=cmd name="xchat_send_modes"> xchat_send_modes() </a><small>(new for 2.0.9)</small></h3> +<b>Prototype:</b> void xchat_send_modes (xchat_plugin *ph, const char *targets[], int ntargets, int modes_per_line, char sign, char mode) +<br> +<br><b>Description:</b> Sends a number of channel mode changes to the current channel. For example, you can Op a whole +group of people in one go. It may send multiple MODE lines if the request doesn't fit on one. Pass 0 for +<b>modes_per_line</b> to use the current server's maximum possible. This function should only be called while +in a channel context. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>targets:</b> Array of targets (strings). The names of people whom the action will be performed on. +<br><b>ntargets:</b> Number of elements in the array given. +<br><b>modes_per_line:</b> Maximum modes to send per line. +<br><b>sign:</b> Mode sign, '-' or '+'. +<br><b>mode:</b> Mode char, e.g. 'o' for Ops.<br> +</blockquote> +<b>Example:</b> (Ops the three names given) +<pre> +const char *names_to_Op[] = {"John", "Jack", "Jill"}; +xchat_send_modes(ph, names_to_Op, 3, 0, '+', 'o'); +</pre> +<br><br> + +<h3><a class=cmd name="xchat_find_context"> xchat_find_context() </a></h3> +<b>Prototype:</b> xchat_context *xchat_find_context(xchat_plugin *ph, const char *servname, const char *channel); +<br> +<br><b>Description:</b> Finds a context based on a channel and servername. If servname is NULL, it finds any channel (or query) by the given name. If channel is NULL, it finds the front-most tab/window of the given servname. If NULL is given for both arguments, the currently focused tab/window will be returned.<br> +Changed in 2.6.1. If servname is NULL, it finds the channel (or query) by the given name in the same server group as the current context. If that doesn't exists then find any by the given name. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>servname:</b> Servername or NULL. +<br><b>channel:</b> Channelname or NULL. +<br> +</blockquote> +<b>Returns:</b> Context pointer (for use with xchat_set_context) or NULL. +<br><br><br> + +<h3><a class=cmd name="xchat_get_context"> xchat_get_context() </a></h3> +<b>Prototype:</b> xchat_context *xchat_get_context(xchat_plugin *ph); +<br> +<br><b>Description:</b> Returns the current context for your plugin. You can use this later with xchat_set_context. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br> +</blockquote> +<b>Returns:</b> Context pointer (for use with xchat_set_context). +<br><br><br> + +<h3><a class=cmd name="xchat_get_info"> xchat_get_info() </a></h3> +<b>Prototype:</b> const char *xchat_get_info(xchat_plugin *ph, const char *id); +<br> +<br><b>Description:</b> Returns information based on your current context. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>id:</b> ID of the information you want. Currently supported IDs are (case sensitive): + <blockquote> + <table border=0> + <tr><td width="18%">away</td><td>away reason or NULL if you are not away.</td></tr> + <tr><td>channel</td><td>current channel name.</td></tr> + <tr><td>charset</td><td>character-set used in the current context (since 2.4.2).</td></tr> + <tr><td>event_text <name></td><td>text event format string for <i>name</i> (since 2.8.2).</td></tr> + <tr><td>gtkwin_ptr</td><td>(GtkWindow *) (since 2.8.9).</td></tr> + <tr><td>host</td><td>real hostname of the server you connected to.</td></tr> + <tr><td>inputbox</td><td>the input-box contents, what the user has typed (since 2.4.1).</td></tr> + <tr><td>libdirfs</td><td>library directory. e.g. /usr/lib/xchat. The same directory used for auto-loading plugins (since 2.4.0).<small>This string isn't necessarily UTF-8, but local file system encoding.</small></td></tr> + <tr><td>modes</td><td>channel modes, if known, or NULL (since 2.8.1).</td></tr> + <tr><td>network</td><td>current network name or NULL.</td></tr> + <tr><td>nick</td><td>your current nick name.</td></tr> + <tr><td>nickserv</td><td>nickserv password for this network or NULL (since 2.4.3).</td></tr> + <tr><td>server</td><td>current server name (what the server claims to be). NULL if you are not connected.</td></tr> + <tr><td>topic</td><td>current channel topic.</td></tr> + <tr><td>version</td><td>xchat version number.</td></tr> + <tr><td>win_ptr</td><td>native window pointer. Unix: (GtkWindow *) Win32: HWND (since 2.6.0).</td></tr> + <tr><td>win_status</td><td>window status: "active", "hidden" or "normal" (since 2.0.9).</td> + <tr><td>xchatdir</td><td>xchat config directory, e.g.: /home/user/.xchat2 <small>This string is encoded in UTF-8, which means you _should_ convert it to "locale" encoding before using functions like open() or OpenFile(). For best <a href="#unicode">Unicode support</a> on Linux, convert this string using g_filename_from_utf8 and on Windows convert this string to UTF-16LE (wide) and use OpenFileW() etc.</small></td></tr> + <tr><td>xchatdirfs</td><td>xchat config directory, e.g.: /home/user/.xchat2 (since 2.0.9).<small>This string is encoded in local file system encoding, making it ideal for direct use with functions like open() or OpenFile(). For real Unicode support on Windows, it's best not to use xchatdirfs, but xchatdir instead.</small></td></tr> + </table> + </blockquote> +</blockquote> +<b>Returns:</b> A string of the requested information, or NULL. This string must +not be freed and must be copied if needed after the call to xchat_get_info. +<br><br><br> + +<h3><a class=cmd name="xchat_get_prefs"> xchat_get_prefs() </a></h3> +<b>Prototype:</b> int xchat_get_prefs(xchat_plugin *ph, const char *name, const char **string, int *integer); +<br> +<br><b>Description:</b> Provides xchat's setting information (that which is available through the /set command). +A few extra bits of information are available that don't appear in the /set list, currently they are: +<br> +<blockquote> + <table border=0 cellpadding=5> + <tr><td width="18%">state_cursor</td><td>Current input-box cursor position (characters, not bytes). Since 2.4.2.</td></tr> + <tr><td width="18%">id</td><td>Unique server id. Since 2.6.1.</td></tr> + </table> +</blockquote> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>name:</b> Setting name required. +<br><b>string:</b> Pointer-pointer which to set. +<br><b>integer:</b> Pointer to an integer to set, if setting is a Boolean or Integer type. +</blockquote> +<b>Returns:</b> 0-Failed 1-Returned a string 2-Returned an Integer 3-Returned a Boolean. +<br><br><b>Example:</b> +<blockquote> +<pre> +{ + int i; + const char *str; + + if (xchat_get_prefs (ph, "irc_nick1", &str, &i) == 1) + { + xchat_printf (ph, "Current nickname setting: %s\n", str); + } +}</pre> +</blockquote> +<br><br> + + +<h3><a class=cmd name="xchat_set_context"> xchat_set_context() </a></h3> +<b>Prototype:</b> int xchat_set_context(xchat_plugin *ph, xchat_context *ctx); +<br> +<br><b>Description:</b> Changes your current context to the one given. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>ctx:</b> Context to change to (obtained with xchat_get_context or xchat_find_context). +<br> +</blockquote> +<b>Returns:</b> 1 for success, 0 for failure. +<br><br><br> + +<h3><a class=cmd name="xchat_nickcmp"> xchat_nickcmp() </a></h3> +<b>Prototype:</b> int xchat_nickcmp(xchat_plugin *ph, const char *s1, const char *s2); +<br> +<br><b>Description:</b> Performs a nick name comparision, based on the current server connection. This might be a RFC1459 compliant string compare, or +plain ascii (in the case of DALNet). Use this to compare channels and nicknames. The function works the same way as strcasecmp. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>s1:</b> String to compare. +<br><b>s2:</b> String to compare s1 to. +<br> +</blockquote> +<b>Quote from RFC1459:</b> +<blockquote> + Because of IRC's scandanavian origin, the characters {}| are + considered to be the lower case equivalents of the characters []\, + respectively. This is a critical issue when determining the + equivalence of two nicknames. +</blockquote> +<b>Returns:</b> + An integer + less than, equal to, or greater than zero if s1 is found, + respectively, to be less than, to match, or be greater than s2. +<br><br><br> + +<h3><a class=cmd name="xchat_strip"> xchat_strip() </a><small>(new for 2.4.2)</small></h3> +<b>Prototype:</b> char *xchat_strip(xchat_plugin *ph, const char *str, int len, int flags); +<br> +<br><b>Description:</b> Strips mIRC color codes and/or text attributes (bold, underlined etc) from the given string and returns a newly allocated string. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>str:</b> String to strip. +<br><b>len:</b> Length of the string (or -1 for NULL terminated). +<br><b>flags:</b> Bit-field of flags: 0-Strip mIRC colors, 1-Strip text attributes. +<br> +</blockquote> +<b>Returns:</b> +A newly allocated string or NULL for failure. You must free this string with xchat_free. +<br><br><b>Example:</b> +<blockquote> +<pre> +{ + char *new_text; + + /* strip both colors and attributes by using the 0 and 1 bits (1 BITWISE-OR 2) */ + new_text = xchat_strip(ph, "\00312Blue\003 \002Bold!\002", -1, 1 | 2); + + if(new_text) + { + /* new_text should now contain only "Blue Bold!" */ + xchat_printf(ph, "%s\n", new_text); + xchat_free(ph, new_text); + } +}</pre> +</blockquote> + +<br><br> + +<h3><a class=cmd name="xchat_free"> xchat_free() </a><small>(new for 2.4.2)</small></h3> +<b>Prototype:</b> void xchat_free(xchat_plugin *ph, void *ptr); +<br> +<br><b>Description:</b> Frees a string returned by xchat_* functions. Currently only used to free strings from xchat_strip. +<br> +<br><b>Arguments:</b> +<blockquote><b>ph:</b> Plugin handle (as given to xchat_plugin_init). +<br><b>ptr:</b> Pointer to free. +<br> +</blockquote> + +<br><br> + +</body> +</html> diff --git a/plugins/python/Makefile.am b/plugins/python/Makefile.am new file mode 100644 index 00000000..1e4adff8 --- /dev/null +++ b/plugins/python/Makefile.am @@ -0,0 +1,10 @@ +EXTRA_DIST = + +libdir = $(xchatlibdir)/plugins + +lib_LTLIBRARIES = python.la +python_la_SOURCES = python.c +python_la_LDFLAGS = -avoid-version -module +python_la_LIBADD = $(PY_LIBS) +INCLUDES = $(PY_CFLAGS) $(COMMON_CFLAGS) -I$(srcdir)/.. + diff --git a/plugins/python/python.c b/plugins/python/python.c new file mode 100644 index 00000000..fd682082 --- /dev/null +++ b/plugins/python/python.c @@ -0,0 +1,2257 @@ +/* +* Copyright (c) 2002-2003 Gustavo Niemeyer <niemeyer@conectiva.com> +* +* XChat Python Plugin Interface +* +* Xchat Python Plugin Interface 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. +* +* pybot 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 file; if not, write to the Free Software +* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +/* Thread support + * ============== + * + * The python interpreter has a global interpreter lock. Any thread + * executing must acquire it before working with data accessible from + * python code. Here we must also care about xchat not being + * thread-safe. We do this by using an xchat lock, which protects + * xchat instructions from being executed out of time (when this + * plugin is not "active"). + * + * When xchat calls python code: + * - Change the current_plugin for the executing plugin; + * - Release xchat lock + * - Acquire the global interpreter lock + * - Make the python call + * - Release the global interpreter lock + * - Acquire xchat lock + * + * When python code calls xchat: + * - Release the global interpreter lock + * - Acquire xchat lock + * - Restore context, if necessary + * - Make the xchat call + * - Release xchat lock + * - Acquire the global interpreter lock + * + * Inside a timer, so that individual threads have a chance to run: + * - Release xchat lock + * - Go ahead threads. Have a nice time! + * - Acquire xchat lock + * + */ + +#include <glib.h> +#include <string.h> +#include <unistd.h> +#include <stdlib.h> +#include <sys/types.h> +#include <dirent.h> + +#include "xchat-plugin.h" +#include "Python.h" +#include "structmember.h" +#include "pythread.h" + +#define VERSION_MAJOR 0 +#define VERSION_MINOR 1 + +#ifdef WIN32 +#undef WITH_THREAD /* Thread support locks up xchat on Win32. */ +#define VERSION "0.8/2.4" /* Linked to python24.dll */ +#else +#define VERSION "0.8" +#endif + +#define NONE 0 +#define ALLOW_THREADS 1 +#define RESTORE_CONTEXT 2 + +#ifdef WITH_THREAD +#define ACQUIRE_XCHAT_LOCK() PyThread_acquire_lock(xchat_lock, 1) +#define RELEASE_XCHAT_LOCK() PyThread_release_lock(xchat_lock) +#define BEGIN_XCHAT_CALLS(x) \ + do { \ + PyObject *calls_plugin = NULL; \ + PyThreadState *calls_thread; \ + if ((x) & RESTORE_CONTEXT) \ + calls_plugin = Plugin_GetCurrent(); \ + calls_thread = PyEval_SaveThread(); \ + ACQUIRE_XCHAT_LOCK(); \ + if (!((x) & ALLOW_THREADS)) { \ + PyEval_RestoreThread(calls_thread); \ + calls_thread = NULL; \ + } \ + if (calls_plugin) \ + xchat_set_context(ph, \ + Plugin_GetContext(calls_plugin)); \ + while (0) +#define END_XCHAT_CALLS() \ + RELEASE_XCHAT_LOCK(); \ + if (calls_thread) \ + PyEval_RestoreThread(calls_thread); \ + } while(0) +#else +#define ACQUIRE_XCHAT_LOCK() +#define RELEASE_XCHAT_LOCK() +#define BEGIN_XCHAT_CALLS(x) +#define END_XCHAT_CALLS() +#endif + +#ifdef WITH_THREAD + +#define BEGIN_PLUGIN(plg) \ + do { \ + xchat_context *begin_plugin_ctx = xchat_get_context(ph); \ + RELEASE_XCHAT_LOCK(); \ + Plugin_AcquireThread(plg); \ + Plugin_SetContext(plg, begin_plugin_ctx); \ + } while (0) +#define END_PLUGIN(plg) \ + do { \ + Plugin_ReleaseThread(plg); \ + ACQUIRE_XCHAT_LOCK(); \ + } while (0) + +#else /* !WITH_THREAD (win32) */ + +static PyThreadState *pTempThread; + +#define BEGIN_PLUGIN(plg) \ + do { \ + xchat_context *begin_plugin_ctx = xchat_get_context(ph); \ + RELEASE_XCHAT_LOCK(); \ + PyEval_AcquireLock(); \ + pTempThread = PyThreadState_Swap(((PluginObject *)(plg))->tstate); \ + Plugin_SetContext(plg, begin_plugin_ctx); \ + } while (0) +#define END_PLUGIN(plg) \ + do { \ + ((PluginObject *)(plg))->tstate = PyThreadState_Swap(pTempThread); \ + PyEval_ReleaseLock(); \ + ACQUIRE_XCHAT_LOCK(); \ + } while (0) + +#endif /* !WITH_THREAD */ + +#define Plugin_Swap(x) \ + PyThreadState_Swap(((PluginObject *)(x))->tstate) +#define Plugin_AcquireThread(x) \ + PyEval_AcquireThread(((PluginObject *)(x))->tstate) +#define Plugin_ReleaseThread(x) \ + Util_ReleaseThread(((PluginObject *)(x))->tstate) +#define Plugin_GetFilename(x) \ + (((PluginObject *)(x))->filename) +#define Plugin_GetName(x) \ + (((PluginObject *)(x))->name) +#define Plugin_GetVersion(x) \ + (((PluginObject *)(x))->version) +#define Plugin_GetDesc(x) \ + (((PluginObject *)(x))->description) +#define Plugin_GetHooks(x) \ + (((PluginObject *)(x))->hooks) +#define Plugin_GetContext(x) \ + (((PluginObject *)(x))->context) +#define Plugin_SetFilename(x, y) \ + ((PluginObject *)(x))->filename = (y); +#define Plugin_SetName(x, y) \ + ((PluginObject *)(x))->name = (y); +#define Plugin_SetVersion(x, y) \ + ((PluginObject *)(x))->version = (y); +#define Plugin_SetDescription(x, y) \ + ((PluginObject *)(x))->description = (y); +#define Plugin_SetHooks(x, y) \ + ((PluginObject *)(x))->hooks = (y); +#define Plugin_SetContext(x, y) \ + ((PluginObject *)(x))->context = (y); + +#define HOOK_XCHAT 1 +#define HOOK_UNLOAD 2 + +/* ===================================================================== */ +/* Object definitions */ + +typedef struct { + PyObject_HEAD + int softspace; /* We need it for print support. */ +} XChatOutObject; + +typedef struct { + PyObject_HEAD + xchat_context *context; +} ContextObject; + +typedef struct { + PyObject_HEAD + const char *listname; + PyObject *dict; +} ListItemObject; + +typedef struct { + PyObject_HEAD + char *name; + char *version; + char *filename; + char *description; + GSList *hooks; + PyThreadState *tstate; + xchat_context *context; + void *gui; +} PluginObject; + +typedef struct { + int type; + PyObject *plugin; + PyObject *callback; + PyObject *userdata; + void *data; /* A handle, when type == HOOK_XCHAT */ +} Hook; + + +/* ===================================================================== */ +/* Function declarations */ + +static PyObject *Util_BuildList(char *word[]); +static void Util_Autoload(); +static char *Util_Expand(char *filename); + +static int Callback_Command(char *word[], char *word_eol[], void *userdata); +static int Callback_Print(char *word[], void *userdata); +static int Callback_Timer(void *userdata); +static int Callback_ThreadTimer(void *userdata); + +static PyObject *XChatOut_New(); +static PyObject *XChatOut_write(PyObject *self, PyObject *args); +static void XChatOut_dealloc(PyObject *self); + +static void Context_dealloc(PyObject *self); +static PyObject *Context_set(ContextObject *self, PyObject *args); +static PyObject *Context_command(ContextObject *self, PyObject *args); +static PyObject *Context_prnt(ContextObject *self, PyObject *args); +static PyObject *Context_get_info(ContextObject *self, PyObject *args); +static PyObject *Context_get_list(ContextObject *self, PyObject *args); +static PyObject *Context_compare(ContextObject *a, ContextObject *b, int op); +static PyObject *Context_FromContext(xchat_context *context); +static PyObject *Context_FromServerAndChannel(char *server, char *channel); + +static PyObject *Plugin_New(char *filename, PyMethodDef *xchat_methods, + PyObject *xcoobj); +static PyObject *Plugin_GetCurrent(); +static PluginObject *Plugin_ByString(char *str); +static Hook *Plugin_AddHook(int type, PyObject *plugin, PyObject *callback, + PyObject *userdata, void *data); +static void Plugin_RemoveHook(PyObject *plugin, Hook *hook); +static void Plugin_RemoveAllHooks(PyObject *plugin); + +static PyObject *Module_xchat_command(PyObject *self, PyObject *args); +static PyObject *Module_xchat_prnt(PyObject *self, PyObject *args); +static PyObject *Module_xchat_get_context(PyObject *self, PyObject *args); +static PyObject *Module_xchat_find_context(PyObject *self, PyObject *args, + PyObject *kwargs); +static PyObject *Module_xchat_get_info(PyObject *self, PyObject *args); +static PyObject *Module_xchat_hook_command(PyObject *self, PyObject *args, + PyObject *kwargs); +static PyObject *Module_xchat_hook_server(PyObject *self, PyObject *args, + PyObject *kwargs); +static PyObject *Module_xchat_hook_print(PyObject *self, PyObject *args, + PyObject *kwargs); +static PyObject *Module_xchat_hook_timer(PyObject *self, PyObject *args, + PyObject *kwargs); +static PyObject *Module_xchat_unhook(PyObject *self, PyObject *args); +static PyObject *Module_xchat_get_info(PyObject *self, PyObject *args); +static PyObject *Module_xchat_get_list(PyObject *self, PyObject *args); +static PyObject *Module_xchat_get_lists(PyObject *self, PyObject *args); +static PyObject *Module_xchat_nickcmp(PyObject *self, PyObject *args); +static PyObject *Module_xchat_strip(PyObject *self, PyObject *args); + +static void IInterp_Exec(char *command); +static int IInterp_Cmd(char *word[], char *word_eol[], void *userdata); + +static void Command_PyList(); +static void Command_PyLoad(char *filename); +static void Command_PyUnload(char *name); +static void Command_PyReload(char *name); +static void Command_PyAbout(); +static int Command_Py(char *word[], char *word_eol[], void *userdata); + +/* ===================================================================== */ +/* Static declarations and definitions */ + +staticforward PyTypeObject Plugin_Type; +staticforward PyTypeObject XChatOut_Type; +staticforward PyTypeObject Context_Type; +staticforward PyTypeObject ListItem_Type; + +static PyThreadState *main_tstate = NULL; +static void *thread_timer = NULL; + +static xchat_plugin *ph; +static GSList *plugin_list = NULL; + +static PyObject *interp_plugin = NULL; +static PyObject *xchatout = NULL; + +#ifdef WITH_THREAD +static PyThread_type_lock xchat_lock = NULL; +#endif + +static const char usage[] = "\ +Usage: /PY LOAD <filename>\n\ + UNLOAD <filename|name>\n\ + RELOAD <filename|name>\n\ + LIST\n\ + EXEC <command>\n\ + CONSOLE\n\ + ABOUT\n\ +\n"; + +static const char about[] = "\ +\n\ +X-Chat Python Interface " VERSION "\n\ +\n\ +Copyright (c) 2002-2003 Gustavo Niemeyer <niemeyer@conectiva.com>\n\ +\n"; + + +/* ===================================================================== */ +/* Utility functions */ + +static PyObject * +Util_BuildList(char *word[]) +{ + PyObject *list; + int listsize = 0; + int i; + while (word[listsize] && word[listsize][0]) + listsize++; + list = PyList_New(listsize); + if (list == NULL) { + PyErr_Print(); + return NULL; + } + for (i = 0; i != listsize; i++) { + PyObject *o = PyString_FromString(word[i]); + if (o == NULL) { + Py_DECREF(list); + PyErr_Print(); + return NULL; + } + PyList_SetItem(list, i, o); + } + return list; +} + +static void +Util_Autoload_from (const char *dir_name) +{ +#ifndef PATH_MAX +#define PATH_MAX 1024 /* Hurd doesn't define it */ +#endif + char oldcwd[PATH_MAX]; + struct dirent *ent; + DIR *dir; + if (getcwd(oldcwd, PATH_MAX) == NULL) + return; + if (chdir(dir_name) != 0) + return; + dir = opendir("."); + if (dir == NULL) + return; + while ((ent = readdir(dir))) { + int len = strlen(ent->d_name); + if (len > 3 && strcmp(".py", ent->d_name+len-3) == 0) + Command_PyLoad(ent->d_name); + } + closedir(dir); + chdir(oldcwd); +} + +static void +Util_Autoload() +{ + /* we need local filesystem encoding for chdir, opendir etc */ + + /* auto-load from ~/.xchat2/ or %APPDATA%\X-Chat 2\ */ + Util_Autoload_from(xchat_get_info(ph, "xchatdirfs")); + +#ifdef WIN32 /* also auto-load C:\Program Files\XChat\Plugins\*.py */ + Util_Autoload_from(XCHATLIBDIR"/plugins"); +#endif +} + +static char * +Util_Expand(char *filename) +{ + char *expanded; + + /* Check if this is an absolute path. */ + if (g_path_is_absolute(filename)) { + if (g_file_test(filename, G_FILE_TEST_EXISTS)) + return g_strdup(filename); + else + return NULL; + } + + /* Check if it starts with ~/ and expand the home if positive. */ + if (*filename == '~' && *(filename+1) == '/') { + expanded = g_build_filename(g_get_home_dir(), + filename+2, NULL); + if (g_file_test(expanded, G_FILE_TEST_EXISTS)) + return expanded; + else { + g_free(expanded); + return NULL; + } + } + + /* Check if it's in the current directory. */ + expanded = g_build_filename(g_get_current_dir(), + filename, NULL); + if (g_file_test(expanded, G_FILE_TEST_EXISTS)) + return expanded; + g_free(expanded); + + /* Check if ~/.xchat2/<filename> exists. */ + expanded = g_build_filename(xchat_get_info(ph, "xchatdir"), + filename, NULL); + if (g_file_test(expanded, G_FILE_TEST_EXISTS)) + return expanded; + g_free(expanded); + + return NULL; +} + +/* Similar to PyEval_ReleaseThread, but accepts NULL thread states. */ +static void +Util_ReleaseThread(PyThreadState *tstate) +{ + PyThreadState *old_tstate; + if (tstate == NULL) + Py_FatalError("PyEval_ReleaseThread: NULL thread state"); + old_tstate = PyThreadState_Swap(NULL); + if (old_tstate != tstate && old_tstate != NULL) + Py_FatalError("PyEval_ReleaseThread: wrong thread state"); + PyEval_ReleaseLock(); +} + +/* ===================================================================== */ +/* Hookable functions. These are the entry points to python code, besides + * the load function, and the hooks for interactive interpreter. */ + +static int +Callback_Command(char *word[], char *word_eol[], void *userdata) +{ + Hook *hook = (Hook *) userdata; + PyObject *retobj; + PyObject *word_list, *word_eol_list; + int ret = 0; + + BEGIN_PLUGIN(hook->plugin); + + word_list = Util_BuildList(word+1); + if (word_list == NULL) { + END_PLUGIN(hook->plugin); + return 0; + } + word_eol_list = Util_BuildList(word_eol+1); + if (word_eol_list == NULL) { + Py_DECREF(word_list); + END_PLUGIN(hook->plugin); + return 0; + } + + retobj = PyObject_CallFunction(hook->callback, "(OOO)", word_list, + word_eol_list, hook->userdata); + Py_DECREF(word_list); + Py_DECREF(word_eol_list); + + if (retobj == Py_None) { + ret = XCHAT_EAT_NONE; + Py_DECREF(retobj); + } else if (retobj) { + ret = PyInt_AsLong(retobj); + Py_DECREF(retobj); + } else { + PyErr_Print(); + } + + END_PLUGIN(hook->plugin); + + return ret; +} + +/* No Callback_Server() here. We use Callback_Command() as well. */ + +static int +Callback_Print(char *word[], void *userdata) +{ + Hook *hook = (Hook *) userdata; + PyObject *retobj; + PyObject *word_list; + PyObject *word_eol_list; + char **word_eol; + char *word_eol_raw; + int listsize = 0; + int next = 0; + int i; + int ret = 0; + + /* Cut off the message identifier. */ + word += 1; + + /* XChat doesn't provide a word_eol for print events, so we + * build our own here. */ + while (word[listsize] && word[listsize][0]) + listsize++; + word_eol = (char **) g_malloc(sizeof(char*)*(listsize+1)); + if (word_eol == NULL) { + xchat_print(ph, "Not enough memory to alloc word_eol " + "for python plugin callback."); + return 0; + } + /* First build a word clone, but NULL terminated. */ + memcpy(word_eol, word, listsize*sizeof(char*)); + word_eol[listsize] = NULL; + /* Then join it. */ + word_eol_raw = g_strjoinv(" ", word_eol); + if (word_eol_raw == NULL) { + xchat_print(ph, "Not enough memory to alloc word_eol_raw " + "for python plugin callback."); + return 0; + } + /* And rebuild the real word_eol. */ + for (i = 0; i != listsize; i++) { + word_eol[i] = word_eol_raw+next; + next += strlen(word[i])+1; + } + word_eol[i] = ""; + + BEGIN_PLUGIN(hook->plugin); + + word_list = Util_BuildList(word); + if (word_list == NULL) { + g_free(word_eol_raw); + g_free(word_eol); + END_PLUGIN(hook->plugin); + return 0; + } + word_eol_list = Util_BuildList(word_eol); + if (word_eol_list == NULL) { + g_free(word_eol_raw); + g_free(word_eol); + Py_DECREF(word_list); + END_PLUGIN(hook->plugin); + return 0; + } + + retobj = PyObject_CallFunction(hook->callback, "(OOO)", word_list, + word_eol_list, hook->userdata); + Py_DECREF(word_list); + Py_DECREF(word_eol_list); + + g_free(word_eol_raw); + g_free(word_eol); + if (retobj == Py_None) { + ret = XCHAT_EAT_NONE; + Py_DECREF(retobj); + } else if (retobj) { + ret = PyInt_AsLong(retobj); + Py_DECREF(retobj); + } else { + PyErr_Print(); + } + + END_PLUGIN(hook->plugin); + + return ret; +} + +static int +Callback_Timer(void *userdata) +{ + Hook *hook = (Hook *) userdata; + PyObject *retobj; + int ret = 0; + PyObject *plugin; + + plugin = hook->plugin; + + BEGIN_PLUGIN(hook->plugin); + + retobj = PyObject_CallFunction(hook->callback, "(O)", hook->userdata); + + if (retobj) { + ret = PyObject_IsTrue(retobj); + Py_DECREF(retobj); + } else { + PyErr_Print(); + } + + /* Returning 0 for this callback unhooks itself. */ + if (ret == 0) + Plugin_RemoveHook(plugin, hook); + + END_PLUGIN(plugin); + + return ret; +} + +#ifdef WITH_THREAD +static int +Callback_ThreadTimer(void *userdata) +{ + RELEASE_XCHAT_LOCK(); + usleep(1); + ACQUIRE_XCHAT_LOCK(); + return 1; +} +#endif + +/* ===================================================================== */ +/* XChatOut object */ + +/* We keep this information global, so we can reset it when the + * deinit function is called. */ +/* XXX This should be somehow bound to the printing context. */ +static char *xchatout_buffer = NULL; +static int xchatout_buffer_size = 0; +static int xchatout_buffer_pos = 0; + +static PyObject * +XChatOut_New() +{ + XChatOutObject *xcoobj; + xcoobj = PyObject_New(XChatOutObject, &XChatOut_Type); + if (xcoobj != NULL) + xcoobj->softspace = 0; + return (PyObject *) xcoobj; +} + +static void +XChatOut_dealloc(PyObject *self) +{ + self->ob_type->tp_free((PyObject *)self); +} + +/* This is a little bit complex because we have to buffer data + * until a \n is received, since xchat breaks the line automatically. + * We also crop the last \n for this reason. */ +static PyObject * +XChatOut_write(PyObject *self, PyObject *args) +{ + int new_buffer_pos, data_size, print_limit, add_space; + char *data, *pos; + if (!PyArg_ParseTuple(args, "s#:write", &data, &data_size)) + return NULL; + if (!data_size) { + Py_INCREF(Py_None); + return Py_None; + } + BEGIN_XCHAT_CALLS(RESTORE_CONTEXT|ALLOW_THREADS); + if (((XChatOutObject *)self)->softspace) { + add_space = 1; + ((XChatOutObject *)self)->softspace = 0; + } else { + add_space = 0; + } + if (xchatout_buffer_size-xchatout_buffer_pos < data_size+add_space) { + char *new_buffer; + /* This buffer grows whenever needed, and does not + * shrink. If we ever implement unloading of the + * python interface, we must find some way to free + * this buffer as well. */ + xchatout_buffer_size += data_size*2+16; + new_buffer = g_realloc(xchatout_buffer, xchatout_buffer_size); + if (new_buffer == NULL) { + xchat_print(ph, "Not enough memory to print"); + /* The system is out of resources. Let's help. */ + g_free(xchatout_buffer); + xchatout_buffer = NULL; + xchatout_buffer_size = 0; + xchatout_buffer_pos = 0; + /* Return something valid, since we have + * already warned the user, and he probably + * won't be able to notice this exception. */ + goto exit; + } + xchatout_buffer = new_buffer; + } + memcpy(xchatout_buffer+xchatout_buffer_pos, data, data_size); + print_limit = new_buffer_pos = xchatout_buffer_pos+data_size; + pos = xchatout_buffer+print_limit; + if (add_space && *(pos-1) != '\n') { + *pos = ' '; + *(pos+1) = 0; + new_buffer_pos++; + } + while (*pos != '\n' && print_limit > xchatout_buffer_pos) { + pos--; + print_limit--; + } + if (*pos == '\n') { + /* Crop it, inserting the string limiter there. */ + *pos = 0; + xchat_print(ph, xchatout_buffer); + if (print_limit < new_buffer_pos) { + /* There's still data to be printed. */ + print_limit += 1; /* Include the limiter. */ + xchatout_buffer_pos = new_buffer_pos-print_limit; + memmove(xchatout_buffer, xchatout_buffer+print_limit, + xchatout_buffer_pos); + } else { + xchatout_buffer_pos = 0; + } + } else { + xchatout_buffer_pos = new_buffer_pos; + } + +exit: + END_XCHAT_CALLS(); + Py_INCREF(Py_None); + return Py_None; +} + +#define OFF(x) offsetof(XChatOutObject, x) + +static PyMemberDef XChatOut_members[] = { + {"softspace", T_INT, OFF(softspace), 0}, + {0} +}; + +static PyMethodDef XChatOut_methods[] = { + {"write", XChatOut_write, METH_VARARGS}, + {NULL, NULL} +}; + +statichere PyTypeObject XChatOut_Type = { + PyObject_HEAD_INIT(NULL) + 0, /*ob_size*/ + "xchat.XChatOut", /*tp_name*/ + sizeof(XChatOutObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + XChatOut_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + XChatOut_methods, /*tp_methods*/ + XChatOut_members, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + _PyObject_Del, /*tp_free*/ + 0, /*tp_is_gc*/ +}; + + +/* ===================================================================== */ +/* Context object */ + +static void +Context_dealloc(PyObject *self) +{ + self->ob_type->tp_free((PyObject *)self); +} + +static PyObject * +Context_set(ContextObject *self, PyObject *args) +{ + PyObject *plugin = Plugin_GetCurrent(); + Plugin_SetContext(plugin, self->context); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +Context_command(ContextObject *self, PyObject *args) +{ + char *text; + if (!PyArg_ParseTuple(args, "s:command", &text)) + return NULL; + BEGIN_XCHAT_CALLS(ALLOW_THREADS); + xchat_set_context(ph, self->context); + xchat_command(ph, text); + END_XCHAT_CALLS(); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +Context_prnt(ContextObject *self, PyObject *args) +{ + char *text; + if (!PyArg_ParseTuple(args, "s:prnt", &text)) + return NULL; + BEGIN_XCHAT_CALLS(ALLOW_THREADS); + xchat_set_context(ph, self->context); + xchat_print(ph, text); + END_XCHAT_CALLS(); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +Context_emit_print(ContextObject *self, PyObject *args) +{ + char *argv[10]; + char *name; + int res; + memset(&argv, 0, sizeof(char*)*10); + if (!PyArg_ParseTuple(args, "s|ssssss:print_event", &name, + &argv[0], &argv[1], &argv[2], + &argv[3], &argv[4], &argv[5], + &argv[6], &argv[7], &argv[8])) + return NULL; + BEGIN_XCHAT_CALLS(ALLOW_THREADS); + xchat_set_context(ph, self->context); + res = xchat_emit_print(ph, name, argv[0], argv[1], argv[2], + argv[3], argv[4], argv[5], + argv[6], argv[7], argv[8]); + END_XCHAT_CALLS(); + return PyInt_FromLong(res); +} + +static PyObject * +Context_get_info(ContextObject *self, PyObject *args) +{ + const char *info; + char *name; + if (!PyArg_ParseTuple(args, "s:get_info", &name)) + return NULL; + BEGIN_XCHAT_CALLS(NONE); + xchat_set_context(ph, self->context); + info = xchat_get_info(ph, name); + END_XCHAT_CALLS(); + if (info == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyString_FromString(info); +} + +static PyObject * +Context_get_list(ContextObject *self, PyObject *args) +{ + PyObject *plugin = Plugin_GetCurrent(); + xchat_context *saved_context = Plugin_GetContext(plugin); + PyObject *ret; + Plugin_SetContext(plugin, self->context); + ret = Module_xchat_get_list((PyObject*)self, args); + Plugin_SetContext(plugin, saved_context); + return ret; +} + +/* needed to make context1 == context2 work */ +static PyObject * +Context_compare(ContextObject *a, ContextObject *b, int op) +{ + PyObject *ret; + /* check for == */ + if (op == Py_EQ) + ret = (a->context == b->context ? Py_True : Py_False); + /* check for != */ + else if (op == Py_NE) + ret = (a->context != b->context ? Py_True : Py_False); + /* only makes sense as == and != */ + else + { + PyErr_SetString(PyExc_TypeError, "contexts are either equal or not equal"); + ret = NULL; + } + + return ret; +} + +static PyMethodDef Context_methods[] = { + {"set", (PyCFunction) Context_set, METH_NOARGS}, + {"command", (PyCFunction) Context_command, METH_VARARGS}, + {"prnt", (PyCFunction) Context_prnt, METH_VARARGS}, + {"emit_print", (PyCFunction) Context_emit_print, METH_VARARGS}, + {"get_info", (PyCFunction) Context_get_info, METH_VARARGS}, + {"get_list", (PyCFunction) Context_get_list, METH_VARARGS}, + {NULL, NULL} +}; + +statichere PyTypeObject Context_Type = { + PyObject_HEAD_INIT(NULL) + 0, /*ob_size*/ + "xchat.Context", /*tp_name*/ + sizeof(ContextObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + Context_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + (richcmpfunc)Context_compare, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Context_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + _PyObject_Del, /*tp_free*/ + 0, /*tp_is_gc*/ +}; + +static PyObject * +Context_FromContext(xchat_context *context) +{ + ContextObject *ctxobj = PyObject_New(ContextObject, &Context_Type); + if (ctxobj != NULL) + ctxobj->context = context; + return (PyObject *) ctxobj; +} + +static PyObject * +Context_FromServerAndChannel(char *server, char *channel) +{ + ContextObject *ctxobj; + xchat_context *context; + BEGIN_XCHAT_CALLS(NONE); + context = xchat_find_context(ph, server, channel); + END_XCHAT_CALLS(); + if (context == NULL) + return NULL; + ctxobj = PyObject_New(ContextObject, &Context_Type); + if (ctxobj == NULL) + return NULL; + ctxobj->context = context; + return (PyObject *) ctxobj; +} + + +/* ===================================================================== */ +/* ListItem object */ + +#undef OFF +#define OFF(x) offsetof(ListItemObject, x) + +static PyMemberDef ListItem_members[] = { + {"__dict__", T_OBJECT, OFF(dict), 0}, + {0} +}; + +static void +ListItem_dealloc(PyObject *self) +{ + Py_DECREF(((ListItemObject*)self)->dict); + self->ob_type->tp_free((PyObject *)self); +} + +static PyObject * +ListItem_repr(PyObject *self) +{ + return PyString_FromFormat("<%s list item at %p>", + ((ListItemObject*)self)->listname, self); +} + +statichere PyTypeObject ListItem_Type = { + PyObject_HEAD_INIT(NULL) + 0, /*ob_size*/ + "xchat.ListItem", /*tp_name*/ + sizeof(ListItemObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + ListItem_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + ListItem_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + ListItem_members, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + OFF(dict), /*tp_dictoffset*/ + 0, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + _PyObject_Del, /*tp_free*/ + 0, /*tp_is_gc*/ +}; + +static PyObject * +ListItem_New(const char *listname) +{ + ListItemObject *item; + item = PyObject_New(ListItemObject, &ListItem_Type); + if (item != NULL) { + /* listname parameter must be statically allocated. */ + item->listname = listname; + item->dict = PyDict_New(); + if (item->dict == NULL) { + Py_DECREF(item); + item = NULL; + } + } + return (PyObject *) item; +} + + +/* ===================================================================== */ +/* Plugin object */ + +#define GET_MODULE_DATA(x, force) \ + o = PyObject_GetAttrString(m, "__module_" #x "__"); \ + if (o == NULL) { \ + if (force) { \ + xchat_print(ph, "Module has no __module_" #x "__ " \ + "defined"); \ + goto error; \ + } \ + plugin->x = g_strdup(""); \ + } else {\ + if (!PyString_Check(o)) { \ + xchat_print(ph, "Variable __module_" #x "__ " \ + "must be a string"); \ + goto error; \ + } \ + plugin->x = g_strdup(PyString_AsString(o)); \ + if (plugin->x == NULL) { \ + xchat_print(ph, "Not enough memory to allocate " #x); \ + goto error; \ + } \ + } + +static PyObject * +Plugin_New(char *filename, PyMethodDef *xchat_methods, PyObject *xcoobj) +{ + PluginObject *plugin = NULL; + PyObject *m, *o; + char *argv[] = {"<xchat>", 0}; + + if (filename) { + char *old_filename = filename; + filename = Util_Expand(filename); + if (filename == NULL) { + xchat_printf(ph, "File not found: %s", old_filename); + return NULL; + } + } + + /* Allocate plugin structure. */ + plugin = PyObject_New(PluginObject, &Plugin_Type); + if (plugin == NULL) { + xchat_print(ph, "Can't create plugin object"); + goto error; + } + + Plugin_SetName(plugin, NULL); + Plugin_SetVersion(plugin, NULL); + Plugin_SetFilename(plugin, NULL); + Plugin_SetDescription(plugin, NULL); + Plugin_SetHooks(plugin, NULL); + Plugin_SetContext(plugin, xchat_get_context(ph)); + + /* Start a new interpreter environment for this plugin. */ + PyEval_AcquireLock(); + plugin->tstate = Py_NewInterpreter(); + if (plugin->tstate == NULL) { + xchat_print(ph, "Can't create interpreter state"); + goto error; + } + + PySys_SetArgv(1, argv); + PySys_SetObject("__plugin__", (PyObject *) plugin); + + /* Set stdout and stderr to xchatout. */ + Py_INCREF(xcoobj); + PySys_SetObject("stdout", xcoobj); + Py_INCREF(xcoobj); + PySys_SetObject("stderr", xcoobj); + + /* Add xchat module to the environment. */ + m = Py_InitModule("xchat", xchat_methods); + if (m == NULL) { + xchat_print(ph, "Can't create xchat module"); + goto error; + } + + PyModule_AddIntConstant(m, "EAT_NONE", XCHAT_EAT_NONE); + PyModule_AddIntConstant(m, "EAT_XCHAT", XCHAT_EAT_XCHAT); + PyModule_AddIntConstant(m, "EAT_PLUGIN", XCHAT_EAT_PLUGIN); + PyModule_AddIntConstant(m, "EAT_ALL", XCHAT_EAT_ALL); + PyModule_AddIntConstant(m, "PRI_HIGHEST", XCHAT_PRI_HIGHEST); + PyModule_AddIntConstant(m, "PRI_HIGH", XCHAT_PRI_HIGH); + PyModule_AddIntConstant(m, "PRI_NORM", XCHAT_PRI_NORM); + PyModule_AddIntConstant(m, "PRI_LOW", XCHAT_PRI_LOW); + PyModule_AddIntConstant(m, "PRI_LOWEST", XCHAT_PRI_LOWEST); + + o = Py_BuildValue("(ii)", VERSION_MAJOR, VERSION_MINOR); + if (o == NULL) { + xchat_print(ph, "Can't create version tuple"); + goto error; + } + PyObject_SetAttrString(m, "__version__", o); + + if (filename) { +#ifdef WIN32 + PyObject* PyFileObject = PyFile_FromString(filename, "r"); + if (PyFileObject == NULL) { + xchat_printf(ph, "Can't open file %s: %s\n", + filename, strerror(errno)); + goto error; + } + + if (PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename) != 0) { + xchat_printf(ph, "Error loading module %s\n", + filename); + goto error; + } + + plugin->filename = filename; + filename = NULL; +#else + FILE *fp; + + plugin->filename = filename; + + /* It's now owned by the plugin. */ + filename = NULL; + + /* Open the plugin file. */ + fp = fopen(plugin->filename, "r"); + if (fp == NULL) { + xchat_printf(ph, "Can't open file %s: %s\n", + plugin->filename, strerror(errno)); + goto error; + } + + /* Run the plugin. */ + if (PyRun_SimpleFile(fp, plugin->filename) != 0) { + xchat_printf(ph, "Error loading module %s\n", + plugin->filename); + fclose(fp); + goto error; + } + fclose(fp); +#endif + m = PyDict_GetItemString(PyImport_GetModuleDict(), + "__main__"); + if (m == NULL) { + xchat_print(ph, "Can't get __main__ module"); + goto error; + } + GET_MODULE_DATA(name, 1); + GET_MODULE_DATA(version, 0); + GET_MODULE_DATA(description, 0); + plugin->gui = xchat_plugingui_add(ph, plugin->filename, + plugin->name, + plugin->description, + plugin->version, NULL); + } + + PyEval_ReleaseThread(plugin->tstate); + + return (PyObject *) plugin; + +error: + g_free(filename); + + if (plugin) { + if (plugin->tstate) + Py_EndInterpreter(plugin->tstate); + Py_DECREF(plugin); + } + PyEval_ReleaseLock(); + + return NULL; +} + +static PyObject * +Plugin_GetCurrent() +{ + PyObject *plugin; + plugin = PySys_GetObject("__plugin__"); + if (plugin == NULL) + PyErr_SetString(PyExc_RuntimeError, "lost sys.__plugin__"); + return plugin; +} + +static PluginObject * +Plugin_ByString(char *str) +{ + GSList *list; + PluginObject *plugin; + char *basename; + list = plugin_list; + while (list != NULL) { + plugin = (PluginObject *) list->data; + basename = g_path_get_basename(plugin->filename); + if (basename == NULL) + break; + if (strcasecmp(plugin->name, str) == 0 || + strcasecmp(plugin->filename, str) == 0 || + strcasecmp(basename, str) == 0) { + g_free(basename); + return plugin; + } + g_free(basename); + list = list->next; + } + return NULL; +} + +static Hook * +Plugin_AddHook(int type, PyObject *plugin, PyObject *callback, + PyObject *userdata, void *data) +{ + Hook *hook = (Hook *) g_malloc(sizeof(Hook)); + if (hook == NULL) { + PyErr_NoMemory(); + return NULL; + } + hook->type = type; + hook->plugin = plugin; + Py_INCREF(callback); + hook->callback = callback; + Py_INCREF(userdata); + hook->userdata = userdata; + hook->data = NULL; + Plugin_SetHooks(plugin, g_slist_append(Plugin_GetHooks(plugin), + hook)); + + return hook; +} + +static void +Plugin_RemoveHook(PyObject *plugin, Hook *hook) +{ + GSList *list; + /* Is this really a hook of the running plugin? */ + list = g_slist_find(Plugin_GetHooks(plugin), hook); + if (list) { + /* Ok, unhook it. */ + if (hook->type == HOOK_XCHAT) { + /* This is an xchat hook. Unregister it. */ + BEGIN_XCHAT_CALLS(NONE); + xchat_unhook(ph, (xchat_hook*)hook->data); + END_XCHAT_CALLS(); + } + Plugin_SetHooks(plugin, + g_slist_remove(Plugin_GetHooks(plugin), + hook)); + Py_DECREF(hook->callback); + Py_DECREF(hook->userdata); + g_free(hook); + } +} + +static void +Plugin_RemoveAllHooks(PyObject *plugin) +{ + GSList *list = Plugin_GetHooks(plugin); + while (list) { + Hook *hook = (Hook *) list->data; + if (hook->type == HOOK_XCHAT) { + /* This is an xchat hook. Unregister it. */ + BEGIN_XCHAT_CALLS(NONE); + xchat_unhook(ph, (xchat_hook*)hook->data); + END_XCHAT_CALLS(); + } + Py_DECREF(hook->callback); + Py_DECREF(hook->userdata); + g_free(hook); + list = list->next; + } + Plugin_SetHooks(plugin, NULL); +} + +static void +Plugin_Delete(PyObject *plugin) +{ + PyThreadState *tstate = ((PluginObject*)plugin)->tstate; + GSList *list = Plugin_GetHooks(plugin); + while (list) { + Hook *hook = (Hook *) list->data; + if (hook->type == HOOK_UNLOAD) { + PyObject *retobj; + retobj = PyObject_CallFunction(hook->callback, "(O)", + hook->userdata); + if (retobj) { + Py_DECREF(retobj); + } else { + PyErr_Print(); + PyErr_Clear(); + } + } + list = list->next; + } + Plugin_RemoveAllHooks(plugin); + xchat_plugingui_remove(ph, ((PluginObject *)plugin)->gui); + Py_DECREF(plugin); + /*PyThreadState_Swap(tstate); needed? */ + Py_EndInterpreter(tstate); +} + +static void +Plugin_dealloc(PluginObject *self) +{ + g_free(self->filename); + g_free(self->name); + g_free(self->version); + g_free(self->description); + self->ob_type->tp_free((PyObject *)self); +} + +statichere PyTypeObject Plugin_Type = { + PyObject_HEAD_INIT(NULL) + 0, /*ob_size*/ + "xchat.Plugin", /*tp_name*/ + sizeof(PluginObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)Plugin_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + _PyObject_Del, /*tp_free*/ + 0, /*tp_is_gc*/ +}; + + +/* ===================================================================== */ +/* XChat module */ + +static PyObject * +Module_xchat_command(PyObject *self, PyObject *args) +{ + char *text; + if (!PyArg_ParseTuple(args, "s:command", &text)) + return NULL; + BEGIN_XCHAT_CALLS(RESTORE_CONTEXT|ALLOW_THREADS); + xchat_command(ph, text); + END_XCHAT_CALLS(); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +Module_xchat_prnt(PyObject *self, PyObject *args) +{ + char *text; + if (!PyArg_ParseTuple(args, "s:prnt", &text)) + return NULL; + BEGIN_XCHAT_CALLS(RESTORE_CONTEXT|ALLOW_THREADS); + xchat_print(ph, text); + END_XCHAT_CALLS(); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +Module_xchat_emit_print(PyObject *self, PyObject *args) +{ + char *argv[10]; + char *name; + int res; + memset(&argv, 0, sizeof(char*)*10); + if (!PyArg_ParseTuple(args, "s|ssssss:print_event", &name, + &argv[0], &argv[1], &argv[2], + &argv[3], &argv[4], &argv[5], + &argv[6], &argv[7], &argv[8])) + return NULL; + BEGIN_XCHAT_CALLS(RESTORE_CONTEXT|ALLOW_THREADS); + res = xchat_emit_print(ph, name, argv[0], argv[1], argv[2], + argv[3], argv[4], argv[5], + argv[6], argv[7], argv[8]); + END_XCHAT_CALLS(); + return PyInt_FromLong(res); +} + +static PyObject * +Module_xchat_get_info(PyObject *self, PyObject *args) +{ + const char *info; + char *name; + if (!PyArg_ParseTuple(args, "s:get_info", &name)) + return NULL; + BEGIN_XCHAT_CALLS(RESTORE_CONTEXT); + info = xchat_get_info(ph, name); + END_XCHAT_CALLS(); + if (info == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyString_FromString(info); +} + +static PyObject * +Module_xchat_get_prefs(PyObject *self, PyObject *args) +{ + PyObject *res; + const char *info; + int integer; + char *name; + int type; + if (!PyArg_ParseTuple(args, "s:get_prefs", &name)) + return NULL; + BEGIN_XCHAT_CALLS(NONE); + type = xchat_get_prefs(ph, name, &info, &integer); + END_XCHAT_CALLS(); + switch (type) { + case 0: + Py_INCREF(Py_None); + res = Py_None; + break; + case 1: + res = PyString_FromString((char*)info); + break; + case 2: + case 3: + res = PyInt_FromLong(integer); + break; + default: + PyErr_Format(PyExc_RuntimeError, + "unknown get_prefs type (%d), " + "please report", type); + res = NULL; + break; + } + return res; +} + +static PyObject * +Module_xchat_get_context(PyObject *self, PyObject *args) +{ + PyObject *plugin; + PyObject *ctxobj; + plugin = Plugin_GetCurrent(); + if (plugin == NULL) + return NULL; + ctxobj = Context_FromContext(Plugin_GetContext(plugin)); + if (ctxobj == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return ctxobj; +} + +static PyObject * +Module_xchat_find_context(PyObject *self, PyObject *args, PyObject *kwargs) +{ + char *server = NULL; + char *channel = NULL; + PyObject *ctxobj; + char *kwlist[] = {"server", "channel", 0}; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|zz:find_context", + kwlist, &server, &channel)) + return NULL; + ctxobj = Context_FromServerAndChannel(server, channel); + if (ctxobj == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return ctxobj; +} + +static PyObject * +Module_xchat_hook_command(PyObject *self, PyObject *args, PyObject *kwargs) +{ + char *name; + PyObject *callback; + PyObject *userdata = Py_None; + int priority = XCHAT_PRI_NORM; + char *help = NULL; + PyObject *plugin; + Hook *hook; + char *kwlist[] = {"name", "callback", "userdata", + "priority", "help", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|Oiz:hook_command", + kwlist, &name, &callback, &userdata, + &priority, &help)) + return NULL; + + plugin = Plugin_GetCurrent(); + if (plugin == NULL) + return NULL; + if (!PyCallable_Check(callback)) { + PyErr_SetString(PyExc_TypeError, "callback is not callable"); + return NULL; + } + + hook = Plugin_AddHook(HOOK_XCHAT, plugin, callback, userdata, NULL); + if (hook == NULL) + return NULL; + + BEGIN_XCHAT_CALLS(NONE); + hook->data = (void*)xchat_hook_command(ph, name, priority, + Callback_Command, help, hook); + END_XCHAT_CALLS(); + + return PyInt_FromLong((long)hook); +} + +static PyObject * +Module_xchat_hook_server(PyObject *self, PyObject *args, PyObject *kwargs) +{ + char *name; + PyObject *callback; + PyObject *userdata = Py_None; + int priority = XCHAT_PRI_NORM; + PyObject *plugin; + Hook *hook; + char *kwlist[] = {"name", "callback", "userdata", "priority", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|Oi:hook_server", + kwlist, &name, &callback, &userdata, + &priority)) + return NULL; + + plugin = Plugin_GetCurrent(); + if (plugin == NULL) + return NULL; + if (!PyCallable_Check(callback)) { + PyErr_SetString(PyExc_TypeError, "callback is not callable"); + return NULL; + } + + hook = Plugin_AddHook(HOOK_XCHAT, plugin, callback, userdata, NULL); + if (hook == NULL) + return NULL; + + BEGIN_XCHAT_CALLS(NONE); + hook->data = (void*)xchat_hook_server(ph, name, priority, + Callback_Command, hook); + END_XCHAT_CALLS(); + + return PyInt_FromLong((long)hook); +} + +static PyObject * +Module_xchat_hook_print(PyObject *self, PyObject *args, PyObject *kwargs) +{ + char *name; + PyObject *callback; + PyObject *userdata = Py_None; + int priority = XCHAT_PRI_NORM; + PyObject *plugin; + Hook *hook; + char *kwlist[] = {"name", "callback", "userdata", "priority", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|Oi:hook_print", + kwlist, &name, &callback, &userdata, + &priority)) + return NULL; + + plugin = Plugin_GetCurrent(); + if (plugin == NULL) + return NULL; + if (!PyCallable_Check(callback)) { + PyErr_SetString(PyExc_TypeError, "callback is not callable"); + return NULL; + } + + hook = Plugin_AddHook(HOOK_XCHAT, plugin, callback, userdata, NULL); + if (hook == NULL) + return NULL; + + BEGIN_XCHAT_CALLS(NONE); + hook->data = (void*)xchat_hook_print(ph, name, priority, + Callback_Print, hook); + END_XCHAT_CALLS(); + + return PyInt_FromLong((long)hook); +} + + +static PyObject * +Module_xchat_hook_timer(PyObject *self, PyObject *args, PyObject *kwargs) +{ + int timeout; + PyObject *callback; + PyObject *userdata = Py_None; + PyObject *plugin; + Hook *hook; + char *kwlist[] = {"timeout", "callback", "userdata", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iO|O:hook_timer", + kwlist, &timeout, &callback, + &userdata)) + return NULL; + + plugin = Plugin_GetCurrent(); + if (plugin == NULL) + return NULL; + if (!PyCallable_Check(callback)) { + PyErr_SetString(PyExc_TypeError, "callback is not callable"); + return NULL; + } + + hook = Plugin_AddHook(HOOK_XCHAT, plugin, callback, userdata, NULL); + if (hook == NULL) + return NULL; + + BEGIN_XCHAT_CALLS(NONE); + hook->data = (void*)xchat_hook_timer(ph, timeout, + Callback_Timer, hook); + END_XCHAT_CALLS(); + + return PyInt_FromLong((long)hook); +} + +static PyObject * +Module_xchat_hook_unload(PyObject *self, PyObject *args, PyObject *kwargs) +{ + PyObject *callback; + PyObject *userdata = Py_None; + PyObject *plugin; + Hook *hook; + char *kwlist[] = {"callback", "userdata", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:hook_unload", + kwlist, &callback, &userdata)) + return NULL; + + plugin = Plugin_GetCurrent(); + if (plugin == NULL) + return NULL; + if (!PyCallable_Check(callback)) { + PyErr_SetString(PyExc_TypeError, "callback is not callable"); + return NULL; + } + + hook = Plugin_AddHook(HOOK_UNLOAD, plugin, callback, userdata, NULL); + if (hook == NULL) + return NULL; + + return PyInt_FromLong((long)hook); +} + +static PyObject * +Module_xchat_unhook(PyObject *self, PyObject *args) +{ + PyObject *plugin; + Hook *hook; + if (!PyArg_ParseTuple(args, "l:unhook", &hook)) + return NULL; + plugin = Plugin_GetCurrent(); + if (plugin == NULL) + return NULL; + Plugin_RemoveHook(plugin, hook); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +Module_xchat_get_list(PyObject *self, PyObject *args) +{ + xchat_list *list; + PyObject *l; + const char *name; + const char *const *fields; + int i; + + if (!PyArg_ParseTuple(args, "s:get_list", &name)) + return NULL; + /* This function is thread safe, and returns statically + * allocated data. */ + fields = xchat_list_fields(ph, "lists"); + for (i = 0; fields[i]; i++) { + if (strcmp(fields[i], name) == 0) { + /* Use the static allocated one. */ + name = fields[i]; + break; + } + } + if (fields[i] == NULL) { + PyErr_SetString(PyExc_KeyError, "list not available"); + return NULL; + } + l = PyList_New(0); + if (l == NULL) + return NULL; + BEGIN_XCHAT_CALLS(RESTORE_CONTEXT); + list = xchat_list_get(ph, (char*)name); + if (list == NULL) + goto error; + fields = xchat_list_fields(ph, (char*)name); + while (xchat_list_next(ph, list)) { + PyObject *o = ListItem_New(name); + if (o == NULL || PyList_Append(l, o) == -1) { + Py_XDECREF(o); + goto error; + } + Py_DECREF(o); /* l is holding a reference */ + for (i = 0; fields[i]; i++) { + const char *fld = fields[i]+1; + PyObject *attr = NULL; + const char *sattr; + int iattr; + switch(fields[i][0]) { + case 's': + sattr = xchat_list_str(ph, list, (char*)fld); + attr = PyString_FromString(sattr?sattr:""); + break; + case 'i': + iattr = xchat_list_int(ph, list, (char*)fld); + attr = PyInt_FromLong((long)iattr); + break; + case 'p': + sattr = xchat_list_str(ph, list, (char*)fld); + if (strcmp(fld, "context") == 0) { + attr = Context_FromContext( + (xchat_context*)sattr); + break; + } + default: /* ignore unknown (newly added?) types */ + continue; + } + if (attr == NULL) + goto error; + PyObject_SetAttrString(o, (char*)fld, attr); /* add reference on attr in o */ + Py_DECREF(attr); /* make o own attr */ + } + } + xchat_list_free(ph, list); + goto exit; +error: + if (list) + xchat_list_free(ph, list); + Py_DECREF(l); + l = NULL; + +exit: + END_XCHAT_CALLS(); + return l; +} + +static PyObject * +Module_xchat_get_lists(PyObject *self, PyObject *args) +{ + PyObject *l, *o; + const char *const *fields; + int i; + /* This function is thread safe, and returns statically + * allocated data. */ + fields = xchat_list_fields(ph, "lists"); + l = PyList_New(0); + if (l == NULL) + return NULL; + for (i = 0; fields[i]; i++) { + o = PyString_FromString(fields[i]); + if (o == NULL || PyList_Append(l, o) == -1) { + Py_DECREF(l); + Py_XDECREF(o); + return NULL; + } + Py_DECREF(o); /* l is holding a reference */ + } + return l; +} + +static PyObject * +Module_xchat_nickcmp(PyObject *self, PyObject *args) +{ + char *s1, *s2; + if (!PyArg_ParseTuple(args, "ss:nickcmp", &s1, &s2)) + return NULL; + return PyInt_FromLong((long) xchat_nickcmp(ph, s1, s2)); +} + +static PyObject * +Module_xchat_strip(PyObject *self, PyObject *args) +{ + PyObject *result; + char *str, *str2; + int len = -1, flags = 1 | 2; + if (!PyArg_ParseTuple(args, "s|ii:strip", &str, &len, &flags)) + return NULL; + str2 = xchat_strip(ph, str, len, flags); + result = PyString_FromString(str2); + xchat_free(ph, str2); + return result; +} + +static PyMethodDef Module_xchat_methods[] = { + {"command", Module_xchat_command, + METH_VARARGS}, + {"prnt", Module_xchat_prnt, + METH_VARARGS}, + {"emit_print", Module_xchat_emit_print, + METH_VARARGS}, + {"get_info", Module_xchat_get_info, + METH_VARARGS}, + {"get_prefs", Module_xchat_get_prefs, + METH_VARARGS}, + {"get_context", Module_xchat_get_context, + METH_NOARGS}, + {"find_context", (PyCFunction)Module_xchat_find_context, + METH_VARARGS|METH_KEYWORDS}, + {"hook_command", (PyCFunction)Module_xchat_hook_command, + METH_VARARGS|METH_KEYWORDS}, + {"hook_server", (PyCFunction)Module_xchat_hook_server, + METH_VARARGS|METH_KEYWORDS}, + {"hook_print", (PyCFunction)Module_xchat_hook_print, + METH_VARARGS|METH_KEYWORDS}, + {"hook_timer", (PyCFunction)Module_xchat_hook_timer, + METH_VARARGS|METH_KEYWORDS}, + {"hook_unload", (PyCFunction)Module_xchat_hook_unload, + METH_VARARGS|METH_KEYWORDS}, + {"unhook", Module_xchat_unhook, + METH_VARARGS}, + {"get_list", Module_xchat_get_list, + METH_VARARGS}, + {"get_lists", Module_xchat_get_lists, + METH_NOARGS}, + {"nickcmp", Module_xchat_nickcmp, + METH_VARARGS}, + {"strip", Module_xchat_strip, + METH_VARARGS}, + {NULL, NULL} +}; + + +/* ===================================================================== */ +/* Python interactive interpreter functions */ + +static void +IInterp_Exec(char *command) +{ + PyObject *m, *d, *o; + char *buffer; + int len; + + BEGIN_PLUGIN(interp_plugin); + + m = PyImport_AddModule("__main__"); + if (m == NULL) { + xchat_print(ph, "Can't get __main__ module"); + goto fail; + } + d = PyModule_GetDict(m); + len = strlen(command); + buffer = (char *) g_malloc(len+2); + if (buffer == NULL) { + xchat_print(ph, "Not enough memory for command buffer"); + goto fail; + } + memcpy(buffer, command, len); + buffer[len] = '\n'; + buffer[len+1] = 0; + o = PyRun_StringFlags(buffer, Py_single_input, d, d, NULL); + g_free(buffer); + if (o == NULL) { + PyErr_Print(); + goto fail; + } + Py_DECREF(o); + if (Py_FlushLine()) + PyErr_Clear(); + +fail: + END_PLUGIN(interp_plugin); + + return; +} + +static int +IInterp_Cmd(char *word[], char *word_eol[], void *userdata) +{ + char *channel = (char *) xchat_get_info(ph, "channel"); + if (channel && channel[0] == '>' && strcmp(channel, ">>python<<") == 0) { + xchat_printf(ph, ">>> %s\n", word_eol[1]); + IInterp_Exec(word_eol[1]); + return 1; + } + return 0; +} + + +/* ===================================================================== */ +/* Python command handling */ + +static void +Command_PyList() +{ + GSList *list; + list = plugin_list; + if (list == NULL) { + xchat_print(ph, "No python modules loaded"); + } else { + xchat_print(ph, + "Name Version Filename Description\n" + "---- ------- -------- -----------\n"); + while (list != NULL) { + PluginObject *plg = (PluginObject *) list->data; + char *basename = g_path_get_basename(plg->filename); + xchat_printf(ph, "%-12s %-8s %-20s %-10s\n", + plg->name, + *plg->version ? plg->version + : "<none>", + basename, + *plg->description ? plg->description + : "<none>"); + g_free(basename); + list = list->next; + } + xchat_print(ph, "\n"); + } +} + +static void +Command_PyLoad(char *filename) +{ + PyObject *plugin; + RELEASE_XCHAT_LOCK(); + plugin = Plugin_New(filename, Module_xchat_methods, xchatout); + ACQUIRE_XCHAT_LOCK(); + if (plugin) + plugin_list = g_slist_append(plugin_list, plugin); +} + +static void +Command_PyUnload(char *name) +{ + PluginObject *plugin = Plugin_ByString(name); + if (!plugin) { + xchat_print(ph, "Can't find a python plugin with that name"); + } else { + BEGIN_PLUGIN(plugin); + Plugin_Delete((PyObject*)plugin); + END_PLUGIN(plugin); + plugin_list = g_slist_remove(plugin_list, plugin); + } +} + +static void +Command_PyReload(char *name) +{ + PluginObject *plugin = Plugin_ByString(name); + if (!plugin) { + xchat_print(ph, "Can't find a python plugin with that name"); + } else { + char *filename = strdup(plugin->filename); + Command_PyUnload(filename); + Command_PyLoad(filename); + g_free(filename); + } +} + +static void +Command_PyAbout() +{ + xchat_print(ph, about); +} + +static int +Command_Py(char *word[], char *word_eol[], void *userdata) +{ + char *cmd = word[2]; + int ok = 0; + if (strcasecmp(cmd, "LIST") == 0) { + ok = 1; + Command_PyList(); + } else if (strcasecmp(cmd, "EXEC") == 0) { + if (word[3][0]) { + ok = 1; + IInterp_Exec(word_eol[3]); + } + } else if (strcasecmp(cmd, "LOAD") == 0) { + if (word[3][0]) { + ok = 1; + Command_PyLoad(word[3]); + } + } else if (strcasecmp(cmd, "UNLOAD") == 0) { + if (word[3][0]) { + ok = 1; + Command_PyUnload(word[3]); + } + } else if (strcasecmp(cmd, "RELOAD") == 0) { + if (word[3][0]) { + ok = 1; + Command_PyReload(word[3]); + } + } else if (strcasecmp(cmd, "CONSOLE") == 0) { + ok = 1; + xchat_command(ph, "QUERY >>python<<"); + } else if (strcasecmp(cmd, "ABOUT") == 0) { + ok = 1; + Command_PyAbout(); + } + if (!ok) + xchat_print(ph, usage); + return XCHAT_EAT_ALL; +} + +static int +Command_Load(char *word[], char *word_eol[], void *userdata) +{ + int len = strlen(word[2]); + if (len > 3 && strcasecmp(".py", word[2]+len-3) == 0) { + Command_PyLoad(word[2]); + return XCHAT_EAT_XCHAT; + } + return XCHAT_EAT_NONE; +} + +static int +Command_Unload(char *word[], char *word_eol[], void *userdata) +{ + int len = strlen(word[2]); + if (len > 3 && strcasecmp(".py", word[2]+len-3) == 0) { + Command_PyUnload(word[2]); + return XCHAT_EAT_XCHAT; + } + return XCHAT_EAT_NONE; +} + +/* ===================================================================== */ +/* Autoload function */ + +/* ===================================================================== */ +/* (De)initialization functions */ + +static int initialized = 0; +static int reinit_tried = 0; + +void +xchat_plugin_get_info(char **name, char **desc, char **version, void **reserved) +{ + *name = "Python"; + *version = VERSION; + *desc = "Python scripting interface"; + if (reserved) + *reserved = NULL; +} + +int +xchat_plugin_init(xchat_plugin *plugin_handle, + char **plugin_name, + char **plugin_desc, + char **plugin_version, + char *arg) +{ + char *argv[] = {"<xchat>", 0}; + + ph = plugin_handle; + + /* Block double initalization. */ + if (initialized != 0) { + xchat_print(ph, "Python interface already loaded"); + /* deinit is called even when init fails, so keep track + * of a reinit failure. */ + reinit_tried++; + return 0; + } + initialized = 1; + + *plugin_name = "Python"; + *plugin_version = VERSION; + *plugin_desc = "Python scripting interface"; + + /* Initialize python. */ + Py_SetProgramName("xchat"); + Py_Initialize(); + PySys_SetArgv(1, argv); + + Plugin_Type.ob_type = &PyType_Type; + Context_Type.ob_type = &PyType_Type; + XChatOut_Type.ob_type = &PyType_Type; + + xchatout = XChatOut_New(); + if (xchatout == NULL) { + xchat_print(ph, "Can't allocate xchatout object"); + return 0; + } + +#ifdef WITH_THREAD + PyEval_InitThreads(); + xchat_lock = PyThread_allocate_lock(); + if (xchat_lock == NULL) { + xchat_print(ph, "Can't allocate xchat lock"); + Py_DECREF(xchatout); + xchatout = NULL; + return 0; + } +#endif + + main_tstate = PyEval_SaveThread(); + + interp_plugin = Plugin_New(NULL, Module_xchat_methods, xchatout); + if (interp_plugin == NULL) { + xchat_print(ph, "Plugin_New() failed.\n"); +#ifdef WITH_THREAD + PyThread_free_lock(xchat_lock); +#endif + Py_DECREF(xchatout); + xchatout = NULL; + return 0; + } + + + xchat_hook_command(ph, "", XCHAT_PRI_NORM, IInterp_Cmd, 0, 0); + xchat_hook_command(ph, "PY", XCHAT_PRI_NORM, Command_Py, usage, 0); + xchat_hook_command(ph, "LOAD", XCHAT_PRI_NORM, Command_Load, 0, 0); + xchat_hook_command(ph, "UNLOAD", XCHAT_PRI_NORM, Command_Unload, 0, 0); +#ifdef WITH_THREAD + thread_timer = xchat_hook_timer(ph, 300, Callback_ThreadTimer, NULL); +#endif + + xchat_print(ph, "Python interface loaded\n"); + + Util_Autoload(); + return 1; +} + +int +xchat_plugin_deinit() +{ + GSList *list; + + /* A reinitialization was tried. Just give up and live the + * environment as is. We are still alive. */ + if (reinit_tried) { + reinit_tried--; + return 1; + } + + list = plugin_list; + while (list != NULL) { + PyObject *plugin = (PyObject *) list->data; + BEGIN_PLUGIN(plugin); + Plugin_Delete(plugin); + END_PLUGIN(plugin); + list = list->next; + } + g_slist_free(plugin_list); + plugin_list = NULL; + + /* Reset xchatout buffer. */ + g_free(xchatout_buffer); + xchatout_buffer = NULL; + xchatout_buffer_size = 0; + xchatout_buffer_pos = 0; + + if (interp_plugin) { + Py_DECREF(interp_plugin); + interp_plugin = NULL; + } + + /* Switch back to the main thread state. */ + if (main_tstate) { + PyThreadState_Swap(main_tstate); + main_tstate = NULL; + } + Py_Finalize(); + +#ifdef WITH_THREAD + if (thread_timer != NULL) { + xchat_unhook(ph, thread_timer); + thread_timer = NULL; + } + PyThread_free_lock(xchat_lock); +#endif + + xchat_print(ph, "Python interface unloaded\n"); + initialized = 0; + + return 1; +} + diff --git a/plugins/tcl/Makefile.am b/plugins/tcl/Makefile.am new file mode 100644 index 00000000..804fc83b --- /dev/null +++ b/plugins/tcl/Makefile.am @@ -0,0 +1,10 @@ + +EXTRA_DIST=printevents.h tclplugin.h README + +libdir = $(xchatlibdir)/plugins + +lib_LTLIBRARIES = tcl.la +tcl_la_SOURCES = tclplugin.c +tcl_la_LDFLAGS = -avoid-version -module +tcl_la_LIBADD = $(TCL_LIBS) +INCLUDES = $(TCL_CFLAGS) $(COMMON_CFLAGS) -I$(srcdir)/.. diff --git a/plugins/tcl/README b/plugins/tcl/README new file mode 100644 index 00000000..e46635ef --- /dev/null +++ b/plugins/tcl/README @@ -0,0 +1,55 @@ +Please read this document before asking questions. + +(1) WHAT IS THE TCL PLUGIN? + + The XChat Tcl Plugin adds the complete Tcl scripting language to the + XChat 1.9.x and 2.x IRC client. The design philosophy behind the tcl + plugin was to give all the power of the C API. yet completely shield + the user from all the complexities of it. It is lightly modeled after + after Xircon; an old windows TCL enabled client with a little bit of + eggdrop functionality to it. + + Features: + * Uses the popular TCL scripting language. + * Familiar to eggdrop bot owners. + * Adds many new XChat specific commands to the Tcl language for + handling of events, user commands, timers, etc. + * It's actually documented! (Hey, what a concept!) + * Works with XChat 1.9.x and 2.x. + * Open source (GPL) + + The supplied documentation for Tcl Plugin commands can be + found in doc/tclplugin.html + + For a comprehensive list of IRC server tokens, see + doc/tokens.txt + + +(2) HOW TO GET TCL PLUGIN + + You can always find the latest version of the Tcl Plugin at: + + http://www.scriptkitties.com/tclplugin + + You must also have Tcl 8.3 or higher installed on your system. + + Tcl can be obtained from: + + http://sourceforge.net/projects/tcl + http://tcl.activestate.com (pre-compiled binaries) + + Tcl Man Pages + + http://tcl.activestate.com/man/ + + Tcl Tutorials: + + http://hegel.ittc.ukans.edu/topics/tcltk/tutorial-noplugin/ + http://jan.netcomp.monash.edu.au/ProgrammingUnix/tcl/tcl_tut.html + http://users.belgacom.net/bruno.champagne/tcl.html + + +(3) QUICK STARTUP + + SEE 'INSTALL' + diff --git a/plugins/tcl/printevents.h b/plugins/tcl/printevents.h new file mode 100644 index 00000000..dfea4aea --- /dev/null +++ b/plugins/tcl/printevents.h @@ -0,0 +1,319 @@ +/*************************************************************************** + printevents.h - TCL plugin header file + ------------------------------------------------- + begin : Sat Nov 9 17:31:20 MST 2002 + copyright : Copyright 2002-2007 Daniel P. Stasinski + email : mooooooo@avenues.org + generated : Mon May 21 06:03:00 PM MST 2007 + ***************************************************************************/ + +/*************************************************************************** + * * + * 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. * + * * + ***************************************************************************/ + +typedef struct { + char *event; + char *emit; + int argc; + xchat_hook *hook; +} print_event; + +enum +{ + CHAT, + XC_APPFOCUS, + XC_TABOPEN, + XC_TABCLOSE, + XC_TABFOCUS, + XC_KEYPRESS, + XC_ADDNOTIFY, + XC_BANLIST, + XC_BANNED, + XC_BEEP, + XC_CHANGENICK, + XC_CHANACTION, + XC_HCHANACTION, + XC_CHANBAN, + XC_CHANDATE, + XC_CHANDEHOP, + XC_CHANDEOP, + XC_CHANDEVOICE, + XC_CHANEXEMPT, + XC_CHANHOP, + XC_CHANINVITE, + XC_CHANLISTHEAD, + XC_CHANMSG, + XC_CHANMODEGEN, + XC_CHANMODES, + XC_HCHANMSG, + XC_CHANNOTICE, + XC_CHANOP, + XC_CHANRMEXEMPT, + XC_CHANRMINVITE, + XC_CHANRMKEY, + XC_CHANRMLIMIT, + XC_CHANSETKEY, + XC_CHANSETLIMIT, + XC_CHANUNBAN, + XC_CHANVOICE, + XC_CONNECTED, + XC_CONNECT, + XC_CONNFAIL, + XC_CTCPGEN, + XC_CTCPGENC, + XC_CTCPSEND, + XC_CTCPSND, + XC_CTCPSNDC, + XC_DCCCHATABORT, + XC_DCCCONCHAT, + XC_DCCCHATF, + XC_DCCCHATOFFER, + XC_DCCCHATOFFERING, + XC_DCCCHATREOFFER, + XC_DCCCONFAIL, + XC_DCCGENERICOFFER, + XC_DCCHEAD, + XC_MALFORMED, + XC_DCCOFFER, + XC_DCCIVAL, + XC_DCCRECVABORT, + XC_DCCRECVCOMP, + XC_DCCCONRECV, + XC_DCCRECVERR, + XC_DCCFILEERR, + XC_DCCRENAME, + XC_DCCRESUMEREQUEST, + XC_DCCSENDABORT, + XC_DCCSENDCOMP, + XC_DCCCONSEND, + XC_DCCSENDFAIL, + XC_DCCSENDOFFER, + XC_DCCSTALL, + XC_DCCTOUT, + XC_DELNOTIFY, + XC_DISCON, + XC_FOUNDIP, + XC_GENMSG, + XC_IGNOREADD, + XC_IGNORECHANGE, + XC_IGNOREFOOTER, + XC_IGNOREHEADER, + XC_IGNOREREMOVE, + XC_IGNOREEMPTY, + XC_INVITE, + XC_INVITED, + XC_JOIN, + XC_KEYWORD, + XC_KICK, + XC_KILL, + XC_MSGSEND, + XC_MOTD, + XC_MOTDSKIP, + XC_NICKCLASH, + XC_NICKFAIL, + XC_NODCC, + XC_NOCHILD, + XC_NOTICE, + XC_NOTICESEND, + XC_NOTIFYEMPTY, + XC_NOTIFYHEAD, + XC_NOTIFYNUMBER, + XC_NOTIFYOFFLINE, + XC_NOTIFYONLINE, + XC_OPENDIALOG, + XC_PART, + XC_PARTREASON, + XC_PINGREP, + XC_PINGTIMEOUT, + XC_PRIVMSG, + XC_DPRIVMSG, + XC_ALREADYPROCESS, + XC_QUIT, + XC_RAWMODES, + XC_WALLOPS, + XC_RESOLVINGUSER, + XC_SERVERCONNECTED, + XC_SERVERERROR, + XC_SERVERLOOKUP, + XC_SERVNOTICE, + XC_SERVTEXT, + XC_STOPCONNECT, + XC_TOPIC, + XC_NEWTOPIC, + XC_TOPICDATE, + XC_UKNHOST, + XC_USERLIMIT, + XC_USERSONCHAN, + XC_WHOIS_AUTH, + XC_WHOIS5, + XC_WHOIS2, + XC_WHOIS6, + XC_WHOIS_ID, + XC_WHOIS4, + XC_WHOIS4T, + XC_WHOIS1, + XC_WHOIS_REALHOST, + XC_WHOIS3, + XC_WHOIS_SPECIAL, + XC_UJOIN, + XC_UKICK, + XC_UPART, + XC_UPARTREASON, + XC_UACTION, + XC_UINVITE, + XC_UCHANMSG, + XC_UCHANGENICK, + XC_SIZE +}; + +static print_event xc[] = { + { "CHAT", "DCC Chat Text", -1, NULL }, + { "XC_APPFOCUS", "Focus Window", -3, NULL }, + { "XC_TABOPEN", "Open Context", -2, NULL }, + { "XC_TABCLOSE", "Close Context", -2, NULL }, + { "XC_TABFOCUS", "Focus Tab", -2, NULL }, + { "XC_KEYPRESS", "Key Press", 4, NULL }, + { "XC_ADDNOTIFY", "Add Notify", 1, NULL }, + { "XC_BANLIST", "Ban List", 4, NULL }, + { "XC_BANNED", "Banned", 1, NULL }, + { "XC_BEEP", "Beep", 0, NULL }, + { "XC_CHANGENICK", "Change Nick", 2, NULL }, + { "XC_CHANACTION", "Channel Action", 3, NULL }, + { "XC_HCHANACTION", "Channel Action Hilight", 3, NULL }, + { "XC_CHANBAN", "Channel Ban", 2, NULL }, + { "XC_CHANDATE", "Channel Creation", 2, NULL }, + { "XC_CHANDEHOP", "Channel DeHalfOp", 2, NULL }, + { "XC_CHANDEOP", "Channel DeOp", 2, NULL }, + { "XC_CHANDEVOICE", "Channel DeVoice", 2, NULL }, + { "XC_CHANEXEMPT", "Channel Exempt", 2, NULL }, + { "XC_CHANHOP", "Channel Half-Operator", 2, NULL }, + { "XC_CHANINVITE", "Channel INVITE", 2, NULL }, + { "XC_CHANLISTHEAD", "Channel List", 0, NULL }, + { "XC_CHANMSG", "Channel Message", 4, NULL }, + { "XC_CHANMODEGEN", "Channel Mode Generic", 4, NULL }, + { "XC_CHANMODES", "Channel Modes", 2, NULL }, + { "XC_HCHANMSG", "Channel Msg Hilight", 4, NULL }, + { "XC_CHANNOTICE", "Channel Notice", 3, NULL }, + { "XC_CHANOP", "Channel Operator", 2, NULL }, + { "XC_CHANRMEXEMPT", "Channel Remove Exempt", 2, NULL }, + { "XC_CHANRMINVITE", "Channel Remove Invite", 2, NULL }, + { "XC_CHANRMKEY", "Channel Remove Keyword", 1, NULL }, + { "XC_CHANRMLIMIT", "Channel Remove Limit", 1, NULL }, + { "XC_CHANSETKEY", "Channel Set Key", 2, NULL }, + { "XC_CHANSETLIMIT", "Channel Set Limit", 2, NULL }, + { "XC_CHANUNBAN", "Channel UnBan", 2, NULL }, + { "XC_CHANVOICE", "Channel Voice", 2, NULL }, + { "XC_CONNECTED", "Connected", 0, NULL }, + { "XC_CONNECT", "Connecting", 3, NULL }, + { "XC_CONNFAIL", "Connection Failed", 1, NULL }, + { "XC_CTCPGEN", "CTCP Generic", 2, NULL }, + { "XC_CTCPGENC", "CTCP Generic to Channel", 3, NULL }, + { "XC_CTCPSEND", "CTCP Send", 2, NULL }, + { "XC_CTCPSND", "CTCP Sound", 2, NULL }, + { "XC_CTCPSNDC", "CTCP Sound to Channel", 3, NULL }, + { "XC_DCCCHATABORT", "DCC CHAT Abort", 1, NULL }, + { "XC_DCCCONCHAT", "DCC CHAT Connect", 2, NULL }, + { "XC_DCCCHATF", "DCC CHAT Failed", 4, NULL }, + { "XC_DCCCHATOFFER", "DCC CHAT Offer", 1, NULL }, + { "XC_DCCCHATOFFERING", "DCC CHAT Offering", 1, NULL }, + { "XC_DCCCHATREOFFER", "DCC CHAT Reoffer", 1, NULL }, + { "XC_DCCCONFAIL", "DCC Conection Failed", 3, NULL }, + { "XC_DCCGENERICOFFER", "DCC Generic Offer", 2, NULL }, + { "XC_DCCHEAD", "DCC Header", 0, NULL }, + { "XC_MALFORMED", "DCC Malformed", 2, NULL }, + { "XC_DCCOFFER", "DCC Offer", 3, NULL }, + { "XC_DCCIVAL", "DCC Offer Not Valid", 0, NULL }, + { "XC_DCCRECVABORT", "DCC RECV Abort", 2, NULL }, + { "XC_DCCRECVCOMP", "DCC RECV Complete", 4, NULL }, + { "XC_DCCCONRECV", "DCC RECV Connect", 3, NULL }, + { "XC_DCCRECVERR", "DCC RECV Failed", 4, NULL }, + { "XC_DCCFILEERR", "DCC RECV File Open Error", 2, NULL }, + { "XC_DCCRENAME", "DCC Rename", 2, NULL }, + { "XC_DCCRESUMEREQUEST", "DCC RESUME Request", 3, NULL }, + { "XC_DCCSENDABORT", "DCC SEND Abort", 2, NULL }, + { "XC_DCCSENDCOMP", "DCC SEND Complete", 3, NULL }, + { "XC_DCCCONSEND", "DCC SEND Connect", 3, NULL }, + { "XC_DCCSENDFAIL", "DCC SEND Failed", 3, NULL }, + { "XC_DCCSENDOFFER", "DCC SEND Offer", 4, NULL }, + { "XC_DCCSTALL", "DCC Stall", 3, NULL }, + { "XC_DCCTOUT", "DCC Timeout", 3, NULL }, + { "XC_DELNOTIFY", "Delete Notify", 1, NULL }, + { "XC_DISCON", "Disconnected", 1, NULL }, + { "XC_FOUNDIP", "Found IP", 1, NULL }, + { "XC_GENMSG", "Generic Message", 2, NULL }, + { "XC_IGNOREADD", "Ignore Add", 1, NULL }, + { "XC_IGNORECHANGE", "Ignore Changed", 1, NULL }, + { "XC_IGNOREFOOTER", "Ignore Footer", 0, NULL }, + { "XC_IGNOREHEADER", "Ignore Header", 0, NULL }, + { "XC_IGNOREREMOVE", "Ignore Remove", 1, NULL }, + { "XC_IGNOREEMPTY", "Ignorelist Empty", 0, NULL }, + { "XC_INVITE", "Invite", 1, NULL }, + { "XC_INVITED", "Invited", 3, NULL }, + { "XC_JOIN", "Join", 3, NULL }, + { "XC_KEYWORD", "Keyword", 1, NULL }, + { "XC_KICK", "Kick", 4, NULL }, + { "XC_KILL", "Killed", 2, NULL }, + { "XC_MSGSEND", "Message Send", 2, NULL }, + { "XC_MOTD", "Motd", 1, NULL }, + { "XC_MOTDSKIP", "MOTD Skipped", 0, NULL }, + { "XC_NICKCLASH", "Nick Clash", 2, NULL }, + { "XC_NICKFAIL", "Nick Failed", 0, NULL }, + { "XC_NODCC", "No DCC", 0, NULL }, + { "XC_NOCHILD", "No Running Process", 0, NULL }, + { "XC_NOTICE", "Notice", 2, NULL }, + { "XC_NOTICESEND", "Notice Send", 2, NULL }, + { "XC_NOTIFYEMPTY", "Notify Empty", 0, NULL }, + { "XC_NOTIFYHEAD", "Notify Header", 0, NULL }, + { "XC_NOTIFYNUMBER", "Notify Number", 1, NULL }, + { "XC_NOTIFYOFFLINE", "Notify Offline", 3, NULL }, + { "XC_NOTIFYONLINE", "Notify Online", 3, NULL }, + { "XC_OPENDIALOG", "Open Dialog", 0, NULL }, + { "XC_PART", "Part", 3, NULL }, + { "XC_PARTREASON", "Part with Reason", 4, NULL }, + { "XC_PINGREP", "Ping Reply", 2, NULL }, + { "XC_PINGTIMEOUT", "Ping Timeout", 1, NULL }, + { "XC_PRIVMSG", "Private Message", 3, NULL }, + { "XC_DPRIVMSG", "Private Message to Dialog", 3, NULL }, + { "XC_ALREADYPROCESS", "Process Already Running", 0, NULL }, + { "XC_QUIT", "Quit", 3, NULL }, + { "XC_RAWMODES", "Raw Modes", 2, NULL }, + { "XC_WALLOPS", "Receive Wallops", 2, NULL }, + { "XC_RESOLVINGUSER", "Resolving User", 2, NULL }, + { "XC_SERVERCONNECTED", "Server Connected", 0, NULL }, + { "XC_SERVERERROR", "Server Error", 1, NULL }, + { "XC_SERVERLOOKUP", "Server Lookup", 1, NULL }, + { "XC_SERVNOTICE", "Server Notice", 2, NULL }, + { "XC_SERVTEXT", "Server Text", 2, NULL }, + { "XC_STOPCONNECT", "Stop Connection", 1, NULL }, + { "XC_TOPIC", "Topic", 2, NULL }, + { "XC_NEWTOPIC", "Topic Change", 3, NULL }, + { "XC_TOPICDATE", "Topic Creation", 3, NULL }, + { "XC_UKNHOST", "Unknown Host", 0, NULL }, + { "XC_USERLIMIT", "User Limit", 1, NULL }, + { "XC_USERSONCHAN", "Users On Channel", 2, NULL }, + { "XC_WHOIS_AUTH", "WhoIs Authenticated", 3, NULL }, + { "XC_WHOIS5", "WhoIs Away Line", 2, NULL }, + { "XC_WHOIS2", "WhoIs Channel/Oper Line", 2, NULL }, + { "XC_WHOIS6", "WhoIs End", 1, NULL }, + { "XC_WHOIS_ID", "WhoIs Identified", 2, NULL }, + { "XC_WHOIS4", "WhoIs Idle Line", 2, NULL }, + { "XC_WHOIS4T", "WhoIs Idle Line with Signon", 3, NULL }, + { "XC_WHOIS1", "WhoIs Name Line", 4, NULL }, + { "XC_WHOIS_REALHOST", "WhoIs Real Host", 4, NULL }, + { "XC_WHOIS3", "WhoIs Server Line", 2, NULL }, + { "XC_WHOIS_SPECIAL", "WhoIs Special", 3, NULL }, + { "XC_UJOIN", "You Join", 3, NULL }, + { "XC_UKICK", "You Kicked", 4, NULL }, + { "XC_UPART", "You Part", 3, NULL }, + { "XC_UPARTREASON", "You Part with Reason", 4, NULL }, + { "XC_UACTION", "Your Action", 3, NULL }, + { "XC_UINVITE", "Your Invitation", 3, NULL }, + { "XC_UCHANMSG", "Your Message", 4, NULL }, + { "XC_UCHANGENICK", "Your Nick Changing", 2, NULL } +}; + diff --git a/plugins/tcl/tclplugin.c b/plugins/tcl/tclplugin.c new file mode 100644 index 00000000..17dc7556 --- /dev/null +++ b/plugins/tcl/tclplugin.c @@ -0,0 +1,2290 @@ +/*************************************************************************** + tclplugin.c - Tcl plugin for xchat 1.9.x / 2.x.x + -------------------------------------------------s + begin : Sat Nov 19 17:31:20 MST 2002 + copyright : Copyright 2002-2010 Daniel P. Stasinski + email : daniel@avenues.org + ***************************************************************************/ + +/*************************************************************************** + * * + * 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. * + * * + ***************************************************************************/ + +static char RCSID[] = "$Id: tclplugin.c,v 1.64 2010/03/10 04:24:16 mooooooo Exp $"; + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <limits.h> +#include <ctype.h> +#include <stdarg.h> +#include <tcl.h> +#include <tclDecls.h> +#include <sys/stat.h> + +#ifdef WIN32 +#include <windows.h> +#define bzero(mem, sz) memset((mem), 0, (sz)) +#define bcopy(src, dest, count) memmove((dest), (src), (count)) +#else +#include <unistd.h> +#endif + +#include "xchat-plugin.h" +#include "tclplugin.h" +#include "printevents.h" + +static int nexttimerid = 0; +static int nexttimerindex = 0; +static timer timers[MAX_TIMERS]; + +static char VERSION[16]; + +static int initialized = 0; +static int reinit_tried = 0; +static Tcl_Interp *interp = NULL; +static xchat_plugin *ph; +static xchat_hook *raw_line_hook; +static xchat_hook *Command_TCL_hook; +static xchat_hook *Command_Source_hook; +static xchat_hook *Command_Reload_hook; +static xchat_hook *Command_Load_hook; +static xchat_hook *Event_Handler_hook; +static xchat_hook *Null_Command_hook; + +static int complete_level = 0; +static t_complete complete[MAX_COMPLETES + 1]; +static Tcl_HashTable cmdTablePtr; +static Tcl_HashTable aliasTablePtr; + +static int nextprocid = 0x1000; +#define PROCPREFIX "__xctcl_" + +static char unknown[] = { +"rename unknown iunknown\n" +"proc ::unknown {args} {\n" +" global errorInfo errorCode\n" +" if { [string index [lindex $args 0] 0] == \"/\" } {\n" +" command \"[string range [join $args \" \"] 1 end]\"\n" +" } else {\n" +" set code [catch {uplevel iunknown $args} msg]\n" +" if {$code == 1} {\n" +" set new [split $errorInfo \\n]\n" +" set new [join [lrange $new 0 [expr {[llength $new] - 8}]] \\n]\n" +" return -code error -errorcode $errorCode -errorinfo $new $msg\n" +" } else {\n" +" return -code $code $msg\n" +" }\n" +" }\n" +"}\n" +"proc unsupported0 {from to {bytes \"\"}} {\n" +" set b [expr {$bytes == \"\" ? \"\" : \"-size [list $bytes]\"}]\n" +" eval [list fcopy $from $to] $b\n" +"}\n" +}; + +static char sourcedirs[] = { + "set files [lsort [glob -nocomplain -directory [xchatdir] \"*.tcl\"]]\n" + "set init [lsearch -glob $files \"*/init.tcl\"]\n" + "if { $init > 0 } {\n" + "set initfile [lindex $files $init]\n" + "set files [lreplace $files $init $init]\n" + "set files [linsert $files 0 $initfile]\n" "}\n" "foreach f $files {\n" "if { [catch { source $f } errMsg] } {\n" "puts \"Tcl plugin\\tError sourcing \\\"$f\\\" ($errMsg)\"\n" "} else {\n" "puts \"Tcl plugin\\tSourced \\\"$f\\\"\"\n" "}\n" "}\n" +}; + +static char inlinetcl[] = { +"proc splitsrc { } {\n" +"uplevel \"scan \\$_src \\\"%\\\\\\[^!\\\\\\]!%\\\\\\[^@\\\\\\]@%s\\\" _nick _ident _host\"\n" +"}\n" + +"proc ::exit { } {\n" +"puts \"Using 'exit' is bad\"\n" +"}\n" + +"proc ::away { args } { return [eval [join [list getinfo $args away]]] }\n" +"proc ::channel { args } { return [eval [join [list getinfo $args channel]]] }\n" +"proc ::tab { args } { return [eval [join [list getinfo $args channel]]] }\n" +"proc ::charset { args } { return [eval [join [list getinfo $args charset]]] }\n" +"proc ::host { args } { return [eval [join [list getinfo $args host]]] }\n" +"proc ::inputbox { args } { return [eval [join [list getinfo $args inputbox]]] }\n" +"proc ::libdirfs { args } { return [eval [join [list getinfo $args libdirfs]]] }\n" +"proc ::network { args } { return [eval [join [list getinfo $args network]]] }\n" +"proc ::nickserv { args } { return [eval [join [list getinfo $args nickserv]]] }\n" +"proc ::server { args } { return [eval [join [list getinfo $args server]]] }\n" +"proc ::version { args } { return [eval [join [list getinfo $args version]]] }\n" +"proc ::win_status { args } { return [eval [join [list getinfo $args win_status]]] }\n" +"proc ::xchatdir { args } { return [eval [join [list getinfo $args xchatdir]]] }\n" +"proc ::xchatdirfs { args } { return [eval [join [list getinfo $args xchatdirfs]]] }\n" + +"proc ::color { {arg {}} } { return \"\\003$arg\" }\n" +"proc ::bold { } { return \"\\002\" }\n" +"proc ::underline { } { return \"\\037\" }\n" +"proc ::reverse { } { return \"\\026\" }\n" +"proc ::reset { } { return \"\\017\" }\n" + +"proc ::__xctcl_errorInfo { } {\n" +" set text [split $::errorInfo \\n]\n" +" puts [string trim [join [lrange $text 0 [expr {[llength $text] - 4}]] \\n]]\n" +"}\n" + +"proc ::bgerror { message } {\n" +" set text [split $::errorInfo \\n]\n" +" puts [string trim [join [lrange $text 0 [expr {[llength $text] - 4}]] \\n]]\n" +"}\n" +}; + +static void NiceErrorInfo () +{ + Tcl_Eval(interp, "::__xctcl_errorInfo"); +} + +static void Tcl_MyDStringAppend(Tcl_DString * ds, char *string) +{ + Tcl_DStringAppend(ds, string, strlen(string)); +} + +static char *InternalProcName(int value) +{ + static char result[32]; + sprintf(result, "%s%08x", PROCPREFIX, value); + return result; +} + +static int SourceInternalProc(int id, const char *args, const char *source) +{ + Tcl_DString ds; + int result; + Tcl_DStringInit(&ds); + + Tcl_MyDStringAppend(&ds, "proc "); + Tcl_MyDStringAppend(&ds, InternalProcName(id)); + Tcl_MyDStringAppend(&ds, " { "); + Tcl_MyDStringAppend(&ds, args); + Tcl_MyDStringAppend(&ds, " } {\n"); + Tcl_MyDStringAppend(&ds, source); + Tcl_MyDStringAppend(&ds, "\n}\n\n"); + + result = Tcl_Eval(interp, ds.string); + + Tcl_DStringFree(&ds); + + return result; +} + +static int EvalInternalProc(const char *procname, int ct, ...) +{ + Tcl_DString ds; + int result; + va_list ap; + char *buf; + + Tcl_DStringInit(&ds); + + Tcl_MyDStringAppend(&ds, procname); + + if (ct) { + va_start(ap, ct); + while (ct--) { + if ((buf = va_arg(ap, char *)) != NULL) + Tcl_DStringAppendElement(&ds, buf); + else + Tcl_MyDStringAppend(&ds, " \"\""); + } + va_end(ap); + } + + result = Tcl_Eval(interp, ds.string); + + Tcl_DStringFree(&ds); + + return result; +} + + +static void DeleteInternalProc(const char *proc) +{ + Tcl_DString ds; + + Tcl_DStringInit(&ds); + Tcl_MyDStringAppend(&ds, "rename "); + Tcl_MyDStringAppend(&ds, proc); + Tcl_MyDStringAppend(&ds, " {}"); + Tcl_Eval(interp, ds.string); + Tcl_DStringFree(&ds); +} + +static char *StrDup(const char *string, int *length) +{ + char *result; + + if (string == NULL) + return NULL; + + *length = strlen(string); + result = Tcl_Alloc(*length + 1); + strncpy(result, string, *length); + result[*length] = 0; + + return result; +} + +static char *myitoa(long value) +{ + static char result[32]; + sprintf(result, "%ld", value); + return result; +} + +static xchat_context *atoctx(const char *nptr) +{ + int isnum = 1; + int x = 0; + + if (!nptr) + return NULL; + + while (isnum && nptr[x]) { + if (!isdigit(nptr[x++])) + isnum--; + } + + if (isnum && x) + return (xchat_context *) atol(nptr); + else + return NULL; +} + +static xchat_context *xchat_smart_context(const char *arg1, const char *arg2) +{ + const char *server, *s, *n; + xchat_context *result = NULL; + xchat_context *ctx = NULL; + xchat_context *actx = NULL; + xchat_list *list; + + if (arg1 == NULL) + return xchat_get_context(ph);; + + if (arg1 && arg2) { + result = xchat_find_context(ph, arg1, arg2); + if (result == NULL) + result = xchat_find_context(ph, arg2, arg1); + return result; + } else { + + actx = atoctx(arg1); + + server = xchat_get_info(ph, "server"); + + list = xchat_list_get(ph, "channels"); + + if (list != NULL) { + + while (xchat_list_next(ph, list)) { + + ctx = (xchat_context *)xchat_list_str(ph, list, "context"); + + if (actx) { + if (ctx == actx) { + result = ctx; + break; + } + } else { + + s = xchat_list_str(ph, list, "server"); + + if (xchat_list_int(ph, list, "type") == 1) { + if (strcasecmp(arg1, s) == 0) { + result = ctx; + break; + } + n = xchat_list_str(ph, list, "network"); + if (n) { + if (strcasecmp(arg1, n) == 0) { + result = ctx; + break; + } + } + } else { + if ((strcasecmp(server, s) == 0) && (strcasecmp(arg1, xchat_list_str(ph, list, "channel")) == 0)) { + result = ctx; + break; + } + } + } + } + + xchat_list_free(ph, list); + } + + } + + return result; +} + +static void queue_nexttimer() +{ + int x; + time_t then; + + nexttimerindex = 0; + then = (time_t) 0x7fffffff; + + for (x = 1; x < MAX_TIMERS; x++) { + if (timers[x].timerid) { + if (timers[x].timestamp < then) { + then = timers[x].timestamp; + nexttimerindex = x; + } + } + } +} + +static int insert_timer(int seconds, int count, const char *script) +{ + int x; + int dummy; + time_t now; + int id; + + if (script == NULL) + return (-1); + + id = (nextprocid++ % INT_MAX) + 1; + + now = time(NULL); + + for (x = 1; x < MAX_TIMERS; x++) { + if (timers[x].timerid == 0) { + if (SourceInternalProc(id, "", script) == TCL_ERROR) { + xchat_printf(ph, "\0039TCL plugin\003\tERROR (timer %d) ", timers[x].timerid); + NiceErrorInfo (); + return (-1); + } + timers[x].timerid = (nexttimerid++ % INT_MAX) + 1; + timers[x].timestamp = now + seconds; + timers[x].count = count; + timers[x].seconds = seconds; + timers[x].procPtr = StrDup(InternalProcName(id), &dummy); + queue_nexttimer(); + return (timers[x].timerid); + } + } + + return (-1); +} + +static void do_timer() +{ + xchat_context *origctx; + time_t now; + int index; + + if (!nexttimerindex) + return; + + now = time(NULL); + + if (now < timers[nexttimerindex].timestamp) + return; + + index = nexttimerindex; + origctx = xchat_get_context(ph); + if (EvalInternalProc(timers[index].procPtr, 0) == TCL_ERROR) { + xchat_printf(ph, "\0039TCL plugin\003\tERROR (timer %d) ", timers[index].timerid); + NiceErrorInfo (); + } + xchat_set_context(ph, origctx); + + if (timers[index].count != -1) + timers[index].count--; + + if (timers[index].count == 0) { + timers[index].timerid = 0; + if (timers[index].procPtr != NULL) { + DeleteInternalProc(timers[index].procPtr); + Tcl_Free(timers[index].procPtr); + } + timers[index].procPtr = NULL; + } else { + timers[index].timestamp += timers[index].seconds; + } + + queue_nexttimer(); + + return; + +} + +static int Server_raw_line(char *word[], char *word_eol[], void *userdata) +{ + char *src, *cmd, *dest, *rest; + char *chancmd = NULL; + char *procList; + Tcl_HashEntry *entry = NULL; + xchat_context *origctx; + int len; + int dummy; + char *string = NULL; + int ctcp = 0; + int count; + int list_argc, proc_argc; + const char **list_argv, **proc_argv; + int private = 0; + + if (word[0][0] == 0) + return XCHAT_EAT_NONE; + + if (complete_level == MAX_COMPLETES) + return XCHAT_EAT_NONE; + + complete_level++; + complete[complete_level].defresult = XCHAT_EAT_NONE; /* XCHAT_EAT_PLUGIN; */ + complete[complete_level].result = XCHAT_EAT_NONE; + complete[complete_level].word = word; + complete[complete_level].word_eol = word_eol; + + if (word[1][0] == ':') { + src = word[1]; + cmd = word[2]; + dest = word[3]; + rest = word_eol[4]; + } else { + src = ""; + cmd = word[1]; + if (word_eol[2][0] == ':') { + dest = ""; + rest = word_eol[2]; + } else { + dest = word[2]; + rest = word_eol[3]; + } + } + + if (src[0] == ':') + src++; + if (dest[0] == ':') + dest++; + if (rest[0] == ':') + rest++; + + if (rest[0] == 0x01) { + rest++; + if (strcasecmp("PRIVMSG", cmd) == 0) { + if (strncasecmp(rest, "ACTION ", 7) == 0) { + cmd = "ACTION"; + rest += 7; + } else + cmd = "CTCP"; + } else if (!strcasecmp("NOTICE", cmd)) + cmd = "CTCR"; + ctcp = 1; + } else if (!strcasecmp("NOTICE", cmd) && (strchr(src, '!') == NULL)) { + cmd = "SNOTICE"; + } else if (rest[0] == '!') { + chancmd = word[4] + 1; + } + + if (chancmd != NULL) { + string = StrDup(chancmd, &dummy); + Tcl_UtfToUpper(string); + if ((entry = Tcl_FindHashEntry(&cmdTablePtr, string)) == NULL) { + Tcl_Free(string); + } else { + cmd = chancmd; + rest = word_eol[5]; + } + } + + if (entry == NULL) { + string = StrDup(cmd, &dummy); + Tcl_UtfToUpper(string); + entry = Tcl_FindHashEntry(&cmdTablePtr, string); + } + + if (entry != NULL) { + + procList = Tcl_GetHashValue(entry); + + if (isalpha(dest[0])) + private = 1; + + rest = StrDup(rest, &len); + if (ctcp) { + if (rest != NULL) { + if ((len > 1) && (rest[len - 1] == 0x01)) + rest[len - 1] = 0; + } + } + + if (Tcl_SplitList(interp, procList, &list_argc, &list_argv) == TCL_OK) { + + for (count = 0; count < list_argc; count++) { + + if (Tcl_SplitList(interp, list_argv[count], &proc_argc, &proc_argv) != TCL_OK) + continue; + + origctx = xchat_get_context(ph); + if (EvalInternalProc(proc_argv[1], 7, src, dest, cmd, rest, word_eol[1], proc_argv[0], myitoa(private)) == TCL_ERROR) { + xchat_printf(ph, "\0039TCL plugin\003\tERROR (on %s %s) ", cmd, proc_argv[0]); + NiceErrorInfo (); + } + xchat_set_context(ph, origctx); + + Tcl_Free((char *) proc_argv); + + if ((complete[complete_level].result == XCHAT_EAT_PLUGIN) || (complete[complete_level].result == XCHAT_EAT_ALL)) + break; + + } + + Tcl_Free((char *) list_argv); + + } + + Tcl_Free(rest); + + } + + if (string) + Tcl_Free(string); + + return complete[complete_level--].result; + +} + +static int Print_Hook(char *word[], void *userdata) +{ + char *procList; + Tcl_HashEntry *entry; + xchat_context *origctx; + int count; + int list_argc, proc_argc; + const char **list_argv, **proc_argv; + Tcl_DString ds; + int x; + + if (complete_level == MAX_COMPLETES) + return XCHAT_EAT_NONE; + + complete_level++; + complete[complete_level].defresult = XCHAT_EAT_NONE; /* XCHAT_EAT_PLUGIN; */ + complete[complete_level].result = XCHAT_EAT_NONE; + complete[complete_level].word = word; + complete[complete_level].word_eol = word; + + if ((entry = Tcl_FindHashEntry(&cmdTablePtr, xc[(int) userdata].event)) != NULL) { + + procList = Tcl_GetHashValue(entry); + + if (Tcl_SplitList(interp, procList, &list_argc, &list_argv) == TCL_OK) { + + for (count = 0; count < list_argc; count++) { + + if (Tcl_SplitList(interp, list_argv[count], &proc_argc, &proc_argv) != TCL_OK) + continue; + + origctx = xchat_get_context(ph); + + Tcl_DStringInit(&ds); + + if ((int) userdata == CHAT) { + Tcl_DStringAppend(&ds, word[3], strlen(word[3])); + Tcl_DStringAppend(&ds, "!*@", 3); + Tcl_DStringAppend(&ds, word[1], strlen(word[1])); + if (EvalInternalProc(proc_argv[1], 7, ds.string, word[2], xc[(int) userdata].event, word[4], "", proc_argv[0], "0") == TCL_ERROR) { + xchat_printf(ph, "\0039TCL plugin\003\tERROR (on %s %s) ", xc[(int) userdata].event, proc_argv[0]); + NiceErrorInfo (); + } + } else { + if (xc[(int) userdata].argc > 0) { + for (x = 0; x <= xc[(int) userdata].argc; x++) + Tcl_DStringAppendElement(&ds, word[x]); + } + if (EvalInternalProc(proc_argv[1], 7, "", "", xc[(int) userdata].event, "", ds.string, proc_argv[0], "0") == TCL_ERROR) { + xchat_printf(ph, "\0039Tcl plugin\003\tERROR (on %s %s) ", xc[(int) userdata].event, proc_argv[0]); + NiceErrorInfo (); + } + } + + Tcl_DStringFree(&ds); + + xchat_set_context(ph, origctx); + + Tcl_Free((char *) proc_argv); + + if ((complete[complete_level].result == XCHAT_EAT_PLUGIN) || (complete[complete_level].result == XCHAT_EAT_ALL)) + break; + + } + + Tcl_Free((char *) list_argv); + + } + } + + return complete[complete_level--].result; +} + + +static int tcl_timerexists(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + int x; + int timerid; + + BADARGS(2, 2, " schedid"); + + if (Tcl_GetInt(irp, argv[1], &timerid) != TCL_OK) { + Tcl_AppendResult(irp, "Invalid timer id", NULL); + return TCL_ERROR; + } + + if (timerid) { + for (x = 1; x < MAX_TIMERS; x++) { + if (timers[x].timerid == timerid) { + Tcl_AppendResult(irp, "1", NULL); + return TCL_OK; + } + } + } + + Tcl_AppendResult(irp, "0", NULL); + + return TCL_OK; +} + +static int tcl_killtimer(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + int x; + int timerid; + + BADARGS(2, 2, " timerid"); + + if (Tcl_GetInt(irp, argv[1], &timerid) != TCL_OK) { + Tcl_AppendResult(irp, "Invalid timer id", NULL); + return TCL_ERROR; + } + + if (timerid) { + for (x = 1; x < MAX_TIMERS; x++) { + if (timers[x].timerid == timerid) { + timers[x].timerid = 0; + if (timers[x].procPtr != NULL) { + DeleteInternalProc(timers[x].procPtr); + Tcl_Free(timers[x].procPtr); + } + timers[x].procPtr = NULL; + break; + } + } + } + + queue_nexttimer(); + + return TCL_OK; +} + +static int tcl_timers(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + int x; + Tcl_DString ds; + time_t now; + + BADARGS(1, 1, ""); + + now = time(NULL); + + Tcl_DStringInit(&ds); + + for (x = 1; x < MAX_TIMERS; x++) { + if (timers[x].timerid) { + Tcl_DStringStartSublist(&ds); + Tcl_DStringAppendElement(&ds, myitoa((long)timers[x].timerid)); + Tcl_DStringAppendElement(&ds, myitoa((long)timers[x].timestamp - now)); + Tcl_DStringAppendElement(&ds, timers[x].procPtr); + Tcl_DStringAppendElement(&ds, myitoa((long)timers[x].seconds)); + Tcl_DStringAppendElement(&ds, myitoa((long)timers[x].count)); + Tcl_DStringEndSublist(&ds); + } + } + + Tcl_AppendResult(interp, ds.string, NULL); + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +static int tcl_timer(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + int seconds; + int timerid; + int repeat = 0; + int count = 0; + int first = 1; + char reply[32]; + + BADARGS(3, 6, " ?-repeat? ?-count times? seconds {script | procname ?args?}"); + + while (argc--) { + if (strcasecmp(argv[first], "-repeat") == 0) { + repeat++; + } else if (strcasecmp(argv[first], "-count") == 0) { + if (Tcl_GetInt(irp, argv[++first], &count) != TCL_OK) + return TCL_ERROR; + } else { + break; + } + first++; + } + + if (repeat && !count) + count = -1; + + if (!count) + count = 1; + + if (Tcl_GetInt(irp, argv[first++], &seconds) != TCL_OK) + return TCL_ERROR; + + if ((timerid = insert_timer(seconds, count, argv[first++])) == -1) { + Tcl_AppendResult(irp, "0", NULL); + return TCL_ERROR; + } + + sprintf(reply, "%d", timerid); + + Tcl_AppendResult(irp, reply, NULL); + + queue_nexttimer(); + + return TCL_OK; +} + +static int tcl_on(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + int newentry; + char *procList; + Tcl_HashEntry *entry; + char *token; + int dummy; + Tcl_DString ds; + int index; + int count; + int list_argc, proc_argc; + int id; + const char **list_argv, **proc_argv; + + BADARGS(4, 4, " token label {script | procname ?args?}"); + + id = (nextprocid++ % INT_MAX) + 1; + + if (SourceInternalProc(id, "_src _dest _cmd _rest _raw _label _private", argv[3]) == TCL_ERROR) { + xchat_printf(ph, "\0039Tcl plugin\003\tERROR (on %s:%s) ", argv[1], argv[2]); + NiceErrorInfo (); + return TCL_OK; + } + + token = StrDup(argv[1], &dummy); + Tcl_UtfToUpper(token); + + Tcl_DStringInit(&ds); + + entry = Tcl_CreateHashEntry(&cmdTablePtr, token, &newentry); + if (!newentry) { + procList = Tcl_GetHashValue(entry); + if (Tcl_SplitList(interp, procList, &list_argc, &list_argv) == TCL_OK) { + for (count = 0; count < list_argc; count++) { + if (Tcl_SplitList(interp, list_argv[count], &proc_argc, &proc_argv) != TCL_OK) + continue; + if (strcmp(proc_argv[0], argv[2])) { + Tcl_DStringStartSublist(&ds); + Tcl_DStringAppendElement(&ds, proc_argv[0]); + Tcl_DStringAppendElement(&ds, proc_argv[1]); + Tcl_DStringEndSublist(&ds); + } else { + DeleteInternalProc(proc_argv[1]); + } + Tcl_Free((char *) proc_argv); + } + Tcl_Free((char *) list_argv); + } + Tcl_Free(procList); + } + + Tcl_DStringStartSublist(&ds); + Tcl_DStringAppendElement(&ds, argv[2]); + Tcl_DStringAppendElement(&ds, InternalProcName(id)); + Tcl_DStringEndSublist(&ds); + + procList = StrDup(ds.string, &dummy); + + Tcl_SetHashValue(entry, procList); + + if ((strncmp(token, "XC_", 3) == 0) || (strcmp(token, "CHAT") == 0)) { + for (index = 0; index < XC_SIZE; index++) { + if (strcmp(xc[index].event, token) == 0) { + if (xc[index].hook == NULL) { + xc[index].hook = xchat_hook_print(ph, xc[index].emit, XCHAT_PRI_NORM, Print_Hook, (void *) index); + break; + } + } + } + } + + Tcl_Free(token); + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +static int tcl_off(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + char *procList; + Tcl_HashEntry *entry; + char *token; + int dummy; + Tcl_DString ds; + int index; + int count; + int list_argc, proc_argc; + const char **list_argv, **proc_argv; + + BADARGS(2, 3, " token ?label?"); + + token = StrDup(argv[1], &dummy); + Tcl_UtfToUpper(token); + + Tcl_DStringInit(&ds); + + if ((entry = Tcl_FindHashEntry(&cmdTablePtr, token)) != NULL) { + + procList = Tcl_GetHashValue(entry); + + if (argc == 3) { + if (Tcl_SplitList(interp, procList, &list_argc, &list_argv) == TCL_OK) { + for (count = 0; count < list_argc; count++) { + if (Tcl_SplitList(interp, list_argv[count], &proc_argc, &proc_argv) != TCL_OK) + continue; + if (strcmp(proc_argv[0], argv[2])) { + Tcl_DStringStartSublist(&ds); + Tcl_DStringAppendElement(&ds, proc_argv[0]); + Tcl_DStringAppendElement(&ds, proc_argv[1]); + Tcl_DStringEndSublist(&ds); + } else + DeleteInternalProc(proc_argv[1]); + Tcl_Free((char *) proc_argv); + } + Tcl_Free((char *) list_argv); + } + } + + Tcl_Free(procList); + + if (ds.length) { + procList = StrDup(ds.string, &dummy); + Tcl_SetHashValue(entry, procList); + } else { + Tcl_DeleteHashEntry(entry); + } + + if (!ds.length) { + if ((strncmp(token, "XC_", 3) == 0) || (strcmp(token, "CHAT") == 0)) { + for (index = 0; index < XC_SIZE; index++) { + if (strcmp(xc[index].event, token) == 0) { + if (xc[index].hook != NULL) { + xchat_unhook(ph, xc[index].hook); + xc[index].hook = NULL; + break; + } + } + } + } + } + } + + Tcl_Free(token); + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +static int tcl_alias(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + int newentry; + alias *aliasPtr; + Tcl_HashEntry *entry; + char *string; + const char *help = NULL; + int dummy; + int id; + + BADARGS(3, 4, " name ?help? {script | procname ?args?}"); + + string = StrDup(argv[1], &dummy); + Tcl_UtfToUpper(string); + + if (strlen(argv[argc - 1])) { + + if (argc == 4) + help = argv[2]; + + id = (nextprocid++ % INT_MAX) + 1; + + if (SourceInternalProc(id, "_cmd _rest", argv[argc - 1]) == TCL_ERROR) { + xchat_printf(ph, "\0039Tcl plugin\003\tERROR (alias %s) ", argv[1]); + NiceErrorInfo (); + return TCL_OK; + } + + entry = Tcl_CreateHashEntry(&aliasTablePtr, string, &newentry); + if (newentry) { + aliasPtr = (alias *) Tcl_Alloc(sizeof(alias)); + if (string[0] == '@') + aliasPtr->hook = NULL; + else + aliasPtr->hook = xchat_hook_command(ph, string, XCHAT_PRI_NORM, Command_Alias, help, 0); + } else { + aliasPtr = Tcl_GetHashValue(entry); + DeleteInternalProc(aliasPtr->procPtr); + Tcl_Free(aliasPtr->procPtr); + } + + aliasPtr->procPtr = StrDup(InternalProcName(id), &dummy); + + Tcl_SetHashValue(entry, aliasPtr); + + } else { + + if ((entry = Tcl_FindHashEntry(&aliasTablePtr, string)) != NULL) { + aliasPtr = Tcl_GetHashValue(entry); + DeleteInternalProc(aliasPtr->procPtr); + Tcl_Free(aliasPtr->procPtr); + if (aliasPtr->hook) + xchat_unhook(ph, aliasPtr->hook); + Tcl_Free((char *) aliasPtr); + Tcl_DeleteHashEntry(entry); + } + } + + Tcl_Free(string); + + return TCL_OK; +} + +static int tcl_complete(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + BADARGS(1, 2, " ?EAT_NONE|EAT_XCHAT|EAT_PLUGIN|EAT_ALL?"); + + if (argc == 2) { + if (Tcl_GetInt(irp, argv[1], &complete[complete_level].result) != TCL_OK) { + if (strcasecmp("EAT_NONE", argv[1]) == 0) + complete[complete_level].result = XCHAT_EAT_NONE; + else if (strcasecmp("EAT_XCHAT", argv[1]) == 0) + complete[complete_level].result = XCHAT_EAT_XCHAT; + else if (strcasecmp("EAT_PLUGIN", argv[1]) == 0) + complete[complete_level].result = XCHAT_EAT_PLUGIN; + else if (strcasecmp("EAT_ALL", argv[1]) == 0) + complete[complete_level].result = XCHAT_EAT_ALL; + else + BADARGS(1, 2, " ?EAT_NONE|EAT_XCHAT|EAT_PLUGIN|EAT_ALL?"); + } + } else + complete[complete_level].result = complete[complete_level].defresult; + + return TCL_RETURN; +} + +static int tcl_command(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_context *origctx; + xchat_context *ctx = NULL; + const char *string = NULL; + + BADARGS(2, 4, " ?server|network|context? ?#channel|nick? text"); + + origctx = xchat_get_context(ph); + + switch (argc) { + case 2: + ctx = origctx; + break; + case 3: + ctx = xchat_smart_context(argv[1], NULL); + break; + case 4: + ctx = xchat_smart_context(argv[1], argv[2]); + break; + default:; + } + + CHECKCTX(ctx); + + string = argv[argc - 1]; + + if (string[0] == '/') + string++; + + xchat_set_context(ph, ctx); + xchat_command(ph, string); + xchat_set_context(ph, origctx); + + return TCL_OK; +} + +static int tcl_raw(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_context *origctx; + xchat_context *ctx = NULL; + const char *string = NULL; + + BADARGS(2, 4, " ?server|network|context? ?#channel|nick? text"); + + origctx = xchat_get_context(ph); + + switch (argc) { + case 2: + ctx = origctx; + break; + case 3: + ctx = xchat_smart_context(argv[1], NULL); + break; + case 4: + ctx = xchat_smart_context(argv[1], argv[2]); + break; + default:; + } + + CHECKCTX(ctx); + + string = argv[argc - 1]; + + xchat_set_context(ph, ctx); + xchat_commandf(ph, "RAW %s", string); + xchat_set_context(ph, origctx); + + return TCL_OK; +} + + +static int tcl_prefs(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + int i; + const char *str; + + BADARGS(2, 2, " name"); + + switch (xchat_get_prefs (ph, argv[1], &str, &i)) { + case 1: + Tcl_AppendResult(irp, str, NULL); + break; + case 2: + case 3: + Tcl_AppendResult(irp, myitoa(i), NULL); + break; + default: + Tcl_AppendResult(irp, NULL); + } + + return TCL_OK; +} + +static int tcl_info(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[], char *id) +{ + char *result; + int max_argc; + xchat_context *origctx, *ctx; + + if (id == NULL) { + BADARGS(2, 3, " ?server|network|context? id"); + max_argc = 3; + } else { + BADARGS(1, 2, " ?server|network|context?"); + max_argc = 2; + } + + origctx = xchat_get_context(ph); + + if (argc == max_argc) { + ctx = xchat_smart_context(argv[1], NULL); + CHECKCTX(ctx); + xchat_set_context(ph, ctx); + } + + if (id == NULL) + id = argv[argc-1]; + + if ((result = xchat_get_info(ph, id)) == NULL) + result = ""; + + Tcl_AppendResult(irp, result, NULL); + + xchat_set_context(ph, origctx); + + return TCL_OK; +} + +static int tcl_me(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + return tcl_info(cd, irp, argc, argv, "nick"); +} + +static int tcl_getinfo(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + return tcl_info(cd, irp, argc, argv, NULL); +} + +static int tcl_getlist(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_list *list = NULL; + const char *name = NULL; + const char * const *fields; + const char *field; + const char *sattr; + int iattr; + int i; + time_t t; + Tcl_DString ds; + xchat_context *origctx; + xchat_context *ctx = NULL; + + origctx = xchat_get_context(ph); + + BADARGS(1, 2, " list"); + + Tcl_DStringInit(&ds); + + fields = xchat_list_fields(ph, "lists"); + + if (argc == 1) { + for (i = 0; fields[i] != NULL; i++) { + Tcl_DStringAppendElement(&ds, fields[i]); + } + goto done; + } + + for (i = 0; fields[i] != NULL; i++) { + if (strcmp(fields[i], argv[1]) == 0) { + name = fields[i]; + break; + } + } + + if (name == NULL) + goto done; + + list = xchat_list_get(ph, name); + if (list == NULL) + goto done; + + fields = xchat_list_fields(ph, name); + + Tcl_DStringStartSublist(&ds); + for (i = 0; fields[i] != NULL; i++) { + field = fields[i] + 1; + Tcl_DStringAppendElement(&ds, field); + } + Tcl_DStringEndSublist(&ds); + + while (xchat_list_next(ph, list)) { + + Tcl_DStringStartSublist(&ds); + + for (i = 0; fields[i] != NULL; i++) { + + field = fields[i] + 1; + + switch (fields[i][0]) { + case 's': + sattr = xchat_list_str(ph, list, (char *) field); + Tcl_DStringAppendElement(&ds, sattr); + break; + case 'i': + iattr = xchat_list_int(ph, list, (char *) field); + Tcl_DStringAppendElement(&ds, myitoa((long)iattr)); + break; + case 't': + t = xchat_list_time(ph, list, (char *) field); + Tcl_DStringAppendElement(&ds, myitoa((long)t)); + break; + case 'p': + sattr = xchat_list_str(ph, list, (char *) field); + if (strcmp(field, "context") == 0) { + ctx = (xchat_context *) sattr; + Tcl_DStringAppendElement(&ds, myitoa((long)ctx)); + } else + Tcl_DStringAppendElement(&ds, "*"); + break; + default: + Tcl_DStringAppendElement(&ds, "*"); + break; + } + } + + Tcl_DStringEndSublist(&ds); + + } + + xchat_list_free(ph, list); + + done: + + xchat_set_context(ph, origctx); + + Tcl_AppendResult(irp, ds.string, NULL); + + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +/* + * tcl_xchat_puts - stub for tcl puts command + * This is modified from the original internal "puts" command. It redirects + * stdout to the current context, while still allowing all normal puts features + */ + +static int tcl_xchat_puts(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + Tcl_Channel chan; + const char *string; + int newline; + const char *channelId = NULL; + int result; + int mode; + int trap_stdout = 0; + + switch (argc) { + + case 2: + string = argv[1]; + newline = 1; + trap_stdout = 1; + break; + + case 3: + if (strcmp(argv[1], "-nonewline") == 0) { + newline = 0; + trap_stdout = 1; + } else { + newline = 1; + channelId = argv[1]; + } + string = argv[2]; + break; + + case 4: + if (strcmp(argv[1], "-nonewline") == 0) { + channelId = argv[2]; + string = argv[3]; + } else { + if (strcmp(argv[3], "nonewline") != 0) { + Tcl_AppendResult(interp, "bad argument \"", argv[3], "\": should be \"nonewline\"", (char *) NULL); + return TCL_ERROR; + } + channelId = argv[1]; + string = argv[2]; + } + newline = 0; + break; + + default: + Tcl_AppendResult(interp, argv, "?-nonewline? ?channelId? string", NULL); + return TCL_ERROR; + } + + if (!trap_stdout && (strcmp(channelId, "stdout") == 0)) + trap_stdout = 1; + + if (trap_stdout) { + if (newline) + xchat_printf(ph, "%s\n", string); + else + xchat_print(ph, string); + return TCL_OK; + } + + chan = Tcl_GetChannel(interp, channelId, &mode); + if (chan == (Tcl_Channel) NULL) { + return TCL_ERROR; + } + if ((mode & TCL_WRITABLE) == 0) { + Tcl_AppendResult(interp, "channel \"", channelId, "\" wasn't opened for writing", (char *) NULL); + return TCL_ERROR; + } + + result = Tcl_Write(chan, string, strlen(string)); + if (result < 0) { + goto error; + } + if (newline != 0) { + result = Tcl_WriteChars(chan, "\n", 1); + if (result < 0) { + goto error; + } + } + return TCL_OK; + + error: + Tcl_AppendResult(interp, "error writing \"", channelId, "\": ", Tcl_PosixError(interp), (char *) NULL); + + return TCL_ERROR; +} + +static int tcl_print(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_context *origctx; + xchat_context *ctx = NULL; + const char *string = NULL; + + BADARGS(2, 4, " ?server|network|context? ?#channel|nick? text"); + + origctx = xchat_get_context(ph); + + switch (argc) { + case 2: + ctx = origctx; + break; + case 3: + ctx = xchat_smart_context(argv[1], NULL); + break; + case 4: + ctx = xchat_smart_context(argv[1], argv[2]); + break; + default:; + } + + CHECKCTX(ctx); + + string = argv[argc - 1]; + + xchat_set_context(ph, ctx); + xchat_print(ph, string); + xchat_set_context(ph, origctx); + + return TCL_OK; +} + +static int tcl_setcontext(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_context *ctx = NULL; + + BADARGS(2, 2, " context"); + + ctx = xchat_smart_context(argv[1], NULL); + + CHECKCTX(ctx); + + xchat_set_context(ph, ctx); + + return TCL_OK; +} + +static int tcl_findcontext(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_context *ctx = NULL; + + BADARGS(1, 3, " ?server|network|context? ?channel?"); + + switch (argc) { + case 1: + ctx = xchat_find_context(ph, NULL, NULL); + break; + case 2: + ctx = xchat_smart_context(argv[1], NULL); + break; + case 3: + ctx = xchat_smart_context(argv[1], argv[2]); + break; + default:; + } + + CHECKCTX(ctx); + + Tcl_AppendResult(irp, myitoa((long)ctx), NULL); + + return TCL_OK; +} + +static int tcl_getcontext(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_context *ctx = NULL; + + BADARGS(1, 1, ""); + + ctx = xchat_get_context(ph); + + Tcl_AppendResult(irp, myitoa((long)ctx), NULL); + + return TCL_OK; +} + +static int tcl_channels(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + const char *server, *channel; + xchat_list *list; + Tcl_DString ds; + xchat_context *origctx; + xchat_context *ctx; + + origctx = xchat_get_context(ph); + + BADARGS(1, 2, " ?server|network|context?"); + + if (argc == 2) { + ctx = xchat_smart_context(argv[1], NULL); + CHECKCTX(ctx); + xchat_set_context(ph, ctx); + } + + server = (char *) xchat_get_info(ph, "server"); + + Tcl_DStringInit(&ds); + + list = xchat_list_get(ph, "channels"); + + if (list != NULL) { + while (xchat_list_next(ph, list)) { + if (xchat_list_int(ph, list, "type") != 2) + continue; + if (strcasecmp(server, xchat_list_str(ph, list, "server")) != 0) + continue; + channel = xchat_list_str(ph, list, "channel"); + Tcl_DStringAppendElement(&ds, channel); + } + xchat_list_free(ph, list); + } + + Tcl_AppendResult(irp, ds.string, NULL); + + Tcl_DStringFree(&ds); + + xchat_set_context(ph, origctx); + + return TCL_OK; +} + +static int tcl_servers(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + const char *server; + xchat_list *list; + Tcl_DString ds; + + BADARGS(1, 1, ""); + + Tcl_DStringInit(&ds); + + list = xchat_list_get(ph, "channels"); + + if (list != NULL) { + while (xchat_list_next(ph, list)) { + if (xchat_list_int(ph, list, "type") == 1) { + server = xchat_list_str(ph, list, "server"); + Tcl_DStringAppendElement(&ds, server); + } + } + xchat_list_free(ph, list); + } + + Tcl_AppendResult(irp, ds.string, NULL); + + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +static int tcl_queries(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + const char *server, *channel; + xchat_list *list; + Tcl_DString ds; + xchat_context *origctx; + xchat_context *ctx; + + origctx = xchat_get_context(ph); + + BADARGS(1, 2, " ?server|network|context?"); + + if (argc == 2) { + ctx = xchat_smart_context(argv[1], NULL); + CHECKCTX(ctx); + xchat_set_context(ph, ctx); + } + + server = (char *) xchat_get_info(ph, "server"); + + Tcl_DStringInit(&ds); + + list = xchat_list_get(ph, "channels"); + + if (list != NULL) { + while (xchat_list_next(ph, list)) { + if (xchat_list_int(ph, list, "type") != 3) + continue; + if (strcasecmp(server, xchat_list_str(ph, list, "server")) != 0) + continue; + channel = xchat_list_str(ph, list, "channel"); + Tcl_DStringAppendElement(&ds, channel); + } + xchat_list_free(ph, list); + } + + Tcl_AppendResult(irp, ds.string, NULL); + + Tcl_DStringFree(&ds); + + xchat_set_context(ph, origctx); + + return TCL_OK; +} + +static int tcl_users(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_context *origctx, *ctx = NULL; + xchat_list *list; + Tcl_DString ds; + + BADARGS(1, 3, " ?server|network|context? ?channel?"); + + origctx = xchat_get_context(ph); + + switch (argc) { + case 1: + ctx = origctx; + break; + case 2: + ctx = xchat_smart_context(argv[1], NULL); + break; + case 3: + ctx = xchat_smart_context(argv[1], argv[2]); + break; + default:; + } + + CHECKCTX(ctx); + + xchat_set_context(ph, ctx); + + Tcl_DStringInit(&ds); + + list = xchat_list_get(ph, "users"); + + if (list != NULL) { + + Tcl_DStringStartSublist(&ds); + Tcl_DStringAppendElement(&ds, "nick"); + Tcl_DStringAppendElement(&ds, "host"); + Tcl_DStringAppendElement(&ds, "prefix"); + Tcl_DStringAppendElement(&ds, "away"); + Tcl_DStringAppendElement(&ds, "lasttalk"); + Tcl_DStringAppendElement(&ds, "selected"); + Tcl_DStringEndSublist(&ds); + + while (xchat_list_next(ph, list)) { + Tcl_DStringStartSublist(&ds); + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "nick")); + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "host")); + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "prefix")); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_int(ph, list, "away"))); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_time(ph, list, "lasttalk"))); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_int(ph, list, "selected"))); + Tcl_DStringEndSublist(&ds); + } + + xchat_list_free(ph, list); + } + + Tcl_AppendResult(irp, ds.string, NULL); + + Tcl_DStringFree(&ds); + + xchat_set_context(ph, origctx); + + return TCL_OK; +} + +static int tcl_notifylist(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_list *list; + Tcl_DString ds; + + BADARGS(1, 1, ""); + + Tcl_DStringInit(&ds); + + list = xchat_list_get(ph, "notify"); + + if (list != NULL) { + + Tcl_DStringStartSublist(&ds); + Tcl_DStringAppendElement(&ds, "nick"); + Tcl_DStringAppendElement(&ds, "flags"); + Tcl_DStringAppendElement(&ds, "on"); + Tcl_DStringAppendElement(&ds, "off"); + Tcl_DStringAppendElement(&ds, "seen"); + Tcl_DStringAppendElement(&ds, "networks"); + Tcl_DStringEndSublist(&ds); + + while (xchat_list_next(ph, list)) { + Tcl_DStringStartSublist(&ds); + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "nick")); + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "flags")); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_time(ph, list, "on"))); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_time(ph, list, "off"))); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_time(ph, list, "seen"))); + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "networks")); + Tcl_DStringEndSublist(&ds); + } + + xchat_list_free(ph, list); + + } + + Tcl_AppendResult(irp, ds.string, NULL); + + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +static int tcl_chats(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_list *list; + Tcl_DString ds; + + BADARGS(1, 1, ""); + + Tcl_DStringInit(&ds); + + list = xchat_list_get(ph, "dcc"); + + if (list != NULL) { + while (xchat_list_next(ph, list)) { + switch (xchat_list_int(ph, list, "type")) { + case 2: + case 3: + if (xchat_list_int(ph, list, "status") == 1) + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "nick")); + break; + } + } + xchat_list_free(ph, list); + } + + Tcl_AppendResult(irp, ds.string, NULL); + + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +static int tcl_ignores(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_list *list; + Tcl_DString ds; + int flags; + + BADARGS(1, 1, ""); + + Tcl_DStringInit(&ds); + + list = xchat_list_get(ph, "ignore"); + + if (list != NULL) { + + while (xchat_list_next(ph, list)) { + Tcl_DStringStartSublist(&ds); + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "mask")); + Tcl_DStringStartSublist(&ds); + flags = xchat_list_int(ph, list, "flags"); + if (flags & 1) + Tcl_DStringAppendElement(&ds, "PRIVMSG"); + if (flags & 2) + Tcl_DStringAppendElement(&ds, "NOTICE"); + if (flags & 4) + Tcl_DStringAppendElement(&ds, "CHANNEL"); + if (flags & 8) + Tcl_DStringAppendElement(&ds, "CTCP"); + if (flags & 16) + Tcl_DStringAppendElement(&ds, "INVITE"); + if (flags & 32) + Tcl_DStringAppendElement(&ds, "UNIGNORE"); + if (flags & 64) + Tcl_DStringAppendElement(&ds, "NOSAVE"); + Tcl_DStringEndSublist(&ds); + Tcl_DStringEndSublist(&ds); + } + xchat_list_free(ph, list); + } + + Tcl_AppendResult(irp, ds.string, NULL); + + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +static int tcl_dcclist(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_list *list; + Tcl_DString ds; + int dcctype; + + BADARGS(1, 1, ""); + + Tcl_DStringInit(&ds); + + list = xchat_list_get(ph, "dcc"); + + if (list != NULL) { + + while (xchat_list_next(ph, list)) { + Tcl_DStringStartSublist(&ds); + dcctype = xchat_list_int(ph, list, "type"); + switch (dcctype) { + case 0: + Tcl_DStringAppendElement(&ds, "filesend"); + break; + case 1: + Tcl_DStringAppendElement(&ds, "filerecv"); + break; + case 2: + Tcl_DStringAppendElement(&ds, "chatrecv"); + break; + case 3: + Tcl_DStringAppendElement(&ds, "chatsend"); + break; + } + switch (xchat_list_int(ph, list, "status")) { + case 0: + Tcl_DStringAppendElement(&ds, "queued"); + break; + case 1: + Tcl_DStringAppendElement(&ds, "active"); + break; + case 2: + Tcl_DStringAppendElement(&ds, "failed"); + break; + case 3: + Tcl_DStringAppendElement(&ds, "done"); + break; + case 4: + Tcl_DStringAppendElement(&ds, "connecting"); + break; + case 5: + Tcl_DStringAppendElement(&ds, "aborted"); + break; + } + + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "nick")); + + switch (dcctype) { + case 0: + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "file")); + break; + case 1: + Tcl_DStringAppendElement(&ds, (const char *) xchat_list_str(ph, list, "destfile")); + break; + } + + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_int(ph, list, "size"))); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_int(ph, list, "resume"))); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_int(ph, list, "pos"))); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_int(ph, list, "cps"))); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_int(ph, list, "address32"))); + Tcl_DStringAppendElement(&ds, myitoa((long)xchat_list_int(ph, list, "port"))); + Tcl_DStringEndSublist(&ds); + } + xchat_list_free(ph, list); + } + + Tcl_AppendResult(irp, ds.string, NULL); + + Tcl_DStringFree(&ds); + + return TCL_OK; +} + + +static int tcl_strip(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + char *new_text; + int flags = 1 | 2; + + BADARGS(2, 3, " text ?flags?"); + + if (argc == 3) { + if (Tcl_GetInt(irp, argv[2], &flags) != TCL_OK) + return TCL_ERROR; + } + + new_text = xchat_strip(ph, argv[1], -1, flags); + + if(new_text) { + Tcl_AppendResult(irp, new_text, NULL); + xchat_free(ph, new_text); + } + + return TCL_OK; +} + +static int tcl_topic(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + xchat_context *origctx, *ctx = NULL; + BADARGS(1, 3, " ?server|network|context? ?channel?"); + + origctx = xchat_get_context(ph); + + switch (argc) { + case 1: + ctx = origctx; + break; + case 2: + ctx = xchat_smart_context(argv[1], NULL); + break; + case 3: + ctx = xchat_smart_context(argv[1], argv[2]); + break; + default:; + } + + CHECKCTX(ctx); + + xchat_set_context(ph, ctx); + Tcl_AppendResult(irp, xchat_get_info(ph, "topic"), NULL); + xchat_set_context(ph, origctx); + + return TCL_OK; +} + +static int tcl_xchat_nickcmp(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + BADARGS(3, 3, " string1 string2"); + Tcl_AppendResult(irp, myitoa((long)xchat_nickcmp(ph, argv[1], argv[2])), NULL); + return TCL_OK; +} + +static int tcl_word(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + int index; + + BADARGS(2, 2, " index"); + + if (Tcl_GetInt(irp, argv[1], &index) != TCL_OK) + return TCL_ERROR; + + if (!index || (index > 31)) + Tcl_AppendResult(interp, "", NULL); + else + Tcl_AppendResult(interp, complete[complete_level].word[index], NULL); + + return TCL_OK; +} + +static int tcl_word_eol(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]) +{ + int index; + + BADARGS(2, 2, " index"); + + if (Tcl_GetInt(irp, argv[1], &index) != TCL_OK) + return TCL_ERROR; + + if (!index || (index > 31)) + Tcl_AppendResult(interp, "", NULL); + else + Tcl_AppendResult(interp, complete[complete_level].word_eol[index], NULL); + + return TCL_OK; +} + +static int Command_Alias(char *word[], char *word_eol[], void *userdata) +{ + alias *aliasPtr; + Tcl_HashEntry *entry; + xchat_context *origctx; + int dummy; + char *string; + + if (complete_level == MAX_COMPLETES) + return XCHAT_EAT_NONE; + + complete_level++; + complete[complete_level].defresult = XCHAT_EAT_ALL; + complete[complete_level].result = XCHAT_EAT_NONE; + complete[complete_level].word = word; + complete[complete_level].word_eol = word_eol; + + string = StrDup(word[1], &dummy); + + Tcl_UtfToUpper(string); + + if ((entry = Tcl_FindHashEntry(&aliasTablePtr, string)) != NULL) { + aliasPtr = Tcl_GetHashValue(entry); + origctx = xchat_get_context(ph); + if (EvalInternalProc(aliasPtr->procPtr, 2, string, word_eol[2]) == TCL_ERROR) { + xchat_printf(ph, "\0039Tcl plugin\003\tERROR (alias %s) ", string); + NiceErrorInfo (); + } + xchat_set_context(ph, origctx); + } + + Tcl_Free(string); + + return complete[complete_level--].result; +} + +static int Null_Command_Alias(char *word[], char *word_eol[], void *userdata) +{ + alias *aliasPtr; + Tcl_HashEntry *entry; + xchat_context *origctx; + int dummy; + const char *channel; + char *string; + Tcl_DString ds; + static int recurse = 0; + + if (recurse) + return XCHAT_EAT_NONE; + + if (complete_level == MAX_COMPLETES) + return XCHAT_EAT_NONE; + + complete_level++; + complete[complete_level].defresult = XCHAT_EAT_ALL; + complete[complete_level].result = XCHAT_EAT_NONE; + complete[complete_level].word = word; + complete[complete_level].word_eol = word_eol; + + recurse++; + + channel = xchat_get_info(ph, "channel"); + Tcl_DStringInit(&ds); + Tcl_DStringAppend(&ds, "@", 1); + Tcl_DStringAppend(&ds, channel, strlen(channel)); + string = StrDup(ds.string, &dummy); + Tcl_DStringFree(&ds); + + Tcl_UtfToUpper(string); + + if ((entry = Tcl_FindHashEntry(&aliasTablePtr, string)) != NULL) { + aliasPtr = Tcl_GetHashValue(entry); + origctx = xchat_get_context(ph); + if (EvalInternalProc(aliasPtr->procPtr, 2, string, word_eol[1]) == TCL_ERROR) { + xchat_printf(ph, "\0039Tcl plugin\003\tERROR (alias %s) ", string); + NiceErrorInfo (); + } + xchat_set_context(ph, origctx); + } + + Tcl_Free(string); + + recurse--; + + return complete[complete_level--].result; +} + +static int Command_TCL(char *word[], char *word_eol[], void *userdata) +{ + const char *errorInfo; + + complete_level++; + complete[complete_level].word = word; + complete[complete_level].word_eol = word_eol; + + if (Tcl_Eval(interp, word_eol[2]) == TCL_ERROR) { + errorInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY); + xchat_printf(ph, "\0039Tcl plugin\003\tERROR: %s ", errorInfo); + } else + xchat_printf(ph, "\0039Tcl plugin\003\tRESULT: %s ", Tcl_GetStringResult(interp)); + + complete_level--; + + return XCHAT_EAT_ALL; +} + +static int Command_Source(char *word[], char *word_eol[], void *userdata) +{ + const char *xchatdir; + Tcl_DString ds; + struct stat dummy; + int len; + const char *errorInfo; + + if (!strlen(word_eol[2])) + return XCHAT_EAT_NONE; + + complete_level++; + complete[complete_level].word = word; + complete[complete_level].word_eol = word_eol; + + len = strlen(word[2]); + + if (len > 4 && strcasecmp(".tcl", word[2] + len - 4) == 0) { + + xchatdir = xchat_get_info(ph, "xchatdir"); + + Tcl_DStringInit(&ds); + + if (stat(word_eol[2], &dummy) == 0) { + Tcl_DStringAppend(&ds, word_eol[2], strlen(word_eol[2])); + } else { + if (!strchr(word_eol[2], '/')) { + Tcl_DStringAppend(&ds, xchatdir, strlen(xchatdir)); + Tcl_DStringAppend(&ds, "/", 1); + Tcl_DStringAppend(&ds, word_eol[2], strlen(word_eol[2])); + } + } + + if (Tcl_EvalFile(interp, ds.string) == TCL_ERROR) { + errorInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY); + xchat_printf(ph, "\0039Tcl plugin\003\tERROR: %s ", errorInfo); + } else + xchat_printf(ph, "\0039Tcl plugin\003\tSourced %s\n", ds.string); + + Tcl_DStringFree(&ds); + + complete_level--; + + return XCHAT_EAT_XCHAT; + + } else { + complete_level--; + return XCHAT_EAT_NONE; + } + +} + +static int Command_Reloadall(char *word[], char *word_eol[], void *userdata) +{ + Tcl_Plugin_DeInit(); + Tcl_Plugin_Init(); + + xchat_print(ph, "\0039Tcl plugin\003\tRehashed\n"); + + return XCHAT_EAT_ALL; +} + +static int TCL_Event_Handler(void *userdata) +{ + Tcl_DoOneEvent(TCL_DONT_WAIT); + do_timer(); + return 1; +} + +static void Tcl_Plugin_Init() +{ + int x; + const char *xchatdir; + + interp = Tcl_CreateInterp(); + + Tcl_FindExecutable(NULL); + + Tcl_Init(interp); + + nextprocid = 0x1000; + + Tcl_CreateCommand(interp, "alias", tcl_alias, NULL, NULL); + Tcl_CreateCommand(interp, "channels", tcl_channels, NULL, NULL); + Tcl_CreateCommand(interp, "chats", tcl_chats, NULL, NULL); + Tcl_CreateCommand(interp, "command", tcl_command, NULL, NULL); + Tcl_CreateCommand(interp, "complete", tcl_complete, NULL, NULL); + Tcl_CreateCommand(interp, "dcclist", tcl_dcclist, NULL, NULL); + Tcl_CreateCommand(interp, "notifylist", tcl_notifylist, NULL, NULL); + Tcl_CreateCommand(interp, "findcontext", tcl_findcontext, NULL, NULL); + Tcl_CreateCommand(interp, "getcontext", tcl_getcontext, NULL, NULL); + Tcl_CreateCommand(interp, "getinfo", tcl_getinfo, NULL, NULL); + Tcl_CreateCommand(interp, "getlist", tcl_getlist, NULL, NULL); + Tcl_CreateCommand(interp, "ignores", tcl_ignores, NULL, NULL); + Tcl_CreateCommand(interp, "killtimer", tcl_killtimer, NULL, NULL); + Tcl_CreateCommand(interp, "me", tcl_me, NULL, NULL); + Tcl_CreateCommand(interp, "on", tcl_on, NULL, NULL); + Tcl_CreateCommand(interp, "off", tcl_off, NULL, NULL); + Tcl_CreateCommand(interp, "nickcmp", tcl_xchat_nickcmp, NULL, NULL); + Tcl_CreateCommand(interp, "print", tcl_print, NULL, NULL); + Tcl_CreateCommand(interp, "prefs", tcl_prefs, NULL, NULL); + Tcl_CreateCommand(interp, "::puts", tcl_xchat_puts, NULL, NULL); + Tcl_CreateCommand(interp, "queries", tcl_queries, NULL, NULL); + Tcl_CreateCommand(interp, "raw", tcl_raw, NULL, NULL); + Tcl_CreateCommand(interp, "servers", tcl_servers, NULL, NULL); + Tcl_CreateCommand(interp, "setcontext", tcl_setcontext, NULL, NULL); + Tcl_CreateCommand(interp, "strip", tcl_strip, NULL, NULL); + Tcl_CreateCommand(interp, "timer", tcl_timer, NULL, NULL); + Tcl_CreateCommand(interp, "timerexists", tcl_timerexists, NULL, NULL); + Tcl_CreateCommand(interp, "timers", tcl_timers, NULL, NULL); + Tcl_CreateCommand(interp, "topic", tcl_topic, NULL, NULL); + Tcl_CreateCommand(interp, "users", tcl_users, NULL, NULL); + Tcl_CreateCommand(interp, "word", tcl_word, NULL, NULL); + Tcl_CreateCommand(interp, "word_eol", tcl_word_eol, NULL, NULL); + + Tcl_InitHashTable(&cmdTablePtr, TCL_STRING_KEYS); + Tcl_InitHashTable(&aliasTablePtr, TCL_STRING_KEYS); + + bzero(timers, sizeof(timers)); + nexttimerid = 0; + nexttimerindex = 0; + + for (x = 0; x < XC_SIZE; x++) + xc[x].hook = NULL; + + xchatdir = xchat_get_info(ph, "xchatdir"); + + if (Tcl_Eval(interp, unknown) == TCL_ERROR) { + xchat_printf(ph, "Error sourcing internal 'unknown' (%s)\n", Tcl_GetStringResult(interp)); + } + + if (Tcl_Eval(interp, inlinetcl) == TCL_ERROR) { + xchat_printf(ph, "Error sourcing internal 'inlinetcl' (%s)\n", Tcl_GetStringResult(interp)); + } + + if (Tcl_Eval(interp, sourcedirs) == TCL_ERROR) { + xchat_printf(ph, "Error sourcing internal 'sourcedirs' (%s)\n", Tcl_GetStringResult(interp)); + } + +} + +static void Tcl_Plugin_DeInit() +{ + int x; + char *procPtr; + alias *aliasPtr; + Tcl_HashEntry *entry; + Tcl_HashSearch search; + + /* Be sure to free all the memory for ON and ALIAS entries */ + + entry = Tcl_FirstHashEntry(&cmdTablePtr, &search); + while (entry != NULL) { + procPtr = Tcl_GetHashValue(entry); + Tcl_Free(procPtr); + entry = Tcl_NextHashEntry(&search); + } + + Tcl_DeleteHashTable(&cmdTablePtr); + + entry = Tcl_FirstHashEntry(&aliasTablePtr, &search); + while (entry != NULL) { + aliasPtr = Tcl_GetHashValue(entry); + Tcl_Free(aliasPtr->procPtr); + if (aliasPtr->hook) + xchat_unhook(ph, aliasPtr->hook); + Tcl_Free((char *) aliasPtr); + entry = Tcl_NextHashEntry(&search); + } + + Tcl_DeleteHashTable(&aliasTablePtr); + + for (x = 1; x < MAX_TIMERS; x++) { + if (timers[x].timerid) { + timers[x].timerid = 0; + if (timers[x].procPtr != NULL) + Tcl_Free(timers[x].procPtr); + timers[x].procPtr = NULL; + break; + } + } + + for (x = 0; x < XC_SIZE; x++) { + if (xc[x].hook != NULL) { + xchat_unhook(ph, xc[x].hook); + xc[x].hook = NULL; + } + } + + Tcl_DeleteInterp(interp); +} + +static void banner() +{ + xchat_printf(ph, "Tcl plugin for XChat - Version %s\n", VERSION); + xchat_print(ph, "Copyright 2002-2005 Daniel P. Stasinski\n"); + xchat_print(ph, "http://www.scriptkitties.com/tclplugin/\n"); +} + +int xchat_plugin_init(xchat_plugin * plugin_handle, char **plugin_name, char **plugin_desc, char **plugin_version, char *arg) +{ +#ifdef WIN32 + HINSTANCE lib; +#endif + + strncpy(VERSION, &RCSID[19], 5); + + ph = plugin_handle; + +#ifdef WIN32 + lib = LoadLibraryA(TCL_DLL); + if (!lib) { + xchat_print(ph, "You must have ActiveTCL installed in order to run Tcl scripts.\n" "http://aspn.activestate.com/ASPN/Tcl/\n" "Make sure Tcl's bin directory is in your PATH.\n\n"); + return 0; + } + FreeLibrary(lib); +#endif + + if (initialized != 0) { + banner(); + xchat_print(ph, "Tcl plugin already loaded"); + reinit_tried++; + return 0; + } + initialized = 1; + + *plugin_name = "Tcl"; + *plugin_desc = "Tcl scripting interface"; + *plugin_version = VERSION; + + Tcl_Plugin_Init(); + + raw_line_hook = xchat_hook_server(ph, "RAW LINE", XCHAT_PRI_NORM, Server_raw_line, NULL); + Command_TCL_hook = xchat_hook_command(ph, "tcl", XCHAT_PRI_NORM, Command_TCL, 0, 0); + Command_Source_hook = xchat_hook_command(ph, "source", XCHAT_PRI_NORM, Command_Source, 0, 0); + Command_Reload_hook = xchat_hook_command(ph, "reloadall", XCHAT_PRI_NORM, Command_Reloadall, 0, 0); + Command_Load_hook = xchat_hook_command(ph, "LOAD", XCHAT_PRI_NORM, Command_Source, 0, 0); + Event_Handler_hook = xchat_hook_timer(ph, 100, TCL_Event_Handler, 0); + Null_Command_hook = xchat_hook_command(ph, "", XCHAT_PRI_NORM, Null_Command_Alias, "", 0); + + banner(); + xchat_print(ph, "Tcl interface loaded\n"); + + return 1; /* return 1 for success */ +} + +int xchat_plugin_deinit() +{ + if (reinit_tried) { + reinit_tried--; + return 1; + } + + xchat_unhook(ph, raw_line_hook); + xchat_unhook(ph, Command_TCL_hook); + xchat_unhook(ph, Command_Source_hook); + xchat_unhook(ph, Command_Reload_hook); + xchat_unhook(ph, Command_Load_hook); + xchat_unhook(ph, Event_Handler_hook); + xchat_unhook(ph, Null_Command_hook); + + Tcl_Plugin_DeInit(); + + xchat_print(ph, "Tcl interface unloaded\n"); + initialized = 0; + + return 1; +} + +void xchat_plugin_get_info(char **name, char **desc, char **version, void **reserved) +{ + strncpy(VERSION, &RCSID[19], 5); + *name = "tclplugin"; + *desc = "Tcl plugin for XChat"; + *version = VERSION; + if (reserved) + *reserved = NULL; +} + diff --git a/plugins/tcl/tclplugin.h b/plugins/tcl/tclplugin.h new file mode 100644 index 00000000..075c28f8 --- /dev/null +++ b/plugins/tcl/tclplugin.h @@ -0,0 +1,98 @@ +/*************************************************************************** + tclplugin.h - TCL plugin header file + ------------------------------------------------- + begin : Sat Nov 9 17:31:20 MST 2002 + copyright : Copyright 2002-2010 Daniel P. Stasinski + email : daniel@avenues.org + ***************************************************************************/ + +/*************************************************************************** + * * + * 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. * + * * + ***************************************************************************/ + +#define BADARGS(nl,nh,example) \ + if ((argc<(nl)) || (argc>(nh))) { \ + Tcl_AppendResult(irp,"wrong # args: should be \"",argv[0], \ + (example),"\"",NULL); \ + return TCL_ERROR; \ + } + +#define CHECKCTX(ctx) \ + if (ctx == NULL) { \ + Tcl_AppendResult(irp, "No such server/channel/nick", NULL); \ + return TCL_ERROR; \ + } + +typedef struct { + char *procPtr; + xchat_hook *hook; +} alias; + +typedef struct { + int timerid; + time_t timestamp; + char *procPtr; + int count; + int seconds; +} timer; + +typedef struct { + int result; + int defresult; + char **word; + char **word_eol; +} t_complete; + +#define MAX_TIMERS 512 +#define MAX_COMPLETES 128 + +static char *StrDup(const char *string, int *length); +static char *myitoa(long value); +static xchat_context *xchat_smart_context(const char *arg1, const char *arg2); +static void queue_nexttimer(); +static int insert_timer(int seconds, int count, const char *script); +static void do_timer(); +static int Server_raw_line(char *word[], char *word_eol[], void *userdata); +static int Print_Hook(char *word[], void *userdata); +static int tcl_timerexists(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_killtimer(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_timers(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_timer(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_on(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_off(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_alias(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_complete(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_raw(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_command(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_xchat_puts(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_print(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_channels(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_servers(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_queries(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_users(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_chats(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_ignores(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_dcclist(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_me(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_xchat_nickcmp(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_strip(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_topic(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_word(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_word_eol(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int tcl_notifylist(ClientData cd, Tcl_Interp * irp, int argc, const char *argv[]); +static int Command_Alias(char *word[], char *word_eol[], void *userdata); +static int Null_Command_Alias(char *word[], char *word_eol[], void *userdata); +static int Command_TCL(char *word[], char *word_eol[], void *userdata); +static int Command_Source(char *word[], char *word_eol[], void *userdata); +static int Command_Reload(char *word[], char *word_eol[], void *userdata); +static int TCL_Event_Handler(void *userdata); +static void Tcl_Plugin_Init(); +static void Tcl_Plugin_DeInit(); +static void banner(); +int xchat_plugin_init(xchat_plugin * plugin_handle, char **plugin_name, char **plugin_desc, char **plugin_version, char *arg); +int xchat_plugin_deinit(); diff --git a/plugins/xchat-plugin.h b/plugins/xchat-plugin.h new file mode 100644 index 00000000..30b19295 --- /dev/null +++ b/plugins/xchat-plugin.h @@ -0,0 +1,334 @@ +/* You can distribute this header with your plugins for easy compilation */ +#ifndef XCHAT_PLUGIN_H +#define XCHAT_PLUGIN_H + +#include <time.h> + +#define XCHAT_IFACE_MAJOR 1 +#define XCHAT_IFACE_MINOR 9 +#define XCHAT_IFACE_MICRO 11 +#define XCHAT_IFACE_VERSION ((XCHAT_IFACE_MAJOR * 10000) + \ + (XCHAT_IFACE_MINOR * 100) + \ + (XCHAT_IFACE_MICRO)) + +#define XCHAT_PRI_HIGHEST 127 +#define XCHAT_PRI_HIGH 64 +#define XCHAT_PRI_NORM 0 +#define XCHAT_PRI_LOW (-64) +#define XCHAT_PRI_LOWEST (-128) + +#define XCHAT_FD_READ 1 +#define XCHAT_FD_WRITE 2 +#define XCHAT_FD_EXCEPTION 4 +#define XCHAT_FD_NOTSOCKET 8 + +#define XCHAT_EAT_NONE 0 /* pass it on through! */ +#define XCHAT_EAT_XCHAT 1 /* don't let xchat see this event */ +#define XCHAT_EAT_PLUGIN 2 /* don't let other plugins see this event */ +#define XCHAT_EAT_ALL (XCHAT_EAT_XCHAT|XCHAT_EAT_PLUGIN) /* don't let anything see this event */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _xchat_plugin xchat_plugin; +typedef struct _xchat_list xchat_list; +typedef struct _xchat_hook xchat_hook; +#ifndef PLUGIN_C +typedef struct _xchat_context xchat_context; +#endif + +#ifndef PLUGIN_C +struct _xchat_plugin +{ + /* these are only used on win32 */ + xchat_hook *(*xchat_hook_command) (xchat_plugin *ph, + const char *name, + int pri, + int (*callback) (char *word[], char *word_eol[], void *user_data), + const char *help_text, + void *userdata); + xchat_hook *(*xchat_hook_server) (xchat_plugin *ph, + const char *name, + int pri, + int (*callback) (char *word[], char *word_eol[], void *user_data), + void *userdata); + xchat_hook *(*xchat_hook_print) (xchat_plugin *ph, + const char *name, + int pri, + int (*callback) (char *word[], void *user_data), + void *userdata); + xchat_hook *(*xchat_hook_timer) (xchat_plugin *ph, + int timeout, + int (*callback) (void *user_data), + void *userdata); + xchat_hook *(*xchat_hook_fd) (xchat_plugin *ph, + int fd, + int flags, + int (*callback) (int fd, int flags, void *user_data), + void *userdata); + void *(*xchat_unhook) (xchat_plugin *ph, + xchat_hook *hook); + void (*xchat_print) (xchat_plugin *ph, + const char *text); + void (*xchat_printf) (xchat_plugin *ph, + const char *format, ...); + void (*xchat_command) (xchat_plugin *ph, + const char *command); + void (*xchat_commandf) (xchat_plugin *ph, + const char *format, ...); + int (*xchat_nickcmp) (xchat_plugin *ph, + const char *s1, + const char *s2); + int (*xchat_set_context) (xchat_plugin *ph, + xchat_context *ctx); + xchat_context *(*xchat_find_context) (xchat_plugin *ph, + const char *servname, + const char *channel); + xchat_context *(*xchat_get_context) (xchat_plugin *ph); + const char *(*xchat_get_info) (xchat_plugin *ph, + const char *id); + int (*xchat_get_prefs) (xchat_plugin *ph, + const char *name, + const char **string, + int *integer); + xchat_list * (*xchat_list_get) (xchat_plugin *ph, + const char *name); + void (*xchat_list_free) (xchat_plugin *ph, + xchat_list *xlist); + const char * const * (*xchat_list_fields) (xchat_plugin *ph, + const char *name); + int (*xchat_list_next) (xchat_plugin *ph, + xchat_list *xlist); + const char * (*xchat_list_str) (xchat_plugin *ph, + xchat_list *xlist, + const char *name); + int (*xchat_list_int) (xchat_plugin *ph, + xchat_list *xlist, + const char *name); + void * (*xchat_plugingui_add) (xchat_plugin *ph, + const char *filename, + const char *name, + const char *desc, + const char *version, + char *reserved); + void (*xchat_plugingui_remove) (xchat_plugin *ph, + void *handle); + int (*xchat_emit_print) (xchat_plugin *ph, + const char *event_name, ...); + int (*xchat_read_fd) (xchat_plugin *ph, + void *src, + char *buf, + int *len); + time_t (*xchat_list_time) (xchat_plugin *ph, + xchat_list *xlist, + const char *name); + char *(*xchat_gettext) (xchat_plugin *ph, + const char *msgid); + void (*xchat_send_modes) (xchat_plugin *ph, + const char **targets, + int ntargets, + int modes_per_line, + char sign, + char mode); + char *(*xchat_strip) (xchat_plugin *ph, + const char *str, + int len, + int flags); + void (*xchat_free) (xchat_plugin *ph, + void *ptr); +}; +#endif + + +xchat_hook * +xchat_hook_command (xchat_plugin *ph, + const char *name, + int pri, + int (*callback) (char *word[], char *word_eol[], void *user_data), + const char *help_text, + void *userdata); + +xchat_hook * +xchat_hook_server (xchat_plugin *ph, + const char *name, + int pri, + int (*callback) (char *word[], char *word_eol[], void *user_data), + void *userdata); + +xchat_hook * +xchat_hook_print (xchat_plugin *ph, + const char *name, + int pri, + int (*callback) (char *word[], void *user_data), + void *userdata); + +xchat_hook * +xchat_hook_timer (xchat_plugin *ph, + int timeout, + int (*callback) (void *user_data), + void *userdata); + +xchat_hook * +xchat_hook_fd (xchat_plugin *ph, + int fd, + int flags, + int (*callback) (int fd, int flags, void *user_data), + void *userdata); + +void * +xchat_unhook (xchat_plugin *ph, + xchat_hook *hook); + +void +xchat_print (xchat_plugin *ph, + const char *text); + +void +xchat_printf (xchat_plugin *ph, + const char *format, ...); + +void +xchat_command (xchat_plugin *ph, + const char *command); + +void +xchat_commandf (xchat_plugin *ph, + const char *format, ...); + +int +xchat_nickcmp (xchat_plugin *ph, + const char *s1, + const char *s2); + +int +xchat_set_context (xchat_plugin *ph, + xchat_context *ctx); + +xchat_context * +xchat_find_context (xchat_plugin *ph, + const char *servname, + const char *channel); + +xchat_context * +xchat_get_context (xchat_plugin *ph); + +const char * +xchat_get_info (xchat_plugin *ph, + const char *id); + +int +xchat_get_prefs (xchat_plugin *ph, + const char *name, + const char **string, + int *integer); + +xchat_list * +xchat_list_get (xchat_plugin *ph, + const char *name); + +void +xchat_list_free (xchat_plugin *ph, + xchat_list *xlist); + +const char * const * +xchat_list_fields (xchat_plugin *ph, + const char *name); + +int +xchat_list_next (xchat_plugin *ph, + xchat_list *xlist); + +const char * +xchat_list_str (xchat_plugin *ph, + xchat_list *xlist, + const char *name); + +int +xchat_list_int (xchat_plugin *ph, + xchat_list *xlist, + const char *name); + +time_t +xchat_list_time (xchat_plugin *ph, + xchat_list *xlist, + const char *name); + +void * +xchat_plugingui_add (xchat_plugin *ph, + const char *filename, + const char *name, + const char *desc, + const char *version, + char *reserved); + +void +xchat_plugingui_remove (xchat_plugin *ph, + void *handle); + +int +xchat_emit_print (xchat_plugin *ph, + const char *event_name, ...); + +char * +xchat_gettext (xchat_plugin *ph, + const char *msgid); + +void +xchat_send_modes (xchat_plugin *ph, + const char **targets, + int ntargets, + int modes_per_line, + char sign, + char mode); + +char * +xchat_strip (xchat_plugin *ph, + const char *str, + int len, + int flags); + +void +xchat_free (xchat_plugin *ph, + void *ptr); + +#if !defined(PLUGIN_C) && defined(WIN32) +#ifndef XCHAT_PLUGIN_HANDLE +#define XCHAT_PLUGIN_HANDLE (ph) +#endif +#define xchat_hook_command ((XCHAT_PLUGIN_HANDLE)->xchat_hook_command) +#define xchat_hook_server ((XCHAT_PLUGIN_HANDLE)->xchat_hook_server) +#define xchat_hook_print ((XCHAT_PLUGIN_HANDLE)->xchat_hook_print) +#define xchat_hook_timer ((XCHAT_PLUGIN_HANDLE)->xchat_hook_timer) +#define xchat_hook_fd ((XCHAT_PLUGIN_HANDLE)->xchat_hook_fd) +#define xchat_unhook ((XCHAT_PLUGIN_HANDLE)->xchat_unhook) +#define xchat_print ((XCHAT_PLUGIN_HANDLE)->xchat_print) +#define xchat_printf ((XCHAT_PLUGIN_HANDLE)->xchat_printf) +#define xchat_command ((XCHAT_PLUGIN_HANDLE)->xchat_command) +#define xchat_commandf ((XCHAT_PLUGIN_HANDLE)->xchat_commandf) +#define xchat_nickcmp ((XCHAT_PLUGIN_HANDLE)->xchat_nickcmp) +#define xchat_set_context ((XCHAT_PLUGIN_HANDLE)->xchat_set_context) +#define xchat_find_context ((XCHAT_PLUGIN_HANDLE)->xchat_find_context) +#define xchat_get_context ((XCHAT_PLUGIN_HANDLE)->xchat_get_context) +#define xchat_get_info ((XCHAT_PLUGIN_HANDLE)->xchat_get_info) +#define xchat_get_prefs ((XCHAT_PLUGIN_HANDLE)->xchat_get_prefs) +#define xchat_list_get ((XCHAT_PLUGIN_HANDLE)->xchat_list_get) +#define xchat_list_free ((XCHAT_PLUGIN_HANDLE)->xchat_list_free) +#define xchat_list_fields ((XCHAT_PLUGIN_HANDLE)->xchat_list_fields) +#define xchat_list_str ((XCHAT_PLUGIN_HANDLE)->xchat_list_str) +#define xchat_list_int ((XCHAT_PLUGIN_HANDLE)->xchat_list_int) +#define xchat_list_time ((XCHAT_PLUGIN_HANDLE)->xchat_list_time) +#define xchat_list_next ((XCHAT_PLUGIN_HANDLE)->xchat_list_next) +#define xchat_plugingui_add ((XCHAT_PLUGIN_HANDLE)->xchat_plugingui_add) +#define xchat_plugingui_remove ((XCHAT_PLUGIN_HANDLE)->xchat_plugingui_remove) +#define xchat_emit_print ((XCHAT_PLUGIN_HANDLE)->xchat_emit_print) +#define xchat_gettext ((XCHAT_PLUGIN_HANDLE)->xchat_gettext) +#define xchat_send_modes ((XCHAT_PLUGIN_HANDLE)->xchat_send_modes) +#define xchat_strip ((XCHAT_PLUGIN_HANDLE)->xchat_strip) +#define xchat_free ((XCHAT_PLUGIN_HANDLE)->xchat_free) +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/plugins/xdcc/Makefile.am b/plugins/xdcc/Makefile.am new file mode 100644 index 00000000..24f93f16 --- /dev/null +++ b/plugins/xdcc/Makefile.am @@ -0,0 +1,7 @@ +libdir = $(xchatdir)/plugins + +lib_LTLIBRARIES = xdcc.la +xdcc_la_SOURCES = xdcc.c +xdcc_la_LDFLAGS = -avoid-version -module +INCLUDES = $(COMMON_CFLAGS) -I$(srcdir)/.. + diff --git a/plugins/xdcc/xdcc.c b/plugins/xdcc/xdcc.c new file mode 100644 index 00000000..147a3c33 --- /dev/null +++ b/plugins/xdcc/xdcc.c @@ -0,0 +1,327 @@ +/* xchat 2.0 plugin: simple xdcc server example */ + +#include <glib.h> +#include <string.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdio.h> + +#include "xchat-plugin.h" + +static xchat_plugin *ph; /* plugin handle */ + +static int xdcc_on = 1; +static int xdcc_slots = 3; +static GSList *file_list = 0; + +typedef struct fileoffer +{ + char *file; + char *fullpath; + char *desc; + int downloads; +} fileoffer; + + +/* find the number of open dccs */ + +static int num_open_dccs(void) +{ + xchat_list *list; + int num = 0; + + list = xchat_list_get(ph, "dcc"); + if(!list) + return 0; + + while(xchat_list_next(ph, list)) + { + /* check only ACTIVE dccs */ + if(xchat_list_int(ph, list, "status") == 1) + { + /* check only SEND dccs */ + if(xchat_list_int(ph, list, "type") == 0) + num++; + } + } + + xchat_list_free(ph, list); + + return num; +} + +static void xdcc_get(char *nick, char *host, char *arg) +{ + int num; + GSList *list; + fileoffer *offer; + + if(arg[0] == '#') + arg++; + + num = atoi(arg); + list = g_slist_nth(file_list, num - 1); + if(!list) + { + xchat_commandf(ph, "quote NOTICE %s :No such file number #%d!", nick, num); + return; + } + + if(num_open_dccs() >= xdcc_slots) + { + xchat_commandf(ph, "quote NOTICE %s :All slots full. Try again later.", nick); + return; + } + + offer = (fileoffer *) list->data; + offer->downloads++; + xchat_commandf(ph, "quote NOTICE %s :Sending offer #%d %s", nick, num, offer->file); + xchat_commandf(ph, "dcc send %s %s", nick, offer->fullpath); +} + +static void xdcc_del(char *name) +{ + GSList *list; + fileoffer *offer; + + list = file_list; + while(list) + { + offer = (fileoffer *) list->data; + if(strcasecmp(name, offer->file) == 0) + { + file_list = g_slist_remove(file_list, offer); + xchat_printf(ph, "%s [%s] removed.\n", offer->file, offer->fullpath); + free(offer->file); + free(offer->desc); + free(offer->fullpath); + free(offer); + return; + } + list = list->next; + } +} + +static void xdcc_add(char *name, char *fullpath, char *desc, int dl) +{ + fileoffer *offer; + + offer = (fileoffer *) malloc(sizeof(fileoffer)); + offer->file = strdup(name); + offer->desc = strdup(desc); + offer->fullpath = strdup(fullpath); + offer->downloads = dl; + + file_list = g_slist_append(file_list, offer); +} + +static void xdcc_list(char *nick, char *host, char *arg, char *cmd) +{ + GSList *list; + int i = 0; + fileoffer *offer; + + xchat_commandf(ph, "%s %s :XDCC List:", cmd, nick); + list = file_list; + while(list) + { + i++; + offer = (fileoffer *) list->data; + xchat_commandf(ph, "%s %s :[#%d] %s - %s [%d dl]", cmd, + nick, i, offer->file, offer->desc, offer->downloads); + list = list->next; + } + + if(i == 0) + xchat_commandf(ph, "%s %s :- list empty.", cmd, nick); + else + xchat_commandf(ph, "%s %s :%d files listed.", cmd, nick, i); +} + +static int xdcc_command(char *word[], char *word_eol[], void *userdata) +{ + if(strcasecmp(word[2], "ADD") == 0) + { + if(!word_eol[5][0]) + xchat_print(ph, "Syntax: /XDCC ADD <name> <path> <description>\n"); + else + { + if(access(word[4], R_OK) == 0) + { + xdcc_add(word[3], word[4], word_eol[5], 0); + xchat_printf(ph, "%s [%s] added.\n", word[3], word[4]); + } + else + xchat_printf(ph, "Cannot read %s\n", word[4]); + } + return XCHAT_EAT_XCHAT; + } + + if(strcasecmp(word[2], "DEL") == 0) + { + xdcc_del(word[3]); + return XCHAT_EAT_XCHAT; + } + + if(strcasecmp(word[2], "SLOTS") == 0) + { + if(word[3][0]) + { + xdcc_slots = atoi(word[3]); + xchat_printf(ph, "XDCC slots set to %d\n", xdcc_slots); + } else + { + xchat_printf(ph, "XDCC slots: %d\n", xdcc_slots); + } + return XCHAT_EAT_XCHAT; + } + + if(strcasecmp(word[2], "ON") == 0) + { + xdcc_on = TRUE; + xchat_print(ph, "XDCC now ON\n"); + return XCHAT_EAT_XCHAT; + } + + if(strcasecmp(word[2], "LIST") == 0) + { + xdcc_list("", "", "", "echo"); + return XCHAT_EAT_XCHAT; + } + + if(strcasecmp(word[2], "OFF") == 0) + { + xdcc_on = FALSE; + xchat_print(ph, "XDCC now OFF\n"); + return XCHAT_EAT_XCHAT; + } + + xchat_print(ph, "Syntax: XDCC ADD <name> <fullpath> <description>\n" + " XDCC DEL <name>\n" + " XDCC SLOTS <number>\n" + " XDCC LIST\n" + " XDCC ON\n" + " XDCC OFF\n\n"); + + return XCHAT_EAT_XCHAT; +} + +static void xdcc_remote(char *from, char *msg) +{ + char *ex, *nick, *host; + + ex = strchr(from, '!'); + if(!ex) + return; + ex[0] = 0; + nick = from; + host = ex + 1; + + if(xdcc_on == 0) + { + xchat_commandf(ph, "notice %s XDCC is turned OFF!", from); + return; + } + + if(strncasecmp(msg, "LIST", 4) == 0) + xdcc_list(nick, host, msg + 4, "quote notice"); + else if(strncasecmp(msg, "GET ", 4) == 0) + xdcc_get(nick, host, msg + 4); + else + xchat_commandf(ph, "notice %s Unknown XDCC command!", from); +} + +static int ctcp_cb(char *word[], void *userdata) +{ + char *msg = word[1]; + char *from = word[2]; + + if(strncasecmp(msg, "XDCC ", 5) == 0) + xdcc_remote(from, msg + 5); + + return XCHAT_EAT_NONE; +} + +static void xdcc_save(void) +{ + char buf[512]; + FILE *fp; + GSList *list; + fileoffer *offer; + + snprintf(buf, sizeof(buf), "%s/xdcclist.conf", xchat_get_info(ph, "xchatdir")); + + fp = fopen(buf, "w"); + if(!fp) + return; + + list = file_list; + while(list) + { + offer = (fileoffer *) list->data; + fprintf(fp, "%s\n%s\n%s\n%d\n\n\n", offer->file, offer->fullpath, + offer->desc, offer->downloads); + list = list->next; + } + + fclose(fp); +} + +static void xdcc_load(void) +{ + char buf[512]; + char file[128]; + char path[128]; + char desc[128]; + char dl[128]; + FILE *fp; + + snprintf(buf, sizeof(buf), "%s/xdcclist.conf", xchat_get_info(ph, "xchatdir")); + + fp = fopen(buf, "r"); + if(!fp) + return; + + while(fgets(file, sizeof(file), fp)) + { + file[strlen(file)-1] = 0; + fgets(path, sizeof(path), fp); + path[strlen(path)-1] = 0; + fgets(desc, sizeof(desc), fp); + desc[strlen(desc)-1] = 0; + fgets(dl, sizeof(dl), fp); + dl[strlen(dl)-1] = 0; + fgets(buf, sizeof(buf), fp); + fgets(buf, sizeof(buf), fp); + xdcc_add(file, path, desc, atoi(dl)); + } + + fclose(fp); +} + +int xchat_plugin_deinit(void) +{ + xdcc_save(); + xchat_print(ph, "XDCC List saved\n"); + return 1; +} + +int xchat_plugin_init(xchat_plugin *plugin_handle, + char **plugin_name, char **plugin_desc, char **plugin_version, + char *arg) +{ + ph = plugin_handle; + + *plugin_name = "XDCC"; + *plugin_desc = "Very simple XDCC server"; + *plugin_version = "0.1"; + + xchat_hook_command(ph, "XDCC", XCHAT_PRI_NORM, xdcc_command, 0, 0); + xchat_hook_print(ph, "CTCP Generic", XCHAT_PRI_NORM, ctcp_cb, 0); + xchat_hook_print(ph, "CTCP Generic to Channel", XCHAT_PRI_NORM, ctcp_cb, 0); + + xdcc_load(); + xchat_print(ph, "XDCC loaded. Type /XDCC for help.\n"); + + return 1; +} |