예제 #1
0
    def setup_toolbar(self):
        '''Setup the top toolbar. Groupthink needs some work here.'''
        toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.edit_toolbar = EditToolbar()
        edit_toolbar_button = ToolbarButton(page=self.edit_toolbar,
                                            icon_name='toolbar-edit')
        self.edit_toolbar.show()
        toolbar_box.toolbar.insert(edit_toolbar_button, -1)
        edit_toolbar_button.show()

        self.edit_toolbar.undo.connect('clicked', self.undobutton_cb)
        self.edit_toolbar.redo.connect('clicked', self.redobutton_cb)
        self.edit_toolbar.copy.connect('clicked', self.copybutton_cb)
        self.edit_toolbar.paste.connect('clicked', self.pastebutton_cb)

        separator = gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl><Shift>Q'
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show()
예제 #2
0
 def __init__(self, activity, **kwargs):
     print "MY Alternative tOOLbARbUTTON init\n"
     toolbar = ActivityToolbar(activity, orientation_left=True)
     toolbar.stop.hide()
     toolbar.keep.hide()
     ToolbarButton.__init__(self, page=toolbar, **kwargs)
     icon = _create_activity_icon(activity.metadata)
     self.set_icon_widget(icon)
     icon.show()
예제 #3
0
    def build_colors_toolbar(self, toolbox):

        barra_colors = gtk.Toolbar()

        item1 = gtk.ToolItem()
        label1 = gtk.Label()
        label1.set_text(_('Color mode') + ' ')
        item1.add(label1)
        barra_colors.insert(item1, -1)

        item2 = gtk.ToolItem()
        modes = ('RGB', 'YUV', 'HSV')
        combo = Combo(modes)
        item2.add(combo)
        combo.connect('changed', self.change_combo)
        barra_colors.insert(item2, -1)

        separator1 = gtk.SeparatorToolItem()
        separator1.props.draw = True
        barra_colors.insert(separator1, -1)

        item_l = gtk.ToolItem()
        label4 = gtk.Label()
        label4.set_text(_('Brightness') + ' ')
        item_l.add(label4)
        barra_colors.insert(item_l, -1)

        item = gtk.ToolItem()
        brightness_spin = gtk.SpinButton()
        brightness_spin.set_range(-1, 255)
        brightness_spin.set_increments(1, 10)
        brightness_spin.props.value = int(self.brightness)
        brightness_spin.connect('notify::value', self.brightness_spin_change)
        item.add(brightness_spin)
        barra_colors.insert(item, -1)

        separator2 = gtk.SeparatorToolItem()
        separator2.props.draw = True
        barra_colors.insert(separator2, -1)

        item3 = gtk.ToolItem()
        label3 = gtk.Label()
        label3.set_text(_('Show threshold view'))
        item3.add(label3)
        barra_colors.insert(item3, -1)

        threshold_view = ToolButton('media-playback-stop')
        threshold_view.connect('clicked', self.threshold_view)
        threshold_view.set_tooltip(_('Yes'))
        barra_colors.insert(threshold_view, -1)

        barra_colors.show_all()
        colors_button = ToolbarButton(label=_('Colors'),
                                      page=barra_colors,
                                      icon_name='toolbar-colors')
        toolbox.toolbar.insert(colors_button, -1)
        colors_button.show()
예제 #4
0
 def addToolBarButton(self, nameID, icon_name, toolbar=None):
     "I wonder if this can be merged with the ad button below?"
     button = ToolbarButton(
         page=toolbar,
         icon_name=icon_name)
     self.toolbar_box.toolbar.insert(button, -1)
     button.show()
     toolbar.show()
     self.nameID.update({nameID:button})
예제 #5
0
    def __init__(self, activity, **kwargs):
        toolbar = ActivityToolbar(activity, orientation_left=True)
        toolbar.stop.hide()

        ToolbarButton.__init__(self, page=toolbar, **kwargs)

        icon = _create_activity_icon(activity.metadata)
        self.set_icon_widget(icon)
        icon.show()
예제 #6
0
    def __init__(self, activity, **kwargs):
        toolbar = ActivityToolbar(activity, orientation_left=True)
        toolbar.stop.hide()

        ToolbarButton.__init__(self, page=toolbar, **kwargs)

        icon = _create_activity_icon(activity.metadata)
        self.set_icon_widget(icon)
        icon.show()
예제 #7
0
    def build_birth_toolbar(self, toolbox):

        birth_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        self.label_birth = gtk.Label()
        self.label_birth.set_text(_('Birth:') + ' ' + _('Day') + ' ')
        item1.add(self.label_birth)
        birth_bar.insert(item1, -1)

        item2 = gtk.ToolItem()
        self.day_birth_spin = gtk.SpinButton()
        self.day_birth_spin.set_range(1, 31)
        self.day_birth_spin.set_increments(1, 5)
        self.day_birth_spin.props.value = 10
        self.day_birth_spin.connect('notify::value', self.day_birth_change)
        item2.add(self.day_birth_spin)
        birth_bar.insert(item2, -1)

        item3 = gtk.ToolItem()
        self.label_birth_month = gtk.Label()
        self.label_birth_month.set_text(' ' + _('Month') + ' ')
        item3.add(self.label_birth_month)
        birth_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        self.month_birth_spin = gtk.SpinButton()
        self.month_birth_spin.set_range(1, 12)
        self.month_birth_spin.set_increments(1, 4)
        self.month_birth_spin.props.value = 2
        self.month_birth_spin.connect('notify::value', self.month_birth_change)
        item4.add(self.month_birth_spin)
        birth_bar.insert(item4, -1)

        item5 = gtk.ToolItem()
        self.label_birth_year = gtk.Label()
        self.label_birth_year.set_text(' ' + _('Year') + ' ')
        item5.add(self.label_birth_year)
        birth_bar.insert(item5, -1)

        item6 = gtk.ToolItem()
        self.year_birth_spin = gtk.SpinButton()
        self.year_birth_spin.set_range(1900, self._now.year)
        self.year_birth_spin.set_increments(1, 10)
        self.year_birth_spin.props.value = 1990
        self.year_birth_spin.connect('notify::value', self.year_birth_change)
        item6.add(self.year_birth_spin)
        birth_bar.insert(item6, -1)

        birth_bar.show_all()
        birth_button = ToolbarButton(label=_('Birth'),
                                     page=birth_bar,
                                     icon_name='write-date')
        toolbox.toolbar.insert(birth_button, -1)
        birth_button.show()
예제 #8
0
    def build_birth_toolbar(self, toolbox):

        birth_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        self.label_birth = gtk.Label()
        self.label_birth.set_text(_('Birth:') + ' ' + _('Day') + ' ')
        item1.add(self.label_birth)
        birth_bar.insert(item1, -1)

        item2 = gtk.ToolItem()
        self.day_birth_spin = gtk.SpinButton()
        self.day_birth_spin.set_range(1, 31)
        self.day_birth_spin.set_increments(1, 5)
        self.day_birth_spin.props.value = 10
        self.day_birth_spin.connect('notify::value', self.day_birth_change)
        item2.add(self.day_birth_spin)
        birth_bar.insert(item2, -1)

        item3 = gtk.ToolItem()
        self.label_birth_month = gtk.Label()
        self.label_birth_month.set_text(' ' + _('Month') + ' ')
        item3.add(self.label_birth_month)
        birth_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        self.month_birth_spin = gtk.SpinButton()
        self.month_birth_spin.set_range(1, 12)
        self.month_birth_spin.set_increments(1, 4)
        self.month_birth_spin.props.value = 2
        self.month_birth_spin.connect('notify::value', self.month_birth_change)
        item4.add(self.month_birth_spin)
        birth_bar.insert(item4, -1)

        item5 = gtk.ToolItem()
        self.label_birth_year = gtk.Label()
        self.label_birth_year.set_text(' ' + _('Year') + ' ')
        item5.add(self.label_birth_year)
        birth_bar.insert(item5, -1)

        item6 = gtk.ToolItem()
        self.year_birth_spin = gtk.SpinButton()
        self.year_birth_spin.set_range(1900, self._now.year)
        self.year_birth_spin.set_increments(1, 10)
        self.year_birth_spin.props.value = 1990
        self.year_birth_spin.connect('notify::value', self.year_birth_change)
        item6.add(self.year_birth_spin)
        birth_bar.insert(item6, -1)

        birth_bar.show_all()
        birth_button = ToolbarButton(label=_('Birth'),
                page=birth_bar,
                icon_name='write-date')
        toolbox.toolbar.insert(birth_button, -1)
        birth_button.show()
예제 #9
0
    def build_today_toolbar(self, toolbox):

        today_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        self.label_today = gtk.Label()
        self.label_today.set_text(_('Today:') + ' ' + _('Day') + ' ')
        item1.add(self.label_today)
        today_bar.insert(item1, -1)

        item2 = gtk.ToolItem()
        self.day_today_spin = gtk.SpinButton()
        self.day_today_spin.set_range(1, 31)
        self.day_today_spin.set_increments(1, 5)
        self.day_today_spin.props.value = self._today[0]
        self.day_today_spin.connect('notify::value', self.day_today_change)
        item2.add(self.day_today_spin)
        today_bar.insert(item2, -1)

        item3 = gtk.ToolItem()
        self.label_today_month = gtk.Label()
        self.label_today_month.set_text(' ' + _('Month') + ' ')
        item3.add(self.label_today_month)
        today_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        self.month_today_spin = gtk.SpinButton()
        self.month_today_spin.set_range(1, 12)
        self.month_today_spin.set_increments(1, 4)
        self.month_today_spin.props.value = self._today[1]
        self.month_today_spin.connect('notify::value', self.month_today_change)
        item4.add(self.month_today_spin)
        today_bar.insert(item4, -1)

        item5 = gtk.ToolItem()
        self.label_today_year = gtk.Label()
        self.label_today_year.set_text(' ' + _('Year') + ' ')
        item5.add(self.label_today_year)
        today_bar.insert(item5, -1)

        item6 = gtk.ToolItem()
        self.year_today_spin = gtk.SpinButton()
        self.year_today_spin.set_range(1900, self._now.year + 1)
        self.year_today_spin.set_increments(1, 10)
        self.year_today_spin.props.value = self._today[2]
        self.year_today_spin.connect('notify::value', self.year_today_change)
        item6.add(self.year_today_spin)
        today_bar.insert(item6, -1)

        today_bar.show_all()
        today_button = ToolbarButton(label=_('Today'),
                page=today_bar,
                icon_name='write-time')
        toolbox.toolbar.insert(today_button, -1)
        today_button.show()
예제 #10
0
    def build_today_toolbar(self, toolbox):

        today_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        self.label_today = gtk.Label()
        self.label_today.set_text(_('Today:') + ' ' + _('Day') + ' ')
        item1.add(self.label_today)
        today_bar.insert(item1, -1)

        item2 = gtk.ToolItem()
        self.day_today_spin = gtk.SpinButton()
        self.day_today_spin.set_range(1, 31)
        self.day_today_spin.set_increments(1, 5)
        self.day_today_spin.props.value = self._today[0]
        self.day_today_spin.connect('notify::value', self.day_today_change)
        item2.add(self.day_today_spin)
        today_bar.insert(item2, -1)

        item3 = gtk.ToolItem()
        self.label_today_month = gtk.Label()
        self.label_today_month.set_text(' ' + _('Month') + ' ')
        item3.add(self.label_today_month)
        today_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        self.month_today_spin = gtk.SpinButton()
        self.month_today_spin.set_range(1, 12)
        self.month_today_spin.set_increments(1, 4)
        self.month_today_spin.props.value = self._today[1]
        self.month_today_spin.connect('notify::value', self.month_today_change)
        item4.add(self.month_today_spin)
        today_bar.insert(item4, -1)

        item5 = gtk.ToolItem()
        self.label_today_year = gtk.Label()
        self.label_today_year.set_text(' ' + _('Year') + ' ')
        item5.add(self.label_today_year)
        today_bar.insert(item5, -1)

        item6 = gtk.ToolItem()
        self.year_today_spin = gtk.SpinButton()
        self.year_today_spin.set_range(1900, self._now.year + 1)
        self.year_today_spin.set_increments(1, 10)
        self.year_today_spin.props.value = self._today[2]
        self.year_today_spin.connect('notify::value', self.year_today_change)
        item6.add(self.year_today_spin)
        today_bar.insert(item6, -1)

        today_bar.show_all()
        today_button = ToolbarButton(label=_('Today'),
                                     page=today_bar,
                                     icon_name='write-time')
        toolbox.toolbar.insert(today_button, -1)
        today_button.show()
예제 #11
0
파일: activity.py 프로젝트: rbuj/followme
    def build_resolution_toolbar(self, toolbox):

        resolution_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        label1 = gtk.Label()
        label1.set_text(' ' + _('Show size') + ' ')
        item1.add(label1)
        resolution_bar.insert(item1, -1)

        item2 = gtk.ToolItem()
        x_size_spin = gtk.SpinButton()
        x_size_spin.set_range(160, 1200)
        x_size_spin.set_increments(1, 10)
        x_size_spin.props.value = int(self.show_size[0])
        x_size_spin.connect('notify::value', self.x_size_spin_change)
        item2.add(x_size_spin)
        resolution_bar.insert(item2, -1)

        item3 = gtk.ToolItem()
        label3 = gtk.Label()
        label3.set_text(' X ')
        item3.add(label3)
        resolution_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        y_size_spin = gtk.SpinButton()
        y_size_spin.set_range(120, 900)
        y_size_spin.set_increments(1, 10)
        y_size_spin.props.value = int(self.show_size[1])
        y_size_spin.connect('notify::value', self.y_size_spin_change)
        item4.add(y_size_spin)
        resolution_bar.insert(item4, -1)

        separator1 = gtk.SeparatorToolItem()
        separator1.props.draw = True
        resolution_bar.insert(separator1, -1)

        item5 = gtk.ToolItem()
        label5 = gtk.Label()
        label5.set_text(' ' + _('Show grid'))
        item5.add(label5)
        resolution_bar.insert(item5, -1)

        grid = ToolButton('grid-icon')
        grid.connect('clicked', self.grid_click)
        resolution_bar.insert(grid, -1)

        resolution_bar.show_all()
        resolution_button = ToolbarButton(label=_('Resolution'),
                page=resolution_bar,
                icon_name='camera')
        toolbox.toolbar.insert(resolution_button, -1)
        resolution_button.show()
예제 #12
0
    def build_resolution_toolbar(self, toolbox):

        resolution_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        label1 = gtk.Label()
        label1.set_text(' ' + _('Show size') + ' ')
        item1.add(label1)
        resolution_bar.insert(item1, -1)

        item2 = gtk.ToolItem()
        x_size_spin = gtk.SpinButton()
        x_size_spin.set_range(160, 1200)
        x_size_spin.set_increments(1, 10)
        x_size_spin.props.value = int(self.show_size[0])
        x_size_spin.connect('notify::value', self.x_size_spin_change)
        item2.add(x_size_spin)
        resolution_bar.insert(item2, -1)

        item3 = gtk.ToolItem()
        label3 = gtk.Label()
        label3.set_text(' X ')
        item3.add(label3)
        resolution_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        y_size_spin = gtk.SpinButton()
        y_size_spin.set_range(120, 900)
        y_size_spin.set_increments(1, 10)
        y_size_spin.props.value = int(self.show_size[1])
        y_size_spin.connect('notify::value', self.y_size_spin_change)
        item4.add(y_size_spin)
        resolution_bar.insert(item4, -1)

        separator1 = gtk.SeparatorToolItem()
        separator1.props.draw = True
        resolution_bar.insert(separator1, -1)

        item5 = gtk.ToolItem()
        label5 = gtk.Label()
        label5.set_text(' ' + _('Show grid'))
        item5.add(label5)
        resolution_bar.insert(item5, -1)

        grid = ToolButton('grid-icon')
        grid.connect('clicked', self.grid_click)
        resolution_bar.insert(grid, -1)

        resolution_bar.show_all()
        resolution_button = ToolbarButton(label=_('Resolution'),
                                          page=resolution_bar,
                                          icon_name='camera')
        toolbox.toolbar.insert(resolution_button, -1)
        resolution_button.show()
예제 #13
0
    def build_size_toolbar(self, toolbox):

        size_bar = gtk.Toolbar()

        #Horizontal
        item1 = gtk.ToolItem()
        label1 = gtk.Label()
        label1.set_text(' %s ' % _('H'))
        item1.add(label1)
        size_bar.insert(item1, -1)

        item2 = gtk.ToolItem()
        self.h_spin = gtk.SpinButton()
        self.h_spin.set_range(2, 30)
        self.h_spin.set_increments(1, 2)
        self.h_spin.props.value = self.game_size[0]
        self.h_spin.connect('notify::value', self.h_spin_change)
        item2.add(self.h_spin)
        size_bar.insert(item2, -1)

        #Vertical
        item3 = gtk.ToolItem()
        label2 = gtk.Label()
        label2.set_text(' %s ' % _('V'))
        item3.add(label2)
        size_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        self.v_spin = gtk.SpinButton()
        self.v_spin.set_range(2, 20)
        self.v_spin.set_increments(1, 2)
        self.v_spin.props.value = self.game_size[1]
        self.v_spin.connect('notify::value', self.v_spin_change)
        item4.add(self.v_spin)
        size_bar.insert(item4, -1)

        size_bar.show_all()
        size_button = ToolbarButton(label=_('Board size'),
                                    page=size_bar,
                                    icon_name='preferences-system')
        toolbox.toolbar.insert(size_button, -1)
        size_button.show()
예제 #14
0
    def _setup_toolbars(self):
        ''' Add buttons to toolbars '''
        custom_toolbar = gtk.Toolbar()
        if HAS_TOOLBARBOX:
            toolbox = ToolbarBox()
            self.toolbar = toolbox.toolbar
            activity_button = ActivityToolbarButton(self)
            self.toolbar.insert(activity_button, 0)
            activity_button.show()

            custom_toolbar_button = ToolbarButton(
                label=_('Custom'),
                page=custom_toolbar,
                icon_name='view-source')
            custom_toolbar.show()
            self.toolbar.insert(custom_toolbar_button, -1)
            custom_toolbar_button.show()

            self._load_standard_buttons(self.toolbar)
            separator_factory(self.toolbar, expand=True, visible=False)

            stop_button = StopButton(self)
            stop_button.props.accelerator = _('<Ctrl>Q')
            self.toolbar.insert(stop_button, -1)
            stop_button.show()

            self.set_toolbox(toolbox)
            toolbox.show()
        else:
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)
            self.toolbar = gtk.Toolbar()
            toolbox.add_toolbar(_('Project'), self.toolbar)
            toolbox.add_toolbar(_('Custom'), custom_toolbar)
            self._load_standard_buttons(self.toolbar)

        self._load_custom_buttons(custom_toolbar)
예제 #15
0
    def __init__(self, toolbar):
        self._timer_combo = TimerCombo()
        toolbar.insert(self._timer_combo, -1)

        self._duration_combo = DurationCombo()
        toolbar.insert(self._duration_combo, -1)

        preferences_toolbar = gtk.Toolbar()
        combo = gtk.combo_box_new_text()
        self.quality = ToolComboBox(combo=combo, label_text=_('Quality:'))
        self.quality.combo.append_text(_('Low'))
        if hw.get_xo_version() != 1:
            # Disable High quality on XO-1. The system simply isn't beefy
            # enough for recording to work well.
            self.quality.combo.append_text(_('High'))
        self.quality.combo.set_active(0)
        self.quality.show_all()
        preferences_toolbar.insert(self.quality, -1)

        preferences_button = ToolbarButton()
        preferences_button.set_page(preferences_toolbar)
        preferences_button.props.icon_name = 'preferences-system'
        preferences_button.props.label = _('Preferences')
        toolbar.insert(preferences_button, -1)
예제 #16
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        if HASTOOLBARBOX:
            self.max_participants = 1
            toolbar_box = ToolbarBox()
            self.set_toolbar_box(toolbar_box)
            activity_button = ActivityToolbarButton(self)
            toolbar_box.toolbar.insert(activity_button, 0)

            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            activity_button.props.page.insert(separator, -1)
            separator.show()

            tool = ToolButton('pdf-export')
            tool.set_tooltip(_('Portable Document Format (PDF)'))
            tool.connect('clicked', self.__export_pdf_cb)
            activity_button.props.page.insert(tool, -1)
            tool.show()

            tool = ToolButton('png-export')
            tool.set_tooltip(_('Portable Network Graphic (PNG)'))
            tool.connect('clicked', self.__export_png_cb)
            activity_button.props.page.insert(tool, -1)
            tool.show()

            tool = ToolbarButton()
            self.edit_toolbar = EditToolbar(self)
            tool.props.page = self.edit_toolbar
            tool.props.icon_name = 'toolbar-edit'
            tool.props.label = _('Edit'),
            toolbar_box.toolbar.insert(tool, -1)

            self._undo = UndoManager.UndoManager(self,
                                                 self.edit_toolbar.undo.child,
                                                 self.edit_toolbar.redo.child)

            self.__build_main_canvas_area()

            tool = ToolbarButton()
            tool.props.page = ViewToolbar(self._main_area)
            tool.props.icon_name = 'toolbar-view'
            tool.props.label = _('View'),
            toolbar_box.toolbar.insert(tool, -1)

            tool = ToolbarButton()
            self.text_format_toolbar = TextAttributesToolbar(self._main_area)
            tool.props.page = self.text_format_toolbar
            tool.props.icon_name = 'toolbar-text'
            tool.props.label = _('Text')
            toolbar_box.toolbar.insert(tool, -1)
            # self._main_area.set_text_attributes(self.text_format_toolbar)

            self.thought_toolbar = ToolbarButton()
            self.thought_toolbar.props.page = ThoughtsToolbar(self)
            self.thought_toolbar.props.icon_name = 'thought'
            self.thought_toolbar.props.label = _('Thought Type')
            toolbar_box.toolbar.insert(self.thought_toolbar, -1)

            self.action_buttons = ActionButtons(self)

            toolbar_box.show_all()

        else:
            # Use old <= 0.84 toolbar design
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)

            activity_toolbar = toolbox.get_activity_toolbar()
            keep_palette = activity_toolbar.keep.get_palette()

            menu_item = MenuItem(_('Portable Document Format (PDF)'))
            menu_item.connect('activate', self.__export_pdf_cb)
            keep_palette.menu.append(menu_item)
            menu_item.show()

            menu_item = MenuItem(_('Portable Network Graphic (PNG)'))
            menu_item.connect('activate', self.__export_png_cb)
            keep_palette.menu.append(menu_item)
            menu_item.show()

            self.edit_toolbar = EditToolbar(self)
            toolbox.add_toolbar(_('Edit'), self.edit_toolbar)
            separator = gtk.SeparatorToolItem()
            self.edit_toolbar.insert(separator, 0)
            self.edit_toolbar.show()

            self._undo = UndoManager.UndoManager(self,
                                                 self.edit_toolbar.undo.child,
                                                 self.edit_toolbar.redo.child)

            self.__build_main_canvas_area()

            view_toolbar = ViewToolbar(self._main_area)
            toolbox.add_toolbar(_('View'), view_toolbar)

            activity_toolbar = toolbox.get_activity_toolbar()
            activity_toolbar.share.props.visible = False
            toolbox.set_current_toolbar(1)

        self.show_all()

        self.__configure_cb(None)

        self._mode = MMapArea.MODE_TEXT
        self._main_area.set_mode(self._mode)
        self.set_focus_child(self._main_area)
예제 #17
0
파일: activity.py 프로젝트: Akirato/speak
    def __init__(self, handle):
        super(SpeakActivity, self).__init__(handle)

        self._notebook = gtk.Notebook()
        self.set_canvas(self._notebook)
        self._notebook.show()

        self._colors = profile.get_color().to_string().split(',')
        lighter = style.Color(self._colors[
            _lighter_color(self._colors)])

        self._mode = MODE_TYPE
        self._tablet_mode = _is_tablet_mode()
        self._robot_idle_id = None
        self._active_eyes = None
        self._active_number_of_eyes = None
        self._current_voice = None

        # make an audio device for playing back and rendering audio
        self.connect('notify::active', self._active_cb)
        self._cfg = {}

        # make a box to type into
        hbox = gtk.HBox()

        if self._tablet_mode:
            self._entry = gtk.Entry()
            hbox.pack_start(self._entry, expand=True)
            talk_button = ToolButton('microphone')
            talk_button.set_tooltip(_('Speak'))
            talk_button.connect('clicked', self._talk_cb)
            hbox.pack_end(talk_button, expand=False)
        else:
            self._entrycombo = gtk.combo_box_entry_new_text()
            self._entrycombo.connect('changed', self._combo_changed_cb)
            self._entry = self._entrycombo.child
            self._entry.set_size_request(-1, style.GRID_CELL_SIZE)
            hbox.pack_start(self._entrycombo, expand=True)
        self._entry.set_editable(True)
        self._entry.connect('activate', self._entry_activate_cb)
        self._entry.connect('key-press-event', self._entry_key_press_cb)
        self._entry.modify_font(pango.FontDescription(str='sans bold 24'))
        hbox.show()

        self.face = face.View(fill_color=lighter)
        self.face.set_size_request(
            -1, gtk.gdk.screen_height() - 2 * style.GRID_CELL_SIZE)
        self.face.show()

        # layout the screen
        box = gtk.VBox(homogeneous=False)
        if self._tablet_mode:
            box.pack_start(hbox, expand=False)
            box.pack_start(self.face)
        else:
            box.pack_start(self.face, expand=True)
            box.pack_start(hbox)

        self.add_events(gtk.gdk.POINTER_MOTION_HINT_MASK
                        | gtk.gdk.POINTER_MOTION_MASK)
        self.connect('motion_notify_event', self._mouse_moved_cb)

        box.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        box.connect('button_press_event', self._mouse_clicked_cb)

        # desktop
        self._notebook.show()
        self._notebook.props.show_border = False
        self._notebook.props.show_tabs = False

        box.show_all()
        self._notebook.append_page(box)

        self._chat = chat.View()
        self._chat.show_all()
        self._notebook.append_page(self._chat)

        # make the text box active right away
        if not self._tablet_mode:
            self._entry.grab_focus()

        self._entry.connect('move-cursor', self._cursor_moved_cb)
        self._entry.connect('changed', self._cursor_moved_cb)

        toolbox = ToolbarBox()
        self._activity_button = ActivityToolbarButton(self)
        self._activity_button.connect('clicked', self._configure_cb)

        toolbox.toolbar.insert(self._activity_button, -1)

        mode_type = RadioToolButton(
            named_icon='mode-type',
            tooltip=_('Type something to hear it'))
        mode_type.connect('toggled', self.__toggled_mode_type_cb)
        toolbox.toolbar.insert(mode_type, -1)

        mode_robot = RadioToolButton(
            named_icon='mode-robot',
            group=mode_type,
            tooltip=_('Ask robot any question'))
        mode_robot.connect('toggled', self.__toggled_mode_robot_cb)
        toolbox.toolbar.insert(mode_robot, -1)

        self._mode_chat = RadioToolButton(
            named_icon='mode-chat',
            group=mode_type,
            tooltip=_('Voice chat'))
        self._mode_chat.connect('toggled', self.__toggled_mode_chat_cb)
        toolbox.toolbar.insert(self._mode_chat, -1)

        self._voice_button = ToolbarButton(
            page=self._make_voice_bar(),
            label=_('Voice'),
            icon_name='voice')
        self._voice_button.connect('clicked', self._configure_cb)
        toolbox.toolbar.insert(self._voice_button, -1)

        self._face_button = ToolbarButton(
            page=self._make_face_bar(),
            label=_('Face'),
            icon_name='face')
        self._face_button.connect('clicked', self._configure_cb)
        toolbox.toolbar.insert(self._face_button, -1)

        separator = gtk.SeparatorToolItem()
        separator.set_draw(False)
        separator.set_expand(True)
        toolbox.toolbar.insert(separator, -1)

        toolbox.toolbar.insert(StopButton(self), -1)

        toolbox.show_all()
        self.toolbar_box = toolbox

        gtk.gdk.screen_get_default().connect('size-changed',
                                             self._configure_cb)

        self._first_time = True
        self._new_instance()

        self._configure_cb()
        self._poll_accelerometer()

        if self.shared_activity:
            # we are joining the activity
            self.connect('joined', self._joined_cb)
            if self.get_shared():
                # we have already joined
                self._joined_cb(self)
            self._mode_chat.set_active(True)
            self._setup_chat_mode()
        elif handle.uri:
            # XMPP non-sugar3 incoming chat, not sharable
            self._activity_button.props.page.share.props.visible = \
                False
            self._one_to_one_connection(handle.uri)
        else:
            # we are creating the activity
            self.connect('shared', self._shared_cb)
예제 #18
0
파일: activity.py 프로젝트: Akirato/speak
class SpeakActivity(activity.Activity):
    def __init__(self, handle):
        super(SpeakActivity, self).__init__(handle)

        self._notebook = gtk.Notebook()
        self.set_canvas(self._notebook)
        self._notebook.show()

        self._colors = profile.get_color().to_string().split(',')
        lighter = style.Color(self._colors[
            _lighter_color(self._colors)])

        self._mode = MODE_TYPE
        self._tablet_mode = _is_tablet_mode()
        self._robot_idle_id = None
        self._active_eyes = None
        self._active_number_of_eyes = None
        self._current_voice = None

        # make an audio device for playing back and rendering audio
        self.connect('notify::active', self._active_cb)
        self._cfg = {}

        # make a box to type into
        hbox = gtk.HBox()

        if self._tablet_mode:
            self._entry = gtk.Entry()
            hbox.pack_start(self._entry, expand=True)
            talk_button = ToolButton('microphone')
            talk_button.set_tooltip(_('Speak'))
            talk_button.connect('clicked', self._talk_cb)
            hbox.pack_end(talk_button, expand=False)
        else:
            self._entrycombo = gtk.combo_box_entry_new_text()
            self._entrycombo.connect('changed', self._combo_changed_cb)
            self._entry = self._entrycombo.child
            self._entry.set_size_request(-1, style.GRID_CELL_SIZE)
            hbox.pack_start(self._entrycombo, expand=True)
        self._entry.set_editable(True)
        self._entry.connect('activate', self._entry_activate_cb)
        self._entry.connect('key-press-event', self._entry_key_press_cb)
        self._entry.modify_font(pango.FontDescription(str='sans bold 24'))
        hbox.show()

        self.face = face.View(fill_color=lighter)
        self.face.set_size_request(
            -1, gtk.gdk.screen_height() - 2 * style.GRID_CELL_SIZE)
        self.face.show()

        # layout the screen
        box = gtk.VBox(homogeneous=False)
        if self._tablet_mode:
            box.pack_start(hbox, expand=False)
            box.pack_start(self.face)
        else:
            box.pack_start(self.face, expand=True)
            box.pack_start(hbox)

        self.add_events(gtk.gdk.POINTER_MOTION_HINT_MASK
                        | gtk.gdk.POINTER_MOTION_MASK)
        self.connect('motion_notify_event', self._mouse_moved_cb)

        box.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        box.connect('button_press_event', self._mouse_clicked_cb)

        # desktop
        self._notebook.show()
        self._notebook.props.show_border = False
        self._notebook.props.show_tabs = False

        box.show_all()
        self._notebook.append_page(box)

        self._chat = chat.View()
        self._chat.show_all()
        self._notebook.append_page(self._chat)

        # make the text box active right away
        if not self._tablet_mode:
            self._entry.grab_focus()

        self._entry.connect('move-cursor', self._cursor_moved_cb)
        self._entry.connect('changed', self._cursor_moved_cb)

        toolbox = ToolbarBox()
        self._activity_button = ActivityToolbarButton(self)
        self._activity_button.connect('clicked', self._configure_cb)

        toolbox.toolbar.insert(self._activity_button, -1)

        mode_type = RadioToolButton(
            named_icon='mode-type',
            tooltip=_('Type something to hear it'))
        mode_type.connect('toggled', self.__toggled_mode_type_cb)
        toolbox.toolbar.insert(mode_type, -1)

        mode_robot = RadioToolButton(
            named_icon='mode-robot',
            group=mode_type,
            tooltip=_('Ask robot any question'))
        mode_robot.connect('toggled', self.__toggled_mode_robot_cb)
        toolbox.toolbar.insert(mode_robot, -1)

        self._mode_chat = RadioToolButton(
            named_icon='mode-chat',
            group=mode_type,
            tooltip=_('Voice chat'))
        self._mode_chat.connect('toggled', self.__toggled_mode_chat_cb)
        toolbox.toolbar.insert(self._mode_chat, -1)

        self._voice_button = ToolbarButton(
            page=self._make_voice_bar(),
            label=_('Voice'),
            icon_name='voice')
        self._voice_button.connect('clicked', self._configure_cb)
        toolbox.toolbar.insert(self._voice_button, -1)

        self._face_button = ToolbarButton(
            page=self._make_face_bar(),
            label=_('Face'),
            icon_name='face')
        self._face_button.connect('clicked', self._configure_cb)
        toolbox.toolbar.insert(self._face_button, -1)

        separator = gtk.SeparatorToolItem()
        separator.set_draw(False)
        separator.set_expand(True)
        toolbox.toolbar.insert(separator, -1)

        toolbox.toolbar.insert(StopButton(self), -1)

        toolbox.show_all()
        self.toolbar_box = toolbox

        gtk.gdk.screen_get_default().connect('size-changed',
                                             self._configure_cb)

        self._first_time = True
        self._new_instance()

        self._configure_cb()
        self._poll_accelerometer()

        if self.shared_activity:
            # we are joining the activity
            self.connect('joined', self._joined_cb)
            if self.get_shared():
                # we have already joined
                self._joined_cb(self)
            self._mode_chat.set_active(True)
            self._setup_chat_mode()
        elif handle.uri:
            # XMPP non-sugar3 incoming chat, not sharable
            self._activity_button.props.page.share.props.visible = \
                False
            self._one_to_one_connection(handle.uri)
        else:
            # we are creating the activity
            self.connect('shared', self._shared_cb)

    def _toolbar_expanded(self):
        if self._activity_button.is_expanded():
            return True
        if self._voice_button.is_expanded():
            return True
        if self._face_button.is_expanded():
            return True
        return False

    def _configure_cb(self, event=None):
        self._entry.set_size_request(-1, style.GRID_CELL_SIZE)
        if self._toolbar_expanded():
            self.face.set_size_request(
                -1, gtk.gdk.screen_height() - 3 * style.GRID_CELL_SIZE)
            self._chat.resize_chat_box(expanded=True)
            self._chat.resize_buddy_list()
        else:
            self.face.set_size_request(
                -1, gtk.gdk.screen_height() - 2 * style.GRID_CELL_SIZE)
            self._chat.resize_chat_box()
            self._chat.resize_buddy_list()

    def _new_instance(self):
        if self._first_time:
            # self.voices.connect('changed', self.__changed_voices_cb)
            self.pitchadj.connect('value_changed', self._pitch_adjusted_cb,
                                  self.pitchadj)
            self.rateadj.connect('value_changed', self._rate_adjusted_cb,
                                 self.rateadj)
        if self._active_number_of_eyes is None:
            self._number_of_eyes_changed_event_cb(None, None, 'two', True)
        if self._active_eyes is None:
            self._eyes_changed_event_cb(None, None, 'eyes', True)

        self._mouth_changed_cb(None, True)

        self.face.look_ahead()

        presenceService = presenceservice.get_instance()
        self.owner = presenceService.get_owner()
        if self._first_time:
            # say hello to the user
            if self._tablet_mode:
                self._entry.props.text = _('Hello %s.') \
                    % self.owner.props.nick.encode('utf-8', 'ignore')
            self.face.say_notification(_('Hello %s. Please Type something.')
                                       % self.owner.props.nick)
        else:
            if self._tablet_mode:
                self._entry.props.text = _('Welcome back %s.') \
                    % self.owner.props.nick.encode('utf-8', 'ignore')
            self.face.say_notification(_('Welcome back %s.')
                                       % self.owner.props.nick)
        self._set_idle_phrase(speak=False)
        self._first_time = False

    def read_file(self, file_path):
        self._cfg = json.loads(file(file_path, 'r').read())

        current_voice = self.face.status.voice

        status = self.face.status = \
            face.Status().deserialize(self._cfg['status'])

        found_my_voice = False
        for name in self._voice_evboxes.keys():
            if self._voice_evboxes[name][1] == current_voice:
                self._voice_evboxes[name][0].modify_bg(
                    0, style.COLOR_BLACK.get_gdk_color())
            if self._voice_evboxes[name][1] == status.voice and \
               not found_my_voice:
                self._voice_evboxes[name][0].modify_bg(
                    0, style.COLOR_BUTTON_GREY.get_gdk_color())
                self.face.set_voice(status.voice)
                if self._mode == MODE_BOT:
                    brain.load(self, status.voice)
                found_my_voice = True

        self.pitchadj.value = self.face.status.pitch
        self.rateadj.value = self.face.status.rate

        if status.mouth in MOUTHS:
            self._mouth_type[MOUTHS.index(status.mouth)].set_active(True)

        self._number_of_eyes_changed_event_cb(
            None, None, NUMBERS[len(status.eyes) - 1], True)
        for name in EYE_DICT.keys():
            if status.eyes[0] == EYE_DICT[name]['widget']:
                self._eye_type[name].set_icon(name + '-selected')
                self._eyes_changed_event_cb(None, None, name, True)
                break

        self._entry.props.text = self._cfg['text'].encode('utf-8', 'ignore')
        if not self._tablet_mode:
            for i in self._cfg['history']:
                self._entrycombo.append_text(i.encode('utf-8', 'ignore'))

        self._new_instance()

    def write_file(self, file_path):
        if self._tablet_mode:
            if 'history' in self._cfg:
                history = self._cfg['history']  # retain old history
            else:
                history = []
        else:
            history = [unicode(i[0], 'utf-8', 'ignore')
                       for i in self._entrycombo.get_model()]
        cfg = {'status': self.face.status.serialize(),
               'text': unicode(self._entry.props.text, 'utf-8', 'ignore'),
               'history': history, }
        file(file_path, 'w').write(json.dumps(cfg))

    def _cursor_moved_cb(self, entry, *ignored):
        # make the eyes track the motion of the text cursor
        index = entry.props.cursor_position
        layout = entry.get_layout()
        pos = layout.get_cursor_pos(index)
        x = pos[0][0] / pango.SCALE - entry.props.scroll_offset
        y = entry.get_allocation().y
        self.face.look_at(pos=(x, y))

    def _poll_accelerometer(self):
        if _has_accelerometer():
            idle_time = self._test_orientation()
            gobject.timeout_add(idle_time, self._poll_accelerometer)

    def _test_orientation(self):
        if _has_accelerometer():
            fh = open(ACCELEROMETER_DEVICE)
            string = fh.read()
            fh.close()
            xyz = string[1:-2].split(',')
            x = int(xyz[0])
            y = int(xyz[1])
            # DO SOMETHING HERE
            if ((gtk.gdk.screen_width() > gtk.gdk.screen_height() and
                 abs(x) > abs(y)) or
                (gtk.gdk.screen_width() < gtk.gdk.screen_height() and
                 abs(x) < abs(y))):
                sideways_phrase = SIDEWAYS_PHRASES[
                    random.randint(0, len(SIDEWAYS_PHRASES) - 1)]
                self.face.say(SIDEWAYS_PHRASES[sideways_phrase])
                return IDLE_DELAY  # Don't repeat the message for a while
            return 1000  # Test again soon

    def get_mouse(self):
        display = gtk.gdk.display_get_default()
        screen, mouseX, mouseY, modifiers = display.get_pointer()
        return mouseX, mouseY

    def _mouse_moved_cb(self, widget, event):
        # make the eyes track the motion of the mouse cursor
        self.face.look_at()
        self._chat.look_at()

    def _mouse_clicked_cb(self, widget, event):
        pass

    def _make_voice_bar(self):
        voicebar = gtk.Toolbar()

        all_voices = []
        for name in sorted(voice_model.allVoices().keys()):
            if len(name) < 26:
                friendly_name = name
            else:
                friendly_name = name[:26] + '...'
            all_voices.append([voice_model.allVoices()[name], friendly_name])

        # A palette for the voice selection
        logging.error(self.face.status.voice)

        self._voice_evboxes = {}
        self._voice_box = gtk.HBox()
        vboxes = [gtk.VBox(), gtk.VBox(), gtk.VBox()]
        count = len(voice_model.allVoices().keys())
        found_my_voice = False
        for i, voice in enumerate(sorted(all_voices)):
            label = gtk.Label()
            label.set_use_markup(True)
            label.set_justify(gtk.JUSTIFY_LEFT)
            label.set_markup('<span size="large">%s</span>' % voice[1])

            alignment = gtk.Alignment(0, 0, 0, 0)
            alignment.add(label)
            label.show()

            evbox = gtk.EventBox()
            self._voice_evboxes[voice[1]] = [evbox, voice[0]]
            self._voice_evboxes[voice[1]][0].connect(
                'button-press-event', self._voices_changed_event_cb, voice)
            if voice[0] == self.face.status.voice and not found_my_voice:
                self._current_voice = voice
                evbox.modify_bg(
                    0, style.COLOR_BUTTON_GREY.get_gdk_color())
                found_my_voice = True
            evbox.add(alignment)
            alignment.show()
            if i < count / 3:
                vboxes[0].pack_start(evbox)
            elif i < 2 * count / 3:
                vboxes[1].pack_start(evbox)
            else:
                vboxes[2].pack_start(evbox)
        self._voice_box.pack_start(vboxes[0], padding=style.DEFAULT_PADDING)
        self._voice_box.pack_start(vboxes[1], padding=style.DEFAULT_PADDING)
        self._voice_box.pack_start(vboxes[2], padding=style.DEFAULT_PADDING)

        voice_palette_button = ToolButton('module-language')
        voice_palette_button.set_tooltip(_('Choose voice:'))
        self._voice_palette = voice_palette_button.get_palette()
        self._voice_palette.set_content(self._voice_box)
        self._voice_box.show_all()
        voice_palette_button.connect('clicked', self._face_palette_cb)
        voicebar.insert(voice_palette_button, -1)
        voice_palette_button.show()

        brain_voices = []
        for name in sorted(brain.BOTS.keys()):
            brain_voices.append([voice_model.allVoices()[name], name])

        self._brain_evboxes = {}
        self._brain_box = gtk.HBox()
        vboxes = gtk.VBox()
        count = brain.BOTS.keys()
        found_my_voice = False
        for i, voice in enumerate(brain_voices):
            label = gtk.Label()
            label.set_use_markup(True)
            label.set_justify(gtk.JUSTIFY_LEFT)
            label.set_markup('<span size="large">%s</span>' % voice[1])

            alignment = gtk.Alignment(0, 0, 0, 0)
            alignment.add(label)
            label.show()

            evbox = gtk.EventBox()
            self._brain_evboxes[voice[1]] = [evbox, voice[0]]
            self._brain_evboxes[voice[1]][0].connect(
                'button-press-event', self._voices_changed_event_cb, voice)
            if voice[0] == self.face.status.voice and not found_my_voice:
                evbox.modify_bg(
                    0, style.COLOR_BUTTON_GREY.get_gdk_color())
                found_my_voice = True
            evbox.add(alignment)
            alignment.show()
            vboxes.pack_start(evbox)
        self._brain_box.pack_start(vboxes, padding=style.DEFAULT_PADDING)
        self._brain_box.show_all()

        separator = gtk.SeparatorToolItem()
        separator.set_draw(True)
        separator.set_expand(False)
        voicebar.insert(separator, -1)

        self.pitchadj = gtk.Adjustment(self.face.status.pitch, 0,
                                       espeak.PITCH_MAX, 1,
                                       espeak.PITCH_MAX/10, 0)
        pitchbar = gtk.HScale(self.pitchadj)
        pitchbar.set_draw_value(False)
        # pitchbar.set_inverted(True)
        pitchbar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        pitchbar.set_size_request(240, 15)

        pitchbar_toolitem = ToolWidget(widget=pitchbar, label_text=_('Pitch:'))
        voicebar.insert(pitchbar_toolitem, -1)

        self.rateadj = gtk.Adjustment(self.face.status.rate, 0,
                                      espeak.RATE_MAX,
                                      1, espeak.RATE_MAX / 10, 0)
        ratebar = gtk.HScale(self.rateadj)
        ratebar.set_draw_value(False)
        # ratebar.set_inverted(True)
        ratebar.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
        ratebar.set_size_request(240, 15)

        ratebar_toolitem = ToolWidget(widget=ratebar, label_text=_('Rate:'))
        voicebar.insert(ratebar_toolitem, -1)

        voicebar.show_all()
        return voicebar

    def _pitch_adjusted_cb(self, get, data=None):
        self.face.status.pitch = get.value
        self.face.say_notification(_('pitch adjusted'))

    def _rate_adjusted_cb(self, get, data=None):
        self.face.status.rate = get.value
        self.face.say_notification(_('rate adjusted'))

    def _make_face_bar(self):
        facebar = gtk.Toolbar()

        self._mouth_type = []
        self._mouth_type.append(RadioToolButton(
            named_icon='mouth',
            group=None,
            tooltip=_('Simple')))
        self._mouth_type[-1].connect('clicked', self._mouth_changed_cb, False)
        facebar.insert(self._mouth_type[-1], -1)

        self._mouth_type.append(RadioToolButton(
            named_icon='waveform',
            group=self._mouth_type[0],
            tooltip=_('Waveform')))
        self._mouth_type[-1].connect('clicked', self._mouth_changed_cb, False)
        facebar.insert(self._mouth_type[-1], -1)

        self._mouth_type.append(RadioToolButton(
            named_icon='frequency',
            group=self._mouth_type[0],
            tooltip=_('Frequency')))
        self._mouth_type[-1].connect('clicked', self._mouth_changed_cb, False)
        facebar.insert(self._mouth_type[-1], -1)

        separator = gtk.SeparatorToolItem()
        separator.set_draw(True)
        separator.set_expand(False)
        facebar.insert(separator, -1)

        eye_box = gtk.VBox()
        self._eye_type = {}
        for name in EYE_DICT.keys():
            self._eye_type[name] = ToolButton(name)
            self._eye_type[name].connect('clicked',
                                         self._eyes_changed_event_cb,
                                         None, name, False)
            label = gtk.Label(EYE_DICT[name]['label'])
            hbox = gtk.HBox()
            hbox.pack_start(self._eye_type[name])
            self._eye_type[name].show()
            hbox.pack_start(label)
            label.show()
            evbox = gtk.EventBox()
            evbox.connect('button-press-event', self._eyes_changed_event_cb,
                          name, False)
            evbox.add(hbox)
            hbox.show()
            eye_box.pack_start(evbox)

        eye_palette_button = ToolButton('eyes')
        eye_palette_button.set_tooltip(_('Choose eyes:'))
        palette = eye_palette_button.get_palette()
        palette.set_content(eye_box)
        eye_box.show_all()
        eye_palette_button.connect('clicked', self._face_palette_cb)
        facebar.insert(eye_palette_button, -1)
        eye_palette_button.show()

        number_of_eyes_box = gtk.VBox()
        self._number_of_eyes_type = {}
        for name in NUMBERS:
            self._number_of_eyes_type[name] = ToolButton(name)
            self._number_of_eyes_type[name].connect(
                'clicked', self._number_of_eyes_changed_event_cb,
                None, name, False)
            label = gtk.Label(name)
            hbox = gtk.HBox()
            hbox.pack_start(self._number_of_eyes_type[name])
            self._number_of_eyes_type[name].show()
            hbox.pack_start(label)
            label.show()
            evbox = gtk.EventBox()
            evbox.connect('button-press-event',
                          self._number_of_eyes_changed_event_cb,
                          name, False)
            evbox.add(hbox)
            hbox.show()
            number_of_eyes_box.pack_start(evbox)

        number_of_eyes_palette_button = ToolButton('number')
        number_of_eyes_palette_button.set_tooltip(_('Eyes number:'))
        palette = number_of_eyes_palette_button.get_palette()
        palette.set_content(number_of_eyes_box)
        number_of_eyes_box.show_all()
        number_of_eyes_palette_button.connect('clicked', self._face_palette_cb)
        facebar.insert(number_of_eyes_palette_button, -1)
        number_of_eyes_palette_button.show()

        facebar.show_all()
        return facebar

    def _face_palette_cb(self, button):
        palette = button.get_palette()
        if palette:
            if not palette.is_up():
                palette.popup(immediate=True, state=palette.SECONDARY)
            else:
                palette.popdown(immediate=True)

    def _get_active_mouth(self):
        for i, button in enumerate(self._mouth_type):
            if button.get_active():
                return MOUTHS[i]

    def _mouth_changed_cb(self, ignored, quiet):
        value = self._get_active_mouth()
        if value is None:
            return

        self.face.status.mouth = value
        self._update_face()

        # this SegFaults: self.face.say(combo.get_active_text())
        if not quiet:
            self.face.say_notification(_('mouth changed'))

    def _voices_changed_event_cb(self, widget, event, voice):
        logging.error('voices_changed_event_cb %r %s' % (voice[0], voice[1]))
        if self._mode == MODE_BOT:
            evboxes = self._brain_evboxes
        else:
            evboxes = self._voice_evboxes
        for old_voice in evboxes.keys():
            if evboxes[old_voice][1] == self.face.status.voice:
                evboxes[old_voice][0].modify_bg(
                    0, style.COLOR_BLACK.get_gdk_color())
                break

        evboxes[voice[1]][0].modify_bg(
            0, style.COLOR_BUTTON_GREY.get_gdk_color())

        self.face.set_voice(voice[0])
        if self._mode == MODE_BOT:
            brain.load(self, voice[0])
        else:
            self._current_voice = voice

    def _get_active_eyes(self):
        for name in EYE_DICT.keys():
            if EYE_DICT[name]['index'] == self._active_eyes:
                return EYE_DICT[name]['widget']
        return None

    def _eyes_changed_event_cb(self, widget, event, name, quiet):
        if self._active_eyes is not None:
            for old_name in EYE_DICT.keys():
                if EYE_DICT[old_name]['index'] == self._active_eyes:
                    self._eye_type[old_name].set_icon(old_name)
                    break

        if self._active_number_of_eyes is None:
            self._active_number_of_eyes = 2

        if name is not None:
            self._active_eyes = EYE_DICT[name]['index']
            self._eye_type[name].set_icon(name + '-selected')
            value = EYE_DICT[name]['widget']
            self.face.status.eyes = [value] * self._active_number_of_eyes
            self._update_face()
            if not quiet:
                self.face.say_notification(_('eyes changed'))

    def _number_of_eyes_changed_event_cb(self, widget, event, name, quiet):
        if self._active_number_of_eyes is not None:
            old_name = NUMBERS[self._active_number_of_eyes - 1]
            self._number_of_eyes_type[old_name].set_icon(old_name)

        if name in NUMBERS:
            self._active_number_of_eyes = NUMBERS.index(name) + 1
            self._number_of_eyes_type[name].set_icon(name + '-selected')
            if self._active_eyes is not None:
                for eye_name in EYE_DICT.keys():
                    if EYE_DICT[eye_name]['index'] == self._active_eyes:
                        value = EYE_DICT[eye_name]['widget']
                        self.face.status.eyes = \
                            [value] * self._active_number_of_eyes
                        self._update_face()
                        if not quiet:
                            self.face.say_notification(_('eyes changed'))
                        break

    def _update_face(self):
        self.face.update()
        self._chat.update(self.face.status)

    def _combo_changed_cb(self, combo):
        # when a new item is chosen, make sure the text is selected
        if not self._entry.is_focus():
            if not self._tablet_mode:
                self._entry.grab_focus()
            self._entry.select_region(0, -1)

    def _entry_key_press_cb(self, combo, event):
        # make the up/down arrows navigate through our history
        if self._tablet_mode:
            return
        keyname = gtk.gdk.keyval_name(event.keyval)
        if keyname == 'Up':
            index = self._entrycombo.get_active()
            if index > 0:
                index -= 1
            self._entrycombo.set_active(index)
            self._entry.select_region(0, -1)
            return True
        elif keyname == 'Down':
            index = self._entrycombo.get_active()
            if index < len(self._entrycombo.get_model()) - 1:
                index += 1
            self._entrycombo.set_active(index)
            self._entry.select_region(0, -1)
            return True
        return False

    def _entry_activate_cb(self, entry):
        # the user pressed Return, say the text and clear it out
        text = entry.props.text
        if self._tablet_mode:
            self._dismiss_OSK(entry)
            timeout = DELAY_BEFORE_SPEAKING
        else:
            timeout = 100
        gobject.timeout_add(timeout, self._speak_the_text, entry, text)

    def _dismiss_OSK(self, entry):
        entry.hide()
        entry.show()

    def _talk_cb(self, button):
        text = self._entry.props.text
        self._speak_the_text(self._entry, text)

    def _speak_the_text(self, entry, text):
        self._remove_idle()

        if text:
            self.face.look_ahead()

            # speak the text
            if self._mode == MODE_BOT:
                self.face.say(brain.respond(text))
            else:
                self.face.say(text)

        if text and not self._tablet_mode:
            # add this text to our history unless it is the same as
            # the last item
            history = self._entrycombo.get_model()
            if len(history) == 0 or history[-1][0] != text:
                self._entrycombo.append_text(text)
                # don't let the history get too big
                while len(history) > 20:
                    self._entrycombo.remove_text(0)
                # select the new item
                self._entrycombo.set_active(len(history) - 1)
        if text:
            # select the whole text
            entry.select_region(0, -1)

        # Launch an robot idle phase after 2 minutes
        self._robot_idle_id = gobject.timeout_add(IDLE_DELAY,
                                                  self._set_idle_phrase)

    def _load_sleeping_face(self):
        current_eyes = self.face.status.eyes
        self.face.status.eyes = [SLEEPY_EYES] * self._active_number_of_eyes
        self._update_face()
        self.face.status.eyes = current_eyes

    def _set_idle_phrase(self, speak=True):
        if speak:
            self._load_sleeping_face()
            idle_phrase = IDLE_PHRASES[random.randint(
                0, len(IDLE_PHRASES) - 1)]
            if self.props.active:
                self.face.say(idle_phrase)

        self._robot_idle_id = gobject.timeout_add(IDLE_DELAY,
                                                  self._set_idle_phrase)

    def _active_cb(self, widget, pspec):
        # only generate sound when this activity is active
        if not self.props.active:
            self._load_sleeping_face()
            self.face.shut_up()
            self._chat.shut_up()

    def _set_voice(self, new_voice=None):
        if new_voice is not None:
            logging.error('set_voice %r' % new_voice)
            self.face.status.voice = new_voice
        else:
            logging.error('set_voice to current voice %s' %
                          self._current_voice[1])
            self.face.status.voice = self._current_voice[0]

    def __toggled_mode_type_cb(self, button):
        if not button.props.active:
            return

        self._mode = MODE_TYPE
        self._chat.shut_up()
        self.face.shut_up()
        self._notebook.set_current_page(0)

        self._voice_palette.set_content(self._voice_box)
        self._set_voice()

    def __toggled_mode_robot_cb(self, button):
        if not button.props.active:
            return

        self._remove_idle()

        self._mode = MODE_BOT
        self._chat.shut_up()
        self.face.shut_up()
        self._notebook.set_current_page(0)

        self._voice_palette.set_content(self._brain_box)

        new_voice = None
        for name in brain.BOTS.keys():
            if self._current_voice[0].short_name == name:
                new_voice == self._current_voice[0]
                break
        if new_voice is None:
            new_voice = brain.get_default_voice()
            if new_voice.friendlyname in self._current_voice[0].friendlyname:
                logging.debug('skipping sorry message for %s %s' %
                              (new_voice.friendlyname,
                               self._current_voice[0].friendlyname))
                sorry = None
            else:
                sorry = _("Sorry, I can't speak %(old_voice)s, "
                          "let's talk %(new_voice)s instead.") % {
                              'old_voice': self._current_voice[0].friendlyname,
                              'new_voice': new_voice.friendlyname}
        else:
            new_voice = new_voice[0]
            sorry = None

        self._set_voice(new_voice)

        evboxes = self._brain_evboxes
        for old_voice in evboxes.keys():
            evboxes[old_voice][0].modify_bg(
                0, style.COLOR_BLACK.get_gdk_color())

        if new_voice.short_name in evboxes:
            evboxes[new_voice.short_name][0].modify_bg(
                0, style.COLOR_BUTTON_GREY.get_gdk_color())

        if not brain.load(self, new_voice, sorry):
            if sorry:
                self.face.say_notification(sorry)

    def __toggled_mode_chat_cb(self, button):
        if not button.props.active:
            return

        self._remove_idle()

        is_first_session = not self.shared_activity

        self._setup_chat_mode()

        if is_first_session:
            self._chat.me.say_notification(
                _('You are in off-line mode, share and invite someone.'))

    def _remove_idle(self):
        if self._robot_idle_id is not None:
            gobject.source_remove(self._robot_idle_id)
            value = self._get_active_eyes()
            if value is not None:
                self.face.status.eyes = [value] * self._active_number_of_eyes
                self._update_face()

    def _setup_chat_mode(self):
        self._mode = MODE_CHAT
        self._remove_idle()
        self.face.shut_up()
        self._notebook.set_current_page(1)

        self._voice_palette.set_content(self._voice_box)
        self._set_voice()

    def _shared_cb(self, sender):
        logging.error('SHARED A CHAT')
        self._setup_text_channel()

    def _joined_cb(self, sender):
        '''Joined a shared activity.'''
        if not self.shared_activity:
            return
        logger.error('JOINED A SHARED CHAT')
        for buddy in self.shared_activity.get_joined_buddies():
            self._buddy_already_exists(buddy)
        self._setup_text_channel()

    def _one_to_one_connection(self, tp_channel):
        '''Handle a private invite from a non-sugar3 XMPP client.'''
        if self.shared_activity or self.text_channel:
            return
        bus_name, connection, channel = json.loads(tp_channel)
        logger.debug('GOT XMPP: %s %s %s', bus_name, connection, channel)
        Connection(bus_name, connection, ready_handler=lambda conn:
                   self._one_to_one_connection_ready_cb(
                       bus_name, channel, conn))

    def _one_to_one_connection_ready_cb(self, bus_name, channel, conn):
        '''Callback for Connection for one to one connection'''
        text_channel = Channel(bus_name, channel)
        self.text_channel = TextChannelWrapper(text_channel, conn)
        self.text_channel.set_received_callback(self._received_cb)
        self.text_channel.handle_pending_messages()
        self.text_channel.set_closed_callback(
            self._one_to_one_connection_closed_cb)

        # XXX How do we detect the sender going offline?
        self._chat.chat_post.set_sensitive(True)
        # self._chat.chat_post.props.placeholder_text = None
        self._chat.chat_post.grab_focus()

    def _one_to_one_connection_closed_cb(self):
        '''Callback for when the text channel closes.'''
        pass

    def _setup_text_channel(self):
        logging.error('_SETUP_TEXTCHANNEL')
        self.text_channel = TextChannelWrapper(
            self.shared_activity.telepathy_text_chan,
            self.shared_activity.telepathy_conn)
        self.text_channel.set_received_callback(self._received_cb)
        self.shared_activity.connect('buddy-joined', self._buddy_joined_cb)
        self.shared_activity.connect('buddy-left', self._buddy_left_cb)
        self._chat.messenger = self.text_channel
        self._chat.chat_post.set_sensitive(True)
        self._chat.chat_post.grab_focus()

    def _buddy_joined_cb(self, sender, buddy):
        '''Show a buddy who joined'''
        if buddy == self.owner:
            return
        logging.error('%s joined the chat (%r)' % (buddy.props.nick, buddy))
        self._chat.post(
            buddy, _('%s joined the chat') % buddy.props.nick,
            status_message=True)

    def _buddy_left_cb(self, sender, buddy):
        '''Show a buddy who joined'''
        if buddy == self.owner:
            return
        logging.error('%s left the chat (%r)' % (buddy.props.nick, buddy))
        self._chat.post(
            buddy, _('%s left the chat') % buddy.props.nick,
            status_message=True)
        self._chat.farewell(buddy)

    def _buddy_already_exists(self, buddy):
        '''Show a buddy already in the chat.'''
        if buddy == self.owner:
            return
        logging.error('%s is here (%r)' % (buddy.props.nick, buddy))
        self._chat.post(
            buddy, _('%s is here') % buddy.props.nick,
            status_message=True)

    def _received_cb(self, buddy, text):
        '''Show message that was received.'''
        if buddy:
            if type(buddy) is dict:
                nick = buddy['nick']
            else:
                nick = buddy.props.nick
        else:
            nick = '???'
        logger.debug('Received message from %s: %s', nick, text)
        self._chat.post(buddy, text)
예제 #19
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)
    def _setup_toolbars(self):
        ''' Setup the toolbars.. '''

        # no sharing
        self.max_participants = 1

        if _HAVE_TOOLBOX:
            toolbox = ToolbarBox()

            # Activity toolbar
            activity_button = ActivityToolbarButton(self)

            toolbox.toolbar.insert(activity_button, 0)
            activity_button.show()

            lesson_toolbar = gtk.Toolbar()
            lesson_toolbar_button = ToolbarButton(label=_('Select a lesson'),
                                                  page=lesson_toolbar,
                                                  icon_name='text-x-generic')
            record_toolbar = gtk.Toolbar()
            record_toolbar_button = ToolbarButton(label=_('Record a sound'),
                                                  page=record_toolbar,
                                                  icon_name='media-audio')

            self.set_toolbar_box(toolbox)
            toolbox.show()
            lesson_toolbar_button.show()
            toolbox.toolbar.insert(lesson_toolbar_button, -1)
            record_toolbar_button.show()
            toolbox.toolbar.insert(record_toolbar_button, -1)
            primary_toolbar = toolbox.toolbar

        else:
            # Use pre-0.86 toolbar design
            primary_toolbar = gtk.Toolbar()
            lesson_toolbar = gtk.Toolbar()
            record_toolbar = gtk.Toolbar()
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)
            toolbox.add_toolbar(_('Page'), primary_toolbar)
            toolbox.show()
            toolbox.add_toolbar(_('Lesson'), lesson_toolbar)
            toolbox.show()
            toolbox.add_toolbar(_('Record'), record_toolbar)
            toolbox.show()
            toolbox.set_current_toolbar(1)

            # no sharing
            if hasattr(toolbox, 'share'):
                toolbox.share.hide()
            elif hasattr(toolbox, 'props'):
                toolbox.props.visible = False

        _label_factory(_('Select a lesson') + ':', lesson_toolbar)
        self._levels = self._get_levels(self._lessons_path)
        self._levels_combo = _combo_factory(self._levels, _('Select a lesson'),
                                            lesson_toolbar, self._levels_cb)

        _separator_factory(lesson_toolbar)

        self._lesson_button = _button_factory(
            'load-from-journal', _('Load a new lesson from the Journal'),
            self._lesson_cb, lesson_toolbar)

        _separator_factory(lesson_toolbar)

        self._create_lesson_button = _button_factory('view-source-insensitive',
                                                     _('Create a new lesson'),
                                                     self._create_lesson_cb,
                                                     lesson_toolbar)

        self._save_lesson_button = _button_factory(
            'save-to-journal-insensitive', _('Nothing to save'),
            self._save_lesson_cb, lesson_toolbar)

        self._sounds = self._get_sounds()
        self.sounds_combo = _combo_factory(self._sounds, _('Record a sound'),
                                           record_toolbar, self._sounds_cb)

        _separator_factory(record_toolbar)

        _label_factory(_('Record a sound') + ':', record_toolbar)
        self._record_lesson_button = _button_factory('media-record',
                                                     _('Start recording'),
                                                     self._record_lesson_cb,
                                                     record_toolbar)

        _separator_factory(record_toolbar)

        self._playback_button = _button_factory(
            'media-playback-start-insensitive', _('Nothing to play'),
            self._playback_recording_cb, record_toolbar)

        self._save_recording_button = _button_factory('sound-save-insensitive',
                                                      _('Nothing to save'),
                                                      self._save_recording_cb,
                                                      record_toolbar)

        _separator_factory(primary_toolbar)

        self._list_button = _button_factory('letter-list', _('Letter list'),
                                            self._list_cb, primary_toolbar)

        self._prev_page_button = _button_factory('previous-letter-insensitive',
                                                 _('Previous letter'),
                                                 self._prev_page_cb,
                                                 primary_toolbar)

        self._next_page_button = _button_factory('next-letter',
                                                 _('Next letter'),
                                                 self._next_page_cb,
                                                 primary_toolbar)

        _separator_factory(primary_toolbar)

        self._read_button = _button_factory('read',
                                            _('Read the sounds one at a time'),
                                            self._read_cb, primary_toolbar)

        _separator_factory(primary_toolbar)

        self._test_button = _button_factory('go-right', _('Self test'),
                                            self._test_cb, primary_toolbar)

        self.status = _label_factory('', primary_toolbar)

        if _HAVE_TOOLBOX:
            _separator_factory(toolbox.toolbar, False, True)

            stop_button = StopButton(self)
            stop_button.props.accelerator = '<Ctrl>q'
            toolbox.toolbar.insert(stop_button, -1)
            stop_button.show()
        lesson_toolbar.show()
        record_toolbar.show()
예제 #21
0
class MeasureActivity(activity.Activity):
    """ Oscilloscope Sugar activity """
    def __init__(self, handle):
        """ Init canvas, toolbars, etc.
        The toolbars are in toolbar_top.py and toolbar_side.py
        The audio controls are in audiograb.py
        The rendering happens in drawwaveform.py
        Logging (Journal interactions) are in journal.py """

        activity.Activity.__init__(self, handle)

        try:
            tmp_dir = path.join(activity.get_activity_root(), "data")
        except AttributeError:
            # Early versions of Sugar (e.g., 656) didn't support
            # get_activity_root()
            tmp_dir = path.join(
                environ['HOME'],
                ".sugar/default/org.laptop.MeasureActivity/data")
        self.using_gconf = _using_gconf
        self.icon_colors = self.get_icon_colors_from_sugar()
        self.stroke_color, self.fill_color = self.icon_colors.split(',')
        self.nick = self.get_nick_from_sugar()
        self.active_status = True
        self.ACTIVE = True
        self.LOGGING_IN_SESSION = False
        self.CONTEXT = ''
        self.adjustmentf = None  # Freq. slider control
        self.connect('notify::active', self._active_cb)
        self.connect('destroy', self.on_quit)
        self.hw = _get_hardware()

        self.closedSound = None
        self.openedSound = None

        self.session_id = 0

        self.ji = JournalInteraction(self)
        colorBlack = Color()
        colorBlack.init_rgba(0, 0, 0, 255)
        self.playsoundWin = PlayVideoWindow(colorBlack.gColor)
        self.playsound = Gplay()
        self.playsound.window = self.playsoundWin
        self.wave = DrawWaveform(self, self.playsound)

        self.hw = _get_hardware()
        log.debug('running on %s hardware' % (self.hw))
        if self.hw == XO15:
            self.audiograb = AudioGrab_XO15(self.wave.new_buffer, self)
        elif self.hw == XO1:
            self.audiograb = AudioGrab_XO1(self.wave.new_buffer, self)
        else:
            self.audiograb = AudioGrab_Unknown(self.wave.new_buffer, self)

        # no sharing
        self.max_participants = 1

        self.has_toolbarbox = _has_toolbarbox

        self.side_toolbar = SideToolbar(self)
        self.text_box = TextBox()

        self.box3 = gtk.HBox(False, 0)
        self.box3.pack_start(self.wave, True, True, 0)
        self.box3.pack_start(self.side_toolbar.box1, False, True, 0)

        self.box1 = gtk.VBox(False, 0)
        self.box1.pack_start(self.box3, True, True, 0)
        self.box1.pack_start(self.text_box.box_main, False, True, 0)

        self.set_canvas(self.box1)
        self.toolbox = None

        if self.has_toolbarbox:
            toolbox = ToolbarBox()
            self.toolbox = toolbox
            activity_button = ActivityToolbarButton(self)
            toolbox.toolbar.insert(activity_button, 0)
            activity_button.show()
        else:
            toolbox = ActivityToolbox(self)
            self.toolbox = toolbox
            # no sharing
            if hasattr(toolbox, 'share'):
                toolbox.share.hide()
            elif hasattr(toolbox, 'props'):
                toolbox.props.visible = False

            self.set_toolbox(toolbox)
            toolbox.connect('current-toolbar-changed',
                            self._toolbar_changed_cb)

        self.sound_toolbar = SoundToolbar(self)
        if self.has_toolbarbox:
            self._sound_button = ToolbarButton(label=_('Sound'),
                                               page=self.sound_toolbar,
                                               icon_name='sound-tools')
            toolbox.toolbar.insert(self._sound_button, -1)
            self._sound_button.show()
        else:
            toolbox.add_toolbar(_('Sound'), self.sound_toolbar)
        self.sound_toolbar.show()

        if _is_xo(self.hw):
            self.sensor_toolbar = SensorToolbar(self)
            if self.has_toolbarbox:
                self._sensor_button = ToolbarButton(label=_('Sensors'),
                                                    page=self.sensor_toolbar,
                                                    icon_name='sensor-tools')
                toolbox.toolbar.insert(self._sensor_button, -1)
                self._sensor_button.show()
            else:
                toolbox.add_toolbar(_('Sensors'), self.sensor_toolbar)
            self.sensor_toolbar.show()

        if self.has_toolbarbox:
            _separator = gtk.SeparatorToolItem()
            _separator.props.draw = False
            toolbox.toolbar.insert(_separator, -1)
            _separator.show()

            # add a "dummy" button to indicate what capture mode we are in
            self.label_button = ToolButton('domain-time2')
            toolbox.toolbar.insert(self.label_button, -1)
            self.label_button.show()
            self.label_button.set_tooltip(_('Time Base'))
            self.label_button.connect('clicked', self._label_cb)

            self.sound_toolbar.add_frequency_slider(toolbox.toolbar)

            _separator = gtk.SeparatorToolItem()
            _separator.props.draw = False
            _separator.set_expand(True)
            toolbox.toolbar.insert(_separator, -1)
            _separator.show()
            _stop_button = StopButton(self)
            _stop_button.props.accelerator = _('<Ctrl>Q')
            toolbox.toolbar.insert(_stop_button, -1)
            _stop_button.show()

            self.set_toolbox(toolbox)
            self._sound_button.set_expanded(True)

        else:
            toolbox.set_current_toolbar(TOOLBARS.index('sensor'))

        toolbox.show()
        self.sound_toolbar.update_page_size()

        self.show_all()

        self.first = True

        self.set_sound_context()
        self.set_sensor_context()
        self.set_show_hide_windows()
        self.wave.set_active(True)
        self.wave.set_context_on()

        self.set_show_hide_windows()

        #wait(10)
        #self.toolbox.set_current_toolbar(TOOLBARS.index('sensor'))
        #self._toolbar_changed_cb(self.toolbox, TOOLBARS.index('sensor'))
        #self.set_show_hide_windows('sensor')

    def set_show_hide_windows(self, mode='sound'):
        """Shows the appropriate window identified by the mode """
        if mode == 'sound':
            self.wave.set_context_on()
            self.side_toolbar.set_show_hide(True, mode)
        elif mode == 'sensor':
            self.wave.set_context_on()
            self.side_toolbar.set_show_hide(True, mode)

    def on_quit(self, data=None):
        """Clean up, close journal on quit"""
        self.audiograb.on_activity_quit()

    def _active_cb(self, widget, pspec):
        """ Callback to handle starting/pausing capture when active/idle """
        if self.first:
            self.audiograb.start_grabbing()
            self.first = False
        if not self.props.active and self.ACTIVE:
            self.audiograb.pause_grabbing()
            self.active_status = False
        elif self.props.active and not self.ACTIVE:
            self.audiograb.resume_grabbing()
            self.active_status = True

        self.ACTIVE = self.props.active
        self.wave.set_active(self.ACTIVE)

    def write_file(self, file_path):
        """ Write data to journal on quit """
        if hasattr(self, 'ji') and len(self.ji.temp_buffer) > 0:
            # Append new data to Journal entry
            writer = csv.writer(open(file_path, 'ab'))

            # Also output to a separate file as a workaround to Ticket 2127
            tmp_file_path = join(environ['SUGAR_ACTIVITY_ROOT'], 'instance',
                                 'sensor_data' + '.csv')
            log.debug('saving sensor data to %s' % (tmp_file_path))
            writer2 = csv.writer(open(tmp_file_path, 'ab'))

            for datum in self.ji.temp_buffer:
                writer.writerow([datum])
                writer2.writerow([datum])

            # Set the mimetype so that the file can be read by other Activities
            self.metadata['mime_type'] = 'text/csv'

            jobject = datastore.create()
            jobject.metadata['title'] = _('Measure Log')
            jobject.metadata['keep'] = '0'
            jobject.metadata['buddies'] = ''
            jobject.metadata['preview'] = ''
            jobject.metadata['icon-color'] = self.icon_colors
            jobject.metadata['mime_type'] = 'text/csv'
            jobject.file_path = tmp_file_path
            datastore.write(jobject)
            jobject.destroy()
            del jobject
            remove(tmp_file_path)

    def read_file(self, file_path):
        """ Read csv data from journal on start """
        reader = csv.reader(open(file_path, "rb"))
        # Count the number of sessions
        for r in reader:
            if len(r) > 0:
                if r[0] == _('Session'):
                    self.session_id += 1
                elif r[0].find('abiword') != -1:
                    # File has been opened by Write cannot be read by Measure
                    # See Ticket 2127
                    log.error('File was opened by Write: Measure cannot read')
                    return

    def _label_cb(self, data=None):
        """ Ignore the click on the label button """
        return

    def _toolbar_changed_cb(self, toolbox, num):
        """ Callback for changing the primary toolbar (0.84-) """
        if TOOLBARS[num] == 'sound':
            self.set_sound_context()
        elif TOOLBARS[num] == 'sensor':
            self.set_sensor_context()
        return True

    def set_sound_context(self):
        """ Called when sound toolbar is selected or button pushed """
        self.set_show_hide_windows('sound')
        if _is_xo(self.hw):
            self.sensor_toolbar.context_off()
        gobject.timeout_add(500, self.sound_toolbar.context_on)
        self.CONTEXT = 'sound'

    def set_sensor_context(self):
        """ Called when sensor toolbar is selected or button pushed """
        self.set_show_hide_windows('sensor')
        self.sound_toolbar.context_off()
        gobject.timeout_add(500, self.sensor_toolbar.context_on)
        self.CONTEXT = 'sensor'

    def get_icon_colors_from_sugar(self):
        """Returns the icon colors from the Sugar profile"""
        if self.using_gconf:
            client = gconf.client_get_default()
            return client.get_string('/desktop/sugar/user/color')
        else:
            return profile.get_color().to_string()

    def get_nick_from_sugar(self):
        """ Returns nick from Sugar """
        if self.using_gconf:
            client = gconf.client_get_default()
            return client.get_string('/desktop/sugar/user/nick')
        else:
            return profile.get_nick_name()
예제 #22
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.props.max_participants = 1

        self._web_view = Browser()

        try:
            from sugar.graphics.toolbarbox import ToolbarBox, ToolbarButton
            from sugar.activity.widgets import ActivityToolbarButton, StopButton, \
                                            ShareButton
            from mybutton import MyActivityToolbarButton

            toolbar_box = ToolbarBox()
            activity_button = MyActivityToolbarButton(self)
            toolbar_box.toolbar.insert(activity_button, 0)
            activity_button.show()

            viewtoolbar = ViewToolbar(self)
            viewbutton = ToolbarButton(page=viewtoolbar, \
                                        icon_name='camera')
            toolbar_box.toolbar.insert(viewbutton, -1)
            viewbutton.show()

            separator = gtk.SeparatorToolItem()
            #separator.props.draw = False
            #separator.set_expand(True)
            toolbar_box.toolbar.insert(separator, -1)
            separator.show()

            #lets reuse the code below
            navtoolbar = Toolbar(self._web_view)

            toolitem = gtk.ToolItem()
            navtoolbar._home.reparent(toolitem)
            toolbar_box.toolbar.insert(toolitem, -1)
            navtoolbar._home.show()
            toolitem.show()

            toolitem = gtk.ToolItem()
            navtoolbar._back.reparent(toolitem)
            toolbar_box.toolbar.insert(toolitem, -1)
            navtoolbar._back.show()
            toolitem.show()

            toolitem = gtk.ToolItem()
            navtoolbar._forward.reparent(toolitem)
            toolbar_box.toolbar.insert(toolitem, -1)
            navtoolbar._forward.show()
            toolitem.show()

            # we do not have collaboration features
            # make the share option insensitive
            self.max_participants = 1

            separator = gtk.SeparatorToolItem()
            separator.props.draw = False
            separator.set_expand(True)
            toolbar_box.toolbar.insert(separator, -1)
            separator.show()

            stop_button = StopButton(self)
            stop_button.props.accelerator = '<Ctrl><Shift>Q'
            toolbar_box.toolbar.insert(stop_button, -1)
            stop_button.show()

            self.set_toolbar_box(toolbar_box)
            toolbar_box.show()

        except ImportError:
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)
            toolbox.show()

            toolbar = Toolbar(self._web_view)
            toolbox.add_toolbar(_('Navigation'), toolbar)
            toolbar.show()
            viewtoolbar = ViewToolbar(self)
            toolbox.add_toolbar(_('View'), viewtoolbar)
            viewtoolbar.show()

            toolbox.set_current_toolbar(1)

        self.set_canvas(self._web_view)
        self._web_view.show()

        self._web_view.load_uri(HOME)
예제 #23
0
파일: activity.py 프로젝트: rbuj/followme
    def build_options_toolbar(self, toolbox):

        options_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        label1 = gtk.Label()
        label1.set_text(' ' + _('Pixels') + ' ')
        item1.add(label1)
        options_bar.insert(item1, -1)

        item2 = gtk.ToolItem()
        pixels = gtk.SpinButton()
        pixels.set_range(0, 1000)
        pixels.set_increments(1, 10)
        pixels.props.value = self.pixels
        pixels.connect('notify::value', self.pixels_value)
        item2.add(pixels)
        options_bar.insert(item2, -1)

        separator1 = gtk.SeparatorToolItem()
        separator1.props.draw = True
        options_bar.insert(separator1, -1)

        item3 = gtk.ToolItem()
        self.label_threshold_red = gtk.Label()
        self.label_threshold_red.set_text(' ' + _('Threshold:') + ' ' + _('Red') + ' ')
        item3.add(self.label_threshold_red)
        options_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        red_spin = gtk.SpinButton()
        red_spin.set_range(0, 255)
        red_spin.set_increments(1, 10)
        red_spin.props.value = self.threshold[0]
        red_spin.connect('notify::value', self.red_spin_threshold)
        item4.add(red_spin)
        options_bar.insert(item4, -1)

        item5 = gtk.ToolItem()
        self.label_threshold_green = gtk.Label()
        self.label_threshold_green.set_text(' ' + _('Green') + ' ')
        item5.add(self.label_threshold_green)
        options_bar.insert(item5, -1)

        item6 = gtk.ToolItem()
        green_spin = gtk.SpinButton()
        green_spin.set_range(0, 255)
        green_spin.set_increments(1, 10)
        green_spin.props.value = self.threshold[1]
        green_spin.connect('notify::value', self.green_spin_threshold)
        item6.add(green_spin)
        options_bar.insert(item6, -1)

        item7 = gtk.ToolItem()
        self.label_threshold_blue = gtk.Label()
        self.label_threshold_blue.set_text(' ' + _('Blue') + ' ')
        item7.add(self.label_threshold_blue)
        options_bar.insert(item7, -1)

        item8 = gtk.ToolItem()
        blue_spin = gtk.SpinButton()
        blue_spin.set_range(0, 255)
        blue_spin.set_increments(1, 10)
        blue_spin.props.value = self.threshold[2]
        blue_spin.connect('notify::value', self.blue_spin_threshold)
        item8.add(blue_spin)
        options_bar.insert(item8, -1)

        options_bar.show_all()
        options_button = ToolbarButton(label=_('Options'),
                page=options_bar,
                icon_name='view-source')
        toolbox.toolbar.insert(options_button, -1)
        options_button.show()
예제 #24
0
    def __init__(self, handle):
        ''' Init canvas, toolbars, etc.
        The toolbars are in sensor_toolbar.py and toolbar_side.py
        The audio controls are in audiograb.py
        The rendering happens in drawwaveform.py
        Logging is in journal.py '''

        activity.Activity.__init__(self, handle)

        self.mode_images = {}
        self.mode_images['sound'] = gtk.gdk.pixbuf_new_from_file_at_size(
            os.path.join(ICONS_DIR, 'media-audio.svg'), 45, 45)
        self.mode_images['resistance'] = gtk.gdk.pixbuf_new_from_file_at_size(
            os.path.join(ICONS_DIR, 'resistance.svg'), 45, 45)
        self.mode_images['voltage'] = gtk.gdk.pixbuf_new_from_file_at_size(
            os.path.join(ICONS_DIR, 'voltage.svg'), 45, 45)

        self.icon_colors = self.get_icon_colors_from_sugar()
        self.stroke_color, self.fill_color = self.icon_colors.split(',')
        self.nick = self.get_nick_from_sugar()
        self.CONTEXT = ''
        self.adjustmentf = None  # Freq. slider control

        self.new_recording = False
        self.session_id = 0
        self.read_metadata()

        self._active = True
        self._dsobject = None

        self.connect('notify::active', self._notify_active_cb)
        self.connect('destroy', self.on_quit)

        self.data_logger = DataLogger(self)

        self.hw = _get_hardware()
        log.debug('running on %s hardware' % (self.hw))

        self.wave = DrawWaveform(self)

        if self.hw == XO15:
            self.audiograb = AudioGrab_XO15(self.wave.new_buffer, self)
        elif self.hw == XO175:
            self.audiograb = AudioGrab_XO175(self.wave.new_buffer, self)
        elif self.hw == XO4:
            self.audiograb = AudioGrab_XO4(self.wave.new_buffer, self)
        elif self.hw == XO1:
            self.audiograb = AudioGrab_XO1(self.wave.new_buffer, self)
        else:
            self.audiograb = AudioGrab_Unknown(self.wave.new_buffer, self)

        # no sharing
        self.max_participants = 1

        box3 = gtk.HBox(False, 0)
        box3.pack_start(self.wave, True, True, 0)

        # We need event boxes in order to set the background color.
        side_eventboxes = []
        self.side_toolbars = []
        for i in range(self.audiograb.channels):
            side_eventboxes.append(gtk.EventBox())
            side_eventboxes[i].modify_bg(
                gtk.STATE_NORMAL, style.COLOR_TOOLBAR_GREY.get_gdk_color())
            self.side_toolbars.append(SideToolbar(self, channel=i))
            side_eventboxes[i].add(self.side_toolbars[i].box1)
            box3.pack_start(side_eventboxes[i], False, True, 0)

        event_box = gtk.EventBox()
        self.text_box = gtk.Label()
        self.text_box.set_justify(gtk.JUSTIFY_LEFT)
        alist = pango.AttrList()
        alist.insert(pango.AttrForeground(65535, 65535, 65535, 0, -1))
        self.text_box.set_attributes(alist)
        event_box.add(self.text_box)
        event_box.modify_bg(gtk.STATE_NORMAL,
                            style.COLOR_TOOLBAR_GREY.get_gdk_color())

        box1 = gtk.VBox(False, 0)
        box1.pack_start(box3, True, True, 0)
        box1.pack_start(event_box, False, True, 0)

        self.set_canvas(box1)

        toolbox = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbox.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.sensor_toolbar = SensorToolbar(self, self.audiograb.channels)
        #Added by Lego
        # Turn on bobot Server
        log.debug('Starting Server...')
        self.bobot = subprocess.Popen(['python', 'pybot_server.py'],
                                      cwd='./pybot')
        log.debug("Start : %s" % time.ctime())
        time.sleep(bobot_delay_start)
        log.debug("Started : %s" % time.ctime())
        self.lego_toolbar = LegoToolbar(self, self.audiograb.channels)
        #Lego end
        # Added by Butia
        self.butia_toolbar = ButiaToolbar(self, self.audiograb.channels)
        #Butia end
        #Added by Arduino
        self.arduino_toolbar = ArduinoToolbar(self, self.audiograb.channels)
        #Arduino end
        self.tuning_toolbar = TuningToolbar(self)
        self.new_instrument_toolbar = InstrumentToolbar(self)
        self._extras_toolbar = gtk.Toolbar()
        self.control_toolbar = gtk.Toolbar()

        sensor_button = ToolbarButton(label=_('Sensors'),
                                      page=self.sensor_toolbar,
                                      icon_name='sensor-tools')
        toolbox.toolbar.insert(sensor_button, -1)
        #Added by Lego
        sensor_button.connect('clicked', self._sensor_toolbar_cb)
        #Lego end
        sensor_button.show()
        lego_button = ToolbarButton(label=_('Lego'),
                                    page=self.lego_toolbar,
                                    icon_name='LEGO-tools')
        toolbox.toolbar.insert(lego_button, -1)
        lego_button.connect('clicked', self._lego_toolbar_cb)
        lego_button.show()
        #Lego end
        #Added by Butia
        sensor_button.connect('clicked', self._sensor_toolbar_cb)
        #Butia end
        sensor_button.show()
        #Added by Butia
        butia_button = ToolbarButton(label=_('Butia'),
                                     page=self.butia_toolbar,
                                     icon_name='butia-tools')
        toolbox.toolbar.insert(butia_button, -1)
        butia_button.connect('clicked', self._butia_toolbar_cb)
        butia_button.show()
        #Butia end
        #Added by Arduino
        sensor_button.connect('clicked', self._sensor_toolbar_cb)
        #Arduino end
        sensor_button.show()
        #Added by Arduino
        arduino_button = ToolbarButton(label=_('Arduino'),
                                       page=self.arduino_toolbar,
                                       icon_name='arduino-tools')
        toolbox.toolbar.insert(arduino_button, -1)
        arduino_button.connect('clicked', self._arduino_toolbar_cb)
        arduino_button.show()
        #Arduino end
        tuning_button = ToolbarButton(
            # TRANS: Tuning insruments
            label=_('Tuning'),
            page=self.tuning_toolbar,
            icon_name='tuning-tools')
        toolbox.toolbar.insert(tuning_button, -1)
        tuning_button.show()
        new_instrument_button = ToolbarButton(label=_('Add instrument'),
                                              page=self.new_instrument_toolbar,
                                              icon_name='view-source')
        toolbox.toolbar.insert(new_instrument_button, -1)
        new_instrument_button.show()
        #Added by butia
        self.butia_toolbar.show()
        #Butia end
        self._extras_button = ToolbarButton(page=self._extras_toolbar,
                                            icon_name='domain-time')
        toolbox.toolbar.insert(self._extras_button, -1)
        self._extras_toolbar_item = gtk.ToolItem()
        self._extras_toolbar.insert(self._extras_toolbar_item, -1)
        self._extras_button.hide()
        self.sensor_toolbar.show()

        self._extra_tools = gtk.HBox()

        # Set up Frequency-domain Button
        self.freq = ToolButton('domain-time')
        self.freq.set_tooltip(_('Time Base'))
        self.freq.connect('clicked', self.timefreq_control)
        self.freq.show()
        self._extra_tools.add(self.freq)

        self.sensor_toolbar.add_frequency_slider(self._extra_tools)

        self._extra_item = gtk.ToolItem()
        self._extra_item.add(self._extra_tools)
        self._extra_tools.show()
        toolbox.toolbar.insert(self._extra_item, -1)
        self._extra_item.show()

        self._pause = ToolButton('media-playback-pause')
        self._pause.set_tooltip(_('Freeze the display'))
        self._pause.connect('clicked', self._pause_play_cb)
        self._pause.show()
        toolbox.toolbar.insert(self._pause, -1)

        self._capture = ToolButton('image-saveoff')
        self._capture.set_tooltip(_('Capture sample now'))
        self._capture.connect('clicked', self._capture_cb)
        self._capture.show()
        toolbox.toolbar.insert(self._capture, -1)

        separator = gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbox.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        stop_button.props.accelerator = _('<Ctrl>Q')
        toolbox.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbox(toolbox)
        sensor_button.set_expanded(True)

        toolbox.show()
        self.sensor_toolbar.update_page_size()

        self.show_all()

        self._first = True

        # Always start in 'sound' mode.
        self.sensor_toolbar.set_mode('sound')
        self.sensor_toolbar.set_sound_context()
        self.sensor_toolbar.set_show_hide_windows()
        self.wave.set_active(True)
        self.wave.set_context_on()

        gtk.gdk.screen_get_default().connect('size-changed',
                                             self._configure_cb)
        self._configure_cb(None)
예제 #25
0
    def _setup_toolbars(self):
        ''' Setup the toolbars. '''

        self.max_participants = 1  # no sharing

        if HAVE_TOOLBOX:
            toolbox = ToolbarBox()

            # Activity toolbar
            activity_button = ActivityToolbarButton(self)

            toolbox.toolbar.insert(activity_button, 0)
            activity_button.show()

            self.set_toolbar_box(toolbox)
            toolbox.show()
            self.toolbar = toolbox.toolbar

            adjust_toolbar = gtk.Toolbar()
            adjust_toolbar_button = ToolbarButton(
                label=_('Adjust'),
                page=adjust_toolbar,
                icon_name='preferences-system')
            adjust_toolbar.show_all()
            adjust_toolbar_button.show()
        else:
            # Use pre-0.86 toolbar design
            primary_toolbar = gtk.Toolbar()
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)
            toolbox.add_toolbar(_('Page'), primary_toolbar)
            adjust_toolbar = gtk.Toolbar()
            toolbox.add_toolbar(_('Adjust'), adjust_toolbar)
            toolbox.show()
            toolbox.set_current_toolbar(1)
            self.toolbar = primary_toolbar

        self._prev_button = button_factory('go-previous-inactive',
                                           _('Prev slide'),
                                           self._prev_cb,
                                           self.toolbar,
                                           accelerator='<Ctrl>P')

        self._next_button = button_factory('go-next',
                                           _('Next slide'),
                                           self._next_cb,
                                           self.toolbar,
                                           accelerator='<Ctrl>N')

        separator_factory(self.toolbar)

        self._auto_button = button_factory('media-playlist-repeat',
                                           _('Autoplay'), self._autoplay_cb,
                                           self.toolbar)

        if HAVE_TOOLBOX:
            toolbox.toolbar.insert(adjust_toolbar_button, -1)

        label = label_factory(_('Adjust playback speed'), adjust_toolbar)
        label.show()

        self._unit_combo = combo_factory(UNITS, TEN,
                                         _('Adjust playback speed'),
                                         self._unit_combo_cb, adjust_toolbar)
        self._unit_combo.show()

        separator_factory(self.toolbar)

        self._thumb_button = button_factory('thumbs-view', _('Thumbnail view'),
                                            self._thumbs_cb, self.toolbar)

        button_factory('view-fullscreen',
                       _('Fullscreen'),
                       self.do_fullscreen_cb,
                       self.toolbar,
                       accelerator='<Alt>Return')

        separator_factory(self.toolbar)

        self._save_button = button_factory('save-as-html', _('Save as HTML'),
                                           self._save_as_html_cb, self.toolbar)

        if HAVE_TOOLBOX:
            separator_factory(toolbox.toolbar, False, True)

            stop_button = StopButton(self)
            stop_button.props.accelerator = '<Ctrl>q'
            toolbox.toolbar.insert(stop_button, -1)
            stop_button.show()
예제 #26
0
    def build_colors_toolbar(self, toolbox):

        colors_bar = gtk.Toolbar()

        ########################################################################
        # Point color
        item = gtk.ToolItem()
        label = gtk.Label()
        label.set_text('%s ' % _('Points'))
        item.add(label)
        colors_bar.insert(item, -1)

        # select color
        item = gtk.ToolItem()
        fill_color = ColorToolButton()
        fill_color.connect('notify::color', self.color_point_change)
        item.add(fill_color)
        colors_bar.insert(item, -1)

        # Separator
        separator = gtk.SeparatorToolItem()
        colors_bar.insert(separator, -1)
        separator.show()

        ########################################################################
        # Back color
        item = gtk.ToolItem()
        label = gtk.Label()
        label.set_text('%s ' % _('Background'))
        item.add(label)
        colors_bar.insert(item, -1)

        # select color
        item = gtk.ToolItem()
        _fill_color = ColorToolButton()
        c = gtk.gdk.Color()
        c.red = 21588
        c.green = 47546
        c.blue = 18504
        _fill_color.set_color(c)
        _fill_color.connect('notify::color', self.color_back_change)
        item.add(_fill_color)
        colors_bar.insert(item, -1)

        # Separator
        separator = gtk.SeparatorToolItem()
        colors_bar.insert(separator, -1)
        separator.show()

        ########################################################################
        # Line color
        item = gtk.ToolItem()
        label = gtk.Label()
        label.set_text('%s ' % _('Lines'))
        item.add(label)
        colors_bar.insert(item, -1)

        # select color
        item = gtk.ToolItem()
        _fill_color = ColorToolButton()
        _fill_color.connect('notify::color', self.color_line_change)
        item.add(_fill_color)
        colors_bar.insert(item, -1)

        # Separator
        separator = gtk.SeparatorToolItem()
        colors_bar.insert(separator, -1)
        separator.show()

        ########################################################################
        # Owner color
        item = gtk.ToolItem()
        label = gtk.Label()
        label.set_text('%s ' % _('Owner'))
        item.add(label)
        colors_bar.insert(item, -1)

        # select color
        item = gtk.ToolItem()
        _fill_color = ColorToolButton()
        c = gtk.gdk.Color()
        c.red = 65535
        _fill_color.set_color(c)
        _fill_color.connect('notify::color', self.color_owner_change)
        item.add(_fill_color)
        colors_bar.insert(item, -1)

        colors_bar.show_all()
        colors_button = ToolbarButton(label=_('Colors'),
                                      page=colors_bar,
                                      icon_name='toolbar-colors')
        toolbox.toolbar.insert(colors_button, -1)
        colors_button.show()
예제 #27
0
    def __init__(self, handle):
        """Set up the XoScope activity."""
        activity.Activity.__init__(self, handle)

        self._instance_directory = os.path.join(self.get_activity_root(),\
                'instance')

        # we do not have collaboration features
        # make the share option insensitive
        self.max_participants = 1
        self._capturing = False
        self._mode = 'live'

        # 0, 2 or 5 second delay before capturing the image
        self._delay = 0

        # Zoom 1x, 2x, 4x
        self._zoom = 1

        # Exposure bracketing
        self._bracketing = '0'

        # Preview mode stuff
        self._num_pics = 0

        # Index of pic to be displayed in preview mode
        self._pic_index = 0

        # This holds the image titles and name information. Saved
        # across activity instances
        self._images = []

        # Flag to store whether image preview element needs to resize
        # the pixbuf
        self._needs_resize = False

        if OLD_TOOLBAR:
            self.toolbox = ActivityToolbox(self)
            self.set_toolbox(self.toolbox)
            self.toolbox.show()

            activity_toolbar = self.toolbox.get_activity_toolbar()
            activity_toolbar = gtk.Toolbar()
            self.toolbox.add_toolbar(_('Control'), activity_toolbar)
            self.toolbox.set_current_toolbar(1)
            self._controls_toolbar = activity_toolbar

            advanced_toolbar = self.toolbox.get_activity_toolbar()
            advanced_toolbar = gtk.Toolbar()
            #self.toolbox.add_toolbar(_('Advanced controls'), advanced_toolbar)
        else:
            toolbar_box = ToolbarBox()
            self.activity_button = ActivityToolbarButton(self)
            toolbar_box.toolbar.insert(self.activity_button, 0)
            self.activity_button.show()
            self.set_toolbar_box(toolbar_box)

            toolbar_box.show()
            activity_toolbar = self.activity_button.page
            self._controls_toolbar = self.get_toolbar_box().toolbar
            self._controls_toolbar.show()

            advanced_toolbar = gtk.Toolbar()
            #advanced_toolbar.show_all()
            advanced_button = ToolbarButton()
            advanced_button.props.page = advanced_toolbar
            advanced_button.props.label = _('Advanced controls')
            advanced_button.props.icon_name = 'advanced'
            #advanced_button.show()
            #toolbar_box.toolbar.insert(advanced_button, -1)

        self._live_toolitem = gtk.ToolItem()
        self._live_toolbar_container = gtk.HBox()

        self._preview_toolitem = gtk.ToolItem()
        self._preview_toolbar_container = gtk.HBox()

        separator = gtk.SeparatorToolItem()
        if not OLD_TOOLBAR:
            separator.props.draw = True
        else:
            separator.props.draw = False
        separator.set_expand(False)
        self._controls_toolbar.insert(separator, -1)
        separator.show()

        self._photo_button = ToolButton('photo')
        self._photo_button.props.label = _('Capture photo')
        self._photo_button.connect('clicked',
                self.__capture_image_cb)
        self._live_toolbar_container.add(self._photo_button)
        self._photo_button.show()

        self._delay_button = ToolButton('delay_%d' % self._delay)
        self._delay_button.props.label = _('Capture delay')
        self._delay_button.connect('clicked',
                self.__change_capture_delay_cb)
        self._live_toolbar_container.add(self._delay_button)
        self._delay_button.show()

        self._zoom_button = ToolButton('zoom_%d' % self._zoom)
        self._zoom_button.props.label = _('Image Zoom')
        self._zoom_button.connect('clicked',
                self.__change_image_zoom_cb)
        self._live_toolbar_container.add(self._zoom_button)
        self._zoom_button.show()

        #if self._check_available_control(v4l2.V4L2_CID_EXPOSURE):
        #    self._bracketing_button = ToolButton('bracketing_%s' % self._bracketing)
        #    self._bracketing_button.props.label = _('bracketing mode')
        #    self._bracketing_button.connect('clicked',
        #            self.__change_capture_bracketing_cb)
        #    self._live_toolbar_container.add(self._bracketing_button)
        #    self._bracketing_button.show()

        separator = gtk.SeparatorToolItem()
        separator.props.draw = True
        separator.set_expand(False)
        self._live_toolbar_container.add(separator)
        separator.show()

        # Camera control settings follow

        if self._check_available_control(v4l2.V4L2_CID_EXPOSURE):
            self._exposure_button = ToolButton('exposure')
            self._exposure_button.set_palette(ScalePalette('Exposure',\
                    v4l2.V4L2_CID_EXPOSURE))
            self._exposure_button.connect('clicked',
                    self.__button_clicked_cb)
            self._live_toolbar_container.add(self._exposure_button)
            self._exposure_button.show()

        if self._check_available_control(v4l2.V4L2_CID_GAIN):
            self._gain_button = ToolButton('gain')
            self._gain_button.set_palette(ScalePalette('Gain',\
                    v4l2.V4L2_CID_GAIN,
                    self._check_available_control(v4l2.V4L2_CID_AUTOGAIN)))
            self._gain_button.connect('clicked',
                    self.__button_clicked_cb)
            advanced_toolbar.insert(self._gain_button, -1)
            self._gain_button.show()

        if self._check_available_control(v4l2.V4L2_CID_BRIGHTNESS):
            self._brightness_button = ToolButton('brightness')
            self._brightness_button.set_palette(ScalePalette('Brightness',\
                    v4l2.V4L2_CID_BRIGHTNESS,
                    self._check_available_control(
                        v4l2.V4L2_CID_AUTOBRIGHTNESS)))
            self._brightness_button.connect('clicked',
                    self.__button_clicked_cb)
            self._live_toolbar_container.add(self._brightness_button)
            self._brightness_button.show()

        if self._check_available_control(v4l2.V4L2_CID_CONTRAST):
            self._contrast_button = ToolButton('contrast')
            self._contrast_button.set_palette(ScalePalette('Contrast',\
                    v4l2.V4L2_CID_CONTRAST))
            self._contrast_button.connect('clicked',
                    self.__button_clicked_cb)
            self._live_toolbar_container.add(self._contrast_button)
            self._contrast_button.show()

        if self._check_available_control(v4l2.V4L2_CID_SATURATION):
            self._saturation_button = ToolButton('saturation')
            self._saturation_button.set_palette(ScalePalette('Saturation',\
                    v4l2.V4L2_CID_SATURATION))
            self._saturation_button.connect('clicked',
                    self.__button_clicked_cb)
            advanced_toolbar.insert(self._saturation_button, -1)
            self._saturation_button.show()

        if self._check_available_control(
                v4l2.V4L2_CID_WHITE_BALANCE_TEMPERATURE):
            self._white_balance_button = ToolButton('white_balance')
            self._white_balance_button.set_palette(ScalePalette('White'
                    ' balance', v4l2.V4L2_CID_WHITE_BALANCE_TEMPERATURE,
                    self._check_available_control(
                        v4l2.V4L2_CID_AUTO_WHITE_BALANCE)))
            self._white_balance_button.connect('clicked',
                    self.__button_clicked_cb)
            advanced_toolbar.insert(self._white_balance_button, -1)
            self._white_balance_button.show()

        if self._check_available_control(v4l2.V4L2_CID_HUE):
            self._color_tone_button = ToolButton('color_tone')
            self._color_tone_button.set_palette(ScalePalette('Color'
                    ' tone', v4l2.V4L2_CID_HUE,
                    self._check_available_control(
                        v4l2.V4L2_CID_HUE_AUTO)))
            self._color_tone_button.connect('clicked',
                    self.__button_clicked_cb)
            advanced_toolbar.insert(self._color_tone_button, -1)
            self._color_tone_button.show()

        #if self._check_available_control(v4l2.V4L2_CID_NIGHT_MODE):
        #    self._night_mode_button = ToolButton('night_mode')
        #    self._night_mode_button.set_palette(ScalePalette('Night mode',\
        #            v4l2.V4L2_CID_NIGHT_MODE))
        #    self._night_mode_button.connect('clicked',
        #            self.__button_clicked_cb)
        #    self._live_toolbar_container.add(self._night_mode_button)
        #    self._night_mode_button.show()

        self._previous_image = ToolButton('go-previous-paired')
        self._previous_image.label = _('Previous image')
        self._previous_image.connect('clicked',
                self.__previous_image_clicked_cb)
        self._preview_toolbar_container.add(self._previous_image)
        self._previous_image.show()

        self._next_image = ToolButton('go-next-paired')
        self._next_image.label = _('Next image')
        self._next_image.connect('clicked',
                self.__next_image_clicked_cb)
        self._preview_toolbar_container.add(self._next_image)
        self._next_image.show()

        self._image_name_entry = gtk.Entry()
        self._image_name_entry.set_text('')
        self._image_name_entry.set_size_request(400, -1)
        self._image_name_entry.connect('activate',
                self.__image_name_entry_activated_cb)
        self._preview_toolbar_container.add(self._image_name_entry)
        self._image_name_entry.show()

        self._save_to_journal = ToolButton('save_to_journal')
        self._save_to_journal.label = _('Save to journal')
        self._save_to_journal.connect('clicked',
                self.__save_to_journal_clicked_cb)
        self._preview_toolbar_container.add(self._save_to_journal)
        self._save_to_journal.show()

        self._trash = ToolButton('trash')
        self._trash.label = _('Delete')
        self._trash.connect('clicked',
                self.__trash_clicked_cb)
        self._preview_toolbar_container.add(self._trash)
        self._trash.show()

        separator = gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        self._controls_toolbar.insert(separator, -1)
        separator.show()

        self._mode_button = ToolButton('%s_mode' % self._mode)
        self._mode_button.props.label = _('Mode')
        self._mode_button.connect('clicked',
                self.__switch_modes_cb)
        self._controls_toolbar.insert(self._mode_button, -1)
        self._mode_button.show()

        if not OLD_TOOLBAR:
            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            separator.set_expand(False)
            self._controls_toolbar.insert(separator, -1)
            separator.show()

            activity_stop = StopButton(self)
            toolbar_box.toolbar.insert(activity_stop, -1)
            activity_stop.show()

        self._preview_toolitem.add(self._preview_toolbar_container)
        self._live_toolitem.add(self._live_toolbar_container)
        self._preview_toolbar_container.show()
        self._live_toolbar_container.show()

        if self._mode == 'preview':
            self._controls_toolbar.insert(self._preview_toolitem, 1)
            self._preview_toolitem.show()
        else:
            self._controls_toolbar.insert(self._live_toolitem, 1)
            self._live_toolitem.show()
            self._mode = 'live'

        self._controls_toolbar.show()
        activity_toolbar.show()

        self._main_view = gtk.HBox()
        self._movie_window = gtk.DrawingArea()
        self._movie_window.connect('realize',
                self.__movie_window_realize_cb)
        self._movie_window.unset_flags(gtk.DOUBLE_BUFFERED)
        self._movie_window.set_flags(gtk.APP_PAINTABLE)
        self._main_view.add(self._movie_window)

        self._preview_frame = gtk.AspectFrame(None, 0.5, 0.5, 1, True)
        self._preview_window = gtk.Image()
        self._preview_frame.add(self._preview_window)
        self._preview_window.connect('size_allocate',
                self.__preview_window_size_allocate_cb)

        self.xoscope = gst.Pipeline('xoscope_pipe')
        camsrc = gst.element_factory_make('v4l2src', 'camsrc')

        caps = gst.Caps('video/x-raw-yuv')

        filt = gst.element_factory_make('capsfilter', 'filter')
        filt.set_property('caps', caps)
        ffmpegcolorspace = gst.element_factory_make('ffmpegcolorspace',
                'ffmpegcolorspace')
        self._disp_sink = gst.element_factory_make('xvimagesink', 'disp_sink')

        # http://thread.gmane.org/gmane.comp.video.gstreamer.devel/29644
        self._disp_sink.set_property('sync', False)

        self.image_sink = gst.element_factory_make('fakesink',
                'image_sink')
        self.image_sink.set_property('silent', True)

        tee = gst.element_factory_make('tee', 'tee')
        queue = gst.element_factory_make('queue', 'dispqueue')
        queue.set_property('leaky', True)
        queue.set_property('max-size-buffers', 20)

        queue2 = gst.element_factory_make('queue', 'imagequeue')
        queue2.set_property('leaky', True)
        queue2.set_property('max-size-buffers', 20)

        self._zoom_element = gst.element_factory_make('videobox', 'zoombox')

        jpeg = gst.element_factory_make('jpegenc', 'pbjpeg')
        jpeg.set_property('quality', 100)

        self.xoscope.add(camsrc, filt, ffmpegcolorspace,\
                self._zoom_element, self._disp_sink, tee, queue, queue2,\
                self.image_sink, jpeg)
        gst.element_link_many(camsrc, filt, self._zoom_element,\
                ffmpegcolorspace, tee, queue, self._disp_sink)
        gst.element_link_many(tee, queue2, jpeg, self.image_sink)

        bus = self.xoscope.get_bus()
        bus.add_signal_watch()
        bus.enable_sync_message_emission()
        bus.connect('message', self.__on_message_cb)
        bus.connect('sync-message::element', self.__on_sync_message_cb)

        self._main_view.show()
        self._movie_window.show()
        self.set_canvas(self._main_view)

        # If we start playing without a delay, the live view window
        # doesn't get attached to the main canvas properly (This is
        # a problem on slow computers like xo1).
        gobject.timeout_add(2000, self.__start_live_view)
예제 #28
0
파일: activity.py 프로젝트: rbuj/followme
    def build_colors_toolbar(self, toolbox):

        barra_colors = gtk.Toolbar()

        item1 = gtk.ToolItem()
        label1 = gtk.Label()
        label1.set_text(_('Color mode') + ' ')
        item1.add(label1)
        barra_colors.insert(item1, -1)

        item2 = gtk.ToolItem()
        modes = ('RGB', 'YUV', 'HSV')
        combo = Combo(modes)
        item2.add(combo)
        combo.connect('changed', self.change_combo)
        barra_colors.insert(item2, -1)

        separator1 = gtk.SeparatorToolItem()
        separator1.props.draw = True
        barra_colors.insert(separator1, -1)

        item_l = gtk.ToolItem()
        label4 = gtk.Label()
        label4.set_text(_('Brightness') + ' ')
        item_l.add(label4)
        barra_colors.insert(item_l, -1)
        
        item = gtk.ToolItem()
        brightness_spin = gtk.SpinButton()
        brightness_spin.set_range(-1, 255)
        brightness_spin.set_increments(1, 10)
        brightness_spin.props.value = int(self.brightness)
        brightness_spin.connect('notify::value', self.brightness_spin_change)
        item.add(brightness_spin)
        barra_colors.insert(item, -1)

        separator2 = gtk.SeparatorToolItem()
        separator2.props.draw = True
        barra_colors.insert(separator2, -1)

        item3 = gtk.ToolItem()
        label3 = gtk.Label()
        label3.set_text(_('Threshold view'))
        item3.add(label3)
        barra_colors.insert(item3, -1)

        threshold_view = ToolButton('media-playback-stop')
        threshold_view.connect('clicked', self.threshold_view)
        threshold_view.set_tooltip(_('Yes'))
        barra_colors.insert(threshold_view, -1)

        separator3 = gtk.SeparatorToolItem()
        separator3.props.draw = True
        barra_colors.insert(separator3, -1)

        item4 = gtk.ToolItem()
        label4 = gtk.Label()
        label4.set_text(_('Outline'))
        item4.add(label4)
        barra_colors.insert(item4, -1)

        outline_view = ToolButton('media-playback-stop')
        outline_view.connect('clicked', self.outline_view)
        outline_view.set_tooltip(_('Yes'))
        barra_colors.insert(outline_view, -1)

        separator4 = gtk.SeparatorToolItem()
        separator4.props.draw = True
        barra_colors.insert(separator4, -1)

        item5 = gtk.ToolItem()
        label5 = gtk.Label()
        label5.set_text(_('Rects'))
        item5.add(label5)
        barra_colors.insert(item5, -1)

        rects_view = ToolButton('media-playback-stop')
        rects_view.connect('clicked', self.rects_view)
        rects_view.set_tooltip(_('Yes'))
        barra_colors.insert(rects_view, -1)

        barra_colors.show_all()
        colors_button = ToolbarButton(label=_('Colors'),
                page=barra_colors,
                icon_name='toolbar-colors')
        toolbox.toolbar.insert(colors_button, -1)
        colors_button.show()
예제 #29
0
    def build_colors_toolbar(self, toolbox):

        colors_bar = gtk.Toolbar()

        ########################################################################
        # Point color
        item = gtk.ToolItem()
        label = gtk.Label()
        label.set_text('%s ' % _('Player 1'))
        item.add(label)
        colors_bar.insert(item, -1)

        # select color
        item = gtk.ToolItem()
        _fill_color = ColorToolButton()
        c = gtk.gdk.Color()
        c.red = 65535
        c.green = 65535
        c.blue = 65535
        _fill_color.set_color(c)
        _fill_color.connect('notify::color', self.color_player1_change)
        item.add(_fill_color)
        colors_bar.insert(item, -1)

        # Separator
        separator = gtk.SeparatorToolItem()
        colors_bar.insert(separator, -1)
        separator.show()

        ########################################################################
        # Back color
        item = gtk.ToolItem()
        label = gtk.Label()
        label.set_text('%s ' % _('Player 2'))
        item.add(label)
        colors_bar.insert(item, -1)

        # select color
        item = gtk.ToolItem()
        _fill_color = ColorToolButton()
        c = gtk.gdk.Color()
        c.red = 0
        c.green = 0
        c.blue = 0
        _fill_color.set_color(c)
        _fill_color.connect('notify::color', self.color_player2_change)
        item.add(_fill_color)
        colors_bar.insert(item, -1)

        # Separator
        separator = gtk.SeparatorToolItem()
        colors_bar.insert(separator, -1)
        separator.show()

        ########################################################################
        # Line color
        item = gtk.ToolItem()
        label = gtk.Label()
        label.set_text('%s ' % _('Lines'))
        item.add(label)
        colors_bar.insert(item, -1)

        # select color
        item = gtk.ToolItem()
        _fill_color = ColorToolButton()
        _fill_color.connect('notify::color', self.color_line_change)
        item.add(_fill_color)
        colors_bar.insert(item, -1)

        # Separator
        separator = gtk.SeparatorToolItem()
        colors_bar.insert(separator, -1)
        separator.show()

        ########################################################################
        # Line color
        item = gtk.ToolItem()
        label = gtk.Label()
        label.set_text('%s ' % _('Background'))
        item.add(label)
        colors_bar.insert(item, -1)

        # select color
        item = gtk.ToolItem()
        _fill_color = ColorToolButton()
        _fill_color.connect('notify::color', self.color_back_change)
        item.add(_fill_color)
        colors_bar.insert(item, -1)

        # Separator
        separator = gtk.SeparatorToolItem()
        colors_bar.insert(separator, -1)
        separator.show()

        ########################################################################
        # Line color
        item = gtk.ToolItem()
        label = gtk.Label()
        label.set_text('%s ' % _('Board'))
        item.add(label)
        colors_bar.insert(item, -1)

        # select color
        item = gtk.ToolItem()
        _fill_color = ColorToolButton()
        _fill_color.connect('notify::color', self.color_board_change)
        item.add(_fill_color)
        colors_bar.insert(item, -1)

        ########################################################################
        colors_bar.show_all()
        colors_button = ToolbarButton(label=_('Colors'),
                page=colors_bar,
                icon_name='toolbar-colors')
        toolbox.toolbar.insert(colors_button, -1)
        colors_button.show()
예제 #30
0
    def __init__(self, handle):
        """ Init canvas, toolbars, etc.
        The toolbars are in toolbar_top.py and toolbar_side.py
        The audio controls are in audiograb.py
        The rendering happens in drawwaveform.py
        Logging (Journal interactions) are in journal.py """

        activity.Activity.__init__(self, handle)

        try:
            tmp_dir = path.join(activity.get_activity_root(), "data")
        except AttributeError:
            # Early versions of Sugar (e.g., 656) didn't support
            # get_activity_root()
            tmp_dir = path.join(
                environ['HOME'],
                ".sugar/default/org.laptop.MeasureActivity/data")
        self.using_gconf = _using_gconf
        self.icon_colors = self.get_icon_colors_from_sugar()
        self.stroke_color, self.fill_color = self.icon_colors.split(',')
        self.nick = self.get_nick_from_sugar()
        self.active_status = True
        self.ACTIVE = True
        self.LOGGING_IN_SESSION = False
        self.CONTEXT = ''
        self.adjustmentf = None  # Freq. slider control
        self.connect('notify::active', self._active_cb)
        self.connect('destroy', self.on_quit)
        self.hw = _get_hardware()

        self.closedSound = None
        self.openedSound = None

        self.session_id = 0

        self.ji = JournalInteraction(self)
        colorBlack = Color()
        colorBlack.init_rgba(0, 0, 0, 255)
        self.playsoundWin = PlayVideoWindow(colorBlack.gColor)
        self.playsound = Gplay()
        self.playsound.window = self.playsoundWin
        self.wave = DrawWaveform(self, self.playsound)

        self.hw = _get_hardware()
        log.debug('running on %s hardware' % (self.hw))
        if self.hw == XO15:
            self.audiograb = AudioGrab_XO15(self.wave.new_buffer, self)
        elif self.hw == XO1:
            self.audiograb = AudioGrab_XO1(self.wave.new_buffer, self)
        else:
            self.audiograb = AudioGrab_Unknown(self.wave.new_buffer, self)

        # no sharing
        self.max_participants = 1

        self.has_toolbarbox = _has_toolbarbox

        self.side_toolbar = SideToolbar(self)
        self.text_box = TextBox()

        self.box3 = gtk.HBox(False, 0)
        self.box3.pack_start(self.wave, True, True, 0)
        self.box3.pack_start(self.side_toolbar.box1, False, True, 0)

        self.box1 = gtk.VBox(False, 0)
        self.box1.pack_start(self.box3, True, True, 0)
        self.box1.pack_start(self.text_box.box_main, False, True, 0)

        self.set_canvas(self.box1)
        self.toolbox = None

        if self.has_toolbarbox:
            toolbox = ToolbarBox()
            self.toolbox = toolbox
            activity_button = ActivityToolbarButton(self)
            toolbox.toolbar.insert(activity_button, 0)
            activity_button.show()
        else:
            toolbox = ActivityToolbox(self)
            self.toolbox = toolbox
            # no sharing
            if hasattr(toolbox, 'share'):
                toolbox.share.hide()
            elif hasattr(toolbox, 'props'):
                toolbox.props.visible = False

            self.set_toolbox(toolbox)
            toolbox.connect('current-toolbar-changed',
                            self._toolbar_changed_cb)

        self.sound_toolbar = SoundToolbar(self)
        if self.has_toolbarbox:
            self._sound_button = ToolbarButton(label=_('Sound'),
                                               page=self.sound_toolbar,
                                               icon_name='sound-tools')
            toolbox.toolbar.insert(self._sound_button, -1)
            self._sound_button.show()
        else:
            toolbox.add_toolbar(_('Sound'), self.sound_toolbar)
        self.sound_toolbar.show()

        if _is_xo(self.hw):
            self.sensor_toolbar = SensorToolbar(self)
            if self.has_toolbarbox:
                self._sensor_button = ToolbarButton(label=_('Sensors'),
                                                    page=self.sensor_toolbar,
                                                    icon_name='sensor-tools')
                toolbox.toolbar.insert(self._sensor_button, -1)
                self._sensor_button.show()
            else:
                toolbox.add_toolbar(_('Sensors'), self.sensor_toolbar)
            self.sensor_toolbar.show()

        if self.has_toolbarbox:
            _separator = gtk.SeparatorToolItem()
            _separator.props.draw = False
            toolbox.toolbar.insert(_separator, -1)
            _separator.show()

            # add a "dummy" button to indicate what capture mode we are in
            self.label_button = ToolButton('domain-time2')
            toolbox.toolbar.insert(self.label_button, -1)
            self.label_button.show()
            self.label_button.set_tooltip(_('Time Base'))
            self.label_button.connect('clicked', self._label_cb)

            self.sound_toolbar.add_frequency_slider(toolbox.toolbar)

            _separator = gtk.SeparatorToolItem()
            _separator.props.draw = False
            _separator.set_expand(True)
            toolbox.toolbar.insert(_separator, -1)
            _separator.show()
            _stop_button = StopButton(self)
            _stop_button.props.accelerator = _('<Ctrl>Q')
            toolbox.toolbar.insert(_stop_button, -1)
            _stop_button.show()

            self.set_toolbox(toolbox)
            self._sound_button.set_expanded(True)

        else:
            toolbox.set_current_toolbar(TOOLBARS.index('sensor'))

        toolbox.show()
        self.sound_toolbar.update_page_size()

        self.show_all()

        self.first = True

        self.set_sound_context()
        self.set_sensor_context()
        self.set_show_hide_windows()
        self.wave.set_active(True)
        self.wave.set_context_on()

        self.set_show_hide_windows()
예제 #31
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.props.max_participants = 1

        self._web_view = Browser()

        try:
            from sugar.graphics.toolbarbox import ToolbarBox, ToolbarButton
            from sugar.activity.widgets import ActivityToolbarButton, StopButton, ShareButton
            from mybutton import MyActivityToolbarButton

            toolbar_box = ToolbarBox()
            activity_button = MyActivityToolbarButton(self)
            toolbar_box.toolbar.insert(activity_button, 0)
            activity_button.show()

            viewtoolbar = ViewToolbar(self)
            viewbutton = ToolbarButton(page=viewtoolbar, icon_name="camera")
            toolbar_box.toolbar.insert(viewbutton, -1)
            viewbutton.show()

            separator = gtk.SeparatorToolItem()
            # separator.props.draw = False
            # separator.set_expand(True)
            toolbar_box.toolbar.insert(separator, -1)
            separator.show()

            # lets reuse the code below
            navtoolbar = Toolbar(self._web_view)

            toolitem = gtk.ToolItem()
            navtoolbar._home.reparent(toolitem)
            toolbar_box.toolbar.insert(toolitem, -1)
            navtoolbar._home.show()
            toolitem.show()

            toolitem = gtk.ToolItem()
            navtoolbar._back.reparent(toolitem)
            toolbar_box.toolbar.insert(toolitem, -1)
            navtoolbar._back.show()
            toolitem.show()

            toolitem = gtk.ToolItem()
            navtoolbar._forward.reparent(toolitem)
            toolbar_box.toolbar.insert(toolitem, -1)
            navtoolbar._forward.show()
            toolitem.show()

            # we do not have collaboration features
            # make the share option insensitive
            self.max_participants = 1

            separator = gtk.SeparatorToolItem()
            separator.props.draw = False
            separator.set_expand(True)
            toolbar_box.toolbar.insert(separator, -1)
            separator.show()

            stop_button = StopButton(self)
            stop_button.props.accelerator = "<Ctrl><Shift>Q"
            toolbar_box.toolbar.insert(stop_button, -1)
            stop_button.show()

            self.set_toolbar_box(toolbar_box)
            toolbar_box.show()

        except ImportError:
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)
            toolbox.show()

            toolbar = Toolbar(self._web_view)
            toolbox.add_toolbar(_("Navigation"), toolbar)
            toolbar.show()
            viewtoolbar = ViewToolbar(self)
            toolbox.add_toolbar(_("View"), viewtoolbar)
            viewtoolbar.show()

            toolbox.set_current_toolbar(1)

        self.set_canvas(self._web_view)
        self._web_view.show()

        self._web_view.load_uri(HOME)
    def __init__(self, handle):
        """ Initiate activity. """
        super(AbacusActivity, self).__init__(handle)

        if _new_sugar_system:
            # Use 0.86 toolbar design
            toolbar_box = ToolbarBox()

            # Buttons added to the Activity toolbar
            activity_button = ActivityToolbarButton(self)
            toolbar_box.toolbar.insert(activity_button, 0)
            activity_button.show()

            # Suanpan (Chinese abacus) 2:5
            self.chinese = ToolButton("Con")
            self.chinese.set_tooltip(_('Suanpan'))
            self.chinese.props.sensitive = True
            self.chinese.connect('clicked', self._chinese_cb)
            toolbar_box.toolbar.insert(self.chinese, -1)
            self.chinese.show()

            # Soroban (Japanese abacus) 1:4
            self.japanese = ToolButton("Joff")
            self.japanese.set_tooltip(_('Soroban'))
            self.japanese.props.sensitive = True
            self.japanese.connect('clicked', self._japanese_cb)
            toolbar_box.toolbar.insert(self.japanese, -1)
            self.japanese.show()

            # Schety (Russian abacus) 0:10
            self.russian = ToolButton("Roff")
            self.russian.set_tooltip(_('Schety'))
            self.russian.props.sensitive = True
            self.russian.connect('clicked', self._russian_cb)
            toolbar_box.toolbar.insert(self.russian, -1)
            self.russian.show()

            # Nepohualtzintzin (Mayan abacus) 3:4 (base 20)
            self.mayan = ToolButton("Moff")
            self.mayan.set_tooltip(_('Nepohualtzintzin'))
            self.mayan.props.sensitive = True
            self.mayan.connect('clicked', self._mayan_cb)
            toolbar_box.toolbar.insert(self.mayan, -1)
            self.mayan.show()

            # Binary (base 2)
            self.binary = ToolButton("Boff")
            self.binary.set_tooltip(_('Binary'))
            self.binary.props.sensitive = True
            self.binary.connect('clicked', self._binary_cb)
            toolbar_box.toolbar.insert(self.binary, -1)
            self.binary.show()

            # Hexadecimal (base 16)
            self.hex = ToolButton("Hoff")
            self.hex.set_tooltip(_('Hexadecimal'))
            self.hex.props.sensitive = True
            self.hex.connect('clicked', self._hex_cb)
            toolbar_box.toolbar.insert(self.hex, -1)
            self.hex.show()

            # Fractions (1/2, 1/3, 1/4, 1/5, 1/6, 1/8, 1/9, 1/10, 1/12)
            self.fraction = ToolButton("Foff")
            self.fraction.set_tooltip(_('Fraction'))
            self.fraction.props.sensitive = True
            self.fraction.connect('clicked', self._fraction_cb)
            toolbar_box.toolbar.insert(self.fraction, -1)
            self.fraction.show()

            separator = gtk.SeparatorToolItem()
            separator.props.draw = False
            separator.set_expand(False)
            separator.show()
            toolbar_box.toolbar.insert(separator, -1)

            # The Customization submenu (roll your own)
            custom_toolbar = gtk.Toolbar()

            self._rods_label = gtk.Label(_("Rods:") + " ")
            self._rods_label.set_line_wrap(True)
            self._rods_label.show()
            self._rods_toolitem = gtk.ToolItem()
            self._rods_toolitem.add(self._rods_label)
            custom_toolbar.insert(self._rods_toolitem, -1)
            self._rods_toolitem.show()

            self._rods_spin_adj = gtk.Adjustment(15, 1, 20, 1, 32, 0)
            self._rods_spin = gtk.SpinButton(self._rods_spin_adj, 0, 0)
            self._rods_spin_id = self._rods_spin.connect(
                'value-changed', self._rods_spin_cb)
            self._rods_spin.set_numeric(True)
            self._rods_spin.show()
            self.tool_item_rods = gtk.ToolItem()
            self.tool_item_rods.add(self._rods_spin)
            custom_toolbar.insert(self.tool_item_rods, -1)
            self.tool_item_rods.show()

            self._top_label = gtk.Label(" " + _("Top:") + " ")
            self._top_label.set_line_wrap(True)
            self._top_label.show()
            self._top_toolitem = gtk.ToolItem()
            self._top_toolitem.add(self._top_label)
            custom_toolbar.insert(self._top_toolitem, -1)
            self._top_toolitem.show()

            self._top_spin_adj = gtk.Adjustment(2, 0, 4, 1, 32, 0)
            self._top_spin = gtk.SpinButton(self._top_spin_adj, 0, 0)
            self._top_spin_id = self._top_spin.connect('value-changed',
                                                       self._top_spin_cb)
            self._top_spin.set_numeric(True)
            self._top_spin.show()
            self.tool_item_top = gtk.ToolItem()
            self.tool_item_top.add(self._top_spin)
            custom_toolbar.insert(self.tool_item_top, -1)
            self.tool_item_top.show()

            self._bottom_label = gtk.Label(" " + _("Bottom:") + " ")
            self._bottom_label.set_line_wrap(True)
            self._bottom_label.show()
            self._bottom_toolitem = gtk.ToolItem()
            self._bottom_toolitem.add(self._bottom_label)
            custom_toolbar.insert(self._bottom_toolitem, -1)
            self._bottom_toolitem.show()

            self._bottom_spin_adj = gtk.Adjustment(5, 1, 15, 1, 32, 0)
            self._bottom_spin = gtk.SpinButton(self._bottom_spin_adj, 0, 0)
            self._bottom_spin_id = self._bottom_spin.connect(
                'value-changed', self._bottom_spin_cb)
            self._bottom_spin.set_numeric(True)
            self._bottom_spin.show()
            self.tool_item_bottom = gtk.ToolItem()
            self.tool_item_bottom.add(self._bottom_spin)
            custom_toolbar.insert(self.tool_item_bottom, -1)
            self.tool_item_bottom.show()

            self._value_label = gtk.Label(" " + _("Factor:") + " ")
            self._value_label.set_line_wrap(True)
            self._value_label.show()
            self._value_toolitem = gtk.ToolItem()
            self._value_toolitem.add(self._value_label)
            custom_toolbar.insert(self._value_toolitem, -1)
            self._value_toolitem.show()

            self._value_spin_adj = gtk.Adjustment(5, 1, 20, 1, 32, 0)
            self._value_spin = gtk.SpinButton(self._value_spin_adj, 0, 0)
            self._value_spin_id = self._value_spin.connect(
                'value-changed', self._value_spin_cb)
            self._value_spin.set_numeric(True)
            self._value_spin.show()
            self.tool_item_value = gtk.ToolItem()
            self.tool_item_value.add(self._value_spin)
            custom_toolbar.insert(self.tool_item_value, -1)
            self.tool_item_value.show()

            self._base_label = gtk.Label(" " + _("Base:") + " ")
            self._base_label.set_line_wrap(True)
            self._base_label.show()
            self._base_toolitem = gtk.ToolItem()
            self._base_toolitem.add(self._base_label)
            custom_toolbar.insert(self._base_toolitem, -1)
            self._base_toolitem.show()

            self._base_spin_adj = gtk.Adjustment(10, 1, 20, 1, 32, 0)
            self._base_spin = gtk.SpinButton(self._base_spin_adj, 0, 0)
            self._base_spin_id = self._base_spin.connect(
                'value-changed', self._base_spin_cb)
            self._base_spin.set_numeric(True)
            self._base_spin.show()
            self.tool_item_base = gtk.ToolItem()
            self.tool_item_base.add(self._base_spin)
            custom_toolbar.insert(self.tool_item_base, -1)
            self.tool_item_base.show()

            # Custom
            self._custom = ToolButton("new-game")
            self._custom.set_tooltip(_('Custom'))
            self._custom.props.sensitive = True
            self._custom.connect('clicked', self._custom_cb)
            custom_toolbar.insert(self._custom, -1)
            self._custom.show()

            custom_toolbar_button = ToolbarButton(page=custom_toolbar,
                                                  icon_name='view-source')
            custom_toolbar.show()
            toolbar_box.toolbar.insert(custom_toolbar_button, -1)
            custom_toolbar_button.show()

            separator = gtk.SeparatorToolItem()
            separator.props.draw = False
            separator.set_expand(True)
            separator.show()
            toolbar_box.toolbar.insert(separator, -1)

            # The ever-present Stop Button
            stop_button = StopButton(self)
            stop_button.props.accelerator = _('<Ctrl>Q')
            toolbar_box.toolbar.insert(stop_button, -1)
            stop_button.show()

            self.set_toolbar_box(toolbar_box)
            toolbar_box.show()

        else:
            # Use pre-0.86 toolbar design
            self.toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(self.toolbox)

            self.projectToolbar = ProjectToolbar(self)
            self.toolbox.add_toolbar(_('Project'), self.projectToolbar)

            self.customToolbar = CustomToolbar(self)
            self.toolbox.add_toolbar(_('Custom'), self.customToolbar)

            self.toolbox.show()

        # Create a canvas
        canvas = gtk.DrawingArea()
        canvas.set_size_request(gtk.gdk.screen_width(),
                                gtk.gdk.screen_height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        # Initialize the canvas
        self.abacus = Abacus(canvas, self)

        # Read the current mode from the Journal
        try:
            if self.metadata['abacus'] == 'suanpan':
                self._chinese_cb(None)
            elif self.metadata['abacus'] == 'soroban':
                self._japanese_cb(None)
            elif self.metadata['abacus'] == 'schety':
                self._russian_cb(None)
            elif self.metadata['abacus'] == 'nepohualtzintzin':
                self._mayan_cb(None)
            elif self.metadata['abacus'] == 'binary':
                self._binary_cb(None)
            elif self.metadata['abacus'] == 'hexadecimal':
                self._hex_cb(None)
            elif self.metadata['abacus'] == 'fraction':
                self._fraction_cb(None)
            else:
                self._chinese_cb(None)
        except:
            pass
        try:
            self.abacus.mode.set_value(self.metadata['value'])
            self.abacus.mode.label(self.abacus.mode.value())
        except:
            pass
예제 #33
0
파일: activity.py 프로젝트: rbuj/followme
    def build_calibrate_toolbar(self, toolbox):

        calibrate_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        label1 = gtk.Label()
        label1.set_text(' ' + _('Calibrate/Follow') + ' ')
        item1.add(label1)
        calibrate_bar.insert(item1, -1)

        stop_calibrate = ToolButton('media-playback-stop')
        stop_calibrate.set_tooltip(_('Stop'))
        stop_calibrate.set_accelerator('<ctrl>space')
        stop_calibrate.connect('clicked', self.stop_execute)
        calibrate_bar.insert(stop_calibrate, -1)

        separator1 = gtk.SeparatorToolItem()
        separator1.props.draw = True
        calibrate_bar.insert(separator1, -1)

        item3 = gtk.ToolItem()
        self.label_color_red = gtk.Label()
        self.label_color_red.set_text(' ' + _('Calibrated color:') + ' ' + _('Red') + ' ')
        item3.add(self.label_color_red)
        calibrate_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        self.red_spin = gtk.SpinButton()
        self.red_spin.set_range(0, 255)
        self.red_spin.set_increments(1, 10)
        self.red_spin.props.value = self.colorC[0]
        self.red_spin.connect('notify::value', self.red_spin_color)
        item4.add(self.red_spin)
        calibrate_bar.insert(item4, -1)

        item5 = gtk.ToolItem()
        self.label_color_green = gtk.Label()
        self.label_color_green.set_text(' ' + _('Green') + ' ')
        item5.add(self.label_color_green)
        calibrate_bar.insert(item5, -1)

        item6 = gtk.ToolItem()
        self.green_spin = gtk.SpinButton()
        self.green_spin.set_range(0, 255)
        self.green_spin.set_increments(1, 10)
        self.green_spin.props.value = self.colorC[1]
        self.green_spin.connect('notify::value', self.green_spin_color)
        item6.add(self.green_spin)
        calibrate_bar.insert(item6, -1)

        item7 = gtk.ToolItem()
        self.label_color_blue = gtk.Label()
        self.label_color_blue.set_text(' ' + _('Blue') + ' ')
        item7.add(self.label_color_blue)
        calibrate_bar.insert(item7, -1)

        item8 = gtk.ToolItem()
        self.blue_spin = gtk.SpinButton()
        self.blue_spin.set_range(0, 255)
        self.blue_spin.set_increments(1, 10)
        self.blue_spin.props.value = self.colorC[2]
        self.blue_spin.connect('notify::value', self.blue_spin_color)
        item8.add(self.blue_spin)
        calibrate_bar.insert(item8, -1)

        calibrate_bar.show_all()
        calibrate_button = ToolbarButton(label=_('Calibrate'),
                page=calibrate_bar,
                icon_name='preferences-system')
        toolbox.toolbar.insert(calibrate_button, -1)
        calibrate_button.show()
예제 #34
0
class MeasureActivity(activity.Activity):
    ''' Oscilloscope Sugar activity '''
    def __init__(self, handle):
        ''' Init canvas, toolbars, etc.
        The toolbars are in sensor_toolbar.py and toolbar_side.py
        The audio controls are in audiograb.py
        The rendering happens in drawwaveform.py
        Logging is in journal.py '''

        activity.Activity.__init__(self, handle)

        self.mode_images = {}
        self.mode_images['sound'] = gtk.gdk.pixbuf_new_from_file_at_size(
            os.path.join(ICONS_DIR, 'media-audio.svg'), 45, 45)
        self.mode_images['resistance'] = gtk.gdk.pixbuf_new_from_file_at_size(
            os.path.join(ICONS_DIR, 'resistance.svg'), 45, 45)
        self.mode_images['voltage'] = gtk.gdk.pixbuf_new_from_file_at_size(
            os.path.join(ICONS_DIR, 'voltage.svg'), 45, 45)

        self.icon_colors = self.get_icon_colors_from_sugar()
        self.stroke_color, self.fill_color = self.icon_colors.split(',')
        self.nick = self.get_nick_from_sugar()
        self.CONTEXT = ''
        self.adjustmentf = None  # Freq. slider control

        self.new_recording = False
        self.session_id = 0
        self.read_metadata()

        self._active = True
        self._dsobject = None

        self.connect('notify::active', self._notify_active_cb)
        self.connect('destroy', self.on_quit)

        self.data_logger = DataLogger(self)

        self.hw = _get_hardware()
        log.debug('running on %s hardware' % (self.hw))

        self.wave = DrawWaveform(self)

        if self.hw == XO15:
            self.audiograb = AudioGrab_XO15(self.wave.new_buffer, self)
        elif self.hw == XO175:
            self.audiograb = AudioGrab_XO175(self.wave.new_buffer, self)
        elif self.hw == XO4:
            self.audiograb = AudioGrab_XO4(self.wave.new_buffer, self)
        elif self.hw == XO1:
            self.audiograb = AudioGrab_XO1(self.wave.new_buffer, self)
        else:
            self.audiograb = AudioGrab_Unknown(self.wave.new_buffer, self)

        # no sharing
        self.max_participants = 1

        box3 = gtk.HBox(False, 0)
        box3.pack_start(self.wave, True, True, 0)

        # We need event boxes in order to set the background color.
        side_eventboxes = []
        self.side_toolbars = []
        for i in range(self.audiograb.channels):
            side_eventboxes.append(gtk.EventBox())
            side_eventboxes[i].modify_bg(
                gtk.STATE_NORMAL, style.COLOR_TOOLBAR_GREY.get_gdk_color())
            self.side_toolbars.append(SideToolbar(self, channel=i))
            side_eventboxes[i].add(self.side_toolbars[i].box1)
            box3.pack_start(side_eventboxes[i], False, True, 0)

        event_box = gtk.EventBox()
        self.text_box = gtk.Label()
        self.text_box.set_justify(gtk.JUSTIFY_LEFT)
        alist = pango.AttrList()
        alist.insert(pango.AttrForeground(65535, 65535, 65535, 0, -1))
        self.text_box.set_attributes(alist)
        event_box.add(self.text_box)
        event_box.modify_bg(gtk.STATE_NORMAL,
                            style.COLOR_TOOLBAR_GREY.get_gdk_color())

        box1 = gtk.VBox(False, 0)
        box1.pack_start(box3, True, True, 0)
        box1.pack_start(event_box, False, True, 0)

        self.set_canvas(box1)

        toolbox = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbox.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.sensor_toolbar = SensorToolbar(self, self.audiograb.channels)
        #Added by Lego
        # Turn on bobot Server
        log.debug('Starting Server...')
        self.bobot = subprocess.Popen(['python', 'pybot_server.py'],
                                      cwd='./pybot')
        log.debug("Start : %s" % time.ctime())
        time.sleep(bobot_delay_start)
        log.debug("Started : %s" % time.ctime())
        self.lego_toolbar = LegoToolbar(self, self.audiograb.channels)
        #Lego end
        # Added by Butia
        self.butia_toolbar = ButiaToolbar(self, self.audiograb.channels)
        #Butia end
        #Added by Arduino
        self.arduino_toolbar = ArduinoToolbar(self, self.audiograb.channels)
        #Arduino end
        self.tuning_toolbar = TuningToolbar(self)
        self.new_instrument_toolbar = InstrumentToolbar(self)
        self._extras_toolbar = gtk.Toolbar()
        self.control_toolbar = gtk.Toolbar()

        sensor_button = ToolbarButton(label=_('Sensors'),
                                      page=self.sensor_toolbar,
                                      icon_name='sensor-tools')
        toolbox.toolbar.insert(sensor_button, -1)
        #Added by Lego
        sensor_button.connect('clicked', self._sensor_toolbar_cb)
        #Lego end
        sensor_button.show()
        lego_button = ToolbarButton(label=_('Lego'),
                                    page=self.lego_toolbar,
                                    icon_name='LEGO-tools')
        toolbox.toolbar.insert(lego_button, -1)
        lego_button.connect('clicked', self._lego_toolbar_cb)
        lego_button.show()
        #Lego end
        #Added by Butia
        sensor_button.connect('clicked', self._sensor_toolbar_cb)
        #Butia end
        sensor_button.show()
        #Added by Butia
        butia_button = ToolbarButton(label=_('Butia'),
                                     page=self.butia_toolbar,
                                     icon_name='butia-tools')
        toolbox.toolbar.insert(butia_button, -1)
        butia_button.connect('clicked', self._butia_toolbar_cb)
        butia_button.show()
        #Butia end
        #Added by Arduino
        sensor_button.connect('clicked', self._sensor_toolbar_cb)
        #Arduino end
        sensor_button.show()
        #Added by Arduino
        arduino_button = ToolbarButton(label=_('Arduino'),
                                       page=self.arduino_toolbar,
                                       icon_name='arduino-tools')
        toolbox.toolbar.insert(arduino_button, -1)
        arduino_button.connect('clicked', self._arduino_toolbar_cb)
        arduino_button.show()
        #Arduino end
        tuning_button = ToolbarButton(
            # TRANS: Tuning insruments
            label=_('Tuning'),
            page=self.tuning_toolbar,
            icon_name='tuning-tools')
        toolbox.toolbar.insert(tuning_button, -1)
        tuning_button.show()
        new_instrument_button = ToolbarButton(label=_('Add instrument'),
                                              page=self.new_instrument_toolbar,
                                              icon_name='view-source')
        toolbox.toolbar.insert(new_instrument_button, -1)
        new_instrument_button.show()
        #Added by butia
        self.butia_toolbar.show()
        #Butia end
        self._extras_button = ToolbarButton(page=self._extras_toolbar,
                                            icon_name='domain-time')
        toolbox.toolbar.insert(self._extras_button, -1)
        self._extras_toolbar_item = gtk.ToolItem()
        self._extras_toolbar.insert(self._extras_toolbar_item, -1)
        self._extras_button.hide()
        self.sensor_toolbar.show()

        self._extra_tools = gtk.HBox()

        # Set up Frequency-domain Button
        self.freq = ToolButton('domain-time')
        self.freq.set_tooltip(_('Time Base'))
        self.freq.connect('clicked', self.timefreq_control)
        self.freq.show()
        self._extra_tools.add(self.freq)

        self.sensor_toolbar.add_frequency_slider(self._extra_tools)

        self._extra_item = gtk.ToolItem()
        self._extra_item.add(self._extra_tools)
        self._extra_tools.show()
        toolbox.toolbar.insert(self._extra_item, -1)
        self._extra_item.show()

        self._pause = ToolButton('media-playback-pause')
        self._pause.set_tooltip(_('Freeze the display'))
        self._pause.connect('clicked', self._pause_play_cb)
        self._pause.show()
        toolbox.toolbar.insert(self._pause, -1)

        self._capture = ToolButton('image-saveoff')
        self._capture.set_tooltip(_('Capture sample now'))
        self._capture.connect('clicked', self._capture_cb)
        self._capture.show()
        toolbox.toolbar.insert(self._capture, -1)

        separator = gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbox.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        stop_button.props.accelerator = _('<Ctrl>Q')
        toolbox.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbox(toolbox)
        sensor_button.set_expanded(True)

        toolbox.show()
        self.sensor_toolbar.update_page_size()

        self.show_all()

        self._first = True

        # Always start in 'sound' mode.
        self.sensor_toolbar.set_mode('sound')
        self.sensor_toolbar.set_sound_context()
        self.sensor_toolbar.set_show_hide_windows()
        self.wave.set_active(True)
        self.wave.set_context_on()

        gtk.gdk.screen_get_default().connect('size-changed',
                                             self._configure_cb)
        self._configure_cb(None)

    def _configure_cb(self, event):
        ''' Screen size has changed, so check to see if the toolbar
        elements still fit.'''
        self.width = gtk.gdk.screen_width()
        if self.width < style.GRID_CELL_SIZE * 14:
            self._extras_button.show()
            if self._extra_tools in self._extra_item:
                self._extra_item.remove(self._extra_tools)
            if not self._extra_tools in self._extras_toolbar_item:
                self._extras_toolbar_item.add(self._extra_tools)
            self._extras_toolbar_item.show()
            self.sensor_toolbar.log_label.hide()
            self.sensor_toolbar.trigger_label.hide()
        else:
            self._extras_button.hide()
            if self._extra_tools in self._extras_toolbar_item:
                self._extras_toolbar_item.remove(self._extra_tools)
            if not self._extra_tools in self._extra_item:
                self._extra_item.add(self._extra_tools)
            if self._extras_button.is_expanded():
                self._extras_button.set_expanded(False)
            self._extras_toolbar_item.hide()
            self.sensor_toolbar.log_label.show()
            self.sensor_toolbar.trigger_label.show()
        self._extra_tools.show()

    #Added by Lego
    def _sensor_toolbar_cb(self, button=None):
        '''Callback al hacer clic en sensor toolbar'''
        log.debug('Click en sensor toolbar')
        self.sensor_toolbar.set_mode('sound')
        self.sensor_toolbar.set_sound_context()
        self.sensor_toolbar.set_show_hide_windows()
        self.limpiar_canales()
        self.CONTEXT = 'sound'

    #Added by Lego
    def _lego_toolbar_cb(self, button=None):
        '''Callback al hacer clic en lego toolbar'''
        log.debug('Click en lego toolbar')
        self.audiograb.stop_grabbing()

        self.limpiar_canales()
        log.debug('CONTEXTO ANTERIOR: %s' % self.CONTEXT)
        self.CONTEXT = 'lego'

        self.sensor_toolbar.update_string_for_textbox()

    #Added by Butia
    def _butia_toolbar_cb(self, button=None):
        '''Callback al hacer clic en butia toolbar'''
        log.debug('Click en butia toolbar')
        self.audiograb.stop_grabbing()

        self.limpiar_canales()
        log.debug('CONTEXTO ANTERIOR: %s' % self.CONTEXT)
        self.CONTEXT = 'butia'

        self.sensor_toolbar.update_string_for_textbox()

#Added by Arduino

    def _arduino_toolbar_cb(self, button=None):
        '''Callback al hacer clic en arduino toolbar'''
        log.debug('Click en arduino toolbar')
        self.audiograb.stop_grabbing()

        self.limpiar_canales()
        log.debug('CONTEXTO ANTERIOR: %s' % self.CONTEXT)
        log.debug('***** ARDUINO CONTEXT ******')
        self.CONTEXT = 'arduino'

        self.sensor_toolbar.update_string_for_textbox()

    #Added by lego
    def limpiar_canales(self):
        for i in range(self.audiograb.channels):
            self.wave.ringbuffer[i] = RingBuffer1d(self.wave.max_samples,
                                                   dtype='int16')
            self.wave.new_buffer([0], i)

    def on_quit(self, data=None):
        '''Clean up, close journal on quit'''
        self.audiograb.on_activity_quit()

    def _notify_active_cb(self, widget, pspec):
        ''' Callback to handle starting/pausing capture when active/idle '''
        if self._first:
            log.debug('_notify_active_cb: start grabbing')
            self.audiograb.start_grabbing()
            self._first = False
        elif not self.props.active:
            log.debug('_notify_active_cb: pause grabbing')
            self.audiograb.pause_grabbing()
        elif self.props.active:
            log.debug('_notify_active_cb: resume grabbing')
            self.audiograb.resume_grabbing()

        self._active = self.props.active
        self.wave.set_active(self._active)

    def read_metadata(self):
        ''' Any saved instruments? '''
        for data in self.metadata.keys():
            if data[0] == PREFIX:  # instrument
                log.debug('found an instrument: %s' % (data[1:]))
                instrument = data[1:]
                log.debug(self.metadata[data])
                INSTRUMENT_DICT[instrument] = []
                for note in self.metadata[data].split(' '):
                    INSTRUMENT_DICT[instrument].append(float(note))

    def write_file(self, file_path):
        ''' Write data to journal, if there is any data to write '''
        # Check to see if there are any new instruments to save
        if hasattr(self, 'new_instrument_toolbar'):
            for i, instrument in enumerate(
                    self.new_instrument_toolbar.new_instruments):
                log.debug('saving %s' % (instrument))
                notes = ''
                for i, note in enumerate(INSTRUMENT_DICT[instrument]):
                    notes += '%0.3f' % note
                    if i < len(INSTRUMENT_DICT[instrument]) - 1:
                        notes += ' '
                self.metadata['%s%s' % (PREFIX, instrument)] = notes

        # FIXME: Don't use ""s around data
        if hasattr(self, 'data_logger') and \
                self.new_recording and \
                len(self.data_logger.data_buffer) > 0:
            # Append new data to Journal entry
            fd = open(file_path, 'ab')
            writer = csv.writer(fd)
            # Also output to a separate file as a workaround to Ticket 2127
            # (the assumption being that this file will be opened by the user)
            tmp_data_file = os.path.join(os.environ['SUGAR_ACTIVITY_ROOT'],
                                         'instance', 'sensor_data' + '.csv')
            log.debug('saving sensor data to %s' % (tmp_data_file))
            if self._dsobject is None:  # first time, so create
                fd2 = open(tmp_data_file, 'wb')
            else:  # we've been here before, so append
                fd2 = open(tmp_data_file, 'ab')
            writer2 = csv.writer(fd2)
            # Pop data off start of buffer until it is empty
            for i in range(len(self.data_logger.data_buffer)):
                datum = self.data_logger.data_buffer.pop(0)
                writer.writerow([datum])
                writer2.writerow([datum])
            fd.close()
            fd2.close()

            # Set the proper mimetype
            self.metadata['mime_type'] = 'text/csv'

            if os.path.exists(tmp_data_file):
                if self._dsobject is None:
                    self._dsobject = datastore.create()
                    self._dsobject.metadata['title'] = _('Measure Log')
                    self._dsobject.metadata['icon-color'] = self.icon_colors
                    self._dsobject.metadata['mime_type'] = 'text/csv'
                self._dsobject.set_file_path(tmp_data_file)
                datastore.write(self._dsobject)
                # remove(tmp_data_file)

    def read_file(self, file_path):
        ''' Read csv data from journal on start '''
        reader = csv.reader(open(file_path, "rb"))
        # Count the number of sessions.
        for row in reader:
            if len(row) > 0:
                if row[0].find(_('Session')) != -1:
                    # log.debug('found a previously recorded session')
                    self.session_id += 1
                elif row[0].find('abiword') != -1:
                    # File has been opened by Write cannot be read by Measure
                    # See Ticket 2127
                    log.error('File was opened by Write: Measure cannot read')
                    self.data_logger.data_buffer = []
                    return
                self.data_logger.data_buffer.append(row[0])
        if self.session_id == 0:
            # log.debug('setting data_logger buffer to []')
            self.data_logger.data_buffer = []

    def _pause_play_cb(self, button=None):
        ''' Callback for Pause Button '''
        if self.audiograb.get_freeze_the_display():
            self.audiograb.set_freeze_the_display(False)
            self._pause.set_icon('media-playback-start')
            self._pause.set_tooltip(_('Unfreeze the display'))
            self._pause.show()
        else:
            self.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 _capture_cb(self, button=None):
        ''' Callback for screen capture '''
        if self.CONTEXT == 'butia':
            self.butia_toolbar.take_screenshot()
        self.audiograb.take_screenshot()

    def timefreq_control(self, button=None):
        ''' Callback for Freq. Button '''
        # Turn off logging when switching modes
        if self.audiograb.we_are_logging:
            self.sensor_toolbar.record_control_cb()
            #Added by Lego
            self.lego_toolbar.set_sound_context()
            #Lego end
            #Added by Butia
            self.butia_toolbar.set_sound_context()
            #Butia end
            #Added by Arduino
            self.arduino_toolbar.set_sound_context()
            #Arduino end
        if self.wave.get_fft_mode():
            self.wave.set_fft_mode(False)
            self.freq.set_icon('domain-time')
            self.freq.set_tooltip(_('Time Base'))
        else:
            self.wave.set_fft_mode(True)
            self.freq.set_icon('domain-freq')
            self.freq.set_tooltip(_('Frequency Base'))
            # Turn off triggering in Frequencey Base
            self.sensor_toolbar.trigger_none.set_active(True)
            self.wave.set_trigger(self.wave.TRIGGER_NONE)
            # Turn off invert in Frequencey Base
            for i in range(self.audiograb.channels):
                if self.wave.get_invert_state(channel=i):
                    self.side_toolbars[i].invert_control_cb()
        self.sensor_toolbar.update_string_for_textbox()
        return False

    def get_icon_colors_from_sugar(self):
        ''' Returns the icon colors from the Sugar profile '''
        return profile.get_color().to_string()

    def get_nick_from_sugar(self):
        ''' Returns nick from Sugar '''
        return profile.get_nick_name()
예제 #35
0
    def _setup_toolbars(self):
        ''' Setup the toolbars. '''

        self.max_participants = 6

        if HAVE_TOOLBOX:
            toolbox = ToolbarBox()

            # Activity toolbar
            activity_button_toolbar = ActivityToolbarButton(self)

            toolbox.toolbar.insert(activity_button_toolbar, 0)
            activity_button_toolbar.show()

            self.set_toolbar_box(toolbox)
            toolbox.show()
            self.toolbar = toolbox.toolbar

            self.record_toolbar = gtk.Toolbar()
            record_toolbar_button = ToolbarButton(
                label=_('Record a sound'),
                page=self.record_toolbar,
                icon_name='media-audio')
            self.record_toolbar.show_all()
            record_toolbar_button.show()
            toolbox.toolbar.insert(record_toolbar_button, -1)
        else:
            # Use pre-0.86 toolbar design
            primary_toolbar = gtk.Toolbar()
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)
            toolbox.add_toolbar(_('Page'), primary_toolbar)
            self.record_toolbar = gtk.Toolbar()
            toolbox.add_toolbar(_('Record'), self.record_toolbar)
            toolbox.show()
            toolbox.set_current_toolbar(1)
            self.toolbar = primary_toolbar

        self._prev_button = button_factory(
            'go-previous-inactive', self.toolbar, self._prev_cb,
            tooltip=_('Prev slide'), accelerator='<Ctrl>P')

        self._next_button = button_factory(
            'go-next', self.toolbar, self._next_cb,
            tooltip=_('Next slide'), accelerator='<Ctrl>N')


        separator_factory(self.toolbar)

        slide_button = radio_factory('slide-view', self.toolbar,
                                     self._slides_cb, group=None,
                                     tooltip=_('Slide view'))
        radio_factory('thumbs-view', self.toolbar, self._thumbs_cb,
                      tooltip=_('Thumbnail view'),
                      group=slide_button)

        button_factory('view-fullscreen', self.toolbar,
                       self.do_fullscreen_cb, tooltip=_('Fullscreen'),
                       accelerator='<Alt>Return')

        separator_factory(self.toolbar)

        journal_button = button_factory(
            'write-journal', self.toolbar, self._do_journal_cb,
            tooltip=_('Update description'))
        self._palette = journal_button.get_palette()
        msg_box = gtk.HBox()

        sw = gtk.ScrolledWindow()
        sw.set_size_request(int(gtk.gdk.screen_width() / 2),
                            2 * style.GRID_CELL_SIZE)
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self._text_view = gtk.TextView()
        self._text_view.set_left_margin(style.DEFAULT_PADDING)
        self._text_view.set_right_margin(style.DEFAULT_PADDING)
        self._text_view.set_wrap_mode(gtk.WRAP_WORD_CHAR)
        self._text_view.connect('focus-out-event',
                               self._text_view_focus_out_event_cb)
        sw.add(self._text_view)
        sw.show()
        msg_box.pack_start(sw, expand=False)
        msg_box.show_all()

        self._palette.set_content(msg_box)

        label_factory(self.record_toolbar, _('Record a sound') + ':')
        self._record_button = button_factory(
            'media-record', self.record_toolbar,
            self._record_cb, tooltip=_('Start recording'))

        separator_factory(self.record_toolbar)

        # Look to see if we have audio previously recorded
        obj_id = self._get_audio_obj_id()
        dsobject = self._search_for_audio_note(obj_id)
        if dsobject is not None:
            _logger.debug('Found previously recorded audio')
            self._add_playback_button(profile.get_nick_name(),
                                      self.colors,
                                      dsobject.file_path)

        if HAVE_TOOLBOX:
            button_factory('system-restart', activity_button_toolbar,
                           self._resend_cb, tooltip=_('Refresh'))
            separator_factory(activity_button_toolbar)
            self._save_pdf = button_factory(
                'save-as-pdf', activity_button_toolbar,
                self._save_as_pdf_cb, tooltip=_('Save as PDF'))
        else:
            separator_factory(self.toolbar)
            self._save_pdf = button_factory(
                'save-as-pdf', self.toolbar,
                self._save_as_pdf_cb, tooltip=_('Save as PDF'))

        if HAVE_TOOLBOX:
            separator_factory(toolbox.toolbar, True, False)

            stop_button = StopButton(self)
            stop_button.props.accelerator = '<Ctrl>q'
            toolbox.toolbar.insert(stop_button, -1)
            stop_button.show()
예제 #36
0
    def build_options_toolbar(self, toolbox):

        options_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        label1 = gtk.Label()
        label1.set_text(' ' + _('Pixels') + ' ')
        item1.add(label1)
        options_bar.insert(item1, -1)

        item2 = gtk.ToolItem()
        pixels = gtk.SpinButton()
        pixels.set_range(0, 1000)
        pixels.set_increments(1, 10)
        pixels.props.value = self.pixels
        pixels.connect('notify::value', self.pixels_value)
        item2.add(pixels)
        options_bar.insert(item2, -1)

        separator1 = gtk.SeparatorToolItem()
        separator1.props.draw = True
        options_bar.insert(separator1, -1)

        item3 = gtk.ToolItem()
        self.label_threshold_red = gtk.Label()
        self.label_threshold_red.set_text(' ' + _('Threshold:') + ' ' +
                                          _('Red') + ' ')
        item3.add(self.label_threshold_red)
        options_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        red_spin = gtk.SpinButton()
        red_spin.set_range(0, 255)
        red_spin.set_increments(1, 10)
        red_spin.props.value = self.threshold[0]
        red_spin.connect('notify::value', self.red_spin_threshold)
        item4.add(red_spin)
        options_bar.insert(item4, -1)

        item5 = gtk.ToolItem()
        self.label_threshold_green = gtk.Label()
        self.label_threshold_green.set_text(' ' + _('Green') + ' ')
        item5.add(self.label_threshold_green)
        options_bar.insert(item5, -1)

        item6 = gtk.ToolItem()
        green_spin = gtk.SpinButton()
        green_spin.set_range(0, 255)
        green_spin.set_increments(1, 10)
        green_spin.props.value = self.threshold[1]
        green_spin.connect('notify::value', self.green_spin_threshold)
        item6.add(green_spin)
        options_bar.insert(item6, -1)

        item7 = gtk.ToolItem()
        self.label_threshold_blue = gtk.Label()
        self.label_threshold_blue.set_text(' ' + _('Blue') + ' ')
        item7.add(self.label_threshold_blue)
        options_bar.insert(item7, -1)

        item8 = gtk.ToolItem()
        blue_spin = gtk.SpinButton()
        blue_spin.set_range(0, 255)
        blue_spin.set_increments(1, 10)
        blue_spin.props.value = self.threshold[2]
        blue_spin.connect('notify::value', self.blue_spin_threshold)
        item8.add(blue_spin)
        options_bar.insert(item8, -1)

        options_bar.show_all()
        options_button = ToolbarButton(label=_('Options'),
                                       page=options_bar,
                                       icon_name='view-source')
        toolbox.toolbar.insert(options_button, -1)
        options_button.show()
예제 #37
0
import gtk

from sugar.graphics.toolbutton import ToolButton
from sugar.graphics.toolbarbox import ToolbarBox, ToolbarButton
from sugar.graphics import style

window = gtk.Window()

box = gtk.VBox()
window.add(box)

toolbar = ToolbarBox()
box.pack_start(toolbar, False)

tollbarbutton_1 = ToolbarButton(
        page=gtk.Button('sub-widget #1'),
        icon_name='computer-xo')
toolbar.toolbar.insert(tollbarbutton_1, -1)

tollbarbutton_2 = ToolbarButton(
        page=gtk.Button('sub-widget #2'),
        icon_name='button_cancel',
        tooltip='with custom palette instead of sub-widget')
toolbar.toolbar.insert(tollbarbutton_2, -1)

toolbar.toolbar.insert(gtk.SeparatorToolItem(), -1)


def del_cb(widget):
    toolbar.toolbar.remove(tollbarbutton_3)
del_b = gtk.Button('delete sub-widget #3')
예제 #38
0
    def build_calibrate_toolbar(self, toolbox):

        calibrate_bar = gtk.Toolbar()

        item1 = gtk.ToolItem()
        label1 = gtk.Label()
        label1.set_text(' ' + _('Calibrate/Follow') + ' ')
        item1.add(label1)
        calibrate_bar.insert(item1, -1)

        stop_calibrate = ToolButton('media-playback-stop')
        stop_calibrate.set_tooltip(_('Stop'))
        stop_calibrate.set_accelerator('<ctrl>space')
        stop_calibrate.connect('clicked', self.stop_execute)
        calibrate_bar.insert(stop_calibrate, -1)

        separator1 = gtk.SeparatorToolItem()
        separator1.props.draw = True
        calibrate_bar.insert(separator1, -1)

        item3 = gtk.ToolItem()
        self.label_color_red = gtk.Label()
        self.label_color_red.set_text(' ' + _('Calibrated color:') + ' ' +
                                      _('Red') + ' ')
        item3.add(self.label_color_red)
        calibrate_bar.insert(item3, -1)

        item4 = gtk.ToolItem()
        self.red_spin = gtk.SpinButton()
        self.red_spin.set_range(0, 255)
        self.red_spin.set_increments(1, 10)
        self.red_spin.props.value = self.colorC[0]
        self.red_spin.connect('notify::value', self.red_spin_color)
        item4.add(self.red_spin)
        calibrate_bar.insert(item4, -1)

        item5 = gtk.ToolItem()
        self.label_color_green = gtk.Label()
        self.label_color_green.set_text(' ' + _('Green') + ' ')
        item5.add(self.label_color_green)
        calibrate_bar.insert(item5, -1)

        item6 = gtk.ToolItem()
        self.green_spin = gtk.SpinButton()
        self.green_spin.set_range(0, 255)
        self.green_spin.set_increments(1, 10)
        self.green_spin.props.value = self.colorC[1]
        self.green_spin.connect('notify::value', self.green_spin_color)
        item6.add(self.green_spin)
        calibrate_bar.insert(item6, -1)

        item7 = gtk.ToolItem()
        self.label_color_blue = gtk.Label()
        self.label_color_blue.set_text(' ' + _('Blue') + ' ')
        item7.add(self.label_color_blue)
        calibrate_bar.insert(item7, -1)

        item8 = gtk.ToolItem()
        self.blue_spin = gtk.SpinButton()
        self.blue_spin.set_range(0, 255)
        self.blue_spin.set_increments(1, 10)
        self.blue_spin.props.value = self.colorC[2]
        self.blue_spin.connect('notify::value', self.blue_spin_color)
        item8.add(self.blue_spin)
        calibrate_bar.insert(item8, -1)

        calibrate_bar.show_all()
        calibrate_button = ToolbarButton(label=_('Calibrate'),
                                         page=calibrate_bar,
                                         icon_name='preferences-system')
        toolbox.toolbar.insert(calibrate_button, -1)
        calibrate_button.show()
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        try:
            # Use new >= 0.86 toolbar design
            self.max_participants = 1
            toolbar_box = ToolbarBox()
            activity_button = ActivityToolbarButton(self)
            toolbar_box.toolbar.insert(activity_button, 0)

            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            activity_button.props.page.insert(separator, -1)
            separator.show()

            tool = ToolButton('pdf-export')
            tool.set_tooltip(_('Portable Document Format (PDF)'))
            tool.connect('clicked', self.__export_pdf_cb)
            activity_button.props.page.insert(tool, -1)
            tool.show()

            tool = ToolButton('png-export')
            tool.set_tooltip(_('Portable Network Graphic (PNG)'))
            tool.connect('clicked', self.__export_png_cb)
            activity_button.props.page.insert(tool, -1)
            tool.show()

            self.edit_toolbar = ToolbarButton()
            self.edit_toolbar.props.page = EditToolbar(self)
            self.edit_toolbar.props.icon_name = 'toolbar-edit'
            self.edit_toolbar.props.label = _('Edit'),
            toolbar_box.toolbar.insert(self.edit_toolbar, -1)

            self._undo = UndoManager.UndoManager(
                self, self.edit_toolbar.props.page.undo.child,
                self.edit_toolbar.props.page.redo.child)

            self.__build_main_canvas_area()

            tool = ToolbarButton()
            tool.props.page = ViewToolbar(self._main_area)
            tool.props.icon_name = 'toolbar-view'
            tool.props.label = _('View'),
            toolbar_box.toolbar.insert(tool, -1)

            separator = gtk.SeparatorToolItem()
            toolbar_box.toolbar.insert(separator, -1)

            separator = gtk.SeparatorToolItem()
            separator.props.draw = False
            separator.set_expand(True)
            separator.show()
            toolbar_box.toolbar.insert(separator, -1)

            target_toolbar = toolbar_box.toolbar
            tool_offset = 4

            tool = StopButton(self)
            toolbar_box.toolbar.insert(tool, -1)

            toolbar_box.show_all()
            self.set_toolbar_box(toolbar_box)

        except NameError:
            # Use old <= 0.84 toolbar design
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)

            activity_toolbar = toolbox.get_activity_toolbar()
            keep_palette = activity_toolbar.keep.get_palette()

            menu_item = MenuItem(_('Portable Document Format (PDF)'))
            menu_item.connect('activate', self.__export_pdf_cb)
            keep_palette.menu.append(menu_item)
            menu_item.show()

            menu_item = MenuItem(_('Portable Network Graphic (PNG)'))
            menu_item.connect('activate', self.__export_png_cb)
            keep_palette.menu.append(menu_item)
            menu_item.show()

            self.edit_toolbar = EditToolbar(self)
            toolbox.add_toolbar(_('Edit'), self.edit_toolbar)
            separator = gtk.SeparatorToolItem()
            self.edit_toolbar.insert(separator, 0)
            self.edit_toolbar.show()

            target_toolbar = self.edit_toolbar
            tool_offset = 0

            self._undo = UndoManager.UndoManager(self,
                                                 self.edit_toolbar.undo.child,
                                                 self.edit_toolbar.redo.child)

            self.__build_main_canvas_area()

            view_toolbar = ViewToolbar(self._main_area)
            toolbox.add_toolbar(_('View'), view_toolbar)

            activity_toolbar = toolbox.get_activity_toolbar()
            activity_toolbar.share.props.visible = False
            toolbox.set_current_toolbar(1)

        self.mods = [None] * 6

        self.mods[0] = RadioToolButton(named_icon='select-mode')
        self.mods[0].set_tooltip(_('Edit mode'))
        self.mods[0].set_accelerator(_('<ctrl>e'))
        self.mods[0].set_group(None)
        self.mods[0].connect('clicked', self.__mode_cb, MMapArea.MODE_NULL)
        target_toolbar.insert(self.mods[0], tool_offset)

        self.mods[1] = RadioToolButton(named_icon='text-mode')
        self.mods[1].set_tooltip(_('Text mode'))
        self.mods[1].set_accelerator(_('<ctrl>t'))
        self.mods[1].set_group(self.mods[0])
        self.mods[1].connect('clicked', self.__mode_cb, MMapArea.MODE_TEXT)
        target_toolbar.insert(self.mods[1], tool_offset + 1)

        self.mods[2] = RadioToolButton(named_icon='draw-mode')
        self.mods[2].set_group(self.mods[0])
        self.mods[2].set_tooltip(_('Drawing mode'))
        self.mods[2].set_accelerator(_('<ctrl>d'))
        self.mods[2].connect('clicked', self.__mode_cb, MMapArea.MODE_DRAW)
        target_toolbar.insert(self.mods[2], tool_offset + 2)

        self.mods[3] = RadioToolButton(named_icon='image-mode')
        self.mods[3].set_group(self.mods[0])
        self.mods[3].set_tooltip(_('Image add mode'))
        self.mods[3].set_accelerator(_('<ctrl>i'))
        self.mods[3].connect('clicked', self.__mode_cb, MMapArea.MODE_IMAGE)
        target_toolbar.insert(self.mods[3], tool_offset + 3)

        self.mods[5] = RadioToolButton(named_icon='label-mode')
        self.mods[5].set_tooltip(_('Label mode'))
        self.mods[5].set_accelerator(_('<ctrl>a'))
        self.mods[5].set_group(self.mods[0])
        self.mods[5].connect('clicked', self.__mode_cb, MMapArea.MODE_LABEL)
        target_toolbar.insert(self.mods[5], tool_offset + 4)

        separator = gtk.SeparatorToolItem()
        target_toolbar.insert(separator, tool_offset + 5)

        tool = ToolButton('link')
        tool.set_tooltip(_('Link/unlink two selected thoughts'))
        tool.set_accelerator(_('<ctrl>l'))
        tool.connect('clicked', self.__link_cb)
        target_toolbar.insert(tool, tool_offset + 6)

        tool = ToolButton('edit-delete')
        tool.set_tooltip(_('Erase selected thought(s)'))
        tool.connect('clicked', self.__delete_cb)
        target_toolbar.insert(tool, tool_offset + 7)

        self.show_all()
        self._mode = MMapArea.MODE_TEXT
        self._main_area.set_mode(self._mode)
        self.mods[MMapArea.MODE_TEXT].set_active(True)
        self.set_focus_child(self._main_area)
    def __init__ (self, handle):
        if os.path.exists('/tmp/1'):
            os.remove('/tmp/1')
            activity.Activity.__init__ (self, handle)

            # abiword uses the current directory for all its file dialogs
            os.chdir(os.path.expanduser('~'))

            # create our main abiword canvas
            self.abiword_canvas = Canvas()

            self.set_canvas(self.abiword_canvas)
            self.abiword_canvas.connect_after('map-event', self.__map_event_cb)
            self.abiword_canvas.show()


        if os.path.exists('/tmp/2'):
            os.remove('/tmp/2')
            toolbar_box = ToolbarBox()

            activity_button = ActivityToolbarButton(self)

            separator = gtk.SeparatorToolItem()
            separator.show()
            activity_button.props.page.insert(separator, 2)
            export_button = ExportButton(self, self.abiword_canvas)
            export_button.show()
            activity_button.props.page.insert(export_button, 2)
            toolbar_box.toolbar.insert(activity_button, 0)

            edit_toolbar = ToolbarButton()
            edit_toolbar.props.page = EditToolbar(self, toolbar_box)
            edit_toolbar.props.icon_name = 'toolbar-edit'
            edit_toolbar.props.label = _('Edit')
            toolbar_box.toolbar.insert(edit_toolbar, -1)

            view_toolbar = ToolbarButton()
            view_toolbar.props.page = ViewToolbar(self.abiword_canvas)
            view_toolbar.props.icon_name = 'toolbar-view'
            view_toolbar.props.label = _('View')
            toolbar_box.toolbar.insert(view_toolbar, -1)

            separator = gtk.SeparatorToolItem()
            toolbar_box.toolbar.insert(separator, -1)
            toolbar_box.show_all()
            self.set_toolbar_box(toolbar_box)

        if os.path.exists('/tmp/3'):
            os.remove('/tmp/3')    

            text_toolbar = ToolbarButton()
            text_toolbar.props.page = TextToolbar(self.abiword_canvas)
            text_toolbar.props.icon_name = 'format-text'
            text_toolbar.props.label = _('Text')
            toolbar_box.toolbar.insert(text_toolbar, -1)    

            para_toolbar = ToolbarButton()
            para_toolbar.props.page = ParagraphToolbar(self.abiword_canvas)
            para_toolbar.props.icon_name = 'paragraph-bar'
            para_toolbar.props.label = _('Paragraph')
            toolbar_box.toolbar.insert(para_toolbar, -1)

            list_toolbar = ToolbarButton()
            list_toolbar.props.page = ListToolbar(self.abiword_canvas)
            list_toolbar.props.icon_name = 'toolbar-bulletlist'
            list_toolbar.props.label = _('Bullet List')
            toolbar_box.toolbar.insert(list_toolbar, -1)
        
            insert_toolbar = ToolbarButton()
            insert_toolbar.props.page = InsertToolbar(self.abiword_canvas)
            insert_toolbar.props.icon_name = 'insert-table'
            insert_toolbar.props.label = _('Table')
            toolbar_box.toolbar.insert(insert_toolbar, -1)

            separator = gtk.SeparatorToolItem()
            toolbar_box.toolbar.insert(separator, -1)

            bold = ToggleToolButton('format-text-bold')
            bold.set_tooltip(_('Bold'))
            bold_id = bold.connect('clicked', lambda sender:
                    self.abiword_canvas.toggle_bold())
            self.abiword_canvas.connect('bold', lambda abi, b:
                    self._setToggleButtonState(bold, b, bold_id))
            toolbar_box.toolbar.insert(bold, -1)

            italic = ToggleToolButton('format-text-italic')
            italic.set_tooltip(_('Italic'))
            italic_id = italic.connect('clicked', lambda sender:
                    self.abiword_canvas.toggle_italic())
            self.abiword_canvas.connect('italic', lambda abi, b:
                    self._setToggleButtonState(italic, b, italic_id))
            toolbar_box.toolbar.insert(italic, -1)

            underline = ToggleToolButton('format-text-underline')
            underline.set_tooltip(_('Underline'))
            underline_id = underline.connect('clicked', lambda sender:
                    self.abiword_canvas.toggle_underline())
            self.abiword_canvas.connect('underline', lambda abi, b:
                    self._setToggleButtonState(underline, b, underline_id))
            toolbar_box.toolbar.insert(underline, -1)

            separator = gtk.SeparatorToolItem()
            toolbar_box.toolbar.insert(separator, -1)

            color = ColorToolButton()
            color.connect('color-set', self._text_color_cb, self.abiword_canvas)
            tool_item = gtk.ToolItem()
            tool_item.add(color)
            toolbar_box.toolbar.insert(tool_item, -1)
            self.abiword_canvas.connect('color', lambda abi, r, g, b:
                    color.set_color(gtk.gdk.Color(r * 256, g * 256, b * 256)))

            separator = gtk.SeparatorToolItem()
            separator.props.draw = False
            separator.set_expand(True)
            separator.show()
            toolbar_box.toolbar.insert(separator, -1)

            stop = StopButton(self)
            toolbar_box.toolbar.insert(stop, -1)

            toolbar_box.show_all()
            self.set_toolbar_box(toolbar_box)


            self._zoom_handler = self.abiword_canvas.connect("zoom", self.__zoom_cb)
예제 #41
0
    def initialize_display(self):
        self._logger = logging.getLogger('butialo-activity')

        # Top toolbar with share and close buttons:

        if OLD_TOOLBAR:
            activity_toolbar = self.toolbox.get_activity_toolbar()
        else:
            activity_toolbar = self.activity_button.page

        # add 'make bundle' entry to 'keep' palette.
        palette = activity_toolbar.keep.get_palette()
        # XXX: should clear out old palette entries?
        from sugar.graphics.menuitem import MenuItem
        from sugar.graphics.icon import Icon
        menu_item = MenuItem(_('As Butialo Document'))
        menu_item.set_image(Icon(file=('%s/activity/activity-icon.svg' %
                                       get_bundle_path()),
                                 icon_size=gtk.ICON_SIZE_MENU))
        menu_item.connect('activate', self.keepbutton_cb)
        palette.menu.append(menu_item)
        menu_item.show()
        #xop guardar como bundle
        #menu_item = MenuItem(_('As Activity Bundle'))
        #menu_item.set_image(Icon(file=('%s/activity/activity-default.svg' %
        #                               get_bundle_path()),
        #                         icon_size=gtk.ICON_SIZE_MENU))
        #menu_item.connect('activate', self.makebutton_cb)
        #palette.menu.append(menu_item)
        #menu_item.show()

        self._edit_toolbar = activity.EditToolbar()

        if OLD_TOOLBAR:
            activity_toolbar = gtk.Toolbar()
            self.toolbox.add_toolbar(_('Actions'), activity_toolbar)
            self.toolbox.set_current_toolbar(1)
            self.toolbox.add_toolbar(_('Edit'), self._edit_toolbar)
        else:
            edit_toolbar_button = ToolbarButton()
            edit_toolbar_button.set_page(self._edit_toolbar)
            edit_toolbar_button.props.icon_name = 'toolbar-edit'
            edit_toolbar_button.props.label = _('Edit')
            self.get_toolbar_box().toolbar.insert(edit_toolbar_button, -1)

        self._edit_toolbar.show()

        self._edit_toolbar.undo.connect('clicked', self.__undobutton_cb)
        self._edit_toolbar.redo.connect('clicked', self.__redobutton_cb)
        self._edit_toolbar.copy.connect('clicked', self.__copybutton_cb)
        self._edit_toolbar.paste.connect('clicked', self.__pastebutton_cb)

        if OLD_TOOLBAR:
            actions_toolbar = activity_toolbar
        else:
            actions_toolbar = self.get_toolbar_box().toolbar

        # The "go" button
        goicon_bw = gtk.Image()
        goicon_bw.set_from_file("%s/icons/run_bw.svg" % os.getcwd())
        goicon_color = gtk.Image()
        goicon_color.set_from_file("%s/icons/run_color.svg" % os.getcwd())
        gobutton = ToolButton(label=_("_Run!"))
        gobutton.props.accelerator = _('<alt>r')
        gobutton.set_icon_widget(goicon_bw)
        gobutton.set_tooltip("Run")
        gobutton.connect('clicked', self.flash_cb, dict({'bw': goicon_bw,
            'color': goicon_color}))
        gobutton.connect('clicked', self.gobutton_cb)
        actions_toolbar.insert(gobutton, -1)

        # The "stop" button
        stopicon_bw = gtk.Image()
        stopicon_bw.set_from_file("%s/icons/stopit_bw.svg" % os.getcwd())
        stopicon_color = gtk.Image()
        stopicon_color.set_from_file("%s/icons/stopit_color.svg" % os.getcwd())
        stopbutton = ToolButton(label=_("_Stop"))
        stopbutton.props.accelerator = _('<alt>s')
        stopbutton.set_icon_widget(stopicon_bw)
        stopbutton.connect('clicked', self.flash_cb, dict({'bw': stopicon_bw,
            'color': stopicon_color}))
        stopbutton.connect('clicked', self.stopbutton_cb)
        stopbutton.set_tooltip("Stop Running")
        actions_toolbar.insert(stopbutton, -1)

        # The "refresh" button
        refreshicon_bw = gtk.Image()
        refreshicon_bw.set_from_file("%s/icons/butiaoff.svg" % os.getcwd())
        refreshicon_color = gtk.Image()
        refreshicon_color.set_from_file("%s/icons/butiaon.svg" % os.getcwd())
        refreshbutton = ToolButton(label=_("_Reload"))
        refreshbutton.props.accelerator = _('<alt>d')
        refreshbutton.set_icon_widget(refreshicon_bw)
        refreshbutton.connect('clicked', self.flash_cb, dict({'bw': refreshicon_bw,
            'color': refreshicon_color}))
        refreshbutton.connect('clicked', self.initialize_snippets_cb)
        refreshbutton.set_tooltip("Reload devices")
        actions_toolbar.insert(refreshbutton, -1)

        # The "clear" button
        #clearicon_bw = gtk.Image()
        #clearicon_bw.set_from_file("%s/icons/eraser_bw.svg" % os.getcwd())
        #clearicon_color = gtk.Image()
        #clearicon_color.set_from_file("%s/icons/eraser_color.svg" %
        #                              os.getcwd())
        #clearbutton = ToolButton(label=_("_Clear"))
        #clearbutton.props.accelerator = _('<alt>c')
        #clearbutton.set_icon_widget(clearicon_bw)
        #clearbutton.connect('clicked', self.clearbutton_cb)
        #clearbutton.connect('clicked', self.flash_cb, dict({'bw': clearicon_bw,
        #    'color': clearicon_color}))
        #clearbutton.set_tooltip("Clear")
        #actions_toolbar.insert(clearbutton, -1)

        # The "beautify" button
        beautifyicon_bw = gtk.Image()
        beautifyicon_bw.set_from_file("%s/icons/beautifyicon_bw.svg" % os.getcwd())
        beautifyicon_color = gtk.Image()
        beautifyicon_color.set_from_file("%s/icons/beautifyicon_color.svg" %
                                      os.getcwd())
        beautifybutton = ToolButton(label=_("_Auto-format"))
        beautifybutton.props.accelerator = _('<alt>f')
        beautifybutton.set_icon_widget(beautifyicon_bw)
        beautifybutton.connect('clicked', self.beautifybutton_cb)
        beautifybutton.connect('clicked', self.flash_cb, dict({'bw': beautifyicon_bw,
            'color': beautifyicon_color}))
        beautifybutton.set_tooltip("Auto-format")
        actions_toolbar.insert(beautifybutton, -1)

        activity_toolbar.show()

        if not OLD_TOOLBAR:
            separator = gtk.SeparatorToolItem()
            separator.props.draw = False
            separator.set_expand(True)
            self.get_toolbar_box().toolbar.insert(separator, -1)
            separator.show()

            stop = StopButton(self)
            self.get_toolbar_box().toolbar.insert(stop, -1)

        # Main layout.
        self.hpane = gtk.HPaned()
        self.vpane = gtk.VPaned()

        # The sidebar.
        self.sidebar = gtk.VBox()
        self.model = gtk.TreeStore(gobject.TYPE_PYOBJECT, gobject.TYPE_STRING)
        treeview = gtk.TreeView(self.model)
        cellrenderer = gtk.CellRendererText()
        treecolumn = gtk.TreeViewColumn(_("Available"), cellrenderer, text=1)
        treeview.get_selection().connect("changed", self.selection_cb)
        treeview.append_column(treecolumn)
        treeview.set_size_request(int(SIZE_X * 0.3), SIZE_Y)

        # Create scrollbars around the view.
        scrolled = gtk.ScrolledWindow()
        scrolled.add(treeview)
        self.sidebar.pack_start(scrolled)
        self.hpane.add1(self.sidebar)

        #root = os.path.join(get_bundle_path(), 'data')

        #initialize snippets 
        self.initialize_snippets_cb(None)

        # Source buffer
        import gtksourceview2
        global text_buffer
        lang_manager = gtksourceview2.language_manager_get_default()
        if hasattr(lang_manager, 'list_languages'):
            langs = lang_manager.list_languages()
        else:
            lang_ids = lang_manager.get_language_ids()
            langs = [lang_manager.get_language(lang_id)
                     for lang_id in lang_ids]
        for lang in langs:
            for m in lang.get_mime_types():
                if m == "text/x-lua":
                    text_buffer.set_language(lang)

        if hasattr(text_buffer, 'set_highlight'):
            text_buffer.set_highlight(True)
        else:
            text_buffer.set_highlight_syntax(True)

        # The GTK source view window
        self.text_view = gtksourceview2.View(text_buffer)
        self.text_view.set_size_request(0, int(SIZE_Y * 0.5))
        self.text_view.set_editable(True)
        self.text_view.set_cursor_visible(True)
        self.text_view.set_show_line_numbers(True)
        self.text_view.set_wrap_mode(gtk.WRAP_CHAR)
        self.text_view.set_insert_spaces_instead_of_tabs(True)
        self.text_view.set_tab_width(2)
        self.text_view.set_auto_indent(True)
        self.text_view.modify_font(pango.FontDescription("Monospace " +
            str(font_zoom(style.FONT_SIZE))))

        # We could change the color theme here, if we want to.
        #mgr = gtksourceview2.style_manager_get_default()
        #style_scheme = mgr.get_scheme('kate')
        #self.text_buffer.set_style_scheme(style_scheme)

        codesw = gtk.ScrolledWindow()
        codesw.set_policy(gtk.POLICY_AUTOMATIC,
                      gtk.POLICY_AUTOMATIC)
        codesw.add(self.text_view)
        self.vpane.add1(codesw)

        # An hbox to hold the vte window and its scrollbar.
        outbox = gtk.HBox()

        # The vte python window
        self._vte = vte.Terminal()
        self._vte.set_encoding('utf-8')
        self._vte.set_size(30, 5)
        font = 'Monospace ' + str(font_zoom(style.FONT_SIZE))
        self._vte.set_font(pango.FontDescription(font))
        self._vte.set_colors(gtk.gdk.color_parse('#000000'),
                             gtk.gdk.color_parse('#E7E7E7'),
                             [])
        self._vte.connect('child_exited', self.child_exited_cb)
        self._child_exited_handler = None
        self._vte.drag_dest_set(gtk.DEST_DEFAULT_ALL,
                                [("text/plain", 0, TARGET_TYPE_TEXT)],
                                gtk.gdk.ACTION_COPY)
        self._vte.connect('drag_data_received', self.vte_drop_cb)
        outbox.pack_start(self._vte)

        outsb = gtk.VScrollbar(self._vte.get_adjustment())
        outsb.show()
        outbox.pack_start(outsb, False, False, 0)
        self.vpane.add2(outbox)
        self.hpane.add2(self.vpane)
        return self.hpane