コード例 #1
0
 def plugin_widget(self):
     self.tray_icon.set_tooltip_text(
         "%s %s" % (time.strftime("%Y-%m-%d"),
                    self.WEEK[int(time.strftime("%w")) - 1]))
     align = self.__setup_align()
     box = gtk.VBox(spacing=5)
     calendar_align = self.__setup_align()
     calendar = deepin_lunar.new()
     self.calendar = deepin_lunar.new()
     if MAIN_LANG == "en_US":
         self.calendar = dltk_calendar.new()
     calendar.mark_day(time.localtime().tm_mday)
     calendar.set_day_padding(0)
     calendar.get_handle().set_property("show-details", False)
     if len(locale.getdefaultlocale([
             'LANGUAGE'
     ])) and locale.getdefaultlocale(['LANGUAGE'])[0] is not None:
         if locale.getdefaultlocale(['LANGUAGE'])[0].find("zh_CN") != 0:
             self.width = 230
     else:
         self.width = 230
     calendar.get_handle().set_size_request(self.width, 172)
     calendar_align.add(calendar.get_handle())
     select_align = self.__setup_align()
     select_button = SelectButton(_("Change date and time settings"),
                                  font_size=10,
                                  ali_padding=5)
     select_button.set_size_request(self.width, 25)
     select_align.add(select_button)
     select_button.connect("clicked", self.__on_day_selected)
     box.pack_start(calendar_align, False, False)
     box.pack_start(select_align, False, False)
     align.add(box)
     return align
コード例 #2
0
 def plugin_widget(self):
     self.tray_icon.set_tooltip_text("%s %s" % (time.strftime("%Y-%m-%d"),   
                                                self.WEEK[int(time.strftime("%w")) - 1]))
     align = self.__setup_align()
     box = gtk.VBox(spacing = 5)
     calendar_align = self.__setup_align()
     calendar = deepin_lunar.new()
     self.calendar = deepin_lunar.new()                                      
     if MAIN_LANG == "en_US":
         self.calendar = dltk_calendar.new()
     calendar.mark_day(time.localtime().tm_mday)
     calendar.set_day_padding(0)
     calendar.get_handle().set_property("show-details", False)
     if len(locale.getdefaultlocale(['LANGUAGE'])) and locale.getdefaultlocale(['LANGUAGE'])[0] is not None:
         if locale.getdefaultlocale(['LANGUAGE'])[0].find("zh_CN") != 0:
             self.width = 230
     else:
         self.width = 230
     calendar.get_handle().set_size_request(self.width, 172)
     calendar_align.add(calendar.get_handle())
     select_align = self.__setup_align()
     select_button = SelectButton(_("Change date and time settings"), 
                                  font_size = 10, 
                                  ali_padding = 5)
     select_button.set_size_request(self.width, 25)
     select_align.add(select_button)
     select_button.connect("clicked", self.__on_day_selected)
     box.pack_start(calendar_align, False, False)
     box.pack_start(select_align, False, False)
     align.add(box)
     return align
コード例 #3
0
    def plugin_widget(self):
        self.__get_devices()
        plugin_box = gtk.VBox()
        adapter_box = gtk.HBox(spacing=5)
        adapter_image = ImageBox(
            app_theme.get_pixbuf("bluetooth/enable_open.png"))
        adapter_label = self.__setup_label(_("Adapter"))
        adapter_toggle = self.__setup_toggle()
        if self.my_bluetooth.adapter:
            adapter_toggle.set_active(self.my_bluetooth.adapter.get_powered())
            if self.my_bluetooth.adapter.get_powered():
                self.tray_icon.set_icon_theme("enable")
            else:
                self.tray_icon.set_icon_theme("enable_disconnect")
        adapter_toggle.connect("toggled", self.__adapter_toggled)
        separator_align = self.__setup_align(padding_bottom=0)
        separator = self.__setup_separator()
        separator_align.add(separator)
        '''
        devices treeview
        '''
        device_treeview = TreeView()
        device_separator_align = self.__setup_align()
        device_separator = self.__setup_separator()
        device_separator_align.add(device_separator)
        device_count = len(self.device_items)
        if device_count:
            device_treeview.delete_all_items()
            device_treeview.add_items(self.device_items)
            device_treeview.set_size_request(
                self.width, device_count * DeviceItem.ITEM_HEIGHT)
        else:
            device_treeview.set_child_visible(False)
            device_separator_align.set_size_request(-1, 0)
            device_separator_align.set_child_visible(False)
        '''
        select button
        '''
        select_button_align = self.__setup_align()
        select_button = SelectButton(_("Advanced options..."),
                                     font_size=10,
                                     ali_padding=5)
        select_button.set_size_request(self.width, 25)
        select_button.connect(
            "clicked", self.__bluetooth_selected
        )  # I don't know why, but replacing "button-press-event" with
        select_button_align.add(select_button)  # clicked really works...

        adapter_box.pack_start(adapter_image, False, False)
        adapter_box.pack_start(adapter_label, False, False)
        adapter_box.pack_start(adapter_toggle, False, False)

        plugin_box.pack_start(adapter_box, False, False)
        plugin_box.pack_start(separator_align, False, False)
        plugin_box.pack_start(device_treeview, False, False)
        plugin_box.pack_start(device_separator_align, False, False)
        plugin_box.pack_start(select_button_align, False, False)

        return plugin_box
コード例 #4
0
    def plugin_widget(self):
        self.__get_devices()
        plugin_box = gtk.VBox()
        adapter_box = gtk.HBox(spacing = 5)
        adapter_image = ImageBox(app_theme.get_pixbuf("bluetooth/enable_open.png"))
        adapter_label = self.__setup_label(_("Adapter"))
        adapter_toggle = self.__setup_toggle()
        if self.my_bluetooth.adapter:
            adapter_toggle.set_active(self.my_bluetooth.adapter.get_powered())
            if self.my_bluetooth.adapter.get_powered():
                self.tray_icon.set_icon_theme("enable")
            else:
                self.tray_icon.set_icon_theme("enable_disconnect")
        adapter_toggle.connect("toggled", self.__adapter_toggled)
        separator_align = self.__setup_align(padding_bottom = 0)
        separator = self.__setup_separator()
        separator_align.add(separator)
        '''
        devices treeview
        '''
        device_treeview = TreeView()
        device_separator_align = self.__setup_align()
        device_separator = self.__setup_separator()
        device_separator_align.add(device_separator)
        device_count = len(self.device_items)
        if device_count:
            device_treeview.delete_all_items()
            device_treeview.add_items(self.device_items)
            device_treeview.set_size_request(self.width, device_count * DeviceItem.ITEM_HEIGHT)
        else:
            device_treeview.set_child_visible(False)
            device_separator_align.set_size_request(-1, 0)
            device_separator_align.set_child_visible(False)
        '''
        select button
        '''
        select_button_align = self.__setup_align()
        select_button = SelectButton(_("Advanced options..."),
                                     font_size = 10,
                                     ali_padding = 5)
        select_button.set_size_request(self.width, 25)
        select_button.connect("clicked", self.__bluetooth_selected) # I don't know why, but replacing "button-press-event" with 
        select_button_align.add(select_button)                      # clicked really works...

        adapter_box.pack_start(adapter_image, False, False)
        adapter_box.pack_start(adapter_label, False, False)
        adapter_box.pack_start(adapter_toggle, False, False)

        plugin_box.pack_start(adapter_box, False, False)
        plugin_box.pack_start(separator_align, False, False)
        plugin_box.pack_start(device_treeview, False, False)
        plugin_box.pack_start(device_separator_align, False, False)
        plugin_box.pack_start(select_button_align, False, False)

        return plugin_box
コード例 #5
0
class TrayGui(gtk.VBox):
    '''sound tray gui'''
    #BASE_HEIGHT = 128  # has microphone
    BASE_HEIGHT = 103   # no microphone

    __gsignals__ = {
        "stream-changed": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ())}

    def __init__(self, tray_obj=None):
        super(TrayGui, self).__init__(False)
        self.tray_obj = tray_obj

        self.stream_icon = app_theme.get_pixbuf("sound/device.png").get_pixbuf().scale_simple(16, 16, gtk.gdk.INTERP_TILES)
        self.stream_num = 0
        self.stream_list = {}    # stream widgets
        self.stream_process = {} # process id to stream widgets
        self.stream_mpris = {}   # stream id to mpris process id

        self.__mpris_total_height = 0
        self.mpris_base_height = 70
        self.mpris_list = {}     # mpris widgets
        self.mpris_stream = {}   # mpris process id to stream id
        self.mpris2 = Mpris2()
        self.mpris2.connect("new", self.mpris2_new_cb)
        self.mpris2.connect("removed", self.mpris2_removed_cb)
        self.mpris2.connect("changed", self.mpris2_changed_cb)

        self.__play_dingdong = Play(os.path.join(get_parent_dir(__file__, 1), 'dingdong.wav'))

        hbox = gtk.HBox(False)
        hbox.set_spacing(WIDGET_SPACING)
        #separator_color = [(0, ("#000000", 0.3)), (0.5, ("#000000", 0.2)), (1, ("#777777", 0.0))]
        #hseparator = HSeparator(app_theme.get_shadow_color("hSeparator").get_color_info(), 0, 0)
        #hseparator.set_size_request(150, 3)
        separator_color = [(0, ("#777777", 0.0)), (0.5, ("#000000", 0.3)), (1, ("#777777", 0.0))]
        hseparator = HSeparator(separator_color, 0, 0)
        hseparator.set_size_request(140, 5)
        #hbox.pack_start(self.__make_align(Label(_("Device"), enable_select=False, enable_double_click=False)), False, False)
        #hbox.pack_start(self.__make_align(hseparator), True, True)
        self.pack_start(self.__make_align(Label(_("Device"), enable_select=False, enable_double_click=False), height=-1), False, False)
        self.pack_start(self.__make_align(hseparator, xalign=0.5, height=5), False, False)

        volume_max_percent = pypulse.MAX_VOLUME_VALUE * 100 / pypulse.NORMAL_VOLUME_VALUE

        table = gtk.Table(2, 3)
        speaker_img = ImageBox(app_theme.get_pixbuf("sound/speaker-3.png"))
        self.speaker_scale = HScalebar(show_value=False, format_value="%", value_min=0, value_max=volume_max_percent)
        self.speaker_scale.set_magnetic_values([(0, 5), (100, 5), (volume_max_percent, 5)])
        self.speaker_scale.set_size_request(90, 10)
        self.speaker_mute_button = SwitchButton(
            inactive_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"), 
            active_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"))
        table.attach(self.__make_align(speaker_img), 0, 1, 0, 1, 4)
        table.attach(self.__make_align(self.speaker_scale, yalign=0.0, yscale=1.0, padding_left=5, padding_right=5, height=25), 1, 2, 0, 1, 4)
        table.attach(self.__make_align(self.speaker_mute_button), 2, 3, 0, 1, 4)

        #microphone_img = ImageBox(app_theme.get_pixbuf("sound/microphone.png"))
        #self.microphone_scale = HScalebar(show_value=False, format_value="%", value_min=0, value_max=volume_max_percent)
        #self.microphone_scale.set_size_request(90, 10)
        #self.microphone_mute_button = SwitchButton(
            #inactive_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"), 
            #active_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"))
        #table.attach(self.__make_align(microphone_img), 0, 1, 1, 2, 4)
        #table.attach(self.__make_align(self.microphone_scale, yalign=0.0, yscale=1.0, padding_left=5, padding_right=5, height=25), 1, 2, 1, 2, 4)
        #table.attach(self.__make_align(self.microphone_mute_button), 2, 3, 1, 2, 4)

        self.pack_start(table, False, False)

        self.__app_vbox = gtk.VBox(False)
        separator_color = [(0, ("#777777", 0.0)), (0.5, ("#000000", 0.3)), (1, ("#777777", 0.0))]
        hseparator = HSeparator(separator_color, 0, 0)
        hseparator.set_size_request(140, 5)
        self.__app_vbox.pack_start(self.__make_align(Label(_("Applications"), enable_select=False, enable_double_click=False)), False, False)
        self.__app_vbox.pack_start(self.__make_align(hseparator, xalign=0.5, height=5), False, False)

        self.__mpris_vbox = gtk.VBox(False)
        self.__app_vbox.pack_start(self.__mpris_vbox)
        self.pack_start(self.__app_vbox)

        hseparator = HSeparator(separator_color, 0, 0)
        hseparator.set_size_request(140, 7)
        self.pack_start(self.__make_align(hseparator, xalign=0.5, height=7), False, False)

        self.button_more = SelectButton(_("Advanced..."), font_size=10, ali_padding=5)
        self.button_more.set_size_request(-1, 25)
        self.pack_start(self.button_more, False, False)
        #self.pack_start(self.__make_align(height=10))
        ##########################################
        self.__fallback_sink_index = None
        self.__fallback_source_index = None
        state_cb_fun = {}
        state_cb_fun["server"] = self.__server_state_cb
        state_cb_fun["sink"] = self.__sink_state_cb
        #state_cb_fun["source"] = self.__source_state_cb
        state_cb_fun["sinkinput"] = self.__sinkinput_state_cb
        pypulse.PULSE.connect_to_pulse(state_cb_fun)
        self.__set_output_status()
        #self.__set_input_status()

        # widget signals
        self.speaker_mute_button.connect("toggled", self.speaker_toggled)
        #self.microphone_mute_button.connect("toggled", self.microphone_toggled)
        self.speaker_scale.connect("value-changed", self.speaker_scale_value_changed)
        self.speaker_scale.connect("button-release-event", lambda w, e: self.__play_dingdong.play())
        #self.microphone_scale.connect("value-changed", self.microphone_scale_value_changed)
        # pulseaudio signals
        pypulse.PULSE.connect("sink-removed", self.sink_removed_cb)
        #pypulse.PULSE.connect("source-removed", self.source_removed_cb)
        pypulse.PULSE.connect("sinkinput-removed", self.sinkinput_removed_cb)

        self.mpris2.get_mpris_list()
        self.mpris_num = len(self.mpris2.mpris_process.keys())
        if self.mpris_num == 0:
            self.__app_vbox.set_no_show_all(True)

    def __make_align(self, widget=None, xalign=0.0, yalign=0.5, xscale=0.0,
                     yscale=0.0, padding_top=0, padding_bottom=0, padding_left=0,
                     padding_right=0, width=-1, height=25):
        align = gtk.Alignment()
        align.set_size_request(width, height)
        align.set(xalign, yalign, xscale, yscale)
        align.set_padding(padding_top, padding_bottom, padding_left, padding_right)
        if widget:
            align.add(widget)
        return align

    def __make_playback_box(self, stream, index):
        process_id = int(stream['proplist']['application.process.id'])
        if process_id == os.getpid():
            return
        # if it has show mpris, then don't show sink_input
        if process_id in self.mpris_list:
            self.mpris_stream[process_id] = index
            self.stream_mpris[index] = process_id
            return
        icon_name, is_filtered = self.__white_list_check(stream, index)
        if is_filtered:
            return
        self.stream_list[index] = {}
        volume_max_percent = pypulse.MAX_VOLUME_VALUE * 100 / pypulse.NORMAL_VOLUME_VALUE
        if icon_name:
            if icon_name[0] == '/':
                try:
                    img = gtk.image_new_from_pixbuf(gtk.gdk.pixbuf_new_from_file(
                        icon_name).scale_simple(16, 16, gtk.gdk.INTERP_TILES))
                except:
                    img = gtk.image_new_from_pixbuf(self.stream_icon)
            else:
                image_pixbuf = self.__get_pixbuf_from_icon_name(icon_name)
                if image_pixbuf:
                    img = gtk.image_new_from_pixbuf(image_pixbuf)
                else:
                    img = gtk.image_new_from_pixbuf(self.stream_icon)
                    #img = gtk.image_new_from_icon_name(icon_name, gtk.ICON_SIZE_MENU)
        else:
            img = gtk.image_new_from_pixbuf(self.stream_icon)
        img.set_size_request(16, 16)
        scale = HScalebar(show_value=False, format_value="%", value_min=0, value_max=volume_max_percent)
        scale.set_magnetic_values([(0, 5), (100, 5), (volume_max_percent, 5)])
        scale.set_size_request(90, 10)
        mute_button = SwitchButton(
            inactive_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"), 
            active_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"))
        hbox = gtk.HBox()
        hbox.pack_start(self.__make_align(img), False, False)
        hbox.pack_start(self.__make_align(scale, yalign=0.0, yscale=1.0, padding_left=5, padding_right=5, height=25), False, False)
        hbox.pack_start(self.__make_align(mute_button), False, False)
        self.stream_list[index]['scale'] = scale
        self.stream_list[index]['button'] = mute_button
        self.stream_list[index]['container'] = hbox
        self.stream_list[index]['process_id'] = process_id
        self.stream_list[index]['stream_id'] = index
        self.stream_process[process_id] = self.stream_list[index]
        self.__set_playback_status(stream, scale, mute_button)
        if stream['volume_writable']:
            scale.connect("value-changed", self.playback_stream_scale_changed_cb, index, mute_button)
            mute_button.connect("toggled", self.playback_stream_toggled_cb, index, scale)
        hbox.show_all()
        self.__app_vbox.pack_start(hbox, False, False)

    def __white_list_check(self, stream, index):
        icon_name = None
        # check deepin-game-center
        if 'application.process.binary' in stream['proplist'] and \
                stream['proplist']['application.process.binary'].startswith('python'):
            process_id = int(stream['proplist']['application.process.id'])
            stream_process_obj = psutil.Process(process_id)
            if len(stream_process_obj.cmdline) > 1 and \
                    'deepin-game-center' in stream_process_obj.cmdline[1]:
                return "deepin-game-center", False
        # check deepin-media-player
        if 'application.process.binary' in stream['proplist'] and \
                stream['proplist']['application.process.binary'] == 'mplayer':
            process_id = int(stream['proplist']['application.process.id'])
            stream_process_obj = psutil.Process(process_id)
            stream_process_parent_obj = stream_process_obj.parent
            if stream_process_parent_obj.pid != 0 and \
                    stream_process_parent_obj.name.startswith("deepin-media"):
                children_process = stream_process_parent_obj.get_children()
                # check this process is the preview window of deepin-media-player
                if process_id != children_process[0].pid:
                    return None, True
                # check deepin-media-player whether enable mpris
                if stream_process_parent_obj.pid in self.mpris_list:
                    self.mpris_stream[stream_process_parent_obj.pid] = index
                    self.stream_mpris[index] = stream_process_parent_obj.pid
                    return None, True
                return "deepin-media-player", False
        if 'application.icon_name' in stream['proplist']:
            icon_name = stream['proplist']['application.icon_name']
        # check deepin-music-player
        if 'application.name' in stream['proplist']:
            if stream['proplist']['application.name'] == 'deepin-music-player':
                icon_name = "deepin-music-player"
        return icon_name, False

    def __get_pixbuf_from_icon_name(self, name, size=16):
        screen = self.get_screen()
        icon_theme = gtk.icon_theme_get_for_screen(screen)
        icon_info = icon_theme.lookup_icon(name, size, 0)
        if not icon_info:
            return None
        filename = icon_info.get_filename()
        if not filename or not os.path.exists(filename):
            return None
        pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
        if icon_info.get_base_size() != size:
            pixbuf = pixbuf.scale_simple(size, size, gtk.gdk.INTERP_TILES)
        return pixbuf

    ####################################################
    # widget signals
    def speaker_value_changed_thread(self):
        ''' speaker hscale value changed callback thread'''
        if not self.speaker_mute_button.get_active():
            self.speaker_mute_button.set_active(True)
        current_sink = self.__fallback_sink_index
        if current_sink is None:
            return
        volume_list = pypulse.output_volumes[current_sink]
        channel_list = pypulse.output_channels[current_sink]
        if not volume_list or not channel_list:
            return
        balance = pypulse.get_volume_balance(channel_list['channels'],
                                             volume_list, channel_list['map'])
        volume = int((self.speaker_scale.get_value()) / 100.0 * pypulse.NORMAL_VOLUME_VALUE)
        pypulse.PULSE.set_output_volume_with_balance(current_sink, volume, balance, channel_list['channels'], channel_list['map'])

    def speaker_scale_value_changed(self, widget, value):
        '''set output volume'''
        self.speaker_value_changed_thread()

    def microphone_value_changed_thread(self):
        ''' microphone value changed callback thread'''
        if not self.microphone_mute_button.get_active():
            self.microphone_mute_button.set_active(True)
        current_source = self.__fallback_source_index
        if current_source is None:
            return
        channel_list = pypulse.input_channels[current_source]
        if not channel_list:
            return

        volume = int((self.microphone_scale.get_value()) / 100.0 * pypulse.NORMAL_VOLUME_VALUE)
        pypulse.PULSE.set_input_volume(current_source, [volume] * channel_list['channels'], channel_list['channels'])

    def microphone_scale_value_changed(self, widget, value):
        ''' set input volume'''
        self.microphone_value_changed_thread()

    def speaker_toggled(self, button):
        active = button.get_active()
        current_sink = self.__fallback_sink_index
        self.speaker_scale.set_enable(active)
        if current_sink is not None:
            pypulse.PULSE.set_output_mute(current_sink, not active)

    def microphone_toggled(self, button):
        active = button.get_active()
        current_source = self.__fallback_source_index
        self.microphone_scale.set_enable(active)
        if current_source is not None:
            pypulse.PULSE.set_input_mute(current_source, not active)

    def playback_stream_scale_changed_cb(self, widget, value, index, button):
        if not button.get_active():
            button.set_active(True)
        volume = int((widget.get_value()) / 100.0 * pypulse.NORMAL_VOLUME_VALUE)
        pypulse.PULSE.set_sink_input_volume(index, [volume] * widget.volume_channels, widget.volume_channels)

    def playback_stream_toggled_cb(self, button, index, scale):
        active = button.get_active()
        scale.set_enable(active)
        pypulse.PULSE.set_sink_input_mute(index, not active)

    # pulseaudio signals callback
    def __sink_state_cb(self, obj, channel, port, volume, sink, idx):
        pypulse.output_channels[idx] = channel
        pypulse.output_active_ports[idx] = port
        pypulse.output_volumes[idx] = volume
        pypulse.output_devices[idx] = sink
        if self.__fallback_sink_index is None and pypulse.get_fallback_sink_name() == sink['name']:
            self.__fallback_sink_index = idx
        if self.__fallback_sink_index == idx:
            self.__set_output_status()

    # update tray_icon
    def update_tray_icon(self):
        if self.tray_obj:
            current_sink = self.__fallback_sink_index
            sinks = pypulse.output_devices
            sink_volume = pypulse.output_volumes
            tip_text = "%s %d%%" % (_("Volume"), round(self.speaker_scale.get_value()))
            if current_sink in sinks and current_sink in sink_volume:
                is_mute = sinks[current_sink]['mute']
                if is_mute:
                    tip_text = _("Mute")
                volume = max(sink_volume[current_sink]) * 100.0 / pypulse.NORMAL_VOLUME_VALUE
                if volume == 0:
                    volume_level = 0
                elif 0 < volume <= 40:
                    volume_level = 1
                elif 40 < volume <= 80:
                    volume_level = 2
                else:
                    volume_level = 3
                self.tray_obj.set_tray_icon(volume_level, is_mute)
            if self.tray_obj.tray_obj:
                self.tray_obj.tray_obj.set_tooltip_text(tip_text)

    def __source_state_cb(self, obj, channel, port, volume, source, idx):
        pypulse.input_channels[idx] = channel
        pypulse.input_active_ports[idx] = port
        pypulse.input_volumes[idx] = volume
        pypulse.input_devices[idx] = source
        if self.__fallback_source_index is None and pypulse.get_fallback_source_name() == source['name']:
            self.__fallback_source_index = idx
        if self.__fallback_source_index == idx:
            self.__set_input_status()

    def __server_state_cb(self, obj, dt):
        pypulse.server_info = dt
        self.__fallback_sink_index = pypulse.get_fallback_sink_index()
        if self.__fallback_sink_index in pypulse.output_volumes:
            self.__set_output_status()
        self.__fallback_source_index = pypulse.get_fallback_source_index()
        if self.__fallback_source_index in pypulse.input_volumes:
            self.__set_input_status()

    def __sinkinput_state_cb(self, obj, dt, index):
        if index in self.stream_mpris:
            return
        process_id = int(dt['proplist']['application.process.id'])
        if process_id == os.getpid():
            return
        if index not in self.stream_list:
            self.__make_playback_box(dt, index)
            stream_num = len(self.stream_list.keys())
            mpris_num = len(self.mpris_list.keys())
            if stream_num > 0 or mpris_num > 0:
                self.__app_vbox.set_no_show_all(False)
                self.__app_vbox.show_all()
            self.adjust_size()
            self.emit("stream-changed")
        else:
            self.__set_playback_status(dt,
                                       self.stream_list[index]['scale'],
                                       self.stream_list[index]['button'])
        pypulse.playback_info[index] = dt

    def sinkinput_removed_cb(self, obj, index):
        if index in self.stream_mpris:
            if self.stream_mpris[index] in self.mpris_stream:
                del self.mpris_stream[self.stream_mpris[index]]
            del self.stream_mpris[index]
        if index in pypulse.playback_info:
            del pypulse.playback_info[index]
        if index in self.stream_list:
            process_id = self.stream_list[index]['process_id']
            if process_id in self.stream_process:
                del self.stream_process[process_id]
            self.stream_list[index]['container'].destroy()
            del self.stream_list[index]
            self.stream_num -= 1
            stream_num = len(self.stream_list.keys())
            mpris_num = len(self.mpris_list.keys())
            if stream_num == 0 and mpris_num == 0:
                self.__app_vbox.hide_all()
                self.__app_vbox.set_no_show_all(True)
            self.adjust_size()
            self.emit("stream-changed")

    def sink_removed_cb(self, obj, index):
        if index in pypulse.output_devices:
            del pypulse.output_devices[index]
        if index in pypulse.output_channels:
            del pypulse.output_channels[index]
        if index in pypulse.output_active_ports:
            del pypulse.output_active_ports[index]
        if index in pypulse.output_volumes:
            del pypulse.output_volumes[index]

    def source_removed_cb(self, obj, index):
        if index in pypulse.input_devices:
            del pypulse.input_devices[index]
        if index in pypulse.input_channels:
            del pypulse.input_channels[index]
        if index in pypulse.input_active_ports:
            del pypulse.input_active_ports[index]
        if index in pypulse.input_volumes:
            del pypulse.input_volumes[index]

    def __set_output_status(self):
        # if sinks list is empty, then can't set output volume
        current_sink = self.__fallback_sink_index
        sinks = pypulse.output_devices
        if current_sink is None:
            self.speaker_scale.set_sensitive(False)
            self.speaker_mute_button.set_sensitive(False)
            self.speaker_scale.set_enable(False)
            self.speaker_mute_button.set_active(False)
        # set output volume
        else:
            self.speaker_scale.set_sensitive(True)
            self.speaker_mute_button.set_sensitive(True)
            is_mute = sinks[current_sink]['mute']
            self.speaker_mute_button.set_active(not is_mute)
            self.speaker_scale.set_enable(not is_mute)
            volume = max(pypulse.output_volumes[current_sink])
            self.speaker_scale.set_value(volume * 100.0 / pypulse.NORMAL_VOLUME_VALUE)
        self.update_tray_icon()

    def __set_input_status(self):
        # if sources list is empty, then can't set input volume
        current_source = self.__fallback_source_index
        sources = pypulse.input_devices
        if current_source is None:
            self.microphone_scale.set_sensitive(False)
            self.microphone_mute_button.set_sensitive(False)
            self.microphone_scale.set_enable(False)
            self.microphone_mute_button.set_active(False)
        # set input volume
        else:
            self.microphone_scale.set_sensitive(True)
            self.microphone_mute_button.set_sensitive(True)
            is_mute = sources[current_source]['mute']
            self.microphone_mute_button.set_active(not is_mute)
            self.microphone_scale.set_enable(not is_mute)
            volume = max(pypulse.input_volumes[current_source])
            self.microphone_scale.set_value(volume * 100.0 / pypulse.NORMAL_VOLUME_VALUE)
    
    def __set_playback_status(self, stream, scale, button):
        if not stream['has_volume']:
            scale.set_sensitive(False)
            button.set_sensitive(False)
            scale.set_enable(False)
            button.set_active(False)
        else:
            scale.set_sensitive(True)
            button.set_sensitive(True)
            is_mute = stream['mute']
            button.set_active(not is_mute)
            scale.set_enable(not is_mute)
            volume = max(stream['volume'])
            scale.set_value(volume * 100.0 / pypulse.NORMAL_VOLUME_VALUE)
            scale.volume_channels = len(stream['volume'])

    # mpris dbus signal
    def mpris2_new_cb(self, obj, pid):
        vbox = gtk.VBox()
        image_pixbuf = self.__get_pixbuf_from_icon_name(
            obj.mpris_process[pid]['property']['DesktopEntry'])
        logo_pixbuf = self.__get_pixbuf_from_icon_name(
            obj.mpris_process[pid]['property']['DesktopEntry'], 32)
        if image_pixbuf:
            img = gtk.image_new_from_pixbuf(image_pixbuf)
        else:
            img = gtk.image_new_from_pixbuf(self.stream_icon)
        img.set_size_request(16, 16)
        # application title
        app_title = obj.mpris_process[pid]['property']['Identity']
        #if obj.mpris_process[pid]['property']['PlaybackStatus'] == 'Stopped':
            #app_title = obj.mpris_process[pid]['property']['Identity']
        #else:
            #app_title = "%s - %s" % (obj.mpris_process[pid]['property']['Identity'], _(obj.mpris_process[pid]['property']['PlaybackStatus']))
        label = Label(app_title, label_width=115)
        hbox = gtk.HBox(False, 5)
        hbox.pack_start(self.__make_align(img), False, False)
        hbox.pack_start(self.__make_align(label), False, False)
        vbox.pack_start(hbox, False, False)

        # metadata info
        meta_box = gtk.HBox(False, 10)
        xesam_vbox = gtk.VBox(False)
        #art_img = gtk.Image()
        art_img = gtk.EventBox()
        art_img.set_size_request(40, 40)
        art_img.connect("expose-event", self.__draw_mpris_art_img)

        xesam_title = Label("", label_width=75)
        xesam_artist = Label("", label_width=75)
        xesam_album = Label("", label_width=75)
        xesam_vbox.pack_start(xesam_title)
        xesam_vbox.pack_start(xesam_artist)
        #xesam_vbox.pack_start(xesam_album)
        meta_box.pack_start(self.__make_align(art_img, padding_left=21, height=40), False, False)
        meta_box.pack_start(xesam_vbox)

        self.mpris_list[pid] = {}
        # mpris control
        scale = HScalebar(app_theme.get_pixbuf("sound/point.png"), show_value=False, format_value="%", value_min=0, value_max=1, line_height=3)
        scale.set_magnetic_values([(0, 0.1), (1, 0.1)])
        scale.set_size_request(70, 10)
        prev_bt = gtk.Button()
        pause_bt = gtk.Button()
        stop_bt = gtk.Button()
        next_bt = gtk.Button()

        prev_bt.set_size_request(20, 22)
        pause_bt.set_size_request(29, 30)
        #stop_bt.set_size_request(16, 16)
        next_bt.set_size_request(20, 22)

        prev_bt.pixbuf = "previous"
        if obj.mpris_process[pid]['property']['PlaybackStatus'] == 'Playing':
            pause_bt.pixbuf = "pause"
        else:
            pause_bt.pixbuf = "play"
        #stop_bt.pixbuf = self.stop_img
        next_bt.pixbuf = "next"

        scale.set_value(obj.mpris_process[pid]['property']['Volume'])

        prev_bt.connect("clicked", self.__mpris_prev_cb, obj, pid)
        pause_bt.connect("clicked", self.__mpris_pause_cb, obj, pid)
        #stop_bt.connect("clicked", self.__mpris_stop_cb, obj, pid)
        next_bt.connect("clicked", self.__mpris_next_cb, obj, pid)
        prev_bt.connect("expose-event", self.__draw_mpris_button_cb)
        pause_bt.connect("expose-event", self.__draw_mpris_button_cb)
        stop_bt.connect("expose-event", self.__draw_mpris_button_cb)
        next_bt.connect("expose-event", self.__draw_mpris_button_cb)
        scale.connect("value-changed", self.__mpris_volume_cb, obj, pid)

        hbox = gtk.HBox()
        hbox.pack_start(self.__make_align(prev_bt, height=-1), False, False)
        hbox.pack_start(self.__make_align(pause_bt, height=-1), False, False)
        #hbox.pack_start(self.__make_align(stop_bt, height=-1), False, False)
        hbox.pack_start(self.__make_align(next_bt, height=-1), False, False)
        hbox.pack_start(self.__make_align(scale, yalign=0.0, yscale=1.0, height=-1), False, False)
        vbox.pack_start(self.__make_align(hbox, xalign=0.5, padding_top=5, padding_bottom=10, height=-1), False, False)

        self.mpris_list[pid]['app_title'] = label
        self.mpris_list[pid]['prev'] = prev_bt
        self.mpris_list[pid]['pause'] = pause_bt
        self.mpris_list[pid]['stop'] = stop_bt
        self.mpris_list[pid]['next'] = next_bt
        self.mpris_list[pid]['scale'] = scale
        self.mpris_list[pid]['meta'] = meta_box
        self.mpris_list[pid]['meta_img'] = art_img
        self.mpris_list[pid]['meta_title'] = xesam_title
        self.mpris_list[pid]['meta_artist'] = xesam_artist
        self.mpris_list[pid]['meta_album'] = xesam_album
        self.mpris_list[pid]['container'] = vbox
        self.mpris_list[pid]['logo'] = logo_pixbuf
        if not obj.mpris_process[pid]['property']['Metadata']:
            self.mpris_list[pid]['height'] = self.mpris_base_height
        else:
            vbox.pack_start(meta_box, False, False)
            vbox.reorder_child(meta_box, 1)
            self.__set_mpris_meta_info(pid)
            self.mpris_list[pid]['height'] = self.mpris_base_height + 40
        self.__mpris_total_height += self.mpris_list[pid]['height']
        # delete playback_stream widget
        if pid in self.stream_process:
            self.stream_process[pid]['container'].destroy()
            del self.stream_list[self.stream_process[pid]['stream_id']]
            del self.stream_process[pid]
        vbox.show_all()
        self.__mpris_vbox.pack_start(vbox, False, False)

        stream_num = len(self.stream_list.keys())
        mpris_num = len(self.mpris_list.keys())
        if stream_num > 0 or mpris_num > 0:
            self.__app_vbox.set_no_show_all(False)
            self.__app_vbox.show_all()
        self.adjust_size()
        self.emit("stream-changed")

    def __draw_mpris_art_img(self, widget, event):
        x, y, w, h = widget.allocation
        cr = widget.window.cairo_create()
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) 
        surface_cr = gtk.gdk.CairoContext(cairo.Context(surface))
        surface_cr.set_source_rgba(0, 0, 0, 1.0)
        surface_cr.rectangle(5, 5, w-10, h-10)
        surface_cr.stroke()

        dtk_cairo_blur.gaussian_blur(surface, 3)
        cr.set_source_surface(surface, 0, 0)
        cr.paint()

        cr.set_source_rgb(1, 1, 1)
        cr.rectangle(2, 2, w-4, h-4)
        cr.fill()

        if widget.pixbuf:
            cr.set_source_pixbuf(widget.pixbuf, 4, 4)
            cr.paint()
        return True

    def __set_mpris_meta_info(self, pid):
        if 'mpris:artUrl' in self.mpris2.mpris_process[pid]['property']['Metadata']:
            arturl = urlparse(self.mpris2.mpris_process[pid]['property']['Metadata']['mpris:artUrl'])
            if arturl.scheme == 'file' and os.path.exists(arturl.path):
                art_pixbuf = gtk.gdk.pixbuf_new_from_file(arturl.path).scale_simple(32, 32, gtk.gdk.INTERP_TILES)
                #self.mpris_list[pid]['meta_img'].set_from_pixbuf(art_pixbuf)
                self.mpris_list[pid]['meta_img'].pixbuf = art_pixbuf
        else:
            self.mpris_list[pid]['meta_img'].pixbuf = self.mpris_list[pid]['logo']
        self.mpris_list[pid]['meta_img'].queue_draw()
        if 'xesam:title' in self.mpris2.mpris_process[pid]['property']['Metadata']:
            self.mpris_list[pid]['meta_title'].set_text(
                markup_escape_text(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:title']))
        else:
            self.mpris_list[pid]['meta_title'].set_text("-")
        if 'xesam:artist' in self.mpris2.mpris_process[pid]['property']['Metadata']:
            self.mpris_list[pid]['meta_artist'].set_text(
                markup_escape_text('&'.join(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:artist'])))
        else:
            self.mpris_list[pid]['meta_artist'].set_text("-")
        if 'xesam:album' in self.mpris2.mpris_process[pid]['property']['Metadata']:
            self.mpris_list[pid]['meta_album'].set_text(
                markup_escape_text(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:album']))
        else:
            self.mpris_list[pid]['meta_album'].set_text("-")
        
    def mpris2_removed_cb(self, obj, pid):
        if pid in self.mpris_list:
            self.mpris_list[pid]['container'].destroy()
            self.mpris_list[pid]['meta'].destroy()
            self.__mpris_total_height -= self.mpris_list[pid]['height']
            del self.mpris_list[pid]
        if pid in self.mpris_stream:
            stream_id = self.mpris_stream[pid]
            if stream_id in pypulse.playback_info:
                self.__make_playback_box(pypulse.playback_info[stream_id], stream_id)
        stream_num = len(self.stream_list.keys())
        mpris_num = len(self.mpris_list.keys())
        if stream_num == 0 and mpris_num == 0:
            self.__app_vbox.hide_all()
            self.__app_vbox.set_no_show_all(True)
        self.adjust_size()
        self.emit("stream-changed")

    def mpris2_changed_cb(self, obj, pid, changed):
        #print "mpris changed", pid, changed
        if pid not in self.mpris_list:
            return
        if 'Volume' in changed:
            self.mpris_list[pid]['scale'].set_value(changed['Volume'])
        if 'PlaybackStatus' in changed:
            # application title && hide meta info
            if changed['PlaybackStatus'] == 'Stopped':
                if self.mpris_list[pid]['meta'] in self.mpris_list[pid]['container'].get_children():
                    self.mpris_list[pid]['container'].remove(self.mpris_list[pid]['meta'])
                    self.__mpris_total_height -= self.mpris_list[pid]['height']
                    self.mpris_list[pid]['height'] = self.mpris_base_height
                    self.__mpris_total_height += self.mpris_list[pid]['height']
                    self.adjust_size()
                    self.emit("stream-changed")
            # button image
            if changed['PlaybackStatus'] == 'Playing':
                self.mpris_list[pid]['pause'].pixbuf = "pause"
            else:
                self.mpris_list[pid]['pause'].pixbuf = "play"
            self.mpris_list[pid]['pause'].queue_draw()
        if 'Metadata' in changed and obj.mpris_process[pid]['property']['PlaybackStatus'] != 'Stopped':
            self.__set_mpris_meta_info(pid)
            if self.mpris_list[pid]['meta'] not in self.mpris_list[pid]['container'].get_children():
                self.mpris_list[pid]['container'].pack_start(self.mpris_list[pid]['meta'], False, False)
                self.mpris_list[pid]['container'].reorder_child(self.mpris_list[pid]['meta'], 1)
                self.mpris_list[pid]['container'].show_all()
                self.__mpris_total_height -= self.mpris_list[pid]['height']
                self.mpris_list[pid]['height'] = self.mpris_base_height + 40
                self.__mpris_total_height += self.mpris_list[pid]['height']
                self.adjust_size()
                self.emit("stream-changed")

    def __mpris_prev_cb(self, bt, obj, pid):
        if pid not in obj.mpris_process:
            return
        try:
            obj.mpris_process[pid]['obj'].get_dbus_method(
                'Previous', 'org.mpris.MediaPlayer2.Player')()
        except Exception, e:
            if e._dbus_error_name == "org.freedesktop.DBus.Error.ServiceUnknown":
                self.mpris2_removed_cb(obj, pid)
コード例 #6
0
class TrayGui(gtk.VBox):
    '''sound tray gui'''
    #BASE_HEIGHT = 128  # has microphone
    BASE_HEIGHT = 103   # no microphone

    __gsignals__ = {
        "stream-changed": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ())}

    def __init__(self, tray_obj=None):
        super(TrayGui, self).__init__(False)
        self.tray_obj = tray_obj

        self.stream_icon = app_theme.get_pixbuf("sound/device.png").get_pixbuf().scale_simple(16, 16, gtk.gdk.INTERP_TILES)
        self.stream_num = 0
        self.stream_list = {}    # stream widgets
        self.stream_process = {} # process id to stream widgets
        self.stream_mpris = {}   # stream id to mpris process id

        self.__mpris_total_height = 0
        self.mpris_base_height = 70
        self.mpris_list = {}     # mpris widgets
        self.mpris_stream = {}   # mpris process id to stream id
        self.mpris2 = Mpris2()
        self.mpris2.connect("new", self.mpris2_new_cb)
        self.mpris2.connect("removed", self.mpris2_removed_cb)
        self.mpris2.connect("changed", self.mpris2_changed_cb)

        hbox = gtk.HBox(False)
        hbox.set_spacing(WIDGET_SPACING)
        #separator_color = [(0, ("#000000", 0.3)), (0.5, ("#000000", 0.2)), (1, ("#777777", 0.0))]
        #hseparator = HSeparator(app_theme.get_shadow_color("hSeparator").get_color_info(), 0, 0)
        #hseparator.set_size_request(150, 3)
        separator_color = [(0, ("#777777", 0.0)), (0.5, ("#000000", 0.3)), (1, ("#777777", 0.0))]
        hseparator = HSeparator(separator_color, 0, 0)
        hseparator.set_size_request(140, 5)
        #hbox.pack_start(self.__make_align(Label(_("Device"), enable_select=False, enable_double_click=False)), False, False)
        #hbox.pack_start(self.__make_align(hseparator), True, True)
        self.pack_start(self.__make_align(Label(_("Device"), enable_select=False, enable_double_click=False), height=-1), False, False)
        self.pack_start(self.__make_align(hseparator, xalign=0.5, height=5), False, False)

        volume_max_percent = pypulse.MAX_VOLUME_VALUE * 100 / pypulse.NORMAL_VOLUME_VALUE

        table = gtk.Table(2, 3)
        speaker_img = ImageBox(app_theme.get_pixbuf("sound/speaker-3.png"))
        self.speaker_scale = HScalebar(show_value=False, format_value="%", value_min=0, value_max=volume_max_percent)
        self.speaker_scale.set_magnetic_values([(0, 5), (100, 5), (volume_max_percent, 5)])
        self.speaker_scale.set_size_request(90, 10)
        self.speaker_mute_button = SwitchButton(
            inactive_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"), 
            active_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"))
        table.attach(self.__make_align(speaker_img), 0, 1, 0, 1, 4)
        table.attach(self.__make_align(self.speaker_scale, yalign=0.0, yscale=1.0, padding_left=5, padding_right=5, height=25), 1, 2, 0, 1, 4)
        table.attach(self.__make_align(self.speaker_mute_button), 2, 3, 0, 1, 4)

        #microphone_img = ImageBox(app_theme.get_pixbuf("sound/microphone.png"))
        #self.microphone_scale = HScalebar(show_value=False, format_value="%", value_min=0, value_max=volume_max_percent)
        #self.microphone_scale.set_size_request(90, 10)
        #self.microphone_mute_button = SwitchButton(
            #inactive_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"), 
            #active_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"))
        #table.attach(self.__make_align(microphone_img), 0, 1, 1, 2, 4)
        #table.attach(self.__make_align(self.microphone_scale, yalign=0.0, yscale=1.0, padding_left=5, padding_right=5, height=25), 1, 2, 1, 2, 4)
        #table.attach(self.__make_align(self.microphone_mute_button), 2, 3, 1, 2, 4)

        self.pack_start(table, False, False)

        self.__app_vbox = gtk.VBox(False)
        separator_color = [(0, ("#777777", 0.0)), (0.5, ("#000000", 0.3)), (1, ("#777777", 0.0))]
        hseparator = HSeparator(separator_color, 0, 0)
        hseparator.set_size_request(140, 5)
        self.__app_vbox.pack_start(self.__make_align(Label(_("Applications"), enable_select=False, enable_double_click=False)), False, False)
        self.__app_vbox.pack_start(self.__make_align(hseparator, xalign=0.5, height=5), False, False)

        self.__mpris_vbox = gtk.VBox(False)
        self.__app_vbox.pack_start(self.__mpris_vbox)
        self.pack_start(self.__app_vbox)

        hseparator = HSeparator(separator_color, 0, 0)
        hseparator.set_size_request(140, 7)
        self.pack_start(self.__make_align(hseparator, xalign=0.5, height=7), False, False)

        self.button_more = SelectButton(_("Advanced..."), font_size=10, ali_padding=5)
        self.button_more.set_size_request(-1, 25)
        self.pack_start(self.button_more, False, False)
        #self.pack_start(self.__make_align(height=10))
        ##########################################
        self.__set_output_status()
        #self.__set_input_status()

        # widget signals
        self.speaker_mute_button.connect("toggled", self.speaker_toggled)
        #self.microphone_mute_button.connect("toggled", self.microphone_toggled)
        self.speaker_scale.connect("value-changed", self.speaker_scale_value_changed)
        #self.microphone_scale.connect("value-changed", self.microphone_scale_value_changed)
        # pulseaudio signals
        pypulse.PULSE.connect("sink-changed", self.sink_changed_cb)
        #pypulse.PULSE.connect("source-changed", self.source_changed_cb)
        pypulse.PULSE.connect("server-changed", self.server_changed_cb)
        pypulse.PULSE.connect("sink-input-new", self.sink_input_new_cb)
        pypulse.PULSE.connect("sink-input-changed", self.sink_input_changed_cb)
        pypulse.PULSE.connect("sink-input-removed", self.sink_input_removed_cb)
        playback_streams = pypulse.PULSE.get_playback_streams()
        self.stream_num = len(playback_streams.keys())
        self.mpris2.get_mpris_list()
        self.mpris_num = len(self.mpris2.mpris_process.keys())
        if self.stream_num == 0 and self.mpris_num == 0:
            self.__app_vbox.set_no_show_all(True)
        for stream in playback_streams:
            self.__make_playback_box(playback_streams[stream], stream)

    def __make_align(self, widget=None, xalign=0.0, yalign=0.5, xscale=0.0,
                     yscale=0.0, padding_top=0, padding_bottom=0, padding_left=0,
                     padding_right=0, width=-1, height=25):
        align = gtk.Alignment()
        align.set_size_request(width, height)
        align.set(xalign, yalign, xscale, yscale)
        align.set_padding(padding_top, padding_bottom, padding_left, padding_right)
        if widget:
            align.add(widget)
        return align

    def __make_playback_box(self, stream, index):
        process_id = int(stream['proplist']['application.process.id'])
        # if it has show mpris, then don't show sink_input
        if process_id in self.mpris_list:
            self.mpris_stream[process_id] = index
            self.stream_mpris[index] = process_id
            return
        self.stream_list[index] = {}
        volume_max_percent = pypulse.MAX_VOLUME_VALUE * 100 / pypulse.NORMAL_VOLUME_VALUE
        icon_name = self.__white_list_check(stream)
        if icon_name:
            if icon_name[0] == '/' and os.path.exists(icon_name):
                try:
                    img = gtk.image_new_from_pixbuf(gtk.gdk.pixbuf_new_from_file(
                        icon_name).scale_simple(16, 16, gtk.gdk.INTERP_TILES))
                except:
                    img = gtk.image_new_from_pixbuf(self.stream_icon)
            else:
                img = gtk.image_new_from_icon_name(icon_name, gtk.ICON_SIZE_MENU)
        else:
            img = gtk.image_new_from_pixbuf(self.stream_icon)
        scale = HScalebar(show_value=False, format_value="%", value_min=0, value_max=volume_max_percent)
        scale.set_magnetic_values([(0, 5), (100, 5), (volume_max_percent, 5)])
        scale.set_size_request(90, 10)
        mute_button = SwitchButton(
            inactive_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"), 
            active_disable_dpixbuf=app_theme.get_pixbuf("toggle_button/inactive_normal.png"))
        hbox = gtk.HBox()
        hbox.pack_start(self.__make_align(img), False, False)
        hbox.pack_start(self.__make_align(scale, yalign=0.0, yscale=1.0, padding_left=5, padding_right=5, height=25), False, False)
        hbox.pack_start(self.__make_align(mute_button), False, False)
        self.stream_list[index]['scale'] = scale
        self.stream_list[index]['button'] = mute_button
        self.stream_list[index]['container'] = hbox
        self.stream_list[index]['process_id'] = process_id
        self.stream_list[index]['stream_id'] = index
        self.stream_process[process_id] = self.stream_list[index]
        self.__set_playback_status(stream, scale, mute_button)
        if stream['volume_writable']:
            scale.connect("value-changed", self.playback_stream_scale_changed_cb, index, mute_button)
            mute_button.connect("toggled", self.playback_stream_toggled_cb, index, scale)
        hbox.show_all()
        self.__app_vbox.pack_start(hbox, False, False)

    def __white_list_check(self, stream):
        icon_name = None
        # check deepin-media-player
        if 'application.process.binary' in stream['proplist']:
            if stream['proplist']['application.process.binary'] == 'mplayer':
                process_id = int(stream['proplist']['application.process.id'])
                process_list = psutil.get_process_list()
                for p in process_list:
                    if p.pid == process_id and p.ppid != 0 and p.parent.name.startswith('deepin-media'):
                        return "deepin-media-player"
        if 'application.icon_name' in stream['proplist']:
            icon_name = stream['proplist']['application.icon_name']
        # check deepin-music-player
        if 'application.name' in stream['proplist']:
            if stream['proplist']['application.name'] == 'deepin-music-player':
                icon_name = "deepin-music-player"
        return icon_name

    ####################################################
    # widget signals
    def speaker_value_changed_thread(self):
        ''' speaker hscale value changed callback thread'''
        if not self.speaker_mute_button.get_active():
            self.speaker_mute_button.set_active(True)
        current_sink = pypulse.get_fallback_sink_index()
        if current_sink is None:
            return
        volume_list = pypulse.PULSE.get_output_volume_by_index(current_sink)
        channel_list = pypulse.PULSE.get_output_channels_by_index(current_sink)
        if not volume_list or not channel_list:
            return
        balance = pypulse.get_volume_balance(channel_list['channels'], volume_list, channel_list['map'])
        volume = int((self.speaker_scale.get_value()) / 100.0 * pypulse.NORMAL_VOLUME_VALUE)
        pypulse.PULSE.set_output_volume_with_balance(current_sink, volume, balance)

    def speaker_scale_value_changed(self, widget, value):
        '''set output volume'''
        self.speaker_value_changed_thread()

    def microphone_value_changed_thread(self):
        ''' microphone value changed callback thread'''
        if not self.microphone_mute_button.get_active():
            self.microphone_mute_button.set_active(True)
        current_source = pypulse.get_fallback_source_index()
        if current_source is None:
            return
        channel_list = pypulse.PULSE.get_input_channels_by_index(current_source)
        if not channel_list:
            return

        volume = int((self.microphone_scale.get_value()) / 100.0 * pypulse.NORMAL_VOLUME_VALUE)
        pypulse.PULSE.set_input_volume(current_source, [volume] * channel_list['channels'])

    def microphone_scale_value_changed(self, widget, value):
        ''' set input volume'''
        self.microphone_value_changed_thread()

    def speaker_toggled(self, button):
        active = button.get_active()
        current_sink = pypulse.get_fallback_sink_index()
        self.speaker_scale.set_enable(active)
        if current_sink is not None:
            pypulse.PULSE.set_output_mute(current_sink, not active)

    def microphone_toggled(self, button):
        active = button.get_active()
        current_source = pypulse.get_fallback_source_index()
        self.microphone_scale.set_enable(active)
        if current_source is not None:
            pypulse.PULSE.set_input_mute(current_source, not active)

    def playback_stream_scale_changed_cb(self, widget, value, index, button):
        if not button.get_active():
            button.set_active(True)
        volume = int((widget.get_value()) / 100.0 * pypulse.NORMAL_VOLUME_VALUE)
        pypulse.PULSE.set_sink_input_volume(index, [volume] * widget.volume_channels)

    def playback_stream_toggled_cb(self, button, index, scale):
        active = button.get_active()
        scale.set_enable(active)
        pypulse.PULSE.set_sink_input_mute(index, not active)

    # pulseaudio signals callback
    def sink_changed_cb(self, obj, index):
        obj.get_devices()
        current_sink = pypulse.get_fallback_sink_index()
        if current_sink is None or current_sink != index:
            return
        self.__set_output_status()

    # update tray_icon
    def update_tray_icon(self):
        if self.tray_obj:
            current_sink = pypulse.get_fallback_sink_index()
            sinks = pypulse.PULSE.get_output_devices()
            sink_volume = pypulse.PULSE.get_output_volume()
            tip_text = "%s %d%%" % (_("Volume"), self.speaker_scale.get_value())
            if current_sink in sinks and current_sink in sink_volume:
                is_mute = sinks[current_sink]['mute']
                if is_mute:
                    tip_text = _("Mute")
                volume = max(sink_volume[current_sink]) * 100.0 / pypulse.NORMAL_VOLUME_VALUE
                if volume == 0:
                    volume_level = 0
                elif 0 < volume <= 40:
                    volume_level = 1
                elif 40 < volume <= 80:
                    volume_level = 2
                else:
                    volume_level = 3
                self.tray_obj.set_tray_icon(volume_level, is_mute)
            if self.tray_obj.tray_obj:
                self.tray_obj.tray_obj.set_tooltip_text(tip_text)

    def source_changed_cb(self, obj, index):
        obj.get_devices()
        current_source = pypulse.get_fallback_source_index()
        if current_source is None or current_source != index:
            return
        self.__set_input_status()

    def server_changed_cb(self, obj):
        obj.get_devices()
        self.__set_output_status()
        #self.__set_input_status()

    def sink_input_new_cb(self, obj, index):
        obj.get_devices()
        playback = obj.get_playback_streams()
        if index in playback:
            self.__make_playback_box(playback[index], index)
            self.stream_num = len(playback.keys())
            stream_num = len(self.stream_list.keys())
            mpris_num = len(self.mpris_list.keys())
            if stream_num > 0 or mpris_num > 0:
                self.__app_vbox.set_no_show_all(False)
                self.__app_vbox.show_all()
            self.adjust_size()
            self.emit("stream-changed")

    def sink_input_changed_cb(self, obj, index):
        obj.get_devices()
        playback = obj.get_playback_streams()
        if index not in self.stream_list and index in playback:
            self.__make_playback_box(playback[index], index)
        elif index in playback:
            self.__set_playback_status(playback[index],
                                       self.stream_list[index]['scale'],
                                       self.stream_list[index]['button'])

    def sink_input_removed_cb(self, obj, index):
        if index in self.stream_mpris:
            if self.stream_mpris[index] in self.mpris_stream:
                del self.mpris_stream[self.stream_mpris[index]]
            del self.stream_mpris[index]
        if index in self.stream_list:
            process_id = self.stream_list[index]['process_id']
            if process_id in self.stream_process:
                del self.stream_process[process_id]
            self.stream_list[index]['container'].destroy()
            del self.stream_list[index]
            self.stream_num -= 1
            stream_num = len(self.stream_list.keys())
            mpris_num = len(self.mpris_list.keys())
            if stream_num == 0 and mpris_num == 0:
                self.__app_vbox.hide_all()
                self.__app_vbox.set_no_show_all(True)
            self.adjust_size()
            self.emit("stream-changed")

    def __set_output_status(self):
        # if sinks list is empty, then can't set output volume
        current_sink = pypulse.get_fallback_sink_index()
        sinks = pypulse.PULSE.get_output_devices()
        if current_sink is None:
            self.speaker_scale.set_sensitive(False)
            self.speaker_mute_button.set_sensitive(False)
            self.speaker_scale.set_enable(False)
            self.speaker_mute_button.set_active(False)
        # set output volume
        elif current_sink in sinks:
            self.speaker_scale.set_sensitive(True)
            self.speaker_mute_button.set_sensitive(True)
            is_mute = sinks[current_sink]['mute']
            self.speaker_mute_button.set_active(not is_mute)
            self.speaker_scale.set_enable(not is_mute)
            sink_volume = pypulse.PULSE.get_output_volume()
            if current_sink in sink_volume:
                volume = max(sink_volume[current_sink])
            else:
                volume = 0
            self.speaker_scale.set_value(volume * 100.0 / pypulse.NORMAL_VOLUME_VALUE)
        self.update_tray_icon()

    def __set_input_status(self):
        # if sources list is empty, then can't set input volume
        current_source = pypulse.get_fallback_source_index()
        sources = pypulse.PULSE.get_input_devices()
        if current_source is None:
            self.microphone_scale.set_sensitive(False)
            self.microphone_mute_button.set_sensitive(False)
            self.microphone_scale.set_enable(False)
            self.microphone_mute_button.set_active(False)
        # set input volume
        elif current_source in sources:
            self.microphone_scale.set_sensitive(True)
            self.microphone_mute_button.set_sensitive(True)
            is_mute = sources[current_source]['mute']
            self.microphone_mute_button.set_active(not is_mute)
            self.microphone_scale.set_enable(not is_mute)
            source_volume = pypulse.PULSE.get_input_volume()
            if current_source in source_volume:
                volume = max(source_volume[current_source])
            else:
                volume = 0
            self.microphone_scale.set_value(volume * 100.0 / pypulse.NORMAL_VOLUME_VALUE)
    
    def __set_playback_status(self, stream, scale, button):
        if not stream['has_volume']:
            scale.set_sensitive(False)
            button.set_sensitive(False)
            scale.set_enable(False)
            button.set_active(False)
        else:
            scale.set_sensitive(True)
            button.set_sensitive(True)
            is_mute = stream['mute']
            button.set_active(not is_mute)
            scale.set_enable(not is_mute)
            volume = max(stream['volume'])
            scale.set_value(volume * 100.0 / pypulse.NORMAL_VOLUME_VALUE)
            scale.volume_channels = len(stream['volume'])

    # mpris dbus signal
    def mpris2_new_cb(self, obj, pid):
        vbox = gtk.VBox()
        img = gtk.image_new_from_icon_name(obj.mpris_process[pid]['property']['DesktopEntry'], gtk.ICON_SIZE_MENU)
        # application title
        app_title = obj.mpris_process[pid]['property']['Identity']
        #if obj.mpris_process[pid]['property']['PlaybackStatus'] == 'Stopped':
            #app_title = obj.mpris_process[pid]['property']['Identity']
        #else:
            #app_title = "%s - %s" % (obj.mpris_process[pid]['property']['Identity'], _(obj.mpris_process[pid]['property']['PlaybackStatus']))
        label = Label(app_title, label_width=115)
        hbox = gtk.HBox(False, 5)
        hbox.pack_start(self.__make_align(img), False, False)
        hbox.pack_start(self.__make_align(label), False, False)
        vbox.pack_start(hbox, False, False)

        # metadata info
        meta_box = gtk.HBox(False, 10)
        xesam_vbox = gtk.VBox(False)
        #art_img = gtk.Image()
        art_img = gtk.EventBox()
        art_img.set_size_request(40, 40)
        art_img.connect("expose-event", self.__draw_mpris_art_img)

        xesam_title = Label("", label_width=75)
        xesam_artist = Label("", label_width=75)
        xesam_album = Label("", label_width=75)
        xesam_vbox.pack_start(xesam_title)
        xesam_vbox.pack_start(xesam_artist)
        #xesam_vbox.pack_start(xesam_album)
        meta_box.pack_start(self.__make_align(art_img, padding_left=21, height=40), False, False)
        meta_box.pack_start(xesam_vbox)

        self.mpris_list[pid] = {}
        # mpris control
        scale = HScalebar(app_theme.get_pixbuf("sound/point.png"), show_value=False, format_value="%", value_min=0, value_max=1, line_height=3)
        scale.set_magnetic_values([(0, 0.1), (1, 0.1)])
        scale.set_size_request(70, 10)
        prev_bt = gtk.Button()
        pause_bt = gtk.Button()
        stop_bt = gtk.Button()
        next_bt = gtk.Button()

        prev_bt.set_size_request(20, 22)
        pause_bt.set_size_request(29, 30)
        #stop_bt.set_size_request(16, 16)
        next_bt.set_size_request(20, 22)

        prev_bt.pixbuf = "previous"
        if obj.mpris_process[pid]['property']['PlaybackStatus'] == 'Playing':
            pause_bt.pixbuf = "pause"
        else:
            pause_bt.pixbuf = "play"
        #stop_bt.pixbuf = self.stop_img
        next_bt.pixbuf = "next"

        scale.set_value(obj.mpris_process[pid]['property']['Volume'])

        prev_bt.connect("clicked", self.__mpris_prev_cb, obj, pid)
        pause_bt.connect("clicked", self.__mpris_pause_cb, obj, pid)
        #stop_bt.connect("clicked", self.__mpris_stop_cb, obj, pid)
        next_bt.connect("clicked", self.__mpris_next_cb, obj, pid)
        prev_bt.connect("expose-event", self.__draw_mpris_button_cb)
        pause_bt.connect("expose-event", self.__draw_mpris_button_cb)
        stop_bt.connect("expose-event", self.__draw_mpris_button_cb)
        next_bt.connect("expose-event", self.__draw_mpris_button_cb)
        scale.connect("value-changed", self.__mpris_volume_cb, obj, pid)

        hbox = gtk.HBox()
        hbox.pack_start(self.__make_align(prev_bt, height=-1), False, False)
        hbox.pack_start(self.__make_align(pause_bt, height=-1), False, False)
        #hbox.pack_start(self.__make_align(stop_bt, height=-1), False, False)
        hbox.pack_start(self.__make_align(next_bt, height=-1), False, False)
        hbox.pack_start(self.__make_align(scale, yalign=0.0, yscale=1.0, height=-1), False, False)
        vbox.pack_start(self.__make_align(hbox, xalign=0.5, padding_top=5, padding_bottom=10, height=-1), False, False)

        self.mpris_list[pid]['app_title'] = label
        self.mpris_list[pid]['prev'] = prev_bt
        self.mpris_list[pid]['pause'] = pause_bt
        self.mpris_list[pid]['stop'] = stop_bt
        self.mpris_list[pid]['next'] = next_bt
        self.mpris_list[pid]['scale'] = scale
        self.mpris_list[pid]['meta'] = meta_box
        self.mpris_list[pid]['meta_img'] = art_img
        self.mpris_list[pid]['meta_title'] = xesam_title
        self.mpris_list[pid]['meta_artist'] = xesam_artist
        self.mpris_list[pid]['meta_album'] = xesam_album
        self.mpris_list[pid]['container'] = vbox
        if not obj.mpris_process[pid]['property']['Metadata']:
            self.mpris_list[pid]['height'] = self.mpris_base_height
        else:
            vbox.pack_start(meta_box, False, False)
            vbox.reorder_child(meta_box, 1)
            self.__set_mpris_meta_info(pid)
            self.mpris_list[pid]['height'] = self.mpris_base_height + 40
        self.__mpris_total_height += self.mpris_list[pid]['height']
        # delete playback_stream widget
        if pid in self.stream_process:
            self.stream_process[pid]['container'].destroy()
            del self.stream_list[self.stream_process[pid]['stream_id']]
            del self.stream_process[pid]
        vbox.show_all()
        self.__mpris_vbox.pack_start(vbox, False, False)

        stream_num = len(self.stream_list.keys())
        mpris_num = len(self.mpris_list.keys())
        if stream_num > 0 or mpris_num > 0:
            self.__app_vbox.set_no_show_all(False)
            self.__app_vbox.show_all()
        self.adjust_size()
        self.emit("stream-changed")

    def __draw_mpris_art_img(self, widget, event):
        x, y, w, h = widget.allocation
        cr = widget.window.cairo_create()
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) 
        surface_cr = gtk.gdk.CairoContext(cairo.Context(surface))
        surface_cr.set_source_rgba(0, 0, 0, 1.0)
        surface_cr.rectangle(5, 5, w-10, h-10)
        surface_cr.stroke()

        dtk_cairo_blur.gaussian_blur(surface, 3)
        cr.set_source_surface(surface, 0, 0)
        cr.paint()

        cr.set_source_rgb(1, 1, 1)
        cr.rectangle(2, 2, w-4, h-4)
        cr.fill()

        if widget.pixbuf:
            cr.set_source_pixbuf(widget.pixbuf, 4, 4)
            cr.paint()
        return True

    def __set_mpris_meta_info(self, pid):
        if 'mpris:artUrl' in self.mpris2.mpris_process[pid]['property']['Metadata']:
            arturl = urlparse(self.mpris2.mpris_process[pid]['property']['Metadata']['mpris:artUrl'])
            if arturl.scheme == 'file' and os.path.exists(arturl.path):
                art_pixbuf = gtk.gdk.pixbuf_new_from_file(arturl.path).scale_simple(32, 32, gtk.gdk.INTERP_TILES)
                #self.mpris_list[pid]['meta_img'].set_from_pixbuf(art_pixbuf)
                self.mpris_list[pid]['meta_img'].pixbuf = art_pixbuf
        else:
            self.mpris_list[pid]['meta_img'].pixbuf = None
        self.mpris_list[pid]['meta_img'].queue_draw()
        if 'xesam:title' in self.mpris2.mpris_process[pid]['property']['Metadata']:
            self.mpris_list[pid]['meta_title'].set_text(
                markup_escape_text(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:title']))
        else:
            self.mpris_list[pid]['meta_title'].set_text("-")
        if 'xesam:artist' in self.mpris2.mpris_process[pid]['property']['Metadata']:
            self.mpris_list[pid]['meta_artist'].set_text(
                markup_escape_text('&'.join(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:artist'])))
        else:
            self.mpris_list[pid]['meta_artist'].set_text("-")
        if 'xesam:album' in self.mpris2.mpris_process[pid]['property']['Metadata']:
            self.mpris_list[pid]['meta_album'].set_text(
                markup_escape_text(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:album']))
        else:
            self.mpris_list[pid]['meta_album'].set_text("-")
        
    def mpris2_removed_cb(self, obj, pid):
        if pid in self.mpris_list:
            self.mpris_list[pid]['container'].destroy()
            self.mpris_list[pid]['meta'].destroy()
            self.__mpris_total_height -= self.mpris_list[pid]['height']
            del self.mpris_list[pid]
        if pid in self.mpris_stream:
            stream_id = self.mpris_stream[pid]
            playback_streams = pypulse.PULSE.get_playback_streams()
            if stream_id in playback_streams:
                self.__make_playback_box(playback_streams[stream_id], stream_id)
        stream_num = len(self.stream_list.keys())
        mpris_num = len(self.mpris_list.keys())
        if stream_num == 0 and mpris_num == 0:
            self.__app_vbox.hide_all()
            self.__app_vbox.set_no_show_all(True)
        self.adjust_size()
        self.emit("stream-changed")

    def mpris2_changed_cb(self, obj, pid, changed):
        #print "mpris changed", pid, changed
        if pid not in self.mpris_list:
            return
        if 'Volume' in changed:
            self.mpris_list[pid]['scale'].set_value(changed['Volume'])
        if 'PlaybackStatus' in changed:
            # application title && hide meta info
            if changed['PlaybackStatus'] == 'Stopped':
                if self.mpris_list[pid]['meta'] in self.mpris_list[pid]['container'].get_children():
                    self.mpris_list[pid]['container'].remove(self.mpris_list[pid]['meta'])
                    self.__mpris_total_height -= self.mpris_list[pid]['height']
                    self.mpris_list[pid]['height'] = self.mpris_base_height
                    self.__mpris_total_height += self.mpris_list[pid]['height']
                    self.adjust_size()
                    self.emit("stream-changed")
            # button image
            if changed['PlaybackStatus'] == 'Playing':
                self.mpris_list[pid]['pause'].pixbuf = "pause"
            else:
                self.mpris_list[pid]['pause'].pixbuf = "play"
            self.mpris_list[pid]['pause'].queue_draw()
        if 'Metadata' in changed and obj.mpris_process[pid]['property']['PlaybackStatus'] != 'Stopped':
            self.__set_mpris_meta_info(pid)
            if self.mpris_list[pid]['meta'] not in self.mpris_list[pid]['container'].get_children():
                self.mpris_list[pid]['container'].pack_start(self.mpris_list[pid]['meta'], False, False)
                self.mpris_list[pid]['container'].reorder_child(self.mpris_list[pid]['meta'], 1)
                self.mpris_list[pid]['container'].show_all()
                self.__mpris_total_height -= self.mpris_list[pid]['height']
                self.mpris_list[pid]['height'] = self.mpris_base_height + 40
                self.__mpris_total_height += self.mpris_list[pid]['height']
                self.adjust_size()
                self.emit("stream-changed")

    def __mpris_prev_cb(self, bt, obj, pid):
        if pid not in obj.mpris_process:
            return
        try:
            obj.mpris_process[pid]['obj'].get_dbus_method(
                'Previous', 'org.mpris.MediaPlayer2.Player')()
        except Exception, e:
            if e._dbus_error_name == "org.freedesktop.DBus.Error.ServiceUnknown":
                self.mpris2_removed_cb(obj, pid)
コード例 #7
0
class TrayUI(gtk.VBox):
    def __init__(self):
        gtk.VBox.__init__(self, spacing=0)
        self.init_ui()
        self.active_ap_index = []
        self.all_showed = False

    def init_ui(self):
        self.wire = Section(app_theme.get_pixbuf("network/cable.png"),
                            _("Wired"))
        self.wireless = Section(app_theme.get_pixbuf("network/wifi.png"),
                                _("Wireless"))
        self.mobile = Section(app_theme.get_pixbuf("network/3g.png"),
                              _("Mobile Network"))
        # vpn
        self.vpn = Section(app_theme.get_pixbuf("network/vpn.png"),
                           _("VPN Network"))
        self.dsl = Section(app_theme.get_pixbuf("network/dsl.png"), _("DSL"))

        self.ssid_list = []
        self.tree_box = gtk.VBox(spacing=0)
        self.button_more = SelectButton(_("Advanced..."),
                                        font_size=10,
                                        ali_padding=5)
        self.button_more.set_size_request(-1, 25)
        #self.pack_start(self.button_more, False, False)
        self.ap_tree = TreeView(mask_bound_height=0)
        self.ap_tree.set_expand_column(0)

        self.vpn_list = ConList()
        self.dsl_list = DSLConList()

        self.wire_box = self.section_box([self.wire])
        self.wireless_box = self.section_box([self.wireless, self.tree_box])
        self.mobile_box = self.section_box([self.mobile])
        self.vpn_box = self.section_box([self.vpn, self.vpn_list])
        self.dsl_box = self.section_box([self.dsl, self.dsl_list])
        self.wire_state = False
        self.wireless_state = False
        self.mobile_state = False
        self.vpn_state = False
        self.dsl_state = False

        self.device_tree = None

        self.pack_start(self.wire_box, False, False)
        self.pack_start(self.wireless_box, False, False)
        self.pack_start(self.mobile_box, False, False)
        self.pack_start(self.vpn_box, False, False)
        self.pack_start(self.dsl_box, False, False)
        self.pack_start(self.button_more, False, False)

    def get_widget_height(self):
        height = 0
        if self.wire_state:
            height += 35
        if self.wireless_state:
            height += 35
            if self.ap_tree.visible_items and self.wireless.get_active():
                height += self.ap_tree.get_size_request()[1]
            if self.device_tree:
                height += 22

        if self.mobile_state:
            height += 35

        if self.vpn_state:
            height += 35 + len(self.vpn_list.get_children()) * 22

        if self.dsl_state:
            height += 35 + len(self.dsl_list.get_children()) * 22
            height += 5
        height += 25

        return height

    def section_box(self, widgets):
        box = gtk.VBox(spacing=0)
        for w in widgets:
            box.pack_start(w, False, False)
        style.add_separator(box, 10)
        return box

    def remove_net(self, net_type):
        #print net_type
        getattr(self, net_type + "_box").set_no_show_all(True)
        #getattr(self, net_type).set_active((True, False))
        getattr(self, net_type + "_box").hide()
        setattr(self, net_type + "_state", False)

    def show_net(self, net_type):
        getattr(self, net_type + "_box").set_no_show_all(False)
        getattr(self, net_type + "_box").show()
        setattr(self, net_type + "_state", True)

    def set_wired_state(self, widget, new_state, reason):
        if new_state is 20:
            self.wire.set_active(0)
        else:
            tray_log.debug(__name__, new_state, reason)

    def set_visible_aps(self, show_all=False):
        if not self.__ap_list:
            self.visible_aps = []
            return

        tray_log.debug(len(self.__ap_list))

        if show_all:
            if len(self.__ap_list) <= 10:
                self.visible_aps = self.__ap_list[:]
            else:
                self.visible_aps = self.__ap_list[:10]
            self.more_button.set_ap_list([])
            self.show_all = True

        else:
            if len(self.__ap_list) <= 5:
                self.visible_aps = self.__ap_list[:]
                self.show_all = True
            else:
                self.visible_aps = self.__ap_list[:5]
                self.more_button.set_ap_list(self.__ap_list[5:])
                self.show_all = False

    def set_ap(self, ap_list, redraw=True):
        if not ap_list:
            return
        self.__set_ap_list(ap_list)
        #print "DEBUG", len(self.visible_aps), self.show_all
        self.ap_tree.delete_all_items()
        container_remove_all(self.tree_box)

        self.ap_tree.add_items(map(lambda ap: SsidItem(ap), self.__ap_list))
        length = len(self.ap_tree.visible_items)
        if length <= 10:
            self.ap_tree.set_size_request(-1, WIDGET_HEIGHT * length)
        else:
            self.ap_tree.set_size_request(-1, WIDGET_HEIGHT * 10)
            for item in self.ap_tree.visible_items:
                item.set_padding(10)

        self.tree_box.pack_start(self.ap_tree, False, False)
        self.show_all()

        if redraw:
            Dispatcher.request_resize()

    def __set_ap_list(self, ap_list):
        self.__ap_list = ap_list

    def move_active(self, index):
        if index != [] and self.__ap_list:
            for i in index:
                if i < len(self.ap_tree.visible_items):
                    self.ap_tree.delete_item_by_index(i)
                    self.ap_tree.add_items([SsidItem(self.__ap_list[i])],
                                           insert_pos=0)
                else:
                    self.ap_tree.delete_item_by_index(-1)
                    self.ap_tree.add_items([SsidItem(self.__ap_list[i])],
                                           insert_pos=0)
                self.ap_tree.visible_items[0].set_active(True)

    def set_active_ap(self, index, state):
        self.active_ap_index = index
        self.set_ap(self.__ap_list, redraw=False)

        if index:
            self.move_active(index)

    def get_active_ap(self):
        return self.active_ap_index

    def add_switcher(self):
        if not hasattr(self, "device_tree") or not self.device_tree:
            self.device_tree = TreeView([DeviceItem()], mask_bound_height=0)
            self.device_tree.set_expand_column(1)
            self.wireless_box.pack_start(self.device_tree, False, False)
            self.wireless_box.reorder_child(
                self.wireless_box.get_children()[-2],
                len(self.wireless_box.get_children()))
            tray_log.debug(self.wireless_box.get_children())
            net_manager.emit_wifi_switch(0)

    def remove_switcher(self):
        if self.device_tree:
            self.wireless_box.remove(self.device_tree)
            self.device_tree = None

    def get_active_in_ui(self):
        return filter(lambda i: i.get_active() == True,
                      self.ap_tree.visible_items)

    def reset_tree(self):
        if len(self.ap_tree.visible_items) >= 5 and self.all_showed:
            remove_items = self.ap_tree.visible_items[5:]
            self.ap_tree.delete_items(remove_items)
            self.ap_tree.set_size_request(-1, WIDGET_HEIGHT * 5)
            self.tree_box.pack_start(self.more_button, False, False)
            self.all_showed = False
コード例 #8
0
class PowerGui(gtk.VBox):
    def __init__(self, power_settings):
        gtk.VBox.__init__(self)
        self.power_settings = power_settings
        self.hbox = gtk.HBox()
        # init top widgets.
        self.icon = vtk_theme.name.get_image("power/power_icon.png") 
        self.label = gtk.Label(_("Power"))
        self.label.connect("expose-event", self.label_expose_event)
        self.hbox.pack_start(self.icon, False, False) 
        self.hbox.pack_start(self.label, False, False)
        # init mid widgets.
        self.top_line_ali = gtk.Alignment(1.0, 1.0, 1.0, 1.0)
        self.top_line_ali.set_padding(5, 5, 0, 0)
        self.top_line = HSeparator(HSEPARATOR_COLOR, 0, 0) 
        self.top_line_ali.add(self.top_line)
        self.one_mode_btn = SelectButton(_("Balanced"), ali_padding=125)
        self.two_mode_btn = SelectButton(_("Power saver"), ali_padding=125)
        self.tree_mode_btn = SelectButton(_("High performance"), ali_padding=125)
        self.customized_mode_btn = SelectButton(_("Custom"), ali_padding=125)
        self.one_mode_btn.connect("clicked", self.one_mode_btn_clicked)
        self.two_mode_btn.connect("clicked", self.two_mode_btn_clicked)
        self.tree_mode_btn.connect("clicked", self.tree_mode_btn_clicked)
        self.customized_mode_btn.connect("clicked", self.__on_customized_mode_btn_clicked)
        self.mode_height = 25
        self.one_mode_btn.set_size_request(-1, self.mode_height)
        self.two_mode_btn.set_size_request(-1, self.mode_height)
        self.tree_mode_btn.set_size_request(-1, self.mode_height)
        self.customized_mode_btn.set_size_request(-1, self.mode_height)
        # init bottom widgets
        self.bottom_line_ali = gtk.Alignment(1.0, 1.0, 1.0, 1.0)
        self.bottom_line_ali.set_padding(5, 5, 0, 0)
        self.bottom_line = HSeparator(HSEPARATOR_COLOR, 0, 0)
        self.bottom_line_ali.add(self.bottom_line)
        self.click_btn = SelectButton(_("Advanced..."), ali_padding=5)
        self.click_btn.set_size_request(-1, 25)
        # add all widgets.
        self.pack_start(self.hbox, False, False)
        self.pack_start(self.top_line_ali, False, False)
        self.pack_start(self.one_mode_btn, False, False)
        self.pack_start(self.two_mode_btn, False, False)
        self.pack_start(self.tree_mode_btn, False, False)
        self.pack_start(self.customized_mode_btn, False, False)
        self.pack_start(self.bottom_line_ali, False, False)
        self.pack_start(self.click_btn, False, False)

    def label_expose_event(self, widget, event):
        cr = widget.window.cairo_create()
        rect = widget.allocation
        #
        draw_text(cr, widget.get_label(), rect.x + 5, rect.y, text_color="#000000")      
        #
        return True

    def one_mode_btn_clicked(self, widget):
        self.set_mode_bit(widget)
        self.power_settings.set_string("current-plan", "balance")

    def two_mode_btn_clicked(self, widget):
        self.set_mode_bit(widget)
        self.power_settings.set_string("current-plan", "saving")

    def tree_mode_btn_clicked(self, widget):
        self.set_mode_bit(widget)
        self.power_settings.set_string("current-plan", "high-performance")

    def __on_customized_mode_btn_clicked(self, widget):
        self.set_mode_bit(widget)
        self.power_settings.set_string("current-plan", "customized")

    def set_mode_bit(self, widget):
        self.one_mode_btn.text_color = "#000000" 
        self.two_mode_btn.text_color = "#000000"
        self.tree_mode_btn.text_color = "#000000"
        self.customized_mode_btn.text_color = "#000000"
        self.one_mode_btn.queue_draw()
        self.two_mode_btn.queue_draw()
        self.tree_mode_btn.queue_draw()
        self.customized_mode_btn.queue_draw()
        # set press color.
        widget.text_color = "#3da1f7"
コード例 #9
0
class Gui(gtk.VBox):
    def __init__(self):
        gtk.VBox.__init__(self)
        self.init_values()
        self.init_widgets()

    def init_values(self):
        self.cmd_dbus = CmdDbus()
        self.gui_theme = app_theme

    def init_widgets(self):
        self.icon_width = self.icon_height = HEIGHT
        #
        self.user_hbox = gtk.HBox()
        self.user_icon = gtk.Image()
        self.user_icon.set_size_request(HEIGHT, HEIGHT)
        #
        user_name = self.cmd_dbus.get_user_name()
        user_name_width = get_text_size(user_name)[0]
        if user_name_width > WIDTH: 
            de_user_name = user_name.decode("utf-8")
            user_name = de_user_name[0:10] + "..."
        self.user_label_ali = gtk.Alignment(0, 0, 1, 1)
        self.user_label_ali.set_padding(0, 0, 5, 0)
        self.user_label_event = gtk.EventBox()
        self.user_label = gtk.Label(user_name)
        self.user_label_event.add(self.user_label)
        self.user_label_ali.add(self.user_label_event)
        self.user_icon.connect_after("expose-event", self.user_label_event_expose_event)
        #
        self.user_hbox.pack_start(self.user_icon, False, False)
        self.user_hbox.pack_start(self.user_label_ali, False, False)
        #
        self.h_separator_top_ali = gtk.Alignment(1, 1, 1, 1)
        self.h_separator_top_ali.set_padding(5, 5, 0, 0)
        hseparator_color = [(0, ("#777777", 0.0)),
                            (0.5, ("#000000", 0.3)), 
                            (1, ("#777777", 0.0))]
        self.h_separator_top = HSeparator(hseparator_color, 0, 0)
        self.h_separator_top_ali.add(self.h_separator_top)

        self.switch_separator_bottom = HSeparator(hseparator_color, 0, 0)
        self.switch_separator_bottom_ali = gtk.Alignment(1, 1, 1, 1)
        self.switch_separator_bottom_ali.set_padding(5, 5, 0, 0)
        self.switch_separator_bottom_ali.add(self.switch_separator_bottom)
        #
        ali_padding = 100  
        font_size = 10
        self.switch_btn = SelectButton(_("Switch user"), 
                                       font_size=font_size, 
                                       ali_padding=ali_padding)
        self.stop_btn = SelectButton(_("Shut down"), 
                                     font_size=font_size, 
                                     ali_padding=ali_padding)
        self.restart_btn = SelectButton(_("Restart"), 
                                        font_size=font_size, 
                                        ali_padding=ali_padding)
        self.suspend_btn = SelectButton(_("Suspend"), 
                                        font_size=font_size, 
                                        ali_padding=ali_padding)
        self.logout_btn = SelectButton(_("Log out"), 
                                       font_size=font_size, 
                                       ali_padding=ali_padding)
        self.lock_btn = SelectButton(_("Lock"), 
                                     font_size=font_size, 
                                     ali_padding=ali_padding)
        #
        self.switch_btn.set_size_request(WIDTH, HEIGHT)
        self.stop_btn.set_size_request(WIDTH, HEIGHT)
        self.restart_btn.set_size_request(WIDTH, HEIGHT)
        self.suspend_btn.set_size_request(WIDTH, HEIGHT)
        self.logout_btn.set_size_request(WIDTH, HEIGHT)
        self.lock_btn.set_size_request(WIDTH, HEIGHT)
        #
        self.pack_start(self.user_hbox, True, True)
        self.pack_start(self.h_separator_top_ali, True, True)
        self.pack_start(self.switch_btn, True, True)
        self.pack_start(self.switch_separator_bottom_ali, True, True)
        self.pack_start(self.stop_btn, True, True)
        self.pack_start(self.restart_btn, True, True)
        self.pack_start(self.suspend_btn, True, True)
        self.pack_start(self.logout_btn, True, True)

        if self.cmd_dbus.real_name != "Guest":
            self.pack_start(self.lock_btn, True, True)
        set_clickable_cursor(self.user_label_event)

        gobject.timeout_add_seconds(2, self.check_is_livecd)

    def check_is_livecd(self):
        try:
            is_livecd = is_deepin_livecd()
        except:
            return True
        if is_livecd:
            self.switch_btn.set_sensitive(False)
            #self.suspend_btn.set_sensitive(False)
            self.logout_btn.set_sensitive(False)
        else:
            self.switch_btn.set_sensitive(True)
            #self.suspend_btn.set_sensitive(True)
            self.logout_btn.set_sensitive(True)

    def user_label_event_expose_event(self, widget, event):
        cr = widget.window.cairo_create()
        rect = widget.allocation
        size = HEIGHT
        with cairo_disable_antialias(cr):
            cr.set_source_rgb(*color_hex_to_cairo("#d2d2d2"))
            cr.set_line_width(1)
            cr.rectangle(rect.x, rect.y, size, size)
            cr.stroke()
        return True