#! /usr/bin/env perl

###################################################
#
#  Copyright (C) 2008-2013 Mario Kemper <mario.kemper@gmail.com>
#
#  This file is part of Shutter.
#
#  Shutter 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 3 of the License, or
#  (at your option) any later version.
#
#  Shutter 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 Shutter; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
###################################################

use utf8;
use strict;
use warnings;

BEGIN {
	use Glib::Object::Introspection;
	Glib::Object::Introspection->setup(
		basename => 'GdkX11',
		version  => '3.0',
		package  => 'Gtk3::GdkX11',
	);
}

use Gtk3 '-init';
use Image::Magick;
use POSIX qw/setlocale/;
use Locale::gettext;
use Glib qw/TRUE FALSE/;
use FindBin '$Bin';    #path where plugin is located
use File::Temp qw/ tempfile tempdir /;
use Time::HiRes qw/usleep/;

#load modules at custom path at runtime
#--------------------------------------
require lib;
import lib $ENV{'SHUTTER_ROOT'}."/share/shutter/resources/modules";

#proc (Thanks to Michael Schilli)
require Proc::Simple;

#load shutter's modules
#--------------------------------------
require Shutter::App::SimpleDialogs;

#Set LC_NUMERIC to C to prevent decimal commas (or anything else)
setlocale(LC_NUMERIC, "C");	
#configure gettext using ENV Variable (setup during shutter start)
setlocale( LC_MESSAGES, "" );
my $d = Locale::gettext->domain("shutter-plugins");
$d->dir( $ENV{'SHUTTER_INTL'} );

#icontheme to determine if icons exist or not
#in some cases we deliver fallback icons
my $icontheme = Gtk3::IconTheme::get_default();
$icontheme->append_search_path($ENV{'SHUTTER_ROOT'} . "/share/icons");

#shutter will ask for some infos
my %plugin_info = 	( 	'name'	=> $d->get( "Barrel Distortion" ),
						'sort'	=> $d->get( "Effect" ),
						'tip'	=> $d->get("Apply a distortion effect to your screenshot"),
					);

binmode( STDOUT, ":utf8" );
if ( exists $plugin_info{$ARGV[ 0 ]} ) {
	print $plugin_info{$ARGV[ 0 ]};
	exit;
}

#these variables are passed to the plugin
my $socket_id = $ARGV[ 0 ];
my $filename  = $ARGV[ 1 ];
my $width     = $ARGV[ 2 ];
my $height    = $ARGV[ 3 ];
my $filetype  = $ARGV[ 4 ];

#decode filename
utf8::decode $filename;

my $plug = Gtk3::Plug->new( $socket_id );
$plug->set_border_width( 10 );

$plug->signal_connect( destroy => sub { Gtk3->main_quit } );

#configure buttons and other needed controls
my $c1_label = Gtk3::Label->new( $d->get( "A:" ) );
my $c1_sbutton = Gtk3::SpinButton->new_with_range( -1, 1, 0.1 );
$c1_sbutton->set_value( 0.2 );

my $c2_label = Gtk3::Label->new( $d->get( "B:" ) );
my $c2_sbutton = Gtk3::SpinButton->new_with_range( -1, 1, 0.1 );
$c2_sbutton->set_value( 0 );

my $c3_label = Gtk3::Label->new( $d->get( "C:" ) );
my $c3_sbutton = Gtk3::SpinButton->new_with_range( -1, 1, 0.1 );
$c3_sbutton->set_value( 0 );

my $c4_label = Gtk3::Label->new( $d->get( "D:" ) );
my $c4_sbutton = Gtk3::SpinButton->new_with_range( -1, 1, 0.1 );
$c4_sbutton->set_value( 1.0 );

$c1_label->set_tooltip_text(
	$d->get(
		"The parameter d describes the linear scaling of the image. Using d=1, and a=b=c=0 leaves the image as it is. Choosing other d-values scales the image by that amount. a,b and c distort the image. Using negative values shifts distant points away from the center.\n\nDefined by Barrel Correction Distortion, by Helmut Dersch.\nhttp://www.all-in-one.ee/~dersch/barrel/barrel.html"
	)
);

	$c1_sbutton->set_tooltip_text(
	$d->get(
		"The parameter d describes the linear scaling of the image. Using d=1, and a=b=c=0 leaves the image as it is. Choosing other d-values scales the image by that amount. a,b and c distort the image. Using negative values shifts distant points away from the center.\n\nDefined by Barrel Correction Distortion, by Helmut Dersch.\nhttp://www.all-in-one.ee/~dersch/barrel/barrel.html"
	)
);

	$c2_label->set_tooltip_text(
	$d->get(
		"The parameter d describes the linear scaling of the image. Using d=1, and a=b=c=0 leaves the image as it is. Choosing other d-values scales the image by that amount. a,b and c distort the image. Using negative values shifts distant points away from the center.\n\nDefined by Barrel Correction Distortion, by Helmut Dersch.\nhttp://www.all-in-one.ee/~dersch/barrel/barrel.html"
	)
);

	$c2_sbutton->set_tooltip_text(
	$d->get(
		"The parameter d describes the linear scaling of the image. Using d=1, and a=b=c=0 leaves the image as it is. Choosing other d-values scales the image by that amount. a,b and c distort the image. Using negative values shifts distant points away from the center.\n\nDefined by Barrel Correction Distortion, by Helmut Dersch.\nhttp://www.all-in-one.ee/~dersch/barrel/barrel.html"
	)
);

	$c3_label->set_tooltip_text(
	$d->get(
		"The parameter d describes the linear scaling of the image. Using d=1, and a=b=c=0 leaves the image as it is. Choosing other d-values scales the image by that amount. a,b and c distort the image. Using negative values shifts distant points away from the center.\n\nDefined by Barrel Correction Distortion, by Helmut Dersch.\nhttp://www.all-in-one.ee/~dersch/barrel/barrel.html"
	)
);

	$c3_sbutton->set_tooltip_text(
	$d->get(
		"The parameter d describes the linear scaling of the image. Using d=1, and a=b=c=0 leaves the image as it is. Choosing other d-values scales the image by that amount. a,b and c distort the image. Using negative values shifts distant points away from the center.\n\nDefined by Barrel Correction Distortion, by Helmut Dersch.\nhttp://www.all-in-one.ee/~dersch/barrel/barrel.html"
	)
);

	$c4_label->set_tooltip_text(
	$d->get(
		"The parameter d describes the linear scaling of the image. Using d=1, and a=b=c=0 leaves the image as it is. Choosing other d-values scales the image by that amount. a,b and c distort the image. Using negative values shifts distant points away from the center.\n\nDefined by Barrel Correction Distortion, by Helmut Dersch.\nhttp://www.all-in-one.ee/~dersch/barrel/barrel.html"
	)
);

	$c4_sbutton->set_tooltip_text(
	$d->get(
		"The parameter d describes the linear scaling of the image. Using d=1, and a=b=c=0 leaves the image as it is. Choosing other d-values scales the image by that amount. a,b and c distort the image. Using negative values shifts distant points away from the center.\n\nDefined by Barrel Correction Distortion, by Helmut Dersch.\nhttp://www.all-in-one.ee/~dersch/barrel/barrel.html"
	)
);

my $back_color_label = Gtk3::Label->new( $d->get("Background color"). ":" );
my $back_color = Gtk3::ColorButton->new();
$back_color->set_rgba( Gtk3::Gdk::RGBA::parse('gray') );
$back_color->set_alpha( int( 0 * 65535 ) );
$back_color->set_use_alpha(TRUE);
$back_color->set_title( $d->get("Choose background color") );

#all labels on the left side 
#need to have the same size
my $sgl = Gtk3::SizeGroup->new ('both');
$sgl->set ('ignore-hidden' => FALSE);
$sgl->add_widget($c1_label);
$sgl->add_widget($c2_label);
$sgl->add_widget($c3_label);
$sgl->add_widget($c4_label);

#we define two Gtk3::Image widgets
#to store the screenshot
#and a throbber that is shown while the changes are processed
my $preview =
	Gtk3::Image->new_from_pixbuf(
	   Gtk3::Gdk::Pixbuf->new_from_file_at_scale( $filename, 300, 300, TRUE ) );

my $preview_throb =
	Gtk3::Image->new_from_file( $ENV{'SHUTTER_ROOT'}."/share/shutter/resources/icons/throbber.gif" );

my $sg = Gtk3::SizeGroup->new ('both');
$sg->set ('ignore-hidden' => FALSE);
$sg->add_widget($preview);
$sg->add_widget($preview_throb);


#we define three Gtk3::Button widgets
#to refresh, save and cancel the plugin's work
my $refresh_btn = Gtk3::Button->new_from_stock( 'gtk-refresh' );
$refresh_btn->signal_connect( 'clicked', \&fct_imagemagick_bardistortion,
							  'refresh' );

my $save_btn = Gtk3::Button->new_from_stock( 'gtk-save' );
$save_btn->signal_connect( 'clicked', \&fct_imagemagick_bardistortion, 'save' );

my $cancel_btn = Gtk3::Button->new_from_stock( 'gtk-cancel' );
$cancel_btn->signal_connect( 'clicked' => sub { Gtk3->main_quit; exit 2; }, 'cancel' );

#define the gui layout
my $hbox1      = Gtk3::HBox->new( FALSE, 8 );
my $hbox2      = Gtk3::HBox->new( FALSE, 8 );
my $hbox3      = Gtk3::HBox->new( FALSE, 8 );
my $hbox4      = Gtk3::HBox->new( FALSE, 8 );
my $hbox5      = Gtk3::HBox->new( FALSE, 8 );

my $hbox_row1 = Gtk3::HBox->new( TRUE, 8 );
my $hbox_row2 = Gtk3::HBox->new( FALSE, 8 );

my $vbox_param = Gtk3::VBox->new( FALSE,  8 );
my $vbox_left = Gtk3::VBox->new( FALSE, 8 );
my $vbox_right = Gtk3::VBox->new( FALSE, 8 );

my $hbox_btn  = Gtk3::HBox->new( TRUE,  8 );
my $vbox_btn  = Gtk3::VBox->new( FALSE, 8 );
my $vbox_main = Gtk3::VBox->new( FALSE, 8 );

#packing
$hbox1->pack_start( $c1_label, FALSE, TRUE, 5 );
$hbox1->pack_start( $c1_sbutton, TRUE,  TRUE, 5 );

$hbox2->pack_start( $c2_label, FALSE, TRUE, 5 );
$hbox2->pack_start( $c2_sbutton, TRUE,  TRUE, 5 );

$hbox3->pack_start( $c3_label, FALSE, TRUE, 5 );
$hbox3->pack_start( $c3_sbutton, TRUE,  TRUE, 5 );

$hbox4->pack_start( $c4_label, FALSE, TRUE, 5 );
$hbox4->pack_start( $c4_sbutton, TRUE,  TRUE, 5 );

$hbox5->pack_start( $back_color_label, FALSE, TRUE, 5 );
$hbox5->pack_start( $back_color, TRUE,  TRUE, 5 );

#row 1
$hbox_row1->pack_start( $hbox5, TRUE, TRUE, 0 );

#controls on the left side
$vbox_left->pack_start( $hbox1, TRUE, TRUE, 0 );
$vbox_left->pack_start( $hbox2, TRUE, TRUE, 0 );
$vbox_left->pack_start( $hbox3, TRUE, TRUE, 0 );
$vbox_left->pack_start( $hbox4 , TRUE, TRUE, 0);

#preview
$vbox_right->pack_start( $preview, TRUE, TRUE, 0 );
$vbox_right->pack_start( $preview_throb, TRUE, TRUE, 0 );

#row 2
$hbox_row2->pack_start( $vbox_left, TRUE, TRUE, 0 );
$hbox_row2->pack_start( $vbox_right, TRUE, TRUE, 0 );

$vbox_param->pack_start( $hbox_row1, TRUE, TRUE, 5 );
$vbox_param->pack_start( $hbox_row2, TRUE, TRUE, 5 );

$vbox_main->pack_start( $vbox_param, FALSE, TRUE, 5 );
$vbox_main->pack_start( $refresh_btn, TRUE, TRUE, 5 );

$hbox_btn->pack_start( $cancel_btn, TRUE, TRUE, 5 );
$hbox_btn->pack_start( $save_btn,   TRUE, TRUE, 5 );

$vbox_main->pack_start( $hbox_btn,  TRUE, TRUE, 5 );

$plug->add( $vbox_main );

$plug->show_all;

#hide the preview widget at startup 
$preview->hide;

#create tempfile
my ( $tmpfh, $tmpfilename ) = tempfile();
#png format
$tmpfilename .= ".png";

#we fork a child process to do the work
my $process = Proc::Simple->new;
#create tempfiles for subprocess outputs
my ( $tmpfh_stdout, $tmpfilename_stdout ) = tempfile(UNLINK => 1);
my ( $tmpfh_stderr, $tmpfilename_sterr ) = tempfile(UNLINK => 1);
$process->redirect_output ($tmpfilename_stdout, $tmpfilename_sterr);

#generate first preview at startup
Glib::Idle->add (
	sub{
		&fct_imagemagick_bardistortion( undef, 'refresh' );
		return FALSE;	
	}, 
undef);

#lets'start
Gtk3->main;

sub fct_imagemagick_bardistortion {
	my ( $widget, $data ) = @_;

	$save_btn->set_sensitive(FALSE);

	if ( $data eq 'save' ) {

		my $image = Image::Magick->new;
		$image->ReadImage( $tmpfilename );
		$image->WriteImage( filename => $filename );

		#delete temp files
		unlink $tmpfilename;

		Gtk3->main_quit;
		return TRUE;
	} else {

		$preview->hide;
		$preview_throb->show_all;

		$process->start(
			sub {
				&apply_effect();
				POSIX::_exit(0);
			}
		);

		#so we can update the gui
		while ( $process->poll ) {
			&fct_update_gui;
			usleep 100000;
		}
		
		eval{		
			$preview->set_from_pixbuf( Gtk3::Gdk::Pixbuf->new_from_file_at_scale(
										$tmpfilename, 300, 300, TRUE)
									 );
		};
		#error -> read output from tempfiles
		if($@){		
			#store error here
			my $error_string = "Plugin error:\n";
			
			#reading stdout from file
			while (<$tmpfh_stdout>){
				$error_string .= $_;	
			}
			#reading stderr from file
			while (<$tmpfh_stderr>){
				$error_string .= $_;	
			}

			#get the parent window of the plug
			require X11::Protocol;
			my $x11 = X11::Protocol->new( $ENV{ 'DISPLAY' } );
			
			my $plugp = Gtk3::GdkX11::X11Window->foreign_new_for_display(Gtk3::Gdk::Display::get_default(), find_wm_window( $x11, $plug->get_id ));
			
			#show error message
			my $shutter_dialog = Shutter::App::SimpleDialogs->new($plug, $plugp);
			$shutter_dialog->dlg_error_message( 
				sprintf ( $d->get(  "Error while executing plugin %s." ), "'" . $plugin_info{'name'} . "'" ) ,
				$d->get( "There was an error executing the plugin." ),
				undef, undef, undef,
				undef, undef, undef,
				$error_string
			);
			
			#delete temp files
			unlink $tmpfilename;

			Gtk3->main_quit;
			exit 1;	
		}

		$save_btn->set_sensitive(TRUE);
		$preview->show_all;
		$preview_throb->hide;

		return TRUE;
	}
}

sub apply_effect {	

	my $color = $back_color->get_color;

	#execute imagemagick command		
	system (
        qw/convert -virtual-pixel Background/,
        -background => sprintf( "#%04x%04x%04x%04x", $color->red, $color->green, $color->blue, $back_color->get_alpha ),
        -distort => Barrel => join(' ',$c1_sbutton->get_value, $c2_sbutton->get_value, $c3_sbutton->get_value, $c4_sbutton->get_value),
        $filename, $tmpfilename
    );
												
}

sub fct_update_gui {

	while ( Gtk3::events_pending() ) {
		Gtk3::main_iteration();
	}
	Gtk3::Gdk::flush();

	return TRUE;
}

sub find_wm_window {
	my $x11  = shift;
	my $xid  = shift;

	do {
		my ( $qroot, $qparent, @qkids ) = $x11->QueryTree($xid);
		return undef unless ( $qroot || $qparent );
		return $xid if ( $qroot == $qparent );
		$xid = $qparent;
	} while (TRUE);
}

1;
