package install::install2; # $Id: install2.pm 255825 2009-04-08 11:54:23Z tv $ use diagnostics; use strict; use vars qw($o); BEGIN { $::isInstall = 1 } #-###################################################################################### #- misc imports #-###################################################################################### use install::steps_list; use common; use install::any 'addToBeDone'; use install::steps; use install::any; use lang; use keyboard; use mouse; use devices; use partition_table; use modules; use detect_devices; use run_program; use any; use log; use fs; use fs::any; use fs::mount; use messages; #-####################################################################################### #-$O #-the big struct which contain, well everything (globals + the interactive methods ...) #-if you want to do a kickstart file, you just have to add all the required fields (see for example #-the variable $default) #-####################################################################################### $o = $::o = { # bootloader => { linear => 0, message => 1, timeout => 5, restricted => 0 }, #- packages => [ qw() ], partitioning => { clearall => 0, eraseBadPartitions => 0, auto_allocate => 0 }, #-, readonly => 0 }, authentication => { blowfish => 1, shadow => 1 }, locale => { lang => 'en_US' }, #- isUpgrade => 0, toRemove => [], toSave => [], #- simple_themes => 1, timezone => { #- timezone => "Europe/Paris", #- UTC => 1, }, #- superuser => { password => 'a', shell => '/bin/bash', realname => 'God' }, #- user => { name => 'foo', password => 'bar', home => '/home/foo', shell => '/bin/bash', realname => 'really, it is foo' }, #- keyboard => 'de', #- display => "192.168.1.19:1", steps => \%install::steps_list::installSteps, orderedSteps => \@install::steps_list::orderedInstallSteps, #- for the list of fields available, see network/network.pm net => { #- network => { HOSTNAME => 'abcd' }, #- resolv => { DOMAINNAME => 'foo.xyz' }, #- ifcfg => { #- eth0 => { DEVICE => "eth0", IPADDR => '1.2.3.4', NETMASK => '255.255.255.128' } #- }, }, untranslated_license => messages::main_license_raw(), #-step : the current one #-prefix #-mouse #-keyboard #-netc #-methods #-packages compss }; sub installStepsCall { my ($o, $auto, $fun, @args) = @_; $fun = "install::steps::$fun" if $auto; $o->$fun(@args); } sub getNextStep { my ($o) = @_; find { !$o->{steps}{$_}{done} && $o->{steps}{$_}{reachable} } @{$o->{orderedSteps}}; } #-###################################################################################### #- Steps Functions #- each step function are called with two arguments : clicked(because if you are a #- beginner you can force the the step) and the entered number #-###################################################################################### #------------------------------------------------------------------------------ sub selectLanguage { my ($auto) = @_; installStepsCall($o, $auto, 'selectLanguage'); } sub acceptLicense { my ($auto) = @_; installStepsCall($o, $auto, 'acceptLicense'); } #------------------------------------------------------------------------------ sub selectMouse { my ($auto) = @_; installStepsCall($o, $auto, 'selectMouse'); addToBeDone { mouse::write($o->do_pkgs, $o->{mouse}) if !$o->{isUpgrade} } 'installPackages'; } #------------------------------------------------------------------------------ sub setupSCSI { my ($auto) = @_; installStepsCall($o, $auto, 'setupSCSI'); } #------------------------------------------------------------------------------ sub selectKeyboard { my ($auto) = @_; my $force; if (my $keyboard = keyboard::read()) { $o->{keyboard} = $keyboard; #- for uprade } elsif ($o->{isUpgrade}) { #- oops, the keyboard config is wrong, forcing prompt and writing $force = 1; } installStepsCall($o, $auto, 'selectKeyboard', $force); } #------------------------------------------------------------------------------ sub selectInstallClass { my ($auto) = @_; installStepsCall($o, $auto, 'selectInstallClass'); if ($o->{isUpgrade}) { @{$o->{orderedSteps}} = uniq(map { $_ eq 'selectInstallClass' ? ($_, 'doPartitionDisks', 'formatPartitions') : $_; } @{$o->{orderedSteps}}); } } #------------------------------------------------------------------------------ sub doPartitionDisks { my ($auto) = @_; $o->{steps}{formatPartitions}{done} = 0; installStepsCall($o, $auto, 'doPartitionDisksBefore'); installStepsCall($o, $auto, 'doPartitionDisks'); installStepsCall($o, $auto, 'doPartitionDisksAfter'); } sub formatPartitions { my ($auto) = @_; $o->{steps}{choosePackages}{done} = 0; installStepsCall($o, $auto, 'choosePartitionsToFormat') if !$o->{isUpgrade} && !$::local_install; my $want_root_formated = fs::get::root($o->{fstab})->{toFormat}; if ($want_root_formated) { foreach ('/usr') { my $part = fs::get::mntpoint2part($_, $o->{fstab}) or next; $part->{toFormat} or die N("You must also format %s", $_); } } installStepsCall($o, $auto, 'formatMountPartitions') if !$::testing; if ($want_root_formated) { #- we formatted /, ensure /var/lib/rpm is cleaned otherwise bad things can happen #- (especially when /var is *not* formatted) eval { rm_rf("$::prefix/var/lib/rpm") }; } fs::any::prepare_minimal_root(); install::any::screenshot_dir__and_move(); install::any::move_compressed_image_to_disk($o); any::rotate_logs($::prefix); require raid; raid::write_conf($o->{all_hds}{raids}); } #------------------------------------------------------------------------------ sub choosePackages { my ($auto) = @_; require install::pkgs; #- always setPackages as it may have to copy hdlist and synthesis files. installStepsCall($o, $auto, 'setPackages'); installStepsCall($o, $auto, 'choosePackages'); my @flags = map_each { if_($::b, $::a) } %{$o->{rpmsrate_flags_chosen}}; log::l("rpmsrate_flags_chosen's: ", join(' ', sort @flags)); #- check pre-condition that basesystem package must be selected. install::pkgs::packageByName($o->{packages}, 'basesystem')->flag_available or die "basesystem package not selected"; #- check if there are packages that need installation. $o->{steps}{installPackages}{done} = 0 if $o->{steps}{installPackages}{done} && install::pkgs::packagesToInstall($o->{packages}) > 0; } #------------------------------------------------------------------------------ sub installPackages { my ($auto) = @_; installStepsCall($o, $auto, 'beforeInstallPackages'); installStepsCall($o, $auto, 'installPackages'); installStepsCall($o, $auto, 'afterInstallPackages'); } #------------------------------------------------------------------------------ sub miscellaneous { my ($auto) = @_; installStepsCall($o, $auto, 'miscellaneousBefore'); installStepsCall($o, $auto, 'miscellaneous'); installStepsCall($o, $auto, 'miscellaneousAfter'); } #------------------------------------------------------------------------------ sub summary { my ($auto) = @_; installStepsCall($o, $auto, 'summaryBefore') if $o->{steps}{summary}{entered} == 1; installStepsCall($o, $auto, 'summary'); installStepsCall($o, $auto, 'summaryAfter'); } #------------------------------------------------------------------------------ sub configureNetwork { my ($auto) = @_; #- get current configuration of network device. require network::network; eval { network::network::read_net_conf($o->{net}) }; modules::load_category($o->{modules_conf}, list_modules::ethernet_categories()); require network::connection::ethernet; if (!$o->{isUpgrade}) { installStepsCall($o, $auto, 'configureNetwork'); } else { network::connection::ethernet::configure_eth_aliases($o->{modules_conf}); } } #------------------------------------------------------------------------------ sub installUpdates { my ($auto) = @_; installStepsCall($o, $auto, 'installUpdates'); } #------------------------------------------------------------------------------ sub configureServices { my ($auto) = @_; installStepsCall($o, $auto, 'configureServices'); } #------------------------------------------------------------------------------ sub setRootPassword_addUser { my ($auto) = @_; installStepsCall($o, $auto, 'setRootPassword_addUser') if !$o->{isUpgrade}; } #------------------------------------------------------------------------------ sub setupBootloader { my ($auto) = @_; return if $::local_install; $o->{modules_conf}->write; installStepsCall($o, $auto, 'setupBootloaderBefore'); installStepsCall($o, $auto, 'setupBootloader'); } #------------------------------------------------------------------------------ sub configureX { my ($auto) = @_; #- done here and also at the end of install2.pm, just in case... install::any::write_fstab($o); $o->{modules_conf}->write; require install::pkgs; installStepsCall($o, $auto, 'configureX') if !$::testing && eval { install::pkgs::packageByName($o->{packages}, 'task-x11')->flag_installed } && !$o->{X}{disabled}; } #------------------------------------------------------------------------------ sub exitInstall { my ($auto) = @_; installStepsCall($o, $auto, 'exitInstall', getNextStep($::o) eq 'exitInstall'); } #-###################################################################################### #- Udev Functions #-###################################################################################### sub start_udev() { return if fuzzy_pidofs('udevd'); # Start up udev: mkdir_p("/run/udev/rules.d"); $ENV{UDEVRULESD} = "/run/udev/rules.d"; run_program::run("/usr/lib/systemd/systemd-udevd", "--daemon", "--resolve-names=never"); # Coldplug all devices: run_program::run("udevadm", "trigger", "--type=subsystems", "--action=add"); run_program::run("udevadm", "trigger", "--type=devices", "--action=add"); } sub stop_udev() { kill 15, fuzzy_pidofs('udevd'); sleep(2); fs::mount::umount($_) foreach '/dev/pts', '/dev/shm'; } #-###################################################################################### #- Other Functions #-###################################################################################### sub init_local_install { my ($o) = @_; push @::auto_steps, # 'selectLanguage', 'selectKeyboard', 'miscellaneous', 'selectInstallClass', 'doPartitionDisks', 'formatPartitions'; fs::mount::sys_kernel_debug(''); #- do it now so that when_load doesn't do it $o->{nomouseprobe} = 1; $o->{mouse} = mouse::fullname2mouse('Universal|Any PS/2 & USB mice'); } sub pre_init_brltty() { if (my ($s) = cat_("/proc/cmdline") =~ /brltty=(\S*)/) { my ($driver, $device, $table) = split(',', $s); $table = "text.$table.tbl" if $table !~ /\.tbl$/; log::l("brltty option $driver $device $table"); $o->{brltty} = { driver => $driver, device => $device, table => $table }; $o->{interactive} = 'curses'; $o->{nomouseprobe} = 1; } } sub init_brltty() { symlink "/tmp/stage2/$_", $_ foreach "/etc/brltty"; devices::make($_) foreach $o->{brltty}{device}; run_program::run("brltty"); } sub init_auto_install() { if ($::auto_install =~ /-IP(\.pl)?$/) { my ($ip) = cat_('/tmp/stage1.log') =~ /configuring device (?!lo)\S+ ip: (\S+)/; my $normalized_ip = join('', map { sprintf "%02X", $_ } split('\.', $ip)); $::auto_install =~ s/-IP(\.pl)?$/-$normalized_ip$1/; } require install::steps_auto_install; eval { $o = $::o = install::any::loadO($o, $::auto_install) }; if ($@) { if ($o->{useless_thing_accepted}) { #- Pixel's hack to be able to fail through log::l("error using auto_install, continuing"); undef $::auto_install; } else { install::steps_auto_install_non_interactive::errorInStep($o, "Error using auto_install\n" . formatError($@)); } } else { log::l("auto install config file loaded successfully"); #- normalize for people not using our special scheme foreach (@{$o->{manualFstab} || []}) { $_->{device} =~ s!^/dev/!!; } } } sub step_init { my ($o) = @_; my $o_; while (1) { $o_ = $::auto_install ? install::steps_auto_install->new($o) : $o->{interactive} eq "stdio" ? install::steps_stdio->new($o) : $o->{interactive} eq "curses" ? install::steps_curses->new($o) : $o->{interactive} eq "gtk" ? install::steps_gtk->new($o) : die "unknown install type"; $o_ and last; log::l("$o->{interactive} failed, trying again with curses"); $o->{interactive} = "curses"; require install::steps_curses; } $o; } sub read_product_id() { my $product_id = cat__(install::any::getFile_($o->{stage2_phys_medium}, "product.id")); log::l('product_id: ' . chomp_($product_id)); $o->{product_id} = common::parse_LDAP_namespace_structure($product_id); $o->{meta_class} ||= { One => 'desktop', Free => 'download', Powerpack => 'powerpack', }->{$o->{product_id}{product}} || 'download'; } sub sig_segv_handler() { my $msg = "segmentation fault: install crashed (maybe memory is missing?)\n" . backtrace(); log::l("$msg\n"); # perl_checker: require UNIVERSAL UNIVERSAL::can($o, 'ask_warn') and $o->ask_warn('', $msg); setVirtual(1); require install::steps_auto_install; install::steps_auto_install_non_interactive::errorInStep($o, $msg); } sub read_stage1_net_conf() { require network::network; #- get stage1 network configuration if any. log::l('found /tmp/network'); add2hash($o->{net}{network} ||= {}, network::network::read_conf('/tmp/network')); if (my ($file) = grep { -f $_ } glob_('/tmp/ifcfg-*')) { log::l("found network config file $file"); my $l = network::network::read_interface_conf($file); $o->{net}{ifcfg}{$l->{DEVICE}} ||= $l; } my $dsl_device = find { $_->{BOOTPROTO} eq 'adsl_pppoe' } values %{$o->{net}{ifcfg}}; if ($dsl_device) { $o->{net}{type} = 'adsl'; $o->{net}{net_interface} = $dsl_device->{DEVICE}; $o->{net}{adsl} = { method => 'pppoe', device => $dsl_device->{DEVICE}, ethernet_device => $dsl_device->{DEVICE}, login => $dsl_device->{USER}, password => $dsl_device->{PASS}, }; %$dsl_device = (); } else { $o->{net}{type} = 'lan'; $o->{net}{net_interface} = first(values %{$o->{net}{ifcfg}}); } } sub parse_args { my ($cfg, $patch); my %cmdline = map { my ($n, $v) = split /=/; $n => defined($v) ? $v : 1; } split ' ', cat_("/proc/cmdline"); my $opt; foreach (@_) { if (/^--?(.*)/) { $cmdline{$opt} = 1 if $opt; $opt = $1; } else { $cmdline{$opt} = $_ if $opt; $opt = ''; } } $cmdline{$opt} = 1 if $opt; #- from stage1 put_in_hash(\%ENV, { getVarsFromSh('/tmp/env') }); exists $ENV{$_} and $cmdline{lc($_)} = $ENV{$_} foreach qw(METHOD PCMCIA KICKSTART); map_each { my ($n, $v) = @_; my $f = ${{ keyboard => sub { $o->{keyboard} = $v; push @::auto_steps, 'selectKeyboard' }, lang => sub { $o->{lang} = $v }, flang => sub { $o->{lang} = $v; push @::auto_steps, 'selectLanguage' }, langs => sub { $o->{locale}{langs} = +{ map { $_ => 1 } split(':', $v) } }, method => sub { $o->{method} = $v }, pcmcia => sub { $o->{pcmcia} = $v }, step => sub { $o->{steps}{first} = $v }, meta_class => sub { $o->{meta_class} = $v }, freedriver => sub { $o->{freedriver} = $v }, # fs/block options: no_bad_drives => sub { $o->{partitioning}{no_bad_drives} = 1 }, nodmraid => sub { $o->{partitioning}{nodmraid} = 1 }, readonly => sub { $o->{partitioning}{readonly} = $v ne "0" }, use_uuid => sub { $::no_uuid_by_default = !$v }, # urpmi options: debug_urpmi => sub { $o->{debug_urpmi} = 1 }, justdb => sub { $o->{justdb} = 1 }, 'tune-rpm' => sub { $o->{'tune-rpm'} = 'all' }, # GUI options: vga16 => sub { $o->{vga16} = $v }, vga => sub { $o->{vga} = $v =~ /0x/ ? hex($v) : $v }, display => sub { $o->{display} = $v }, askdisplay => sub { print "Please enter the X11 display to perform the install on ? "; $o->{display} = chomp_(scalar()) }, text => sub { $o->{interactive} = "curses" }, stdio => sub { $o->{interactive} = "stdio" }, newt => sub { $o->{interactive} = "curses" }, simple_themes => sub { $o->{simple_themes} = 1 }, theme => sub { $o->{theme} = $v }, doc => sub { $o->{doc} = 1 }, #- will be used to know that we're running for the doc team, #- e.g. we want screenshots with a good B&W contrast security => sub { $o->{security} = $v }, # auto install options: noauto => sub { $::noauto = 1 }, testing => sub { $::testing = 1 }, patch => sub { $patch = 1 }, defcfg => sub { $cfg = $v }, kickstart => sub { $::auto_install = $v }, local_install => sub { $::local_install = 1 }, uml_install => sub { $::uml_install = $::local_install = 1 }, auto_install => sub { $::auto_install = $v }, # debugging options: useless_thing_accepted => sub { $o->{useless_thing_accepted} = 1 }, alawindows => sub { $o->{security} = 0; $o->{partitioning}{clearall} = 1; $o->{bootloader}{crushMbr} = 1 }, fdisk => sub { $o->{partitioning}{fdisk} = 1 }, nomouseprobe => sub { $o->{nomouseprobe} = $v }, updatemodules => sub { $o->{updatemodules} = 1 }, suppl => sub { $o->{supplmedia} = $v }, askmedia => sub { $o->{askmedia} = 1 }, restore => sub { $::isRestore = 1 }, compsslistlevel => sub { $o->{compssListLevel} = $v }, }}{lc $n}; &$f if $f; } %cmdline; ($cfg, $patch); } sub init_env_share() { if ($::testing) { $ENV{SHARE_PATH} ||= "/export/install/stage2/live/usr/share"; $ENV{SHARE_PATH} = "/usr/share" if !-e $ENV{SHARE_PATH}; } else { $ENV{SHARE_PATH} ||= "/usr/share"; } } sub init_path() { #- make sure we do not pick up any gunk from the outside world my $remote_path = "$::prefix/sbin:$::prefix/bin:$::prefix/usr/sbin:$::prefix/usr/bin"; $ENV{PATH} = "/usr/bin:/bin:/sbin:/usr/sbin:$remote_path"; } sub init_mouse() { eval { $o->{mouse} = mouse::detect($o->{modules_conf}) } if !$o->{mouse} && !$o->{nomouseprobe}; mouse::load_modules($o->{mouse}); } sub init_modules_conf() { list_modules::load_default_moddeps(); require modules::any_conf; require modules::modules_conf; # read back config from stage1: $o->{modules_conf} = modules::modules_conf::read(modules::any_conf::vnew(), '/tmp/modules.conf'); modules::read_already_loaded($o->{modules_conf}); } sub process_auto_steps() { foreach (@::auto_steps) { if (my $s = $o->{steps}{/::(.*)/ ? $1 : $_}) { $s->{auto} = $s->{hidden} = 1; } else { log::l("ERROR: unknown step $_ in auto_steps"); } } } sub process_patch { my ($cfg, $patch) = @_; #- oem patch should be read before to still allow patch or defcfg. eval { $o = $::o = install::any::loadO($o, "install/patch-oem.pl"); log::l("successfully read oem patch") }; #- patch should be read after defcfg in order to take precedance. eval { $o = $::o = install::any::loadO($o, $cfg); log::l("successfully read default configuration: $cfg") } if $cfg; eval { $o = $::o = install::any::loadO($o, "patch"); log::l("successfully read patch") } if $patch; } #-###################################################################################### #- MAIN #-###################################################################################### sub main { $SIG{SEGV} = \&sig_segv_handler; $ENV{PERL_BADLANG} = 1; delete $ENV{TERMINFO}; umask 022; $::isWizard = 1; $::no_ugtk_init = 1; push @::textdomains, 'DrakX', 'drakx-net', 'drakx-kbd-mouse-x11'; my ($cfg, $patch) = parse_args(@_); init_env_share(); undef $::auto_install if $cfg; $o->{stage2_phys_medium} = install::media::stage2_phys_medium($o->{method}); log::l("second stage install running (", install::any::drakx_version($o), ")"); eval { touch('/root/non-chrooted-marker.DrakX') }; #- helps distinguishing /root and /mnt/root when we don't know if we are chrooted if ($::local_install) { init_local_install($o); } else { start_udev(); # load some modules early but asynchronously: run_program::raw({ detach => 1 }, 'modprobe', 'microcode'); } $o->{prefix} = $::prefix = $::testing ? "/tmp/test-perl-install" : "/mnt"; mkdir $::prefix, 0755 if ! -d $::prefix; init_path(); eval { install::any::spawnShell() }; init_modules_conf(); #- done before auto_install is called to allow the -IP feature on auto_install file name read_stage1_net_conf() if -e '/tmp/network'; #- done after module dependencies are loaded for "vfat depends on fat" if ($::auto_install) { init_auto_install(); } else { $o->{interactive} ||= 'gtk'; } if ($o->{interactive} eq "gtk" && availableMemory() < 22 * 1024) { log::l("switching to curses install cuz not enough memory"); $o->{interactive} = "curses"; } pre_init_brltty(); # perl_checker: require install::steps_gtk # perl_checker: require install::steps_curses # perl_checker: require install::steps_stdio require "install/steps_$o->{interactive}.pm" if $o->{interactive}; #- needed before accessing floppy (in case of usb floppy) modules::load_category($o->{modules_conf}, 'bus/usb'); process_patch($cfg, $patch); eval { modules::load("af_packet") }; require harddrake::sound; harddrake::sound::configure_sound_slots($o->{modules_conf}); #- need to be after oo-izing $o init_brltty() if $o->{brltty}; #- needed very early for install::steps_gtk init_mouse() if !$::testing; #- for auto_install compatibility with old $o->{lang}, #- and also for --lang and --flang if ($o->{lang}) { put_in_hash($o->{locale}, lang::lang_to_ourlocale($o->{lang})); } lang::set($o->{locale}); # keep the result otherwise monitor-edid does not return good results afterwards eval { any::monitor_full_edid() }; $o->{allowFB} = listlength(cat_("/proc/fb")); read_product_id() if !$::testing; log::l("META_CLASS=$o->{meta_class}"); process_auto_steps(); $ENV{COLUMNS} ||= 80; $ENV{LINES} ||= 25; $::o = $o = step_init($o); eval { output('/proc/splash', "verbose\n") }; real_main(); finish_install(); } sub real_main() { #-the main cycle MAIN: for ($o->{step} = $o->{steps}{first};; $o->{step} = getNextStep($o)) { $o->{steps}{$o->{step}}{entered}++; $o->enteringStep($o->{step}); my $time = time(); eval { &{$install::install2::{$o->{step}}}($o->{steps}{$o->{step}}{auto}); }; my $err = $@; log::l("step \"$o->{step}\" took: ", formatTimeRaw(time() - $time)); $o->kill_action; if ($err) { local $_ = $err; $o->kill_action; if (!/^already displayed/) { eval { $o->errorInStep($_) }; $o->{steps}{$o->{step}}{auto} = 0; $err = $@; $err and next; } $o->{step} = $o->{steps}{$o->{step}}{onError}; next MAIN unless $o->{steps}{$o->{step}}{reachable}; #- sanity check: avoid a step not reachable on error. redo MAIN; } $o->{steps}{$o->{step}}{done} = 1; $o->leavingStep($o->{step}); last if $o->{step} eq 'exitInstall'; } } sub finish_install() { unlink $install::any::compressed_image_on_disk; install::media::clean_postinstall_rpms(); install::media::log_sizes(); install::any::remove_advertising(); install::any::write_fstab($o); $o->{modules_conf}->write; detect_devices::install_addons($::prefix); install::any::adjust_files_mtime_to_timezone(); #- make sure failed upgrade will not hurt too much. install::steps::cleanIfFailedUpgrade($o); #- drop urpmi DB if urpmi is not installed: -e "$::prefix/usr/sbin/urpmi" or eval { rm_rf("$::prefix/var/lib/urpmi") }; system("chroot", $::prefix, "bash", "-c", $o->{postInstallBeforeReboot}) if $o->{postInstallBeforeReboot}; #- copy latest log files eval { cp_af("/tmp/$_", "$::prefix/root/drakx") foreach qw(ddebug.log stage1.log) }; #- ala pixel? :-) [fpons] common::sync(); common::sync(); stop_udev() if !$::local_install; log::l("installation complete, leaving"); log::l("files still open by install2: ", readlink($_)) foreach glob_("/proc/self/fd/*"); print "\n" x 80 if !$::local_install; } 1; ='n651' href='#n651'>651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
# vim: set et ts=4 sw=4:
package ManaTools::MainDisplay;
#============================================================= -*-perl-*-

=head1 NAME

ManaTools::MainDisplay - class for ManaTools main window

=head1 SYNOPSIS

    $mainDisplay = new ManaTools::MainDisplay();
    $mainDisplay->start();
    $mainDisplay->cleanup();

=head1 METHODS

=head1 DESCRIPTION

    ManaTools::MainDisplay implements the main window panel adding buttons
    reading the configuration for every categories and modules


=head1 SUPPORT

    You can find documentation for this module with the perldoc command:

    perldoc ManaTools::MainDisplay

=head1 AUTHOR

    Steven Tucker

=head1 COPYRIGHT and LICENSE

    Copyright (C) 2012-2015, Angelo Naselli.
    Copyright (C) 2012, Steven Tucker.

    ManaTools 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.

    ManaTools 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 ManaTools.  If not, see <http://www.gnu.org/licenses/>.

=head1 METHODS

=cut

use Moose;
extends qw( ManaTools::Module );

use I18N::LangTags::Detect;

use diagnostics;
use ManaTools::SettingsReader;
use ManaTools::ConfigReader;
use ManaTools::Category;
use ManaTools::Module;
use ManaTools::Shared;
use ManaTools::Shared::GUI;
use ManaTools::Shared::GUI::Dialog;
use ManaTools::Shared::Locales;
use File::ShareDir ':ALL';

use yui;
with 'ManaTools::LoggingRole';

has 'configDir' => (
    is      => 'ro',
    isa     => 'Str',
);

with 'ManaTools::ConfigDirRole';

#=============================================================

=head2 new

=head3 INPUT

    hash ref containing
        configDir: configuration files directory
        name:    application name, logging identity,
                 configuration subdirectory

=head3 other attributes

    title:        window title got from configuration file,
                  default is name.
    categories:   ArrayRef[ManaTools::Category]
    settings:     HashRef containing settings file content
    currCategory: Selected category
    mainWin:      Main Dialog window
    factory:      yui::YUI::widgetFactory
    menus:        HashRef containing menu items
    leftPane:     left panel layout
    rightPane:    right panel layout
  rightPaneFrame: right frame (needed for category title)
    replacePoint: replace point where to set new layout on
                  category selection
  selectedModule: module to be returned when selected

=head3 DESCRIPTION

    This method instanziates the MainWindo object, and setups
    the startup GUI.

=cut

#=============================================================
has '+name' => (
    is      => 'ro',
    isa     => 'Str',
    default => 'mpan',
);

has '+icon' => (
    is      => 'rw',
    isa     => 'Str',
    default => File::ShareDir::dist_file(ManaTools::Shared::distName(), 'images/mageia.png'),
);

has 'title'  => (
    is       => 'rw',
    isa      => 'Str',
    init_arg => undef,
    lazy     => 1,
    builder  => '_titleInitialize',
);

sub _titleInitialize {
    my $self = shift;

    return $self->name();
}

has 'settings' => (
    is       => 'rw',
    isa      => 'HashRef',
    init_arg => undef,
    default  => sub {return {};},
);

has 'categories' => (
    is => 'rw',
    isa => 'ArrayRef[ManaTools::Category]',
    init_arg => undef,
    lazy => 1,
    default => sub {[];},
);

has 'currCategory' => (
    is => 'rw',
    isa => 'Maybe[ManaTools::Category]',
    init_arg => undef,
    default => undef,
);

has 'factory' => (
    is => 'ro',
    isa => 'Maybe[yui::YWidgetFactory]',
    lazy => 1,
    init_arg => undef,
    default => sub {
       return yui::YUI::widgetFactory;
    },
);

has 'mainWin' => (
    is => 'rw',
    isa => 'Maybe[ManaTools::Shared::GUI::Dialog]',
    init_arg => undef,
    default => undef,
);

has 'menus' => (
    is => 'rw',
    isa => 'HashRef',
    init_arg => undef,
    default => sub {
        {
            file => {},
            help => {},
        };
    },
);

has 'leftPane' => (
    is => 'rw',
    isa => 'Maybe[yui::YLayoutBox]',
    init_arg => undef,
    default => undef,
);

has 'rightPane' => (
    is => 'rw',
    isa => 'Maybe[yui::YLayoutBox]',
    init_arg => undef,
    default => undef,
);

has 'rightPaneFrame' => (
    is => 'rw',
    isa => 'Maybe[yui::YFrame]',
    init_arg => undef,
    default => undef,
);

has 'replacePoint' => (
    is => 'rw',
    isa => 'Maybe[yui::YReplacePoint]',
    init_arg => undef,
    default => undef,
);

has 'selectedModule' => (
    is => 'rw',
    isa => 'Maybe[ManaTools::Module]',
    init_arg => undef,
    default => undef,
);


#=============================================================

=head2 configName

=head3 INPUT

    $self: this object

=head3 OUTPUT

    name: application name

=head3 DESCRIPTION

    Returns the application name as configuration subdirectory.
    This method is required by ConfifDirRole

=cut

#=============================================================
sub configName {
    my $self = shift;

    return $self->name();
}

#=============================================================

=head2 identifier

=head3 INPUT

    $self: this object

=head3 OUTPUT

    name: application name

=head3 DESCRIPTION

    Returns the application name as logging identifier.
    This method is required by LoggingRole

=cut

#=============================================================
sub identifier {
    my $self = shift;

    return $self->name();
}


sub _showAboutDialog {
    my $self = shift;

    my $translators = $self->{loc}->N("_: Translator(s) name(s) & email(s)\n");
    $translators =~ s/\</\&lt\;/g;
    $translators =~ s/\>/\&gt\;/g;
    my $sh_gui = ManaTools::Shared::GUI->new();
    $sh_gui->AboutDialog({ name => $self->{name},
        version => $self->Version(),
        credits => $self->loc()->N("Copyright (C) %s Mageia community", '2013-2015'),
        license => $self->loc()->N("GPLv2"),
        description => $self->loc()->N("mpan is the ManaTools panel that collects all the utilities."),
        authors => $self->loc()->N("<h3>Developers</h3>
                                    <ul><li>%s</li>
                                        <li>%s</li>
                                    </ul>
                                    <h3>Translators</h3>
                                    <ul><li>%s</li></ul>",
                                    "Angelo Naselli &lt;anaselli\@linux.it&gt;",
                                    "Matteo Pasotti &lt;matteo.pasotti\@gmail.com&gt;",
                                    $translators
        ),

    });
}



## Begin the program event loop
=head2 start

    contains the main loop of the application
    where we can check for events

=cut

sub start {
    my $self = shift;

    $self->_setupGui();

    return $self->selectedModule();
}

#=============================================================

=head2 cleanup

=head3 INPUT

    $self:     this object

=head3 DESCRIPTION

    This method cleanup data for a further start.

=cut

#=============================================================
sub cleanup {
    my $self = shift;

    $self->mainWin(undef);
    $self->menus({
        file => {},
        help => {},
    });

    for (my $cat=0; $cat < scalar(@{$self->categories()}); $cat++ ) {
        my $catSel = @{$self->categories()}[$cat];
        $catSel->button(undef);
        $catSel->removeButtons();
    }
    $self->leftPane(undef);
    $self->rightPane(undef);
    $self->rightPaneFrame(undef);
    $self->replacePoint(undef);
}

#=============================================================

=head2 _setupGui

=head3 INPUT

    $self:     this object

=head3 DESCRIPTION

    This method load configuration and build the GUI layout.

=cut

#=============================================================
sub _setupGui {
    my $self = shift;

    $self->selectedModule(undef);

    # fill $self->settings from settings.conf
    $self->_loadSettings();

    $DB::single = 1;
    $self->title($self->settings()->{title});
    $self->icon($self->settings()->{icon}) if $self->settings()->{icon};

    my $dialog = ManaTools::Shared::GUI::Dialog->new(
        module => $self,
        dialogType => ManaTools::Shared::GUI::Dialog::mainDialog,
        title => $self->title(),
        icon => $self->icon,
        buttons => {
            ManaTools::Shared::GUI::Dialog::aboutButton => sub {
                my $event = shift; ## ManaTools::Shared::GUI::Event
                my $self = $event->parentDialog()->module(); #this object

                $self->_showAboutDialog();
                return 1;
            },
            ManaTools::Shared::GUI::Dialog::closeButton => sub {return 0;},
        },
        layout => sub {
            my $self = shift;
            my $layoutstart = shift;
            my $ydialog = $self->dialog();
            my $module  = $self->module();
            my $info = $self->info();
            my $factory = $self->factory();
            my $optFactory = $self->optFactory();

            my $mainLayout = $factory->createVBox($layoutstart);
            my $menuLayout = $factory->createHBox($mainLayout);

            ## Menu File
            my $align = $factory->createAlignment($menuLayout, 1, 0);
            $module->menus()->{file} = {
                    widget => $factory->createMenuButton($align, $self->loc()->N("File")),
                    quit   => new yui::YMenuItem($self->loc()->N("&Quit")),
            };


            my @ordered_menu_lines = qw(quit);
            foreach (@ordered_menu_lines) {
                $module->menus()->{file}->{widget}->addItem($module->menus()->{file}->{ $_ });
            }
            $module->menus()->{file}->{ widget }->rebuildMenuTree();

            $align = $factory->createAlignment($menuLayout, 2, 0);
            $module->menus()->{help} = {
                    widget => $factory->createMenuButton($align, $self->loc()->N("Help")),
                    help   => new yui::YMenuItem($self->loc()->N("Help")),
                    about  => new yui::YMenuItem($self->loc()->N("&About")),
            };

            ## Menu Help
            @ordered_menu_lines = qw(help about);
            foreach (@ordered_menu_lines) {
                $module->menus()->{help}->{ widget }->addItem($module->menus()->{help}->{ $_ });
            }
            $module->menus()->{help}->{ widget }->rebuildMenuTree();
            ManaTools::Shared::GUI::Event->new(
                name => 'AboutMenuEvent',
                eventHandler => $self,
                eventType => $yui::YEvent::MenuEvent,
                item      => $module->menus()->{help}->{about},
                event => sub {
                    my $event = shift;
                    my $dialog = $event->parentDialog();
                    my $self = $dialog->module(); #this object

                    $self->_showAboutDialog();

                    return 1;
                },
            );
            ManaTools::Shared::GUI::Event->new(
                name => 'QuitMenuEvent',
                eventHandler => $self,
                eventType => $yui::YEvent::MenuEvent,
                item      => $module->menus()->{file}->{quit},
                event => sub {
                    return 0;
                },
            );

            my $layout = $factory->createHBox($mainLayout);
            #create left Panel Frame no need to add a label for title
            my $leftPaneFrame = $factory->createFrame($layout, $module->settings()->{category_title});
            #create right Panel Frame no need to add a label for title (use setLabel when module changes)
            my $rightPaneFrame = $factory->createFrame($layout, "");
            #create replace point for dynamically created widgets
            $module->replacePoint($factory->createReplacePoint($rightPaneFrame));
            $module->rightPane($factory->createVBox($module->replacePoint()));
            $module->leftPane($factory->createVBox($leftPaneFrame));
            $module->rightPaneFrame($rightPaneFrame);

            #logo from settings
            my $logofile = defined($module->settings()->{logo}) ?
                    $module->settings()->{logo} :
                    File::ShareDir::dist_file(ManaTools::Shared::distName(), 'images/logo_mageia.png'
            );

            my $logo = $factory->createImage($module->leftPane(), $logofile);
            $logo->setAutoScale(1);

            #$leftPaneFrame->setWeight(0, 1);
            $rightPaneFrame->setWeight(0, 2);

            $module->_loadCategories();

            $factory->createVStretch($module->leftPane());

            my $closeButton = $self->widget('closeButton');
            my $quitIcon = File::ShareDir::dist_file(ManaTools::Shared::distName(), 'images/quit.png');
            $closeButton->setIcon($quitIcon);

            if (!$module->currCategory()) {
                $module->currCategory(@{$module->categories()}[0]);
            }
            $module->currCategory()->addButtons($module);
            $module->rightPaneFrame()->setLabel($module->currCategory()->name());
            $factory->createSpacing($module->rightPane(), 1, 1, 1.0 );

            # Note that Since mpan is a Manatools::Module and creates other modules
            # title and application are set into BUILD (e.g. constructor) so last
            # built one is the one shown. Forcing setting again here
            yui::YUI::app()->setApplicationTitle($self->title);
            yui::YUI::app()->setApplicationIcon($self->icon);

            return $self->widget('layout');
        },
    );

    $self->mainWin($dialog);
    return $dialog->call();
}


## internal methods

## Check if event is from current Category View
## If icon click, returns the module to be launched

sub _moduleSelected {
    my ($self, $selectedWidget) = @_;

    for(@{$self->currCategory()->modules()}) {
        if( $_->button() == $selectedWidget ){
            return $_;
        }
    }
    return 0;
}


## Discover if a category button was selected.
## If category button is selected, sets right panel to display
## the selected Category Modules
## returns 1 if category button is selected
sub _categorySelected {
    my ($self, $selectedWidget) = @_;

    for (@{$self->categories()}) {
        if( $_->button() == $selectedWidget ) {

            #if current is already set then skips
            if ($self->currCategory() == $_) {
                ## returns 1 to skip any other checks on
                ## the selected widget
                return 1;
            }

            ## Menu item selected, set right pane
            my $ydialog = $self->mainWin()->dialog();
            $ydialog->startMultipleChanges();

            ## NOTE widget and item events (Shared::GUI:Event) created in the
            ## previous replacePoint MUST be cleaned up
            my $currCategory = $self->currCategory();
            ## Change Current Category to the selected one
            $self->currCategory($_);
            foreach my $mod (@{$currCategory->modules()}) {
                $self->mainWin()->delWidget(
                    $self->mainWin()->widget($mod->name())
                );
            }

            ## Remove existing modules
            $self->replacePoint()->deleteChildren();
            $self->rightPane($self->factory()->createVBox($self->replacePoint()));

            ## Add new Module Buttons to Right Pane
            $self->currCategory()->addButtons($self);
            $self->rightPaneFrame()->setLabel($self->currCategory()->name());
            $self->factory()->createSpacing($self->rightPane(), 1, 1, 1.0 );
            $self->replacePoint()->showChild();
            $ydialog->recalcLayout();
            $ydialog->doneMultipleChanges();

            return 1;
        }
    }

    return 0;
}

# return the localized string from a hash and given the key
# by default en value
sub _localizedValue {
    my ($self, $hash, $key) = @_;

    return if !defined($hash->{$key});

    if (ref($hash->{$key}) ne "HASH") {
        $self->logger()->W($self->loc()->N("Bad configuration file, %s has not xml:lang attribute, guessing it is a string", $key));
        # Force array is set for "title"
        return $hash->{$key}[0];
    }

    my @lang = I18N::LangTags::Detect::detect();
    # Adding default value as English (en)
    push @lang, 'en';
    foreach my $l ( @lang ) {
        return $hash->{$key}->{$l} if defined($hash->{$key}->{$l});
    }

    return;
}

## mpan settings
sub _loadSettings {
    my ($self, $force_load) = @_;

    # configuration file name
    my $fileName = $self->configPathName() . "/settings.conf";

    if (! -e $fileName) {
        my $err = $self->loc()->N("Configuration file %s is missing", $fileName);
        $self->logger()->E($err);
        die $err;
    }

    $self->logger()->I($self->loc()->N("Reading configuration file %s", $fileName));

    if (! scalar %{$self->settings()} || $force_load) {
        my $settingsReader = ManaTools::SettingsReader->new({fileName => $fileName});

        my $settings;
        my @lang = I18N::LangTags::Detect::detect();
        my $read = $settingsReader->settings();
        foreach (keys %{$read}) {
            my $key = $_;
            # localized strings
            if ($key eq "title" or $key eq "category_title") {
                # default is en
                $settings->{$key} = $self->_localizedValue(
                    $read,
                    $key
                );
                $self->logger()->I($self->loc()->N("Load settings: %s content is <<%s>>", $key, $settings->{$key}));
            }
            elsif (($key eq "icon" || $key eq "logo") && (substr( $read->{$key}, 0, 1) ne '/')) {
                # icon with relative path?
                $settings->{$key} = File::ShareDir::dist_file(ManaTools::Shared::distName(), $read->{$key});
            }
            else {
                $settings->{$key} = $read->{$key};
            }
        }

        $self->settings($settings);
    }
}

#=============================================================
#  _categoryLoaded
#
# INPUT
#
#     $self:     this object
#     $category: category to look for
#
# OUTPUT
#
#     $present: category is present or not
#
# DESCRIPTION
#
#     This method looks for the given category and if already in
#     returns true.
#
#=============================================================
sub _categoryLoaded {
    my ($self, $category) = @_;
    my $present = 0;

    if (!$category) {
        return $present;
    }

    foreach my $cat (@{$self->categories()}) {
        if ($cat->name() eq $category->name()) {
            $present = 1;
            last;
        }
    }

    return $present;
}

#=============================================================
#  _getCategory
#
#  INPUT
#
#     $self:     this object
#     $name:     category name
#
#  OUTPUT
#
#     $category: category object if exists
#
#  DESCRIPTION
#
#     This method looks for the given category name and returns
#     the realte object.
#=============================================================
sub _getCategory {
    my ($self, $name) = @_;
    my $category = undef;

    foreach $category (@{$self->categories()}) {
        if ($category->name() eq $name) {
            return $category;
        }
    }

    return $category;
}

# _loadCategory
#
# creates a new button representing a category
#
sub _loadCategory {
    my ($self, $category) = @_;

    if (!$self->_categoryLoaded($category)) {
        push ( @{$self->categories()}, $category );
        my $cat = @{$self->categories()}[-1];

        $cat->button(
            $self->factory()->createPushButton(
                $self->leftPane(),
                $cat->name()
            )
        );
        $cat->setIcon();
        $cat->button()->setStretchable(0, 1);
        $self->mainWin()->addWidget(
            $cat->name(),
            $cat->button(),  sub {
                my $event = shift; ## ManaTools::Shared::GUI::Event
                my $self = $event->parentDialog()->module(); #this object
                $self->_categorySelected($event->widget());

                return 1;
            }
        );
    }
    else {
        for (my $cat=0; $cat < scalar(@{$self->categories()}); $cat++ ) {
            my $catSelected = @{$self->categories()}[$cat];
            if( $catSelected->name() eq $category->name() &&
                !$catSelected->button())  {
                    $catSelected->button(
                        $self->factory()->createPushButton(
                            $self->leftPane(),
                            $catSelected->name()
                        )
                    );
                    $catSelected->setIcon();
                    $catSelected->button()->setStretchable(0, 1);
                    $self->mainWin()->addWidget(
                        $catSelected->name(),
                        $catSelected->button(),  sub {
                            my $event = shift; ## ManaTools::Shared::GUI::Event
                            my $self = $event->parentDialog()->module(); #this object
                            $self->_categorySelected($event->widget());

                            return 1;
                        }
                    );
                    last;

            }
        }
    }
}

sub _loadCategories {
    my $self = shift;

    # category files
    my @categoryFiles;
    my $fileName = $self->configPathName() . "/categories.conf";

    # configuration file dir
    my $directory = $self->configPathName() . "/categories.conf.d";

    push(@categoryFiles, $fileName);
    push(@categoryFiles, <$directory/*.conf>);
    my $currCategory;

    foreach $fileName (@categoryFiles) {
        $self->logger()->I($self->loc()->N("Parsing category file %s", $fileName));
        my $inFile = new ManaTools::ConfigReader({fileName => $fileName});
        my $tmpCat;
        my $tmp;
        my $hasNextCat = $inFile->hasNextCat();
        while( $hasNextCat ) {
            $tmp = $inFile->getNextCat();
            my $title = $self->_localizedValue(
                $tmp,
                'title'
            );
            $self->logger()->D($self->loc()->N("Load categories: title content is <<%s>>", $title));
            my $icon = $tmp->{icon};
            if ((substr( $icon, 0, 1) ne '/')) {
                # icon with relative path?
                $icon = File::ShareDir::dist_file(ManaTools::Shared::distName(), $tmp->{icon});
            }

            $tmpCat = $self->_getCategory($title);
            if (!$tmpCat) {
                $tmpCat = new ManaTools::Category({
                    name => $title,
                    icon => $icon,
                });
            }
            $self->_loadCategory($tmpCat);
            $hasNextCat  = $inFile->hasNextCat();
            $currCategory = $tmpCat;

            my $hasNextMod = $inFile->hasNextMod();
            while( $hasNextMod ) {
                $tmp = $inFile->getNextMod();
                my $tmpMod;
                my $loaded = 0;

                if (exists $tmp->{title}) {
                    my $title = $self->_localizedValue(
                        $tmp,
                        'title'
                    );
                    my $icon = $tmp->{icon};
                    if ((substr( $icon, 0, 1) ne '/')) {
                        # icon with relative path?
                        $icon = File::ShareDir::dist_file(ManaTools::Shared::distName(), $tmp->{icon});
                    }

                    $self->logger()->D($self->loc()->N("Load categories: module title is <<%s>>", $title));
                    if (not $currCategory->moduleLoaded($title)) {
                        $tmpMod = ManaTools::Module->create(
                            name => $title,
                            icon => $icon,
                            launch => $tmp->{launcher}
                        );
                    }
                }
                elsif (exists $tmp->{class}) {
                    if (not $currCategory->moduleLoaded(-CLASS => $tmp->{class})) {
                        $tmpMod = ManaTools::Module->create(-CLASS => $tmp->{class});
                    }
                }
                if ($tmpMod) {
                    $loaded = $currCategory->loadModule($tmpMod);
                    undef $tmpMod if !$loaded;
                }
                $hasNextMod = $inFile->hasNextMod();
            }
        }
    }
}

no Moose;
1;