class PPTPConf(gtk.VBox):
    ENTRY_WIDTH = 222
    LEFT_PADDING = 210
    def __init__(self, connection, module_frame, set_button_callback=None, settings_obj=None):
        gtk.VBox.__init__(self)
        self.connection = connection
        self.tab_name = _("PPTP")
        self.module_frame = module_frame
        self.set_button = set_button_callback
        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj

        self.vpn_setting = self.connection.get_setting("vpn")

        # UI

        pptp_table = gtk.Table(7, 4, False)

        name_label = Label(_("Connection Name:"),
                               enable_select=False,
                               enable_double_click=False)
        name_label.set_can_focus(False)
        gateway_label = Label(_("Gateway:"),
                               enable_select=False,
                               enable_double_click=False)
        gateway_label.set_can_focus(False)
        user_label = Label(_("Username:"******"Password:"******"NT Domain:"),
                               enable_select=False,
                               enable_double_click=False)
        nt_domain_label.set_can_focus(False)
        # Radio Button
        self.pptp_radio = RadioButton(_("PPTP"))
        self.l2tp_radio = RadioButton(_("L2TP"))
        radio_box = gtk.HBox(spacing=30)
        radio_box.pack_start(self.pptp_radio, True, True)
        radio_box.pack_start(self.l2tp_radio, True, True)
        #pack labels
        pptp_table.attach(style.wrap_with_align(radio_box, align="left"), 2,4, 0, 1)
        pptp_table.attach(style.wrap_with_align(name_label, width=self.LEFT_PADDING), 0, 2, 1, 2)
        pptp_table.attach(style.wrap_with_align(gateway_label, width=self.LEFT_PADDING), 0, 2 , 2, 3)
        pptp_table.attach(style.wrap_with_align(user_label, width=self.LEFT_PADDING), 0, 2, 3, 4)
        pptp_table.attach(style.wrap_with_align(password_label, width=self.LEFT_PADDING), 0, 2, 4, 5)
        #pptp_table.attach(style.wrap_with_align(nt_domain_label), 0, 2, 5, 6)

        # entries
        self.name_entry = InputEntry()
        self.name_entry.set_size(self.ENTRY_WIDTH, 22)

        self.gateway_entry = InputEntry()
        self.gateway_entry.set_size(self.ENTRY_WIDTH,22)
        self.user_entry = InputEntry()
        self.user_entry.set_size(self.ENTRY_WIDTH, 22)
        # FIXME should change to new_entry PasswordEntry
        self.password_entry = PasswordEntry()
        self.password_entry.set_size(self.ENTRY_WIDTH, 22)
        self.password_show = CheckButton(_("Show Password"), padding_x=0)
        self.password_show.set_active(False)
        self.password_show.connect("toggled", self.show_password)
        self.nt_domain_entry = InputEntry()
        self.nt_domain_entry.set_size(self.ENTRY_WIDTH, 22)

        #pack entries
        pptp_table.attach(style.wrap_with_align(self.name_entry, align="left"), 2, 4, 1, 2)
        pptp_table.attach(style.wrap_with_align(self.gateway_entry, align="left"), 2, 4, 2, 3)
        pptp_table.attach(style.wrap_with_align(self.user_entry, align="left"), 2, 4, 3, 4)
        pptp_table.attach(style.wrap_with_align(self.password_entry, align="left"), 2, 4, 4, 5)
        pptp_table.attach(style.wrap_with_align(self.password_show, align="left"), 2, 4, 5, 6)
        #pptp_table.attach(style.wrap_with_align(self.nt_domain_entry), 2, 4, 5, 6)
        # Advance setting button
        #advanced_button = Button(_("Advanced Setting"))
        #advanced_button.connect("clicked", self.advanced_button_click)

        #pptp_table.attach(style.wrap_with_align(advanced_button), 3, 4, 6, 7)
        self.service_type = self.vpn_setting.service_type.split(".")[-1]
        if self.service_type == "l2tp":
            self.l2tp_radio.set_active(True)
        else:
            self.pptp_radio.set_active(True)
        self.pptp_radio.connect("toggled",self.radio_toggled, "pptp")
        self.l2tp_radio.connect("toggled",self.radio_toggled, "l2tp")
        # set signals

        #align = style.set_box_with_align(pptp_table, "text")
        table_align = gtk.Alignment(0, 0, 0, 0)
        table_align.add(pptp_table)
        #style.set_table_items(pptp_table, "entry")
        style.draw_background_color(self)
        style.set_table(pptp_table)
        self.add(table_align)
        self.show_all()
        self.refresh()
        self.name_entry.entry.connect("changed", self.entry_changed, "name")
        self.gateway_entry.entry.connect("changed", self.entry_changed, "gateway")
        self.user_entry.entry.connect("changed", self.entry_changed, "user")
        self.password_entry.entry.connect("changed", self.entry_changed, "password")
        self.nt_domain_entry.entry.connect("changed", self.entry_changed, "domain")

        #if self.connection.check_setting_finish():
            #print "in vpn"
            #Dispatcher.set_button("save", True)
        #else:
            #print "in vpn"
            #Dispatcher.set_button("save", False)
        ##############
        #is_valid = self.connection.check_setting_finish()
        #self.settings_obj.vpn_is_valid = is_valid
        #self.settings_obj.set_button("save", is_valid)

    def refresh(self):
        #print ">>>",self.vpn_setting.data
        #print self.vpn_setting.data
        name = self.connection.get_setting("connection").id
        gateway = self.vpn_setting.get_data_item("gateway")
        user = self.vpn_setting.get_data_item("user")
        domain = self.vpn_setting.get_data_item("domain")

        if type(self.connection) == NMRemoteConnection:
            self.name_entry.set_text(name)

        if gateway:
            self.gateway_entry.set_text(gateway)
        if user:
            self.user_entry.set_text(user)

        (setting_name, method) = self.connection.guess_secret_info() 
        try:
            password = nm_module.secret_agent.agent_get_secrets(self.connection.object_path,
                                                    setting_name,
                                                    method)
            if password is None:
                #self.password_entry.entry.set_text("")
                self.password_entry.entry.set_text("")
            else:
                #self.password_entry.entry.set_text(password)
                self.password_entry.entry.set_text(password)
                self.vpn_setting.set_secret_item("password", password)
        except:
            pass

        if domain:
            self.nt_domain_entry.set_text(domain)
                
    def save_setting(self):
        pass

    def show_password(self, widget):
        if widget.get_active():
            self.password_entry.show_password(True)
        else:
            self.password_entry.show_password(False)


    def entry_changed(self, widget, content, item):
        text = content
        if item == "name":
            self.connection.get_setting("connection").id = content

        if text:
            if item == "password":
                self.vpn_setting.set_secret_item(item, text)
            elif item != "name":
                self.vpn_setting.set_data_item(item, text)
            
        else:
            if item == "password":
                self.vpn_setting.set_secret_item(item, "")
            else:
                self.vpn_setting.delete_data_item(item)

        #if self.connection.check_setting_finish():
            #Dispatcher.set_button("save", True)
        #else:
            #Dispatcher.set_button("save", False)
        ##############
        is_valid = self.connection.check_setting_finish()
        self.settings_obj.vpn_is_valid = is_valid
        self.settings_obj.set_button("save", is_valid)
    
    def radio_toggled(self, widget, service_type):
        if widget.get_active():
            self.vpn_setting.service_type = "org.freedesktop.NetworkManager." + service_type
            self.service_type = service_type

        if self.connection.check_setting_finish():
            Dispatcher.set_button("save", True)
        else:
            Dispatcher.set_button("save", False)
            self.refresh()

        Dispatcher.emit("vpn-type-change", self.connection)
            

    def advanced_button_click(self, widget):
        ppp = PPPConf(self.module_frame, Dispatcher.set_button)
        ppp.refresh(self.connection)
        Dispatcher.send_submodule_crumb(3, _("Advanced"))
        nm_module.slider.slide_to_page(ppp, "none")
class BlueToothView(gtk.VBox):
    '''
    class docs
    '''

    def __init__(self, module_frame):
        '''
        init docs
        '''
        gtk.VBox.__init__(self)

        self.module_frame = module_frame

        self.my_bluetooth = MyBluetooth(self.__on_adapter_removed,
                                        self.__on_default_adapter_changed,
                                        self.__device_found)
        self.periodic_timer = None
        self.is_discoverable = False
        self.is_searching = False
        '''
        enable open
        '''
        if self.my_bluetooth.adapter:
            self.my_bluetooth.adapter.connect("property-changed", self.__on_property_changed)
            if self.my_bluetooth.adapter.get_powered():
                self.title_align, self.title_label = self.__setup_title_align(
                    app_theme.get_pixbuf("bluetooth/enable_open.png"), _("Bluetooth"))
                self.title_label.set_sensitive(True)
            else:
                self.title_align, self.title_label = self.__setup_title_align(
                    app_theme.get_pixbuf("bluetooth/enable_open_disable.png"), _("Bluetooth"))
        else:
            self.title_align, self.title_label = self.__setup_title_align(
                app_theme.get_pixbuf("bluetooth/enable_open_disable.png"), _("Bluetooth"))
            self.title_label.set_sensitive(False)
        self.enable_align = self.__setup_align()
        self.enable_box = gtk.HBox(spacing=WIDGET_SPACING)
        self.enable_open_label = self.__setup_label(_("Enable bluetooth"))
        if self.my_bluetooth.adapter:
            self.my_bluetooth.adapter.set_powered(permanent_settings.get_powered())
            self.enable_open_label.set_sensitive(self.my_bluetooth.adapter.get_powered())
        else:
            self.enable_open_label.set_sensitive(False)
        self.enable_open_toggle_align = self.__setup_align(padding_top = 4, padding_left = 158)
        self.enable_open_toggle = self.__setup_toggle()
        if self.my_bluetooth.adapter:
            self.enable_open_toggle.set_active(self.my_bluetooth.adapter.get_powered())
        self.enable_open_toggle.connect("toggled", self.__toggled, "enable_open")
        self.enable_open_toggle_align.add(self.enable_open_toggle)
        self.__widget_pack_start(self.enable_box,
                                 [self.enable_open_label,
                                  self.enable_open_toggle_align])
        self.enable_align.add(self.enable_box)
        '''
        display
        '''
        self.display_align = self.__setup_align()
        self.display_box = gtk.HBox(spacing=WIDGET_SPACING)
        self.display_device_label = self.__setup_label(_("Device name"))
        if self.my_bluetooth.adapter:
            self.display_device_label.set_sensitive(self.my_bluetooth.adapter.get_powered())
        else:
            self.display_device_label.set_sensitive(False)
        self.display_device_entry = InputEntry()
        if self.my_bluetooth.adapter:
            self.display_device_entry.set_text(self.my_bluetooth.adapter.get_name())
            self.display_device_entry.set_sensitive(self.my_bluetooth.adapter.get_powered())
        else:
            self.display_device_entry.set_sensitive(False)
        self.display_device_entry.set_size(HSCALEBAR_WIDTH, WIDGET_HEIGHT)
        self.display_device_entry.entry.connect("changed", self.__display_device_changed)
        self.__widget_pack_start(self.display_box,
                                 [self.display_device_label, self.display_device_entry])
        self.display_align.add(self.display_box)
        '''
        enable searchable
        '''
        self.search_align = self.__setup_align()
        self.search_box = gtk.HBox(spacing=WIDGET_SPACING)
        self.search_label = self.__setup_label(_("Discoverable"))
        if self.my_bluetooth.adapter:
            self.search_label.set_sensitive(self.my_bluetooth.adapter.get_powered())
        else:
            self.search_label.set_sensitive(False)
        self.search_timeout_align = self.__setup_align(padding_top = 0, padding_left = 0)
        self.search_timeout_label = self.__setup_label("", width = 110, align = ALIGN_START)
        self.search_timeout_align.add(self.search_timeout_label)
        self.search_toggle_align = self.__setup_align(padding_top = 4, padding_left = 18)
        self.search_toggle = self.__setup_toggle()
        if self.my_bluetooth.adapter:
            self.search_toggle.set_active(self.my_bluetooth.adapter.get_discoverable())
        self.search_toggle.connect("toggled", self.__toggled, "search")
        self.search_toggle_align.add(self.search_toggle)
        self.__widget_pack_start(self.search_box,
                                 [self.search_label,
                                  self.search_timeout_align,
                                  self.search_toggle_align
                                 ])
        self.search_align.add(self.search_box)
        '''
        device iconview
        '''
        self.device_align = self.__setup_align()
        self.device_iconview = DeviceIconView()
        self.device_iconview.set_size_request(690, 228)
        self.device_align.add(self.device_iconview)
        '''
        operation
        '''
        self.oper_align = self.__setup_align()
        self.oper_box = gtk.HBox(spacing = WIDGET_SPACING)
        self.notice_label = Label("", text_x_align = ALIGN_START, label_width = 610)
        self.search_button = Button(_("Search"))
        if self.my_bluetooth.adapter:
            self.search_button.set_sensitive(self.my_bluetooth.adapter.get_powered())
        else:
            self.search_button.set_sensitive(False)
        self.search_button.connect("clicked", self.__on_search)
        self.__widget_pack_start(self.oper_box,
                [self.notice_label,
                 self.search_button,
                ])
        self.oper_align.add(self.oper_box)
        '''
        this->gtk.VBox pack_start
        '''
        self.__widget_pack_start(self,
                                 [self.title_align,
                                  self.enable_align,
                                  self.display_align,
                                  self.search_align,
                                  self.device_align,
                                  self.oper_align])

        if self.my_bluetooth.adapter == None:
            self.set_sensitive(False)

        self.connect("expose-event", self.__expose)

        if self.my_bluetooth.adapter and self.my_bluetooth.adapter.get_powered():
            self.__get_devices()

    def __on_property_changed(self, adapter, key, value):
        if key == "Powered":
            if value == 1:
                self.enable_open_toggle.set_active(True)
                # removed by hualet, this will cause devices are added twice.
                # self.__set_enable_open(True)
            else:
                self.enable_open_toggle.set_active(False)
                # self.__set_enable_open(False)
        if key == "Devices":    # fixbug: iconview didn't update accordingly 
                                # while adapter paired other devices in system tray. 
            self.device_iconview.clear()
            self.__get_devices()

    def sendfile(self, device_name):
        event_manager.emit("send-file", device_name)

    def cancel(self):
        event_manager.emit("cancel", None)

    def __on_adapter_removed(self):
        self.set_sensitive(False)

    def __on_default_adapter_changed(self):
        self.set_sensitive(True)
        self.display_device_entry.set_text(self.my_bluetooth.adapter.get_name())

    def __display_device_changed(self, widget, event):
        self.my_bluetooth.adapter.set_name(widget.get_text())

    def __setup_separator(self):
        hseparator = HSeparator(app_theme.get_shadow_color("hSeparator").get_color_info(), 0, 0)
        hseparator.set_size_request(500, HSEPARATOR_HEIGHT)
        return hseparator

    def __setup_title_label(self,
                            text="",
                            text_color=app_theme.get_color("globalTitleForeground"),
                            text_size=TITLE_FONT_SIZE,
                            text_x_align=ALIGN_START,
                            label_width=180):
        return Label(text = text,
                     text_color = text_color,
                     text_size = text_size,
                     text_x_align = text_x_align,
                     label_width = label_width,
                     enable_select = False,
                     enable_double_click = False)

    def __setup_title_align(self,
                            pixbuf,
                            text,
                            padding_top=TEXT_WINDOW_TOP_PADDING,
                            padding_left=TEXT_WINDOW_LEFT_PADDING):
        align = self.__setup_align(padding_top = padding_top, padding_left = padding_left)
        align_box = gtk.VBox(spacing = WIDGET_SPACING)
        title_box = gtk.HBox(spacing = WIDGET_SPACING)
        image = ImageBox(pixbuf)
        label = self.__setup_title_label(text)
        separator = self.__setup_separator()
        self.__widget_pack_start(title_box, [image, label])
        self.__widget_pack_start(align_box, [title_box, separator])
        align.add(align_box)
        return align, label

    def __get_devices(self):
        devices = self.my_bluetooth.get_devices()
        items = []
        i = 0

        while i < len(devices):
            items.append(DeviceItem(devices[i].get_name(),
                         app_theme.get_pixbuf("bluetooth/%s.png" % bluetooth_class_to_type(devices[i].get_class())).get_pixbuf(),
                         devices[i],
                         self.my_bluetooth.adapter,
                         devices[i].get_paired(),
                         self.module_frame))
            i += 1

        self.device_iconview.add_items(items)

    def __refresh_notice_label(self):
        searching_str = _("Discovering device")

        if self.notice_label.get_text().count(".") == 3:
            self.notice_label.set_text(searching_str + ".")
        else:
            self.notice_label.set_text(self.notice_label.get_text() + ".")

        return True

    def __on_search(self, widget):
        if not self.is_searching:
            self.my_bluetooth.adapter.start_discovery()
            self.notice_label.set_text(_("Discovering device"))
            self.refresh_lable_timeout = gobject.timeout_add_seconds(1, self.__refresh_notice_label)
            self.my_bluetooth.adapter.connect("property-changed", self.on_adapter_property_changed)
            self.is_searching = True
            
    def on_adapter_property_changed(self, obj, key, value):
        if key == "Discovering" and value == False:
            gobject.source_remove(self.refresh_lable_timeout)
            if self.is_searching:
                self.my_bluetooth.adapter.stop_discovery()
            self.is_searching = False
            self.notice_label.set_text("")

    def __device_found(self, adapter, address, values):
        print "address", address
        if address not in adapter.get_address_records():
            device_path = adapter.create_device(address)
            if device_path == "None":
                return 
            
            device = Device(device_path)
            items = []
        
            if not values.has_key("Name"):
                return
        
            print bluetooth_class_to_type(device.get_class())
            items.append(DeviceItem(values['Name'],
                                    app_theme.get_pixbuf("bluetooth/%s.png" 
                                                         % bluetooth_class_to_type(device.get_class())).get_pixbuf(), 
                                    device, 
                                    adapter))
            self.device_iconview.add_items(items)
                
    def __set_enable_open(self, is_open=True):
        self.enable_open_label.set_sensitive(is_open)
        self.display_device_label.set_sensitive(is_open)
        self.search_label.set_sensitive(is_open)
        self.display_align.set_sensitive(is_open)
        self.display_device_entry.set_sensitive(is_open)
        # self.device_iconview.set_sensitive(is_open)
        self.search_align.set_sensitive(is_open)
        self.search_timeout_label.set_child_visible(False)
        self.search_button.set_sensitive(is_open)
        # changed by hualet, to fix the bug that device icons stay while disabling the iconview widget
        if is_open:
            self.__get_devices()
        else:
            self.device_iconview.clear()

    def __toggled(self, widget, object):
        if self.my_bluetooth.adapter == None:
            return

        if object == "enable_open":
            self.__set_enable_open(widget.get_active())
            permanent_settings.set_powered(widget.get_active())
            self.my_bluetooth.adapter.set_powered(widget.get_active())
            return

        if object == "search":
            self.is_discoverable = widget.get_active()
            self.my_bluetooth.adapter.set_discoverable(self.is_discoverable)
            self.search_timeout_label.set_child_visible(self.is_discoverable)
            if self.is_discoverable:
                self.periodic_timer = PerodicTimer(self, 1)
            else:
                self.periodic_timer.stop()
            return

    def __expose(self, widget, event):
        cr = widget.window.cairo_create()
        rect = widget.allocation

        cr.set_source_rgb(*color_hex_to_cairo(MODULE_BG_COLOR))
        cr.rectangle(rect.x, rect.y, rect.width, rect.height)
        cr.fill()

    def __setup_label(self, text="", width=180, align=ALIGN_END):
        return Label(text, None, TITLE_FONT_SIZE, align, width, False, False, False)

    def __setup_combo(self, items=[], width=HSCALEBAR_WIDTH):
        combo = ComboBox(items, None, 0, width, width)
        combo.set_size_request(width, WIDGET_HEIGHT)
        return combo

    def __setup_toggle(self):
        return ToggleButton(
                app_theme.get_pixbuf("toggle_button/inactive_normal.png"),
                app_theme.get_pixbuf("toggle_button/active_normal.png"),
                inactive_disable_dpixbuf = app_theme.get_pixbuf("toggle_button/inactive_normal.png"),
                active_disable_dpixbuf = app_theme.get_pixbuf("toggle_button/inactive_normal.png"))

    def __setup_align(self, xalign=0, yalign=0, xscale=0, yscale=0,
                      padding_top=BETWEEN_SPACING,
                      padding_bottom=0,
                      padding_left=TEXT_WINDOW_LEFT_PADDING,
                      padding_right=20):
        align = gtk.Alignment()
        align.set(xalign, yalign, xscale, yscale)
        align.set_padding(padding_top, padding_bottom, padding_left, padding_right)
        return align

    def __widget_pack_start(self, parent_widget, widgets=[], expand=False, fill=False):
        if parent_widget == None:
            return
        for item in widgets:
            parent_widget.pack_start(item, expand, fill)
Beispiel #3
0
class SongInfo(gtk.VBox):
    def __init__(self, song=None):
        super(SongInfo, self).__init__()
        self.set_spacing(10)
        block_box = gtk.EventBox()
        block_box.set_visible_window(False)
        block_box.set_size_request(-1, 10)
        self.detail_table = gtk.Table(5, 4)
        self.detail_table.set_row_spacings(5)
        self.create_detail_box()
        self.pack_start(block_box, False, True)
        self.pack_start(self.create_simpler_box(), False, True)
        self.pack_start(create_separator_box(), False, True)
        self.pack_start(self.detail_table, False, True)
        self.pack_start(create_separator_box(), False, True)
        self.pack_start(self.create_location_box(), False, True)

        # update_song.
        if song:
            self.update_song(song)

    def create_simpler_box(self):
        simpler_box = gtk.HBox(spacing=30)
        cover_image_align = gtk.Alignment()
        cover_image_align.set_padding(0, 0, 50, 0)
        self.cover_image = gtk.Image()
        self.cover_image.set_size_request(92, 92)
        cover_image_align.add(self.cover_image)

        content_box_align = gtk.Alignment()
        content_box_align.set_padding(20, 0, 0, 0)
        content_box = gtk.VBox(spacing=5)
        title_box, self.title_label = self.create_combo_label(_("Title"))
        artist_box, self.artist_label = self.create_combo_label(_("Artist"))
        album_box, self.album_label = self.create_combo_label(_("Album"))
        content_box_align.add(content_box)

        content_box.pack_start(title_box, False, False)
        content_box.pack_start(artist_box, False, False)
        content_box.pack_start(album_box, False, False)

        simpler_box.pack_start(cover_image_align, False, False)
        simpler_box.pack_start(content_box_align, False, False)

        return simpler_box

    def create_combo_label(self, title, content=""):
        hbox = gtk.HBox(spacing=5)
        title_label = Label("%s:" % title)
        content_label = Label(content)
        content_label.set_size_request(200, -1)
        hbox.pack_start(title_label, False, False)
        hbox.pack_start(content_label, False, False)
        return hbox, content_label

    def create_detail_box(self):
        self.file_type_label, self.file_format_label = self.create_double_combo_label(
            0, 1, _("Type"), _("Format"))
        self.file_size_label, self.song_duration_label = self.create_double_combo_label(
            1, 2, _("Size"), _("Duration"))
        self.song_bitrate_label, self.song_rate_label = self.create_double_combo_label(
            2, 3, _("Bitrate"), _("Rate"))
        self.song_added_label, self.song_lasted_label = self.create_double_combo_label(
            3, 4, _("Added"), _("Recently"))
        self.song_playcount_label, self.song_date_label = self.create_double_combo_label(
            4, 5, _("Playcount"), _("Date"))

    def get_song_attr(self, song, song_type=True):
        try:
            gio_file = gio.File(self.song.get_path())
            gio_file_info = gio_file.query_info(",".join([
                gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
                gio.FILE_ATTRIBUTE_STANDARD_TYPE,
                gio.FILE_ATTRIBUTE_STANDARD_NAME,
                gio.FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
                gio.FILE_ATTRIBUTE_STANDARD_SIZE,
                gio.FILE_ATTRIBUTE_STANDARD_ICON,
                gio.FILE_ATTRIBUTE_TIME_MODIFIED,
                gio.FILE_ATTRIBUTE_TIME_CHANGED,
            ]))

            info_attr = gio_file_info.get_attribute_as_string(
                gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE)

            if song_type:
                return gio.content_type_get_description(info_attr)
            else:
                return info_attr
        except:
            return ""

    def create_double_combo_label(self,
                                  top_attach,
                                  bottom_attach,
                                  first_label,
                                  second_label,
                                  first_content="",
                                  second_content=""):
        first_label_box = gtk.HBox()
        first_title_label = Label("%s:" % first_label)
        first_label_box.pack_start(create_right_align(), True, True)
        first_label_box.pack_start(first_title_label, False, False)
        first_content_label = Label(first_content)

        second_label_box = gtk.HBox()
        second_title_label = Label(second_label)
        second_label_box.pack_start(create_right_align(), True, True)
        second_label_box.pack_start(second_title_label, False, False)
        second_content_label = Label(second_content)

        self.detail_table.attach(first_label_box, 0, 1, top_attach,
                                 bottom_attach)
        self.detail_table.attach(first_content_label,
                                 1,
                                 2,
                                 top_attach,
                                 bottom_attach,
                                 xpadding=5)
        self.detail_table.attach(second_label_box,
                                 2,
                                 3,
                                 top_attach,
                                 bottom_attach,
                                 xpadding=5)
        self.detail_table.attach(second_content_label, 3, 4, top_attach,
                                 bottom_attach)

        return first_content_label, second_content_label

    def create_location_box(self):
        location_align = gtk.Alignment()
        location_align.set(1.0, 1.0, 0.5, 0.5)
        location_box = gtk.HBox(spacing=5)
        location_label = Label("%s" % _("Location"))
        self.location_entry = InputEntry("")
        self.location_entry.set_size(250, 25)
        open_button = Button(_("Open directory"))
        open_button.connect("clicked", self.open_song_location)
        location_box.pack_start(location_label, False, True)
        location_box.pack_start(self.location_entry, False, True)
        location_box.pack_start(open_button, False, True)
        location_align.add(location_box)
        return location_align

    def open_song_location(self, widget):
        utils.open_file_directory(self.song.get_path())

    def update_song(self, song):
        self.song = song

        # Update simpler.
        self.cover_image.set_from_pixbuf(
            CoverManager.get_pixbuf_from_song(song, 92, 92, False, False))
        self.title_label.set_text(utils.xmlescape(song.get_str("title")))
        self.artist_label.set_text(utils.xmlescape(song.get_str("artist")))
        self.album_label.set_text(utils.xmlescape(song.get_str("album")))

        # Update detail.
        if self.song.get_type() not in ["cue", "local", "cdda"]:
            utils.ThreadRun(self.get_song_attr, self.file_type_label.set_text,
                            (song, True)).start()
            utils.ThreadRun(self.get_song_attr,
                            self.file_format_label.set_text,
                            (song, False)).start()
        else:
            self.file_type_label.set_text(self.get_song_attr(song, True))
            self.file_format_label.set_text(self.get_song_attr(song, False))

        self.file_size_label.set_text(song.get_str("#size"))
        self.song_duration_label.set_text(song.get_str("#duration"))
        self.song_bitrate_label.set_text(song.get_str("#bitrate"))
        self.song_rate_label.set_text(song.get_str("#rate"))
        self.song_added_label.set_text(song.get_str("#added"))
        self.song_lasted_label.set_text(song.get_str("#lastplayed"))
        self.song_playcount_label.set_text(song.get_str("#playcount"))
        self.song_date_label.set_text(song.get_str("#date"))

        # Update location.
        self.location_entry.set_text(song.get_path())
class NewSessionDialog(DialogBox):
    '''
    Simple input dialog.
    
    @undocumented: click_confirm_button
    @undocumented: click_cancel_button
    '''
	
    def __init__(self,
                 default_width=350,
                 default_height=160,
                 confirm_callback=None, 
                 cancel_callback=None):
        '''
        Initialize InputDialog class.
        
        @param title: Input dialog title.
        @param init_text: Initialize input text.
        @param default_width: Width of dialog, default is 330 pixel.
        @param default_height: Height of dialog, default is 330 pixel.
        @param confirm_callback: Callback when user click confirm button, this callback accept one argument that return by user input text.
        @param cancel_callback: Callback when user click cancel button, this callback not need argument.
        '''
        # Init.
        DialogBox.__init__(self, _("Autostart app"), default_width, default_height, DIALOG_MASK_SINGLE_PAGE)
        self.confirm_callback = confirm_callback
        self.cancel_callback = cancel_callback
        self.on_click = None
        
        self.confirm_button = Button(_("OK"))
        self.cancel_button = Button(_("Cancel"))
        
        self.confirm_button.connect("clicked", lambda w: self.click_confirm_button())
        self.cancel_button.connect("clicked", lambda w: self.click_cancel_button())
        self.connect("destroy", self._close_callback) #self.close_callback is None at this moment, so we use _close_callback
        # get system pixbuf
        icon_theme = gtk.IconTheme()
        icon_theme.set_custom_theme("Deepin")
        icon_info = None
        if icon_theme:
            icon_info = icon_theme.lookup_icon("folder-open", 16, gtk.ICON_LOOKUP_NO_SVG)
        
        
        self.icon_pixbuf = None
        if icon_info:
            self.icon_pixbuf = DynamicPixbuf(icon_info.get_filename())
        else:
            self.icon_pixbuf = app_theme.get_pixbuf("navigate/none-small.png")
        
        table = self.add_new_box() 
        self.pack(self.body_box, [table])
        self.right_button_box.set_buttons([self.cancel_button, self.confirm_button])
        
        self.connect("show", self.focus_input)


    def set_on_click(self, func):
        self.on_click = func
    def pack(self, container, widgets, expand=False, fill=False):
        for widget in widgets:
            container.pack_start(widget, expand, fill)

    def add_new_box(self):
        table = gtk.Table()
        #hbox.set_size_request(-1, 30)
        name_label = Label(_("Name:"), enable_select=False)
        name_label.set_can_focus(False)
        exec_label = Label(_("Exec:"), enable_select=False)
        exec_label.set_can_focus(False)
        desc_label = Label(_("Comment:"), enable_select=False)
        desc_label.set_can_focus(False)
        
        self.name_entry = InputEntry()
        self.exec_entry = InputEntry()
        self.desc_entry = InputEntry()
        self.name_entry.set_size(200, 22)
        self.exec_entry.set_size(200, 22)
        self.desc_entry.set_size(200, 22)

        name_label_align = self.wrap_with_align(name_label)
        exec_label_align = self.wrap_with_align(exec_label)
        desc_label_align = self.wrap_with_align(desc_label)

        name_align = style.wrap_with_align(self.name_entry)
        exec_align = style.wrap_with_align(self.exec_entry)
        desc_align = style.wrap_with_align(self.desc_entry)

        table = gtk.Table(3, 4)
        self.table_add(table, [name_label_align, exec_label_align, desc_label_align], 0)
        self.table_add(table, [name_align, exec_align, desc_align], 1)

        open_folder = ImageButton(self.icon_pixbuf, self.icon_pixbuf, self.icon_pixbuf)
        open_folder.connect("clicked", lambda w: OpenFileDialog("Choose file", self, ok_callback=self.ok_callback))
        table.attach(style.wrap_with_align(open_folder), 2, 3, 1, 2)
        
        align = gtk.Alignment(0.5, 0, 0, 0)
        style.set_table(table)
        align.add(table)
        return align

    def table_add(self, table,  widget, column):
        for index, w in enumerate(widget):
            table.attach(w, column, column + 1, index, index + 1)

    def wrap_with_align(self, label):

        align = gtk.Alignment(1, 0.5, 0, 0)
        align.set_padding(0, 0, 1, 0)
        align.add(label)
        return align

    def ok_callback(self, file_name):
        self.exec_entry.set_text(file_name)

    def _close_callback(self, widget):
        self.cancel_callback()
        self.destroy()

        
    def focus_input(self, widget):
        '''
        Grab focus on input entry.
        
        @param widget: InputDialog widget.
        '''
        self.name_entry.entry.grab_focus()        
        
    def click_confirm_button(self):
        '''
        Inernal fucntion to handle click confirm button.
        '''
        if self.confirm_callback != None:
            self.confirm_callback(self)
        
        self.destroy()
        
    def click_cancel_button(self):
        '''
        Inernal fucntion to handle click cancel button.
        '''
        if self.cancel_callback != None:
            self.cancel_callback()
        
        self.destroy()
Beispiel #5
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()
Beispiel #6
0
class NewSessionDialog(DialogBox):
    '''
    Simple input dialog.
    
    @undocumented: click_confirm_button
    @undocumented: click_cancel_button
    '''
    def __init__(self,
                 default_width=350,
                 default_height=160,
                 confirm_callback=None,
                 cancel_callback=None):
        '''
        Initialize InputDialog class.
        
        @param title: Input dialog title.
        @param init_text: Initialize input text.
        @param default_width: Width of dialog, default is 330 pixel.
        @param default_height: Height of dialog, default is 330 pixel.
        @param confirm_callback: Callback when user click confirm button, this callback accept one argument that return by user input text.
        @param cancel_callback: Callback when user click cancel button, this callback not need argument.
        '''
        # Init.
        DialogBox.__init__(self, _("Autostart app"), default_width,
                           default_height, DIALOG_MASK_SINGLE_PAGE)
        self.confirm_callback = confirm_callback
        self.cancel_callback = cancel_callback
        self.on_click = None

        self.confirm_button = Button(_("OK"))
        self.cancel_button = Button(_("Cancel"))

        self.confirm_button.connect("clicked",
                                    lambda w: self.click_confirm_button())
        self.cancel_button.connect("clicked",
                                   lambda w: self.click_cancel_button())
        self.connect(
            "destroy", self._close_callback
        )  #self.close_callback is None at this moment, so we use _close_callback
        # get system pixbuf
        icon_theme = gtk.IconTheme()
        icon_theme.set_custom_theme("Deepin")
        icon_info = None
        if icon_theme:
            icon_info = icon_theme.lookup_icon("folder-open", 16,
                                               gtk.ICON_LOOKUP_NO_SVG)

        self.icon_pixbuf = None
        if icon_info:
            self.icon_pixbuf = DynamicPixbuf(icon_info.get_filename())
        else:
            self.icon_pixbuf = app_theme.get_pixbuf("navigate/none-small.png")

        table = self.add_new_box()
        self.pack(self.body_box, [table])
        self.right_button_box.set_buttons(
            [self.cancel_button, self.confirm_button])

        self.connect("show", self.focus_input)

    def set_on_click(self, func):
        self.on_click = func

    def pack(self, container, widgets, expand=False, fill=False):
        for widget in widgets:
            container.pack_start(widget, expand, fill)

    def add_new_box(self):
        table = gtk.Table()
        #hbox.set_size_request(-1, 30)
        name_label = Label(_("Name:"), enable_select=False)
        name_label.set_can_focus(False)
        exec_label = Label(_("Exec:"), enable_select=False)
        exec_label.set_can_focus(False)
        desc_label = Label(_("Comment:"), enable_select=False)
        desc_label.set_can_focus(False)

        self.name_entry = InputEntry()
        self.exec_entry = InputEntry()
        self.desc_entry = InputEntry()
        self.name_entry.set_size(200, 22)
        self.exec_entry.set_size(200, 22)
        self.desc_entry.set_size(200, 22)

        name_label_align = self.wrap_with_align(name_label)
        exec_label_align = self.wrap_with_align(exec_label)
        desc_label_align = self.wrap_with_align(desc_label)

        name_align = style.wrap_with_align(self.name_entry)
        exec_align = style.wrap_with_align(self.exec_entry)
        desc_align = style.wrap_with_align(self.desc_entry)

        table = gtk.Table(3, 4)
        self.table_add(table,
                       [name_label_align, exec_label_align, desc_label_align],
                       0)
        self.table_add(table, [name_align, exec_align, desc_align], 1)

        open_folder = ImageButton(self.icon_pixbuf, self.icon_pixbuf,
                                  self.icon_pixbuf)
        open_folder.connect(
            "clicked", lambda w: OpenFileDialog(
                "Choose file", self, ok_callback=self.ok_callback))
        table.attach(style.wrap_with_align(open_folder), 2, 3, 1, 2)

        align = gtk.Alignment(0.5, 0, 0, 0)
        style.set_table(table)
        align.add(table)
        return align

    def table_add(self, table, widget, column):
        for index, w in enumerate(widget):
            table.attach(w, column, column + 1, index, index + 1)

    def wrap_with_align(self, label):

        align = gtk.Alignment(1, 0.5, 0, 0)
        align.set_padding(0, 0, 1, 0)
        align.add(label)
        return align

    def ok_callback(self, file_name):
        self.exec_entry.set_text(file_name)

    def _close_callback(self, widget):
        self.cancel_callback()
        self.destroy()

    def focus_input(self, widget):
        '''
        Grab focus on input entry.
        
        @param widget: InputDialog widget.
        '''
        self.name_entry.entry.grab_focus()

    def click_confirm_button(self):
        '''
        Inernal fucntion to handle click confirm button.
        '''
        if self.confirm_callback != None:
            self.confirm_callback(self)

        self.destroy()

    def click_cancel_button(self):
        '''
        Inernal fucntion to handle click cancel button.
        '''
        if self.cancel_callback != None:
            self.cancel_callback()

        self.destroy()
class DSLConf(gtk.VBox):
    LEFT_PADDING = 210

    def __init__(self, connection, set_button_callback=None, settings_obj=None):
        gtk.VBox.__init__(self)
        self.tab_name = _("DSL")
        self.connection = connection
        self.set_button = set_button_callback
        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj
        self.dsl_setting = self.connection.get_setting("pppoe")

        # UI
        dsl_table = gtk.Table(5, 3, False)
        ssid_label = Label(_("Connection Name:"),
                               text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        ssid_label.set_can_focus(False)

        username_label = Label(_("Username:"******"Service:"), 
                              text_size=CONTENT_FONT_SIZE,
                              enable_select=False,
                              enable_double_click=False)
        service_label.set_can_focus(False)
        password_label = Label(_("Password:"******"Show Password"), font_size=CONTENT_FONT_SIZE, padding_x=0)
        def show_password(widget):
            if widget.get_active():
                self.password_entry.show_password(True)
            else:
                self.password_entry.show_password(False)
        self.show_password.connect("toggled", show_password)

        #pack entries
        dsl_table.attach(style.wrap_with_align(self.ssid_entry, align="left"), 1, 3, 0, 1)
        dsl_table.attach(style.wrap_with_align(self.username_entry, align="left"), 1, 3, 1, 2)
        dsl_table.attach(style.wrap_with_align(self.service_entry, align="left"), 1, 3, 2, 3)
        dsl_table.attach(style.wrap_with_align(self.password_entry, align="left"), 1, 3, 3, 4)
        dsl_table.attach(style.wrap_with_align(self.show_password, align="left"), 1, 3, 4, 5)

        style.draw_background_color(self)
        style.set_table(dsl_table)
        # just make table postion looks right
        table_align = gtk.Alignment(0, 0, 0, 0)
        table_align.add(dsl_table)
        self.pack_start(table_align, False, False)
        #self.add(align)
        self.show_all()
        self.refresh()

        self.ssid_entry.entry.connect("changed", self.save_changes, "ssid")
        self.username_entry.entry.connect("changed", self.save_changes, "username")
        self.service_entry.entry.connect("changed", self.save_changes, "service")
        self.password_entry.entry.connect("changed", self.save_changes, "password")

    def refresh(self):
        #print ">>>",self.connection.settings_dict
        # get dsl settings
        ssid = self.connection.get_setting("connection").id
        if type(self.connection) == NMRemoteConnection:
            self.ssid_entry.set_text(ssid)
        username = self.dsl_setting.username
        service = self.dsl_setting.service
        (setting_name, method) = self.connection.guess_secret_info() 
        try:
            password = nm_module.secret_agent.agent_get_secrets(self.connection.object_path,
                                                    setting_name,
                                                    method)
        except:
            password = ""
        # check if empty
        if username == None:
            username = ""
        if service == None:
            service = ""
        if password == None:
            password = ""
            self.settings_obj.dsl_is_valid = False
        # fill entry
        self.username_entry.entry.set_text(str(username))
        self.service_entry.entry.set_text(str(service))
        self.password_entry.entry.set_text(str(password))
        setattr(self.dsl_setting, "password", str(password))

    def save_changes(self, widget, value, types):
        if types == "ssid":
            self.connection.get_setting("connection").id = value
        else:
            if value:
                
                setattr(self.dsl_setting, types, value)
            else:
                delattr(self.dsl_setting, types)
        #check_settings(self.connection, self.set_button)
        ############
        is_valid = self.connection.check_setting_finish()
        self.settings_obj.dsl_is_valid = is_valid
        self.settings_obj.set_button("save", is_valid)
class DscPreferenceDialog(PreferenceDialog):
    def __init__(self):
        PreferenceDialog.__init__(self, 566, 488)

        self.current_mirror_item = None
        self.normal_settings = gtk.VBox()
        self.normal_settings.set_spacing(TABLE_ROW_SPACING)
        self.normal_settings.pack_start(self.create_uninstall_box(), False, True)
        self.normal_settings.pack_start(self.create_download_dir_table(), False, True)

        self.normal_settings_align = gtk.Alignment(0, 0, 1, 1)
        self.normal_settings_align.set_padding(padding_left=5, padding_right=5, padding_top=25, padding_bottom=10)
        self.normal_settings_align.add(self.normal_settings)

        self.mirror_settings = gtk.VBox()
        self.mirror_settings.set_app_paintable(True)
        self.mirror_settings.connect("expose-event", self.mirror_settings_align_expose)
        self.mirror_settings.set_spacing(TABLE_ROW_SPACING)
        self.mirror_settings.pack_start(self.create_mirror_select_table(), False, True)
        self.mirror_settings.pack_start(self.create_source_update_frequency_table(), False, True)

        self.mirror_settings_inner_align = gtk.Alignment(0.5, 0.5, 1, 1)
        self.mirror_settings_inner_align.set_padding(padding_top=25, padding_bottom=10, padding_left=0, padding_right=0)
        self.mirror_settings_inner_align.add(self.mirror_settings)

        self.mirror_settings_scrolled_win = ScrolledWindow()
        self.mirror_settings_scrolled_win.add_child(self.mirror_settings_inner_align)

        self.mirror_settings_align = gtk.Alignment(0, 0, 1, 1)
        self.mirror_settings_align.set_padding(padding_left=0, padding_right=0, padding_top=0, padding_bottom=3)
        self.mirror_settings_align.add(self.mirror_settings_scrolled_win)

        self.set_preference_items([
            (_("General"), self.normal_settings_align),
            (_("Mirrors"), self.mirror_settings_align),
            (_("About"), AboutBox()),
            ])
        
    def mirror_settings_align_expose(self, widget, event=None):
        cr = widget.window.cairo_create()
        rect = widget.allocation

        # draw backgound
        cr.rectangle(*rect)
        #cr.set_source_rgb(*color_hex_to_cairo("#ff0000"))
        cr.set_source_rgba(1, 1, 1, 0)
        cr.fill()

    def mirror_select_action(self, repo_urls):
        self.data_manager.change_source_list(repo_urls, reply_handler=handle_dbus_reply, error_handler=handle_dbus_error)

    def create_mirror_select_table(self):
        vbox = gtk.VBox()
        vbox.set_size_request(423, -1)
        main_table = gtk.Table(2, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        
        dir_title_label = Label(_("Select mirror"))
        dir_title_label.set_size_request(423, 12)
        label_align = gtk.Alignment()
        label_align.set_padding(0, 0, 10, 0)
        label_align.add(dir_title_label)

        self.mirrors_dir = os.path.join(get_parent_dir(__file__, 2), 'mirrors')
        self.current_mirror_hostname = utils.get_current_mirror_hostname()
        self.mirror_items = self.get_mirror_items()
        self.mirror_view = TreeView(self.mirror_items,
                                enable_drag_drop=False,
                                enable_multiple_select=False,
                                #mask_bound_height=0,
                             )
        self.mirror_view.set_expand_column(1)
        self.mirror_view.set_size_request(-1, len(self.mirror_view.visible_items) * self.mirror_view.visible_items[0].get_height())
        self.mirror_view.draw_mask = self.mirror_treeview_draw_mask
        #self.display_current_mirror()

        self.mirror_test_progressbar = ProgressBar()

        main_table.attach(label_align, 0, 2, 0, 1, yoptions=gtk.FILL, xpadding=8)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        
        title = _("Select best mirror")
        info_message = _("Please wait. The process will take 30 seconds or more depending on your network connection")
        self.select_best_mirror_dialog = WaitingDialog(title, info_message, self.cancel_mirror_test)
        global_event.register_event("mirror-changed", self.mirror_changed_handler)
        global_event.register_event("update-list-finish", self.update_list_finish_handler)

        vbox.pack_start(main_table, False, False)
        vbox.pack_start(self.mirror_view, False, False)

        return vbox

    def cancel_mirror_test(self, widget):
        try:
            self.mirror_test.terminated = True
            gobject.source_remove(self.update_status_id)
        except:
            pass
        self.select_best_mirror_dialog.hide_all()

    def update_list_finish_handler(self):
        self.select_best_mirror_dialog.hide_all()

    def mirror_changed_handler(self, item):
        for i in self.mirror_items:
            if i != item and i.radio_button.active == True:
                i.radio_button.active = False
            elif i == item:
                i.radio_button.active = True
        self.mirror_view.queue_draw()
    
    def test_mirror_action(self, widget):
        self.select_best_mirror_dialog.set_transient_for(self)
        self.select_best_mirror_dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        self.select_best_mirror_dialog.show_all()
        distro = aptsources.distro.get_distro()
        #distro.get_sources(SourcesList())
        pipe = os.popen("dpkg --print-architecture")
        arch = pipe.read().strip()
        test_file = "dists/%s/Contents-%s.gz" % \
                    (
                    distro.codename,
                    #"quantal",
                    arch,
                    )

        self.mirror_test = MirrorTest(self.mirrors_list, test_file)
        self.mirror_test.start()

        # now run the tests in a background thread, and update the UI on each event
        self.update_status_id = gtk.timeout_add(100, self.update_progress)

    def update_progress(self):
        if self.mirror_test.running:
            return True
        else:
            time.sleep(1)
            if self.mirror_test.best != None:
                for item in self.mirror_items:
                    if item.mirror == self.mirror_test.best[1]:
                        print item.mirror.get_repo_urls()
                        self.mirror_clicked_callback(item)
            else:
                self.select_best_mirror_dialog.loading_widget.hide_all()
                self.select_best_mirror_dialog.info_message_label.set_text(_("Test for downloading mirror failed. Please check your network connection."))
                self.select_best_mirror_dialog.close_button.set_label(_("Close"))
            return False

    def mirror_treeview_draw_mask(self, cr, x, y, w, h):
        cr.set_source_rgba(1, 1, 1, 0.9)
        cr.rectangle(x, y, w, h)
        cr.fill()

    def get_mirror_items(self):
        items = []
        self.mirrors_list = []
        for ini_file in os.listdir(self.mirrors_dir):
            m = Mirror(os.path.join(self.mirrors_dir, ini_file))
            item = MirrorItem(m, self.mirror_clicked_callback)
            if m.hostname == self.current_mirror_hostname:
                item.radio_button.active = True
                self.current_mirror_item = item
            self.mirrors_list.append(m)
            items.append(item)
        
        items.sort(key=lambda x:x.mirror.priority)
        
        return items

    def mirror_clicked_callback(self, item):
        if item != self.current_mirror_item:
            self.current_mirror_item = item
            global_event.emit('change-mirror', item)
            self.hide_all()

    def create_source_update_frequency_table(self):
        main_table = gtk.Table(3, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        
        dir_title_label = Label(_("Update applications lists"))
        dir_title_label.set_size_request(200, 12)
        label_align = gtk.Alignment()
        label_align.set_padding(0, 0, 0, 0)
        label_align.add(dir_title_label)

        self.is_auto_update_button = CheckButton(label_text=_('Update automatically'))
        self.is_auto_update_button.connect('toggled', self.change_auto_update)
        
        self.update_label = Label(_("Time interval: "))
        self.update_spin = SpinBox(int(get_update_interval()), 0, 168, 1)
        self.update_spin.connect("value-changed", lambda w, v: set_update_interval(v))
        self.hour_lablel = Label(_(" hour"))
        self.hour_lablel.set_size_request(50, 12)
        spin_hbox = gtk.HBox(spacing=3)
        spin_hbox.pack_start(self.update_label, False, False)
        spin_hbox.pack_start(self.update_spin, False, False)
        spin_hbox.pack_start(self.hour_lablel, False, False)

        main_table.attach(label_align, 0, 2, 0, 1, yoptions=gtk.FILL, xpadding=8)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(self.is_auto_update_button, 0, 1, 2, 3, xpadding=10, xoptions=gtk.FILL)
        main_table.attach(spin_hbox, 1, 2, 2, 3, xpadding=10, xoptions=gtk.FILL)

        if is_auto_update():
            self.is_auto_update_button.set_active(True)
        else:
            self.is_auto_update_button.toggled()

        return main_table

    def create_download_dir_table(self):    
        main_table = gtk.Table(4, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        
        dir_title_label = Label(_("Download settings"))
        dir_title_label.set_size_request(200, 12)
        label_align = gtk.Alignment()
        label_align.set_padding(0, 0, 0, 0)
        label_align.add(dir_title_label)

        download_number_label = Label(_('Max download task number: '))
        self.download_number_comobox = ComboBox(
                items = [(str(i+1), i+1) for i in range(10)],
                select_index = int(get_download_number())-1,
                )
        self.download_number_comobox.connect("item-selected", self.download_number_comobox_changed)
        download_number_hbox = gtk.HBox(spacing=5)
        download_number_hbox.pack_start(download_number_label, False, False)
        download_number_hbox.pack_start(self.download_number_comobox, False, False)
        
        change_download_dir_label = Label(_("Download directory: "))
        self.dir_entry = InputEntry()
        self.dir_entry.set_text(get_software_download_dir())
        self.dir_entry.set_editable(False)
        self.dir_entry.set_size(200, 25)
        
        modify_button = Button(_("Change"))
        modify_button.connect("clicked", self.change_download_save_dir)
        download_dir_hbox = gtk.HBox(spacing=5)
        download_dir_hbox.pack_start(change_download_dir_label, False, False)
        download_dir_hbox.pack_start(self.dir_entry, False, False)
        download_dir_hbox.pack_start(modify_button, False, False)
        
        main_table.attach(label_align, 0, 2, 0, 1, yoptions=gtk.FILL, xpadding=8)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(download_number_hbox, 0, 2, 2, 3, xpadding=10, xoptions=gtk.FILL)
        main_table.attach(download_dir_hbox, 0, 2, 3, 4, xpadding=10, xoptions=gtk.FILL)
        return main_table

    def create_uninstall_box(self):
        main_table = gtk.Table(2, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        uninstall_title_label = Label(_("On uninstall software"))
        uninstall_title_label.set_size_request(350, 12)
        
        # mini_check_button

        self.delete_check_button = CheckButton(_("Delete configuration files"))
        self.delete_check_button.set_active(get_purg_flag())
        self.delete_check_button.connect("toggled", lambda w: set_purge_flag(self.delete_check_button.get_active()))
        
        main_table.attach(uninstall_title_label, 0, 2, 0, 1, yoptions=gtk.FILL, xpadding=8)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(self.delete_check_button, 0, 1, 2, 3, yoptions=gtk.FILL)
        
        return main_table

    def change_download_save_dir(self, widget):
        local_dir = WinDir(False).run()
        if local_dir:
            local_dir = os.path.expanduser(local_dir)
            if local_dir != get_software_download_dir():
                self.dir_entry.set_editable(True)        
                self.dir_entry.set_text(local_dir)
                self.dir_entry.set_editable(False)
                set_software_download_dir(local_dir)
                global_event.emit('download-directory-changed')

    def download_number_comobox_changed(self, widget, name, value, index):
        set_download_number(value)
        global_event.emit('max-download-number-changed', value)

    def change_auto_update(self, widget, data=None):
        self.update_spin.set_sensitive(widget.get_active())
        set_auto_update(widget.get_active())
        self.update_label.set_sensitive(widget.get_active())
        self.hour_lablel.set_sensitive(widget.get_active())
        dsc_daemon_path = os.path.join(get_parent_dir(__file__, 2), 'update_data/apt/dsc-daemon.py')
        if widget.get_active():
            subprocess.Popen(['python', dsc_daemon_path], stderr=subprocess.STDOUT, shell=False)
class Form(DialogBox):
    def __init__(self):
        DialogBox.__init__(
            self,
            _("Convert"),
            FORM_WIDTH,
            FORM_HEIGHT,
            mask_type=DIALOG_MASK_SINGLE_PAGE,
            close_callback=self.hide_all,
            modal=True,
            window_hint=gtk.gdk.WINDOW_TYPE_HINT_DIALOG,
            window_pos=gtk.WIN_POS_CENTER,
            # skip_taskbar_hint=False,
            resizable=False,
        )
        # Init value.
        self.init_value()
        # Init all widgets.
        self.InitializeComponent()

    def init_value(self):
        read_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "xml")
        self.read_xml = ReadXml(read_path)
        self.model_dict = {}

        # init brand EN list.
        self.brand_dict = {
            "intel": _("intel"),
            "zte": _("zte"),
            "hasee": _("hasee"),
            "apple": _("apple"),
            "nokia": _("nokia"),
            "alcatel": _("alcatel"),
            "google": _("google"),
            "asus": _("asus"),
            "hp": _("hp"),
            "sony": _("sony"),
            "hedy": _("hedy"),
            "archos": _("archos"),
            "boway": _("boway"),
            "bird": _("bird"),
            "vivo": _("vivo"),
            "great wall": _("great wall"),
            "changhong": _("changhong"),
            "skyworth": _("skyworth"),
            "dell": _("dell"),
            "philips": _("philips"),
            "toshiba": _("toshiba"),
            "amazon": _("amazon"),
            "sdo": _("sdo"),
            "disney": _("disney"),
            "haier": _("haier"),
            "fujitsu": _("fujitsu"),
            "acer": _("acer"),
            "lenovo": _("lenovo"),
            "gigabyte": _("gigabyte"),
            "xiaomi": _("xiaomi"),
            "huawei": _("huawei"),
            "blackberry": _("blackberry"),
            "motorola": _("motorola"),
            "sangsung": _("sangsung"),
            "meizu ": _("meizu "),
            "benq": _("benq"),
            "panasonic": _("panasonic"),
            "sony ericsson": _("sony ericsson"),
            "pioneer": _("pioneer"),
            "hyundai": _("hyundai"),
            "newman": _("newman"),
            "coolpad": _("coolpad"),
            "malata": _("malata"),
            "malata": _("malata"),
            "sharp": _("sharp"),
            "gionee": _("gionee"),
            "k-touch": _("k-touch"),
            "Pantech": _("Pantech"),
            "hisense": _("hisense"),
            "teclast": _("teclast"),
            "cube": _("cube"),
            "amoi": _("amoi"),
            "doov": _("doov"),
            "minte": _("minte"),
            "dopod": _("dopod"),
            "eton": _("eton"),
            "cherr": _("cherr"),
            "gaoxinqi": _("gaoxinqi"),
            "konka": _("konka"),
            "viewsonic": _("viewsonic"),
            "xibo": _("xibo"),
            "hosin": _("hosin"),
            "apanda": _("apanda"),
            "iocean": _("iocean"),
            "mastone": _("mastone"),
        }

    def InitializeComponent(self):
        # Init form event.
        # self.connect("destroy", lambda w : self.destroy())
        self.connect("destroy", lambda w: self.hide_all())
        # Init widgets.
        self.brand_label = Label("%s: " % _("Phone brand"))
        self.format_label = Label("%s: " % _("Output format"))
        self.bit_rate_label = Label("%s: " % _("Audio encoder"))
        self.frame_rate_label = Label("%s: " % _("Video encoder"))
        self.path_label = Label("%s: " % _("Output directory"))
        self.model_label = Label("%s: " % _("Phone model"))
        self.ratio_label = Label("    %s: " % _("Resolution"))

        self.path_entry = InputEntry()
        self.save_path_entry = InputEntry()
        fixed_width = 108
        self.brand_combo = NewComboBox(fixed_width)
        self.format_combo = NewComboBox(fixed_width)
        self.bit_rate_combo = NewComboBox(fixed_width)
        self.frame_rate_combo = NewComboBox(fixed_width)
        self.model_combo = NewComboBox(fixed_width)
        self.ratio_combo = NewComboBox(fixed_width)

        self.modify_chooser_btn = FileChooserButton("选择")  # connect self.FileChooser
        self.save_chooser_btn = Button(_("Change"))
        self.start_btn = Button(_("Start"))
        self.close_btn = Button(_("Close"))
        self.higt_set_bool = False
        self.higt_set_btn = LabelButton()  # Button(_("Advanced"))

        self.show_and_hide_task_btn = Button(_("Task Manager"))

        self.higt_hbox = gtk.HBox()
        self.higt_hbox.pack_start(self.higt_set_btn)

        self.higt_align = gtk.Alignment()
        self.higt_align.add(self.higt_hbox)
        self.higt_align.set_padding(0, 0, 7, 0)
        self.higt_align.set(1, 0, 1, 0)

        self.left_button_box.set_buttons([self.higt_align])
        self.right_button_box.set_buttons([self.start_btn, self.close_btn])

        # ratio_combo.
        self.__ratio_list = [
            "176 x 220",
            "240 x 320",
            "320 x 240",
            "320 x 480",
            "400 x 240",
            "480 x 800",
            "540 x 960",
            "600 x 1024",
            "640 x 480",
            "720 x 1280",
            "800 x 480",
            "800 x 600",
            "1024 x 600",
            "1024 x 768",
            "1152 x 864",
        ]
        self.ratio_items = []
        for ratio in self.__ratio_list:
            self.ratio_combo.append_text(ratio)
            self.ratio_items.append((ratio, ratio))
        self.ratio_combo.set_active(5)
        # brand_combo.
        brand_items = []
        for brand in self.read_xml.brand_dict.keys():
            brand_po = brand
            if self.brand_dict.has_key(brand):
                brand_po = self.brand_dict[brand]
            brand_items.append((brand_po, brand))

        self.brand_combo.set_items(brand_items, 0)
        # self.brand_combo.add_items(brand_items, 0)

        self.brand_combo.prepend_text(_("No Presets"))
        self.brand_combo.connect("changed", self.brand_combo_item_selected)
        # model_combo.
        self.model_label.set_sensitive(False)
        self.model_combo.set_sensitive(False)
        self.model_combo.prepend_text(_("No Model"))
        self.model_combo.connect("changed", self.model_combo_item_selected)
        #
        self.save_chooser_btn.set_size_request(75, 21)
        self.save_chooser_btn.connect("clicked", self.save_chooser_btn_clicked)

        # path_entry.
        PATH_ENTRY_WIDTH = 240
        PATH_ENTRY_HEIGHT = 22
        self.save_path_entry.set_sensitive(False)
        self.save_path_entry.set_text(self.get_home_path())
        self.save_path_entry.set_size(PATH_ENTRY_WIDTH, PATH_ENTRY_HEIGHT)
        self.close_btn.connect("clicked", lambda w: self.hide_all())
        # higt_set_btn.
        self.higt_set_btn.connect("clicked", self.higt_set_btn_clicked)

        # form body box add main fixed.
        self.body_table_ali = gtk.Alignment()
        self.body_table_ali.set_padding(6, 0, 0, 0)
        self.body_table = gtk.Table(rows=6, columns=4, homogeneous=False)
        self.body_table_ali.add(self.body_table)

        self.brand_model_hbox = gtk.HBox()
        top, bottom = 5, 5
        brand_position = eval(_("('brand_position', 20)"))
        model_position = eval(_("('model_position', 20)"))
        self.brand_hbox_ali, self.brand_hbox = self.create_hbox(
            bottom, top, 15 + int(brand_position[1]), 0, self.brand_label, self.brand_combo
        )
        self.model_hbox_ali, self.model_hbox = self.create_hbox(
            bottom, top, 50 - int(model_position[1]), 0, self.model_label, self.model_combo
        )

        self.brand_model_hbox.pack_start(self.brand_hbox_ali, False, False)
        self.brand_model_hbox.pack_start(self.model_hbox_ali, False, False)
        format_position = eval(_("('format_position', 12)"))
        ratio_position = eval(_("('ratio_position', 18)"))
        self.format_hbox_ali, self.format_hbox = self.create_hbox(
            bottom, top, 15 + int(format_position[1]), 0, self.format_label, self.format_combo
        )
        self.ratio_hbox_ali, ratio_hbox = self.create_hbox(
            bottom, top, 50 - int(ratio_position[1]), 0, self.ratio_label, self.ratio_combo
        )

        self.format_ratio_hbox = gtk.HBox()
        self.format_ratio_hbox.pack_start(self.format_hbox_ali, False, False)
        self.format_ratio_hbox.pack_start(self.ratio_hbox_ali, False, False)

        frame_rate_position = eval(_("('frame_position', 13)"))
        bit_rate_position = eval(_("('bit_rate_position', 28)"))
        self.frame_rate_hbox_ali, self.frame_rate_hbox = self.create_hbox(
            bottom, top, 15 + int(frame_rate_position[1]), 0, self.frame_rate_label, self.frame_rate_combo
        )
        self.bit_rate_hbox_ali, self.bit_rate_hbox = self.create_hbox(
            bottom, top, 50 - int(bit_rate_position[1]), 0, self.bit_rate_label, self.bit_rate_combo
        )

        self.bit_frame_hbox = gtk.HBox()
        self.bit_frame_hbox.pack_start(self.frame_rate_hbox_ali, False, False)
        self.bit_frame_hbox.pack_start(self.bit_rate_hbox_ali, False, False)

        # self.path_label, self.save_path_entry, self.save_chooser_btn
        self.save_path_hbox_ali = gtk.Alignment()
        self.save_path_hbox = gtk.HBox()
        self.save_path_hbox_ali.set_padding(5, 5, 16, 0)
        self.save_path_hbox_ali.add(self.save_path_hbox)

        self.save_path_entry_ali = gtk.Alignment()
        self.save_path_entry_ali.set_padding(1, 0, 0, 0)
        self.save_path_entry_ali.add(self.save_path_entry)

        self.save_chooser_btn_ali = gtk.Alignment()
        self.save_chooser_btn_ali.set_padding(0, 0, 10, 0)
        self.save_chooser_btn_ali.add(self.save_chooser_btn)

        self.save_path_hbox.pack_start(self.path_label, False, False)
        self.save_path_hbox.pack_start(self.save_path_entry_ali, False, False)
        self.save_path_hbox.pack_start(self.save_chooser_btn_ali, False, False)

        # left right top, bottom.
        """brand_model_hbox."""
        # self.body_table.attach(self.brand_model_hbox, 0, 1, 0, 1, gtk.EXPAND, gtk.EXPAND)
        self.body_table.attach(self.brand_model_hbox, 0, 1, 0, 1, gtk.FILL, gtk.FILL)
        # self.body_table.attach(self.model_hbox, 1, 2, 0, 1, gtk.EXPAND, gtk.EXPAND)
        # self.body_table.attach(self.model_hbox, 2, 3, 0, 1, gtk.EXPAND, gtk.EXPAND)
        # self.body_table.attach(self.model_hbox, 3, 4, 0, 1, gtk.EXPAND, gtk.EXPAND)
        """format_ratio_hbox."""
        # self.body_table.attach(self.format_ratio_hbox, 0, 1, 1, 2, gtk.EXPAND, gtk.EXPAND)
        self.body_table.attach(self.format_ratio_hbox, 0, 1, 1, 2, gtk.FILL, gtk.FILL)
        # self.body_table.attach(self.format_combo, 1, 2, 1, 2, gtk.EXPAND, gtk.EXPAND)
        # self.body_table.attach(self.ratio_hbox, 2, 3, 1, 2, gtk.EXPAND, gtk.EXPAND)
        # self.body_table.attach(self.ratio_combo, 3, 4, 1, 2, gtk.EXPAND, gtk.EXPAND)
        """bit_frame_hbox."""
        # self.body_table.attach(self.bit_frame_hbox, 0, 1, 2, 3, gtk.EXPAND, gtk.EXPAND)
        self.body_table.attach(self.bit_frame_hbox, 0, 1, 2, 3, gtk.FILL, gtk.FILL)
        """save_path_hbox."""
        # self.body_table.attach(self.save_path_hbox_ali, 0, 1, 3, 4, gtk.EXPAND, gtk.EXPAND)
        self.body_table.attach(self.save_path_hbox_ali, 0, 1, 3, 4, gtk.FILL, gtk.FILL)

        self.body_box.pack_start(self.body_table_ali, True, True)
        self.hide_setting()

    def create_hbox(self, top, bottom, left, right, child1, child2):
        hbox_ali = gtk.Alignment()
        hbox_ali.set_padding(top, bottom, left, right)
        hbox = gtk.HBox()
        hbox_ali.add(hbox)
        hbox.pack_start(child1, False, False)
        hbox.pack_start(child2, False, False)
        return hbox_ali, hbox

    def get_home_path(self):
        return os.path.expanduser("~")

    def save_chooser_btn_clicked(self, widget):
        """保存目录... ..."""
        self.show_open_dir_dialog_window()

    def show_open_dir_dialog_window(self):
        open_dialog = gtk.FileChooserDialog(
            _("Choose a directory"),
            None,
            gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK),
        )
        # current floader set.
        open_dialog.set_current_folder(self.get_home_path())
        # run dir dialog window.
        res = open_dialog.run()

        if res == gtk.RESPONSE_OK:
            path_string = open_dialog.get_filename()
            if path_string:
                self.save_path_entry.set_text(path_string)
        # destroy dialog window.
        open_dialog.destroy()

    def brand_combo_item_selected(self, combo, item_content):
        self.model_combo.clear_items()
        self.ratio_combo.clear_items()
        #
        try:
            self.model_dict = self.read_xml.load(self.read_xml.brand_dict[item_content])
        except Exception, e:
            print "brand_combo_item_selected[error]:", e
            self.model_dict = {}
        #
        if item_content != _("No Presets") and self.model_dict != {}:
            model_items = []
            for model in self.model_dict:
                model_items.append((model, model))
            self.model_combo.set_items(model_items, 0)

            # self.model_combo.droplist.set_size_request(-1, self.model_combo.droplist_height)
            self.model_combo.set_active(0)
            self.model_combo.set_sensitive(True)
            self.model_label.set_sensitive(True)
        else:
            # clear model and ratio all text.
            self.model_combo.append_text(_("No Model"))
            self.model_combo.set_sensitive(False)
            self.model_label.set_sensitive(False)
            # add ratios.
            for ratio in self.ratio_items:
                self.ratio_combo.append_text(ratio[0])
            self.ratio_combo.set_active(5)
Beispiel #10
0
class Broadband(gtk.VBox):
    ENTRY_WIDTH = 222
    LEFT_PADDING = 210
    def __init__(self, connection, set_button_callback, settings_obj=None):
        gtk.VBox.__init__(self)
        self.tab_name = _("Broadband")
        self.connection = connection        
        self.set_button = set_button_callback
        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj

        # Init widgets
        self.table = gtk.Table(12, 4, False)
        
        #self.label_basic = Label(_("Basic"), text_size = TITLE_FONT_SIZE)
        self.label_basic = TitleBar(None, _("Basic"))
        self.label_number = Label(_("Code:"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.label_username = Label(_("Username:"******"Password:"******"Show password"), padding_x=0)
        self.button_to_region = Button(_("Regions setting"))


        #self.table = gtk.Table(6, 4, False)
        self.label_advanced = TitleBar(None,_("Advanced"))
        self.label_apn = Label(_("APN:"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.label_network = Label(_("Network ID:"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.label_type = Label(_("Type:"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.label_pin = Label(_("PIN:"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)

        self.apn = InputEntry()
        self.network_id = InputEntry()
        self.network_type = ComboBox([("Any", None),
                                      ("3G", 0),
                                      ("2G", 1),
                                      ("Prefer 3G", 2),
                                      ("Prefer 2G", 3)],
                                      fixed_width=self.ENTRY_WIDTH)
        self.roam_check = CheckButton(_("Allow roaming if home network is not available"), padding_x=0)
        self.pin = InputEntry()
        
        
        # Connect signals
        self.number.entry.connect("changed", self.save_settings_by, "number")
        self.username.entry.connect("changed", self.save_settings_by, "username")
        self.password.entry.connect("changed", self.save_settings_by, "password")
        self.apn.entry.connect("changed", self.save_settings_by, "apn")
        self.network_id.entry.connect("changed", self.save_settings_by, "network_id")
        self.network_type.connect("item-selected", self.network_type_selected)

        self.password_show.connect("toggled", self.password_show_toggled)
        self.roam_check.connect("toggled", self.roam_check_toggled)


        table_align = gtk.Alignment(0, 0, 0, 0)
        table_align.add(self.table)
        self.pack_start(table_align)

        # wrap with alignment
        
        # Refesh
        self.refresh()

    def password_show_toggled(self, widget):
        if widget.get_active():
            self.password.show_password(True)
        else:
            self.password.show_password(False)

    def init_table(self, network_type):
        #container_remove_all(self.table)
        if self.table.get_children() != []:
            pass
        else:
            #self.table.attach(self.label_basic, 0,2 ,0, 1)
            self.table.attach(style.wrap_with_align(self.label_number, width=self.LEFT_PADDING), 0, 1, 1, 2)
            self.table.attach(style.wrap_with_align(self.label_username, width=self.LEFT_PADDING), 0, 1, 2, 3)
            self.table.attach(style.wrap_with_align(self.label_password, width=self.LEFT_PADDING), 0, 1, 3, 4)

            self.table.attach(style.wrap_with_align(self.number), 1, 2, 1, 2)
            self.table.attach(style.wrap_with_align(self.username), 1, 2, 2, 3)
            self.table.attach(style.wrap_with_align(self.password), 1, 2, 3, 4)
            self.table.attach(style.wrap_with_align(self.password_show, align="left"), 1, 2, 4, 5)

            def to_region(widget):
                region = slider.get_page_by_name("region")
                region.init(self.connection)
                #region.need_new_connection =False
                slider._slide_to_page("region", "none")

            if network_type == "gsm":
                self.button_to_region.connect("clicked", to_region)
                self.table.attach(style.wrap_with_align(self.button_to_region), 1,2,5,6)
                self.table.attach(self.label_advanced, 0, 2, 6, 7)
                self.table.attach(style.wrap_with_align(self.label_apn), 0, 1 , 7, 8)
                self.table.attach(style.wrap_with_align(self.label_network), 0, 1, 8, 9)
                self.table.attach(style.wrap_with_align(self.label_type), 0, 1, 9, 10)
                self.table.attach(style.wrap_with_align(self.label_pin), 0, 1, 11, 12)

                self.table.attach(style.wrap_with_align(self.apn), 1, 2, 7, 8)
                self.table.attach(style.wrap_with_align(self.network_id), 1, 2, 8, 9)
                self.table.attach(style.wrap_with_align(self.network_type), 1, 2, 9, 10)
                self.table.attach(style.wrap_with_align(self.roam_check, align="left"), 1, 2, 10, 11)
                self.table.attach(style.wrap_with_align(self.pin), 1, 2, 11, 12)
            #TODO ui change
            #style.set_table_items(self.table, 'entry')
            entry_list = ["number", "username", "password",
                          "apn", "network_id", "pin"]
            for entry in entry_list:
                widget = getattr(self, entry)
                widget.entry.set_size_request(self.ENTRY_WIDTH, 22)

            style.set_table(self.table)
        self.table.show_all()

    def refresh(self):
        # get_settings
        mobile_type = self.connection.get_setting("connection").type
        self.broadband_setting = self.connection.get_setting(mobile_type)
        number = self.broadband_setting.number
        username = self.broadband_setting.username

        password = self.broadband_setting.password

        if password == None:
            try:
                (setting_name, method) = self.connection.guess_secret_info() 
                password = nm_module.secret_agent.agent_get_secrets(self.connection.object_path,
                                                        setting_name,
                                                        method)
            except:
                password = ""

        # both
        self.number.set_text(number)
        self.username.set_text(username)
        self.password.entry.set_text(password)

        if  mobile_type == "gsm":
            apn = self.broadband_setting.apn
            network_id = self.broadband_setting.network_id
            network_type = self.broadband_setting.network_type
            home_only = self.broadband_setting.home_only
            
            # gsm
            self.apn.set_text(apn)
            self.network_id.set_text(network_id)
            if network_type:
                self.network_type.set_select_index(network_type + 1)
            else:
                self.network_type.set_select_index(0)

            self.roam_check.set_active(home_only is None)

        self.init_table(mobile_type)
        
        ## retrieve wired info

    def set_new_values(self, new_dict, type):
        params = new_dict[type]

        for key, value in params.iteritems():
            setattr(self.broadband_setting, key, value)
        self.refresh()

    def save_settings_by(self, widget, text, attr):
        if text == "":
            delattr(self.broadband_setting, attr)
        else:
            setattr(self.broadband_setting, attr, text)
        self.set_button("save", True)

    def network_type_selected(self, widget, content, value, index):
        if value == None:
            del self.broadband_setting.network_type
        else:
            self.broadband_setting.network_type = value

    def roam_check_toggled(self, widget):
        if widget.get_active():
            del self.broadband_setting.home_only
        else:
            self.broadband_setting.home_only = 1

    def expose_bg(self, widget, event):
        cr = widget.window.cairo_create()
        rect = widget.allocation
        cr.set_source_rgb( 1, 1, 1) 
        cr.rectangle(rect.x, rect.y, rect.width, rect.height)
        cr.fill()
class PPPConf(gtk.VBox):
    ENTRY = 0
    OFFBUTTON = 1

    TABLE_WIDTH = 150

    def __init__(self, settings_obj=None):
        gtk.VBox.__init__(self)

        #self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        #Dispatcher.set_button = set_button_callback
        #self.module_frame = module_frame

        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj

        self.method_title = TitleBar(None,
                                     _("Configure Method"),
                                     width=self.TABLE_WIDTH,
                                     has_separator=False)

        self.refuse_eap_label = Label(_("EAP"),
                                      text_size=CONTENT_FONT_SIZE,
                                      enable_select=False,
                                      enable_double_click=False)
        self.refuse_pap_label = Label(_("PAP"),
                                      text_size=CONTENT_FONT_SIZE,
                                      enable_select=False,
                                      enable_double_click=False)
        self.refuse_chap_label = Label(_("CHAP"),
                                       text_size=CONTENT_FONT_SIZE,
                                       enable_select=False,
                                       enable_double_click=False)
        self.refuse_mschap_label = Label(_("MSCHAP"),
                                         text_size=CONTENT_FONT_SIZE,
                                         enable_select=False,
                                         enable_double_click=False)
        self.refuse_mschapv2_label = Label(_("MSCHAP v2"),
                                           text_size=CONTENT_FONT_SIZE,
                                           enable_select=False,
                                           enable_double_click=False)
        self.refuse_eap = SwitchButton()
        self.refuse_pap = SwitchButton()
        self.refuse_chap = SwitchButton()
        self.refuse_mschap = SwitchButton()
        self.refuse_mschapv2 = SwitchButton()

        self.method_table = gtk.Table(23, 3, False)

        # visible settings

        self.compression_title = TitleBar(None,
                                          _("Compression"),
                                          width=self.TABLE_WIDTH,
                                          has_separator=False)

        self.echo_title = TitleBar(None,
                                   _("Echo"),
                                   width=self.TABLE_WIDTH,
                                   has_separator=False)

        #compressio))n = Label(_("Compression"), text_size=TITLE_FONT_SIZE)
        self.require_mppe_label = Label(
            _("Use point-to-point encryption(mppe)"),
            text_size=CONTENT_FONT_SIZE,
            enable_select=False,
            enable_double_click=False)
        self.require_mppe_128_label = Label(_("Require 128-bit encryption"),
                                            text_size=CONTENT_FONT_SIZE,
                                            enable_select=False,
                                            enable_double_click=False)
        self.mppe_stateful_label = Label(_("Use stateful MPPE"),
                                         text_size=CONTENT_FONT_SIZE,
                                         enable_select=False,
                                         enable_double_click=False)
        self.nobsdcomp_label = Label(_("Allow BSD data Compression"),
                                     text_size=CONTENT_FONT_SIZE,
                                     enable_select=False,
                                     enable_double_click=False)
        self.nodeflate_label = Label(_("Allow Deflate data compression"),
                                     text_size=CONTENT_FONT_SIZE,
                                     enable_select=False,
                                     enable_double_click=False)
        self.no_vj_comp_label = Label(_("Use TCP header compression"),
                                      text_size=CONTENT_FONT_SIZE,
                                      enable_select=False,
                                      enable_double_click=False)
        #echo = Label("Echo", text_size=TITLE_FONT_SIZE)
        self.ppp_echo_label = Label(_("Send PPP echo packets"),
                                    text_size=CONTENT_FONT_SIZE,
                                    enable_select=False,
                                    enable_double_click=False)
        self.nopcomp_label = Label(
            _("Use protocal field compression negotiation"),
            text_size=CONTENT_FONT_SIZE,
            enable_select=False,
            enable_double_click=False)
        self.noaccomp_label = Label(_("Use Address/Control compression"),
                                    text_size=CONTENT_FONT_SIZE,
                                    enable_select=False,
                                    enable_double_click=False)

        self.require_mppe = SwitchButton()
        self.require_mppe_128 = SwitchButton()
        self.mppe_stateful = SwitchButton()

        self.nobsdcomp = SwitchButton()
        self.nodeflate = SwitchButton()
        self.no_vj_comp = SwitchButton()
        self.nopcomp = SwitchButton()
        self.noaccomp = SwitchButton()
        self.ppp_echo = SwitchButton()
        self.ip_sec_enable = SwitchButton()

        ## Settings for IPSec
        self.ipsec_title = TitleBar(None,
                                    _("IPSec Setting"),
                                    width=self.TABLE_WIDTH,
                                    has_separator=False)

        self.ip_sec_enable_label = Label(_("Enable IPSec tunnel to l2tp host"),
                                         text_size=CONTENT_FONT_SIZE,
                                         enable_select=False,
                                         enable_double_click=False)
        self.group_name_label = Label(_("Group Name:"),
                                      text_size=CONTENT_FONT_SIZE,
                                      enable_select=False,
                                      enable_double_click=False)
        self.gateway_id_label = Label(_("Gateway ID:"),
                                      text_size=CONTENT_FONT_SIZE,
                                      enable_select=False,
                                      enable_double_click=False)
        self.pre_shared_key_label = Label(_("Pre_Shared_key"),
                                          text_size=CONTENT_FONT_SIZE,
                                          enable_select=False,
                                          enable_double_click=False)
        self.group_name = InputEntry()
        self.group_name.set_size(self.TABLE_WIDTH, 22)
        self.gateway_id = InputEntry()
        self.gateway_id.set_size(self.TABLE_WIDTH, 22)
        self.pre_shared_key = PasswordEntry()
        self.pre_shared_key.set_text = self.pre_shared_key.entry.set_text
        self.pre_shared_key.set_size(self.TABLE_WIDTH, 22)

        methods_list = [
            "refuse_eap", "refuse_eap_label", "refuse_pap", "refuse_pap_label",
            "refuse_chap", "refuse_chap_label", "refuse_mschap",
            "refuse_mschap_label", "refuse_mschapv2", "refuse_mschapv2_label"
        ]
        compression_list = [
            "require_mppe_label", "require_mppe", "require_mppe_128_label",
            "require_mppe_128", "mppe_stateful_label", "mppe_stateful",
            "nobsdcomp_label", "nobsdcomp", "nodeflate_label", "nodeflate",
            "no_vj_comp_label", "no_vj_comp", "nopcomp_label", "nopcomp",
            "noaccomp_label", "noaccomp"
        ]

        echo_list = ["ppp_echo_label", "ppp_echo"]

        ip_sec_list = [
            "ip_sec_enable_label", "ip_sec_enable", "group_name_label",
            "group_name", "gateway_id_label", "gateway_id",
            "pre_shared_key_label", "pre_shared_key"
        ]

        for name in (compression_list + echo_list + methods_list +
                     ip_sec_list):
            widget = getattr(self, name)
            if not name.endswith("label"):
                align = style.wrap_with_align(widget, align="left")
            else:
                align = style.wrap_with_align(widget, width=210)

            setattr(self, name + "_align", align)

        #vbox = gtk.VBox()
        table_align = gtk.Alignment(0, 0, 0, 0)
        table_align.add(self.method_table)
        style.set_table(self.method_table)

        self.pack_start(table_align, False, False)
        self.method_table.set_row_spacing(5, 20)
        self.method_table.set_row_spacing(15, 20)
        self.method_table.set_row_spacing(18, 20)

        Dispatcher.connect("vpn-type-change", lambda w, c: self.refresh(c))
        #align = style.set_box_with_align(vbox, "text")
        #self.add_with_viewport(align)
        #style.draw_background_color(align)

        #confirm_button = Button("Confirm")
        #confirm_button.connect("clicked", self.confirm_button_cb)
        #button_aligns = gtk.Alignment(0.5 , 1, 0, 0)
        #button_aligns.add(confirm_button)
        #self.add(button_aligns)

        #self.require_mppe_128.set_sensitive(False)
        #self.mppe_stateful.set_sensitive(False)
        ##self.refresh()

    def init_signal(self):
        self.refuse_eap.connect("toggled", self.check_button_cb, "refuse-eap")
        self.refuse_pap.connect("toggled", self.check_button_cb, "refuse-pap")
        self.refuse_chap.connect("toggled", self.check_button_cb,
                                 "refuse-chap")
        self.refuse_mschap.connect("toggled", self.check_button_cb,
                                   "refuse-mschap")
        self.refuse_mschapv2.connect("toggled", self.check_button_cb,
                                     "refuse-mschapv2")
        self.require_mppe.connect("toggled", self.click_mppe_callback,
                                  "require-mppe")
        self.require_mppe_128.connect("toggled", self.check_button_cb,
                                      "require-mppe-128")
        self.mppe_stateful.connect("toggled", self.check_button_cb,
                                   "mppe-stateful")
        self.nobsdcomp.connect("toggled", self.check_button_cb, "nobsdcomp")
        self.nodeflate.connect("toggled", self.check_button_cb, "nodeflate")
        self.no_vj_comp.connect("toggled", self.check_button_cb, "no-vj-comp")
        self.ppp_echo.connect("toggled", self.check_button_cb, "echo")
        self.nopcomp.connect("toggled", self.check_button_cb, "nopcomp")
        self.noaccomp.connect("toggled", self.check_button_cb, "noaccomp")

        self.ip_sec_enable.connect("toggled", self.enable_ipsec_cb)
        #self.group_name.entry.connect("focus-out-event", self.entry_focus_out_cb, "ipsec-group-name")
        #self.gateway_id.entry.connect("focus-out-event", self.entry_focus_out_cb, "ipsec-gataway-id")
        #self.pre_shared_key.entry.connect("focus-out-event", self.entry_focus_out_cb, "ipsec-psk")
        self.group_name.entry.connect("changed", self.entry_changed_cb,
                                      "ipsec-group-name")
        self.gateway_id.entry.connect("changed", self.entry_changed_cb,
                                      "ipsec-gateway-id")
        self.pre_shared_key.entry.connect("changed", self.entry_changed_cb,
                                          "ipsec-psk")

    def init_ui(self):

        self.service_type = self.vpn_setting.service_type.split(".")[-1]

        def table_attach(widget_name, row, padding=0):
            label = getattr(self, widget_name + "_label_align")
            widget = getattr(self, widget_name + "_align")
            self.method_table.attach(label, 0, 2, row, row + 1)
            self.method_table.attach(widget,
                                     2,
                                     3,
                                     row,
                                     row + 1,
                                     xpadding=padding)

        #print self.service_type
        container_remove_all(self.method_table)
        self.method_table.attach(self.method_title, 0, 3, 0, 1)
        table_attach("refuse_eap", 1)
        table_attach("refuse_pap", 2)
        table_attach("refuse_chap", 3)
        table_attach("refuse_mschap", 4)
        table_attach("refuse_mschapv2", 5)
        self.method_table.attach(self.compression_title, 0, 3, 6, 7)
        table_attach("require_mppe", 8)
        if self.require_mppe.get_active():
            table_attach("require_mppe_128", 9)
            table_attach("mppe_stateful", 10)
        table_attach("nobsdcomp", 11)
        table_attach("nodeflate", 12)
        table_attach("no_vj_comp", 13)
        self.method_table.attach(self.echo_title, 0, 3, 16, 17)
        table_attach("ppp_echo", 18)

        if self.service_type == "l2tp":
            #print "this is l2tp"
            table_attach("nopcomp", 14)
            table_attach("noaccomp", 15)

            self.method_table.attach(self.ipsec_title, 0, 3, 19, 20)
            table_attach("ip_sec_enable", 20)
            if self.ip_sec_enable.get_active():
                table_attach("group_name", 21)
                table_attach("gateway_id", 22)
                table_attach("pre_shared_key", 23)

        self.method_table.show_all()

    def refresh(self, connection):
        self.connection = connection
        self.vpn_setting = self.connection.get_setting("vpn")
        #=========================
        # retreieve settings
        self.service_type = self.vpn_setting.service_type.split(".")[-1]
        #print ">>",self.vpn_setting.data
        refuse_eap = self.vpn_setting.get_data_item("refuse-eap")
        refuse_pap = self.vpn_setting.get_data_item("refuse-pap")
        refuse_chap = self.vpn_setting.get_data_item("refuse-chap")
        refuse_mschap = self.vpn_setting.get_data_item("refuse-mschap")
        refuse_mschapv2 = self.vpn_setting.get_data_item("refuse-mschapv2")

        require_mppe = self.vpn_setting.get_data_item("require-mppe")
        require_mppe_128 = self.vpn_setting.get_data_item("require-mppe-128")
        mppe_stateful = self.vpn_setting.get_data_item("mppe-stateful")

        nobsdcomp = self.vpn_setting.get_data_item("nobsdcomp")
        nodeflate = self.vpn_setting.get_data_item("nodeflate")
        no_vj_comp = self.vpn_setting.get_data_item("no-vj-comp")

        lcp_echo_failure = self.vpn_setting.get_data_item("lcp-echo-failure")
        lcp_echo_interval = self.vpn_setting.get_data_item("lcp-echo-interval")

        self.refuse_mschap.set_active(refuse_mschap == None)
        self.refuse_mschapv2.set_active(refuse_mschapv2 == None)
        self.require_mppe.set_active(require_mppe != None)

        self.refuse_eap.set_active(refuse_eap == None)
        self.refuse_pap.set_active(refuse_pap == None)
        self.refuse_chap.set_active(refuse_chap == None)

        self.require_mppe_128.set_active(require_mppe_128 != None)
        if self.require_mppe_128.get_active() or self.mppe_stateful.get_active(
        ):
            self.require_mppe.set_active(True)
        self.mppe_stateful.set_active(mppe_stateful != None)
        self.nobsdcomp.set_active(nobsdcomp == None)
        self.nodeflate.set_active(nodeflate == None)
        self.no_vj_comp.set_active(no_vj_comp == None)

        if self.service_type == "l2tp":
            nopcomp = self.vpn_setting.get_data_item("nopcomp")
            noaccomp = self.vpn_setting.get_data_item("noaccomp")
            ipsec_enabled = self.vpn_setting.get_data_item("ipsec-enabled")

            self.nopcomp.set_active(nopcomp == None)
            self.noaccomp.set_active(noaccomp == None)

            if ipsec_enabled:
                self.ip_sec_enable.set_active(True)

                ipsec_group_name = self.vpn_setting.get_data_item(
                    "ipsec-group-name")
                ipsec_gateway_id = self.vpn_setting.get_data_item(
                    "ipsec-gateway-id")
                ipsec_psk = self.vpn_setting.get_data_item("ipsec-psk")
                self.group_name.set_text(ipsec_group_name)
                self.gateway_id.set_text(ipsec_gateway_id)
                self.pre_shared_key.set_text(ipsec_psk)

            else:
                self.ip_sec_enable.set_active(False)

        if lcp_echo_failure == None and lcp_echo_interval == None:
            self.ppp_echo.set_active(False)
        else:
            self.ppp_echo.set_active(True)

        self.init_signal()
        self.init_lock = False
        self.require_mppe.emit("toggled")
        self.init_lock = True
        self.init_ui()
        #==================================
        # Connect signal
    def enable_ipsec_cb(self, widget):
        active = widget.get_active()
        if active:
            self.vpn_setting.set_data_item("ipsec-enabled", "yes")
            self.group_name.set_sensitive(True)
            self.gateway_id.set_sensitive(True)
            self.pre_shared_key.set_sensitive(True)

            ipsec_group_name = self.vpn_setting.get_data_item(
                "ipsec-group-name")
            ipsec_gateway_id = self.vpn_setting.get_data_item(
                "ipsec-gateway-id")
            ipsec_psk = self.vpn_setting.get_data_item("ipsec-psk")

            #print ipsec_group_name
            self.group_name.set_text(ipsec_group_name)
            self.gateway_id.set_text(ipsec_gateway_id)
            self.pre_shared_key.set_text(ipsec_psk)
            self.init_ui()
        else:
            self.vpn_setting.delete_data_item("ipsec-enabled")
            self.group_name.set_text("")
            self.gateway_id.set_text("")
            self.pre_shared_key.set_text("")

            self.group_name.set_sensitive(False)
            self.gateway_id.set_sensitive(False)
            self.pre_shared_key.set_sensitive(False)
            self.init_ui()

    def entry_focus_out_cb(self, widget, event, key):
        text = widget.get_text()
        if text and key != "name":
            self.vpn_setting.set_data_item(key, text)
        else:
            self.vpn_setting.delete_data_item(key)

    def entry_changed_cb(self, widget, string, key):
        if string == "":
            #print key,"entry is empty"
            self.vpn_setting.delete_data_item(key)
        elif key != "name":
            self.vpn_setting.set_data_item(key, string)

        if self.connection.check_setting_finish():
            Dispatcher.set_button("save", True)
        else:
            Dispatcher.set_button("save", False)

    def check_button_cb(self, widget, key):
        auth_lock = self.auth_lock()
        active = widget.get_active()
        if key.startswith("refuse"):
            if active:
                self.vpn_setting.delete_data_item(key)
            else:
                self.vpn_setting.set_data_item(key, "yes")

            if auth_lock:
                self.require_mppe_label.set_sensitive(False)
                self.require_mppe.set_sensitive(False)

                self.set_group_sensitive(True)
            else:
                self.require_mppe_label.set_sensitive(True)
                self.require_mppe.set_sensitive(True)

        elif key.startswith("no"):
            if active:
                self.vpn_setting.delete_data_item(key)
            else:
                self.vpn_setting.set_data_item(key, "yes")

        elif key == "echo":
            if active:
                self.vpn_setting.set_data_item("lcp-echo-failure", "5")
                self.vpn_setting.set_data_item("lcp-echo-interval", "30")
            else:
                self.vpn_setting.delete_data_item("lcp-echo-failure")
                self.vpn_setting.delete_data_item("lcp-echo-interval")
        elif key.startswith("ipsec"):
            if active:
                self.vpn_setting.set_data_item(key, "yes")
            else:
                self.vpn_setting.delete_data_item(key)
        elif key.startswith("require") or key.startswith("mppe"):
            if active:
                self.vpn_setting.set_data_item(key, "yes")
            else:
                self.vpn_setting.delete_data_item(key)

        if self.connection.check_setting_finish():
            Dispatcher.set_button("save", True)
        else:
            Dispatcher.set_button("save", False)

    def click_mppe_callback(self, widget, key):
        active = widget.get_active()
        if active and key != "name":
            self.vpn_setting.set_data_item(key, "yes")
            #self.set_group_active(False)
            self.set_group_sensitive(False)

            self.mppe_group_set_sensitive(True)
            self.init_ui()
        else:
            #self.set_group_active(True)
            self.set_group_sensitive(True)
            self.vpn_setting.delete_data_item(key)
            self.mppe_group_set_active(False)
            self.mppe_group_set_sensitive(False)
            self.init_ui()

        if self.init_lock:
            if self.connection.check_setting_finish():
                Dispatcher.set_button("save", True)
            else:
                Dispatcher.set_button("save", False)

        if self.auth_lock():
            self.require_mppe_label.set_sensitive(False)
            self.require_mppe.set_sensitive(False)
            return

    def mppe_group_set_sensitive(self, boolean):
        self.require_mppe_128_label.set_sensitive(boolean)
        self.mppe_stateful_label.set_sensitive(boolean)
        self.require_mppe_128.set_sensitive(boolean)
        self.mppe_stateful.set_sensitive(boolean)

    def mppe_group_set_active(self, boolean):
        log.debug()
        self.require_mppe_128.set_active(boolean)
        self.mppe_stateful.set_active(boolean)

    def confirm_button_cb(self, widget):
        self.module_frame.send_message("change_crumb", 2)
        nm_module.slider._slide_to_page("vpn", "none")

    def auth_lock(self):
        if self.refuse_mschap.get_active() or self.refuse_mschapv2.get_active(
        ):
            return False
        else:
            return True

    def set_group_active(self, boolean):
        self.refuse_eap.set_active(boolean)
        self.refuse_pap.set_active(boolean)
        self.refuse_chap.set_active(boolean)

    def set_group_sensitive(self, boolean):
        self.refuse_eap.set_sensitive(boolean)
        self.refuse_pap.set_sensitive(boolean)
        self.refuse_chap.set_sensitive(boolean)
        self.refuse_eap_label.set_sensitive(boolean)
        self.refuse_pap_label.set_sensitive(boolean)
        self.refuse_chap_label.set_sensitive(boolean)
class PPTPConf(gtk.VBox):
    ENTRY_WIDTH = 222
    LEFT_PADDING = 210

    def __init__(self,
                 connection,
                 module_frame,
                 set_button_callback=None,
                 settings_obj=None):
        gtk.VBox.__init__(self)
        self.connection = connection
        self.tab_name = _("PPTP")
        self.module_frame = module_frame
        self.set_button = set_button_callback
        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj

        self.vpn_setting = self.connection.get_setting("vpn")

        # UI

        pptp_table = gtk.Table(7, 4, False)

        name_label = Label(_("Connection Name:"),
                           enable_select=False,
                           enable_double_click=False)
        name_label.set_can_focus(False)
        gateway_label = Label(_("Gateway:"),
                              enable_select=False,
                              enable_double_click=False)
        gateway_label.set_can_focus(False)
        user_label = Label(_("Username:"******"Password:"******"NT Domain:"),
                                enable_select=False,
                                enable_double_click=False)
        nt_domain_label.set_can_focus(False)
        # Radio Button
        self.pptp_radio = RadioButton(_("PPTP"))
        self.l2tp_radio = RadioButton(_("L2TP"))
        radio_box = gtk.HBox(spacing=30)
        radio_box.pack_start(self.pptp_radio, True, True)
        radio_box.pack_start(self.l2tp_radio, True, True)
        #pack labels
        pptp_table.attach(style.wrap_with_align(radio_box, align="left"), 2, 4,
                          0, 1)
        pptp_table.attach(
            style.wrap_with_align(name_label, width=self.LEFT_PADDING), 0, 2,
            1, 2)
        pptp_table.attach(
            style.wrap_with_align(gateway_label, width=self.LEFT_PADDING), 0,
            2, 2, 3)
        pptp_table.attach(
            style.wrap_with_align(user_label, width=self.LEFT_PADDING), 0, 2,
            3, 4)
        pptp_table.attach(
            style.wrap_with_align(password_label, width=self.LEFT_PADDING), 0,
            2, 4, 5)
        #pptp_table.attach(style.wrap_with_align(nt_domain_label), 0, 2, 5, 6)

        # entries
        self.name_entry = InputEntry()
        self.name_entry.set_size(self.ENTRY_WIDTH, 22)

        self.gateway_entry = InputEntry()
        self.gateway_entry.set_size(self.ENTRY_WIDTH, 22)
        self.user_entry = InputEntry()
        self.user_entry.set_size(self.ENTRY_WIDTH, 22)
        # FIXME should change to new_entry PasswordEntry
        self.password_entry = PasswordEntry()
        self.password_entry.set_size(self.ENTRY_WIDTH, 22)
        self.password_show = CheckButton(_("Show Password"), padding_x=0)
        self.password_show.set_active(False)
        self.password_show.connect("toggled", self.show_password)
        self.nt_domain_entry = InputEntry()
        self.nt_domain_entry.set_size(self.ENTRY_WIDTH, 22)

        #pack entries
        pptp_table.attach(style.wrap_with_align(self.name_entry, align="left"),
                          2, 4, 1, 2)
        pptp_table.attach(
            style.wrap_with_align(self.gateway_entry, align="left"), 2, 4, 2,
            3)
        pptp_table.attach(style.wrap_with_align(self.user_entry, align="left"),
                          2, 4, 3, 4)
        pptp_table.attach(
            style.wrap_with_align(self.password_entry, align="left"), 2, 4, 4,
            5)
        pptp_table.attach(
            style.wrap_with_align(self.password_show, align="left"), 2, 4, 5,
            6)
        #pptp_table.attach(style.wrap_with_align(self.nt_domain_entry), 2, 4, 5, 6)
        # Advance setting button
        #advanced_button = Button(_("Advanced Setting"))
        #advanced_button.connect("clicked", self.advanced_button_click)

        #pptp_table.attach(style.wrap_with_align(advanced_button), 3, 4, 6, 7)
        self.service_type = self.vpn_setting.service_type.split(".")[-1]
        if self.service_type == "l2tp":
            self.l2tp_radio.set_active(True)
        else:
            self.pptp_radio.set_active(True)
        self.pptp_radio.connect("toggled", self.radio_toggled, "pptp")
        self.l2tp_radio.connect("toggled", self.radio_toggled, "l2tp")
        # set signals

        #align = style.set_box_with_align(pptp_table, "text")
        table_align = gtk.Alignment(0, 0, 0, 0)
        table_align.add(pptp_table)
        #style.set_table_items(pptp_table, "entry")
        style.draw_background_color(self)
        style.set_table(pptp_table)
        self.add(table_align)
        self.show_all()
        self.refresh()
        self.name_entry.entry.connect("changed", self.entry_changed, "name")
        self.gateway_entry.entry.connect("changed", self.entry_changed,
                                         "gateway")
        self.user_entry.entry.connect("changed", self.entry_changed, "user")
        self.password_entry.entry.connect("changed", self.entry_changed,
                                          "password")
        self.nt_domain_entry.entry.connect("changed", self.entry_changed,
                                           "domain")

        #if self.connection.check_setting_finish():
        #print "in vpn"
        #Dispatcher.set_button("save", True)
        #else:
        #print "in vpn"
        #Dispatcher.set_button("save", False)
        ##############
        #is_valid = self.connection.check_setting_finish()
        #self.settings_obj.vpn_is_valid = is_valid
        #self.settings_obj.set_button("save", is_valid)

    def refresh(self):
        #print ">>>",self.vpn_setting.data
        #print self.vpn_setting.data
        name = self.connection.get_setting("connection").id
        gateway = self.vpn_setting.get_data_item("gateway")
        user = self.vpn_setting.get_data_item("user")
        domain = self.vpn_setting.get_data_item("domain")

        if type(self.connection) == NMRemoteConnection:
            self.name_entry.set_text(name)

        if gateway:
            self.gateway_entry.set_text(gateway)
        if user:
            self.user_entry.set_text(user)

        (setting_name, method) = self.connection.guess_secret_info()
        try:
            password = nm_module.secret_agent.agent_get_secrets(
                self.connection.object_path, setting_name, method)
            if password is None:
                #self.password_entry.entry.set_text("")
                self.password_entry.entry.set_text("")
            else:
                #self.password_entry.entry.set_text(password)
                self.password_entry.entry.set_text(password)
                self.vpn_setting.set_secret_item("password", password)
        except:
            pass

        if domain:
            self.nt_domain_entry.set_text(domain)

    def save_setting(self):
        pass

    def show_password(self, widget):
        if widget.get_active():
            self.password_entry.show_password(True)
        else:
            self.password_entry.show_password(False)

    def entry_changed(self, widget, content, item):
        text = content
        if item == "name":
            self.connection.get_setting("connection").id = content

        if text:
            if item == "password":
                self.vpn_setting.set_secret_item(item, text)
            elif item != "name":
                self.vpn_setting.set_data_item(item, text)

        else:
            if item == "password":
                self.vpn_setting.set_secret_item(item, "")
            else:
                self.vpn_setting.delete_data_item(item)

        #if self.connection.check_setting_finish():
        #Dispatcher.set_button("save", True)
        #else:
        #Dispatcher.set_button("save", False)
        ##############
        is_valid = self.connection.check_setting_finish()
        self.settings_obj.vpn_is_valid = is_valid
        self.settings_obj.set_button("save", is_valid)

    def radio_toggled(self, widget, service_type):
        if widget.get_active():
            self.vpn_setting.service_type = "org.freedesktop.NetworkManager." + service_type
            self.service_type = service_type

        if self.connection.check_setting_finish():
            Dispatcher.set_button("save", True)
        else:
            Dispatcher.set_button("save", False)
            self.refresh()

        Dispatcher.emit("vpn-type-change", self.connection)

    def advanced_button_click(self, widget):
        ppp = PPPConf(self.module_frame, Dispatcher.set_button)
        ppp.refresh(self.connection)
        Dispatcher.send_submodule_crumb(3, _("Advanced"))
        nm_module.slider.slide_to_page(ppp, "none")
class PPPConf(gtk.VBox):
    ENTRY = 0
    OFFBUTTON = 1

    TABLE_WIDTH = 150
    def __init__(self, settings_obj=None):
        gtk.VBox.__init__(self)
        
        #self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        #Dispatcher.set_button = set_button_callback
        #self.module_frame = module_frame

        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj
        
        self.method_title = TitleBar(None,
                                     _("Configure Method"),
                                     width=self.TABLE_WIDTH,
                                     has_separator=False)

        self.refuse_eap_label = Label(_("EAP"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.refuse_pap_label = Label(_("PAP"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.refuse_chap_label = Label(_("CHAP"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.refuse_mschap_label = Label(_("MSCHAP"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.refuse_mschapv2_label = Label(_("MSCHAP v2"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.refuse_eap = SwitchButton()
        self.refuse_pap = SwitchButton()
        self.refuse_chap = SwitchButton()
        self.refuse_mschap = SwitchButton()
        self.refuse_mschapv2 = SwitchButton()
        
        self.method_table = gtk.Table(23, 3, False)

        # visible settings

        self.compression_title = TitleBar(None,
                                          _("Compression"),
                                          width=self.TABLE_WIDTH,
                                          has_separator=False)

        self.echo_title = TitleBar(None,
                                   _("Echo"),
                                   width=self.TABLE_WIDTH,
                                   has_separator=False)


        #compressio))n = Label(_("Compression"), text_size=TITLE_FONT_SIZE)
        self.require_mppe_label = Label(_("Use point-to-point encryption(mppe)"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.require_mppe_128_label = Label(_("Require 128-bit encryption"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.mppe_stateful_label = Label(_("Use stateful MPPE"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.nobsdcomp_label = Label(_("Allow BSD data Compression"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.nodeflate_label = Label(_("Allow Deflate data compression"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.no_vj_comp_label = Label(_("Use TCP header compression"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        #echo = Label("Echo", text_size=TITLE_FONT_SIZE)
        self.ppp_echo_label = Label(_("Send PPP echo packets"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.nopcomp_label = Label(_("Use protocal field compression negotiation"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.noaccomp_label = Label(_("Use Address/Control compression"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)

        self.require_mppe = SwitchButton()
        self.require_mppe_128 = SwitchButton()
        self.mppe_stateful = SwitchButton()
        
        self.nobsdcomp = SwitchButton()
        self.nodeflate = SwitchButton()
        self.no_vj_comp = SwitchButton()
        self.nopcomp = SwitchButton()
        self.noaccomp = SwitchButton() 
        self.ppp_echo = SwitchButton()
        self.ip_sec_enable = SwitchButton()

        ## Settings for IPSec
        self.ipsec_title = TitleBar(None,
                                    _("IPSec Setting"),
                                    width=self.TABLE_WIDTH,
                                    has_separator=False)

        self.ip_sec_enable_label = Label(_("Enable IPSec tunnel to l2tp host"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.group_name_label = Label(_("Group Name:"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.gateway_id_label = Label(_("Gateway ID:"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.pre_shared_key_label = Label(_("Pre_Shared_key"), text_size=CONTENT_FONT_SIZE,
                               enable_select=False,
                               enable_double_click=False)
        self.group_name = InputEntry()
        self.group_name.set_size(self.TABLE_WIDTH, 22)
        self.gateway_id = InputEntry()
        self.gateway_id.set_size(self.TABLE_WIDTH, 22)
        self.pre_shared_key = PasswordEntry()
        self.pre_shared_key.set_text = self.pre_shared_key.entry.set_text
        self.pre_shared_key.set_size(self.TABLE_WIDTH, 22)
        
        methods_list = ["refuse_eap", "refuse_eap_label",
                        "refuse_pap", "refuse_pap_label",
                        "refuse_chap", "refuse_chap_label",
                        "refuse_mschap", "refuse_mschap_label",
                        "refuse_mschapv2", "refuse_mschapv2_label"]
        compression_list = ["require_mppe_label", "require_mppe",
                            "require_mppe_128_label", "require_mppe_128",
                            "mppe_stateful_label", "mppe_stateful",
                            "nobsdcomp_label", "nobsdcomp",
                            "nodeflate_label", "nodeflate",
                            "no_vj_comp_label", "no_vj_comp",
                            "nopcomp_label", "nopcomp",
                            "noaccomp_label", "noaccomp"]

        echo_list = ["ppp_echo_label","ppp_echo"]

        ip_sec_list = ["ip_sec_enable_label", "ip_sec_enable",
                       "group_name_label", "group_name",
                       "gateway_id_label", "gateway_id",
                       "pre_shared_key_label", "pre_shared_key"]

        for name in (compression_list+echo_list+methods_list + ip_sec_list):
            widget = getattr(self, name)
            if not name.endswith("label"):
                align = style.wrap_with_align(widget, align="left")
            else:
                align = style.wrap_with_align(widget, width=210)

            setattr(self, name + "_align", align)

        #vbox = gtk.VBox()
        table_align = gtk.Alignment(0, 0, 0, 0)
        table_align.add(self.method_table)
        style.set_table(self.method_table)

        self.pack_start(table_align, False, False)
        self.method_table.set_row_spacing(5, 20)
        self.method_table.set_row_spacing(15, 20)
        self.method_table.set_row_spacing(18, 20)

        Dispatcher.connect("vpn-type-change", lambda w,c:self.refresh(c))
        #align = style.set_box_with_align(vbox, "text")
        #self.add_with_viewport(align)
        #style.draw_background_color(align)


        #confirm_button = Button("Confirm")
        #confirm_button.connect("clicked", self.confirm_button_cb)
        #button_aligns = gtk.Alignment(0.5 , 1, 0, 0)
        #button_aligns.add(confirm_button)
        #self.add(button_aligns)

        #self.require_mppe_128.set_sensitive(False)
        #self.mppe_stateful.set_sensitive(False)
        ##self.refresh()
    
    def init_signal(self):
        self.refuse_eap.connect("toggled", self.check_button_cb, "refuse-eap")
        self.refuse_pap.connect("toggled", self.check_button_cb, "refuse-pap")
        self.refuse_chap.connect("toggled", self.check_button_cb, "refuse-chap")
        self.refuse_mschap.connect("toggled", self.check_button_cb, "refuse-mschap")
        self.refuse_mschapv2.connect("toggled", self.check_button_cb, "refuse-mschapv2")
        self.require_mppe.connect("toggled", self.click_mppe_callback, "require-mppe")
        self.require_mppe_128.connect("toggled", self.check_button_cb, "require-mppe-128")
        self.mppe_stateful.connect("toggled", self.check_button_cb,"mppe-stateful")
        self.nobsdcomp.connect("toggled", self.check_button_cb, "nobsdcomp")
        self.nodeflate.connect("toggled", self.check_button_cb, "nodeflate")
        self.no_vj_comp.connect("toggled", self.check_button_cb, "no-vj-comp")
        self.ppp_echo.connect("toggled", self.check_button_cb, "echo")
        self.nopcomp.connect("toggled", self.check_button_cb, "nopcomp")
        self.noaccomp.connect("toggled", self.check_button_cb, "noaccomp")

        self.ip_sec_enable.connect("toggled", self.enable_ipsec_cb)
        #self.group_name.entry.connect("focus-out-event", self.entry_focus_out_cb, "ipsec-group-name")
        #self.gateway_id.entry.connect("focus-out-event", self.entry_focus_out_cb, "ipsec-gataway-id")
        #self.pre_shared_key.entry.connect("focus-out-event", self.entry_focus_out_cb, "ipsec-psk")
        self.group_name.entry.connect("changed", self.entry_changed_cb, "ipsec-group-name")
        self.gateway_id.entry.connect("changed", self.entry_changed_cb, "ipsec-gateway-id")
        self.pre_shared_key.entry.connect("changed", self.entry_changed_cb, "ipsec-psk")

    def init_ui(self):

        self.service_type = self.vpn_setting.service_type.split(".")[-1]
        def table_attach(widget_name, row, padding=0):
            label = getattr(self, widget_name + "_label_align")
            widget = getattr(self, widget_name + "_align")
            self.method_table.attach(label, 0, 2, row, row + 1)
            self.method_table.attach(widget, 2, 3, row, row + 1, xpadding=padding)
        #print self.service_type
        container_remove_all(self.method_table)
        self.method_table.attach(self.method_title, 0, 3, 0, 1)
        table_attach( "refuse_eap", 1)
        table_attach( "refuse_pap", 2 )
        table_attach( "refuse_chap", 3)
        table_attach( "refuse_mschap", 4 )
        table_attach( "refuse_mschapv2", 5)
        self.method_table.attach( self.compression_title, 0, 3, 6 ,7)
        table_attach("require_mppe", 8)
        if self.require_mppe.get_active():
            table_attach("require_mppe_128", 9)
            table_attach("mppe_stateful", 10)
        table_attach("nobsdcomp", 11)
        table_attach("nodeflate", 12)
        table_attach("no_vj_comp", 13)
        self.method_table.attach(self.echo_title, 0, 3, 16, 17)
        table_attach("ppp_echo", 18)

        if self.service_type == "l2tp":
            #print "this is l2tp"
            table_attach("nopcomp", 14)
            table_attach("noaccomp", 15)
            
            self.method_table.attach(self.ipsec_title, 0, 3, 19, 20)
            table_attach("ip_sec_enable", 20)
            if self.ip_sec_enable.get_active():
                table_attach("group_name", 21)
                table_attach("gateway_id", 22)
                table_attach("pre_shared_key", 23)

        self.method_table.show_all()



    def refresh(self, connection):
        self.connection = connection
        self.vpn_setting = self.connection.get_setting("vpn")
        #=========================
        # retreieve settings
        self.service_type = self.vpn_setting.service_type.split(".")[-1]
        #print ">>",self.vpn_setting.data
        refuse_eap = self.vpn_setting.get_data_item("refuse-eap")
        refuse_pap = self.vpn_setting.get_data_item("refuse-pap")
        refuse_chap = self.vpn_setting.get_data_item("refuse-chap")
        refuse_mschap = self.vpn_setting.get_data_item("refuse-mschap")
        refuse_mschapv2 = self.vpn_setting.get_data_item("refuse-mschapv2")

        require_mppe = self.vpn_setting.get_data_item("require-mppe")
        require_mppe_128 = self.vpn_setting.get_data_item("require-mppe-128")
        mppe_stateful = self.vpn_setting.get_data_item("mppe-stateful")

        nobsdcomp = self.vpn_setting.get_data_item("nobsdcomp")
        nodeflate = self.vpn_setting.get_data_item("nodeflate")
        no_vj_comp = self.vpn_setting.get_data_item("no-vj-comp")


        lcp_echo_failure = self.vpn_setting.get_data_item("lcp-echo-failure")
        lcp_echo_interval = self.vpn_setting.get_data_item("lcp-echo-interval")
        
        self.refuse_mschap.set_active(refuse_mschap == None)
        self.refuse_mschapv2.set_active(refuse_mschapv2 == None)
        self.require_mppe.set_active(require_mppe != None)
        
        self.refuse_eap.set_active(refuse_eap == None)
        self.refuse_pap.set_active(refuse_pap == None)
        self.refuse_chap.set_active(refuse_chap == None)

        self.require_mppe_128.set_active(require_mppe_128 != None)
        if self.require_mppe_128.get_active() or self.mppe_stateful.get_active():
            self.require_mppe.set_active(True)
        self.mppe_stateful.set_active(mppe_stateful != None)
        self.nobsdcomp.set_active(nobsdcomp == None)
        self.nodeflate.set_active(nodeflate == None)
        self.no_vj_comp.set_active(no_vj_comp == None)

        if self.service_type == "l2tp":
            nopcomp = self.vpn_setting.get_data_item("nopcomp")
            noaccomp = self.vpn_setting.get_data_item("noaccomp")
            ipsec_enabled = self.vpn_setting.get_data_item("ipsec-enabled")

            self.nopcomp.set_active(nopcomp == None)
            self.noaccomp.set_active(noaccomp == None)
            
            if ipsec_enabled:
                self.ip_sec_enable.set_active(True)

                ipsec_group_name = self.vpn_setting.get_data_item("ipsec-group-name")
                ipsec_gateway_id = self.vpn_setting.get_data_item("ipsec-gateway-id")
                ipsec_psk = self.vpn_setting.get_data_item("ipsec-psk")
                self.group_name.set_text(ipsec_group_name)
                self.gateway_id.set_text(ipsec_gateway_id)
                self.pre_shared_key.set_text(ipsec_psk)

            else:
                self.ip_sec_enable.set_active(False)

        if lcp_echo_failure == None and lcp_echo_interval == None:
            self.ppp_echo.set_active(False)
        else:
            self.ppp_echo.set_active(True)

        self.init_signal()
        self.init_lock = False
        self.require_mppe.emit("toggled")
        self.init_lock = True
        self.init_ui()
        #==================================
        # Connect signal
    def enable_ipsec_cb(self, widget):
        active = widget.get_active()
        if active:
            self.vpn_setting.set_data_item("ipsec-enabled", "yes")
            self.group_name.set_sensitive(True)
            self.gateway_id.set_sensitive(True)
            self.pre_shared_key.set_sensitive(True)

            ipsec_group_name = self.vpn_setting.get_data_item("ipsec-group-name")
            ipsec_gateway_id = self.vpn_setting.get_data_item("ipsec-gateway-id")
            ipsec_psk = self.vpn_setting.get_data_item("ipsec-psk")
            
            #print ipsec_group_name
            self.group_name.set_text(ipsec_group_name)
            self.gateway_id.set_text(ipsec_gateway_id)
            self.pre_shared_key.set_text(ipsec_psk)
            self.init_ui()
        else:
            self.vpn_setting.delete_data_item("ipsec-enabled")
            self.group_name.set_text("")
            self.gateway_id.set_text("")
            self.pre_shared_key.set_text("")

            self.group_name.set_sensitive(False)
            self.gateway_id.set_sensitive(False)
            self.pre_shared_key.set_sensitive(False)
            self.init_ui()

    def entry_focus_out_cb(self, widget, event, key):
        text = widget.get_text()
        if text and key != "name":
            self.vpn_setting.set_data_item(key, text)
        else:
            self.vpn_setting.delete_data_item(key)
    def entry_changed_cb(self, widget, string, key):
        if string == "":
            #print key,"entry is empty"
            self.vpn_setting.delete_data_item(key)
        elif key != "name":
            self.vpn_setting.set_data_item(key, string)

        if self.connection.check_setting_finish():
            Dispatcher.set_button("save", True)
        else:
            Dispatcher.set_button("save", False)


    def check_button_cb(self, widget, key):
        auth_lock = self.auth_lock()
        active = widget.get_active()
        if key.startswith("refuse"):
            if active:
                self.vpn_setting.delete_data_item(key)
            else:
                self.vpn_setting.set_data_item(key, "yes")

            if auth_lock:
                self.require_mppe_label.set_sensitive(False)
                self.require_mppe.set_sensitive(False)

                self.set_group_sensitive(True)
            else:
                self.require_mppe_label.set_sensitive(True)
                self.require_mppe.set_sensitive(True)

        elif key.startswith("no"):
            if active:
                self.vpn_setting.delete_data_item(key)
            else:
                self.vpn_setting.set_data_item(key, "yes")

        elif key == "echo":
            if active:
                self.vpn_setting.set_data_item("lcp-echo-failure", "5")
                self.vpn_setting.set_data_item("lcp-echo-interval", "30")
            else:
                self.vpn_setting.delete_data_item("lcp-echo-failure")
                self.vpn_setting.delete_data_item("lcp-echo-interval")
        elif key.startswith("ipsec"):
            if active:
                self.vpn_setting.set_data_item(key, "yes")
            else:
                self.vpn_setting.delete_data_item(key)
        elif key.startswith("require") or key.startswith("mppe"):
            if active:
                self.vpn_setting.set_data_item(key, "yes")
            else:
                self.vpn_setting.delete_data_item(key)
            

        if self.connection.check_setting_finish():
            Dispatcher.set_button("save", True)
        else:
            Dispatcher.set_button("save", False)
    
    def click_mppe_callback(self, widget, key):
        active = widget.get_active()
        if active and key != "name":
            self.vpn_setting.set_data_item(key, "yes")
            #self.set_group_active(False)
            self.set_group_sensitive(False)

            self.mppe_group_set_sensitive(True)
            self.init_ui()
        else:
            #self.set_group_active(True)
            self.set_group_sensitive(True)
            self.vpn_setting.delete_data_item(key)
            self.mppe_group_set_active(False)
            self.mppe_group_set_sensitive(False)
            self.init_ui()
        
        if self.init_lock:
            if self.connection.check_setting_finish():
                Dispatcher.set_button("save", True)
            else:
                Dispatcher.set_button("save", False)

        if self.auth_lock():
            self.require_mppe_label.set_sensitive(False)
            self.require_mppe.set_sensitive(False)
            return


    def mppe_group_set_sensitive(self, boolean):
        self.require_mppe_128_label.set_sensitive(boolean)
        self.mppe_stateful_label.set_sensitive(boolean)
        self.require_mppe_128.set_sensitive(boolean)
        self.mppe_stateful.set_sensitive(boolean)

    def mppe_group_set_active(self, boolean):
        log.debug()
        self.require_mppe_128.set_active(boolean)
        self.mppe_stateful.set_active(boolean)

    def confirm_button_cb(self, widget):
        self.module_frame.send_message("change_crumb", 2)
        nm_module.slider._slide_to_page("vpn", "none")
        
    def auth_lock(self):
        if self.refuse_mschap.get_active() or self.refuse_mschapv2.get_active():
            return False
        else:
            return True

    def set_group_active(self, boolean):
        self.refuse_eap.set_active(boolean)
        self.refuse_pap.set_active(boolean)
        self.refuse_chap.set_active(boolean)

    def set_group_sensitive(self, boolean):
        self.refuse_eap.set_sensitive(boolean)
        self.refuse_pap.set_sensitive(boolean)
        self.refuse_chap.set_sensitive(boolean)
        self.refuse_eap_label.set_sensitive(boolean)
        self.refuse_pap_label.set_sensitive(boolean)
        self.refuse_chap_label.set_sensitive(boolean)
Beispiel #14
0
class Security(gtk.VBox):
    ENTRY_WIDTH = 222

    def __init__(self,
                 connection,
                 set_button_cb,
                 need_ssid=False,
                 settings_obj=None):
        gtk.VBox.__init__(self)
        self.tab_name = _("Security")
        self.connection = connection
        self.set_button = set_button_cb
        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj
        self.settings_obj.initial_lock = True

        self.need_ssid = need_ssid
        self.presave_index = None

        if self.need_ssid:
            log.info("enter hidden network settings")
            self.add_ssid_entry()

        if self.connection.get_setting(
                "802-11-wireless").security == "802-11-wireless-security":
            self.has_security = True
            self.setting = self.connection.get_setting(
                "802-11-wireless-security")
        else:
            self.has_security = False
        self.security_label = Label(_("Security:"),
                                    enable_select=False,
                                    enable_double_click=False)
        self.key_label = Label(_("Key:"),
                               enable_select=False,
                               enable_double_click=False)
        self.wep_index_label = Label(_("Wep index:"),
                                     enable_select=False,
                                     enable_double_click=False)

        self.auth_label = Label(_("Authentication:"),
                                enable_select=False,
                                enable_double_click=False)
        self.password_label = Label(_("Password:"******"None"), None),
                           (_("WEP (Hex or ASCII)"), "none"),
                           (_("WEP 104/128-bit Passphrase"), "none"),
                           (_("WPA WPA2 Personal"), "wpa-psk")]
        #entry_item = map(lambda l: (l[1],l[0]), enumerate(self.encry_list))
        self.security_combo = ComboBox(self.encry_list,
                                       fixed_width=self.ENTRY_WIDTH)
        #self.security_combo.set_size_request(self.ENTRY_WIDTH, 22)

        self.key_entry = PasswordEntry()
        self.password_entry = PasswordEntry()
        self.show_key_check = CheckButton(_("Show password"), padding_x=0)
        self.show_key_check.connect("toggled", self.show_key_check_button_cb)
        self.wep_index_spin = SpinBox(0, 1, 4, 1, self.ENTRY_WIDTH)
        self.auth_combo = ComboBox([(_("Shared Key"), "shared"),
                                    (_("Open System"), "open")],
                                   fixed_width=self.ENTRY_WIDTH)

        ## advance button
        self.align = gtk.Alignment(0, 1.0, 0, 0)
        self.align.set_padding(0, 0, 376, 0)
        self.align.set_size_request(-1, 30)
        self.button = Button(_("Advanced"))
        self.align.add(self.button)

        ## Create table
        self.table = gtk.Table(5, 4)
        #TODO UI change
        label_list = [
            "security_label", "key_label", "wep_index_label", "auth_label",
            "password_label"
        ]
        widget_list = [
            "password_entry", "key_entry", "wep_index_spin", "auth_combo",
            "security_combo"
        ]
        for label in label_list:
            l = getattr(self, label)
            l.set_can_focus(False)
            align = style.wrap_with_align(l, width=210)
            setattr(self, label + "_align", align)

        for w in widget_list:
            l = getattr(self, w)
            align = style.wrap_with_align(l, align="left")
            setattr(self, w + "_align", align)

        self.show_key_check_align = style.wrap_with_align(self.show_key_check,
                                                          align="left")

        self.reset(self.has_security)
        self.security_combo.connect("item-selected", self.change_encry_type)
        self.key_entry.entry.connect("changed", self.save_wep_pwd)
        self.password_entry.entry.connect("changed", self.save_wpa_pwd)
        self.wep_index_spin.connect("value-changed", self.wep_index_spin_cb)
        self.auth_combo.connect("item-selected", self.save_auth_cb)

        style.set_table(self.table)
        table_align = gtk.Alignment(0, 0, 0, 0)
        table_align.add(self.table)
        style.draw_background_color(self)
        width, height = self.ENTRY_WIDTH, 22
        self.key_entry.set_size(width, height)
        self.password_entry.set_size(width, height)
        self.wep_index_spin.set_size_request(width, height)
        self.auth_combo.set_size_request(width, height)
        self.security_combo.set_size_request(width, height)
        self.pack_start(table_align, False, False)
        self.pack_start(self.align, False, False, 0)
        self.settings_obj.initial_lock = False

    def add_ssid_entry(self):
        self.wireless = self.connection.get_setting("802-11-wireless")
        self.ssid_label = Label(_("SSID:"),
                                enable_select=False,
                                enable_double_click=False)
        self.ssid_label_align = style.wrap_with_align(self.ssid_label,
                                                      width=210)
        self.ssid_entry = InputEntry()
        self.ssid_entry.set_size(self.ENTRY_WIDTH, 22)
        self.ssid_entry_align = style.wrap_with_align(self.ssid_entry,
                                                      align="left")
        self.ssid_entry.entry.connect("changed", self.set_ssid)
        self.ssid_entry.set_text(self.wireless.ssid)

        #self.add(align)

    def set_ssid(self, widget, content):
        self.wireless.ssid = content
        check_settings(self.connection, None)

    def advand_cb(self, widget):
        pass

    def reset(self, security=True):
        ## Add security
        container_remove_all(self.table)
        if self.need_ssid:
            self.table.attach(self.ssid_label_align, 0, 1, 0, 1)
            self.table.attach(self.ssid_entry_align, 1, 4, 0, 1)

        self.table.resize(2, 4)
        self.table.attach(self.security_label_align, 0, 1, 1, 2)
        self.table.attach(self.security_combo_align, 1, 4, 1, 2)

        if not security:
            self.presave_index = self.security_combo.get_select_index()
            return

        keys = [None, "none", "none", "wpa-psk"]

        self.key_mgmt = self.setting.key_mgmt
        if self.key_mgmt == "none":
            key_type = self.setting.wep_key_type
            self.security_combo.set_select_index(key_type)
        else:
            self.security_combo.set_select_index(keys.index(self.key_mgmt))

        if not self.security_combo.get_current_item()[1] == None:
            try:
                (setting_name, method) = self.connection.guess_secret_info()
                secret = nm_module.secret_agent.agent_get_secrets(
                    self.connection.object_path, setting_name, method)
                if secret == None:
                    secret = ''
                log.debug("get secret", setting_name, method, "secret")
            except Exception, e:
                log.error("get secret error", e)
                secret = ""

            if self.security_combo.get_current_item()[1] == "wpa-psk":
                self.table.resize(4, 4)
                self.table.attach(self.password_label_align, 0, 1, 2, 3)
                self.table.attach(self.password_entry_align, 1, 4, 2, 3)
                self.table.attach(self.show_key_check_align, 1, 4, 3, 4)

                self.password_entry.entry.set_text(secret)
                if secret:
                    #Dispatcher.set_button("save", True)
                    ###########
                    self.settings_obj.wlan_encry_is_valid = True
                    self.settings_obj.set_button("save", True)
                self.setting.psk = secret

            elif self.security_combo.get_current_item()[1] == "none":
                self.table.resize(6, 4)
                # Add Key
                self.table.attach(self.key_label_align, 0, 1, 2, 3)
                self.table.attach(self.key_entry_align, 1, 4, 2, 3)
                self.table.attach(self.show_key_check_align, 1, 4, 3, 4)
                # Add wep index
                self.table.attach(self.wep_index_label_align, 0, 1, 4, 5)
                self.table.attach(self.wep_index_spin_align, 1, 4, 4, 5)
                # Add Auth
                self.table.attach(self.auth_label_align, 0, 1, 5, 6)
                self.table.attach(self.auth_combo_align, 1, 4, 5, 6)

                # Retrieve wep properties
                try:
                    index = self.setting.wep_tx_keyidx
                    auth = self.setting.auth_alg
                    log.debug(auth, index)
                    self.auth_combo.set_select_index(["shared",
                                                      "open"].index(auth))
                except Exception, e:
                    log.error(e)
                    index = 0
                    auth = "shared"
                # must convert long int to int
                index = int(index)

                #init_key = True
                #if isinstance(self.connection, NMRemoteConnection):
                #init_setting = self.connection.get_setting("802-11-wireless-security")
                #if init_setting.wep_key_type != self.setting.wep_key_type:
                #init_key = False

                #if init_key:
                self.key_entry.entry.set_text(secret)
                self.setting.set_wep_key(index, secret)
                self.wep_index_spin.set_value(index + 1)
                self.auth_combo.set_select_index(["shared",
                                                  "open"].index(auth))
Beispiel #15
0
class Form(DialogBox):
    def __init__(self):
        DialogBox.__init__(
            self,
            _("Convert"),
            FORM_WIDTH,
            FORM_HEIGHT,
            mask_type=DIALOG_MASK_SINGLE_PAGE,
            close_callback=self.hide_all,
            modal=True,
            window_hint=gtk.gdk.WINDOW_TYPE_HINT_DIALOG,
            window_pos=gtk.WIN_POS_CENTER,
            # skip_taskbar_hint=False,
            resizable=False,
        )
        # Init value.
        self.init_value()
        # Init all widgets.
        self.InitializeComponent()

    def init_value(self):
        read_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 "xml")
        self.read_xml = ReadXml(read_path)
        self.model_dict = {}

        # init brand EN list.
        self.brand_dict = {
            "intel": _("intel"),
            "zte": _("zte"),
            "hasee": _("hasee"),
            "apple": _("apple"),
            "nokia": _("nokia"),
            "alcatel": _("alcatel"),
            "google": _("google"),
            "asus": _("asus"),
            "hp": _("hp"),
            "sony": _("sony"),
            "hedy": _("hedy"),
            "archos": _("archos"),
            "boway": _("boway"),
            "bird": _("bird"),
            "vivo": _("vivo"),
            "great wall": _("great wall"),
            "changhong": _("changhong"),
            "skyworth": _("skyworth"),
            "dell": _("dell"),
            "philips": _("philips"),
            "toshiba": _("toshiba"),
            "amazon": _("amazon"),
            "sdo": _("sdo"),
            "disney": _("disney"),
            "haier": _("haier"),
            "fujitsu": _("fujitsu"),
            "acer": _("acer"),
            "lenovo": _("lenovo"),
            "gigabyte": _("gigabyte"),
            "xiaomi": _("xiaomi"),
            "huawei": _("huawei"),
            "blackberry": _("blackberry"),
            "motorola": _("motorola"),
            "sangsung": _("sangsung"),
            "meizu ": _("meizu "),
            "benq": _("benq"),
            "panasonic": _("panasonic"),
            "sony ericsson": _("sony ericsson"),
            "pioneer": _("pioneer"),
            "hyundai": _("hyundai"),
            "newman": _("newman"),
            "coolpad": _("coolpad"),
            "malata": _("malata"),
            "malata": _("malata"),
            "sharp": _("sharp"),
            "gionee": _("gionee"),
            "k-touch": _("k-touch"),
            "Pantech": _("Pantech"),
            "hisense": _("hisense"),
            "teclast": _("teclast"),
            "cube": _("cube"),
            "amoi": _("amoi"),
            "doov": _("doov"),
            "minte": _("minte"),
            "dopod": _("dopod"),
            "eton": _("eton"),
            "cherr": _("cherr"),
            "gaoxinqi": _("gaoxinqi"),
            "konka": _("konka"),
            "viewsonic": _("viewsonic"),
            "xibo": _("xibo"),
            "hosin": _("hosin"),
            "apanda": _("apanda"),
            "iocean": _("iocean"),
            "mastone": _("mastone")
        }

    def InitializeComponent(self):
        # Init form event.
        # self.connect("destroy", lambda w : self.destroy())
        self.connect("destroy", lambda w: self.hide_all())
        # Init widgets.
        self.brand_label = Label("%s: " % _("Phone brand"))
        self.format_label = Label("%s: " % _("Output format"))
        self.bit_rate_label = Label("%s: " % _("Audio encoder"))
        self.frame_rate_label = Label("%s: " % _("Video encoder"))
        self.path_label = Label("%s: " % _("Output directory"))
        self.model_label = Label("%s: " % _("Phone model"))
        self.ratio_label = Label('    %s: ' % _("Resolution"))

        self.path_entry = InputEntry()
        self.save_path_entry = InputEntry()
        fixed_width = 108
        self.brand_combo = NewComboBox(fixed_width)
        self.format_combo = NewComboBox(fixed_width)
        self.bit_rate_combo = NewComboBox(fixed_width)
        self.frame_rate_combo = NewComboBox(fixed_width)
        self.model_combo = NewComboBox(fixed_width)
        self.ratio_combo = NewComboBox(fixed_width)

        self.modify_chooser_btn = FileChooserButton(
            "选择")  # connect self.FileChooser
        self.save_chooser_btn = Button(_("Change"))
        self.start_btn = Button(_("Start"))
        self.close_btn = Button(_("Close"))
        self.higt_set_bool = False
        self.higt_set_btn = LabelButton()  #Button(_("Advanced"))

        self.show_and_hide_task_btn = Button(_("Task Manager"))

        self.higt_hbox = gtk.HBox()
        self.higt_hbox.pack_start(self.higt_set_btn)

        self.higt_align = gtk.Alignment()
        self.higt_align.add(self.higt_hbox)
        self.higt_align.set_padding(0, 0, 7, 0)
        self.higt_align.set(1, 0, 1, 0)

        self.left_button_box.set_buttons([self.higt_align])
        self.right_button_box.set_buttons([self.start_btn, self.close_btn])

        # ratio_combo.
        self.__ratio_list = [
            "176 x 220",
            "240 x 320",
            "320 x 240",
            "320 x 480",
            "400 x 240",
            "480 x 800",
            "540 x 960",
            "600 x 1024",
            "640 x 480",
            "720 x 1280",
            "800 x 480",
            "800 x 600",
            "1024 x 600",
            "1024 x 768",
            "1152 x 864",
        ]
        self.ratio_items = []
        for ratio in self.__ratio_list:
            self.ratio_combo.append_text(ratio)
            self.ratio_items.append((ratio, ratio))
        self.ratio_combo.set_active(5)
        # brand_combo.
        brand_items = []
        for brand in self.read_xml.brand_dict.keys():
            brand_po = brand
            if self.brand_dict.has_key(brand):
                brand_po = self.brand_dict[brand]
            brand_items.append((brand_po, brand))

        self.brand_combo.set_items(brand_items, 0)
        #self.brand_combo.add_items(brand_items, 0)

        self.brand_combo.prepend_text(_("No Presets"))
        self.brand_combo.connect("changed", self.brand_combo_item_selected)
        # model_combo.
        self.model_label.set_sensitive(False)
        self.model_combo.set_sensitive(False)
        self.model_combo.prepend_text(_("No Model"))
        self.model_combo.connect("changed", self.model_combo_item_selected)
        #
        self.save_chooser_btn.set_size_request(75, 21)
        self.save_chooser_btn.connect("clicked", self.save_chooser_btn_clicked)

        # path_entry.
        PATH_ENTRY_WIDTH = 240
        PATH_ENTRY_HEIGHT = 22
        self.save_path_entry.set_sensitive(False)
        self.save_path_entry.set_text(self.get_home_path())
        self.save_path_entry.set_size(PATH_ENTRY_WIDTH, PATH_ENTRY_HEIGHT)
        self.close_btn.connect("clicked", lambda w: self.hide_all())
        # higt_set_btn.
        self.higt_set_btn.connect("clicked", self.higt_set_btn_clicked)

        # form body box add main fixed.
        self.body_table_ali = gtk.Alignment()
        self.body_table_ali.set_padding(6, 0, 0, 0)
        self.body_table = gtk.Table(rows=6, columns=4, homogeneous=False)
        self.body_table_ali.add(self.body_table)

        self.brand_model_hbox = gtk.HBox()
        top, bottom = 5, 5
        brand_position = eval(_("('brand_position', 20)"))
        model_position = eval(_("('model_position', 20)"))
        self.brand_hbox_ali, self.brand_hbox = self.create_hbox(
            bottom, top, 15 + int(brand_position[1]), 0, self.brand_label,
            self.brand_combo)
        self.model_hbox_ali, self.model_hbox = self.create_hbox(
            bottom, top, 50 - int(model_position[1]), 0, self.model_label,
            self.model_combo)

        self.brand_model_hbox.pack_start(self.brand_hbox_ali, False, False)
        self.brand_model_hbox.pack_start(self.model_hbox_ali, False, False)
        format_position = eval(_("('format_position', 12)"))
        ratio_position = eval(_("('ratio_position', 18)"))
        self.format_hbox_ali, self.format_hbox = self.create_hbox(
            bottom, top, 15 + int(format_position[1]), 0, self.format_label,
            self.format_combo)
        self.ratio_hbox_ali, ratio_hbox = self.create_hbox(
            bottom, top, 50 - int(ratio_position[1]), 0, self.ratio_label,
            self.ratio_combo)

        self.format_ratio_hbox = gtk.HBox()
        self.format_ratio_hbox.pack_start(self.format_hbox_ali, False, False)
        self.format_ratio_hbox.pack_start(self.ratio_hbox_ali, False, False)

        frame_rate_position = eval(_("('frame_position', 13)"))
        bit_rate_position = eval(_("('bit_rate_position', 28)"))
        self.frame_rate_hbox_ali, self.frame_rate_hbox = self.create_hbox(
            bottom, top, 15 + int(frame_rate_position[1]), 0,
            self.frame_rate_label, self.frame_rate_combo)
        self.bit_rate_hbox_ali, self.bit_rate_hbox = self.create_hbox(
            bottom, top, 50 - int(bit_rate_position[1]), 0,
            self.bit_rate_label, self.bit_rate_combo)

        self.bit_frame_hbox = gtk.HBox()
        self.bit_frame_hbox.pack_start(self.frame_rate_hbox_ali, False, False)
        self.bit_frame_hbox.pack_start(self.bit_rate_hbox_ali, False, False)

        # self.path_label, self.save_path_entry, self.save_chooser_btn
        self.save_path_hbox_ali = gtk.Alignment()
        self.save_path_hbox = gtk.HBox()
        self.save_path_hbox_ali.set_padding(5, 5, 16, 0)
        self.save_path_hbox_ali.add(self.save_path_hbox)

        self.save_path_entry_ali = gtk.Alignment()
        self.save_path_entry_ali.set_padding(1, 0, 0, 0)
        self.save_path_entry_ali.add(self.save_path_entry)

        self.save_chooser_btn_ali = gtk.Alignment()
        self.save_chooser_btn_ali.set_padding(0, 0, 10, 0)
        self.save_chooser_btn_ali.add(self.save_chooser_btn)

        self.save_path_hbox.pack_start(self.path_label, False, False)
        self.save_path_hbox.pack_start(self.save_path_entry_ali, False, False)
        self.save_path_hbox.pack_start(self.save_chooser_btn_ali, False, False)

        # left right top, bottom.
        '''brand_model_hbox.'''
        # self.body_table.attach(self.brand_model_hbox, 0, 1, 0, 1, gtk.EXPAND, gtk.EXPAND)
        self.body_table.attach(self.brand_model_hbox, 0, 1, 0, 1, gtk.FILL,
                               gtk.FILL)
        # self.body_table.attach(self.model_hbox, 1, 2, 0, 1, gtk.EXPAND, gtk.EXPAND)
        # self.body_table.attach(self.model_hbox, 2, 3, 0, 1, gtk.EXPAND, gtk.EXPAND)
        # self.body_table.attach(self.model_hbox, 3, 4, 0, 1, gtk.EXPAND, gtk.EXPAND)
        '''format_ratio_hbox.'''
        # self.body_table.attach(self.format_ratio_hbox, 0, 1, 1, 2, gtk.EXPAND, gtk.EXPAND)
        self.body_table.attach(self.format_ratio_hbox, 0, 1, 1, 2, gtk.FILL,
                               gtk.FILL)
        # self.body_table.attach(self.format_combo, 1, 2, 1, 2, gtk.EXPAND, gtk.EXPAND)
        # self.body_table.attach(self.ratio_hbox, 2, 3, 1, 2, gtk.EXPAND, gtk.EXPAND)
        # self.body_table.attach(self.ratio_combo, 3, 4, 1, 2, gtk.EXPAND, gtk.EXPAND)
        '''bit_frame_hbox.'''
        # self.body_table.attach(self.bit_frame_hbox, 0, 1, 2, 3, gtk.EXPAND, gtk.EXPAND)
        self.body_table.attach(self.bit_frame_hbox, 0, 1, 2, 3, gtk.FILL,
                               gtk.FILL)
        '''save_path_hbox.'''
        # self.body_table.attach(self.save_path_hbox_ali, 0, 1, 3, 4, gtk.EXPAND, gtk.EXPAND)
        self.body_table.attach(self.save_path_hbox_ali, 0, 1, 3, 4, gtk.FILL,
                               gtk.FILL)

        self.body_box.pack_start(self.body_table_ali, True, True)
        self.hide_setting()

    def create_hbox(self, top, bottom, left, right, child1, child2):
        hbox_ali = gtk.Alignment()
        hbox_ali.set_padding(top, bottom, left, right)
        hbox = gtk.HBox()
        hbox_ali.add(hbox)
        hbox.pack_start(child1, False, False)
        hbox.pack_start(child2, False, False)
        return hbox_ali, hbox

    def get_home_path(self):
        return os.path.expanduser("~")

    def save_chooser_btn_clicked(self, widget):
        '''保存目录... ...'''
        self.show_open_dir_dialog_window()

    def show_open_dir_dialog_window(self):
        open_dialog = gtk.FileChooserDialog(
            _("Choose a directory"), None,
            gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
             gtk.RESPONSE_OK))
        # current floader set.
        open_dialog.set_current_folder(self.get_home_path())
        # run dir dialog window.
        res = open_dialog.run()

        if res == gtk.RESPONSE_OK:
            path_string = open_dialog.get_filename()
            if path_string:
                self.save_path_entry.set_text(path_string)
        # destroy dialog window.
        open_dialog.destroy()

    def brand_combo_item_selected(self, combo, item_content):
        self.model_combo.clear_items()
        self.ratio_combo.clear_items()
        #
        try:
            self.model_dict = self.read_xml.load(
                self.read_xml.brand_dict[item_content])
        except Exception, e:
            print "brand_combo_item_selected[error]:", e
            self.model_dict = {}
        #
        if item_content != _("No Presets") and self.model_dict != {}:
            model_items = []
            for model in self.model_dict:
                model_items.append((model, model))
            self.model_combo.set_items(model_items, 0)

            # self.model_combo.droplist.set_size_request(-1, self.model_combo.droplist_height)
            self.model_combo.set_active(0)
            self.model_combo.set_sensitive(True)
            self.model_label.set_sensitive(True)
        else:
            # clear model and ratio all text.
            self.model_combo.append_text(_("No Model"))
            self.model_combo.set_sensitive(False)
            self.model_label.set_sensitive(False)
            # add ratios.
            for ratio in self.ratio_items:
                self.ratio_combo.append_text(ratio[0])
            self.ratio_combo.set_active(5)
Beispiel #16
0
class Wireless(gtk.VBox):
    ENTRY_WIDTH = 222

    def __init__(self, connection, set_button_cb, settings_obj=None):
        gtk.VBox.__init__(self)
        self.tab_name = _("Wireless")
        self.connection = connection
        self.set_button = set_button_cb
        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj

        self.wireless = self.connection.get_setting("802-11-wireless")
        ### UI
        self.ssid_label = Label(_("SSID:"),
                                enable_select=False,
                                enable_double_click=False)
        self.ssid_entry = InputEntry()
        self.ssid_entry.set_size(self.ENTRY_WIDTH, 22)

        self.mode_label = Label(_("Mode:"),
                                enable_select=False,
                                enable_double_click=False)
        self.mode_combo = ComboBox([(_("Infrastructure"), "infrastructure"),
                                    (_("Ad-hoc"), "adhoc")],
                                   fixed_width=130)

        # TODO need to put this section to personal wifi
        self.band_label = Label(_("Band:"),
                                enable_select=False,
                                enable_double_click=False)

        self.band_combo = ComboBox([(_("Automatic"), None), ("a (5 GHZ)", "a"),
                                    ("b/g (2.4)", "bg")],
                                   fixed_width=self.ENTRY_WIDTH)
        self.channel_label = Label(_("Channel:"),
                                   enable_select=False,
                                   enable_double_click=False)
        self.channel_spin = SpinBox(0, 0, 1500, 1, self.ENTRY_WIDTH)
        # BSSID
        self.bssid_label = Label(_("BSSID:"),
                                 enable_select=False,
                                 enable_double_click=False)
        self.bssid_entry = MACEntry()
        self.mac_address_label = Label(_("Device Mac Address:"),
                                       enable_select=False,
                                       enable_double_click=False)
        self.mac_entry = MACEntry()
        self.clone_addr_label = Label(_("Cloned Mac Address:"),
                                      enable_select=False,
                                      enable_double_click=False)
        self.clone_entry = MACEntry()

        self.mtu_label = Label(_("MTU:"),
                               enable_select=False,
                               enable_double_click=False)
        self.mtu_spin = SpinBox(0, 0, 1500, 1, 130)

        self.table = gtk.Table(8, 2, False)
        """
        wrap with alignment
        """
        widget_list = [
            "ssid_label", "ssid_entry", "mode_label", "mode_combo",
            "band_label", "band_combo", "channel_label", "channel_spin",
            "bssid_label", "bssid_entry", "mac_address_label", "mac_entry",
            "clone_addr_label", "clone_entry", "mtu_label", "mtu_spin"
        ]

        for widget in widget_list:
            item = getattr(self, widget)
            if widget.endswith("label"):
                item.set_can_focus(False)
                align = style.wrap_with_align(item, width=210)
            else:
                align = style.wrap_with_align(item, align="left")
            setattr(self, widget + "_align", align)

        #TODO UI change
        style.draw_background_color(self)
        #align = style.set_box_with_align(self.table, 'text')
        style.set_table(self.table)

        self.section = SettingSection(_("Default Settings"),
                                      always_show=False,
                                      revert=True,
                                      label_right=True,
                                      has_seperator=False)
        self.pack_start(self.section, False, False)
        self.section.toggle_off = self.use_default_setting
        self.section.toggle_on = self.use_user_setting
        self.section.load([self.table])
        #self.pack_start(self.table, False, False)
        #self.table.set_size_request(340, 227)

        #self.ssid_entry.set_size_request(130, 22)
        self.bssid_entry.set_size_request(130, 22)
        self.mac_entry.set_size_request(130, 22)
        self.clone_entry.set_size_request(130, 22)

        self.reset()
        #self.mode_combo.connect("item-selected", self.mode_combo_selected)
        self.band_combo.connect("item-selected", self.band_combo_selected)
        self.mtu_spin.connect("value-changed", self.spin_value_changed, "mtu")
        self.mtu_spin.value_entry.connect("changed", self.spin_user_set)
        self.channel_spin.connect("value-changed", self.spin_value_changed,
                                  "channel")
        self.ssid_entry.entry.connect("changed", self.entry_changed, "ssid")
        self.bssid_entry.connect("changed", self.entry_changed, "bssid")
        self.mac_entry.connect("changed", self.entry_changed, "mac_address")
        self.clone_entry.connect("changed", self.entry_changed,
                                 "cloned_mac_address")

    def use_default_setting(self):
        log.debug()
        self.bssid_entry.set_address("")
        self.mac_entry.set_address("")
        self.clone_entry.set_address("")
        self.mtu_spin.set_value(0)

    def use_user_setting(self):
        pass

    def spin_user_set(self, widget, value):
        if value == "":
            return
        value = int(value)
        if self.mtu_spin.lower_value <= value <= self.mtu_spin.upper_value:
            self.mtu_spin.update_and_emit(value)
        elif value < self.mtu_spin.lower_value:
            self.mtu_spin.update_and_emit(self.mtu_spin.lower_value)
        else:
            self.mtu_spin.update_and_emit(self.mtu_spin.upper_value)

    def spin_value_changed(self, widget, value, types):
        setattr(self.wireless, types, value)
        is_valid = self.connection.check_setting_finish()
        self.settings_obj.set_button("save", is_valid)

    def entry_changed(self, widget, content, types):
        is_valid = True
        if types == "ssid":
            setattr(self.wireless, types, content)
        else:
            from nmlib.nm_utils import TypeConvert
            if (content == "") or TypeConvert.is_valid_mac_address(content):
                setattr(self.wireless, types, content)
                #check_settings(self.connection, self.set_button)
                is_valid = self.connection.check_setting_finish()
            else:
                is_valid = False
                #Dispatcher.set_button("save", False)
        self.settings_obj.mac_is_valid = is_valid
        self.settings_obj.set_button("save", is_valid)

    def band_combo_selected(self, widget, content, value, index):
        self.wirless.band = value

    def mode_combo_selected(self, widget, content, value, index):
        self.wireless.mode = value
        self.wireless.adapt_wireless_commit()
        self.reset_table()

    def reset_table(self):
        container_remove_all(self.table)
        mode = self.mode_combo.get_current_item()[1]

        #self.table.attach(self.ssid_label_align, 0, 1, 0, 1)
        #self.table.attach(self.ssid_entry_align, 1, 2, 0, 1)
        # Mode
        self.table.attach(self.mode_label_align, 0, 1, 1, 2)
        self.table.attach(self.mode_combo_align, 1, 2, 1, 2)
        if mode == "adhoc":
            self.table.attach(self.band_label_align, 0, 1, 2, 3)
            self.table.attach(self.band_combo_align, 1, 2, 2, 3)
            self.table.attach(self.channel_label_align, 0, 1, 3, 4)
            self.table.attach(self.channel_spin_align, 1, 2, 3, 4)

        # Bssid
        self.table.attach(self.bssid_label_align, 0, 1, 4, 5)
        self.table.attach(self.bssid_entry_align, 1, 2, 4, 5)

        # MAC
        self.table.attach(self.mac_address_label_align, 0, 1, 5, 6)
        self.table.attach(self.mac_entry_align, 1, 2, 5, 6)
        # MAC_CLONE
        self.table.attach(self.clone_addr_label_align, 0, 1, 6, 7)
        self.table.attach(self.clone_entry_align, 1, 2, 6, 7)
        # MTU
        self.table.attach(self.mtu_spin_align, 1, 2, 7, 8)
        self.table.attach(self.mtu_label_align, 0, 1, 7, 8)

    def reset(self):
        wireless = self.wireless
        ## retrieve wireless info
        setting_list = ['bssid', 'mac_address', 'cloned_mac_address', 'mtu']
        if wireless.ssid != None:
            self.ssid_entry.set_text(wireless.ssid)

        if wireless.bssid != None:
            self.bssid_entry.set_address(wireless.bssid)

        if wireless.mode == 'infrastructure':
            #self.mode_combo.set_select_index(0)
            self.mode_combo.set_select_index(0)
        else:
            #self.mode_combo.set_select_index(1)
            self.mode_combo.set_select_index(1)

        if wireless.mac_address != None:
            self.mac_entry.set_address(wireless.mac_address)

        if wireless.cloned_mac_address != None:
            self.clone_entry.set_address(wireless.cloned_mac_address)

        if wireless.mtu != None:
            self.mtu_spin.set_value(int(wireless.mtu))

        if any(map(lambda i: getattr(wireless, i), setting_list)):
            self.section.set_active(False)

        self.reset_table()

    def save_change(self):

        self.wireless.ssid = self.ssid_entry.get_text()
        self.wireless.mode = self.mode_combo.get_current_item()[0]

        if self.bssid_entry.get_address() != "":
            self.wireless.bssid = self.bssid_entry.get_address()
        if self.mac_entry.get_address() != "":
            self.wireless.mac_address = self.mac_entry.get_address()
        if self.clone_entry.get_address() != "":
            self.wireless.cloned_mac_address = self.clone_entry.get_address()

        self.wireless.mtu = self.mtu_spin.get_value()
        self.wireless.adapt_wireless_commit()
class Security(gtk.VBox):
    ENTRY_WIDTH = 222

    def __init__(self, connection, set_button_cb, need_ssid=False, settings_obj=None):
        gtk.VBox.__init__(self)
        self.tab_name = _("Security")
        self.connection = connection
        self.set_button = set_button_cb
        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj
        self.settings_obj.initial_lock = True

        self.need_ssid = need_ssid
        self.presave_index = None

        if self.need_ssid:
            log.info("enter hidden network settings")
            self.add_ssid_entry()
        
        if self.connection.get_setting("802-11-wireless").security == "802-11-wireless-security":
            self.has_security = True
            self.setting = self.connection.get_setting("802-11-wireless-security")
        else:
            self.has_security = False
        self.security_label = Label(_("Security:"),
                                    enable_select=False,
                                    enable_double_click=False)
        self.key_label = Label(_("Key:"),
                               enable_select=False,
                               enable_double_click=False)
        self.wep_index_label = Label(_("Wep index:"),
                                     enable_select=False,
                                     enable_double_click=False)

        self.auth_label = Label(_("Authentication:"),
                                enable_select=False,
                                enable_double_click=False)
        self.password_label = Label(_("Password:"******"None"), None),
                      (_("WEP (Hex or ASCII)"), "none"),
                      (_("WEP 104/128-bit Passphrase"), "none"),
                      (_("WPA WPA2 Personal"), "wpa-psk")]
        #entry_item = map(lambda l: (l[1],l[0]), enumerate(self.encry_list))
        self.security_combo = ComboBox(self.encry_list, fixed_width=self.ENTRY_WIDTH)
        #self.security_combo.set_size_request(self.ENTRY_WIDTH, 22)

        self.key_entry = PasswordEntry()
        self.password_entry = PasswordEntry()
        self.show_key_check = CheckButton(_("Show password"), padding_x=0)
        self.show_key_check.connect("toggled", self.show_key_check_button_cb)
        self.wep_index_spin = SpinBox(0, 1, 4, 1, self.ENTRY_WIDTH)
        self.auth_combo = ComboBox([
                                    (_("Shared Key"), "shared"),
                                    (_("Open System"), "open")],fixed_width=self.ENTRY_WIDTH)

        ## advance button
        self.align = gtk.Alignment(0, 1.0, 0, 0)
        self.align.set_padding(0, 0, 376, 0)
        self.align.set_size_request(-1 ,30)
        self.button = Button(_("Advanced"))
        self.align.add(self.button)

        ## Create table
        self.table = gtk.Table(5, 4)
        #TODO UI change
        label_list = ["security_label", "key_label", "wep_index_label", "auth_label", "password_label"]
        widget_list = ["password_entry", "key_entry", "wep_index_spin", "auth_combo", "security_combo"]
        for label in label_list:
            l = getattr(self, label)
            l.set_can_focus(False)
            align = style.wrap_with_align(l, width=210)
            setattr(self, label+"_align", align)

        for w in widget_list:
            l = getattr(self, w)
            align = style.wrap_with_align(l, align="left")
            setattr(self, w+"_align", align)

        self.show_key_check_align = style.wrap_with_align(self.show_key_check, align="left")

        self.reset(self.has_security)
        self.security_combo.connect("item-selected", self.change_encry_type)
        self.key_entry.entry.connect("changed", self.save_wep_pwd)
        self.password_entry.entry.connect("changed", self.save_wpa_pwd)
        self.wep_index_spin.connect("value-changed", self.wep_index_spin_cb)
        self.auth_combo.connect("item-selected", self.save_auth_cb)
        
        style.set_table(self.table)
        table_align = gtk.Alignment(0, 0, 0, 0)
        table_align.add(self.table)
        style.draw_background_color(self)
        width, height = self.ENTRY_WIDTH, 22
        self.key_entry.set_size(width, height)
        self.password_entry.set_size(width, height)
        self.wep_index_spin.set_size_request(width, height)
        self.auth_combo.set_size_request(width, height)
        self.security_combo.set_size_request(width, height)
        self.pack_start(table_align, False, False)
        self.pack_start(self.align, False, False, 0)
        self.settings_obj.initial_lock = False

    def add_ssid_entry(self):
        self.wireless = self.connection.get_setting("802-11-wireless")
        self.ssid_label = Label(_("SSID:"),
                                enable_select=False,
                                enable_double_click=False)
        self.ssid_label_align = style.wrap_with_align(self.ssid_label, width=210)
        self.ssid_entry = InputEntry()
        self.ssid_entry.set_size(self.ENTRY_WIDTH, 22)
        self.ssid_entry_align = style.wrap_with_align(self.ssid_entry, align="left")
        self.ssid_entry.entry.connect("changed", self.set_ssid)
        self.ssid_entry.set_text(self.wireless.ssid)

        #self.add(align)

    def set_ssid(self, widget, content):
        self.wireless.ssid = content
        check_settings(self.connection, None)

    def advand_cb(self, widget):
        pass

    def reset(self, security=True):
        ## Add security
        container_remove_all(self.table)
        if self.need_ssid:
            self.table.attach(self.ssid_label_align, 0, 1, 0, 1)
            self.table.attach(self.ssid_entry_align, 1, 4, 0, 1)
        
        self.table.resize(2, 4)
        self.table.attach(self.security_label_align, 0, 1, 1, 2)
        self.table.attach(self.security_combo_align, 1, 4, 1, 2)

        if not security:
            self.presave_index = self.security_combo.get_select_index()
            return 
        
        keys = [None, "none", "none","wpa-psk"]
        
        self.key_mgmt = self.setting.key_mgmt
        if self.key_mgmt == "none":
            key_type = self.setting.wep_key_type
            self.security_combo.set_select_index(key_type)
        else:
            self.security_combo.set_select_index(keys.index(self.key_mgmt))

        if not self.security_combo.get_current_item()[1] == None: 
            try:
                (setting_name, method) = self.connection.guess_secret_info() 
                secret = nm_module.secret_agent.agent_get_secrets(self.connection.object_path,
                                                        setting_name,
                                                        method)
                if secret == None:
                    secret = ''
                log.debug("get secret", setting_name, method, "secret")
            except Exception, e:
                log.error("get secret error", e)
                secret = ""

            if self.security_combo.get_current_item()[1] == "wpa-psk":
                self.table.resize(4, 4)
                self.table.attach(self.password_label_align, 0, 1, 2, 3)
                self.table.attach(self.password_entry_align, 1, 4, 2, 3)
                self.table.attach(self.show_key_check_align, 1, 4, 3, 4)
                
                self.password_entry.entry.set_text(secret)
                if secret:
                    #Dispatcher.set_button("save", True)
                    ###########
                    self.settings_obj.wlan_encry_is_valid = True
                    self.settings_obj.set_button("save", True)
                self.setting.psk = secret

            elif self.security_combo.get_current_item()[1] == "none":
                self.table.resize(6, 4)
                # Add Key
                self.table.attach(self.key_label_align, 0, 1, 2, 3)
                self.table.attach(self.key_entry_align, 1, 4, 2, 3)
                self.table.attach(self.show_key_check_align, 1, 4, 3, 4)
                # Add wep index
                self.table.attach(self.wep_index_label_align, 0, 1, 4, 5)
                self.table.attach(self.wep_index_spin_align, 1, 4, 4, 5)
                # Add Auth
                self.table.attach(self.auth_label_align, 0, 1, 5, 6)
                self.table.attach(self.auth_combo_align, 1, 4, 5, 6)

                # Retrieve wep properties
                try:
                    index = self.setting.wep_tx_keyidx
                    auth = self.setting.auth_alg
                    log.debug(auth, index)
                    self.auth_combo.set_select_index(["shared", "open"].index(auth))
                except Exception, e:
                    log.error(e)
                    index = 0
                    auth = "shared"
                # must convert long int to int 
                index = int(index)
                
                #init_key = True
                #if isinstance(self.connection, NMRemoteConnection):
                    #init_setting = self.connection.get_setting("802-11-wireless-security")
                    #if init_setting.wep_key_type != self.setting.wep_key_type:
                        #init_key = False

                #if init_key:
                self.key_entry.entry.set_text(secret)
                self.setting.set_wep_key(index, secret)
                self.wep_index_spin.set_value(index + 1)
                self.auth_combo.set_select_index(["shared", "open"].index(auth))
Beispiel #18
0
class GeneralBox(BaseBox):
    def __init__(self):
        BaseBox.__init__(self)

        self.main_box.pack_start(self.create_uninstall_box(), False, True)
        self.main_box.pack_start(self.create_download_dir_table(), False, True)

    def create_uninstall_box(self):
        main_table = gtk.Table(2, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        uninstall_title_label = Label(_("On uninstalling the software"))

        # mini_check_button
        self.delete_check_button = CheckButton(_("Delete configuration files"))
        self.delete_check_button.set_active(get_purg_flag())
        self.delete_check_button.connect("toggled", lambda w: set_purge_flag(self.delete_check_button.get_active()))

        main_table.attach(uninstall_title_label, 0, 2, 0, 1, yoptions=gtk.FILL)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(self.delete_check_button, 0, 1, 2, 3, yoptions=gtk.FILL)

        return main_table

    def create_download_dir_table(self):
        main_table = gtk.Table(4, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)

        dir_title_label = Label(_("Download settings"))
        dir_title_label.set_size_request(200, 12)
        label_align = gtk.Alignment()
        label_align.set_padding(0, 0, 0, 0)
        label_align.add(dir_title_label)

        download_number_label = Label(_('Maximum number of download tasks: '))
        self.download_number_comobox = ComboBox(
                items = [(str(i+1), i+1) for i in range(10)],
                select_index = int(get_download_number())-1,
                )
        self.download_number_comobox.connect("item-selected", self.download_number_comobox_changed)
        download_number_hbox = gtk.HBox(spacing=5)
        download_number_hbox.pack_start(download_number_label, False, False)
        download_number_hbox.pack_start(self.download_number_comobox, False, False)

        change_download_dir_label = Label(_("Download directory: "))
        self.dir_entry = InputEntry()
        self.dir_entry.set_text(get_software_download_dir())
        self.dir_entry.set_editable(False)
        self.dir_entry.set_size(200, 25)

        modify_button = Button(_("Change"))
        modify_button.connect("clicked", self.change_download_save_dir)
        download_dir_hbox = gtk.HBox(spacing=5)
        download_dir_hbox.pack_start(change_download_dir_label, False, False)
        download_dir_hbox.pack_start(self.dir_entry, False, False)
        download_dir_hbox.pack_start(modify_button, False, False)

        main_table.attach(label_align, 0, 2, 0, 1, yoptions=gtk.FILL)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(download_number_hbox, 0, 2, 2, 3, xoptions=gtk.FILL)
        main_table.attach(download_dir_hbox, 0, 2, 3, 4, xoptions=gtk.FILL)
        return main_table

    def download_number_comobox_changed(self, widget, name, value, index):
        set_download_number(value)
        global_event.emit('max-download-number-changed', value)

    def change_download_save_dir(self, widget):
        local_dir = FolderChooseDialog(False).run()
        if local_dir:
            local_dir = os.path.expanduser(local_dir)
            if local_dir != get_software_download_dir():
                self.dir_entry.set_editable(True)
                self.dir_entry.set_text(local_dir)
                self.dir_entry.set_editable(False)
                set_software_download_dir(local_dir)
                global_event.emit('download-directory-changed')
class Wireless(gtk.VBox):
    ENTRY_WIDTH = 222

    def __init__(self, connection, set_button_cb, settings_obj=None):
        gtk.VBox.__init__(self)
        self.tab_name = _("Wireless")
        self.connection = connection 
        self.set_button = set_button_cb
        # 新增settings_obj变量,用于访问shared_methods.Settings对象
        self.settings_obj = settings_obj

        self.wireless = self.connection.get_setting("802-11-wireless")
        ### UI
        self.ssid_label = Label(_("SSID:"),
                                enable_select=False,
                                enable_double_click=False)
        self.ssid_entry = InputEntry()
        self.ssid_entry.set_size(self.ENTRY_WIDTH, 22)

        self.mode_label = Label(_("Mode:"),
                               enable_select=False,
                               enable_double_click=False)
        self.mode_combo = ComboBox([(_("Infrastructure"),"infrastructure"),(_("Ad-hoc"), "adhoc")], fixed_width=130)
        
        # TODO need to put this section to personal wifi
        self.band_label = Label(_("Band:"),
                               enable_select=False,
                               enable_double_click=False)
                                
        self.band_combo = ComboBox([(_("Automatic"), None),
                                    ("a (5 GHZ)", "a"),
                                    ("b/g (2.4)", "bg")],
                                    fixed_width=self.ENTRY_WIDTH)
        self.channel_label = Label(_("Channel:"),
                                   enable_select=False,
                                   enable_double_click=False)
        self.channel_spin = SpinBox(0, 0, 1500, 1, self.ENTRY_WIDTH)
        # BSSID
        self.bssid_label = Label(_("BSSID:"),
                                 enable_select=False,
                                 enable_double_click=False)
        self.bssid_entry = MACEntry()
        self.mac_address_label = Label(_("Device Mac Address:"),
                                 enable_select=False,
                                 enable_double_click=False)
        self.mac_entry = MACEntry()
        self.clone_addr_label = Label(_("Cloned Mac Address:"),
                                 enable_select=False,
                                 enable_double_click=False)
        self.clone_entry = MACEntry()

        self.mtu_label = Label(_("MTU:"),
                           enable_select=False,
                           enable_double_click=False)
        self.mtu_spin = SpinBox(0, 0, 1500, 1, 130)

        self.table = gtk.Table(8, 2, False)

        """
        wrap with alignment
        """
        widget_list = ["ssid_label", "ssid_entry", "mode_label", "mode_combo",
                       "band_label", "band_combo", "channel_label", "channel_spin",
                       "bssid_label", "bssid_entry", "mac_address_label", "mac_entry",
                       "clone_addr_label", "clone_entry", "mtu_label", "mtu_spin"]

        for widget in widget_list:
            item = getattr(self, widget)
            if widget.endswith("label"):
                item.set_can_focus(False)
                align = style.wrap_with_align(item, width=210)
            else:
                align = style.wrap_with_align(item, align="left")
            setattr(self, widget + "_align", align)

        #TODO UI change
        style.draw_background_color(self)
        #align = style.set_box_with_align(self.table, 'text')
        style.set_table(self.table)

        self.section = SettingSection(_("Default Settings"), always_show= False, revert=True, label_right=True, has_seperator=False)
        self.pack_start(self.section, False, False)
        self.section.toggle_off = self.use_default_setting
        self.section.toggle_on = self.use_user_setting
        self.section.load([self.table])
        #self.pack_start(self.table, False, False)
        #self.table.set_size_request(340, 227)

        #self.ssid_entry.set_size_request(130, 22)
        self.bssid_entry.set_size_request(130, 22)
        self.mac_entry.set_size_request(130, 22)
        self.clone_entry.set_size_request(130, 22)

        self.reset()
        #self.mode_combo.connect("item-selected", self.mode_combo_selected)
        self.band_combo.connect("item-selected", self.band_combo_selected)
        self.mtu_spin.connect("value-changed", self.spin_value_changed, "mtu")
        self.mtu_spin.value_entry.connect("changed", self.spin_user_set)
        self.channel_spin.connect("value-changed", self.spin_value_changed, "channel")
        self.ssid_entry.entry.connect("changed", self.entry_changed, "ssid")
        self.bssid_entry.connect("changed", self.entry_changed, "bssid")
        self.mac_entry.connect("changed", self.entry_changed, "mac_address")
        self.clone_entry.connect("changed", self.entry_changed, "cloned_mac_address")

    def use_default_setting(self):
        log.debug()
        self.bssid_entry.set_address("")
        self.mac_entry.set_address("")
        self.clone_entry.set_address("")
        self.mtu_spin.set_value(0)

    def use_user_setting(self):
        pass

    def spin_user_set(self, widget, value):
        if value == "":
            return
        value = int(value)
        if self.mtu_spin.lower_value <= value <= self.mtu_spin.upper_value:
            self.mtu_spin.update_and_emit(value)
        elif value < self.mtu_spin.lower_value:
            self.mtu_spin.update_and_emit(self.mtu_spin.lower_value)
        else:
            self.mtu_spin.update_and_emit(self.mtu_spin.upper_value)
            

    def spin_value_changed(self, widget, value, types):
        setattr(self.wireless, types, value)
        is_valid = self.connection.check_setting_finish()
        self.settings_obj.set_button("save", is_valid)

    def entry_changed(self, widget, content, types):
        is_valid = True
        if types == "ssid":
            setattr(self.wireless, types, content)
        else:
            from nmlib.nm_utils import TypeConvert
            if (content == "") or TypeConvert.is_valid_mac_address(content):
                setattr(self.wireless, types, content)
                #check_settings(self.connection, self.set_button)
                is_valid = self.connection.check_setting_finish()
            else:
                is_valid = False
                #Dispatcher.set_button("save", False)
        self.settings_obj.mac_is_valid = is_valid
        self.settings_obj.set_button("save", is_valid)

    def band_combo_selected(self, widget, content, value, index):
        self.wirless.band = value

    def mode_combo_selected(self, widget, content, value, index):
        self.wireless.mode = value
        self.wireless.adapt_wireless_commit()
        self.reset_table()

    def reset_table(self):
        container_remove_all(self.table)
        mode = self.mode_combo.get_current_item()[1]

        #self.table.attach(self.ssid_label_align, 0, 1, 0, 1)
        #self.table.attach(self.ssid_entry_align, 1, 2, 0, 1)
        # Mode
        self.table.attach(self.mode_label_align, 0, 1, 1, 2)
        self.table.attach(self.mode_combo_align, 1, 2, 1, 2)
        if mode == "adhoc":
            self.table.attach(self.band_label_align, 0, 1, 2, 3)
            self.table.attach(self.band_combo_align, 1, 2, 2, 3)
            self.table.attach(self.channel_label_align, 0, 1, 3, 4)
            self.table.attach(self.channel_spin_align, 1, 2, 3, 4)

        # Bssid
        self.table.attach(self.bssid_label_align, 0, 1, 4, 5)
        self.table.attach(self.bssid_entry_align, 1, 2, 4, 5)

        # MAC
        self.table.attach(self.mac_address_label_align, 0, 1, 5, 6)
        self.table.attach(self.mac_entry_align, 1, 2, 5, 6)
        # MAC_CLONE
        self.table.attach(self.clone_addr_label_align, 0, 1, 6, 7)
        self.table.attach(self.clone_entry_align, 1,2, 6, 7)
        # MTU
        self.table.attach(self.mtu_spin_align, 1, 2, 7, 8)
        self.table.attach(self.mtu_label_align, 0, 1, 7, 8)

    def reset(self):
        wireless = self.wireless
        ## retrieve wireless info
        setting_list = ['bssid','mac_address', 'cloned_mac_address', 'mtu']
        if wireless.ssid != None:
            self.ssid_entry.set_text(wireless.ssid)

        if wireless.bssid != None:
            self.bssid_entry.set_address(wireless.bssid)

        if wireless.mode == 'infrastructure':
            #self.mode_combo.set_select_index(0)
            self.mode_combo.set_select_index(0)
        else:
            #self.mode_combo.set_select_index(1)
            self.mode_combo.set_select_index(1)

        if wireless.mac_address != None:
            self.mac_entry.set_address(wireless.mac_address)

        if wireless.cloned_mac_address !=None:
            self.clone_entry.set_address(wireless.cloned_mac_address)

        if wireless.mtu != None:
            self.mtu_spin.set_value(int(wireless.mtu))

        if any(map(lambda i: getattr(wireless, i), setting_list)):
            self.section.set_active(False)
        
        self.reset_table()
    
    def save_change(self):
        
        self.wireless.ssid = self.ssid_entry.get_text()
        self.wireless.mode = self.mode_combo.get_current_item()[0]

        if self.bssid_entry.get_address() != "":
            self.wireless.bssid = self.bssid_entry.get_address()
        if self.mac_entry.get_address() != "":
            self.wireless.mac_address = self.mac_entry.get_address()
        if self.clone_entry.get_address() != "":
            self.wireless.cloned_mac_address = self.clone_entry.get_address()

        self.wireless.mtu = self.mtu_spin.get_value()
        self.wireless.adapt_wireless_commit()
class AttributesUI(DialogBox):
    def __init__(self, songs=None):
        DialogBox.__init__(self,
                           _("Converter"),
                           385,
                           200,
                           DIALOG_MASK_SINGLE_PAGE,
                           modal=True)

        self.songs = songs or [Player.song]
        default_format = "MP3 (CBR)"
        default_index = FORMATS.keys().index(default_format)
        format_box, self.format_combo_box = self.create_combo_widget(
            _("Format"), [(key, None) for key in FORMATS.keys()],
            default_index)
        quality_box, self.quality_combo_box = self.create_combo_widget(
            _("Quality"), self.get_quality_items(default_format),
            self.get_quality_index(default_format), 65)
        format_quality_box = gtk.HBox(spacing=68)
        format_quality_box.pack_start(format_box, False, False)
        format_quality_box.pack_start(quality_box, False, False)

        exists_box, self.exists_combo_box = self.create_combo_widget(
            _("Target file already exists"), [(_("Ask"), True),
                                              (_("Cover"), False)], 0)

        start_button = Button(_("Start"))
        close_button = Button(_("Close"))
        self.add_check_button = CheckButton(
            _("Add to Playlist after finished"), padding_x=2)

        main_table = gtk.Table()
        main_table.set_row_spacings(10)
        main_table.attach(format_quality_box, 0, 2, 0, 1, yoptions=gtk.FILL)
        main_table.attach(set_widget_left(exists_box),
                          0,
                          2,
                          1,
                          2,
                          yoptions=gtk.FILL)
        main_table.attach(self.create_output_box(),
                          0,
                          2,
                          2,
                          3,
                          yoptions=gtk.FILL)
        main_table.attach(set_widget_left(self.add_check_button),
                          0,
                          2,
                          3,
                          4,
                          yoptions=gtk.FILL)

        main_align = gtk.Alignment()
        main_align.set_padding(10, 10, 15, 10)
        main_align.add(main_table)

        # Connect signals.
        self.format_combo_box.connect("item-selected",
                                      self.reset_quality_items)
        start_button.connect("clicked", self.add_and_close)
        close_button.connect("clicked", lambda w: self.destroy())

        self.body_box.pack_start(main_align, False, True)
        self.right_button_box.set_buttons([start_button, close_button])

    def create_output_box(self):
        output_label = Label("%s:" % _("Output"))
        self.output_entry = InputEntry(os.path.expanduser("~/"))
        self.output_entry.set_size(210, 24)
        change_button = Button(_("Change"))
        change_button.connect("clicked", self.set_output_directory)
        output_box = gtk.HBox(spacing=5)
        output_box.pack_start(output_label, False, False)
        output_box.pack_start(self.output_entry, False, False)
        output_box.pack_start(change_button, False, False)
        return output_box

    def set_output_directory(self, widget):
        directory = WinDir(False).run()
        if directory:
            self.output_entry.set_text(directory)

    def get_quality_items(self, name):
        kbs_steps = [str(key) for key in FORMATS[name]["kbs_steps"]]
        return zip(kbs_steps, FORMATS[name]["raw_steps"])

    def get_quality_index(self, name):
        return FORMATS[name]["default_index"]

    def create_combo_widget(self,
                            label_content,
                            items,
                            select_index=0,
                            max_width=None):
        label = Label("%s:" % label_content)
        combo_box = ComboBox(items,
                             select_index=select_index,
                             max_width=max_width)

        hbox = gtk.HBox(spacing=5)
        hbox.pack_start(label, False, False)
        hbox.pack_start(combo_box, False, False)
        return hbox, combo_box

    def reset_quality_items(self, widget, label, allocated_data, index):
        self.quality_combo_box.add_items(self.get_quality_items(label),
                                         clear_first=True)
        self.quality_combo_box.set_select_index(self.get_quality_index(label))
        self.quality_combo_box.queue_draw()

    def get_output_location(self, song):
        ext = FORMATS[self.format_combo_box.get_current_item()[0]]["extension"]
        if song.get_type() == "audiocd":
            filename = "%s.%s" % (song.get("title"), ext)
        else:
            filename = "%s.%s" % (song.get_filename(), ext)
        return os.path.join(self.output_entry.get_text(), filename)

    def add_and_close(self, widget):
        trans_data = {}
        if self.songs:
            for song in self.songs:
                if not song.exists():
                    continue
                trans_data["format"] = self.format_combo_box.get_current_item(
                )[0]
                trans_data[
                    "quality"] = self.quality_combo_box.get_current_item()[1]
                trans_data["song"] = song
                trans_data["output"] = self.get_output_location(song)
                trans_data["prompt"] = self.exists_combo_box.get_current_item(
                )[1]
                trans_data["to_playlist"] = self.add_check_button.get_active()
                Dispatcher.transfor_job(TranscoderJob(trans_data))
            self.destroy()
class BlueToothView(gtk.VBox):
    '''
    class docs
    '''
    def __init__(self, module_frame):
        '''
        init docs
        '''
        gtk.VBox.__init__(self)

        self.module_frame = module_frame

        self.my_bluetooth = MyBluetooth(self.__on_adapter_removed,
                                        self.__on_default_adapter_changed,
                                        self.__device_found)
        self.periodic_timer = None
        self.is_discoverable = False
        self.is_searching = False
        '''
        enable open
        '''
        if self.my_bluetooth.adapter:
            self.my_bluetooth.adapter.connect("property-changed",
                                              self.__on_property_changed)
            if self.my_bluetooth.adapter.get_powered():
                self.title_align, self.title_label = self.__setup_title_align(
                    app_theme.get_pixbuf("bluetooth/enable_open.png"),
                    _("Bluetooth"))
                self.title_label.set_sensitive(True)
            else:
                self.title_align, self.title_label = self.__setup_title_align(
                    app_theme.get_pixbuf("bluetooth/enable_open_disable.png"),
                    _("Bluetooth"))
        else:
            self.title_align, self.title_label = self.__setup_title_align(
                app_theme.get_pixbuf("bluetooth/enable_open_disable.png"),
                _("Bluetooth"))
            self.title_label.set_sensitive(False)
        self.enable_align = self.__setup_align()
        self.enable_box = gtk.HBox(spacing=WIDGET_SPACING)
        self.enable_open_label = self.__setup_label(_("Enable bluetooth"))
        if self.my_bluetooth.adapter:
            self.my_bluetooth.adapter.set_powered(
                permanent_settings.get_powered())
            self.enable_open_label.set_sensitive(
                self.my_bluetooth.adapter.get_powered())
        else:
            self.enable_open_label.set_sensitive(False)
        self.enable_open_toggle_align = self.__setup_align(padding_top=4,
                                                           padding_left=158)
        self.enable_open_toggle = self.__setup_toggle()
        if self.my_bluetooth.adapter:
            self.enable_open_toggle.set_active(
                self.my_bluetooth.adapter.get_powered())
        self.enable_open_toggle.connect("toggled", self.__toggled,
                                        "enable_open")
        self.enable_open_toggle_align.add(self.enable_open_toggle)
        self.__widget_pack_start(
            self.enable_box,
            [self.enable_open_label, self.enable_open_toggle_align])
        self.enable_align.add(self.enable_box)
        '''
        display
        '''
        self.display_align = self.__setup_align()
        self.display_box = gtk.HBox(spacing=WIDGET_SPACING)
        self.display_device_label = self.__setup_label(_("Device name"))
        if self.my_bluetooth.adapter:
            self.display_device_label.set_sensitive(
                self.my_bluetooth.adapter.get_powered())
        else:
            self.display_device_label.set_sensitive(False)
        self.display_device_entry = InputEntry()
        if self.my_bluetooth.adapter:
            self.display_device_entry.set_text(
                self.my_bluetooth.adapter.get_name())
            self.display_device_entry.set_sensitive(
                self.my_bluetooth.adapter.get_powered())
        else:
            self.display_device_entry.set_sensitive(False)
        self.display_device_entry.set_size(HSCALEBAR_WIDTH, WIDGET_HEIGHT)
        self.display_device_entry.entry.connect("changed",
                                                self.__display_device_changed)
        self.__widget_pack_start(
            self.display_box,
            [self.display_device_label, self.display_device_entry])
        self.display_align.add(self.display_box)
        '''
        enable searchable
        '''
        self.search_align = self.__setup_align()
        self.search_box = gtk.HBox(spacing=WIDGET_SPACING)
        self.search_label = self.__setup_label(_("Discoverable"))
        if self.my_bluetooth.adapter:
            self.search_label.set_sensitive(
                self.my_bluetooth.adapter.get_powered())
        else:
            self.search_label.set_sensitive(False)
        self.search_timeout_align = self.__setup_align(padding_top=0,
                                                       padding_left=0)
        self.search_timeout_label = self.__setup_label("",
                                                       width=110,
                                                       align=ALIGN_START)
        self.search_timeout_align.add(self.search_timeout_label)
        self.search_toggle_align = self.__setup_align(padding_top=4,
                                                      padding_left=18)
        self.search_toggle = self.__setup_toggle()
        if self.my_bluetooth.adapter:
            self.search_toggle.set_active(
                self.my_bluetooth.adapter.get_discoverable())
        self.search_toggle.connect("toggled", self.__toggled, "search")
        self.search_toggle_align.add(self.search_toggle)
        self.__widget_pack_start(self.search_box, [
            self.search_label, self.search_timeout_align,
            self.search_toggle_align
        ])
        self.search_align.add(self.search_box)
        '''
        device iconview
        '''
        self.device_align = self.__setup_align()
        self.device_iconview = DeviceIconView()
        self.device_iconview.set_size_request(690, 228)
        self.device_align.add(self.device_iconview)
        '''
        operation
        '''
        self.oper_align = self.__setup_align()
        self.oper_box = gtk.HBox(spacing=WIDGET_SPACING)
        self.notice_label = Label("",
                                  text_x_align=ALIGN_START,
                                  label_width=610)
        self.search_button = Button(_("Search"))
        if self.my_bluetooth.adapter:
            self.search_button.set_sensitive(
                self.my_bluetooth.adapter.get_powered())
        else:
            self.search_button.set_sensitive(False)
        self.search_button.connect("clicked", self.__on_search)
        self.__widget_pack_start(self.oper_box, [
            self.notice_label,
            self.search_button,
        ])
        self.oper_align.add(self.oper_box)
        '''
        this->gtk.VBox pack_start
        '''
        self.__widget_pack_start(self, [
            self.title_align, self.enable_align, self.display_align,
            self.search_align, self.device_align, self.oper_align
        ])

        if self.my_bluetooth.adapter == None:
            self.set_sensitive(False)

        self.connect("expose-event", self.__expose)

        if self.my_bluetooth.adapter and self.my_bluetooth.adapter.get_powered(
        ):
            self.__get_devices()

    def __on_property_changed(self, adapter, key, value):
        if key == "Powered":
            if value == 1:
                self.enable_open_toggle.set_active(True)
                # removed by hualet, this will cause devices are added twice.
                # self.__set_enable_open(True)
            else:
                self.enable_open_toggle.set_active(False)
                # self.__set_enable_open(False)
        if key == "Devices":  # fixbug: iconview didn't update accordingly
            # while adapter paired other devices in system tray.
            self.device_iconview.clear()
            self.__get_devices()

    def sendfile(self, device_name):
        event_manager.emit("send-file", device_name)

    def cancel(self):
        event_manager.emit("cancel", None)

    def __on_adapter_removed(self):
        self.set_sensitive(False)

    def __on_default_adapter_changed(self):
        self.set_sensitive(True)
        self.display_device_entry.set_text(
            self.my_bluetooth.adapter.get_name())

    def __display_device_changed(self, widget, event):
        self.my_bluetooth.adapter.set_name(widget.get_text())

    def __setup_separator(self):
        hseparator = HSeparator(
            app_theme.get_shadow_color("hSeparator").get_color_info(), 0, 0)
        hseparator.set_size_request(500, HSEPARATOR_HEIGHT)
        return hseparator

    def __setup_title_label(
            self,
            text="",
            text_color=app_theme.get_color("globalTitleForeground"),
            text_size=TITLE_FONT_SIZE,
            text_x_align=ALIGN_START,
            label_width=180):
        return Label(text=text,
                     text_color=text_color,
                     text_size=text_size,
                     text_x_align=text_x_align,
                     label_width=label_width,
                     enable_select=False,
                     enable_double_click=False)

    def __setup_title_align(self,
                            pixbuf,
                            text,
                            padding_top=TEXT_WINDOW_TOP_PADDING,
                            padding_left=TEXT_WINDOW_LEFT_PADDING):
        align = self.__setup_align(padding_top=padding_top,
                                   padding_left=padding_left)
        align_box = gtk.VBox(spacing=WIDGET_SPACING)
        title_box = gtk.HBox(spacing=WIDGET_SPACING)
        image = ImageBox(pixbuf)
        label = self.__setup_title_label(text)
        separator = self.__setup_separator()
        self.__widget_pack_start(title_box, [image, label])
        self.__widget_pack_start(align_box, [title_box, separator])
        align.add(align_box)
        return align, label

    def __get_devices(self):
        devices = self.my_bluetooth.get_devices()
        items = []
        i = 0

        while i < len(devices):
            items.append(
                DeviceItem(
                    devices[i].get_name(),
                    app_theme.get_pixbuf(
                        "bluetooth/%s.png" % bluetooth_class_to_type(
                            devices[i].get_class())).get_pixbuf(), devices[i],
                    self.my_bluetooth.adapter, devices[i].get_paired(),
                    self.module_frame))
            i += 1

        self.device_iconview.add_items(items)

    def __refresh_notice_label(self):
        searching_str = _("Discovering device")

        if self.notice_label.get_text().count(".") == 3:
            self.notice_label.set_text(searching_str + ".")
        else:
            self.notice_label.set_text(self.notice_label.get_text() + ".")

        return True

    def __on_search(self, widget):
        if not self.is_searching:
            self.my_bluetooth.adapter.start_discovery()
            self.notice_label.set_text(_("Discovering device"))
            self.refresh_lable_timeout = gobject.timeout_add_seconds(
                1, self.__refresh_notice_label)
            self.my_bluetooth.adapter.connect("property-changed",
                                              self.on_adapter_property_changed)
            self.is_searching = True

    def on_adapter_property_changed(self, obj, key, value):
        if key == "Discovering" and value == False:
            gobject.source_remove(self.refresh_lable_timeout)
            if self.is_searching:
                self.my_bluetooth.adapter.stop_discovery()
            self.is_searching = False
            self.notice_label.set_text("")

    def __device_found(self, adapter, address, values):
        print "address", address
        if address not in adapter.get_address_records():
            device_path = adapter.create_device(address)
            if device_path == "None":
                return

            device = Device(device_path)
            items = []

            if not values.has_key("Name"):
                return

            print bluetooth_class_to_type(device.get_class())
            items.append(
                DeviceItem(
                    values['Name'],
                    app_theme.get_pixbuf(
                        "bluetooth/%s.png" % bluetooth_class_to_type(
                            device.get_class())).get_pixbuf(), device,
                    adapter))
            self.device_iconview.add_items(items)

    def __set_enable_open(self, is_open=True):
        self.enable_open_label.set_sensitive(is_open)
        self.display_device_label.set_sensitive(is_open)
        self.search_label.set_sensitive(is_open)
        self.display_align.set_sensitive(is_open)
        self.display_device_entry.set_sensitive(is_open)
        # self.device_iconview.set_sensitive(is_open)
        self.search_align.set_sensitive(is_open)
        self.search_timeout_label.set_child_visible(False)
        self.search_button.set_sensitive(is_open)
        # changed by hualet, to fix the bug that device icons stay while disabling the iconview widget
        if is_open:
            self.__get_devices()
        else:
            self.device_iconview.clear()

    def __toggled(self, widget, object):
        if self.my_bluetooth.adapter == None:
            return

        if object == "enable_open":
            self.__set_enable_open(widget.get_active())
            permanent_settings.set_powered(widget.get_active())
            self.my_bluetooth.adapter.set_powered(widget.get_active())
            return

        if object == "search":
            self.is_discoverable = widget.get_active()
            self.my_bluetooth.adapter.set_discoverable(self.is_discoverable)
            self.search_timeout_label.set_child_visible(self.is_discoverable)
            if self.is_discoverable:
                self.periodic_timer = PerodicTimer(self, 1)
            else:
                self.periodic_timer.stop()
            return

    def __expose(self, widget, event):
        cr = widget.window.cairo_create()
        rect = widget.allocation

        cr.set_source_rgb(*color_hex_to_cairo(MODULE_BG_COLOR))
        cr.rectangle(rect.x, rect.y, rect.width, rect.height)
        cr.fill()

    def __setup_label(self, text="", width=180, align=ALIGN_END):
        return Label(text, None, TITLE_FONT_SIZE, align, width, False, False,
                     False)

    def __setup_combo(self, items=[], width=HSCALEBAR_WIDTH):
        combo = ComboBox(items, None, 0, width, width)
        combo.set_size_request(width, WIDGET_HEIGHT)
        return combo

    def __setup_toggle(self):
        return ToggleButton(
            app_theme.get_pixbuf("toggle_button/inactive_normal.png"),
            app_theme.get_pixbuf("toggle_button/active_normal.png"),
            inactive_disable_dpixbuf=app_theme.get_pixbuf(
                "toggle_button/inactive_normal.png"),
            active_disable_dpixbuf=app_theme.get_pixbuf(
                "toggle_button/inactive_normal.png"))

    def __setup_align(self,
                      xalign=0,
                      yalign=0,
                      xscale=0,
                      yscale=0,
                      padding_top=BETWEEN_SPACING,
                      padding_bottom=0,
                      padding_left=TEXT_WINDOW_LEFT_PADDING,
                      padding_right=20):
        align = gtk.Alignment()
        align.set(xalign, yalign, xscale, yscale)
        align.set_padding(padding_top, padding_bottom, padding_left,
                          padding_right)
        return align

    def __widget_pack_start(self,
                            parent_widget,
                            widgets=[],
                            expand=False,
                            fill=False):
        if parent_widget == None:
            return
        for item in widgets:
            parent_widget.pack_start(item, expand, fill)
class GeneralSetting(gtk.VBox):
    
    def __init__(self):
        super(GeneralSetting, self).__init__()
        self.set_spacing(TABLE_ROW_SPACING)
        self.pack_start(self.create_start_box(), False, True)
        self.pack_start(self.create_close_box(), False, True)
        self.pack_start(self.create_play_box(), False, True)
        self.pack_start(self.create_lyrics_dir_table(), False, False)
        
        # Load.
        self.load_status()
        
        # Signals.
        self.splash_check_button.connect("toggled", self.update_splash_status)
        self.open_lyrics_check_button.connect("toggled", self.update_lyrics_status)
        self.auto_play_check_button.connect("toggled", self.update_auto_play_status)
        self.resume_last_check_button.connect("toggled", self.update_resume_status)
        self.tray_radio_button.connect("toggled", self.update_close_to_tray_status)
        self.fade_check_button.connect("toggled", self.update_fade_status)
        self.album_check_button.connect("toggled", self.update_album_status)
        self.fade_spin.connect("value-changed", self.update_fade_time_status)
        
    def load_status(self):    
        self.splash_check_button.set_active(config.getboolean("setting", "use_splash"))
        self.open_lyrics_check_button.set_active(config.getboolean("lyrics", "status"))
        self.auto_play_check_button.set_active(config.getboolean("player", "play_on_startup"))
        self.resume_last_check_button.set_active(config.getboolean("player", "resume_last_progress"))
        
        close_to_tray = config.getboolean("setting", "close_to_tray")
        if close_to_tray:
            self.tray_radio_button.set_active(True)
        else:    
            self.quit_radio_button.set_active(True)
        
        self.fade_check_button.set_active(config.getboolean("player", "crossfade"))
        self.album_check_button.set_active(config.getboolean("player", "crossfade_gapless_album"))
        
        new_value = int(float(config.get("player", "crossfade_time")) * 100)
        self.fade_spin.set_value(new_value)
        
    def update_splash_status(self, widget):    
        if widget.get_active():
            config.set("setting", "use_splash", "true")
        else:    
            config.set("setting", "use_splash", "false")
            
    def update_lyrics_status(self, widget):        
        if widget.get_active():    
            config.set("lyrics", "status", "true")
        else:    
            config.set("lyrics", "status", "false")
            
    def update_auto_play_status(self, widget):       
        if widget.get_active():    
            config.set("player", "play_on_startup", "true")            
        else:    
            config.set("player", "play_on_startup", "false")
            
    def update_resume_status(self, widget):        
        if widget.get_active():
            config.set("player", "resume_last_progress", "true")
        else:    
            config.set("player", "resume_last_progress", "false")
            
    def update_close_to_tray_status(self, widget):        
        if widget.get_active():   
            config.set("setting", "close_to_tray", "true")
        else:    
            config.set("setting", "close_to_tray", "false")
            
    def update_fade_status(self, widget):        
        if widget.get_active():
            config.set("player", "crossfade", "true")
            self.fade_spin.set_sensitive(True)
        else:    
            config.set("player", "crossfade", "false")
            self.fade_spin.set_sensitive(False)
            
    def update_album_status(self, widget):        
        if self.album_check_button.get_active():    
            config.set("player", "crossfade_gapless_album", "true")
        else:    
            config.set("player", "crossfade_gapless_album", "false")
            
    def update_fade_time_status(self, widget, value):        
        new_value = value / 100.0
        config.set("player", "crossfade_time", str(new_value))        
            
    def create_start_box(self):    
        main_table = gtk.Table(4, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        start_title_label = Label(_("On starting the player"))
        start_title_label.set_size_request(350, 12)
        label_align = gtk.Alignment()
        label_align.set_padding(20, 0, 0, 0)
        label_align.add(start_title_label)
        
        # splash check_button
        self.splash_check_button = CheckButton(_("Display splash-screen"))
        splash_hbox = gtk.HBox()
        splash_hbox.pack_start(self.splash_check_button, False, False)
        splash_hbox.pack_start(create_right_align(), True, True)        
        
        # open_lyrics_check_button.
        open_lyrics_hbox = gtk.HBox()
        self.open_lyrics_check_button = CheckButton(_("Show lyrics"))
        open_lyrics_hbox.pack_start(self.open_lyrics_check_button, False, False)

        
        # startup_check_button.
        self.auto_play_check_button = CheckButton(_("Start playback automatically"))
        auto_play_hbox = gtk.HBox()
        auto_play_hbox.pack_start(self.auto_play_check_button, False, False)
        auto_play_hbox.pack_start(create_right_align(), True, True)                
        
        # resume last check_button.
        self.resume_last_check_button = CheckButton(_("Resume playback"))
        resume_hbox = gtk.HBox()
        resume_hbox.pack_start(self.resume_last_check_button, False, False)
        
        main_table.attach(label_align, 0, 2, 0, 1, yoptions=gtk.FILL, xpadding=8)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, gtk.FILL)
        #main_table.attach(splash_hbox, 0, 1, 2, 3)
        main_table.attach(open_lyrics_hbox, 0, 1, 2, 3)
        main_table.attach(auto_play_hbox, 1, 2, 2, 3, yoptions=gtk.EXPAND)
        main_table.attach(resume_hbox, 0, 1, 3, 4)
        return main_table
    
    def create_close_box(self):
        main_table = gtk.Table(3, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        close_title_label = Label(_("When pressing the close button"))
        close_title_label.set_size_request(350, 12)
        
        # mini_check_button

        self.tray_radio_button = RadioButton(_("Minimize to tray"))
        self.quit_radio_button = RadioButton(_("Quit"))
        
        main_table.attach(close_title_label, 0, 2, 0, 1, yoptions=gtk.FILL, xpadding=8)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(self.tray_radio_button, 0, 1, 2, 3, yoptions=gtk.FILL)
        main_table.attach(self.quit_radio_button, 1, 2, 2, 3)
        
        return main_table
    
    def create_play_box(self):
        main_table = gtk.Table(5, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        
        play_title_label = Label(_("Playback settings"))
        play_title_label.set_size_request(350, 12)
        
        fade_check_hbox = gtk.HBox()
        self.fade_check_button = CheckButton(_("Enable crossfade"))        
        fade_check_hbox.pack_start(self.fade_check_button, False, False)
        fade_check_hbox.pack_start(create_right_align(), True, True)
        self.album_check_button = CheckButton(_("Seamless switching between the same album"))
        album_check_hbox = gtk.HBox()
        album_check_hbox.pack_start(self.album_check_button, False, False)
        album_check_hbox.pack_start(create_right_align(), True, True)
        
        fade_label = Label("%s" % _("Crossfade"))
        self.fade_spin = SpinBox(200, 0, 900, 100)
        millisecond_lablel = Label(_(" ms"))        
        millisecond_lablel.set_size_request(50, 12)
        spin_hbox = gtk.HBox(spacing=3)
        spin_hbox.pack_start(fade_label, False, False)
        spin_hbox.pack_start(self.fade_spin, False, False)
        spin_hbox.pack_start(millisecond_lablel, False, False)
        
        main_table.attach(play_title_label, 0, 2, 0, 1, yoptions=gtk.FILL, xpadding=8)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(fade_check_hbox, 0, 2, 2, 3, yoptions=gtk.FILL)
        main_table.attach(album_check_hbox, 0, 2, 3, 4, yoptions=gtk.FILL)
        main_table.attach(spin_hbox, 0, 1, 4, 5, yoptions=gtk.FILL, xpadding=8)
        return main_table

    def create_lyrics_dir_table(self):    
        main_table = gtk.Table(3, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        
        dir_title_label = Label(_("Lyrics directory"))
        dir_title_label.set_size_request(200, 12)
        label_align = gtk.Alignment()
        label_align.set_padding(0, 0, 0, 0)
        label_align.add(dir_title_label)
        
        self.dir_entry = InputEntry()
        self.dir_entry.set_text(os.path.expanduser(config.get("lyrics", "save_lrc_path", "~/.lyrics")))
        self.dir_entry.set_editable(False)        
        self.dir_entry.set_size(250, 25)
        
        modify_button = Button(_("Change"))
        modify_button.connect("clicked", self.change_lyrics_save_dir)
        hbox = gtk.HBox(spacing=5)
        hbox.pack_start(self.dir_entry, False, False)
        hbox.pack_start(modify_button, False, False)
        
        main_table.attach(label_align, 0, 2, 0, 1, yoptions=gtk.FILL, xpadding=8)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(hbox, 0, 2, 2, 3, xpadding=10, xoptions=gtk.FILL)
        return main_table
    
    def change_lyrics_save_dir(self, widget):
        local_dir = WinDir(False).run()
        if local_dir:
            config.set("lyrics", "save_lrc_path", local_dir)
            self.dir_entry.set_editable(True)        
            self.dir_entry.set_text(os.path.expanduser(local_dir))
            self.dir_entry.set_editable(False)
class AttributesUI(DialogBox):
    
    def __init__(self, songs=None):
        DialogBox.__init__(self, _("Converter"), 385, 200, DIALOG_MASK_SINGLE_PAGE,
                           modal=True)
        
        self.songs = songs or [Player.song]
        default_format = "MP3 (CBR)"
        default_index = FORMATS.keys().index(default_format)
        format_box, self.format_combo_box = self.create_combo_widget(_("Format"),
                                                                [(key, None) for key in FORMATS.keys()],
                                                                default_index)
        quality_box, self.quality_combo_box = self.create_combo_widget(_("Quality"),
                                                                       self.get_quality_items(default_format),
                                                                       self.get_quality_index(default_format),
                                                                       65)
        format_quality_box = gtk.HBox(spacing=68)
        format_quality_box.pack_start(format_box, False, False)
        format_quality_box.pack_start(quality_box, False, False)
        
        exists_box, self.exists_combo_box = self.create_combo_widget(_("Target file already exists"),
                                                                [(_("Ask"), True), (_("Cover"), False)],
                                                                0)
        
        start_button = Button(_("Start"))
        close_button = Button(_("Close"))
        self.add_check_button = CheckButton(_("Add to Playlist after finished"), padding_x=2)
        
        main_table = gtk.Table()
        main_table.set_row_spacings(10)
        main_table.attach(format_quality_box, 0, 2, 0, 1, yoptions=gtk.FILL)
        main_table.attach(set_widget_left(exists_box), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(self.create_output_box(), 0, 2, 2, 3, yoptions=gtk.FILL)
        main_table.attach(set_widget_left(self.add_check_button), 0, 2, 3, 4, yoptions=gtk.FILL)
        
        main_align = gtk.Alignment()
        main_align.set_padding(10, 10, 15, 10)
        main_align.add(main_table)
        
        # Connect signals.
        self.format_combo_box.connect("item-selected", self.reset_quality_items)
        start_button.connect("clicked", self.add_and_close)
        close_button.connect("clicked", lambda w: self.destroy())
        
        self.body_box.pack_start(main_align, False, True)
        self.right_button_box.set_buttons([start_button, close_button])
        
    def create_output_box(self):
        output_label = Label("%s:" % _("Output"))
        self.output_entry = InputEntry(os.path.expanduser("~/"))
        self.output_entry.set_size(210, 24)
        change_button = Button(_("Change"))
        change_button.connect("clicked", self.set_output_directory)
        output_box = gtk.HBox(spacing=5)
        output_box.pack_start(output_label, False, False)
        output_box.pack_start(self.output_entry, False, False)
        output_box.pack_start(change_button, False, False)
        return output_box
    
    def set_output_directory(self, widget): 
        directory = WinDir(False).run()
        if directory:
            self.output_entry.set_text(directory)
        
    def get_quality_items(self, name):    
        kbs_steps = [str(key) for key in FORMATS[name]["kbs_steps"]]
        return zip(kbs_steps, FORMATS[name]["raw_steps"])
    
    def get_quality_index(self, name):
        return FORMATS[name]["default_index"]
        
    def create_combo_widget(self, label_content, items, select_index=0, max_width=None):    
        label = Label("%s:" % label_content)
        combo_box = ComboBox(items, select_index=select_index, max_width=max_width)
        
        hbox = gtk.HBox(spacing=5)
        hbox.pack_start(label, False, False)
        hbox.pack_start(combo_box, False, False)
        return hbox, combo_box
    
    def reset_quality_items(self, widget, label, allocated_data, index):
        self.quality_combo_box.add_items(self.get_quality_items(label), clear_first=True)
        self.quality_combo_box.set_select_index(self.get_quality_index(label))
        self.quality_combo_box.queue_draw()
        
    def get_output_location(self, song):    
        ext = FORMATS[self.format_combo_box.get_current_item()[0]]["extension"]        
        if song.get_type() == "audiocd":
            filename = "%s.%s" % (song.get("title"), ext)
        else:
            filename = "%s.%s" % (song.get_filename(), ext)
        return os.path.join(self.output_entry.get_text(), filename)
    
    def add_and_close(self, widget):
        trans_data = {}
        if self.songs:
            for song in self.songs:
                if not song.exists():
                    continue
                trans_data["format"] = self.format_combo_box.get_current_item()[0]
                trans_data["quality"] = self.quality_combo_box.get_current_item()[1]
                trans_data["song"] = song
                trans_data["output"] = self.get_output_location(song)
                trans_data["prompt"] = self.exists_combo_box.get_current_item()[1]
                trans_data["to_playlist"] = self.add_check_button.get_active()
                Dispatcher.transfor_job(TranscoderJob(trans_data))
            self.destroy()
class SongInfo(gtk.VBox):
    def __init__(self, song=None):
        super(SongInfo, self).__init__()
        self.set_spacing(10)
        block_box = gtk.EventBox()
        block_box.set_visible_window(False)
        block_box.set_size_request(-1, 10)
        self.detail_table = gtk.Table(5, 4)
        self.detail_table.set_row_spacings(5)
        self.create_detail_box()
        self.pack_start(block_box, False, True)
        self.pack_start(self.create_simpler_box(), False, True)
        self.pack_start(create_separator_box(), False, True)
        self.pack_start(self.detail_table, False, True)
        self.pack_start(create_separator_box(), False, True)
        self.pack_start(self.create_location_box(), False, True)
        
        # update_song.
        if song:
            self.update_song(song)
            
    def create_simpler_box(self):    
        simpler_box = gtk.HBox(spacing=30)
        cover_image_align = gtk.Alignment()
        cover_image_align.set_padding(0, 0, 50, 0)
        self.cover_image = gtk.Image()
        self.cover_image.set_size_request(92, 92)
        cover_image_align.add(self.cover_image)
        
        content_box_align = gtk.Alignment()
        content_box_align.set_padding(20, 0, 0, 0)
        content_box = gtk.VBox(spacing=5)
        title_box, self.title_label = self.create_combo_label(_("Title:"))
        artist_box, self.artist_label = self.create_combo_label(_("Artist:"))
        album_box, self.album_label  = self.create_combo_label(_("Album:"))        
        content_box_align.add(content_box)
        
        content_box.pack_start(title_box, False, False)        
        content_box.pack_start(artist_box, False, False)
        content_box.pack_start(album_box, False, False)        

        simpler_box.pack_start(cover_image_align, False, False)
        simpler_box.pack_start(content_box_align, False, False)

        return simpler_box

    def create_combo_label(self, title, content=""):   
        hbox = gtk.HBox(spacing=5)
        title_label  = Label(title)
        content_label = Label(content)
        content_label.set_size_request(200, -1)
        hbox.pack_start(title_label, False, False)
        hbox.pack_start(content_label, False, False)
        return hbox, content_label
    
    def create_detail_box(self):
        self.file_type_label, self.file_format_label = self.create_double_combo_label(0, 1, _("Type:"), _("Format:"))
        self.file_size_label, self.song_duration_label = self.create_double_combo_label(1, 2, _("Size:"), _("Duration:"))
        self.song_bitrate_label, self.song_rate_label = self.create_double_combo_label(2, 3, _("Bitrate:"), _("Rate:"))
        self.song_added_label, self.song_lasted_label = self.create_double_combo_label(3, 4, _("Added:"), _("Recently:"))
        self.song_playcount_label, self.song_date_label = self.create_double_combo_label(4, 5, _("Playcount:"), _("Date:"))
        
    def get_song_attr(self, song, song_type=True):    
        gio_file = gio.File(self.song.get_path())
        gio_file_info = gio_file.query_info(",".join([gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
                                                      gio.FILE_ATTRIBUTE_STANDARD_TYPE, 
                                                      gio.FILE_ATTRIBUTE_STANDARD_NAME,
                                                      gio.FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
                                                      gio.FILE_ATTRIBUTE_STANDARD_SIZE,
                                                      gio.FILE_ATTRIBUTE_STANDARD_ICON,
                                                      gio.FILE_ATTRIBUTE_TIME_MODIFIED,
                                                      gio.FILE_ATTRIBUTE_TIME_CHANGED,]))
        
        info_attr = gio_file_info.get_attribute_as_string(gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE)                
        
        if song_type:
            return gio.content_type_get_description(info_attr)
        else:
            return info_attr
        
    def create_double_combo_label(self, top_attach, bottom_attach, first_label, second_label, first_content="", second_content=""):
        first_label_box = gtk.HBox()
        first_title_label = Label(first_label)
        first_label_box.pack_start(create_right_align(), True, True)        
        first_label_box.pack_start(first_title_label, False, False)
        first_content_label = Label(first_content)
        
        second_label_box = gtk.HBox()
        second_title_label = Label(second_label)
        second_label_box.pack_start(create_right_align(), True, True)
        second_label_box.pack_start(second_title_label, False, False)
        second_content_label = Label(second_content)
        
        self.detail_table.attach(first_label_box, 0, 1, top_attach, bottom_attach)
        self.detail_table.attach(first_content_label, 1, 2, top_attach, bottom_attach, xpadding=5)
        self.detail_table.attach(second_label_box, 2, 3, top_attach, bottom_attach, xpadding=5)
        self.detail_table.attach(second_content_label, 3, 4, top_attach, bottom_attach)
        
        return first_content_label, second_content_label
    
    def create_location_box(self):
        location_align = gtk.Alignment()
        location_align.set(1.0, 1.0, 0.5, 0.5)
        location_box = gtk.HBox(spacing=5)
        location_label = Label(_("Location:"))
        self.location_entry = InputEntry("")
        self.location_entry.set_size(250, 25)
        open_button = Button(_("Open directory"))
        open_button.connect("clicked", self.open_song_location)
        location_box.pack_start(location_label, False, True)
        location_box.pack_start(self.location_entry, False, True)
        location_box.pack_start(open_button, False, True)
        location_align.add(location_box)
        return location_align
    
    def open_song_location(self, widget):
        utils.open_file_directory(self.song.get_path())
    
    def update_song(self, song):
        self.song = song
        
        # Update simpler.
        self.cover_image.set_from_pixbuf(CoverManager.get_pixbuf_from_song(song, 92, 92, False, False))
        self.title_label.set_text(song.get_str("title"))
        self.artist_label.set_text(song.get_str("artist"))
        self.album_label.set_text(song.get_str("album"))
        
        # Update detail.
        self.file_type_label.set_text(self.get_song_attr(song, True))
        self.file_format_label.set_text(self.get_song_attr(song, False))        
        self.file_size_label.set_text(song.get_str("#size"))
        self.song_duration_label.set_text(song.get_str("#duration"))        
        self.song_bitrate_label.set_text(song.get_str("#bitrate"))
        self.song_rate_label.set_text(song.get_str("#rate"))        
        self.song_added_label.set_text(song.get_str("#added"))
        self.song_lasted_label.set_text(song.get_str("#lastplayed"))
        self.song_playcount_label.set_text(song.get_str("#playcount"))
        self.song_date_label.set_text(song.get_str("#date"))        
        
        # Update location.
        self.location_entry.set_text(song.get_path())
class HotspotBox(gtk.HBox):
    '''docstring for HotspotBox'''
    DISCONNECT = 0
    CONNECTING = 1
    ACTIVE = 2
    def __init__(self, action_btn_click_cb):
        super(HotspotBox, self).__init__()
        self.action_btn_click = action_btn_click_cb
        self.set_size_request(-1, 30)
        self.connect("expose-event", self.expose_background)

        self.__init_ui()
    
    def __init_ui(self):
        #self.check_bar = Imag\cceBox(app_theme.get_pixbuf("network/check_box-2.png"))
        self.ssid_label = Label(_("SSID:"))
        self.ssid_entry = InputEntry("Deepin.org")
        self.ssid_entry.entry.set_size_request(200 ,22)

        self.password_label = Label(_("Password:"******"")
        self.password_entry.entry.set_size_request(200 ,22)

        self.active_btn = Button(_("Active"))
        self.jump_bar = ImageButton(app_theme.get_pixbuf("network/jump_to.png"),
                app_theme.get_pixbuf("network/jump_to.png"),
                app_theme.get_pixbuf("network/jump_to.png"))
                                    
        self.check_bar_align = gtk.Alignment(0, 0, 0, 0)
        self.check_bar_align.set_size_request(36, 30)
        self.check_bar_align.connect("expose-event", self.expose_state)
        #check_bar_align = self.__wrap_align(self.check_bar, (0, 0, 10, 10))
        ssid_label_align = self.__wrap_align(self.ssid_label, (0, 0, 0, 10))
        self.ssid_entry_align = self.__wrap_align(self.ssid_entry)
        password_label_align = self.__wrap_align(self.password_label, (0, 0, 20, 10))
        self.password_entry_align = self.__wrap_align(self.password_entry)
        
        self.active_align = gtk.Alignment(1, 0.5, 0, 0)
        self.active_align.set_padding(0, 0, 0, 10)
        self.active_align.add(self.active_btn)

        self.__pack_begin(self, [self.check_bar_align, ssid_label_align, 
                               self.ssid_entry_align, password_label_align,
                               self.password_entry_align
                               ])
        self.ssid_entry_align.set_size_request(200, 30)
        self.password_entry_align.set_size_request(200, 30)
        self.pack_end(self.active_align, False, True)
        self.show_all()

        self.active_btn.connect("clicked", self.active_btn_callback)
        #self.password_entry.expose_input_entry = self.expose_input_entry
        self.check_out_pixbuf = app_theme.get_pixbuf('network/check_box_out.png')
        self.loading_pixbuf = app_theme.get_pixbuf('network/loading.png')
        self.check_pixbuf = app_theme.get_pixbuf('network/check_box-2.png')
        #self.check_bar = ImageBox(app_theme.get_pixbuf("network/"+pixbufs[state]))

        self.position = 1
        self.net_state = 0

    def active_btn_callback(self, widget):
        if self.action_btn_click():
            self.__active_action(False)
            self.set_net_state(1)

    def expose_state(self, widget, event):
        cr = widget.window.cairo_create()
        rect = widget.allocation

        if self.net_state == 1:
            self.draw_loading(cr, rect)
        elif self.net_state == 2:
            draw_pixbuf(cr, self.check_pixbuf.get_pixbuf(), rect.x + 10, rect.y + 7)


    def draw_loading(self, cr, rect):
        with cairo_state(cr):
            cr.translate(rect.x + rect.width*0.5 , rect.y + rect.height * 0.5)
            cr.rotate(radians(60*self.position))
            cr.translate(-rect.width* 0.5, -rect.height * 0.5)
            draw_pixbuf(cr, self.loading_pixbuf.get_pixbuf(), 10, 7)

    def expose_background(self, widget, event):
        cr = widget.window.cairo_create()
        rect = widget.allocation
        with cairo_disable_antialias(cr):
            cr.set_source_rgb(*BG_COLOR)
            cr.rectangle(rect.x, rect.y, rect.width, rect.height)
            cr.fill()

            cr.set_source_rgb(*BORDER_COLOR)
            cr.set_line_width(1)
            cr.rectangle(rect.x, rect.y , rect.width, rect.height)
            cr.stroke()

    def __pack_begin(self, parent, widget_list, expand=False, fill=False):
        for w in widget_list:
            parent.pack_start(w, expand, fill)

    def __wrap_align(self, widget, padding=(0, 0, 0, 0)):
        align = gtk.Alignment(0, 0.5, 0, 0)
        align.set_padding(*padding)
        align.add(widget)
        return align

    def __active_action(self, state):
        container_remove_all(self.ssid_entry_align)
        container_remove_all(self.password_entry_align)
        container_remove_all(self.active_align)
        if state == False:
            label1 = Label(self.ssid_entry.get_text())
            label2 = Label(self.password_entry.get_text())
            label1.connect("button-press-event", lambda w, e: self.__active_action(True))
            label2.connect("button-press-event", lambda w, e: self.__active_action(True))

            self.ssid_entry_align.add(label1)
            self.password_entry_align.add(label2)
            self.show_all()
        else:
            self.ssid_entry_align.add(self.ssid_entry)
            self.password_entry_align.add(self.password_entry)
            self.active_align.add(self.active_btn)

    def set_active(self, state):
        self.__active_action(state)

    def get_ssid(self):
        return self.ssid_entry.get_text()

    def get_pwd(self):
        return self.password_entry.get_text()

    def set_ssid(self, text):
        self.ssid_entry.set_text(text)
        self.ssid_entry.queue_draw()

    def set_pwd(self, text):
        self.password_entry.set_text(text)
        self.password_entry.queue_draw()
    
    def set_net_state(self, state):
        self.net_state = state
        if self.net_state == 1:
            self.position = 0
            LoadingThread(self).start()
        self.check_bar_align.queue_draw()

    def get_net_state(self):
        return self.net_state

    def refresh_loading(self, position):
        self.position = position
        self.check_bar_align.queue_draw()
Beispiel #26
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()
Beispiel #27
0
class GeneralBox(BaseBox):
    def __init__(self):
        BaseBox.__init__(self)

        self.main_box.pack_start(self.create_uninstall_box(), False, True)
        self.main_box.pack_start(self.create_download_dir_table(), False, True)

    def create_uninstall_box(self):
        main_table = gtk.Table(2, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)
        uninstall_title_label = Label(_("On uninstalling the software"))

        # mini_check_button
        self.delete_check_button = CheckButton(_("Delete configuration files"))
        self.delete_check_button.set_active(get_purg_flag())
        self.delete_check_button.connect("toggled", lambda w: set_purge_flag(self.delete_check_button.get_active()))

        main_table.attach(uninstall_title_label, 0, 2, 0, 1, yoptions=gtk.FILL)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(self.delete_check_button, 0, 1, 2, 3, yoptions=gtk.FILL)

        return main_table

    def create_download_dir_table(self):
        main_table = gtk.Table(4, 2)
        main_table.set_row_spacings(CONTENT_ROW_SPACING)

        dir_title_label = Label(_("Download settings"))
        dir_title_label.set_size_request(200, 12)
        label_align = gtk.Alignment()
        label_align.set_padding(0, 0, 0, 0)
        label_align.add(dir_title_label)

        download_number_label = Label(_('Maximum number of download tasks: '))
        self.download_number_comobox = ComboBox(
                items = [(str(i+1), i+1) for i in range(10)],
                select_index = int(get_download_number())-1,
                )
        self.download_number_comobox.connect("item-selected", self.download_number_comobox_changed)
        download_number_hbox = gtk.HBox(spacing=5)
        download_number_hbox.pack_start(download_number_label, False, False)
        download_number_hbox.pack_start(self.download_number_comobox, False, False)

        change_download_dir_label = Label(_("Download directory: "))
        self.dir_entry = InputEntry()
        self.dir_entry.set_text(get_software_download_dir())
        self.dir_entry.set_editable(False)
        self.dir_entry.set_size(200, 25)

        modify_button = Button(_("Change"))
        modify_button.connect("clicked", self.change_download_save_dir)
        download_dir_hbox = gtk.HBox(spacing=5)
        download_dir_hbox.pack_start(change_download_dir_label, False, False)
        download_dir_hbox.pack_start(self.dir_entry, False, False)
        download_dir_hbox.pack_start(modify_button, False, False)

        main_table.attach(label_align, 0, 2, 0, 1, yoptions=gtk.FILL)
        main_table.attach(create_separator_box(), 0, 2, 1, 2, yoptions=gtk.FILL)
        main_table.attach(download_number_hbox, 0, 2, 2, 3, xoptions=gtk.FILL)
        main_table.attach(download_dir_hbox, 0, 2, 3, 4, xoptions=gtk.FILL)
        return main_table

    def download_number_comobox_changed(self, widget, name, value, index):
        set_download_number(value)
        global_event.emit('max-download-number-changed', value)

    def change_download_save_dir(self, widget):
        local_dir = FolderChooseDialog(False).run()
        if local_dir:
            local_dir = os.path.expanduser(local_dir)
            if local_dir != get_software_download_dir():
                self.dir_entry.set_editable(True)
                self.dir_entry.set_text(local_dir)
                self.dir_entry.set_editable(False)
                set_software_download_dir(local_dir)
                global_event.emit('download-directory-changed')