
use strict;
use warnings;
use Xchat qw(:all);
use Glib qw(TRUE FALSE);
use Gtk2 -init;
initialize();

sub initialize {
	my $scrollbar = get_scrollbar();

	return unless $scrollbar;
	my $adjustment = $scrollbar->get_adjustment;

	hook_command( "pause", sub {
		pause( $scrollbar, $adjustment );
		return EAT_XCHAT;
	});

	hook_command( "pauseall", sub {
		my $original = get_context;
		for my $channel ( grep { $_->{type} == 2 } get_list "channels" ) {
			if( set_context( $channel->{context} ) ) {
				command( "GUI FOCUS" );
				pause( $scrollbar, $adjustment );
			}
		}

		set_context( $original );
		command( "GUI FOCUS" );
		return EAT_XCHAT;
	});
}

sub pause {
	my $scrollbar  = shift;
	my $adjustment = shift;
	my $new_value  = $scrollbar->get_value;
	$new_value--;

	if ( $new_value > 0 ) {
		$scrollbar->set_value( $new_value );
	}
}

sub get_ptr {
	if( $^O ne 'MSWin32' ) {
		return get_info "win_ptr";
	} else {
		my $session = unpack( "P1532", pack( "L", get_context() ) );
		my $gui_address = unpack( "x1516L", $session );
		my $session_gui = unpack( "P232", pack( "L", $gui_address ) );
		my $win_ptr = unpack( "x8L", $session_gui );
		return $win_ptr;
	}
}

sub get_scrollbar {
	my $widget = Glib::Object->new_from_pointer( get_ptr() , 0 );

	my @candidates = ($widget);

	while( @candidates ) {
		my $candidate = shift @candidates;

		next unless $candidate->isa( "Gtk2::Widget" );
		if( $candidate->isa( "Gtk2::VScrollbar" ) ) {
			return $candidate;
		} elsif ( $candidate->isa( "Gtk2::Container" ) ) {
			push @candidates, $candidate->get_children;
		}
	}

	return;
}

