summaryrefslogtreecommitdiff
path: root/portato/gui/windows/main.py
blob: 472ddf0552a8cc359aec45d34d7ee388aa90bfd3 (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
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
# -*- coding: utf-8 -*-
#
# File: portato/gui/windows/main.py
# This file is part of the Portato-Project, a graphical portage-frontend.
#
# Copyright (C) 2006-2009 René 'Necoro' Neumann
# This is free software.  You may redistribute copies of it under the terms of
# the GNU General Public License version 2.
# There is NO WARRANTY, to the extent permitted by law.
#
# Written by René 'Necoro' Neumann <necoro@necoro.net>

from __future__ import absolute_import, with_statement

# gtk stuff
import gtk
import gobject

# other
import os.path
import itertools as itt
from collections import defaultdict

# our backend stuff
from ...backend import flags, system # must be the first to avoid circular deps
from ... import get_listener, plugin
from ...helper import debug, warning, error, info, unique_array
from ...session import Session
from ...db import Database
from ...constants import CONFIG_LOCATION, VERSION, APP_ICON, ICON_DIR
from ...backend.exceptions import PackageNotFoundException, BlockedException, VersionsNotFoundException

# more GUI stuff
from ..utils import Config, GtkThread, get_color
from ..queue import EmergeQueue
from ..session import SESSION_VERSION, SessionException, OldSessionException, NewSessionException
from ..wrapper import GtkTree, GtkConsole
from ..views import LogView, HighlightView, InstalledOnlyView, LazyStoreView
from ..dialogs import (blocked_dialog, changed_flags_dialog, io_ex_dialog,
        nothing_found_dialog, queue_not_empty_dialog, remove_deps_dialog,
        remove_queue_dialog, remove_updates_dialog, unmask_dialog,
        no_versions_dialog)
from ..exceptions import PreReqError

# even more GUI stuff
from .basic import Window, Popup
from .about import AboutWindow
from .plugin import PluginWindow
from .preference import PreferenceWindow
from .search import SearchWindow
from .update import UpdateWindow

class PackageTable:
    """A window with data about a specfic package."""

    def __init__ (self, main):
        """Build up window contents.
        
        @param main: the main window
        @type main: MainWindow"""

        self.main = main
        self.tree = main.tree
        self.window = main.window
        self.tree.signal_autoconnect(self)
        
        # all the package data is in this one VB
        self.vb = self.tree.get_widget("packageVB")

        # the notebook
        self.notebook = self.tree.get_widget("packageNotebook")
        
        # chechboxes
        self.installedCheck = self.tree.get_widget("installedCheck")
        self.maskedCheck = self.tree.get_widget("maskedCheck")
        self.testingCheck = self.tree.get_widget("testingCheck")
        self.maskedLabel = self.tree.get_widget("maskedLabel")

        # labels
        generalVB = self.tree.get_widget("generalVB")
        generalVB.modify_bg(gtk.STATE_NORMAL, get_color(self.main.cfg, "packagetable"))
        
        self.nameLabel = self.tree.get_widget("nameLabel")
        self.descLabel = self.tree.get_widget("descLabel")
        self.overlayLabel = self.tree.get_widget("overlayLabel")
        self.overlayLL = self.tree.get_widget("overlayLabelLabel")
        self.licenseLabel = self.tree.get_widget("licenseLabel")
        self.linkBox = self.tree.get_widget("linkBox")
        self.notInSysLabel = self.tree.get_widget("notInSysLabel")
        self.missingLabel = self.tree.get_widget("missingLabel")
        self.useFlagsLabel = self.tree.get_widget("useFlagsLabel")
        self.useFlagsLL = self.tree.get_widget("useFlagsLabelLabel")
        
        # buttons
        self.emergeBtn = self.tree.get_widget("pkgEmergeBtn")
        self.unmergeBtn = self.tree.get_widget("pkgUnmergeBtn")
        self.revertBtn = self.tree.get_widget("pkgRevertBtn")
        
        # views
        self.views = map (lambda x: self.tree.get_widget(x).get_child(),
                [
                    "ebuildScroll", "changelogScroll", "filesScroll",
                    "dependencyScroll", "useListScroll"
                ])

        self.useList = self.tree.get_widget("useListScroll").get_child()


    def update (self, pkg, queue = None, doEmerge = True, instantChange = False, type = None):
        """Updates the table to show the contents for the package.
        
        @param pkg: the selected package
        @type pkg: Package
        @param queue: emerge-queue (if None the emerge-buttons are disabled)
        @type queue: EmergeQueue
        @param doEmerge: if False, the emerge buttons are disabled
        @type doEmerge: boolean
        @param instantChange: if True the changed keywords are updated instantly
        @type instantChange: boolean
        @param type: the type of the queue this package is in; if None there is no queue :)
        @type type: string"""
        
        self.pkg = pkg
        self.queue = queue
        self.doEmerge = doEmerge
        self.instantChange = instantChange
        self.type = type

        if not self.queue or not self.doEmerge:
            self.emergeBtn.set_sensitive(False)
            self.unmergeBtn.set_sensitive(False)
        
        # current status
        self._update_table()
        self.vb.show_all()

    def hide (self):
        self.vb.hide_all()

    def set_labels (self):
        pkg = self.pkg
        
        # name
        self.nameLabel.set_markup("<b>%s</b>" % pkg.get_cpv())
        
        # description
        desc = pkg.get_package_settings("DESCRIPTION") or _("<no description>")
        self.descLabel.set_label(desc)

        # overlay
        if pkg.is_in_overlay():
            self.overlayLabel.set_label(pkg.get_overlay_path())
            self.overlayLabel.show()
            self.overlayLL.show()
        else:
            self.overlayLabel.hide()
            self.overlayLL.hide()

        # license
        self.licenseLabel.set_label(pkg.get_package_settings("LICENSE"))

        # link
        for c in self.linkBox.get_children():
            self.linkBox.remove(c)
        
        text = pkg.get_package_settings("HOMEPAGE")
        texts = text.split(" ")
        ftexts = []

        for count, t in enumerate(texts):
            if not t.startswith(("http", "ftp")):
                if count == 0:
                    error(_("The first homepage part does not start with 'http' or 'ftp'."))
                    ftexts.append(t)
                    continue
                else:
                    info(_("Blank inside homepage."))
                    ftexts[-1] += " %s" % t
            else:
                ftexts.append(t)

        for t in ftexts:
            link = gtk.LinkButton(t)
            link.set_alignment(0.0, 0.5)
            link.set_border_width(0)
            self.linkBox.add(link)

        # useflags
        flaglist = list(itt.ifilterfalse(pkg.use_expanded, pkg.get_iuse_flags()))
        flaglist.sort()
        flags = ", ".join(flaglist)

        if flags:
            self.useFlagsLL.show()
            self.useFlagsLabel.show()
            self.useFlagsLabel.set_label(flags)
        else:
            self.useFlagsLL.hide()
            self.useFlagsLabel.hide()

    def _update_keywords (self, emerge, update = False):
        if emerge:
            type = "install" if not self.type else self.type
            try:
                try:
                    self.queue.append(self.pkg.get_cpv(), type = type, update = update)
                except PackageNotFoundException, e:
                    if unmask_dialog(e[0]) == gtk.RESPONSE_YES:
                        self.queue.append(self.pkg.get_cpv(), type = type, unmask = True, update = update)
            except BlockedException, e:
                blocked_dialog(e[0], e[1])
        else:
            try:
                self.queue.append(self.pkg.get_cpv(), type = "uninstall")
            except PackageNotFoundException, e:
                error(_("Package could not be found: %s"), e[0])
                #masked_dialog(e[0])

    def _update_table (self, *args):

        pkg = self.pkg

        # set the views
        nb_page = self.notebook.get_nth_page(self.notebook.get_current_page())
        for v in self.views:
            v.update(pkg, force = nb_page == v.get_parent())

        # set the labels
        self.set_labels()

        #
        # rebuild the buttons and checkboxes in all the different manners which are possible
        #
        if (not pkg.is_in_system()) or pkg.is_missing_keyword():
            if not pkg.is_in_system():
                self.missingLabel.hide()
                self.notInSysLabel.show()
            else: # missing keyword
                self.missingLabel.show()
                self.notInSysLabel.hide()
#            
            self.installedCheck.hide()
            self.maskedCheck.hide()
            self.maskedLabel.hide()
            self.testingCheck.hide()
            self.emergeBtn.set_sensitive(False)
        else: # normal package
            self.missingLabel.hide()
            self.notInSysLabel.hide()
            self.installedCheck.show()
            self.maskedCheck.show()
            self.maskedLabel.show()
            self.testingCheck.show()
            if self.doEmerge:
                self.emergeBtn.set_sensitive(True)
            self.installedCheck.set_active(pkg.is_installed())
            
            reason = pkg.get_masking_reason() or " "
            if pkg.is_masked(use_changed = False) and not pkg.is_masked(use_changed = True):
                self.maskedCheck.set_label("<i>(%s)</i>" % _("Masked"))
                self.maskedCheck.get_child().set_use_markup(True)
            else:
                self.maskedCheck.set_label(_("Masked"))
            
            if pkg.is_locally_masked():
                self.maskedCheck.set_label("<b>%s</b>" % _("Masked"))
                self.maskedCheck.get_child().set_use_markup(True)
                self.maskedCheck.set_active(True)
                reason = _("Masked by user")
            else:
                self.maskedCheck.set_active(pkg.is_masked(use_changed = False))
            
            if reason:
                self.maskedLabel.set_label(reason)
            
            if pkg.is_testing(use_keywords = False) and not pkg.is_testing(use_keywords = True):
                self.testingCheck.set_label("<i>(%s)</i>" % _("Testing"))
                self.testingCheck.get_child().set_use_markup(True)
            else:
                self.testingCheck.set_label(_("Testing"))
            
            self.testingCheck.set_active(pkg.is_testing(use_keywords = False))

        if self.doEmerge:
            # set emerge-button-label
            if not pkg.is_installed():
                self.unmergeBtn.set_sensitive(False)
            else:
                self.unmergeBtn.set_sensitive(True)
        
        self.vb.show_all()
        return True

    def cb_button_pressed (self, b, event):
        """Callback for pressed checkboxes. Just quits the event-loop - no redrawing."""
        if not isinstance(b, gtk.CellRendererToggle):
            b.emit_stop_by_name("button-press-event")
        return True

    def cb_package_revert_clicked (self, button):
        """Callback for pressed revert-button."""
        self.pkg.remove_new_use_flags()
        self.pkg.remove_new_masked()
        self.pkg.remove_new_testing()
        self._update_table()
        if self.instantChange:
            self._update_keywords(True, update = True)
        return True

    def cb_package_emerge_clicked (self, button):
        """Callback for pressed emerge-button. Adds the package to the EmergeQueue."""
        self._update_keywords(True)
        self.main.sysNotebook.set_current_page(self.main.QUEUE_PAGE)
        return True

    def cb_package_unmerge_clicked (self, button):
        """Callback for pressed unmerge-button clicked. Adds the package to the UnmergeQueue."""
        self._update_keywords(False)
        self.main.sysNotebook.set_current_page(self.main.QUEUE_PAGE)
        return True

    def cb_testing_toggled (self, button):
        """Callback for toggled testing-checkbox."""
        status = button.get_active()

        # end of recursion :)
        if self.pkg.is_testing(use_keywords = False) == status:
            return False

        # if the package is not testing - don't allow to set it as such
        if not self.pkg.is_testing(use_keywords = False):
            button.set_active(False)
            return True

        # re-set to testing status
        if not self.pkg.is_testing(use_keywords = True):
            self.pkg.set_testing(False)
            button.set_label(_("Testing"))
            button.set_active(True)
        else: # disable testing
            self.pkg.set_testing(True)
            button.set_label("<i>(%s)</i>" % _("Testing"))
            button.get_child().set_use_markup(True)
            button.set_active(True)

        if self.instantChange:
            self._update_keywords(True, update = True)
        
        return True

    def cb_masked_toggled (self, button):
        """Callback for toggled masking-checkbox."""
        status = button.get_active()
        pkg = self.pkg

        if pkg.is_masked(use_changed = False) == status and not pkg.is_locally_masked():
            return False

        if pkg.is_locally_masked() and status:
            return False
    
        if not pkg.is_masked(use_changed = True):
            pkg.set_masked(True)
            if pkg.is_locally_masked():
                button.set_label("<b>%s</b>" % _("Masked"))
                button.get_child().set_use_markup(True)
                self.maskedLabel.set_label(_("Masked by user"))
            else:
                button.set_label(_("Masked"))

            button.set_active(True)
        else:
            locally = pkg.is_locally_masked()
            pkg.set_masked(False)
            if pkg.is_masked(use_changed=False) and not locally:
                button.set_label("<i>(%s)</i>" % _("Masked"))
                button.get_child().set_use_markup(True)
                button.set_active(True)
            else:
                button.set_label(_("Masked"))
                self.maskedLabel.set_label("")
        
        if self.instantChange:
            self._update_keywords(True, update = True)
        
        return True

    def cb_use_flag_toggled (self, cell, path):
        """Callback for a toggled use-flag button."""

        store = self.useList.get_model()

        flag = store[path][2]
        pkg = self.pkg
        
        if pkg.use_expanded(flag): # ignore expanded flags
            return False

        store[path][0] = not store[path][0]
        prefix = ""
        if not store[path][0]:
            prefix = "-"
        
        pkg.set_use_flag(prefix+flag)
        if self.instantChange:
            self._update_keywords(True, update = True)
    
        return True

class MainWindow (Window):
    """
    Application main window.
    """

    # NOTEBOOK PAGE CONSTANTS
    (
            QUEUE_PAGE,
            CONSOLE_PAGE,
            LOG_PAGE
    ) = range(3)

    def __init__ (self, splash = None):
        """
        Build up window.

        @param splash: the splash screen =)
        @type splash: SplashScreen
        """

        self.check_prereqs()

        if splash is None:
            splash = lambda x: True
        
        # the title
        self.main_title = "Portato (%s)" % VERSION

        # main window stuff
        Window.__init__(self)
        self.window.set_title(self.main_title)
        self.window.set_geometry_hints (self.window, max_height = gtk.gdk.screen_height(), max_width = gtk.gdk.screen_width())
        
        # booleans
        self.doUpdate = False
        self.showAll = True # show only installed or all packages?
        self.__searchChanged = False

        # icons
        self.icons = {}
        self.icons["use"] = self.window.render_icon(gtk.STOCK_REMOVE, gtk.ICON_SIZE_MENU)
        self.icons["installed"] = self.window.render_icon(gtk.STOCK_YES, gtk.ICON_SIZE_MENU)
        self.icons["or"] = self.window.render_icon(gtk.STOCK_MEDIA_PAUSE, gtk.ICON_SIZE_MENU)
        self.icons["block"] = self.window.render_icon(gtk.STOCK_NO, gtk.ICON_SIZE_MENU)
        
        # get the logging window as soon as possible
        self.logView = LogView(self.tree.get_widget("logView"))
        
        # config
        splash(_("Loading Config"))
        try:
            self.cfg = Config(CONFIG_LOCATION)
        except IOError, e:
            io_ex_dialog(e)
            raise

        self.cfg.modify_external_configs()
        self.set_uri_hook(self.cfg.get("browserCmd", section = "GUI"))
        gtk.about_dialog_set_url_hook(lambda *args: True) # dummy - if not set link is not set as link; if link is clicked the normal uuri_hook is called too - thus do not call browser here

        # package db
        splash(_("Creating Database"))
        self.db = Database()
        
        # set plugins and plugin-menu
        splash(_("Loading Plugins"))

        plugin.load_plugins()
        menus = [p.menus for p in plugin.get_plugin_queue().get_plugins()]
        if menus:
            self.tree.get_widget("pluginMenuItem").set_no_show_all(False)
            pluginMenu = self.tree.get_widget("pluginMenu")

            for m in itt.chain(*menus):
                item = gtk.MenuItem(m.label)
                item.connect("activate", m.call)
                pluginMenu.append(item)

        splash(_("Building frontend"))
        # set paned position
        self.vpaned = self.tree.get_widget("vpaned")
        self.vpaned.set_position(int(self.window.get_size()[1]/2))
        self.hpaned = self.tree.get_widget("hpaned")
        self.hpaned.set_position(int(self.window.get_size()[0]/1.5))

        # lists
        self.selCatName = ""
        self.selCP = ""
        self.selCPV = ""
        self.sortPkgListByName = True
        self.catList = self.tree.get_widget("catList")
        self.pkgList = self.tree.get_widget("pkgList")
        self.versionList = self.tree.get_widget("versionList")
        self.build_cat_list()
        self.build_pkg_list()
        self.build_version_list()

        # search entry
        self.searchEntry = self.tree.get_widget("searchEntry")

        # queue list
        self.queueOneshot = self.tree.get_widget("oneshotCB")
        self.queueOneshotHandler = self.queueOneshot.connect("toggled", self.cb_oneshot_clicked)
        self.queueList = self.tree.get_widget("queueList")
        self.build_queue_list()

        # the terminal
        self.console = GtkConsole()
        self.termHB = self.tree.get_widget("termHB")
        self.build_terminal()
        
        # notebooks
        self.sysNotebook = self.tree.get_widget("systemNotebook")
        self.pkgNotebook = self.tree.get_widget("packageNotebook")
        self.set_notebook_tabpos(map(PreferenceWindow.tabpos.get, map(int, (self.cfg.get("packageTabPos", "GUI"), self.cfg.get("systemTabPos", "GUI")))))
        
        # the different scrolls
        ebuildScroll = self.tree.get_widget("ebuildScroll")
        ebuildScroll.add(HighlightView(lambda p: p.get_ebuild_path(), ["gentoo", "sh"]))

        changelogScroll = self.tree.get_widget("changelogScroll")
        changelogScroll.add(HighlightView(lambda p: os.path.join(p.get_package_path(), "ChangeLog"), ["changelog"]))

        def show_files (p):
            try:
                for f in p.get_files():
                    yield " %s\n" % f
            except IOError, e:
                yield _("Error: %s") % e.strerror

        filesScroll = self.tree.get_widget("filesScroll")
        filesScroll.add(InstalledOnlyView(show_files))

        depScroll = self.tree.get_widget("dependencyScroll")
        depScroll.add(self.build_dep_list())
        
        useScroll = self.tree.get_widget("useListScroll")
        useScroll.add(self.build_use_list())
        
        # table
        self.packageTable = PackageTable(self)

        # popups
        self.consolePopup = Popup("consolePopup", self, self.__file__)
        self.trayPopup = Popup("systrayPopup", self)

        # pause menu items
        self.emergePaused = False
        self.pauseItems = {}
        self.pauseItems["tray"] = self.trayPopup.tree.get_widget("pauseItemTray")
        self.pauseItems["popup"] = self.consolePopup.tree.get_widget("pauseItemPopup")
        self.pauseItems["menu"] = self.tree.get_widget("pauseItemMenu")

        for k,v in self.pauseItems.iteritems():
            self.pauseItems[k] = (v, v.connect_after("activate", self.cb_pause_emerge(k)))

        # systray
        if self.cfg.get_boolean("showSystray", "GUI"):
            self.tray = gtk.status_icon_new_from_file(APP_ICON)
            self.tray.connect("activate", self.cb_systray_activated)
            self.tray.connect("popup-menu", lambda icon, btn, time: self.trayPopup.popup(None, None, None, btn, time))
        else:
            self.tray = None

        # set emerge queue
        self.queueTree = GtkTree(self.queueList.get_model())
        self.queue = EmergeQueue(console = self.console, tree = self.queueTree, db = self.db, title_update = self.title_update, threadClass = GtkThread)
        
        # session
        splash(_("Restoring Session"))
        try:
            try:
                self.load_session()
            except OldSessionException, e:
                self.load_session(e)
        except SessionException, e:
            warning(str(e))
            self.load_session(defaults_only = True) # last ressort
        
        splash(_("Finishing startup"))
        
        self.window.show_all()
    
    def show_package (self, pkg = None, cpv = None, cp = None, version = None, **kwargs):
        p = None

        if pkg:
            p = pkg
        elif cpv:
            p = system.find_packages("="+cpv, masked = True)[0]
        elif cp:
            if version:
                p = system.find_packages("=%s-%s" % (cp, version), masked = True)[0]
            
            else:
                best = system.find_best_match(cp)
                if best:
                    p = best
                else:
                    p = system.find_packages(cp)[0]
        
        self.packageTable.update(p, **kwargs)

    def build_terminal (self):
        """
        Builds the terminal.
        """
        
        self.console.set_scrollback_lines(int(self.cfg.get("scrollbacklines", "GUI")))
        self.console.set_scroll_on_output(True)
        self.console.set_font_from_string(self.cfg.get("consolefont", "GUI"))
        self.console.connect("button-press-event", self.cb_right_click)
        self.termHB.pack_start(self.console, True, True)
        
        # add scrollbar
        termScroll = gtk.VScrollbar(self.console.get_adjustment())
        self.termHB.pack_start(termScroll, False)

    def build_queue_list (self):
        """
        Builds the queue list.
        """

        store = gtk.TreeStore(str,str,bool)
        
        self.queueList.set_model(store)
        
        cell = gtk.CellRendererText()
        col = gtk.TreeViewColumn(_("Queue"), cell, markup = 0)
        self.queueList.append_column(col)
        
        col = gtk.TreeViewColumn(_("Options"), cell, markup = 1)
        self.queueList.append_column(col)

        self.queueList.get_selection().connect("changed", self.cb_queue_list_selection)

    def build_cat_list (self):
        """
        Builds the category list.
        """
        
        store = gtk.TreeStore(str)

        self.fill_cat_store(store)

        self.catList.set_model(store)
        cell = gtk.CellRendererText()
        col = gtk.TreeViewColumn(_("Categories"), cell, text = 0)
        self.catList.append_column(col)

        self.catList.get_selection().connect("changed", self.cb_cat_list_selection)

    def fill_cat_store (self, store = None):
        """
        Fills the category store with data.
    
        @param store: the store to fill
        @type store: gtk.ListStore
        """

        if store is None:
            store = self.catList.get_model()
        
        store.clear()

        cats = self.db.get_categories(installed = not self.showAll)

        if not self.cfg.get_boolean("collapseCats", "GUI"):
            for p in cats:
                store.append(None, [p])
        else:
            splitCats = defaultdict(list)
            for c in cats:
                try:
                    pre, post = c.split("-", 1)
                except ValueError: # no "-" in cat name -- do not split
                    debug("Category '%s' can't be split up. Should be no harm.", c)
                    splitCats["not-split"].append(c)
                else:
                    splitCats[pre].append(post)

            for sc in splitCats:
                if sc == "not-split":
                    it = None # append not splitted stuff to root
                else:
                    it = store.append(None, [sc])
                for cat in splitCats[sc]:
                    store.append(it, [cat])
        
        # sort them alphabetically
        store.set_sort_column_id(0, gtk.SORT_ASCENDING)

    def build_pkg_list (self, name = None):
        """
        Builds the package list.
        
        @param name: name of the selected catetegory
        @type name: string
        """
        
        store = gtk.ListStore(gtk.gdk.Pixbuf, str, str)
        self.fill_pkg_store(store, name)
        
        # build view
        self.pkgList.set_model(store)
        
        col = gtk.TreeViewColumn(_("Packages"))
        col.set_clickable(True)
        col.connect("clicked", self.cb_pkg_list_header_clicked)

        # adding the pixbuf
        cell = gtk.CellRendererPixbuf()
        col.pack_start(cell, False)
        col.add_attribute(cell, "pixbuf", 0)
        
        # adding the package name
        cell = gtk.CellRendererText()
        col.pack_start(cell, True)
        col.add_attribute(cell, "text", 1)
        
        self.pkgList.append_column(col)

        self.pkgList.get_selection().connect("changed", self.cb_pkg_list_selection)

    def fill_pkg_store (self, store = None, name = None):
        """
        Fills a given ListStore with the packages in a category.
        
        @param store: the store to fill
        @type store: gtk.ListStore
        @param name: the name of the category
        @type name: string
        """
        
        if store is None:
            store = self.pkgList.get_model()
        store.clear()

        if name:
            for cat, pkg, is_inst, disabled in self.db.get_cat(name, self.sortPkgListByName):
                if disabled:
                    warning(_("Package '%s/%s' is disabled."), cat, pkg)
                    continue

                if is_inst:
                    icon = self.icons["installed"]
                elif not self.showAll:
                    continue # ignore not installed packages
                else:
                    icon = None
                store.append([icon, pkg, cat])

    def build_version_list (self):
        store = gtk.ListStore(gtk.gdk.Pixbuf, str, str)

        # build view
        self.versionList.set_model(store)
        
        col = gtk.TreeViewColumn(_("Versions"))
        col.set_property("expand", True)
        
        self.slotcol = gtk.TreeViewColumn(_("Slot"))
        self.slotcol.set_property("expand", True)

        # adding the pixbuf
        cell = gtk.CellRendererPixbuf()
        col.pack_start(cell, False)
        col.add_attribute(cell, "pixbuf", 0)

        # adding the package name
        cell = gtk.CellRendererText()
        col.pack_start(cell, True)
        col.add_attribute(cell, "text", 1)

        # adding the slot
        cell = gtk.CellRendererText()
        self.slotcol.pack_start(cell, True)
        self.slotcol.add_attribute(cell, "text", 2)

        self.versionList.append_column(col)
        self.versionList.append_column(self.slotcol)

        self.versionList.get_selection().connect("changed", self.cb_vers_list_selection)

    def fill_version_list (self, cp, version = None):
        
        store = self.versionList.get_model()
        store.clear()

        # this is here for performance reasons
        # to not query the package with info, we do not need
        if self.cfg.get_boolean("showSlots", "GUI"):
            def get_slot(pkg):
                return pkg.get_package_settings("SLOT")
            
            self.slotcol.set_visible(True)
        
        else:
            def get_slot(*args):
                return ""
            
            self.slotcol.set_visible(False)

        packages = system.sort_package_list(system.find_packages(cp, masked=True))
        if not packages:
            raise VersionsNotFoundException(cp)
        
        # append versions
        for vers, inst, slot in ((x.get_version(), x.is_installed(), get_slot(x)) for x in packages):
            if inst:
                icon = self.icons["installed"]
            else:
                icon = None
                
            store.append([icon, vers, slot])

        pos = ((0,)) # default
        
        # activate the first one
        try:
            best_version = ""
            if version:
                best_version = version
            else:
                best_version = system.find_best_match(packages[0].get_cp()).get_version()
            for i, p in enumerate(packages):
                if p.get_version() == best_version:
                    pos = (i,)
                    break
        except AttributeError: # no package found
            pass

        self.versionList.get_selection().select_path(pos)
        self.versionList.scroll_to_cell(pos)

    def build_dep_list (self):

        listView = LazyStoreView(self.fill_dep_list)

        col = gtk.TreeViewColumn()

        cell = gtk.CellRendererPixbuf()
        col.pack_start(cell, False)
        col.add_attribute(cell, "pixbuf", 0)

        cell = gtk.CellRendererText()
        col.pack_start(cell, True)
        col.add_attribute(cell, "text", 1)

        listView.append_column(col)
        listView.set_headers_visible(False)

        return listView

    def fill_dep_list(self, pkg):

        store = gtk.TreeStore(gtk.gdk.Pixbuf, str)
        
        def sort_key (x):
            split = system.split_cpv(x.dep)

            if split is None: # split_cpv returns None if this is only a CP; we assume there are only valid deps
                return x.dep
            else:
                return "/".join(split[0:2])

        def cmp_flag (x, y):
            # get strings - as tuples are passed
            x = x[0]
            y = y[0]

            # remove "!"
            ret = 0
            if x[0] == "!":
                ret = 1
                x = x[1:]
            if y[0] == "!":
                ret = ret - 1 # if it is already 1, it is 0 now :)
                y = y[1:]

            # cmp -- if two flags are equal, the negated one is greater
            return cmp(x,y) or ret
        
        def get_icon (dep):
            if dep.satisfied:
                return self.icons["installed"]
            elif dep.dep[0] == "!":
                return self.icons["block"]
            else:
                return None
                
        def add (tree, it):
            # useflags
            flags = sorted(tree.flags.iteritems(), cmp = cmp_flag)
            for use, usetree in flags:
                if use[0] == "!":
                    usestring = _("If '%s' is disabled") % use[1:]
                else:
                    usestring = _("If '%s' is enabled") % use
                useit = store.append(it, [self.icons["use"], usestring])
                add(usetree, useit)
            
            # ORs
            for ortree in tree.ors:
                orit = store.append(it, [self.icons["or"], _("One of the following")])
                add(ortree, orit)

            # Sub (all of)
            for subtree in tree.subs:
                allit = store.append(it, [None, _("All of the following")])
                add(subtree, allit)

            # normal    
            ndeps = sorted(tree.deps, key = sort_key)
            for dep in ndeps:
                store.append(it, [get_icon(dep), dep.dep])
        
        try:
            deptree = pkg.get_dependencies()
        except AssertionError:
            w =  _("Can't display dependencies: This package has an unsupported dependency string.")
            error(w)
            store.append(None, [None, w])
        else:
            add(deptree, None)

        return store

    def build_use_list (self):
        """Builds the useList."""

        useList = LazyStoreView(self.fill_use_list)

        # build view
        cell = gtk.CellRendererText()
        iCell = gtk.CellRendererToggle()
        iCell.set_property("activatable", False)
        tCell = gtk.CellRendererToggle()
        tCell.set_property("activatable", True)
        tCell.connect("toggled", self.cb_use_flag_toggled)
        useList.append_column(gtk.TreeViewColumn(_("Enabled"), tCell, active = 0))
        useList.append_column(gtk.TreeViewColumn(_("Installed"), iCell, active = 1))
        useList.append_column(gtk.TreeViewColumn(_("Flag"), cell, text = 2))
        useList.append_column(gtk.TreeViewColumn(_("Description"), cell, markup = 3))

        useList.set_search_column(2)
        useList.set_enable_tree_lines(True)

        return useList
    
    def fill_use_list(self, pkg):
        store = gtk.TreeStore(bool, bool, str, str)

        pkg_flags = pkg.get_iuse_flags()
        pkg_flags.sort()
    
        actual_exp = None
        actual_exp_it = None

        euse = pkg.get_actual_use_flags()
        instuse = pkg.get_installed_use_flags()

        for use in pkg_flags:
            exp = pkg.use_expanded(use, suggest = actual_exp)
            if exp is not None:
                if exp != actual_exp:
                    actual_exp_it = store.append(None, [None, None, exp, "<i>%s</i>" % _("This is an expanded use flag and cannot be selected")])
                    actual_exp = exp
            else:
                actual_exp_it = None
                actual_exp = None

            enabled = use in euse
            installed = use in instuse
            store.append(actual_exp_it, [enabled, installed, use, system.get_use_desc(use, pkg.get_cp())])

        return store

    def refresh_stores (self):
        """
        Refreshes the category and package stores.
        """
        self.fill_cat_store()

        if self.selCatName:
            self.fill_pkg_store(name = self.selCatName)
        else: # no selCatName -> so no category selected --> ignore
            debug("No category selected --> should be no harm.")

    def load_session(self, sessionEx = None, defaults_only = False):
        """
        Loads the session data.
        """
        try:
            self.session = Session("gui.cfg", name="GUI", oldfiles=["gtk_session.cfg"])
        except (OSError, IOError), e:
            io_ex_dialog(e)
            return

        oldVersion = SESSION_VERSION
        allowedVersions = (1,3,4)

        if not defaults_only and sessionEx and isinstance(sessionEx, SessionException):
            if sessionEx.got in allowedVersions:
                info(_("Translating session from version %d to %d.") % (sessionEx.got, sessionEx.expected))
                oldVersion = sessionEx.got
            else:
                warning(_("Cannot translate session from version %d to %d.") % (sessionEx.got, sessionEx.expected))
                raise sessionEx

        #
        # the callbacks for the different session variables
        #

        # QUEUE
        def load_queue (merge, unmerge, oneshot):
            def _load(q, **kwargs):
                if q:
                    for i in q.split(","):
                        self.queue.append(i, **kwargs)

            _load(merge)
            _load(unmerge, unmerge = True)
            _load(oneshot, oneshot = True)
            
        def save_queue ():
            if self.__save_queue:
                return (",".join(self.queue.mergequeue), ",".join(self.queue.unmergequeue), ",".join(self.queue.oneshotmerge))
            else:
                return ("", "", "")

        # PANED
        def load_paned (*pos):
            pos = map(int, pos)
            [x.set_position(p) for x,p in zip((self.vpaned, self.hpaned), pos)]

        def save_paned ():
            return [x.get_position() for x in (self.vpaned, self.hpaned)]

        # SELECTION
        def load_pkg_selection (name):
            pos = "0"
            col = 1
            model = self.pkgList.get_model()

            if name:
                if oldVersion > 1: # newer one
                    name, pos = name.split("@")

                if model[pos][col] != name: # need to search :(
                    debug("Pkg path does not match. Searching...")
                    for cname, path in ((x[col], x.path) for x in model):
                        if cname == name:
                            pos = path
                            break


            debug("Selecting pkg path '%s'. Value: '%s'", pos, model[pos][col])
            self.pkgList.get_selection().select_path(pos)
            self.pkgList.scroll_to_cell(pos)

        def load_cat_selection (name):
            pos = "0"
            col = 0
            model = self.catList.get_model()

            if name:
                if oldVersion > 1: # newer one
                    name, pos = name.split("@")

                if self.cfg.get_boolean("collapseCats", "GUI"):
                    try:
                            sname = name.split("-", 1)
                    except ValueError: # nothing to split
                            sname = None
                else:
                    sname = None

                if sname is None and model[pos][col] != name: # need to search in normal list
                    debug("Cat path does not match. Searching...")
                    for cname, path in ((x[col], x.path) for x in model):
                        if cname == name:
                            pos = path
                            break
                
                elif sname: # the collapse case
                    row = model[pos.split(":")[0]]
                    no_match = False
                    if row[col] != sname[0]: # first part does not match :(
                        debug("First part of cat path does not match. Searching...")
                        no_match = True
                        for r in model:
                            if r[col] == sname[0]:
                                row = r
                                break

                    if no_match or model[pos][col] != sname[1]:
                        debug("Second part of cat path does not match. Searching...")
                        for cname, path in ((x[col], x.path) for x in row.iterchildren()):
                            if cname == sname[1]: # found second
                                pos = ":".join(map(str,path))
                                break
                    
                    self.catList.expand_to_path(pos)


            debug("Selecting cat path '%s'. Value: '%s'", pos, model[pos][col])
            self.catList.get_selection().select_path(pos)
            self.catList.scroll_to_cell(pos)

        def save_pkg_selection ():
            store, iter = self.pkgList.get_selection().get_selected()
            if iter:
                return "%s@%s" % (store.get_value(iter, 1), store.get_string_from_iter(iter))
            else:
                return ""

        def save_cat_selection ():
            # try to find the correct category using the pkgList selection
            # so we do not select ALL =)
            # if no package has been selected - return selCatName

            catStore, catIter = self.catList.get_selection().get_selected()
            pkgStore, pkgIter = self.pkgList.get_selection().get_selected()
            if pkgIter:
                pkgVal = pkgStore.get_value(pkgIter, 2)
                pos = "0"

                if catIter: # check for the more exact category position if possible
                    catVal = catStore.get_value(catIter, 0)
                    catParent = self.catList.get_model().iter_parent(catIter)

                    if catParent:
                        catVal = "%s-%s" % (catStore.get_value(catParent, 0), catVal)
                    
                    if catVal == pkgVal: # the info in the pkgList has higher precedence
                        pos = catStore.get_string_from_iter(catIter)

                return "%s@%s" % (pkgVal, pos)
            else:
                return "%s@0" % self.selCatName

        # PLUGIN
        def load_plugin (p):
            def _load(val):
                if val:
                    p.status = int(val)*2

            return _load
        
        def save_plugin (p):
            def _save ():
                if p.status == p.STAT_HARD_DISABLED:
                    return ""

                return int(p.status >= p.STAT_ENABLED)
            
            return _save

        # SESSION VERSION
        def load_session_version (version):

            if oldVersion < 4:
                self.session.rename_section("window", "GUI")

            if oldVersion != SESSION_VERSION: # we are trying to convert
                return
            
            version = int(version)

            if version < SESSION_VERSION:
                raise OldSessionException(version, SESSION_VERSION)
            elif version > SESSION_VERSION:
                raise NewSessionException(version, SESSION_VERSION)

        def _add (value):
            if len(value) == 4:
                self.session.add_handler(value[:3], default = value[3])
            else:
                self.session.add_handler(value)

        # set the simple ones :)
        map(_add,[
            ([("gtksessionversion", "session")], load_session_version, lambda: SESSION_VERSION),
            (["width", "height"], lambda w,h: self.window.resize(int(w), int(h)), self.window.get_size),
            (["vpanedpos", "hpanedpos"], load_paned, save_paned),
            (["catsel"], load_cat_selection, save_cat_selection, ["app-portage@0"]),
            (["pkgsel"], load_pkg_selection, save_pkg_selection, ["portato@0"])
            #([("merge", "queue"), ("unmerge", "queue"), ("oneshot", "queue")], load_queue, save_queue),
            ])

        # set the plugins
        queue = plugin.get_plugin_queue()
        if queue:
            for p in queue.get_plugins():
                self.session.add_handler(([(p.name.replace(" ","_"), "plugins")], load_plugin(p), save_plugin(p)))

        # the other things
        def load_cfg ((name, cat)):
            def load (v):
                self.cfg.set_session(name, cat, v)

            def save ():
                v = self.cfg.get_session(name, cat)
                if v is None:
                    return ""
                else:
                    return v

            self.session.add_handler(([(name, cat)], load, save))

        map(load_cfg, [("prefheight", "GUI"), ("prefwidth", "GUI")])

        # now we have the handlers -> load
        self.session.load(defaults_only)
    
    def jump_to (self, cp, version = None):
        """
        Is called when we want to jump to a specific package.

        @param cp: the CP to jump to
        @type cp: string
        @param version: if not None jump to a specific version
        @type version: string
        """

        cat, pkg = cp.split("/")

        for list, idx, what, expr in ((self.catList, 0, "categories", cat), (self.pkgList, 1, "packages", pkg)):
            pathes = [row.path for row in list.get_model() if row[idx] == expr]

            if len(pathes) == 1:
                list.get_selection().select_path(pathes[0])
                list.scroll_to_cell(pathes[0])
            else:
                debug("Unexpected number of %s returned after search: %d", what, len(pathes))
                break

        self.show_package(cp = cp, version = version, queue = self.queue)

    def set_uri_hook (self, browser):
        """
        Sets the browser command which is called when a URL is going to be opened.

        @param browser: the browser command
        @type browser: string
        """

        browser = browser.split()
        gtk.link_button_set_uri_hook(lambda btn, x: get_listener().send_cmd(browser+[btn.get_uri()]))

    def set_notebook_tabpos (self, tabposlist):
        """
        Sets the positions of the tabs of the notebooks.

        @param tabposlist: the list of positions: first comes the one for package tabs; sndly for sys tabs
        @type tabposlist: int[]
        """
        self.pkgNotebook.set_tab_pos(tabposlist[0])
        self.sysNotebook.set_tab_pos(tabposlist[1])

    def title_update (self, title):
        """
        Updates the titles of the window and the systray.
        Mainly used with emerge term titles.

        @param title: the title
        @type title: string
        """
        
        def window_title_update (title):
            """
            Updates the title of the main window.
            """
            if title is None or not self.cfg.get_boolean("updateTitle", "GUI"):
                self.window.set_title(self.main_title)
            else:
                title = title.strip()
                if title[0] == '*':
                    self.window.set_title(self.main_title)
                else:
                    space_idx = title.rfind(" ")
                    if space_idx != -1:
                        title = title[:space_idx]

                    self.window.set_title(("Portato >>> %s" % title))

        def __update(title):
            if self.tray:
                self.tray.set_tooltip(title)
            
            window_title_update(title)
            if title is None or not self.cfg.get_boolean("updateConsole", "GUI"):
                title = _("Console")
            else:
                title = ("%s (%s)") % (_("Console"), title)
            
            tlength = int(self.cfg.get("titlelength", "GUI"))
            if (len(title) > tlength): title = "%s..." % title[:tlength-3]
            self.sysNotebook.set_tab_label_text(self.termHB, title)

            return False

        # as this might get called from other threads use gobject.idle_add
        gobject.idle_add(__update, title)

    def cb_cat_list_selection (self, selection):
        """
        Callback for a category-list selection. 
        Updates the package list with the packages in the category.
        """
        # get the selected category
        store, it = selection.get_selected()
        if it:
            if not self.cfg.get_boolean("collapseCats", "GUI"):
                self.selCatName = store.get_value(it, 0)
            else:
                parent = store.iter_parent(it)
                if parent is None:
                    if store.iter_has_child(it): # this is a split up selector -> do nothing
                        return True
                    else:
                        self.selCatName = store.get_value(it, 0) # this is a non-split up top
                else:
                    self.selCatName = ("%s-%s" % (store.get_value(parent, 0), store.get_value(it, 0)))

            self.fill_pkg_store(name = self.selCatName)
        return True

    def cb_pkg_list_selection (self, selection):
        """
        Callback for a package-list selection.
        Updates the version list.
        """
        store, it = selection.get_selected()
        if it:
            oldcp = self.selCP

            self.selCP = "%s/%s" % (store.get_value(it, 2), store.get_value(it, 1))
            try:
                self.fill_version_list(self.selCP)
            except VersionsNotFoundException, e:
                warning(_("No versions of package '%s' found!.") % self.selCP)
                no_versions_dialog(self.selCP)
                self.db.disable(self.selCP)
                self.selCP = oldcp

        return True

    def cb_pkg_list_header_clicked(self, col):
        self.sortPkgListByName = not self.sortPkgListByName
        self.fill_pkg_store(name = self.selCatName)
        return True

    def cb_vers_list_selection (self, selection):
        """
        Callback for a package-list selection.
        Updates the version list.
        """
        store, it = selection.get_selected()
        if it:
            self.selCPV = "%s-%s" % (self.selCP, store.get_value(it, 1))
            self.show_package(cpv = self.selCPV, queue = self.queue)
        
        return True

    def cb_queue_list_selection (self, selection):

        def set_val (val):
            self.queueOneshot.handler_block(self.queueOneshotHandler)
            self.queueOneshot.set_active(val)
            self.queueOneshot.handler_unblock(self.queueOneshotHandler)

        store, it = selection.get_selected()
        if it:
            parent = self.queueTree.parent_iter(it)
            if self.queueTree.is_in_emerge(it) and parent and not self.queueTree.iter_has_parent(parent):
                package = store.get_value(it, 0)
                self.queueOneshot.set_sensitive(True)
                set_val(package in self.queue.oneshotmerge)
                return True

        self.queueOneshot.set_sensitive(False)
        set_val(False)
        return True

    def cb_queue_row_activated (self, view, path, *args):
        """Callback for an activated row in the emergeQueue. Opens a package window."""
        store = self.queueTree
        if len(path) > 1:
            iterator = store.get_original().get_iter(path)
            if store.iter_has_parent(iterator):
                package = store.get_value(iterator, store.get_cpv_column())

                if store.is_in_emerge(iterator):
                    type = "install"
                elif store.is_in_unmerge(iterator):
                    type = "uninstall"
                elif store.is_in_update(iterator):
                    type = "update"

                self.show_package(cpv = package, queue = self.queue, instantChange = True, doEmerge = False, type = type)
        return True
    
    def cb_queue_tooltip_queried (self, view, x, y, is_keyboard, tooltip):
        store = self.queueList.get_model()
        path = self.queueList.get_path_at_pos(x,y)

        if path is None:
            return False

        it = store.get_iter(path[0])

        if store.iter_parent(it) is None:
            return False # do not show tooltips for the root entries

        pkg = system.new_package(store.get_value(it, 0))
        
        enabled = []
        disabled = []
        expanded = set()

        pkg_flags = pkg.get_iuse_flags()
        pkg_flags.sort()
        if not pkg_flags: # no flags - stop here
            return None
        
        actual = set(pkg.get_actual_use_flags())
        
        if pkg.is_installed():
            installed = set(pkg.get_iuse_flags()).intersection(pkg.get_installed_use_flags())
        else:
            inst = system.find_packages(pkg.get_slot_cp(), system.SET_INSTALLED)
            if inst:
                installed = set(inst[0].get_iuse_flags()).intersection(inst[0].get_installed_use_flags())
            else:
                installed = set()

        diff = actual.symmetric_difference(installed)

        for use in pkg_flags:
            exp = pkg.use_expanded(use)
            if exp:
                expanded.add(exp)
            
            else:
                useStr = use
                if installed and use in diff:
                    useStr += " %"
                if use in actual:
                    enabled.append(useStr)
                else:
                    disabled.append(useStr)
        
        string = ""
        
        if enabled:
            string = "<b>+%s</b>" % ("\n+".join(enabled),)
            if len(disabled) > 0:
                string = string + "\n"
        
        if disabled:
            string = string+"<i>- %s</i>" % ("\n- ".join(disabled),)

        if expanded:
            if string:
                string += "\n\n"

            string += "\n".join(expanded)
        
        tooltip.set_markup(string)
        return string != ""

    def cb_execute_clicked (self, action):
        """Execute the current queue."""
        
        if len(flags.newUseFlags) > 0:
            if not self.session.get_boolean("useflags", "dialogs"):
                self.session.set("useflags", changed_flags_dialog(_("use flags"))[1], "dialogs")
            try:
                flags.write_use_flags()
            except IOError, e:
                io_ex_dialog(e)
                return True
        
        if len(flags.new_masked)>0 or len(flags.new_unmasked)>0 or len(flags.newTesting)>0:
            debug("new masked: %s",flags.new_masked)
            debug("new unmasked: %s", flags.new_unmasked)
            debug("new testing: %s", flags.newTesting)
            if not self.session.get_boolean("keywords", "dialogs"):
                self.session.set("keywords", changed_flags_dialog(_("masking keywords"))[1], "dialogs")
            try:
                flags.write_masked()
                flags.write_testing()
            except IOError, e:
                io_ex_dialog(e)
                return True
            else:
                system.reload_settings()

        model, iter = self.queueList.get_selection().get_selected()

        if iter is None:
            if model.iter_n_children(None) == 1: # only one queue there - take this as being selected
                iter = model.get_iter_root()
            else:
                return False

        self.sysNotebook.set_current_page(self.CONSOLE_PAGE)
        
        # test which type of queue we have here
        if self.queueTree.is_in_emerge(iter):
            self.queue.emerge(force = True)
        elif self.queueTree.is_in_unmerge(iter):
            self.queue.unmerge(force = True)
        else:
            self.queue.update_world(sets = self.updateSets, force=True, newuse = self.cfg.get_boolean("newuse"), deep = self.cfg.get_boolean("deep"))

        return True
        
    def cb_update_clicked (self, action):
        def __update():
            
            def cb_idle_append (updating):
                try:
                    try:
                        for pkg, old_pkg in updating:
                            self.queue.append(pkg.get_cpv(), type = "update", unmask = False)
                    except PackageNotFoundException, e:
                        if unmask_dialog(e[0]) == gtk.RESPONSE_YES:
                            for pkg, old_pkg in updating:
                                self.queue.append(pkg.get_cpv(), type = "update", unmask = True)

                except BlockedException, e:
                    blocked_dialog(e[0], e[1])
                    self.queue.remove_children(self.queueTree.get_update_it())
                
                return False

            watch = gtk.gdk.Cursor(gtk.gdk.WATCH)
            self.window.window.set_cursor(watch)
            try:
                if system.has_set_support():
                    confsets = [x.strip() for x in self.cfg.get("updatesets").split(",")]
                    self.updateSets = [s for s in confsets if s in system.get_sets()]
                    updating = system.update_world(sets = self.updateSets, newuse = self.cfg.get_boolean("newuse"), deep = self.cfg.get_boolean("deep"))
                else:
                    updating = system.update_world(newuse = self.cfg.get_boolean("newuse"), deep = self.cfg.get_boolean("deep"))
                    self.updateSets = ("world",)
                
                debug("updating list: %s --> length: %s", [(x.get_cpv(), y.get_cpv()) for x,y in updating], len(updating))
                gobject.idle_add(cb_idle_append, updating)
            finally:
                self.window.window.set_cursor(None)
            
        GtkThread(name="Update-Thread", target=__update).start()
        
        return True

    def cb_remove_clicked (self, button):
        """Removes a selected item in the (un)emerge-queue if possible."""
        model, iter = self.queueList.get_selection().get_selected()

        if iter:
            parent = model.iter_parent(iter)
            
            if self.queueTree.is_in_update(iter) and parent:
                if remove_updates_dialog() == gtk.RESPONSE_YES:
                    self.queue.remove_with_children(self.queueTree.get_update_it())
            
            elif not parent: # top-level
                if model.iter_n_children(iter) > 0: # and has children which can be removed :)
                    if remove_queue_dialog() == gtk.RESPONSE_YES :
                        self.queue.remove_with_children(iter)
                else:
                    self.queue.remove(iter)
            
            elif model.iter_parent(parent): # this is in the 3rd level => dependency
                remove_deps_dialog()
            else:
                self.queue.remove_with_children(iter)

                if model.iter_n_children(parent) == 0: # no more children left - remove queue too
                    self.queue.remove(parent)
        
            return True
        return False

    def cb_sync_clicked (self, action):
        self.sysNotebook.set_current_page(self.CONSOLE_PAGE)
        cmd = self.cfg.get("syncCommand")

        if cmd != "emerge --sync":
            cmd = cmd.split()
            self.queue.sync(cmd)
        else:
            self.queue.sync()

    def cb_save_flags_clicked (self, action):
        try:
            flags.write_use_flags()
            flags.write_testing()
            flags.write_masked()
        except IOError, e:
            io_ex_dialog(e)

    @Window.watch_cursor
    def cb_reload_clicked (self, action):
        """Reloads the portage settings and the database."""
        system.reload_settings()
        self.db.reload()

    @Window.watch_cursor
    def cb_search_clicked (self, entry):
        """Do a search."""
        text = entry.get_text()
        if text != "":
            if "/" not in text:
                text = "/.*"+text # only look for package names

            packages = system.find_packages(text, with_version = False)

            if packages == []:
                nothing_found_dialog()
            else:
                if len(packages) == 1:
                    self.jump_to(packages[0])
                else:
                    SearchWindow(self.window, packages, self.jump_to)

        return True

    def cb_search_changed (self, *args):
        """
        Called when the user enters something in the search field.
        Updates the packages according to the search expression.
        """
        if not self.__searchChanged and self.cfg.get_boolean("searchOnType", section="GUI"):
            self.__searchChanged = True
            
            def __update():
                self.__searchChanged = False
                txt = self.searchEntry.get_text()

                if txt or self.db.restrict:
                    self.db.restrict = txt

                self.refresh_stores()
                self.catList.get_selection().select_path("0") # XXX make this smarter

                return False # not again ;)

            gobject.timeout_add(100, __update)

    def cb_delete_search_clicked (self, *args):
        self.searchEntry.set_text("")
        return True

    def cb_preferences_clicked (self, *args):
        """
        User wants to open preferences.
        """
        PreferenceWindow(self.window, self.cfg, self.console.set_font_from_string, self.set_uri_hook, self.set_notebook_tabpos, self.fill_cat_store)
        return True

    def cb_about_clicked (self, *args):
        """
        User wants to open about dialog.
        """
        AboutWindow(self.window)
        return True

    def cb_plugins_clicked (self, *args):
        """
        User wants to open plugin dialog.
        """
        queue = plugin.get_plugin_queue()
        if queue is None:
            plugins = []
        else:
            plugins = list(queue.get_plugins())

        PluginWindow(self.window, plugins, self.queue)
        return True
    
    def cb_show_updates_clicked (self, *args):
        """
        Show the list of updateble packages.
        """

        def __update():
            def cb_idle_show(packages):
                """
                Callback opening the menu when the calculation is finished.

                @returns: False to signal that it is finished
                """
                UpdateWindow(self.window, packages, self.queue, self.jump_to)
                return False
            
            watch = gtk.gdk.Cursor(gtk.gdk.WATCH)
            self.window.window.set_cursor(watch)
            
            packages = []
            try:
                packages.extend(system.get_updated_packages())
            finally:
                self.window.window.set_cursor(None)

            gobject.idle_add(cb_idle_show, packages)
        
        GtkThread(name="Show Updates Thread", target = __update).start()
        return True

    def cb_show_installed_toggled (self, *args):
        """
        Toggle the "show only installed" option.
        """
        self.showAll = not self.showAll
        self.refresh_stores()

    def cb_right_click (self, object, event):
        """
        Called when the user right clicks somewhere.
        Used to display a menu.
        
        This method should handle ALL such menus.

        @param object: the object/widget where the click is done
        @type object: gtk.Widget
        @param event: the event triggered
        @type event: gtk.gdk.Event
        """

        if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3: # 3 == right click
            x = int(event.x)
            y = int(event.y)
            time = event.time
            
            if object == self.console:
                self.consolePopup.popup(None, None, None, event.button, time)
            else:
                return False
        else:
            return False

    def cb_oneshot_clicked (self, *args):
        """
        Mark a package as oneshot.
        """
        sel = self.queueList.get_selection()
        store, it = sel.get_selected()
        if it:
            if self.queueTree.is_in_emerge(it) and self.queueTree.iter_has_parent(it):
                package = store.get_value(it, 0)
                set = (package not in self.queue.oneshotmerge)
                
                self.queue.append(package, update = True, oneshot = set, forceUpdate = True)

    def cb_pause_emerge (self, curr):
        """
        This method returns a callback for a "pause emerge" toggle button.
        It is needed as there are different toggle buttons of this type and if one is clicked,
        the others should be marked too.

        @param curr: The button to return the callback for.
        @type curr: gtk.ToggleButton
        """
        def pause (cb):
            """
            The actual callback.

            Mark all other buttons too.

            @param cb: The button which got toggled.
            @type cb: gtk.ToggleButton
            """

            # pause or continue
            self.emergePaused = cb.get_active()
            if not self.emergePaused:
                self.queue.continue_emerge()
                #self.tray.set_from_file(APP_ICON)
            else:
                self.queue.stop_emerge()
                #self.tray.set_from_file(os.path.join(ICON_DIR, "pausing.png"))

            # block the handlers of the other buttons
            # so that calling "set_active" does not call this callback recursivly
            for v in self.pauseItems.itervalues():
                v[0].handler_block(v[1])

            # mark the others
            for k, v in self.pauseItems.iteritems():
                if k != curr:
                    v[0].set_active(self.emergePaused)

            # unblock
            for v in self.pauseItems.itervalues():
                v[0].handler_unblock(v[1])
            
            return False
        return pause

    def cb_kill_clicked (self, *args):
        """
        Kill emerge.
        """
        self.queue.kill_emerge()
        if self.emergePaused: # unmark the "pause emerge" buttons
            self.pauseItems["menu"][0].set_active(False) # calling one button is enough (see: cb_pause_emerge)

    def cb_copy_clicked (self, *args):
        """
        Copy marked text in the terminal to clipboard.
        """
        self.console.copy_clipboard()

    def cb_delete (self, *args):
        """
        Called when the user wants to quit the application.

        Asks the user for confirmation if there is something in the queue.
        Also saves session data.
        """

        self.__save_queue = False

        if not self.queue.is_empty():
            ret = queue_not_empty_dialog()
            if ret == gtk.RESPONSE_CANCEL:
                return True
            else: # there is sth in queue AND the user still wants to close -> kill emerge
                self.__save_queue = (ret == gtk.RESPONSE_YES)
                self.queue.kill_emerge()

        # write sessions
        Session.close()
        
        return False

    def cb_minimized (self, window, event):
        """
        User wants to minimize the window. 
        If it is possible to minimize to tray, it is done.
        """

        if self.tray and self.cfg.get_boolean("hideOnMinimize", "GUI"):
            if event.changed_mask & gtk.gdk.WINDOW_STATE_ICONIFIED:
                if event.new_window_state & gtk.gdk.WINDOW_STATE_ICONIFIED:
                    self.window.hide()
                    return True
        
        return False

    def cb_systray_activated (self, *args):
        """
        Systray was activated. Show or hide the window.
        """
        if self.window.iconify_initially:
            self.window.deiconify()
            self.window.show()
            self.window.window.show()
        else:
            self.window.iconify()
    
    def cb_use_flag_toggled (self, *args):
        return self.packageTable.cb_use_flag_toggled(*args)

    def cb_close (self, *args):
        """
        "Close" menu entry called.
        Emulate normal quitting.
        """
        if not self.cb_delete(): # do the checks
            self.window.destroy()

    def cb_destroy (self, *args):
        """
        Calls main_quit().
        """
        gtk.main_quit()

    def check_prereqs (self):

        def fail (m):
            error("PreReqError: %s", m)
            raise PreReqError(m)

        pdir = system.get_global_settings("PORTDIR")

        if not os.path.exists(pdir):
            fail(_("The portage tree is not existing."))

        ls = os.listdir(system.get_global_settings("PORTDIR"))
        if not "eclass" in ls:
            fail(_("The portage tree seems to be empty."))

        debug("All prereqs matched. Fine :)")

    def main (self):
        """
        Main.
        """
        gobject.threads_init()
        # now subthreads can run normally, but are not allowed to touch the GUI. If threads should change sth there - use gobject.idle_add().
        # for more informations on threading and gtk: http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq20.006.htp
        plugin.hook("main")(gtk.main)()