package any; # $Id$ use diagnostics; use strict; use vars qw(@users); #-###################################################################################### #- misc imports #-###################################################################################### use common qw(:common :system :file :functional); use commands; use detect_devices; use partition_table qw(:types); use fsedit; use fs; use run_program; use modules; use log; sub facesdir { my ($prefix) = @_; "$prefix/usr/share/faces/"; } sub face2xpm { my ($face, $prefix) = @_; facesdir($prefix) . $face . ".xpm"; } sub facesnames { my ($prefix) = @_; my $dir = facesdir($prefix); grep { -e "$dir/$_.png" } map { /(.*)\.xpm/ } all($dir); } sub addKdmIcon { my ($prefix, $user, $icon) = @_; my $dest = "$prefix/usr/share/faces/$user.png"; eval { commands::cp("-f", facesdir($prefix) . $icon . ".png", $dest) } if $icon; } sub allocUsers { my ($prefix, @users) = @_; my @m = my @l = facesnames($prefix); foreach (grep { !$_->{icon} || $_->{icon} eq "automagic" } @users) { $_->{auto_icon} = splice(@m, rand(@m), 1); #- known biased (see cookbook for better) log::l("auto_icon is $_->{auto_icon}"); @m = @l unless @m; } } sub addUsers { my ($prefix, @users) = @_; my $msec = "$prefix/etc/security/msec"; allocUsers($prefix, @users); foreach my $u (@users) { substInFile { s/^$u->{name}\n//; $_ .= "$u->{name}\n" if eof } "$msec/user.conf" if -d $msec; addKdmIcon($prefix, $u->{name}, delete $u->{auto_icon} || $u->{icon}); } run_program::rooted($prefix, "/usr/share/msec/grpuser.sh --refresh >/dev/null"); # addKdmIcon($prefix, 'root', 'root'); } sub crypt { my ($password, $md5) = @_; $md5 ? c::crypt_md5($password, salt(8)) : crypt ($password, salt(2)); } sub enableShadow { my ($prefix) = @_; run_program::rooted($prefix, "pwconv") or log::l("pwconv failed"); run_program::rooted($prefix, "grpconv") or log::l("grpconv failed"); } sub enableMD5Shadow { my ($prefix, $shadow, $md5) = @_; substInFile { if (/^password.*pam_pwdb.so/) { s/\s*shadow//; s/\s*md5//; s/$/ shadow/ if $shadow; s/$/ md5/ if $md5; } } grep { -r $_ } map { "$prefix/etc/pam.d/$_" } qw(login rlogin passwd); } sub setupBootloader { my ($in, $b, $hds, $fstab, $security, $prefix, $more) = @_; $more++ if $b->{bootUnsafe}; if ($::beginner && $more >= 1) { my @l = (__("First sector of drive (MBR)"), __("First sector of boot partition")); $in->set_help('setupBootloaderBeginner') unless $::isStandalone; if (arch() =~ /sparc/) { $b->{use_partition} = $in->ask_from_list_(_("SILO Installation"), _("Where do you want to install the bootloader?"), \@l, $l[$b->{use_partition}]); } else { my $boot = $hds->[0]{device}; my $onmbr = "/dev/$boot" eq $b->{boot}; $b->{boot} = "/dev/" . ($in->ask_from_list_(_("LILO/grub Installation"), _("Where do you want to install the bootloader?"), \@l, $l[!$onmbr]) eq $l[0] ? $boot : fsedit::get_root($fstab, 'boot')->{device}); } } elsif ($more || !$::beginner) { $in->set_help(arch() =~ /sparc/ ? "setupSILOGeneral" : "setupBootloaderGeneral") unless $::isStandalone; #- TO MERGE ? if ($::expert) { my $default = arch() =~ /sparc/ ? 'silo' : 'grub'; my $m = $in->ask_from_list_('', _("Which bootloader(s) do you want to use?"), [ keys(%{$b->{methods}}), __("None") ], $default) or return; $b->{methods}{$_} = 0 foreach keys %{$b->{methods}}; $b->{methods}{$m} = 1 if $m ne "None"; } #- at least one method grep_each { $::b } %{$b->{methods}} or return; #- put lilo if grub is chosen, so that /etc/lilo.conf is generated exists $b->{methods}{lilo} and $b->{methods}{lilo} = 1 if $b->{methods}{grub}; my @silo_install_lang = (_("First sector of drive (MBR)"), _("First sector of boot partition")); my $silo_install_lang = $silo_install_lang[$b->{use_partition}]; my @l = ( arch() =~ /sparc/ ? ( _("Bootloader installation") => { val => \$silo_install_lang, list => \@silo_install_lang }, ) : ( _("Boot device") => { val => \$b->{boot}, list => [ map { "/dev/$_" } (map { $_->{device} } @$hds, @$fstab), detect_devices::floppies() ], not_edit => !$::expert }, _("LBA (doesn't work on old BIOSes)") => { val => \$b->{lba32}, type => "bool", text => "lba" }, _("Compact") => { val => \$b->{compact}, type => "bool", text => _("compact") }, _("Video mode") => { val => \$b->{vga}, list => [ keys %bootloader::vga_modes ], not_edit => $::beginner }, ), _("Delay before booting default image") => \$b->{timeout}, $security < 4 ? () : ( _("Password") => { val => \$b->{password}, hidden => 1 }, _("Password (again)") => { val => \$b->{password2}, hidden => 1 }, _("Restrict command line options") => { val => \$b->{restricted}, type => "bool", text => _("restrict") }, ) ); @l = @l[0..3] unless $::expert; #- take "bootloader installation" and "delay before ..." on SPARC. $b->{vga} ||= 'Normal'; $in->ask_from_entries_refH('', _("Bootloader main options"), \@l, complete => sub { #- $security > 4 && length($b->{password}) < 6 and $in->ask_warn('', _("At this level of security, a password (and a good one) in lilo is requested")), return 1; $b->{restricted} && !$b->{password} and $in->ask_warn('', _("Option ``Restrict command line options'' is of no use without a password")), return 1; $b->{password} eq $b->{password2} or !$b->{restricted} or $in->ask_warn('', [ _("The passwords do not match"), _("Please try again") ]), return 1; 0; } ) or return 0; $b->{use_partition} = $silo_install_lang eq _("First sector of drive (MBR)") ? 0 : 1; $b->{vga} = $bootloader::vga_modes{$b->{vga}} || $b->{vga}; } until ($::beginner && $more <= 1) { $in->set_help(arch() =~ /sparc/ ? 'setupSILOAddEntry' : 'setupBootloaderAddEntry') unless $::isStandalone; my $c = $in->ask_from_listf([''], _("Here are the different entries. You can add some more or change the existing ones."), sub { my ($e) = @_; ref $e ? "$e->{label} ($e->{kernel_or_dev})" . ($b->{default} eq $e->{label} && " *") : translate($e); }, [ @{$b->{entries}}, __("Add"), __("Done") ]); $c eq "Done" and last; my ($e); if ($c eq "Add") { my @labels = map { $_->{label} } @{$b->{entries}}; my $prefix; if ($in->ask_from_list_('', _("Which type of entry do you want to add?"), [ __("Linux"), arch() =~ /sparc/ ? __("Other OS (SunOS...)") : __("Other OS (windows...)") ] ) eq "Linux") { $e = { type => 'image', root => '/dev/' . fsedit::get_root($fstab)->{device}, #- assume a good default. }; $prefix = "linux"; } else { $e = { type => 'other' }; $prefix = arch() =~ /sparc/ ? "sunos" : "windows"; } $e->{label} = $prefix; for (my $nb = 0; member($e->{label}, @labels); $nb++) { $e->{label} = "$prefix-$nb" } } else { $e = $c; } my %old_e = %$e; my $default = my $old_default = $e->{label} eq $b->{default}; my @l; if ($e->{type} eq "image") { @l = ( _("Image") => { val => \$e->{kernel_or_dev}, list => [ map { s/$prefix//; $_ } glob_("$prefix/boot/vmlinuz*") ], not_edit => 0 }, _("Root") => { val => \$e->{root}, list => [ map { "/dev/$_->{device}" } @$fstab ], not_edit => !$::expert }, _("Append") => \$e->{append}, _("Video mode") => { val => \$e->{vga}, list => [ keys %bootloader::vga_modes ], not_edit => !$::expert }, _("Initrd") => { val => \$e->{initrd}, list => [ map { s/$prefix//; $_ } glob_("$prefix/boot/initrd*") ] }, _("Read-write") => { val => \$e->{'read-write'}, type => 'bool' } ); @l = @l[0..5] unless $::expert; } else { @l = ( _("Root") => { val => \$e->{kernel_or_dev}, list => [ map { "/dev/$_->{device}" } @$fstab ], not_edit => !$::expert }, arch() !~ /sparc/ ? ( _("Table") => { val => \$e->{table}, list => [ '', map { "/dev/$_->{device}" } @$hds ], not_edit => !$::expert }, _("Unsafe") => { val => \$e->{unsafe}, type => 'bool' } ) : (), ); @l = @l[0..1] unless $::expert; } @l = ( _("Label") => \$e->{label}, @l, _("Default") => { val => \$default, type => 'bool' }, ); if ($in->ask_from_entries_refH($c eq "Add" ? '' : ['', _("Ok"), _("Remove entry")], '', \@l, complete => sub { $e->{label} or $in->ask_warn('', _("Empty label not allowed")), return 1; member($e->{label}, map { $_->{label} } grep { $_ != $e } @{$b->{entries}}) and $in->ask_warn('', _("This label is already used")), return 1; 0; })) { $b->{default} = $old_default || $default ? $default && $e->{label} : $b->{default}; $e->{vga} = $bootloader::vga_modes{$e->{vga}} || $e->{vga}; require bootloader; bootloader::configure_entry($prefix, $e); #- hack to make sure initrd file are built. push @{$b->{entries}}, $e if $c eq "Add"; } else { @{$b->{entries}} = grep { $_ != $e } @{$b->{entries}}; } } 1; } sub setAutologin { my ($prefix, $user, $desktop) = @_; if ($user) { local *F; open F, ">$prefix/etc/sysconfig/desktop" or die "Can't open $!"; print F uc($desktop) . "\n"; close F; } setVarsInSh("$prefix/etc/sysconfig/autologin", { USER => $user, AUTOLOGIN => bool2yesno($user), EXEC => "/usr/X11R6/bin/startx" }); } sub writeandclean_ldsoconf { my ($prefix) = @_; my $file = "$prefix/etc/ld.so.conf"; output $file, grep { !m|^(/usr)?/lib$| } #- no need to have /lib and /usr/lib in ld.so.conf uniq cat_($file), "/usr/X11R6/lib\n"; } sub shells { my ($prefix) = @_; grep { -x "$prefix$_" } map { chomp; $_ } cat_("$prefix/etc/shells"); } sub inspect { my ($part, $prefix, $rw) = @_; isMountableRW($part) or return; my $dir = "/tmp/inspect_tmp_dir"; if ($part->{isMounted}) { $dir = ($prefix || '') . $part->{mntpoint}; } elsif ($part->{notFormatted} && !$part->{isFormatted}) { $dir = ''; } else { mkdir $dir, 0700; eval { fs::mount($part->{device}, $dir, type2fs($part->{type}), !$rw) }; $@ and return; } my $h = before_leaving { if (!$part->{isMounted} && $dir) { fs::umount($dir); unlink($dir) } }; $h->{dir} = $dir; $h; } #-----modem conf sub pppConfig { my ($in, $modem, $prefix, $install) = @_; $modem or return; symlinkf($modem->{device}, "$prefix/dev/modem") or log::l("creation of $prefix/dev/modem failed"); $install->(qw(ppp)) unless $::testing; my %toreplace; $toreplace{$_} = $modem->{$_} foreach qw(connection phone login passwd auth domain dns1 dns2); $toreplace{kpppauth} = ${{ 'Script-based' => 0, 'PAP' => 1, 'Terminal-based' => 2, }}{$modem->{auth}}; $toreplace{phone} =~ s/\D//g; $toreplace{dnsserver} = join ',', map { $modem->{$_} } "dns1", "dns2"; $toreplace{dnsserver} .= $toreplace{dnsserver} && ','; #- using peerdns or dns1,dns2 avoid writing a /etc/resolv.conf file. $toreplace{peerdns} = "yes"; $toreplace{connection} ||= 'DialupConnection'; $toreplace{domain} ||= 'localdomain'; $toreplace{intf} ||= 'ppp0'; $toreplace{papname} = $modem->{auth} eq 'PAP' && $toreplace{login}; #- build ifcfg-ppp0. my $ifcfg = "$prefix/etc/sysconfig/network-scripts/ifcfg-ppp0"; local *IFCFG; open IFCFG, ">$ifcfg" or die "Can't open $ifcfg"; print IFCFG <$chat" or die "Can't open $chat"; print CHAT <{special_command}) { print CHAT <{special_command}' END } print CHAT <{auth} eq 'Terminal-based' || $modem->{auth} eq 'Script-based') { print CHAT <{auth} eq 'PAP') { #- need to create a secrets file for the connection. my $secrets = "$prefix/etc/ppp/" . lc($modem->{auth}) . "-secrets"; my @l = cat_($secrets); my $replaced = 0; do { $replaced ||= 1 if s/^\s*"?$toreplace{login}"?\s+ppp0\s+(\S+)/"$toreplace{login}" ppp0 "$toreplace{passwd}"/; } foreach @l; if ($replaced) { local *F; open F, ">$secrets" or die "Can't open $secrets: $!"; print F @l; } else { local *F; open F, ">>$secrets" or die "Can't open $secrets: $!"; print F "$toreplace{login} ppp0 \"$toreplace{passwd}\"\n"; } #- restore access right to secrets file, just in case. chmod 0600, $secrets; } #- install kppprc file according to used configuration. commands::mkdir_("-p", "$prefix/usr/share/config"); local *KPPPRC; open KPPPRC, ">$prefix/usr/share/config/kppprc" or die "Can't open $prefix/usr/share/config/kppprc: $!"; chmod 0600, "$prefix/usr/share/config/kppprc"; print KPPPRC <{miscellaneous}, qw(http_proxy ftp_proxy)); setVarsInCsh("$prefix/etc/profile.d/proxy.csh", $::o->{miscellaneous}, qw(http_proxy ftp_proxy)); } sub load_thiskind { my ($in, $type) = @_; my $w; modules::load_thiskind($type, sub { $w = wait_load_module($in, $type, @_) }); } sub setup_thiskind { my ($in, $type, $auto, $at_least_one) = @_; return if arch() eq "ppc"; my @l; if (!$::noauto) { @l = load_thiskind($in, $type); if (my @err = grep { $_ } map { $_->{error} } @l) { $in->ask_warn('', join("\n", @err)); } return @l if $auto && (@l || !$at_least_one); } @l = map { $_->{description} } @l; while (1) { (my $msg_type = $type) =~ s/\|.*//; my $msg = @l ? [ _("Found %s %s interfaces", join(", ", @l), $msg_type), _("Do you have another one?") ] : _("Do you have any %s interfaces?", $msg_type); my $opt = [ __("Yes"), __("No") ]; push @$opt, __("See hardware info") if $::expert; my $r = "Yes"; $r = $in->ask_from_list_('', $msg, $opt, "No") unless $at_least_one && @l == 0; if ($r eq "No") { return @l } if ($r eq "Yes") { push @l, load_module($in, $type) || next; } else { $in->ask_warn('', [ detect_devices::stringlist() ]); } } } sub wait_load_module { my ($in, $type, $text, $module) = @_; #-PO: the first %s is the card type (scsi, network, sound,...) #-PO: the second is the vendor+model name $in->wait_message('', [ _("Installing driver for %s card %s", $type, $text), $::beginner ? () : _("(module %s)", $module) ]); } sub load_module { my ($in, $type) = @_; my @options; (my $msg_type = $type) =~ s/\|.*//; my $m = $in->ask_from_listf('', #-PO: the %s is the driver type (scsi, network, sound,...) _("Which %s driver should I try?", $msg_type), \&modules::module2text, [ modules::module_of_type($type) ]) or return; my $l = modules::module2text($m); require modparm; my @names = modparm::get_options_name($m); if ((@names != 0) && $in->ask_from_list_('', _("In some cases, the %s driver needs to have extra information to work properly, although it normally works fine without. Would you like to specify extra options for it or allow the driver to probe your machine for the information it needs? Occasionally, probing will hang a computer, but it should not cause any damage.", $l), [ __("Autoprobe"), __("Specify options") ], "Autoprobe") ne "Autoprobe") { ASK: if (@names >= 0) { my @l = $in->ask_from_entries('', _("You may now provide its options to module %s.", $l), \@names) or return; @options = modparm::get_options_result($m, @l); } else { @options = split ' ', $in->ask_from_entry('', _("You may now provide its options to module %s. Options are in format ``name=value name2=value2 ...''. For instance, ``io=0x300 irq=7''", $l), _("Module options:"), ); } } eval { my $w = wait_load_module($in, $type, $l, $m); modules::load($m, $type, @options); }; if ($@) { $in->ask_yesorno('', _("Loading module %s failed. Do you want to try again with other parameters?", $l), 1) or return; goto ASK; } $l; } 1; ref='#n345'>345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
package install::steps_gtk; # $Id$

use diagnostics;
use strict;
use vars qw(@ISA);

@ISA = qw(install::steps_interactive interactive::gtk);

#-######################################################################################
#- misc imports
#-######################################################################################
use install::pkgs;
use install::steps_interactive;
use interactive::gtk;
use xf86misc::main;
use common;
use mygtk2;
use ugtk2 qw(:helpers :wrappers :create);
use devices;
use modules;
use install::gtk;
use install::any;
use mouse;
use install::help::help;
use log;

#-######################################################################################
#- In/Out Steps Functions
#-######################################################################################
sub new($$) {
    my ($type, $o) = @_;

    $ENV{DISPLAY} ||= $o->{display} || ":0";
    my $wanted_DISPLAY = $::testing && -x '/usr/bin/Xnest' ? ':9' : $ENV{DISPLAY};

    if (!$::local_install && 
	($::testing ? $ENV{DISPLAY} ne $wanted_DISPLAY : $ENV{DISPLAY} =~ /^:\d/)) { #- is the display local or distant?
	my $f = "/tmp/Xconf";
	if (!$::testing) {
	    devices::make("/dev/kbd");
	}
	my $launchX = sub {
	    my ($server, $Driver) = @_;

	    mkdir '/var/log' if !-d '/var/log';

	    my @options = $wanted_DISPLAY;
	    if ($server eq 'Xnest') {
		push @options, '-ac', '-geometry', $o->{vga} || ($o->{vga16} ? '640x480' : '800x600');
	    } else {
		install::gtk::createXconf($f, @{$o->{mouse}}{'Protocol', 'device'}, $o->{mouse}{wacom}[0], $Driver);

		push @options, '-kb', '-allowMouseOpenFail', '-xf86config', $f if arch() !~ /^sparc/;
		push @options, 'tty7', '-s', '240';

		#- old weird servers: Xsun
		push @options, '-fp', '/usr/share/fonts:unscaled' if $server =~ /Xsun/;
	    }

	    if (!fork()) {
		c::setsid();
		exec $server, @options or c::_exit(1);
	    }

	    #- wait for the server to start
	    foreach (1..5) {
		sleep 1;
		last if fuzzy_pidofs(qr/\b$server\b/);
		log::l("$server still not running, trying again");
	    }
	    my $nb;
	    foreach (1..60) {
		log::l("waiting for the server to start ($_ $nb)");
		log::l("Server died"), return 0 if !fuzzy_pidofs(qr/\b$server\b/);
		$nb++ if xf86misc::main::Xtest($wanted_DISPLAY);
		if ($nb > 2) { #- one succeeded test is not enough :-(
		    log::l("AFAIK X server is up");
		    return 1;
		}
		sleep 1;
	    }
	    log::l("Timeout!!");
	    0;
	};
	my @servers = qw(Driver:fbdev); #-)
	if ($::testing) {
	    @servers = 'Xnest';
	} elsif (arch() eq "alpha") {
	    require Xconfig::card;
	    my ($card) = Xconfig::card::probe();
	    Xconfig::card::add_to_card__using_Cards($card, $card->{type}) if $card && $card->{type};
	    @servers = $card->{server} || "TGA";
	    #-@servers = qw(SVGA 3DLabs TGA) 
	} elsif (arch() =~ /^sparc/) {
	    local $_ = cat_("/proc/fb");
	    if (/Mach64/) {
		@servers = qw(Mach64);
	    } elsif (/Permedia2/) {
		@servers = qw(3DLabs);
	    } else {
		@servers = qw(Xsun24);
	    }
	} elsif (arch() =~ /ia64/) {
	    require Xconfig::card;
	    my ($card) = Xconfig::card::probe();
	    @servers = map { if_($_, "Driver:$_") } $card && $card->{Driver}, 'fbdev';
        }

	foreach (@servers) {
	    log::l("Trying with server $_");
	    my ($prog, $Driver) = /Driver:(.*)/ ? ('Xorg', $1) : /Xsun|Xnest|^X_move$/ ? $_ : "XF86_$_";
	    if (/FB/i) {
		!$o->{vga16} && $o->{allowFB} or next;

		$o->{allowFB} = &$launchX($prog, $Driver) #- keep in mind FB is used.
		  and goto OK;
	    } else {
		$o->{vga16} = 1 if /VGA16/;
		&$launchX($prog, $Driver) and goto OK;
	    }
	}
	return undef;
    }
  OK:
    $ENV{DISPLAY} = $wanted_DISPLAY;
    require detect_devices;
    if (detect_devices::is_xbox()) {
        modules::load('xpad');
        run_program::run('xset', 'm', '1/8', '1');
    }
    install::gtk::init_gtk($o);
    install::gtk::init_sizes($o);
    install::gtk::install_theme($o);
    install::gtk::create_logo_window($o);
    install::gtk::create_steps_window($o);

    $ugtk2::grab = 1;

    $o = (bless {}, ref($type) || $type)->SUPER::new($o);
    $o->interactive::gtk::new;
    $o;
}

sub enteringStep {
    my ($o, $step) = @_;

    printf "Entering step `%s'\n", common::remove_translate_context($o->{steps}{$step}{text});
    if (my @banner_elts = @{$o->{steps}{$step}}{qw(banner_icon banner_title)}) {
        ugtk2::set_default_step_items(@banner_elts);
    }
    $o->SUPER::enteringStep($step);
    install::gtk::update_steps_position($o);
}
sub leavingStep {
    my ($o, $step) = @_;
    $o->SUPER::leavingStep($step);
}


sub charsetChanged {
    my ($o) = @_;
    Gtk2->set_locale;
    install::gtk::load_font($o);
    install::gtk::create_steps_window($o);
}


sub interactive_help_has_id {
    my ($_o, $id) = @_;
    exists $install::help::help::{$id};
}

sub interactive_help_get_id {
    my ($_o, @l) = @_;
    @l = map { 
	join("\n\n", map { s/\n/ /mg; $_ } split("\n\n", translate($install::help::help::{$_}->())));
    } grep { exists $install::help::help::{$_} } @l;
    join("\n\n\n", @l);
}

#-######################################################################################
#- Steps Functions
#-######################################################################################
sub selectLanguage {
    my ($o) = @_;
    $o->SUPER::selectLanguage;
  
    $o->ask_warn('',
formatAlaTeX(N("Your system is low on resources. You may have some problem installing
Mandriva Linux. If that occurs, you can try a text install instead. For this,
press `F1' when booting on CDROM, then enter `text'."))) if availableRamMB() < 70; # 70MB

}

#------------------------------------------------------------------------------
sub selectMouse {
    my ($o, $force) = @_;
    my %old = %{$o->{mouse}};
    $o->SUPER::selectMouse($force) or return;
    my $mouse = $o->{mouse};
    $mouse->{type} eq 'none' ||
      $old{type}   eq $mouse->{type}   && 
      $old{name}   eq $mouse->{name}   &&
      $old{device} eq $mouse->{device} and return;

    while (1) {
	my $x_protocol_changed = mouse::change_mouse_live($mouse, \%old);
	mouse::test_mouse_install($mouse, $x_protocol_changed) and return;

	%old = %$mouse;
	$o->SUPER::selectMouse;
	$mouse = $o->{mouse};
    } 
}

sub reallyChooseGroups {
    my ($o, $size_to_display, $individual, $_compssUsers) = @_;

    my $w = ugtk2->new(N("Package Group Selection"), icon => 'banner-sys');
    my $w_size = gtknew('Label', text => &$size_to_display);

    my $entry = sub {
	my ($e) = @_;

	gtknew('CheckButton', 
	       text => translate($e->{label}), 
	       tip => translate($e->{descr}),
	       active_ref => \$e->{selected},
	       toggled => sub { 
		   gtkset($w_size, text => &$size_to_display);
	       });
    };
    #- when restarting this step, it might be necessary to reload the compssUsers.pl (bug 11558). kludgy.
    if (!ref $o->{gtk_display_compssUsers}) { install::any::load_rate_files($o) }
    ugtk2::gtkadd($w->{window},
	   gtknew('VBox', children => [
		    1, $o->{gtk_display_compssUsers}->($entry),
		    1, '',
		    0, if_($individual,
			      gtknew('CheckButton', text => N("Individual package selection"), active_ref => $individual),
			  ),
		    0, gtknew('HBox', children_loose => [
			  gtknew('Button', text => N("Help"), clicked => $o->interactive_help_sub_display_id('choosePackages')),
			  $w_size,
			  gtknew('Button', text => N("Next"), clicked => sub { Gtk2->main_quit }),
			 ]),
		  ]),
	  );
    $w->main;
    1;
}

sub choosePackagesTree {
    my ($o, $packages, $o_limit_medium) = @_;

    my $available = install::any::getAvailableSpace($o);
    my $availableCorrected = install::pkgs::invCorrectSize($available / sqr(1024)) * sqr(1024);

    my $common;
    $common = {             get_status => sub {
				my $size = install::pkgs::selectedSize($packages);
				N("Total size: %d / %d MB", install::pkgs::correctSize($size / sqr(1024)), $available / sqr(1024));
			    },
			    node_state => sub {
				my $p = install::pkgs::packageByName($packages, $_[0]) or return;
				install::pkgs::packageMedium($packages, $p)->{selected} or return;
				$p->arch eq 'src'                       and return;
				$p->flag_base                           and return 'base';
				$p->flag_installed && !$p->flag_upgrade and return 'installed';
				$p->flag_selected                       and return 'selected';
				return 'unselected';
			    },
			    build_tree => sub {
				my ($add_node, $flat) = @_;
				if ($flat) {
				    foreach (sort map { $_->name }
					     grep { !$o_limit_medium || install::pkgs::packageMedium($packages, $_) == $o_limit_medium }
					     grep { $_ && $_->arch ne 'src' }
					     @{$packages->{depslist}}) {
					$add_node->($_, undef);
				    }
				} else {
				    foreach my $root (@{$o->{compssUsers}}) {
					my (@firstchoice, @others);
					my %fl = map { ("CAT_$_" => 1) } @{$root->{flags}};
					foreach my $p (@{$packages->{depslist}}) {
					    !$o_limit_medium || install::pkgs::packageMedium($packages, $p) == $o_limit_medium or next;
					    my @flags = $p->rflags;
					    next if !($p->rate && any { any { !/^!/ && $fl{$_} } split('\|\|') } @flags);
					    $p->rate >= 3 ?
					      push(@firstchoice, $p->name) :
						push(@others,    $p->name);
					}
					my $root2 = translate($root->{path}) . '|' . translate($root->{label});
					$add_node->($_, $root2)                    foreach sort @firstchoice;
					$add_node->($_, $root2 . '|' . N("Other")) foreach sort @others;
				    }
				}
			    },
			    get_info => sub {
				my $p = install::pkgs::packageByName($packages, $_[0]) or return '';
				install::pkgs::extractHeaders([$p], $packages->{media});

				my $imp = translate($install::pkgs::compssListDesc{$p->flag_base ? 5 : $p->rate});

                                my $tag = { 'foreground' => 'royalblue3' };
				$@ ? N("Bad package") :
				  [ [ N("Name: "), $tag ], [ $p->name . "\n" ],
                                    [ N("Version: "), $tag ], [ $p->version . '-' . $p->release . "\n" ],
                                    [ N("Size: "), $tag ], [ N("%d KB\n", $p->size / 1024) ],
                                    if_($imp, [ N("Importance: "), $tag ], [ "$imp\n" ]),
                                    [ "\n" ], [ formatLines($p->description) ] ];
			    },
			    toggle_nodes => sub {
				my $set_state = shift @_;
				my $isSelection = 0;
				my %l = map { my $p = install::pkgs::packageByName($packages, $_);
					      $isSelection ||= !$p->flag_selected;
					      $p->id => 1 } @_;
				my $state = $packages->{state} ||= {};
				$packages->{rpmdb} ||= install::pkgs::rpmDbOpen(); #- WORKAROUND
				my @l = $isSelection ? $packages->resolve_requested($packages->{rpmdb}, $state, \%l,
										    callback_choices => \&install::pkgs::packageCallbackChoices) :
						       $packages->disable_selected($packages->{rpmdb}, $state,
										   map { $packages->{depslist}[$_] } keys %l);
				my $size = install::pkgs::selectedSize($packages);
				my $error;

				if (!@l) {
				    #- no package can be selected or unselected.
				    my @ask_unselect = grep { $state->{rejected}{$_}{backtrack} &&
								exists $l{$packages->search($_, strict_fullname => 1)->id} }
				      keys %{$state->{rejected} || {}};
				    #- extend to closure (to given more detailed and not absurd reason).
				    my %ask_unselect;
				    while (@ask_unselect > keys %ask_unselect) {
					@ask_unselect{@ask_unselect} = ();
					foreach (keys %ask_unselect) {
					    foreach (keys %{$state->{rejected}{$_}{backtrack}{closure} || {}}) {
						next if exists $ask_unselect{$_};
						push @ask_unselect, $_;
					    }
					}
				    }
				    $error = [ N("You can not select/unselect this package"),
					       formatList(20, map { my $rb = $state->{rejected}{$_}{backtrack};
									    my @froms = keys %{$rb->{closure} || {}};
									    my @unsatisfied = @{$rb->{unsatisfied} || []};
									    my $s = join ", ", ((map { N("due to missing %s", $_) } @froms),
												(map { N("due to unsatisfied %s", $_) } @unsatisfied),
												$rb->{promote} && !$rb->{keep} ? N("trying to promote %s", join(", ", @{$rb->{promote}})) : @{[]},
												$rb->{keep} ? N("in order to keep %s", join(", ", @{$rb->{keep}})) : @{[]},
											       );
									    $_ . ($s ? " ($s)" : '');
									} sort @ask_unselect) ];
				} elsif (install::pkgs::correctSize($size / sqr(1024)) > $available / sqr(1024)) {
				    $error = N("You can not select this package as there is not enough space left to install it");
				} elsif (@l > @_ && $common->{state}{auto_deps}) {
				    $o->ask_okcancel(N("Confirmation"), [ $isSelection ? 
							   N("The following packages are going to be installed") :
							   N("The following packages are going to be removed"),
							       formatList(20, sort(map { $_->name } @l)) ], 1) or $error = ''; #- defined
				}
				if (defined $error) {
				    $o->ask_warn('', $error) if $error;
				    #- disable selection (or unselection).
				    $packages->{rpmdb} ||= install::pkgs::rpmDbOpen(); #- WORKAROUND
				    $isSelection ? $packages->disable_selected($packages->{rpmdb}, $state, @l) :
				                   $packages->resolve_requested($packages->{rpmdb}, $state, { map { $_->id => 1 } @l });
				} else {
				    #- keep the changes, update visible state.
				    foreach (@l) {
					$set_state->($_->name, $_->flag_selected ? 'selected' : 'unselected');
				    }
				}
			    },
			    grep_allowed_to_toggle => sub {
				grep { my $p = install::pkgs::packageByName($packages, $_); $p && !$p->flag_base } @_;
			    },
			    grep_unselected => sub {
				grep { !install::pkgs::packageByName($packages, $_)->flag_selected } @_;
			    },
			    check_interactive_to_toggle => sub {
				my $p = install::pkgs::packageByName($packages, $_[0]) or return;
				if ($p->flag_base) {
				    $o->ask_warn('', N("This is a mandatory package, it can not be unselected"));
				} elsif ($p->flag_installed && !$p->flag_upgrade) {
				    $o->ask_warn('', N("You can not unselect this package. It is already installed"));
				} elsif ($p->flag_selected && $p->flag_installed) {
				    $o->ask_warn('', N("You can not unselect this package. It must be upgraded"));
				} else { return 1 }
				return;
			    },
			    auto_deps => N("Show automatically selected packages"),
			    interactive_help_id => 'choosePackagesTree',
			    ok => N("Install"),
			    cancel => N("Previous"),
			    icons => [ { icon         => 'floppy',
					 help         => N("Load/Save selection"),
					 wait_message => N("Updating package selection"),
					 code         => sub { $o->loadSavePackagesOnFloppy($packages); 1 },
				       }, 
				       if_(0, 
				       { icon         => 'feather',
					 help         => N("Minimal install"),
					 code         => sub {
					     
					     install::any::unselectMostPackages($o);
					     install::pkgs::setSelectedFromCompssList($packages, { SYSTEM => 1 }, 4, $availableCorrected);
					     1;
					 } }),
				     ],
			    state => {
				      auto_deps => 1,
				      flat      => $o_limit_medium,
				     },
			  };

    $o->ask_browse_tree_info(N("Software Management"), N("Choose the packages you want to install"), $common);
}

#------------------------------------------------------------------------------
sub beforeInstallPackages {
    my ($o) = @_;    
    $o->SUPER::beforeInstallPackages;
    install::any::copy_advertising($o);
}

#------------------------------------------------------------------------------
sub installPackages {
    my ($o, $packages) = @_;

    my ($current_total_size, $last_size, $nb, $total_size, $last_dtime, $_trans_progress_total);

    local $::noborderWhenEmbedded = 1;
    my $w = ugtk2->new(N("Installing"), icon => 'banner-sys');
    my $show_advertising if 0;

    my $pkg_log_widget = gtknew('TextView', editable => 0);
    my ($advertising_image, $change_time, $i);
    my $advertize = sub {
	my ($update) = @_;

	@install::any::advertising_images && $show_advertising && $update or return;
	
	$change_time = time();
	my $f = $install::any::advertising_images[$i++ % @install::any::advertising_images];
	log::l("advertising $f");
	gtkval_modify(\$advertising_image, $f);

	if (my $banner = $w->{window}{banner}) {
	    my ($title);
	    my $pl = $f; $pl =~ s/\.png$/.pl/;
	    eval(cat_($pl)) if -e $pl;    
	    $banner->{text} = $title;
	    Gtk2::Banner::set_pixmap($banner);
	}
    };

    my $cancel = gtknew('Button', text => N("Cancel"), clicked => sub { $install::pkgs::cancel_install = 1 });
    my $details = gtknew('Button', text_ref => \$show_advertising, 
			 format => sub { $show_advertising ? N("Details") : N("No details") },
			 clicked => sub {
			     gtkval_modify(\$show_advertising, !$show_advertising);
			     $pkg_log_widget->{to_bottom}->('force');
			 });

    ugtk2::gtkadd($w->{window}, my $box = gtknew('VBox', children_tight => [ 
	gtknew('Image_using_pixmap', file_ref => \$advertising_image, show_ref => \$show_advertising),
    ]));

    $box->pack_end(gtkshow(gtknew('VBox', border_width => 7, spacing => 3, children_loose => [
	gtknew('ScrolledWindow', child => $pkg_log_widget, 
	       hide_ref => \$show_advertising, height => 250, to_bottom => 1),
	gtknew('ProgressBar', fraction_ref => \ (my $pkg_progress), hide_ref => \$show_advertising),
	gtknew('Table', children => [ [ 
	    N("Time remaining "), 
	    gtknew('Label', text_ref => \ (my $msg_time_remaining = N("Estimating"))),
	] ]),
	gtknew('HBox', children => [
	    1, gtknew('VBox', children_centered => [ gtknew('ProgressBar', fraction_ref => \ (my $progress_total), height => 25) ]),
	    0, gtknew('HButtonBox', children_loose => [ $cancel, $details ]),
	]),
    ])), 0, 1, 0);
    
    #- for the hide_ref & show_ref to work, we must set $show_advertising after packing
    gtkval_modify(\$show_advertising, 
		  defined $show_advertising ? $show_advertising : to_bool(@install::any::advertising_images));

    $details->hide if !@install::any::advertising_images;
    $w->sync;
    foreach ($cancel, $details) {
	gtkset_mousecursor_normal($_->window);
    }

    $advertize->(0);

    local *install::steps::installCallback = sub {
	my ($packages, $type, $id, $subtype, $amount, $total) = @_;
	if ($type eq 'user' && $subtype eq 'install') {
	    #- $amount and $total are used to return number of package and total size.
	    $nb = $amount;
	    $total_size = $total; $current_total_size = 0;
	    $o->{install_start_time} = time();
	    mygtk2::gtkadd($pkg_log_widget, text => P("%d package", "%d packages", $nb, $nb));
	    $w->flush;
	} elsif ($type eq 'open') {
	    gtkval_modify(\$pkg_progress, 0);
	    my $p = $packages->{depslist}[$id];
	    mygtk2::gtkadd($pkg_log_widget, text => sprintf("\n%s: %s", $p->name, (split /\n/, $p->summary)[0] || ''));
	    $current_total_size += $last_size;
	    $last_size = $p->size;
	    $advertize->(1) if $show_advertising && $total_size > 20_000_000 && time() - $change_time > 20;
	    $w->flush;
	} elsif ($type eq 'inst' && $subtype eq 'progress') {
	    gtkval_modify(\$pkg_progress, $total ? $amount / $total : 0);

	    my $dtime = time() - $o->{install_start_time};
	    my $ratio = 
	      $total_size == 0 ? 0 :
		install::pkgs::size2time($current_total_size + $amount, $total_size) / install::pkgs::size2time($total_size, $total_size);
	    $ratio >= 1 and $ratio = 1;
	    my $total_time = $ratio ? $dtime / $ratio : time();

	    gtkval_modify(\$progress_total, $ratio);
	    if ($dtime != $last_dtime && $current_total_size > 80_000_000) {
		gtkval_modify(\$msg_time_remaining, formatTime(10 * round(max($total_time - $dtime, 0) / 10) + 10));
		$last_dtime = $dtime;
	    }
	    $w->flush;
	}
    };
    my $install_result;
    catch_cdie { $install_result = $o->install::steps::installPackages($packages) }
      sub { 
	  my $rc = install::steps_interactive::installPackages__handle_error($o, $_[0]);
	  $rc or $w->destroy;
	  $rc;
      };
    if ($install::pkgs::cancel_install) {
	$install::pkgs::cancel_install = 0;
	die 'already displayed';
    }
    $w->destroy;
    $install_result;
}

sub summary_prompt {
    my ($o, $l, $check_complete) = @_;

    my $w = ugtk2->new(N("Summary"), icon => 'banner-summary');

    my $set_entry_labels;
    my @table;
    my $group;
    foreach my $e (@$l) {
	if ($group ne $e->{group}) {
	    $group = $e->{group};
	    push @table, [ gtknew('HBox', children_tight => [ gtknew('Title1', label => escape_text_for_TextView_markup_format($group)) ]), '' ];
	}
	$e->{widget} = gtknew('WrappedLabel', width => $::real_windowwidth * 0.72);

	push @table, [], [ gtknew('HBox', spacing => 30, children_tight => [ '', $e->{widget} ]),
			   gtknew('Button', text => N("Configure"), clicked => sub { 
						 $w->{rwindow}->hide;
						 $e->{clicked}(); 
						 $w->{rwindow}->show;
						 $set_entry_labels->();
					     }) ];
    }

    $set_entry_labels = sub {
	foreach (@$l) {
	    my $t;
	    if ($_->{val}) {
		$t = $_->{val}() || '<span foreground="red">' . N("not configured") . '</span>';
		$t =~ s/&/&amp;/g;
	    }
	    gtkset($_->{widget}, text_markup => $_->{label} . ($t ? " - $t" : ''));
	}
    };
    $set_entry_labels->();

    my $help_sub = $o->interactive_help_sub_display_id('summary');

    ugtk2::gtkadd($w->{window},
	   gtknew('VBox', spacing => 5, children => [
		    1, gtknew('ScrolledWindow', child => gtknew('Table', mcc => 1, children => \@table)),
		    0, $w->create_okcancel(undef, '', '', if_($help_sub, [ N("Help"), $help_sub, 1 ]))
		  ]));

    $w->main($check_complete);
}

#- group by CD
sub ask_deselect_media__copy_on_disk {
    my ($_o, $hdlists, $o_copy_rpms_on_disk) = @_;

    my @names = uniq(map { $_->{name} } @$hdlists);
    my %selection = map { $_ => 1 } @names;

    if (@names > 1 || $o_copy_rpms_on_disk) {
	my $w = ugtk2->new("");
	$w->sync;
	ugtk2::gtkadd(
	    $w->{window},
	    gtkpack(
		Gtk2::VBox->new(0, 5),
		Gtk2::WrappedLabel->new(formatAlaTeX(N("The following installation media have been found.
If you want to skip some of them, you can unselect them now."))),
		(map {
			my $b = gtknew('CheckButton', text => $_, active_ref => \$selection{$_});
			$b->set_sensitive(0) if $_ eq $names[0];
			$b;
		    } @names),
		gtknew('HSeparator'),
		if_($o_copy_rpms_on_disk,
		    Gtk2::WrappedLabel->new(formatAlaTeX(N("You have the option to copy the contents of the CDs onto the hard drive before installation.
It will then continue from the hard drive and the packages will remain available once the system is fully installed."))),
		    gtknew('CheckButton', text => N("Copy whole CDs"), active_ref => $o_copy_rpms_on_disk),
		    gtknew('HSeparator'),
		),
		gtknew('HBox', children_tight => [
		    gtknew('Button', text => N("Next"), clicked => sub { Gtk2->main_quit }),
		]),
	    ),
	);
	$w->main;
    }
    $_->{selected} = $selection{$_->{name}} foreach @$hdlists;
    log::l("keeping media " . join ',', map { $_->{rpmsdir} } grep { $_->{selected} } @$hdlists);
}

1;