def _build_palette(self, tool): if tool.palette_enabled: if tool.palette_mode == tools.PALETTE_MODE_ICONS: grid = Gtk.Grid() for s, settings in enumerate(tool.palette_settings): self.game.toolList[tool.name].buttons.append([]) for i, icon_value in enumerate(settings['icon_values']): if i == 0: button = RadioToolButton(group=None) firstbutton = button else: button = RadioToolButton(group=firstbutton) button.set_icon_name(settings['icons'][i]) button.connect('clicked', self._palette_icon_clicked, tool.name, s, settings['name'], icon_value) grid.attach(button, i, s, 1, 1) self.game.toolList[tool.name].buttons[s].append(button) button.show() if settings['active'] == settings['icons'][i]: button.set_icon_name(settings['icons'][i] + '-selected') button.set_active(True) return grid else: return None
class ToolbarInfo(Gtk.Toolbar): __gsignals__ = { "show-simulation": (GObject.SIGNAL_RUN_FIRST, None, []), "show-info": (GObject.SIGNAL_RUN_FIRST, None, []), "go-back": (GObject.SIGNAL_RUN_FIRST, None, []), "go-forward": (GObject.SIGNAL_RUN_FIRST, None, []), } def __init__(self): Gtk.Toolbar.__init__(self) self.button = ToolbarButton(page=self, icon_name="info") self.button_simulation = RadioToolButton(icon_name="solar-system", group=None) self.button_simulation.set_tooltip(_("Show solar system")) self.button_simulation.connect("toggled", self._show_simulation_cb) self.insert(self.button_simulation, -1) self.button_info = RadioToolButton(icon_name="info", group=self.button_simulation) self.button_info.set_tooltip(_("Show information")) self.button_info.connect("toggled", self._show_info_cb) self.insert(self.button_info, -1) self.insert(make_separator(False), -1) self.back_button = ToolButton("go-previous-paired") self.back_button.set_tooltip(_("Go back")) self.back_button.set_sensitive(False) self.back_button.connect("clicked", self._go_back_cb) self.insert(self.back_button, -1) self.forward_button = ToolButton("go-next-paired") self.forward_button.set_tooltip(_("Go forward")) self.forward_button.set_sensitive(False) self.forward_button.connect("clicked", self._go_forward_cb) self.insert(self.forward_button, -1) self.show_all() def _show_simulation_cb(self, widget): self.emit("show-simulation") def _show_info_cb(self, widget): self.emit("show-info") def _go_back_cb(self, widget): self.emit("go-back") def _go_forward_cb(self, widget): self.emit("go-forward") def select_screen(self, screen): if screen == Screen.SOLAR_SYSTEM: self.button_simulation.props = True elif screen == Screen.INFO: self.button_info.props.active = True
def __init__(self, owner): GObject.GObject.__init__(self) self.owner = owner self._insert_separator(True) self.desktop = [] btn = RadioToolButton(group=None) btn.set_icon_name('jam-preset1') btn.connect('toggled', self.setDesktop, 0) btn.set_tooltip(_('Desktop 1')) self.insert(btn, -1) self.desktop.append(btn) for i in range(2, 11): btn = RadioToolButton(group=self.desktop[0]) btn.set_icon_name('jam-preset%d' % i) btn.connect('toggled', self.setDesktop, i - 1) btn.set_tooltip(_('Desktop %d' % i)) self.insert(btn, -1) self.desktop.append(btn) self._insert_separator(True) self.show_all()
def __init__(self, activity_name, has_local_help): Gtk.Toolbar.__init__(self) self._webview = None self._add_separator(False) if has_local_help and get_social_help_server(): help_button = RadioToolButton() icon = Icon(icon_name='toolbar-help', pixel_size=style.STANDARD_ICON_SIZE, fill_color=style.COLOR_TRANSPARENT.get_svg(), stroke_color=style.COLOR_WHITE.get_svg()) help_button.set_icon_widget(icon) icon.show() help_button.props.tooltip = _('Help Manual') help_button.connect('toggled', self.__button_toggled_cb, _MODE_HELP) self.insert(help_button, -1) help_button.show() self._add_separator(False) social_help_button = RadioToolButton() icon = Icon(icon_name='toolbar-social-help', pixel_size=style.STANDARD_ICON_SIZE, fill_color=style.COLOR_TRANSPARENT.get_svg(), stroke_color=style.COLOR_WHITE.get_svg()) social_help_button.set_icon_widget(icon) icon.show() social_help_button.props.tooltip = _('Social Help') social_help_button.props.group = help_button social_help_button.connect('toggled', self.__button_toggled_cb, _MODE_SOCIAL_HELP) self.insert(social_help_button, -1) social_help_button.show() self._add_separator(False) self._back_button = ToolButton(icon_name='go-previous-paired') self._back_button.props.tooltip = _('Back') self._back_button.connect('clicked', self.__back_clicked_cb) self.insert(self._back_button, -1) self._back_button.show() self._forward_button = ToolButton(icon_name='go-next-paired') self._forward_button.props.tooltip = _('Forward') self._forward_button.connect('clicked', self.__forward_clicked_cb) self.insert(self._forward_button, -1) self._forward_button.show() title = _('Help: %s') % activity_name self._label = Gtk.Label() self._label.set_markup('<b>%s</b>' % title) self._label.set_alignment(0, 0.5) self._add_widget(self._label) self._add_separator(True) stop = ToolButton(icon_name='dialog-cancel') stop.set_tooltip(_('Close')) stop.connect('clicked', self.__stop_clicked_cb) self.insert(stop, -1) stop.show()
def __init__(self, favorite_view): RadioToolButton.__init__(self) self.props.tooltip = _('Favorites view %d' % (favorite_view + 1)) self.props.accelerator = _('<Ctrl>%d' % (favorite_view + 1)) self.props.group = None self.props.icon_name = desktop.get_view_icons()[favorite_view] favorites_settings = favoritesview.get_settings(favorite_view) self._layout = favorites_settings.layout # someday, this will be a Gtk.Table() layouts_grid = Gtk.HBox() layout_item = None for layoutid, layoutclass in sorted(favoritesview.LAYOUT_MAP.items()): layout_item = RadioToolButton(icon_name=layoutclass.icon_name, group=layout_item, active=False) if layoutid == self._layout: layout_item.set_active(True) layouts_grid.pack_start(layout_item, True, False, 0) layout_item.connect('toggled', self.__layout_activate_cb, layoutid, favorite_view) layouts_grid.show_all() self.props.palette.set_content(layouts_grid)
def __init__(self, activity_name, has_local_help): Gtk.Toolbar.__init__(self) self._add_separator(False) if has_local_help and get_social_help_server(): help_button = RadioToolButton() icon = Icon(icon_name='toolbar-help', pixel_size=style.STANDARD_ICON_SIZE, fill_color=style.COLOR_TRANSPARENT.get_svg(), stroke_color=style.COLOR_WHITE.get_svg()) help_button.set_icon_widget(icon) icon.show() help_button.props.tooltip = _('Help Manual') help_button.connect('toggled', self.__button_toggled_cb, _MODE_HELP) self.insert(help_button, -1) help_button.show() self._add_separator(False) social_help_button = RadioToolButton() icon = Icon(icon_name='toolbar-social-help', pixel_size=style.STANDARD_ICON_SIZE, fill_color=style.COLOR_TRANSPARENT.get_svg(), stroke_color=style.COLOR_WHITE.get_svg()) social_help_button.set_icon_widget(icon) icon.show() social_help_button.props.tooltip = _('Social Help') social_help_button.props.group = help_button social_help_button.connect( 'toggled', self.__button_toggled_cb, _MODE_SOCIAL_HELP) self.insert(social_help_button, -1) social_help_button.show() self._add_separator(False) self._back_button = ToolButton(icon_name='go-previous-paired') self._back_button.props.tooltip = _('Back') self._back_button.connect('clicked', self.__back_clicked_cb) self.insert(self._back_button, -1) self._back_button.show() self._forward_button = ToolButton(icon_name='go-next-paired') self._forward_button.props.tooltip = _('Forward') self._forward_button.connect('clicked', self.__forward_clicked_cb) self.insert(self._forward_button, -1) self._forward_button.show() title = _('Help: %s') % activity_name self._label = Gtk.Label() self._label.set_markup('<b>%s</b>' % title) self._label.set_alignment(0, 0.5) self._add_widget(self._label) self._add_separator(True) stop = ToolButton(icon_name='dialog-cancel') stop.set_tooltip(_('Close')) stop.connect('clicked', self.__stop_clicked_cb) self.insert(stop, -1) stop.show()
def instance(self): book.wiki = book.WikiBook() if not book.custom: book.custom = book.CustomBook() self.edit_page = 1 self.edit = edit.View() self.library = library.View(self) toolbar_box = ToolbarBox() activity_button = ActivityToolbarButton(self) toolbar_box.toolbar.insert(activity_button, 0) self.set_toolbar_box(toolbar_box) self._toolbar = toolbar_box.toolbar tool_group = None search_button = RadioToolButton() search_button.props.group = tool_group tool_group = search_button search_button.props.icon_name = 'white-search' search_button.set_tooltip(_('Library')) search_button.mode = 'search' search_button.connect('clicked', self.__mode_button_clicked) self._toolbar.insert(search_button, -1) edit_button = RadioToolButton() edit_button.props.group = tool_group edit_button.props.icon_name = 'toolbar-edit' edit_button.set_tooltip(_('Edit')) edit_button.mode = 'edit' edit_button.connect('clicked', self.__mode_button_clicked) self._toolbar.insert(edit_button, -1) self._toolbar.insert(Gtk.SeparatorToolItem(), -1) self.edit_bar = edit.ToolbarBuilder(self.edit, self._toolbar) self.library_bar = library.ToolbarBuilder(self.library, activity_button) self.library_bar.publish.show() edit_fake = Gtk.EventBox() self.notebook.append_page(self.library, None) self.notebook.append_page(self.edit, None) self.notebook.append_page(edit_fake, None) self.show_all() self.__mode_button_clicked(search_button) separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) separator.show() self._toolbar.insert(separator, -1) stop_button = StopButton(self) stop_button.show() self._toolbar.insert(stop_button, -1)
def __init__(self, parent): Gtk.Toolbar.__init__(self) self._parent = parent text_mode_btn = RadioToolButton(icon_name='text-mode') text_mode_btn.set_tooltip(_('Text mode')) text_mode_btn.set_accelerator(_('<ctrl>t')) text_mode_btn.connect('clicked', self._parent.mode_cb, MMapArea.MODE_TEXT) self.insert(text_mode_btn, -1) image_mode_btn = RadioToolButton(icon_name='image-mode', group=text_mode_btn) image_mode_btn.set_tooltip(_('Image add mode')) image_mode_btn.set_accelerator(_('<ctrl>i')) image_mode_btn.connect('clicked', self._parent.mode_cb, MMapArea.MODE_IMAGE) self.insert(image_mode_btn, -1) draw_mode_btn = RadioToolButton(icon_name='draw-mode', group=text_mode_btn) draw_mode_btn.set_tooltip(_('Drawing mode')) draw_mode_btn.set_accelerator(_('<ctrl>d')) draw_mode_btn.connect('clicked', self._parent.mode_cb, MMapArea.MODE_DRAW) self.insert(draw_mode_btn, -1) label_mode_btn = RadioToolButton(icon_name='label-mode', group=text_mode_btn) label_mode_btn.set_tooltip(_('Label mode')) label_mode_btn.set_accelerator(_('<ctrl>a')) label_mode_btn.connect('clicked', self._parent.mode_cb, MMapArea.MODE_LABEL) self.insert(label_mode_btn, -1) self.show_all()
def __init__(self, owner): GObject.GObject.__init__(self) self.owner = owner self.toolItem = {} self.blockBeat = False self.beatWheel = [] btn = RadioToolButton(group=None) btn.set_icon_name('beats') btn.connect('toggled', self.setBeat, 0) btn.set_tooltip(_('Jump To Beat')) self.insert(btn, -1) self.beatWheel.append(btn) for i in range(1, 12): btn = RadioToolButton(group=self.beatWheel[0]) btn.set_icon_name('beats') btn.connect('toggled', self.setBeat, i) btn.set_tooltip(_('Jump To Beat')) self.insert(btn, -1) self.beatWheel.append(btn) label = Gtk.Label(label=_("Synch to:")) self.syncLabel = Gtk.ToolItem() self.syncLabel.add(label) self.insert(self.syncLabel, 0) self.comboBox = ComboBox() self.comboBox.append_item(1, _("1 Beat")) self.comboBox.append_item(2, _("2 Beats")) self.comboBox.append_item(3, _("3 Beats")) self.comboBox.append_item(4, _("4 Beats")) self.comboBox.append_item(5, _("5 Beats")) self.comboBox.append_item(6, _("6 Beats")) self.comboBox.append_item(7, _("7 Beats")) self.comboBox.append_item(8, _("8 Beats")) self.comboBox.append_item(9, _("9 Beats")) self.comboBox.append_item(10, _("10 Beats")) self.comboBox.append_item(11, _("11 Beats")) self.comboBox.append_item(12, _("12 Beats")) self.comboBox.set_active(4 - 1) # default 4 beats self.comboBox.connect("changed", self.changeSync) self.syncBox = ToolComboBox(self.comboBox) self.insert(self.syncBox, 1) self.show_all()
def add_level_button(icon_name, tooltip, numeric_level): if self._levels_buttons: button = RadioToolButton(icon_name=icon_name, group=self._levels_buttons[0]) else: button = RadioToolButton(icon_name=icon_name) self._levels_buttons.append(button) def callback(source): if source.get_active(): self.game.set_level(numeric_level) self.game.run() button.connect('clicked', callback) button.set_tooltip(tooltip)
def add_level_button(icon_name, tooltip, numeric_level): if self._levels_buttons: button = RadioToolButton(icon_name=icon_name, group=self._levels_buttons[0]) else: button = RadioToolButton(icon_name=icon_name) self._levels_buttons.append(button) toolbar.add(button) def callback(source): if source.get_active(): self._game.set_level(numeric_level) self._game.new_game() button.connect('clicked', callback) button.set_tooltip(tooltip)
def radio_factory(icon_name, toolbar, callback, cb_arg=None, tooltip=None, group=None): ''' Add a radio button to a toolbar ''' button = RadioToolButton(group=group) button.set_icon_name(icon_name) if tooltip is not None: button.set_tooltip(tooltip) if cb_arg is None: button.connect('clicked', callback) else: button.connect('clicked', callback, cb_arg) if hasattr(toolbar, 'insert'): # the main toolbar toolbar.insert(button, -1) else: # or a secondary toolbar toolbar.props.page.insert(button, -1) button.show() return button
def radio_factory(button_name, toolbar, callback, cb_arg=None, tooltip=None, group=None): """ Add a radio button to a toolbar """ button = RadioToolButton(group=group) button.set_icon_name(button_name) if callback is not None: if cb_arg is None: button.connect("clicked", callback) else: button.connect("clicked", callback, cb_arg) if hasattr(toolbar, "insert"): # Add button to the main toolbar... toolbar.insert(button, -1) else: # ...or a secondary toolbar. toolbar.props.page.insert(button, -1) button.show() if tooltip is not None: button.set_tooltip(tooltip) return button
def add_level_button(icon_name, tooltip, numeric_level): if self._levels_buttons: button = RadioToolButton(icon_name=icon_name, group=self._levels_buttons[0]) else: button = RadioToolButton(icon_name=icon_name) self._levels_buttons.append(button) toolbar.add(button) def callback(source): if source.get_active(): self._collab.post({'action': icon_name}) self._game.set_level(numeric_level) self._game.new_game() button.connect('toggled', callback) button.set_tooltip(tooltip)
def _add_button(self, icon_name, label, accelerator, zoom_level): if self.get_children(): group = self.get_children()[0] else: group = None button = RadioToolButton(icon_name=icon_name, group=group, accelerator=accelerator) button.connect('clicked', self.__level_clicked_cb, zoom_level) self.add(button) button.show() palette = Palette(glib.markup_escape_text(label)) palette.props.invoker = FrameWidgetInvoker(button) palette.set_group_id('frame') button.set_palette(palette) return button
def _add_button(self, icon_name, label, accelerator, zoom_level): if self.get_children(): group = self.get_children()[0] else: group = None button = RadioToolButton(icon_name=icon_name, group=group, accelerator=accelerator) button.connect('clicked', self.__level_clicked_cb, zoom_level) self.add(button) button.show() palette = Palette(GLib.markup_escape_text(label)) palette.props.invoker = FrameWidgetInvoker(button) palette.set_group_id('frame') button.set_palette(palette) return button
def __init__(self, favorite_view): RadioToolButton.__init__(self) self.props.tooltip = desktop.get_favorite_names()[favorite_view] self.props.accelerator = _("<Ctrl>%d" % (favorite_view + 1)) self.props.group = None self.props.icon_name = desktop.get_view_icons()[favorite_view] favorites_settings = favoritesview.get_settings(favorite_view) self._layout = favorites_settings.layout # someday, this will be a Gtk.Table() layouts_grid = Gtk.HBox() layout_item = None for layoutid, layoutclass in sorted(favoritesview.LAYOUT_MAP.items()): layout_item = RadioToolButton(icon_name=layoutclass.icon_name, group=layout_item, active=False) if layoutid == self._layout: layout_item.set_active(True) layouts_grid.pack_start(layout_item, True, False, 0) layout_item.connect("toggled", self.__layout_activate_cb, layoutid, favorite_view) layouts_grid.show_all() self.props.palette.set_content(layouts_grid)
def _add_clock_controls(self, display_toolbar): # First group of radio button to select the type of clock to display button1 = RadioToolButton(icon_name="simple-clock") button1.set_tooltip(_('Simple Clock')) button1.connect("toggled", self._display_mode_changed_cb, _MODE_SIMPLE_CLOCK) display_toolbar.insert(button1, -1) self._display_mode_buttons.append(button1) button2 = RadioToolButton(icon_name="nice-clock", group=button1) button2.set_tooltip(_('Nice Clock')) button2.connect("toggled", self._display_mode_changed_cb, _MODE_NICE_CLOCK) display_toolbar.insert(button2, -1) self._display_mode_buttons.append(button2) button3 = RadioToolButton(icon_name="digital-clock", group=button1) button3.set_tooltip(_('Digital Clock')) button3.connect("toggled", self._display_mode_changed_cb, _MODE_DIGITAL_CLOCK) display_toolbar.insert(button3, -1) self._display_mode_buttons.append(button3) # A separator between the two groups of buttons separator = Gtk.SeparatorToolItem() separator.set_draw(True) display_toolbar.insert(separator, -1) # Now the options buttons to display other elements: date, day # of week... A button in the toolbar to write the time in # full letters self._write_time_btn = ToggleToolButton("write-time") self._write_time_btn.set_tooltip(_('Display time in full letters')) self._write_time_btn.connect("toggled", self._write_time_clicked_cb) display_toolbar.insert(self._write_time_btn, -1) # The button to display the weekday and date self._write_date_btn = ToggleToolButton("write-date") self._write_date_btn.set_tooltip(_('Display weekday and date')) self._write_date_btn.connect("toggled", self._write_date_clicked_cb) display_toolbar.insert(self._write_date_btn, -1) # Another button to speak aloud the time self._speak_time_btn = ToggleToolButton("microphone") self._speak_time_btn.set_tooltip(_('Talking clock')) self._speak_time_btn.connect("toggled", self._speak_time_clicked_cb) display_toolbar.insert(self._speak_time_btn, -1) # A separator between the two groups of buttons separator = Gtk.SeparatorToolItem() separator.set_draw(True) display_toolbar.insert(separator, -1) # And another button to toggle grabbing the hands self._grab_button = ToggleToolButton("grab") self._grab_button.set_tooltip(_('Grab the hands')) self._grab_button.connect("toggled", self._grab_clicked_cb) display_toolbar.insert(self._grab_button, -1)
def _insert_create_tools(self, create_toolbar): # Make + add the component buttons self.radioList = {} for i, c in enumerate(tools.allTools): if i == 0: button = RadioToolButton(group=None) firstbutton = button else: button = RadioToolButton(group=firstbutton) button.set_icon_name(c.icon) button.set_tooltip(c.toolTip) button.set_accelerator(c.toolAccelerator) button.connect("clicked", self.radioClicked) palette = self._build_palette(c) if palette is not None: palette.show() button.get_palette().set_content(palette) self._insert_item(create_toolbar, button, -1) button.show() self.radioList[button] = c.name if hasattr(c, "constructor"): self._constructors[c.name] = self.game.toolList[c.name].constructor
def build_toolbox(self): view_tool_group = None registerbtn = RadioToolButton() registerbtn.props.icon_name = 'view-list' registerbtn.props.label = _('Register') registerbtn.set_tooltip(_("Register")) registerbtn.props.group = view_tool_group view_tool_group = registerbtn registerbtn.props.accelerator = '<Ctrl>1' registerbtn.connect('clicked', self.register_cb) budgetbtn = RadioToolButton() budgetbtn.props.icon_name = 'budget' budgetbtn.props.label = _('Budget') budgetbtn.set_tooltip(_("Budget")) budgetbtn.props.group = view_tool_group budgetbtn.props.accelerator = '<Ctrl>2' budgetbtn.connect('clicked', self.budget_cb) chartbtn = RadioToolButton() chartbtn.props.icon_name = 'chart' chartbtn.props.label = _('Chart') chartbtn.set_tooltip(_("Chart")) chartbtn.props.group = view_tool_group chartbtn.props.accelerator = '<Ctrl>3' chartbtn.connect('clicked', self.chart_cb) helpbutton = self._create_help_button() helpbutton.show_all() self.toolbar_box = ToolbarBox() activity_button = ActivityToolbarButton(self) self.toolbar_box.toolbar.insert(activity_button, 0) activity_button.show() self.toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1) self.toolbar_box.toolbar.insert(registerbtn, -1) self.toolbar_box.toolbar.insert(budgetbtn, -1) self.toolbar_box.toolbar.insert(chartbtn, -1) self.toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1) self.toolbar_box.toolbar.insert(helpbutton, -1) separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) self.toolbar_box.toolbar.insert(separator, -1) self.toolbar_box.toolbar.insert(StopButton(self), -1) self.set_toolbar_box(self.toolbar_box) activity_button.page.insert(self._create_export_button(), -1) self.toolbar_box.show_all()
def _insert_create_tools(self, create_toolbar): # Make + add the component buttons self.radioList = {} for i, c in enumerate(tools.allTools): if i == 0: button = RadioToolButton(group=None) firstbutton = button else: button = RadioToolButton(group=firstbutton) button.set_icon_name(c.icon) button.set_tooltip(c.toolTip) button.set_accelerator(c.toolAccelerator) button.connect('clicked', self.radioClicked) palette = self._build_palette(c) if palette is not None: palette.show() button.get_palette().set_content(palette) self._insert_item(create_toolbar, button, -1) button.show() self.radioList[button] = c.name if hasattr(c, 'constructor'): self._constructors[c.name] = \ self.game.toolList[c.name].constructor
def __init__(self): RadioToolButton.__init__(self) self.props.tooltip = _('Favorites view') self.props.accelerator = _('<Ctrl>1') self.props.group = None favorites_settings = favoritesview.get_settings() self._layout = favorites_settings.layout self._update_icon() # someday, this will be a Gtk.Table() layouts_grid = Gtk.HBox() layout_item = None for layoutid, layoutclass in sorted(favoritesview.LAYOUT_MAP.items()): layout_item = RadioToolButton(icon_name=layoutclass.icon_name, group=layout_item, active=False) if layoutid == self._layout: layout_item.set_active(True) layouts_grid.pack_start(layout_item, True, False, 0) layout_item.connect('toggled', self.__layout_activate_cb, layoutid) layouts_grid.show_all() self.props.palette.set_content(layouts_grid)
def _create_chart_buttons(self, toolbar): add_vbar_chart = RadioToolButton() 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.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.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.set_tooltip(_('Pie Chart')) add_pie_chart.props.icon_name = 'pie' add_pie_chart.props.group = charts_group toolbar.insert(add_pie_chart, -1) add_vbar_chart.connect('toggled', self._add_chart_cb, charts.VERTICAL_BAR) add_hbar_chart.connect('toggled', self._add_chart_cb, charts.HORIZONTAL_BAR) add_line_chart.connect('toggled', self._add_chart_cb, charts.LINE) add_pie_chart.connect('toggled', self._add_chart_cb, charts.PIE) 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) self._add_chart_cb(add_vbar_chart, charts.VERTICAL_BAR)
class ShareButton(RadioMenuButton): def __init__(self, activity, **kwargs): palette = RadioPalette() self.private = RadioToolButton( icon_name='zoom-home') palette.append(self.private, _('Private')) self.neighborhood = RadioToolButton( icon_name='zoom-neighborhood', group=self.private) self._neighborhood_handle = self.neighborhood.connect( 'clicked', self.__neighborhood_clicked_cb, activity) palette.append(self.neighborhood, _('My Neighborhood')) activity.connect('shared', self.__update_share_cb) activity.connect('joined', self.__update_share_cb) RadioMenuButton.__init__(self, **kwargs) self.props.palette = palette if activity.max_participants == 1: self.props.sensitive = False def __neighborhood_clicked_cb(self, button, activity): activity.share() def __update_share_cb(self, activity): self.neighborhood.handler_block(self._neighborhood_handle) try: if activity.shared_activity is not None and \ not activity.shared_activity.props.private: self.private.props.sensitive = False self.neighborhood.props.sensitive = False self.neighborhood.props.active = True else: self.private.props.sensitive = True self.neighborhood.props.sensitive = True self.private.props.active = True finally: self.neighborhood.handler_unblock(self._neighborhood_handle)
def _load_standard_buttons(self, toolbar): fraction_button = RadioToolButton(group=None) fraction_button.set_icon_name('fraction') fraction_button.set_tooltip(_('fractions')) fraction_button.connect('clicked', self._fraction_cb) toolbar.insert(fraction_button, -1) fraction_button.show() sector_button = RadioToolButton(group=fraction_button) sector_button.set_icon_name('sector') sector_button.set_tooltip(_('sectors')) sector_button.connect('clicked', self._sector_cb) toolbar.insert(sector_button, -1) sector_button.show() percent_button = RadioToolButton(group=fraction_button) percent_button.set_icon_name('percent') percent_button.set_tooltip(_('percents')) percent_button.connect('clicked', self._percent_cb) toolbar.insert(percent_button, -1) percent_button.show() self._player = Gtk.Image() self._player.set_from_pixbuf( svg_str_to_pixbuf( generate_xo_svg(scale=0.8, colors=['#282828', '#282828']))) self._player.set_tooltip_text(self.nick) toolitem = Gtk.ToolItem() toolitem.add(self._player) self._player.show() toolbar.insert(toolitem, -1) toolitem.show() self._label = Gtk.Label(_("Click the ball to start.")) self._label.set_line_wrap(True) if Gdk.Screen.width() < 1024: self._label.set_size_request(275, -1) else: self._label.set_size_request(500, -1) self.toolitem = Gtk.ToolItem() self.toolitem.add(self._label) self._label.show() toolbar.insert(self.toolitem, -1) self.toolitem.show()
def _load_standard_buttons(self, toolbar): fraction_button = RadioToolButton(group=None) fraction_button.set_icon_name('fraction') fraction_button.set_tooltip(_('fractions')) fraction_button.connect('clicked', self._fraction_cb) toolbar.insert(fraction_button, -1) fraction_button.show() sector_button = RadioToolButton(group=fraction_button) sector_button.set_icon_name('sector') sector_button.set_tooltip(_('sectors')) sector_button.connect('clicked', self._sector_cb) toolbar.insert(sector_button, -1) sector_button.show() percent_button = RadioToolButton(group=fraction_button) percent_button.set_icon_name('percent') percent_button.set_tooltip(_('percents')) percent_button.connect('clicked', self._percent_cb) toolbar.insert(percent_button, -1) percent_button.show() self._player = Gtk.Image() self._player.set_from_pixbuf(svg_str_to_pixbuf( generate_xo_svg(scale=0.8, colors=['#282828', '#282828']))) self._player.set_tooltip_text(self.nick) toolitem = Gtk.ToolItem() toolitem.add(self._player) self._player.show() toolbar.insert(toolitem, -1) toolitem.show() self._label = Gtk.Label(_("Click the ball to start.")) self._label.set_line_wrap(True) if Gdk.Screen.width() < 1024: self._label.set_size_request(275, -1) else: self._label.set_size_request(500, -1) self.toolitem = Gtk.ToolItem() self.toolitem.add(self._label) self._label.show() toolbar.insert(self.toolitem, -1) self.toolitem.show()
def _insert_stop_play_button(self, toolbar): self.stop_play_toolbar = ToolbarButton() st_toolbar = self.stop_play_toolbar st_toolbar.props.page = Gtk.Toolbar() st_toolbar.props.icon_name = "media-playback-stop" self.stop_play_state = True self.stop_play = ToolButton("media-playback-stop") self.stop_play.set_tooltip(_("Stop")) self.stop_play.set_accelerator(_("<ctrl>space")) self.stop_play.connect("clicked", self.stop_play_cb) self._insert_item(st_toolbar, self.stop_play) self.stop_play.show() slowest_button = RadioToolButton(group=None) slowest_button.set_icon_name("slow-walk-milton-raposo") slowest_button.set_tooltip(_("Run slower")) slowest_button.connect("clicked", self._set_fps_cb, SLOWEST_FPS) self._insert_item(st_toolbar, slowest_button) slowest_button.show() slow_button = RadioToolButton(group=slowest_button) slow_button.set_icon_name("walking") slow_button.set_tooltip(_("Run slow")) slow_button.connect("clicked", self._set_fps_cb, SLOW_FPS) self._insert_item(st_toolbar, slow_button) slow_button.show() fast_button = RadioToolButton(group=slowest_button) fast_button.set_icon_name("running") fast_button.set_tooltip("Run fast") fast_button.connect("clicked", self._set_fps_cb, FAST_FPS) self._insert_item(st_toolbar, fast_button) fast_button.show() fast_button.set_active(True) toolbar.insert(self.stop_play_toolbar, -1) self.stop_play_toolbar.show_all()
def _insert_stop_play_button(self, toolbar): self.stop_play_toolbar = ToolbarButton() st_toolbar = self.stop_play_toolbar st_toolbar.props.page = Gtk.Toolbar() st_toolbar.props.icon_name = 'media-playback-stop' self.stop_play_state = True self.stop_play = ToolButton('media-playback-stop') self.stop_play.set_tooltip(_('Stop')) self.stop_play.set_accelerator(_('<ctrl>space')) self.stop_play.connect('clicked', self.stop_play_cb) self._insert_item(st_toolbar, self.stop_play) self.stop_play.show() slowest_button = RadioToolButton(group=None) slowest_button.set_icon_name('slow-walk-milton-raposo') slowest_button.set_tooltip(_('Run slower')) slowest_button.connect('clicked', self._set_fps_cb, SLOWEST_FPS) self._insert_item(st_toolbar, slowest_button) slowest_button.show() slow_button = RadioToolButton(group=slowest_button) slow_button.set_icon_name('walking') slow_button.set_tooltip(_('Run slow')) slow_button.connect('clicked', self._set_fps_cb, SLOW_FPS) self._insert_item(st_toolbar, slow_button) slow_button.show() fast_button = RadioToolButton(group=slowest_button) fast_button.set_icon_name('running') fast_button.set_tooltip('Run fast') fast_button.connect('clicked', self._set_fps_cb, FAST_FPS) self._insert_item(st_toolbar, fast_button) fast_button.show() fast_button.set_active(True) toolbar.insert(self.stop_play_toolbar, -1) self.stop_play_toolbar.show_all()
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()
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)
class ToolbarSpeed(Gtk.Toolbar): __gsignals__ = { "speed-changed": (GObject.SIGNAL_RUN_FIRST, None, [float]), } def __init__(self): Gtk.Toolbar.__init__(self) self.button = ToolbarButton(page=self, icon_name="media-playback-stop") self.playing = True self.speed = None self.stop_play = ToolButton("media-playback-stop") self.stop_play.set_tooltip(_("Stop")) self.stop_play.connect("clicked", self._stop_play) self.insert(self.stop_play, -1) self.slow_button = RadioToolButton(group=None, icon_name="slow-walk-milton-raposo") self.slow_button.set_tooltip(_("Run slow")) self.slow_button.connect("clicked", self._speed_changed_cb, Speed.SLOW) self.insert(self.slow_button, -1) self.normal_button = RadioToolButton(group=self.slow_button, icon_name="walking") self.normal_button.set_tooltip(_("Run Normal")) self.normal_button.connect("clicked", self._speed_changed_cb, Speed.NORMAL) self.insert(self.normal_button, -1) self.fast_button = RadioToolButton(group=self.slow_button, icon_name="running") self.fast_button.set_tooltip(_("Run fast")) self.fast_button.connect("clicked", self._speed_changed_cb, Speed.FAST) self.insert(self.fast_button, -1) self.slow_button.set_active(True) self.show_all() def _stop_play(self, button=None): self.playing = not self.playing if self.playing: self.stop_play.set_icon_name("media-playback-stop") self.stop_play.set_tooltip(_("Stop")) self.button.set_icon_name("media-playback-stop") if self.speed is None: self.speed = Speed.SLOW self.emit("speed-changed", self.speed) else: self.stop_play.set_icon_name("media-playback-start") self.stop_play.set_tooltip(_("Start")) self.button.set_icon_name("media-playback-start") self.emit("speed-changed", Speed.STOPPED) def _speed_changed_cb(self, button, speed): if not self.playing: self.speed = speed self._stop_play() else: self.emit("speed-changed", speed) self.speed = speed def enable(self): self.set_sensitive_buttons(True) def disable(self): self.set_sensitive_buttons(False) def set_sensitive_buttons(self, sensitive): self.stop_play.set_sensitive(sensitive) self.slow_button.set_sensitive(sensitive) self.normal_button.set_sensitive(sensitive) self.fast_button.set_sensitive(sensitive)
def __init__(self, handle): activity.Activity.__init__(self, handle) GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.close) Gst.init(None) self._what_list = [] self.play_recording_thread = None self.playing_recording = False self.firstTime = False self.playing = False self.regularity = 0.7 self._drums_store = [] self.recording = False self.recorded_keys = [] self.is_valid_recording = False # we do not have collaboration features # make the share option insensitive self.max_participants = 1 self.csnd = new_csound_client() self.rythmInstrument = 'drum1kick' # toolbar with the new toolbar redesign toolbar_box = ToolbarBox() activity_button = ActivityToolbarButton(self) toolbar_box.toolbar.insert(activity_button, 0) toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ) self.play_index = 0 self.play_recording_button = ToolButton( icon_name='media-playback-start') self.play_recording_button.set_property('can-default', True) self.play_recording_button.show() self.record_button = ToggleToolButton(icon_name='media-record') self.record_button.set_property('can-default', True) self.record_button.show() self.play_recording_button.set_sensitive(False) self.record_button.connect('clicked', self.__record_button_click_cb) self.play_recording_button.connect('clicked', self.handlePlayRecordingButton) toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ) # TODO: disabe until is implemented with csnd6 # self.createPercussionToolbar(toolbar_box) toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1) keybord_labels = RadioToolButton() keybord_labels.props.icon_name = 'q_key' keybord_labels.props.group = keybord_labels keybord_labels.connect('clicked', self.set_keyboard_labels_cb) toolbar_box.toolbar.insert(keybord_labels, -1) notes_labels = RadioToolButton() notes_labels.props.icon_name = 'do_key' notes_labels.props.group = keybord_labels notes_labels.connect('clicked', self.set_notes_labels_cb) toolbar_box.toolbar.insert(notes_labels, -1) ti_notes_labels = RadioToolButton() ti_notes_labels.props.icon_name = 'ti_key' ti_notes_labels.props.group = keybord_labels ti_notes_labels.connect('clicked', self.set_ti_notes_labels_cb) toolbar_box.toolbar.insert(ti_notes_labels, -1) german_labels = RadioToolButton() german_labels.props.icon_name = 'c_key' german_labels.props.group = keybord_labels german_labels.connect('clicked', self.set_german_labels_cb) toolbar_box.toolbar.insert(german_labels, -1) no_labels = RadioToolButton() no_labels.props.icon_name = 'edit-clear' no_labels.props.group = keybord_labels no_labels.connect('clicked', self.set_keyboard_no_labels_cb) toolbar_box.toolbar.insert(no_labels, -1) self._what_widget = Gtk.ToolItem() self._what_search_button = FilterToolItem(_('Select Instrument'), 'view-type', _('Piano'), self._what_widget) self._what_widget.show() toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1) toolbar_box.toolbar.insert(self._what_search_button, -1) self._what_search_button.show() self._what_search_button.set_is_important(True) self._what_widget_contents = None self._what_drum_widget_contents = None separator = Gtk.SeparatorToolItem() toolbar_box.toolbar.insert(separator, -1) toolbar_box.toolbar.insert(self.record_button, -1) toolbar_box.toolbar.insert(self.play_recording_button, -1) separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) toolbar_box.toolbar.insert(separator, -1) stop_button = StopButton(self) toolbar_box.toolbar.insert(stop_button, -1) stop_button.show() self._save_as_audio_bt = ToolButton(icon_name='save-as-audio') self._save_as_audio_bt.props.tooltip = _('Save as audio') self._save_as_audio_bt.connect('clicked', self._save_ogg_cb) self._save_as_audio_bt.show() self._save_as_audio_bt.set_sensitive(False) activity_button.page.insert(self._save_as_audio_bt, -1) self.set_toolbar_box(toolbar_box) toolbar_box.show_all() self.keyboard_letters = ['ZSXDCVGBHNJM', 'Q2W3ER5T6Y7U', 'I'] notes = [ 'DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA', ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'SIb'], 'SI' ] self.notes_labels = [notes, notes, ['DO']] # some countries use TI instead of SI ti_notes = [ 'DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA', ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'TIb'], 'TI' ] self.ti_notes_labels = [ti_notes, ti_notes, ['DO']] german_notes = [ 'C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F', ['F#', 'Gb'], 'G', ['G#', 'Ab'], 'A', ['A#', 'Bb'], 'B' ] self.german_labels = [german_notes, german_notes, ['C']] self.piano = PianoKeyboard(octaves=2, add_c=True, labels=self.keyboard_letters) # init csound self.instrumentDB = InstrumentDB.getRef() self.timeout_ms = 50 self.instVolume = 50 self.drumVolume = 0.5 self.instrument = 'piano' self.beat = 4 self.reverb = 0.1 self.tempo = PLAYER_TEMPO self.beatDuration = 60.0 / self.tempo self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0 self.sequencer = MiniSequencer(self.recordStateButton, self.recordOverSensitivity) self.loop = Loop(self.beat, math.sqrt(self.instVolume * 0.01)) self.drumFillin = Fillin(self.beat, self.tempo, self.rythmInstrument, self.reverb, self.drumVolume) self.muteInst = False self.csnd.setTempo(self.tempo) self.noteList = [] for i in range(21): self.csnd.setTrackVolume(100, i) # TODO commented because apparently are not used in the activity # for i in range(10): # self.csnd.load_instrument('guidice' + str(i + 1)) self.volume = 100 self.csnd.setMasterVolume(self.volume) self.enableKeyboard() self.setInstrument(self.instrument) self.connect('key-press-event', self.onKeyPress) self.connect('key-release-event', self.onKeyRelease) self.piano.connect('key_pressed', self.__key_pressed_cb) self.piano.connect('key_released', self.__key_released_cb) vbox = Gtk.VBox() vbox.set_homogeneous(False) self.load_instruments() self._event_box = Gtk.EventBox() self._event_box.modify_bg(Gtk.StateType.NORMAL, style.COLOR_WHITE.get_gdk_color()) vbox.pack_start(self._event_box, False, False, 0) vbox.pack_end(self.piano, True, True, 0) vbox.show_all() self.set_canvas(vbox) piano_height = Gdk.Screen.width() / 2 self._event_box.set_size_request( -1, Gdk.Screen.height() - piano_height - style.GRID_CELL_SIZE) self.connect('size-allocate', self.__allocate_cb)
class ViewToolbar(Gtk.Toolbar): __gtype_name__ = 'SugarViewToolbar' __gsignals__ = { 'query-changed': (GObject.SignalFlags.RUN_FIRST, None, ([str])), 'view-changed': (GObject.SignalFlags.RUN_FIRST, None, ([object])), } def __init__(self): Gtk.Toolbar.__init__(self) self._favorites_views_indicies = [] for i in range(desktop.get_number_of_views()): self._favorites_views_indicies.append(i) self._list_view_index = self._favorites_views_indicies[-1] + 1 self._desktop_model = desktop.get_model() self._desktop_model.connect('desktop-view-icons-changed', self.__desktop_view_icons_changed_cb) self._query = None self._autosearch_timer = None self._add_separator() tool_item = Gtk.ToolItem() self.insert(tool_item, -1) tool_item.show() self.search_entry = iconentry.IconEntry() self.search_entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY, 'entry-search') self.set_placeholder_text_for_view(_('Home')) self.search_entry.add_clear_button() self.search_entry.set_width_chars(25) self.search_entry.connect('activate', self._entry_activated_cb) self.search_entry.connect('changed', self._entry_changed_cb) tool_item.add(self.search_entry) self.search_entry.show() self._add_separator(expand=True) self._button_box = Gtk.HBox() self._favorites_buttons = [] for i in range(desktop.get_number_of_views()): self._add_favorites_button(i) toolitem = Gtk.ToolItem() toolitem.add(self._button_box) self.insert(toolitem, -1) self._button_box.show() toolitem.show() self._list_button = RadioToolButton(icon_name='view-list') self._list_button.props.group = self._favorites_buttons[0] self._list_button.props.tooltip = _('List view') self._list_button.props.accelerator = \ _('<Ctrl>%d' % (len(self._favorites_views_indicies) + 1)) self._list_view_toggle_id = self._list_button.connect( 'toggled', self.__view_button_toggled_cb, self._list_view_index) self.insert(self._list_button, -1) self._add_separator() def _add_favorites_button(self, i): logging.debug('adding FavoritesButton %d' % (i)) self._favorites_buttons.append(FavoritesButton(i)) self._favorites_buttons[i].connect('toggled', self.__view_button_toggled_cb, self._favorites_views_indicies[i]) if i > 0: self._favorites_buttons[i].props.group = self._favorites_buttons[0] self._button_box.add(self._favorites_buttons[i]) self._favorites_buttons[i].show() def show_view_buttons(self): for i in range(desktop.get_number_of_views()): self._favorites_buttons[i].show() self._list_button.show() def hide_view_buttons(self): for i in range(desktop.get_number_of_views()): self._favorites_buttons[i].hide() self._list_button.hide() def clear_query(self): self.search_entry.props.text = '' def set_placeholder_text_for_view(self, view_name): text = _('Search in %s') % view_name self.search_entry.set_placeholder_text(text) def _add_separator(self, expand=False): separator = Gtk.SeparatorToolItem() separator.props.draw = False if expand: separator.set_expand(True) else: separator.set_size_request(style.GRID_CELL_SIZE, style.GRID_CELL_SIZE) self.insert(separator, -1) separator.show() def _entry_activated_cb(self, entry): if self._autosearch_timer: GObject.source_remove(self._autosearch_timer) new_query = entry.props.text if self._query != new_query: self._query = new_query self.emit('query-changed', self._query) def _entry_changed_cb(self, entry): if not entry.props.text: entry.activate() return if self._autosearch_timer: GObject.source_remove(self._autosearch_timer) self._autosearch_timer = GObject.timeout_add(_AUTOSEARCH_TIMEOUT, self._autosearch_timer_cb) def _autosearch_timer_cb(self): logging.debug('_autosearch_timer_cb') self._autosearch_timer = None self.search_entry.activate() return False def __view_button_toggled_cb(self, button, view): if button.props.active: self.emit('view-changed', view) def __desktop_view_icons_changed_cb(self, model): number_of_views = desktop.get_number_of_views() if len(self._favorites_views_indicies) < number_of_views: for i in range(number_of_views - len(self._favorites_views_indicies)): n = len(self._favorites_views_indicies) self._favorites_views_indicies.append(n) self._add_favorites_button(n) self._favorites_buttons[n].show() elif number_of_views < len(self._favorites_views_indicies): for i in range( len(self._favorites_views_indicies) - number_of_views): n = len(self._favorites_views_indicies) - 1 logging.debug('removing FavoritesButton %d' % (n)) button = self._favorites_buttons[n] self._favorites_buttons.remove(button) button.destroy() self._favorites_views_indicies.remove( self._favorites_views_indicies[n]) self._button_box.show() self._list_view_index = number_of_views self._list_button.props.accelerator = \ _('<Ctrl>%d' % (len(self._favorites_views_indicies) + 1)) self._list_button.disconnect(self._list_view_toggle_id) self._list_view_toggle_id = self._list_button.connect( 'toggled', self.__view_button_toggled_cb, self._list_view_index) self._list_button.show()
class ConvertActivity(activity.Activity): def __init__(self, handle): activity.Activity.__init__(self, handle, True) self.max_participants = 1 self.dic = {} # Canvas self._canvas = Gtk.VBox() hbox = Gtk.HBox() self._liststore1 = Gtk.ListStore(str) self.combo1 = Gtk.ComboBox(self._liststore1) cell = Gtk.CellRendererText() self.combo1.pack_start(cell, True) self.combo1.add_attribute(cell, 'markup', 0) self.combo1.connect('changed', self._call) flip_btn = Gtk.Button() flip_btn.connect('clicked', self._flip) flip_btn.add(Gtk.image_new_from_file('icons/flip.svg')) self._liststore2 = Gtk.ListStore(str) self.combo2 = Gtk.ComboBox(self._liststore1) cell = Gtk.CellRendererText() self.combo2.pack_start(cell, True) self.combo2.add_attribute(cell, 'markup', 0) self.combo2.connect('changed', self._call) self.label_box = Gtk.HBox() self.adjustment = Gtk.Adjustment(1.0, 0.0000000001, 10.0 ** 20.0, 0.1, 1.0) self.spin = Gtk.SpinButton(self.adjustment, 0.0, 2) self.label = Gtk.Label() self.label.set_selectable(True) self.label._size = 12 self.label.connect('expose-event', self.resize_label) self.convert_btn = Gtk.Button(_('Convert')) self.convert_btn.connect('clicked', self._call) self._canvas.pack_start(hbox, False, False, 20) hbox.pack_start(self.combo1, False, True, 20) hbox.pack_start(flip_btn, True, False) hbox.pack_end(self.combo2, False, True, 20) spin_box = Gtk.HBox() convert_box = Gtk.HBox() convert_box.pack_start(spin_box, True, False, 0) spin_box.pack_start(self.spin, False, False, 0) self._canvas.pack_start(convert_box, False, False, 5) self._canvas.pack_start(self.label_box, True, False, 0) self.label_box.add(self.label) spin_box.pack_start(self.convert_btn, False, False, 20) self.set_canvas(self._canvas) # Toolbar toolbarbox = ToolbarBox() activity_button = ActivityToolbarButton(self) toolbarbox.toolbar.insert(activity_button, 0) separator = Gtk.SeparatorToolItem() separator.set_expand(False) separator.set_draw(True) toolbarbox.toolbar.insert(separator, -1) # RadioToolButton self._length_btn = RadioToolButton() self._length_btn.connect('clicked', lambda w: self._update_combo(convert.length)) # TRANS: https://en.wikipedia.org/wiki/Length self._length_btn.set_tooltip(_('Length')) self._length_btn.props.icon_name = 'length' self._volume_btn = RadioToolButton() self._volume_btn.connect('clicked', lambda w: self._update_combo(convert.volume)) # TRANS: https://en.wikipedia.org/wiki/Volume self._volume_btn.set_tooltip(_('Volume')) self._volume_btn.props.icon_name = 'volume' self._volume_btn.props.group = self._length_btn self._area_btn = RadioToolButton() self._area_btn.connect('clicked', lambda w: self._update_combo(convert.area)) # TRANS: https://en.wikipedia.org/wiki/Area self._area_btn.set_tooltip(_('Area')) self._area_btn.props.icon_name = 'area' self._area_btn.props.group = self._length_btn self._weight_btn = RadioToolButton() self._weight_btn.connect('clicked', lambda w: self._update_combo(convert.weight)) # TRANS: https://en.wikipedia.org/wiki/Weight self._weight_btn.set_tooltip(_('Weight')) self._weight_btn.props.icon_name = 'weight' self._weight_btn.props.group = self._length_btn self._speed_btn = RadioToolButton() self._speed_btn.connect('clicked', lambda w: self._update_combo(convert.speed)) # TRANS: https://en.wikipedia.org/wiki/Speed self._speed_btn.set_tooltip(_('Speed')) self._speed_btn.props.icon_name = 'speed' self._speed_btn.props.group = self._length_btn self._time_btn = RadioToolButton() self._time_btn.connect('clicked', lambda w: self._update_combo(convert.time)) # TRANS: https://en.wikipedia.org/wiki/Time self._time_btn.set_tooltip(_('Time')) self._time_btn.props.icon_name = 'time' self._time_btn.props.group = self._length_btn self._temp_btn = RadioToolButton() self._temp_btn.connect('clicked', lambda w: self._update_combo(convert.temp)) # TRANS: https://en.wikipedia.org/wiki/Temperature self._temp_btn.set_tooltip(_('Temperature')) self._temp_btn.props.icon_name = 'temp' self._temp_btn.props.group = self._length_btn toolbarbox.toolbar.insert(self._length_btn, -1) toolbarbox.toolbar.insert(self._volume_btn, -1) toolbarbox.toolbar.insert(self._area_btn, -1) toolbarbox.toolbar.insert(self._weight_btn, -1) toolbarbox.toolbar.insert(self._speed_btn, -1) toolbarbox.toolbar.insert(self._time_btn, -1) toolbarbox.toolbar.insert(self._temp_btn, -1) separator = Gtk.SeparatorToolItem() separator.set_expand(True) separator.set_draw(False) toolbarbox.toolbar.insert(separator, -1) stopbtn = StopButton(self) toolbarbox.toolbar.insert(stopbtn, -1) self.set_toolbar_box(toolbarbox) self._update_combo(convert.length) self.show_all() def _update_label(self): try: spin_value = str(self.spin.get_value()) decimals = str(len(spin_value.split('.')[-1])) fmt = '%.' + decimals + 'f' new_value = locale.format(fmt, float(spin_value)) convert_value = str(self.convert()) decimals = str(len(convert_value.split('.')[-1])) fmt = '%.' + decimals + 'f' new_convert = locale.format(fmt, float(convert_value)) text = '%s ~ %s' % (new_value, new_convert) self.label.set_text(text) except KeyError: pass def _call(self, widget=None): self._update_label() self.show_all() def _update_combo(self, data): self._liststore1.clear() self._liststore2.clear() self.dic = data keys = self.dic.keys() keys.sort() for x in keys: symbol = '' if len(self.dic[x]) == 3: symbol = self.dic[x][-1] symbol = '<sup><b>%s</b></sup>' % symbol self._liststore1.append(['%s%s' % (x, symbol)]) self._liststore2.append(['%s%s' % (x, symbol)]) self.combo1.set_active(0) self.combo2.set_active(0) self._call() self.show_all() def _get_active_text(self, combobox): active = combobox.get_active() keys = self.dic.keys() keys.sort() if active < 0: return None text = keys[active] if '<sup>' in text: text = text.split('<b>')[1].split('</b>')[0] return text def _flip(self, widget): active_combo1 = self.combo1.get_active() active_combo2 = self.combo2.get_active() self.combo1.set_active(active_combo2) self.combo2.set_active(active_combo1) value = float(self.label.get_text().split(' ~ ')[1].replace(',', '.')) self.spin.set_value(value) self._call() def resize_label(self, widget, event): num_label = len(self.label.get_text()) try: size = str((60 * SCREEN_WIDTH / 100) / num_label) if not size == self.label._size: self.label.modify_font(pango.FontDescription(size)) self.label._size = size except ZeroDivisionError: pass def convert(self): number = float(self.spin.get_text().replace(',', '.')) unit = self._get_active_text(self.combo1) to_unit = self._get_active_text(self.combo2) return convert.convert(number, unit, to_unit, self.dic)
def __init__(self, title, bundle_path, document_path, sugar_toolkit_path): Gtk.Toolbar.__init__(self) document_button = None self.bundle_path = bundle_path self.sugar_toolkit_path = sugar_toolkit_path self._add_separator() activity_bundle = ActivityBundle(bundle_path) file_name = activity_bundle.get_icon() if document_path is not None and os.path.exists(document_path): document_button = DocumentButton(file_name, document_path, title) document_button.connect('toggled', self.__button_toggled_cb, document_path) self.insert(document_button, -1) document_button.show() self._add_separator() if bundle_path is not None and os.path.exists(bundle_path): activity_button = DocumentButton(file_name, bundle_path, title, bundle=True) icon = Icon(file=file_name, icon_size=Gtk.IconSize.LARGE_TOOLBAR, fill_color=style.COLOR_TRANSPARENT.get_svg(), stroke_color=style.COLOR_WHITE.get_svg()) activity_button.set_icon_widget(icon) icon.show() if document_button is not None: activity_button.props.group = document_button activity_button.props.tooltip = _('Activity Bundle Source') activity_button.connect('toggled', self.__button_toggled_cb, bundle_path) self.insert(activity_button, -1) activity_button.show() self._add_separator() if sugar_toolkit_path is not None: sugar_button = RadioToolButton() icon = Icon(icon_name='computer-xo', icon_size=Gtk.IconSize.LARGE_TOOLBAR, fill_color=style.COLOR_TRANSPARENT.get_svg(), stroke_color=style.COLOR_WHITE.get_svg()) sugar_button.set_icon_widget(icon) icon.show() if document_button is not None: sugar_button.props.group = document_button else: sugar_button.props.group = activity_button sugar_button.props.tooltip = _('Sugar Toolkit Source') sugar_button.connect('toggled', self.__button_toggled_cb, sugar_toolkit_path) self.insert(sugar_button, -1) sugar_button.show() self._add_separator() self.activity_title_text = _('View source: %s') % title self.sugar_toolkit_title_text = _('View source: %r') % 'Sugar Toolkit' self.label = Gtk.Label() self.label.set_markup('<b>%s</b>' % self.activity_title_text) self.label.set_alignment(0, 0.5) self._add_widget(self.label) self._add_separator(True) stop = ToolButton(icon_name='dialog-cancel') stop.set_tooltip(_('Close')) stop.connect('clicked', self.__stop_clicked_cb) self.insert(stop, -1) stop.show()
window.add(box) box.show() def echo(button, label): if not button.props.active: return print label palette = RadioPalette() # Adding 3 RadioToolButtons to a palette button1 = RadioToolButton(icon_name='document-save', accelerator="<ctrl>S", xo_color=XoColor("white")) button1.connect('toggled', lambda button: echo(button, 'document-save')) palette.append(button1, 'menu.document-save') button2 = RadioToolButton(icon_name='document-open', accelerator="<ctrl>O", xo_color=XoColor("white"), group=button1) button2.connect('toggled', lambda button: echo(button, 'document-open')) palette.append(button2, 'menu.document-open') button3 = RadioToolButton(icon_name='document-send', accelerator="<ctrl>F", xo_color=XoColor("white"), group=button1) button3.connect('toggled', lambda button: echo(button, 'document-send')) palette.append(button3, 'menu.document-send') button = RadioMenuButton(palette=palette) box.pack_start(button, False, False, 1) button.show()
class ActionButtons(): ''' This class manages the action buttons that move among toolsbars ''' def __init__(self, parent): self._main_toolbar = parent.get_toolbar_box().toolbar self._main_area = parent._main_area self._erase_button = parent.edit_toolbar.erase_button self._sw = parent._sw if HASTOOLBARBOX: target_toolbar = self._main_toolbar else: target_toolbar = self.parent.edit_toolbar self._mods = RadioToolButton(icon_name='select-mode') self._mods.set_tooltip(_('Select thoughts')) self._mods.set_accelerator(_('<ctrl>e')) self._mods.connect('clicked', parent.mode_cb, MMapArea.MODE_NULL) target_toolbar.insert(self._mods, -1) self._link_button = RadioToolButton(icon_name='link', group=self._mods) self._link_button.set_tooltip(_('Link/unlink two selected thoughts')) self._link_button.set_accelerator(_('<ctrl>l')) self._link_button.connect('clicked', self.__link_cb) target_toolbar.insert(self._link_button, -1) self.move_button = RadioToolButton(icon_name='move', group=self._mods) self.move_button.set_tooltip(_('Move selected thoughs')) self.move_button.set_accelerator(_('<ctrl>m')) self.move_button.connect('clicked', self.__move_cb) target_toolbar.insert(self.move_button, -1) self.drag_button = RadioToolButton(icon_name='drag', group=self._mods) self.drag_button.set_tooltip(_('Scroll the screen')) self.drag_button.connect('clicked', self.__drag_cb) target_toolbar.insert(self.drag_button, -1) if HASTOOLBARBOX: self._separator_2 = Gtk.SeparatorToolItem() self._separator_2.props.draw = False #self._separator_2.set_size_request(0, -1) self._separator_2.set_expand(True) self._separator_2.show() target_toolbar.insert(self._separator_2, -1) self._stop_button = StopButton(parent) target_toolbar.insert(self._stop_button, -1) def stop_dragging(self): if self._main_area.is_dragging(): self._main_area.drag_menu_cb(self._sw, False) def _stop_moving(self): self._main_area.move_mode = False def __link_cb(self, widget): self._stop_moving() self.stop_dragging() self._main_area.link_menu_cb() def __move_cb(self, widget): self.stop_dragging() if self._main_area.move_mode: self._main_area.stop_moving() else: self._main_area.start_moving(self.move_button) self._erase_button.set_sensitive(False) def __drag_cb(self, widget): # If we were moving, stop self._stop_moving() if not self._main_area.is_dragging(): self._main_area.drag_menu_cb(self._sw, True) else: self.stop_dragging() self._erase_button.set_sensitive(False) def reconfigure(self): ''' If screen width has changed, we may need to reconfigure the toolbars ''' if not HASTOOLBARBOX: return if hasattr(self, '_separator_2'): if Gdk.Screen.width() / 13 > style.GRID_CELL_SIZE: if self._separator_2.get_parent() is None: self._main_toolbar.remove(self._stop_button) self._main_toolbar.insert(self._separator_2, -1) self._main_toolbar.insert(self._stop_button, -1) else: self._main_toolbar.remove(self._separator_2)
def __init__(self, model, alerts=None): SectionView.__init__(self) self._model = model self._images_loaded = False self._append_to_store_sid = None self.connect('realize', self.__realize_cb) self.connect('unrealize', self.__unrealize_cb) self.set_border_width(style.DEFAULT_SPACING * 2) self.set_spacing(style.DEFAULT_SPACING) label_box = Gtk.Box() label_bg = Gtk.Label(label=_('Select a background:')) label_bg.modify_fg(Gtk.StateType.NORMAL, style.COLOR_SELECTION_GREY.get_gdk_color()) label_bg.show() label_box.pack_start(label_bg, False, True, 0) label_box.show() self.pack_start(label_box, False, True, 1) clear_button = Gtk.Button() clear_button.set_label(_('Clear background')) clear_button.connect('clicked', self._clear_clicked_cb) clear_button.show() self.pack_end(clear_button, False, True, 0) scrolled_window = Gtk.ScrolledWindow() scrolled_window.set_shadow_type(Gtk.ShadowType.ETCHED_IN) scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.pack_start(scrolled_window, True, True, 0) scrolled_window.show() self._store = Gtk.ListStore(GdkPixbuf.Pixbuf, str) self._icon_view = Gtk.IconView.new_with_model(self._store) self._icon_view.set_selection_mode(Gtk.SelectionMode.SINGLE) self._icon_view.connect('selection-changed', self._background_selected) self._icon_view.set_pixbuf_column(0) self._icon_view.grab_focus() scrolled_window.add(self._icon_view) self._icon_view.show() alpha = self._model.get_background_alpha_level() alpha_box = Gtk.HBox() alpha_buttons = [] alpha_icons = [[1.0, 'network-wireless-000'], [0.8, 'network-wireless-020'], [0.6, 'network-wireless-040'], [0.4, 'network-wireless-060'], [0.2, 'network-wireless-080']] for value, icon_name in alpha_icons: if len(alpha_buttons) > 0: button = RadioToolButton(group=alpha_buttons[0]) else: button = RadioToolButton(group=None) button.set_icon_name(icon_name) button.value = value button.props.active = value == alpha button.show() alpha_box.pack_start(button, False, True, 0) alpha_buttons.append(button) for button in alpha_buttons: button.connect('toggled', self._set_alpha_cb) alpha_alignment = Gtk.Alignment() alpha_alignment.set(0.5, 0, 0, 0) alpha_alignment.add(alpha_box) alpha_box.show() self.pack_start(alpha_alignment, False, False, 0) alpha_alignment.show() self._paths_list = [] file_paths = [] for directory in self._model.BACKGROUNDS_DIRS: if directory is not None and os.path.exists(directory): for root, dirs, files in os.walk(directory): for file_ in files: file_paths.append(os.path.join(root, file_)) self._append_to_store(file_paths) self.setup()
class Record(activity.Activity): def __init__(self, handle): activity.Activity.__init__(self, handle) if Gst.version() == (1, 0, 10, 0): return self._incompatible() # for fullscreen feature, use local rather than toolkit self.props.enable_fullscreen_mode = False self._state = None Instance(self) # the main classes self.model = Model(self) self.ui_init() # CSCL self.connect("shared", self._shared_cb) if self.get_shared_activity(): # have you joined or shared this activity yourself? if self.get_shared(): self._joined_cb(self) else: self.connect("joined", self._joined_cb) # Changing to the first toolbar kicks off the rest of the setup if self.model.get_cameras(): self.model.change_mode(constants.MODE_PHOTO) else: self.model.change_mode(constants.MODE_AUDIO) # Start live video pipeline when the video window becomes visible def on_defer_cb(): self.model.set_visible(True) self.connect("notify::active", self.__active_cb) return False def on_event_cb(widget, event): if event.state == Gdk.VisibilityState.UNOBSCURED: GLib.timeout_add(50, on_defer_cb) self._media_view._video.disconnect_by_func(on_event_cb) self._media_view._video.add_events( Gdk.EventMask.VISIBILITY_NOTIFY_MASK) self._media_view._video.connect('visibility-notify-event', on_event_cb) def _incompatible(self): ''' Display abbreviated activity user interface with alert ''' toolbox = ToolbarBox() stop = StopButton(self) toolbox.toolbar.add(stop) self.set_toolbar_box(toolbox) title = _('Activity not compatible with this system.') msg = _('Please downgrade activity and try again.') alert = Alert(title=title, msg=msg) alert.add_button(0, 'Stop', Icon(icon_name='activity-stop')) self.add_alert(alert) label = Gtk.Label(_('Uh oh, GStreamer is too old.')) self.set_canvas(label) alert.connect('response', self.__incompatible_response_cb) stop.connect('clicked', self.__incompatible_stop_clicked_cb, alert) self.show_all() def __incompatible_stop_clicked_cb(self, button, alert): self.remove_alert(alert) def __incompatible_response_cb(self, alert, response): self.remove_alert(alert) self.close() def read_file(self, path): if hasattr(self, 'model'): self.model.read_file(path) def write_file(self, path): if hasattr(self, 'model'): self.model.write_file(path) def close(self, **kwargs): if hasattr(self, 'model'): self.model.close() activity.Activity.close(self, **kwargs) def __active_cb(self, widget, pspec): self.model.set_visible(self.props.active) def _shared_cb(self, activity): self.model.collab.set_activity_shared() def _joined_cb(self, activity): self.model.collab.joined() def ui_init(self): self._fullscreen = False self._showing_info = False # FIXME: if _thumb_tray becomes some kind of button group, we wouldn't # have to track which recd is active self._active_recd = None self.connect('key-press-event', self._key_pressed) self._active_toolbar_idx = 0 toolbar_box = ToolbarBox() self._activity_toolbar_button = ActivityToolbarButton(self) toolbar_box.toolbar.insert(self._activity_toolbar_button, 0) self.set_toolbar_box(toolbar_box) self._toolbar = self.get_toolbar_box().toolbar tool_group = None if self.model.get_cameras(): self._photo_button = RadioToolButton() self._photo_button.props.group = tool_group tool_group = self._photo_button self._photo_button.props.icon_name = 'camera-external' self._photo_button.props.label = _('Photo') self._photo_button.props.accelerator = '<ctrl>1' self._photo_button.props.tooltip = _( 'Picture camera mode\n\n' 'When the record button is pressed,\n' 'take one picture from the camera.') self._photo_button.mode = constants.MODE_PHOTO self._photo_button.connect('clicked', self._mode_button_clicked) self._toolbar.insert(self._photo_button, -1) self._video_button = RadioToolButton() self._video_button.props.group = tool_group self._video_button.props.icon_name = 'media-video' self._video_button.props.accelerator = '<ctrl>2' self._video_button.props.label = _('Video') self._video_button.props.tooltip = _( 'Video camera mode\n\n' 'When the record button is pressed,\n' 'take photographs many times a second,\n' 'and record sound using the microphone,\n' 'until the button is pressed again.') self._video_button.mode = constants.MODE_VIDEO self._video_button.connect('clicked', self._mode_button_clicked) self._toolbar.insert(self._video_button, -1) else: self._photo_button = None self._video_button = None self._audio_button = RadioToolButton() self._audio_button.props.group = tool_group self._audio_button.props.icon_name = 'media-audio' self._audio_button.props.accelerator = '<ctrl>3' self._audio_button.props.label = _('Audio') self._audio_button.props.tooltip = _( 'Audio recording mode\n\n' 'When the record button is pressed,\n' 'take one photograph,\n' 'and record sound using the microphone,\n' 'until the button is pressed again.') self._audio_button.mode = constants.MODE_AUDIO self._audio_button.connect('clicked', self._mode_button_clicked) self._toolbar.insert(self._audio_button, -1) self._toolbar.insert(Gtk.SeparatorToolItem(), -1) self._mirror_btn = ToggleToolButton('mirror-horizontal') self._mirror_btn.set_tooltip(_( 'Mirror view\n\n' 'Swap left for right, as if looking at a mirror.\n' 'Does not affect recording.')) self._mirror_btn.props.accelerator = '<ctrl>m' self._mirror_btn.show() self._mirror_btn.connect('toggled', self.__mirror_toggled_cb) self._toolbar.insert(self._mirror_btn, -1) self._toolbar_controls = RecordControl(self._toolbar) if self.model.get_cameras() and len(self.model.get_cameras()) > 1: switch_camera_btn = ToolButton('switch-camera') switch_camera_btn.set_tooltip(_('Switch camera')) switch_camera_btn.show() switch_camera_btn.connect('clicked', self.__switch_camera_click_cb) self._toolbar.insert(switch_camera_btn, -1) separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) self._toolbar.insert(separator, -1) self._toolbar.insert(StopButton(self), -1) self.get_toolbar_box().show_all() self._media_view = MediaView() self._media_view.connect('media-clicked', self._media_view_media_clicked) self._media_view.connect('pip-clicked', self._media_view_pip_clicked) self._media_view.connect('info-clicked', self._media_view_info_clicked) self._media_view.connect('fullscreen-clicked', self._media_view_fullscreen_clicked) self._media_view.connect('tags-changed', self._media_view_tags_changed) self._media_view.show() self._controls_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) trim_height_shutter_button = 7 self._controls_hbox.set_size_request(-1, style.GRID_CELL_SIZE + trim_height_shutter_button) self._shutter_button = ShutterButton() self._shutter_button.connect("clicked", self._shutter_clicked) self._shutter_button.modify_bg(Gtk.StateType.NORMAL, COLOR_BLACK) self._controls_hbox.pack_start(self._shutter_button, True, False, 0) self._countdown_image = CountdownImage() self._controls_hbox.pack_start(self._countdown_image, True, False, 0) self._play_button = PlayButton() self._play_button.connect('clicked', self._play_pause_clicked) self._controls_hbox.pack_start(self._play_button, False, True, 0) self._playback_scale = PlaybackScale(self.model) self._controls_hbox.pack_start(self._playback_scale, True, True, 0) self._progress = ProgressInfo() self._controls_hbox.pack_start(self._progress, True, True, 0) self._title_label = Gtk.Label() self._title_label.set_markup("<b><span foreground='white'>" + _('Title:') + '</span></b>') self._controls_hbox.pack_start(self._title_label, False, True, 0) self._title_entry = Gtk.Entry() self._title_entry.modify_bg(Gtk.StateType.INSENSITIVE, COLOR_BLACK) self._title_entry.connect('changed', self._title_changed) self._controls_hbox.pack_start(self._title_entry, expand=True, fill=True, padding=10) self._controls_hbox.show() height_tray = 150 # height of tray self._thumb_tray = HTray(hexpand=True, height_request=height_tray) self._thumb_tray.show() height = Gdk.Screen.height() - style.GRID_CELL_SIZE * 2 - \ height_tray - trim_height_shutter_button self._media_view.set_size_request(-1, height) self._grid = Gtk.Grid(orientation=Gtk.Orientation.VERTICAL) self._media_view.props.hexpand = True self._media_view.props.vexpand = True for row in [self._media_view, self._controls_hbox, self._thumb_tray]: self._grid.add(row) self._grid.modify_bg(Gtk.StateType.NORMAL, COLOR_BLACK) self._grid.show() self.set_canvas(self._grid) def set_title_visible(self, visible): self._grid.remove(self._controls_hbox) if visible: self._grid.attach_next_to(self._controls_hbox, self._media_view, Gtk.PositionType.TOP, 1, 1) else: self._grid.attach_next_to(self._controls_hbox, self._media_view, Gtk.PositionType.BOTTOM, 1, 1) def __switch_camera_click_cb(self, btn): self.model.switch_camera() def __mirror_toggled_cb(self, button): self.model.set_mirror(button.props.active) def serialize(self): data = {} data['timer'] = self._toolbar_controls.get_timer_idx() data['duration'] = self._toolbar_controls.get_duration_idx() data['quality'] = self._toolbar_controls.get_quality() return data def deserialize(self, data): self._toolbar_controls.set_timer_idx(data.get('timer', 0)) self._toolbar_controls.set_duration_idx(data.get('duration', 0)) self._toolbar_controls.set_quality(data.get('quality', 0)) def _key_pressed(self, widget, event): key = event.keyval ctrl = event.state & Gdk.ModifierType.CONTROL_MASK # while activity toolbar is visible, only escape key is taken if self._activity_toolbar_button.is_expanded(): if key == Gdk.KEY_Escape: self._activity_toolbar_button.set_expanded(False) return True return False # while title is focused, only escape key is taken if self._title_entry.is_focus(): if key == Gdk.KEY_Escape: self.model.set_state(constants.STATE_READY) return False # while info tags are focused, only escape key is taken if self._media_view.info_view.textview.is_focus(): if key == Gdk.KEY_Escape: self.model.set_state(constants.STATE_READY) return False if ctrl and key == Gdk.KEY_f: self._toggle_fullscreen() return True if ctrl and key == Gdk.KEY_s: self.model.glive.stop() return True if ctrl and key == Gdk.KEY_p: self.model.glive.play() return True if (ctrl and key == Gdk.KEY_space) or \ (ctrl and key == Gdk.KEY_r) or \ key == Gdk.KEY_KP_Page_Up: # game key O if self._shutter_button.props.visible: if self._shutter_button.props.sensitive: self._shutter_button.clicked() else: # return to live mode self.model.set_state(constants.STATE_READY) return True if key == Gdk.KEY_space and self._active_recd: if self._active_recd.type in (constants.TYPE_VIDEO, constants.TYPE_AUDIO): self.model.play_pause() return True # if viewing media, return to live mode if key == Gdk.KEY_Escape and self._active_recd: self.model.set_state(constants.STATE_READY) return True if self.model.ui_frozen(): return True if ctrl and key == Gdk.KEY_c: self._copy_to_clipboard(self._active_recd) return True if key == Gdk.KEY_i and self._active_recd: self._toggle_info() return True if key == Gdk.KEY_Escape and self._fullscreen: self._toggle_fullscreen() return True return False def _play_pause_clicked(self, widget): self.model.play_pause() def set_mode(self, mode): self._toolbar_controls.set_mode(mode) # can be called from GStreamer thread, so must not do any GTK+ stuff def set_glive_sink(self, sink): return self._media_view.set_video_sink(sink) # can be called from GStreamer thread, so must not do any GTK+ stuff def set_gplay_sink(self, sink): return self._media_view.set_video2_sink(sink) def get_selected_quality(self): return self._toolbar_controls.get_quality() def get_selected_timer(self): return self._toolbar_controls.get_timer() def get_selected_duration(self): return self._toolbar_controls.get_duration() * 60 # convert to secs def set_progress(self, value, text): self._progress.set_progress(value) self._progress.set_text(text) def set_countdown(self, value): if value == 0: self._shutter_button.show() self._countdown_image.hide() return self._shutter_button.hide() self._countdown_image.show() self._countdown_image.set_value(value) def _title_changed(self, widget): self._active_recd.setTitle(self._title_entry.get_text()) def _media_view_media_clicked(self, widget): if self._play_button.props.visible and \ self._play_button.props.sensitive: self._play_button.clicked() def _media_view_pip_clicked(self, widget): # clicking on the PIP always returns to live mode self.model.set_state(constants.STATE_READY) def _media_view_info_clicked(self, widget): self._toggle_info() def _toggle_info(self): recd = self._active_recd if not recd: return if self._showing_info: self._show_recd(recd, play=False) return self._showing_info = True still_modes = (constants.MODE_PHOTO, constants.MODE_AUDIO) if self.model.get_mode() in still_modes: func = self._media_view.show_info_photo else: func = self._media_view.show_info_video self._play_button.hide() self._progress.hide() self._playback_scale.hide() self._title_entry.set_text(recd.title) self._title_entry.show() self._title_label.show() self.set_title_visible(True) func(recd.recorderName, recd.colorStroke, recd.colorFill, utils.getDateString(recd.time), recd.tags) def _media_view_fullscreen_clicked(self, widget): # logger.debug('_media_view_fullscreen_clicked') self._toggle_fullscreen() def _media_view_tags_changed(self, widget, tbuffer): text = tbuffer.get_text(tbuffer.get_start_iter(), tbuffer.get_end_iter(), True) self._active_recd.setTags(text) def _toggle_fullscreen(self): # logger.debug('_toggle_fullscreen') self._fullscreen = not self._fullscreen if not self._active_recd: self.model.glive.stop() if self._fullscreen: self.get_toolbar_box().hide() self._thumb_tray.hide() if self._active_recd: self._controls_hbox.hide() else: self.get_toolbar_box().show() self._thumb_tray.show() self._controls_hbox.show() self._media_view.set_fullscreen(self._fullscreen) if self._active_recd: return if self.model.get_state() == constants.STATE_RECORDING: return # hack, reason unknown # problem: call to self.mode.glive.play() does not show live view # solution: defer until after VideoBox resize is complete self._timer_hid = None def on_timer_cb(): self.model.glive.play() self._timer_hid = None return False self._timer_hid = GLib.timeout_add(1000, on_timer_cb) def on_defer_cb(): self.model.glive.play() if self._timer_hid: GLib.source_remove(self._timer_hid) self._timer_hid = None return False def on_event_cb(widget, event): if event.state == Gdk.VisibilityState.UNOBSCURED: GLib.timeout_add(30, on_defer_cb) self._media_view._video.disconnect_by_func(on_event_cb) self._media_view._video.add_events( Gdk.EventMask.VISIBILITY_NOTIFY_MASK) self._media_view._video.connect('visibility-notify-event', on_event_cb) # FIXME: fullscreen toggle during video recording gives black # window, TODO: do the same as above for the video recording # pipeline when it is active def _mode_button_clicked(self, button): self.model.change_mode(button.mode) def _shutter_clicked(self, arg): self.model.do_shutter() def set_shutter_sensitive(self, value): self._shutter_button.set_sensitive(value) def set_state(self, state): radio_state = (state == constants.STATE_READY) for item in (self._photo_button, self._audio_button, self._video_button): if item: item.set_sensitive(radio_state) self._showing_info = False if state == constants.STATE_READY: if self._state == constants.STATE_PROCESSING: self.unbusy() self._active_recd = None self._mirror_btn.props.sensitive = True self._title_entry.hide() self._title_label.hide() self.set_title_visible(False) self._play_button.hide() self._playback_scale.hide() self._progress.hide() self._controls_hbox.set_child_packing(self._shutter_button, expand=True, fill=False, padding=0, pack_type=Gtk.PackType.START) self._shutter_button.set_normal() self._shutter_button.set_sensitive(True) self._shutter_button.show() self._media_view.show_live() elif state == constants.STATE_RECORDING: self._mirror_btn.props.sensitive = False self._shutter_button.set_recording() self._controls_hbox.set_child_packing(self._shutter_button, expand=False, fill=False, padding=0, pack_type=Gtk.PackType.START) self._progress.show() elif state == constants.STATE_PROCESSING: self.busy() self._shutter_button.hide() self._progress.show() elif state == constants.STATE_DOWNLOADING: self._shutter_button.hide() self._progress.show() self._state = state def set_paused(self, value): if value: self._play_button.set_play() else: self._play_button.set_pause() def _thumbnail_clicked(self, button, recd): if self.model.ui_frozen(): return self.model.abort_countdown() self.model.glive.stop() self._mirror_btn.props.sensitive = False self._active_recd = recd self._show_recd(recd) def add_thumbnail(self, recd): button = RecdButton(recd) clicked_handler = button.connect("clicked", self._thumbnail_clicked, recd) remove_handler = button.connect("remove-requested", self._remove_recd) clipboard_handler = button.connect("copy-clipboard-requested", self._thumbnail_copy_clipboard) button.handler_ids = (clicked_handler, remove_handler, clipboard_handler) button.show() self._thumb_tray.add_item(button) self._thumb_tray.scroll_to_item(button) # FIXME: possible toolkit bug; scroll_to_item is ineffective, # only noticed when the tray is full def _copy_to_clipboard(self, recd): if recd is None: return if not recd.isClipboardCopyable(): return clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) clipboard.set_image(recd.getCopyClipboardPixbuf()) def _thumbnail_copy_clipboard(self, recdbutton): self._copy_to_clipboard(recdbutton.get_recd()) def _remove_recd(self, recdbutton): recd = recdbutton.get_recd() self.model.delete_recd(recd) if self._active_recd == recd: self.model.set_state(constants.STATE_READY) self._remove_thumbnail(recdbutton) def _remove_thumbnail(self, recdbutton): for handler in recdbutton.handler_ids: recdbutton.disconnect(handler) self._thumb_tray.remove_item(recdbutton) recdbutton.cleanup() def show_still(self, pixbuf): self._media_view.show_still(pixbuf) def _show_photo(self, recd): path = self._get_photo_path(recd) self._media_view.show_photo(path) self._title_entry.set_text(recd.title) self._title_entry.show() self._title_label.show() self.set_title_visible(True) self._shutter_button.hide() self._progress.hide() def _show_audio(self, recd, play): self._progress.hide() self._shutter_button.hide() self._title_entry.hide() self._title_label.hide() self.set_title_visible(False) self._play_button.show() self._playback_scale.show() path = recd.getAudioImageFilepath() self._media_view.show_photo(path) if play: self.model.play_audio(recd) def _show_video(self, recd, play): self._progress.hide() self._shutter_button.hide() self._title_entry.hide() self._title_label.hide() self.set_title_visible(False) self._play_button.show() self._playback_scale.show() self._media_view.show_video() if play: self.model.play_video(recd) def set_playback_scale(self, value): self._playback_scale.set_value(value) def _get_photo_path(self, recd): # FIXME should live (partially) in recd? # downloading = self.ca.requestMeshDownload(recd) # self.MESHING = downloading if True: # not downloading: # self.progressWindow.updateProgress(0, "") return recd.getMediaFilepath() # maybe it is not downloaded from the mesh yet... # but we can show the low res thumb in the interim return recd.getThumbFilepath() def _show_recd(self, recd, play=True): self._showing_info = False if recd.buddy and not recd.downloadedFromBuddy: self.model.request_download(recd) elif recd.type == constants.TYPE_PHOTO: self._show_photo(recd) elif recd.type == constants.TYPE_AUDIO: self._show_audio(recd, play) elif recd.type == constants.TYPE_VIDEO: self._show_video(recd, play) def remote_recd_available(self, recd): self.model.set_state(constants.STATE_INVISIBLE) if recd == self._active_recd: self._show_recd(recd) def update_download_progress(self, recd): if recd != self._active_recd: return if not recd.meshDownloading: msg = _('Download failed.') elif recd.meshDownloadingProgress: msg = _('Downloading...') else: msg = _('Requesting...') self.set_progress(recd.meshDownlodingPercent, msg)
def __init__(self, handle): activity.Activity.__init__(self, handle) GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.close) Gst.init(None) self._what_list = [] self.play_recording_thread = None self.playing_recording = False self.firstTime = False self.playing = False self.regularity = 0.7 self._drums_store = [] self.recording = False self.recorded_keys = [] self.is_valid_recording = False # we do not have collaboration features # make the share option insensitive self.max_participants = 1 self.csnd = new_csound_client() self.rythmInstrument = 'drum1kick' # toolbar with the new toolbar redesign toolbar_box = ToolbarBox() activity_button = ActivityToolbarButton(self) toolbar_box.toolbar.insert(activity_button, 0) toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ) self.play_index = 0 self.play_recording_button = ToolButton( icon_name='media-playback-start') self.play_recording_button.set_property('can-default', True) self.play_recording_button.show() self.record_button = ToggleToolButton(icon_name='media-record') self.record_button.set_property('can-default', True) self.record_button.show() self.play_recording_button.set_sensitive(False) self.record_button.connect('clicked', self.__record_button_click_cb) self.play_recording_button.connect('clicked', self.handlePlayRecordingButton) toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ) # TODO: disabe until is implemented with csnd6 # self.createPercussionToolbar(toolbar_box) toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1) keybord_labels = RadioToolButton() keybord_labels.props.icon_name = 'q_key' keybord_labels.props.group = keybord_labels keybord_labels.connect('clicked', self.set_keyboard_labels_cb) toolbar_box.toolbar.insert(keybord_labels, -1) notes_labels = RadioToolButton() notes_labels.props.icon_name = 'do_key' notes_labels.props.group = keybord_labels notes_labels.connect('clicked', self.set_notes_labels_cb) toolbar_box.toolbar.insert(notes_labels, -1) ti_notes_labels = RadioToolButton() ti_notes_labels.props.icon_name = 'ti_key' ti_notes_labels.props.group = keybord_labels ti_notes_labels.connect('clicked', self.set_ti_notes_labels_cb) toolbar_box.toolbar.insert(ti_notes_labels, -1) german_labels = RadioToolButton() german_labels.props.icon_name = 'c_key' german_labels.props.group = keybord_labels german_labels.connect('clicked', self.set_german_labels_cb) toolbar_box.toolbar.insert(german_labels, -1) no_labels = RadioToolButton() no_labels.props.icon_name = 'edit-clear' no_labels.props.group = keybord_labels no_labels.connect('clicked', self.set_keyboard_no_labels_cb) toolbar_box.toolbar.insert(no_labels, -1) self._what_widget = Gtk.ToolItem() self._what_search_button = FilterToolItem(_('Select Instrument'), 'view-type', _('Piano'), self._what_widget) self._what_widget.show() toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1) toolbar_box.toolbar.insert(self._what_search_button, -1) self._what_search_button.show() self._what_search_button.set_is_important(True) self._what_widget_contents = None self._what_drum_widget_contents = None separator = Gtk.SeparatorToolItem() toolbar_box.toolbar.insert(separator, -1) toolbar_box.toolbar.insert(self.record_button, -1) toolbar_box.toolbar.insert(self.play_recording_button, -1) separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) toolbar_box.toolbar.insert(separator, -1) stop_button = StopButton(self) toolbar_box.toolbar.insert(stop_button, -1) stop_button.show() self._save_as_audio_bt = ToolButton(icon_name='save-as-audio') self._save_as_audio_bt.props.tooltip = _('Save as audio') self._save_as_audio_bt.connect('clicked', self._save_ogg_cb) self._save_as_audio_bt.show() self._save_as_audio_bt.set_sensitive(False) activity_button.page.insert(self._save_as_audio_bt, -1) self.set_toolbar_box(toolbar_box) toolbar_box.show_all() self.keyboard_letters = ['ZSXDCVGBHNJM', 'Q2W3ER5T6Y7U', 'I'] notes = ['DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA', ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'SIb'], 'SI'] self.notes_labels = [notes, notes, ['DO']] # some countries use TI instead of SI ti_notes = ['DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA', ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'TIb'], 'TI'] self.ti_notes_labels = [ti_notes, ti_notes, ['DO']] german_notes = ['C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F', ['F#', 'Gb'], 'G', ['G#', 'Ab'], 'A', ['A#', 'Bb'], 'B'] self.german_labels = [german_notes, german_notes, ['C']] self.piano = PianoKeyboard(octaves=2, add_c=True, labels=self.keyboard_letters) # init csound self.instrumentDB = InstrumentDB.getRef() self.timeout_ms = 50 self.instVolume = 50 self.drumVolume = 0.5 self.instrument = 'piano' self.beat = 4 self.reverb = 0.1 self.tempo = PLAYER_TEMPO self.beatDuration = 60.0 / self.tempo self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0 self.sequencer = MiniSequencer(self.recordStateButton, self.recordOverSensitivity) self.loop = Loop(self.beat, math.sqrt(self.instVolume * 0.01)) self.drumFillin = Fillin(self.beat, self.tempo, self.rythmInstrument, self.reverb, self.drumVolume) self.muteInst = False self.csnd.setTempo(self.tempo) self.noteList = [] for i in range(21): self.csnd.setTrackVolume(100, i) # TODO commented because apparently are not used in the activity # for i in range(10): # self.csnd.load_instrument('guidice' + str(i + 1)) self.volume = 100 self.csnd.setMasterVolume(self.volume) self.enableKeyboard() self.setInstrument(self.instrument) self.connect('key-press-event', self.onKeyPress) self.connect('key-release-event', self.onKeyRelease) self.piano.connect('key_pressed', self.__key_pressed_cb) self.piano.connect('key_released', self.__key_released_cb) vbox = Gtk.VBox() vbox.set_homogeneous(False) self.load_instruments() self._event_box = Gtk.EventBox() self._event_box.modify_bg( Gtk.StateType.NORMAL, style.COLOR_WHITE.get_gdk_color()) vbox.pack_start(self._event_box, False, False, 0) vbox.pack_end(self.piano, True, True, 0) vbox.show_all() self.set_canvas(vbox) piano_height = Gdk.Screen.width() / 2 self._event_box.set_size_request( -1, Gdk.Screen.height() - piano_height - style.GRID_CELL_SIZE) self.connect('size-allocate', self.__allocate_cb)
class ImageToolbar(Gtk.Toolbar): _EFFECT_RAINBOW_NAME = 'rainbow' _EFFECT_KALIDOSCOPE_NAME = 'kalidoscope' def __init__(self, activity): Gtk.Toolbar.__init__(self) self._activity = activity self.properties = self._activity.area.tool self._object_insert = ToolButton('insert-picture') self.insert(self._object_insert, -1) self._object_insert.set_tooltip(_('Insert Image')) separator = Gtk.SeparatorToolItem() separator.set_draw(True) self.insert(separator, -1) self.width_percent = 1. self.height_percent = 1. # FIXME: Sometimes we get the gnome icons not the sugar ones self._object_rotate_left = ToolButton('object-rotate-left-sugar') self.insert(self._object_rotate_left, -1) self._object_rotate_left.set_tooltip(_('Rotate Left')) self._object_rotate_right = ToolButton('object-rotate-right-sugar') self.insert(self._object_rotate_right, -1) self._object_rotate_right.set_tooltip(_('Rotate Right')) self._mirror_horizontal = ToolButton('mirror-horizontal') self.insert(self._mirror_horizontal, -1) self._mirror_horizontal.show() self._mirror_horizontal.set_tooltip(_('Horizontal Mirror')) self._mirror_vertical = ToolButton('mirror-vertical') self.insert(self._mirror_vertical, -1) self._mirror_vertical.show() self._mirror_vertical.set_tooltip(_('Vertical Mirror')) separator = Gtk.SeparatorToolItem() separator.set_draw(True) self.insert(separator, -1) self._effect_grayscale = ToolButton('effect-grayscale') self.insert(self._effect_grayscale, -1) self._effect_grayscale.set_tooltip(_('Grayscale')) self._effect_rainbow = RadioToolButton('effect-rainbow') self._effect_rainbow.props.group = activity.tool_group self.insert(self._effect_rainbow, -1) self._effect_rainbow.set_tooltip(_('Rainbow')) self._effect_kalidoscope = RadioToolButton('effect-kalidoscope') self._effect_kalidoscope.props.group = activity.tool_group self.insert(self._effect_kalidoscope, -1) self._effect_kalidoscope.set_tooltip(_('Kaleidoscope')) self._invert_colors = ToolButton('invert-colors') self.insert(self._invert_colors, -1) self._invert_colors.set_tooltip(_('Invert Colors')) self._object_insert.connect('clicked', self.insertImage, activity) self._object_rotate_left.connect('clicked', self.rotate_left, activity) self._object_rotate_right.connect('clicked', self.rotate_right, activity) self._mirror_vertical.connect('clicked', self.mirror_vertical) self._mirror_horizontal.connect('clicked', self.mirror_horizontal) self._effect_grayscale.connect('clicked', self.grayscale) self._effect_rainbow.connect('clicked', self.rainbow) self._effect_kalidoscope.connect('clicked', self.kalidoscope) self._invert_colors.connect('clicked', self.invert_colors) self.show_all() def rotate_left(self, widget, activity): activity.area.rotate_left(activity.area) def rotate_right(self, widget, activity): activity.area.rotate_right(activity.area) def mirror_horizontal(self, widget): self._activity.area.mirror(widget) def mirror_vertical(self, widget): self._activity.area.mirror(widget, horizontal=False) def insertImage(self, widget, activity): try: chooser = ObjectChooser(self._activity, what_filter='Image', filter_type=FILTER_TYPE_GENERIC_MIME, show_preview=True) except: # for compatibility with older versions chooser = ObjectChooser(self._activity, what_filter='Image') try: result = chooser.run() if result == Gtk.ResponseType.ACCEPT: logging.debug('ObjectChooser: %r', chooser.get_selected_object()) jobject = chooser.get_selected_object() if jobject and jobject.file_path: self._activity.area.load_image(jobject.file_path) finally: chooser.destroy() del chooser # Make the colors be in grayscale def grayscale(self, widget): self._activity.area.grayscale(widget) # Like the brush, but change it color when painting def rainbow(self, widget): self.properties['name'] = self._EFFECT_RAINBOW_NAME self._activity.area.set_tool(self.properties) def kalidoscope(self, widget): self.properties['name'] = self._EFFECT_KALIDOSCOPE_NAME self._activity.area.set_tool(self.properties) def invert_colors(self, widget): self._activity.area.invert_colors()
def __init__(self, title, bundle_path, document_path, sugar_toolkit_path): Gtk.Toolbar.__init__(self) document_button = None self.bundle_path = bundle_path self.sugar_toolkit_path = sugar_toolkit_path self._add_separator() activity_bundle = get_bundle_instance(bundle_path) file_name = activity_bundle.get_icon() activity_name = activity_bundle.get_name() if document_path is not None and os.path.exists(document_path): document_button = DocumentButton(file_name, document_path, activity_name, title) document_button.connect('toggled', self.__button_toggled_cb, document_path) self.insert(document_button, -1) document_button.show() self._add_separator() if bundle_path is not None and os.path.exists(bundle_path): activity_button = DocumentButton(file_name, bundle_path, activity_name, title, bundle=True) icon = Icon(file=file_name, pixel_size=style.STANDARD_ICON_SIZE, fill_color=style.COLOR_TRANSPARENT.get_svg(), stroke_color=style.COLOR_WHITE.get_svg()) activity_button.set_icon_widget(icon) icon.show() if document_button is not None: activity_button.props.group = document_button activity_button.props.tooltip = _('Activity Bundle Source') activity_button.connect('toggled', self.__button_toggled_cb, bundle_path) self.insert(activity_button, -1) activity_button.show() self._add_separator() if sugar_toolkit_path is not None: sugar_button = RadioToolButton() icon = Icon(icon_name='computer-xo', pixel_size=style.STANDARD_ICON_SIZE, fill_color=style.COLOR_TRANSPARENT.get_svg(), stroke_color=style.COLOR_WHITE.get_svg()) sugar_button.set_icon_widget(icon) icon.show() if document_button is not None: sugar_button.props.group = document_button else: sugar_button.props.group = activity_button sugar_button.props.tooltip = _('Sugar Toolkit Source') sugar_button.connect('toggled', self.__button_toggled_cb, sugar_toolkit_path) self.insert(sugar_button, -1) sugar_button.show() self._add_separator() self.activity_title_text = _('View source: %s') % title self.sugar_toolkit_title_text = _('View source: %r') % 'Sugar Toolkit' self.label = Gtk.Label() self.label.set_markup('<b>%s</b>' % self.activity_title_text) self.label.set_ellipsize(style.ELLIPSIZE_MODE_DEFAULT) self.label.set_alignment(0, 0.5) self._add_widget(self.label, expand=True) self._add_separator(False) stop = ToolButton(icon_name='dialog-cancel') stop.set_tooltip(_('Close')) stop.connect('clicked', self.__stop_clicked_cb) self.insert(stop, -1) stop.show()
class ReflectActivity(activity.Activity): ''' An activity for reflecting on one's work ''' def __init__(self, handle): ''' Initialize the toolbar ''' try: super(ReflectActivity, self).__init__(handle) except dbus.exceptions.DBusException as e: _logger.error(str(e)) logging.error('setting reflection data to []') self.reflection_data = [] self.connect('realize', self.__realize_cb) self.font_size = 8 self.max_participants = 4 self._setup_toolbars() color = profile.get_color() color_stroke = color.get_stroke_color() color_fill = color.get_fill_color() lighter = utils.lighter_color([color_stroke, color_fill]) darker = 1 - lighter if lighter == 0: self.bg_color = style.Color(color_stroke) self.fg_color = style.Color(color_fill) else: self.bg_color = style.Color(color_fill) self.fg_color = style.Color(color_stroke) self.modify_bg(Gtk.StateType.NORMAL, self.bg_color.get_gdk_color()) self.bundle_path = activity.get_bundle_path() self.tmp_path = os.path.join(activity.get_activity_root(), 'instance') self.sharing = False self._copy_entry = None self._paste_entry = None self._webkit = None self._clipboard_text = '' self._fixed = None self.initiating = True if self.shared_activity: # We're joining if not self.get_shared(): self.initiating = False self.busy_cursor() share_icon = Icon(icon_name='zoom-neighborhood') self._joined_alert = Alert() self._joined_alert.props.icon = share_icon self._joined_alert.props.title = _('Please wait') self._joined_alert.props.msg = _('Starting connection...') self.add_alert(self._joined_alert) # Wait for joined signal self.connect("joined", self._joined_cb) self._open_reflect_windows() self._setup_presence_service() # Joiners wait to receive data from sharer # Otherwise, load reflections from local store if not self.shared_activity: self.busy_cursor() GObject.idle_add(self._load_reflections) def read_file(self, file_path): fd = open(file_path, 'r') data = fd.read() fd.close() self.reflection_data = json.loads(data) def write_file(self, file_path): data = json.dumps(self.reflection_data) fd = open(file_path, 'w') fd.write(data) fd.close() self.metadata['font_size'] = str(self.font_size) def _load_reflections(self): self._find_starred() self._reflect_window.load(self.reflection_data) self.reset_cursor() def _found_obj_id(self, obj_id): for item in self.reflection_data: if 'obj_id' in item and item['obj_id'] == obj_id: return True return False def reload_data(self, data): ''' Reload data after sorting or searching ''' self._reflection_data = data[:] self._reflect_window.reload(self._reflection_data) self.reset_scrolled_window_adjustments() def _find_starred(self): ''' Find all the _stars in the Journal. ''' self.dsobjects, self._nobjects = datastore.find({'keep': '1'}) for dsobj in self.dsobjects: if self._found_obj_id(dsobj.object_id): continue # Already have this object -- TODO: update it self._add_new_from_journal(dsobj) def _add_new_from_journal(self, dsobj): self.reflection_data.append({ 'title': _('Untitled'), 'obj_id': dsobj.object_id }) if hasattr(dsobj, 'metadata'): if 'creation_time' in dsobj.metadata: self.reflection_data[-1]['creation_time'] = \ dsobj.metadata['creation_time'] else: self.reflection_data[-1]['creation_time'] = \ int(time.time()) if 'timestamp' in dsobj.metadata: self.reflection_data[-1]['modification_time'] = \ dsobj.metadata['timestamp'] else: self.reflection_data[-1]['modification_time'] = \ self.reflection_data[-1]['creation_time'] if 'activity' in dsobj.metadata: self.reflection_data[-1]['activities'] = \ [utils.bundle_id_to_icon(dsobj.metadata['activity'])] if 'title' in dsobj.metadata: self.reflection_data[-1]['title'] = \ dsobj.metadata['title'] if 'description' in dsobj.metadata: self.reflection_data[-1]['content'] = \ [{'text': dsobj.metadata['description']}] else: self.reflection_data[-1]['content'] = [] if 'tags' in dsobj.metadata: self.reflection_data[-1]['tags'] = [] tags = dsobj.metadata['tags'].split() for tag in tags: if tag[0] != '#': self.reflection_data[-1]['tags'].append('#' + tag) else: self.reflection_data[-1]['tags'].append(tag) if 'comments' in dsobj.metadata: try: comments = json.loads(dsobj.metadata['comments']) except BaseException: comments = [] self.reflection_data[-1]['comments'] = [] for comment in comments: try: data = { 'nick': comment['from'], 'comment': comment['message'] } if 'icon-color' in comment: colors = comment['icon-color'].split(',') darker = 1 - utils.lighter_color(colors) data['color'] = colors[darker] else: data['color'] = '#000000' self.reflection_data[-1]['comments'].append(data) except BaseException: _logger.debug('could not parse comment %s' % comment) if 'mime_type' in dsobj.metadata and \ dsobj.metadata['mime_type'][0:5] == 'image': new_path = os.path.join(self.tmp_path, dsobj.object_id) try: shutil.copy(dsobj.file_path, new_path) except Exception as e: logging.error("Couldn't copy %s to %s: %s" % (dsobj.file_path, new_path, e)) self.reflection_data[-1]['content'].append({'image': new_path}) elif 'preview' in dsobj.metadata: pixbuf = utils.get_pixbuf_from_journal(dsobj, 300, 225) if pixbuf is not None: path = os.path.join(self.tmp_path, dsobj.object_id + '.png') utils.save_pixbuf_to_file(pixbuf, path) self.reflection_data[-1]['content'].append({'image': path}) self.reflection_data[-1]['stars'] = 0 def delete_item(self, obj_id): for i, obj in enumerate(self.reflection_data): if obj['obj_id'] == obj_id: self.reflection_data.remove(self.reflection_data[i]) return def busy_cursor(self): self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH)) def reset_cursor(self): self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR)) def _open_reflect_windows(self): # Most things need only be done once if self._fixed is None: self._fixed = Gtk.Fixed() self._fixed.set_size_request(Gdk.Screen.width(), Gdk.Screen.height()) # Offsets from the bottom of the screen dy1 = 2 * style.GRID_CELL_SIZE dy2 = 1 * style.GRID_CELL_SIZE self._button_area = Gtk.Alignment.new(0.5, 0, 0, 0) self._button_area.set_size_request(Gdk.Screen.width(), style.GRID_CELL_SIZE) self._fixed.put(self._button_area, 0, 0) self._button_area.show() self._scrolled_window = Gtk.ScrolledWindow() self._scrolled_window.set_size_request(Gdk.Screen.width(), Gdk.Screen.height() - dy1) self._set_scroll_policy() self._graphics_area = Gtk.Alignment.new(0.5, 0, 0, 0) self._scrolled_window.add_with_viewport(self._graphics_area) self._graphics_area.show() self._fixed.put(self._scrolled_window, 0, dy2) self._scrolled_window.show() self._overlay_window = Gtk.ScrolledWindow() self._overlay_window.set_size_request(style.GRID_CELL_SIZE * 10, style.GRID_CELL_SIZE * 6) self._overlay_window.modify_bg(Gtk.StateType.NORMAL, style.COLOR_WHITE.get_gdk_color()) self._overlay_window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) self._overlay_area = Gtk.Alignment.new(0.5, 0, 0, 0) self._overlay_window.add_with_viewport(self._overlay_area) self._overlay_area.show() x = int((Gdk.Screen.width() - style.GRID_CELL_SIZE * 10) / 2) self._fixed.put(self._overlay_window, 0, Gdk.Screen.height()) self._overlay_window.show() self._old_overlay_widget = None self._reflect_window = ReflectWindow(self) self._reflect_window.show() Gdk.Screen.get_default().connect('size-changed', self._configure_cb) self._toolbox.connect('hide', self._resize_hide_cb) self._toolbox.connect('show', self._resize_show_cb) self._reflect_window.set_events(Gdk.EventMask.KEY_PRESS_MASK) self._reflect_window.connect('key_press_event', self._reflect_window.keypress_cb) self._reflect_window.set_can_focus(True) self._reflect_window.grab_focus() self.set_canvas(self._fixed) self._fixed.show() def reset_scrolled_window_adjustments(self): adj = self._scrolled_window.get_hadjustment() if adj is not None: adj.set_value(0) adj = self._scrolled_window.get_vadjustment() if adj is not None: adj.set_value(0) def load_graphics_area(self, widget): self._graphics_area.add(widget) def load_button_area(self, widget): self._button_area.add(widget) def load_overlay_area(self, widget): if self._old_overlay_widget is not None: self._overlay_area.remove(self._old_overlay_widget) self._overlay_area.add(widget) self._old_overlay_widget = widget def show_overlay_area(self): x = int((Gdk.Screen.width() - style.GRID_CELL_SIZE * 10) / 2) self._fixed.move(self._overlay_window, x, style.GRID_CELL_SIZE) def hide_overlay_area(self): self._fixed.move(self._overlay_window, 0, Gdk.Screen.height()) def collapse_overlay_area(self, button, event): self._fixed.move(self._overlay_window, 0, Gdk.Screen.height()) def _resize_hide_cb(self, widget): self._resize_canvas(widget, True) def _resize_show_cb(self, widget): self._resize_canvas(widget, False) def _configure_cb(self, event): self._fixed.set_size_request(Gdk.Screen.width(), Gdk.Screen.height()) self._set_scroll_policy() self._resize_canvas(None) self._reflect_window.reload_graphics() def _resize_canvas(self, widget, fullscreen=False): # When a toolbar is expanded or collapsed, resize the canvas if hasattr(self, '_reflect_window'): if self.toolbar_expanded(): dy1 = 3 * style.GRID_CELL_SIZE dy2 = 2 * style.GRID_CELL_SIZE else: dy1 = 2 * style.GRID_CELL_SIZE dy2 = 1 * style.GRID_CELL_SIZE if fullscreen: dy1 -= 2 * style.GRID_CELL_SIZE dy2 -= 2 * style.GRID_CELL_SIZE self._scrolled_window.set_size_request(Gdk.Screen.width(), Gdk.Screen.height() - dy2) self._fixed.move(self._button_area, 0, 0) self._about_panel_visible = False def toolbar_expanded(self): if self.activity_button.is_expanded(): return True elif self.edit_toolbar_button.is_expanded(): return True elif self.view_toolbar_button.is_expanded(): return True return False def get_activity_version(self): info_path = os.path.join(self.bundle_path, 'activity', 'activity.info') try: info_file = open(info_path, 'r') except Exception as e: _logger.error('Could not open %s: %s' % (info_path, e)) return 'unknown' cp = ConfigParser() cp.readfp(info_file) section = 'Activity' if cp.has_option(section, 'activity_version'): activity_version = cp.get(section, 'activity_version') else: activity_version = 'unknown' return activity_version def get_uid(self): if len(self.volume_data) == 1: return self.volume_data[0]['uid'] else: return 'unknown' def _setup_toolbars(self): ''' Setup the toolbars. ''' self._toolbox = ToolbarBox() self.activity_button = ActivityToolbarButton(self) self.activity_button.connect('clicked', self._resize_canvas) self._toolbox.toolbar.insert(self.activity_button, 0) self.activity_button.show() self.set_toolbar_box(self._toolbox) self._toolbox.show() self.toolbar = self._toolbox.toolbar view_toolbar = Gtk.Toolbar() self.view_toolbar_button = ToolbarButton(page=view_toolbar, label=_('View'), icon_name='toolbar-view') self.view_toolbar_button.connect('clicked', self._resize_canvas) self._toolbox.toolbar.insert(self.view_toolbar_button, 1) view_toolbar.show() self.view_toolbar_button.show() button = ToolButton('view-fullscreen') button.set_tooltip(_('Fullscreen')) button.props.accelerator = '<Alt>Return' view_toolbar.insert(button, -1) button.show() button.connect('clicked', self._fullscreen_cb) edit_toolbar = Gtk.Toolbar() self.edit_toolbar_button = ToolbarButton(page=edit_toolbar, label=_('Edit'), icon_name='toolbar-edit') self.edit_toolbar_button.connect('clicked', self._resize_canvas) self._toolbox.toolbar.insert(self.edit_toolbar_button, 1) edit_toolbar.show() self.edit_toolbar_button.show() self._copy_button = ToolButton('edit-copy') self._copy_button.set_tooltip(_('Copy')) self._copy_button.props.accelerator = '<Ctrl>C' edit_toolbar.insert(self._copy_button, -1) self._copy_button.show() self._copy_button.connect('clicked', self._copy_cb) self._copy_button.set_sensitive(False) self._paste_button = ToolButton('edit-paste') self._paste_button.set_tooltip(_('Paste')) self._paste_button.props.accelerator = '<Ctrl>V' edit_toolbar.insert(self._paste_button, -1) self._paste_button.show() self._paste_button.connect('clicked', self._paste_cb) self._paste_button.set_sensitive(False) button = ToolButton('list-add') button.set_tooltip(_('Add Item')) button.props.accelerator = '<Ctrl>+' self._toolbox.toolbar.insert(button, -1) button.show() button.connect('clicked', self.__add_item_cb) self._date_button = RadioToolButton('date-sort', group=None) self._date_button.set_tooltip(_('Sort by Date')) self._date_button.connect('clicked', self._date_button_cb) self._toolbox.toolbar.insert(self._date_button, -1) self._date_button.show() self._title_button = RadioToolButton('title-sort', group=self._date_button) self._title_button.set_tooltip(_('Sort by Title')) self._title_button.connect('clicked', self._title_button_cb) self._toolbox.toolbar.insert(self._title_button, -1) self._title_button.show() self._stars_button = RadioToolButton('stars-sort', group=self._date_button) self._stars_button.set_tooltip(_('Sort by Favourite')) self._stars_button.connect('clicked', self._stars_button_cb) self._toolbox.toolbar.insert(self._stars_button, -1) self._stars_button.show() # setup the search options self._search_entry = iconentry.IconEntry() self._search_entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY, 'system-search') self._search_entry.connect('activate', self._search_entry_activated_cb) self._search_entry.connect('changed', self._search_entry_changed_cb) self._search_entry.add_clear_button() tool_item = Gtk.ToolItem() tool_item.set_expand(True) tool_item.add(self._search_entry) self._search_entry.show() self._toolbox.toolbar.insert(tool_item, -1) tool_item.show() self._search_button = ToolButton('dialog-ok') self._search_button.set_tooltip(_('Search by Tags')) self._search_button.connect('clicked', self._search_button_cb) self._toolbox.toolbar.insert(self._search_button, -1) self._search_button.show() separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) self._toolbox.toolbar.insert(separator, -1) separator.show() stop_button = StopButton(self) stop_button.props.accelerator = '<Ctrl>q' self._toolbox.toolbar.insert(stop_button, -1) stop_button.show() def _search_button_cb(self, button): self.busy_cursor() self._do_search() def _search_entry_activated_cb(self, entry): self.busy_cursor() self._do_search() def _do_search(self): logging.debug('_search_entry_activated_cb') if self._search_entry.props.text == '': logging.debug('clearing search') for item in self.reflection_data: item['hidden'] = False else: tags = self._search_entry.props.text.split() for i, tag in enumerate(tags): if not tag[0] == '#': tags[i] = '#%s' % tag logging.error(tags) for item in self.reflection_data: hidden = True if 'tags' in item: for tag in tags: if tag in item['tags']: hidden = False item['hidden'] = hidden self.reload_data(self.reflection_data) self.reset_cursor() def _search_entry_changed_cb(self, entry): logging.debug('_search_entry_changed_cb search for \'%s\'', self._search_entry.props.text) self.busy_cursor() self._do_search_changed() def _do_search_changed(self): if self._search_entry.props.text == '': logging.debug('clearing search') for item in self.reflection_data: item['hidden'] = False self.reload_data(self.reflection_data) self.reset_cursor() def _title_button_cb(self, button): ''' sort by title ''' self.busy_cursor() GObject.idle_add(self._title_sort) def _title_sort(self): sorted_data = sorted(self.reflection_data, key=lambda item: item['title'].lower()) self.reload_data(sorted_data) self.reset_cursor() def _date_button_cb(self, button): ''' sort by modification date ''' self.busy_cursor() GObject.idle_add(self._date_sort) def _date_sort(self): sorted_data = sorted(self.reflection_data, key=lambda item: int(item['modification_time']), reverse=True) self.reload_data(sorted_data) self.reset_cursor() def _stars_button_cb(self, button): ''' sort by number of stars ''' self.busy_cursor() GObject.idle_add(self._stars_sort) def _stars_sort(self): sorted_data = sorted(self.reflection_data, key=lambda item: item['stars'], reverse=True) self.reload_data(sorted_data) self.reset_cursor() def __realize_cb(self, window): self.window_xid = window.get_window().get_xid() def set_copy_widget(self, webkit=None, text_entry=None): # Each task is responsible for setting a widget for copy if webkit is not None: self._webkit = webkit else: self._webkit = None if text_entry is not None: self._copy_entry = text_entry else: self._copy_entry = None self._copy_button.set_sensitive(webkit is not None or text_entry is not None) def _copy_cb(self, button): if self._copy_entry is not None: self._copy_entry.copy_clipboard() elif self._webkit is not None: self._webkit.copy_clipboard() else: _logger.debug('No widget set for copy.') def set_paste_widget(self, text_entry=None): # Each task is responsible for setting a widget for paste if text_entry is not None: self._paste_entry = text_entry self._paste_button.set_sensitive(text_entry is not None) def _paste_cb(self, button): clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.clipboard_text = clipboard.wait_for_text() if self._paste_entry is not None: self._paste_entry.paste_clipboard() else: _logger.debug('No widget set for paste (%s).' % self.clipboard_text) def _fullscreen_cb(self, button): ''' Hide the Sugar toolbars. ''' self.fullscreen() def __add_item_cb(self, button): try: chooser = ObjectChooser(parent=self, what_filter=None) except TypeError: chooser = ObjectChooser( None, self._reflection.activity, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT) try: result = chooser.run() if result == Gtk.ResponseType.ACCEPT: jobject = chooser.get_selected_object() if jobject: self._add_new_from_journal(jobject) self.reload_data(self.reflection_data) finally: chooser.destroy() del chooser def _set_scroll_policy(self): if Gdk.Screen.width() < Gdk.Screen.height(): self._scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) else: self._scrolled_window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) def _remove_alert_cb(self, alert, response_id): self.remove_alert(alert) def _close_alert_cb(self, alert, response_id): self.remove_alert(alert) if response_id is Gtk.ResponseType.OK: self.close() def _setup_presence_service(self): ''' Setup the Presence Service. ''' self.pservice = presenceservice.get_instance() owner = self.pservice.get_owner() self.owner = owner self._share = '' self.connect('shared', self._shared_cb) self.connect('joined', self._joined_cb) def _shared_cb(self, activity): ''' Either set up initial share...''' if self.shared_activity is None: _logger.error('Failed to share or join activity ... \ shared_activity is null in _shared_cb()') return self.initiating = True self._waiting_for_reflections = False _logger.debug('I am sharing...') self.conn = self.shared_activity.telepathy_conn self.tubes_chan = self.shared_activity.telepathy_tubes_chan self.text_chan = self.shared_activity.telepathy_text_chan self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( 'NewTube', self._new_tube_cb) _logger.debug('This is my activity: making a tube...') self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube( SERVICE, {}) self.sharing = True def _joined_cb(self, activity): ''' ...or join an exisiting share. ''' if self.shared_activity is None: _logger.error('Failed to share or join activity ... \ shared_activity is null in _shared_cb()') return if self._joined_alert is not None: self.remove_alert(self._joined_alert) self._joined_alert = None self.initiating = False self._waiting_for_reflections = True _logger.debug('I joined a shared activity.') self.conn = self.shared_activity.telepathy_conn self.tubes_chan = self.shared_activity.telepathy_tubes_chan self.text_chan = self.shared_activity.telepathy_text_chan self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( 'NewTube', self._new_tube_cb) _logger.debug('I am joining an activity: waiting for a tube...') self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes( reply_handler=self._list_tubes_reply_cb, error_handler=self._list_tubes_error_cb) self.sharing = True def _list_tubes_reply_cb(self, tubes): ''' Reply to a list request. ''' for tube_info in tubes: self._new_tube_cb(*tube_info) def _list_tubes_error_cb(self, e): ''' Log errors. ''' _logger.error('ListTubes() failed: %s', e) def _new_tube_cb(self, id, initiator, type, service, params, state): ''' Create a new tube. ''' _logger.debug( 'New tube: ID=%d initator=%d type=%d service=%s ' 'params=%r state=%d', id, initiator, type, service, params, state) if (type == telepathy.TUBE_TYPE_DBUS and service == SERVICE): if state == telepathy.TUBE_STATE_LOCAL_PENDING: self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube( id) self.collab = CollabWrapper(self) self.collab.message.connect(self.event_received_cb) self.collab.setup() if self._waiting_for_reflections: self.send_event(JOIN_CMD, {}) self._joined_alert = Alert() self._joined_alert.props.title = _('Please wait') self._joined_alert.props.msg = _('Requesting reflections...') self.add_alert(self._joined_alert) def event_received_cb(self, collab, buddy, msg): ''' Data is passed as tuples: cmd:text ''' command = msg.get("command") payload = msg.get("payload") logging.debug(command) if command == JOIN_CMD: # Sharer needs to send reflections database to joiners. if self.initiating: # Send pictures first. for item in self.reflection_data: if 'content' in item: for content in item['content']: if 'image' in content: pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( content['image'], 120, 90) if pixbuf is not None: data = utils.pixbuf_to_base64(pixbuf) self.send_event( PICTURE_CMD, { "image": os.path.basename( content['image']), "data": data }) data = json.dumps(self.reflection_data) self.send_event(SHARE_CMD, {"data": data}) elif command == NEW_REFLECTION_CMD: self._reflect_window.add_new_reflection(payload) elif command == TITLE_CMD: obj_id = payload.get("obj_id") title = payload.get("title") for item in self.reflection_data: if item['obj_id'] == obj_id: found_the_object = True self._reflect_window.update_title(obj_id, title) break if not found_the_object: logging.error('Could not find obj_id %s' % obj_id) elif command == TAG_CMD: obj_id = payload.get("obj_id") data = payload.get("data") for item in self.reflection_data: if item['obj_id'] == obj_id: found_the_object = True self._reflect_window.update_tags(obj_id, data) break if not found_the_object: logging.error('Could not find obj_id %s' % obj_id) elif command == ACTIVITY_CMD: obj_id = payload.get("obj_id") bundle_id = payload.get("bundle_id") for item in self.reflection_data: if item['obj_id'] == obj_id: found_the_object = True self._reflect_window.insert_activity(obj_id, bundle_id) break if not found_the_object: logging.error('Could not find obj_id %s' % obj_id) elif command == STAR_CMD: obj_id = payload.get("obj_id") stars = payload.get("stars") for item in self.reflection_data: if item['obj_id'] == obj_id: found_the_object = True self._reflect_window.update_stars(obj_id, int(stars)) break if not found_the_object: logging.error('Could not find obj_id %s' % obj_id) elif command == COMMENT_CMD: found_the_object = False # Receive a comment and associated reflection ID obj_id = payload.get("obj_id") nick = payload.get("nick") color = payload.get("color") comment = payload.get("comment") for item in self.reflection_data: if item['obj_id'] == obj_id: found_the_object = True if 'comments' not in item: item['comments'] = [] data = {'nick': nick, 'comment': comment, 'color': color} item['comments'].append(data) self._reflect_window.insert_comment(obj_id, data) break if not found_the_object: logging.error('Could not find obj_id %s' % obj_id) elif command == REFLECTION_CMD: found_the_object = False # Receive a reflection and associated reflection ID obj_id = payload.get("obj_id") reflection = payload.get("reflection") for item in self.reflection_data: if item['obj_id'] == obj_id: found_the_object = True if '' not in item: item['content'] = [] item['content'].append({'text': reflection}) self._reflect_window.insert_reflection(obj_id, reflection) break if not found_the_object: logging.error('Could not find obj_id %s' % obj_id) elif command == IMAGE_REFLECTION_CMD: found_the_object = False # Receive a picture reflection and associated reflection ID obj_id = payload.get("obj_id") basename = payload.get("basename") for item in self.reflection_data: if item['obj_id'] == obj_id: found_the_object = True if '' not in item: item['content'] = [] item['content'].append( {'image': os.path.join(self.tmp_path, basename)}) self._reflect_window.insert_picture( obj_id, os.path.join(self.tmp_path, basename)) break if not found_the_object: logging.error('Could not find obj_id %s' % obj_id) elif command == PICTURE_CMD: # Receive a picture (MAYBE DISPLAY IT AS IT ARRIVES?) basename = payload.get("basename") data = payload.get("data") utils.base64_to_file(data, os.path.join(self.tmp_path, basename)) elif command == SHARE_CMD: # Joiner needs to load reflection database. if not self.initiating: # Note that pictures should be received. self.reflection_data = payload self._reflect_window.load(self.reflection_data) self._waiting_for_reflections = False self.reset_cursor() if self._joined_alert is not None: self.remove_alert(self._joined_alert) self._joined_alert = None def send_event(self, command, data): ''' Send event through the tube. ''' if hasattr(self, 'collab') and self.collab is not None: data["command"] = command self.collab.post(data)
def __init__(self, handle): """Set up the Develop activity.""" self._dirty = False super(DevelopActivity, self).__init__(handle) self.max_participants = 1 self.current_theme = "light" logging.info(repr(handle.get_dict())) # Source buffer self.editor = sourceview_editor.GtkSourceview2Editor() self.editor.connect('tab-changed', self.__editor_tab_changed_cb) self.editor.connect('changed', self.__editor_changed_cb) # Show tabs after Welcome Page self.editor.set_show_tabs(False) toolbarbox = ToolbarBox() activity_button = ActivityToolbarButton(self) toolbarbox.toolbar.insert(activity_button, 0) self.set_toolbar_box(toolbarbox) view_btn = ToolbarButton() view_toolbar = DevelopViewToolbar(self) view_btn.props.page = view_toolbar view_btn.props.icon_name = 'toolbar-view' view_btn.props.label = _('View') view_toolbar.connect('theme-changed', self.editor.theme_changed_cb) view_toolbar.connect('font-size-changed', self.editor.font_changed_cb) toolbarbox.toolbar.insert(view_btn, -1) self.view_toolbar = view_toolbar edit_btn = ToolbarButton() edit_btn.props.page = DevelopEditToolbar(self) edit_btn.props.icon_name = 'toolbar-edit' edit_btn.props.label = _('Edit') toolbarbox.toolbar.insert(edit_btn, -1) search_btn = ToolbarButton() search_btn.props.page = DevelopSearchToolbar(self) search_btn.props.icon_name = 'search' search_btn.props.label = _('Search') toolbarbox.toolbar.insert(search_btn, -1) toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1) show_files_btn = RadioToolButton() show_files_btn.props.icon_name = 'sources' show_files_btn.props.group = show_files_btn show_files_btn.set_active(True) show_files_btn.set_tooltip(_('Show source files')) toolbarbox.toolbar.insert(show_files_btn, -1) show_files_btn.connect('clicked', self._change_treenotebook_page, 0) show_symbols_btn = RadioToolButton() show_symbols_btn.props.icon_name = 'symbols' show_symbols_btn.props.group = show_files_btn show_symbols_btn.set_active(False) show_symbols_btn.set_tooltip(_('Show file symbols')) toolbarbox.toolbar.insert(show_symbols_btn, -1) show_symbols_btn.connect('clicked', self._explore_code) show_log_btn = RadioToolButton() show_log_btn.props.icon_name = 'logs' show_log_btn.props.group = show_files_btn show_log_btn.set_active(False) show_log_btn.set_tooltip(_('Show log files')) toolbarbox.toolbar.insert(show_log_btn, -1) show_log_btn.connect('clicked', self._change_treenotebook_page, 2) toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1) create_file_btn = ToolButton('text-x-generic') create_file_btn.set_tooltip(_('Create empty file')) toolbarbox.toolbar.insert(create_file_btn, -1) create_file_btn.show() create_file_btn.connect('clicked', self.__create_empty_file_cb) erase_btn = ToolButton('erase') erase_btn.set_tooltip(_('Remove file')) toolbarbox.toolbar.insert(erase_btn, -1) erase_btn.show() erase_btn.connect('clicked', self.__remove_file_cb) toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1) run_btn = ToolButton('activity-start') run_btn.set_tooltip(_('Run activity')) toolbarbox.toolbar.insert(run_btn, -1) run_btn.connect('clicked', self.__run_actvity_cb) separator = Gtk.SeparatorToolItem() separator.set_draw(False) separator.set_expand(True) toolbarbox.toolbar.insert(separator, -1) stopbtn = StopButton(self) toolbarbox.toolbar.insert(stopbtn, -1) save_bundle_btn = ToolButton('save-as-bundle') save_bundle_btn.set_tooltip(_('Create bundle (.xo file)')) activity_button.get_page().insert(save_bundle_btn, -1) save_bundle_btn.connect('clicked', self.save_bundle) save_bundle_btn.show() toolbarbox.show_all() # Main layout. hbox = Gtk.HPaned() # The treeview and selected pane reflect each other. self.numb = False # Wait to save until first change, but save an unchanged # backup copy when that happens. self.save_unchanged = False # The sidebar sidebar = Gtk.VBox() self.treenotebook = notebook.Notebook(can_close_tabs=False) self.treenotebook.set_show_tabs(False) sidebar.pack_start(self.treenotebook, True, True, 0) self.activity_tree_view = FileViewer() self.treenotebook.add_page(_("Activity"), self.activity_tree_view) self.treenotebook.set_size_request(Gdk.Screen.width() / 5, -1) # Symbols tree self._symbolstree = SymbolsTree() self._symbolstree.connect('symbol-selected', self.editor.symbol_selected_cb) scrolled = Gtk.ScrolledWindow() scrolled.add(self._symbolstree) scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.treenotebook.add_page(_('Symbols Tree'), scrolled) hbox.pack1(sidebar, resize=True, shrink=False) # Show sidebar after welcome page ends # sidebar.show() self.sidebar = sidebar logging.info('finished check') self.editor.show() hbox.pack2(self.editor, resize=True, shrink=True) self.set_canvas(hbox) hbox.show() logging.critical('finished initialization') self.activity_dir = None self.show() if not handle.object_id or not self.metadata.get('source'): GObject.timeout_add(10, self._show_welcome)
class ConvertActivity(activity.Activity): def __init__(self, handle): activity.Activity.__init__(self, handle, True) self.max_participants = 1 self.dic = {} # Canvas self._canvas = Gtk.VBox() hbox = Gtk.HBox() self._liststore = Gtk.ListStore(str) self.combo1 = Gtk.ComboBox.new_with_model_and_entry(self._liststore) cell = Gtk.CellRendererText() self.combo1.pack_start(cell, True) self.combo1.set_entry_text_column(0) self.combo1.connect('changed', self._update_label) flip_btn = Gtk.Button() flip_btn.connect('clicked', self._flip) flip_btn.set_tooltip_text("Flip Units") flip_btn.add(Gtk.Image.new_from_file('icons/flip.svg')) self.combo2 = Gtk.ComboBox.new_with_model_and_entry(self._liststore) cell = Gtk.CellRendererText() self.combo2.pack_start(cell, True) self.combo2.set_entry_text_column(0) self.combo2.connect('changed', self._update_label) self.label_box = Gtk.HBox() self.value_entry = Gtk.Entry() self.value_entry.set_placeholder_text("Enter number") self.value_entry.connect('insert-text', self._value_insert_text) self.value_entry.connect('changed', self._update_label) self.label = Gtk.Label() self.label.set_selectable(True) self.label._size = 12 self.label.connect('draw', self.resize_label) self._canvas.pack_start(hbox, False, False, 20) hbox.pack_start(self.combo1, False, True, 20) hbox.pack_start(flip_btn, True, False, 20) hbox.pack_end(self.combo2, False, True, 20) value_box = Gtk.HBox() convert_box = Gtk.HBox() convert_box.pack_start(value_box, True, False, 0) value_box.pack_start(self.value_entry, False, False, 0) self._canvas.pack_start(convert_box, False, False, 5) self._canvas.pack_start(self.label_box, True, False, 0) self.label_box.add(self.label) self.set_canvas(self._canvas) # Toolbar toolbarbox = ToolbarBox() activity_button = ActivityToolbarButton(self) toolbarbox.toolbar.insert(activity_button, 0) separator = Gtk.SeparatorToolItem() separator.set_expand(False) separator.set_draw(True) toolbarbox.toolbar.insert(separator, -1) # RadioToolButton self._length_btn = RadioToolButton() self._length_btn.connect('clicked', lambda w: self._update_combo(convert.length)) # TRANS: https://en.wikipedia.org/wiki/Length self._length_btn.set_tooltip(_('Length')) self._length_btn.props.icon_name = 'length' self._volume_btn = RadioToolButton() self._volume_btn.connect('clicked', lambda w: self._update_combo(convert.volume)) # TRANS: https://en.wikipedia.org/wiki/Volume self._volume_btn.set_tooltip(_('Volume')) self._volume_btn.props.icon_name = 'volume' self._volume_btn.props.group = self._length_btn self._area_btn = RadioToolButton() self._area_btn.connect('clicked', lambda w: self._update_combo(convert.area)) # TRANS: https://en.wikipedia.org/wiki/Area self._area_btn.set_tooltip(_('Area')) self._area_btn.props.icon_name = 'area' self._area_btn.props.group = self._length_btn self._weight_btn = RadioToolButton() self._weight_btn.connect('clicked', lambda w: self._update_combo(convert.weight)) # TRANS: https://en.wikipedia.org/wiki/Weight self._weight_btn.set_tooltip(_('Weight')) self._weight_btn.props.icon_name = 'weight' self._weight_btn.props.group = self._length_btn self._speed_btn = RadioToolButton() self._speed_btn.connect('clicked', lambda w: self._update_combo(convert.speed)) # TRANS: https://en.wikipedia.org/wiki/Speed self._speed_btn.set_tooltip(_('Speed')) self._speed_btn.props.icon_name = 'speed' self._speed_btn.props.group = self._length_btn self._time_btn = RadioToolButton() self._time_btn.connect('clicked', lambda w: self._update_combo(convert.time)) # TRANS: https://en.wikipedia.org/wiki/Time self._time_btn.set_tooltip(_('Time')) self._time_btn.props.icon_name = 'time' self._time_btn.props.group = self._length_btn self._temp_btn = RadioToolButton() self._temp_btn.connect('clicked', lambda w: self._update_combo(convert.temp)) # TRANS: https://en.wikipedia.org/wiki/Temperature self._temp_btn.set_tooltip(_('Temperature')) self._temp_btn.props.icon_name = 'temp' self._temp_btn.props.group = self._length_btn #Circle self._circle_btn = RadioToolButton() self._circle_btn.connect('clicked', lambda w: self._update_combo(convert.circle)) self._circle_btn.set_tooltip(_('Angles of Circles')) self._circle_btn.props.icon_name = 'circle' self._circle_btn.props.group = self._length_btn #pressure self._pressure_btn = RadioToolButton() self._pressure_btn.connect('clicked', lambda w: self._update_combo(convert.pressure)) self._pressure_btn.set_tooltip(_('Pressure')) self._pressure_btn.props.icon_name = 'pressure' self._pressure_btn.props.group = self._length_btn #force self._force_btn = RadioToolButton() self._force_btn.connect('clicked', lambda w: self._update_combo(convert.force)) self._force_btn.set_tooltip(_('Force')) self._force_btn.props.icon_name = 'force' self._force_btn.props.group = self._length_btn #energy self._energy_btn = RadioToolButton() self._energy_btn.connect('clicked', lambda w: self._update_combo(convert.energy)) self._energy_btn.set_tooltip(_('Energy')) self._energy_btn.props.icon_name = 'energy' self._energy_btn.props.group = self._length_btn #Storage self._storage_btn = RadioToolButton() self._storage_btn.connect('clicked', lambda w: self._update_combo(convert.storage)) self._storage_btn.set_tooltip(_('Digital Storage')) self._storage_btn.props.icon_name = 'storage' self._storage_btn.props.group = self._length_btn toolbarbox.toolbar.insert(self._length_btn, -1) toolbarbox.toolbar.insert(self._volume_btn, -1) toolbarbox.toolbar.insert(self._area_btn, -1) toolbarbox.toolbar.insert(self._weight_btn, -1) toolbarbox.toolbar.insert(self._speed_btn, -1) toolbarbox.toolbar.insert(self._time_btn, -1) toolbarbox.toolbar.insert(self._temp_btn, -1) toolbarbox.toolbar.insert(self._circle_btn, -1) toolbarbox.toolbar.insert(self._pressure_btn, -1) toolbarbox.toolbar.insert(self._force_btn, -1) toolbarbox.toolbar.insert(self._energy_btn, -1) toolbarbox.toolbar.insert(self._storage_btn, -1) separator = Gtk.SeparatorToolItem() separator.set_expand(True) separator.set_draw(False) toolbarbox.toolbar.insert(separator, -1) stopbtn = StopButton(self) toolbarbox.toolbar.insert(stopbtn, -1) self.set_toolbar_box(toolbarbox) self._update_combo(convert.length) self.show_all() def _update_label(self, entry): try: num_value = str(self.value_entry.get_text()) num_value = str(num_value.replace(',', '')) decimals = str(len(num_value.split('.')[-1])) fmt = '%.' + decimals + 'f' new_value = locale.format(fmt, float(num_value)) new_value = new_value.rstrip("0") if new_value[-1] == '.': new_value = new_value[0:len(new_value)-1] convert_value = str(self.convert()) decimals = str(len(convert_value.split('.')[-1])) fmt = '%.' + decimals + 'f' new_convert = locale.format(fmt, float(convert_value)) new_convert = new_convert.rstrip("0") if new_convert[-1] == '.': new_convert = new_convert[0:len(new_convert)-1] text = '%s ~ %s' % (new_value, new_convert) self.label.set_text(text) except ValueError: pass def _update_combo(self, data): self._liststore.clear() self.dic = data keys = self.dic.keys() keys.sort() for x in keys: self._liststore.append(['%s' % (x)]) if keys[0] == 'Cables': self.combo1.set_active(12) self.combo2.set_active(12) elif keys[0] == 'Cubic Centimeter': self.combo1.set_active(3) self.combo2.set_active(3) elif keys[0] == 'Acre': self.combo1.set_active(4) self.combo2.set_active(4) elif keys[0] == 'Carat': self.combo1.set_active(2) self.combo2.set_active(2) elif keys[0] == 'Centimeters/Minute': self.combo1.set_active(9) self.combo2.set_active(9) elif keys[0] == 'Day': self.combo1.set_active(8) self.combo2.set_active(8) elif keys[0] == 'Celsius': self.combo1.set_active(2) self.combo2.set_active(2) elif keys[0] == 'Degrees': self.combo1.set_active(1) self.combo2.set_active(1) elif keys[0] == 'Atmosphere (atm)': self.combo1.set_active(2) self.combo2.set_active(2) elif keys[0] == 'Dyne (dyn)': self.combo1.set_active(2) self.combo2.set_active(2) elif keys[0] == 'Calories (cal)': self.combo1.set_active(2) self.combo2.set_active(2) elif keys[0] == 'Bit': self.combo1.set_active(1) self.combo2.set_active(1) else: pass self.show_all() def _get_active_text(self, combobox): active = combobox.get_active() keys = self.dic.keys() keys.sort() if active < 0: active = 0 text = keys[active] if '<sup>' in text: text = text.split('<b>')[1].split('</b>')[0] return text def _flip(self, widget): value = self.label.get_text().split(' ~ ') self.value_entry.set_text(value[1]) active_combo1 = self.combo1.get_active() active_combo2 = self.combo2.get_active() self.combo1.set_active(active_combo2) self.combo2.set_active(active_combo1) def resize_label(self, widget, event): num_label = len(self.label.get_text()) try: size = str((60 * SCREEN_WIDTH / 100) / num_label) if not size == self.label._size: self.label.modify_font(Pango.FontDescription(size)) self.label._size = size except ZeroDivisionError: pass def convert(self): number = float(self.value_entry.get_text().replace(',', '')) unit = self._get_active_text(self.combo1) to_unit = self._get_active_text(self.combo2) return convert.convert(number, unit, to_unit, self.dic) def _value_insert_text(self, entry, text, length, position): for char in text: if char == "-" and \ self.value_entry.get_text() is "" and len(text) == 1: return False elif not re.match('[0-9,.]', char): entry.emit_stop_by_name('insert-text') return True return False
def create_palette(self): self._palette = self.get_child().create_palette() color_palette_hbox = self._palette._picker_hbox self.custom_box = Gtk.VBox() self.vbox_brush_options = Gtk.VBox() # This is where we set restrictions for size: # Initial value, minimum value, maximum value, step adj = Gtk.Adjustment(self.properties['line size'], 1.0, 100.0, 1.0) self.size_scale = Gtk.HScale() self.size_scale.set_adjustment(adj) self.size_scale.set_draw_value(False) self.size_scale.set_size_request(style.zoom(200), -1) self.size_label = Gtk.Label(label=_('Size')) self.size_label.props.halign = Gtk.Align.START self.vbox_brush_options.pack_start(self.size_label, True, True, 0) self.vbox_brush_options.pack_start(self.size_scale, True, True, 0) self.size_scale.connect('value-changed', self._on_value_changed) # Control alpha alpha = self.properties['alpha'] * 100 adj_alpha = Gtk.Adjustment(alpha, 10.0, 100.0, 1.0) self.alpha_scale = Gtk.HScale() self.alpha_scale.set_adjustment(adj_alpha) self.alpha_scale.set_draw_value(False) self.alpha_scale.set_size_request(style.zoom(200), -1) self.alpha_label = Gtk.Label(label=_('Opacity')) self.alpha_label.props.halign = Gtk.Align.START self.vbox_brush_options.pack_start(self.alpha_label, True, True, 0) self.vbox_brush_options.pack_start(self.alpha_scale, True, True, 0) self.alpha_scale.connect('value-changed', self._on_alpha_changed) # User is able to choose Shapes for 'Brush' and 'Eraser' self.shape_box = Gtk.HBox() self.custom_box.pack_start(self.vbox_brush_options, True, True, 0) item1 = RadioToolButton() item1.set_icon_name('tool-shape-ellipse') item2 = RadioToolButton() item2.set_icon_name('tool-shape-rectangle') item2.props.group = item1 if self.properties['line shape'] == 'circle': item1.set_active(True) else: item2.set_active(True) item1.connect('toggled', self._on_toggled, self.properties, 'circle') item2.connect('toggled', self._on_toggled, self.properties, 'square') self.shape_box.pack_start(Gtk.Label(_('Shape')), True, True, 0) self.shape_box.pack_start(item1, True, True, 0) self.shape_box.pack_start(item2, True, True, 0) self.vbox_brush_options.pack_start(self.shape_box, True, True, 0) self.keep_aspect_checkbutton = Gtk.CheckButton(_('Keep aspect')) ratio = self._activity.area.keep_aspect_ratio self.keep_aspect_checkbutton.set_active(ratio) self.keep_aspect_checkbutton.connect( 'toggled', self._keep_aspect_checkbutton_toggled) self.vbox_brush_options.pack_start(self.keep_aspect_checkbutton, True, True, 0) self.custom_separator = Gtk.VSeparator() color_palette_hbox.pack_start(self.custom_separator, True, True, padding=style.DEFAULT_SPACING) color_palette_hbox.pack_start(self.custom_box, True, True, padding=style.DEFAULT_SPACING) color_palette_hbox.show_all() self._update_palette() return self._palette
class ViewToolbar(Gtk.Toolbar): __gtype_name__ = 'SugarViewToolbar' __gsignals__ = { 'query-changed': (GObject.SignalFlags.RUN_FIRST, None, ([str])), 'view-changed': (GObject.SignalFlags.RUN_FIRST, None, ([object])), } def __init__(self): Gtk.Toolbar.__init__(self) self._favorites_views_indicies = [] for i in range(desktop.get_number_of_views()): self._favorites_views_indicies.append(i) self._list_view_index = self._favorites_views_indicies[-1] + 1 self._desktop_model = desktop.get_model() self._desktop_model.connect('desktop-view-icons-changed', self.__desktop_view_icons_changed_cb) self._query = None self._autosearch_timer = None self._add_separator() tool_item = Gtk.ToolItem() self.insert(tool_item, -1) tool_item.show() self.search_entry = iconentry.IconEntry() self.search_entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY, 'entry-search') self.set_placeholder_text_for_view(_('Home')) self.search_entry.add_clear_button() self.search_entry.set_width_chars(25) self.search_entry.connect('activate', self._entry_activated_cb) self.search_entry.connect('changed', self._entry_changed_cb) tool_item.add(self.search_entry) self.search_entry.show() self._add_separator(expand=True) self._button_box = Gtk.HBox() self._favorites_buttons = [] for i in range(desktop.get_number_of_views()): self._add_favorites_button(i) toolitem = Gtk.ToolItem() toolitem.add(self._button_box) self.insert(toolitem, -1) self._button_box.show() toolitem.show() self._list_button = RadioToolButton(icon_name='view-list') self._list_button.props.group = self._favorites_buttons[0] self._list_button.props.tooltip = _('List view') self._list_button.props.accelerator = \ _('<Ctrl>%d' % (len(self._favorites_views_indicies) + 1)) self._list_view_toggle_id = self._list_button.connect( 'toggled', self.__view_button_toggled_cb, self._list_view_index) self.insert(self._list_button, -1) self._add_separator() def _add_favorites_button(self, i): logging.debug('adding FavoritesButton %d' % (i)) self._favorites_buttons.append(FavoritesButton(i)) self._favorites_buttons[i].connect('toggled', self.__view_button_toggled_cb, self._favorites_views_indicies[i]) if i > 0: self._favorites_buttons[i].props.group = self._favorites_buttons[0] self._button_box.add(self._favorites_buttons[i]) self._favorites_buttons[i].show() def show_view_buttons(self): for i in range(desktop.get_number_of_views()): self._favorites_buttons[i].show() self._list_button.show() def hide_view_buttons(self): for i in range(desktop.get_number_of_views()): self._favorites_buttons[i].hide() self._list_button.hide() def clear_query(self): self.search_entry.props.text = '' def set_placeholder_text_for_view(self, view_name): text = _('Search in %s') % view_name self.search_entry.set_placeholder_text(text) def _add_separator(self, expand=False): separator = Gtk.SeparatorToolItem() separator.props.draw = False if expand: separator.set_expand(True) else: separator.set_size_request(style.GRID_CELL_SIZE, style.GRID_CELL_SIZE) self.insert(separator, -1) separator.show() def _entry_activated_cb(self, entry): if self._autosearch_timer: GObject.source_remove(self._autosearch_timer) new_query = entry.props.text if self._query != new_query: self._query = new_query self.emit('query-changed', self._query) def _entry_changed_cb(self, entry): if not entry.props.text: entry.activate() return if self._autosearch_timer: GObject.source_remove(self._autosearch_timer) self._autosearch_timer = GObject.timeout_add(_AUTOSEARCH_TIMEOUT, self._autosearch_timer_cb) def _autosearch_timer_cb(self): logging.debug('_autosearch_timer_cb') self._autosearch_timer = None self.search_entry.activate() return False def __view_button_toggled_cb(self, button, view): if button.props.active: self.emit('view-changed', view) def __desktop_view_icons_changed_cb(self, model): number_of_views = desktop.get_number_of_views() if len(self._favorites_views_indicies) < number_of_views: for i in range(number_of_views - len(self._favorites_views_indicies)): n = len(self._favorites_views_indicies) self._favorites_views_indicies.append(n) self._add_favorites_button(n) self._favorites_buttons[n].show() elif number_of_views < len(self._favorites_views_indicies): for i in range(len(self._favorites_views_indicies) - number_of_views): n = len(self._favorites_views_indicies) - 1 logging.debug('removing FavoritesButton %d' % (n)) button = self._favorites_buttons[n] self._favorites_buttons.remove(button) button.destroy() self._favorites_views_indicies.remove( self._favorites_views_indicies[n]) self._button_box.show() self._list_view_index = number_of_views self._list_button.props.accelerator = \ _('<Ctrl>%d' % (len(self._favorites_views_indicies) + 1)) self._list_button.disconnect(self._list_view_toggle_id) self._list_view_toggle_id = self._list_button.connect( 'toggled', self.__view_button_toggled_cb, self._list_view_index) self._list_button.show()
text_view = Gtk.TextView() box.pack_start(text_view, True, True, 0) def echo(button, label): if not button.props.active: return text_view.props.buffer.props.text += '\n' + label # RadioMenuButton palette = RadioPalette() group = RadioToolButton( icon_name='document-open') group.connect('clicked', lambda button: echo(button, 'document-open')) palette.append(group, 'menu.document-open') button = RadioToolButton( icon_name='document-save', group=group) button.connect('clicked', lambda button: echo(button, 'document-save')) palette.append(button, 'menu.document-save') button = RadioToolButton( icon_name='document-send', group=group) button.connect('clicked', lambda button: echo(button, 'document-send')) palette.append(button, 'menu.document-send') button = RadioMenuButton(palette=palette)
class ViewToolbar(Gtk.Toolbar): __gtype_name__ = 'SugarViewToolbar' __gsignals__ = { 'query-changed': (GObject.SignalFlags.RUN_FIRST, None, ([str])), 'view-changed': (GObject.SignalFlags.RUN_FIRST, None, ([object])), } def __init__(self): Gtk.Toolbar.__init__(self) self._query = None self._autosearch_timer = None self._add_separator() tool_item = Gtk.ToolItem() self.insert(tool_item, -1) tool_item.show() self.search_entry = iconentry.IconEntry() self.search_entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY, 'entry-search') self.set_placeholder_text_for_view(_('Home')) self.search_entry.add_clear_button() self.search_entry.set_width_chars(25) self.search_entry.connect('activate', self._entry_activated_cb) self.search_entry.connect('changed', self._entry_changed_cb) tool_item.add(self.search_entry) self.search_entry.show() self._add_separator(expand=True) self._favorites_button = FavoritesButton() self._favorites_button.connect('toggled', self.__view_button_toggled_cb, _FAVORITES_VIEW) self.insert(self._favorites_button, -1) self._list_button = RadioToolButton(icon_name='view-list') self._list_button.props.group = self._favorites_button self._list_button.props.tooltip = _('List view') self._list_button.props.accelerator = _('<Ctrl>2') self._list_button.connect('toggled', self.__view_button_toggled_cb, _LIST_VIEW) self.insert(self._list_button, -1) self._add_separator() def show_view_buttons(self): self._favorites_button.show() self._list_button.show() def hide_view_buttons(self): self._favorites_button.hide() self._list_button.hide() def clear_query(self): self.search_entry.props.text = '' def set_placeholder_text_for_view(self, view_name): text = _('Search in %s') % view_name self.search_entry.set_placeholder_text(text) def _add_separator(self, expand=False): separator = Gtk.SeparatorToolItem() separator.props.draw = False if expand: separator.set_expand(True) else: separator.set_size_request(style.GRID_CELL_SIZE, style.GRID_CELL_SIZE) self.insert(separator, -1) separator.show() def _entry_activated_cb(self, entry): if self._autosearch_timer: GObject.source_remove(self._autosearch_timer) new_query = entry.props.text if self._query != new_query: self._query = new_query self.emit('query-changed', self._query) def _entry_changed_cb(self, entry): if not entry.props.text: entry.activate() return if self._autosearch_timer: GObject.source_remove(self._autosearch_timer) self._autosearch_timer = GObject.timeout_add(_AUTOSEARCH_TIMEOUT, self._autosearch_timer_cb) def _autosearch_timer_cb(self): logging.debug('_autosearch_timer_cb') self._autosearch_timer = None self.search_entry.activate() return False def __view_button_toggled_cb(self, button, view): if button.props.active: self.emit('view-changed', view)