#! /usr/bin/perl

use Gtk2::ImageView;
use Gtk2 '-init';

use strict;
use warnings;
use utf8;

my $window = Gtk2::Window->new();
$window->set_default_size( 650, 500 );
$window->signal_connect( 'delete-event' => sub {Gtk2->main_quit; return 0;} );

my $view        = Gtk2::ImageView->new;
my $pixbuf 	= &fct_take_screenshot(undef, $view);

my $button = Gtk2::Button->new_with_label('Take screenshot');
$button->signal_connect('clicked' => \&fct_take_screenshot, $view );

#pack widgets
my $vbox = Gtk2::VBox->new(0, 0);
$vbox->pack_start($button, 0, 0, 0);
$vbox->pack_start_defaults($view);

$window->add($vbox);

$window->show_all;

Gtk2->main();

0;

sub fct_take_screenshot {
	my $button = shift;
	my $view = shift;

	#!!!!!!uncomment the following two lines to fix the memory leak here!!!!!!
	my $selector    = Gtk2::ImageView::Tool::Selector->new($view);
	$view->set_tool($selector);

	#root window
	my $root = Gtk2::Gdk->get_default_root_window;
	my ($x, $y, $w, $h) = $root->get_geometry;

	my $pixbuf = Gtk2::Gdk::Pixbuf->get_from_drawable(
		$root, undef, 0, 0, 0, 0,
		$w,
		$h
	);

	my $scaled_pixbuf = $pixbuf->scale_simple(640, 480,'bilinear');

	$view->set_pixbuf($scaled_pixbuf, 1);
	$view->show_all;		
} 


