Exemplo n.º 1
0
class GameCenterApp(dbus.service.Object):

    def __init__(self, session_bus):
        dbus.service.Object.__init__(self, session_bus, GAME_CENTER_DBUS_PATH)
        self.conf_db = get_config_file("conf.db")
        self.in_wizard_showing = False

        self.init_ui()

    def init_ui(self):
        self.application = Application()
        self.application.set_default_size(1000, 660)
        self.application.set_skin_preview(get_common_image("frame.png"))
        self.application.set_icon(get_common_image("logo48.png"))
        self.application.add_titlebar(
                ["theme", "menu", "max","min", "close"],
                show_title=False
                )
        self.application.window.set_title(_("Deepin Games"))

        # Init page box.
        self.page_box = gtk.VBox()
        self.page_box.connect('expose-event', self.page_box_render)
        
        # Init page align.
        self.page_align = gtk.Alignment()
        self.page_align.set(0.5, 0.5, 1, 1)
        self.page_align.set_padding(0, 0, 2, 2)
        
        # Append page to switcher.
        self.paned_box = PanedBox(24)
        self.paned_box.add_content_widget(self.page_box)
        self.bottom_tip_bar = BottomTipBar()
        self.bottom_tip_bar.close_button.connect('clicked', lambda w: self.paned_box.bottom_window.hide())
        self.paned_box.add_bottom_widget(self.bottom_tip_bar)

        self.page_align.add(self.paned_box)
        self.application.main_box.pack_start(self.page_align, True, True)
        
        # Init status bar.
        self.statusbar = Statusbar(30)
        status_box = gtk.HBox()

        self.statusbar.status_box.pack_start(status_box, True, True)
        self.application.main_box.pack_start(self.statusbar, False, False)

        self.webview = WebView(COOKIE_FILE)
        webkit.set_web_database_directory_path(CACHE_DIR)
        web_settings = self.webview.get_settings()
        web_settings.set_property("enable-page-cache", True)
        web_settings.set_property("enable-offline-web-application-cache", True)
        #web_settings.set_property("enable-file-access-from-file-uris", True)
        web_settings.set_property("enable-xss-auditor", False)
        web_settings.set_property('enable-universal-access-from-file-uris', True)
        web_settings.set_property("enable-default-context-menu", False)
        self.webview.set_settings(web_settings)
        #self.webview.enable_inspector()
        self.webview.connect('new-window-policy-decision-requested', self.navigation_policy_decision_requested_cb)
        #self.webview.connect('notify::load-status', self.webview_load_status_handler)
        self.webview.connect('notify::title', self.webview_title_changed_handler)
        self.webview.connect('script-alert', self.webview_script_alert_handler)
        self.webview.connect('window-object-cleared', self.webview_window_object_cleared)
        #self.webview.connect('load-progress-changed', self.load_progress)
        
        self.home_url = urllib.basejoin(GAME_CENTER_SERVER_ADDRESS, 'game/?hl=%s' % LANGUAGE)
        self.network_failed_box = NetworkConnectFailed(self.check_network_connection)
        self.check_network_connection()
        #self.page_box.add(self.network_failed_box)

        self.navigatebar = Navigatebar(
                [
                (None, _("Home"), self.show_home_page),
                (None, _("Topics"), self.show_subject_page),
                (None, _("My Games"), self.show_mygame_page),
                ],
                font_size = 11,
                padding_x = 5,
                padding_y = 16,
                vertical=False,
                item_normal_pixbuf=DynamicPixbuf(get_common_image('top/nav_normal.png')),
                item_hover_pixbuf=DynamicPixbuf(get_common_image('top/nav_hover.png')),
                item_press_pixbuf=DynamicPixbuf(get_common_image('top/nav_press.png')),
                )
        self.navigatebar.set_size_request(-1, 56)
        self.navigatebar_align = gtk.Alignment(0, 0, 1, 1)
        self.navigatebar_align.set_padding(0, 0, 4, 0)
        self.navigatebar_align.add(self.navigatebar)
        self.application.titlebar.set_size_request(-1, 56)
        self.application.titlebar.left_box.pack_start(self.navigatebar_align, True, True)
        self.application.window.add_move_event(self.navigatebar)

        self.about_dialog = AboutDialog(_('About us'))
        self.about_dialog.set_transient_for(self.application.window)

        # Init menu.
        #if LANGUAGE == 'en_US':
            #menu_min_width = 185
        #else:
            #menu_min_width = 150

        menu = Menu(
            [
             (None, _("Clear all cached data"), self.clean_download_cache),
             (None, _("See what's new"), lambda : self.show_wizard_win()),
             (None, _("About us"), self.show_about_dialog),
             (None, _("Quit"), lambda: gtk.main_quit()),
             ],
            is_root_menu=True,
            #menu_min_width=menu_min_width,
            )
        self.application.set_menu_callback(
            lambda button:
                menu.show(
                get_widget_root_coordinate(button, WIDGET_POS_BOTTOM_LEFT),
                (button.get_allocation().width, 0)))
        
        self.no_favorite_html_path = os.path.join(static_dir, "error-no-favorite.html")
        self.no_recent_html_path = os.path.join(static_dir, "error-no-recent.html")
        self.mygame_frame_path = os.path.join(static_dir, "mygame-frame.html")
        self.gallery_html_path = os.path.join(static_dir, 'game-mygame.html')

        skin_config.connect('theme-changed', self.theme_changed_handler)
        global_event.register_event('show-message', self.update_message)

    def page_box_render(self, widget, event):
        cr = widget.window.cairo_create()
        rect = widget.get_allocation()
        cr.set_source_rgb(1, 1, 1)
        cr.rectangle(*rect)
        cr.fill()

    def check_network_connection(self):
        if is_network_connected():
            self.network_connected_flag = True
            self.webview.load_uri(self.home_url)
            self.switch_page_view(self.webview)
        else:    
            self.network_connected_flag = False
            self.switch_page_view(self.network_failed_box)
    
    def switch_page_view(self, box):
        container_remove_all(self.page_box)
        self.page_box.add(box)

    def load_progress(self, webview, progress):
        print progress

    def webview_window_object_cleared(self, webview, frame, context, window_object):
        ctx = jswebkit.JSContext(frame.get_global_context())
        window = ctx.EvaluateScript("window")
        window.css_color = skin_config.theme_name
        location = window.location.href
        parse_result = urlparse.urlparse(location)

        frame.get_web_view().execute_script('var global_l18n_str = %s' % json.dumps({
                'my_favorites': _('My favorites'),
                'my_recent': _('My recents'),
                },
                encoding='UTF-8',
                ensure_ascii=False,
                ))
        frame.get_web_view().execute_script('var global_language = %s' %
                json.dumps(LANGUAGE, encoding='UTF-8', ensure_ascii=False))

        if parse_result.path == self.no_favorite_html_path or parse_result.path == self.no_recent_html_path:
            window.css_language = LANGUAGE

    def update_message(self, message, hide_timeout=0):
        if not self.paned_box.bottom_window.is_visible():
            self.paned_box.bottom_window.show()
        if isinstance(message, list) and len(message) == 3:
            self.bottom_tip_bar.update_info(*message)
        else:
            self.bottom_tip_bar.update_info(message)
        if hide_timeout != 0:
            gtk.timeout_add(hide_timeout, lambda:self.paned_box.bottom_window.hide())
    
    def ready_show(self):    
        if not utils.is_wizard_showed():
            self.in_wizard_showing = True
            self.show_wizard_win(True, callback=self.wizard_callback)
            utils.set_wizard_showed()
        else:    
            self.application.window.show_all()
        gtk.main()

    def show_wizard_win(self, show_button=False, callback=None):    

        self.wizard_win = Wizard(
            [get_common_locale_image('wizard', '%s.png' % i) for i in range(3)],
            (
                get_common_image('wizard/dot_normal.png'), 
                get_common_image('wizard/dot_active.png'),
            ),
            (
                get_common_locale_image('wizard', 'start_normal.png'), 
                get_common_locale_image('wizard', 'start_press.png'), 
            ),
            show_button,
            callback
            )
        self.wizard_win.show_all()
        
    def wizard_callback(self):
        self.in_wizard_showing = False
        self.application.window.show_all()
        gtk.timeout_add(200, self.application.raise_to_top)

    def clean_download_cache(self):
        info = {
                'file_num':0,
                'total_size':0
                }
        downloads_dir = os.path.join(CACHE_DIR, 'downloads')
        appids =  os.listdir(downloads_dir)
        for appid in appids:
            files = os.listdir(os.path.join(downloads_dir, appid))
            for f in files:
                if f.endswith('.swf'):
                    swf_path = os.path.join(downloads_dir, appid, f)
                    info['file_num'] += 1
                    info['total_size'] += os.path.getsize(swf_path)
                    os.remove(os.path.join(downloads_dir, appid, f))
        
        if info['file_num']:
            cache_cleaned_message = _('%s files are deleted and %s disk space is freed.') % (
                    info['file_num'], utils.get_human_size(info['total_size']))
        else:
            cache_cleaned_message = _('Your game cache is empty.')
        global_event.emit('show-message', cache_cleaned_message, 5000)

    def show_about_dialog(self):
        self.about_dialog.show_all()

    def theme_changed_handler(self, widget, name):
        self.webview.execute_script('change_color_theme(%s)' %
            json.dumps(name, encoding="UTF-8", ensure_ascii=False))
        self.webview.execute_script('$("#game-gallery").get(0).contentWindow.change_color_theme(%s)' %
            json.dumps(name, encoding="UTF-8", ensure_ascii=False))
        self.webview.execute_script('alert("scroll_top://" + $($("#game-gallery").get(0).contentWindow.document.body).scrollTop())')

    def send_event(self, data=0):
        press_event = gtk.gdk.Event(gtk.gdk.BUTTON_PRESS)
        press_event.window = self.webview.window
        press_event.x = 1062.0
        press_event.y = 35.0 + int(data) + 20.0
        press_event.button = 1

        release_event = gtk.gdk.Event(gtk.gdk.BUTTON_RELEASE)
        release_event.window = self.webview.window
        release_event.x = 1062.0
        release_event.y = 35.0 + int(data) + 20.0
        release_event.button = 1

        self.webview.event(press_event)
        self.webview.event(release_event)
        self.webview.window.invalidate_rect(self.webview.allocation, True)

    def webview_message_handler(self, info):
        info = info.split('://')
        if len(info) == 2:
            order, data = info

            if order == 'play':
                self.show_play(data)

            elif order == 'star':
                self.toggle_favorite(data)

            elif order == 'local':
                if data == 'recent':
                    self.show_recent_page()
                elif data == 'star':
                    self.show_favorite_page()

            elif order == 'document_ready' and data == 'game_gallery':
                self.document_ready()
                
            elif order == 'onload' and data == 'game_gallery':
                gtk.timeout_add(200, self.fresh_favotite_status)

            elif order == 'onload' and data == 'local_game_gallery':
                self.webview.execute_script('$("#game-gallery").get(0).contentWindow.set_right_menu()')
                gtk.timeout_add(200, self.fresh_favotite_status)

            elif order == 'onload' and data == 'main_frame':
                gtk.timeout_add(200, self.show_favorite_page)

            elif order == 'onload' and data == 'footer':
                self.webview.execute_script('if(infos){append_data_to_gallery(infos);}')

            elif order == 'favorite':
                record_info.record_favorite(data, self.conf_db)
                FetchInfo(data).start()
                favorite_animation(self.application.window)

            elif order == 'unfavorite':
                record_info.remove_favorite(data, self.conf_db)

            elif order == 'local_action':
                info = data.split('-')
                if len(info) == 2:
                    action_type= info[0]
                    appid = info[1]
                    if action_type == 'favorite':
                        record_info.remove_favorite(appid, self.conf_db)
                        utils.ThreadMethod(utils.send_analytics, ('unfavorite', appid)).start()
                        #var favorite_url = 'http://' + location.host + '/game/analytics/?type=unfavorite&appid=' + id;
                        self.webview.execute_script('if(infos){infos_remove(%s);}else{gallery_change(%s);}' % (
                                json.dumps(appid, encoding="UTF-8", ensure_ascii=False),
                                json.dumps(self.no_favorite_html_path, encoding="UTF-8", ensure_ascii=False),
                                ))
                    elif action_type == 'recent':
                        record_info.remove_recent_play(appid, self.conf_db)
                        self.webview.execute_script('if(infos){infos_remove(%s);}else{gallery_change(%s);}' % (
                                json.dumps(appid, encoding="UTF-8", ensure_ascii=False),
                                json.dumps(self.no_recent_html_path, encoding="UTF-8", ensure_ascii=False),
                                ))

            elif order == 'scroll_top':
                self.send_event(data)

    def navigation_policy_decision_requested_cb(self, web_view, frame, request, navigation_action, policy_decision):
        uri = request.get_uri()
        if uri.startswith('http://') or uri.startswith('https://'):
            return False
        else:
            self.webview_message_handler(uri)
            return True

    def webview_script_alert_handler(self, widget, frame, uri, data=None):
        self.webview_message_handler(uri)
        return True

    def webview_title_changed_handler(self, webview, data=None):
        title = webview.get_title()
        if title:
            self.webview_message_handler(title)

    def fresh_favotite_status(self):
        if os.path.exists(self.conf_db):
            data = utils.load_db(self.conf_db)
            if data.get('favorite'):
                for id in data['favorite']:
                    self.webview.execute_script("change_favorite_status(%s, 'ilike')" %
                        json.dumps(id, encoding="UTF-8", ensure_ascii=False))

    def webview_load_status_handler(self, widget=None, status=None):
        load_status = widget.get_load_status()
        if load_status == webkit.LOAD_FINISHED:
            self.webview.execute_script("$('#game-gallery').contents().find('#grid span span').removeClass('ilike')")
            self.webview.execute_script("$('#game-gallery').contents().find('#grid span span').addClass('like')")

    def document_ready(self):
        self.webview.execute_script("$('#game-gallery').contents().find('#grid span span').removeClass('ilike')")
        self.webview.execute_script("$('#game-gallery').contents().find('#grid span span').addClass('like')")

    def show_play(self, data):
        data = data.split(',')
        player_path = os.path.join(get_parent_dir(__file__), 'deepin-game-center.py')
        order = ['python2', player_path]
        order.append('-p')
        order.append(','.join(data))
        try:
            self.p = subprocess.Popen(order, stderr=subprocess.STDOUT, shell=False)
        except OSError:    
            order[0] = 'python'
            self.p = subprocess.Popen(order, stderr=subprocess.STDOUT, shell=False)


    #def mute_handler(self, widget, data=None):
        #active = widget.get_active()
        #current_sink = pypulse.get_fallback_sink_index()
        #if current_sink is not None:
            #pypulse.PULSE.set_output_mute(current_sink, active)

    def print_info(self, info_type, info):
        if info:
            print info_type, info

    def toggle_favorite(self, data):
        print "toggle favorite"

    def show_home_page(self):
        self.webview.load_uri(self.home_url)

    def show_subject_page(self):
        self.subject_url = urllib.basejoin(GAME_CENTER_SERVER_ADDRESS, 'game/subjects/?hl=%s' % LANGUAGE)
        self.webview.load_uri(self.subject_url)

    def show_mygame_page(self):
        self.webview.open('file://' + self.mygame_frame_path)
        
    def show_favorite_page(self):
        downloads_dir = os.path.join(CACHE_DIR, 'downloads')
        if os.path.exists(self.conf_db):
            data = utils.load_db(self.conf_db)
            if data.get('favorite'):
                infos = []
                favorite_list = data['favorite']
                for id in favorite_list:
                    try:
                        info_js_path = os.path.join(downloads_dir, str(id), 'info.json')
                        info = json.load(open(info_js_path))
                        info['index_pic_url'] = os.path.join(downloads_dir, str(id), info['index_pic_url'].split('/')[-1])
                        #info['swf_game'] = os.path.join(downloads_dir, str(id), info['swf_game'].split('/')[-1])
                        info['swf_game'] = urlparse.urlparse(info['swf_game']).path[1:]
                        info['type'] = 'favorite'
                        infos.append(info)
                    except Exception, e:
                        print "Load favorite page error:", e
                if infos:
                    self.webview.execute_script('var infos=%s' % 
                            json.dumps(infos, encoding="UTF-8", ensure_ascii=False))
                    self.webview.execute_script("gallery_change(%s)" %
                            json.dumps(self.gallery_html_path, encoding="UTF-8", ensure_ascii=False))
                    return

        self.webview.execute_script("gallery_change(%s)" %
                json.dumps(self.no_favorite_html_path, encoding="UTF-8", ensure_ascii=False))
Exemplo n.º 2
0
class DeepinSoftwareCenter(dbus.service.Object, Logger):
    '''
    class docs
    '''

    pages = ['home', 'upgrade', 'uninstall', 'install']

    def __init__(self, session_bus, arguments):
        '''
        init docs
        '''
        dbus.service.Object.__init__(self, session_bus, DSC_FRONTEND_PATH)
        Logger.__init__(self)

        self.simulate = "--simulate" in arguments

        global debug_flag
        debug_flag = "--debug" in arguments
        self.in_wizard_showing = False
        self.init_hide = False

    def exit(self):
        gtk.main_quit()

    def open_download_directory(self):
        run_command("xdg-open %s" % get_software_download_dir())

    def switch_page(self, page):
        switch_page(self.page_switcher, self.page_box, page, self.detail_page)

    def show_home_page(self):
        if self.detail_page and self.home_page:
            self.switch_page(self.home_page)

    def show_upgrade_page(self):
        if self.detail_page and self.upgrade_page:
            self.switch_page(self.upgrade_page)

    def show_uninstall_page(self):
        if self.detail_page and self.uninstall_page:
            self.switch_page(self.uninstall_page)

    def show_install_page(self):
        if self.detail_page and self.install_page:
            self.switch_page(self.install_page)

    @dbus.service.method(DSC_FRONTEND_NAME, in_signature="s", out_signature="")
    def show_page(self, key):
        try:
            index = self.pages.index(key)
            if index != self.navigatebar.get_index():
                method = "show_%s_page" % key
                getattr(self, method)()
                self.navigatebar.set_index(index)
        except:
            print "Unknow page:", key

    def init_ui(self):
        self.loginfo("Init ui")
        # Init application.
        self.application = Application(
            resizable=False,
            destroy_func=self.application_close_window,
            )
        self.application.set_default_size(888, 634)
        self.application.set_skin_preview(utils.get_common_image("frame.png"))
        self.application.set_icon(utils.get_common_image("logo48.png"))
        self.application.add_titlebar(
                ["theme", "menu", "min", "close"],
                show_title=False
                )
        self.application.window.set_title(_("Deepin Store"))
        self.application.window.connect("delete-event", self.application_close_window)

        # Init page box.
        self.page_box = gtk.VBox()

        # Init page switcher.
        self.page_switcher = HSlider(200)
        self.page_switcher.append_page(self.page_box)
        self.page_switcher.set_to_page(self.page_box)

        # Init page align.
        self.page_align = gtk.Alignment()
        self.page_align.set(0.5, 0.5, 1, 1)
        self.page_align.set_padding(0, 0, 2, 2)

        # Append page to switcher.
        self.paned_box = PanedBox(24)
        self.paned_box.add_content_widget(self.page_switcher)
        self.bottom_tip_bar = BottomTipBar()
        self.bottom_tip_bar.close_button.connect('clicked', lambda w: self.paned_box.bottom_window.hide())
        self.paned_box.add_bottom_widget(self.bottom_tip_bar)
        self.page_align.add(self.paned_box)
        self.application.main_box.pack_start(self.page_align, True, True)

        # Init status bar.
        self.statusbar = Statusbar(24)
        status_box = gtk.HBox()
        self.message_box = gtk.HBox()

        self.message_label = Label("", enable_gaussian=True)
        label_align = gtk.Alignment()
        label_align.set(0.0, 0.5, 0, 0)
        label_align.set_padding(0, 0, 10, 0)
        label_align.add(self.message_label)
        self.message_box.pack_start(label_align)

        join_us_button = LinkButton(_("Join us"), "http://www.linuxdeepin.com/joinus/job")
        join_us_button_align = gtk.Alignment()
        join_us_button_align.set(0.5, 0.5, 0, 0)
        join_us_button_align.set_padding(0, 3, 0, 10)
        join_us_button_align.add(join_us_button)
        status_box.pack_start(self.message_box, True, True)
        status_box.pack_start(join_us_button_align, False, False)
        self.statusbar.status_box.pack_start(status_box, True, True)
        self.application.main_box.pack_start(self.statusbar, False, False)

        # Init navigatebar.
        self.detail_page = None
        self.home_page = None
        self.upgrade_page = None
        self.uninstall_page = None
        self.install_page = None

        self.navigatebar = Navigatebar(
                [
                (DynamicPixbuf(utils.get_common_image("navigatebar/nav_home.png")), _("Home"), self.show_home_page),
                (DynamicPixbuf(utils.get_common_image("navigatebar/nav_update.png")), _("Upgrade"), self.show_upgrade_page),
                (DynamicPixbuf(utils.get_common_image("navigatebar/nav_uninstall.png")), _("Uninstall"), self.show_uninstall_page),
                (DynamicPixbuf(utils.get_common_image("navigatebar/nav_download.png")), _("Installation"), self.show_install_page),
                ],
                font_size = 11,
                padding_x = 2,
                padding_y = 2,
                vertical=False,
                item_hover_pixbuf=DynamicPixbuf(utils.get_common_image("navigatebar/nav_hover.png")),
                item_press_pixbuf=DynamicPixbuf(utils.get_common_image("navigatebar/nav_press.png")),
                )
        self.navigatebar.set_size_request(-1, 56)
        self.navigatebar_align = gtk.Alignment(0, 0, 1, 1)
        self.navigatebar_align.set_padding(0, 0, 4, 0)
        self.navigatebar_align.add(self.navigatebar)
        self.application.titlebar.set_size_request(-1, 56)
        self.application.titlebar.left_box.pack_start(self.navigatebar_align, True, True)
        self.application.window.add_move_event(self.navigatebar)

        # Init menu.
        if LANGUAGE == 'en_US':
            menu_min_width = 185
        else:
            menu_min_width = 150
        menu = Menu(
            [
             (None, _("Refresh package lists"), lambda:global_event.emit('start-update-list')),
             (None, _("Open download directory"), self.open_download_directory),
             (None, _("Clear up cached packages"), self.clean_download_cache),
             (None, _("View new features"), lambda : self.show_wizard_win()),
             (self.get_pixbuf_group("menu", "setting"), _("Preferences"), self.show_preference_dialog),
             (self.get_pixbuf_group("menu", "close"), _("Quit"), self.exit),
             ],
            is_root_menu=True,
            menu_min_width=menu_min_width,
            )
        self.application.set_menu_callback(
            lambda button:
                menu.show(
                get_widget_root_coordinate(button, WIDGET_POS_BOTTOM_LEFT),
                (button.get_allocation().width, 0)))

        self.preference_dialog = DscPreferenceDialog()

        if hasattr(self, 'recommend_status'):
            self.init_home_page(self.recommend_status)
        else:
            self.init_home_page()

    def get_pixbuf_group(self, folder, name):
        return (app_theme.get_pixbuf("%s/%s_normal.png" % (folder, name)),
                app_theme.get_pixbuf("%s/%s_hover.png" % (folder, name)),
                app_theme.get_pixbuf("%s/%s_disable.png" % (folder, name)),
                )

    def application_close_window(self, widget=None, event=None):
        self.application.window.hide_all()
        gtk.main_quit()

        return True

    def upgrade_finish_action(self, pkg_info_list):
        return
        """
        if len(pkg_info_list) > 0:
            # Delete items from treeview.
            upgraded_items = []

            for (pkg_name, marked_delete, marked_install, marked_upgrade) in pkg_info_list:
                for item in self.upgrade_page.upgrade_treeview.visible_items:
                    if item.pkg_name == pkg_name:
                        upgraded_items.append(item)
                        break

            print upgraded_items
            self.upgrade_page.upgrade_treeview.delete_items(upgraded_items)
            print len(self.upgrade_page.upgrade_treeview.visible_items)
        """

    def show_preference_dialog(self):
        self.preference_dialog.show_all()

    def ready_show(self):
        if utils.is_first_started():
            utils.set_first_started()
            self.in_wizard_showing = True
            self.show_wizard_win(True, callback=self.wizard_callback)
            self.init_ui()
        else:
            self.init_ui()
            if not self.init_hide:
                self.application.window.show_all()
        #self.paned_box.bottom_window.set_composited(True)

    def show_wizard_win(self, show_button=False, callback=None):
        program_dir = get_parent_dir(__file__, 2)
        wizard_dir = os.path.join(program_dir, 'wizard', LANGUAGE)
        if not os.path.exists(wizard_dir):
            wizard_dir = os.path.join(program_dir, 'wizard', 'en_US')
        wizard_root_dir = os.path.dirname(wizard_dir)

        self.wizard = Wizard(
            [os.path.join(wizard_dir, "%d.png" % i) for i in range(3)],
            (os.path.join(wizard_root_dir, "dot_normal.png"),
             os.path.join(wizard_root_dir, "dot_active.png"),
             ),
            (os.path.join(wizard_dir, "start_normal.png"),
             os.path.join(wizard_dir, "start_press.png"),
             ),
            show_button,
            callback
            )
        self.wizard.set_icon(utils.get_common_image_pixbuf("logo48.png"))
        if not self.init_hide:
            self.wizard.show_all()

    def wizard_callback(self):
        self.in_wizard_showing = False
        self.application.window.show_all()
        gtk.timeout_add(200, self.application.raise_to_top)

    def init_home_page(self, recommend_status="publish"):

        # Init DBus.
        self.system_bus = dbus.SystemBus()
        bus_object = self.system_bus.get_object(DSC_SERVICE_NAME, DSC_SERVICE_PATH)
        self.bus_interface = dbus.Interface(bus_object, DSC_SERVICE_NAME)
        # Say hello to backend.
        #self.bus_interface.say_hello(self.simulate)
        self.set_software_download_dir()
        self.inhibit_obj = InhibitObject()

        self.loginfo("Init data manager")

        # Init data manager.
        self.data_manager = DataManager(self.bus_interface, debug_flag)

        # Init packages status
        self.packages_status = {}

        # Init home page.
        self.home_page = HomePage(self.data_manager, recommend_status)

        # Init switch page.
        self.switch_page(self.home_page)

        self.in_update_list = False

        self.init_backend()

    def init_backend(self):

        # Init detail view.
        self.detail_page = DetailPage(self.data_manager)

        self.page_switcher.append_page(self.detail_page)

        log("Init pages.")

        self.loginfo("Init pages")
        self.upgrade_page = UpgradePage(self.bus_interface, self.data_manager, self.preference_dialog)
        self.uninstall_page = UninstallPage(self.bus_interface, self.data_manager)
        self.install_page = InstallPage(self.bus_interface, self.data_manager)


        log("Handle global event.")

        # Handle global event.
        global_event.register_event("install-pkg", lambda pkg_names: install_pkg(
            self.bus_interface, self.install_page, pkg_names, self.application.window))
        global_event.register_event("upgrade-pkg", self.upgrade_pkgs)
        global_event.register_event("uninstall-pkg", lambda pkg_name, purge_flag: self.uninstall_pkg(pkg_name, purge_flag))
        global_event.register_event("stop-download-pkg", self.bus_interface.stop_download_pkg)
        global_event.register_event("switch-to-detail-page", lambda pkg_name : switch_to_detail_page(self.page_switcher, self.detail_page, pkg_name))
        global_event.register_event("switch-from-detail-page", lambda : switch_from_detail_page(self.page_switcher, self.detail_page, self.page_box))
        global_event.register_event("remove-wait-action", self.bus_interface.RemoveWaitMissions)
        global_event.register_event("remove-wait-download", self.bus_interface.remove_wait_downloads)
        global_event.register_event("request-clear-action-pages", request_clear_action_pages)
        global_event.register_event("request-stop-install-actions", request_stop_install_actions)
        global_event.register_event("request-clear-failed-action", request_clear_failed_action)
        global_event.register_event("update-upgrade-notify-number", lambda number: update_navigatebar_number(self.navigatebar, 1, number))
        global_event.register_event("update-install-notify-number", lambda number: update_navigatebar_number(self.navigatebar, 3, number))
        global_event.register_event("jump-to-category",
                                    lambda first_category_name, second_category_name:
                                    jump_to_category(self.page_switcher,
                                                     self.page_box,
                                                     self.home_page,
                                                     self.detail_page,
                                                     first_category_name,
                                                     second_category_name))
        global_event.register_event("grade-pkg", lambda pkg, star: grade_pkg(self.application.window, pkg, star))
        global_event.register_event("set-cursor", lambda cursor: set_cursor(self.application.window, cursor))
        global_event.register_event("show-message", self.update_status_bar_message)
        global_event.register_event("start-pkg", lambda alias_name, desktop_infos, offset: start_pkg(
            alias_name, desktop_infos, offset, self.application.window))
        global_event.register_event("show-pkg-name-tooltip", lambda pkg_name: show_tooltip(self.application.window, pkg_name))
        global_event.register_event("hide-pkg-name-tooltip", lambda :tool_tip.hide())
        global_event.register_event("update-current-status-pkg-page", update_current_status_pkg_page)
        global_event.register_event('start-change-mirror', self.change_mirror_action)
        global_event.register_event('download-directory-changed', self.set_software_download_dir)
        global_event.register_event('vote-send-success', lambda p: vote_send_success_callback(p, self.application.window))
        global_event.register_event('vote-send-failed', lambda p: vote_send_failed_callback(p, self.application.window))
        global_event.register_event('max-download-number-changed', self.init_download_manager)
        global_event.register_event('update-list-finish', self.update_list_finish)
        global_event.register_event('start-update-list', self.update_list_handler)
        global_event.register_event("upgrade-finish-action", self.upgrade_finish_action)
        global_event.register_event("upload-error-log", self.exec_upload_error_log)

        self.bus_interface.connect_to_signal(
                signal_name="update_signal",
                handler_function=lambda messages: message_handler(messages,
                                         self.bus_interface,
                                         self.upgrade_page,
                                         self.uninstall_page,
                                         self.install_page,
                                         self.home_page,
                                         self.inhibit_obj,
                                         ),
                )
        glib.timeout_add(1000, lambda : clear_action_pages(self.bus_interface, self.upgrade_page, self.uninstall_page, self.install_page))
        glib.timeout_add(1000, lambda : clear_install_stop_list(self.install_page))
        glib.timeout_add(1000, lambda : clear_failed_action(self.install_page, self.upgrade_page))

        #self.init_download_manager()

        #self.request_update_list()
        self.upgrade_page.fetch_upgrade_info(utils.get_backend_running())

    def change_mirror_action(self, mirror):
        repo_urls = mirror.get_repo_urls()
        self.bus_interface.change_source_list(
            repo_urls,
            reply_handler=lambda :self.handle_mirror_change_reply(mirror),
            error_handler=lambda e:handle_dbus_error("change_source_list", e)
            )

    def exec_upload_error_log(self):
        SendErrorLog().start()

    @dbus.service.method(DSC_FRONTEND_NAME, in_signature="sb", out_signature="")
    def uninstall_pkg(self, pkg_name, purge_flag):
        self.bus_interface.uninstall_pkg(pkg_name, purge_flag,
                reply_handler=lambda :handle_dbus_reply("uninstall_pkg"),
                error_handler=lambda e:handle_dbus_error("uninstall_pkg", e))
        SendUninstallCount(pkg_name).start()

        self.install_page.delete_item_match_pkgname(pkg_name)

    def init_download_manager(self, v=5):
        self.bus_interface.init_download_manager(
                v,
                reply_handler=lambda :self.init_download_manager_handler(),
                error_handler=lambda e:handle_dbus_error("init_download_manager", e))

    def init_download_manager_handler(self):
        self.dbus_request_status()
        self.loginfo("Init download manager")

    def dbus_request_status(self):
        self.bus_interface.request_status(
                reply_handler=lambda reply: request_status_reply_hander(reply, self.install_page, self.upgrade_page, self.uninstall_page),
                error_handler=lambda e:handle_dbus_error("request_status", e),
                )

    def set_software_download_dir(self):
        self.bus_interface.set_download_dir(
                get_software_download_dir(),
                reply_handler=lambda :handle_dbus_reply("set_download_dir"),
                error_handler=lambda e:handle_dbus_error("set_download_dir", e))

    def update_list_handler(self):
        self.show_page("upgrade")
        if not self.in_update_list:
            self.request_update_list()
            global_event.emit('show-updating-view')

    def update_list_finish(self):
        try:
            self.hide_dialog('update_list_dialog')
        except:
            pass
        self.in_update_list = False
        self.data_manager.init_cache_soft_db()

    def hide_dialog(self, name):
        getattr(self, name).hide_all()

    def show_dialog(self, name):
        getattr(self, name).show_all()

    def handle_mirror_change_reply(self, mirror):
        global_event.emit("mirror-backend-changed", mirror)

    def update_status_bar_message(self, message, hide_timeout=0):
        if not self.paned_box.bottom_window.is_visible():
            self.paned_box.bottom_window.show()
        if isinstance(message, list) and len(message) == 4:
            self.bottom_tip_bar.update_info(message[0], message[2], message[3])
            self.bottom_tip_bar.update_end_info(message[1])
        elif isinstance(message, list) and len(message) == 3:
            self.bottom_tip_bar.update_info(*message)
            self.bottom_tip_bar.update_end_info("")
        elif isinstance(message, list) and len(message) == 2:
            self.bottom_tip_bar.update_info(message[0])
            self.bottom_tip_bar.update_end_info(message[1])
        else:
            self.bottom_tip_bar.update_info(message)
            self.bottom_tip_bar.update_end_info("")
        if hide_timeout != 0:
            gtk.timeout_add(hide_timeout, lambda:self.paned_box.bottom_window.hide())

    def request_update_list(self):
        self.in_update_list = True
        self.bus_interface.start_update_list(
                reply_handler=lambda :handle_dbus_reply("start_update_list"),
                error_handler=lambda e:handle_dbus_error("start_update_list", e),)

    def upgrade_pkgs(self, pkg_names):
        self.bus_interface.upgrade_pkgs_with_new_policy(
                pkg_names,
                reply_handler=lambda :handle_dbus_reply("upgrade_pkgs"),
                error_handler=lambda e:handle_dbus_error("upgrade_pkgs", e))
        return False

    def clean_download_cache(self):
        self.bus_interface.clean_download_cache(
                reply_handler=self.clean_download_cache_reply,
                error_handler=lambda e:handle_dbus_error("clean_download_cache", e),
                )

    def clean_download_cache_reply(obj, result):
        num, size = result
        if num != 0:
            message = _("You have cleared up %s packages and saved %s of space.") % (num, bit_to_human_str(size))
        else:
            message = _("Your system cache is empty.")
        global_event.emit("show-message", message, 5000)

    def run(self):
        self.ready_show()
        gtk.main()

        # Send exit request to backend when frontend exit.
        self.bus_interface.request_quit(
                reply_handler=lambda :handle_dbus_reply("request_quit"),
                error_handler=lambda e:handle_dbus_error("request_quit", e))

        # Remove id from config file.
        data_exit()
        self.loginfo('Data id removed')

    @dbus.service.method(DSC_FRONTEND_NAME, in_signature="", out_signature="")
    def request_exit(self):
        self.exit()
        self.bus_interface.request_quit(
                reply_handler=lambda :handle_dbus_reply("request_quit"),
                error_handler=lambda e:handle_dbus_error("request_quit", e))
        data_exit()
        self.loginfo('Data id removed')

    @dbus.service.method(DSC_FRONTEND_NAME, in_signature="as", out_signature="")
    def install_pkgs(self, pkg_names):
        for pkg_name in pkg_names:
            self.install_page.download_wait(pkg_name)
        create_thread(lambda : self.bus_interface.install_pkg(
                                    pkg_names,
                                    reply_handler=lambda :handle_dbus_reply("install_pkg"),
                                    error_handler=lambda e:handle_dbus_error("install_pkg", e))).start()
        for pkg_name in pkg_names:
            SendDownloadCount(pkg_name).start()

    @dbus.service.method(DSC_FRONTEND_NAME, in_signature="", out_signature="")
    def raise_to_top(self):
        if not self.in_wizard_showing:
            self.application.window.show_all()
            self.application.raise_to_top()
        else:
            self.wizard.present()

    @dbus.service.signal(DSC_FRONTEND_NAME)
    def update_signal(self, message):
        pass