#!/usr/bin/perl

use warnings;
use strict;
use threads;
use threads::shared;

use Glib qw(TRUE FALSE);
Glib::Object->set_threadsafe (TRUE);

use Gtk2 qw(-threads-init -init);
use Gtk2 qw(-init);

my $window = Gtk2::Window->new;
my $box = Gtk2::VBox->new;
my $buttonQuit = Gtk2::Button->new('Quit');
my $buttonStart = Gtk2::Button->new('Start');

$window->add ($box);

my $N_PBARS = 15;
my @pbars = ();
for (1..$N_PBARS) {
  my $pbar = Gtk2::ProgressBar->new;
  $box->add($pbar);
  push @pbars, $pbar;
}

$box->add($buttonQuit);
$box->add($buttonStart);

$buttonQuit->signal_connect(clicked => sub{Gtk2->main_quit});
$buttonStart->signal_connect(clicked => \&signal);
$window->show_all;

Gtk2::Gdk::Threads->enter;
Gtk2->main;
Gtk2::Gdk::Threads->leave;
exit;

sub signal {
  for my $index (1..$N_PBARS) {
    my $thread = threads->new(sub {
      my $n = 10;
      for (my $i = 0; $i <= $n; $i++) {
        select(undef, undef, undef, rand(0.3));
        #my $inner_thread = threads->new(sub {
          Gtk2::Gdk::Threads->enter;
          $pbars[$index - 1]->set_fraction($i/$n);
          $pbars[$index - 1]->set_text("Running $i of $n");
          Gtk2::Gdk::Threads->leave;
        #});
        #$inner_thread->detach;
      }
    });
    $thread->detach;
  }
}
