def update_instrument_control(self, *args):
     ''' Callback for instrument control '''
     instrument = self.instrument[self.instrument_combo.get_active()]
     if self._tuning_tool is not None:
         self.remove(self._tuning_tool)
     if instrument == _('None'):
         self.activity.wave.instrument = None
         if hasattr(self, '_notes_tool'):
             self.insert(self._notes_tool, 2)
         return
     self.remove(self._notes_tool)
     self.activity.wave.instrument = instrument
     # If we are not already in freq. base, switch.
     if not self.activity.wave.get_fft_mode():
         self.activity.timefreq_control()
     # Add a Tuning Combo box for this instrument
     self._tuning_combo = ComboBox()
     self.tuning = [_('All notes')]
     for f in INSTRUMENT_DICT[instrument]:
         self.tuning.append(freq_note(f))
     self._tuning_changed_id = self._tuning_combo.connect(
         'changed', self.update_tuning_control)
     for i, s in enumerate(self.tuning):
         self._tuning_combo.append_item(i, s, None)
     self._tuning_combo.set_active(0)
     if hasattr(self._tuning_combo, 'set_tooltip_text'):
         self._tuning_combo.set_tooltip_text(instrument)
     self._tuning_tool = ToolComboBox(self._tuning_combo)
     self.insert(self._tuning_tool, 1)
     self._tuning_combo.show()
     self._tuning_tool.show()
     self.show_all()
Exemplo n.º 2
0
    def __init__(self, activity):
        gtk.Toolbar.__init__(self)
        voicebar = gtk.Toolbar()
        self._activity = activity
        if not speech.supported:
            return

        self.load_speech_parameters()

        self.sorted_voices = [i for i in speech.voices()]
        self.sorted_voices.sort(self.compare_voices)
        default = 0
        for voice in self.sorted_voices:
            if voice[0] == speech.voice[0]:
                break
            default = default + 1

        # Play button
        self.play_btn = ToggleToolButton('media-playback-start')
        self.play_btn.show()
        self.play_btn.connect('toggled', self.play_cb)
        self.insert(self.play_btn, -1)
        self.play_btn.set_tooltip(_('Play / Pause'))

        self.voice_combo = ComboBox()
        for voice in self.sorted_voices:
            self.voice_combo.append_item(voice, voice[0])
        self.voice_combo.set_active(default)

        self.voice_combo.connect('changed', self.voice_changed_cb)
        combotool = ToolComboBox(self.voice_combo)
        self.insert(combotool, -1)
        combotool.show()

        self.pitchadj = gtk.Adjustment(0, -100, 100, 1, 10, 0)
        pitchbar = gtk.HScale(self.pitchadj)
        pitchbar.set_draw_value(False)
        pitchbar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        pitchbar.set_size_request(150, 15)
        self.pitchadj.set_value(speech.pitch)
        pitchtool = gtk.ToolItem()
        pitchtool.add(pitchbar)
        pitchtool.show()
        self.insert(pitchtool, -1)
        pitchbar.show()

        self.rateadj = gtk.Adjustment(0, -100, 100, 1, 10, 0)
        ratebar = gtk.HScale(self.rateadj)
        ratebar.set_draw_value(False)
        ratebar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        ratebar.set_size_request(150, 15)
        self.rateadj.set_value(speech.rate)
        ratetool = gtk.ToolItem()
        ratetool.add(ratebar)
        ratetool.show()
        self.insert(ratetool, -1)
        ratebar.show()
        self.pitchadj.connect("value_changed", self.pitch_adjusted_cb)
        self.rateadj.connect("value_changed", self.rate_adjusted_cb)
Exemplo n.º 3
0
    def load_toolbar(self):
        self.context = self.emit("load-pango-context")
        self.family_combo = ComboBox()
        family_renderer = gtk.CellRendererText()
        family_renderer.set_property("family-set", True)
        self.family_combo.pack_start(family_renderer)
        self.family_combo.add_attribute(family_renderer, 'text', 0)
        self.family_combo.add_attribute(family_renderer, 'family', 0)
        self.family_model = gtk.ListStore(str)
        monospace_index = 0
        count = 0
        self.faces = {}
        for i in self.context.list_families():
            name = i.get_name()
            monospace_index = count if name == "Monospace" else 0
            count += 1
            self.family_model.append([name])
            family_faces = gtk.ListStore(str, str)
            for face in i.list_faces():
                face_name = face.get_face_name()
                family_faces.append([face_name, "%s %s" % (name, face_name)])
            self.faces[name] = family_faces
        self.family_combo.set_model(self.family_model)
        self.family_combo.set_active(monospace_index)
        self.family_combo.connect("changed", self.family_changed)
        self.family_combo.show()
        self.family_tool_item = ToolComboBox(self.family_combo)
        self.family_tool_item.show()
        self.toolbar.insert(self.family_tool_item, -1)

        self.face_combo = ComboBox()
        face_renderer = gtk.CellRendererText()
        face_renderer.set_property("family-set", True)
        self.face_combo.pack_start(face_renderer)
        self.face_combo.add_attribute(face_renderer, 'text', 0)
        self.face_combo.add_attribute(face_renderer, 'font', 1)
        current_model = self.faces["Monospace"]
        self.face_combo.set_model(current_model)
        self.face_combo.set_active(0)
        self.face_combo.connect("changed", self.face_changed)
        self.face_combo.show()
        self.face_tool_item = ToolComboBox(self.face_combo)
        self.face_tool_item.show()
        self.toolbar.insert(self.face_tool_item, -1)

        self.size_adj = gtk.Adjustment(value=10,
                                       lower=5,
                                       upper=100,
                                       step_incr=1)
        self.size_adj.connect("value-changed", self.size_changed)
        self.size_spin = gtk.SpinButton(self.size_adj)
        self.size_spin.show()
        self.size_spin_item = gtk.ToolItem()
        self.size_spin_item.add(self.size_spin)
        self.size_spin_item.show()
        self.toolbar.insert(self.size_spin_item, -1)

        self.toolbar.show()
    def __init__(self, icon_name, **kwargs):
        gtk.ToolItem.__init__(self, **kwargs)

        self.icon_name = icon_name
        self.set_border_width(style.DEFAULT_PADDING)

        self.combo = ComboBox()
        self.combo.set_focus_on_click(False)
        self.combo.show()

        self.add(self.combo)
Exemplo n.º 5
0
    def __init__(self, abi):
        ComboBox.__init__(self)

        self._abi_handler = abi.connect("font-size", self._font_size_cb)

        self._font_sizes = ["8", "9", "10", "11", "12", "14", "16", "20", "22", "24", "26", "28", "36", "48", "72"]
        self._changed_id = self.connect("changed", self._font_size_changed_cb, abi)

        for i, s in enumerate(self._font_sizes):
            self.append_item(i, s, None)
            if s == "12":
                self.set_active(i)
Exemplo n.º 6
0
    def __init__(self, abi):
        ComboBox.__init__(self)

        self._has_custom_fonts = False
        self._fonts = sorted(abi.get_font_names())
        self._fonts_changed_id = self.connect("changed", self._font_changed_cb, abi)

        for i, f in enumerate(self._fonts):
            self.append_item(i, f, None)
            if f == "Times New Roman":
                self.set_active(i)

        self._abi_handler = abi.connect("font-family", self._font_family_cb)
Exemplo n.º 7
0
    def __init__(self, toolbox, abiword_canvas, parent):
        gtk.Toolbar.__init__(self)

        self._toolbox = toolbox
        self._abiword_canvas = abiword_canvas
        self._parent = parent

        style_label = gtk.Label(_("Style: "))
        style_label.show()
        tool_item_style_label = gtk.ToolItem()
        tool_item_style_label.add(style_label)
        self.insert(tool_item_style_label, -1)
        tool_item_style_label.show()

        self._has_custom_styles = False

        self._style_combo = ComboBox()
        self._styles = [['Heading 1', _('Heading 1')],
                        ['Heading 2', _('Heading 2')],
                        ['Heading 3', _('Heading 3')],
                        ['Heading 4', _('Heading 4')],
                        ['Bullet List', _('Bullet List')],
                        ['Dashed List', _('Dashed List')],
                        ['Numbered List', _('Numbered List')],
                        ['Lower Case List',
                         _('Lower Case List')],
                        ['Upper Case List',
                         _('Upper Case List')],
                        ['Block Text',
                         _('Block Text')], ['Normal', _('Normal')],
                        ['Plain Text', _('Plain Text')]]
        self._style_changed_id = self._style_combo.connect(
            'changed', self._style_changed_cb)
        for i, s in enumerate(self._styles):
            self._style_combo.append_item(i, s[1], None)
            if s[0] == 'Normal':
                self._style_combo.set_active(i)
        tool_item = ToolComboBox(self._style_combo)
        self.insert(tool_item, -1)
        tool_item.show()

        self._abiword_canvas.connect('style-name', self._style_cb)

        ####btn salir del barrido del menu item
        self._btn_barrido_menu = ToolButton()
        self._btn_barrido_menu.set_tooltip(_('Salir \nMenú'))
        self._btn_barrido_menu_id = self._btn_barrido_menu.connect(
            'clicked', self._btn_barrido_menu_cb)
        self.insert(self._btn_barrido_menu, -1)
        self._btn_barrido_menu.set_no_show_all(True)
Exemplo n.º 8
0
    def __init__(self, abi):
        ComboBox.__init__(self)

        self._abi_handler = abi.connect('font-size', self._font_size_cb)

        self._font_sizes = ['8', '9', '10', '11', '12', '14', '16', '20', \
                            '22', '24', '26', '28', '36', '48', '72']
        self._changed_id = self.connect('changed', self._font_size_changed_cb,
                                        abi)

        for i, s in enumerate(self._font_sizes):
            self.append_item(i, s, None)
            if s == '12':
                self.set_active(i)
Exemplo n.º 9
0
    def __init__(self, abi):
        ComboBox.__init__(self)

        self._has_custom_fonts = False
        self._fonts = sorted(abi.get_font_names())
        self._fonts_changed_id = self.connect('changed', self._font_changed_cb,
                                              abi)

        for i, f in enumerate(self._fonts):
            self.append_item(i, f, None)
            if f == 'Times New Roman':
                self.set_active(i)

        self._abi_handler = abi.connect('font-family', self._font_family_cb)
Exemplo n.º 10
0
    def __init__(self, owner):
        gtk.Toolbar.__init__(self)

        self.owner = owner

        self.toolItem = {}

        self.blockBeat = False
        self.beatWheel = []

        btn = RadioToolButton(group=None)
        btn.set_named_icon('beats')
        btn.connect('toggled', self.setBeat, 0)
        btn.set_tooltip(_('Jump To Beat'))
        self.insert(btn, -1)
        self.beatWheel.append(btn)

        for i in range(1, 12):
            btn = RadioToolButton(group=self.beatWheel[0])
            btn.set_named_icon('beats')
            btn.connect('toggled', self.setBeat, i)
            btn.set_tooltip(_('Jump To Beat'))
            self.insert(btn, -1)
            self.beatWheel.append(btn)

        label = gtk.Label(_("Synch to:"))
        self.syncLabel = gtk.ToolItem()
        self.syncLabel.add(label)
        self.insert(self.syncLabel, 0)

        self.comboBox = ComboBox()
        self.comboBox.append_item(1, _("1 Beat"))
        self.comboBox.append_item(2, _("2 Beats"))
        self.comboBox.append_item(3, _("3 Beats"))
        self.comboBox.append_item(4, _("4 Beats"))
        self.comboBox.append_item(5, _("5 Beats"))
        self.comboBox.append_item(6, _("6 Beats"))
        self.comboBox.append_item(7, _("7 Beats"))
        self.comboBox.append_item(8, _("8 Beats"))
        self.comboBox.append_item(9, _("9 Beats"))
        self.comboBox.append_item(10, _("10 Beats"))
        self.comboBox.append_item(11, _("11 Beats"))
        self.comboBox.append_item(12, _("12 Beats"))
        self.comboBox.set_active(4 - 1)  # default 4 beats
        self.comboBox.connect("changed", self.changeSync)
        self.syncBox = ToolComboBox(self.comboBox)
        self.insert(self.syncBox, 1)

        self.show_all()
Exemplo n.º 11
0
    def __init__(self):
        gtk.Toolbar.__init__(self)

        self._mount_point = None

        self._search_entry = iconentry.IconEntry()
        self._search_entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY,
                                              'system-search')
        self._search_entry.connect('activate', self._search_entry_activated_cb)
        self._search_entry.connect('changed', self._search_entry_changed_cb)
        self._search_entry.add_clear_button()
        self._autosearch_timer = None
        self._add_widget(self._search_entry, expand=True)

        self._favorite_button = ToggleToolButton('emblem-favorite')
        self._favorite_button.connect('toggled',
                                      self.__favorite_button_toggled_cb)
        self.insert(self._favorite_button, -1)
        self._favorite_button.show()

        self._what_search_combo = ComboBox()
        self._what_combo_changed_sid = self._what_search_combo.connect(
            'changed', self._combo_changed_cb)
        tool_item = ToolComboBox(self._what_search_combo)
        self.insert(tool_item, -1)
        tool_item.show()

        self._when_search_combo = self._get_when_search_combo()
        tool_item = ToolComboBox(self._when_search_combo)
        self.insert(tool_item, -1)
        tool_item.show()

        self._sorting_button = SortingButton()
        self._sorting_button.connect('clicked',
                                     self.__sorting_button_clicked_cb)
        self.insert(self._sorting_button, -1)
        self._sorting_button.connect('sort-property-changed',
                                     self.__sort_changed_cb)
        self._sorting_button.show()

        # TODO: enable it when the DS supports saving the buddies.
        #self._with_search_combo = self._get_with_search_combo()
        #tool_item = ToolComboBox(self._with_search_combo)
        #self.insert(tool_item, -1)
        #tool_item.show()

        self._query = self._build_query()

        self.refresh_filters()
class InstrumentToolbar(gtk.Toolbar):
    ''' The toolbar for adding new instruments '''
    def __init__(self, activity):
        gtk.Toolbar.__init__(self)
        self.activity = activity
        self.new_instruments = []

        self._name_entry = gtk.Entry()
        self._name_entry.set_text(_('my instrument'))
        self._name_entry_changed_id = self._name_entry.connect(
            'changed', self.update_name_entry)
        if hasattr(self._name_entry, 'set_tooltip_text'):
            self._name_entry.set_tooltip_text(_('Enter instrument name.'))
        self._name_entry.set_width_chars(24)
        self._name_entry.show()
        toolitem = gtk.ToolItem()
        toolitem.add(self._name_entry)
        self.insert(toolitem, -1)
        toolitem.show()

        self._notes_combo = ComboBox()
        n = 0
        for octave in range(9):
            for i in range(len(NOTES)):
                if octave == 0 and i < 9:  # Start with A0
                    continue
                self._notes_combo.append_item(n, note_octave(i, octave), None)
                n += 1
        self._notes_combo.set_active(48)  # A4
        if hasattr(self._notes_combo, 'set_tooltip_text'):
            self._notes_combo.set_tooltip_text(_('Notes'))
        self._notes_tool = ToolComboBox(self._notes_combo)
        self.insert(self._notes_tool, -1)
        self._notes_tool.show()

        self._new_note = ToolButton('list-add')
        self._new_note.show()
        self.insert(self._new_note, -1)
        self._new_note.set_tooltip(_('Add a new note.'))
        self._new_note.connect('clicked', self.new_note_cb)

    def update_name_entry(self, *args):
        ''' Add name to INSTRUMENT_DICT and combo box '''
        # Wait until a note has been added...
        return

    def new_note_cb(self, *args):
        ''' Add a new note to instrument tuning list '''
        name = self._name_entry.get_text()
        if name not in INSTRUMENT_DICT:
            INSTRUMENT_DICT[name] = []
            self.activity.tuning_toolbar.instrument.append(name)
            i = len(self.activity.tuning_toolbar.instrument)
            self.activity.tuning_toolbar.instrument_combo.append_item(
                i, name, None)
            self.new_instruments.append(name)
        i = self._notes_combo.get_active()
        freq = A0 * pow(TWELTHROOT2, i)
        if freq not in INSTRUMENT_DICT[name]:
            INSTRUMENT_DICT[name].append(freq)
Exemplo n.º 13
0
def combo_factory(combo_array, default, tooltip, callback, toolbar):
    '''Factory for making a toolbar combo box'''
    my_combo = ComboBox()
    if hasattr(my_combo, 'set_tooltip_text'):
        my_combo.set_tooltip_text(tooltip)

    my_combo.connect('changed', callback)

    for i, s in enumerate(combo_array):
        my_combo.append_item(i, s, None)

    tool = ToolComboBox(my_combo)
    if hasattr(toolbar, 'insert'):  # the main toolbar
        toolbar.insert(tool, -1)
    else:  # or a secondary toolbar
        toolbar.props.page.insert(tool, -1)
    tool.show()
    my_combo.set_active(default)
    return my_combo
Exemplo n.º 14
0
    def __init__(self, handle):
        gtk.Toolbar.__init__(self)

        self.handle = handle
        self._logger = logging.getLogger("activity-knut")
        self._logger.setLevel(logging.DEBUG)
        # First log handler: outputs to a file
        file_handler = logging.FileHandler("/home/wiktor/code/knut.log")
        file_formatter = logging.Formatter("%(message)s")
        file_handler.setFormatter(file_formatter)
        self._logger.addHandler(file_handler)

        # Tytuł pola tekstowego
        self.add_widget(gtk.Label("Kategoria: "))

        # Pole tekstowe
        self.test_type = ComboBox()
        for id, name in BrowseToolbar.TEST_CATEGORIES.items():
            self.test_type.append_item(id, name)
        self.test_type.set_active(0)
        self.add_widget(self.test_type)

        # Separator
        #        separator = gtk.SeparatorToolItem()
        #        separator.set_draw(True)
        #        separator.set_size_request(50,25)
        #        self.add_widget(separator)

        # Tytuł pola tekstowego
        self.add_widget(gtk.Label(" Szukaj w tytule: "))

        # Pole tekstowe
        self.search_entry = gtk.Entry()
        self.search_entry.set_size_request(100, 25)
        #        self.pass_entry.set_text('123123')
        self.add_widget(self.search_entry)

        # Przycisk pobierania
        download_button = ToolButton("download")
        download_button.set_tooltip("Przeglądaj testy")
        download_button.connect("clicked", self.list_download)
        self.add_widget(download_button)

        separator2 = gtk.SeparatorToolItem()
        separator2.set_draw(True)
        separator2.set_size_request(50, 25)
        self.add_widget(separator2)

        self.add_widget(gtk.Label("Hasło: "))
        self.pass_entry = gtk.Entry()
        self.pass_entry.set_size_request(100, 25)
        #        self.pass_entry.set_text('123123')
        self.add_widget(self.pass_entry)
    def __init__(self, activity):
        gtk.Toolbar.__init__(self)
        self.activity = activity
        self.new_instruments = []

        self._name_entry = gtk.Entry()
        self._name_entry.set_text(_('my instrument'))
        self._name_entry_changed_id = self._name_entry.connect(
            'changed', self.update_name_entry)
        if hasattr(self._name_entry, 'set_tooltip_text'):
            self._name_entry.set_tooltip_text(_('Enter instrument name.'))
        self._name_entry.set_width_chars(24)
        self._name_entry.show()
        toolitem = gtk.ToolItem()
        toolitem.add(self._name_entry)
        self.insert(toolitem, -1)
        toolitem.show()

        self._notes_combo = ComboBox()
        n = 0
        for octave in range(9):
            for i in range(len(NOTES)):
                if octave == 0 and i < 9:  # Start with A0
                    continue
                self._notes_combo.append_item(n, note_octave(i, octave), None)
                n += 1
        self._notes_combo.set_active(48)  # A4
        if hasattr(self._notes_combo, 'set_tooltip_text'):
            self._notes_combo.set_tooltip_text(_('Notes'))
        self._notes_tool = ToolComboBox(self._notes_combo)
        self.insert(self._notes_tool, -1)
        self._notes_tool.show()

        self._new_note = ToolButton('list-add')
        self._new_note.show()
        self.insert(self._new_note, -1)
        self._new_note.set_tooltip(_('Add a new note.'))
        self._new_note.connect('clicked', self.new_note_cb)
Exemplo n.º 16
0
    def __init__(self):
        gtk.Toolbar.__init__(self)

        self._mount_point = None

        self._search_entry = iconentry.IconEntry()
        self._search_entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY,
                                              'system-search')
        self._search_entry.connect('activate', self._search_entry_activated_cb)
        self._search_entry.connect('changed', self._search_entry_changed_cb)
        self._search_entry.add_clear_button()
        self._autosearch_timer = None
        self._add_widget(self._search_entry, expand=True)

        self._favorite_button = ToggleToolButton('emblem-favorite')
        self._favorite_button.connect('toggled',
                                      self.__favorite_button_toggled_cb)
        self.insert(self._favorite_button, -1)
        self._favorite_button.show()

        self._what_search_combo = ComboBox()
        self._what_combo_changed_sid = self._what_search_combo.connect(
                'changed', self._combo_changed_cb)
        tool_item = ToolComboBox(self._what_search_combo)
        self.insert(tool_item, -1)
        tool_item.show()

        self._when_search_combo = self._get_when_search_combo()
        tool_item = ToolComboBox(self._when_search_combo)
        self.insert(tool_item, -1)
        tool_item.show()

        self._sorting_button = SortingButton()
        self._sorting_button.connect('clicked',
                                     self.__sorting_button_clicked_cb)
        self.insert(self._sorting_button, -1)
        self._sorting_button.connect('sort-property-changed',
                                     self.__sort_changed_cb)
        self._sorting_button.show()

        # TODO: enable it when the DS supports saving the buddies.
        #self._with_search_combo = self._get_with_search_combo()
        #tool_item = ToolComboBox(self._with_search_combo)
        #self.insert(tool_item, -1)
        #tool_item.show()

        self._query = self._build_query()

        self.refresh_filters()
Exemplo n.º 17
0
    def __init__(self, owner):
        gtk.Toolbar.__init__(self)

        self.owner = owner

        self.toolItem = {}

        self.blockBeat = False
        self.beatWheel = []

        btn = RadioToolButton(group=None)
        btn.set_named_icon('beats')
        btn.connect('toggled', self.setBeat, 0)
        btn.set_tooltip(_('Jump To Beat'))
        self.insert(btn, -1)
        self.beatWheel.append(btn)

        for i in range(1, 12):
            btn = RadioToolButton(group=self.beatWheel[0])
            btn.set_named_icon('beats')
            btn.connect('toggled', self.setBeat, i)
            btn.set_tooltip(_('Jump To Beat'))
            self.insert(btn, -1)
            self.beatWheel.append(btn)

        label = gtk.Label(_("Synch to:"))
        self.syncLabel = gtk.ToolItem()
        self.syncLabel.add(label)
        self.insert(self.syncLabel, 0)

        self.comboBox = ComboBox()
        self.comboBox.append_item(1, _("1 Beat"))
        self.comboBox.append_item(2, _("2 Beats"))
        self.comboBox.append_item(3, _("3 Beats"))
        self.comboBox.append_item(4, _("4 Beats"))
        self.comboBox.append_item(5, _("5 Beats"))
        self.comboBox.append_item(6, _("6 Beats"))
        self.comboBox.append_item(7, _("7 Beats"))
        self.comboBox.append_item(8, _("8 Beats"))
        self.comboBox.append_item(9, _("9 Beats"))
        self.comboBox.append_item(10, _("10 Beats"))
        self.comboBox.append_item(11, _("11 Beats"))
        self.comboBox.append_item(12, _("12 Beats"))
        self.comboBox.set_active(4 - 1)  # default 4 beats
        self.comboBox.connect("changed", self.changeSync)
        self.syncBox = ToolComboBox(self.comboBox)
        self.insert(self.syncBox, 1)

        self.show_all()
Exemplo n.º 18
0
class ToolComboBox(gtk.ToolItem):
    __gproperties__ = {
        'label-text' : (str, None, None, None,
                        gobject.PARAM_WRITABLE),
    }

    def __init__(self, combo=None, **kwargs):
        self.label = None
        self._label_text = ''

        gobject.GObject.__init__(self, **kwargs)

        self.set_border_width(style.DEFAULT_PADDING)

        hbox = gtk.HBox(False, style.DEFAULT_SPACING)

        self.label = gtk.Label(self._label_text)
        hbox.pack_start(self.label, False)
        self.label.show()

        if combo:
            self.combo = combo
        else:
            self.combo = ComboBox()

        hbox.pack_start(self.combo)
        self.combo.show()

        self.add(hbox)
        hbox.show()

    def do_set_property(self, pspec, value):
        if pspec.name == 'label-text':
            self._label_text = value
            if self.label:
                self.label.set_text(self._label_text)
Exemplo n.º 19
0
class ToolComboBox(gtk.ToolItem):

    __gproperties__ = {
        'label-text': (str, None, None, None, gobject.PARAM_WRITABLE),
    }

    def __init__(self, combo=None, **kwargs):
        self.label = None
        self._label_text = ''

        gobject.GObject.__init__(self, **kwargs)

        self.set_border_width(style.DEFAULT_PADDING)

        hbox = gtk.HBox(False, style.DEFAULT_SPACING)

        self.label = gtk.Label(self._label_text)
        hbox.pack_start(self.label, False)
        self.label.show()

        if combo:
            self.combo = combo
        else:
            self.combo = ComboBox()

        hbox.pack_start(self.combo)
        self.combo.show()

        self.add(hbox)
        hbox.show()

    def do_set_property(self, pspec, value):
        if pspec.name == 'label-text':
            self._label_text = value
            if self.label:
                self.label.set_text(self._label_text)
Exemplo n.º 20
0
    def __init__(self, combo=None, **kwargs):
        self.label = None
        self._label_text = ''

        gobject.GObject.__init__(self, **kwargs)

        self.set_border_width(style.DEFAULT_PADDING)

        hbox = gtk.HBox(False, style.DEFAULT_SPACING)

        self.label = gtk.Label(self._label_text)
        hbox.pack_start(self.label, False)
        self.label.show()

        if combo:
            self.combo = combo
        else:
            self.combo = ComboBox()

        hbox.pack_start(self.combo)
        self.combo.show()

        self.add(hbox)
        hbox.show()
Exemplo n.º 21
0
class IconComboBox(gtk.ToolItem):
    def __init__(self, icon_name, **kwargs):
        gtk.ToolItem.__init__(self, **kwargs)

        self.icon_name = icon_name
        self.set_border_width(style.DEFAULT_PADDING)

        self.combo = ComboBox()
        self.combo.set_focus_on_click(False)
        self.combo.show()

        self.add(self.combo)

    def append_item(self, i, text):
        self.combo.append_item(i, text, icon_name=self.icon_name)
Exemplo n.º 22
0
    def __init__(self, combo=None, **kwargs):
        self.label = None
        self._label_text = ''

        gobject.GObject.__init__(self, **kwargs)

        self.set_border_width(style.DEFAULT_PADDING)

        hbox = gtk.HBox(False, style.DEFAULT_SPACING)

        self.label = gtk.Label(self._label_text)
        hbox.pack_start(self.label, False)
        self.label.show()

        if combo:
            self.combo = combo
        else:
            self.combo = ComboBox()

        hbox.pack_start(self.combo)
        self.combo.show()

        self.add(hbox)
        hbox.show()
class SensorToolbar(gtk.Toolbar):
    """ The toolbar for resitance and voltage sensors """
    __gsignals__ = {
        'add-media': (gobject.SIGNAL_RUN_FIRST, None, [object]),
        'add-opened': (gobject.SIGNAL_RUN_FIRST, None, [object])
    }

    def __init__(self, activity):
        """ By default, start with resistance mode """

        gtk.Toolbar.__init__(self)

        self.mode = 'resistance'

        self._STR_BASIC = \
        _("Sensors, DC (connect sensor to pink 'Mic In' on left side of XO)") \
        + ' '
        self._STR_R = _('Bias/Offset Enabled') + ' ' + _('Ohms') + ' '
        self._STR_V = _('Bias/Offset Disabled') + ' ' + _('Volts') + ' '
        self._STR_I = ' ' + _('Invert') + ' '

        self.string_for_textbox = ""

        self.activity = activity
        self.activity.audiograb.set_sensor(self)

        # Set up Resistance Button
        if self.activity.has_toolbarbox:
            self.resistance = ToolButton('bias-on')
        else:
            self.resistance = ToolButton('bias-on2')
        self.insert(self.resistance, -1)
        self.resistance.show()
        self.resistance.set_tooltip(_('Resistance Sensor'))
        self.resistance.connect('clicked', self.set_resistance_voltage_mode,
                                'resistance')

        # Set up Voltage Button
        self.voltage = ToolButton('bias-off')
        self.insert(self.voltage, -1)
        self.voltage.set_tooltip(_('Voltage Sensor'))
        self.voltage.connect('clicked', self.set_resistance_voltage_mode,
                             'voltage')

        # Set up Invert Button
        self._invert = ToolButton('invert')
        self.insert(self._invert, -1)
        self._invert.set_tooltip(_('Invert'))
        self._invert.connect('clicked', self._invert_control_cb)
        self.activity.wave.set_invert_state(False)

        separator = gtk.SeparatorToolItem()
        separator.props.draw = True
        self.insert(separator, -1)

        self.audiobutton = ToolButton('add-icon')
        self.insert(self.audiobutton, -1)
        self.audiobutton.show()
        self.audiobutton.set_tooltip('Close Sound')
        self.audiobutton.connect('clicked', self.addAudio)
        self.connect('add-media', self.addThisAudio)

        self.insert(separator, -1)
        self.insert(separator, -1)

        self.openedbutton = ToolButton('delete-icon')
        self.insert(self.openedbutton, -1)
        self.openedbutton.show()
        self.openedbutton.set_tooltip('Open Sound')
        self.openedbutton.connect('clicked', self.addOpenedAudio)
        self.connect('add-opened', self.addThisOpenedAudio)

        self.insert(separator, -1)
        self.insert(separator, -1)

        # Set up Logging Interval combo box
        self.loginterval_img = gtk.Image()
        self.loginterval_img.set_from_file(ICONS_DIR + '/sample_rate.svg')
        self.loginterval_img_tool = gtk.ToolItem()
        self.loginterval_img_tool.add(self.loginterval_img)
        self.insert(self.loginterval_img_tool, -1)

        self._loginterval_combo = ComboBox()
        self.interval = [
            _('1/10 second'),
            _('1 second'),
            _('30 seconds'),
            _('5 minutes'),
            _('30 minutes')
        ]

        if hasattr(self._loginterval_combo, 'set_tooltip_text'):
            self._loginterval_combo.set_tooltip_text(_('Sampling interval'))

        self._interval_changed_id = self._loginterval_combo.connect(
            "changed", self.loginterval_control)

        for i, s in enumerate(self.interval):
            self._loginterval_combo.append_item(i, s, None)
            if s == _('1 second'):
                self._loginterval_combo.set_active(i)

        self._loginterval_tool = ToolComboBox(self._loginterval_combo)
        self.insert(self._loginterval_tool, -1)
        self.logginginterval_status = '1 second'

        # Set up Logging/Stop Logging Button
        self._record = ToolButton('media-record')
        self.insert(self._record, -1)
        self._record.set_tooltip(_('Start Recording'))
        self._record.connect('clicked', self.record_control)

        self.show_all()

    def addAudio(self, button):
        #self.activity.showFileLoadBlocker(True)
        fp = FilePicker()
        dOb = fp.show()
        if (dOb != None):
            if (dOb.file_path != None):
                self.emit('add-media', dOb)
        #self.activity.showFileLoadBlocker(False)

    def addOpenedAudio(self, button):
        fp = FilePicker()
        dOb = fp.show()
        if (dOb != None):
            if (dOb.file_path != None):
                self.emit('add-opened', dOb)

    def addThisAudio(self, ot, datastoreOb):
        self.activity.closedSound = datastoreOb
        #self.activity.playsound.setLocation("file://"+datastoreOb.file_path)
        #self.activity.playsound.play()

    def addThisOpenedAudio(self, ot, datastoreOb):
        self.activity.openedSound = datastoreOb

    def set_sample_value(self, label=None):
        """ Write a sample value to the textbox """
        gtk.threads_enter()
        self._update_string_for_textbox(label)
        gtk.threads_leave()
        return

    def record_control(self, data=None):
        """Depending upon the selected interval, does either
        a logging session, or just logs the current buffer"""

        if not self.activity.LOGGING_IN_SESSION:
            Xscale = (1.00 / self.activity.audiograb.get_sampling_rate())
            Yscale = 0.0
            interval = self.interval_convert()
            username = self.activity.nick
            print "calling start new session"
            self.activity.ji.start_new_session(username, Xscale, Yscale,
                                               _(self.logginginterval_status))
            self.activity.audiograb.set_logging_params(True, interval, False)
            self.activity.LOGGING_IN_SESSION = True
            self._record.set_icon('record-stop')
            self._record.show()
            self._record.set_tooltip(_('Stop Recording'))
        else:
            self.activity.audiograb.set_logging_params(False)
            self.activity.LOGGING_IN_SESSION = False
            self._record.set_icon('media-record')
            self._record.show()
            self._record.set_tooltip(_('Start Recording'))

    def interval_convert(self):
        """Converts interval string to an integer that denotes the number
        of times the audiograb buffer must be called before a value is written.
        When set to 0, the whole of current buffer will be written"""
        interval_dictionary = {
            '1/10 second': 0.1,
            '1 second': 1,
            '30 seconds': 30,
            '5 minutes': 300,
            '30 minutes': 1800
        }
        try:
            return interval_dictionary[self.logginginterval_status]
        except ValueError:
            logging.error('logging interval status = %s' %\
                              (str(self.logginginterval_status)))
            return 0

    def loginterval_control(self, combobox):
        """ Callback from the Logging Interval Combo box: sets status """
        if self._loginterval_combo.get_active() != -1:
            intervals = [
                '1/10 second', '1 second', '30 seconds', '5 minutes',
                '30 minutes'
            ]
            self.logginginterval_status = \
                              intervals[self._loginterval_combo.get_active()]

    def set_resistance_voltage_mode(self, data=None, mode_to_set='resistance'):
        """ Callback for Resistance/Voltage Buttons """

        # Make sure the current context is for sensor capture.
        if self.activity.CONTEXT != 'sensor':
            self.activity.set_sensor_context()

        self.set_mode(mode_to_set)
        if mode_to_set == 'resistance':
            self.resistance.set_icon('bias-on2')
            self.voltage.set_icon('bias-off')
            self.resistance.show()
            self.voltage.show()
            self._update_string_for_textbox()
            if self.activity.has_toolbarbox:
                self.activity.label_button.set_icon('bias-on2')
                self.activity.label_button.set_tooltip(_('Resistance Sensor'))
        elif mode_to_set == 'voltage':
            self.resistance.set_icon('bias-on')
            self.voltage.set_icon('bias-off2')
            self.resistance.show()
            self.voltage.show()
            self._update_string_for_textbox()
            if self.activity.has_toolbarbox:
                self.activity.label_button.set_icon('bias-off2')
                self.activity.label_button.set_tooltip(_('Voltage Sensor'))
        else:
            logging.error('unknown mode %s' % (mode_to_set))
        if self.activity.has_toolbarbox:
            self.activity.sound_toolbar.time.set_icon('domain-time')
            self.activity.sound_toolbar.freq.set_icon('domain-freq')
        return False

    def _invert_control_cb(self, data=None):
        """ Callback for Invert Button """
        if self.activity.wave.get_invert_state():
            self.activity.wave.set_invert_state(False)
            self._invert.set_icon('invert')
            self._invert.show()
        else:
            self.activity.wave.set_invert_state(True)
            self._invert.set_icon('invert2')
            self._invert.show()
        self._update_string_for_textbox()
        return False

    def set_mode(self, mode='resistance'):
        """ Set the mixer settings to match the current mode. """
        self.mode = mode
        self.activity.audiograb.set_sensor_type(self.mode)
        return

    def context_off(self):
        """ Called when sensor toolbar is no longer selected. """
        self.activity.audiograb.pause_grabbing()

    def context_on(self):
        """ Called when sensor toolbar is selected. """
        self.activity.audiograb.resume_grabbing()
        self.activity.audiograb.set_sensor_type(self.mode)
        self._update_string_for_textbox()
        self.activity.wave.set_trigger(self.activity.wave.TRIGGER_NONE)
        return False

    def _update_string_for_textbox(self, value=None):
        """ Update the status field at the bottom of the canvas. """
        self.string_for_textbox = ""
        self.string_for_textbox += (self._STR_BASIC + "\n")
        if self.mode == 'resistance':
            self.string_for_textbox += self._STR_R
        else:
            self.string_for_textbox += self._STR_V
        if self.activity.wave.get_invert_state():
            self.string_for_textbox += self._STR_I
        if value is not None:
            self.string_for_textbox += '\t(%s)' % (str(value))
        self.activity.text_box.set_data_params(0, self.string_for_textbox)
Exemplo n.º 24
0
 def _get_when_search_combo(self):
     when_search = ComboBox()
     when_search.append_item(_ACTION_ANYTIME, _('Anytime'))
     when_search.append_separator()
     when_search.append_item(_ACTION_TODAY, _('Today'))
     when_search.append_item(_ACTION_SINCE_YESTERDAY,
                                   _('Since yesterday'))
     # TRANS: Filter entries modified during the last 7 days.
     when_search.append_item(_ACTION_PAST_WEEK, _('Past week'))
     # TRANS: Filter entries modified during the last 30 days.
     when_search.append_item(_ACTION_PAST_MONTH, _('Past month'))
     # TRANS: Filter entries modified during the last 356 days.
     when_search.append_item(_ACTION_PAST_YEAR, _('Past year'))
     when_search.set_active(0)
     when_search.connect('changed', self._combo_changed_cb)
     return when_search
Exemplo n.º 25
0
class SpeechToolbar(gtk.Toolbar):

    def __init__(self, activity):
        gtk.Toolbar.__init__(self)
        voicebar = gtk.Toolbar()
        self._activity = activity
        if not speech.supported:
            return

        self.load_speech_parameters()

        self.sorted_voices = [i for i in speech.voices()]
        self.sorted_voices.sort(self.compare_voices)
        default = 0
        for voice in self.sorted_voices:
            if voice[0] == speech.voice[0]:
                break
            default = default + 1

        # Play button
        self.play_btn = ToggleToolButton('media-playback-start')
        self.play_btn.show()
        self.play_btn.connect('toggled', self.play_cb)
        self.insert(self.play_btn, -1)
        self.play_btn.set_tooltip(_('Play / Pause'))

        self.voice_combo = ComboBox()
        for voice in self.sorted_voices:
            self.voice_combo.append_item(voice, voice[0])
        self.voice_combo.set_active(default)

        self.voice_combo.connect('changed', self.voice_changed_cb)
        combotool = ToolComboBox(self.voice_combo)
        self.insert(combotool, -1)
        combotool.show()

        self.pitchadj = gtk.Adjustment(0, -100, 100, 1, 10, 0)
        pitchbar = gtk.HScale(self.pitchadj)
        pitchbar.set_draw_value(False)
        pitchbar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        pitchbar.set_size_request(150, 15)
        self.pitchadj.set_value(speech.pitch)
        pitchtool = gtk.ToolItem()
        pitchtool.add(pitchbar)
        pitchtool.show()
        self.insert(pitchtool, -1)
        pitchbar.show()

        self.rateadj = gtk.Adjustment(0, -100, 100, 1, 10, 0)
        ratebar = gtk.HScale(self.rateadj)
        ratebar.set_draw_value(False)
        ratebar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        ratebar.set_size_request(150, 15)
        self.rateadj.set_value(speech.rate)
        ratetool = gtk.ToolItem()
        ratetool.add(ratebar)
        ratetool.show()
        self.insert(ratetool, -1)
        ratebar.show()
        self.pitchadj.connect("value_changed", self.pitch_adjusted_cb)
        self.rateadj.connect("value_changed", self.rate_adjusted_cb)

    def compare_voices(self,  a,  b):
        if a[0].lower() == b[0].lower():
            return 0
        if a[0] .lower() < b[0].lower():
            return -1
        if a[0] .lower() > b[0].lower():
            return 1

    def voice_changed_cb(self, combo):
        speech.voice = combo.props.value
        speech.say(speech.voice[0])
        self.save_speech_parameters()

    def pitch_adjusted_cb(self, get):
        speech.pitch = int(get.value)
        speech.say(_("pitch adjusted"))
        self.save_speech_parameters()

    def rate_adjusted_cb(self, get):
        speech.rate = int(get.value)
        speech.say(_("rate adjusted"))
        self.save_speech_parameters()

    def load_speech_parameters(self):
        speech_parameters = {}
        data_path = os.path.join(self._activity.get_activity_root(), 'data')
        data_file_name = os.path.join(data_path, 'speech_params.json')
        if os.path.exists(data_file_name):
            f = open(data_file_name, 'r')
            try:
                speech_parameters = simplejson.load(f)
                speech.pitch = speech_parameters['pitch']
                speech.rate = speech_parameters['rate']
                speech.voice = speech_parameters['voice']
            finally:
                f.close()

    def save_speech_parameters(self):
        speech_parameters = {}
        speech_parameters['pitch'] = speech.pitch
        speech_parameters['rate'] = speech.rate
        speech_parameters['voice'] = speech.voice
        data_path = os.path.join(self._activity.get_activity_root(), 'data')
        data_file_name = os.path.join(data_path, 'speech_params.json')
        f = open(data_file_name, 'w')
        try:
            simplejson.dump(speech_parameters, f)
        finally:
            f.close()

    def play_cb(self, widget):
        if widget.get_active():
            self.play_btn.set_named_icon('media-playback-pause')
            if speech.is_stopped():
                speech.play(self._activity._view.get_marked_words())
        else:
            self.play_btn.set_named_icon('media-playback-start')
            speech.stop()
Exemplo n.º 26
0
    def _get_with_search_combo(self):
        with_search = ComboBox()
        with_search.append_item(_ACTION_EVERYBODY, _('Anyone'))
        with_search.append_separator()
        with_search.append_item(_ACTION_MY_FRIENDS, _('My friends'))
        with_search.append_item(_ACTION_MY_CLASS, _('My class'))
        with_search.append_separator()

        # TODO: Ask the model for buddies.
        with_search.append_item(3, 'Dan', 'theme:xo')

        with_search.set_active(0)
        with_search.connect('changed', self._combo_changed_cb)
        return with_search
Exemplo n.º 27
0
class BeatToolbar(gtk.Toolbar):

    def __init__(self, owner):
        gtk.Toolbar.__init__(self)

        self.owner = owner

        self.toolItem = {}

        self.blockBeat = False
        self.beatWheel = []

        btn = RadioToolButton(group=None)
        btn.set_named_icon('beats')
        btn.connect('toggled', self.setBeat, 0)
        btn.set_tooltip(_('Jump To Beat'))
        self.insert(btn, -1)
        self.beatWheel.append(btn)

        for i in range(1, 12):
            btn = RadioToolButton(group=self.beatWheel[0])
            btn.set_named_icon('beats')
            btn.connect('toggled', self.setBeat, i)
            btn.set_tooltip(_('Jump To Beat'))
            self.insert(btn, -1)
            self.beatWheel.append(btn)

        label = gtk.Label(_("Synch to:"))
        self.syncLabel = gtk.ToolItem()
        self.syncLabel.add(label)
        self.insert(self.syncLabel, 0)

        self.comboBox = ComboBox()
        self.comboBox.append_item(1, _("1 Beat"))
        self.comboBox.append_item(2, _("2 Beats"))
        self.comboBox.append_item(3, _("3 Beats"))
        self.comboBox.append_item(4, _("4 Beats"))
        self.comboBox.append_item(5, _("5 Beats"))
        self.comboBox.append_item(6, _("6 Beats"))
        self.comboBox.append_item(7, _("7 Beats"))
        self.comboBox.append_item(8, _("8 Beats"))
        self.comboBox.append_item(9, _("9 Beats"))
        self.comboBox.append_item(10, _("10 Beats"))
        self.comboBox.append_item(11, _("11 Beats"))
        self.comboBox.append_item(12, _("12 Beats"))
        self.comboBox.set_active(4 - 1)  # default 4 beats
        self.comboBox.connect("changed", self.changeSync)
        self.syncBox = ToolComboBox(self.comboBox)
        self.insert(self.syncBox, 1)

        self.show_all()

    #def _add_palette(self, widget, palette, position = Palette.DEFAULT):
    def _add_palette(self, widget, palette):
        widget._palette = palette
        widget._palette.props.invoker = WidgetInvoker(widget)
        #widget._palette.set_property("position", position)

    def _add_tooltip(self, widget, tooltip):
        #self._add_palette(widget, Palette(tooltip), Palette.DEFAULT)
        self._add_palette(widget, Palette(tooltip))

    def _insert_widget(self, widget, pos):
        self.toolItem[widget] = gtk.ToolItem()
        self.toolItem[widget].add(widget)
        self.insert(self.toolItem[widget], pos)

    def _insert_separator(self, expand=False):
        separator = gtk.SeparatorToolItem()
        separator.set_draw(False)
        separator.set_expand(expand)
        self.insert(separator, -1)

    def setBeat(self, widget, beat):
        if not self.blockBeat and widget.get_active():
            self.owner._setBeat(beat)

    def updateBeatWheel(self, beat):
        self.blockBeat = True
        self.beatWheel[beat].set_active(True)
        self.blockBeat = False

    def setSyncBeats(self, beats):
        self.comboBox.set_active(beats - 1)

    def changeSync(self, widget):
        beats = widget.get_active() + 1
        for i in range(beats):
            self.beatWheel[i].show()
        for i in range(beats, 12):
            self.beatWheel[i].hide()

        self.owner._setSyncBeats(beats)
Exemplo n.º 28
0
class BrowseToolbar(gtk.Toolbar):

    TEST_CATEGORIES = {0: "Różności", 1: "Matematyka", 2: "Informatyka", 3: "Geografia", 4: "Historia"}

    def __init__(self, handle):
        gtk.Toolbar.__init__(self)

        self.handle = handle
        self._logger = logging.getLogger("activity-knut")
        self._logger.setLevel(logging.DEBUG)
        # First log handler: outputs to a file
        file_handler = logging.FileHandler("/home/wiktor/code/knut.log")
        file_formatter = logging.Formatter("%(message)s")
        file_handler.setFormatter(file_formatter)
        self._logger.addHandler(file_handler)

        # Tytuł pola tekstowego
        self.add_widget(gtk.Label("Kategoria: "))

        # Pole tekstowe
        self.test_type = ComboBox()
        for id, name in BrowseToolbar.TEST_CATEGORIES.items():
            self.test_type.append_item(id, name)
        self.test_type.set_active(0)
        self.add_widget(self.test_type)

        # Separator
        #        separator = gtk.SeparatorToolItem()
        #        separator.set_draw(True)
        #        separator.set_size_request(50,25)
        #        self.add_widget(separator)

        # Tytuł pola tekstowego
        self.add_widget(gtk.Label(" Szukaj w tytule: "))

        # Pole tekstowe
        self.search_entry = gtk.Entry()
        self.search_entry.set_size_request(100, 25)
        #        self.pass_entry.set_text('123123')
        self.add_widget(self.search_entry)

        # Przycisk pobierania
        download_button = ToolButton("download")
        download_button.set_tooltip("Przeglądaj testy")
        download_button.connect("clicked", self.list_download)
        self.add_widget(download_button)

        separator2 = gtk.SeparatorToolItem()
        separator2.set_draw(True)
        separator2.set_size_request(50, 25)
        self.add_widget(separator2)

        self.add_widget(gtk.Label("Hasło: "))
        self.pass_entry = gtk.Entry()
        self.pass_entry.set_size_request(100, 25)
        #        self.pass_entry.set_text('123123')
        self.add_widget(self.pass_entry)

    def add_widget(self, widget):
        tool_item = gtk.ToolItem()
        tool_item.add(widget)
        widget.show()
        self.insert(tool_item, -1)
        tool_item.show()

    def list_download(self, widget):
        self._logger.debug("list_download")
        category_id = self.test_type.value
        category = BrowseToolbar.TEST_CATEGORIES[category_id]
        self._logger.debug("%s" % (category))
        search = self.search_entry.get_text()
        self._logger.debug(search)
        data = {"cat": category, "search": search}
        url_values = urllib.urlencode(data)
        url = self.handle.server + "/test_list_all/?" + url_values
        self._logger.debug(url)
        response = urllib2.urlopen(url)
        tests_xml = response.read()
        self.tests_list = objectify.fromstring(tests_xml)
        self._logger.debug("xml:%s" % tests_xml)
        self._logger.debug("objectified:%s" % self.tests_list.countchildren())
        if self.tests_list.countchildren() > 0:
            tests_browser = TestsBrowser(self.tests_list, self.handle)
            self.handle.set_canvas(tests_browser)
            tests_browser.show_all()
        else:
            self.handle.set_canvas(gtk.Label())
            self.handle.show_alert(
                title="Pobieranie listy testów", msg="Na serwerze nie testów z wybranej kategorii, spróbuj inną"
            )
Exemplo n.º 29
0
    def _get_with_search_combo(self):
        with_search = ComboBox()
        with_search.append_item(_ACTION_EVERYBODY, _('Anyone'))
        with_search.append_separator()
        with_search.append_item(_ACTION_MY_FRIENDS, _('My friends'))
        with_search.append_item(_ACTION_MY_CLASS, _('My class'))
        with_search.append_separator()

        # TODO: Ask the model for buddies.
        with_search.append_item(3, 'Dan', 'theme:xo')

        with_search.set_active(0)
        with_search.connect('changed', self._combo_changed_cb)
        return with_search
Exemplo n.º 30
0
class BeatToolbar(gtk.Toolbar):
    def __init__(self, owner):
        gtk.Toolbar.__init__(self)

        self.owner = owner

        self.toolItem = {}

        self.blockBeat = False
        self.beatWheel = []

        btn = RadioToolButton(group=None)
        btn.set_named_icon('beats')
        btn.connect('toggled', self.setBeat, 0)
        btn.set_tooltip(_('Jump To Beat'))
        self.insert(btn, -1)
        self.beatWheel.append(btn)

        for i in range(1, 12):
            btn = RadioToolButton(group=self.beatWheel[0])
            btn.set_named_icon('beats')
            btn.connect('toggled', self.setBeat, i)
            btn.set_tooltip(_('Jump To Beat'))
            self.insert(btn, -1)
            self.beatWheel.append(btn)

        label = gtk.Label(_("Synch to:"))
        self.syncLabel = gtk.ToolItem()
        self.syncLabel.add(label)
        self.insert(self.syncLabel, 0)

        self.comboBox = ComboBox()
        self.comboBox.append_item(1, _("1 Beat"))
        self.comboBox.append_item(2, _("2 Beats"))
        self.comboBox.append_item(3, _("3 Beats"))
        self.comboBox.append_item(4, _("4 Beats"))
        self.comboBox.append_item(5, _("5 Beats"))
        self.comboBox.append_item(6, _("6 Beats"))
        self.comboBox.append_item(7, _("7 Beats"))
        self.comboBox.append_item(8, _("8 Beats"))
        self.comboBox.append_item(9, _("9 Beats"))
        self.comboBox.append_item(10, _("10 Beats"))
        self.comboBox.append_item(11, _("11 Beats"))
        self.comboBox.append_item(12, _("12 Beats"))
        self.comboBox.set_active(4 - 1)  # default 4 beats
        self.comboBox.connect("changed", self.changeSync)
        self.syncBox = ToolComboBox(self.comboBox)
        self.insert(self.syncBox, 1)

        self.show_all()

    #def _add_palette(self, widget, palette, position = Palette.DEFAULT):
    def _add_palette(self, widget, palette):
        widget._palette = palette
        widget._palette.props.invoker = WidgetInvoker(widget)
        #widget._palette.set_property("position", position)

    def _add_tooltip(self, widget, tooltip):
        #self._add_palette(widget, Palette(tooltip), Palette.DEFAULT)
        self._add_palette(widget, Palette(tooltip))

    def _insert_widget(self, widget, pos):
        self.toolItem[widget] = gtk.ToolItem()
        self.toolItem[widget].add(widget)
        self.insert(self.toolItem[widget], pos)

    def _insert_separator(self, expand=False):
        separator = gtk.SeparatorToolItem()
        separator.set_draw(False)
        separator.set_expand(expand)
        self.insert(separator, -1)

    def setBeat(self, widget, beat):
        if not self.blockBeat and widget.get_active():
            self.owner._setBeat(beat)

    def updateBeatWheel(self, beat):
        self.blockBeat = True
        self.beatWheel[beat].set_active(True)
        self.blockBeat = False

    def setSyncBeats(self, beats):
        self.comboBox.set_active(beats - 1)

    def changeSync(self, widget):
        beats = widget.get_active() + 1
        for i in range(beats):
            self.beatWheel[i].show()
        for i in range(beats, 12):
            self.beatWheel[i].hide()

        self.owner._setSyncBeats(beats)
Exemplo n.º 31
0
    def __init__(self):
        gtk.Toolbar.__init__(self)
        voicebar = gtk.Toolbar()
        self.activity = None
        self.sorted_voices = [i for i in speech.voices()]
        self.sorted_voices.sort(self.compare_voices)
        default = 0
        for voice in self.sorted_voices:
            if voice[0] == 'default':
                break
            default = default + 1

        # Play button Image
        play_img = gtk.Image()
        play_img.show()
        play_img.set_from_icon_name('media-playback-start',
                gtk.ICON_SIZE_LARGE_TOOLBAR)

        # Pause button Image
        pause_img = gtk.Image()
        pause_img.show()
        pause_img.set_from_icon_name('media-playback-pause',
                gtk.ICON_SIZE_LARGE_TOOLBAR)

        # Play button
        self.play_btn = ToggleToolButton('media-playback-start')
        self.play_btn.show()
        self.play_btn.connect('toggled', self._play_cb, [play_img, pause_img])
        self.insert(self.play_btn, -1)
        self.play_btn.set_tooltip(_('Play / Pause'))

        self.voice_combo = ComboBox()
        self.voice_combo.connect('changed', self.voice_changed_cb)
        for voice in self.sorted_voices:
            self.voice_combo.append_item(voice, voice[0])
        self.voice_combo.set_active(default)
        combotool = ToolComboBox(self.voice_combo)
        self.insert(combotool, -1)
        combotool.show()

        self.pitchadj = gtk.Adjustment(0, -100, 100, 1, 10, 0)
        self.pitchadj.connect("value_changed", self.pitch_adjusted_cb)
        pitchbar = gtk.HScale(self.pitchadj)
        pitchbar.set_draw_value(False)
        pitchbar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        pitchbar.set_size_request(240,15)
        pitchtool = gtk.ToolItem()
        pitchtool.add(pitchbar)
        pitchtool.show()
        self.insert(pitchtool, -1)
        pitchbar.show()

        self.rateadj = gtk.Adjustment(0, -100, 100, 1, 10, 0)
        self.rateadj.connect("value_changed", self.rate_adjusted_cb)
        ratebar = gtk.HScale(self.rateadj)
        ratebar.set_draw_value(False)
        ratebar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        ratebar.set_size_request(240,15)
        ratetool = gtk.ToolItem()
        ratetool.add(ratebar)
        ratetool.show()
        self.insert(ratetool, -1)
        ratebar.show()
Exemplo n.º 32
0
 def _get_when_search_combo(self):
     when_search = ComboBox()
     when_search.append_item(_ACTION_ANYTIME, _('Anytime'))
     when_search.append_separator()
     when_search.append_item(_ACTION_TODAY, _('Today'))
     when_search.append_item(_ACTION_SINCE_YESTERDAY, _('Since yesterday'))
     # TRANS: Filter entries modified during the last 7 days.
     when_search.append_item(_ACTION_PAST_WEEK, _('Past week'))
     # TRANS: Filter entries modified during the last 30 days.
     when_search.append_item(_ACTION_PAST_MONTH, _('Past month'))
     # TRANS: Filter entries modified during the last 356 days.
     when_search.append_item(_ACTION_PAST_YEAR, _('Past year'))
     when_search.set_active(0)
     when_search.connect('changed', self._combo_changed_cb)
     return when_search
Exemplo n.º 33
0
class   SpeechToolbar(gtk.Toolbar):
    def __init__(self):
        gtk.Toolbar.__init__(self)
        voicebar = gtk.Toolbar()
        self.activity = None
        self.sorted_voices = [i for i in speech.voices()]
        self.sorted_voices.sort(self.compare_voices)
        default = 0
        for voice in self.sorted_voices:
            if voice[0] == 'default':
                break
            default = default + 1

        # Play button Image
        play_img = gtk.Image()
        play_img.show()
        play_img.set_from_icon_name('media-playback-start',
                gtk.ICON_SIZE_LARGE_TOOLBAR)

        # Pause button Image
        pause_img = gtk.Image()
        pause_img.show()
        pause_img.set_from_icon_name('media-playback-pause',
                gtk.ICON_SIZE_LARGE_TOOLBAR)

        # Play button
        self.play_btn = ToggleToolButton('media-playback-start')
        self.play_btn.show()
        self.play_btn.connect('toggled', self._play_cb, [play_img, pause_img])
        self.insert(self.play_btn, -1)
        self.play_btn.set_tooltip(_('Play / Pause'))

        self.voice_combo = ComboBox()
        self.voice_combo.connect('changed', self.voice_changed_cb)
        for voice in self.sorted_voices:
            self.voice_combo.append_item(voice, voice[0])
        self.voice_combo.set_active(default)
        combotool = ToolComboBox(self.voice_combo)
        self.insert(combotool, -1)
        combotool.show()

        self.pitchadj = gtk.Adjustment(0, -100, 100, 1, 10, 0)
        self.pitchadj.connect("value_changed", self.pitch_adjusted_cb)
        pitchbar = gtk.HScale(self.pitchadj)
        pitchbar.set_draw_value(False)
        pitchbar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        pitchbar.set_size_request(240,15)
        pitchtool = gtk.ToolItem()
        pitchtool.add(pitchbar)
        pitchtool.show()
        self.insert(pitchtool, -1)
        pitchbar.show()

        self.rateadj = gtk.Adjustment(0, -100, 100, 1, 10, 0)
        self.rateadj.connect("value_changed", self.rate_adjusted_cb)
        ratebar = gtk.HScale(self.rateadj)
        ratebar.set_draw_value(False)
        ratebar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        ratebar.set_size_request(240,15)
        ratetool = gtk.ToolItem()
        ratetool.add(ratebar)
        ratetool.show()
        self.insert(ratetool, -1)
        ratebar.show()

    def compare_voices(self,  a,  b):
        if a[0].lower() == b[0].lower():
            return 0
        if a[0] .lower()< b[0].lower():
            return -1
        if a[0] .lower()> b[0].lower():
            return 1
        
    def voice_changed_cb(self, combo):
        speech.voice = combo.props.value
        if self.activity != None:
            speech.say(speech.voice[0])

    def pitch_adjusted_cb(self, get):
        speech.pitch = int(get.value)
        speech.say(_("pitch adjusted"))

    def rate_adjusted_cb(self, get):
        speech.rate = int(get.value)
        speech.say(_("rate adjusted"))
      
    def set_activity(self, activity):
        self.activity = activity
    
    def _play_cb(self, widget, images):
        widget.set_icon_widget(images[int(widget.get_active())])

        if widget.get_active():
            if speech.is_stopped():
                speech.play(self.activity.add_word_marks())
        else:
            speech.stop()
Exemplo n.º 34
0
def combo_factory(combo_array, toolbar, callback, cb_arg=None,
                  tooltip=None, default=None):
    '''Factory for making a toolbar combo box'''
    combo = ComboBox()
    if tooltip is not None and hasattr(combo, 'set_tooltip_text'):
        combo.set_tooltip_text(tooltip)
    if cb_arg is not None:
        combo.connect('changed', callback, cb_arg)
    else:
        combo.connect('changed', callback)
    for i, selection in enumerate(combo_array):
        combo.append_item(i, selection, None)
    combo.show()
    toolitem = gtk.ToolItem()
    toolitem.add(combo)
    if hasattr(toolbar, 'insert'):  # the main toolbar
        toolbar.insert(toolitem, -1)
    else:  # or a secondary toolbar
        toolbar.props.page.insert(toolitem, -1)
    toolitem.show()
    if default is not None:
        combo.set_active(combo_array.index(default))
    return combo
Exemplo n.º 35
0
    def create_dialog(self):
        """Setup most of the dialog."""

# Toolbar
        try:
            self._toolbar_box = ToolbarBox()

            activity_button = ActivityToolbarButton(self._parent)
            self._toolbar_box.toolbar.insert(activity_button, 0)

            def append(icon_name, label, page, position):
                toolbar_button = ToolbarButton()
                toolbar_button.props.page = page
                toolbar_button.props.icon_name = icon_name
                toolbar_button.props.label = label
                self._toolbar_box.toolbar.insert(toolbar_button, position)

            append('toolbar-edit',
                   _('Edit'),
                   EditToolbar(self._parent),
                   -1)

            append('toolbar-algebra',
                   _('Algebra'),
                   AlgebraToolbar(self._parent),
                   -1)

            append('toolbar-trigonometry',
                   _('Trigonometry'),
                   TrigonometryToolbar(self._parent),
                   -1)

            append('toolbar-boolean',
                   _('Boolean'),
                   BooleanToolbar(self._parent),
                   -1)

            self._misc_toolbar = MiscToolbar(
                self._parent,
                target_toolbar=self._toolbar_box.toolbar)

            append('toolbar-constants',
                   _('Miscellaneous'),
                   self._misc_toolbar,
                   5)

            self._stop_separator = gtk.SeparatorToolItem()
            self._stop_separator.props.draw = False
            self._stop_separator.set_expand(True)
            self._stop_separator.show()
            self._toolbar_box.toolbar.insert(self._stop_separator, -1)

            self._stop = StopButton(self._parent)
            self._toolbar_box.toolbar.insert(self._stop, -1)

            self._toolbar_box.show_all()
            self._parent.set_toolbar_box(self._toolbar_box)

        except NameError:
            # Use old toolbar design
            toolbox = activity.ActivityToolbox(self._parent)
            self._parent.set_toolbox(toolbox)
            toolbox.add_toolbar(_('Edit'), EditToolbar(self._parent))
            toolbox.add_toolbar(_('Algebra'), AlgebraToolbar(self._parent))
            toolbox.add_toolbar(
                _('Trigonometry'), TrigonometryToolbar(self._parent))
            toolbox.add_toolbar(_('Boolean'), BooleanToolbar(self._parent))
            toolbox.add_toolbar(_('Miscellaneous'), MiscToolbar(self._parent))
            toolbox.show_all()

# Some layout constants
        self.input_font = pango.FontDescription(str='sans bold 12')
        self.button_font = pango.FontDescription(str='sans bold 16')
        self.col_white = self.create_color(1.00, 1.00, 1.00)
        self.col_gray1 = self.create_color(0.76, 0.76, 0.76)
        self.col_gray2 = self.create_color(0.50, 0.50, 0.50)
        self.col_gray3 = self.create_color(0.25, 0.25, 0.25)
        self.col_black = self.create_color(0.00, 0.00, 0.00)
        self.col_red = self.create_color(1.00, 0.00, 0.00)

# Big - Table, 16 rows, 10 columns, homogeneously divided
        self.grid = gtk.Table(26, 11, True)
        self.grid.set_border_width(0)
        self.grid.set_row_spacings(0)
        self.grid.set_col_spacings(4)

# Left part: container and input
        vc1 = gtk.VBox(False, 0)
        hc1 = gtk.HBox(False, 10)
        eb = gtk.EventBox()
        eb.add(hc1)
        eb.modify_bg(gtk.STATE_NORMAL, self.col_black)
        eb.set_border_width(12)
        eb2 = gtk.EventBox()
        eb2.add(eb)
        eb2.modify_bg(gtk.STATE_NORMAL, self.col_black)
        label1 = gtk.Label(_('Label:'))
        label1.modify_fg(gtk.STATE_NORMAL, self.col_white)
        label1.set_alignment(1, 0.5)
        hc1.pack_start(label1, expand=False, fill=False, padding=10)
        self.label_entry = gtk.Entry()
        self.label_entry.modify_bg(gtk.STATE_INSENSITIVE, self.col_black)
        hc1.pack_start(self.label_entry, expand=True, fill=True, padding=0)
        vc1.pack_start(eb2, expand=False)

        self.text_entry = gtk.Entry()
        try:
            self.text_entry.props.im_module = 'gtk-im-context-simple'
        except AttributeError:
            pass
        self.text_entry.set_size_request(-1, 75)
        self.text_entry.connect('key_press_event', self._parent.ignore_key_cb)
        self.text_entry.modify_font(self.input_font)
        self.text_entry.modify_bg(gtk.STATE_INSENSITIVE, self.col_black)
        eb = gtk.EventBox()
        eb.add(self.text_entry)
        eb.modify_bg(gtk.STATE_NORMAL, self.col_black)
        eb.set_border_width(12)
        eb2 = gtk.EventBox()
        eb2.add(eb)
        eb2.modify_bg(gtk.STATE_NORMAL, self.col_black)
        vc1.pack_start(eb2, expand=True, fill=True, padding=0)
        self.grid.attach(vc1, 0, 7, 0, 6)

# Left part: buttons
        self.pad = gtk.Table(9, 6, True)
        self.pad.set_row_spacings(12)
        self.pad.set_col_spacings(12)
        self.pad.set_border_width(12)
        self.create_button_data()
        self.buttons = {}
        for x, y, w, h, cap, bgcol, cb in self.button_data:
            button = self.create_button(
                _(cap), cb, self.col_white, bgcol, w, h)
            self.buttons[cap] = button
            self.pad.attach(button, x, x + w, y, y + h)

        eb = gtk.EventBox()
        eb.add(self.pad)
        eb.modify_bg(gtk.STATE_NORMAL, self.col_black)
        self.grid.attach(eb, 0, 7, 6, 26)

# Right part: container and equation button
        hc2 = gtk.HBox()
        combo = ComboBox()
        combo.append_item(0, _('All equations'))
        combo.append_item(1, _('My equations'))
        combo.append_item(2, _('Show variables'))
        combo.set_active(0)
        combo.connect('changed', self._history_filter_cb)
        hc2.pack_start(combo)
        hc2.set_border_width(6)
        self.grid.attach(hc2, 7, 11, 0, 2)

# Right part: last equation
        self.last_eq = gtk.TextView()
        self.last_eq.set_editable(False)
        self.last_eq.set_wrap_mode(gtk.WRAP_WORD_CHAR)
        self.last_eq.connect('realize', self._textview_realize_cb)
        self.last_eq.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse(
                                 sugar.profile.get_color().get_fill_color()))
        self.last_eq.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(
                               sugar.profile.get_color().get_stroke_color()))
        self.last_eq.set_border_window_size(gtk.TEXT_WINDOW_LEFT, 4)
        self.last_eq.set_border_window_size(gtk.TEXT_WINDOW_RIGHT, 4)
        self.last_eq.set_border_window_size(gtk.TEXT_WINDOW_TOP, 4)
        self.last_eq.set_border_window_size(gtk.TEXT_WINDOW_BOTTOM, 4)

        # TODO Fix for old Sugar 0.82 builds, red_float not available
        xo_color = sugar.profile.get_color()
        bright = (
            gtk.gdk.color_parse(xo_color.get_fill_color()).red_float +
            gtk.gdk.color_parse(xo_color.get_fill_color()).green_float +
            gtk.gdk.color_parse(xo_color.get_fill_color()).blue_float) / 3.0
        if bright < 0.5:
            self.last_eq.modify_text(gtk.STATE_NORMAL, self.col_white)
        else:
            self.last_eq.modify_text(gtk.STATE_NORMAL, self.col_black)

        self.grid.attach(self.last_eq, 7, 11, 2, 7)

# Right part: history
        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)

        self.history_vbox = gtk.VBox()
        self.history_vbox.set_homogeneous(False)
        self.history_vbox.set_border_width(0)
        self.history_vbox.set_spacing(4)

        self.variable_vbox = gtk.VBox()
        self.variable_vbox.set_homogeneous(False)
        self.variable_vbox.set_border_width(0)
        self.variable_vbox.set_spacing(4)

        vbox = gtk.VBox()
        vbox.pack_start(self.history_vbox)
        vbox.pack_start(self.variable_vbox)
        scrolled_window.add_with_viewport(vbox)
        self.grid.attach(scrolled_window, 7, 11, 7, 26)

        gtk.gdk.screen_get_default().connect('size-changed',
                                             self._configure_cb)
    def __init__(self, activity):
        """ By default, start with resistance mode """

        gtk.Toolbar.__init__(self)

        self.mode = 'resistance'

        self._STR_BASIC = \
        _("Sensors, DC (connect sensor to pink 'Mic In' on left side of XO)") \
        + ' '
        self._STR_R = _('Bias/Offset Enabled') + ' ' + _('Ohms') + ' '
        self._STR_V = _('Bias/Offset Disabled') + ' ' + _('Volts') + ' '
        self._STR_I = ' ' + _('Invert') + ' '

        self.string_for_textbox = ""

        self.activity = activity
        self.activity.audiograb.set_sensor(self)

        # Set up Resistance Button
        if self.activity.has_toolbarbox:
            self.resistance = ToolButton('bias-on')
        else:
            self.resistance = ToolButton('bias-on2')
        self.insert(self.resistance, -1)
        self.resistance.show()
        self.resistance.set_tooltip(_('Resistance Sensor'))
        self.resistance.connect('clicked', self.set_resistance_voltage_mode,
                                'resistance')

        # Set up Voltage Button
        self.voltage = ToolButton('bias-off')
        self.insert(self.voltage, -1)
        self.voltage.set_tooltip(_('Voltage Sensor'))
        self.voltage.connect('clicked', self.set_resistance_voltage_mode,
                             'voltage')

        # Set up Invert Button
        self._invert = ToolButton('invert')
        self.insert(self._invert, -1)
        self._invert.set_tooltip(_('Invert'))
        self._invert.connect('clicked', self._invert_control_cb)
        self.activity.wave.set_invert_state(False)

        separator = gtk.SeparatorToolItem()
        separator.props.draw = True
        self.insert(separator, -1)

        self.audiobutton = ToolButton('add-icon')
        self.insert(self.audiobutton, -1)
        self.audiobutton.show()
        self.audiobutton.set_tooltip('Close Sound')
        self.audiobutton.connect('clicked', self.addAudio)
        self.connect('add-media', self.addThisAudio)

        self.insert(separator, -1)
        self.insert(separator, -1)

        self.openedbutton = ToolButton('delete-icon')
        self.insert(self.openedbutton, -1)
        self.openedbutton.show()
        self.openedbutton.set_tooltip('Open Sound')
        self.openedbutton.connect('clicked', self.addOpenedAudio)
        self.connect('add-opened', self.addThisOpenedAudio)

        self.insert(separator, -1)
        self.insert(separator, -1)

        # Set up Logging Interval combo box
        self.loginterval_img = gtk.Image()
        self.loginterval_img.set_from_file(ICONS_DIR + '/sample_rate.svg')
        self.loginterval_img_tool = gtk.ToolItem()
        self.loginterval_img_tool.add(self.loginterval_img)
        self.insert(self.loginterval_img_tool, -1)

        self._loginterval_combo = ComboBox()
        self.interval = [
            _('1/10 second'),
            _('1 second'),
            _('30 seconds'),
            _('5 minutes'),
            _('30 minutes')
        ]

        if hasattr(self._loginterval_combo, 'set_tooltip_text'):
            self._loginterval_combo.set_tooltip_text(_('Sampling interval'))

        self._interval_changed_id = self._loginterval_combo.connect(
            "changed", self.loginterval_control)

        for i, s in enumerate(self.interval):
            self._loginterval_combo.append_item(i, s, None)
            if s == _('1 second'):
                self._loginterval_combo.set_active(i)

        self._loginterval_tool = ToolComboBox(self._loginterval_combo)
        self.insert(self._loginterval_tool, -1)
        self.logginginterval_status = '1 second'

        # Set up Logging/Stop Logging Button
        self._record = ToolButton('media-record')
        self.insert(self._record, -1)
        self._record.set_tooltip(_('Start Recording'))
        self._record.connect('clicked', self.record_control)

        self.show_all()
Exemplo n.º 37
0
class SearchToolbar(gtk.Toolbar):
    __gtype_name__ = 'SearchToolbar'

    __gsignals__ = {
        'query-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                          ([object])),
        }

    def __init__(self):
        gtk.Toolbar.__init__(self)

        self._mount_point = None

        self._search_entry = iconentry.IconEntry()
        self._search_entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY,
                                              'system-search')
        self._search_entry.connect('activate', self._search_entry_activated_cb)
        self._search_entry.connect('changed', self._search_entry_changed_cb)
        self._search_entry.add_clear_button()
        self._autosearch_timer = None
        self._add_widget(self._search_entry, expand=True)

        self._favorite_button = ToggleToolButton('emblem-favorite')
        self._favorite_button.connect('toggled',
                                      self.__favorite_button_toggled_cb)
        self.insert(self._favorite_button, -1)
        self._favorite_button.show()

        self._what_search_combo = ComboBox()
        self._what_combo_changed_sid = self._what_search_combo.connect(
                'changed', self._combo_changed_cb)
        tool_item = ToolComboBox(self._what_search_combo)
        self.insert(tool_item, -1)
        tool_item.show()

        self._when_search_combo = self._get_when_search_combo()
        tool_item = ToolComboBox(self._when_search_combo)
        self.insert(tool_item, -1)
        tool_item.show()

        self._sorting_button = SortingButton()
        self._sorting_button.connect('clicked',
                                     self.__sorting_button_clicked_cb)
        self.insert(self._sorting_button, -1)
        self._sorting_button.connect('sort-property-changed',
                                     self.__sort_changed_cb)
        self._sorting_button.show()

        # TODO: enable it when the DS supports saving the buddies.
        #self._with_search_combo = self._get_with_search_combo()
        #tool_item = ToolComboBox(self._with_search_combo)
        #self.insert(tool_item, -1)
        #tool_item.show()

        self._query = self._build_query()

        self.refresh_filters()

    def give_entry_focus(self):
        self._search_entry.grab_focus()

    def _get_when_search_combo(self):
        when_search = ComboBox()
        when_search.append_item(_ACTION_ANYTIME, _('Anytime'))
        when_search.append_separator()
        when_search.append_item(_ACTION_TODAY, _('Today'))
        when_search.append_item(_ACTION_SINCE_YESTERDAY,
                                      _('Since yesterday'))
        # TRANS: Filter entries modified during the last 7 days.
        when_search.append_item(_ACTION_PAST_WEEK, _('Past week'))
        # TRANS: Filter entries modified during the last 30 days.
        when_search.append_item(_ACTION_PAST_MONTH, _('Past month'))
        # TRANS: Filter entries modified during the last 356 days.
        when_search.append_item(_ACTION_PAST_YEAR, _('Past year'))
        when_search.set_active(0)
        when_search.connect('changed', self._combo_changed_cb)
        return when_search

    def _get_with_search_combo(self):
        with_search = ComboBox()
        with_search.append_item(_ACTION_EVERYBODY, _('Anyone'))
        with_search.append_separator()
        with_search.append_item(_ACTION_MY_FRIENDS, _('My friends'))
        with_search.append_item(_ACTION_MY_CLASS, _('My class'))
        with_search.append_separator()

        # TODO: Ask the model for buddies.
        with_search.append_item(3, 'Dan', 'theme:xo')

        with_search.set_active(0)
        with_search.connect('changed', self._combo_changed_cb)
        return with_search

    def _add_widget(self, widget, expand=False):
        tool_item = gtk.ToolItem()
        tool_item.set_expand(expand)

        tool_item.add(widget)
        widget.show()

        self.insert(tool_item, -1)
        tool_item.show()

    def _build_query(self):
        query = {}

        if self._mount_point:
            query['mountpoints'] = [self._mount_point]

        if self._favorite_button.props.active:
            query['keep'] = 1

        if self._what_search_combo.props.value:
            value = self._what_search_combo.props.value
            generic_type = mime.get_generic_type(value)
            if generic_type:
                mime_types = generic_type.mime_types
                query['mime_type'] = mime_types
            else:
                query['activity'] = self._what_search_combo.props.value

        if self._when_search_combo.props.value:
            date_from, date_to = self._get_date_range()
            query['timestamp'] = {'start': date_from, 'end': date_to}

        if self._search_entry.props.text:
            text = self._search_entry.props.text.strip()
            if text:
                query['query'] = text

        property_, order = self._sorting_button.get_current_sort()

        if order == gtk.SORT_ASCENDING:
            sign = '+'
        else:
            sign = '-'
        query['order_by'] = [sign + property_]

        return query

    def _get_date_range(self):
        today_start = datetime.today().replace(hour=0, minute=0, second=0)
        right_now = datetime.today()
        if self._when_search_combo.props.value == _ACTION_TODAY:
            date_range = (today_start, right_now)
        elif self._when_search_combo.props.value == _ACTION_SINCE_YESTERDAY:
            date_range = (today_start - timedelta(1), right_now)
        elif self._when_search_combo.props.value == _ACTION_PAST_WEEK:
            date_range = (today_start - timedelta(7), right_now)
        elif self._when_search_combo.props.value == _ACTION_PAST_MONTH:
            date_range = (today_start - timedelta(30), right_now)
        elif self._when_search_combo.props.value == _ACTION_PAST_YEAR:
            date_range = (today_start - timedelta(356), right_now)

        return (time.mktime(date_range[0].timetuple()),
                time.mktime(date_range[1].timetuple()))

    def _combo_changed_cb(self, combo):
        self._update_if_needed()

    def __sort_changed_cb(self, button):
        self._update_if_needed()

    def __sorting_button_clicked_cb(self, button):
        self._sorting_button.palette.popup(immediate=True, state=1)

    def _update_if_needed(self):
        new_query = self._build_query()
        if self._query != new_query:
            self._query = new_query
            self.emit('query-changed', self._query)

    def _search_entry_activated_cb(self, search_entry):
        if self._autosearch_timer:
            gobject.source_remove(self._autosearch_timer)
        new_query = self._build_query()
        if self._query != new_query:
            self._query = new_query
            self.emit('query-changed', self._query)

    def _search_entry_changed_cb(self, search_entry):
        if not search_entry.props.text:
            search_entry.activate()
            return

        if self._autosearch_timer:
            gobject.source_remove(self._autosearch_timer)
        self._autosearch_timer = gobject.timeout_add(_AUTOSEARCH_TIMEOUT,
                                                     self._autosearch_timer_cb)

    def _autosearch_timer_cb(self):
        logging.debug('_autosearch_timer_cb')
        self._autosearch_timer = None
        self._search_entry.activate()
        return False

    def set_mount_point(self, mount_point):
        self._mount_point = mount_point
        new_query = self._build_query()
        if self._query != new_query:
            self._query = new_query
            self.emit('query-changed', self._query)

    def set_what_filter(self, what_filter):
        combo_model = self._what_search_combo.get_model()
        what_filter_index = -1
        for i in range(0, len(combo_model) - 1):
            if combo_model[i][0] == what_filter:
                what_filter_index = i
                break

        if what_filter_index == -1:
            logging.warning('what_filter %r not known', what_filter)
        else:
            self._what_search_combo.set_active(what_filter_index)

    def refresh_filters(self):
        current_value = self._what_search_combo.props.value
        current_value_index = 0

        self._what_search_combo.handler_block(self._what_combo_changed_sid)
        try:
            self._what_search_combo.remove_all()
            # TRANS: Item in a combo box that filters by entry type.
            self._what_search_combo.append_item(_ACTION_ANYTHING,
                                                _('Anything'))

            registry = bundleregistry.get_registry()
            appended_separator = False

            types = mime.get_all_generic_types()
            for generic_type in types:
                if not appended_separator:
                    self._what_search_combo.append_separator()
                    appended_separator = True
                self._what_search_combo.append_item(
                    generic_type.type_id, generic_type.name, generic_type.icon)
                if generic_type.type_id == current_value:
                    current_value_index = \
                            len(self._what_search_combo.get_model()) - 1

                self._what_search_combo.set_active(current_value_index)

            self._what_search_combo.append_separator()

            for service_name in model.get_unique_values('activity'):
                activity_info = registry.get_bundle(service_name)
                if activity_info is None:
                    continue

                if service_name == current_value:
                    combo_model = self._what_search_combo.get_model()
                    current_value_index = len(combo_model)

                # try activity-provided icon
                if os.path.exists(activity_info.get_icon()):
                    try:
                        self._what_search_combo.append_item(service_name,
                                activity_info.get_name(),
                                file_name=activity_info.get_icon())
                    except glib.GError, exception:
                        logging.warning('Falling back to default icon for'
                                        ' "what" filter because %r (%r) has an'
                                        ' invalid icon: %s',
                                        activity_info.get_name(),
                                        str(service_name), exception)
                    else:
                        continue

                # fall back to generic icon
                self._what_search_combo.append_item(service_name,
                        activity_info.get_name(),
                        icon_name='application-octet-stream')

        finally:
            self._what_search_combo.handler_unblock(
                    self._what_combo_changed_sid)

    def __favorite_button_toggled_cb(self, favorite_button):
        self._update_if_needed()

    def clear_query(self):
        self._search_entry.props.text = ''
        self._what_search_combo.set_active(0)
        self._when_search_combo.set_active(0)
        self._favorite_button.props.active = False
Exemplo n.º 38
0
def combo_factory(combo_array,
                  toolbar,
                  callback,
                  cb_arg=None,
                  tooltip=None,
                  default=None):
    '''Factory for making a toolbar combo box'''
    combo = ComboBox()
    if tooltip is not None and hasattr(combo, 'set_tooltip_text'):
        combo.set_tooltip_text(tooltip)
    if cb_arg is not None:
        combo.connect('changed', callback, cb_arg)
    else:
        combo.connect('changed', callback)
    for i, selection in enumerate(combo_array):
        combo.append_item(i, selection, None)
    combo.show()
    toolitem = gtk.ToolItem()
    toolitem.add(combo)
    if hasattr(toolbar, 'insert'):  # the main toolbar
        toolbar.insert(toolitem, -1)
    else:  # or a secondary toolbar
        toolbar.props.page.insert(toolitem, -1)
    toolitem.show()
    if default is not None:
        combo.set_active(combo_array.index(default))
    return combo
Exemplo n.º 39
0
class SoundToolbar(gtk.Toolbar):
    """ Set up the toolbar for audio (analog) capture mode """

    SAMPLE_NOW = _('Capture now')
    SAMPLE_30_SEC = _('Every 30 sec.')
    SAMPLE_2_MIN = _('Every 2 min.')
    SAMPLE_10_MIN = _('Every 10 min.')
    SAMPLE_30_MIN = _('Every 30 min.')

    LOWER = 0.0
    UPPER = 1.0

    def __init__(self, activity):
        """ Initialize the toolbar controls. """
        gtk.Toolbar.__init__(self)

        self.activity = activity

        self._STR_BASIC = _('Sound') + ' '
        self._STR1 = _('Time Base') + ' '
        self._STR2 = _('Frequency Base') + ' '
        self._STR3 = ' ' + _('Invert') + ' '
        self._STR_SCALEX = ""
        self._STR_XAXIS_TEXT = \
            _('X Axis Scale: 1 division = %(division)s %(unit)s')
        # TRANSLATORS: This is milli seconds.
        self._ms = _('ms')
        # TRANSLATORS: This is Hertz, so 1/second.
        self._Hz = _('Hz')

        self._update_page_size_id = None

        self.string_for_textbox = ""

        self.gain = 1.0
        self.y_mag = 3.0
        self.capture_gain = CAPTURE_GAIN
        self.mic_boost = MIC_BOOST

        # self.logging_status = False
        self._record = None

        # Set up Time-domain Button
        self.time = ToolButton('domain-time2')
        self.insert(self.time, -1)
        self.time.set_tooltip(_('Time Base'))
        self.time.connect('clicked', self._timefreq_control_cb, True)

        # Set up Frequency-domain Button
        self.freq = ToolButton('domain-freq')
        self.insert(self.freq, -1)
        self.freq.show()
        self.freq.set_tooltip(_('Frequency Base'))
        self.freq.connect('clicked', self._timefreq_control_cb, False)

        # Set up Frequency-control Slider and corresponding buttons
        if not self.activity.has_toolbarbox:
            self.add_frequency_slider(self)

        # Set up the Pause Button
        self._pause = ToolButton('media-playback-pause')
        self.insert(self._pause, -1)
        self._pause.set_tooltip(_('Freeze the display'))
        self._pause.connect('clicked', self._pauseplay_control_cb)

        if self.activity.has_toolbarbox:
            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            self.insert(separator, -1)
            separator.show()

        self.loginterval_img = gtk.Image()
        self.loginterval_img.set_from_file(ICONS_DIR + 'sample_rate.svg')
        self.loginterval_img_tool = gtk.ToolItem()
        self.loginterval_img_tool.add(self.loginterval_img)
        self.insert(self.loginterval_img_tool, -1)

        # Set up the Logging-interval Combo box
        self._loginterval_combo = ComboBox()
        self.interval = [
            _(self.SAMPLE_NOW),
            _(self.SAMPLE_30_SEC),
            _(self.SAMPLE_2_MIN),
            _(self.SAMPLE_10_MIN),
            _(self.SAMPLE_30_MIN)
        ]

        if hasattr(self._loginterval_combo, 'set_tooltip_text'):
            self._loginterval_combo.set_tooltip_text(_('Sampling interval'))

        self._interval_changed_id = self._loginterval_combo.connect(
            'changed', self.loginterval_control)

        for i, s in enumerate(self.interval):
            self._loginterval_combo.append_item(i, s, None)
            if s == self.SAMPLE_NOW:
                self._loginterval_combo.set_active(i)

        self._loginterval_tool = ToolComboBox(self._loginterval_combo)
        self.insert(self._loginterval_tool, -1)
        self.logginginterval_status = 'picture'

        # Set up Start/Stop Logging Button
        self._record = ToolButton('media-record')
        self.insert(self._record, -1)
        self._record.set_tooltip(_('Capture sample now'))

        self._record.connect('clicked', self.record_control)

        if self.activity.has_toolbarbox:
            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            self.insert(separator, -1)

        # Set up Trigger Combo box
        self._trigger_combo = ComboBox()
        self.trigger = [_('None'), _('Rising Edge'), _('Falling Edge')]
        self.trigger_conf = [
            self.activity.wave.TRIGGER_NONE, self.activity.wave.TRIGGER_POS,
            self.activity.wave.TRIGGER_NEG
        ]

        self._trigger_changed_id = self._trigger_combo.connect(
            'changed', self.update_trigger_control)

        for i, s in enumerate(self.trigger):
            self._trigger_combo.append_item(i, s, None)
        self._trigger_combo.set_active(0)

        if hasattr(self._trigger_combo, 'set_tooltip_text'):
            self._trigger_combo.set_tooltip_text(_('Create a trigger'))

        self._trigger_tool = ToolComboBox(self._trigger_combo)
        self.insert(self._trigger_tool, -1)
        self.show_all()

        return

    def add_frequency_slider(self, toolbar):
        """ Either on the Sound toolbar or the Main toolbar """
        self._freq_stepper_up = ToolButton('freq-high')
        self._freq_stepper_up.set_tooltip(_('Zoom out'))
        self._freq_stepper_up.connect('clicked', self._freq_stepper_up_cb)

        self.activity.adjustmentf = gtk.Adjustment(0.5, self.LOWER, self.UPPER,
                                                   0.01, 0.1, 0)
        self.activity.adjustmentf.connect('value_changed', self.cb_page_sizef)
        self._freq_range = gtk.HScale(self.activity.adjustmentf)
        self._freq_range.set_inverted(True)
        self._freq_range.set_draw_value(False)
        self._freq_range.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self._freq_range.set_size_request(120, 15)

        self._freq_stepper_down = ToolButton('freq-low')
        self._freq_stepper_down.set_tooltip(_('Zoom in'))
        self._freq_stepper_down.connect('clicked', self._freq_stepper_down_cb)

        self._freq_range_tool = gtk.ToolItem()
        self._freq_range_tool.add(self._freq_range)

        toolbar.insert(self._freq_stepper_up, -1)
        toolbar.insert(self._freq_range_tool, -1)
        toolbar.insert(self._freq_stepper_down, -1)

        return

    def _set_icon_ready(self):
        self._record.set_icon('media-record')
        self._record.show()
        return False

    def _set_icon_stop(self):
        self._record.set_icon('record-stop')
        self._record.show()
        return False

    def record_control_delayed(self, data=None):
        """Depending upon the selected interval, either starts/stops
        a logging session, or just logs the current buffer"""
        if not self.activity.LOGGING_IN_SESSION:
            Xscale = (1.00 / self.activity.audiograb.get_sampling_rate())
            Yscale = 0.0
            interval = self.interval_convert()
            username = self.activity.nick
            self.activity.ji.start_new_session(username, Xscale, Yscale,
                                               self.logginginterval_status)
            self.activity.audiograb.set_logging_params(True, interval, True)
            self.activity.LOGGING_IN_SESSION = True
            self._set_icon_stop()
            if interval == 0:
                # Flash the stop button when grabbing just one image
                gobject.timeout_add(250, self._set_icon_ready)
                self.record_state = False
                self.activity.LOGGING_IN_SESSION = False
                self.logging_status = False
        else:
            self.activity.audiograb.set_logging_params(False)
            self.activity.LOGGING_IN_SESSION = False
            self._set_icon_ready()
        self._set_record_button_tooltip()
        return False

    def record_control(self, data=None):
        self._record.palette.popdown()
        gtk.gdk.flush()
        gobject.timeout_add(10, self.record_control_delayed, data)

    def interval_convert(self):
        """Converts picture/time interval to an integer that denotes the number
        of times the audiograb buffer must be called before a value is written.
        When set to 0, the whole of current buffer will be written
        1second= about 66 ticks at 48khz sampling"""
        if self.logginginterval_status == 'picture':
            return 0
        elif self.logginginterval_status == '30second':
            return 30  #2667
        elif self.logginginterval_status == '2minute':
            return 120  #10668
        elif self.logginginterval_status == '10minute':
            return 600  #53340
        elif self.logginginterval_status == '30minute':
            return 1800  #160000

    def loginterval_control(self, combobox):
        """ The combo box has changed. Set the logging interval
        status correctly and then set the tooltip on the record
        button properly depending upon whether logging is currently
        in progress or not. """
        if (self._loginterval_combo.get_active() != -1):
            if (self._loginterval_combo.get_active() == 0):
                self.logginginterval_status = 'picture'
            elif (self._loginterval_combo.get_active() == 1):
                self.logginginterval_status = '30second'
            elif (self._loginterval_combo.get_active() == 2):
                self.logginginterval_status = '2minute'
            elif (self._loginterval_combo.get_active() == 3):
                self.logginginterval_status = '10minute'
            elif (self._loginterval_combo.get_active() == 4):
                self.logginginterval_status = '30minute'
            self._set_record_button_tooltip()
        return

    def _set_record_button_tooltip(self):
        """ Determines the tool tip for the record button. The tool tip
        text depends upon whether sampling is currently on and whether
        the sampling interval > 0. """
        if self._record == None:
            return
        if self.activity.LOGGING_IN_SESSION:
            self._record.set_tooltip(_('Stop sampling'))
        else:  # No sampling in progress
            if (self._loginterval_combo.get_active() == 0):
                self._record.set_tooltip(_('Capture sample now'))
            else:
                self._record.set_tooltip(_('Start sampling'))
        return

    def update_trigger_control(self, *args):
        """ Callback for trigger control """
        active = self._trigger_combo.get_active()
        if active == -1:
            return

        self.activity.wave.set_trigger(self.trigger_conf[active])
        return

    def _pauseplay_control_cb(self, data=None):
        """ Callback for Pause Button """
        if self.activity.audiograb.get_freeze_the_display():
            self.activity.audiograb.set_freeze_the_display(False)
            self._pause.set_icon('media-playback-pause-insensitive')
            self._pause.set_tooltip(_('Unfreeze the display'))
            self._pause.show()
        else:
            self.activity.audiograb.set_freeze_the_display(True)
            self._pause.set_icon('media-playback-pause')
            self._pause.set_tooltip(_('Freeze the display'))
            self._pause.show()
        return False

    def _timefreq_control_cb(self, data=None, time_state=True):
        """ Callback for Time and Freq. Buttons """

        # Make sure the current context is for sound capture.
        if self.activity.CONTEXT != 'sound':
            self.activity.set_sound_context()

        if time_state:
            self.activity.wave.set_fft_mode(False)
            self.time.set_icon('domain-time2')
            self.freq.set_icon('domain-freq')
            self.time.show()
            self.freq.show()
            self._update_string_for_textbox()
            if self.activity.has_toolbarbox:
                self.activity.label_button.set_icon('domain-time2')
                self.activity.label_button.set_tooltip(_('Time Base'))
        else:
            self.activity.wave.set_fft_mode(True)
            self.time.set_icon('domain-time')
            self.freq.set_icon('domain-freq2')
            self.time.show()
            self.freq.show()
            self._update_string_for_textbox()
            if self.activity.has_toolbarbox:
                self.activity.label_button.set_icon('domain-freq2')
                self.activity.label_button.set_tooltip(_('Frequency Base'))
        if self.activity.has_toolbarbox and \
                hasattr(self.activity, 'sensor_toolbar'):
            self.activity.sensor_toolbar.resistance.set_icon('bias-on')
            self.activity.sensor_toolbar.voltage.set_icon('bias-off')
        return False

    def _freq_stepper_up_cb(self, data=None):
        """Moves the horizontal zoom slider to the left one notch, where
        one notch is 1/100 of the total range. This correspond to zooming
        out as a larger number of Hertz or milliseconds will be
        represented by the same space on the screen."""
        new_value = self._freq_range.get_value() +\
                    (self.UPPER - self.LOWER) / 100.0
        if new_value <= self.UPPER:
            self._freq_range.set_value(new_value)
        else:
            self._freq_range.set_value(self.UPPER)

    def _freq_stepper_down_cb(self, data=None):
        """Moves the horizontal zoom slider to the right one notch, where
        one notch is 1/100 of the total range. This corresponds to zooming
        in."""
        new_value = self._freq_range.get_value() -\
                    (self.UPPER - self.LOWER) / 100.0
        if new_value >= self.LOWER:
            self._freq_range.set_value(new_value)
        else:
            self._freq_range.set_value(self.LOWER)

    def cb_page_sizef(self, data=None):
        """ Callback to scale the frequency range (zoom in and out) """
        if self._update_page_size_id:
            gobject.source_remove(self._update_page_size_id)
        self._update_page_size_id =\
            gobject.timeout_add(250, self.update_page_size)
        return True

    def update_page_size(self):
        """ Set up the scaling of the display """
        self._update_page_size_id = None

        new_value = round(self.activity.adjustmentf.value * 100.0) / 100.0
        if self.activity.adjustmentf.value != new_value:
            self.activity.adjustmentf.value = new_value
            return False

        time_div = 0.001 * max(self.activity.adjustmentf.value, 0.05)
        freq_div = 1000 * max(self.activity.adjustmentf.value, 0.01)

        self.activity.wave.set_div(time_div, freq_div)

        self._update_string_for_textbox()

        return False

    def context_off(self):
        """When some other context is switched to and the sound context 
        is switched off"""
        print "context off: gain and y_mag were %f and %f" %\
            (self.gain, self.y_mag)
        self.gain, self.y_mag = self.activity.wave.get_mag_params()
        print "context off: gain and y_mag are %f and %f" %\
            (self.gain, self.y_mag)
        self.capture_gain = self.activity.audiograb.get_capture_gain()
        self.mic_boost = self.activity.audiograb.get_mic_boost()
        print "context off: capture gain %s and mic boost %s" %\
              (str(self.capture_gain), str(self.mic_boost))
        self.activity.audiograb.stop_sound_device()
        self.activity.wave.set_fft_mode(False)

    def context_on(self):
        """When the sound context is switched on"""
        self.activity.audiograb.start_sound_device()
        self.activity.audiograb.set_sensor_type('sound')
        self.activity.wave.set_fft_mode(False)
        print "context on: gain and y_mag are %f and %f" %\
              (self.gain, self.y_mag)
        self.activity.wave.set_mag_params(self.gain, self.y_mag)
        self._update_string_for_textbox()
        self.update_trigger_control()
        return False

    def _update_string_for_textbox(self):
        """ Update the text at the bottom of the canvas """
        if not self.activity.wave.get_fft_mode():
            self._STR_SCALEX = self._STR_XAXIS_TEXT % \
                {'unit': self._ms,
                 'division': self.activity.wave.time_div*1000}
        else:
            self._STR_SCALEX = self._STR_XAXIS_TEXT % \
                {'unit': self._Hz, 'division': self.activity.wave.freq_div}

        self.string_for_textbox = ""
        self.string_for_textbox += (self._STR_BASIC + '\t')
        if not self.activity.wave.get_fft_mode():
            self.string_for_textbox += self._STR1
        else:
            self.string_for_textbox += self._STR2
        if self.activity.wave.get_invert_state():
            self.string_for_textbox += self._STR3
        self.string_for_textbox += ('\n' + self._STR_SCALEX)
        self.activity.text_box.set_data_params(0, self.string_for_textbox)
Exemplo n.º 40
0
class SearchToolbar(gtk.Toolbar):
    __gtype_name__ = 'SearchToolbar'

    __gsignals__ = {
        'query-changed':
        (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([object])),
    }

    def __init__(self):
        gtk.Toolbar.__init__(self)

        self._mount_point = None

        self._search_entry = iconentry.IconEntry()
        self._search_entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY,
                                              'system-search')
        self._search_entry.connect('activate', self._search_entry_activated_cb)
        self._search_entry.connect('changed', self._search_entry_changed_cb)
        self._search_entry.add_clear_button()
        self._autosearch_timer = None
        self._add_widget(self._search_entry, expand=True)

        self._favorite_button = ToggleToolButton('emblem-favorite')
        self._favorite_button.connect('toggled',
                                      self.__favorite_button_toggled_cb)
        self.insert(self._favorite_button, -1)
        self._favorite_button.show()

        self._what_search_combo = ComboBox()
        self._what_combo_changed_sid = self._what_search_combo.connect(
            'changed', self._combo_changed_cb)
        tool_item = ToolComboBox(self._what_search_combo)
        self.insert(tool_item, -1)
        tool_item.show()

        self._when_search_combo = self._get_when_search_combo()
        tool_item = ToolComboBox(self._when_search_combo)
        self.insert(tool_item, -1)
        tool_item.show()

        self._sorting_button = SortingButton()
        self._sorting_button.connect('clicked',
                                     self.__sorting_button_clicked_cb)
        self.insert(self._sorting_button, -1)
        self._sorting_button.connect('sort-property-changed',
                                     self.__sort_changed_cb)
        self._sorting_button.show()

        # TODO: enable it when the DS supports saving the buddies.
        #self._with_search_combo = self._get_with_search_combo()
        #tool_item = ToolComboBox(self._with_search_combo)
        #self.insert(tool_item, -1)
        #tool_item.show()

        self._query = self._build_query()

        self.refresh_filters()

    def give_entry_focus(self):
        self._search_entry.grab_focus()

    def _get_when_search_combo(self):
        when_search = ComboBox()
        when_search.append_item(_ACTION_ANYTIME, _('Anytime'))
        when_search.append_separator()
        when_search.append_item(_ACTION_TODAY, _('Today'))
        when_search.append_item(_ACTION_SINCE_YESTERDAY, _('Since yesterday'))
        # TRANS: Filter entries modified during the last 7 days.
        when_search.append_item(_ACTION_PAST_WEEK, _('Past week'))
        # TRANS: Filter entries modified during the last 30 days.
        when_search.append_item(_ACTION_PAST_MONTH, _('Past month'))
        # TRANS: Filter entries modified during the last 356 days.
        when_search.append_item(_ACTION_PAST_YEAR, _('Past year'))
        when_search.set_active(0)
        when_search.connect('changed', self._combo_changed_cb)
        return when_search

    def _get_with_search_combo(self):
        with_search = ComboBox()
        with_search.append_item(_ACTION_EVERYBODY, _('Anyone'))
        with_search.append_separator()
        with_search.append_item(_ACTION_MY_FRIENDS, _('My friends'))
        with_search.append_item(_ACTION_MY_CLASS, _('My class'))
        with_search.append_separator()

        # TODO: Ask the model for buddies.
        with_search.append_item(3, 'Dan', 'theme:xo')

        with_search.set_active(0)
        with_search.connect('changed', self._combo_changed_cb)
        return with_search

    def _add_widget(self, widget, expand=False):
        tool_item = gtk.ToolItem()
        tool_item.set_expand(expand)

        tool_item.add(widget)
        widget.show()

        self.insert(tool_item, -1)
        tool_item.show()

    def _build_query(self):
        query = {}

        if self._mount_point:
            query['mountpoints'] = [self._mount_point]

        if self._favorite_button.props.active:
            query['keep'] = 1

        if self._what_search_combo.props.value:
            value = self._what_search_combo.props.value
            generic_type = mime.get_generic_type(value)
            if generic_type:
                mime_types = generic_type.mime_types
                query['mime_type'] = mime_types
            else:
                query['activity'] = self._what_search_combo.props.value

        if self._when_search_combo.props.value:
            date_from, date_to = self._get_date_range()
            query['timestamp'] = {'start': date_from, 'end': date_to}

        if self._search_entry.props.text:
            text = self._search_entry.props.text.strip()
            if text:
                query['query'] = text

        property_, order = self._sorting_button.get_current_sort()

        if order == gtk.SORT_ASCENDING:
            sign = '+'
        else:
            sign = '-'
        query['order_by'] = [sign + property_]

        return query

    def _get_date_range(self):
        today_start = datetime.today().replace(hour=0, minute=0, second=0)
        right_now = datetime.today()
        if self._when_search_combo.props.value == _ACTION_TODAY:
            date_range = (today_start, right_now)
        elif self._when_search_combo.props.value == _ACTION_SINCE_YESTERDAY:
            date_range = (today_start - timedelta(1), right_now)
        elif self._when_search_combo.props.value == _ACTION_PAST_WEEK:
            date_range = (today_start - timedelta(7), right_now)
        elif self._when_search_combo.props.value == _ACTION_PAST_MONTH:
            date_range = (today_start - timedelta(30), right_now)
        elif self._when_search_combo.props.value == _ACTION_PAST_YEAR:
            date_range = (today_start - timedelta(356), right_now)

        return (time.mktime(date_range[0].timetuple()),
                time.mktime(date_range[1].timetuple()))

    def _combo_changed_cb(self, combo):
        self._update_if_needed()

    def __sort_changed_cb(self, button):
        self._update_if_needed()

    def __sorting_button_clicked_cb(self, button):
        self._sorting_button.palette.popup(immediate=True, state=1)

    def _update_if_needed(self):
        new_query = self._build_query()
        if self._query != new_query:
            self._query = new_query
            self.emit('query-changed', self._query)

    def _search_entry_activated_cb(self, search_entry):
        if self._autosearch_timer:
            gobject.source_remove(self._autosearch_timer)
        new_query = self._build_query()
        if self._query != new_query:
            self._query = new_query
            self.emit('query-changed', self._query)

    def _search_entry_changed_cb(self, search_entry):
        if not search_entry.props.text:
            search_entry.activate()
            return

        if self._autosearch_timer:
            gobject.source_remove(self._autosearch_timer)
        self._autosearch_timer = gobject.timeout_add(_AUTOSEARCH_TIMEOUT,
                                                     self._autosearch_timer_cb)

    def _autosearch_timer_cb(self):
        logging.debug('_autosearch_timer_cb')
        self._autosearch_timer = None
        self._search_entry.activate()
        return False

    def set_mount_point(self, mount_point):
        self._mount_point = mount_point
        new_query = self._build_query()
        if self._query != new_query:
            self._query = new_query
            self.emit('query-changed', self._query)

    def set_what_filter(self, what_filter):
        combo_model = self._what_search_combo.get_model()
        what_filter_index = -1
        for i in range(0, len(combo_model) - 1):
            if combo_model[i][0] == what_filter:
                what_filter_index = i
                break

        if what_filter_index == -1:
            logging.warning('what_filter %r not known', what_filter)
        else:
            self._what_search_combo.set_active(what_filter_index)

    def refresh_filters(self):
        current_value = self._what_search_combo.props.value
        current_value_index = 0

        self._what_search_combo.handler_block(self._what_combo_changed_sid)
        try:
            self._what_search_combo.remove_all()
            # TRANS: Item in a combo box that filters by entry type.
            self._what_search_combo.append_item(_ACTION_ANYTHING,
                                                _('Anything'))

            registry = bundleregistry.get_registry()
            appended_separator = False

            types = mime.get_all_generic_types()
            for generic_type in types:
                if not appended_separator:
                    self._what_search_combo.append_separator()
                    appended_separator = True
                self._what_search_combo.append_item(generic_type.type_id,
                                                    generic_type.name,
                                                    generic_type.icon)
                if generic_type.type_id == current_value:
                    current_value_index = \
                            len(self._what_search_combo.get_model()) - 1

                self._what_search_combo.set_active(current_value_index)

            self._what_search_combo.append_separator()

            for service_name in model.get_unique_values('activity'):
                activity_info = registry.get_bundle(service_name)
                if activity_info is None:
                    continue

                if service_name == current_value:
                    combo_model = self._what_search_combo.get_model()
                    current_value_index = len(combo_model)

                # try activity-provided icon
                if os.path.exists(activity_info.get_icon()):
                    try:
                        self._what_search_combo.append_item(
                            service_name,
                            activity_info.get_name(),
                            file_name=activity_info.get_icon())
                    except glib.GError, exception:
                        logging.warning(
                            'Falling back to default icon for'
                            ' "what" filter because %r (%r) has an'
                            ' invalid icon: %s', activity_info.get_name(),
                            str(service_name), exception)
                    else:
                        continue

                # fall back to generic icon
                self._what_search_combo.append_item(
                    service_name,
                    activity_info.get_name(),
                    icon_name='application-octet-stream')

        finally:
            self._what_search_combo.handler_unblock(
                self._what_combo_changed_sid)

    def __favorite_button_toggled_cb(self, favorite_button):
        self._update_if_needed()

    def clear_query(self):
        self._search_entry.props.text = ''
        self._what_search_combo.set_active(0)
        self._when_search_combo.set_active(0)
        self._favorite_button.props.active = False
Exemplo n.º 41
0
class SensorToolbar(gtk.Toolbar):
    ''' The toolbar for specifiying the sensor: sound, resitance, or
    voltage '''

    LOWER = 0.0
    UPPER = 1.0
    STR_DC_R = \
        _("Resistive sensor (connect sensor to pink 'Mic In' on left side \
of XO)"       ) + ' '
    STR_DC_V = \
        _("Voltage sensor (connect sensor to pink 'Mic In' on left side \
of XO)"       ) + ' '
    STR_AC = _('Sound') + ' '
    STR_RESISTANCE = _('Resistance') + ' (' + _('Ohms') + ') '
    STR_VOLTAGE = _('Voltage') + ' (' + _('Volts') + ') '
    STR_TIME = _('Time Base') + ' '
    STR_FREQUENCY = _('Frequency Base') + ' '
    STR_INVERT = ' ' + _('Invert') + ' '
    STR_XAXIS_TEXT = _('X Axis Scale: 1 division = %(division)s %(unit)s')
    # TRANSLATORS: This is milli seconds.
    MS = _('ms')
    # TRANSLATORS: This is Hertz, so 1/second.
    HZ = _('Hz')

    def __init__(self, activity, channels):
        ''' By default, start with resistance mode '''

        gtk.Toolbar.__init__(self)

        self.activity = activity
        self._channels = channels
        self._lock_radio_buttons = False
        self._radio_button_pushed = False
        self.values = []
        for i in range(self._channels):
            self.values.append('')

        self.string_for_textbox = ''

        self.gain = 1.0
        self.y_mag = 3.0
        self.capture_gain = CAPTURE_GAIN
        self.mic_boost = MIC_BOOST

        self.mode = 'sound'

        # Set up Time-domain Button
        self.time = RadioToolButton(group=None)
        self.time.set_named_icon('media-audio')
        self.insert(self.time, -1)
        self.time.set_tooltip(_('Sound'))
        self.time.connect('clicked', self.analog_resistance_voltage_mode_cb,
                          'sound')

        # Set up Resistance Button
        self.resistance = RadioToolButton(group=self.time)
        self.resistance.set_named_icon('resistance')
        if _is_xo(self.activity.hw):
            self.insert(self.resistance, -1)
        self.resistance.show()
        self.resistance.set_tooltip(_('Resistance Sensor'))
        self.resistance.connect('clicked',
                                self.analog_resistance_voltage_mode_cb,
                                'resistance')

        # Set up Voltage Button
        self.voltage = RadioToolButton(group=self.time)
        self.voltage.set_named_icon('voltage')
        if _is_xo(self.activity.hw):
            self.insert(self.voltage, -1)
        self.voltage.set_tooltip(_('Voltage Sensor'))
        self.voltage.connect('clicked', self.analog_resistance_voltage_mode_cb,
                             'voltage')

        separator = gtk.SeparatorToolItem()
        separator.props.draw = True
        self.insert(separator, -1)

        self._log_interval_combo = ComboBox()
        self.interval = [
            _('1/10 second'),
            _('1 second'),
            _('30 seconds'),
            _('5 minutes'),
            _('30 minutes')
        ]

        if hasattr(self._log_interval_combo, 'set_tooltip_text'):
            self._log_interval_combo.set_tooltip_text(_('Sampling interval'))

        self._interval_changed_id = self._log_interval_combo.connect(
            'changed', self.log_interval_cb)

        for i, s in enumerate(self.interval):
            self._log_interval_combo.append_item(i, s, None)
            if s == _('1 second'):
                self._log_interval_combo.set_active(i)

        self._log_interval_tool = ToolComboBox(self._log_interval_combo)
        self.insert(self._log_interval_tool, -1)
        self.logging_interval_status = '1 second'

        # Set up Logging/Stop Logging Button
        self._record = ToolButton('media-record')
        self.insert(self._record, -1)
        self._record.set_tooltip(_('Start Recording'))
        self._record.connect('clicked', self.record_control_cb)

        if self.activity.has_toolbarbox:
            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            self.insert(separator, -1)

        # Set up Trigger Combo box
        self.trigger_combo = ComboBox()
        self.trigger = [_('None'), _('Rising Edge'), _('Falling Edge')]
        self.trigger_conf = [
            self.activity.wave.TRIGGER_NONE, self.activity.wave.TRIGGER_POS,
            self.activity.wave.TRIGGER_NEG
        ]
        self._trigger_changed_id = self.trigger_combo.connect(
            'changed', self.update_trigger_control)
        for i, s in enumerate(self.trigger):
            self.trigger_combo.append_item(i, s, None)
        self.trigger_combo.set_active(0)
        if hasattr(self.trigger_combo, 'set_tooltip_text'):
            self.trigger_combo.set_tooltip_text(_('Create a trigger'))
        self._trigger_tool = ToolComboBox(self.trigger_combo)
        self.insert(self._trigger_tool, -1)

        self.show_all()

    def add_frequency_slider(self, toolbar):
        ''' Either on the Sound toolbar or the Main toolbar '''
        self._freq_stepper_up = ToolButton('freq-high')
        self._freq_stepper_up.set_tooltip(_('Zoom out'))
        self._freq_stepper_up.connect('clicked', self._freq_stepper_up_cb)
        self.activity.adjustmentf = gtk.Adjustment(0.5, self.LOWER, self.UPPER,
                                                   0.01, 0.1, 0)
        self.activity.adjustmentf.connect('value_changed', self.cb_page_sizef)
        self._freq_range = gtk.HScale(self.activity.adjustmentf)
        self._freq_range.set_inverted(True)
        self._freq_range.set_draw_value(False)
        self._freq_range.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self._freq_range.set_size_request(120, 15)

        self._freq_stepper_down = ToolButton('freq-low')
        self._freq_stepper_down.set_tooltip(_('Zoom in'))
        self._freq_stepper_down.connect('clicked', self._freq_stepper_down_cb)

        self._freq_range_tool = gtk.ToolItem()
        self._freq_range_tool.add(self._freq_range)

        toolbar.insert(self._freq_stepper_up, -1)
        toolbar.insert(self._freq_range_tool, -1)
        toolbar.insert(self._freq_stepper_down, -1)
        return

    def update_trigger_control(self, *args):
        ''' Callback for trigger control '''
        if self.activity.wave.get_fft_mode():
            self.trigger_combo.set_active(self.activity.wave.TRIGGER_NONE)
        active = self.trigger_combo.get_active()
        if active == -1:
            return

        self.activity.wave.set_trigger(self.trigger_conf[active])
        return

    def analog_resistance_voltage_mode_cb(self,
                                          button=None,
                                          mode_to_set='sound'):
        ''' Callback for Analog/Resistance/Voltage Buttons '''
        if self._lock_radio_buttons:
            logging.debug('mode selector locked')
            self._radio_button_pushed = True
            return
        if self.mode == mode_to_set:
            logging.debug('mode already set to %s' % mode_to_set)
            return
        self._lock_radio_buttons = True
        if self.activity.CONTEXT == 'sound':
            self.sound_context_off()
        else:
            self.sensor_context_off()

        # Force time domain when switching modes
        if self.activity.wave.get_fft_mode():
            self.activity.timefreq_control()
        # Turn off logging when switching modes
        if self.activity.audiograb.we_are_logging:
            self.record_control_cb()

        self.set_mode(mode_to_set)
        if mode_to_set == 'sound':
            self.set_sound_context()
        elif mode_to_set == 'resistance':
            self.set_sensor_context()
        elif mode_to_set == 'voltage':
            self.set_sensor_context()
        self.update_string_for_textbox()
        return False

    def unlock_radio_buttons(self):
        ''' Enable radio button selection '''
        logging.debug('unlocking radio buttons')
        if self._radio_button_pushed:
            if self.mode == 'sound':
                self.time.set_active(True)
            elif self.mode == 'resistance':
                self.resistance.set_active(True)
            elif self.mode == 'voltage':
                self.voltage.set_active(True)
        self._lock_radio_buttons = False
        self._radio_button_pushed = False

    def set_mode(self, mode='sound'):
        ''' Set the mixer settings to match the current mode. '''
        self.mode = mode
        self.activity.audiograb.set_sensor_type(self.mode)
        for i in range(self._channels):
            self.values[i] = 0.0
        return

    def get_mode(self):
        ''' Get the mixer settings. '''
        return self.mode

    def _freq_stepper_up_cb(self, button=None):
        ''' Moves the horizontal zoom slider to the left one notch,
        where one notch is 1/100 of the total range. This correspond
        to zooming out as a larger number of Hertz or milliseconds
        will be represented by the same space on the screen. '''
        new_value = self._freq_range.get_value() +\
                    (self.UPPER - self.LOWER) / 100.0
        if new_value <= self.UPPER:
            self._freq_range.set_value(new_value)
        else:
            self._freq_range.set_value(self.UPPER)

    def _freq_stepper_down_cb(self, button=None):
        ''' Moves the horizontal zoom slider to the right one notch,
        where one notch is 1/100 of the total range. This corresponds
        to zooming in. '''
        new_value = self._freq_range.get_value() -\
                    (self.UPPER - self.LOWER) / 100.0
        if new_value >= self.LOWER:
            self._freq_range.set_value(new_value)
        else:
            self._freq_range.set_value(self.LOWER)

    def cb_page_sizef(self, button=None):
        ''' Callback to scale the frequency range (zoom in and out) '''
        if self._update_page_size_id:
            gobject.source_remove(self._update_page_size_id)
        self._update_page_size_id =\
            gobject.timeout_add(250, self.update_page_size)
        return True

    def update_page_size(self):
        ''' Set up the scaling of the display. '''
        self._update_page_size_id = None
        new_value = round(self.activity.adjustmentf.value * 100.0) / 100.0
        if self.activity.adjustmentf.value != new_value:
            self.activity.adjustmentf.value = new_value
            return False
        time_div = 0.001 * max(self.activity.adjustmentf.value, 0.05)
        freq_div = 1000 * max(self.activity.adjustmentf.value, 0.01)
        self.activity.wave.set_div(time_div, freq_div)
        self.update_string_for_textbox()
        return False

    def set_sound_context(self):
        ''' Called when analog sensing is selected '''
        self.set_show_hide_windows(mode='sound')
        gobject.timeout_add(500, self.sound_context_on)
        self.activity.CONTEXT = 'sound'

    def set_sensor_context(self):
        ''' Called when digital sensing is selected '''
        self.set_show_hide_windows(mode='sensor')
        gobject.timeout_add(500, self.sensor_context_on)
        self.activity.CONTEXT = 'sensor'

    def set_show_hide_windows(self, mode='sound'):
        ''' Shows the appropriate window identified by the mode '''
        self.activity.wave.set_context_on()
        for i in range(self._channels):
            self.activity.side_toolbars[i].set_show_hide(True, mode)

    def sensor_context_off(self):
        ''' Called when a DC sensor is no longer selected '''
        # self.activity.audiograb.pause_grabbing()
        self.activity.audiograb.stop_grabbing()

    def sensor_context_on(self):
        ''' Called when a DC sensor is selected '''
        self.update_string_for_textbox()
        self.activity.wave.set_trigger(self.activity.wave.TRIGGER_NONE)
        # self.activity.audiograb.resume_grabbing()
        self.activity.audiograb.start_grabbing()
        return False

    def sound_context_off(self):
        ''' Called when an analog sensor is no longer selected '''
        self.gain, self.y_mag = self.activity.wave.get_mag_params()
        self.capture_gain = self.activity.audiograb.get_capture_gain()
        self.mic_boost = self.activity.audiograb.get_mic_boost()
        self.activity.audiograb.stop_grabbing()

    def sound_context_on(self):
        ''' Called when an analog sensor is selected '''
        self.activity.wave.set_mag_params(self.gain, self.y_mag)
        self.update_string_for_textbox()
        self.update_trigger_control()
        self.activity.audiograb.start_grabbing()
        return False

    def set_sample_value(self, value='', channel=0):
        ''' Write a sample value to the textbox. '''
        gtk.threads_enter()
        self.values[channel] = value
        self.update_string_for_textbox()
        gtk.threads_leave()
        return

    def record_control_cb(self, button=None):
        ''' Depending upon the selected interval, does either a logging
        session, or just logs the current buffer. '''
        if self.activity.audiograb.we_are_logging:
            self.activity.audiograb.set_logging_params(start_stop=False)
            self._record.set_icon('media-record')
            self._record.show()
            self._record.set_tooltip(_('Start Recording'))
        else:
            Xscale = (1.00 / self.activity.audiograb.get_sampling_rate())
            Yscale = 0.0
            interval = self.interval_convert()
            username = self.activity.nick
            if self.activity.wave.get_fft_mode():
                self.activity.data_logger.start_new_session(
                    username,
                    Xscale,
                    Yscale,
                    _(self.logging_interval_status),
                    channels=self._channels,
                    mode='frequency')
            else:
                self.activity.data_logger.start_new_session(
                    username,
                    Xscale,
                    Yscale,
                    _(self.logging_interval_status),
                    channels=self._channels,
                    mode=self.mode)
            self.activity.audiograb.set_logging_params(start_stop=True,
                                                       interval=interval,
                                                       screenshot=False)
            self._record.set_icon('record-stop')
            self._record.show()
            self._record.set_tooltip(_('Stop Recording'))
            self.activity.new_recording = True

    def interval_convert(self):
        ''' Converts interval string to an integer that denotes the
        number of times the audiograb buffer must be called before a
        value is written.  When set to 0, the whole of current buffer
        will be written. '''
        interval_dictionary = {
            '1/10 second': 0.1,
            '1 second': 1,
            '30 seconds': 30,
            '5 minutes': 300,
            '30 minutes': 1800
        }
        try:
            return interval_dictionary[self.logging_interval_status]
        except ValueError:
            logging.error('logging interval status = %s' %\
                              (str(self.logging_interval_status)))
            return 0

    def log_interval_cb(self, combobox):
        ''' Callback from the Logging Interval Combo box: sets status '''
        if self._log_interval_combo.get_active() != -1:
            intervals = [
                '1/10 second', '1 second', '30 seconds', '5 minutes',
                '30 minutes'
            ]
            self.logging_interval_status = \
                              intervals[self._log_interval_combo.get_active()]

    def update_string_for_textbox(self):
        ''' Update the status field at the bottom of the canvas. '''
        if self.activity.CONTEXT == 'butia':
            string_for_textbox = ''
        else:
            if self.mode == 'resistance':
                string_for_textbox = (self.STR_DC_R + '\n')
                string_for_textbox += self.STR_RESISTANCE
            elif self.mode == 'voltage':
                string_for_textbox = (self.STR_DC_V + '\n')
                string_for_textbox += self.STR_VOLTAGE
            else:
                string_for_textbox = (self.STR_AC + '\t')
            if self.activity.wave.get_fft_mode():
                scalex = self.STR_XAXIS_TEXT % {
                    'unit': self.HZ,
                    'division': self.activity.wave.freq_div
                }
                string_for_textbox += self.STR_FREQUENCY
                string_for_textbox += ('\n' + scalex)
            elif self.mode == 'sound':
                scalex = self.STR_XAXIS_TEXT % {
                    'unit': self.MS,
                    'division': self.activity.wave.time_div * 1000
                }
                string_for_textbox += self.STR_TIME
                string_for_textbox += ('\n' + scalex)
            else:
                for i in range(self._channels):
                    string_for_textbox += '\t(%s)' % (self.values[i])
        invert = False
        for i in range(self._channels):
            if self.activity.wave.get_invert_state(channel=i):
                invert = True
        if invert:
            string_for_textbox += self.STR_INVERT
        self.activity.text_box.set_label(string_for_textbox)
Exemplo n.º 42
0
    def __init__(self, activity):
        """ Initialize the toolbar controls. """
        gtk.Toolbar.__init__(self)

        self.activity = activity

        self._STR_BASIC = _('Sound') + ' '
        self._STR1 = _('Time Base') + ' '
        self._STR2 = _('Frequency Base') + ' '
        self._STR3 = ' ' + _('Invert') + ' '
        self._STR_SCALEX = ""
        self._STR_XAXIS_TEXT = \
            _('X Axis Scale: 1 division = %(division)s %(unit)s')
        # TRANSLATORS: This is milli seconds.
        self._ms = _('ms')
        # TRANSLATORS: This is Hertz, so 1/second.
        self._Hz = _('Hz')

        self._update_page_size_id = None

        self.string_for_textbox = ""

        self.gain = 1.0
        self.y_mag = 3.0
        self.capture_gain = CAPTURE_GAIN
        self.mic_boost = MIC_BOOST

        # self.logging_status = False
        self._record = None

        # Set up Time-domain Button
        self.time = ToolButton('domain-time2')
        self.insert(self.time, -1)
        self.time.set_tooltip(_('Time Base'))
        self.time.connect('clicked', self._timefreq_control_cb, True)

        # Set up Frequency-domain Button
        self.freq = ToolButton('domain-freq')
        self.insert(self.freq, -1)
        self.freq.show()
        self.freq.set_tooltip(_('Frequency Base'))
        self.freq.connect('clicked', self._timefreq_control_cb, False)

        # Set up Frequency-control Slider and corresponding buttons
        if not self.activity.has_toolbarbox:
            self.add_frequency_slider(self)

        # Set up the Pause Button
        self._pause = ToolButton('media-playback-pause')
        self.insert(self._pause, -1)
        self._pause.set_tooltip(_('Freeze the display'))
        self._pause.connect('clicked', self._pauseplay_control_cb)

        if self.activity.has_toolbarbox:
            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            self.insert(separator, -1)
            separator.show()

        self.loginterval_img = gtk.Image()
        self.loginterval_img.set_from_file(ICONS_DIR + 'sample_rate.svg')
        self.loginterval_img_tool = gtk.ToolItem()
        self.loginterval_img_tool.add(self.loginterval_img)
        self.insert(self.loginterval_img_tool, -1)

        # Set up the Logging-interval Combo box
        self._loginterval_combo = ComboBox()
        self.interval = [
            _(self.SAMPLE_NOW),
            _(self.SAMPLE_30_SEC),
            _(self.SAMPLE_2_MIN),
            _(self.SAMPLE_10_MIN),
            _(self.SAMPLE_30_MIN)
        ]

        if hasattr(self._loginterval_combo, 'set_tooltip_text'):
            self._loginterval_combo.set_tooltip_text(_('Sampling interval'))

        self._interval_changed_id = self._loginterval_combo.connect(
            'changed', self.loginterval_control)

        for i, s in enumerate(self.interval):
            self._loginterval_combo.append_item(i, s, None)
            if s == self.SAMPLE_NOW:
                self._loginterval_combo.set_active(i)

        self._loginterval_tool = ToolComboBox(self._loginterval_combo)
        self.insert(self._loginterval_tool, -1)
        self.logginginterval_status = 'picture'

        # Set up Start/Stop Logging Button
        self._record = ToolButton('media-record')
        self.insert(self._record, -1)
        self._record.set_tooltip(_('Capture sample now'))

        self._record.connect('clicked', self.record_control)

        if self.activity.has_toolbarbox:
            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            self.insert(separator, -1)

        # Set up Trigger Combo box
        self._trigger_combo = ComboBox()
        self.trigger = [_('None'), _('Rising Edge'), _('Falling Edge')]
        self.trigger_conf = [
            self.activity.wave.TRIGGER_NONE, self.activity.wave.TRIGGER_POS,
            self.activity.wave.TRIGGER_NEG
        ]

        self._trigger_changed_id = self._trigger_combo.connect(
            'changed', self.update_trigger_control)

        for i, s in enumerate(self.trigger):
            self._trigger_combo.append_item(i, s, None)
        self._trigger_combo.set_active(0)

        if hasattr(self._trigger_combo, 'set_tooltip_text'):
            self._trigger_combo.set_tooltip_text(_('Create a trigger'))

        self._trigger_tool = ToolComboBox(self._trigger_combo)
        self.insert(self._trigger_tool, -1)
        self.show_all()

        return
Exemplo n.º 43
0
    def create_dialog(self):
        """Setup most of the dialog."""

# Toolbar
        try:
            self._toolbar_box = ToolbarBox()

            activity_button = ActivityToolbarButton(self._parent)
            self._toolbar_box.toolbar.insert(activity_button, 0)
            
            def append(icon_name, label, page, position):
                toolbar_button = ToolbarButton()
                toolbar_button.props.page = page
                toolbar_button.props.icon_name = icon_name
                toolbar_button.props.label = label
                self._toolbar_box.toolbar.insert(toolbar_button, position)

            append('toolbar-edit',
                   _('Edit'),
                   EditToolbar(self._parent),
                   -1)
                                  
            append('toolbar-algebra',
                   _('Algebra'),
                   AlgebraToolbar(self._parent),
                   -1)
            
            append('toolbar-trigonometry',
                   _('Trigonometry'),
                   TrigonometryToolbar(self._parent),
                   -1)

            append('toolbar-boolean',
                   _('Boolean'),
                   BooleanToolbar(self._parent),
                   -1)

            self._misc_toolbar = MiscToolbar(
                self._parent,
                target_toolbar=self._toolbar_box.toolbar)

            append('toolbar-constants',
                   _('Miscellaneous'),
                   self._misc_toolbar,
                   5)
            
            self._stop_separator = gtk.SeparatorToolItem()
            self._stop_separator.props.draw = False
            self._stop_separator.set_expand(True)
            self._stop_separator.show()
            self._toolbar_box.toolbar.insert(self._stop_separator, -1)

            self._stop = StopButton(self._parent)
            self._toolbar_box.toolbar.insert(self._stop, -1)

            self._toolbar_box.show_all()
            self._parent.set_toolbar_box(self._toolbar_box)

        except NameError:
            # Use old toolbar design
            toolbox = activity.ActivityToolbox(self._parent)
            self._parent.set_toolbox(toolbox)
            toolbox.add_toolbar(_('Edit'), EditToolbar(self._parent))
            toolbox.add_toolbar(_('Algebra'), AlgebraToolbar(self._parent))
            toolbox.add_toolbar(_('Trigonometry'), TrigonometryToolbar(self._parent))
            toolbox.add_toolbar(_('Boolean'), BooleanToolbar(self._parent))
            toolbox.add_toolbar(_('Miscellaneous'), MiscToolbar(self._parent))
            toolbox.show_all()

# Some layout constants
        self.input_font = pango.FontDescription(str='sans bold 12')
        self.button_font = pango.FontDescription(str='sans bold 16')
        self.col_white = self.create_color(1.00, 1.00, 1.00)
        self.col_gray1 = self.create_color(0.76, 0.76, 0.76)
        self.col_gray2 = self.create_color(0.50, 0.50, 0.50)
        self.col_gray3 = self.create_color(0.25, 0.25, 0.25)
        self.col_black = self.create_color(0.00, 0.00, 0.00)
        self.col_red = self.create_color(1.00, 0.00, 0.00)

# Big - Table, 16 rows, 10 columns, homogeneously divided
        self.grid = gtk.Table(26, 11, True)
        self.grid.set_border_width(0)
        self.grid.set_row_spacings(0)
        self.grid.set_col_spacings(4)

# Left part: container and input
        vc1 = gtk.VBox(False, 0)
        hc1 = gtk.HBox(False, 10)
        eb = gtk.EventBox()
        eb.add(hc1)
        eb.modify_bg(gtk.STATE_NORMAL, self.col_black)
        eb.set_border_width(12)
        eb2 = gtk.EventBox()
        eb2.add(eb)
        eb2.modify_bg(gtk.STATE_NORMAL, self.col_black)
        label1 = gtk.Label(_('Label:'))
        label1.modify_fg(gtk.STATE_NORMAL, self.col_white)
        label1.set_alignment(1, 0.5)
        hc1.pack_start(label1, expand=False, fill=False, padding=10)
        self.label_entry = gtk.Entry()
        self.label_entry.modify_bg(gtk.STATE_INSENSITIVE, self.col_black)
        hc1.pack_start(self.label_entry, expand=True, fill=True, padding=0)
        vc1.pack_start(eb2, expand=False)
        
        self.text_entry = gtk.Entry()
        try:
            self.text_entry.props.im_module = 'gtk-im-context-simple'
        except AttributeError:
            pass
        self.text_entry.set_size_request(-1, 75)
        self.text_entry.connect('key_press_event', self._parent.ignore_key_cb)
        self.text_entry.modify_font(self.input_font)
        self.text_entry.modify_bg(gtk.STATE_INSENSITIVE, self.col_black)
        eb = gtk.EventBox()
        eb.add(self.text_entry)
        eb.modify_bg(gtk.STATE_NORMAL, self.col_black)
        eb.set_border_width(12)
        eb2 = gtk.EventBox()
        eb2.add(eb)
        eb2.modify_bg(gtk.STATE_NORMAL, self.col_black)
        vc1.pack_start(eb2, expand=True, fill=True, padding=0)
        self.grid.attach(vc1, 0, 7, 0, 6)

# Left part: buttons
        self.pad = gtk.Table(9, 6, True)
        self.pad.set_row_spacings(12)
        self.pad.set_col_spacings(12)
        self.pad.set_border_width(12)
        self.create_button_data()
        self.buttons = {}
        for x, y, w, h, cap, bgcol, cb in self.button_data:
            button = self.create_button(_(cap), cb, self.col_white, bgcol, w, h)
            self.buttons[cap] = button
            self.pad.attach(button, x, x + w, y, y + h)

        eb = gtk.EventBox()
        eb.add(self.pad)
        eb.modify_bg(gtk.STATE_NORMAL, self.col_black)
        self.grid.attach(eb, 0, 7, 6, 26)

# Right part: container and equation button
        hc2 = gtk.HBox()
        combo = ComboBox()
        combo.append_item(0, _('All equations'))
        combo.append_item(1, _('My equations'))
        combo.append_item(2, _('Show variables'))
        combo.set_active(0)
        combo.connect('changed', self._history_filter_cb)
        hc2.pack_start(combo) 
        hc2.set_border_width(6)
        self.grid.attach(hc2, 7, 11, 0, 2)
        
# Right part: last equation
        self.last_eq = gtk.TextView()
        self.last_eq.set_editable(False)
        self.last_eq.set_wrap_mode(gtk.WRAP_WORD_CHAR)
        self.last_eq.connect('realize', self._textview_realize_cb)
        self.last_eq.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse(
                                 sugar.profile.get_color().get_fill_color()))
        self.last_eq.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(
                                 sugar.profile.get_color().get_stroke_color()))
        self.last_eq.set_border_window_size(gtk.TEXT_WINDOW_LEFT, 4)
        self.last_eq.set_border_window_size(gtk.TEXT_WINDOW_RIGHT, 4)
        self.last_eq.set_border_window_size(gtk.TEXT_WINDOW_TOP, 4)
        self.last_eq.set_border_window_size(gtk.TEXT_WINDOW_BOTTOM, 4)

        # TODO Fix for old Sugar 0.82 builds, red_float not available
        bright = (gtk.gdk.color_parse(sugar.profile.get_color().get_fill_color()).red_float +
                  gtk.gdk.color_parse(sugar.profile.get_color().get_fill_color()).green_float +
                  gtk.gdk.color_parse(sugar.profile.get_color().get_fill_color()).blue_float) / 3.0
        if bright < 0.5:
            self.last_eq.modify_text(gtk.STATE_NORMAL, self.col_white)
        else:
            self.last_eq.modify_text(gtk.STATE_NORMAL, self.col_black)

        self.grid.attach(self.last_eq, 7, 11, 2, 7)

# Right part: history
        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)

        self.history_vbox = gtk.VBox()
        self.history_vbox.set_homogeneous(False)
        self.history_vbox.set_border_width(0)
        self.history_vbox.set_spacing(4)

        self.variable_vbox = gtk.VBox()
        self.variable_vbox.set_homogeneous(False)
        self.variable_vbox.set_border_width(0)
        self.variable_vbox.set_spacing(4)

        vbox = gtk.VBox()
        vbox.pack_start(self.history_vbox)
        vbox.pack_start(self.variable_vbox)
        scrolled_window.add_with_viewport(vbox)
        self.grid.attach(scrolled_window, 7, 11, 7, 26)

        gtk.gdk.screen_get_default().connect('size-changed',
                                             self._configure_cb)
Exemplo n.º 44
0
    def __init__(self, activity, channels):
        ''' By default, start with resistance mode '''

        gtk.Toolbar.__init__(self)

        self.activity = activity
        self._channels = channels
        self._lock_radio_buttons = False
        self._radio_button_pushed = False
        self.values = []
        for i in range(self._channels):
            self.values.append('')

        self.string_for_textbox = ''

        self.gain = 1.0
        self.y_mag = 3.0
        self.capture_gain = CAPTURE_GAIN
        self.mic_boost = MIC_BOOST

        self.mode = 'sound'

        # Set up Time-domain Button
        self.time = RadioToolButton(group=None)
        self.time.set_named_icon('media-audio')
        self.insert(self.time, -1)
        self.time.set_tooltip(_('Sound'))
        self.time.connect('clicked', self.analog_resistance_voltage_mode_cb,
                          'sound')

        # Set up Resistance Button
        self.resistance = RadioToolButton(group=self.time)
        self.resistance.set_named_icon('resistance')
        if _is_xo(self.activity.hw):
            self.insert(self.resistance, -1)
        self.resistance.show()
        self.resistance.set_tooltip(_('Resistance Sensor'))
        self.resistance.connect('clicked',
                                self.analog_resistance_voltage_mode_cb,
                                'resistance')

        # Set up Voltage Button
        self.voltage = RadioToolButton(group=self.time)
        self.voltage.set_named_icon('voltage')
        if _is_xo(self.activity.hw):
            self.insert(self.voltage, -1)
        self.voltage.set_tooltip(_('Voltage Sensor'))
        self.voltage.connect('clicked', self.analog_resistance_voltage_mode_cb,
                             'voltage')

        separator = gtk.SeparatorToolItem()
        separator.props.draw = True
        self.insert(separator, -1)

        self._log_interval_combo = ComboBox()
        self.interval = [
            _('1/10 second'),
            _('1 second'),
            _('30 seconds'),
            _('5 minutes'),
            _('30 minutes')
        ]

        if hasattr(self._log_interval_combo, 'set_tooltip_text'):
            self._log_interval_combo.set_tooltip_text(_('Sampling interval'))

        self._interval_changed_id = self._log_interval_combo.connect(
            'changed', self.log_interval_cb)

        for i, s in enumerate(self.interval):
            self._log_interval_combo.append_item(i, s, None)
            if s == _('1 second'):
                self._log_interval_combo.set_active(i)

        self._log_interval_tool = ToolComboBox(self._log_interval_combo)
        self.insert(self._log_interval_tool, -1)
        self.logging_interval_status = '1 second'

        # Set up Logging/Stop Logging Button
        self._record = ToolButton('media-record')
        self.insert(self._record, -1)
        self._record.set_tooltip(_('Start Recording'))
        self._record.connect('clicked', self.record_control_cb)

        if self.activity.has_toolbarbox:
            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            self.insert(separator, -1)

        # Set up Trigger Combo box
        self.trigger_combo = ComboBox()
        self.trigger = [_('None'), _('Rising Edge'), _('Falling Edge')]
        self.trigger_conf = [
            self.activity.wave.TRIGGER_NONE, self.activity.wave.TRIGGER_POS,
            self.activity.wave.TRIGGER_NEG
        ]
        self._trigger_changed_id = self.trigger_combo.connect(
            'changed', self.update_trigger_control)
        for i, s in enumerate(self.trigger):
            self.trigger_combo.append_item(i, s, None)
        self.trigger_combo.set_active(0)
        if hasattr(self.trigger_combo, 'set_tooltip_text'):
            self.trigger_combo.set_tooltip_text(_('Create a trigger'))
        self._trigger_tool = ToolComboBox(self.trigger_combo)
        self.insert(self._trigger_tool, -1)

        self.show_all()
Exemplo n.º 45
0
 def __init__(self):
 
     ComboBox.__init__(self)