~gary-lasker/software-center/launcher-integration-for-p

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
# Copyright (C) 2009 Canonical
#
# Authors:
#  Michael Vogt
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

import atexit
import atk
import locale
import dbus
import dbus.service
import gettext
import logging
import gobject as GObject
import gtk
import os
import subprocess
import sys
import xapian
import glob


# purely to initialize the netstatus
import softwarecenter.netstatus
from softwarecenter.netstatus import network_state_is_connected
# make pyflakes shut up
softwarecenter.netstatus.NETWORK_STATE

from SimpleGtkbuilderApp import SimpleGtkbuilderApp
from softwarecenter.db.application import Application
from softwarecenter.db import DebFileApplication

from softwarecenter.enums import (Icons,
                                  PkgStates,
                                  ViewPages,
                                  NavButtons,
                                  AppActions,
                                  DB_SCHEMA_VERSION,
                                  MOUSE_EVENT_FORWARD_BUTTON,
                                  MOUSE_EVENT_BACK_BUTTON,
                                  SOFTWARE_CENTER_NAME_KEYRING,
                                  SOFTWARE_CENTER_SSO_DESCRIPTION,
                                 )

from softwarecenter.paths import SOFTWARE_CENTER_PLUGIN_DIRS, ICON_PATH
from softwarecenter.utils import (clear_token_from_ubuntu_sso,
                                  wait_for_apt_cache_ready)
from softwarecenter.version import VERSION
from softwarecenter.db.database import StoreDatabase
import dependency_dialogs as dependency_dialogs
import deauthorize_dialog as deauthorize_dialog
from softwarecenter.backend.transactionswatcher import TransactionFinishedResult
try:
    from aptd_gtk2 import InstallBackendUI
    InstallBackendUI # pyflakes
except ImportError:
    from softwarecenter.backend.installbackend import InstallBackendUI

from viewswitcher import ViewSwitcher
from pendingview import PendingView
from installedpane import InstalledPane
from channelpane import ChannelPane
from availablepane import AvailablePane
from softwarepane import SoftwareSection
from historypane import HistoryPane
from viewmanager import ViewManager

from softwarecenter.config import get_config
from softwarecenter.backend import get_install_backend
from softwarecenter.paths import SOFTWARE_CENTER_ICON_CACHE_DIR

from softwarecenter.plugin import PluginManager
from softwarecenter.backend.reviews import get_review_loader, UsefulnessCache
from softwarecenter.distro import get_distro
from softwarecenter.db.pkginfo import get_pkg_info
import dialogs
from gettext import gettext as _

LOG = logging.getLogger(__name__)


class SoftwarecenterDbusController(dbus.service.Object):
    """ 
    This is a helper to provide the SoftwarecenterIFace
    
    It provides only a bringToFront method that takes 
    additional arguments about what packages to show
    """
    def __init__(self, parent, bus_name,
                 object_path='/com/ubuntu/Softwarecenter'):
        dbus.service.Object.__init__(self, bus_name, object_path)
        self.parent = parent

    @dbus.service.method('com.ubuntu.SoftwarecenterIFace')
    def bringToFront(self, args):
        if args != 'nothing-to-show':
            self.parent.show_available_packages(args)
        self.parent.window_main.present()
        return True

    @dbus.service.method('com.ubuntu.SoftwarecenterIFace')
    def triggerDatabaseReopen(self):
        self.parent.db.emit("reopen")

    @dbus.service.method('com.ubuntu.SoftwarecenterIFace')
    def triggerCacheReload(self):
        self.parent.cache.emit("cache-ready")

class SoftwareCenterApp(SimpleGtkbuilderApp):
    
    WEBLINK_URL = "http://apt.ubuntu.com/p/%s"
    
    # the size of the icon for dialogs
    APP_ICON_SIZE = 48  # gtk.ICON_SIZE_DIALOG ?

    def __init__(self, datadir, xapian_base_path, options, args=None):

        self.datadir = datadir
        SimpleGtkbuilderApp.__init__(self, 
                                     datadir+"/ui/gtk/SoftwareCenter.ui", 
                                     "software-center")
        gettext.bindtextdomain("software-center", "/usr/share/locale")
        gettext.textdomain("software-center")

        try:
            locale.setlocale(locale.LC_ALL, "")
        except:
            LOG.exception("setlocale failed, resetting to C")
            locale.setlocale(locale.LC_ALL, "C")

        # setup dbus and exit if there is another instance already
        # running
        self.setup_dbus_or_bring_other_instance_to_front(args)
        self.setup_database_rebuilding_listener()
        
        # distro specific stuff
        self.distro = get_distro()

        # Disable software-properties if it does not exist
        if not os.path.exists("/usr/bin/software-properties-gtk"):
            sources = self.builder.get_object("menuitem_software_sources")
            sources.set_sensitive(False)

        # a main iteration friendly apt cache
        self.cache = get_pkg_info()
        self.cache.connect("cache-broken", self._on_apt_cache_broken)

        # backend
        self.backend = get_install_backend()
        self.backend.ui = InstallBackendUI()
        self.backend.connect("transaction-finished", self._on_transaction_finished)
        self.backend.connect("channels-changed", self.on_channels_changed)
        # xapian
        pathname = os.path.join(xapian_base_path, "xapian")
        self._use_axi = not options.disable_apt_xapian_index

        try:
            self.db = StoreDatabase(pathname, self.cache)
            self.db.open(use_axi = self._use_axi)
            if self.db.schema_version() != DB_SCHEMA_VERSION:
                LOG.warn("database format '%s' expected, but got '%s'" % (
                         DB_SCHEMA_VERSION, self.db.schema_version()))
                if os.access(pathname, os.W_OK):
                    self._rebuild_and_reopen_local_db(pathname)
        except xapian.DatabaseOpeningError:
            # Couldn't use that folder as a database
            # This may be because we are in a bzr checkout and that
            #   folder is empty. If the folder is empty, and we can find the
            # script that does population, populate a database in it.
            if os.path.isdir(pathname) and not os.listdir(pathname):
                self._rebuild_and_reopen_local_db(pathname)
        except xapian.DatabaseCorruptError, e:
            LOG.exception("xapian open failed")
            dialogs.error(None, 
                          _("Sorry, can not open the software database"),
                          _("Please re-install the 'software-center' "
                            "package."))
            # FIXME: force rebuild by providing a dbus service for this
            sys.exit(1)

        # reviews
        self.review_loader = get_review_loader(self.cache, self.db)
        # FIXME: add some kind of throttle, I-M-S here
        self.review_loader.refresh_review_stats(self.on_review_stats_loaded)
        #load usefulness votes from server when app starts
        self.useful_cache = UsefulnessCache(True)
    
        # additional icons come from app-install-data
        self.icons = gtk.icon_theme_get_default()
        self.icons.append_search_path(ICON_PATH)
        self.icons.append_search_path(os.path.join(self.datadir,"icons"))
        self.icons.append_search_path(os.path.join(self.datadir,"emblems"))
        # HACK: make it more friendly for local installs (for mpt)
        self.icons.append_search_path(self.datadir+"/icons/32x32/status")
        # add the humanity icon theme to the iconpath, as not all icon 
        # themes contain all the icons we need
        # this *shouldn't* lead to any performance regressions
        path = '/usr/share/icons/Humanity'
        if os.path.exists(path):
            for subpath in os.listdir(path):
                subpath = os.path.join(path, subpath)
                if os.path.isdir(subpath):
                    for subsubpath in os.listdir(subpath):
                        subsubpath = os.path.join(subpath, subsubpath)
                        if os.path.isdir(subsubpath):
                            self.icons.append_search_path(subsubpath)
        gtk.window_set_default_icon_name("softwarecenter")

        # misc state
        self._block_menuitem_view = False
        
        # for use when viewing previous purchases
        self.scagent = None
        self.sso = None
 
        # hackery, paint viewport borders around notebook
        self.notebook_view.set_border_width(1)
        self.notebook_view.connect('expose-event', self._on_notebook_expose)

        # register view manager and create view panes/widgets
        self.view_manager = ViewManager(self.notebook_view)
        
        # available pane
        self.available_pane = AvailablePane(self.cache,
                                            self.db,
                                            self.distro,
                                            self.icons,
                                            self.datadir,
                                            self.navhistory_back_action,
                                            self.navhistory_forward_action)
        self.available_pane.connect("available-pane-created", self.on_available_pane_created)
        self.view_manager.register(self.available_pane, ViewPages.AVAILABLE)

        # channel pane (view not fully initialized at this point)
        self.channel_pane = ChannelPane(self.cache,
                                        self.db,
                                        self.distro,
                                        self.icons,
                                        self.datadir)
        self.channel_pane.connect("channel-pane-created", self.on_channel_pane_created)
        self.view_manager.register(self.channel_pane, ViewPages.CHANNEL)
        
        # installed pane (view not fully initialized at this point)
        self.installed_pane = InstalledPane(self.cache,
                                            self.db, 
                                            self.distro,
                                            self.icons,
                                            self.datadir)
        self.installed_pane.connect("installed-pane-created", self.on_installed_pane_created)
        self.view_manager.register(self.installed_pane, ViewPages.INSTALLED)
        
        # history pane (not fully loaded at this point)
        self.history_pane = HistoryPane(self.cache,
                                        self.db,
                                        self.distro,
                                        self.icons,
                                        self.datadir)
        self.history_pane.connect("history-pane-created", self.on_history_pane_created)
        self.view_manager.register(self.history_pane, ViewPages.HISTORY)

        # pending view
        self.pending_view = PendingView(self.icons)
        self.view_manager.register(self.pending_view, ViewPages.PENDING)
        
        # keep track of the current active pane
        self.active_pane = self.available_pane

        # view switcher
        self.view_switcher = ViewSwitcher(self.view_manager, self.datadir, self.db, self.cache, self.icons)
        self.scrolledwindow_viewswitcher.add(self.view_switcher)
        self.view_switcher.show()
        self.view_switcher.connect("view-changed", 
                                   self.on_view_switcher_changed)
        self.view_switcher.width = self.scrolledwindow_viewswitcher.get_property('width-request')
        self.view_switcher.connect('size-allocate', self.on_viewswitcher_resized)
        
        # expand the Get Software node in the viewswitcher by default so that its important subitems
        # (e.g., For Purchase and Independent) are always clearly visible and available
        self.view_switcher.expand_available_node()

        # launchpad integration help, its ok if that fails
        try:
            import LaunchpadIntegration
            LaunchpadIntegration.set_sourcepackagename("software-center")
            LaunchpadIntegration.add_items(self.menu_help, 1, True, False)
        except Exception, e:
            LOG.debug("launchpad integration error: '%s'" % e)
            
        # set up accelerator keys for navigation history actions
        accel_group = gtk.AccelGroup()
        self.window_main.add_accel_group(accel_group)
        self.menuitem_go_back.add_accelerator("activate",
                                              accel_group,
                                              ord('['),
                                              gtk.gdk.CONTROL_MASK,
                                              gtk.ACCEL_VISIBLE)
        self.menuitem_go_forward.add_accelerator("activate",
                                                 accel_group,
                                                 ord(']'),
                                                 gtk.gdk.CONTROL_MASK,
                                                 gtk.ACCEL_VISIBLE)
        self.menuitem_go_back.add_accelerator("activate",
                                              accel_group,
                                              gtk.gdk.keyval_from_name("Left"),
                                              gtk.gdk.MOD1_MASK,
                                              gtk.ACCEL_VISIBLE)
        self.menuitem_go_forward.add_accelerator("activate",
                                                 accel_group,
                                                 gtk.gdk.keyval_from_name("Right"),
                                                 gtk.gdk.MOD1_MASK,
                                                 gtk.ACCEL_VISIBLE)
        self.menuitem_go_back.add_accelerator("activate",
                                              accel_group,
                                              gtk.gdk.keyval_from_name("KP_Left"),
                                              gtk.gdk.MOD1_MASK,
                                              gtk.ACCEL_VISIBLE)
        self.menuitem_go_forward.add_accelerator("activate",
                                                 accel_group,
                                                 gtk.gdk.keyval_from_name("KP_Right"),
                                                 gtk.gdk.MOD1_MASK,
                                                 gtk.ACCEL_VISIBLE)

        # specify the smallest allowable window size
        self.window_main.set_size_request(700, 400)

        # setup window name and about information (needs branding)
        name = self.distro.get_app_name()
        self.window_main.set_title(name)
        self.aboutdialog.set_name(name)
        about_description = self.distro.get_app_description()
        self.aboutdialog.set_comments(about_description)

        # about dialog
        self.aboutdialog.connect("response",
                                 lambda dialog, rid: dialog.hide())
        self.aboutdialog.connect("delete_event", self.aboutdialog.hide_on_delete)

        # restore state
        self.config = get_config()
        self.restore_state()

        # create label_status for in our eventbox
        self.label_status = gtk.Label()
        self.status_box.a11y = self.status_box.get_accessible()
        self.status_box.a11y.set_role(atk.ROLE_STATUSBAR)
        self.status_box.add(self.label_status)

        # open plugin manager and load plugins
        self.plugin_manager = PluginManager(self, SOFTWARE_CENTER_PLUGIN_DIRS)
        self.plugin_manager.load_plugins()
        
        # make the local cache directory if it doesn't already exist
        icon_cache_dir = SOFTWARE_CENTER_ICON_CACHE_DIR
        if not os.path.exists(icon_cache_dir):
            os.makedirs(icon_cache_dir)
        self.icons.append_search_path(icon_cache_dir)

        # run s-c-agent update
        if options.disable_buy:
            file_menu = self.builder.get_object("menu1")
            file_menu.remove(self.builder.get_object("menuitem_reinstall_purchases"))
        else:
            sc_agent_update = os.path.join(
                self.datadir, "update-software-center-agent")
            (pid, stdin, stdout, stderr) = GObject.spawn_async(
                [sc_agent_update, "--datadir", datadir], 
                flags=GObject.SPAWN_DO_NOT_REAP_CHILD)
            GObject.child_watch_add(
                pid, self._on_update_software_center_agent_finished)


        # FIXME:  REMOVE THIS once launchpad integration is enabled
        #         by default
        if not options.enable_lp:
            file_menu = self.builder.get_object("menu1")
            file_menu.remove(self.builder.get_object("menuitem_launchpad_private_ppas"))

        if options.disable_buy and not options.enable_lp:
            file_menu.remove(self.builder.get_object("separator_login"))

        # TODO: Remove the following two lines once we have remove repository
        #       support in aptdaemon (see LP: #723911)
        file_menu = self.builder.get_object("menu1")
        file_menu.remove(self.builder.get_object("menuitem_deauthorize_computer"))
            
    # helper
    def _rebuild_and_reopen_local_db(self, pathname):
        """ helper that rebuilds a db and reopens it """
        from softwarecenter.db.update import rebuild_database
        LOG.info("building local database")
        rebuild_database(pathname)
        self.db = StoreDatabase(pathname, self.cache)
        self.db.open(use_axi=self._use_axi)

    # callbacks
    def on_available_pane_created(self, widget):
        available_section = SoftwareSection()
        available_section.set_view_id(ViewPages.AVAILABLE)
        self.available_pane.set_section(available_section)

        # connect signals
        self.available_pane.connect("app-list-changed", 
                                    self.on_app_list_changed,
                                    ViewPages.AVAILABLE)
        self.available_pane.app_details_view.connect("selected", 
                                                     self.on_app_details_changed,
                                                     ViewPages.AVAILABLE)
        self.available_pane.app_details_view.connect("application-request-action", 
                                                     self.on_application_request_action)
        self.available_pane.app_view.connect("application-request-action", 
                                             self.on_application_request_action)
        self.available_pane.app_view.connect("mouse-nav-requested", 
                                             self.on_window_main_button_press_event)
        self.available_pane.searchentry.grab_focus()
    
    def on_channel_pane_created(self, widget):
        channel_section = SoftwareSection()
        # note that the view_id for each channel's section is set later
        # depending on whether the channel view will display available or
        # installed items
        self.channel_pane.set_section(channel_section)

        # connect signals
        self.channel_pane.connect("app-list-changed", 
                                    self.on_app_list_changed,
                                    ViewPages.CHANNEL)
        self.channel_pane.app_details_view.connect("selected", 
                                                   self.on_app_details_changed,
                                                   ViewPages.CHANNEL)
        self.channel_pane.app_details_view.connect("application-request-action", 
                                                   self.on_application_request_action)
        self.channel_pane.app_view.connect("application-request-action", 
                                           self.on_application_request_action)
                                           
    def on_installed_pane_created(self, widget):
        installed_section = SoftwareSection()
        installed_section.set_view_id(ViewPages.INSTALLED)
        self.installed_pane.set_section(installed_section)
        
        # connect signals
        self.installed_pane.connect("app-list-changed", 
                                    self.on_app_list_changed,
                                    ViewPages.INSTALLED)
        self.installed_pane.app_details_view.connect("selected", 
                                                     self.on_app_details_changed,
                                                     ViewPages.INSTALLED)
        self.installed_pane.app_details_view.connect("application-request-action", 
                                                     self.on_application_request_action)
        self.installed_pane.app_view.connect("application-request-action", 
                                             self.on_application_request_action)
                                             
    def on_history_pane_created(self, widget):
        # connect signal
        self.history_pane.connect("app-list-changed", 
                                  self.on_app_list_changed,
                                  ViewPages.HISTORY)
    
    def _on_update_software_center_agent_finished(self, pid, condition):
        LOG.info("software-center-agent finished with status %i" % os.WEXITSTATUS(condition))
        if os.WEXITSTATUS(condition) == 0:
            self.db.reopen()

    def on_review_stats_loaded(self, reviews):
        LOG.debug("on_review_stats_loaded: '%s'" % len(reviews))

    def on_app_details_changed(self, widget, app, page):
        self.update_status_bar()

    def on_app_list_changed(self, pane, new_len, page):
        if self.view_manager.get_active_view() == page:
            self.update_status_bar()

    def on_window_main_delete_event(self, widget, event):
        if hasattr(self, "glaunchpad"):
            self.glaunchpad.shutdown()
        self.save_state()
        gtk.main_quit()
        
    def on_window_main_key_press_event(self, widget, event):
        """
        Implement the backspace key as a hotkey to back up one level in
        the navigation heirarchy.  This works everywhere except when
        purchasing software in the purchase_view where backspace works
        as expected in the webkit text fields.
        """
        if (event.keyval == gtk.gdk.keyval_from_name("BackSpace") and 
            self.active_pane and
            hasattr(self.active_pane, 'navigation_bar') and
            not self.active_pane.searchentry.is_focus() and
            not self.active_pane.navigation_bar.has_id(NavButtons.PURCHASE)):
            self.active_pane.navigation_bar.navigate_up()
            
    def on_window_main_button_press_event(self, widget, event):
        """
        Implement back/forward navigation via mouse navigation keys using
        the same button codes as used in Nautilus.
        """
        if (event.button == MOUSE_EVENT_BACK_BUTTON and
            self.active_pane and
            hasattr(self.active_pane, 'navigation_bar') and
            not self.active_pane.navigation_bar.has_id(NavButtons.PURCHASE)):
            self.on_navhistory_back_action_activate()
        elif (event.button == MOUSE_EVENT_FORWARD_BUTTON and
            self.active_pane and
            hasattr(self.active_pane, 'navigation_bar') and
            not self.active_pane.navigation_bar.has_id(NavButtons.PURCHASE)):
            self.on_navhistory_forward_action_activate()
        
    def on_view_switcher_changed(self, view_switcher, view_id, channel):
        LOG.debug("view_switcher_activated: %s %s" % (view_switcher, view_id))

        # set active pane
        self.active_pane = self.view_manager.get_view_widget(view_id)

        # set menu sensitve
        self.menuitem_view_supported_only.set_sensitive(self.active_pane != None)
        self.menuitem_view_all.set_sensitive(self.active_pane != None)
        # set menu state
        if self.active_pane:
            self._block_menuitem_view = True
            if not self.active_pane.apps_filter:
                self.menuitem_view_all.set_sensitive(False)
                self.menuitem_view_supported_only.set_sensitive(False)
            elif self.active_pane.apps_filter.get_supported_only():
                self.menuitem_view_supported_only.activate()
            else:
                self.menuitem_view_all.activate()
            self._block_menuitem_view = False
        if view_id == ViewPages.AVAILABLE:
            back_action = self.available_pane.nav_history.navhistory_back_action
            forward_action = self.available_pane.nav_history.navhistory_forward_action
            self.menuitem_go_back.set_sensitive(back_action.get_sensitive())
            self.menuitem_go_forward.set_sensitive(forward_action.get_sensitive())
        else:
            self.menuitem_go_back.set_sensitive(False)
            self.menuitem_go_forward.set_sensitive(False)
         # switch to new page
        self.view_manager.set_active_view(view_id)
        if (view_id == ViewPages.INSTALLED and
            not self.installed_pane.loaded and
            not self.installed_pane.get_current_app()):
            self.installed_pane.refresh_apps()
        self.update_app_list_view(channel)
        self.update_status_bar()

    def on_viewswitcher_resized(self, widget, allocation):
        self.view_switcher.width = allocation.width

    def _on_lp_login(self, lp, token):
        self._lp_login_successful = True
        private_archives = self.glaunchpad.get_subscribed_archives()
        self.view_switcher.get_model().channel_manager.feed_in_private_sources_list_entries(
            private_archives)

    def _on_sso_login(self, sso, oauth_result):
        self._sso_login_successful = True
        # consumer key is the openid identifier
        self.scagent.query_available_for_me(oauth_result["token"],
                                            oauth_result["consumer_key"])

    def _available_for_me_result(self, scagent, result_list):
        #print "available_for_me_result", result_list
        from softwarecenter.db.update import add_from_purchased_but_needs_reinstall_data
        available_for_me_query = add_from_purchased_but_needs_reinstall_data(
            result_list, self.db, self.cache)
        self.available_pane.on_previous_purchases_activated(available_for_me_query) 
        
    def on_application_request_action(self, widget, app, addons_install, addons_remove, action):
        """callback when an app action is requested from the appview,
           if action is "remove", must check if other dependencies have to be
           removed as well and show a dialog in that case
        """
        LOG.debug("on_application_action_requested: '%s' %s" % (app, action))
        appdetails = app.get_details(self.db)
        if action == "remove":
            if not dependency_dialogs.confirm_remove(None, self.datadir, app,
                                                     self.db, self.icons):
                    # craft an instance of TransactionFinishedResult to send with the
                    # transaction-stopped signal
                    result = TransactionFinishedResult(None, False)
                    result.pkgname = app.pkgname
                    self.backend.emit("transaction-stopped", result)
                    return
        elif action == "install":
            # If we are installing a package, check for dependencies that will 
            # also be removed and show a dialog for confirmation
            # generic removal text (fixing LP bug #554319)
            if not dependency_dialogs.confirm_install(None, self.datadir, app, 
                                                      self.db, self.icons):
                    # craft an instance of TransactionFinishedResult to send with the
                    # transaction-stopped signal
                    result = TransactionFinishedResult(None, False)
                    result.pkgname = app.pkgname
                    self.backend.emit("transaction-stopped", result)
                    return

        # this allows us to 'upgrade' deb files
        if action == 'upgrade' and app.request and type(app) == DebFileApplication:
            action = 'install'
 
        # action_func is one of:  "install", "remove", "upgrade", "apply_changes"
        action_func = getattr(self.backend, action)
        if action == 'install':
            # the package.deb path name is in the request
            if app.request and type(app) == DebFileApplication:
                debfile_name = app.request
            else:
                debfile_name = None
            action_func(app.pkgname, app.appname, appdetails.icon, debfile_name, addons_install, addons_remove)
        elif callable(action_func):
            action_func(app.pkgname, app.appname, appdetails.icon, addons_install=addons_install, addons_remove=addons_remove)
        else:
            LOG.error("Not a valid action in AptdaemonBackend: '%s'" % action)
            
    def get_icon_filename(self, iconname, iconsize):
        iconinfo = self.icons.lookup_icon(iconname, iconsize, 0)
        if not iconinfo:
            iconinfo = self.icons.lookup_icon(Icons.MISSING_APP, iconsize, 0)
        return iconinfo.get_filename()

    # Menu Items
    def on_menu_file_activate(self, menuitem):
        """Enable/disable install/remove"""
        LOG.debug("on_menu_file_activate")
        # check if we have a pkg for this page
        app = None
        if self.active_pane:
            app = self.active_pane.get_current_app()
        if app is None:
            self.menuitem_install.set_sensitive(False)
            self.menuitem_remove.set_sensitive(False)
            return False
        # wait for the cache to become ready (if needed)
        if not self.cache.ready:
            GObject.timeout_add(100, lambda: self.on_menu_file_activate(menuitem))
            return False
        # update menu items
        pkg_state = None
        error = None
        is_network_available = network_state_is_connected()
        # FIXME:  Use a gtk.Action for the Install/Remove/Buy/Add Source/Update Now action
        #         so that all UI controls (menu item, applist view button and appdetails
        #         view button) are managed centrally:  button text, button sensitivity,
        #         and callback method
        # FIXME:  Add buy support here by implementing the above
        appdetails = app.get_details(self.db)
        if appdetails:
            pkg_state = appdetails.pkg_state
            error = appdetails.error
        if self.active_pane.app_view.is_action_in_progress_for_selected_app():
            self.menuitem_install.set_sensitive(False)
            self.menuitem_remove.set_sensitive(False)
        elif pkg_state == PkgStates.UPGRADABLE or pkg_state == PkgStates.REINSTALLABLE and not error:
            self.menuitem_install.set_sensitive(is_network_available)
            self.menuitem_remove.set_sensitive(True)
        elif pkg_state == PkgStates.INSTALLED:
            self.menuitem_install.set_sensitive(False)
            self.menuitem_remove.set_sensitive(True)
        elif pkg_state == PkgStates.UNINSTALLED and not error:
            self.menuitem_install.set_sensitive(is_network_available)
            self.menuitem_remove.set_sensitive(False)
        elif (not pkg_state and 
              not self.active_pane.is_category_view_showing() and 
              app.pkgname in self.cache and 
              not self.active_pane.app_view.is_action_in_progress_for_selected_app() and
              not error):
            pkg = self.cache[app.pkgname]
            installed = bool(pkg.installed)
            self.menuitem_install.set_sensitive(not installed)
            self.menuitem_remove.set_sensitive(installed)
        else:
            self.menuitem_install.set_sensitive(False)
            self.menuitem_remove.set_sensitive(False)
        self.menuitem_reinstall_purchases.set_sensitive(is_network_available)
        # return False to ensure that a possible GObject.timeout_add ends
        return False

    def on_menuitem_launchpad_private_ppas_activate(self, menuitem):
        from softwarecenter.backend.launchpad import GLaunchpad
        self.glaunchpad = GLaunchpad()
        self.glaunchpad.connect("login-successful", self._on_lp_login)
        from view.logindialog import LoginDialog
        d = LoginDialog(self.glaunchpad, self.datadir, parent=self.window_main)
        d.login()

    def _create_buildin_sso_if_needed(self):
        if not self.sso:
            from softwarecenter.backend.restfulclient import UbuntuSSOlogin
            self.sso = UbuntuSSOlogin()
            self.sso.connect("login-successful", self._on_sso_login)
    def _login_via_buildin_sso(self):
        self._create_buildin_sso_if_needed()
        if "SOFTWARE_CENTER_TEST_REINSTALL_PURCHASED" in os.environ:
            self.scagent.query_available_for_me("dummy", "mvo")
        else:
            from view.logindialog import LoginDialog
            d = LoginDialog(self.sso, self.datadir, parent=self.window_main)
            d.login()

    def _create_dbus_sso_if_needed(self):
        if not self.sso:
            from softwarecenter.backend.login_sso import get_sso_backend
            appname = SOFTWARE_CENTER_NAME_KEYRING
            login_text = SOFTWARE_CENTER_SSO_DESCRIPTION
            self.sso = get_sso_backend(self.window_main.window.xid,
                                       appname, _(login_text))
            self.sso.connect("login-successful", self._on_sso_login)

    def _login_via_dbus_sso(self):
        self._create_dbus_sso_if_needed()
        self.sso.login()

    def _create_scagent_if_needed(self):
        if not self.scagent:
            from softwarecenter.backend.scagent import SoftwareCenterAgent
            self.scagent = SoftwareCenterAgent(xid=self.window_main.window.xid)
            self.scagent.connect("available-for-me", self._available_for_me_result)
            
    def on_menuitem_reinstall_purchases_activate(self, menuitem):
        self.view_switcher.select_available_node()
        self._create_scagent_if_needed()
        # support both buildin or ubuntu-sso-login
        if "SOFTWARE_CENTER_USE_BUILTIN_LOGIN" in os.environ:
            self._login_via_buildin_sso()
        else:
            self._login_via_dbus_sso()
            
    def on_menuitem_deauthorize_computer_activate(self, menuitem):
    
        # FIXME: need Ubuntu SSO username here
        # account_name = get_person_from_config()
        account_name = None
        
        # get a list of installed purchased packages
        installed_purchased_packages = self.db.get_installed_purchased_packages()

        # display the deauthorize computer dialog
        deauthorize = deauthorize_dialog.deauthorize_computer(None,
                                                              self.datadir,
                                                              self.db,
                                                              self.icons,
                                                              account_name,
                                                              installed_purchased_packages)
        if deauthorize:
            # clear the ubuntu SSO token for this account
            # FIXME: this needs to be consolidated - one token is 
            #        aquired for purchase in utils/submit_review.py
            #        the other one in softwarecenter/app.py
            clear_token_from_ubuntu_sso(_("Ubuntu Software Center"))
            clear_token_from_ubuntu_sso(_("Ubuntu Software Center Store"))
            
            # uninstall the list of purchased packages
            # TODO: do we need to check for dependencies and show a removal
            # dialog for that case?  seems not since these are purchased apps
            for pkgname in installed_purchased_packages:
                app = Application(pkgname=pkgname)
                appdetails = app.get_details(self.db)
                self.backend.remove(app.pkgname, app.appname, appdetails.icon)
            
            # TODO: remove the corresponding private PPA sources
            # FIXME: this should really be done using aptdaemon, update this if/when
            #        remove repository support is added to aptdaemon
            # (private-ppa.launchpad.net_commercial-ppa-uploaders*)
            purchased_sources = glob.glob("/etc/apt/sources.list.d/private-ppa.launchpad.net_commercial-ppa-uploaders*")
            for source in purchased_sources:
                print "source: ", source
        
    def on_menuitem_install_activate(self, menuitem):
        app = self.active_pane.get_current_app()
        self.on_application_request_action(self, app, [], [], AppActions.INSTALL)

    def on_menuitem_remove_activate(self, menuitem):
        app = self.active_pane.get_current_app()
        self.on_application_request_action(self, app, [], [], AppActions.REMOVE)
        
    def on_menuitem_close_activate(self, widget):
        gtk.main_quit()

    def on_menu_edit_activate(self, menuitem):
        """
        Check whether the search field is focused and if so, focus some items
        """
        edit_menu_items = [self.menuitem_undo,
                           self.menuitem_redo,
                           self.menuitem_cut, 
                           self.menuitem_copy,
                           self.menuitem_copy_web_link,
                           self.menuitem_paste,
                           self.menuitem_delete,
                           self.menuitem_select_all,
                           self.menuitem_search]
        for item in edit_menu_items:
            item.set_sensitive(False)
        if (self.active_pane and 
            self.active_pane.searchentry and
            self.active_pane.searchentry.flags() & gtk.VISIBLE):
            # undo, redo, cut, copy, paste, delete, select_all sensitive 
            # if searchentry is focused (and other more specific conditions)
            if self.active_pane.searchentry.is_focus():
                if len(self.active_pane.searchentry._undo_stack) > 1:
                    self.menuitem_undo.set_sensitive(True)
                if len(self.active_pane.searchentry._redo_stack) > 0:
                    self.menuitem_redo.set_sensitive(True)
                bounds = self.active_pane.searchentry.get_selection_bounds()
                if bounds:
                    self.menuitem_cut.set_sensitive(True)
                    self.menuitem_copy.set_sensitive(True)
                self.menuitem_paste.set_sensitive(True)
                if self.active_pane.searchentry.get_text():
                    self.menuitem_delete.set_sensitive(True)
                    self.menuitem_select_all.set_sensitive(True)
            # search sensitive if searchentry is not focused
            else:
                self.menuitem_search.set_sensitive(True)

        # weblink
        if self.active_pane:
            app = self.active_pane.get_current_app()
            if app and app.pkgname in self.cache:
                self.menuitem_copy_web_link.set_sensitive(True)

        # details view
        if (self.active_pane and 
            self.active_pane.is_app_details_view_showing()):

            self.menuitem_select_all.set_sensitive(True)
            sel_text = self.active_pane.app_details_view.desc.get_selected_text()

            if sel_text:
                self.menuitem_copy.set_sensitive(True)

    def on_menuitem_undo_activate(self, menuitem):
        self.active_pane.searchentry.undo()
        
    def on_menuitem_redo_activate(self, menuitem):
        self.active_pane.searchentry.redo()

    def on_menuitem_cut_activate(self, menuitem):
        self.active_pane.searchentry.cut_clipboard()

    def on_menuitem_copy_activate(self, menuitem):
        if (self.active_pane and
            self.active_pane.is_app_details_view_showing()):

            self.active_pane.app_details_view.desc.copy_clipboard()

        elif self.active_pane:
            self.active_pane.searchentry.copy_clipboard()

    def on_menuitem_paste_activate(self, menuitem):
        self.active_pane.searchentry.paste_clipboard()

    def on_menuitem_delete_activate(self, menuitem):
        self.active_pane.searchentry.set_text("")

    def on_menuitem_select_all_activate(self, menuitem):
        if (self.active_pane and
            self.active_pane.is_app_details_view_showing()):

            self.active_pane.app_details_view.desc.select_all()
            self.active_pane.app_details_view.desc.grab_focus()

        elif self.active_pane:
            self.active_pane.searchentry.select_region(0, -1)

    def on_menuitem_copy_web_link_activate(self, menuitem):
        app = self.active_pane.get_current_app()
        if app:
            clipboard = gtk.Clipboard()
            clipboard.set_text(self.WEBLINK_URL % app.pkgname)

    def on_menuitem_search_activate(self, widget):
        if self.active_pane:
            self.active_pane.searchentry.grab_focus()
            self.active_pane.searchentry.select_region(0, -1)

    def on_menuitem_software_sources_activate(self, widget):
        #print "on_menu_item_software_sources_activate"
        self.window_main.set_sensitive(False)
        # run software-properties-gtk
        p = subprocess.Popen(
            ["/usr/bin/software-properties-gtk", 
             "-n", 
             "-t", str(self.window_main.window.xid)])
        # Monitor the subprocess regularly
        GObject.timeout_add(100, self._poll_software_sources_subprocess, p)

    def _poll_software_sources_subprocess(self, popen):
        ret = popen.poll()
        if ret is None:
            # Keep monitoring
            return True
        # A return code of 1 means that the sources have changed
        if ret == 1:
            self.run_update_cache()
        self.window_main.set_sensitive(True)
        # Stop monitoring
        return False

    def on_menuitem_about_activate(self, widget):
        self.aboutdialog.set_version(VERSION)
        self.aboutdialog.set_transient_for(self.window_main)
        self.aboutdialog.show()

    def on_menuitem_help_activate(self, menuitem):
        # run yelp
        p = subprocess.Popen(["yelp","ghelp:software-center"])
        # collect the exit status (otherwise we leave zombies)
        GObject.timeout_add_seconds(1, lambda p: p.poll() == None, p)

    def on_menuitem_view_all_activate(self, widget):
        if (not self._block_menuitem_view and
            self.active_pane.apps_filter and
            self.active_pane.apps_filter.get_supported_only()):
            self.active_pane.apps_filter.set_supported_only(False)
            self.active_pane.refresh_apps()

            # update recommended widget counter
            if self.available_pane and self.available_pane.cat_view:
                self.available_pane.cat_view._append_recommendations()

            # update subcategory view
            if (self.available_pane and
                self.available_pane == self.active_pane and
                self.available_pane.subcategories_view and
                self.available_pane.subcategories_view.current_category):
                self.available_pane.subcategories_view._append_subcat_departments(
                    self.available_pane.subcategories_view.current_category,
                    len(self.available_pane.app_view.get_model()))

    def on_menuitem_view_supported_only_activate(self, widget):
        if (not self._block_menuitem_view and
            self.active_pane.apps_filter and
            not self.active_pane.apps_filter.get_supported_only()):
            self.active_pane.apps_filter.set_supported_only(True)
            self.active_pane.refresh_apps()

            # navigate up if the details page is no longer available
            ap = self.active_pane
            if (ap and ap.is_app_details_view_showing and ap.app_details_view.app and
                not self.distro.is_supported(self.cache, None, ap.app_details_view.app.pkgname)):
                if len(ap.app_view.get_model()) == 0:
                    ap.navigation_bar.navigate_up_twice()
                else:
                    ap.navigation_bar.navigate_up()
                ap.on_application_selected(None, None)    

            # navigate up if the list page is empty
            elif (ap and ap.is_applist_view_showing() and 
                len(ap.app_view.get_model()) == 0):
                ap.navigation_bar.navigate_up()
                ap.on_application_selected(None, None)    

            # update recommended widget counter
            if self.available_pane and self.available_pane.cat_view:
                self.available_pane.cat_view._append_recommendations()

            # update subcategory view
            if (self.available_pane and
                self.available_pane == self.active_pane and
                self.available_pane.subcategories_view and
                self.available_pane.subcategories_view.current_category):
                self.available_pane.subcategories_view._append_subcat_departments(
                    self.available_pane.subcategories_view.current_category,
                    len(self.available_pane.app_view.get_model()))

    def on_navhistory_back_action_activate(self, navhistory_back_action=None):
        self.available_pane.nav_history.nav_back()
        self.available_pane._status_text = ""
        self.update_status_bar()
        
    def on_navhistory_forward_action_activate(self, navhistory_forward_action=None):
        self.available_pane.nav_history.nav_forward()
        self.available_pane._status_text = ""
        self.update_status_bar()
            
    def _ask_and_repair_broken_cache(self):
        # wait until the window window is available
        if self.window_main.props.visible == False:
            GObject.timeout_add_seconds(1, self._ask_and_repair_broken_cache)
            return
        if dialogs.confirm_repair_broken_cache(self.window_main,
                                               self.datadir):
            self.backend.fix_broken_depends()

    def _on_notebook_expose(self, widget, event):
        # use availabel pane as the Style source so viewport colours are the same
        # as a real Viewport
        self.available_pane.style.paint_shadow(widget.window,
                                    gtk.STATE_NORMAL,
                                    gtk.SHADOW_IN,
                                    event.area,
                                    widget,
                                    'viewport',
                                    widget.allocation.x,
                                    widget.allocation.y,
                                    widget.allocation.width,
                                    widget.allocation.height)
        return

    def _on_apt_cache_broken(self, aptcache):
        self._ask_and_repair_broken_cache()

    def _on_transaction_finished(self, backend, result):
        """ callback when an application install/remove transaction 
            (or a cache reload) has finished 
        """
        self.cache.open()

    def on_channels_changed(self, backend, res):
        """ callback when the set of software channels has changed """
        LOG.debug("on_channels_changed %s" % res)
        if res:
            # reopen the database, this will ensure that the right signals
            # are send and triggers "refresh_apps"
            # and refresh the displayed app in the details as well
            self.db.reopen()
            self.update_status_bar()

    # helper

    def run_update_cache(self):
        """update the apt cache (e.g. after new sources where added """
        self.backend.reload()

    def update_status_bar(self):
        "Helper that updates the status bar"
        if self.active_pane:
            s = self.active_pane.get_status_text()
        else:
            # FIXME: deal with the pending view status
            s = ""
        self.label_status.set_text(s)

        # update a11y
        if s:
            self.status_box.a11y.set_name(s)
            self.status_box.set_property('can-focus', True)
        else:
            self.status_box.set_property('can-focus', False)
        
    def update_app_list_view(self, channel=None):
        """Helper that updates the app view list """
        if self.active_pane is None:
            return
        if channel is None and self.active_pane.is_category_view_showing():
            return
        if channel:
            self.channel_pane.set_channel(channel)
            self.active_pane.refresh_apps()

    def _on_database_rebuilding_handler(self, is_rebuilding):
        LOG.debug("_on_database_rebuilding_handler %s" % is_rebuilding)
        self._database_is_rebuilding = is_rebuilding

        if is_rebuilding:
            pass
        else:
            # we need to reopen when the database finished updating
            self.db.reopen()

    def setup_database_rebuilding_listener(self):
        """
        Setup system bus listener for database rebuilding
        """
        self._database_is_rebuilding = False
        # get dbus
        try:
            bus = dbus.SystemBus()
        except:
            LOG.exception("could not get system bus")
            return
        # check if its currently rebuilding (most likely not, so we
        # just ignore errors from dbus because the interface
        try:
            proxy_obj = bus.get_object("com.ubuntu.Softwarecenter",
                                       "/com/ubuntu/Softwarecenter")
            iface = dbus.Interface(proxy_obj, "com.ubuntu.Softwarecenter")
            res = iface.IsRebuilding()
            self._on_database_rebuilding_handler(res)
        except Exception ,e:
            LOG.debug("query for the update-database exception '%s' (probably ok)" % e)

        # add signal handler
        bus.add_signal_receiver(self._on_database_rebuilding_handler,
                                "DatabaseRebuilding",
                                "com.ubuntu.Softwarecenter")

    def setup_dbus_or_bring_other_instance_to_front(self, args):
        """ 
        This sets up a dbus listener
        """
        try:
            bus = dbus.SessionBus()
        except:
            LOG.exception("could not initiate dbus")
            return
        # if there is another Softwarecenter running bring it to front
        # and exit, otherwise install the dbus controller
        try:
            proxy_obj = bus.get_object('com.ubuntu.Softwarecenter', 
                                       '/com/ubuntu/Softwarecenter')
            iface = dbus.Interface(proxy_obj, 'com.ubuntu.SoftwarecenterIFace')
            if args:
                iface.bringToFront(args)
            else:
                # None can not be transported over dbus
                iface.bringToFront('nothing-to-show')
            sys.exit()
        except dbus.DBusException:
            bus_name = dbus.service.BusName('com.ubuntu.Softwarecenter',bus)
            self.dbusControler = SoftwarecenterDbusController(self, bus_name)

    def show_available_packages(self, packages):
        """ Show packages given as arguments in the available_pane
            If the list of packages is only one element long show that,
            otherwise turn it into a comma seperated search
        """
        # strip away the apt: prefix
        if packages and packages[0].startswith("apt:///"):
            # this is for 'apt:pkgname' in alt+F2 in gnome
            packages[0] = packages[0].partition("apt:///")[2]
        elif packages and packages[0].startswith("apt://"):
            packages[0] = packages[0].partition("apt://")[2]
        elif packages and packages[0].startswith("apt:"):
            packages[0] = packages[0].partition("apt:")[2]

        # allow s-c to be called with a search term
        if packages and packages[0].startswith("search:"):
            packages[0] = packages[0].partition("search:")[2]
            self.available_pane.navigation_bar.remove_all(animate=False) # animate *must* be false here
            self.view_switcher.set_view(ViewPages.AVAILABLE)
            self.available_pane.notebook.set_current_page(
                self.available_pane.PAGE_APPLIST)
            self.available_pane.searchentry.set_text(" ".join(packages))
            return

        if len(packages) == 1:
            request = packages[0]

            # are we dealing with a path?
            if os.path.exists(request) and not os.path.isdir(request):
                if not request.startswith('/'):
                # we may have been given a relative path
                    request = os.path.join(os.getcwd(), request)
                app = DebFileApplication(request)
                # display a "Loading" spinner until we actually display the
                # details view for the deb file
                self.available_pane.show_appview_spinner(spinner_text=_("Loading"))
            else:
                # package from archive
                # if there is a "/" in the string consider it as tuple
                # of (pkgname, appname) for exact matching (used by
                # e.g. unity
                (pkgname, sep, appname) = packages[0].partition("/")
                app = Application(appname, pkgname)

            @wait_for_apt_cache_ready
            def show_app(self, app):
                # if the pkg is installed, show it in the installed pane
                if (app.pkgname in self.cache and 
                    self.cache[app.pkgname].installed):
                    self.installed_pane.loaded = True
                    self.view_switcher.set_view(ViewPages.INSTALLED)
                    self.installed_pane.loaded = False
                    self.installed_pane.show_app(app)
                    self.available_pane.hide_appview_spinner()
                else:
                    self.view_switcher.set_view(ViewPages.AVAILABLE)
                    self.available_pane.show_app(app)
                    self.available_pane.hide_appview_spinner()

            show_app(self, app)

        if len(packages) > 1:
            # turn multiple packages into a search with ","
            self.available_pane.searchentry.set_text(",".join(packages))
            self.available_pane.notebook.set_current_page(
                self.available_pane.PAGE_APPLIST)

    def restore_state(self):
        if self.config.has_option("general", "size"):
            (x, y) = self.config.get("general", "size").split(",")
            self.window_main.set_default_size(int(x), int(y))
        else:
            # on first launch, specify the default window size to take advantage
            # of the available screen real estate (but set a reasonable limit
            # in case of a crazy-huge monitor)
            screen_height = gtk.gdk.screen_height()
            screen_width = gtk.gdk.screen_width()
            self.window_main.set_default_size(min(int(.85 * screen_width), 1200),
                                              min(int(.85 * screen_height), 800))
        if (self.config.has_option("general", "maximized") and
            self.config.getboolean("general", "maximized")):
            self.window_main.maximize()
        if (self.config.has_option("general", "installed-node-expanded") and
            self.config.getboolean("general", "installed-node-expanded")):
            self.view_switcher.expand_installed_node()
        if (self.config.has_option("general", "sidebar-width")):
            width = int(self.config.get("general", "sidebar-width"))
            self.scrolledwindow_viewswitcher.set_property('width_request', width)

    def save_state(self):
        LOG.debug("save_state")
        # this happens on a delete event, we explicitely save_state() there
        if self.window_main.window is None:
            return
        if not self.config.has_section("general"):
            self.config.add_section("general")
        maximized = self.window_main.window.get_state() & gtk.gdk.WINDOW_STATE_MAXIMIZED
        if maximized:
            self.config.set("general", "maximized", "True")
        else:
            self.config.set("general", "maximized", "False")
            # size only matters when non-maximized
            size = self.window_main.get_size() 
            self.config.set("general","size", "%s, %s" % (size[0], size[1]))
        installed_node_expanded = self.view_switcher.is_installed_node_expanded()
        if installed_node_expanded:
            self.config.set("general", "installed-node-expanded", "True")
        else:
            self.config.set("general", "installed-node-expanded", "False")
        width = self.view_switcher.width
        if width != 1:
            width += 2
        self.config.set("general", "sidebar-width", str(width))
        self.config.write()

    def run(self, args):
        self.window_main.show_all()
        # support both "pkg1 pkg" and "pkg1,pkg2" (and pkg1,pkg2 pkg3)
        if args:
            for (i, arg) in enumerate(args[:]):
                if "," in arg:
                    args.extend(arg.split(","))
                    del args[i]
        self.show_available_packages(args)
        atexit.register(self.save_state)
        SimpleGtkbuilderApp.run(self)