#!/usr/bin/perl

use warnings;
use strict;
use threads;
use threads::shared;
use Thread::Semaphore;
use Gtk2 qw(-init -threads-init);
use Glib qw(TRUE FALSE);             # To get TRUE and FALSE

Glib::Object->set_threadsafe (TRUE);

my $semaphore = Thread::Semaphore->new(0);
my @queue:shared;
my $process:shared;
my $die:shared;
my $thread = threads->new(sub {
 while (TRUE) {
  $semaphore->down;
  last if $die;
  eval $process;
 }
});

# Create the windows
my $window = Gtk2::Window->new('toplevel');
my $box = Gtk2::VBox->new;
my $pbar = Gtk2::ProgressBar->new;
my $buttonQuit = Gtk2::Button->new('Quit');
my $buttonStart = Gtk2::Button->new('Start');

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

# We should also link this to the destroy message on the main window,
# this is just quick and dirty
$buttonQuit->signal_connect(clicked => sub{Gtk2->main_quit});
$buttonStart->signal_connect(clicked => sub{
 $process = '
 my $n = 4;
  for (my $i = 0; $i <= $n; $i++) {
   sleep(1);
   push @queue, $i/$n;
   push @queue, "Running $i of $n";
  }';
 $semaphore->up;
 Glib::Timeout->add (200, sub{
  if (@queue) {
   my $fraction = shift @queue;
   my $text = shift @queue;
   $pbar->set_fraction($fraction);
   $pbar->set_text($text);
   if ($fraction == 1) {
    $thread->join;
    return FALSE;
   }
  }
  return TRUE;
 });
});
$window->show_all;
Gtk2->main;
$die = TRUE;
$semaphore->up;
$thread->join;
