#!/usr/bin/perl
# Mandrake Remote FrameBuffer 
#
# Copyright (C) 2001-2002 MandrakeSoft Daouda Lo <daouda@mandrakesoft.com>
#
# 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, 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.
###############################################################################

use Config;
use Gtk;
use POSIX;
use lib qw(/usr/lib/libDrakX);
init Gtk;
Gtk->set_locale;
use MDK::Common;
use c;
require Gtk;
require Gtk::Gdk::ImlibImage;
use my_gtk qw(:helpers :wrappers :ask);

Gtk::Gdk::ImlibImage->init;

#-------------------------------------------------------------
# i18n routines
# IMPORTANT: next two routines have to be redefined here to
#         get correct namespace (rfbdrake instead of libDrakX)
#         (This version is now UTF8 compliant - Sg 2001-08-31)
#-------------------------------------------------------------

sub _ {
    my $s = shift @_; my $t = translate($s);
    sprintf $t, @_;
}

sub translate {
    my ($s) = @_;
    $s ? c::dgettext('rfbdrake', $s) : '';
}

my $_version = "0.8.2";
my $_copyright = "2001, 2002";
my $pix_dir="/usr/share/rfbdrake/pixmaps";

init();

Gtk->main_iteration while Gtk->events_pending;
Gtk->main;

sub init() 
{
    my $window_global = new Gtk::Window -toplevel;
    $window_global->set_policy($false,$false,$true);
    $window_global->set_position( 1 );
    $window_global->border_width( 5 );
    $window_global->set_title(_("Remote Framebuffer"));
    $window_global->set_usize(540, 430);
    $window_global->signal_connect( "delete_event", \&quit_global);
    my $nb = new Gtk::Notebook;
    my $client_rad=new Gtk::RadioButton(_("Want to take control (linux client)"));
    my $server_rad=new Gtk::RadioButton(_("Allow control of my machine (linux server)"),$client_rad);
    my $win_rad=new Gtk::RadioButton(_("Windows Terminal Services"),$client_rad);
    my $vbox_global=new Gtk::VBox(0,0);
    my $notebook_global = new Gtk::Notebook;
    $notebook_global->set_show_border($false);
    $notebook_global->set_show_tabs($false);
    my $button_cancel = new Gtk::Button(" "._("Cancel")." ");
    $button_cancel->signal_connect(clicked => \&quit_global);
    my $button_connect = new Gtk::Button(" "._("Connection")." ");
    my $button_help = new Gtk::Button(" "._("Help")." ");
    my $pass_lab = new Gtk::Label(_("Enter Password"));
    my $pass_bool = 'FALSE';
    $window_global->add($nb);
    $nb->set_show_border($false);
    $nb->set_show_tabs($false);
    $nb->append_page($vbox_global, new Gtk::Label("appli page"));
    writ_on_pixmaps($vbox_global,"$pix_dir/remote.png",_("Remote Access Configuration"),540,100);
    gtkpack__(
	      gtkadd(my $frame_client = new Gtk::Frame(_("Client configuration")),
		     gtkpack__(new Gtk::VBox(1,0),
			       gtkpack__(new Gtk::HBox(1,5),
					 gtkpack(new Gtk::Label(_("Remote server Address"))),
					 gtkpack(my $host_ip = new Gtk::Combo()),
					 ),
			       gtkpack__(new Gtk::HBox(1,5),
					 gtkpack(new Gtk::Label(_("Display Number(default 0)"))),
					 gtkpack(my $display = new Gtk::Entry()),
					 ),
			       gtkpack__(new Gtk::HBox(1,5),
					 gtkpack($pass_lab),
				       gtkpack(my $pass_client = new Gtk::Entry()),
					 ),
			       gtkpack_(
					my $full_toggle = new Gtk::CheckButton(_("FullScreen")),
				       ),
			       ),
		     ),
	      );
    $full_toggle->set_uposition(100,160);
    #$full_toggle->set_active(1);
    touch("$ENV{HOME}/.rfb_hist");
    touch("$ENV{HOME}/.rfb_hist_win");
    $host_ip->set_popdown_strings("",load_text("$ENV{HOME}/.rfb_hist")); $host_ip->set_use_arrows ('TRUE');
  $pass_client->get_chars(0,-1);
    gtkpack__(
	      gtkadd(my $frame_server = new Gtk::Frame(_("Server configuration")),
		     gtkpack__(new Gtk::VBox(1,0),
			       gtkpack__(new Gtk::HBox(1,5),
					 gtkpack(new Gtk::Label(_("Set Password"))),
					 gtkpack(my $pass_serv = new Gtk::Entry()),
					 ),
			       ),
		     ),
	      );
    gtkpack__(
	    gtkadd(my $frame_win = new Gtk::Frame(_("Windows Terminal Services")),
		   gtkpack__(new Gtk::VBox(1,0),
			     gtkpack__(new Gtk::HBox(1,5),
				       gtkpack(new Gtk::Label(_("Windows Hostname"))),
				       gtkpack(my $win_serv = new Gtk::Combo()),
				       ),
			     ),
		   ),
	      );
    $win_serv->set_popdown_strings("",load_text("$ENV{HOME}/.rfb_hist_win")); $win_serv->set_use_arrows ('TRUE');
    $pass_serv->signal_connect("changed", sub { $pass_bool = 'TRUE' });
    $notebook_global->append_page($frame_client,new Gtk::Label("client page"));
    $notebook_global->append_page($frame_server,new Gtk::Label("server page"));
    $notebook_global->append_page($frame_win,new Gtk::Label("Terminal services page"));
    gtkpack__(
	      gtkadd(my $frame_sel = new Gtk::Frame(_("Remote Access Type")),
		     gtkpack__(new Gtk::VBox(0,5),
			       gtksignal_connect($client_rad, clicked => sub{$notebook_global->set_page(0); $button_connect->child->set(_("Connection"));}),
			       gtksignal_connect($server_rad, clicked => sub{$notebook_global->set_page(1); $button_connect->child->set(_("Launch server"));}),
			       gtksignal_connect($win_rad, clicked => sub{$notebook_global->set_page(2); $button_connect->child->set(_("Connection"));}),
			       ),
		     ),
	   );
    $pass_client->set_visibility( $false ); 
    $pass_serv->set_visibility( $false ); 
    $client_rad->set_uposition(80,130);
    $server_rad->set_uposition(80,150);
    $win_rad->set_uposition(80,170);
    $button_connect->signal_connect("clicked", sub {   
	$page = $notebook_global->get_current_page();
	if ($page <= 0) {
	    my $tog;
	    my $disp=$display->get_chars(0,-1);
	    if (($full_toggle->get_active)==1) {
		$tog ='-fullscreen';
	    } else { $tog='-shared';}
	    ($disp eq '') ? $disp=0:$disp;
	    my $host_cl = $host_ip->entry->get_text();
	    unless ($host_cl ne '') { splash_warning("\n "._("Enter a valid address please!")." \n")}
	    else {
		my $passcli = $pass_client->get_chars(0,-1);
		refresh_host_list($host_cl,"$ENV{HOME}/.rfb_hist");
		my $vssh_script = "";
		foreach ("/usr/bin/vssh.exp","./vssh.exp") {
		    [ -e "$_" ] and $vssh_script="$_", last;
							     }
		if ($passcli eq '') { 
		    exec("/usr/bin/vncviewer $tog $host_cl:$disp") if -e "/usr/bin/vncviewer";
		    splash_warning(_("\nYou should install vnc client \nto connect to the server\n"));
		} else {
		    exec $vssh_script,'--',$tog,$host_cl,$disp,$passcli;
		}
	    }
						     } elsif ($page == 1){
							 if (!-e "$ENV{HOME}/.x0rfbserver" || $pass_bool eq 'TRUE') {
							     my $pserv=$pass_serv->get_chars(0,-1);
							     $pserv =`genpassHex '$pserv' 2>&1`;
							     output "$ENV{HOME}/.x0rfbserver",
							     qq([Connection]
SocketConnections = 1
Display = 0
AutoDisplay = 1
Password = $pserv
DisableRemote = 0
DisableLocal = 0

[Update]
ShowMousePointer = 1
);}						   

	                                               exec("/usr/bin/x0rfbserver") if -e "/usr/bin/x0rfbserver" ;
	                                               splash_warning(_("\nInstall the rfb package if you want to export \nyour desktop to a remote client\n"));
						       
                                                     } elsif ($page == 2) {
							 my $host_win = $win_serv->entry->get_text();
						       unless ($host_win ne '') { splash_warning("\n "._("Enter a valid address please!")." \n")}
						       else {
							   refresh_host_list($host_win,"$ENV{HOME}/.rfb_hist_win");
							   exec("rdesktop -F $host_win") if -e "/usr/bin/rdesktop";
                                                           splash_warning(_("\nRdesktop is not installed,\ninstall it with 'urpmi rdesktop'\n"));
							}
						    }
						   });
 #help section 
  $vbx = new Gtk::VBox(0,0);
  writ_on_pixmaps($vbx,"$pix_dir/remote.png",_("Help"),540,100);
  my $text = new Gtk::Text(undef,undef);
  my $buttonok = new Gtk::Button(_("Click Here to return"));
  $buttonok->signal_connect("clicked", sub {$nb->prev_page()});
  $text->backward_delete($text->get_length);
  $text->insert(undef, undef, undef, _(" Remote FrameBuffer - Copyright (C) %s MandrakeSoft S.A.", $_copyright)."\n\t\t\t"._("Author:")."   Daouda Lo <daouda\@mandrakesoft.com>\n\n\t "._("The rfbdrake tool is both a client and server desktop remote control utility.")."\n\t "._("It exports the framebuffer of the X server to one or more clients using strong\n\t compression and injects keyboard and mouse inputs from the clients into\n\t the server.")."\n\n\t "._("Rfbdrake allows to initiate a Window Terminal Services session with a\n\t Windows 2000/XP server.")."\n\n\t "._("The password is encrypted and one should always set it before giving the\n\t control to a remote client.\n")); 
  $text->set_word_wrap(1);
  $text->thaw;
  $vbx->pack_start($text,1,1,0);
  $vbx->pack_start($buttonok,0,0,0);
  $nb->append_page($vbx,new Gtk::Label(_("Help")));
  $button_help->signal_connect( "clicked",sub {$nb->set_page(1);} );
  $vbox_global->pack_start($frame_sel,0,0,1);
  $vbox_global->pack_start($notebook_global,1,1,0);
  my $hbox_final= new Gtk::HBox(0,10);
  $hbox_final->pack_end($button_cancel,0,0,1);
  $hbox_final->pack_end($button_connect,0,0,1);
  $hbox_final->pack_start($button_help,0,0,1);
  $vbox_global->pack_end($hbox_final,0,0,1);
  $window_global->show_all;
  
}

sub on_help_clicked {
#  my $link="/usr/share/doc/HTML/index.html";
#  my $browser=$ENV{'BROWSER'};
#  print "test browser\n";
#  if (!$browser) { print splash_warning( " ". _("Warning: No browser specified") ." "); return;}
#  else {
#    system("$browser $link &");
#  }
    my ($notbook, $vbox) = @_;
    writ_on_pixmaps($vbox,"$pix_dir/remote.png",_("Help"),540,100);
    my $text = new Gtk::Text(undef,undef);
    my $button_ok = new Gtk::Button(_("OK"));
    $text->backward_delete($text->get_length);
    #$text->insert(undef, undef, undef, _(" Rfbrake will help you :\n\n\tmove your body\n\ntest\n")); 
    $text->set_word_wrap(1);
    $text->thaw;
    $vbox->pack_start($text,0,0,1);
    $vbox->pack_start($button_ok,0,0,1);
    $notbook->append_page($vbox,new Gtk::Label("Help"));
    $button_ok->signal_connect("clicked", sub {$notbook->prev_page()});
    print "2\n";
    $notbook;
}

sub load_text {
  my ($file)=@_;
  my @list_hosts;
  open( FILE, $file ) or die "load_text: missing file $file : $!";
  while (<FILE>) {
      chomp;
      unshift(@list_hosts,$_);
    }
  close( FILE );
  @list_hosts;
}

sub refresh_host_list {
  my ($hostname,$file)=@_;
  my @old_hosts = load_text($file);
  my $line;
  my $i=0;
  open( FILE, "+>$file") or die "refresh_host_list : missing file $file : $!";
  foreach $line (@old_hosts) {
      unless($i==4) {
	  next if $line eq $hostname;
	  print FILE "$line$/";
	  $i++;
      }
  }
  print FILE "$hostname$/";
  close (FILE);
}


sub splash_warning {
  my ($label) = @_;
  my $win_about = new Gtk::Dialog();
  $win_about->set_position(1);
  
  my $bbox1 = new Gtk::HButtonBox;
  $win_about->action_area->pack_start($bbox1,0,0,0);
  
  my $button = new Gtk::Button(_("Close"));
  $button->signal_connect_object("clicked",$win_about => 'destroy');
  $bbox1->add($button);
  
  my $lab = new Gtk::Label($label);
  my $style1 = new Gtk::Style;
  $win_about->vbox->pack_start($lab, 1, 1, 0);
  $win_about->show_all();
  $win_about->set_modal(1);
}

sub writ_on_pixmaps {
  my ($vbox, $pix_name, $step_label, $width, $height)=@_;
  my $darea= new Gtk::DrawingArea();
  $darea->set_usize($width,$height);
  $vbox->pack_start($darea,0,0,0);
  my ($pix1,$pix_mask1) = gtkcreate_png("$xpm_path/$pix_name");
  my ($y1, $x1) = $pix1->get_size;
  my $style= new Gtk::Style;
  $style->font(Gtk::Gdk::Font->fontset_load(_("-adobe-times-bold-r-normal--17-*-100-100-p-*-iso8859-*,*-r-*")));
  my $w = $style->font->string_width(_("Welcome"));
  $darea->signal_connect('expose_event' => sub {
			   my $i;
			   for ($i=0;$i<($width/$y1);$i++) {
			     $darea->window->draw_pixmap ($darea->style->bg_gc('normal'),
							  $pix1, 0, 0, 0, $y1*$i,
							  $x1 , $y1 );
			       $darea->window->draw_string(
							   $style->font,
							   $darea->style->white_gc,
							   80+(380-$w)/2, 62,
							   $step_label );
			   }
			 })
}

sub quit_global {
  Gtk->exit(0);
}

sub about_rfbdrake {
  my $window_about = new Gtk::Dialog();
  $window_about->set_position(1);
  
  my $bbox1 = new Gtk::HButtonBox;
  $window_about->action_area->pack_start($bbox1,0,0,0);
  
  my $button = new Gtk::Button(_("Close"));
  $button->signal_connect_object("clicked",$window_about => 'destroy');
  $bbox1->add($button);
  
  my $label = new Gtk::Label( _("Remote FrameBuffer %s \n \n Copyright (C) %s MandrakeSoft S.A.\n", $_version, $_copyright) );
  $window_about->vbox->pack_start( $label, 1, 1, 0 );
  
  $window_about->vbox->pack_start( new Gtk::Label( _("Authors: \n\n Daouda Lo <daouda\@mandrakesoft.com> \n\n")), 1, 1, 0 );
  
  $window_about->show_all();
  $window_about->set_modal(1);
}

