#! /usr/bin/perl -w

use strict;

use Gtk3 -init;
use Glib qw/TRUE FALSE/;

my $w_main;
my $main_treeview;

sub new_treestore {
    my ($parent, $storetype) = @_;

    my @titles = qw/Col1 Col2 Col3/;
    my $wscrolledwindow = Gtk3::ScrolledWindow->new;
    $wscrolledwindow->set_policy ('automatic','automatic');
    # Original packed menu first
    $parent->pack_start($wscrolledwindow, FALSE, TRUE, 5);
    my $model;
    my @collist = qw/ Glib::String
                      Glib::String
                      Glib::String/;
   if ($storetype eq 'tree') {
       $model = Gtk3::TreeStore->new (@collist) or die "Failed to create TreeStore";
   }
   elsif ($storetype eq 'list') {
       $model = Gtk3::ListStore->new (@collist) or die "Failed to create ListStore";
   }
   else {
       die "Unknown treestore type: $storetype";
   }

   my $treeview = Gtk3::TreeView->new ($model);
   $treeview->set_hexpand(TRUE);
   $treeview->set_vexpand(TRUE);

   for my $col (0 ... (scalar(@titles) - 1)) {
       my $rend = Gtk3::CellRendererText->new;
       my $txt;
       my $colhd = shift @titles;
       $txt = "text";
       $treeview->insert_column_with_attributes ( -1,$colhd,$rend,$txt=>$col);
   }

   $wscrolledwindow->add ($treeview);
   $wscrolledwindow->show_all;
   return $treeview;
}

sub populate_list {
    my ($ttl, $data) = @_;

    my $model_main = $main_treeview->get_model;

    my $topiter = $model_main->append(undef);
    $model_main->set ($topiter, 0, $ttl);

    foreach my $row (@$data) {
        my $childiter = $model_main->append ($topiter);

        for my $n (0 ... 2) {
            $model_main->set ($childiter, $n, $row->[$n]);
        }
    }
}

my $list1 = [
    ["l1_1a", "l1_1b", "l1_1c"],
    ["l1_2a", "l1_2b", "l1_2c"],
    ["l1_3a", "l1_3b", "l1_3c"],
    ["l1_4a", "l1_4b", "l1_4c"]
];

my $list2 = [
    ["l2_1a", "l2_1b", "l2_1c"],
    ["l2_2a", "l2_2b", "l2_2c"],
    ["l2_3a", "l2_3b", "l2_3c"],
    ["l2_4a", "l2_4b", "l2_4c"]
];

$w_main = Gtk3::Window->new;
$w_main->signal_connect ('delete_event' => sub {Gtk3->main_quit});
$w_main->set_default_size (200, 100);
my $vbox = Gtk3::Box->new('vertical',3);
$main_treeview = new_treestore($vbox, 'tree');
my $selection = $main_treeview->get_selection;
$selection->set_mode("single");
my $iter = undef;
populate_list("List 1",$list1);
populate_list("List 2",$list2);
$w_main->add ($vbox);
$w_main->show_all;
Gtk3->main;
