#!/usr/bin/perl
#*****************************************************************************
#
#  Copyright (c) 2002 Guillaume Cottenceau (gc at mandriva dot com)
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2, as
#  published by the Free Software Foundation.
#
#  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.
#
#*****************************************************************************
#
# $Id: rpmdrake,v 1.364 2005/09/07 16:03:16 rgarciasuarez Exp $


use MDK::Common 'any';
use lib qw(/usr/lib/libDrakX);
use common;

BEGIN {  
    my $basename = sub { local $_ = shift; s|/*\s*$||; s|.*/||; $_ };
    any { /^--?h/ } @ARGV and do {
	printf join("\n", N("Usage: %s [OPTION]..."),
N("  --changelog-first      display changelog before filelist in the description window"),
N("  --media=medium1,..     limit to given media"),
N("  --merge-all-rpmnew     propose to merge all .rpmnew/.rpmsave files found"),
N("  --mode=MODE            set mode (install (default), remove, update)"),
N("  --no-confirmation      don't ask first confirmation question in update mode"),
N("  --no-media-update      don't update media at startup"),
N("  --no-verify-rpm        don't verify packages signatures"),
N("  --parallel=alias,host  be in parallel mode, use \"alias\" group, use \"host\" machine to show needed deps"),
N("  --pkg-nosel=pkg1,..    show only these packages"),
N("  --pkg-sel=pkg1,..      preselect these packages"),
N("  --root                 force to run as root"),
N("  --search=pkg           run search for \"pkg\""),
""
), $basename->($0);
	exit 0;
    };
}

use rpmdrake;




use POSIX qw(setlocale LC_ALL LC_COLLATE strftime);
use locale;
my $collation_locale = $ENV{LC_ALL};
if ($collation_locale) {
  $collation_locale =~ /UTF-8/ or setlocale(LC_ALL, "$collation_locale.UTF-8");
} else {
  $collation_locale = setlocale(LC_COLLATE);
  $collation_locale =~ /UTF-8/ or setlocale(LC_COLLATE, "$collation_locale.UTF-8");
}

our %options;
foreach (@ARGV) {
    /^-?-(\S+)$/ or next;
    my $val = $1;
    if ($val =~ /=/) {
        my ($name, $values) = split /=/, $val;
        my @values = split /,/, $values;
        $options{$name} = \@values if @values;
    } else {
        $options{$val} = 1;
    }
}

our $MODE = ref $options{mode} ? $options{mode}[0] : undef;
unless ($MODE) {
    $MODE = 'install';
    $0 =~ m|remove$|  and $MODE = 'remove';
    $0 =~ m|update$|i and $MODE = 'update';
}

eval { require ugtk2; ugtk2->import(qw(:all)); require Gtk2::Pango; require Gtk2::Gdk::Keysyms };
if ($@) {
    print "This program cannot be run in console mode.\n";
    c::_exit(0);  
}

$MODE eq 'update' || $options{root} and require_root_capability();
$ugtk2::wm_icon = "title-$MODE";
$::isStandalone = 1;
$::noborderWhenEmbedded = 1;

package gurpm;

ugtk2->import(':all');

our ($mainw, $label, $progressbar, $vbox, $cancel, $hbox_cancel);

sub init {
    my ($title, $initializing, %options) = @_;
    $mainw = ugtk2->new($title, %options);
    $label = Gtk2::Label->new($initializing);
    $progressbar = gtkset_size_request(Gtk2::ProgressBar->new, 300, -1);
    gtkadd($mainw->{window}, gtkpack__($vbox = gtkset_border_width(Gtk2::VBox->new(0, 5),6), $label, $progressbar));
    $mainw->{rwindow}->set_position('center');
    $mainw->sync;
}

sub label {
    $label->set($_[0]);
    select(undef, undef, undef, 0.1);  
    $mainw->flush;
}

sub progress {
    $progressbar->set_fraction($_[0]);
    $mainw->flush;
}

sub end {
    $mainw and $mainw->destroy;
    $mainw = undef;
    $cancel = undef;  
}

sub validate_cancel {
    my ($cancel_msg, $cancel_cb) = @_;
    if (!$cancel) {
        gtkpack__(
	    $vbox,
	    $hbox_cancel = gtkpack__(
		create_hbox(),
		$cancel = gtksignal_connect(Gtk2::Button->new($cancel_msg), clicked => \&$cancel_cb),
	    ),
	);
    }
    $cancel->set_sensitive(1);
    $cancel->show;
}

sub invalidate_cancel {
    $cancel and $cancel->set_sensitive(0);
}

sub invalidate_cancel_forever {
    $hbox_cancel or return;
    $hbox_cancel->destroy;
    $mainw->shrink_topwindow;
}

package main;

our $w;
my $changelog_first;
my $treeview_dialog_run = 0;
our $statusbar;

sub interactive_msg_  {  interactive_msg(@_, if_(exists $w->{rwindow}, transient => $w->{rwindow})) }
sub interactive_list_ { interactive_list(@_, if_(exists $w->{rwindow}, transient => $w->{rwindow})) }
sub wait_msg_         {         wait_msg(@_, if_(exists $w->{rwindow}, transient => $w->{rwindow})) }
sub wait_msg_with_banner { push @_, banner => 1 if $::isEmbedded && !$treeview_dialog_run; &statusbar_msg }
sub interactive_msg_with_banner { push @_, banner => 1 if $::isEmbedded; &interactive_msg_ }

$> and (interactive_msg_(N("Running in user mode"),
N("You are launching this program as a normal user.
You will not be able to perform modifications on the system,
but you may still browse the existing database."), yesno => 1, text => { no => N("Cancel"), yes => N("Ok") }) or myexit(0));

my $dont_show_selections = $> ? 1 : 0;


if (0) {
    my @valid_groups = (
	N_("Accessibility"),
	N_("Archiving"), N_("Backup"),
	N_("Archiving"), N_("Cd burning"),
	N_("Archiving"), N_("Compression"),
	N_("Archiving"), N_("Other"),
	N_("Books"), N_("Computer books"),
	N_("Books"), N_("Faqs"),
	N_("Books"), N_("Howtos"),
	N_("Books"), N_("Literature"),
	N_("Books"), N_("Other"),
	N_("Cluster"), N_("Message Passing"),
	N_("Cluster"), N_("Queueing Services"),
	N_("Communications"),
	N_("Databases"),
	N_("Development"), N_("C"),
	N_("Development"), N_("C++"),
	N_("Development"), N_("Databases"),
	N_("Development"), N_("GNOME and GTK+"),
	N_("Development"), N_("Java"),
	N_("Development"), N_("KDE and Qt"),
	N_("Development"), N_("Kernel"),
	N_("Development"), N_("Other"),
	N_("Development"), N_("Perl"),
	N_("Development"), N_("Python"),
	N_("Editors"),
	N_("Education"),
	N_("Emulators"),
	N_("File tools"),
	N_("Games"), N_("Adventure"),
	N_("Games"), N_("Arcade"),
	N_("Games"), N_("Boards"),
	N_("Games"), N_("Cards"),
	N_("Games"), N_("Other"),
	N_("Games"), N_("Puzzles"),
	N_("Games"), N_("Sports"),
	N_("Games"), N_("Strategy"),
	N_("Graphical desktop"), N_("Enlightenment"),
	N_("Graphical desktop"), N_("FVWM based"),
	N_("Graphical desktop"), N_("GNOME"),
	N_("Graphical desktop"), N_("Icewm"),
	N_("Graphical desktop"), N_("KDE"),
	N_("Graphical desktop"), N_("Other"),
	N_("Graphical desktop"), N_("Sawfish"),
	N_("Graphical desktop"), N_("WindowMaker"),
	N_("Graphics"),
	N_("Monitoring"),
	N_("Multimedia"),
	N_("Networking"), N_("Chat"),
	N_("Networking"), N_("File transfer"),
	N_("Networking"), N_("IRC"),
	N_("Networking"), N_("Instant messaging"),
	N_("Networking"), N_("Mail"),
	N_("Networking"), N_("News"),
	N_("Networking"), N_("Other"),
	N_("Networking"), N_("Remote access"),
	N_("Networking"), N_("WWW"),
	N_("Office"),
	N_("Public Keys"),
	N_("Publishing"),
	N_("Sciences"), N_("Astronomy"),
	N_("Sciences"), N_("Biology"),
	N_("Sciences"), N_("Chemistry"),
	N_("Sciences"), N_("Computer science"),
	N_("Sciences"), N_("Geosciences"),
	N_("Sciences"), N_("Mathematics"),
	N_("Sciences"), N_("Other"),
	N_("Sciences"), N_("Physics"),
	N_("Shells"),
	N_("Sound"),
	N_("System"), N_("Base"),
	N_("System"), N_("Configuration"), N_("Boot and Init"),
	N_("System"), N_("Configuration"), N_("Hardware"),
	N_("System"), N_("Configuration"), N_("Networking"),
	N_("System"), N_("Configuration"), N_("Other"),
	N_("System"), N_("Configuration"), N_("Packaging"),
	N_("System"), N_("Configuration"), N_("Printing"),
	N_("System"), N_("Deploiement"),
	N_("System"), N_("Deployment"),
	N_("System"), N_("Fonts"), N_("Console"),
	N_("System"), N_("Fonts"), N_("True type"),
	N_("System"), N_("Fonts"), N_("Type1"),
	N_("System"), N_("Fonts"), N_("X11 bitmap"),
	N_("System"), N_("Internationalization"),
	N_("System"), N_("Kernel and hardware"),
	N_("System"), N_("Libraries"),
	N_("System"), N_("Servers"),
	N_("System"), N_("XFree86"),
	N_("Terminals"),
	N_("Text tools"),
	N_("Toys"),
	N_("Video"),
    );
}


my $tag_tag = { 'foreground' => 'royalblue3', 'weight' => Gtk2::Pango->PANGO_WEIGHT_BOLD };
my $tag_fix = { 'font' => 'monospace' };

sub ctreefy {
    join('|', map { translate($_) } split m|/|, $_[0]);
}

sub rpm_summary {
    my ($summary) = @_;
    c::set_tagged_utf8($summary);
    $summary;
}

sub rpm_description {
    my ($description) = @_;
    c::set_tagged_utf8($description);
    my ($t, $tmp);
    foreach (split "\n", $description) {
	s/^\s*//;
        if (/^$/ || /^\s*(-|\*|\+|o)\s/) {
            $t || $tmp and $t .= "$tmp\n";
            $tmp = $_;
        } else {
            $tmp = ($tmp ? "$tmp " : ($t && "\n") . $tmp) . $_;
        }
    }
    "$t$tmp\n";
}

sub myformatList {
    my $r = formatList(40, @_);
    $r =~ s/(.{50}\S*)\s/$1\n/g;
    $r;
}

sub split_fullname { $_[0] =~ /^(.*)-([^-]+-[^-]+)$/ }
sub my_fullname {
    return '?-?-?' unless ref $_[0];
    my ($name, $version, $release) = $_[0]->fullname;
    "$name-$version-$release";
}
sub urpm_name {
    return '?-?-?.?' unless ref $_[0];
    my ($name, $version, $release, $arch) = $_[0]->fullname;
    "$name-$version-$release.$arch";
}

sub parse_compssUsers_flat {
    my (%compssUsers, $category);
    my $compss = '/var/lib/urpmi/compssUsers.flat';
    -r $compss or $compss = '/usr/share/rpmdrake/compssUsers.flat.default';
    -r $compss or do {
	print STDERR "No compssUsers.flat file found\n";
	return undef;
    };
    foreach (cat_($compss)) {
	s/#.*//;
	/^\s*$/ and next;
	if (/^\S/) {
	    if (/^(.+?) \[icon=.+?\] \[path=(.+?)\]/) {
		$category = translate($2) . '|' . translate($1);
	    } else {
		print STDERR "Malformed category in compssUsers.flat: <$_>\n";
	    }
	} elsif (/^\t(\d) (\S+)\s*$/) {
	    $category or print STDERR "Entry without category <$_>\n";
	    push @{$compssUsers{$2}}, $category . ($1 <= 3 ? '|' . N("Other") : '');
	}
    }
    \%compssUsers;
}

sub pkg2medium {
    my ($p, $urpm) = @_;
    foreach (@{$urpm->{media}}) {
	!$_->{ignore} && $p->id <= $_->{end} and return $_;
    }
    undef;
}







sub localtime2changelog { to_utf8(strftime("%c", localtime($_[0]))) }

sub extract_header {
    my ($pkg, $urpm) = @_;
    my $chg_prepro = sub {
	
	[ map { [ "$_\n", if_(/^\*/, { 'weight' => Gtk2::Pango->PANGO_WEIGHT_BOLD }) ] } split("\n", $_[0]) ];
    };
    my $name = my_fullname($pkg->{pkg});
    if ($MODE eq 'remove') {
	@$max_info_in_descr or return;
	add2hash($pkg, { files => [ split /\n/, chomp_(scalar(`rpm -ql $name`)) || N("(none)") ],
                         changelog => $chg_prepro->(to_utf8(scalar(`rpm -q --changelog $name`))) });
    } else {
	my ($p, $medium) = ($pkg->{pkg}, pkg2medium($pkg->{pkg}, $urpm));
	my $hdlist = $medium->{virtual} ? "$medium->{url}/$medium->{with_hdlist}" : "$urpm->{statedir}/$medium->{hdlist}";
	$hdlist =~ s/^file:\/+//;
	if (-r $hdlist) {
	    standalone::explanations("Extracting header of " . $p->header_filename . " from $hdlist");
	    my $packer;
	    eval { require packdrake; $packer = new packdrake($hdlist, quiet => 1) }
		or log::l("Warning, hdlist seems corrupted :-("), goto header_non_available;
            my $headersdir = chomp_(`mktemp -d /tmp/rpmdrake.XXXXXX`);
            -d $headersdir or die "Could not create temporary directory";
	    $packer->extract_archive($headersdir, $p->header_filename);
	    $p->update_header("$headersdir/" . $p->header_filename) or log::l("Warning, could not extract header!"), goto header_non_available;
	    rm_rf($headersdir);
	    add2hash($pkg, { summary => rpm_summary($p->summary), description => rpm_description($p->description) });
	    @$max_info_in_descr and add2hash($pkg, {
	        files => scalar($p->files) ? [ $p->files ] : [ N("(none)") ],
		changelog => $chg_prepro->(join("\n", mapn { "* " . localtime2changelog($_[2]) . " $_[0]\n\n$_[1]\n" }
						[ $p->changelog_name ], [ $p->changelog_text ], [ $p->changelog_time ])) });
	    $p->pack_header;
	} else {
           header_non_available:
             add2hash($pkg, { summary => $p->summary || N("(Not available)"), description => undef });
	}
    }
}

sub db {
    my ($force) = @_;
    my $host;
    if ($options{parallel} && ((undef, $host) = @{$options{parallel}})) {
        my $done if 0;
        my $dblocation = "/var/cache/urpmi/distantdb/$host";
        if (!$done || $force) {
            print "syncing db from $host to $dblocation...";
            mkdir_p "$dblocation/var/lib/rpm";
            system "rsync -Sauz -e ssh $host:/var/lib/rpm/ $dblocation/var/lib/rpm";
            $? == 0 or die "Couldn't sync db from $host to $dblocation";
            $done = 1;
            print "done.\n";
        }
        URPM::DB::open($dblocation) or die "Couldn't open RPM DB";
    } else {
        URPM::DB::open or die "Couldn't open RPM DB";
    }
}

sub do_search($$$$$$$) {
    my ($find_entry, $tree, $tree_model, $options, $current_search_type, $urpm, $pkgs) = @_;
    my $entry = quotemeta $find_entry->get_text or return;
    my $entry_rx = eval { qr/$entry/i } or return;
    my ($results_ok, $results_none) = (N("Search results"), N("Search results (none)"));
    $options->{delete_category}->($_) foreach $results_ok, $results_none;
    $options->{state}{flat} and $options->{delete_all}->();
    $tree->collapse_all;
    my @search_results;
    if ($current_search_type ne 'normal') {
	if ($MODE eq 'remove') {
	    if ($current_search_type eq 'descriptions') {
		@search_results = grep { ($pkgs->{$_}{summary} . $pkgs->{$_}{description}) =~ $entry_rx } keys %$pkgs;
	    } else {
		slow_func_statusbar(
		    N("Please wait, searching..."),
		    $w->{rwindow},
		    sub {
			db->traverse(sub {
			    push @search_results, map { if_(($_ =~ $entry_rx), my_fullname($_[0])) } $_[0]->files;
			});
			@search_results = grep { exists $pkgs->{$_} } uniq(@search_results);
		    },
		);
	    }
	} else {
	    my @hdlists = map {
		my $h = $_->{virtual} ? "$_->{url}/$_->{with_hdlist}" : "$urpm->{statedir}/$_->{hdlist}";
		$h =~ s/^file:\/+//;
		if_(!$_->{ignore} && ($MODE ne 'update' || $_->{update}) && -r $h, $h);
	    } @{$urpm->{media}};
	    my $total_size = sum(
		map {
		    my $pack;
		    eval { require packdrake; $pack = new packdrake($_, quiet => 1) } ? $pack->{toc_f_count} : 0;
		} @hdlists
	    );
	    my $searchstop;
	    my $searchw = ugtk2->new(N("Rpmdrake"), grab => 1, transient => $w->{rwindow});
	    gtkadd(
		$searchw->{window},
		gtkpack__(
		    Gtk2::VBox->new(0, 5),
		    Gtk2::Label->new(N("Please wait, searching...")),
		    my $searchprogress = gtkset_size_request(Gtk2::ProgressBar->new, 300, -1),
		    gtkpack__(
			gtkset_layout(Gtk2::HButtonBox->new, 'spread'),
			gtksignal_connect(
			    Gtk2::Button->new(but(N("Stop"))),
			    clicked => sub { $searchstop = 1 },
			),
		    ),
		),
	    );
	    $searchw->sync;
	    open my $sf, 'parsehdlist --fileswinfo --description --summary ' . join(' ', map { "'$_'" } @hdlists) . ' |';
	    my ($pkg, $progresscount);
	    while (<$sf>) {
		$searchstop and last;
		if (/^NAME<([^>]+)> VERSION<([^>]+)> RELEASE<([^>]+)>/) {
		    $pkg = "$1-$2-$3";
		    $progresscount++; $progresscount <= $total_size and $searchprogress->set_fraction($progresscount/$total_size);
		    $searchw->flush;
		    next;
		}
		$pkg or next;
		my (undef, $key, $value) = split ':', $_;
		if ($current_search_type eq 'descriptions') {
		    $key =~ /^summary|description$/ or next;
		} else {
		    $key eq 'files' or next;
		}
		if ($value =~ $entry_rx) {
		    exists $pkgs->{$pkg} and push @search_results, $pkg;
		    $pkg = '';
		}
	    }
	    close $sf;
	    @search_results = uniq(@search_results); 
	    $searchw->destroy;
	}
    } else {
	@search_results = grep { $_ =~ $entry_rx } keys %$pkgs;
    }
    if (@search_results) {
	$options->{add_nodes}->(map { [ $_, N("Search results") . ($options->{tree_mode} eq 'by_presence'
								 ? '|' . ($pkgs->{$_}{pkg}->flag_installed ? N("Upgradable") : N("Addable"))
								 : ($options->{tree_mode} eq 'by_selection'
								    ? '|' . ($pkgs->{$_}{selected} ? N("Selected") : N("Not selected"))
								    : ''))
				      ] } sort { uc($a) cmp uc($b) } @search_results);
	my $last_iter = $tree_model->iter_nth_child(undef, $tree_model->iter_n_children(undef) - 1);
	my $path = $tree_model->get_path($last_iter);
	$tree->expand_row($path, 0);
    	$tree->scroll_to_cell($path, undef, 1, 0.5, 0);
    } else {
	$options->{add_nodes}->([ '', $results_none, { nochild => 1 } ]);
    }
}

sub find_installed_version {
    my ($p) = @_;
    my @version;
    db->traverse_tag('name', [ $p->name ], sub { push @version, $_[0]->version . '-' . $_[0]->release });
    @version ? join(',', sort @version) : N("(none)");
}


sub remove_arch {
    $_[0] =~ /(.*)\.[^\.]+$/ ? $1 : $_[0];
}

sub formatlistpkg { myformatList(sort { uc($a) cmp uc($b) } @_) }

sub format_pkg_info {
    my ($pkgs, $key, $urpm, $descriptions) = @_;
    my ($name, $version) = split_fullname($key);
    my @files = (
	[ N("Files:\n"), $tag_tag ],
	exists $pkgs->{$key}{files}
	    ? [ join("\n", map { "\x{200e}$_" } @{$pkgs->{$key}{files}}), $tag_fix ]
	    : [ N("(Not available)") ],
    );
    my @chglo = ([ N("Changelog:\n"), $tag_tag ], @{$pkgs->{$key}{changelog} || [[ N("(Not available)") ]]});
    my @source_info = (
	$MODE eq 'remove' || !@$max_info_in_descr
	    ? ()
	    : (
		[ N("Medium: "), $tag_tag ],
		[ pkg2medium($pkgs->{$key}{pkg}, $urpm)->{name} ], [ "\n" ],
		[ N("Currently installed version: "), $tag_tag ],
		[ find_installed_version($pkgs->{$key}{pkg}) ], [ "\n" ]
	    )
    );
    my @max_info = if_(
	@$max_info_in_descr,
	$changelog_first ? (@chglo, [ "\n" ], @files) : (@files, [ "\n\n" ], @chglo),
    );
    [ [ N("Name: "),    $tag_tag ], [ "$name\n" ],
      [ N("Version: "), $tag_tag ], [ "$version\n" ],
      [ N("Architecture: "), $tag_tag ], [ $pkgs->{$key}{pkg}->arch . "\n" ],
      [ N("Size: "),    $tag_tag ], [ N("%s KB", int($pkgs->{$key}{pkg}->size/1024)) . "\n" ],
      if_(
	  $MODE eq 'update',
	  [ N("Importance: "), $tag_tag ], [ "$descriptions->{$name}{importance}\n" ]
      ),
      @source_info,
      [ "\n" . N("Summary: "), $tag_tag ], [ "$pkgs->{$key}{summary}\n\n" ],
      if_(
	  $MODE eq 'update',
	  [ N("Reason for update: "), $tag_tag ], [ rpm_description($descriptions->{$name}{pre}) . "\n" ],
      ),
      [ N("Description: "), $tag_tag ], [ ($pkgs->{$key}{description} || $descriptions->{$name}{description} || N("No description")) . "\n" ],
      @max_info,
    ];
}

sub run_treeview_dialog {
    my ($pkgs_provider, $callback_action) = @_;

    my ($urpm, $pkgs, $descriptions) = $pkgs_provider->();

    my ($options, $size_selected, $compssUsers, $tree, $tree_model, %elems);
    my (undef, $size_free) = MDK::Common::System::df('/usr');

    $w = ugtk2->new(N("Rpmdrake"));
    $::main_window = $w->{real_window};

    my $is_locale_available = sub {
	any { $urpm->{depslist}[$_]->flag_selected } keys %{$urpm->{provides}{$_[0]} || {}} and return 1;
	my $found;
	db->traverse_tag('name', [ $_ ], sub { $found ||= 1 });
	return $found;
    };
    my $callback_choices = sub {
	my (undef, undef, undef, $choices) = @_;
	foreach my $pkg (@$choices) {
	    foreach ($pkg->requires_nosense) {
		/locales-/ or next;
		$is_locale_available->($_) and return $pkg;
	    }
	}
	my $callback = sub { interactive_msg_(N("More information on package..."), $options->{get_info}->($_[0]), scroll => 1) };
	$choices->[interactive_list_(N("Please choose"), N("One of the following packages is needed:"),
				     [ map { my_fullname($_) } @$choices ], $callback)];
    };
    my $closure_removal = sub {
        my @to_remove;
        $urpm->{state} = {};
	foreach (@_) {
            $urpm->resolve_rejected(db(), $urpm->{state}, $pkgs->{$_}{pkg}, removed => 1);
            foreach (keys %{$urpm->{state}{rejected}}) {
                $urpm->{state}{rejected}{$_}{removed} && !$urpm->{state}{rejected}{$_}{obsoleted} and push @to_remove, remove_arch($_);
            }
	}
        @to_remove;
    };
    $options = {
	node_state => sub {
	    $_[0] ? ($pkgs->{$_[0]}{selected} ? 'selected' : 'unselected') : 'XXX';
	},  
	build_tree => sub {
	    my ($add_node, $flat, $mode) = @_;
	    my @elems;
	    my $wait; $wait = statusbar_msg(N("Please wait, listing packages...")) if $MODE ne 'update';
	    gtkflush();
	    if ($mode eq 'mandrake_choices') {
		foreach my $pkg (keys %$pkgs) {
		    my ($name) = split_fullname($pkg);
		    push @elems, [ $pkg, $_ ] foreach @{$compssUsers->{$name}};
		}
	    } else {
		my @keys = keys %$pkgs;
		if ($MODE eq 'update') {
		    @keys = grep {
			my ($name) = split_fullname($_);
			member($descriptions->{$name}{importance}, @$mandrakeupdate_wanted_categories)
			|| ! $descriptions->{$name}{importance};
		    } @keys;
		    if (@keys == 0) {
			$add_node->('', N("(none)"), { nochild => 1 });
			my $explanation_only_once if 0;
			$explanation_only_once or interactive_msg_(N("No update"),
N("The list of updates is empty. This means that either there is
no available update for the packages installed on your computer,
or you already installed all of them."));
			$explanation_only_once = 1;
		    }
		}
		@elems = map { [ $_, !$flat && ctreefy($pkgs->{$_}{pkg}->group) ] } @keys;
	    }
	    my %sortmethods = (
		by_size => sub { sort { $pkgs->{$b->[0]}{pkg}->size <=> $pkgs->{$a->[0]}{pkg}->size } @_ },
		by_selection => sub { sort { $pkgs->{$b->[0]}{selected} <=> $pkgs->{$a->[0]}{selected}
			|| uc($a->[0]) cmp uc($b->[0]) } @_ },
		by_leaves => sub {
		    my $pkgs_times = 'rpm -q --qf "%{name}-%{version}-%{release} %{installtime}\n" `urpmi_rpm-find-leaves`';
		    sort { $b->[1] <=> $a->[1] } grep { exists $pkgs->{$_->[0]} } map { [ split ] } `$pkgs_times`;
		},
		flat => sub { sort { uc($a->[0]) cmp uc($b->[0]) } @_ },
		by_medium => sub { sort { $a->[2] <=> $b->[2] || uc($a->[0]) cmp uc($b->[0]) } @_ },
	    );
	    if ($flat) {
		$add_node->($_->[0], '') foreach $sortmethods{$mode || 'flat'}->(@elems);
	    } else {
		if ($MODE eq 'update') {
		    $add_node->($_->[0], N("All")) foreach $sortmethods{flat}->(@elems);
		    $tree->expand_row($tree_model->get_path($tree_model->get_iter_first), 0);
		} elsif ($mode eq 'by_source') {
		    $add_node->($_->[0], $_->[1]) foreach $sortmethods{by_medium}->(map {
			my $m = pkg2medium($pkgs->{$_->[0]}{pkg}, $urpm); [ $_->[0], $m->{name}, $m->{priority} ];
		    } @elems);
		} elsif ($mode eq 'by_presence') {
		    $add_node->(
			$_->[0], $pkgs->{$_->[0]}{pkg}->flag_installed && !$pkgs->{$_->[0]}{pkg}->flag_skip
			? N("Upgradable") : N("Addable")
		    ) foreach $sortmethods{flat}->(@elems);
		} else {
		    
		    %elems = ();
		    foreach my $root (sort { $a cmp $b } uniq(map { ($_->[1] =~ /([^\|]+)\|?/)[0] } @elems)) {
			$add_node->('', $root);
			@{$elems{$root}} = sort { $a->[1] cmp $b->[1] || uc($a->[0]) cmp uc($b->[0]) }
			grep { $_->[1] =~ /^\Q$root\E\b/ } @elems;
		    }
		}
	    }
	    statusbar_msg_remove($wait) if defined $wait;
	},
	grep_unselected => sub { grep { exists $pkgs->{$_} && !$pkgs->{$_}{selected} } @_ },
	partialsel_unsel => sub {
	    my ($unsel, $sel) = @_;
	    @$sel = grep { exists $pkgs->{$_} } @$sel;
	    @$unsel < @$sel;
	},
	toggle_nodes => sub {
	    my ($set_state, @nodes) = @_;
	    @nodes = grep { exists $pkgs->{$_} } @nodes
		or return;
	    
	    return if !$dont_show_selections && (($MODE ne 'update' && @nodes == keys %$pkgs) || @nodes > 2000);
	    my $new_state = !$pkgs->{$nodes[0]}{selected};

	    my @nodes_with_deps;
	    my $deps_msg = sub {
		return 1 if $dont_show_selections;
		my ($title, $msg, $nodes, $nodes_with_deps) = @_;
		my @deps = sort { $a cmp $b } difference2($nodes_with_deps, $nodes);
		@deps > 0 or return 1;
		deps_msg_again:
		my $results = interactive_msg_(
		    $title, $msg . formatlistpkg(@deps),
		    yesno => [ N("Cancel"), N("More info"), N("Ok") ],
		    scroll => 1,
		);
		if ($results eq
		    
		    N("More info"))
		{
		    interactive_packtable(
			N("Information on packages"),
			$w->{rwindow},
			undef,
			[ map { my $pkg = $_;
			    [ gtkpack__(Gtk2::HBox->new(0,0), gtkset_selectable(Gtk2::Label->new($pkg),1)),
			    gtksignal_connect(Gtk2::Button->new(N("More information on package...")),
				clicked => sub {
				    interactive_msg(N("More information on package..."), $options->{get_info}->($pkg), scroll => 1);
				}) ] } @deps ],
			[ gtksignal_connect(Gtk2::Button->new(N("Ok")),
			    clicked => sub { Gtk2->main_quit }) ]
		    );
		    goto deps_msg_again;
		} else {
		    return $results eq N("Ok");
		}
	    };
	    if ($MODE eq 'remove') {
		if ($new_state) {
		    my @remove;
		    slow_func($tree->window, sub { @remove = $closure_removal->(@nodes) });
		    @nodes_with_deps = grep { !$pkgs->{$_}{selected} && !/^basesystem/ } @remove;
		    $deps_msg->(N("Some additional packages need to be removed"),
			N("Because of their dependencies, the following package(s) also need to be\nremoved:\n\n"),
			\@nodes, \@nodes_with_deps) or @nodes_with_deps = ();
		    my @impossible_to_remove;
		    foreach (grep { exists $pkgs->{$_}{base} } @remove) {
			${$pkgs->{$_}{base}} == 1 ? push @impossible_to_remove, $_ : ${$pkgs->{$_}{base}}--;
		    }
		    @impossible_to_remove and interactive_msg_(N("Some packages can't be removed"),
			N("Removing these packages would break your system, sorry:\n\n") .
			formatlistpkg(@impossible_to_remove));
		    @nodes_with_deps = difference2(\@nodes_with_deps, \@impossible_to_remove);
		} else {
		    slow_func($tree->window,
			sub { @nodes_with_deps = grep { intersection(\@nodes, [ $closure_removal->($_) ]) }
			    grep { $pkgs->{$_}{selected} && !member($_, @nodes) } keys %$pkgs });
		    push @nodes_with_deps, @nodes;
		    $deps_msg->(N("Some packages can't be removed"),
			N("Because of their dependencies, the following package(s) must be\nunselected now:\n\n"),
			\@nodes, \@nodes_with_deps) or @nodes_with_deps = ();
		    $pkgs->{$_}{base} && ${$pkgs->{$_}{base}}++ foreach @nodes_with_deps;
		}
	    } else {
		if ($new_state) {
		    if (@nodes > 1) {
			
			my @bad_i18n_pkgs;
			foreach my $sel (@nodes) {
			    foreach ($pkgs->{$sel}{pkg}->requires_nosense) {
				/locales-([^-]+)/ or next;
				$sel =~ /-$1[-_]/ && !$is_locale_available->($_) and push @bad_i18n_pkgs, $sel;
			    }
			}
			@nodes = difference2(\@nodes, \@bad_i18n_pkgs);
		    }
		    my @requested;
		    slow_func(
			$tree->window,
			sub {
			    @requested = $urpm->resolve_requested(
				db(), $urpm->{state},
				{ map { $pkgs->{$_}{pkg}->id => 1 } @nodes },
				callback_choices => $callback_choices,
			    );
			},
		    );
		    @nodes_with_deps = map { my_fullname($_) } @requested;
		    if (!$deps_msg->(N("Additional packages needed"),
			    N("To satisfy dependencies, the following package(s) also need\nto be installed:\n\n"),
			    \@nodes, \@nodes_with_deps))
		    {
			@nodes_with_deps = ();
			$urpm->disable_selected(db(), $urpm->{state}, @requested);
			goto packages_selection_ok;
		    }

		    if (my @cant = sort(difference2(\@nodes, \@nodes_with_deps))) {
			my @ask_unselect = $urpm->unselected_packages($urpm->{state});
			my @reasons = map {
			    my $cant = $_;
			    my $unsel = find { remove_arch($_) eq $cant } @ask_unselect;
			    $unsel
			    ? to_utf8(join "\n", $urpm->translate_why_unselected($urpm->{state}, $unsel))
			    : ($pkgs->{$_}{pkg}->flag_skip ? N("%s (belongs to the skip list)", $cant) : $cant);
			} @cant;
			interactive_msg_(
			    N("Some packages can't be installed"),
			    N("Sorry, the following package(s) can't be selected:\n\n%s", join("\n", @reasons)),
			    scroll => 1,
			);
			foreach (@cant) {
			    $pkgs->{$_}{pkg}->set_flag_requested(0);
			    $pkgs->{$_}{pkg}->set_flag_required(0);
			}
		    }
		    packages_selection_ok:
		} else {
		    my @unrequested;
		    slow_func($tree->window,
			sub { @unrequested = $urpm->disable_selected(db(), $urpm->{state},
				map { $pkgs->{$_}{pkg} } @nodes) });
		    @nodes_with_deps = map { my_fullname($_) } @unrequested;
		    if (!$deps_msg->(N("Some packages need to be removed"),
			    N("Because of their dependencies, the following package(s) must be\nunselected now:\n\n"),
			    \@nodes, \@nodes_with_deps))
		    {
			@nodes_with_deps = ();
			$urpm->resolve_requested(db(), $urpm->{state}, { map { $_->id => 1 } @unrequested });
			goto packages_unselection_ok;
		    }
		    packages_unselection_ok:
		}
	    }

	    foreach (@nodes_with_deps) {
		
		
		exists $pkgs->{$_} or next;
		$pkgs->{$_}{pkg} or $new_state = 0; 
		$set_state->($_, $new_state ? 'selected' : 'unselected');
		$pkgs->{$_}{selected} = $new_state;
		$pkgs->{$_}{pkg}
		    and $size_selected += $pkgs->{$_}{pkg}->size * ($new_state ? 1 : -1);
	    }
	}, 
	get_status => sub {
	    $MODE eq 'install'
		? N("Selected: %d MB / Free disk space: %d MB", $size_selected/(1024*1024), $size_free/1024)
		: N("Selected size: %d MB", $size_selected/(1024*1024));
	},
	get_info => sub {
	    my ($key) = @_;
	    return if $key eq ''; 
	    
	    exists $pkgs->{$key} or return [ [ N("Description not available for this package\n") ] ];
	    exists $pkgs->{$key}{description} && (!@$max_info_in_descr || exists $pkgs->{$key}{files})
		or slow_func($tree->window, sub { extract_header($pkgs->{$key}, $urpm) });
	    format_pkg_info($pkgs, $key, $urpm, $descriptions);
	},
	check_interactive_to_toggle => sub { 1 },
	grep_allowed_to_toggle => sub { @_ },
	rebuild_tree => sub {},
    };

    if (my @initial_selection = grep { $pkgs->{$_}{selected} } keys %$pkgs) {
        $options->{initial_selection} = \@initial_selection;
        $pkgs->{$_}{selected} = 0 foreach keys %$pkgs;
    }

    $tree_model = Gtk2::TreeStore->new("Glib::String", "Gtk2::Gdk::Pixbuf", "Glib::String");
    $tree = Gtk2::TreeView->new_with_model($tree_model);
    $tree->get_selection->set_mode('browse');

    $tree->append_column(my $pixcolumn  = Gtk2::TreeViewColumn->new_with_attributes(undef, Gtk2::CellRendererPixbuf->new, 'pixbuf' => 1));
    $pixcolumn->{is_pix} = 1;
    $tree->append_column(my $textcolumn = Gtk2::TreeViewColumn->new_with_attributes(undef, Gtk2::CellRendererText->new, 'text' => 0));

    $tree->append_column(Gtk2::TreeViewColumn->new_with_attributes(undef, Gtk2::CellRendererText->new, 'text' => 2));
    $tree->set_headers_visible(0);
    $tree->set_rules_hint(1);

    ($typical_width) = string_size($tree, translate("Graphical Environment") . "xmms-more-vis-plugins");
    $typical_width > 500 and $typical_width = 500;  
    $typical_width < 150 and $typical_width = 150;
    
    #$textcolumn->set_min_width($typical_width*0.7);

    my $cursor_to_restore;
    $tree->signal_connect(
	expose_event => sub {
	    $cursor_to_restore or return;
	    gtkset_mousecursor_normal($tree->window);
	    undef $cursor_to_restore;
	},
    );
    $tree->signal_connect(
	row_expanded => sub {
	    my ($tree, $iter, $path) = @_;
	    
	    # availability, then we need to expand on the fly. (by update availability,
	    # selecting all packages will be too slow and expose too much choice conflicts)
	    my $child = $tree_model->iter_children($iter);
	    if ($options->{tree_mode} ne 'by_presence' && $tree_model->get($child, 0) eq '') {
		$tree_model->remove($child);
		slow_func(
		    $tree->window,
		    sub { $options->{add_nodes}->(@{$elems{$tree_model->get($iter, 0)}}) }
		);
	    } else {
		if ($tree_model->iter_n_children($iter) > 500) {
		    
		    $cursor_to_restore = 1;
		    gtkset_mousecursor_wait($tree->window);
		}
	    }
	    $tree->expand_row($path, 0);
	},
    );

    my @modes_buttons;
    if ($MODE eq 'update') {
	$options->{state}{flat} = 0;
	my %toggle_infos = (security => N("Security updates"), bugfix => N("Bugfixes updates"), normal => N("Normal updates"));
	my @toggle_names_ordered = qw(security bugfix normal);
	@modes_buttons = map { Gtk2::CheckButton->new(but($toggle_infos{$_})) } @toggle_names_ordered;
	mapn {
	    member($_[0], @$mandrakeupdate_wanted_categories) and $_[1]->set_active(1);
	    my $capture_value = $_[0];
	    $_[1]->signal_connect(
		clicked => sub {
		    if ($_[0]->get_active) {
			push @$mandrakeupdate_wanted_categories, $capture_value;
		    } else {
			@$mandrakeupdate_wanted_categories = difference2($mandrakeupdate_wanted_categories, [ $capture_value ]);
		    }
		    $options->{rebuild_tree}->();
		},
	    );
	} \@toggle_names_ordered, \@modes_buttons;
    } else {
	my %radios_infos = (
	    mandrake_choices => {
		name => $rpmdrake::branded ? N("%s choices", $rpmdrake::distrib{system}) : N("Mandriva Linux choices"),
		flat => 0,
	    },
	    flat             => { name => N("All packages, alphabetical"), flat => 1 },
	    by               => { name => '',                              flat => 0 },
	);
	my @radios_names_ordered = qw(mandrake_choices flat by);
	$compssUsers = parse_compssUsers_flat()
	    or shift @radios_names_ordered;

	my @advanced_modes = (
	    [ 'by_group', N("All packages, by group"), 0 ],
	    [ 'by_size', N("All packages, by size"), 1 ],
	    [ 'by_selection', N("All packages, by selection state"), 1 ],
	);
	if ($MODE eq 'install') {
	    push @advanced_modes, (
		[ 'by_source', N("All packages, by medium repository"), 0 ],
		[ 'by_presence', N("All packages, by update availability"), 0 ],
	    );
	}
	elsif ($MODE eq 'remove') {
	    push @advanced_modes, [ 'by_leaves', N("Leaves only, sorted by install date"), 1 ];
	}

	my $default_radio = $options->{tree_mode} = 'mandrake_choices';
        if (member($tree_mode->[0], keys %radios_infos, map { $_->[0] } @advanced_modes)) {
            $default_radio = $options->{tree_mode} = $tree_mode->[0];
            $options->{state}{flat} = $tree_flat->[0];
            $default_radio =~ s/^by.*/by/;
        }

	@modes_buttons = gtkradio($radios_infos{$default_radio}{name}, map { $radios_infos{$_}{name} } @radios_names_ordered);

	mapn {
	    my $capture_mode = $_[0];
            $capture_mode eq $tree_mode->[0] and $_[1]->set_active(1);
	    $_[1]->signal_connect(clicked => sub {
		if ($options->{tree_mode} ne $capture_mode && $_[0]->get_active) {
		    ($options->{tree_mode}, $options->{state}{flat}) = $capture_mode eq 'by'
			? ($options->{tree_submode}, $options->{tree_subflat})
			: ($capture_mode,            $radios_infos{$capture_mode}{flat});
		    $tree_mode->[0] = $options->{tree_mode};
		    $tree_flat->[0] = $options->{state}{flat};
		    $options->{rebuild_tree}->();
		}
	    });
	} \@radios_names_ordered, \@modes_buttons;

	my $radio_by;
	$options->{tree_submode} ||= $advanced_modes[0][0];
	$options->{tree_subflat} ||= $advanced_modes[0][2];
	each_index {
	    if ($_ eq 'by') {
		$radio_by = $modes_buttons[$::i];
		$modes_buttons[$::i] = gtkpack(
		    Gtk2::HBox->new(0, 0),
		    $modes_buttons[$::i],
		    my $t = Gtk2::ComboBox->new
		);
		$t->set_model(Gtk2::ListStore->new('Glib::String'));
		my $search_types_renderer = Gtk2::CellRendererText->new;
		$t->pack_start($search_types_renderer, Glib::FALSE());
		$t->set_attributes($search_types_renderer, text => 0);
		my $iter = $t->get_model->iter_nth_child(undef, 0);
		my $n = 0; my $active = 0;
		foreach my $m (@advanced_modes) {
		    $m->[0] eq $tree_mode->[0] and $active = $n;
		    $iter = $t->get_model->insert($n++);
		    $t->get_model->set($iter, 0, $m->[1]);
		}
		$t->set_active($active);
		$options->{tree_submode} = $advanced_modes[$active][0];
		$options->{tree_subflat} = $advanced_modes[$active][2];
		$t->signal_connect(
		    changed => sub {
			my $act = $t->get_active;
			$options->{tree_submode} = $advanced_modes[$act][0];
			$options->{tree_subflat} = $advanced_modes[$act][2];
			$radio_by->activate;
		    },
		);
	    }
	} @radios_names_ordered;
    }

    my @search_types = qw(normal descriptions files);
    my $current_search_type = $search_types[0];
    my $search_types_optionmenu = Gtk2::ComboBox->new;
    {
	$search_types_optionmenu->set_model(Gtk2::ListStore->new('Glib::String'));
	my $search_types_renderer = Gtk2::CellRendererText->new;
	$search_types_optionmenu->pack_start($search_types_renderer, Glib::FALSE());
	$search_types_optionmenu->set_attributes($search_types_renderer, text => 0);
	my $iter = $search_types_optionmenu->get_model->iter_nth_child(undef, 0);
	$iter = $search_types_optionmenu->get_model->insert(0);
	$search_types_optionmenu->get_model->set($iter, 0, N("in names"));
	$iter = $search_types_optionmenu->get_model->insert(1);
	$search_types_optionmenu->get_model->set($iter, 0, N("in descriptions"));
	$iter = $search_types_optionmenu->get_model->insert(2);
	$search_types_optionmenu->get_model->set($iter, 0, N("in file names"));
	$search_types_optionmenu->set_active(0);
	$search_types_optionmenu->signal_connect(
	    changed => sub {
		$current_search_type = $search_types[$search_types_optionmenu->get_active];
	    },
	);
    }

    my @menu_descr_modes = ([ N("Normal information"), [] ], [ N("Maximum information"), [1] ]);
    my @descr_modes = gtkradio($menu_descr_modes[@$max_info_in_descr ? 1 : 0][0], map { $_->[0] } @menu_descr_modes);
    mapn {
	my $val = $_[1][1];
	$_[0]->signal_connect(clicked => sub {
				  if ($_[0]->get_active) {
				      $max_info_in_descr = $val;
				      $options->{display_info}->();
				  }
			      });
    } \@descr_modes, \@menu_descr_modes;
    my $info = Gtk2::TextView->new;
    $info->set_left_margin(2);
    $info->set_right_margin(15);  

    my $find_entry;
    my $find_callback = sub { do_search($find_entry, $tree, $tree_model, $options, $current_search_type, $urpm, $pkgs) };

    my $do_action = sub {
	if (!int(grep { $pkgs->{$_}{selected} } keys %$pkgs)) {
	    interactive_msg_(N("You need to select some packages first."), N("You need to select some packages first."));
            return;
        }
	my $size_added = sum(map { if_($_->flag_selected && !$_->flag_installed, $_->size) } @{$urpm->{depslist}});
	if ($MODE eq 'install' && $size_free - $size_added/1024 < 50*1024) {
	    interactive_msg_(N("Too many packages are selected"),
N("Warning: it seems that you are attempting to add so much
packages that your filesystem may run out of free diskspace,
during or after package installation ; this is particularly
dangerous and should be considered with care.

Do you really want to install all the selected packages?"), yesno => 1)
	      or return;
	}
	if ($MODE ne 'remove') {
            @{$urpm->{ask_remove}} = sort $urpm->removed_packages($urpm->{state});
            if (@{$urpm->{ask_remove}}) {
		my $r = join "\n", $urpm->translate_why_removed($urpm->{state}, @{$urpm->{ask_remove}});
		interactive_msg_(N("Some packages need to be removed"),
N("The following packages have to be removed for others to be upgraded:

%s

Is it ok to continue?",
		    to_utf8($r)),
		scroll => 1,
		yesno => 1) or return;
	    }
	}
	if (!$callback_action->($urpm, $pkgs)) {
	    ($urpm, $pkgs, $descriptions) = $pkgs_provider->({ skip_updating_mu => 1 });
	    $size_selected = 0;
	    (undef, $size_free) = MDK::Common::System::df('/usr');
	    $options->{rebuild_tree}->();
            gtktext_insert($info, '');
	}
    };

    my $table = Gtk2::Table->new(0, 0, 0);
    $table->attach(gtkpack__(Gtk2::HBox->new(0, 0), gtkpack(Gtk2::VBox->new(0, 0), @modes_buttons)),
		   0, 1, 0, 1, 'fill', 'fill', 0, 0);
    $table->attach(gtkpack__(Gtk2::HBox->new(0, 0), gtkpack(Gtk2::VBox->new(0, 0), Gtk2::Label->new, @descr_modes)),
		   1, 2, 0, 1, 'fill', 'fill', 0, 0);

    my $hpaned = Gtk2::HPaned->new;
    $hpaned->pack1(gtkset_size_request(create_scrolled_window($tree), $typical_width*1.25, -1) , 0, 0);
    $hpaned->pack2(create_scrolled_window($info), 1, 0);
    $table->attach($hpaned, 0, 2, 1, 2, ['expand', 'fill'], ['expand', 'fill'], 0, 0);

    my $status = Gtk2::Label->new;
    my $checkbox_show_autoselect;
    my ($menu, $factory) = create_factory_menu(
	$w->{real_window},
	[ N("/_File"), undef, undef, undef, '<Branch>' ],
	if_(
	    $MODE ne 'remove' && ! $>,
	    [ N("/_File") . N("/_Update media"), undef, sub {
		update_sources_interactive($urpm, transient => $w->{rwindow})
		    and do {
			($urpm, $pkgs, $descriptions) = $pkgs_provider->({ skip_updating_mu => 1 });
			$size_selected = 0;
			$options->{rebuild_tree}->();
		    };
	    }, undef, '<Item>' ]
	),
	[ N("/_File") . N("/_Reset the selection"), undef, sub {
	    if ($MODE ne 'remove') {
		$urpm->disable_selected(
		    db(), $urpm->{state},
		    map { if_($pkgs->{$_}{selected}, $pkgs->{$_}{pkg}) } keys %$pkgs,
		);
	    }
	    $pkgs->{$_}{selected} = 0 foreach keys %$pkgs;
	    $size_selected = 0;
	    $options->{rebuild_tree}->();
	}, undef, '<Item>' ],
	[ N("/_File") . N("/Reload the _packages list"), undef, sub {
	    ($urpm, $pkgs, $descriptions) = $pkgs_provider->({ skip_updating_mu => 1 });
	    $size_selected = 0;
	    $options->{rebuild_tree}->();
	}, undef, '<Item>' ],
	[ N("/_File") . N("/_Quit"), N("<control>Q"), sub { Gtk2->main_quit }, undef, '<Item>', ],
	#[ N("/_View"), undef, undef, undef, '<Branch>' ],
	if_(!$>,
	    [ N("/_Options"), undef, undef, undef, '<Branch>' ],
	    [ N("/_Options") . N("/_Show automatically selected packages"), undef, sub {
		$dont_show_selections = !$checkbox_show_autoselect->get_active;
	    }, undef, '<CheckItem>' ],
	),
	[ N("/_Help"), undef, undef, undef, '<Branch>' ],
	[ N("/_Help") . N("/_Help"), undef, sub { rpmdrake::open_help($MODE) }, undef, '<Item>' ],
    );
    $checkbox_show_autoselect = $factory->get_widget("<main>" . strip_first_underscore(N("/_Options"), N("/_Show automatically selected packages")))
	and $checkbox_show_autoselect->set_active(!$dont_show_selections);
    gtkadd(
	$w->{window},
	gtkpack_(
	    Gtk2::VBox->new(0, 3),
	    0, $menu,
	    0, getbanner,
	    1, gtkadd(
		gtkset_shadow_type(gtkset_border_width(Gtk2::Frame->new, 3), 'none'),
		gtkpack_(
		    Gtk2::VBox->new(0, 3),
		    0, gtkpack__(
			Gtk2::HBox->new(0, 10),
			Gtk2::Label->new(N("Find:")),
			$search_types_optionmenu,
			gtksignal_connect($find_entry = Gtk2::Entry->new,
			    key_press_event => sub { $_[1]->keyval == $Gtk2::Gdk::Keysyms{Return}
				    and $find_callback->() }),
			gtksignal_connect(Gtk2::Button->new(but(N("Search"))), clicked => $find_callback)
		    ),
		    1, $table,
		    0, gtkpack_(
			Gtk2::HBox->new(0, 20),
			0, my $action_button = gtksignal_connect(
			    Gtk2::Button->new(but_($MODE eq 'remove' ? N("Remove") : N("Install"))),
			    clicked => sub { $do_action->() },
			),
			1, $status,
			0, gtksignal_connect(
			    Gtk2::Button->new(but_(N("Quit"))),
			    clicked => sub { Gtk2->main_quit },
			),
		    ),
		),
	    ),
	    0, $statusbar = Gtk2::Statusbar->new,
	),
    );
    $action_button->set_sensitive(0) if $>;
    $find_entry->grab_focus;

    $w->{rwindow}->set_default_size($typical_width*2.7, 500) if !$::isEmbedded;
    $find_entry->set_text($options{search}[0]) if $options{search};

    $w->{rwindow}->show_all;
    $options->{widgets} = {
	w => $w,
	tree => $tree,
	tree_model => $tree_model,
	textcolumn => $textcolumn,
	pixcolumn => $pixcolumn,
	info => $info,
	status => $status,
    };
    $options->{init_callback} = $find_callback if $options{search};

    $treeview_dialog_run = 1;
    ask_browse_tree_info_given_widgets($options);
}

# -=-=-=---=-=-=---=-=-=-- install packages -=-=-=---=-=-=---=-=-=-

sub get_installable_pkgs {
    my ($updates, $opts) = @_;
    my $update_name = 'update_source';
    my %update_descr;
    my @update_medias;

    if ($updates) {
        my $urpm = urpm->new;
        $urpm->configure;
        $urpm->{fatal} = sub {
            interactive_msg(N("Fatal error"),
                            N("A fatal error occurred: %s.", $_[1]));
            myexit(-1);
        };
	my $statedir = $urpm->{statedir};
	@update_medias = grep { !$_->{ignore} && $_->{update} } @{$urpm->{media}};
	unless ($options{'no-media-update'}) {
	    if (@update_medias > 0) {
		if (!$opts->{skip_updating_mu}) {
		    $options{'no-confirmation'} or interactive_msg_with_banner(N("Rpmdrake"),
N("I need to contact the mirror to get latest update packages.
Please check that your network is currently running.

Is it ok to continue?"), yesno => 1) or myexit(-1);
		    $urpm->select_media(map { $_->{name} } @update_medias);
		    update_sources($urpm, noclean => 1, banner => $::isEmbedded);
		}
	    } else {
		if (any { $_->{update} } @{$urpm->{media}}) {
		    interactive_msg_(N("Already existing update media"),
N("You already have at least one update medium configured, but
all of them are currently disabled. You should run the Software
Media Manager to enable at least one (check it in the Enabled?
column).

Then, restart %s.", $rpmdrake::myname_update));
		    myexit(-1);
		}
	      mu_retry_another_mirror:
		my $m = choose_mirror(if_(exists $w->{rwindow}, transient => $w->{rwindow}));
		$m or interactive_msg_(N("How to choose manually your mirror"),
N("You may also choose your desired mirror manually: to do so,
launch the Software Media Manager, and then add a `Security
updates' medium.

Then, restart %s.", $rpmdrake::myname_update)), myexit(-1);
		add_medium_and_check(
		    $urpm, {},
		    $update_name, make_url_mirror($m), 'media_info/synthesis.hdlist.cz', update => 1,
		);
		@update_medias = { name => $update_name };  
	    }
	}

	my ($cur, $section);
	
	foreach (map { cat_("$statedir/descriptions.$_->{name}"), '%package dummy' } @update_medias) {
	    /^%package +(.+)/ and do {
		my @pkg_list = split /\s+/, $1;
		exists $cur->{importance} && $cur->{importance} !~ /^(?:security|bugfix)\z/
		    and $cur->{importance} = 'normal';
		$update_descr{$_} = $cur foreach @{$cur->{pkgs} || []};
		$cur = {};
		$cur->{pkgs} = [ @pkg_list ];
		$section = 'pkg';
		next;
	    };
	    /^%(pre|description)/ and do { $section = $1; next };
	    /^Updated?: +(.+)/ && $section eq 'pkg'
		and do { $cur->{update} = $1; next };
	    /^Importance: +(.+)/ && $section eq 'pkg'
		and do { $cur->{importance} = $1; next };
	    /^(ID|URL): +(.+)/ && $section eq 'pkg'
		and do { $cur->{$1} = $2; next };
	    $section =~ /^(pre|description)\z/ and $cur->{$1} .= $_;
	}
    }
    my $wait = wait_msg_with_banner(N("Please wait, finding available packages..."));
    gtkflush();
    my $urpm = urpm->new;
    $urpm->{state} = {};
    my %installable_pkgs;

    my $media = ref $options{media} ? join(',', @{$options{media}}) : '';
    $urpm->configure(media => $media);

    @update_medias = grep { !$_->{ignore} && $_->{update} } @{$urpm->{media}};
    check_update_media_version($urpm, @update_medias);

    $urpm->compute_installed_flags(db()) unless $updates;
    my $requested = {};
    $urpm->request_packages_to_upgrade(
	db(),
	{}, 
	$requested,
	start => 0,
	end   => $#{$urpm->{depslist}},
    );
    $urpm->{depslist}[$_]->set_flag_installed foreach keys %$requested; 

    my %pkg_sel   = map { $_ => 1 } @{$options{'pkg-sel'}   || []};
    my %pkg_nosel = map { $_ => 1 } @{$options{'pkg-nosel'} || []};
    foreach my $pkg (@{$urpm->{depslist}}) {
	$pkg->flag_upgrade or next;
        my $selected = 0;
	if ($updates) {
            $pkg->flag_installed or next;
            any { $pkg->id >= $_->{start} && $pkg->id <= $_->{end} } @update_medias or next;
            if ($options{'pkg-sel'} || $options{'pkg-nosel'}) {
		my $n = urpm_name($pkg);
		$pkg_sel{$n} || $pkg_nosel{$n} or next;
		$pkg_sel{$n} and $selected = 1;
	    }
	}
	$installable_pkgs{my_fullname($pkg)} = { selected => $selected, pkg => $pkg };
    }
    if ($options{'pkg-sel'} && $options{'pkg-nosel'}) {
        push @{$options{'pkg-nosel'}}, @{$options{'pkg-sel'}};
        delete $options{'pkg-sel'};
    }

    statusbar_msg_remove($wait);
    ($urpm, \%installable_pkgs, \%update_descr);
}

# /var/lib/nfs/etab /var/lib/nfs/rmtab /var/lib/nfs/xtab /var/cache/man/whatis
my %ignores_rpmnew = map { $_ => 1 } qw(
    /etc/adjtime
    /etc/group
    /etc/ld.so.conf
    /etc/localtime
    /etc/modules
    /etc/passwd
    /etc/security/fileshare.conf
    /etc/shells
    /etc/sudoers
    /etc/sysconfig/alsa
    /etc/sysconfig/autofsck
    /etc/sysconfig/harddisks
    /etc/sysconfig/init
    /etc/sysconfig/installkernel
    /etc/sysconfig/msec
    /etc/sysconfig/nfs
    /etc/sysconfig/pcmcia
    /etc/sysconfig/rawdevices
    /etc/sysconfig/saslauthd
    /etc/sysconfig/syslog
    /etc/sysconfig/usb
    /etc/sysconfig/xinetd
);

sub dialog_rpmnew {
    my ($msg, %p2r) = @_;
    @{$p2r{$_}} = grep { !$ignores_rpmnew{$_} } @{$p2r{$_}} foreach keys %p2r;
    my $sum_rpmnew = sum(map { int @{$p2r{$_}} } keys %p2r);
    $sum_rpmnew == 0 and return 1;
    my @inspect_wsize = ($typical_width*2.5, 500);
    my $inspect = sub {
	my ($file) = @_;
	my ($rpmnew, $rpmsave) = ("$file.rpmnew", "$file.rpmsave");
	my $rpmfile = 'rpmnew';
	-r $rpmnew or $rpmfile = 'rpmsave';
	-r $rpmnew && -r $rpmsave && (stat $rpmsave)[9] > (stat $rpmnew)[9] and $rpmfile = 'rpmsave';
	$rpmfile eq 'rpmsave' and $rpmnew = $rpmsave;
	my @diff = `/usr/bin/diff -u '$file' '$rpmnew'`;
	return if !@diff;
	my $d = ugtk2->new(N("Inspecting %s", $file), grab => 1, transient => $w->{rwindow});
	my $save_wsize = sub { @inspect_wsize = $d->{rwindow}->get_size };
	my %texts;
	gtkadd(
	    $d->{window},
	    gtkpack_(
		Gtk2::VBox->new(0, 5),
		1, create_vpaned(
		    create_vpaned(
			gtkpack_(
			    Gtk2::VBox->new(0, 0),
			    0, gtkset_markup(Gtk2::Label->new, qq(<span font_desc="monospace">$file:</span>)),
			    1, create_scrolled_window($texts{file} = Gtk2::TextView->new),
			),
			gtkpack_(
			    Gtk2::VBox->new(0, 0),
			    0, gtkset_markup(Gtk2::Label->new, qq(<span font_desc="monospace">$rpmnew:</span>)),
			    1, create_scrolled_window($texts{rpmnew} = Gtk2::TextView->new),
			),
			resize1 => 1,
		    ),
		    gtkpack_(
			Gtk2::VBox->new(0, 0),
			0, Gtk2::Label->new(N("changes:")),
			1, create_scrolled_window($texts{diff} = Gtk2::TextView->new),
		    ),
		    resize1 => 1,
		),
		0, gtkpack__(
		    create_hbox(),
		    gtksignal_connect(
			Gtk2::Button->new(N("Remove .%s", $rpmfile)),
			clicked => sub { $save_wsize->(); unlink $rpmnew; Gtk2->main_quit },
		    ),
		    gtksignal_connect(
			Gtk2::Button->new(N("Use .%s as main file", $rpmfile)),
			clicked => sub { $save_wsize->(); renamef($rpmnew, $file); Gtk2->main_quit },
		    ),
		    gtksignal_connect(
			Gtk2::Button->new(N("Do nothing")),
			clicked => sub { $save_wsize->(); Gtk2->main_quit },
		    ),
		)
	    )
	);
	my %contents = (file => scalar(cat_($file)), rpmnew => scalar(cat_($rpmnew)));
	gtktext_insert($texts{$_}, [ [ $contents{$_}, { 'font' => 'monospace' } ] ]) foreach keys %contents;
	my @regexps = ([ '^(--- )|(\+\+\+ )', 'blue' ], [ '^@@ ', 'darkcyan' ], [ '^-', 'red3' ], [ '^\+', 'green3' ]);
	my $line2col = sub { $_[0] =~ /$_->[0]/ and return $_->[1] foreach @regexps; 'black' };
	gtktext_insert($texts{diff}, [ map { [ $_, { 'font' => 'monospace', 'foreground' => $line2col->($_) } ] } @diff ]);
	$d->{rwindow}->set_default_size(@inspect_wsize);
	$d->main;
    };

    interactive_packtable(
	N("Installation finished"),
	$w->{rwindow},
	$msg,
	[ map { my $pkg = $_;
	    map {
		my $f = $_;
		my $b;
		[ gtkpack__(
		    Gtk2::HBox->new(0, 0),
		    gtkset_markup(
			gtkset_selectable(Gtk2::Label->new, 1),
			qq($pkg:<span font_desc="monospace">$f</span>),
		    )
		),
		gtksignal_connect(
		    $b = Gtk2::Button->new(N("Inspect...")),
		    clicked => sub {
			$inspect->($f);
			-r "$f.rpmnew" || -r "$f.rpmsave" or $b->set_sensitive(0);
		    },
		) ];
	    } @{$p2r{$pkg}};
	} keys %p2r ],
	[ gtksignal_connect(Gtk2::Button->new(N("Ok")),
	    clicked => sub { Gtk2->main_quit }) ]
    );
    return 0;
}

sub perform_installation {  
    my ($urpm) = @_;

    my $fatal_msg;
    my @error_msgs;
    my @Readmes;
    my $statusbar_msg_id;
    local $urpm->{fatal} = sub { printf STDERR "Fatal: %s\n", $_[1]; $fatal_msg = to_utf8($_[1]); goto fatal_error };
    local $urpm->{error} = sub { printf STDERR "Error: %s\n", $_[0]; push @error_msgs, to_utf8($_[0]) };

    $w->{rwindow}->set_sensitive(0);

    my $group;
    if ($options{parallel} && (($group) = @{$options{parallel}})) {
        my $pkgs = join(' ', map { if_($_->flag_requested, my_fullname($_)) } @{$urpm->{depslist}});
        system("urpmi -v --X --parallel $group $pkgs");
        if ($? == 0) {
            $statusbar_msg_id = statusbar_msg(
		#N("Everything installed successfully"),
		N("All requested packages were installed successfully."),
	    );
        } else {
            interactive_msg_(
		N("Problem during installation"),
		N("There was a problem during the installation:\n\n%s", join("\n", @error_msgs)),
		scroll => 1,
	    );
        }
        db('force_sync');
        $w->{rwindow}->set_sensitive(1);
        return 0;
    }

    standalone::explanations("Removing package $_") foreach sort @{$urpm->{ask_remove}};

    my %pkgs = map { $_->id => undef } grep { $_->flag_selected } @{$urpm->{depslist}};
    my ($local_sources, $list, $local_to_removes) = $urpm->get_source_packages(\%pkgs);
    my $distant_number = scalar keys %pkgs;
    if (!$local_sources && (!$list || !@$list)) {
        interactive_msg_(
	    N("Unable to get source packages."),
	    N("Unable to get source packages, sorry. %s",
		@error_msgs ? N("\n\nError(s) reported:\n%s", join("\n", @error_msgs)) : ''),
	    scroll => 1,
	);
        goto return_with_error;
    }
    foreach (@$local_to_removes) {
        unlink $_;
    }

    gurpm::init(N("Package installation..."), N("Initializing..."), transient => $w->{rwindow});
    my $distant_progress;
    my $canceled;
    my %sources = $urpm->download_source_packages(
	$local_sources,
	$list,
	force_local => 1,
	ask_for_medium => sub {
	    interactive_msg_(
		N("Change medium"),
		N("Please insert the medium named \"%s\" on device [%s]", $_[0], $_[1]),
		yesno => 1, text => { no => N("Cancel"), yes => N("Ok") },
	    );
	},
	callback => sub {
	    my ($mode, $file, $percent) = @_;
	    if ($mode eq 'start') {
		gurpm::label(N("Downloading package `%s' (%s/%s)...",
			basename($file), ++$distant_progress, $distant_number));
		gurpm::validate_cancel(but(N("Cancel")), sub { $canceled = 1 });
	    } elsif ($mode eq 'progress') {
		gurpm::progress($percent/100);
	    } elsif ($mode eq 'end') {
		gurpm::progress(1);
		gurpm::invalidate_cancel();
	    }
	    $canceled and return 'canceled';
	},
	limit_rate => $urpm->{options}{'limit-rate'},
	compress => $urpm->{options}{compress},
	resume => $urpm->{options}{resume},
    );
    $canceled and goto return_with_error;
    gurpm::invalidate_cancel_forever();

    my %sources_install = %{$urpm->extract_packages_to_install(\%sources) || {}};
    my @rpms_install = grep { !/\.src\.rpm$/ } values %sources_install;
    my @rpms_upgrade = grep { !/\.src\.rpm$/ } values %sources;

    if (!$options{'no-verify-rpm'}) {
        gurpm::label(N("Verifying package signatures..."));
        my $total = @rpms_install + @rpms_upgrade;
        my $progress;
	my @invalid_sources = $urpm->check_sources_signatures(
	    \%sources_install, \%sources,
	    translate => 1, basename => 1,
	    callback => sub {
		gurpm::progress(++$progress/$total);
	    },
	);
        if (@invalid_sources) {
            interactive_msg_(
		N("Rpmdrake"),
		N("The following packages have bad signatures:\n\n%s\n\nDo you want to continue installation?",
		to_utf8(join "\n", sort @invalid_sources)), yesno => 1, if_(@invalid_sources > 10, scroll => 1),
	    ) or goto return_with_error;
        }
    }

    if (@rpms_install || @rpms_upgrade) {
        if (my @missing = grep { m|^/| && ! -e $_ } @rpms_install, @rpms_upgrade) {
            interactive_msg_(
		N("Installation failed"),
		N("Installation failed, some files are missing:\n%s\n\nYou may want to update your media database.",
		    join "\n", map { "    $_" } @missing) .
		    (@error_msgs ? N("\n\nError(s) reported:\n%s", join("\n", @error_msgs)) : ''),
		if_(@error_msgs > 1, scroll => 1),
	    );
            goto return_with_error;
        }
        my $progress_nb;
        my $total_nb = scalar grep { m|^/| } @rpms_install, @rpms_upgrade;
        my $something_installed;
        my $callback_inst = sub {
            my ($urpm, $type, $id, $subtype, $amount, $total) = @_;
            my $pkg = defined $id && $urpm->{depslist}[$id];
            if ($subtype eq 'start') {
                if ($type eq 'trans') {
                    gurpm::label(N("Preparing packages installation..."));
                } else {
                    $something_installed = 1;
                    gurpm::label(N("Installing package `%s' (%s/%s)...", $pkg->name, ++$progress_nb, $total_nb));
                }
            } elsif ($subtype eq 'progress') {
                gurpm::progress($total ? $amount/$total : 1);
            }
        };
	my $fh;
        my @errors = $urpm->install(
	    $urpm->{ask_remove},
	    \%sources_install,
	    \%sources,
	    translate_message => 1,
	    post_clean_cache => 1,
	    callback_open => sub {
		my ($data, $type, $id) = @_;
		my $f = $sources_install{$id} || $sources{$id};
		open $fh, $f or $urpm->{error}(N("unable to access rpm file [%s]", $f));
		return fileno $fh;
	    },
	    callback_inst => $callback_inst,
	    callback_trans => $callback_inst,
	    callback_close => sub {
		my ($urpm, undef, $pkgid) = @_;
		return unless defined $pkgid;
		return if $MODE ne 'install' && $MODE ne 'update';
		my $pkg = $urpm->{depslist}[$pkgid];
		my $fullname = $pkg->fullname;
		my $trtype = (any { /$fullname/ } values %sources_install) ? 'install' : '(update|upgrade)';
		push @Readmes, map { [ $_, $fullname ] } grep { /\bREADME(\.$trtype)?\.urpmi$/ } $pkg->files;
		close $fh;
	    },
	);
        gurpm::end();
        $urpm->try_umounting_removables;

        if (@errors || @error_msgs) {
            interactive_msg_(
		N("Problem during installation"),
		N("There was a problem during the installation:\n\n%s",
		    join("\n", @errors, @error_msgs)),
		if_(@errors + @error_msgs > 1, scroll => 1),
	    );
            $w->{rwindow}->set_sensitive(1);
            return !$something_installed;
        }

        my %pkg2rpmnew;
        foreach my $u (@rpms_upgrade) {
            $u =~ m|/([^/]+-[^-]+-[^-]+)\.[^\./]+\.rpm$|
              and $pkg2rpmnew{$1} = [ grep { m|^/etc| && (-r "$_.rpmnew" || -r "$_.rpmsave") }
                                      map { chomp_($_) } `rpm -ql $1` ];
        }
        dialog_rpmnew(N("The installation is finished; %s.\n\nSome configuration files were created as `.rpmnew' or `.rpmsave',\nyou may now inspect some in order to take actions:", N("everything was installed correctly")),
                      %pkg2rpmnew)
          and $statusbar_msg_id = statusbar_msg(#N("Everything installed successfully"),
                               N("All requested packages were installed successfully."));
	if (@Readmes) { 
	    interactive_packtable(
		N("Information on packages"),
		$w->{rwindow},
		N("These packages come with upgrade information"),
		[ map {
		    my $pkg = $_;
		    [ gtkpack__(
			    Gtk2::HBox->new(0, 0),
			    gtkset_selectable(Gtk2::Label->new($pkg->[1]),1),
			),
			gtksignal_connect(
			    
			    Gtk2::Button->new(N("More information on package...")),
			    clicked => sub {
				interactive_msg(
				    N("More information on package... [%s]", $pkg->[0]),
				    (join '' => cat_($pkg->[0])),
				    scroll => 1,
				);
			    },
			),
		    ] } @Readmes ],
		[ gtksignal_connect(Gtk2::Button->new(N("Ok")), clicked => sub { Gtk2->main_quit }) ]
	    );
	}
    } else {
        gurpm::end();
        $urpm->try_umounting_removables;
        interactive_msg_(N("No package found for installation."),
                         N("Unrecoverable error: no package found for installation, sorry."));
    }

    $w->{rwindow}->set_sensitive(1);
    statusbar_msg_remove($statusbar_msg_id); 
    return 0;

  fatal_error:
    gurpm::end();
    interactive_msg_(N("Installation failed"),
                     N("There was a problem during the installation:\n\n%s", $fatal_msg));
  return_with_error:
    gurpm::end();
    $w->{rwindow}->set_sensitive(1);
    return 1;
}


# -=-=-=---=-=-=---=-=-=-- remove packages -=-=-=---=-=-=---=-=-=-

sub get_installed_pkgs {
    use URPM;

    my $wait = wait_msg_with_banner(N("Please wait, reading packages database..."));
    gtkflush();
    my @base = qw(basesystem);
    my (%base, %basepackages);
    my $db = db();
    my $sig_handler = sub { undef $db; exit 3 };
    local $SIG{INT} = $sig_handler;
    local $SIG{QUIT} = $sig_handler;
    while (defined(local $_ = shift @base)) {
	exists $basepackages{$_} and next;
	$db->traverse_tag(m|^/| ? 'path' : 'whatprovides', [ $_ ], sub {
			      push @{$basepackages{$_}}, my_fullname($_[0]);
			      push @base, $_[0]->requires_nosense;
			  });
    }
    foreach (values %basepackages) {
	my $n = @$_;
	foreach (@$_) {
	    $base{$_} = \$n;
	}
    }
    my %installed_pkgs;
    $db->traverse(sub {
	    my ($pkg) = @_;
	    my $fullname = my_fullname($pkg);
	    if (!$base{$fullname} || ${$base{$fullname}} != 1) {
		
		$installed_pkgs{$fullname} = {
		    selected => 0, pkg => $pkg, urpm_name => urpm_name($pkg),
		    summary => rpm_summary($pkg->summary),
		    description => rpm_description($pkg->description),
		} unless $installed_pkgs{$fullname} && $installed_pkgs{$fullname}{description};
		$base{$fullname} and $installed_pkgs{$fullname}{base} = \${$base{$fullname}};
	    }
	    $pkg->pack_header;
	});
    statusbar_msg_remove($wait);
    my $urpm = urpm->new;
    my $group;
    if ($options{parallel} && (($group) = @{$options{parallel}})) {
        $urpm->configure(parallel => $group);
    }
    ($urpm, \%installed_pkgs);
}

sub perform_removal {
    my ($urpm, $pkgs) = @_;
    my @toremove = map { if_($pkgs->{$_}{selected}, $pkgs->{$_}{urpm_name}) } keys %$pkgs;
    standalone::explanations("Removing package $_") foreach sort @toremove;
    my @results;
    slow_func_statusbar(
	N("Please wait, removing packages..."),
	$w->{rwindow},
	sub {
	    @results = $options{parallel}
		? $urpm->parallel_remove(\@toremove, translate_message => 1)
		: $urpm->install(\@toremove, {}, {}, translate_message => 1);
	    db('force_sync');
	},
    );
    if (@results) {
	interactive_msg_(
	    N("Problem during removal"),
	    N("There was a problem during the removal of packages:\n\n%s", join("\n",  @results)),
	    if_(@results > 1, scroll => 1),
	);
	return 1;
    } else {
	return 0;
    }
}


# -=-=-=---=-=-=---=-=-=-- main -=-=-=---=-=-=---=-=-=-

if ($options{'merge-all-rpmnew'}) {
    my %pkg2rpmnew;
    print "Searching .rpmnew and .rpmsave files...\n";
    db->traverse(sub {
		     my $n = my_fullname($_[0]);
		     $pkg2rpmnew{$n} = [ grep { m|^/etc| && (-r "$_.rpmnew" || -r "$_.rpmsave") } map { chomp_($_) } $_[0]->files ];
		 });
    print "done.\n";
    $typical_width = 280;
    dialog_rpmnew('', %pkg2rpmnew) and print "Nothing to do.\n";
    myexit(0);
}

readconf();
$changelog_first = $changelog_first_config->[0];
$changelog_first = 1 if $options{'changelog-first'};

if (!$> && !member($MODE, @$already_splashed)) {
    interactive_msg(N("Rpmdrake"),
N("%s

Is it ok to continue?",
        $MODE eq 'remove' ?
  N("Welcome to the software removal tool!

This tool will help you choose which software you want to remove from
your computer.")
      : $MODE eq 'update' ?
  N("Welcome to %s!

This tool will help you choose the updates you want to install on your
computer.", $rpmdrake::myname_update)
      :
  ($rpmdrake::branded ? N("Welcome to the software installation tool!")
      : N("Welcome to the software installation tool!

Your Mandriva Linux system comes with several thousands of software
packages on CDROM or DVD. This tool will help you choose which software
you want to install on your computer.")))
  , yesno => 1) or myexit(-1);
	push @$already_splashed, $MODE;
    }

if ($MODE eq 'remove') {
    run_treeview_dialog(sub { get_installed_pkgs() }, \&perform_removal);
} elsif ($MODE eq 'update') {
    run_treeview_dialog(sub { get_installable_pkgs(1, @_) }, \&perform_installation);
} else {
    run_treeview_dialog(sub { get_installable_pkgs() }, \&perform_installation);
}

writeconf();

myexit(0);
