aboutsummaryrefslogtreecommitdiffstats
path: root/rpmdrake
blob: c3ae8e5df7775d263182980e6a584808ea6dffe7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
#!/usr/bin/perl
#*****************************************************************************
#
#  Copyright (c) 2002 Guillaume Cottenceau
#  Copyright (c) 2003-2005 Mandriva Linux
#
#  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$

use strict;
use MDK::Common 'any';
use lib qw(/usr/lib/libDrakX);
use common;
use POSIX qw(_exit);
use URPM;

BEGIN {  #- we want to run this code before the Gtk->init of the use-my_gtk
    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;
    };
}

BEGIN { #- for mcc
    if ("@ARGV" =~ /--embedded (\w+)/) {
	$::XID = $1;
	$::isEmbedded = 1;
    }
}

use rpmdrake;

#- This is needed because text printed by Gtk2 will always be encoded
#- in UTF-8; we first check if LC_ALL is defined, because if it is,
#- changing only LC_COLLATE will have no effect.
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";
    _exit(0);  #- skip ugtk2::END
}

$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);  #- hackish :-(
    $mainw->flush;
}

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

sub end {
    $mainw and $mainw->destroy;
    $mainw = undef;
    $cancel = undef;  #- in case we'll do another one later
}

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;

#- /usr/share/rpmlint/TagsCheck.py (duplicates are normal, so that we are not too far away from .py)
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"),
    );
}

#- to highlight information
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) = @_;
    utf8::decode($summary);
    $summary;
}

sub rpm_description {
    my ($description) = @_;
    utf8::decode($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;
}

#- strftime returns a string in the locale charset encoding;
#- but gtk2 requires UTF-8, so we use to_utf8() to ensure the
#- output of localtime2changelog() is always in UTF-8
#- as to_utf8() uses LC_CTYPE for locale encoding and strftime() uses LC_TIME,
#- it doesn't work if those two variables have values with different
#- encodings; but if a user has a so broken setup we can't do much anyway
sub localtime2changelog { to_utf8(strftime("%c", localtime($_[0]))) }

sub extract_header {
    my ($pkg, $urpm) = @_;
    my $chg_prepro = sub {
	#- preprocess changelog for faster TextView insert reaction
	[ 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) {
	    my $packer;
	    # TODO use more modern API
	    eval { require packdrake; $packer = new packdrake($hdlist, quiet => 1) }
		or do {
		    warn "Warning, hdlist seems corrupted\n";
		    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 do {
		warn "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); #- there can be multiple packages with same version/release for different arch's
	    $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)");
}

#- remove architecture
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' : $pkgs->{$_[0]}{pkg}->flag_base ? '/usr/share/rpmdrake/icons/base.png' : 'unselected') : 'XXX';
	},  #- checks $_[0] -> hack for partial tree displaying
	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 { no locale; 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 {
		    #- special case, we don't populate all the tree at first (to speed things up)
		    %elems = ();
		    foreach my $root (sort { $a cmp $b } uniq(map { (split /\|/, $_->[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;
	    #- avoid selecting too many packages at once
	    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
		    #-PO: Keep it short, this is gonna be on a button
		    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) {
			#- unselect i18n packages of which locales is not already present (happens when user clicks on KDE group)
			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) {
		#- some deps may exist on some packages which aren't listed because
		#- not upgradable (older than what currently installed)
		exists $pkgs->{$_} or next;
		$pkgs->{$_}{pkg} or $new_state = 0; #- can't be removed
		$set_state->($_, $new_state ? 'selected' : 'unselected');
		$pkgs->{$_}{selected} = $new_state;
		$pkgs->{$_}{pkg}
		    and $size_selected += $pkgs->{$_}{pkg}->size * ($new_state ? 1 : -1);
	    }
	}, #- toggle_nodes
	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 ''; #- related to the partial tree displaying hackery
	    #- the package information hasn't been loaded. Instead of rescanning the media, just give up.
	    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;  #- try to not being crazy with a too large value
    $typical_width < 150 and $typical_width = 150;
    #- XXX : work around bug in gtk2 that clobbers display (see bugzilla #16575)
    #$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) = @_;
	    #- hackish: if first child has '' as name, and if we're not listing by update
	    # 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) {
		    #- populating large groups is slow
		    $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);  #- workaround when right elevator of scrolled window appears

    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 };  #- hack to simulate a medium for parsing of descriptions
	    }
	}

	my ($cur, $section);
	#- parse the description file
	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(),
	{}, #- $state,
	$requested,
	start => 0,
	end   => $#{$urpm->{depslist}},
    );
    $urpm->{depslist}[$_]->set_flag_installed foreach keys %$requested; #- pretend it's installed

    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 {  #- (partially) duplicated from /usr/sbin/urpmi :-(
    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;
    }

    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)';
		for ($pkg->files) { /\bREADME(\.$trtype)?\.urpmi$/ and $Readmes{$_} = $fullname }
		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; everything was installed correctly.

Some configuration files were created as `.rpmnew' or `.rpmsave',
you may now inspect some in order to take actions:"),
	    %pkg2rpmnew)
	    and $statusbar_msg_id = statusbar_msg(N("All requested packages were installed successfully."));
	if (keys %Readmes) { #- display the README*.urpmi files
	    interactive_packtable(
		N("Information on packages"),
		$w->{rwindow},
		N("These packages come with upgrade information"),
		[ map {
		    my $fullname = $_;
		    [ gtkpack__(
			    Gtk2::HBox->new(0, 0),
			    gtkset_selectable(Gtk2::Label->new($Readmes{$fullname}),1),
			),
			gtksignal_connect(
			    #- TODO change those labels to something more sensible, e.g. "Upgrade information about this package"
			    Gtk2::Button->new(N("More information on package...")),
			    clicked => sub {
				interactive_msg(
				    N("More information on package... [%s]", $fullname),
				    (join '' => cat_($fullname)),
				    scroll => 1,
				);
			    },
			),
		    ] } keys %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); #- XXX maybe remove this
    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 {
    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 = @$_; #- count number of times it's provided
	foreach (@$_) {
	    $base{$_} = \$n;
	}
    }
    my %installed_pkgs;
    $db->traverse(sub {
	    my ($pkg) = @_;
	    my $fullname = my_fullname($pkg);
	    #- I need to extract summary and description since they'll be lost when $pkg->pack_header
	    $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}};
	    if ($base{$fullname} && ${$base{$fullname}} == 1) { $pkg->set_flag_base(1) }
	    $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;
    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);