#     G-Tablix, graphical user interface for Tablix
#     Copyright (C) 2004,2005 Bostjan Spetic
# 
#     This program 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 2 of the License, or
#     (at your option) any later version.
# 
#     This program 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 this program; if not, write to the Free Software
#     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# author: Bostjan Spetic, igzebedze@cyberpipe.org
# module that plot graphs
# 30.1.2005

# parameters

use strict;

sub on_spinbutton_tablix_l_changed {
	my $me = shift;
	my $form = &get_form;
	&set_tablix_command_line;
}
sub on_spinbutton_tablix_t_changed {
	my $me = shift;
	my $form = &get_form;
	&set_tablix_command_line;
}
sub on_spinbutton_tablix_n_changed {
	my $me = shift;
	my $form = &get_form;
	&set_tablix_command_line;
}
sub on_checkbutton_tablix_resume_toggled {
	&set_tablix_command_line;
}
sub on_checkbutton_tablix2_toggled {
	&set_tablix_command_line;
}
sub set_tablix_command_line {
	my $form = &get_form;
	my $tempentry = $form->get_widget('entry_temp');
	my $tempdir = &get_temp;
	my $tablix = &get_external(&get_tablix);
	my $r = $form->get_widget('checkbutton_tablix_resume')->get_active;
	if ($r) { 
		$tempdir = $tempentry->get_text;
	}
	my $l = $form->get_widget('spinbutton_tablix_l')->get_text;
	my $t = $form->get_widget('spinbutton_tablix_t')->get_text;
	my $n = $form->get_widget('spinbutton_tablix_n')->get_text;	
	$tablix = "$tablix -n $n -l $l -t $t -o $tempdir";
	if ($r) { $tablix = $tablix.' -r'; }
	$form->get_widget('entry_tablix_params')->set_text($tablix);
}
# ---------------------- tablix ----------------------------------
sub on_entry_tablix_params_activate { &on_button_tablix_start_clicked; }
sub on_button_tablix_start_clicked {
	my $form = &get_form;
	my $filename0 = (split/ - /,($form->get_widget('window_main')->get_title))[1];
	my $log = $form->get_widget('label_tablix_log');
	my $tempdir = &get_temp;
	my $filename = "$tempdir/temp.xml";
	my $tablix = $form->get_widget('entry_tablix_params')->get_text;
	my $version = 1;
		if ($tablix =~ /tablix2/) { $version = 2; }
	
# check for pvmd	
	if (!&get_process('pvmd')) { 
		&check(gettext("No pvm was found running...\nuse the Tools->XPVM"),'error',1); 
		return 0; 
	} else {
# check the project
		$log->set_text(gettext("Testing project definitions... "));
		if (!&do_internal_test(undef,1)) {
		my $check = &check(gettext("Errors were found in the project. 
Run 'Tools->Check' for more informations.\n
Do you want to continue anyway?")); 
		if ($check eq 'cancel') { return 0; }
	}

# if the user does not want to try to continue, empty temp dir and export project
# otherwise just set tablix to run 
	$log->set_text(gettext("Exporting project to temporary file... "));
	my $r = $form->get_widget('checkbutton_tablix_resume')->get_active;
	if (!$r) {
		system ("rm -f $tempdir/*");
		&save_file ($filename,$version,1);	# WARN: doesn't save the project...
		if (&get_file_type($filename) eq 'gzip') {
			#system ("cp -f $filename $filename.gz");
			system ("gunzip $filename");
		} else {
			#system ("cp -f $filename0 $filename");			
		}
	}

	$form->get_widget('button_tablix_start')->set('sensitive' => 0);
	$form->get_widget('button_tablix_kill')->set('sensitive' => 1);
# init...
	my $image = $form->get_widget('image_plot'); 
	my $label_errors = $form->get_widget('label_tablix_errors');
	my $label_mandas = $form->get_widget('label_tablix_mandas');
	my $label_speed = $form->get_widget('label_tablix_speed');
	my $label_nodes = $form->get_widget('label_tablix_nodes');
	my $label_time = $form->get_widget('label_tablix_time');
	my $label_gen = $form->get_widget('label_tablix_generation');				
	my $label_res = $form->get_widget('spinbutton_plot_res');	
	my $label_status = $form->get_widget('label_plot_status');	
	
	$log->set_text(gettext("Calling Tablix... ").$tablix);
	my $pid = open (TABLIX,'export LC_ALL=C ; '.$tablix." -o $tempdir/ $filename |");
	$form->get_widget('label_pid')->set_text($pid);

	my $line = "";
	my $errors = "";

	Glib::IO->add_watch (fileno TABLIX, ['in', 'hup'], sub {
		my $no = sysread(TABLIX, my $lines, 40);
		if (!defined $no) {
			close TABLIX;
			#system ("rm $tempdir/*");			
			&check(gettext("Undefined error occured while trying to run Tablix.\n"),'error',1); 
			&on_button_tablix_kill_clicked; 
			return FALSE;
		} elsif ($no == 0) {
			close TABLIX;
			if ($errors) { 
				&check(gettext("Tablix reported:")." \n$errors",'info');
			} #else { &success; }
			if (-e "$tempdir/result0.xml") {
				&success;
			}
			&on_button_tablix_kill_clicked; 
			return FALSE;
		} else {			
			$line = $line.$lines;
			#my @linne = split/running/,$line;
			my @linne = split/\n/,$line;
		if (@linne > 1) {
			$lines = shift(@linne);
			$line = join("\n",@linne);
 			$log->set_text($lines);
	  		my @line = split/ /,$lines;
	  	   if ($line[1] eq "reports") {
		# 			[40008] reports 25758 (418) at 48, 760.0 GPM, 00:00:15 elapsed, 4/4 running
	  			my (undef,undef,$errors,$mands,undef,$gens,$speed,undef,$time,undef,$nodes) = @line;
	  			$gens =~ s/\,//g;

	 	  		$label_errors->set_text($errors);
	 	  		$label_mandas->set_text($mands);
	 	  		$label_time->set_text($time);
	 	  		$label_speed->set_text($speed);
	 	  		$label_nodes->set_text($nodes);
	 	  		$label_gen->set_text($gens);

				my $resolution = $label_res->get_value;
				if (($resolution > 0) and (($gens % $resolution) == 0)) { 
					&on_button_plot_now_clicked;
				}		 	  
 	 	 	 } elsif ($line[1] ne 'TABLIX') {
	#(((split/:/,$line[0])[1] eq "xmlsup]") or ($line[1] eq 'fatal:')) {
 					$errors = $errors."$lines\n";
			 }
	 	  }
	 	  return 1;
	  } 
	});
	}
}
sub success {
	my ($form,undef,$defined_tt_entries,$uid_tt_entries) = &get_vars;
	my $tempdir = &get_temp;
	my @results = split/\n/,readpipe("ls $tempdir/result*.xml");
	if ($#results >= 0) {
	 	my $note = gettext("It seems that Tablix completed successfuly.\nResults are placed in file(s):\n");
		&clear_results;			# (in ttview.pm)
	 	foreach my $result (@results) {
	 		$note = $note."\t$result\n";
			&load_result($result);	# (in ttview.pm)
	 	}
		$note = $note.gettext("\nThey were loaded into lists in the 'Timetable' tab.");
		&check($note,'info');
	} 
}
sub on_button_tablix_kill_clicked {
	my $form = &get_form;
	$form->get_widget('button_tablix_start')->set('sensitive' => 1);
	$form->get_widget('button_tablix_kill')->set('sensitive' => 0);
	my $tablix = &get_tablix;
	my $pid = $form->get_widget('label_pid')->get_text;
	if (defined $pid) {
	 	system ("kill $pid");
	 	system ("killall $tablix"."_kernel");
#		system ("killall $tablix");
		#system ("rm $tempdir/*");
	 	$form->get_widget('label_tablix_log')->set_text("Tablix Stopped...");	
		$form->get_widget('label_pid')->set_text("");
	}
}

sub on_button_plot_now_clicked {
	my $form = &get_form;
	my $tempdir = &get_temp;
	my $filename = "$tempdir/temp.xml";
	my $tablix = &get_tablix;
	my $tablixplot = &get_external($tablix."_plot");
	my %style;
	if ($tablix eq 'tablix2') {
		%style = (gettext('conv-fitness') => 'conv-fitness',
					 gettext('fit-fitness') => 'fit-fitness',
					 gettext('functions') => 'functions'
					);
	} elsif ($tablix eq 'tablix') {
		%style = (gettext('conv-grade') => 'conv-grade',
					 gettext('conv-mandatory') => 'conv-mandatory',
					 gettext('fit-grade') => 'fit-grade',
					 gettext('modules') => 'modules'
					);
	} else {
		return 0;
	}
	if (-e $filename) {
	 	my $image = $form->get_widget('image_plot'); 
			my $x = $image->get('width-request');
			my $y = $image->get('height-request');
			my $scale = $x.'x'.$y;
	 	my $label_status = $form->get_widget('label_plot_status');		
	 	
		my $format = &get_format('svg');  
	 	my $gens = $form->get_widget('label_tablix_generation')->get_text;
	 	my $style = $style{$form->get_widget('entry_plot_style')->get_text};
		my $plot_scale = $form->get_widget('spinbutton_plot_scale')->get_value;
			if ($plot_scale == 0) { $plot_scale = " ";
			} else { $plot_scale = " --scale $plot_scale "; }
	 	
		$label_status->set_text(gettext("Plotting convergence graph for generation").
										" $gens; ".gettext("using format").
										" $format ".gettext("and size")." $scale.");	  
	   my $plotline = "SVGOUTPUT=\"$tempdir/example.svg\" $tablixplot --$style$plot_scale$tempdir/";
		if (($style eq "modules") or ($style eq 'functions')) { $plotline = $plotline."conv0.txt $filename"; }
	 	system ($plotline); 		
	 	if ($format ne 'svg') { 
			system ("convert $tempdir/example.svg -resize $scale $tempdir/example.$format"); }	 	
		my $pixbuf = Gtk2::Gdk::Pixbuf->new_from_file_at_size("$tempdir/example.$format",$x,$y);
		$image->set_from_pixbuf($pixbuf);		
	}
}
# [40008] reports 25758 (418) at 48, 760.0 GPM, 00:00:15 elapsed, 4/4 running
#                 ^      ^       ^   ^          ^                 ^
#                 |      |       |   |          |    _____________|
#                 |      |       |   |          |   |             
#                 |      |       |   |          |   |_ Number of running  
#                 |      |       |   |          |      nodes / number of 
#                 |      |       |   |          |      nodes in the cluster 
#                 |      |       |   |          |
#                 |      |       |   |          |_ Elapsed time since Tablix
#                 |      |       |   |             was started.
#                 |      |       |   |
#                 |      |       |   |_ Total generations per minute count for
#                 |      |       |      the cluster.
#                 |      |       |      
#                 |      |       |_ Population serial number
#                 |      |
#                 |      |_ Sum of "mandatory" errors.
#                 |         This must be zero for at least 300
#                 |         generations for Tablix to stop.
#                 |
#                 |_ Weighted sum of all errors

sub on_button_save_plot_clicked {
	my $form = &get_form;
	my $filename = &get_filename("save",gettext("Save plot as PNG"));
	if ($filename ne 'cancel') { 
		my $plot = $form->get_widget('image_plot')->get_pixbuf;
		$plot->save($filename,'png');
		&write_to_statusbar(gettext("Plot saved to file")." $filename.");
	}
}
sub on_button_plus_y_clicked {
	my $form = &get_form;
	my $image = $form->get_widget('image_plot'); 
	my $x = $image->get('width-request');
	my $y = $image->get('height-request');
	$image->set('width-request' => ($x * 1.5));	
	$image->set('height-request' => ($y * 1.5));	
	&on_button_plot_now_clicked;
}
sub on_button_less_y_clicked {
	my $form = &get_form;
	my $image = $form->get_widget('image_plot'); 
	my $x = $image->get('width-request');
	my $y = $image->get('height-request');
	$image->set('width-request' => ($x * 0.75));	
	$image->set('height-request' => ($y * 0.75));	
	&on_button_plot_now_clicked;
}
sub on_button_norm_y_clicked {
	my $form = &get_form;
	my $image = $form->get_widget('image_plot'); 
	$image->set('width-request' => 400);	
	$image->set('height-request' => 300);	
	&on_button_plot_now_clicked;
}
sub on_entry_plot_style_changed { &on_button_plot_now_clicked; }

return 1;
