#!/usr/bin/perl
#
# xchat-inputcount.pl: add a character count next to xchat's input box.
# (useful when twittering, to see if you are within 140 characters)
#
# usage: Xchat / Load plugin...
#
# prereqs: libgtk2-perl
#
# bug: character count lags one keypress behind the actual input. Press
# any key (e.g. Ctrl, Shift, arrow keys) to cause the count to be updated.
#
# Public domain; written by Khisanth on freenode #xchat IRC.
#
# please send any improvements to Gerald Oskoboiny <gerald@impressive.net>
#
# source: http://impressive.net/people/gerald/2009/05/xchat-inputcount.pl
#
# also available at:
# http://xchat.cvs.sourceforge.net/viewvc/xchat/xchat2/plugins/perl/char_count.pl?view=markup
#
# $Id: xchat-inputcount.pl,v 1.2 2009/05/07 20:33:28 gerald Exp $
#

use strict;
use warnings;
use Xchat qw(:all);
use Glib;
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();
	$hbox->pack_end( $label, 0, 0, 5 );
	$label->show();

	hook_print( "Key Press",
	    sub {
		my $ctx_type = context_info->{"type"};
		if( $ctx_type == 2 || $ctx_type == 3 ) {
		    my $count = length get_info "inputbox";
		    $label->set_text( $count ? $count : "" );
		} else {
		    $label->set_text( "" );
		}
		return EAT_NONE;
	    }
	);

	hook_command( "",
	    sub {
		$label->set_text( "" );
		return EAT_NONE;
	    }
	);
	register( "Character Counter", "1.0.0",
	    "Display the number of characters in the inputbox",
	    sub {
		$hbox->remove( $label );
	    }
	);
    } else {
	    prnt "Couldn't find hbox";
    }

} else {
    prnt "Couldn't find input box";
}

#
# $Log: xchat-inputcount.pl,v $
# Revision 1.2  2009/05/07 20:33:28  gerald
# added a link to the version available in xchat CVS
#
# Revision 1.1  2009-05-07 20:13:03  gerald
# xchat script to add a character count next to xchat's input box.
# (useful when twittering, to see if you are within 140 characters)
#
#