Пример #1
0
class ChartActivity(activity.Activity):

    def __init__(self, handle):

        activity.Activity.__init__(self, handle, True)

        self.max_participants = 1

        # CHART_OPTIONS

        self._font_option = TITLE_FONT
        self.x_label = ''
        self.y_label = ''
        self.chart_color = utils.get_user_fill_color('str')
        self.chart_line_color = utils.get_user_stroke_color('str')
        self.current_chart = None
        self.charts_area = None
        self.chart_data = []
        self.chart_type_buttons = []
        self._font_options = {
            'titleColor': '#000000',
            'titleFont': 'Sans',
            'titleFontSize': 12,
            'axis': {
                'tickFont': 'Sans',
                'tickFontSize': 12,
                'tickColor': '#000000',
                'labelFontSize': 14,
                'labelColor': '#666666',
                'labelFont': 'Sans',
                'lineColor': '#b3b3b3'}}

        # TOOLBARS
        self._labels_font = RadioToolButton()
        self._title_font = RadioToolButton()

        toolbarbox = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        activity_btn_toolbar = activity_button.page

        activity_btn_toolbar.title.connect('changed', self._set_chart_title)

        save_as_image = ToolButton('save-as-image')
        save_as_image.connect('clicked', self._save_as_image)
        save_as_image.set_tooltip(_('Save as image'))
        activity_btn_toolbar.insert(save_as_image, -1)

        save_as_image.show()

        import_stopwatch = ToolButton('import-stopwatch')
        import_stopwatch.connect('clicked', self.__import_stopwatch_cb)
        import_stopwatch.set_tooltip(_('Read StopWatch data'))
        activity_btn_toolbar.insert(import_stopwatch, -1)

        import_stopwatch.show()

        import_measure = ToolButton('import-measure')
        import_measure.set_tooltip(_('Read Measure data'))

        if utils.get_channels() == 1:
            import_measure.connect('clicked', self.__import_measure_cb, 1)

        else:
            import_measure.connect('clicked', self._measure_btn_clicked)
            self._create_measure_palette(import_measure)

        activity_btn_toolbar.insert(import_measure, -1)
        import_measure.show()

        toolbarbox.toolbar.insert(activity_button, 0)

        add_v = ToolButton('gtk-add')
        add_v.connect('clicked', self._add_value)
        add_v.set_tooltip(_('Add a value'))

        toolbarbox.toolbar.insert(add_v, -1)

        remove_v = ToolButton('gtk-remove')
        remove_v.connect('clicked', self._remove_value)
        remove_v.set_tooltip(_('Remove the selected value'))

        toolbarbox.toolbar.insert(remove_v, -1)

        self._remove_v = remove_v

        separator = Gtk.SeparatorToolItem()
        separator.set_draw(True)
        separator.set_expand(False)
        toolbarbox.toolbar.insert(separator, -1)

        # We create two sets: one for the main toolbar and one for the
        # chart toolbar. We choose which set to use based on the
        # screen width.
        self._create_chart_buttons(toolbarbox.toolbar)

        self._chart_button = ToolbarButton(icon_name='vbar')
        chart_toolbar = Gtk.Toolbar()
        self._create_chart_buttons(chart_toolbar)
        self._chart_button.props.page = chart_toolbar
        chart_toolbar.show_all()
        toolbarbox.toolbar.insert(self._chart_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.set_draw(True)
        separator.set_expand(False)
        toolbarbox.toolbar.insert(separator, -1)

        self._options_button = ToolbarButton(icon_name='preferences-system')
        options_toolbar = Gtk.Toolbar()

        self.chart_color_btn = ColorToolButton()
        self.chart_color_btn.set_color(_COLOR1)
        self.chart_color_btn.set_title(_('Chart Color'))
        options_toolbar.insert(self.chart_color_btn, -1)
        GObject.timeout_add(1000,
                            self._connect_color_btn,
                            self.chart_color_btn,
                            self._set_chart_color)

        self.line_color_btn = ColorToolButton()
        self.line_color_btn.set_color(_COLOR2)
        self.line_color_btn.set_title(_('Line Color'))
        options_toolbar.insert(self.line_color_btn, -1)
        GObject.timeout_add(1000,
                            self._connect_color_btn,
                            self.line_color_btn,
                            self._set_chart_line_color)

        separator = Gtk.SeparatorToolItem()
        separator.set_draw(True)
        separator.set_expand(False)
        options_toolbar.insert(separator, -1)

        h_label_icon = Icon(icon_name='hlabel')
        h_label_tool_item = Gtk.ToolItem()
        h_label_tool_item.add(h_label_icon)
        options_toolbar.insert(h_label_tool_item, -1)

        self.h_label = Entry(_('Horizontal label...'))
        self.h_label.entry.connect('changed', self._set_h_label)
        options_toolbar.insert(self.h_label, -1)

        separator = Gtk.SeparatorToolItem()
        separator.set_draw(False)
        separator.set_expand(False)
        options_toolbar.insert(separator, -1)

        v_label_icon = Icon(icon_name='vlabel')
        v_label_tool_item = Gtk.ToolItem()
        v_label_tool_item.add(v_label_icon)
        options_toolbar.insert(v_label_tool_item, -1)

        self.v_label = Entry(_('Vertical label...'))
        self.v_label.entry.connect('changed', self._set_v_label)
        options_toolbar.insert(self.v_label, -1)

        self._options_button.props.page = options_toolbar
        options_toolbar.show_all()

        toolbarbox.toolbar.insert(self._options_button, -1)

        text_toolbar_btn = ToolbarButton()
        text_toolbar_btn.props.icon_name = 'format-text'
        text_toolbar_btn.props.label = _('Text')
        toolbarbox.toolbar.insert(text_toolbar_btn, -1)
        self._text_options_btn = text_toolbar_btn

        texttoolbar = Gtk.Toolbar()

        self.font_name_combo = FontComboBox()
        self.font_name_combo.set_font_name('Sans')

        def set_font_name(w):
            self._set_chart_font_options(font=w.get_font_name())

        self.font_name_combo.connect("changed", set_font_name)
        texttoolbar.insert(ToolComboBox(self.font_name_combo), -1)

        self.font_size = FontSize()

        def set_font_size(w):
            self._set_chart_font_options(size=w.get_font_size())

        self.font_size.connect("changed", set_font_size)
        texttoolbar.insert(self.font_size, -1)

        self.text_color_btn = ColorToolButton()
        self.text_color_btn.set_color(style.COLOR_BLACK.get_gdk_color())
        self.text_color_btn.set_title(_('Font Color'))
        texttoolbar.insert(self.text_color_btn, -1)
        GObject.timeout_add(1000, self._connect_color_btn,
                            self.text_color_btn,
                            self._set_text_color)

        # self._title_font created in the top of the file
        self._title_font.connect('clicked', self._set_font_option,
                                 TITLE_FONT)
        self._title_font.set_tooltip(_('Title font'))
        self._title_font.props.icon_name = 'title-font'
        op_group = self._title_font

        texttoolbar.insert(self._title_font, 0)

        # self._labels_font created in the top of the file
        self._labels_font.connect('clicked', self._set_font_option,
                                  LABELS_FONT)
        self._labels_font.set_tooltip(_('Labels font'))
        self._labels_font.props.icon_name = 'labels-font'
        self._labels_font.props.group = op_group
        texttoolbar.insert(self._labels_font, 1)

        tick_font = RadioToolButton()
        tick_font.connect('clicked', self._set_font_option, TICK_FONT)
        tick_font.set_tooltip(_('Tick font'))
        tick_font.props.icon_name = 'tick-font'
        tick_font.props.group = op_group
        texttoolbar.insert(tick_font, 2)

        separator = Gtk.SeparatorToolItem()
        texttoolbar.insert(separator, 3)

        text_toolbar_btn.props.page = texttoolbar
        texttoolbar.show_all()

        separator = Gtk.SeparatorToolItem()
        separator.set_draw(True)
        separator.set_expand(False)
        toolbarbox.toolbar.insert(separator, -1)

        self._fullscreen_button = ToolButton('view-fullscreen')
        self._fullscreen_button.set_tooltip(_("Fullscreen"))
        self._fullscreen_button.props.accelerator = '<Alt>Return'
        self._fullscreen_button.connect('clicked', self.__fullscreen_cb)
        toolbarbox.toolbar.insert(self._fullscreen_button, -1)

        charthelp.create_help(toolbarbox.toolbar)

        separator = Gtk.SeparatorToolItem()
        separator.set_draw(False)
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        stopbtn = StopButton(self)
        toolbarbox.toolbar.insert(stopbtn, -1)

        self.set_toolbar_box(toolbarbox)

        # CANVAS
        paned = Gtk.HPaned()
        box = Gtk.VBox()
        self.box = box

        # Set the info box width to 1/3 of the screen:
        def size_allocate_cb(widget, allocation):
            paned.disconnect(self._setup_handle)
            box_width = allocation.width / 3
            box.set_size_request(box_width, -1)

        self._setup_handle = paned.connect('size_allocate',
                                           size_allocate_cb)

        scroll = Gtk.ScrolledWindow()
        scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        self.labels_and_values = ChartData(self)
        scroll.add(self.labels_and_values)

        self.labels_and_values.connect('label-changed', self._label_changed)
        self.labels_and_values.connect('value-changed', self._value_changed)

        box.pack_start(scroll, True, True, 0)

        liststore_toolbar = Gtk.Toolbar()

        move_up = ToolButton('go-up')
        move_up.set_tooltip(_('Move up'))
        move_up.connect('clicked', self._move_up)

        move_down = ToolButton('go-down')
        move_down.set_tooltip(_('Move down'))
        move_down.connect('clicked', self._move_down)

        liststore_toolbar.insert(move_up, 0)
        liststore_toolbar.insert(move_down, 1)

        box.pack_end(liststore_toolbar, False, False, 0)

        paned.add1(box)

        # CHARTS AREA
        eventbox = Gtk.EventBox()
        self.charts_area = ChartArea(self)

        eventbox.modify_bg(Gtk.StateType.NORMAL, _WHITE)
        eventbox.add(self.charts_area)

        self._notebook = Gtk.Notebook()
        self._notebook.set_property('show-tabs', False)
        self._notebook.append_page(eventbox, Gtk.Label())

        # EMPTY WIDGETS
        empty_widgets = Gtk.EventBox()
        empty_widgets.modify_bg(Gtk.StateType.NORMAL,
                                style.COLOR_WHITE.get_gdk_color())

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        mvbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        vbox.pack_start(mvbox, True, False, 0)

        image_icon = Icon(pixel_size=style.LARGE_ICON_SIZE,
                          icon_name='chart',
                          stroke_color=style.COLOR_BUTTON_GREY.get_svg(),
                          fill_color=style.COLOR_TRANSPARENT.get_svg())
        mvbox.pack_start(image_icon, False, False, style.DEFAULT_PADDING)

        label = Gtk.Label('<span foreground="%s"><b>%s</b></span>' %
                          (style.COLOR_BUTTON_GREY.get_html(),
                           _('No data')))
        label.set_use_markup(True)
        mvbox.pack_start(label, False, False, style.DEFAULT_PADDING)

        hbox = Gtk.Box()
        open_image_btn = Gtk.Button()
        open_image_btn.connect('clicked', self._add_value)
        add_image = Gtk.Image.new_from_stock(Gtk.STOCK_ADD,
                                             Gtk.IconSize.BUTTON)
        buttonbox = Gtk.Box()
        buttonbox.pack_start(add_image, False, True, 0)
        buttonbox.pack_end(Gtk.Label(_('Add a value')), True, True, 5)
        open_image_btn.add(buttonbox)
        hbox.pack_start(open_image_btn, True, False, 0)
        mvbox.pack_start(hbox, False, False, style.DEFAULT_PADDING)

        empty_widgets.add(vbox)
        empty_widgets.show_all()
        self._notebook.append_page(empty_widgets, Gtk.Label())

        paned.add2(self._notebook)

        self.set_canvas(paned)
        self.charts_area.connect('size_allocate', self._chart_size_allocate)

        self.show_all()

        Gdk.Screen.get_default().connect('size-changed', self._configure_cb)
        self._configure_cb()

    def _set_text_color(self, *args):
        color = utils.rgb2html(args[-1].get_color())
        self._set_chart_font_options(color=color)

    def _set_chart_font_options(self, font=None, size=None, color=None):
        op = self._font_options
        if self._font_option == TITLE_FONT:
            op['titleFont'] = font or op['titleFont']
            op['titleFontSize'] = size or op['titleFontSize']
            op['titleColor'] = color or op['titleColor']

        elif self._font_option == LABELS_FONT:
            op['axis']['labelFont'] = font or op['axis']['labelFont']
            op['axis']['labelFontSize'] = size or op['axis']['labelFontSize']
            op['axis']['labelColor'] = color or op['axis']['labelColor']

        elif self._font_option == TICK_FONT:
            op['axis']['tickFont'] = font or op['axis']['tickFont']
            op['axis']['tickFontSize'] = size or op['axis']['tickFontSize']
            op['axis']['tickColor'] = color or op['axis']['tickColor']

        self._font_options = op
        self._render_chart()

    def _get_chart_font_options(self, option):
        chart_options = self._font_options
        if option == TITLE_FONT:
            font = chart_options['titleFont']
            size = chart_options['titleFontSize']
            color = chart_options['titleColor']

        elif option == LABELS_FONT:
            font = chart_options['axis']['labelFont']
            size = chart_options['axis']['labelFontSize']
            color = chart_options['axis']['labelColor']

        elif option == TICK_FONT:
            font = chart_options['axis']['tickFont']
            size = chart_options['axis']['tickFontSize']
            color = chart_options['axis']['tickColor']

        else:
            return None, None, None
        return font, size, color

    def _set_font_option(self, *args):
        if not hasattr(self, 'font_name_combo'):
            return

        self._font_option = args[-1]

        font, size, color = self._get_chart_font_options(self._font_option)

        self.font_name_combo.set_font_name(font)
        self.font_size.set_font_size(size)
        self.text_color_btn.set_color(Color(color).get_gdk_color())

    def _create_chart_buttons(self, toolbar):
        add_vbar_chart = RadioToolButton()
        add_vbar_chart.connect('clicked', self._add_chart_cb,
                               charts.VERTICAL_BAR)
        add_vbar_chart.set_tooltip(_('Vertical Bar Chart'))
        add_vbar_chart.props.icon_name = 'vbar'
        charts_group = add_vbar_chart

        toolbar.insert(add_vbar_chart, -1)

        add_hbar_chart = RadioToolButton()
        add_hbar_chart.connect('clicked', self._add_chart_cb,
                               charts.HORIZONTAL_BAR)
        add_hbar_chart.set_tooltip(_('Horizontal Bar Chart'))
        add_hbar_chart.props.icon_name = 'hbar'
        add_hbar_chart.props.group = charts_group
        toolbar.insert(add_hbar_chart, -1)

        add_line_chart = RadioToolButton()
        add_line_chart.connect('clicked', self._add_chart_cb, charts.LINE)
        add_line_chart.set_tooltip(_('Line Chart'))
        add_line_chart.props.icon_name = 'line'
        add_line_chart.props.group = charts_group
        toolbar.insert(add_line_chart, -1)

        add_pie_chart = RadioToolButton()
        add_pie_chart.set_active(True)
        add_pie_chart.connect('clicked', self._add_chart_cb, charts.PIE)
        add_pie_chart.set_tooltip(_('Pie Chart'))
        add_pie_chart.props.icon_name = 'pie'
        add_pie_chart.props.group = charts_group
        toolbar.insert(add_pie_chart, -1)

        self.chart_type_buttons.append(add_vbar_chart)
        self.chart_type_buttons.append(add_hbar_chart)
        self.chart_type_buttons.append(add_line_chart)
        self.chart_type_buttons.append(add_pie_chart)

    def _show_empty_widgets(self):
        if hasattr(self, '_notebook'):
            self._notebook.set_current_page(1)
            self._remove_v.set_sensitive(False)

            for btn in self.chart_type_buttons:
                btn.set_sensitive(False)

            self._options_button.set_sensitive(False)
            self._text_options_btn.set_sensitive(False)
            self._fullscreen_button.set_sensitive(False)

    def _show_chart_area(self):
        if self._notebook.get_current_page() == 1:
            self._notebook.set_current_page(0)
            self._remove_v.set_sensitive(True)

            for btn in self.chart_type_buttons:
                btn.set_sensitive(True)

            self._options_button.set_sensitive(True)
            self._text_options_btn.set_sensitive(True)
            self._fullscreen_button.set_sensitive(True)

    def _create_measure_palette(self, button):
        palette = button.get_palette()
        hbox = Gtk.HBox()

        channel1 = ToolButton('measure-channel-1')
        channel1.connect('clicked', self.__import_measure_cb, 1)

        channel2 = ToolButton('measure-channel-2')
        channel2.connect('clicked', self.__import_measure_cb, 2)

        hbox.pack_start(channel1, False, True, 0)
        hbox.pack_end(channel2, False, True, 0)

        hbox.show_all()

        palette.set_content(hbox)

    def _measure_btn_clicked(self, button):
        palette = button.get_palette()
        palette.popup(immediate=True, state=1)

    def _add_value(self, widget, label='', value='0.0'):
        if label == '':
            label = str(len(self.chart_data) + 1)

        is_number = True
        try:
            float(value)
        except ValueError:
            _logger.debug('data (%s) not a number' % (str(value)))
            is_number = False

        if is_number:
            data = (label, float(value))
            if data not in self.chart_data:
                pos = self.labels_and_values.add_value(label, value)
                self.chart_data.insert(pos, data)
                self._update_chart_data()

        elif not is_number:
            _invalid_number_alert(activity)

    def _remove_value(self, widget):
        value = self.labels_and_values.remove_selected_value()
        self.chart_data.remove(value)
        self._update_chart_data()

    def _add_chart_cb(self, widget, type=charts.VERTICAL_BAR):
        self.current_chart = charts.Chart(type)

        def update_btn():
            if (type == charts.PIE and
                    not self.chart_type_buttons[3].get_active() and
                    not self.chart_type_buttons[7].get_active()):
                self.chart_type_buttons[3].set_active(True)
                self.chart_type_buttons[7].set_active(True)

        GObject.idle_add(update_btn)

        self.update_chart()

    def _configure_cb(self, event=None):
        # If we have room, put buttons on the main toolbar
        if Gdk.Screen.width() / 14 > style.GRID_CELL_SIZE:
            self._chart_button.set_expanded(False)
            self._chart_button.hide()
            for i in range(4):
                self.chart_type_buttons[i].show()
                self.chart_type_buttons[i + 4].hide()
        else:
            self._chart_button.show()
            self._chart_button.set_expanded(True)
            for i in range(4):
                self.chart_type_buttons[i].hide()
                self.chart_type_buttons[i + 4].show()

    def _chart_size_allocate(self, widget, allocation):
            self._render_chart()

    def unfullscreen(self):
        self.box.show()
        activity.Activity.unfullscreen(self)
        GObject.idle_add(self._render_chart)

    def __fullscreen_cb(self, button):
        self.box.hide()
        self._render_chart(fullscreen=True)
        activity.Activity.fullscreen(self)

    def _render_chart(self, fullscreen=False):
        if not self.chart_data:
            self._show_empty_widgets()
            return

        if self.current_chart is None or self.charts_area is None:
            return

        try:
            # Resize the chart for all the screen sizes
            alloc = self.get_allocation()

            if fullscreen:
                new_width = alloc.width
                new_height = alloc.height
                self.current_chart.width = alloc.width
                self.current_chart.height = alloc.height
            if not fullscreen:
                alloc = self.charts_area.get_allocation()
                new_width = alloc.width - 40
                new_height = alloc.height - 40
            self.current_chart.width = new_width
            self.current_chart.height = new_height

            # Set options
            self.current_chart.set_color_scheme(color=self.chart_color)
            self.current_chart.set_line_color(self.chart_line_color)
            self.current_chart.set_font_options(self._font_options)

            if self.current_chart.type == charts.PIE:
                self.current_chart.render(self)
            else:
                self.current_chart.render()
            self.charts_area.queue_draw()

        except (ZeroDivisionError, ValueError):
            pass

        self._show_chart_area()
        return False

    def _update_chart_active_button(self, type=None):
        if self.current_chart is None and type is None:
            return

        _type = type or self.current_chart.type

        if _type == charts.VERTICAL_BAR:
            self.chart_type_buttons[0].set_active(True)
            self.chart_type_buttons[4].set_active(True)

        elif _type == charts.HORIZONTAL_BAR:
            self.chart_type_buttons[1].set_active(True)
            self.chart_type_buttons[5].set_active(True)

        elif _type == charts.LINE:
            self.chart_type_buttons[2].set_active(True)
            self.chart_type_buttons[6].set_active(True)

        elif _type == charts.PIE:
            self.chart_type_buttons[3].set_active(True)
            self.chart_type_buttons[7].set_active(True)
            self._labels_font.set_sensitive(False)

    def _update_chart_data(self):
        if self.current_chart is None:
            return
        self.current_chart.data_set(self.chart_data)
        self._update_chart_labels()

    def _set_chart_title(self, widget):
        self._update_chart_labels(title=widget.get_text())

    def _update_chart_labels(self, title=''):
        if self.current_chart is None:
            return

        if not title and self.metadata['title']:
            title = self.metadata['title']

        self.current_chart.set_title(title)
        self.current_chart.set_x_label(self.x_label)
        self.current_chart.set_y_label(self.y_label)
        self._render_chart()

    def update_chart(self):
        if self.current_chart:
            self.current_chart.data_set(self.chart_data)
            self.current_chart.set_title(self.metadata['title'])
            self.current_chart.set_x_label(self.x_label)
            self.current_chart.set_y_label(self.y_label)
            self._set_font_option(self._font_option)
            self._render_chart()

    def _label_changed(self, treeview, path, new_label):
        path = int(path)
        self.chart_data[path] = (new_label, self.chart_data[path][1])
        self._update_chart_data()

    def _value_changed(self, treeview, path, new_value):
        path = int(path)
        self.chart_data[path] = (self.chart_data[path][0], float(new_value))
        self._update_chart_data()

    def _move_up(self, widget):
        old, new = self.labels_and_values.move_up()
        _object = self.chart_data[old]
        self.chart_data.remove(_object)
        self.chart_data.insert(new, _object)
        self._update_chart_data()

    def _move_down(self, widget):
        old, new = self.labels_and_values.move_down()
        if old is not None:
            _object = self.chart_data[old]
            self.chart_data.remove(_object)
            self.chart_data.insert(new, _object)
            self._update_chart_data()

    def _set_h_label(self, widget):
        self.x_label = widget.get_text()
        self._update_chart_labels()

    def _set_v_label(self, widget):
        self.y_label = widget.get_text()
        self._update_chart_labels()

    def _set_chart_color(self, *args):
        self.chart_color = utils.rgb2html(args[-1].get_color())
        self._render_chart()

    def _set_chart_line_color(self, *args):
        self.chart_line_color = utils.rgb2html(args[-1].get_color())
        self._render_chart()

    def _connect_color_btn(self, colorbtn, function):
        if colorbtn._palette is None:
            return True

        for scale in colorbtn._palette._scales:
            scale.connect('button-release-event', function, colorbtn)

        for button in colorbtn._palette._swatch_tray.get_children():
            button.connect('clicked', function, colorbtn)

        return False

    def _object_chooser(self, mime_type, type_name):
        chooser = ObjectChooser()
        matches_mime_type = False

        response = chooser.run()
        if response == Gtk.ResponseType.ACCEPT:
            jobject = chooser.get_selected_object()
            metadata = jobject.metadata
            file_path = jobject.file_path

            if metadata['mime_type'] == mime_type:
                matches_mime_type = True

            else:
                alert = Alert()

                alert.props.title = _('Invalid object')
                alert.props.msg = \
                    _('The selected object must be a %s file' % (type_name))

                ok_icon = Icon(icon_name='dialog-ok')
                alert.add_button(Gtk.ResponseType.OK, _('Ok'), ok_icon)
                ok_icon.show()

                alert.connect('response', lambda a, r: self.remove_alert(a))

                self.add_alert(alert)

                alert.show()

        return matches_mime_type, file_path, metadata['title']

    def _graph_from_reader(self, reader):
        self.labels_and_values.model.clear()
        self.chart_data = []

        chart_data = reader.get_chart_data()

        horizontal, vertical = reader.get_labels_name()

        self.v_label.entry.set_text(horizontal)
        self.h_label.entry.set_text(vertical)

        # Load the data
        for row in chart_data:
            self._add_value(None,
                            label=row[0], value=float(row[1]))

            self.update_chart()

    def __import_stopwatch_cb(self, widget):
        matches_mime_type, file_path, title = \
            self._object_chooser(_STOPWATCH_MIME_TYPE, _('StopWatch'))

        if matches_mime_type:
            f = open(file_path)
            reader = StopWatchReader(f)
            self._graph_from_reader(reader)

            f.close()

    def __import_measure_cb(self, widget, channel=1):
        matches_mime_type, file_path, title = \
            self._object_chooser(_CSV_MIME_TYPE, _('Measure'))

        if matches_mime_type:
            f = open(file_path)
            reader = MeasureReader(f, channel)
            self._graph_from_reader(reader)

            f.close()

    def _save_as_image(self, widget):
        if self.current_chart:
            jobject = datastore.create()

            jobject.metadata['title'] = self.metadata['title']
            jobject.metadata['mime_type'] = 'image/png'

            self.current_chart.as_png(_CHART_FILE)
            jobject.set_file_path(_CHART_FILE)

            datastore.write(jobject)

    def load_from_file(self, f):
        try:
            data = json.load(f)
        finally:
            f.close()

        self.metadata['title'] = data['title']
        self.x_label = data['x_label']
        self.y_label = data['y_label']
        self.chart_color = data['chart_color']
        self.chart_line_color = data['chart_line_color']
        self.current_chart.type = data['current_chart.type']

        # Make it compatible with old Chart instances
        if 'font_options' in data:
            self._font_options = data['font_options']

        chart_data = data['chart_data']

        # Update charts buttons
        self._update_chart_active_button()

        # Update the controls in the config subtoolbar
        self.chart_color_btn.set_color(Color(self.chart_color).get_gdk_color())
        self.line_color_btn.set_color(Color(self.chart_line_color).
                                      get_gdk_color())

        # If the saved label is not '', set the text entry with the saved label
        if self.x_label != '':
            self.h_label.entry.set_text(self.x_label)

        if self.y_label != '':
            self.v_label.entry.set_text(self.y_label)

        # load the data
        for row in chart_data:
            self._add_value(None, label=row[0], value=float(row[1]))

        self.update_chart()

    def write_file(self, file_path):
        self.metadata['mime_type'] = 'application/x-chart-activity'
        if self.current_chart:

            data = {}
            data['title'] = self.metadata['title']
            data['x_label'] = self.x_label
            data['y_label'] = self.y_label
            data['chart_color'] = self.chart_color
            data['chart_line_color'] = self.chart_line_color
            data['current_chart.type'] = self.current_chart.type
            data['chart_data'] = self.chart_data
            data['font_options'] = self._font_options

            f = open(file_path, 'w')
            try:
                json.dump(data, f)
            finally:
                f.close()

    def read_file(self, file_path):
        f = open(file_path, 'r')
        GObject.idle_add(self.load_from_file, f)
Пример #2
0
    def __init__(self, main_area):

        Gtk.Toolbar.__init__(self)

        self._main_area = main_area
        self._font_list = ['ABC123', 'Sans', 'Serif', 'Monospace', 'Symbol']
        self._font_sizes = [
            '8', '9', '10', '11', '12', '14', '16', '20', '22', '24', '26',
            '28', '36', '48', '72'
        ]

        self.font_button = ToolButton('font-text')
        self.font_button.set_tooltip(_('Select font'))
        self.font_button.connect('clicked', self.__font_selection_cb)
        self.insert(self.font_button, -1)
        self._setup_font_palette()

        self.insert(Gtk.SeparatorToolItem(), -1)

        self.font_size_up = ToolButton('resize+')
        self.font_size_up.set_tooltip(_('Bigger'))
        self.font_size_up.connect('clicked', self.__font_sizes_cb, True)
        self.insert(self.font_size_up, -1)

        if len(self._main_area.selected) > 0:
            font_size = self._main_area.font_size

        else:
            font_size = utils.default_font_size

        self.size_label = Gtk.Label(str(font_size))
        self.size_label.show()
        toolitem = Gtk.ToolItem()
        toolitem.add(self.size_label)
        toolitem.show()
        self.insert(toolitem, -1)

        self.font_size_down = ToolButton('resize-')
        self.font_size_down.set_tooltip(_('Smaller'))
        self.font_size_down.connect('clicked', self.__font_sizes_cb, False)
        self.insert(self.font_size_down, -1)

        self.insert(Gtk.SeparatorToolItem(), -1)

        self.bold = ToolButton('bold-text')
        self.bold.set_tooltip(_('Bold'))
        self.bold.connect('clicked', self.__bold_cb)
        self.insert(self.bold, -1)

        self.italics = ToolButton('italics-text')
        self.italics.set_tooltip(_('Italics'))
        self.italics.connect('clicked', self.__italics_cb)
        self.insert(self.italics, -1)

        self.underline = ToolButton('underline-text')
        self.underline.set_tooltip(_('Underline'))
        self.underline.connect('clicked', self.__underline_cb)
        self.insert(self.underline, -1)

        foreground_color = ColorToolButton()
        foreground_color.set_title(_('Set font color'))
        foreground_color.connect('color-set', self.__foreground_color_cb)
        self.insert(foreground_color, -1)

        bakground_color = ColorToolButton()
        bakground_color.set_title(_('Set background color'))
        bakground_color.connect('color-set', self.__background_color_cb)
        bakground_color.set_color(Gdk.Color(65535, 65535, 65535))
        self.insert(bakground_color, -1)

        self.show_all()
    def __init__(self, main_area):

        Gtk.Toolbar.__init__(self)

        self._main_area = main_area
        self._font_list = ['ABC123', 'Sans', 'Serif', 'Monospace', 'Symbol']
        self._font_sizes = ['8', '9', '10', '11', '12', '14', '16', '20',
                            '22', '24', '26', '28', '36', '48', '72']

        self.font_button =  ToolButton('font-text')
        self.font_button.set_tooltip(_('Select font'))
        self.font_button.connect('clicked', self.__font_selection_cb)
        self.insert(self.font_button, -1)
        self._setup_font_palette()

        self.insert(Gtk.SeparatorToolItem(), -1)

        self.font_size_up = ToolButton('resize+')
        self.font_size_up.set_tooltip(_('Bigger'))
        self.font_size_up.connect('clicked', self.__font_sizes_cb, True)
        self.insert(self.font_size_up, -1)

        if len(self._main_area.selected) > 0:
            font_size = self._main_area.font_size

        else:
            font_size = utils.default_font_size

        self.size_label = Gtk.Label(str(font_size))
        self.size_label.show()
        toolitem = Gtk.ToolItem()
        toolitem.add(self.size_label)
        toolitem.show()
        self.insert(toolitem, -1)

        self.font_size_down = ToolButton('resize-')
        self.font_size_down.set_tooltip(_('Smaller'))
        self.font_size_down.connect('clicked', self.__font_sizes_cb, False)
        self.insert(self.font_size_down, -1)

        self.insert(Gtk.SeparatorToolItem(), -1)

        self.bold = ToolButton('bold-text')
        self.bold.set_tooltip(_('Bold'))
        self.bold.connect('clicked', self.__bold_cb)
        self.insert(self.bold, -1)

        self.italics = ToolButton('italics-text')
        self.italics.set_tooltip(_('Italics'))
        self.italics.connect('clicked', self.__italics_cb)
        self.insert(self.italics, -1)

        self.underline = ToolButton('underline-text')
        self.underline.set_tooltip(_('Underline'))
        self.underline.connect('clicked', self.__underline_cb)
        self.insert(self.underline, -1)

        foreground_color = ColorToolButton()
        foreground_color.set_title(_('Set font color'))
        foreground_color.connect('color-set', self.__foreground_color_cb)
        self.insert(foreground_color, -1)

        bakground_color = ColorToolButton()
        bakground_color.set_title(_('Set background color'))
        bakground_color.connect('color-set', self.__background_color_cb)
        bakground_color.set_color(Gdk.Color(65535, 65535, 65535))
        self.insert(bakground_color, -1)

        self.show_all()
Пример #4
0
    def make_toolbar(self):
        def make_separator(expand=False, size=0):
            separator = Gtk.SeparatorToolItem()
            separator.set_size_request(size, -1)
            if expand:
                separator.set_expand(True)

            if expand or size:
                separator.props.draw = False

            return separator

        self.color_palettes = []

        toolbar_box = ToolbarBox()
        toolbar = toolbar_box.toolbar

        activity_button = ToolButton()
        activity_button.set_icon_widget(ActivityIcon(None))
        toolbar.insert(activity_button, -1)

        toolbar.insert(make_separator(size=30), -1)

        button_copy = ToolButton(Gtk.STOCK_COPY)
        button_copy.set_tooltip('Copy the text.')
        button_copy.connect('clicked', self.copy_text)
        toolbar.insert(button_copy, -1)

        button_cut = ToolButton('cut')
        button_cut.set_tooltip('Cut the text.')
        button_cut.connect('clicked', self.cut_text)
        toolbar.insert(button_cut, -1)

        button_remove = ToolButton(Gtk.STOCK_REMOVE)
        button_remove.set_tooltip('Remove all the text.')
        button_remove.connect('clicked', self.remove_text)
        toolbar.insert(button_remove, -1)

        toolbar.insert(make_separator(size=30), -1)

        button_normal = ColorToolButton()
        button_normal.set_color(G.cairo_to_gdk(self.area.normal_color))
        button_normal.set_title('Choose a color for the buttons.')
        button_normal.connect('color-set', self._normal_color_changed)
        toolbar.insert(button_normal, -1)

        self.color_palettes.append(button_normal)

        button_selected = ColorToolButton()
        button = button_selected.get_child()
        button_selected.set_color(G.cairo_to_gdk(self.area.selected_color))
        button_selected.set_title('Choose a color for the selected buttons.')
        button_selected.connect('color-set', self._selected_color_changed)
        toolbar.insert(button_selected, -1)

        self.color_palettes.append(button_selected)

        button_labels = ColorToolButton()
        button_labels.set_color(G.cairo_to_gdk(self.area.label_color))
        button_labels.set_title('Choose a color for the labels buttons.')
        button_labels.connect('color-set', self._label_color_changed)
        toolbar.insert(button_labels, -1)

        self.color_palettes.append(button_labels)

        button_background = ColorToolButton()
        button_background.set_color(G.cairo_to_gdk(self.area.background_color))
        button_background.set_title('Choose a color for the background.')
        button_background.connect('color-set', self._background_color_changed)
        toolbar.insert(button_background, -1)

        self.color_palettes.append(button_background)
        toolbar.insert(make_separator(expand=True), -1)

        stop_button = ToolButton('activity-stop')
        stop_button.connect('clicked', lambda w: self.close())
        stop_button.props.accelerator = '<Ctrl>Q'
        toolbar.insert(stop_button, -1)

        self.set_toolbar_box(toolbar_box)
Пример #5
0
class TerminalActivity(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        # HACK to avoid Escape key disable fullscreen mode on Terminal Activity
        # This is related with http://bugs.sugarlabs.org/ticket/440
        self.disconnect_by_func(self._Window__key_press_cb)
        self.connect('key-press-event', self.__key_press_cb)
        self.vt = None
        self.max_participants = 1
        self._theme_colors = {
            "light": {
                'fg_color': '#000000',
                'bg_color': '#FFFFFF'
            },
            "dark": {
                'fg_color': '#FFFFFF',
                'bg_color': '#000000'
            },
            "custom": {
                'fg_color': '#000000',
                'bg_color': '#FFFFFF'
            }
        }
        self._theme_state = "light"

        self._font_size = FONT_SIZE
        self.build_notebook()
        self.build_toolbar()

    def build_notebook(self):
        self._notebook = BrowserNotebook()
        self._notebook.connect("tab-added", self.__open_tab_cb)
        self._notebook.set_property("tab-pos", Gtk.PositionType.TOP)
        self._notebook.set_scrollable(True)
        self._notebook.show()
        self.set_canvas(self._notebook)
        self._create_tab(None)

    def build_toolbar(self):
        toolbar_box = ToolbarBox()

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

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

        view_toolbar = self._create_view_toolbar()
        view_toolbar_button = ToolbarButton(page=view_toolbar,
                                            icon_name='toolbar-view')
        view_toolbar.show()
        toolbar_box.toolbar.insert(view_toolbar_button, -1)
        view_toolbar_button.show()

        self._delete_tab_toolbar = None
        self._previous_tab_toolbar = None
        self._next_tab_toolbar = None

        helpbutton = self._create_help_button()
        toolbar_box.toolbar.insert(helpbutton, -1)
        helpbutton.show_all()

        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()

    def fullscreen(self):
        self._notebook.set_show_tabs(False)
        activity.Activity.fullscreen(self)

    def unfullscreen(self):
        self._notebook.set_show_tabs(True)
        activity.Activity.unfullscreen(self)

    def _create_edit_toolbar(self):
        edit_toolbar = EditToolbar()
        edit_toolbar.undo.props.visible = False
        edit_toolbar.redo.props.visible = False
        edit_toolbar.separator.props.visible = False
        edit_toolbar.copy.connect('clicked', self.__copy_cb)
        edit_toolbar.copy.props.accelerator = '<Ctrl><Shift>C'
        edit_toolbar.paste.connect('clicked', self.__paste_cb)
        edit_toolbar.paste.props.accelerator = '<Ctrl><Shift>V'

        clear = ToolButton('edit-clear')
        clear.set_tooltip(_('Clear scrollback'))
        clear.connect('clicked', self.__clear_cb)
        edit_toolbar.insert(clear, -1)
        clear.show()
        return edit_toolbar

    def __copy_cb(self, button):
        vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
        if vt.get_has_selection():
            vt.copy_clipboard()

    def __paste_cb(self, button):
        vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
        vt.paste_clipboard()

    def __bg_color_notify_cb(self, button, pspec):
        color = button.get_color()
        self._theme_state = 'custom'
        self._theme_colors['custom']['bg_color'] = get_svg_color_string(color)
        self._update_theme()

    def __fg_color_notify_cb(self, button, pspec):
        color = button.get_color()
        self._theme_state = 'custom'
        self._theme_colors['custom']['fg_color'] = get_svg_color_string(color)
        self._update_theme()

    def _update_custom_theme(self, fg_color, bg_color):
        self._theme_colors['custom']['fg_color'] = fg_color
        self._theme_colors['custom']['bg_color'] = bg_color

    def _toggled_theme(self, button):
        previous_theme = self._theme_colors[self._theme_state]
        if self._theme_state == "dark":
            self._theme_state = "light"
        elif self._theme_state == "light":
            self._theme_state = "dark"
        else:
            self._theme_state = "light"
        self._update_custom_theme(previous_theme['fg_color'],
                                  previous_theme['bg_color'])
        self._update_theme()

    def _update_theme(self):
        if self._theme_state == "light":
            self._theme_toggler.set_icon_name('dark-theme')
            self._theme_toggler.set_tooltip('Switch to Dark Theme')
        elif self._theme_state == "dark":
            self._theme_toggler.set_icon_name('light-theme')
            self._theme_toggler.set_tooltip('Switch to Light Theme')
        else:
            self._theme_toggler.set_icon_name('light-theme')
            self._theme_toggler.set_tooltip('Switch to Light Theme')

        for i in range(self._notebook.get_n_pages()):
            vt = self._notebook.get_nth_page(i).vt
            vt.set_term_colors(self._theme_colors['custom'])

    def _create_view_toolbar(self):  # Color changer and Zoom toolbar
        view_toolbar = Gtk.Toolbar()

        self._theme_toggler = ToolButton('dark-theme')
        self._theme_toggler.set_tooltip('Switch to Dark Theme')
        self._theme_toggler.props.accelerator = '<Ctrl><Shift>I'
        self._theme_toggler.connect('clicked', self._toggled_theme)
        view_toolbar.insert(self._theme_toggler, -1)
        self._theme_toggler.show()

        self.fg_color_palette = ColorToolButton('color-preview')
        self.fg_color_palette._tooltip = "Set Foreground Text color"
        self.fg_color_palette.set_title('Foreground Color')
        self.fg_color_palette.connect('notify::color',
                                      self.__fg_color_notify_cb)
        view_toolbar.insert(self.fg_color_palette, -1)
        self.fg_color_palette.show()

        self.bg_color_palette = ColorToolButton('color-preview')
        self.bg_color_palette._tooltip = "Set Background color"
        self.bg_color_palette.set_title('Background Color')
        self.bg_color_palette.connect('notify::color',
                                      self.__bg_color_notify_cb)
        self.bg_color_palette.set_color(Gdk.Color.parse('#FFFFFF')[1])
        view_toolbar.insert(self.bg_color_palette, -1)
        self.bg_color_palette.show()

        sep = Gtk.SeparatorToolItem()
        view_toolbar.insert(sep, -1)
        sep.show()

        zoom_out_button = ToolButton('zoom-out')
        zoom_out_button.set_tooltip(_('Zoom out'))
        zoom_out_button.props.accelerator = '<Ctrl>minus'
        zoom_out_button.connect('clicked', self.__zoom_out_cb)
        view_toolbar.insert(zoom_out_button, -1)
        zoom_out_button.show()

        zoom_in_button = ToolButton('zoom-in')
        zoom_in_button.set_tooltip(_('Zoom in'))
        zoom_in_button.props.accelerator = '<Ctrl>plus'
        zoom_in_button.connect('clicked', self.__zoom_in_cb)
        view_toolbar.insert(zoom_in_button, -1)
        zoom_in_button.show()

        fullscreen_button = ToolButton('view-fullscreen')
        fullscreen_button.set_tooltip(_("Fullscreen"))
        fullscreen_button.props.accelerator = '<Alt>Return'
        fullscreen_button.connect('clicked', self.__fullscreen_cb)
        view_toolbar.insert(fullscreen_button, -1)
        fullscreen_button.show()
        return view_toolbar

    def _zoom(self, step):

        current_page = self._notebook.get_current_page()
        vt = self._notebook.get_nth_page(current_page).vt
        font_desc = vt.get_font()
        font_desc.set_size(font_desc.get_size() + Pango.SCALE * step)
        vt.set_font(font_desc)

    def __zoom_out_cb(self, button):
        self._zoom(-1)

    def __zoom_in_cb(self, button):
        self._zoom(1)

    def __fullscreen_cb(self, button):
        self.fullscreen()

    def _create_help_button(self):
        helpitem = HelpButton()

        helpitem.add_section(_('Useful commands'))
        helpitem.add_section(_('cd'))
        helpitem.add_paragraph(_('Change directory'))
        helpitem.add_paragraph(_('To use it, write: cd directory'))
        helpitem.add_paragraph(
            _('If you call it without parameters, will change\n'
              'to the user directory'))
        helpitem.add_section(_('ls'))
        helpitem.add_paragraph(_('List the content of a directory.'))
        helpitem.add_paragraph(_('To use it, write: ls directory'))
        helpitem.add_paragraph(
            _('If you call it without parameters, will list the\n'
              'working directory'))
        helpitem.add_section(_('cp'))
        helpitem.add_paragraph(_('Copy a file to a specific location'))
        helpitem.add_paragraph(_('Call it with the file and the new location'))
        helpitem.add_paragraph(_('Use: cp file directory'))
        helpitem.add_section(_('rm'))
        helpitem.add_paragraph(_('Removes a file in any path'))
        helpitem.add_paragraph(_('Use: rm file'))
        helpitem.add_section(_('su'))
        helpitem.add_paragraph(_('Login as superuser (root)'))
        helpitem.add_paragraph(
            _('The root user is the administrator of the\nsystem'))
        helpitem.add_paragraph(
            _('You must be careful, because you can modify\nsystem files'))

        return helpitem

    def __open_tab_cb(self, btn):
        vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
        font_desc = vt.get_font()
        self._font_size = font_desc.get_size() / Pango.SCALE

        index = self._create_tab(None)
        self._notebook.page = index

    def __close_tab_cb(self, btn, child):
        index = self._notebook.page_num(child)
        self._close_tab(index)

    def __prev_tab_cb(self, btn):
        if self._notebook.props.page == 0:
            self._notebook.props.page = self._notebook.get_n_pages() - 1
        else:
            self._notebook.props.page = self._notebook.props.page - 1
        vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
        vt.grab_focus()

    def __next_tab_cb(self, btn):
        if self._notebook.props.page == self._notebook.get_n_pages() - 1:
            self._notebook.props.page = 0
        else:
            self._notebook.props.page = self._notebook.props.page + 1
        vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
        vt.grab_focus()

    def _close_tab(self, index):
        self._notebook.remove_page(index)
        if self._notebook.get_n_pages() == 0:
            self.close()
        if self._notebook.get_n_pages() == 1:
            self._notebook.get_tab_label(
                self._notebook.get_nth_page(0)).hide_close_button()

    def __tab_child_exited_cb(self, vt, status=None):
        for i in range(self._notebook.get_n_pages()):
            if self._notebook.get_nth_page(i).vt == vt:
                self._close_tab(i)
                return

    def __tab_title_changed_cb(self, vt):
        for i in range(self._notebook.get_n_pages()):
            if self._notebook.get_nth_page(i).vt == vt:
                label = self._notebook.get_nth_page(i).label
                label.set_text(vt.get_window_title())
                return

    def __drag_data_received_cb(self, widget, context, x, y, selection, target,
                                time):
        widget.feed_child(selection.get_text(), -1)
        context.finish(True, False, time)
        return True

    def _create_tab(self, tab_state):
        vt = SugarTerminal(self)
        vt.connect("child-exited", self.__tab_child_exited_cb)
        vt.connect("window-title-changed", self.__tab_title_changed_cb)

        vt.drag_dest_set(Gtk.DestDefaults.MOTION | Gtk.DestDefaults.DROP, [
            Gtk.TargetEntry.new('text/plain', 0, 0),
            Gtk.TargetEntry.new('STRING', 0, 1)
        ], Gdk.DragAction.DEFAULT | Gdk.DragAction.COPY)
        vt.drag_dest_add_text_targets()
        vt.connect('drag_data_received', self.__drag_data_received_cb)

        vt.set_term_colors(self._theme_colors['custom'])

        vt.show()

        scrollbar = Gtk.VScrollbar.new(vt.get_vadjustment())

        box = Gtk.HBox()
        box.pack_start(vt, True, True, 0)
        box.pack_start(scrollbar, False, True, 0)

        box.vt = vt
        box.show()

        tablabel = TabLabel(box)
        tablabel.connect('tab-close', self.__close_tab_cb)
        tablabel.update_size(200)
        box.label = tablabel

        index = self._notebook.append_page(box, tablabel)
        tablabel.show_all()

        # Uncomment this to only show the tab bar when there is at least
        # one tab. I think it's useful to always see it, since it displays
        # the 'window title'.
        # self._notebook.props.show_tabs = self._notebook.get_n_pages() > 1
        if self._notebook.get_n_pages() == 1:
            tablabel.hide_close_button()
        if self._notebook.get_n_pages() == 2:
            self._notebook.get_tab_label(
                self._notebook.get_nth_page(0)).show_close_button()
        self._notebook.show_all()

        # Launch the default shell in the HOME directory.
        os.chdir(os.environ["HOME"])

        if tab_state:
            # Restore the environment.
            # This is currently not enabled.
            environment = tab_state['env']

            filtered_env = []
            for e in environment:
                var, sep, value = e.partition('=')
                if var not in MASKED_ENVIRONMENT:
                    filtered_env.append(var + sep + value)

            # TODO: Make the shell restore these environment variables,
            # then clear out TERMINAL_ENV.
            # os.environ['TERMINAL_ENV'] = '\n'.join(filtered_env)

            # Restore the working directory.
            if 'cwd' in tab_state and os.path.exists(tab_state['cwd']):
                try:
                    os.chdir(tab_state['cwd'])
                except:
                    # ACLs may deny access
                    sys.stdout.write("Could not chdir to " + tab_state['cwd'])

            if 'font_size' in tab_state:
                font_desc = vt.get_font()
                font_desc.set_size(tab_state['font_size'])
                vt.set_font(font_desc)

            # Restore the scrollback buffer.
            for l in tab_state['scrollback']:
                vt.feed(l.encode('utf-8') + b'\r\n')

        argv = [os.environ.get('SHELL') or '/bin/bash']
        envv = [
            'SUGAR_TERMINAL_VERSION=%s' % os.environ['SUGAR_BUNDLE_VERSION']
        ]

        saved = {}
        for name in [
                'SUGAR_BUNDLE_PATH', 'SUGAR_ACTIVITY_ROOT', 'SUGAR_BUNDLE_ID',
                'SUGAR_BUNDLE_NAME', 'SUGAR_BUNDLE_VERSION'
        ]:
            if name in os.environ:
                saved[name] = os.environ[name]
                del os.environ[name]

        if hasattr(vt, 'fork_command_full'):
            _, box.pid = vt.fork_command_full(
                Vte.PtyFlags.DEFAULT, os.environ["HOME"], argv, envv,
                GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None)
        else:
            _, box.pid = vt.spawn_sync(Vte.PtyFlags.DEFAULT,
                                       os.environ["HOME"], argv, envv,
                                       GLib.SpawnFlags.DO_NOT_REAP_CHILD, None,
                                       None)

        for name in saved:
            os.environ[name] = saved[name]

        self._notebook.props.page = index
        vt.grab_focus()

        return index

    def __key_press_cb(self, window, event):
        """Route some keypresses directly to the vte and then drop them.

        This prevents Sugar from hijacking events that are useful in
        the vte.

        """
        def event_to_vt(event):
            current_page = self._notebook.get_current_page()
            vt = self._notebook.get_nth_page(current_page).vt
            vt.event(event)

        key_name = Gdk.keyval_name(event.keyval)

        # Escape is used in Sugar to cancel fullscreen mode.
        if key_name == 'Escape':
            event_to_vt(event)
            return True

        elif event.get_state() & Gdk.ModifierType.CONTROL_MASK:
            if key_name in ['z', 'q']:
                event_to_vt(event)
                return True
            elif key_name == 'Tab':
                current_index = self._notebook.get_current_page()
                if current_index == self._notebook.get_n_pages() - 1:
                    self._notebook.set_current_page(0)
                else:
                    self._notebook.set_current_page(current_index + 1)
                return True
            elif event.get_state() & Gdk.ModifierType.SHIFT_MASK:
                if key_name == 'ISO_Left_Tab':
                    current_index = self._notebook.get_current_page()
                    if current_index == 0:
                        self._notebook.set_current_page(
                            self._notebook.get_n_pages() - 1)
                    else:
                        self._notebook.set_current_page(current_index - 1)
                    return True
                elif key_name == 'T':
                    self._create_tab(None)
                    return True

        return False

    def read_file(self, file_path):
        if self.metadata['mime_type'] != 'text/plain':
            return

        fd = open(file_path, 'r')
        text = fd.read()
        data = json.loads(text)
        fd.close()
        # Clean out any existing tabs.
        while self._notebook.get_n_pages():
            self._notebook.remove_page(0)

        # Restore theme
        if data['theme'] == 'custom':
            self._theme_colors['custom'] = data['theme_hex']
        else:
            self._theme_colors['custom'] = self._theme_colors[data['theme']]
        self.fg_color_palette.set_color(
            Gdk.Color.parse(self._theme_colors['custom']['fg_color'])[1])
        self.bg_color_palette.set_color(
            Gdk.Color.parse(self._theme_colors['custom']['bg_color'])[1])
        self._update_theme()

        # Create new tabs from saved state.
        for tab_state in data['tabs']:
            self._create_tab(tab_state)

        # Restore active tab.
        self._notebook.props.page = data['current-tab']

        # Create a blank one if this state had no terminals.
        if self._notebook.get_n_pages() == 0:
            self._create_tab(None)

    def write_file(self, file_path):
        if not self.metadata['mime_type']:
            self.metadata['mime_type'] = 'text/plain'

        data = {}
        data['current-tab'] = self._notebook.get_current_page()
        # make sures this doesn't conflict with older terminal version
        data['theme'] = 'custom'
        data['theme_hex'] = self._theme_colors['custom']
        data['tabs'] = []

        for i in range(self._notebook.get_n_pages()):

            def is_selected(vte, *args):
                return True

            page = self._notebook.get_nth_page(i)

            text = ''
            if VTE_VERSION >= 38:
                # in older versions of vte, get_text() makes crash
                # the activity at random - SL #4627
                try:
                    # get_text is only available in latest vte #676999
                    # and pygobject/gobject-introspection #690041
                    text, attr_ = page.vt.get_text(is_selected, None)
                except AttributeError:
                    pass

            scrollback_lines = text.split('\n')

            environ_file = '/proc/%d/environ' % page.pid
            if os.path.isfile(environ_file):
                # Note- this currently gets the child's initial environment
                # rather than the current environment,
                # making it not very useful.
                environment = open(environ_file, 'r').read().split('\0')

                cwd = os.readlink('/proc/%d/cwd' % page.pid)
            else:
                # terminal killed by the user
                environment = []
                cwd = '~'

            font_desc = page.vt.get_font()

            tab_state = {
                'env': environment,
                'cwd': cwd,
                'font_size': font_desc.get_size(),
                'scrollback': scrollback_lines
            }

            data['tabs'].append(tab_state)
        fd = open(file_path, 'w')
        text = json.dumps(data)
        fd.write(text)
        fd.close()

    def __clear_cb(self, button):
        vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
        n = vt.props.scrollback_lines
        vt.set_scrollback_lines(0)
        vt.set_scrollback_lines(n)
Пример #6
0
    def make_toolbar(self):
        toolbar_box = ToolbarBox()
        toolbar = toolbar_box.toolbar

        activity_button = ToolButton()
        activity_button.set_icon_widget(ActivityIcon(None))
        toolbar.insert(activity_button, -1)

        utils.make_separator(toolbar, False)

        edit_toolbar = EditToolbar()
        edit_toolbar.undo.props.visible = False
        edit_toolbar.redo.props.visible = False
        edit_toolbar.separator.props.visible = False
        edit_toolbar.copy.connect("clicked", self.copy_cb)
        edit_toolbar.copy.props.accelerator = "<Ctrl><Shift>C"
        edit_toolbar.paste.connect("clicked", self.paste_cb)
        edit_toolbar.paste.props.accelerator = "<Ctrl><Shift>V"

        self.copy_button = edit_toolbar.copy
        self.copy_button.set_sensitive(False)

        edit_toolbar_button = ToolbarButton(page=edit_toolbar,
                                            icon_name="toolbar-edit")
        toolbar_box.toolbar.insert(edit_toolbar_button, -1)

        view_toolbar = Gtk.Toolbar()

        boton_toolbar_view = ToolbarButton(page=view_toolbar,
                                           icon_name="toolbar-view")
        toolbar.insert(boton_toolbar_view, -1)

        background_color_button = ColorToolButton()
        background_color_button.set_color(self.background_color)
        background_color_button.set_title("Background color")
        background_color_button.connect("color-set",
                                        self.background_color_changed)
        view_toolbar.insert(background_color_button, -1)

        text_color_button = ColorToolButton()
        text_color_button.set_color(self.text_color)
        text_color_button.set_title("Text color")
        text_color_button.connect("color-set", self.text_color_changed)
        view_toolbar.insert(text_color_button, -1)

        item_font_size = FontSize()
        item_font_size.set_font_size(self.font_size, False)
        item_font_size.connect("changed", self.font_size_changed)
        view_toolbar.insert(item_font_size, -1)

        utils.make_separator(view_toolbar, False)

        button_left = Gtk.RadioToolButton()
        button_left.set_icon_name('go-left')
        button_left.set_tooltip_text("Move 'add' button to the left")
        view_toolbar.insert(button_left, -1)

        button_right = Gtk.RadioToolButton.new_from_widget(button_left)
        button_right.set_icon_name('go-right')
        button_right.set_tooltip_text("Move 'add' button to the right")
        view_toolbar.insert(button_right, -1)

        if self.button_position == Gtk.PackType.START:
            button_left.set_active(True)
        elif self.button_position == Gtk.PackType.END:
            button_right.set_active(True)

        button_left.connect("toggled", self.move_button, Gtk.PackType.START)
        button_right.connect("toggled", self.move_button, Gtk.PackType.END)

        view_toolbar.show_all()

        self.button_new = ToolButton("add")
        self.button_new.props.accelerator = "<Ctrl><Shift>T"
        self.button_new.connect("clicked",
                                lambda button: self.notebook.new_terminal())
        toolbar.insert(self.button_new, -1)

        utils.make_separator(toolbar, True)

        button_stop = ToolButton("activity-stop")
        button_stop.props.accelerator = "<Ctrl><Shift>C"
        button_stop.connect("clicked", self._close)
        toolbar.insert(button_stop, -1)

        toolbar.show_all()

        self.set_toolbar_box(toolbar_box)