# Arch Perl library, Copyright (C) 2004 Mikhael Goikhman, Enno Cramer
#
# 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

use 5.006;
use strict;
use warnings;

package ArchWay::Widget::Tree;

use Glib qw(TRUE FALSE);
use Gtk2;

use base qw(Gtk2::TreeView);

sub new ($$) {
	my $class = shift;
	my $model = shift;

	my $self = bless Gtk2::TreeView->new($model), $class;
	$self->set_rules_hint(TRUE);

	return $self;
}

sub add_columns ($@) {
	my $self = shift;

	foreach my $col (@_) {
		my $column = Gtk2::TreeViewColumn->new;
		$column->set_title($col->{title});

		foreach my $rdr ($col->{renderer} || @{$col->{renderers}}) {
			my $renderer = Gtk2::Object->new(
				$rdr->{class},
				%{$rdr->{static}},
			);

			$column->pack_start($renderer, TRUE);
			$column->set_attributes($renderer, %{$rdr->{dynamic}});
		}

		$column->set_resizable(TRUE);
		$column->set_sort_column_id($col->{sort_column})
			if exists $col->{sort_column};

		$self->append_column($column);
	}
}

sub get_selected ($@) {
	my $self = shift;

	my $model = $self->get_model;
	my $row = ($self->get_selection->get_selected_rows)[0];

	return $model->get($model->get_iter($row), @_);
}

sub get_all_selected ($@) {
	my $self = shift;

	my $model = $self->get_model;
	my @rows = $self->get_selection->get_selected_rows;

	return map { [ $model->get($model->get_iter($_), @_) ] } @rows;
}

sub select ($&) {
	my $self = shift;
	my $sub = shift;

	my $model = $self->get_model;
	my $iter  = $model->get_iter_first;

	if (defined $iter) {
		return $self->_select($model, $iter, $sub);
	} else {
		return 0;
	}
}

sub _select($$$&) {
	my ($self, $model, $iter, $sub) = @_;

	if ($sub->($model, $iter)) {
		$self->expand_to_path($model->get_path($iter));
		$self->get_selection->select_iter($iter);
	}

	my $child = $model->iter_children($iter);
	while (defined $child) {
		$self->_select($model, $child, $sub);
		$child = $model->iter_next($child);
	}
}

1;

__END__
