def __init__(self, width, height):
     WebView.__init__(self)
     self.__index_file = None
     self.set_size_request(width, height)
     settings = self.get_settings()
     if LANGUAGE == "en":
         settings.set_property("default-font-size", 10)
    def fetch_comment(self):
        if is_network_connected():
            container_remove_all(self.right_comment_box)
            loading_label = Label(_("Loading comments..."))
            loading_label_align = gtk.Alignment(0.5, 0, 0, 0)
            loading_label_align.add(loading_label)
            loading_label_align.set_padding(10, 0, 0, 0)
            self.right_comment_box.pack_start(loading_label_align, False, False)
            web_view = WebView(os.path.join(CONFIG_DIR, "cookie.txt"))
            web_view.connect("new-window-policy-decision-requested", self.open_url)
            web_view.connect('console-message', self.webview_console_message_handler)
            web_view_align = gtk.Alignment()
            web_view_align.set(0.5, 0, 0, 0)
            web_view_align.set_padding(33, 33, 33, 33)
            web_view_align.add(web_view)
            web_settings = web_view.get_settings()
            web_settings.set_property("enable-plugins", False)
            web_settings.set_property("enable-scripts", True)
            web_view.open("%s/softcenter/v1/comment?n=%s&hl=%s" % (
                    SERVER_ADDRESS,
                    self.pkg_name,
                    LANGUAGE,
                    ))

            web_view.connect("load-finished", self.comment_load_finished_cb, web_view_align)

            create_thread(self.fetch_screenshot).start()
Exemple #3
0
class MainWin(gtk.Window):
    def __init__(self):
        super(MainWin, self).__init__()

        self.set_size_request(600, 400)
        self.set_position(gtk.WIN_POS_CENTER)
        self.connect("destroy", gtk.main_quit)
        
        cookie_file = "/tmp/dupan4linux.txt"
        self.web_view = WebView(cookie_file)
        self.web_view.connect("notify::load-status", self.web_view_load_status)
        self.web_view.open(login_url)

        self.loading = Loading()
        
        self.main_vbox = gtk.VBox()
        self.main_vbox.pack_start(self.web_view)

        self.add(self.main_vbox)
        self.show_all()
        gtk.main()

    def web_view_load_status(self, web_view, status):
        state = web_view.get_property("load-status")
        uri = web_view.get_property("uri")
        if state == webkit.LOAD_COMMITTED:
            print "Commited:"
            print uri
        elif status == webkit.LOAD_FINISHED:
            print "Finished:"
            print uri.split("&")
Exemple #4
0
    def __init__(self, session_bus, appid, dbus_name, dbus_path):
        dbus.service.Object.__init__(self, session_bus, dbus_path)

        self.appid = appid
        self.dbus_name = dbus_name
        self.dbus_path = dbus_path
        
        # WARING: only use once in one process
        DBusGMainLoop(set_as_default=True) 
        
        self.plug = gtk.Plug(0)

        self.webview = WebView(COOKIE_FILE)
        self.webview.connect('title-changed', self.webview_message_handler)
        self.webview.connect('script-alert', self.webview_message_handler)
        #self.webview.enable_inspector()
        self.paned_box = PanedBox(2, True, 2, True)
        self.paned_box.enter_bottom_win_callback = self.enter_bottom_notify
        self.paned_box.enter_top_win_callback = self.enter_top_notify
        self.paned_box.add_content_widget(self.webview)
        self.plug.add(self.paned_box)
        self.plug.connect('delete-event', self.plug_delete_event)
        
        # Handle signals.
        self.plug.connect("realize", self.flash_frame_realize)
        self.plug.connect("destroy", self.flash_frame_exit)

        glib.timeout_add(1000, self.is_exist)
        glib.timeout_add(200, self.connect_signal)

        def message_receiver(self, *message):
            message_type, contents = message
            if message_type == 'exit':
                self.exit()
            elif message_type == 'load_uri':
                self.load_flash(contents)
            elif message_type == 'load_loading_uri':
                self.webview.load_uri(contents)
                self.send_message('loading_uri_finish', '')
            elif message_type == 'load_string':
                self.webview.load_string(contents)
            elif message_type == 'get_plug_id':
                self.send_flash_info()
            elif message_type == 'app_info_download_finish':
                self.webview.execute_script("app_info=%s" %
                        json.dumps(str(contents), encoding="UTF-8", ensure_ascii=False))

        setattr(FlashFrame, 
                'message_receiver', 
                dbus.service.method(dbus_name)(message_receiver))
Exemple #5
0
    def __init__(self):
        super(MainWin, self).__init__()

        self.set_size_request(600, 400)
        self.set_position(gtk.WIN_POS_CENTER)
        self.connect("destroy", gtk.main_quit)
        
        cookie_file = "/tmp/dupan4linux.txt"
        self.web_view = WebView(cookie_file)
        self.web_view.connect("notify::load-status", self.web_view_load_status)
        self.web_view.open(login_url)

        self.loading = Loading()
        
        self.main_vbox = gtk.VBox()
        self.main_vbox.pack_start(self.web_view)

        self.add(self.main_vbox)
        self.show_all()
        gtk.main()
Exemple #6
0
    def __init__(self, filename=""):
        '''
        init share
        @param filename: the file to share
        '''
        self.upload_image = filename
        self.thumb_width = 188
        self.thumb_height = 168
        self.MAX_CHAR = 140
        #self.__text_frame_color = (0.76, 0.76, 0.76)
        self.__win_width = 602
        open(COOKIE_FILE,'wb').close()

        self.window = DialogBox(_("Share to social networks"), close_callback=gtk.main_quit)
        self.window.set_keep_above(True)
        self.window.set_size_request(self.__win_width+20, 288)
        self.window.set_resizable(False)
        self.window.titlebar.connect("expose-event", self.__expose_top_and_bottome)
        self.window.button_box.connect("expose-event", self.__expose_top_and_bottome)

        # create slider
        self.slider = HSlider()
        self.slider_list = []

        self.share_box = gtk.VBox(False, 2)     # first page, input context
        self.web_box = gtk.VBox(False, 10)      # second page, login
        self.result_box = gtk.VBox(False, 10)   # third page, share result

        share_align = gtk.Alignment()
        share_align.set(0.5, 0.5, 0, 0)
        share_align.add(self.share_box)
        share_align.connect("expose-event", self.__slider_expose)

        # go back button
        web_left_button = ImageButton(
            app_theme.get_pixbuf("share/back_normal.png"),
            app_theme.get_pixbuf("share/back_hover.png"),
            app_theme.get_pixbuf("share/back_press.png"))
        web_left_button.connect("clicked", lambda w: self.set_slide_index(0))
        web_left_button.set_can_focus(False)
        utils.set_clickable_cursor(web_left_button)
        # show url entry
        self.web_url_entry = InputEntry()
        self.web_url_entry.set_editable(False)
        self.web_url_entry.set_size(555, 20)
        self.web_url_entry.entry.right_menu_visible_flag = False
        # alig url entry
        web_navigate_vbox = gtk.VBox(False)
        web_navigate_vbox.pack_start(self.web_url_entry)
        web_navigate_t_align = gtk.Alignment()
        web_navigate_t_align.set(0.0, 0.5, 0, 0)
        web_navigate_t_align.add(web_navigate_vbox)
        # pack back button and url entry
        web_navigate_box = gtk.HBox(False, 7)
        web_navigate_box.pack_start(web_left_button, False, False)
        web_navigate_box.pack_start(web_navigate_t_align)

        web_navigate_align = gtk.Alignment()
        web_navigate_align.set(0.5, 0.5, 0, 0)
        web_navigate_align.set_padding(4, 0, 11, 13)
        web_navigate_align.add(web_navigate_box)

        # create a webkit
        self.web_view = WebView(COOKIE_FILE)
        self.web_view.connect("notify::load-status", self.web_view_load_status)
        self.web_view.connect("load-error", self.web_view_load_error)
        self.web_scrolled_window = ScrolledWindow()
        self.web_scrolled_window.add(self.web_view)
        self.web_scrolled_window.set_size_request(590, 228)

        self.web_box.pack_start(web_navigate_align, False, False)
        self.web_box.pack_start(self.web_scrolled_window)
        #self.web_box.set_size_request(-1, 258)
        web_align = gtk.Alignment()
        web_align.set(0.5, 0.0, 0, 1)
        web_align.add(self.web_box)
        web_align.connect("expose-event", self.__slider_expose)

        res_align = gtk.Alignment()
        res_align.set(0.5, 0.5, 0, 0)
        res_align.add(self.result_box)
        res_align.connect("expose-event", self.__slider_expose)

        self.slider.set_to_page(share_align)
        self.slider_list.append(share_align)
        self.slider_list.append(web_align)
        self.slider_list.append(res_align)

        self.__weibo_list = []
        self.sina = weibo.Sina(self.web_view)
        self.qq = weibo.Tencent(self.web_view)
        self.twitter = weibo.Twitter(self.web_view)
        self.__weibo_list.append(self.sina)
        self.__weibo_list.append(self.qq)
        self.__weibo_list.append(self.twitter)
        self.__current_weibo = None

        self.window.body_box.pack_start(self.slider, True, True)
        self.init_share_box()
Exemple #7
0
class ShareToWeibo(object):
    '''share picture to weibo'''
    def __init__(self, filename=""):
        '''
        init share
        @param filename: the file to share
        '''
        self.upload_image = filename
        self.thumb_width = 188
        self.thumb_height = 168
        self.MAX_CHAR = 140
        #self.__text_frame_color = (0.76, 0.76, 0.76)
        self.__win_width = 602
        open(COOKIE_FILE,'wb').close()

        self.window = DialogBox(_("Share to social networks"), close_callback=gtk.main_quit)
        self.window.set_keep_above(True)
        self.window.set_size_request(self.__win_width+20, 288)
        self.window.set_resizable(False)
        self.window.titlebar.connect("expose-event", self.__expose_top_and_bottome)
        self.window.button_box.connect("expose-event", self.__expose_top_and_bottome)

        # create slider
        self.slider = HSlider()
        self.slider_list = []

        self.share_box = gtk.VBox(False, 2)     # first page, input context
        self.web_box = gtk.VBox(False, 10)      # second page, login
        self.result_box = gtk.VBox(False, 10)   # third page, share result

        share_align = gtk.Alignment()
        share_align.set(0.5, 0.5, 0, 0)
        share_align.add(self.share_box)
        share_align.connect("expose-event", self.__slider_expose)

        # go back button
        web_left_button = ImageButton(
            app_theme.get_pixbuf("share/back_normal.png"),
            app_theme.get_pixbuf("share/back_hover.png"),
            app_theme.get_pixbuf("share/back_press.png"))
        web_left_button.connect("clicked", lambda w: self.set_slide_index(0))
        web_left_button.set_can_focus(False)
        utils.set_clickable_cursor(web_left_button)
        # show url entry
        self.web_url_entry = InputEntry()
        self.web_url_entry.set_editable(False)
        self.web_url_entry.set_size(555, 20)
        self.web_url_entry.entry.right_menu_visible_flag = False
        # alig url entry
        web_navigate_vbox = gtk.VBox(False)
        web_navigate_vbox.pack_start(self.web_url_entry)
        web_navigate_t_align = gtk.Alignment()
        web_navigate_t_align.set(0.0, 0.5, 0, 0)
        web_navigate_t_align.add(web_navigate_vbox)
        # pack back button and url entry
        web_navigate_box = gtk.HBox(False, 7)
        web_navigate_box.pack_start(web_left_button, False, False)
        web_navigate_box.pack_start(web_navigate_t_align)

        web_navigate_align = gtk.Alignment()
        web_navigate_align.set(0.5, 0.5, 0, 0)
        web_navigate_align.set_padding(4, 0, 11, 13)
        web_navigate_align.add(web_navigate_box)

        # create a webkit
        self.web_view = WebView(COOKIE_FILE)
        self.web_view.connect("notify::load-status", self.web_view_load_status)
        self.web_view.connect("load-error", self.web_view_load_error)
        self.web_scrolled_window = ScrolledWindow()
        self.web_scrolled_window.add(self.web_view)
        self.web_scrolled_window.set_size_request(590, 228)

        self.web_box.pack_start(web_navigate_align, False, False)
        self.web_box.pack_start(self.web_scrolled_window)
        #self.web_box.set_size_request(-1, 258)
        web_align = gtk.Alignment()
        web_align.set(0.5, 0.0, 0, 1)
        web_align.add(self.web_box)
        web_align.connect("expose-event", self.__slider_expose)

        res_align = gtk.Alignment()
        res_align.set(0.5, 0.5, 0, 0)
        res_align.add(self.result_box)
        res_align.connect("expose-event", self.__slider_expose)

        self.slider.set_to_page(share_align)
        self.slider_list.append(share_align)
        self.slider_list.append(web_align)
        self.slider_list.append(res_align)

        self.__weibo_list = []
        self.sina = weibo.Sina(self.web_view)
        self.qq = weibo.Tencent(self.web_view)
        self.twitter = weibo.Twitter(self.web_view)
        self.__weibo_list.append(self.sina)
        self.__weibo_list.append(self.qq)
        self.__weibo_list.append(self.twitter)
        self.__current_weibo = None

        self.window.body_box.pack_start(self.slider, True, True)
        self.init_share_box()

    # webkit load-status, login success, go back
    def web_view_load_status(self, web, status):
        '''web_view notify load-status callback'''
        state = web.get_property("load-status")
        url = web.get_property('uri')
        if url:
            self.web_url_entry.set_editable(True)
            self.web_url_entry.set_text(url)
            self.web_url_entry.entry.move_to_start()
            self.web_url_entry.set_editable(False)
        if state == webkit.LOAD_FAILED:  # load failed
            print "load failed",
            print web.get_property('uri')

        elif state == webkit.LOAD_COMMITTED:
            if self.__current_weibo and self.__current_weibo.is_callback_url(url):
                web.stop_loading()  # if go to  callback url, stop loading
                # access token
                #print "load committed", url
                t = threading.Thread(target=self.weibo_login_thread)
                t.setDaemon(True)
                t.start()

    def web_view_load_error(self, web, fram, url, error, data=None):
        web.load_string(
            "<html><body><p><h1>%s</h1></p>%s</body></html>" % (
            _("Unable to load page"),
            _("Problem occurred while loading the URL '%s'") % (url)),
            "text/html", "UTF-8", "")
        print url
        return True
    
    # login or switch user
    def weibo_login(self, widget, weibo):
        '''weibo button clicked callback'''
        self.web_view.load_uri("about:blank")
        utils.set_cursor(widget)
        self.set_slide_index(1)
        self.__current_weibo = weibo
        t = threading.Thread(target=self.__current_weibo.request_oauth)
        t.setDaemon(True)
        t.start()

    def weibo_login_thread(self):
        '''in webkit login finish, get user info again'''
        self.__current_weibo.access_token()
        self.get_user_info_again()
        gtk.gdk.threads_enter()
        self.set_slide_index(0)
        gtk.gdk.threads_leave()

    def get_user_info_again(self):
        ''' login or switch user, and get user info again'''
        box = self.__current_weibo.get_box()
        #print "cuurent weibo:", self.__current_weibo.t_type
        gtk.gdk.threads_enter()
        children = box.get_children()
        for child in children:
            if child in self.__weibo_check_button_list:
                self.__weibo_check_button_list.remove(child)
            if child in self.__weibo_image_button_list:
                self.__weibo_image_button_list.remove(child)
            child.destroy()
        gtk.gdk.threads_leave()

        self.get_user_info(self.__current_weibo)

        gtk.gdk.threads_enter()
        box.show_all()
        gtk.gdk.threads_leave()

    def set_slide_index(self, index):
        '''
        set slide to index
        @param index: the index of widget in slider, an int num
        '''
        if index >= len(self.slider_list):
            return
        direct = "right"
        if index == 1 and self.window.button_box in self.window.window_frame.get_children():
            #self.slider.set_size_request(-1, 260)
            win = self.window
            if win.left_button_box in win.button_box.get_children():
                win.button_box.remove(win.left_button_box)
            if win.right_button_box in win.button_box.get_children():
                win.button_box.remove(win.right_button_box)
            tmp = gtk.HSeparator()
            tmp.set_size_request(-1, 1)
            tmp.show()
            win.button_box.pack_start(tmp)
            direct = "right"
            #if self.window.button_box in self.window.window_frame.get_children():
                #self.window.window_frame.remove(self.window.button_box)
        elif index == 0:
            #self.slider.set_size_request(-1, 223)
            win = self.window
            for each in win.button_box.get_children():
                each.destroy()
            if win.left_button_box not in win.button_box.get_children():
                win.button_box.pack_start(win.left_button_box)
            if win.right_button_box not in win.button_box.get_children():
                win.button_box.pack_start(win.right_button_box)
            direct = "left"
            #if self.window.button_box not in self.window.window_frame.get_children():
                #self.window.window_frame.pack_start(self.window.button_box, False, False)
        elif index == 2:
            self.window.left_button_box.set_buttons([])
            l = Label("  ")
            l.show()
            self.window.right_button_box.set_buttons([l])
            direct = "right"
            #self.slider.set_size_request(-1, 223)
            
        self.slider.slide_to_page(self.slider_list[index], direct)

    def weibo_check_toggle(self, button, weibo):
        '''weibo check button toggled callback. check the weibo to share'''
        if button.get_active():
            self.to_share_weibo[weibo] = 1
        else:
            self.to_share_weibo[weibo] = 0

    def create_ico_image(self, name):
        ''' create image from file'''
        pix1 = app_theme_get_dynamic_pixbuf('image/share/%s.png' % name).get_pixbuf()
        pix2 = app_theme_get_dynamic_pixbuf('image/share/%s_no.png' % name).get_pixbuf()
        return (pix1, pix2)
    
    def get_user_info(self, weibo):
        '''get weibo user info'''
        info = weibo.get_user_name()
        gtk.gdk.threads_enter()
        #self.get_user_error_text = ""
        weibo_hbox = weibo.get_box()
        hbox = gtk.HBox(False)
        vbox = gtk.VBox(False)
        weibo_hbox.pack_start(vbox, False, False)
        vbox.pack_start(hbox)
        #print weibo.t_type, info
        if info:
            self.is_get_user_info[weibo] = 1
            label = Label(text=info, label_width=70, enable_select=False)
            check = CheckButton()
            #check = gtk.CheckButton()
            check.connect("toggled", self.weibo_check_toggle, weibo)
            check.set_active(True)
            check_vbox = gtk.VBox(False)
            check_align = gtk.Alignment(0.5, 0.5, 0, 0)
            check_align.add(check_vbox)
            check_vbox.pack_start(check, False, False)
            button = ImageButton(
                app_theme.get_pixbuf("share/" + weibo.t_type + ".png"),
                app_theme.get_pixbuf("share/" + weibo.t_type + ".png"),
                app_theme.get_pixbuf("share/" + weibo.t_type + ".png"))
            utils.set_clickable_cursor(button)
            button.connect("enter-notify-event", self.show_tooltip, _("Click to switch user"))
            hbox.pack_start(check_align, False, False)
            hbox.pack_start(button, False, False, 5)
            hbox.pack_start(label, False, False)
        else:
            self.is_get_user_info[weibo] = 0
            check = CheckButton()
            #check = gtk.CheckButton()
            check.set_sensitive(False)
            check_vbox = gtk.VBox(False)
            check_align = gtk.Alignment(0.5, 0.5, 0, 0)
            check_align.add(check_vbox)
            check_vbox.pack_start(check, False, False)
            button = ImageButton(
                app_theme.get_pixbuf("share/" + weibo.t_type + "_no.png"),
                app_theme.get_pixbuf("share/" + weibo.t_type + "_no.png"),
                app_theme.get_pixbuf("share/" + weibo.t_type + "_no.png"))
            utils.set_clickable_cursor(button)
            button.connect("enter-notify-event", self.show_tooltip, _("Click to login"))
            hbox.pack_start(check_align, False, False)
            hbox.pack_start(button, False, False, 5)
            # curl time out
            info_error = weibo.get_curl_error()
            if info_error:
                #self.get_user_error_text += "%s:%s." % (weibo.t_type, _(info_error))
                hbox.pack_start(
                    Label(text="(%s)" % _(info_error), label_width=70,enable_select=False,
                    text_color = app_theme.get_color("left_char_num1")), False, False)
            
        button.connect("clicked", self.weibo_login, weibo)
        self.__weibo_check_button_list.append(check)
        self.__weibo_image_button_list.append(button)
        gtk.gdk.threads_leave()
        return weibo_hbox
    
    def show_tooltip(self, widget, event, text):
        '''Create help tooltip.'''
        Tooltip.text(widget, text)

    def init_user_info_thread(self, button, text_view):
        '''get user name thread'''
        time.sleep(0.1)

        for weibo in self.__weibo_list:
            self.get_user_info(weibo)

        gtk.gdk.threads_enter()
        #self.share_box.set_sensitive(True)
        button.set_sensitive(True)
        text_view.set_editable(True)
        for weibo in self.__weibo_list:
            weibo.get_box().show_all()
            weibo.get_box().queue_draw()
        self.loading_label.destroy()
        gtk.gdk.threads_leave()
    
    # init share box, create share button, input
    def init_share_box(self):
        '''get weibo info, and create button'''
        self.to_share_weibo = {}
        self.to_share_weibo_res = {}
        self.deepin_info = {}
        self.is_get_user_info = {}
        self.__weibo_check_button_list = []
        self.__weibo_image_button_list = []

        # create Thumbnail
        if exists(self.upload_image):
            pixbuf = gtk.gdk.pixbuf_new_from_file(self.upload_image)
            pix_w = pixbuf.get_width()
            pix_h = pixbuf.get_height()
            if pix_w > pix_h:
                pix_s_w = self.thumb_width
                pix_s_h = int(pix_h / (float(pix_w) / self.thumb_width))
            else:
                pix_s_h = self.thumb_height
                pix_s_w = int(pix_w / (float(pix_h) / self.thumb_height))
            pixbuf = pixbuf.scale_simple(pix_s_w, pix_s_h, gtk.gdk.INTERP_TILES)
            thumb = gtk.image_new_from_pixbuf(pixbuf)
        else:
            thumb = gtk.Image()
        thumb.set_size_request(self.thumb_width, self.thumb_height)

        # weibo context input
        text_box = gtk.HBox(False, 2)
        text_vbox = gtk.VBox(False, 2)
        text_bg_vbox = gtk.VBox(False)
        text_bg_align = gtk.Alignment()
        text_bg_align.set(0.5, 0.5, 0, 0)
        text_bg_align.set_padding(5, 5, 16, 5)
        text_bg_align.connect("expose-event", self.text_view_bg_expose)
        text_scrolled_win = ScrolledWindow()
        text_scrolled_win.set_size_request(340, 157)

        text_view = gtk.TextView()
        text_view.set_left_margin(10)
        text_view.set_right_margin(10)
        text_view.set_pixels_above_lines(5)
        text_view.set_pixels_below_lines(5)
        text_view.set_wrap_mode(gtk.WRAP_WORD| gtk.WRAP_CHAR)
        text_view.connect("expose-event", self.text_view_expose)
        buf = text_view.get_buffer()
        text_scrolled_win.add(text_view)
        text_bg_vbox.pack_start(text_scrolled_win)
        text_bg_align.add(text_bg_vbox)

        text_align = gtk.Alignment() 
        text_align.set(0.5, 0.5, 0, 0)
        text_align.set_padding(25, 30, 10, 10)

        text_box.pack_start(thumb, False, False, 10)
        text_box.pack_start(text_bg_align)
        text_vbox.pack_start(text_box, False, False, 10)

        text_align.add(text_vbox)
        #tmp_align = gtk.Alignment()
        #tmp_align.set(0.5, 0, 0, 1)
        #self.share_box.pack_start(tmp_align, False, False)
        self.share_box.pack_start(text_align, False, False)

        # dialog button box
        left_box = self.window.left_button_box
        right_box = self.window.right_button_box

        # input tip label
        self.input_num_label = Label("%d" % self.MAX_CHAR,
            text_size=16, text_x_align=pango.ALIGN_CENTER, label_width=50, enable_select=False)
        self.input_num_label.text_color = app_theme.get_color("left_char_num")

        # login box
        #weibo_box = gtk.HBox(False, 1)
        #weibo_box.set_size_request(-1, 50)
        weibo_box_list = []
        self.loading_label = Label("%s..." % _("Loading"), text_size=12,
            label_width=70, enable_select=False)
        weibo_box_list.append(self.loading_label)

        for weibo in self.__weibo_list:
            box = gtk.HBox(False, 2)
            weibo.set_box(box)
            weibo_box_list.append(box)
        left_box.set_buttons(weibo_box_list)

        # share button
        button = Button(_("Share"))
        #button.set_size_request(75, 25)
        button.connect("clicked", self.share_button_clicked, text_view)
        buf.connect("changed", self.text_view_changed, button)  # check char num

        tmp_vbox = gtk.VBox(False)
        tmp_align = gtk.Alignment()
        tmp_align.set(0.5, 0.5, 0, 0)
        tmp_vbox.pack_start(button, False, False)
        #tmp_vbox.pack_start(tmp_align)
        tmp_align.add(tmp_vbox)
        right_box.set_buttons([self.input_num_label, tmp_align])

        # at first, set widget insensitive
        button.set_sensitive(False)
        text_view.set_editable(False)
        t = threading.Thread(target=self.init_user_info_thread, args=(button, text_view))
        t.setDaemon(True)
        t.start()

    # draw text view background
    def text_view_bg_expose(self, widget, event):
        '''draw text view bg'''
        cr = widget.window.cairo_create()
        rect = widget.allocation
        text_pixbuf = app_theme_get_dynamic_pixbuf('image/share/text_view.png').get_pixbuf()
        draw.draw_pixbuf(cr, text_pixbuf, rect.x, rect.y)

    # if text is empty, show tip info
    def text_view_expose(self, text_view, event):
        '''text_view expose'''
        buf = text_view.get_buffer()
        text = buf.get_text(*buf.get_bounds())

        if text == "" and text_view.get_editable() and not text_view.is_focus():
            win = text_view.get_window(gtk.TEXT_WINDOW_TEXT)
            cr = win.cairo_create()
            cr.move_to(10, 5)
            context = pangocairo.CairoContext(cr)
            layout = context.create_layout()
            layout.set_font_description(pango.FontDescription("Snas 10"))
            layout.set_alignment(pango.ALIGN_LEFT)
            layout.set_text(_("Please input text here"))
            cr.set_source_rgb(0.66, 0.66, 0.66)
            context.update_layout(layout)
            context.show_layout(layout)
    
    # show input char num
    def text_view_changed(self, buf, button):
        '''text_view changed callback'''
        count = buf.get_char_count()
        if count <= self.MAX_CHAR:
            #self.input_tip_label.set_text(_("left"))
            self.input_num_label.set_text("%d" % (self.MAX_CHAR - count))
            self.input_num_label.text_color = app_theme.get_color("left_char_num")
            if not button.is_sensitive():
                button.set_sensitive(True)
        else:
            #self.input_tip_label.set_text(_("exceeds"))
            self.input_num_label.set_text("-%d" % (count - self.MAX_CHAR))
            self.input_num_label.text_color = app_theme.get_color("left_char_num1")
            if button.is_sensitive():
                button.set_sensitive(False)

    def share_button_clicked(self, button, text_view):
        '''share_button_clicked callback'''
        # file is not exist.
        if not exists(self.upload_image):
            d = ConfirmDialog(_("Error"), "%s." % ( _("Picture does not exist.")))
            d.show_all()
            d.set_transient_for(self.window)
            return False
        has_share_web = False
        for weibo in self.to_share_weibo:
            if self.to_share_weibo[weibo]:
                has_share_web = True
                break
        # have no web selected
        if not has_share_web:
            d = ConfirmDialog(_("Error"), _("Please choose at least one platform to share on"))
            d.show_all()
            d.set_transient_for(self.window)
            return False
        # at first, set widget insensitive
        button.set_sensitive(False)
        text_view.set_editable(False)
        #self.window.left_button_box.set_sensitive(False)
        # set weibo checkbutton sensitive
        for check in self.__weibo_check_button_list:
            check.set_sensitive(False)
        # disconnect weibo ico button clicked function
        for img in self.__weibo_image_button_list:
            try:
                img.disconnect_by_func(self.weibo_login)
            except:
                pass
        button.set_label(_("Uploading"))
        t = threading.Thread(target=self.share_to_weibo_thread, args=(text_view, ))
        t.setDaemon(True)
        t.start()
    
    # upload image thread
    def share_to_weibo_thread(self, text_view):
        '''share in thread'''
        buf = text_view.get_buffer()
        text = buf.get_text(*buf.get_bounds())
        if text.strip() == "":
            text = _("from Deepin Screenshot")
        # get deepin official info
        self.deepin_info[self.sina] = self.sina.get_deepin_info()
        self.deepin_info[self.qq] = self.qq.get_deepin_info()
        if default_locale != 'zh_CN':
            self.deepin_info[self.twitter] = self.twitter.get_deepin_info()
        # upload
        for weibo in self.to_share_weibo:
            if self.to_share_weibo[weibo]:
                self.to_share_weibo_res[weibo] = weibo.upload_image(self.upload_image, text)
        self.share_to_weibo_result()
    
    # show upload result
    @post_gui
    def share_to_weibo_result(self):
        '''result of share to weibo'''
        font_color = app_theme.get_color("share_result_text")
        res_hbox = gtk.HBox(False)
        res_hbox.set_size_request(-1, 240)

        res_left_box = DialogLeftButtonBox()
        res_right_box = DialogRightButtonBox()

        res_left_box.button_align.set(0.5, 0.0, 0, 1)
        res_right_box.button_align.set(0.5, 0.0, 0, 1)
        res_left_box.button_align.set_padding(5, 9, 19, 0)
        res_right_box.button_align.set_padding(30, 0, 0, 0)

        res_left_box.set_size_request(405, -1)
        res_right_box.set_size_request(195, -1)
        
        res_hbox.pack_start(res_left_box)
        res_hbox.pack_start(
            VSeparator(app_theme.get_shadow_color("VSeparator").get_color_info(), 0, 0))
        res_hbox.pack_start(res_right_box)

        res_vbox = gtk.VBox(False)
        follow_vbox = gtk.VBox(False)

        tmp_img = gtk.Image()       # only use as a placeholder
        tmp_img.set_size_request(-1, 50) 
        res_vbox.pack_start(tmp_img, False, False)

        follow_tip_hbox = gtk.HBox(False)
        img = gtk.image_new_from_file(app_theme.get_theme_file_path("image/share/deepin_logo.png"))
        follow_tip_hbox.pack_start(img, False, False, 5)
        follow_tip_hbox.pack_start(
            Label("%s %s" % (_("Follow"), "Linux Deepin"), 
                text_color=app_theme_get_dynamic_color("#5f5f5f"),
                text_size=12, enable_select=False), False, False)
        follow_vbox.pack_start(follow_tip_hbox, False, False, 13)
        for weibo in self.to_share_weibo_res:
            vbox = gtk.VBox(False, 1)
            tip_box = gtk.HBox()
            error_box = gtk.HBox()
            vbox.pack_start(tip_box, False, False)
            vbox.pack_start(error_box, False, False)
            if self.to_share_weibo_res[weibo][0]:   # upload succeed
                img = gtk.image_new_from_file(app_theme.get_theme_file_path("image/share/share_succeed.png"))
                #link = LinkButton(_(weibo.t_type), text_size=13, self.to_share_weibo_res[weibo][1])
                link = Label(_(weibo.t_type), text_size=12, 
                    text_color=app_theme.get_color("link_text"))
                #, enable_gaussian=True, gaussian_radious=1, border_radious=0)
                link.add_events(gtk.gdk.BUTTON_PRESS_MASK)
                link.connect("enter-notify-event", lambda w, e: self.__draw_under_line(w))
                link.connect("leave-notify-event", lambda w, e: w.queue_draw())
                link.connect("button-press-event", self.goto_weibo_button_clicked, weibo)
                link_box = gtk.HBox(False)
                link_box.pack_start(link, False, False)
                utils.set_clickable_cursor(link)
                text = _("Share to")
                label = Label(text, text_size=12, 
                    text_color=font_color, enable_select=False)
                text = _("Successful")
                label1 = Label(text, text_size=12, 
                    text_color=font_color, enable_select=False)
                tip_box.pack_start(img, False, False, 15)
                tip_box.pack_start(label, False, False, 3)
                tip_box.pack_start(link_box, False, False, 3)
                tip_box.pack_start(label1, False, False)
                # only use as a placeholder
                img = gtk.Image()
                img.set_size_request(20, 1)
                error_box.pack_start(img, False, False, 16)
                tmp = Label(" ", text_size=9, label_width=200)
                tmp.set_size_request(200, 1)
                error_box.pack_start(tmp, False, False)
                #print text
            else:   # upload failed
                img = gtk.image_new_from_file(app_theme.get_theme_file_path("image/share/share_failed.png"))
                #text = "% %s %s." % (_(weibo.t_type), _("upload failed"))
                text = _("Share to")
                label1 = Label(text, text_size=12, 
                    text_color=font_color, enable_select=False)
                label2 = Label(_(weibo.t_type), text_size=12, 
                    text_color=font_color, enable_select=False)
                text = _("Failed")
                label3 = Label(text, text_size=12, 
                    text_color=font_color, enable_select=False)
                if weibo.curl.error:
                    error = "(%s)" % _(weibo.curl.error)
                elif weibo.get_error_msg():
                    error = "(%s)" % _(weibo.get_error_msg()) 
                else:
                    error = "(%s)" % _("Unknown reason")
                #print "%s: %s" % (weibo.t_type, error)
                #print "%s: %s" % (weibo.t_type, weibo.get_error_msg())
                label = Label(text, text_size=12,
                    text_color=font_color, enable_select=False)
                tip_box.pack_start(img, False, False, 15)
                tip_box.pack_start(label1, False, False, 3)
                tip_box.pack_start(label2, False, False, 3)
                tip_box.pack_start(label3, False, False)
                img = gtk.Image()   # only use as a placeholder
                img.set_size_request(20, 20)
                error_box.pack_start(img, False, False, 16)
                error_box.pack_start(Label(error, text_size=9, label_width=200,
                    text_color=font_color, enable_select=False), False, False)
                #print text
            res_vbox.pack_start(vbox, False, False, 10)

        for weibo in self.deepin_info:
            box = gtk.HBox(False, 15)
            # followed
            img = gtk.image_new_from_pixbuf(app_theme.get_pixbuf("share/"+weibo.t_type+".png").get_pixbuf())
            box.pack_start(img, False, False)
            if self.deepin_info[weibo] is not None and self.deepin_info[weibo][3]:
                if not default_locale.startswith("zh_"):
                    button = gtk.image_new_from_pixbuf(
                        app_theme.get_pixbuf("share/followed_en.png").get_pixbuf())
                else:
                    button = gtk.image_new_from_pixbuf(
                        app_theme.get_pixbuf("share/followed.png").get_pixbuf())
            else:   # to follow
                if not default_locale.startswith("zh_"):
                    button = ImageButton(
                        app_theme.get_pixbuf("share/follow_normal_en.png"),
                        app_theme.get_pixbuf("share/follow_hover_en.png"),
                        app_theme.get_pixbuf("share/follow_press_en.png"))
                else:
                    button = ImageButton(
                        app_theme.get_pixbuf("share/follow_normal.png"),
                        app_theme.get_pixbuf("share/follow_hover.png"),
                        app_theme.get_pixbuf("share/follow_press.png"))
                button.connect("clicked", self.friendships_add_button_clicked, weibo, box)
            box.pack_start(button, False, False)
            align = gtk.Alignment()
            align.set(0.0, 0.5, 0, 0)
            align.set_padding(0, 0, 30, 0)
            align.add(box)
            follow_vbox.pack_start(align, False, False, 8)

        res_left_box.set_buttons([res_vbox])
        res_right_box.set_buttons([follow_vbox])

        self.result_box.pack_start(res_hbox, False, False)
        self.result_box.show_all()
        self.set_slide_index(2)
    
    def goto_weibo_button_clicked(self, widget, event, weibo):
        '''goto my weibo'''
        #print "goto weibo button clicked", weibo.t_type, "xdg-open %s" % self.to_share_weibo_res[weibo][1]
        if weibo in self.to_share_weibo_res:
            if self.to_share_weibo_res[weibo][1]:
                utils.run_command("xdg-open %s" % self.to_share_weibo_res[weibo][1])
        
    def friendships_add_button_clicked(self, widget, weibo, box):
        '''add friendships'''
        #self.result_box.set_sensitive(False)
        if not self.is_get_user_info[weibo]:
            utils.run_command("xdg-open %s" % weibo.index_url)
            return True

        widget.set_sensitive(False)
        t = threading.Thread(target=self.friendships_add_thread, args=(widget, weibo, box))
        t.setDaemon(True)
        t.start()
    
    def friendships_add_thread(self, button, weibo, box):
        '''add friendships'''
        if weibo.friendships_create() is not None:
            gtk.gdk.threads_enter()
            button.destroy()
            if not default_locale.startswith("zh_"):
                button = gtk.image_new_from_pixbuf(
                    app_theme.get_pixbuf("share/followed_en.png").get_pixbuf())
            else:
                button = gtk.image_new_from_pixbuf(
                    app_theme.get_pixbuf("share/followed.png").get_pixbuf())
            button.show()
            box.pack_start(button, False, False)
            #button.set_label("已关注")
            gtk.gdk.threads_leave()
    
    # show window
    def show(self):
        '''show'''
        self.window.show_window()

    # close widnow
    def quit(self, widget):
        ''' close '''
        gtk.main_quit()

    def __slider_expose(self, widget, event):
        ''' slider expose redraw'''
        cr = widget.window.cairo_create()
        rect = widget.allocation
        cr.set_source_rgba(1.0, 1.0, 1.0, 0.8)
        cr.rectangle(rect.x, rect.y, rect.width, rect.height)
        cr.fill()
    
    def __expose_top_and_bottome(self, widget, event):
        '''titlebar or button_box expose'''
        cr = widget.window.cairo_create()
        rect = widget.allocation
        cr.set_source_rgb(0.89, 0.89, 0.89)
        cr.rectangle(rect.x+2, rect.y+2, rect.width-4, rect.height-4)
        cr.fill()

    def __draw_under_line(self, widget):
        '''draw under line'''
        cr = widget.window.cairo_create()
        with utils.cairo_disable_antialias(cr):
            x, y, w, h = widget.allocation
            # #1A70b1
            cr.set_source_rgba(0.1, 0.43, 0.69, 1.0)
            cr.set_line_width(1)
            cr.move_to(x, y+h-3)
            cr.line_to(x+w, y+h-3)
            cr.stroke()
Exemple #8
0
    temp_hbox.pack_start(combo_button, False, False)

    star_view = StarView()
    temp_hbox.pack_start(star_view, False, False)

    # Add statusbar.
    statusbar = Statusbar(36)
    tab_1_box.pack_start(statusbar, False)
    application.window.add_move_event(statusbar)
    application.window.add_toggle_event(statusbar)

    link_button = LinkButton("加入我们", "http://www.linuxdeepin.com/joinus/job")
    statusbar.status_item_box.pack_start(link_button)

    web_view = WebView()
    web_scrolled_window = ScrolledWindow()
    web_scrolled_window.add(web_view)
    web_view.open("http://www.linuxdeepin.com")
    tab_2_box.pack_start(web_scrolled_window)

    icon_view_hframe = HorizontalFrame()
    icon_view_vframe = gtk.Alignment()
    icon_view_vframe.set(0, 0, 1, 1)
    icon_view_vframe.set_padding(0, 1, 0, 0)

    icon_view_scrolled_window = ScrolledWindow()
    icon_view = IconView(10, 10)
    icon_view_scrolled_window.add_child(icon_view)
    icon_view_hframe.add(icon_view_scrolled_window)
Exemple #9
0
    def __init__(self, filename=""):
        '''
        init share
        @param filename: the file to share
        '''
        self.upload_image = filename
        self.thumb_width = 188
        self.thumb_height = 168
        self.MAX_CHAR = 140
        #self.__text_frame_color = (0.76, 0.76, 0.76)
        self.__win_width = 602
        open(COOKIE_FILE,'wb').close()

        self.window = DialogBox(_("Share to social networks"), close_callback=gtk.main_quit)
        self.window.set_keep_above(True)
        self.window.set_size_request(self.__win_width+20, 288)
        self.window.set_resizable(False)
        #self.window.titlebar.connect("expose-event", self.__expose_top_and_bottome)
        #self.window.button_box.connect("expose-event", self.__expose_top_and_bottome)

        # create slider
        self.slider = HSlider()
        self.slider_list = []

        self.share_box = gtk.VBox(False)     # first page, input context
        self.web_box = gtk.VBox(False, 10)      # second page, login
        self.result_box = gtk.VBox(False, 10)   # third page, share result

        share_align = gtk.Alignment()
        share_align.set(0.5, 0.5, 0, 0)
        share_align.add(self.share_box)
        share_align.connect("expose-event", self.__slider_expose)

        # go back button
        web_left_button = ImageButton(
            app_theme.get_pixbuf("share/back_normal.png"),
            app_theme.get_pixbuf("share/back_hover.png"),
            app_theme.get_pixbuf("share/back_press.png"))
        web_left_button.connect("clicked", lambda w: self.set_slide_index(0))
        web_left_button.set_can_focus(False)
        utils.set_clickable_cursor(web_left_button)
        # show url entry
        self.web_url_entry = InputEntry()
        self.web_url_entry.set_editable(False)
        self.web_url_entry.set_size(555, 20)
        self.web_url_entry.entry.right_menu_visible_flag = False
        # alig url entry
        web_navigate_vbox = gtk.VBox(False)
        web_navigate_vbox.pack_start(self.web_url_entry)
        web_navigate_t_align = gtk.Alignment()
        web_navigate_t_align.set(0.0, 0.5, 0, 0)
        web_navigate_t_align.add(web_navigate_vbox)
        # pack back button and url entry
        web_navigate_box = gtk.HBox(False, 7)
        web_navigate_box.pack_start(web_left_button, False, False)
        web_navigate_box.pack_start(web_navigate_t_align)

        web_navigate_align = gtk.Alignment()
        web_navigate_align.set(0.5, 0.5, 0, 0)
        web_navigate_align.set_padding(4, 0, 11, 13)
        web_navigate_align.add(web_navigate_box)

        # create a webkit
        self.web_view = WebView(COOKIE_FILE)
        self.web_view.connect("notify::load-status", self.web_view_load_status)
        self.web_view.connect("load-error", self.web_view_load_error)
        self.web_scrolled_window = ScrolledWindow()
        self.web_scrolled_window.add(self.web_view)
        self.web_scrolled_window.set_size_request(590, 228)

        self.web_box.pack_start(web_navigate_align, False, False)
        self.web_box.pack_start(self.web_scrolled_window)
        #self.web_box.set_size_request(-1, 258)
        web_align = gtk.Alignment()
        web_align.set(0.5, 0.0, 0, 1)
        web_align.add(self.web_box)
        web_align.connect("expose-event", self.__slider_expose)

        res_align = gtk.Alignment()
        res_align.set(0.5, 0.5, 0, 0)
        res_align.add(self.result_box)
        res_align.connect("expose-event", self.__slider_expose)

        self.slider.set_to_page(share_align)
        self.slider_list.append(share_align)
        self.slider_list.append(web_align)
        self.slider_list.append(res_align)

        self.__weibo_list = []
        self.sina = weibo.Sina(self.web_view)
        self.qq = weibo.Tencent(self.web_view)
        self.__weibo_list.append(self.sina)
        self.__weibo_list.append(self.qq)
        if default_locale != 'zh_CN':
            self.twitter = weibo.Twitter(self.web_view)
            #self.__weibo_list.append(self.twitter)
        self.__current_weibo = None

        self.weibo_name_l18n = {
                'Sina': _("Sina"),
                'Tencent': _("Tencent"),
                'Twitter': _("Twitter"),
                }

        self.window.body_box.pack_start(self.slider, True, True)
        self.init_share_box()
Exemple #10
0
class ShareToWeibo(object):
    '''share picture to weibo'''
    def __init__(self, filename=""):
        '''
        init share
        @param filename: the file to share
        '''
        self.upload_image = filename
        self.thumb_width = 188
        self.thumb_height = 168
        self.MAX_CHAR = 140
        #self.__text_frame_color = (0.76, 0.76, 0.76)
        self.__win_width = 602
        open(COOKIE_FILE,'wb').close()

        self.window = DialogBox(_("Share to social networks"), close_callback=gtk.main_quit)
        self.window.set_keep_above(True)
        self.window.set_size_request(self.__win_width+20, 288)
        self.window.set_resizable(False)
        #self.window.titlebar.connect("expose-event", self.__expose_top_and_bottome)
        #self.window.button_box.connect("expose-event", self.__expose_top_and_bottome)

        # create slider
        self.slider = HSlider()
        self.slider_list = []

        self.share_box = gtk.VBox(False)     # first page, input context
        self.web_box = gtk.VBox(False, 10)      # second page, login
        self.result_box = gtk.VBox(False, 10)   # third page, share result

        share_align = gtk.Alignment()
        share_align.set(0.5, 0.5, 0, 0)
        share_align.add(self.share_box)
        share_align.connect("expose-event", self.__slider_expose)

        # go back button
        web_left_button = ImageButton(
            app_theme.get_pixbuf("share/back_normal.png"),
            app_theme.get_pixbuf("share/back_hover.png"),
            app_theme.get_pixbuf("share/back_press.png"))
        web_left_button.connect("clicked", lambda w: self.set_slide_index(0))
        web_left_button.set_can_focus(False)
        utils.set_clickable_cursor(web_left_button)
        # show url entry
        self.web_url_entry = InputEntry()
        self.web_url_entry.set_editable(False)
        self.web_url_entry.set_size(555, 20)
        self.web_url_entry.entry.right_menu_visible_flag = False
        # alig url entry
        web_navigate_vbox = gtk.VBox(False)
        web_navigate_vbox.pack_start(self.web_url_entry)
        web_navigate_t_align = gtk.Alignment()
        web_navigate_t_align.set(0.0, 0.5, 0, 0)
        web_navigate_t_align.add(web_navigate_vbox)
        # pack back button and url entry
        web_navigate_box = gtk.HBox(False, 7)
        web_navigate_box.pack_start(web_left_button, False, False)
        web_navigate_box.pack_start(web_navigate_t_align)

        web_navigate_align = gtk.Alignment()
        web_navigate_align.set(0.5, 0.5, 0, 0)
        web_navigate_align.set_padding(4, 0, 11, 13)
        web_navigate_align.add(web_navigate_box)

        # create a webkit
        self.web_view = WebView(COOKIE_FILE)
        self.web_view.connect("notify::load-status", self.web_view_load_status)
        self.web_view.connect("load-error", self.web_view_load_error)
        self.web_scrolled_window = ScrolledWindow()
        self.web_scrolled_window.add(self.web_view)
        self.web_scrolled_window.set_size_request(590, 228)

        self.web_box.pack_start(web_navigate_align, False, False)
        self.web_box.pack_start(self.web_scrolled_window)
        #self.web_box.set_size_request(-1, 258)
        web_align = gtk.Alignment()
        web_align.set(0.5, 0.0, 0, 1)
        web_align.add(self.web_box)
        web_align.connect("expose-event", self.__slider_expose)

        res_align = gtk.Alignment()
        res_align.set(0.5, 0.5, 0, 0)
        res_align.add(self.result_box)
        res_align.connect("expose-event", self.__slider_expose)

        self.slider.set_to_page(share_align)
        self.slider_list.append(share_align)
        self.slider_list.append(web_align)
        self.slider_list.append(res_align)

        self.__weibo_list = []
        self.sina = weibo.Sina(self.web_view)
        self.qq = weibo.Tencent(self.web_view)
        self.__weibo_list.append(self.sina)
        self.__weibo_list.append(self.qq)
        if default_locale != 'zh_CN':
            self.twitter = weibo.Twitter(self.web_view)
            #self.__weibo_list.append(self.twitter)
        self.__current_weibo = None

        self.weibo_name_l18n = {
                'Sina': _("Sina"),
                'Tencent': _("Tencent"),
                'Twitter': _("Twitter"),
                }

        self.window.body_box.pack_start(self.slider, True, True)
        self.init_share_box()

    # webkit load-status, login success, go back
    def web_view_load_status(self, web, status):
        '''web_view notify load-status callback'''
        state = web.get_property("load-status")
        url = web.get_property('uri')
        if url:
            self.web_url_entry.set_editable(True)
            self.web_url_entry.set_text(url)
            self.web_url_entry.entry.move_to_start()
            self.web_url_entry.set_editable(False)
        if state == webkit.LOAD_FAILED:  # load failed
            print "load failed",
            print web.get_property('uri')

        elif state == webkit.LOAD_COMMITTED:
            if self.__current_weibo and self.__current_weibo.is_callback_url(url):
                web.stop_loading()  # if go to  callback url, stop loading
                # access token
                #print "load committed", url
                t = threading.Thread(target=self.weibo_login_thread)
                t.setDaemon(True)
                t.start()

    def web_view_load_error(self, web, fram, url, error, data=None):
        web.load_string(
            "<html><body><p><h1>%s</h1></p>%s</body></html>" % (
            _("Unable to load page"),
            _("Problem occurred while loading the URL '%s'") % (url)),
            "text/html", "UTF-8", "")
        print url
        return True

    # login or switch user
    def weibo_login(self, widget, weibo):
        '''weibo button clicked callback'''
        self.web_view.load_uri("about:blank")
        utils.set_cursor(widget)
        self.set_slide_index(1)
        self.__current_weibo = weibo
        t = threading.Thread(target=self.__current_weibo.request_oauth)
        t.setDaemon(True)
        t.start()

    def weibo_login_thread(self):
        '''in webkit login finish, get user info again'''
        self.__current_weibo.access_token()
        self.get_user_info_again()
        gtk.gdk.threads_enter()
        self.set_slide_index(0)
        gtk.gdk.threads_leave()

    def get_user_info_again(self):
        ''' login or switch user, and get user info again'''
        box = self.__current_weibo.get_box()
        #print "cuurent weibo:", self.__current_weibo.t_type
        gtk.gdk.threads_enter()
        children = box.get_children()
        for child in children:
            if child in self.__weibo_check_button_list:
                self.__weibo_check_button_list.remove(child)
            if child in self.__weibo_image_button_list:
                self.__weibo_image_button_list.remove(child)
            child.destroy()
        gtk.gdk.threads_leave()

        self.get_user_info(self.__current_weibo)

        gtk.gdk.threads_enter()
        box.show_all()
        gtk.gdk.threads_leave()

    def set_slide_index(self, index):
        '''
        set slide to index
        @param index: the index of widget in slider, an int num
        '''
        if index >= len(self.slider_list):
            return
        direct = "right"
        if index == 1 and self.window.button_box in self.window.window_frame.get_children():
            #self.slider.set_size_request(-1, 260)
            win = self.window
            if win.left_button_box in win.button_box.get_children():
                win.button_box.remove(win.left_button_box)
            if win.right_button_box in win.button_box.get_children():
                win.button_box.remove(win.right_button_box)
            tmp = gtk.HSeparator()
            tmp.set_size_request(-1, 1)
            tmp.show()
            win.button_box.pack_start(tmp)
            direct = "right"
            #if self.window.button_box in self.window.window_frame.get_children():
                #self.window.window_frame.remove(self.window.button_box)
        elif index == 0:
            #self.slider.set_size_request(-1, 223)
            win = self.window
            for each in win.button_box.get_children():
                each.destroy()
            if win.left_button_box not in win.button_box.get_children():
                win.button_box.pack_start(win.left_button_box)
            if win.right_button_box not in win.button_box.get_children():
                win.button_box.pack_start(win.right_button_box)
            direct = "left"
            #if self.window.button_box not in self.window.window_frame.get_children():
                #self.window.window_frame.pack_start(self.window.button_box, False, False)
        elif index == 2:
            self.window.left_button_box.set_buttons([])
            l = Label("  ")
            l.show()
            self.window.right_button_box.set_buttons([l])
            direct = "right"
            #self.slider.set_size_request(-1, 223)

        self.slider.slide_to_page(self.slider_list[index], direct)

    def weibo_check_toggle(self, button, weibo):
        '''weibo check button toggled callback. check the weibo to share'''
        if button.get_active():
            self.to_share_weibo[weibo] = 1
        else:
            self.to_share_weibo[weibo] = 0

    def create_ico_image(self, name):
        ''' create image from file'''
        pix1 = app_theme_get_dynamic_pixbuf('image/share/%s.png' % name).get_pixbuf()
        pix2 = app_theme_get_dynamic_pixbuf('image/share/%s_no.png' % name).get_pixbuf()
        return (pix1, pix2)

    def get_user_info(self, weibo):
        '''get weibo user info'''
        info = weibo.get_user_name()
        gtk.gdk.threads_enter()
        #self.get_user_error_text = ""
        weibo_hbox = weibo.get_box()
        hbox = gtk.HBox(False)
        vbox = gtk.VBox(False)
        weibo_hbox.pack_start(vbox, False, False)
        vbox.pack_start(hbox)
        #print weibo.t_type, info
        if info:
            self.is_get_user_info[weibo] = 1
            label = Label(text=info, label_width=70, enable_select=False)
            check = CheckButton()
            #check = gtk.CheckButton()
            check.connect("toggled", self.weibo_check_toggle, weibo)
            check.set_active(True)
            check_vbox = gtk.VBox(False)
            check_align = gtk.Alignment(0.5, 0.5, 0, 0)
            check_align.add(check_vbox)
            check_vbox.pack_start(check, False, False)
            button = ImageButton(
                app_theme.get_pixbuf("share/" + weibo.t_type + ".png"),
                app_theme.get_pixbuf("share/" + weibo.t_type + ".png"),
                app_theme.get_pixbuf("share/" + weibo.t_type + ".png"))
            utils.set_clickable_cursor(button)
            button.connect("enter-notify-event", self.show_tooltip, _("Click to switch user"))
            hbox.pack_start(check_align, False, False)
            hbox.pack_start(button, False, False, 5)
            hbox.pack_start(label, False, False)
        else:
            self.is_get_user_info[weibo] = 0
            check = CheckButton()
            #check = gtk.CheckButton()
            check.set_sensitive(False)
            check_vbox = gtk.VBox(False)
            check_align = gtk.Alignment(0.5, 0.5, 0, 0)
            check_align.add(check_vbox)
            check_vbox.pack_start(check, False, False)
            button = ImageButton(
                app_theme.get_pixbuf("share/" + weibo.t_type + "_no.png"),
                app_theme.get_pixbuf("share/" + weibo.t_type + "_no.png"),
                app_theme.get_pixbuf("share/" + weibo.t_type + "_no.png"))
            utils.set_clickable_cursor(button)
            button.connect("enter-notify-event", self.show_tooltip, _("Click to login"))
            hbox.pack_start(check_align, False, False)
            hbox.pack_start(button, False, False, 5)
            # curl time out
            info_error = weibo.get_curl_error()
            if info_error:
                #self.get_user_error_text += "%s:%s." % (weibo.t_type, _(info_error))
                hbox.pack_start(
                    Label(text="(%s)" % _(info_error), label_width=70,enable_select=False,
                    text_color = ui_theme.get_color("category_item")), False, False)

        button.connect("clicked", self.weibo_login, weibo)
        self.__weibo_check_button_list.append(check)
        self.__weibo_image_button_list.append(button)
        gtk.gdk.threads_leave()
        return weibo_hbox

    def show_tooltip(self, widget, event, text):
        '''Create help tooltip.'''
        Tooltip.text(widget, text)

    def init_user_info_thread(self, button, text_view):
        '''get user name thread'''
        time.sleep(0.1)

        for weibo in self.__weibo_list:
            self.get_user_info(weibo)

        gtk.gdk.threads_enter()
        #self.share_box.set_sensitive(True)
        button.set_sensitive(True)
        text_view.set_editable(True)
        for weibo in self.__weibo_list:
            weibo.get_box().show_all()
            weibo.get_box().queue_draw()
        self.loading_label.destroy()
        gtk.gdk.threads_leave()

    # init share box, create share button, input
    def init_share_box(self):
        '''get weibo info, and create button'''
        self.to_share_weibo = {}
        self.to_share_weibo_res = {}
        self.deepin_info = {}
        self.is_get_user_info = {}
        self.__weibo_check_button_list = []
        self.__weibo_image_button_list = []

        # create Thumbnail
        if exists(self.upload_image):
            pixbuf = gtk.gdk.pixbuf_new_from_file(self.upload_image)
            pix_w = pixbuf.get_width()
            pix_h = pixbuf.get_height()
            if pix_w > pix_h:
                pix_s_w = self.thumb_width
                pix_s_h = int(pix_h / (float(pix_w) / self.thumb_width))
            else:
                pix_s_h = self.thumb_height
                pix_s_w = int(pix_w / (float(pix_h) / self.thumb_height))
            pixbuf = pixbuf.scale_simple(pix_s_w, pix_s_h, gtk.gdk.INTERP_TILES)
            thumb = gtk.image_new_from_pixbuf(pixbuf)
        else:
            thumb = gtk.Image()
        thumb.set_size_request(self.thumb_width, self.thumb_height)

        # weibo context input
        text_box = gtk.HBox(False, 2)
        text_vbox = gtk.VBox(False, 2)
        text_bg_vbox = gtk.VBox(False)
        text_bg_align = gtk.Alignment()
        text_bg_align.set(0.5, 0.5, 0, 0)
        text_bg_align.set_padding(5, 5, 16, 5)
        text_bg_align.connect("expose-event", self.text_view_bg_expose)
        text_scrolled_win = gtk.ScrolledWindow()
        text_scrolled_win.set_policy(gtk.POLICY_NEVER, gtk.POLICY_NEVER)
        text_scrolled_win.set_size_request(340, 157)

        text_view = gtk.TextView()
        text_view.set_left_margin(10)
        text_view.set_right_margin(10)
        text_view.set_pixels_above_lines(5)
        text_view.set_pixels_below_lines(5)
        text_view.set_wrap_mode(gtk.WRAP_WORD| gtk.WRAP_CHAR)
        text_view.connect("expose-event", self.text_view_expose)
        buf = text_view.get_buffer()
        text_scrolled_win.add(text_view)
        text_bg_vbox.pack_start(text_scrolled_win)
        text_bg_align.add(text_bg_vbox)

        text_align = gtk.Alignment()
        text_align.set(0.5, 0.5, 0, 0)
        text_align.set_padding(25, 30, 10, 10)

        text_box.pack_start(thumb, False, False, 10)
        text_box.pack_start(text_bg_align)
        text_vbox.pack_start(text_box, False, False, 10)

        text_align.add(text_vbox)
        #tmp_align = gtk.Alignment()
        #tmp_align.set(0.5, 0, 0, 1)
        #self.share_box.pack_start(tmp_align, False, False)
        self.share_box.pack_start(text_align, False, False)

        # dialog button box
        left_box = self.window.left_button_box
        right_box = self.window.right_button_box

        # input tip label
        self.input_num_label = Label("%d" % self.MAX_CHAR,
            text_size=16, text_x_align=pango.ALIGN_CENTER, label_width=50, enable_select=False)
        self.input_num_label.text_color = ui_theme.get_color("label_select_text")

        # login box
        #weibo_box = gtk.HBox(False, 1)
        #weibo_box.set_size_request(-1, 50)
        weibo_box_list = []
        self.loading_label = Label("%s..." % _("Loading"), text_size=12,
            label_width=70, enable_select=False)
        weibo_box_list.append(self.loading_label)

        for weibo in self.__weibo_list:
            box = gtk.HBox(False, 2)
            weibo.set_box(box)
            weibo_box_list.append(box)
        left_box.set_buttons(weibo_box_list)

        # share button
        button = Button(_("Share"))
        #button.set_size_request(75, 25)
        button.connect("clicked", self.share_button_clicked, text_view)
        buf.connect("changed", self.text_view_changed, button)  # check char num

        tmp_vbox = gtk.VBox(False)
        tmp_align = gtk.Alignment()
        tmp_align.set(0.5, 0.5, 0, 0)
        tmp_vbox.pack_start(button, False, False)
        #tmp_vbox.pack_start(tmp_align)
        tmp_align.add(tmp_vbox)
        right_box.set_buttons([self.input_num_label, tmp_align])

        # at first, set widget insensitive
        button.set_sensitive(False)
        text_view.set_editable(False)
        t = threading.Thread(target=self.init_user_info_thread, args=(button, text_view))
        t.setDaemon(True)
        t.start()

    # draw text view background
    def text_view_bg_expose(self, widget, event):
        '''draw text view bg'''
        cr = widget.window.cairo_create()
        rect = widget.allocation
        text_pixbuf = app_theme_get_dynamic_pixbuf('image/share/text_view.png').get_pixbuf()
        draw.draw_pixbuf(cr, text_pixbuf, rect.x, rect.y)

    # if text is empty, show tip info
    def text_view_expose(self, text_view, event):
        '''text_view expose'''
        buf = text_view.get_buffer()
        text = buf.get_text(*buf.get_bounds())

        if text == "" and text_view.get_editable() and not text_view.is_focus():
            win = text_view.get_window(gtk.TEXT_WINDOW_TEXT)
            cr = win.cairo_create()
            cr.move_to(10, 5)
            context = pangocairo.CairoContext(cr)
            layout = context.create_layout()
            layout.set_font_description(pango.FontDescription("Snas 10"))
            layout.set_alignment(pango.ALIGN_LEFT)
            layout.set_text(_("Please input text here"))
            cr.set_source_rgb(0.66, 0.66, 0.66)
            context.update_layout(layout)
            context.show_layout(layout)

    # show input char num
    def text_view_changed(self, buf, button):
        '''text_view changed callback'''
        count = buf.get_char_count()
        if count <= self.MAX_CHAR:
            #self.input_tip_label.set_text(_("left"))
            self.input_num_label.set_text("%d" % (self.MAX_CHAR - count))
            self.input_num_label.text_color = ui_theme.get_color("category_item")
            if not button.is_sensitive():
                button.set_sensitive(True)
        else:
            #self.input_tip_label.set_text(_("exceeds"))
            self.input_num_label.set_text("-%d" % (count - self.MAX_CHAR))
            self.input_num_label.text_color = ui_theme.get_color("category_item")
            if button.is_sensitive():
                button.set_sensitive(False)

    def show_confirm_dialog(self, title, content):
        d = ConfirmDialog(
                title,
                content,
                text_wrap_width=300,
                )
        d.show_all()
        d.set_transient_for(self.window)

    def share_button_clicked(self, button, text_view):
        '''share_button_clicked callback'''
        # file is not exist.
        if not exists(self.upload_image):
            self.show_confirm_dialog(
                    _("Error"),
                    _("Nonexistent picture"),
                    )
            return False
        has_share_web = False
        for weibo in self.to_share_weibo:
            if self.to_share_weibo[weibo]:
                has_share_web = True
                break
        # have no web selected
        if not has_share_web:
            self.show_confirm_dialog(
                    _("Error"),
                    _("Please choose at least one platform to share on"),
                    )
            return False
        # at first, set widget insensitive
        button.set_sensitive(False)
        text_view.set_editable(False)
        #self.window.left_button_box.set_sensitive(False)
        # set weibo checkbutton sensitive
        for check in self.__weibo_check_button_list:
            check.set_sensitive(False)
        # disconnect weibo ico button clicked function
        for img in self.__weibo_image_button_list:
            try:
                img.disconnect_by_func(self.weibo_login)
            except:
                pass
        button.set_label(_("Sharing"))
        t = threading.Thread(target=self.share_to_weibo_thread, args=(text_view, ))
        t.setDaemon(True)
        t.start()

    # upload image thread
    def share_to_weibo_thread(self, text_view):
        '''share in thread'''
        buf = text_view.get_buffer()
        text = buf.get_text(*buf.get_bounds())
        if text.strip() == "":
            text = _("from Deepin Game")
        # get deepin official info
        self.deepin_info[self.sina] = self.sina.get_deepin_info()
        self.deepin_info[self.qq] = self.qq.get_deepin_info()
        if default_locale != 'zh_CN':
            self.deepin_info[self.twitter] = self.twitter.get_deepin_info()
        # upload
        for weibo in self.to_share_weibo:
            if self.to_share_weibo[weibo]:
                self.to_share_weibo_res[weibo] = weibo.upload_image(self.upload_image, text)
        self.share_to_weibo_result()

    # show upload result
    @post_gui
    def share_to_weibo_result(self):
        '''result of share to weibo'''
        font_color = ui_theme.get_color("category_item")
        res_hbox = gtk.HBox(False)
        res_hbox.set_size_request(-1, 240)

        res_left_box = DialogLeftButtonBox()
        res_right_box = DialogRightButtonBox()

        res_left_box.button_align.set(0.5, 0.0, 0, 1)
        res_right_box.button_align.set(0.5, 0.0, 0, 1)
        res_left_box.button_align.set_padding(5, 9, 19, 0)
        res_right_box.button_align.set_padding(30, 0, 0, 0)

        res_left_box.set_size_request(405, -1)
        res_right_box.set_size_request(195, -1)

        res_hbox.pack_start(res_left_box)
        res_hbox.pack_start(
            VSeparator(app_theme.get_shadow_color("VSeparator").get_color_info(), 0, 0))
        res_hbox.pack_start(res_right_box)

        res_vbox = gtk.VBox(False)
        follow_vbox = gtk.VBox(False)

        tmp_img = gtk.Image()       # only use as a placeholder
        tmp_img.set_size_request(-1, 50)
        res_vbox.pack_start(tmp_img, False, False)

        follow_tip_hbox = gtk.HBox(False)
        img = gtk.image_new_from_icon_name("deepin-logo", 16)
        if img.get_pixel_size() == -1:
            img = gtk.image_new_from_file(app_theme.get_theme_file_path("image/share/deepin_logo.png"))
        follow_tip_hbox.pack_start(img, False, False, 5)
        follow_tip_hbox.pack_start(
            Label("%s %s" % (_("Follow"), "Linux Deepin"),
                text_color=app_theme_get_dynamic_color("#5f5f5f"),
                text_size=12, enable_select=False), False, False)
        follow_vbox.pack_start(follow_tip_hbox, False, False, 13)
        for weibo in self.to_share_weibo_res:
            vbox = gtk.VBox(False, 1)
            tip_box = gtk.HBox()
            error_box = gtk.HBox()
            vbox.pack_start(tip_box, False, False)
            vbox.pack_start(error_box, False, False)
            if self.to_share_weibo_res[weibo][0]:   # upload succeed
                img = gtk.image_new_from_file(app_theme.get_theme_file_path("image/share/share_succeed.png"))
                #link = LinkButton(_(weibo.t_type), text_size=13, self.to_share_weibo_res[weibo][1])
                link = Label(self.weibo_name_l18n[weibo.t_type], text_size=12,
                    text_color=ui_theme.get_color("link_text"))
                #, enable_gaussian=True, gaussian_radious=1, border_radious=0)
                link.add_events(gtk.gdk.BUTTON_PRESS_MASK)
                link.connect("enter-notify-event", lambda w, e: self.__draw_under_line(w))
                link.connect("leave-notify-event", lambda w, e: w.queue_draw())
                link.connect("button-press-event", self.goto_weibo_button_clicked, weibo)
                link_box = gtk.HBox(False)
                link_box.pack_start(link, False, False)
                utils.set_clickable_cursor(link)
                text = _("Share to")
                label = Label(text, text_size=12,
                    text_color=font_color, enable_select=False)
                text = _("Successful")
                label1 = Label(text, text_size=12,
                    text_color=font_color, enable_select=False)
                tip_box.pack_start(img, False, False, 15)
                tip_box.pack_start(label, False, False, 3)
                tip_box.pack_start(link_box, False, False, 3)
                tip_box.pack_start(label1, False, False)
                # only use as a placeholder
                img = gtk.Image()
                img.set_size_request(20, 1)
                error_box.pack_start(img, False, False, 16)
                tmp = Label(" ", text_size=9, label_width=200)
                tmp.set_size_request(200, 1)
                error_box.pack_start(tmp, False, False)
                #print text
            else:   # upload failed
                img = gtk.image_new_from_file(app_theme.get_theme_file_path("image/share/share_failed.png"))
                #text = "% %s %s." % (_(weibo.t_type), _("upload failed"))
                text = _("Share to")
                label1 = Label(text, text_size=12,
                    text_color=font_color, enable_select=False)
                label2 = Label(_(weibo.t_type), text_size=12,
                    text_color=font_color, enable_select=False)
                text = _("Failed")
                label3 = Label(text, text_size=12,
                    text_color=font_color, enable_select=False)
                if weibo.curl.error:
                    error = "(%s)" % _(weibo.curl.error)
                elif weibo.get_error_msg():
                    error = "(%s)" % _(weibo.get_error_msg())
                else:
                    error = "(%s)" % _("Unknown reason")
                #print "%s: %s" % (weibo.t_type, error)
                #print "%s: %s" % (weibo.t_type, weibo.get_error_msg())
                label = Label(text, text_size=12,
                    text_color=font_color, enable_select=False)
                tip_box.pack_start(img, False, False, 15)
                tip_box.pack_start(label1, False, False, 3)
                tip_box.pack_start(label2, False, False, 3)
                tip_box.pack_start(label3, False, False)
                img = gtk.Image()   # only use as a placeholder
                img.set_size_request(20, 20)
                error_box.pack_start(img, False, False, 16)
                error_box.pack_start(Label(error, text_size=9, label_width=200,
                    text_color=font_color, enable_select=False), False, False)
                #print text
            res_vbox.pack_start(vbox, False, False, 10)

        for weibo in self.deepin_info:
            box = gtk.HBox(False, 15)
            # followed
            img = gtk.image_new_from_pixbuf(app_theme.get_pixbuf("share/"+weibo.t_type+".png").get_pixbuf())
            box.pack_start(img, False, False)
            if self.deepin_info[weibo] is not None and self.deepin_info[weibo][3]:
                if not default_locale.startswith("zh_"):
                    button = gtk.image_new_from_pixbuf(
                        app_theme.get_pixbuf("share/followed_en.png").get_pixbuf())
                else:
                    button = gtk.image_new_from_pixbuf(
                        app_theme.get_pixbuf("share/followed.png").get_pixbuf())
            else:   # to follow
                if not default_locale.startswith("zh_"):
                    button = ImageButton(
                        app_theme.get_pixbuf("share/follow_normal_en.png"),
                        app_theme.get_pixbuf("share/follow_hover_en.png"),
                        app_theme.get_pixbuf("share/follow_press_en.png"))
                else:
                    button = ImageButton(
                        app_theme.get_pixbuf("share/follow_normal.png"),
                        app_theme.get_pixbuf("share/follow_hover.png"),
                        app_theme.get_pixbuf("share/follow_press.png"))
                button.connect("clicked", self.friendships_add_button_clicked, weibo, box)
            box.pack_start(button, False, False)
            align = gtk.Alignment()
            align.set(0.0, 0.5, 0, 0)
            align.set_padding(0, 0, 30, 0)
            align.add(box)
            follow_vbox.pack_start(align, False, False, 8)

        res_left_box.set_buttons([res_vbox])
        res_right_box.set_buttons([follow_vbox])

        self.result_box.pack_start(res_hbox, False, False)
        self.result_box.show_all()
        self.set_slide_index(2)

    def goto_weibo_button_clicked(self, widget, event, weibo):
        '''goto my weibo'''
        #print "goto weibo button clicked", weibo.t_type, "xdg-open %s" % self.to_share_weibo_res[weibo][1]
        if weibo in self.to_share_weibo_res:
            if self.to_share_weibo_res[weibo][1]:
                webbrowser.open(self.to_share_weibo_res[weibo][1])

    def friendships_add_button_clicked(self, widget, weibo, box):
        '''add friendships'''
        #self.result_box.set_sensitive(False)
        if not self.is_get_user_info[weibo]:
            utils.run_command("xdg-open %s" % weibo.index_url)
            return True

        widget.set_sensitive(False)
        t = threading.Thread(target=self.friendships_add_thread, args=(widget, weibo, box))
        t.setDaemon(True)
        t.start()

    def friendships_add_thread(self, button, weibo, box):
        '''add friendships'''
        if weibo.friendships_create() is not None:
            gtk.gdk.threads_enter()
            button.destroy()
            if not default_locale.startswith("zh_"):
                button = gtk.image_new_from_pixbuf(
                    app_theme.get_pixbuf("share/followed_en.png").get_pixbuf())
            else:
                button = gtk.image_new_from_pixbuf(
                    app_theme.get_pixbuf("share/followed.png").get_pixbuf())
            button.show()
            box.pack_start(button, False, False)
            #button.set_label("已关注")
            gtk.gdk.threads_leave()

    # show window
    def show(self):
        '''show'''
        self.window.show_window()

    # close widnow
    def quit(self, widget):
        ''' close '''
        gtk.main_quit()

    def __slider_expose(self, widget, event):
        ''' slider expose redraw'''
        cr = widget.window.cairo_create()
        rect = widget.allocation
        cr.set_source_rgba(1.0, 1.0, 1.0, 0.8)
        cr.rectangle(rect.x, rect.y, rect.width, rect.height)
        cr.fill()

    def __expose_top_and_bottome(self, widget, event):
        '''titlebar or button_box expose'''
        cr = widget.window.cairo_create()
        rect = widget.allocation
        cr.set_source_rgb(0.89, 0.89, 0.89)
        cr.rectangle(rect.x+2, rect.y+2, rect.width-4, rect.height-4)
        cr.fill()

    def __draw_under_line(self, widget):
        '''draw under line'''
        cr = widget.window.cairo_create()
        with utils.cairo_disable_antialias(cr):
            x, y, w, h = widget.allocation
            # #1A70b1
            cr.set_source_rgba(0.1, 0.43, 0.69, 1.0)
            cr.set_line_width(1)
            cr.move_to(x, y+h-3)
            cr.line_to(x+w, y+h-3)
            cr.stroke()
Exemple #11
0
     )
 combo_button.connect("button-clicked", click_combo_button)
 combo_button.connect("arrow-clicked", show_combo_menu)
 
 tab_1_box.pack_start(combo_button, False, False)
 
 # Add statusbar.
 statusbar = Statusbar(36)
 tab_1_box.pack_start(statusbar, False)
 application.window.add_move_event(statusbar)
 application.window.add_toggle_event(statusbar)
 
 link_button = LinkButton("加入我们", "http://www.linuxdeepin.com/joinus/job")
 statusbar.status_item_box.pack_start(link_button)
 
 web_view = WebView()
 web_scrolled_window = ScrolledWindow()
 web_scrolled_window.add(web_view)
 web_view.open("http://www.linuxdeepin.com")
 tab_2_box.pack_start(web_scrolled_window)
 
 icon_view_hframe = HorizontalFrame()
 icon_view_vframe = gtk.Alignment()
 icon_view_vframe.set(0, 0, 1, 1)
 icon_view_vframe.set_padding(0, 1, 0, 0)
 
 icon_view_scrolled_window = ScrolledWindow()
 icon_view = IconView(10, 10)
 icon_view_scrolled_window.add_child(icon_view)
 icon_view_hframe.add(icon_view_scrolled_window)
 
    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)
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))
Exemple #14
0
class FlashFrame(dbus.service.Object):
    '''
    class docs
    '''
	
    def __init__(self, session_bus, appid, dbus_name, dbus_path):
        dbus.service.Object.__init__(self, session_bus, dbus_path)

        self.appid = appid
        self.dbus_name = dbus_name
        self.dbus_path = dbus_path
        
        # WARING: only use once in one process
        DBusGMainLoop(set_as_default=True) 
        
        self.plug = gtk.Plug(0)

        self.webview = WebView(COOKIE_FILE)
        self.webview.connect('title-changed', self.webview_message_handler)
        self.webview.connect('script-alert', self.webview_message_handler)
        #self.webview.enable_inspector()
        self.paned_box = PanedBox(2, True, 2, True)
        self.paned_box.enter_bottom_win_callback = self.enter_bottom_notify
        self.paned_box.enter_top_win_callback = self.enter_top_notify
        self.paned_box.add_content_widget(self.webview)
        self.plug.add(self.paned_box)
        self.plug.connect('delete-event', self.plug_delete_event)
        
        # Handle signals.
        self.plug.connect("realize", self.flash_frame_realize)
        self.plug.connect("destroy", self.flash_frame_exit)

        glib.timeout_add(1000, self.is_exist)
        glib.timeout_add(200, self.connect_signal)

        def message_receiver(self, *message):
            message_type, contents = message
            if message_type == 'exit':
                self.exit()
            elif message_type == 'load_uri':
                self.load_flash(contents)
            elif message_type == 'load_loading_uri':
                self.webview.load_uri(contents)
                self.send_message('loading_uri_finish', '')
            elif message_type == 'load_string':
                self.webview.load_string(contents)
            elif message_type == 'get_plug_id':
                self.send_flash_info()
            elif message_type == 'app_info_download_finish':
                self.webview.execute_script("app_info=%s" %
                        json.dumps(str(contents), encoding="UTF-8", ensure_ascii=False))

        setattr(FlashFrame, 
                'message_receiver', 
                dbus.service.method(dbus_name)(message_receiver))

    def plug_delete_event(self, widget, event):
        return True

    def webview_message_handler(self, webview, frame, message):
        if message == 'finish_load':
            self.webview.execute_script('loading_flash(%s)' %
                json.dumps(self.swf_info, encoding="UTF-8", ensure_ascii=False))
        elif message == 'onload_loading':
            self.send_message('onload_loading', '')
            self.webview.execute_script('change_color_theme(%s)' %
                json.dumps(skin_config.theme_name, encoding="UTF-8", ensure_ascii=False))
        return True

    def load_flash(self, contents):
        flash_html_path = os.path.join(static_dir, 'flash.html')
        self.webview.load_uri("file://" + flash_html_path)
        self.swf_info = str(contents).split(',')

    def enter_bottom_notify(self):
        self.send_message('enter_bottom', '')

    def enter_top_notify(self):
        self.send_message('enter_top', '')

    def is_exist(self):
        if dbus.SessionBus().name_has_owner("com.deepin.game_player_%s" % self.appid):
            return True
        else:
            glib.timeout_add(0, gtk.main_quit)
            return False

    def run(self):    
        self.plug.show_all()
        self.paned_box.bottom_window.set_composited(True)
        self.paned_box.top_window.set_composited(True)
        gtk.main()

    def do_delete_event(self, w):
        #a trick to prevent plug destroyed!.  the  better way is recreate an GtkPlug when need reuse it's content
        return True

    def flash_frame_realize(self, widget):
        # Send module information.
        self.send_flash_info()

    def exit(self):
        gtk.main_quit()

    def flash_frame_exit(self, widget):
        gtk.main_quit()
        
    def send_message(self, message_type, message_content):
        session_bus = dbus.SessionBus()
        GAME_PLAYER_DBUS_NAME = "com.deepin.game_player_%s" % self.appid
        GAME_PLAYER_DBUS_PATH = "/com/deepin/game_player_%s" % self.appid
        if is_dbus_name_exists(GAME_PLAYER_DBUS_NAME):

            bus_object = session_bus.get_object(GAME_PLAYER_DBUS_NAME, GAME_PLAYER_DBUS_PATH)
            method = bus_object.get_dbus_method("message_receiver")
            method(message_type, 
                   message_content,
                   reply_handler=self.handle_dbus_reply, # add reply handler
                   error_handler=self.handle_dbus_error  # add error handler
                   )

    def connect_signal(self):
        session_bus = dbus.SessionBus()
        GAME_PLAYER_DBUS_NAME = "com.deepin.game_player_%s" % self.appid
        GAME_PLAYER_DBUS_PATH = "/com/deepin/game_player_%s" % self.appid
        if is_dbus_name_exists(GAME_PLAYER_DBUS_NAME):
            session_bus.add_signal_receiver(
                    self.signal_receiver, 
                    signal_name="update_signal", 
                    dbus_interface=GAME_PLAYER_DBUS_NAME, 
                    path=GAME_PLAYER_DBUS_PATH)
            return False
        else:
            return True

    def signal_receiver(self, message):
        message_type, contents = message
        if message_type == 'download_update':
            self.webview.execute_script('if (fresh_loading){fresh_loading(%s);}' % 
                    json.dumps(str(contents), encoding="UTF-8", ensure_ascii=False))
        elif message_type == 'download_finish':
            self.load_flash(str(contents))
        elif message_type == 'load_uri':
            self.webview.execute_script("window.location.href = %s" %
                    json.dumps(str(contents).split(',')[0], encoding="UTF-8", ensure_ascii=False))
        elif message_type == 'load_loading_uri':
            self.webview.load_uri(contents)
            self.send_message('loading_uri_finish', '')
        elif message_type == 'game_action':
            if contents == 'pause':
                self.webview.execute_script('$("#mask").hide()')
                self.send_message('game_action', 'pause')
            elif contents == 'continue':
                self.webview.execute_script('$("#mask").hide()')
            
    def handle_dbus_reply(self, *reply):
        # print "%s (reply): %s" % (self.module_dbus_name, str(reply))
        pass
        
    def handle_dbus_error(self, *error):
        #print "%s (error): %s" % (self.module_dbus_name, str(error))
        pass
        
    def send_flash_info(self):
        self.send_message("send_plug_id", (self.appid, self.plug.get_id()))
Exemple #15
0
    def fetch_comment(self):
        if is_network_connected():
            container_remove_all(self.right_comment_box)
            loading_label = Label(_("Loading comments..."))
            loading_label_align = gtk.Alignment(0.5, 0, 0, 0)
            loading_label_align.add(loading_label)
            loading_label_align.set_padding(10, 0, 0, 0)
            self.right_comment_box.pack_start(loading_label_align, False,
                                              False)
            web_view = WebView(os.path.join(CONFIG_DIR, "cookie.txt"))
            web_view.connect("new-window-policy-decision-requested",
                             self.open_url)
            web_view.connect('console-message',
                             self.webview_console_message_handler)
            web_view_align = gtk.Alignment()
            web_view_align.set(0.5, 0, 0, 0)
            web_view_align.set_padding(33, 33, 33, 33)
            web_view_align.add(web_view)
            web_settings = web_view.get_settings()
            web_settings.set_property("enable-plugins", False)
            web_settings.set_property("enable-scripts", True)
            web_view.open("%s/softcenter/v1/comment?n=%s&hl=%s" % (
                SERVER_ADDRESS,
                self.pkg_name,
                LANGUAGE,
            ))

            web_view.connect("load-finished", self.comment_load_finished_cb,
                             web_view_align)

            create_thread(self.fetch_screenshot).start()