Esempio n. 1
0
def add_menu(icon_name, tooltip, tool_name, button, activate_cb):
    menu_item = PaletteMenuItem(icon_name=icon_name, text_label=tooltip)
    menu_item.connect('activate', activate_cb, tool_name)
    menu_item.icon_name = icon_name
    button.menu_box.append_item(menu_item)
    menu_item.show()
    return menu_item
Esempio n. 2
0
 def _add_menu(self, font_name, activate_cb):
     label = '<span font="%s">%s</span>' % (font_name, font_name)
     menu_item = PaletteMenuItem()
     menu_item.set_label(label)
     menu_item.connect('activate', activate_cb, font_name)
     self._menu_box.append_item(menu_item)
     menu_item.show()
Esempio n. 3
0
class OwnerIcon(BuddyIcon):
    __gtype_name__ = 'SugarFavoritesOwnerIcon'

    __gsignals__ = {
        'register-activate': (GObject.SignalFlags.RUN_FIRST, None,
                              ([])),
    }

    def __init__(self, size):
        BuddyIcon.__init__(self, buddy=get_owner_instance(), pixel_size=size)

        self.palette_invoker.cache_palette = True

        self._palette_enabled = False
        self._register_menu = None

        # This is a workaround to skip the callback for
        # enter-notify-event in the parent class the first time.
        def __enter_notify_event_cb(icon, event):
            self.unset_state_flags(Gtk.StateFlags.PRELIGHT)
            self.disconnect(self._enter_notify_hid)

        self._enter_notify_hid = self.connect('enter-notify-event',
                                              __enter_notify_event_cb)

    def create_palette(self):
        if not self._palette_enabled:
            self._palette_enabled = True
            return

        palette = BuddyMenu(get_owner_instance())

        client = GConf.Client.get_default()
        backup_url = client.get_string('/desktop/sugar/backup_url')

        if not backup_url:
            self._register_menu = PaletteMenuItem(_('Register'),
                                                  'media-record')
        else:
            self._register_menu = PaletteMenuItem(_('Register again'),
                                                  'media-record')

        self._register_menu.connect('activate', self.__register_activate_cb)
        palette.menu_box.pack_end(self._register_menu, True, True, 0)
        self._register_menu.show()

        self.connect_to_palette_pop_events(palette)

        return palette

    def __register_activate_cb(self, menuitem):
        self.emit('register-activate')

    def set_registered(self):
        self.palette.menu_box.remove(self._register_menu)
        self._register_menu = PaletteMenuItem(_('Register again'),
                                              'media-record')
        self._register_menu.connect('activate', self.__register_activate_cb)
        self.palette.menu_box.pack_end(self._register_menu, True, True, 0)
        self._register_menu.show()
Esempio n. 4
0
    def __init__(self, invite):
        Palette.__init__(self, '')

        self._invite = invite

        self.menu_box = PaletteMenuBox()
        self.set_content(self.menu_box)
        self.menu_box.show()

        menu_item = PaletteMenuItem(_('Join'), icon_name='dialog-ok')
        menu_item.connect('activate', self.__join_activate_cb)
        self.menu_box.append_item(menu_item)
        menu_item.show()

        menu_item = PaletteMenuItem(_('Decline'), icon_name='dialog-cancel')
        menu_item.connect('activate', self.__decline_activate_cb)
        self.menu_box.append_item(menu_item)
        menu_item.show()

        bundle_id = invite.get_bundle_id()

        registry = bundleregistry.get_registry()
        self._bundle = registry.get_bundle(bundle_id)
        if self._bundle:
            name = self._bundle.get_name()
        else:
            name = bundle_id

        self.set_primary_text(name)
Esempio n. 5
0
    def create_palette(self):
        primary_text = GLib.markup_escape_text(self._model.bundle.get_name())
        secondary_text = GLib.markup_escape_text(self._model.get_name())
        palette_icon = Icon(file=self._model.bundle.get_icon(),
                            xo_color=self._model.get_color())
        palette_icon.props.icon_size = Gtk.IconSize.LARGE_TOOLBAR
        palette = Palette(None,
                          primary_text=primary_text,
                          secondary_text=secondary_text,
                          icon=palette_icon)

        private = self._model.props.private
        joined = get_owner_instance() in self._model.props.buddies

        menu_box = PaletteMenuBox()

        if joined:
            item = PaletteMenuItem(_('Resume'))
            icon = Icon(icon_size=Gtk.IconSize.MENU, icon_name='activity-start')
            item.set_image(icon)
            item.connect('activate', self.__palette_item_clicked_cb)
            menu_box.append_item(item)
        elif not private:
            item = PaletteMenuItem(_('Join'))
            icon = Icon(icon_size=Gtk.IconSize.MENU, icon_name='activity-start')
            item.set_image(icon)
            item.connect('activate', self.__palette_item_clicked_cb)
            menu_box.append_item(item)

        palette.set_content(menu_box)
        menu_box.show_all()

        self.connect_to_palette_pop_events(palette)
        return palette
Esempio n. 6
0
    def __init__(self, name):
        Gtk.VBox.__init__(self)
        self._name = name

        self._notifications_box = Gtk.VBox()
        self._notifications_box.show()

        self._scrolled_window = Gtk.ScrolledWindow()
        self._scrolled_window.add_with_viewport(self._notifications_box)
        self._scrolled_window.set_policy(Gtk.PolicyType.NEVER,
                                         Gtk.PolicyType.AUTOMATIC)
        self._scrolled_window.show()

        separator = PaletteMenuItemSeparator()
        separator.show()

        clear_item = PaletteMenuItem(_('Clear notifications'), 'dialog-cancel')
        clear_item.connect('activate', self.__clear_cb)
        clear_item.show()

        self.add(self._scrolled_window)
        self.add(separator)
        self.add(clear_item)

        self._service = notifications.get_service()
        entries = self._service.retrieve_by_name(self._name)

        if entries:
            for entry in entries:
                self._add(entry['summary'], entry['body'])

        self._service.notification_received.connect(
            self.__notification_received_cb)

        self.connect('destroy', self.__destroy_cb)
Esempio n. 7
0
    def __init__(self):
        ToolButton.__init__(self)

        self._property = 'timestamp'
        self._order = Gtk.SortType.ASCENDING

        self.props.tooltip = _('Sort view')
        self.props.icon_name = 'view-lastedit'

        self.props.hide_tooltip_on_click = False
        self.palette_invoker.props.toggle_palette = True

        menu_box = PaletteMenuBox()
        self.props.palette.set_content(menu_box)
        menu_box.show()

        sort_options = [
            ('timestamp', 'view-lastedit', _('Sort by date modified')),
            ('creation_time', 'view-created', _('Sort by date created')),
            ('filesize', 'view-size', _('Sort by size')),
        ]

        for property_, icon, label in sort_options:
            button = PaletteMenuItem(label)
            button_icon = Icon(pixel_size=style.SMALL_ICON_SIZE,
                               icon_name=icon)
            button.set_image(button_icon)
            button_icon.show()
            button.connect('activate',
                           self.__sort_type_changed_cb,
                           property_,
                           icon)
            button.show()
            menu_box.append_item(button)
Esempio n. 8
0
    def __init__(self, file_name, document_path, activity_name, title,
                 bundle=False):
        RadioToolButton.__init__(self)

        self._document_path = document_path
        self._title = title
        self._jobject = None
        self._activity_name = activity_name

        self.props.tooltip = _('Instance Source')

        settings = Gio.Settings('org.sugarlabs.user')
        self._color = settings.get_string('color')
        icon = Icon(file=file_name,
                    pixel_size=style.STANDARD_ICON_SIZE,
                    xo_color=XoColor(self._color))
        self.set_icon_widget(icon)
        icon.show()

        box = PaletteMenuBox()
        self.props.palette.set_content(box)
        box.show()

        if bundle:
            menu_item = PaletteMenuItem(_('Duplicate'), 'edit-duplicate',
                                        xo_color=XoColor(self._color))
            menu_item.connect('activate', self.__show_duplicate_alert)
        else:
            menu_item = PaletteMenuItem(_('Keep'), 'document-save',
                                        xo_color=XoColor(self._color))
            menu_item.connect('activate', self.__keep_in_journal_cb)

        box.append_item(menu_item)
        menu_item.show()
Esempio n. 9
0
    def _refresh_resume_palette(self):
        if self._metadata.get('activity_id', ''):
            # TRANS: Action label for resuming an activity.
            self._resume.set_tooltip(_('Resume'))
        else:
            # TRANS: Action label for starting an entry.
            self._resume.set_tooltip(_('Start'))

        palette = self._resume.get_palette()

        if self._resume_menu is not None:
            self._resume_menu.destroy()

        self._resume_menu = PaletteMenuBox()
        palette.set_content(self._resume_menu)
        self._resume_menu.show()

        for activity_info in misc.get_activities(self._metadata):
            menu_item = PaletteMenuItem(file_name=activity_info.get_icon(),
                                        text_label=activity_info.get_name())
            menu_item.connect('activate', self._resume_menu_item_activate_cb,
                              activity_info.get_bundle_id())
            self._resume_menu.append_item(menu_item)
            menu_item.show()

        if not misc.can_resume(self._metadata):
            self._resume.set_tooltip(_('No activity to start entry'))
Esempio n. 10
0
    def setup_rollover_options(self, info):
        palette = Palette(info, text_maxlen=50)
        self.set_palette(palette)

        box = PaletteMenuBox()
        palette.set_content(box)
        box.show()

        menu_item = PaletteMenuItem(_('Remove'), 'list-remove')
        menu_item.connect('activate', self.item_remove_cb)
        box.append_item(menu_item)
        menu_item.show()

        separator = PaletteMenuItemSeparator()
        box.append_item(separator)
        separator.show()

        textview = Gtk.TextView()
        textview.props.height_request = style.GRID_CELL_SIZE * 2
        textview.props.width_request = style.GRID_CELL_SIZE * 3
        textview.props.hexpand = True
        textview.props.vexpand = True
        box.append_item(textview)
        textview.show()

        buffer = textview.get_buffer()
        if self.notes is None:
            buffer.set_text(_('Take notes on this page'))
        else:
            buffer.set_text(self.notes)
        buffer.connect('changed', self.__buffer_changed_cb)
Esempio n. 11
0
    def __init__(self, activity_info, journal_entries):
        ActivityPalette.__init__(self, activity_info)

        if not journal_entries:
            xo_color = XoColor('%s,%s' % (style.COLOR_BUTTON_GREY.get_svg(),
                                          style.COLOR_WHITE.get_svg()))
        else:
            xo_color = misc.get_icon_color(journal_entries[0])

        self.props.icon = Icon(file=activity_info.get_icon(),
                               xo_color=xo_color,
                               pixel_size=style.STANDARD_ICON_SIZE)

        if journal_entries:
            self.props.secondary_text = journal_entries[0]['title']

            menu_items = []
            for entry in journal_entries:
                icon_file_name = misc.get_icon_name(entry)
                color = misc.get_icon_color(entry)

                menu_item = PaletteMenuItem(text_label=entry['title'],
                                            file_name=icon_file_name,
                                            xo_color=color)
                menu_item.connect('activate', self.__resume_entry_cb, entry)
                menu_items.append(menu_item)
                menu_item.show()

            if journal_entries:
                separator = PaletteMenuItemSeparator()
                menu_items.append(separator)
                separator.show()

            for i in range(0, len(menu_items)):
                self.menu_box.pack_start(menu_items[i], True, True, 0)
Esempio n. 12
0
    def __init__(self):
        ToolButton.__init__(self)

        self._property = 'timestamp'
        self._order = Gtk.SortType.ASCENDING

        self.props.tooltip = _('Sort view')
        self.props.icon_name = 'view-lastedit'

        self.props.hide_tooltip_on_click = False
        self.palette_invoker.props.toggle_palette = True

        menu_box = PaletteMenuBox()
        self.props.palette.set_content(menu_box)
        menu_box.show()

        for property_, icon, label in self._SORT_OPTIONS:
            button = PaletteMenuItem(label)
            button_icon = Icon(icon_size=Gtk.IconSize.MENU, icon_name=icon)
            button.set_image(button_icon)
            button_icon.show()
            button.connect('activate',
                           self.__sort_type_changed_cb,
                           property_,
                           icon)
            button.show()
            menu_box.append_item(button)
Esempio n. 13
0
    def _add_erase_option(self, registry, activity_info):
        menu_item = PaletteMenuItem(_("Erase"), "list-remove")
        menu_item.connect("activate", self.__erase_activate_cb)
        self.menu_box.append_item(menu_item)
        menu_item.show()

        if not os.access(activity_info.get_path(), os.W_OK) or registry.is_activity_protected(self._bundle_id):
            menu_item.props.sensitive = False
Esempio n. 14
0
 def create_menu_item(history_item, item_index):
     """Create a MenuItem for the back or forward palettes."""
     title = history_item.get_title()
     if not isinstance(title, unicode):
         title = unicode(title, "utf-8")
     # This is a fix until the Sugar MenuItem is fixed:
     menu_item = PaletteMenuItem(text_label=title)
     menu_item.connect("activate", self._history_item_activated_cb, item_index)
     return menu_item
Esempio n. 15
0
 def create_menu_item(history_item):
     """Create a MenuItem for the back or forward palettes."""
     title = history_item.get_title() or _('No Title')
     if not isinstance(title, unicode):
         title = unicode(title, 'utf-8')
     # This is a fix until the Sugar MenuItem is fixed:
     menu_item = PaletteMenuItem(text_label=title)
     menu_item.connect('activate', self._history_item_activated_cb,
                       history_item)
     return menu_item
Esempio n. 16
0
def set_palette_list(instrument_list):
    text_label = instrument_list[0]['instrument_desc']
    file_name = instrument_list[0]['file_name']
    _menu_item = PaletteMenuItem(text_label=text_label,
                                 file_name=file_name)
    req2 = _menu_item.get_preferred_size()[1]
    menuitem_width = req2.width
    menuitem_height = req2.height

    palette_width = Gdk.Screen.width() - style.GRID_CELL_SIZE * 3
    palette_height = Gdk.Screen.height() - style.GRID_CELL_SIZE * 3

    nx = min(int(palette_width / menuitem_width), MAX_PALETTE_WIDTH)
    ny = min(int(palette_height / menuitem_height), len(instrument_list) + 1)
    if ny >= len(instrument_list):
        nx = 1
        ny = len(instrument_list)

    grid = Gtk.Grid()
    grid.set_row_spacing(style.DEFAULT_PADDING)
    grid.set_column_spacing(0)
    grid.set_border_width(0)
    grid.show()

    x = 0
    y = 0

    for item in sorted(instrument_list,
                       cmp=lambda x, y: cmp(x['instrument_desc'],
                                            y['instrument_desc'])):
        menu_item = PaletteMenuItem(text_label=item['instrument_desc'],
                                    file_name=item['file_name'])
        menu_item.connect('button-release-event', item['callback'], item)

        # menu_item.connect('button-release-event', lambda x: x, item)
        grid.attach(menu_item, x, y, 1, 1)
        x += 1
        if x == nx:
            x = 0
            y += 1

        menu_item.show()

    if palette_height < (y * menuitem_height + style.GRID_CELL_SIZE):
        # if the grid is bigger than the palette, put in a scrolledwindow
        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.set_policy(Gtk.PolicyType.NEVER,
                                   Gtk.PolicyType.AUTOMATIC)
        scrolled_window.set_size_request(nx * menuitem_width,
                                         (ny + 1) * menuitem_height)
        scrolled_window.add_with_viewport(grid)
        return scrolled_window
    else:
        return grid
Esempio n. 17
0
 def _add_menu(self, option, icon=None, activate_cb=None):
     if icon is not None:
         menu_item = PaletteMenuItem(icon_name=icon)
         if activate_cb is not None:
             menu_item.connect('activate', activate_cb, [option, icon])
     else:
         menu_item = PaletteMenuItem()
         if activate_cb is not None:
             menu_item.connect('activate', activate_cb, option)
     menu_item.set_label(option)
     self._menu_box.append_item(menu_item)
     menu_item.show()
Esempio n. 18
0
class DisplayPalette(Palette):

    def __init__(self):
        Palette.__init__(self, label=_('My Display'))

        self._screenshot = PaletteMenuItem(_('Take a screenshot'))
        icon = Icon(icon_name='camera-external',
                    pixel_size=style.SMALL_ICON_SIZE)
        self._screenshot.set_image(icon)
        icon.show()
        self._screenshot.connect('activate', self.__screenshot_cb)
        self._screenshot.show()

        self._box = PaletteMenuBox()

        self._brightness_manager = None
        # only add this widget if device available
        if brightness.get_instance().get_path():
            self._add_brightness_manager()

        self._box.append_item(self._screenshot, 0, 0)
        self._box.show()

        self.set_content(self._box)
        self.connect('popup', self.__popup_cb)

    def _add_brightness_manager(self):
        self._brightness_manager = BrightnessManagerWidget(_('Brightness'),
                                                           'brightness-100')
        self._brightness_manager.show()

        separator = PaletteMenuItemSeparator()
        separator.show()

        self._box.append_item(self._brightness_manager, 0, 0)
        self._box.append_item(separator, 0, 0)

    def __popup_cb(self, palette):
        if self._brightness_manager is not None:
            self._brightness_manager.update()

    def __screenshot_cb(self, palette):
        frame_ = frame.get_view()
        frame_.hide()
        GObject.idle_add(self.__take_screenshot_cb, frame_)

    def __take_screenshot_cb(self, frame_):
        if frame_.is_visible():
            return True
        take_screenshot()
        frame_.show()
        return False
Esempio n. 19
0
    def set_palette_list(self, options):
        _menu_item = PaletteMenuItem(text_label=options[options.keys()[0]])
        req2 = _menu_item.get_preferred_size()[1]
        menuitem_width = req2.width
        menuitem_height = req2.height

        palette_width = Gdk.Screen.width() - style.GRID_CELL_SIZE
        palette_height = Gdk.Screen.height() - style.GRID_CELL_SIZE * 3

        nx = min(self._MAXIMUM_PALETTE_COLUMNS,
                 int(palette_width / menuitem_width))
        ny = min(int(palette_height / menuitem_height), len(options) + 1)
        if ny >= len(options):
            nx = 1
            ny = len(options)

        grid = Gtk.Grid()
        grid.set_row_spacing(style.DEFAULT_PADDING)
        grid.set_column_spacing(0)
        grid.set_border_width(0)
        grid.show()

        x = 0
        y = 0

        for key in options.keys():
            menu_item = PaletteMenuItem()
            menu_item.set_label(options[key])

            menu_item.set_size_request(style.GRID_CELL_SIZE * 3, -1)

            menu_item.connect('button-release-event', self._option_selected,
                              key)
            grid.attach(menu_item, x, y, 1, 1)
            x += 1
            if x == nx:
                x = 0
                y += 1

            menu_item.show()

        if palette_height < (y * menuitem_height + style.GRID_CELL_SIZE):
            # if the grid is bigger than the palette, put in a scrolledwindow
            scrolled_window = Gtk.ScrolledWindow()
            scrolled_window.set_policy(Gtk.PolicyType.NEVER,
                                       Gtk.PolicyType.AUTOMATIC)
            scrolled_window.set_size_request(nx * menuitem_width,
                                             (ny + 1) * menuitem_height)
            scrolled_window.add_with_viewport(grid)
            return scrolled_window
        else:
            return grid
Esempio n. 20
0
class OwnerIcon(BuddyIcon):
    __gtype_name__ = 'SugarFavoritesOwnerIcon'

    __gsignals__ = {
        'register-activate': (GObject.SignalFlags.RUN_FIRST, None,
                              ([])),
    }

    def __init__(self, size):
        BuddyIcon.__init__(self, buddy=get_owner_instance(), pixel_size=size)

        self.palette_invoker.cache_palette = True

        self._palette_enabled = False
        self._register_menu = None

    def create_palette(self):
        if not self._palette_enabled:
            self._palette_enabled = True
            return

        palette = BuddyMenu(get_owner_instance())

        client = GConf.Client.get_default()
        backup_url = client.get_string('/desktop/sugar/backup_url')

        if not backup_url:
            self._register_menu = PaletteMenuItem(_('Register'),
                                                  'media-record')
        else:
            self._register_menu = PaletteMenuItem(_('Register again'),
                                                  'media-record')

        self._register_menu.connect('activate', self.__register_activate_cb)
        palette.menu_box.pack_end(self._register_menu, True, True, 0)
        self._register_menu.show()

        self.connect_to_palette_pop_events(palette)

        return palette

    def __register_activate_cb(self, menuitem):
        self.emit('register-activate')

    def set_registered(self):
        self.palette.menu_box.remove(self._register_menu)
        self._register_menu = PaletteMenuItem(_('Register again'),
                                              'media-record')
        self._register_menu.connect('activate', self.__register_activate_cb)
        self.palette.menu_box.pack_end(self._register_menu, True, True, 0)
        self._register_menu.show()
Esempio n. 21
0
    def __init__(self, url):
        Palette.__init__(self, url)
        self.owns_clipboard = False
        self.url = self._url_check_protocol(url)

        menu_box = Gtk.VBox()
        self.set_content(menu_box)
        menu_box.show()
        self._content.set_border_width(1)
        menu_item = PaletteMenuItem(_('Copy to Clipboard'), 'edit-copy')
        menu_item.connect('activate', self._copy_to_clipboard_cb)
        menu_box.pack_start(menu_item, False, False, 0)
        menu_item.show()
        self.props.invoker = ContentInvoker()
Esempio n. 22
0
    def _create_export_button(self):
        # Add expoprt button
        export_data = ToolButton('save-as-data')

        export_data.props.tooltip = _('Export data')
        export_data.props.hide_tooltip_on_click = False
        export_data.palette_invoker.props.toggle_palette = True
        export_data.show()

        menu_box = PaletteMenuBox()
        export_data.props.palette.set_content(menu_box)

        menu_item = PaletteMenuItem(text_label=_('Export credits by day'))
        menu_item.connect('activate', self.__export_data_to_chart_cb,
                          'credit', DAY)
        menu_box.append_item(menu_item)

        menu_item = PaletteMenuItem(text_label=_('Export debits by day'))
        menu_item.connect('activate', self.__export_data_to_chart_cb,
                          'debit', DAY)
        menu_box.append_item(menu_item)

        menu_item = PaletteMenuItem(text_label=_('Export credits by month'))
        menu_item.connect('activate', self.__export_data_to_chart_cb,
                          'credit', MONTH)
        menu_box.append_item(menu_item)

        menu_item = PaletteMenuItem(text_label=_('Export debits by month'))
        menu_item.connect('activate', self.__export_data_to_chart_cb,
                          'debit', MONTH)
        menu_box.append_item(menu_item)

        menu_box.show_all()
        return export_data
Esempio n. 23
0
    def _show_menu(self):
        logging.error('Show menu ')
        if self._palette_invoker is not None:
            self._palette = Palette(_('Select tag'))
            menu_box = PaletteMenuBox()
            self._palette.set_content(menu_box)
            menu_box.show()
            for tag in TAG_LIST:
                menu_item = PaletteMenuItem()
                menu_item.set_label(tag)
                menu_item.connect('activate', self._add_tag, tag)
                menu_box.append_item(menu_item)
                menu_item.show()

            self._palette_invoker.set_palette(self._palette)
            self._palette.popup(immediate=True)
Esempio n. 24
0
def set_palette_list(palette_list, nx, ny, item_height, return_dict=False):
    palette_dict = {}
    item_width = style.GRID_CELL_SIZE * 3

    grid = Gtk.Grid()
    grid.set_row_spacing(style.DEFAULT_PADDING)
    grid.set_column_spacing(0)
    grid.set_border_width(0)

    scrolled_window = Gtk.ScrolledWindow()
    scrolled_window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
    scrolled_window.set_size_request(nx * item_width, ny * item_height)
    scrolled_window.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
    scrolled_window.add_with_viewport(grid)
    grid.show()

    x = 0
    y = 0

    for item in palette_list:
        menu_item = PaletteMenuItem()
        menu_item.set_label(item['label'])
        menu_item.set_image(item['icon'])
        item['icon'].show()
        if return_dict:
            menu_item.set_image(item['selected'])
            item['selected'].hide()

        if return_dict:
            palette_dict[item['label']] = {'menu': menu_item,
                                           'icon': item['icon'],
                                           'selected': item['selected']}

        menu_item.connect('button-release-event', item['callback'],
                          item['label'])
        grid.attach(menu_item, x, y, 1, 1)
        x += 1
        if x == nx:
            x = 0
            y += 1

        menu_item.show()

    if return_dict:
        return scrolled_window, palette_dict
    else:
        return scrolled_window
Esempio n. 25
0
    def __init__(self, activity_info):
        self._activity_info = activity_info

        color = profile.get_color()
        activity_icon = Icon(file=activity_info.get_icon(), xo_color=color, pixel_size=style.STANDARD_ICON_SIZE)

        name = activity_info.get_name()
        Palette.__init__(self, primary_text=GLib.markup_escape_text(name), icon=activity_icon)

        xo_color = XoColor("%s,%s" % (style.COLOR_WHITE.get_svg(), style.COLOR_TRANSPARENT.get_svg()))
        self.menu_box = PaletteMenuBox()
        menu_item = PaletteMenuItem(text_label=_("Start new"), file_name=activity_info.get_icon(), xo_color=xo_color)
        menu_item.connect("activate", self.__start_activate_cb)
        self.menu_box.pack_end(menu_item, True, True, 0)
        menu_item.show()
        self.set_content(self.menu_box)
        self.menu_box.show_all()
Esempio n. 26
0
    def create_palette(self):
        palette = VolumePalette(self._mount)
        palette.set_group_id('frame')

        menu_item = PaletteMenuItem(_('Show contents'))
        color = profile.get_color()
        icon = Icon(icon_name=self._icon_name, icon_size=Gtk.IconSize.MENU,
                    xo_color=color)
        menu_item.set_image(icon)
        icon.show()

        menu_item.connect('activate', self.__show_contents_cb)
        palette.content_box.pack_start(menu_item, True, True, 0)
        palette.content_box.reorder_child(menu_item, 0)
        menu_item.show()

        return palette
Esempio n. 27
0
    def create_palette(self):
        palette = VolumePalette(self._mount)
        palette.set_group_id('frame')

        menu_item = PaletteMenuItem(_('Show contents'))
        client = GConf.Client.get_default()
        color = XoColor(client.get_string('/desktop/sugar/user/color'))
        icon = Icon(icon_name=self._icon_name, icon_size=Gtk.IconSize.MENU,
                    xo_color=color)
        menu_item.set_image(icon)
        icon.show()

        menu_item.connect('activate', self.__show_contents_cb)
        palette.content_box.pack_start(menu_item, True, True, 0)
        palette.content_box.reorder_child(menu_item, 0)
        menu_item.show()

        return palette
Esempio n. 28
0
    def create_palette(self):
        palette = VolumePalette(self._mount)
        palette.set_group_id('frame')

        menu_item = PaletteMenuItem(_('Show contents'))
        color = get_mount_color(self._mount)
        icon = Icon(icon_name=self._icon_name,
                    pixel_size=style.SMALL_ICON_SIZE,
                    xo_color=color)
        menu_item.set_image(icon)
        icon.show()

        menu_item.connect('activate', self.__show_contents_cb)
        palette.content_box.pack_start(menu_item, True, True, 0)
        palette.content_box.reorder_child(menu_item, 0)
        menu_item.show()

        return palette
Esempio n. 29
0
    def setup_palette(self):
        activity_name = self._home_activity.get_activity_name()
        if activity_name:
            self.props.primary_text = activity_name

        title = self._home_activity.get_title()
        if title and title != activity_name:
            self.props.secondary_text = title

        self.menu_box = PaletteMenuBox()

        menu_item = PaletteMenuItem(_('Resume'), 'activity-start')
        menu_item.connect('activate', self.__resume_activate_cb)
        self.menu_box.append_item(menu_item)
        menu_item.show()

        # TODO: share-with, keep

        menu_item = PaletteMenuItem(_('View Source'), 'view-source')
        menu_item.connect('activate', self.__view_source__cb)
        menu_item.set_accelerator('Shift+Alt+V')
        self.menu_box.append_item(menu_item)
        menu_item.show()

        help_url_and_title = get_help_url_and_title(self._home_activity)
        if help_url_and_title:
            menu_item = PaletteMenuItem(_('View Help'), 'toolbar-help')
            menu_item.connect('activate', self.__view_help__cb)
            menu_item.set_accelerator('Shift+Alt+H')
            self.menu_box.append_item(menu_item)
            menu_item.show()

        # avoid circular importing reference
        from jarabe.frame.notification import NotificationBox

        menu_item = NotificationBox(self._home_activity.get_activity_id())
        self.menu_box.append_item(menu_item, 0, 0)

        separator = PaletteMenuItemSeparator()
        menu_item.add(separator)
        menu_item.reorder_child(separator, 0)
        separator.show()

        separator = PaletteMenuItemSeparator()
        self.menu_box.append_item(separator)
        separator.show()

        menu_item = PaletteMenuItem(_('Stop'), 'activity-stop')
        menu_item.connect('activate', self.__stop_activate_cb)
        self.menu_box.append_item(menu_item)
        menu_item.show()

        self.set_content(self.menu_box)
        self.menu_box.show()
Esempio n. 30
0
    def _add_buddy_items(self):
        menu_item = None
        if friends.get_model().has_buddy(self._buddy):
            menu_item = PaletteMenuItem(_("Remove friend"), "list-remove")
            menu_item.connect("activate", self._remove_friend_cb)
        else:
            menu_item = PaletteMenuItem(_("Make friend"), "list-add")
            menu_item.connect("activate", self._make_friend_cb)

        self.menu_box.pack_start(menu_item, True, True, 0)

        self._invite_menu = PaletteMenuItem("")
        self._invite_menu.connect("activate", self._invite_friend_cb)
        self.menu_box.pack_start(self._invite_menu, True, True, 0)

        home_model = shell.get_model()
        self._active_activity_changed_hid = home_model.connect("active-activity-changed", self._cur_activity_changed_cb)
        activity = home_model.get_active_activity()
        self._update_invite_menu(activity)
Esempio n. 31
0
class ActivityListPalette(ActivityPalette):
    __gtype_name__ = 'SugarActivityListPalette'

    __gsignals__ = {
        'erase-activated': (GObject.SignalFlags.RUN_FIRST, None, ([str])),
    }

    def __init__(self, activity_info):
        ActivityPalette.__init__(self, activity_info)

        self._bundle_id = activity_info.get_bundle_id()
        self._version = activity_info.get_activity_version()

        registry = bundleregistry.get_registry()
        self._favorite = registry.is_bundle_favorite(self._bundle_id,
                                                     self._version)

        self._favorite_item = PaletteMenuItem()
        self._favorite_icon = Icon(icon_name='emblem-favorite',
                                   icon_size=Gtk.IconSize.MENU)
        self._favorite_item.set_image(self._favorite_icon)
        self._favorite_icon.show()
        self._favorite_item.connect('activate',
                                    self.__change_favorite_activate_cb)
        self.menu_box.append_item(self._favorite_item)
        self._favorite_item.show()

        if activity_info.is_user_activity():
            self._add_erase_option(registry, activity_info)

        registry = bundleregistry.get_registry()
        self._activity_changed_sid = registry.connect(
            'bundle_changed', self.__activity_changed_cb)
        self._update_favorite_item()

        self.menu_box.connect('destroy', self.__destroy_cb)

    def _add_erase_option(self, registry, activity_info):
        menu_item = PaletteMenuItem(_('Erase'), 'list-remove')
        menu_item.connect('activate', self.__erase_activate_cb)
        self.menu_box.append_item(menu_item)
        menu_item.show()

        if not os.access(activity_info.get_path(), os.W_OK) or \
           registry.is_activity_protected(self._bundle_id):
            menu_item.props.sensitive = False

    def __destroy_cb(self, palette):
        registry = bundleregistry.get_registry()
        registry.disconnect(self._activity_changed_sid)

    def _update_favorite_item(self):
        if self._favorite:
            self._favorite_item.set_label(_('Remove favorite'))
            xo_color = XoColor('%s,%s' % (style.COLOR_WHITE.get_svg(),
                                          style.COLOR_TRANSPARENT.get_svg()))
        else:
            self._favorite_item.set_label(_('Make favorite'))
            client = GConf.Client.get_default()
            xo_color = XoColor(client.get_string('/desktop/sugar/user/color'))

        self._favorite_icon.props.xo_color = xo_color

    def __change_favorite_activate_cb(self, menu_item):
        registry = bundleregistry.get_registry()
        registry.set_bundle_favorite(self._bundle_id, self._version,
                                     not self._favorite)

    def __activity_changed_cb(self, activity_registry, activity_info):
        if activity_info.get_bundle_id() == self._bundle_id and \
               activity_info.get_activity_version() == self._version:
            registry = bundleregistry.get_registry()
            self._favorite = registry.is_bundle_favorite(
                self._bundle_id, self._version)
            self._update_favorite_item()

    def __erase_activate_cb(self, menu_item):
        self.emit('erase-activated', self._bundle_id)
Esempio n. 32
0
class SugarAdhocView(EventPulsingIcon):
    """To mimic the mesh behavior on devices where mesh hardware is
    not available we support the creation of an Ad-hoc network on
    three channels 1, 6, 11. This is the class for an icon
    representing a channel in the neighborhood view.

    """

    _ICON_NAME = 'network-adhoc-'
    _NAME = 'Ad-hoc Network '

    def __init__(self, channel):
        EventPulsingIcon.__init__(self,
                                  icon_name=self._ICON_NAME + str(channel),
                                  pixel_size=style.STANDARD_ICON_SIZE,
                                  cache=True)
        self._bus = dbus.SystemBus()
        self._channel = channel
        self._disconnect_item = None
        self._connect_item = None
        self._palette_icon = None
        self._filtered = False

        get_adhoc_manager_instance().connect('members-changed',
                                             self.__members_changed_cb)
        get_adhoc_manager_instance().connect('state-changed',
                                             self.__state_changed_cb)

        pulse_color = XoColor('%s,%s' % (style.COLOR_BUTTON_GREY.get_svg(),
                                         style.COLOR_TRANSPARENT.get_svg()))
        self.props.pulse_color = pulse_color
        self._state_color = XoColor('%s,%s' % \
                                       (profile.get_color().get_stroke_color(),
                                        style.COLOR_TRANSPARENT.get_svg()))
        self.props.base_color = self._state_color
        self.palette_invoker.props.toggle_palette = True
        self._palette = self._create_palette()
        self.set_palette(self._palette)
        self._palette_icon.props.xo_color = self._state_color

    def _create_palette(self):
        self._palette_icon = Icon( \
                icon_name=self._ICON_NAME + str(self._channel),
                icon_size=style.STANDARD_ICON_SIZE)

        text = _('Ad-hoc Network %d') % (self._channel, )
        palette_ = palette.Palette(GLib.markup_escape_text(text),
                                   icon=self._palette_icon)

        self.menu_box = Gtk.VBox()

        self._connect_item = PaletteMenuItem(_('Connect'))
        icon = Icon(icon_size=Gtk.IconSize.MENU, icon_name='dialog-ok')
        self._connect_item.set_image(icon)
        self._connect_item.connect('activate', self.__connect_activate_cb)
        self.menu_box.add(self._connect_item)

        self._disconnect_item = PaletteMenuItem(_('Disconnect'))
        icon = Icon(icon_size=Gtk.IconSize.MENU, icon_name='media-eject')
        self._disconnect_item.set_image(icon)
        self._disconnect_item.connect('activate',
                                      self.__disconnect_activate_cb)
        self.menu_box.add(self._disconnect_item)

        palette_.set_content(self.menu_box)
        self.menu_box.show_all()
        self._disconnect_item.hide()

        self.connect_to_palette_pop_events(palette_)

        return palette_

    def __connect_activate_cb(self, icon):
        get_adhoc_manager_instance().activate_channel(self._channel)

    def __disconnect_activate_cb(self, icon):
        get_adhoc_manager_instance().deactivate_active_channel()

    def __state_changed_cb(self, adhoc_manager, channel, device_state):
        if self._channel == channel:
            state = device_state
        else:
            state = network.NM_DEVICE_STATE_UNKNOWN

        if state == network.NM_DEVICE_STATE_ACTIVATED:
            icon_name = '%s-connected' % (self._ICON_NAME + str(self._channel))
        else:
            icon_name = self._ICON_NAME + str(self._channel)

        if icon_name is not None:
            self.props.icon_name = icon_name
            icon = self._palette.props.icon
            icon.props.icon_name = icon_name

        if (state >= network.NM_DEVICE_STATE_PREPARE) and \
           (state <= network.NM_DEVICE_STATE_IP_CONFIG):
            if self._disconnect_item:
                self._disconnect_item.show()
            self._connect_item.hide()
            self._palette.props.secondary_text = _('Connecting...')
            self.props.pulsing = True
        elif state == network.NM_DEVICE_STATE_ACTIVATED:
            if self._disconnect_item:
                self._disconnect_item.show()
            self._connect_item.hide()
            self._palette.props.secondary_text = _('Connected')
            self.props.pulsing = False
        else:
            if self._disconnect_item:
                self._disconnect_item.hide()
            self._connect_item.show()
            self._palette.props.secondary_text = None
            self.props.pulsing = False
        self._update_color()

    def _update_color(self):
        self.props.base_color = self._state_color
        if self._filtered:
            self.props.pulsing = False
            self.alpha = _FILTERED_ALPHA
        else:
            self.alpha = 1.0

    def __members_changed_cb(self, adhoc_manager, channel, has_members):
        if channel == self._channel:
            if has_members == True:
                self._state_color = profile.get_color()
            else:
                color = '%s,%s' % (profile.get_color().get_stroke_color(),
                                   style.COLOR_TRANSPARENT.get_svg())
                self._state_color = XoColor(color)

            if not self._filtered:
                self.props.base_color = self._state_color
                self._palette_icon.props.xo_color = self._state_color
                self.alpha = 1.0
            else:
                self.alpha = _FILTERED_ALPHA

    def set_filter(self, query):
        name = self._NAME + str(self._channel)
        self._filtered = name.lower().find(query) == -1
        self._update_color()
Esempio n. 33
0
    def __init__(self, toolbar, edit_toolbar, activity):

        self._page = activity.page
        self._activity = activity

        # agregar cuadro
        self.add_photo = ToolButton()
        self.add_photo.props.icon_name = 'insert-picture'
        self.add_photo.connect('clicked', self.__add_photo_clicked_cb)
        self.add_photo.set_tooltip(_('Add Photo'))
        toolbar.insert(self.add_photo, -1)

        self._globes = {
            'globe': _('Globe'),
            'think': _('Think'),
            'whisper': _('Whisper'),
            'exclamation': _('Exclamation'),
            'box': _('Box')
        }

        self._globes_menu = ToolButton(icon_name='globe')
        self._globes_menu.props.tooltip = _('Add a globe')
        self._globes_menu.props.hide_tooltip_on_click = False
        self._globes_menu.palette_invoker.props.toggle_palette = True

        menu_box = PaletteMenuBox()
        self._globes_menu.props.palette.set_content(menu_box)
        menu_box.show()

        for globe in list(self._globes.keys()):
            menu_item = PaletteMenuItem(icon_name=globe,
                                        text_label=self._globes[globe])
            menu_item.connect('activate', self.__activate_add_globe_cb, globe)
            menu_box.append_item(menu_item)
            menu_item.show()
        toolbar.insert(self._globes_menu, -1)

        # lineas de movimiento
        # Agregar aqui el nombre de archivo de una linea de moviemiento
        self._lines = {
            'curves': _('Curves'),
            'straight': _('Straight'),
            'highlight': _('Highlight'),
            'idea': _('Idea')
        }

        self._lines_menu = ToolButton(icon_name='curves')
        self._lines_menu.props.tooltip = _('Choose a movement line')
        self._lines_menu.props.hide_tooltip_on_click = False
        self._lines_menu.palette_invoker.props.toggle_palette = True

        menu_box = PaletteMenuBox()
        self._lines_menu.props.palette.set_content(menu_box)
        menu_box.show()

        for line in list(self._lines.keys()):
            menu_item = PaletteMenuItem(icon_name=line,
                                        text_label=self._lines[line])
            menu_item.connect('activate', self.__activate_add_line_cb, line)
            menu_box.append_item(menu_item)
            menu_item.show()
        toolbar.insert(self._lines_menu, -1)

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

        # girar
        self.b_girar = ToolButton('object-rotate-right')
        self.b_girar.connect('clicked', self.girar)
        self.b_girar.set_tooltip(_('Turn'))
        self.b_girar.show()
        edit_toolbar.insert(self.b_girar, -1)

        # borrar
        self.b_borrar = ToolButton('gtk-delete')
        self.b_borrar.connect('clicked', self.borrar)
        self.b_borrar.set_tooltip(_('Delete'))
        self.b_borrar.show()
        edit_toolbar.insert(self.b_borrar, -1)
Esempio n. 34
0
class PrimaryToolbar(ToolbarBase):
    __gtype_name__ = 'PrimaryToolbar'

    __gsignals__ = {
        'add-link': (GObject.SignalFlags.RUN_FIRST, None, ([])),
        'go-home': (GObject.SignalFlags.RUN_FIRST, None, ([])),
        'reset-home': (GObject.SignalFlags.RUN_FIRST, None, ([])),
        'go-library': (GObject.SignalFlags.RUN_FIRST, None, ([])),
    }

    def __init__(self, tabbed_view, act):
        ToolbarBase.__init__(self)

        self._url_toolbar = UrlToolbar()

        self._activity = act

        self._tabbed_view = self._canvas = tabbed_view

        self._loading = False

        toolbar = self.toolbar
        activity_button = ActivityToolbarButton(self._activity)
        toolbar.insert(activity_button, 0)

        separator = Gtk.SeparatorToolItem()

        save_as_pdf = ToolButton('save-as-pdf')
        save_as_pdf.set_tooltip(_('Save page as pdf'))
        save_as_pdf.connect('clicked', self.save_as_pdf)

        activity_button.props.page.insert(separator, -1)
        activity_button.props.page.insert(save_as_pdf, -1)
        separator.show()
        save_as_pdf.show()

        self._go_home = ToolButton('go-home')
        self._go_home.set_tooltip(_('Home page'))
        self._go_home.connect('clicked', self._go_home_cb)
        # add a menu to save the home page
        menu_box = PaletteMenuBox()
        self._go_home.props.palette.set_content(menu_box)

        self._reset_home_menu = PaletteMenuItem()
        self._reset_home_menu.set_label(_('Reset initial page'))
        self._reset_home_menu.connect('activate', self._reset_home_cb)
        menu_box.append_item(self._reset_home_menu)

        if os.path.isfile(LIBRARY_PATH):
            library_menu = PaletteMenuItem()
            library_menu.set_label(_('Library'))
            library_menu.connect('activate', self._go_library_cb)
            menu_box.append_item(library_menu)

        menu_box.show_all()

        # verify if the home page is configured
        self._reset_home_menu.set_visible(False)

        toolbar.insert(self._go_home, -1)
        self._go_home.show()

        self.entry = WebEntry()
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-stop')
        self.entry.connect('icon-press', self._stop_and_reload_cb)
        self.entry.connect('activate', self._entry_activate_cb)
        self.entry.connect('focus-in-event', self.__focus_in_event_cb)
        self.entry.connect('focus-out-event', self.__focus_out_event_cb)
        self.entry.connect('key-press-event', self.__key_press_event_cb)
        self.entry.connect('changed', self.__changed_cb)

        self._entry_item = Gtk.ToolItem()
        self._entry_item.set_expand(True)
        self._entry_item.add(self.entry)
        self.entry.show()

        toolbar.insert(self._entry_item, -1)

        self._entry_item.show()

        self._back = ToolButton('go-previous-paired')
        self._back.set_tooltip(_('Back'))
        self._back.props.sensitive = False
        self._back.connect('clicked', self._go_back_cb)
        toolbar.insert(self._back, -1)
        self._back.show()

        palette = self._back.get_palette()
        self._back_box_menu = Gtk.VBox()
        self._back_box_menu.show()
        palette.set_content(self._back_box_menu)
        # FIXME, this is a hack, should be done in the theme:
        palette._content.set_border_width(1)

        self._forward = ToolButton('go-next-paired')
        self._forward.set_tooltip(_('Forward'))
        self._forward.props.sensitive = False
        self._forward.connect('clicked', self._go_forward_cb)
        toolbar.insert(self._forward, -1)
        self._forward.show()

        palette = self._forward.get_palette()
        self._forward_box_menu = Gtk.VBox()
        self._forward_box_menu.show()
        palette.set_content(self._forward_box_menu)
        # FIXME, this is a hack, should be done in the theme:
        palette._content.set_border_width(1)

        self._link_add = ToolButton('emblem-favorite')
        self._link_add.set_tooltip(_('Bookmark'))
        self._link_add.connect('clicked', self._link_add_clicked_cb)
        toolbar.insert(self._link_add, -1)
        self._link_add.show()

        self._toolbar_separator = Gtk.SeparatorToolItem()
        self._toolbar_separator.props.draw = False
        self._toolbar_separator.set_expand(True)

        stop_button = StopButton(self._activity)
        toolbar.insert(stop_button, -1)

        self._progress_listener = None
        self._browser = None

        self._loading_changed_hid = None
        self._progress_changed_hid = None
        self._session_history_changed_hid = None
        self._uri_changed_hid = None
        self._security_status_changed_hid = None

        if tabbed_view.get_n_pages():
            self._connect_to_browser(tabbed_view.props.current_browser)

        tabbed_view.connect_after('switch-page', self.__switch_page_cb)
        tabbed_view.connect_after('page-added', self.__page_added_cb)

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

        self._configure_toolbar()

    def __key_press_event_cb(self, entry, event):
        self._tabbed_view.current_browser.loading_uri = entry.props.text

    def __switch_page_cb(self, tabbed_view, page, page_num):
        if tabbed_view.get_n_pages():
            self._connect_to_browser(tabbed_view.props.current_browser)

    def __page_added_cb(self, notebook, child, pagenum):
        self.entry._search_popdown()

    def _configure_toolbar(self, screen=None):
        # Adapt the toolbars for portrait or landscape mode.

        if screen is None:
            screen = Gdk.Screen.get_default()

        if screen.get_width() < screen.get_height():
            if self._entry_item in self._url_toolbar.toolbar.get_children():
                return

            self.toolbar.remove(self._entry_item)
            self._url_toolbar.toolbar.insert(self._entry_item, -1)

            separator_pos = len(self.toolbar.get_children()) - 1
            self.toolbar.insert(self._toolbar_separator, separator_pos)
            self._toolbar_separator.show()

            self.pack_end(self._url_toolbar, True, True, 0)
            self._url_toolbar.show()

        else:
            if self._entry_item in self.toolbar.get_children():
                return

            self.toolbar.remove(self._toolbar_separator)

            position = len(self.toolbar.get_children()) - 4
            self._url_toolbar.toolbar.remove(self._entry_item)
            self.toolbar.insert(self._entry_item, position)

            self._toolbar_separator.hide()
            self.remove(self._url_toolbar)

    def __screen_size_changed_cb(self, screen):
        self._configure_toolbar(screen)

    def _connect_to_browser(self, browser):
        if self._browser is not None:
            self._browser.disconnect(self._uri_changed_hid)
            self._browser.disconnect(self._progress_changed_hid)
            self._browser.disconnect(self._loading_changed_hid)
            self._browser.disconnect(self._security_status_changed_hid)

        self._browser = browser
        if not isinstance(self._browser, DummyBrowser):
            address = self._browser.props.uri or self._browser.loading_uri
        else:
            address = self._browser.props.uri
        self._set_address(address)
        self._set_progress(self._browser.props.progress)
        self._set_status(self._browser.props.load_status)
        self._set_security_status(self._browser.security_status)

        is_webkit_browser = isinstance(self._browser, Browser)
        self.entry.props.editable = is_webkit_browser

        self._uri_changed_hid = self._browser.connect('notify::uri',
                                                      self.__uri_changed_cb)
        self._progress_changed_hid = self._browser.connect(
            'notify::progress', self.__progress_changed_cb)
        self._loading_changed_hid = self._browser.connect(
            'notify::load-status', self.__loading_changed_cb)
        self._security_status_changed_hid = self._browser.connect(
            'security-status-changed', self.__security_status_changed_cb)

        self._update_navigation_buttons()

    def __loading_changed_cb(self, widget, param):
        self._set_status(widget.get_load_status())

    def __security_status_changed_cb(self, widget):
        self._set_security_status(widget.security_status)

    def __progress_changed_cb(self, widget, param):
        self._set_progress(widget.get_progress())

    def _set_status(self, status):
        self._set_loading(status < WebKit.LoadStatus.FINISHED)

    def _set_security_status(self, security_status):
        # Display security status as a lock icon in the left side of
        # the URL entry.
        if security_status is None:
            self.entry.set_icon_from_pixbuf(iconentry.ICON_ENTRY_PRIMARY, None)
        elif security_status == Browser.SECURITY_STATUS_SECURE:
            self.entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY,
                                          'channel-secure-symbolic')
        elif security_status == Browser.SECURITY_STATUS_INSECURE:
            self.entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY,
                                          'channel-insecure-symbolic')

    def _set_progress(self, progress):
        if progress == 1.0:
            self.entry.set_progress_fraction(0.0)
        else:
            self.entry.set_progress_fraction(progress)

    def _set_address(self, uri):
        if uri is None:
            self.entry.props.address = ''
        else:
            self.entry.props.address = uri

    def __changed_cb(self, iconentry):
        # The WebEntry can be changed when we click on a link, then we
        # have to show the clear icon only if is the user who has
        # changed the entry
        if self.entry.has_focus():
            if not self.entry.props.text:
                self._show_no_icon()
            else:
                self._show_clear_icon()

    def __focus_in_event_cb(self, entry, event):
        if not self._tabbed_view.is_current_page_pdf():
            if not self.entry.props.text:
                self._show_no_icon()
            else:
                self._show_clear_icon()

    def __focus_out_event_cb(self, entry, event):
        if self._loading:
            self._show_stop_icon()
        else:
            if not self._tabbed_view.is_current_page_pdf():
                self._show_reload_icon()

    def _show_no_icon(self):
        self.entry.remove_icon(iconentry.ICON_ENTRY_SECONDARY)

    def _show_stop_icon(self):
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-stop')

    def _show_reload_icon(self):
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-refresh')

    def _show_clear_icon(self):
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-cancel')

    def _update_navigation_buttons(self):
        can_go_back = self._browser.can_go_back()
        self._back.props.sensitive = can_go_back

        can_go_forward = self._browser.can_go_forward()
        self._forward.props.sensitive = can_go_forward

        is_webkit_browser = isinstance(self._browser, Browser)
        self._link_add.props.sensitive = is_webkit_browser
        self._go_home.props.sensitive = is_webkit_browser
        if is_webkit_browser:
            self._reload_session_history()

    def _entry_activate_cb(self, entry):
        url = entry.props.text
        effective_url = self._tabbed_view.normalize_or_autosearch_url(url)
        self._browser.load_uri(effective_url)
        self._browser.loading_uri = effective_url
        self.entry.props.address = effective_url
        self._browser.grab_focus()

    def _go_home_cb(self, button):
        self.emit('go-home')

    def _go_library_cb(self, button):
        self.emit('go-library')

    def _reset_home_cb(self, button):
        self._reset_home_menu.set_visible(False)
        self.emit('reset-home')

    def _go_back_cb(self, button):
        self._browser.go_back()

    def _go_forward_cb(self, button):
        self._browser.go_forward()

    def __uri_changed_cb(self, widget, param):
        self._set_address(widget.get_uri())
        self._update_navigation_buttons()
        filepicker.cleanup_temp_files()

    def _stop_and_reload_cb(self, entry, icon_pos, button):
        if entry.has_focus() and \
                not self._tabbed_view.is_current_page_pdf():
            entry.set_text('')
        else:
            if self._loading:
                self._browser.stop_loading()
            else:
                self._browser.reload()

    def _set_loading(self, loading):
        self._loading = loading

        if self._loading:
            self._show_stop_icon()
        else:
            if not self._tabbed_view.is_current_page_pdf():
                self.set_sensitive(True)
                self._show_reload_icon()
            else:
                self.set_sensitive(False)
                self._show_no_icon()

    def _reload_session_history(self):
        back_forward_list = self._browser.get_back_forward_list()
        item_index = 0  # The index of the history item

        # Clear menus in palettes:
        for box_menu in (self._back_box_menu, self._forward_box_menu):
            for menu_item in box_menu.get_children():
                box_menu.remove(menu_item)

        def create_menu_item(history_item, item_index):
            """Create a MenuItem for the back or forward palettes."""
            title = history_item.get_title()
            if not isinstance(title, unicode):
                title = unicode(title, 'utf-8')
            # This is a fix until the Sugar MenuItem is fixed:
            menu_item = PaletteMenuItem(text_label=title)
            menu_item.connect('activate', self._history_item_activated_cb,
                              item_index)
            return menu_item

        back_list = back_forward_list.get_back_list_with_limit(
            _MAX_HISTORY_ENTRIES)
        back_list.reverse()
        for item in back_list:
            menu_item = create_menu_item(item, item_index)
            self._back_box_menu.pack_end(menu_item, False, False, 0)
            menu_item.show()
            item_index += 1

        # Increment the item index to count the current page:
        item_index += 1

        forward_list = back_forward_list.get_forward_list_with_limit(
            _MAX_HISTORY_ENTRIES)
        forward_list.reverse()
        for item in forward_list:
            menu_item = create_menu_item(item, item_index)
            self._forward_box_menu.pack_start(menu_item, False, False, 0)
            menu_item.show()
            item_index += 1

    def _history_item_activated_cb(self, menu_item, index):
        self._back.get_palette().popdown(immediate=True)
        self._forward.get_palette().popdown(immediate=True)
        self._browser.set_history_index(index)

    def _link_add_clicked_cb(self, button):
        self.emit('add-link')

    def save_as_pdf(self, widget):
        tmp_dir = os.path.join(self._activity.get_activity_root(), 'tmp')
        fd, file_path = tempfile.mkstemp(dir=tmp_dir)
        os.close(fd)

        page = self._canvas.get_current_page()
        webview = self._canvas.get_children()[page].get_children()[0]

        operation = Gtk.PrintOperation.new()
        operation.set_export_filename(file_path)

        webview.get_main_frame().print_full(operation,
                                            Gtk.PrintOperationAction.EXPORT)

        jobject = datastore.create()
        try:
            jobject.metadata['title'] = _('Browse activity as PDF')
            jobject.metadata['mime_type'] = 'application/pdf'
            jobject.file_path = file_path
            datastore.write(jobject)
        finally:
            self.__pdf_alert(jobject.object_id)
            jobject.destroy()
            del jobject

    def __pdf_alert(self, object_id):
        alert = Alert()
        alert.props.title = _('Page saved')
        alert.props.msg = _('The page has been saved as PDF to journal')

        alert.add_button(Gtk.ResponseType.APPLY, _('Show in Journal'),
                         Icon(icon_name='zoom-activity'))
        alert.add_button(Gtk.ResponseType.OK, _('Ok'),
                         Icon(icon_name='dialog-ok'))

        # Remove other alerts
        for alert in self._activity._alerts:
            self._activity.remove_alert(alert)

        self._activity.add_alert(alert)
        alert.connect('response', self.__pdf_response_alert, object_id)
        alert.show_all()

    def __pdf_response_alert(self, alert, response_id, object_id):

        if response_id is Gtk.ResponseType.APPLY:
            activity.show_object_in_journal(object_id)

        self._activity.remove_alert(alert)
Esempio n. 35
0
class GsmPalette(Palette):
    __gtype_name__ = 'SugarGsmPalette'

    __gsignals__ = {
        'gsm-connect': (GObject.SignalFlags.RUN_FIRST, None, ([])),
        'gsm-disconnect': (GObject.SignalFlags.RUN_FIRST, None, ([])),
    }

    def __init__(self):
        Palette.__init__(self, primary_text=_('Wireless modem'))

        self._current_state = None
        self._failed_connection = False

        self.info_box = Gtk.VBox()

        self._toggle_state_item = PaletteMenuItem('')
        self._toggle_state_item.connect('activate', self.__toggle_state_cb)
        self.info_box.pack_start(self._toggle_state_item, True, True, 0)
        self._toggle_state_item.show()

        self.error_title_label = Gtk.Label(label="")
        self.error_title_label.set_alignment(0, 0.5)
        self.error_title_label.set_line_wrap(True)
        self.info_box.pack_start(self.error_title_label, True, True, 0)
        self.error_description_label = Gtk.Label(label="")
        self.error_description_label.set_alignment(0, 0.5)
        self.error_description_label.set_line_wrap(True)
        self.info_box.pack_start(self.error_description_label, True, True, 0)

        self.connection_info_box = Gtk.HBox()
        icon = Icon(icon_name='data-upload', pixel_size=style.SMALL_ICON_SIZE)
        self.connection_info_box.pack_start(icon, True, True, 0)
        icon.show()

        self._data_label_up = Gtk.Label()
        self._data_label_up.props.xalign = 0.0
        label_alignment = self._add_widget_with_padding(self._data_label_up)
        self.connection_info_box.pack_start(label_alignment, True, True, 0)
        self._data_label_up.show()
        label_alignment.show()

        icon = Icon(icon_name='data-download',
                    pixel_size=style.SMALL_ICON_SIZE)
        self.connection_info_box.pack_start(icon, True, True, 0)
        icon.show()
        self._data_label_down = Gtk.Label()
        self._data_label_down.props.xalign = 0.0
        label_alignment = self._add_widget_with_padding(self._data_label_down)
        self.connection_info_box.pack_start(label_alignment, True, True, 0)
        self._data_label_down.show()
        label_alignment.show()

        self.info_box.pack_start(self.connection_info_box, True, True, 0)

        self.info_box.show()
        self.set_content(self.info_box)

        self.update_state(_GSM_STATE_NOT_READY)

    def _add_widget_with_padding(self, child, xalign=0, yalign=0.5):
        alignment = Gtk.Alignment.new(xalign=xalign,
                                      yalign=yalign,
                                      xscale=1,
                                      yscale=0.33)
        alignment.set_padding(style.DEFAULT_SPACING, style.DEFAULT_SPACING,
                              style.DEFAULT_SPACING, style.DEFAULT_SPACING)
        alignment.add(child)
        return alignment

    def update_state(self, state, reason=0):
        self._current_state = state
        self._update_label_and_text(reason)

    def _update_label_and_text(self, reason=0):
        if self._current_state == _GSM_STATE_NOT_READY:
            self._toggle_state_item.set_label('...')
            self.props.secondary_text = _('Please wait...')

        elif self._current_state == _GSM_STATE_DISCONNECTED:
            if not self._failed_connection:
                self._toggle_state_item.set_label(_('Connect'))
            self.props.secondary_text = _('Disconnected')
            icon = Icon(icon_name='dialog-ok',
                        pixel_size=style.SMALL_ICON_SIZE)
            self._toggle_state_item.set_image(icon)

        elif self._current_state == _GSM_STATE_CONNECTING:
            self._toggle_state_item.set_label(_('Cancel'))
            self.props.secondary_text = _('Connecting...')
            icon = Icon(icon_name='dialog-cancel',
                        pixel_size=style.SMALL_ICON_SIZE)
            self._toggle_state_item.set_image(icon)

        elif self._current_state == _GSM_STATE_CONNECTED:
            self._failed_connection = False
            self._toggle_state_item.set_label(_('Disconnect'))
            self.update_connection_time()
            icon = Icon(icon_name='media-eject',
                        pixel_size=style.SMALL_ICON_SIZE)
            self._toggle_state_item.set_image(icon)

        elif self._current_state == _GSM_STATE_FAILED:
            message_error = self._get_error_by_nm_reason(reason)
            self.add_alert(message_error[0], message_error[1])
        else:
            raise ValueError('Invalid GSM state while updating label and '
                             'text, %s' % str(self._current_state))

    def __toggle_state_cb(self, menuitem):
        if self._current_state == _GSM_STATE_NOT_READY:
            pass
        elif self._current_state == _GSM_STATE_DISCONNECTED:
            self.error_title_label.hide()
            self.error_description_label.hide()
            self.emit('gsm-connect')
        elif self._current_state == _GSM_STATE_CONNECTING:
            self.emit('gsm-disconnect')
        elif self._current_state == _GSM_STATE_CONNECTED:
            self.emit('gsm-disconnect')
        else:
            raise ValueError('Invalid GSM state while emitting signal, %s' %
                             str(self._current_state))

    def add_alert(self, error, suggestion):
        self._failed_connection = True
        action = _('Try connection again')
        self._toggle_state_item.set_label(action)

        title = _('Error: %s') % error
        self.error_title_label.set_markup('<b>%s</b>' % title)
        self.error_title_label.show()

        message = _('Suggestion: %s') % suggestion
        self.error_description_label.set_text(message)
        self.error_description_label.show()

    def update_connection_time(self, connection_time=None):
        if connection_time is not None:
            formatted_time = connection_time.strftime('%H:%M:%S')
        else:
            formatted_time = '00:00:00'

        self.props.secondary_text = _('Connected for %s') % (formatted_time, )

    def update_stats(self, in_bytes, out_bytes):
        in_KBytes = in_bytes / 1024
        out_KBytes = out_bytes / 1024
        self._data_label_up.set_text(_('%d KB') % (out_KBytes))
        self._data_label_down.set_text(_('%d KB') % (in_KBytes))

    def _get_error_by_nm_reason(self, reason):
        if reason in [
                network.NM_DEVICE_STATE_REASON_NO_SECRETS,
                network.NM_DEVICE_STATE_REASON_GSM_PIN_CHECK_FAILED
        ]:
            message = _('Check your PIN/PUK configuration.')
        elif reason in [
                network.NM_DEVICE_STATE_REASON_PPP_DISCONNECT,
                network.NM_DEVICE_STATE_REASON_PPP_FAILED
        ]:
            message = _('Check your Access Point Name ' '(APN) configuration')
        elif reason in [
                network.NM_DEVICE_STATE_REASON_MODEM_NO_CARRIER,
                network.NM_DEVICE_STATE_REASON_MODEM_DIAL_TIMEOUT
        ]:
            message = _('Check the Number configuration.')
        elif reason == network.NM_DEVICE_STATE_REASON_CONFIG_FAILED:
            message = _('Check your configuration.')
        else:
            message = ''
        message_tuple = (network.get_error_by_reason(reason), message)
        return message_tuple
Esempio n. 36
0
class OwnerIcon(BuddyIcon):
    __gtype_name__ = 'SugarFavoritesOwnerIcon'

    __gsignals__ = {
        'register-activate': (GObject.SignalFlags.RUN_FIRST, None, ([])),
    }

    def __init__(self, size):
        BuddyIcon.__init__(self, buddy=get_owner_instance(), pixel_size=size)

        self.palette_invoker.cache_palette = True

        self._palette_enabled = False
        self._register_menu = None

        # This is a workaround to skip the callback for
        # enter-notify-event in the parent class the first time.
        def __enter_notify_event_cb(icon, event):
            self.unset_state_flags(Gtk.StateFlags.PRELIGHT)
            self.disconnect(self._enter_notify_hid)

        self._enter_notify_hid = self.connect('enter-notify-event',
                                              __enter_notify_event_cb)

    def create_palette(self):
        if not self._palette_enabled:
            self._palette_enabled = True
            return

        palette = BuddyMenu(get_owner_instance())

        settings = Gio.Settings('org.sugarlabs')
        if settings.get_boolean('show-register'):
            backup_url = settings.get_string('backup-url')

            if not backup_url:
                self._register_menu = PaletteMenuItem(_('Register'),
                                                      'media-record')
            else:
                self._register_menu = PaletteMenuItem(_('Register again'),
                                                      'media-record')

            self._register_menu.connect('activate',
                                        self.__register_activate_cb)
            palette.menu_box.pack_end(self._register_menu, True, True, 0)
            self._register_menu.show()

        self.connect_to_palette_pop_events(palette)

        return palette

    def __register_activate_cb(self, menuitem):
        self.emit('register-activate')

    def set_registered(self):
        self.palette.menu_box.remove(self._register_menu)
        self._register_menu = PaletteMenuItem(_('Register again'),
                                              'media-record')
        self._register_menu.connect('activate', self.__register_activate_cb)
        self.palette.menu_box.pack_end(self._register_menu, True, True, 0)
        self._register_menu.show()
Esempio n. 37
0
    def __after_get_text_cb(self, browser, async_result, user_data):
        self._all_text = self._browser.props.title
        self._browser.run_javascript(
            'document.title = document.SugarBrowseOldTitle')
        self._link_text = self._hit.props.link_label \
            or self._hit.props.link_title

        self._title = self._link_text or self._all_text
        self._url = self._hit.props.link_uri or self._hit.props.image_uri \
            or self._hit.props.media_uri
        self._image_url = self._hit.props.image_uri \
            or self._hit.props.media_uri

        if self._title not in (None, ''):
            self.props.primary_text = GLib.markup_escape_text(self._title)
            if self._url is not None:
                self.props.secondary_text = GLib.markup_escape_text(self._url)
        else:
            if self._url is not None:
                self.props.primary_text = GLib.markup_escape_text(self._url)

        if not self._all_text and not self._url:
            self.popdown(immediate=True)
            return  # Nothing to see here!

        menu_box = Gtk.VBox()
        self.set_content(menu_box)
        menu_box.show()
        self._content.set_border_width(1)

        first_section_added = False
        if self._hit.context_is_link():
            first_section_added = True

            menu_item = PaletteMenuItem(_('Follow link'), 'browse-follow-link')
            menu_item.connect('activate', self.__follow_activate_cb)
            menu_box.pack_start(menu_item, False, False, 0)
            menu_item.show()

            menu_item = PaletteMenuItem(_('Follow link in new tab'),
                                        'browse-follow-link-new-tab')
            menu_item.connect('activate', self.__follow_activate_cb, True)
            menu_box.pack_start(menu_item, False, False, 0)
            menu_item.show()

            # Add "keep link" only if it is not an image.  "Keep
            # image" will be shown in that case.
            if not self._hit.context_is_image():
                menu_item = PaletteMenuItem(_('Keep link'), 'document-save')
                menu_item.icon.props.xo_color = profile.get_color()
                menu_item.connect('activate', self.__download_activate_cb)
                menu_box.pack_start(menu_item, False, False, 0)
                menu_item.show()

            menu_item = PaletteMenuItem(_('Copy link'), 'edit-copy')
            menu_item.icon.props.xo_color = profile.get_color()
            menu_item.connect('activate', self.__copy_cb, self._url)
            menu_box.pack_start(menu_item, False, False, 0)
            menu_item.show()

            if self._link_text:
                menu_item = PaletteMenuItem(_('Copy link text'), 'edit-copy')
                menu_item.icon.props.xo_color = profile.get_color()
                menu_item.connect('activate', self.__copy_cb, self._link_text)
                menu_box.pack_start(menu_item, False, False, 0)
                menu_item.show()

        if self._hit.context_is_image():
            if not first_section_added:
                first_section_added = True
            else:
                separator = PaletteMenuItemSeparator()
                menu_box.pack_start(separator, False, False, 0)
                separator.show()

            # FIXME: Copy image is broken
            menu_item = PaletteMenuItem(_('Copy image'), 'edit-copy')
            menu_item.icon.props.xo_color = profile.get_color()
            menu_item.connect('activate', self.__copy_image_activate_cb)
            menu_box.pack_start(menu_item, False, False, 0)
            menu_item.show()

            menu_item = PaletteMenuItem(_('Keep image'), 'document-save')
            menu_item.icon.props.xo_color = profile.get_color()
            menu_item.connect('activate', self.__download_activate_cb,
                              self._image_url)
            menu_box.pack_start(menu_item, False, False, 0)
            menu_item.show()

        if self._hit.context_is_selection() and self._all_text:
            if not first_section_added:
                first_section_added = True
            else:
                separator = PaletteMenuItemSeparator()
                menu_box.pack_start(separator, False, False, 0)
                separator.show()

            menu_item = PaletteMenuItem(_('Copy text'), 'edit-copy')
            menu_item.icon.props.xo_color = profile.get_color()
            menu_item.connect('activate', self.__copy_cb, self._all_text)
            menu_box.pack_start(menu_item, False, False, 0)
            menu_item.show()
Esempio n. 38
0
    def __init__(self, pc, toolbar_box):

        GObject.GObject.__init__(self)

        self._abiword_canvas = pc.abiword_canvas

        copy = CopyButton()
        copy.props.accelerator = '<Ctrl>C'
        copy.connect('clicked', lambda button: pc.abiword_canvas.copy())
        self.insert(copy, -1)
        copy.show()

        paste = PasteButton()
        paste.props.accelerator = '<Ctrl>V'
        paste.connect('clicked', self.__paste_button_cb)
        self.insert(paste, -1)
        paste.show()

        menu_box = PaletteMenuBox()
        paste.props.palette.set_content(menu_box)
        menu_box.show()
        menu_item = PaletteMenuItem()
        menu_item.set_label(_('Paste unformatted'))
        menu_item.connect('activate', self.__paste_special_button_cb)
        menu_box.append_item(menu_item)

        separator = Gtk.SeparatorToolItem()
        self.insert(separator, -1)
        separator.show()

        undo = UndoButton(sensitive=True)
        undo.connect('clicked', lambda button: pc.abiword_canvas.undo())
        pc.abiword_canvas.connect(
            "can-undo", lambda abi, can_undo: undo.set_sensitive(can_undo))
        self.insert(undo, -1)
        undo.show()

        redo = RedoButton(sensitive=True)
        redo.connect('clicked', lambda button: pc.abiword_canvas.redo())
        pc.abiword_canvas.connect(
            "can-redo", lambda abi, can_redo: redo.set_sensitive(can_redo))
        self.insert(redo, -1)
        redo.show()

        pc.abiword_canvas.connect('text-selected',
                                  lambda abi, b: copy.set_sensitive(True))
        pc.abiword_canvas.connect('image-selected',
                                  lambda abi, b: copy.set_sensitive(True))
        pc.abiword_canvas.connect('selection-cleared',
                                  lambda abi, b: copy.set_sensitive(False))

        separator = Gtk.SeparatorToolItem()
        self.insert(separator, -1)
        separator.show()

        search_label = Gtk.Label(label=_("Search") + ": ")
        search_label.show()
        search_item_page_label = Gtk.ToolItem()
        search_item_page_label.add(search_label)
        self.insert(search_item_page_label, -1)
        search_item_page_label.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()
        self._add_widget(self._search_entry, expand=True)

        self._findprev = ToolButton('go-previous-paired')
        self._findprev.set_tooltip(_('Find previous'))
        self.insert(self._findprev, -1)
        self._findprev.show()
        self._findprev.connect('clicked', self._findprev_cb)

        self._findnext = ToolButton('go-next-paired')
        self._findnext.set_tooltip(_('Find next'))
        self.insert(self._findnext, -1)
        self._findnext.show()
        self._findnext.connect('clicked', self._findnext_cb)

        # set the initial state of the search controls
        # note: we won't simple call self._search_entry_changed_cb
        # here, as that will call into the abiword_canvas, which
        # is not mapped on screen here, causing the set_find_string
        # call to fail
        self._findprev.set_sensitive(False)
        self._findnext.set_sensitive(False)
Esempio n. 39
0
    def _update(self):
        box = PaletteMenuBox()
        self.set_content(box)
        box.show()

        logging.debug('_update state: %r', self.file_transfer.props.state)
        if self.file_transfer.props.state == filetransfer.FT_STATE_PENDING:
            menu_item = PaletteMenuItem(_('Accept'))
            icon = Icon(icon_name='dialog-ok',
                        pixel_size=style.SMALL_ICON_SIZE)
            menu_item.set_image(icon)
            icon.show()
            menu_item.connect('activate', self.__accept_activate_cb)
            box.append_item(menu_item)
            menu_item.show()

            menu_item = PaletteMenuItem(_('Decline'))
            icon = Icon(icon_name='dialog-cancel',
                        pixel_size=style.SMALL_ICON_SIZE)
            menu_item.set_image(icon)
            icon.show()
            menu_item.connect('activate', self.__decline_activate_cb)
            box.append_item(menu_item)
            menu_item.show()

            separator = PaletteMenuItemSeparator()
            box.append_item(separator)
            separator.show()

            inner_box = Gtk.VBox()
            inner_box.set_spacing(style.DEFAULT_PADDING)
            box.append_item(inner_box, vertical_padding=0)
            inner_box.show()

            if self.file_transfer.description:
                text = self.file_transfer.description.replace('\n', ' ')
                label = Gtk.Label(label=text)
                label.set_max_width_chars(style.MENU_WIDTH_CHARS)
                label.set_ellipsize(style.ELLIPSIZE_MODE_DEFAULT)
                inner_box.add(label)
                label.show()

            mime_type = self.file_transfer.mime_type
            type_description = mime.get_mime_description(mime_type)

            size = self._format_size(self.file_transfer.file_size)
            label = Gtk.Label(label='%s (%s)' % (size, type_description))
            inner_box.add(label)
            label.show()

        elif self.file_transfer.props.state in \
                [filetransfer.FT_STATE_ACCEPTED, filetransfer.FT_STATE_OPEN]:
            menu_item = PaletteMenuItem(_('Cancel'))
            icon = Icon(icon_name='dialog-cancel',
                        pixel_size=style.SMALL_ICON_SIZE)
            menu_item.set_image(icon)
            icon.show()
            menu_item.connect('activate', self.__cancel_activate_cb)
            box.append_item(menu_item)
            menu_item.show()

            separator = PaletteMenuItemSeparator()
            box.append_item(separator)
            separator.show()

            inner_box = Gtk.VBox()
            inner_box.set_spacing(style.DEFAULT_PADDING)
            box.append_item(inner_box, vertical_padding=0)
            inner_box.show()

            self.progress_bar = Gtk.ProgressBar()
            inner_box.add(self.progress_bar)
            self.progress_bar.show()

            self.progress_label = Gtk.Label(label='')
            inner_box.add(self.progress_label)
            self.progress_label.show()

            self.update_progress()

        elif self.file_transfer.props.state == filetransfer.FT_STATE_COMPLETED:
            menu_item = PaletteMenuItem(_('Dismiss'))
            icon = Icon(icon_name='dialog-cancel',
                        pixel_size=style.SMALL_ICON_SIZE)
            menu_item.set_image(icon)
            icon.show()
            menu_item.connect('activate', self.__dismiss_activate_cb)
            box.append_item(menu_item)
            menu_item.show()

            self.update_progress()

        elif self.file_transfer.props.state == filetransfer.FT_STATE_CANCELLED:
            if self.file_transfer.reason_last_change == \
                    filetransfer.FT_REASON_REMOTE_STOPPED:
                menu_item = PaletteMenuItem(_('Dismiss'))
                icon = Icon(icon_name='dialog-cancel',
                            pixel_size=style.SMALL_ICON_SIZE)
                menu_item.set_image(icon)
                icon.show()
                menu_item.connect('activate', self.__dismiss_activate_cb)
                box.append_item(menu_item)
                menu_item.show()

                inner_box = Gtk.VBox()
                inner_box.set_spacing(style.DEFAULT_PADDING)
                box.append_item(inner_box, vertical_padding=0)
                inner_box.show()

                text = _('The other participant canceled the file transfer')
                label = Gtk.Label(label=text)
                inner_box.add(label)
                label.show()
Esempio n. 40
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

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

        # create our main abiword canvas
        self.abiword_canvas = DocumentView()
        self._new_instance = True
        toolbar_box = ToolbarBox()

        self.activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(self.activity_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.show()
        self.activity_button.props.page.insert(separator, 2)
        ExportButtonFactory(self, self.abiword_canvas)
        self.activity_button.show()

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

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

        # due to http://bugzilla.abisource.com/show_bug.cgi?id=13585
        if self.abiword_canvas.get_version() != '3.0':
            self.speech_toolbar_button = ToolbarButton(icon_name='speak')
            toolbar_box.toolbar.insert(self.speech_toolbar_button, -1)
            self._init_speech()

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

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

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

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

        image = ToolButton('insert-picture')
        image.set_tooltip(_('Insert Image'))
        self._image_id = image.connect('clicked', self.__image_cb)
        toolbar_box.toolbar.insert(image, -1)

        palette = image.get_palette()
        box = PaletteMenuBox()
        palette.set_content(box)
        box.show()
        menu_item = PaletteMenuItem(_('Floating'))
        menu_item.connect('activate', self.__image_cb, True)
        box.append_item(menu_item)
        menu_item.show()

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

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

        toolbar_box.show_all()
        self.set_toolbar_box(toolbar_box)

        # add a overlay to be able to show a icon while joining a shared doc
        overlay = Gtk.Overlay()
        overlay.add(self.abiword_canvas)
        overlay.show()

        self._connecting_box = ConnectingBox()
        overlay.add_overlay(self._connecting_box)

        self.set_canvas(overlay)

        # we want a nice border so we can select paragraphs easily
        self.abiword_canvas.set_show_margin(True)

        # Set default font face and size
        self._default_font_face = 'Sans'
        self._default_font_size = 12

        # activity sharing
        self.participants = {}
        self.joined = False

        self.connect('shared', self._shared_cb)

        if self.shared_activity:
            # we are joining the activity
            logger.debug('We are joining an activity')
            # display a icon while joining
            self._connecting_box.show()
            # disable the abi widget
            self.abiword_canvas.set_sensitive(False)
            self._new_instance = False
            self.connect('joined', self._joined_cb)
            self.shared_activity.connect('buddy-joined', self._buddy_joined_cb)
            self.shared_activity.connect('buddy-left', self._buddy_left_cb)
            if self.get_shared():
                self._joined_cb(self)
        else:
            # we are creating the activity
            logger.debug("We are creating an activity")

        self.abiword_canvas.zoom_width()
        self.abiword_canvas.show()
        self.connect_after('map-event', self.__map_activity_event_cb)

        self.abiword_canvas.connect('size-allocate', self.size_allocate_cb)
Esempio n. 41
0
class SpeakerPalette(Palette):
    def __init__(self, primary_text, model):
        Palette.__init__(self, label=primary_text)

        self._model = model

        box = PaletteMenuBox()
        self.set_content(box)
        box.show()

        self._mute_item = PaletteMenuItem('')
        self._mute_icon = Icon(pixel_size=style.SMALL_ICON_SIZE)
        self._mute_item.set_image(self._mute_icon)
        box.append_item(self._mute_item)
        self._mute_item.show()
        self._mute_item.connect('activate', self.__mute_activate_cb)

        separator = PaletteMenuItemSeparator()
        box.append_item(separator)
        separator.show()

        vol_step = sound.VOLUME_STEP
        self._adjustment = Gtk.Adjustment(value=self._model.props.level,
                                          lower=0,
                                          upper=100 + vol_step,
                                          step_incr=vol_step,
                                          page_incr=vol_step,
                                          page_size=vol_step)

        hscale = Gtk.HScale()
        hscale.props.draw_value = False
        hscale.set_adjustment(self._adjustment)
        hscale.set_digits(0)
        box.append_item(hscale, vertical_padding=0)
        hscale.show()

        self._adjustment_handler_id = \
            self._adjustment.connect('value_changed',
                                     self.__adjustment_changed_cb)

        self._model_notify_level_handler_id = \
            self._model.connect('notify::level', self.__level_changed_cb)
        self._model.connect('notify::muted', self.__muted_changed_cb)

        self.connect('popup', self.__popup_cb)

    def _update_muted(self):
        if self._model.props.muted:
            mute_item_text = _('Unmute')
            mute_item_icon_name = 'dialog-ok'
        else:
            mute_item_text = _('Mute')
            mute_item_icon_name = 'dialog-cancel'
        self._mute_item.set_label(mute_item_text)
        self._mute_icon.props.icon_name = mute_item_icon_name
        self._mute_icon.show()

    def _update_level(self):
        if self._adjustment.props.value != self._model.props.level:
            self._adjustment.handler_block(self._adjustment_handler_id)
            try:
                self._adjustment.props.value = self._model.props.level
            finally:
                self._adjustment.handler_unblock(self._adjustment_handler_id)

    def __adjustment_changed_cb(self, adj_):
        self._model.handler_block(self._model_notify_level_handler_id)
        try:
            self._model.props.level = self._adjustment.props.value
        finally:
            self._model.handler_unblock(self._model_notify_level_handler_id)
        self._model.props.muted = self._adjustment.props.value == 0

    def __level_changed_cb(self, pspec_, param_):
        self._update_level()

    def __mute_activate_cb(self, menuitem_):
        self._model.props.muted = not self._model.props.muted

    def __muted_changed_cb(self, pspec_, param_):
        self._update_muted()

    def __popup_cb(self, palette_):
        self._update_level()
        self._update_muted()
Esempio n. 42
0
class WirelessPalette(Palette):
    __gtype_name__ = 'SugarWirelessPalette'

    __gsignals__ = {
        'deactivate-connection': (GObject.SignalFlags.RUN_FIRST, None, ([])),
    }

    def __init__(self, primary_text):
        Palette.__init__(self, label=primary_text)

        self._disconnect_item = None

        self._channel_label = Gtk.Label()
        self._channel_label.props.xalign = 0.0
        self._channel_label.show()

        self._ip_address_label = Gtk.Label()
        self._ip_address_label.props.xalign = 0.0
        self._ip_address_label.show()

        self._info = Gtk.VBox()

        self._disconnect_item = PaletteMenuItem(_('Disconnect'))
        icon = Icon(pixel_size=style.SMALL_ICON_SIZE, icon_name='media-eject')
        self._disconnect_item.set_image(icon)
        self._disconnect_item.connect('activate',
                                      self.__disconnect_activate_cb)
        self._info.add(self._disconnect_item)

        separator = PaletteMenuItemSeparator()
        self._info.pack_start(separator, True, True, 0)

        def _padded(child, xalign=0, yalign=0.5):
            padder = Gtk.Alignment.new(xalign=xalign,
                                       yalign=yalign,
                                       xscale=1,
                                       yscale=0.33)
            padder.set_padding(style.DEFAULT_SPACING, style.DEFAULT_SPACING,
                               style.DEFAULT_SPACING, style.DEFAULT_SPACING)
            padder.add(child)
            return padder

        self._info.pack_start(_padded(self._channel_label), True, True, 0)
        self._info.pack_start(_padded(self._ip_address_label), True, True, 0)
        self._info.show_all()

    def set_connecting(self):
        self.props.secondary_text = _('Connecting...')

    def _set_connected(self, iaddress):
        self.set_content(self._info)
        self.props.secondary_text = _('Connected')
        self._set_ip_address(iaddress)
        self._disconnect_item.show()

    def set_connected_with_frequency(self, frequency, iaddress):
        self._set_connected(iaddress)
        self._set_frequency(frequency)

    def set_connected_with_channel(self, channel, iaddress):
        self._set_connected(iaddress)
        self._set_channel(channel)

    def set_disconnected(self):
        self.props.primary_text = _('No wireless connection')
        self.props.secondary_text = ''
        self._disconnect_item.hide()
        self.set_content(None)

    def __disconnect_activate_cb(self, menuitem):
        self.emit('deactivate-connection')

    def _set_frequency(self, frequency):
        channel = network.frequency_to_channel(frequency)
        self._set_channel(channel)

    def _set_channel(self, channel):
        if channel == 0:
            self._channel_label.set_text('%s: %s' %
                                         (_('Channel'), _('Unknown')))
        else:
            self._channel_label.set_text('%s: %d' % (_('Channel'), channel))

    def _set_ip_address(self, ip_address):
        if ip_address is not None:
            ip_address_text = IP_ADDRESS_TEXT_TEMPLATE % \
                socket.inet_ntoa(struct.pack('I', ip_address))
        else:
            ip_address_text = ""
        self._ip_address_label.set_text(ip_address_text)
    def __init__(self, tabbed_view, act):
        ToolbarBase.__init__(self)

        self._url_toolbar = UrlToolbar()

        self._activity = act
        self.model = act.model
        self.model.link_removed_signal.connect(self.__link_removed_cb)

        self._tabbed_view = self._canvas = tabbed_view

        self._loading = False
        self._download_running_hid = None

        toolbar = self.toolbar
        activity_button = ActivityToolbarButton(self._activity)
        toolbar.insert(activity_button, 0)

        separator = Gtk.SeparatorToolItem()
        '''
        Disabled since the python gi bindings don't expose the critical
        WebKit2.PrintOperation.print function

        save_as_pdf = ToolButton('save-as-pdf')
        save_as_pdf.set_tooltip(_('Save page as pdf'))
        save_as_pdf.connect('clicked', self.save_as_pdf)

        activity_button.props.page.insert(separator, -1)
        activity_button.props.page.insert(save_as_pdf, -1)
        separator.show()
        save_as_pdf.show()
        '''
        inspect_view = ToolButton('emblem-view-source')
        inspect_view.set_tooltip(_('Show Web Inspector'))
        inspect_view.connect('clicked', self.inspect_view)

        activity_button.props.page.insert(separator, -1)
        activity_button.props.page.insert(inspect_view, -1)
        separator.show()
        inspect_view.show()

        self._go_home = ToolButton('go-home')
        self._go_home.set_tooltip(_('Home page'))
        self._go_home.connect('clicked', self._go_home_cb)
        # add a menu to save the home page
        menu_box = PaletteMenuBox()
        self._go_home.props.palette.set_content(menu_box)
        menu_item = PaletteMenuItem()
        menu_item.set_label(_('Select as initial page'))
        menu_item.connect('activate', self._set_home_cb)
        menu_box.append_item(menu_item)

        self._reset_home_menu = PaletteMenuItem()
        self._reset_home_menu.set_label(_('Reset initial page'))
        self._reset_home_menu.connect('activate', self._reset_home_cb)
        menu_box.append_item(self._reset_home_menu)

        if os.path.isfile(LIBRARY_PATH):
            library_menu = PaletteMenuItem()
            library_menu.set_label(_('Library'))
            library_menu.connect('activate', self._go_library_cb)
            menu_box.append_item(library_menu)

        menu_box.show_all()

        # verify if the home page is configured
        client = GConf.Client.get_default()
        self._reset_home_menu.set_visible(
            client.get_string(HOME_PAGE_GCONF_KEY) is not None)

        toolbar.insert(self._go_home, -1)
        self._go_home.show()

        self.entry = WebEntry()
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-stop')
        self.entry.connect('icon-press', self._stop_and_reload_cb)
        self.entry.connect('activate', self._entry_activate_cb)
        self.entry.connect('focus-in-event', self.__focus_in_event_cb)
        self.entry.connect('focus-out-event', self.__focus_out_event_cb)
        self.entry.connect('key-press-event', self.__key_press_event_cb)
        self.entry.connect('changed', self.__changed_cb)

        # In an event box so that it can render the background
        entry_box = Gtk.EventBox()
        entry_box.add(self.entry)
        entry_box.show()

        self._entry_item = Gtk.ToolItem()
        self._entry_item.set_expand(True)
        self._entry_item.add(entry_box)
        self.entry.show()

        toolbar.insert(self._entry_item, -1)

        self._entry_item.show()

        self._back = ToolButton('go-previous-paired', accelerator='<ctrl>Left')
        self._back.set_tooltip(_('Back'))
        self._back.props.sensitive = False
        self._back.connect('clicked', self._go_back_cb)
        toolbar.insert(self._back, -1)
        self._back.show()

        palette = self._back.get_palette()
        self._back_box_menu = Gtk.VBox()
        self._back_box_menu.show()
        palette.set_content(self._back_box_menu)
        # FIXME, this is a hack, should be done in the theme:
        palette._content.set_border_width(1)

        self._forward = ToolButton('go-next-paired', accelerator='<ctrl>Right')
        self._forward.set_tooltip(_('Forward'))
        self._forward.props.sensitive = False
        self._forward.connect('clicked', self._go_forward_cb)
        toolbar.insert(self._forward, -1)
        self._forward.show()

        palette = self._forward.get_palette()
        self._forward_box_menu = Gtk.VBox()
        self._forward_box_menu.show()
        palette.set_content(self._forward_box_menu)
        # FIXME, this is a hack, should be done in the theme:
        palette._content.set_border_width(1)

        self._download_icon = ProgressToolButton(
            icon_name='emblem-downloads', tooltip=_('No Downloads Running'))
        toolbar.insert(self._download_icon, -1)
        self._download_icon.show()
        downloadmanager.connect_donwload_started(self.__download_started_cb)

        self._link_add = ToggleToolButton('emblem-favorite')
        self._link_add.set_accelerator('<ctrl>d')
        self._link_add.set_tooltip(_('Bookmark'))
        self._link_add_toggled_hid = \
            self._link_add.connect('toggled', self.__link_add_toggled_cb)
        toolbar.insert(self._link_add, -1)
        self._link_add.show()

        self._toolbar_separator = Gtk.SeparatorToolItem()
        self._toolbar_separator.props.draw = False
        self._toolbar_separator.set_expand(True)

        self._stop_button = StopButton(self._activity)
        toolbar.insert(self._stop_button, -1)

        self._progress_listener = None
        self._browser = None

        self._loading_changed_hid = None
        self._progress_changed_hid = None
        self._session_history_changed_hid = None
        self._uri_changed_hid = None
        self._load_changed_hid = None
        self._security_status_changed_hid = None

        if tabbed_view.get_n_pages():
            self._connect_to_browser(tabbed_view.props.current_browser)

        tabbed_view.connect_after('switch-page', self.__switch_page_cb)
        tabbed_view.connect_after('page-added', self.__page_added_cb)

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

        self._configure_toolbar()
Esempio n. 44
0
class BuddyMenu(Palette):
    def __init__(self, buddy):
        self._buddy = buddy

        buddy_icon = Icon(icon_name='computer-xo',
                          xo_color=buddy.get_color(),
                          pixel_size=style.STANDARD_ICON_SIZE)
        nick = buddy.get_nick()
        Palette.__init__(self, None, primary_text=nick, icon=buddy_icon)
        self.menu_box = Gtk.VBox()
        self.set_content(self.menu_box)
        self.menu_box.show_all()
        self._invite_menu = None
        self._active_activity_changed_hid = None
        # Fixme: we need to make the widget accessible through the Palette API
        self._widget.connect('destroy', self.__destroy_cb)

        self._buddy.connect('notify::nick', self.__buddy_notify_nick_cb)

        if buddy.is_owner():
            self._add_my_items()
        else:
            self._add_buddy_items()

    def __destroy_cb(self, menu):
        if self._active_activity_changed_hid is not None:
            home_model = shell.get_model()
            home_model.disconnect(self._active_activity_changed_hid)
        self._buddy.disconnect_by_func(self.__buddy_notify_nick_cb)

    def _add_buddy_items(self):
        menu_item = None
        if friends.get_model().has_buddy(self._buddy):
            menu_item = PaletteMenuItem(_('Remove friend'), 'list-remove')
            menu_item.connect('activate', self._remove_friend_cb)
        else:
            menu_item = PaletteMenuItem(_('Make friend'), 'list-add')
            menu_item.connect('activate', self._make_friend_cb)

        self.menu_box.pack_start(menu_item, True, True, 0)

        self._invite_menu = PaletteMenuItem('')
        self._invite_menu.connect('activate', self._invite_friend_cb)
        self.menu_box.pack_start(self._invite_menu, True, True, 0)

        home_model = shell.get_model()
        self._active_activity_changed_hid = home_model.connect(
            'active-activity-changed', self._cur_activity_changed_cb)
        activity = home_model.get_active_activity()
        self._update_invite_menu(activity)

    def _add_my_items(self):
        settings = Gio.Settings('org.sugarlabs')

        show_shutdown = settings.get_boolean('show-shutdown')
        show_restart = settings.get_boolean('show-restart')
        show_logout = settings.get_boolean('show-logout')

        if "SUGAR_SHOW_SHUTDOWN" in os.environ:
            show_shutdown = os.environ["SUGAR_SHOW_SHUTDOWN"] == "yes"

        if "SUGAR_SHOW_RESTART" in os.environ:
            show_restart = os.environ["SUGAR_SHOW_RESTART"] == "yes"

        if "SUGAR_SHOW_LOGOUT" in os.environ:
            show_logout = os.environ["SUGAR_SHOW_LOGOUT"] == "yes"

        if show_shutdown:
            item = PaletteMenuItem(_('Shutdown'), 'system-shutdown')
            item.connect('activate', self.__shutdown_activate_cb)
            self.menu_box.pack_start(item, True, True, 0)

        if show_restart:
            item = PaletteMenuItem(_('Restart'), 'system-restart')
            item.connect('activate', self.__reboot_activate_cb)
            self.menu_box.pack_start(item, True, True, 0)
            item.show()

        if show_logout:
            item = PaletteMenuItem(_('Logout'), 'system-logout')
            item.connect('activate', self.__logout_activate_cb)
            self.menu_box.pack_start(item, True, True, 0)
            item.show()

        item = PaletteMenuItem(_('My Settings'), 'preferences-system')
        item.connect('activate', self.__controlpanel_activate_cb)
        self.menu_box.pack_start(item, True, True, 0)
        item.show()

    def _quit(self, action):
        jarabe.desktop.homewindow.get_instance().busy()
        action()
        GObject.timeout_add_seconds(3, self.__quit_timeout_cb)

    def __quit_timeout_cb(self):
        jarabe.desktop.homewindow.get_instance().unbusy()
        alert = TimeoutAlert(30)
        alert.props.title = _('An activity is not responding.')
        alert.props.msg = _('You may lose unsaved work if you continue.')
        alert.connect('response', self.__quit_accept_cb)

        jarabe.desktop.homewindow.get_instance().add_alert(alert)
        alert.show()

    def __quit_accept_cb(self, alert, response_id):
        jarabe.desktop.homewindow.get_instance().remove_alert(alert)
        if response_id is Gtk.ResponseType.CANCEL:
            get_session_manager().cancel_shutdown()
        else:
            jarabe.desktop.homewindow.get_instance().busy()
            get_session_manager().shutdown_completed()

    def __logout_activate_cb(self, menu_item):
        self._quit(get_session_manager().logout)

    def __reboot_activate_cb(self, menu_item):
        self._quit(get_session_manager().reboot)

    def __shutdown_activate_cb(self, menu_item):
        self._quit(get_session_manager().shutdown)

    def __controlpanel_activate_cb(self, menu_item):
        # hide the frame when control panel is shown
        import jarabe.frame
        frame = jarabe.frame.get_view()
        frame.hide()

        # show the control panel
        panel = ControlPanel()
        panel.show()

    def _update_invite_menu(self, activity):
        buddy_activity = self._buddy.props.current_activity
        if buddy_activity is not None:
            buddy_activity_id = buddy_activity.activity_id
        else:
            buddy_activity_id = None

        if activity is None or activity.is_journal() or \
           activity.get_activity_id() == buddy_activity_id:
            self._invite_menu.hide()
        else:
            title = activity.get_title()
            self._invite_menu.set_label(_('Invite to %s') % title)

            icon = Icon(file=activity.get_icon_path(),
                        pixel_size=style.SMALL_ICON_SIZE)
            icon.props.xo_color = activity.get_icon_color()
            self._invite_menu.set_image(icon)
            icon.show()

            self._invite_menu.show()

    def _cur_activity_changed_cb(self, home_model, activity_model):
        self._update_invite_menu(activity_model)

    def __buddy_notify_nick_cb(self, buddy, pspec):
        self.set_primary_text(buddy.props.nick)

    def _make_friend_cb(self, menuitem):
        friends.get_model().make_friend(self._buddy)

    def _remove_friend_cb(self, menuitem):
        friends.get_model().remove(self._buddy)

    def _invite_friend_cb(self, menuitem):
        activity = shell.get_model().get_active_activity()
        service = activity.get_service()
        if service:
            try:
                service.InviteContact(self._buddy.props.account,
                                      self._buddy.props.contact_id)
            except dbus.DBusException, e:
                expected_exceptions = [
                    'org.freedesktop.DBus.Error.UnknownMethod',
                    'org.freedesktop.DBus.Python.NotImplementedError'
                ]
                if e.get_dbus_name() in expected_exceptions:
                    logging.warning('Trying deprecated Activity.Invite')
                    service.Invite(self._buddy.props.key)
                else:
                    raise
        else:
class PrimaryToolbar(ToolbarBase):
    __gtype_name__ = 'PrimaryToolbar'

    __gsignals__ = {
        'add-link': (GObject.SignalFlags.RUN_FIRST, None, ([])),
        'remove-link': (GObject.SignalFlags.RUN_FIRST, None, ([])),
        'go-home': (GObject.SignalFlags.RUN_FIRST, None, ([])),
        'set-home': (GObject.SignalFlags.RUN_FIRST, None, ([])),
        'reset-home': (GObject.SignalFlags.RUN_FIRST, None, ([])),
        'go-library': (GObject.SignalFlags.RUN_FIRST, None, ([])),
    }

    def __init__(self, tabbed_view, act):
        ToolbarBase.__init__(self)

        self._url_toolbar = UrlToolbar()

        self._activity = act
        self.model = act.model
        self.model.link_removed_signal.connect(self.__link_removed_cb)

        self._tabbed_view = self._canvas = tabbed_view

        self._loading = False
        self._download_running_hid = None

        toolbar = self.toolbar
        activity_button = ActivityToolbarButton(self._activity)
        toolbar.insert(activity_button, 0)

        separator = Gtk.SeparatorToolItem()
        '''
        Disabled since the python gi bindings don't expose the critical
        WebKit2.PrintOperation.print function

        save_as_pdf = ToolButton('save-as-pdf')
        save_as_pdf.set_tooltip(_('Save page as pdf'))
        save_as_pdf.connect('clicked', self.save_as_pdf)

        activity_button.props.page.insert(separator, -1)
        activity_button.props.page.insert(save_as_pdf, -1)
        separator.show()
        save_as_pdf.show()
        '''
        inspect_view = ToolButton('emblem-view-source')
        inspect_view.set_tooltip(_('Show Web Inspector'))
        inspect_view.connect('clicked', self.inspect_view)

        activity_button.props.page.insert(separator, -1)
        activity_button.props.page.insert(inspect_view, -1)
        separator.show()
        inspect_view.show()

        self._go_home = ToolButton('go-home')
        self._go_home.set_tooltip(_('Home page'))
        self._go_home.connect('clicked', self._go_home_cb)
        # add a menu to save the home page
        menu_box = PaletteMenuBox()
        self._go_home.props.palette.set_content(menu_box)
        menu_item = PaletteMenuItem()
        menu_item.set_label(_('Select as initial page'))
        menu_item.connect('activate', self._set_home_cb)
        menu_box.append_item(menu_item)

        self._reset_home_menu = PaletteMenuItem()
        self._reset_home_menu.set_label(_('Reset initial page'))
        self._reset_home_menu.connect('activate', self._reset_home_cb)
        menu_box.append_item(self._reset_home_menu)

        if os.path.isfile(LIBRARY_PATH):
            library_menu = PaletteMenuItem()
            library_menu.set_label(_('Library'))
            library_menu.connect('activate', self._go_library_cb)
            menu_box.append_item(library_menu)

        menu_box.show_all()

        # verify if the home page is configured
        client = GConf.Client.get_default()
        self._reset_home_menu.set_visible(
            client.get_string(HOME_PAGE_GCONF_KEY) is not None)

        toolbar.insert(self._go_home, -1)
        self._go_home.show()

        self.entry = WebEntry()
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-stop')
        self.entry.connect('icon-press', self._stop_and_reload_cb)
        self.entry.connect('activate', self._entry_activate_cb)
        self.entry.connect('focus-in-event', self.__focus_in_event_cb)
        self.entry.connect('focus-out-event', self.__focus_out_event_cb)
        self.entry.connect('key-press-event', self.__key_press_event_cb)
        self.entry.connect('changed', self.__changed_cb)

        # In an event box so that it can render the background
        entry_box = Gtk.EventBox()
        entry_box.add(self.entry)
        entry_box.show()

        self._entry_item = Gtk.ToolItem()
        self._entry_item.set_expand(True)
        self._entry_item.add(entry_box)
        self.entry.show()

        toolbar.insert(self._entry_item, -1)

        self._entry_item.show()

        self._back = ToolButton('go-previous-paired', accelerator='<ctrl>Left')
        self._back.set_tooltip(_('Back'))
        self._back.props.sensitive = False
        self._back.connect('clicked', self._go_back_cb)
        toolbar.insert(self._back, -1)
        self._back.show()

        palette = self._back.get_palette()
        self._back_box_menu = Gtk.VBox()
        self._back_box_menu.show()
        palette.set_content(self._back_box_menu)
        # FIXME, this is a hack, should be done in the theme:
        palette._content.set_border_width(1)

        self._forward = ToolButton('go-next-paired', accelerator='<ctrl>Right')
        self._forward.set_tooltip(_('Forward'))
        self._forward.props.sensitive = False
        self._forward.connect('clicked', self._go_forward_cb)
        toolbar.insert(self._forward, -1)
        self._forward.show()

        palette = self._forward.get_palette()
        self._forward_box_menu = Gtk.VBox()
        self._forward_box_menu.show()
        palette.set_content(self._forward_box_menu)
        # FIXME, this is a hack, should be done in the theme:
        palette._content.set_border_width(1)

        self._download_icon = ProgressToolButton(
            icon_name='emblem-downloads', tooltip=_('No Downloads Running'))
        toolbar.insert(self._download_icon, -1)
        self._download_icon.show()
        downloadmanager.connect_donwload_started(self.__download_started_cb)

        self._link_add = ToggleToolButton('emblem-favorite')
        self._link_add.set_accelerator('<ctrl>d')
        self._link_add.set_tooltip(_('Bookmark'))
        self._link_add_toggled_hid = \
            self._link_add.connect('toggled', self.__link_add_toggled_cb)
        toolbar.insert(self._link_add, -1)
        self._link_add.show()

        self._toolbar_separator = Gtk.SeparatorToolItem()
        self._toolbar_separator.props.draw = False
        self._toolbar_separator.set_expand(True)

        self._stop_button = StopButton(self._activity)
        toolbar.insert(self._stop_button, -1)

        self._progress_listener = None
        self._browser = None

        self._loading_changed_hid = None
        self._progress_changed_hid = None
        self._session_history_changed_hid = None
        self._uri_changed_hid = None
        self._load_changed_hid = None
        self._security_status_changed_hid = None

        if tabbed_view.get_n_pages():
            self._connect_to_browser(tabbed_view.props.current_browser)

        tabbed_view.connect_after('switch-page', self.__switch_page_cb)
        tabbed_view.connect_after('page-added', self.__page_added_cb)

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

        self._configure_toolbar()

    def __download_started_cb(self):
        if self._download_running_hid is None:
            self._download_running_hid = GLib.timeout_add(
                80, self.__download_running_cb)

    def __download_running_cb(self):
        print('__DLR')
        progress = downloadmanager.overall_downloads_progress()
        self._download_icon.update(progress)
        if downloadmanager.num_downloads() > 0:
            self._download_icon.props.tooltip = \
                _('{}% Downloaded').format(int(progress*100))
            self._download_icon.props.xo_color = XoColor(None)
            return True
        else:
            GLib.source_remove(self._download_running_hid)
            self._download_running_hid = None
            self._download_icon.props.tooltip = _('No Downloads Running')
            self._download_icon.props.xo_color = XoColor('insensitive')
            return False

    def __key_press_event_cb(self, entry, event):
        self._tabbed_view.current_browser.loading_uri = entry.props.text

    def __switch_page_cb(self, tabbed_view, page, page_num):
        if tabbed_view.get_n_pages():
            self._connect_to_browser(tabbed_view.props.current_browser)

    def __page_added_cb(self, notebook, child, pagenum):
        self.entry._search_popdown()

    def _configure_toolbar(self, screen=None):
        # Adapt the toolbars for portrait or landscape mode.

        if screen is None:
            screen = Gdk.Screen.get_default()

        if screen.get_width() < screen.get_height():
            if self._entry_item in self._url_toolbar.toolbar.get_children():
                return

            self.toolbar.remove(self._entry_item)
            self._url_toolbar.toolbar.insert(self._entry_item, -1)

            separator_pos = len(self.toolbar.get_children()) - 1
            self.toolbar.insert(self._toolbar_separator, separator_pos)
            self._toolbar_separator.show()

            self.pack_end(self._url_toolbar, True, True, 0)
            self._url_toolbar.show()

        else:
            if self._entry_item in self.toolbar.get_children():
                return

            self.toolbar.remove(self._toolbar_separator)

            position = len(self.toolbar.get_children()) - 4
            self._url_toolbar.toolbar.remove(self._entry_item)
            self.toolbar.insert(self._entry_item, position)

            self._toolbar_separator.hide()
            self.remove(self._url_toolbar)

    def __screen_size_changed_cb(self, screen):
        self._configure_toolbar(screen)

    def _connect_to_browser(self, browser):
        if self._browser is not None:
            self._browser.disconnect(self._uri_changed_hid)
            self._browser.disconnect(self._load_changed_hid)
            self._browser.disconnect(self._progress_changed_hid)
            self._browser.disconnect(self._security_status_changed_hid)

        self._browser = browser
        if not isinstance(self._browser, DummyBrowser):
            address = self._browser.props.uri or self._browser.loading_uri
        else:
            address = self._browser.props.uri
        self._set_address(address)
        self._set_progress(self._browser.props.estimated_load_progress)
        self._set_loading(self._browser.props.estimated_load_progress < 1.0)
        self._set_security_status(self._browser.security_status)

        is_webkit_browser = isinstance(self._browser, Browser)
        self.entry.props.editable = is_webkit_browser

        self._uri_changed_hid = self._browser.connect('notify::uri',
                                                      self.__uri_changed_cb)
        self._load_changed_hid = self._browser.connect('load-changed',
                                                       self.__load_changed_cb)
        self._progress_changed_hid = self._browser.connect(
            'notify::estimated-load-progress', self.__progress_changed_cb)
        self._security_status_changed_hid = self._browser.connect(
            'security-status-changed', self.__security_status_changed_cb)

        self._update_navigation_buttons()

    def __security_status_changed_cb(self, widget):
        self._set_security_status(widget.security_status)

    def __progress_changed_cb(self, widget, param):
        self._set_progress(widget.props.estimated_load_progress)
        self._set_loading(widget.props.estimated_load_progress < 1.0)

    def _set_security_status(self, security_status):
        # Display security status as a lock icon in the left side of
        # the URL entry.
        if security_status is None:
            self.entry.set_icon_from_pixbuf(iconentry.ICON_ENTRY_PRIMARY, None)
        elif security_status == Browser.SECURITY_STATUS_SECURE:
            self.entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY,
                                          'channel-secure-symbolic')
        elif security_status == Browser.SECURITY_STATUS_INSECURE:
            self.entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY,
                                          'channel-insecure-symbolic')

    def _set_progress(self, progress):
        if progress == 1.0:
            self.entry.set_progress_fraction(0.0)
        else:
            self.entry.set_progress_fraction(progress)

    def _set_address(self, uri):
        if uri is None:
            self.entry.props.address = ''
        else:
            self.entry.props.address = uri

    def __changed_cb(self, iconentry):
        # The WebEntry can be changed when we click on a link, then we
        # have to show the clear icon only if is the user who has
        # changed the entry
        if self.entry.has_focus():
            if not self.entry.props.text:
                self._show_no_icon()
            else:
                self._show_clear_icon()

    def __focus_in_event_cb(self, entry, event):
        if not self._tabbed_view.is_current_page_pdf():
            if not self.entry.props.text:
                self._show_no_icon()
            else:
                self._show_clear_icon()

    def __focus_out_event_cb(self, entry, event):
        if self._loading:
            self._show_stop_icon()
        else:
            if not self._tabbed_view.is_current_page_pdf():
                self._show_reload_icon()

    def _show_no_icon(self):
        self.entry.remove_icon(iconentry.ICON_ENTRY_SECONDARY)

    def _show_stop_icon(self):
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-stop')

    def _show_reload_icon(self):
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-refresh')

    def _show_clear_icon(self):
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-cancel')

    def _update_navigation_buttons(self):
        can_go_back = self._browser.can_go_back()
        self._back.props.sensitive = can_go_back

        can_go_forward = self._browser.can_go_forward()
        self._forward.props.sensitive = can_go_forward

        is_webkit_browser = isinstance(self._browser, Browser)
        self._go_home.props.sensitive = is_webkit_browser
        if is_webkit_browser:
            self._reload_session_history()

        with self._link_add.handler_block(self._link_add_toggled_hid):
            uri = self._browser.get_uri()
            print(self.model.has_link(uri), uri)
            self._link_add.props.active = self.model.has_link(uri)

    def __link_removed_cb(self, model):
        self._update_navigation_buttons()

    def _entry_activate_cb(self, entry):
        url = entry.props.text
        effective_url = self._tabbed_view.normalize_or_autosearch_url(url)
        self._browser.load_uri(effective_url)
        self._browser.loading_uri = effective_url
        self.entry.props.address = effective_url
        self._browser.grab_focus()

    def _go_home_cb(self, button):
        self.emit('go-home')

    def _go_library_cb(self, button):
        self.emit('go-library')

    def _set_home_cb(self, button):
        self._reset_home_menu.set_visible(True)
        self.emit('set-home')

    def _reset_home_cb(self, button):
        self._reset_home_menu.set_visible(False)
        self.emit('reset-home')

    def _go_back_cb(self, button):
        self._browser.go_back()

    def _go_forward_cb(self, button):
        self._browser.go_forward()

    def __uri_changed_cb(self, widget, param):
        self._set_address(widget.get_uri())
        self._update_navigation_buttons()
        filepicker.cleanup_temp_files()

    def __load_changed_cb(self, widget, event):
        self._update_navigation_buttons()

    def _stop_and_reload_cb(self, entry, icon_pos, button):
        if entry.has_focus() and \
                not self._tabbed_view.is_current_page_pdf():
            entry.set_text('')
        else:
            if self._loading:
                self._browser.stop_loading()
            else:
                self._browser.reload()

    def _set_loading(self, loading):
        self._loading = loading

        if self._loading:
            self._show_stop_icon()
        else:
            if not self._tabbed_view.is_current_page_pdf():
                self._set_sensitive(True)
                self._show_reload_icon()
            else:
                self._set_sensitive(False)
                self._show_no_icon()

    def _set_sensitive(self, value):
        for widget in self.toolbar:
            if widget not in (self._stop_button, self._link_add):
                widget.set_sensitive(value)

    def _reload_session_history(self):
        back_forward_list = self._browser.get_back_forward_list()
        item_index = 0  # The index of the history item

        # Clear menus in palettes:
        for box_menu in (self._back_box_menu, self._forward_box_menu):
            for menu_item in box_menu.get_children():
                box_menu.remove(menu_item)

        def create_menu_item(history_item):
            """Create a MenuItem for the back or forward palettes."""
            title = history_item.get_title() or _('No Title')
            if not isinstance(title, unicode):
                title = unicode(title, 'utf-8')
            # This is a fix until the Sugar MenuItem is fixed:
            menu_item = PaletteMenuItem(text_label=title)
            menu_item.connect('activate', self._history_item_activated_cb,
                              history_item)
            return menu_item

        back_list = back_forward_list.get_back_list_with_limit(
            _MAX_HISTORY_ENTRIES)
        back_list.reverse()
        for item in back_list:
            menu_item = create_menu_item(item)
            self._back_box_menu.pack_end(menu_item, False, False, 0)
            menu_item.show()
            item_index += 1

        # Increment the item index to count the current page:
        item_index += 1

        forward_list = back_forward_list.get_forward_list_with_limit(
            _MAX_HISTORY_ENTRIES)
        forward_list.reverse()
        for item in forward_list:
            menu_item = create_menu_item(item)
            self._forward_box_menu.pack_start(menu_item, False, False, 0)
            menu_item.show()
            item_index += 1

    def _history_item_activated_cb(self, menu_item, history_item):
        self._back.get_palette().popdown(immediate=True)
        self._forward.get_palette().popdown(immediate=True)
        # self._browser.set_history_index(index)
        self._browser.go_to_back_forward_list_item(history_item)

    def __link_add_toggled_cb(self, button):
        if button.props.active:
            self.emit('add-link')
        else:
            self.emit('remove-link')

    def inspect_view(self, button):
        page = self._canvas.get_current_page()
        webview = self._canvas.get_children()[page].props.browser

        # If get_inspector returns None, it is not a real WebView
        inspector = webview.get_inspector()
        if inspector is not None:
            # Inspector window will be blank if disabled
            web_settings = webview.get_settings()
            web_settings.props.enable_developer_extras = True

            inspector.show()
            inspector.attach()

    '''
Esempio n. 46
0
class OlpcMeshView(EventPulsingIcon):
    def __init__(self, mesh_mgr, channel):
        EventPulsingIcon.__init__(self,
                                  icon_name=_OLPC_MESH_ICON_NAME,
                                  pixel_size=style.STANDARD_ICON_SIZE,
                                  cache=True)
        self._bus = dbus.SystemBus()
        self._channel = channel
        self._mesh_mgr = mesh_mgr
        self._disconnect_item = None
        self._connect_item = None
        self._filtered = False
        self._device_state = None
        self._active = False
        device = mesh_mgr.mesh_device

        interface_props = dbus.Interface(device, dbus.PROPERTIES_IFACE)
        interface_props.Get(network.NM_DEVICE_IFACE,
                            'State',
                            reply_handler=self.__get_device_state_reply_cb,
                            error_handler=self.__get_device_state_error_cb)
        interface_props.Get(network.NM_OLPC_MESH_IFACE,
                            'ActiveChannel',
                            reply_handler=self.__get_active_channel_reply_cb,
                            error_handler=self.__get_active_channel_error_cb)

        self._bus.add_signal_receiver(self.__device_state_changed_cb,
                                      signal_name='StateChanged',
                                      path=device.object_path,
                                      dbus_interface=network.NM_DEVICE_IFACE)
        self._bus.add_signal_receiver(
            self.__wireless_properties_changed_cb,
            signal_name='PropertiesChanged',
            path=device.object_path,
            dbus_interface=network.NM_OLPC_MESH_IFACE)

        pulse_color = XoColor('%s,%s' % (style.COLOR_BUTTON_GREY.get_svg(),
                                         style.COLOR_TRANSPARENT.get_svg()))
        self.props.pulse_color = pulse_color
        self.props.base_color = profile.get_color()
        self.palette_invoker.props.toggle_palette = True
        self._palette = self._create_palette()
        self.set_palette(self._palette)

    def _create_palette(self):
        _palette = palette.Palette(_('Mesh Network %d') % (self._channel, ))

        self.menu_box = Gtk.VBox()

        self._connect_item = PaletteMenuItem(_('Connect'))
        icon = Icon(pixel_size=style.SMALL_ICON_SIZE, icon_name='dialog-ok')
        self._connect_item.set_image(icon)
        self._connect_item.connect('activate', self.__connect_activate_cb)
        self.menu_box.add(self._connect_item)

        _palette.set_content(self.menu_box)
        self.menu_box.show_all()

        return _palette

    def __get_device_state_reply_cb(self, state):
        self._device_state = state
        self._update()

    def __get_device_state_error_cb(self, err):
        logging.error('Error getting the device state: %s', err)

    def __device_state_changed_cb(self, new_state, old_state, reason):
        self._device_state = new_state
        self._update()
        self._update_color()

    def __get_active_channel_reply_cb(self, channel):
        self._active = (channel == self._channel)
        self._update()

    def __get_active_channel_error_cb(self, err):
        logging.error('Error getting the active channel: %s', err)

    def __wireless_properties_changed_cb(self, properties):
        if 'ActiveChannel' in properties:
            channel = properties['ActiveChannel']
            self._active = (channel == self._channel)
            self._update()

    def _update(self):
        if self._active:
            state = self._device_state
        else:
            state = network.NM_DEVICE_STATE_UNKNOWN

        if state in [
                network.NM_DEVICE_STATE_PREPARE,
                network.NM_DEVICE_STATE_CONFIG,
                network.NM_DEVICE_STATE_NEED_AUTH,
                network.NM_DEVICE_STATE_IP_CONFIG
        ]:
            if self._disconnect_item:
                self._disconnect_item.show()
            self._connect_item.hide()
            self._palette.props.secondary_text = _('Connecting...')
            self.props.pulsing = True
        elif state == network.NM_DEVICE_STATE_ACTIVATED:
            if self._disconnect_item:
                self._disconnect_item.show()
            self._connect_item.hide()
            self._palette.props.secondary_text = _('Connected')
            self.props.pulsing = False
        else:
            if self._disconnect_item:
                self._disconnect_item.hide()
            self._connect_item.show()
            self._palette.props.secondary_text = None
            self.props.pulsing = False

    def _update_color(self):
        self.props.base_color = profile.get_color()
        if self._filtered:
            self.alpha = _FILTERED_ALPHA
        else:
            self.alpha = 1.0

    def __connect_activate_cb(self, icon):
        self._connect()

    def _connect(self):
        self._mesh_mgr.user_activate_channel(self._channel)

    def set_filter(self, query):
        self._filtered = (query != '')
        self._update_color()

    def disconnect(self):
        device_object_path = self._mesh_mgr.mesh_device.object_path

        self._bus.remove_signal_receiver(
            self.__device_state_changed_cb,
            signal_name='StateChanged',
            path=device_object_path,
            dbus_interface=network.NM_DEVICE_IFACE)
        self._bus.remove_signal_receiver(
            self.__wireless_properties_changed_cb,
            signal_name='PropertiesChanged',
            path=device_object_path,
            dbus_interface=network.NM_OLPC_MESH_IFACE)
Esempio n. 47
0
    def _update(self):
        new_state = self.file_transfer.props.state
        logging.debug('_update state: %r', new_state)

        box = PaletteMenuBox()
        self.set_content(box)
        box.show()
        if new_state == filetransfer.FT_STATE_PENDING:
            menu_item = PaletteMenuItem(_('Cancel'))
            icon = Icon(icon_name='dialog-cancel',
                        pixel_size=style.SMALL_ICON_SIZE)
            menu_item.set_image(icon)
            icon.show()
            menu_item.connect('activate', self.__cancel_activate_cb)
            box.append_item(menu_item)
            menu_item.show()

            separator = PaletteMenuItemSeparator()
            box.append_item(separator)
            separator.show()

            inner_box = Gtk.VBox()
            inner_box.set_spacing(style.DEFAULT_PADDING)
            box.append_item(inner_box, vertical_padding=0)
            inner_box.show()

            if self.file_transfer.description:
                label = Gtk.Label(label=self.file_transfer.description)
                inner_box.add(label)
                label.show()

            mime_type = self.file_transfer.mime_type
            type_description = mime.get_mime_description(mime_type)

            size = self._format_size(self.file_transfer.file_size)
            label = Gtk.Label(label='%s (%s)' % (size, type_description))
            inner_box.add(label)
            label.show()

        elif new_state in [filetransfer.FT_STATE_ACCEPTED,
                           filetransfer.FT_STATE_OPEN]:
            menu_item = PaletteMenuItem(_('Cancel'))
            icon = Icon(icon_name='dialog-cancel',
                        pixel_size=style.SMALL_ICON_SIZE)
            menu_item.set_image(icon)
            icon.show()
            menu_item.connect('activate', self.__cancel_activate_cb)
            box.append_item(menu_item)
            menu_item.show()

            separator = PaletteMenuItemSeparator()
            box.append_item(separator)
            separator.show()

            inner_box = Gtk.VBox()
            inner_box.set_spacing(style.DEFAULT_PADDING)
            box.append_item(inner_box, vertical_padding=0)
            inner_box.show()

            self.progress_bar = Gtk.ProgressBar()
            inner_box.add(self.progress_bar)
            self.progress_bar.show()

            self.progress_label = Gtk.Label(label='')
            inner_box.add(self.progress_label)
            self.progress_label.show()

            self.update_progress()

        elif new_state in [filetransfer.FT_STATE_COMPLETED,
                           filetransfer.FT_STATE_CANCELLED]:
            menu_item = PaletteMenuItem(_('Dismiss'))
            icon = Icon(icon_name='dialog-cancel',
                        pixel_size=style.SMALL_ICON_SIZE)
            menu_item.set_image(icon)
            icon.show()
            menu_item.connect('activate', self.__dismiss_activate_cb)
            box.append_item(menu_item)
            menu_item.show()

            self.update_progress()
Esempio n. 48
0
class SpeechPalette(Palette):
    def __init__(self, primary_text, manager):
        Palette.__init__(self, label=primary_text)

        self._manager = manager
        self._manager.connect('play', self._set_menu_state, 'play')
        self._manager.connect('stop', self._set_menu_state, 'stop')
        self._manager.connect('pause', self._set_menu_state, 'pause')

        box = PaletteMenuBox()
        self.set_content(box)
        box.show()

        self._play_icon = Icon(icon_name='player_play')
        self._pause_icon = Icon(icon_name='player_pause')
        self._play_pause_menu = PaletteMenuItem(
            icon_name='player_play',
            text_label=_('Say selected text'),
            accelerator='Shift+Alt+S')
        self._play_pause_menu.set_image(self._play_icon)
        self._play_pause_menu.connect('activate', self.__play_activated_cb)
        box.append_item(self._play_pause_menu)
        self._play_pause_menu.show()

        self._stop_menu = PaletteMenuItem(icon_name='player_stop',
                                          text_label=_('Stop playback'))
        self._stop_menu.connect('activate', self.__stop_activated_cb)
        self._stop_menu.set_sensitive(False)
        box.append_item(self._stop_menu)

        separator = PaletteMenuItemSeparator()
        box.append_item(separator)
        separator.show()

        pitch_label = Gtk.Label(_('Pitch'))
        box.append_item(pitch_label, vertical_padding=0)
        pitch_label.show()

        self._adj_pitch = Gtk.Adjustment(value=self._manager.get_pitch(),
                                         lower=self._manager.MIN_PITCH,
                                         upper=self._manager.MAX_PITCH)

        hscale_pitch = Gtk.HScale()
        hscale_pitch.set_adjustment(self._adj_pitch)
        hscale_pitch.set_draw_value(False)

        box.append_item(hscale_pitch, vertical_padding=0)
        hscale_pitch.show()

        rate_label = Gtk.Label(_('Rate'))
        box.append_item(rate_label, vertical_padding=0)
        rate_label.show()

        self._adj_rate = Gtk.Adjustment(value=self._manager.get_rate(),
                                        lower=self._manager.MIN_RATE,
                                        upper=self._manager.MAX_RATE)

        hscale_rate = Gtk.HScale()
        hscale_rate.set_adjustment(self._adj_rate)
        hscale_rate.set_draw_value(False)

        box.append_item(hscale_rate, vertical_padding=0)
        hscale_rate.show()

        self._adj_pitch.connect('value_changed', self.__adj_pitch_changed_cb)
        self._adj_rate.connect('value_changed', self.__adj_rate_changed_cb)

    def __adj_pitch_changed_cb(self, adjustment):
        self._manager.set_pitch(int(adjustment.get_value()))

    def __adj_rate_changed_cb(self, adjustment):
        self._manager.set_rate(int(adjustment.get_value()))

    def __play_activated_cb(self, widget):
        if self._manager.is_paused:
            self._manager.restart()
        elif not self._manager.is_playing:
            self._manager.say_selected_text()
        else:
            self._manager.pause()

    def __stop_activated_cb(self, widget):
        self._manager.stop()

    def _set_menu_state(self, manager, signal):
        if signal == 'play':
            self._play_pause_menu.set_image(self._pause_icon)
            self._play_pause_menu.set_label(_('Pause playback'))
            self._stop_menu.set_sensitive(True)

        elif signal == 'pause':
            self._play_pause_menu.set_image(self._play_icon)
            self._play_pause_menu.set_label(_('Say selected text'))
            self._stop_menu.set_sensitive(True)

        elif signal == 'stop':
            self._play_pause_menu.set_image(self._play_icon)
            self._play_pause_menu.set_label(_('Say selected text'))
            self._stop_menu.set_sensitive(False)
Esempio n. 49
0
class BuddyMenu(Palette):
    def __init__(self, buddy):
        self._buddy = buddy

        buddy_icon = Icon(icon_name='computer-xo',
                          xo_color=buddy.get_color(),
                          icon_size=Gtk.IconSize.LARGE_TOOLBAR)
        nick = buddy.get_nick()
        Palette.__init__(self, None,
                         primary_text=GLib.markup_escape_text(nick),
                         icon=buddy_icon)
        self.menu_box = Gtk.VBox()
        self.set_content(self.menu_box)
        self.menu_box.show_all()
        self._invite_menu = None
        self._active_activity_changed_hid = None
        # Fixme: we need to make the widget accessible through the Palette API
        self._widget.connect('destroy', self.__destroy_cb)

        self._buddy.connect('notify::nick', self.__buddy_notify_nick_cb)

        if buddy.is_owner():
            self._add_my_items()
        else:
            self._add_buddy_items()

    def __destroy_cb(self, menu):
        if self._active_activity_changed_hid is not None:
            home_model = shell.get_model()
            home_model.disconnect(self._active_activity_changed_hid)
        self._buddy.disconnect_by_func(self.__buddy_notify_nick_cb)

    def _add_buddy_items(self):
        menu_item = None
        if friends.get_model().has_buddy(self._buddy):
            menu_item = PaletteMenuItem(_('Remove friend'), 'list-remove')
            menu_item.connect('activate', self._remove_friend_cb)
        else:
            menu_item = PaletteMenuItem(_('Make friend'), 'list-add')
            menu_item.connect('activate', self._make_friend_cb)

        self.menu_box.pack_start(menu_item, True, True, 0)

        self._invite_menu = PaletteMenuItem('')
        self._invite_menu.connect('activate', self._invite_friend_cb)
        self.menu_box.pack_start(self._invite_menu, True, True, 0)

        home_model = shell.get_model()
        self._active_activity_changed_hid = home_model.connect(
                'active-activity-changed', self._cur_activity_changed_cb)
        activity = home_model.get_active_activity()
        self._update_invite_menu(activity)

    def _add_my_items(self):
        item = PaletteMenuItem(_('Shutdown'), 'system-shutdown')
        item.connect('activate', self.__shutdown_activate_cb)
        self.menu_box.pack_start(item, True, True, 0)

        client = GConf.Client.get_default()

        if client.get_bool('/desktop/sugar/show_restart'):
            item = PaletteMenuItem(_('Restart'), 'system-restart')
            item.connect('activate', self.__reboot_activate_cb)
            self.menu_box.pack_start(item, True, True, 0)
            item.show()

        if client.get_bool('/desktop/sugar/show_logout'):
            item = PaletteMenuItem(_('Logout'), 'system-logout')
            item.connect('activate', self.__logout_activate_cb)
            self.menu_box.pack_start(item, True, True, 0)
            item.show()

        item = PaletteMenuItem(_('My Settings'), 'preferences-system')
        item.connect('activate', self.__controlpanel_activate_cb)
        self.menu_box.pack_start(item, True, True, 0)
        item.show()

    def _quit(self, action):
        home_window = jarabe.desktop.homewindow.get_instance()
        home_window.busy_during_delayed_action(action)

    def __logout_activate_cb(self, menu_item):
        self._quit(get_session_manager().logout)

    def __reboot_activate_cb(self, menu_item):
        self._quit(get_session_manager().reboot)

    def __shutdown_activate_cb(self, menu_item):
        self._quit(get_session_manager().shutdown)

    def __controlpanel_activate_cb(self, menu_item):
        # hide the frame when control panel is shown
        import jarabe.frame
        frame = jarabe.frame.get_view()
        frame.hide()

        # show the control panel
        panel = ControlPanel()
        panel.show()

    def _update_invite_menu(self, activity):
        buddy_activity = self._buddy.props.current_activity
        if buddy_activity is not None:
            buddy_activity_id = buddy_activity.activity_id
        else:
            buddy_activity_id = None

        if activity is None or activity.is_journal() or \
           activity.get_activity_id() == buddy_activity_id:
            self._invite_menu.hide()
        else:
            title = activity.get_title()
            self._invite_menu.set_label(_('Invite to %s') % title)

            icon = Icon(file=activity.get_icon_path(),
                        icon_size=Gtk.IconSize.SMALL_TOOLBAR)
            icon.props.xo_color = activity.get_icon_color()
            self._invite_menu.set_image(icon)
            icon.show()

            self._invite_menu.show()

    def _cur_activity_changed_cb(self, home_model, activity_model):
        self._update_invite_menu(activity_model)

    def __buddy_notify_nick_cb(self, buddy, pspec):
        self.set_primary_text(GLib.markup_escape_text(buddy.props.nick))

    def _make_friend_cb(self, menuitem):
        friends.get_model().make_friend(self._buddy)

    def _remove_friend_cb(self, menuitem):
        friends.get_model().remove(self._buddy)

    def _invite_friend_cb(self, menuitem):
        activity = shell.get_model().get_active_activity()
        service = activity.get_service()
        if service:
            try:
                service.InviteContact(self._buddy.props.account,
                                      self._buddy.props.contact_id)
            except dbus.DBusException, e:
                expected_exceptions = [
                        'org.freedesktop.DBus.Error.UnknownMethod',
                        'org.freedesktop.DBus.Python.NotImplementedError']
                if e.get_dbus_name() in expected_exceptions:
                    logging.warning('Trying deprecated Activity.Invite')
                    service.Invite(self._buddy.props.key)
                else:
                    raise
        else:
Esempio n. 50
0
class WirelessNetworkView(EventPulsingIcon):
    def __init__(self, initial_ap):
        EventPulsingIcon.__init__(self,
                                  pixel_size=style.STANDARD_ICON_SIZE,
                                  cache=True)
        self._bus = dbus.SystemBus()
        self._access_points = {initial_ap.model.object_path: initial_ap}
        self._active_ap = None
        self._device = initial_ap.device
        self._palette_icon = None
        self._disconnect_item = None
        self._connect_item = None
        self._filtered = False
        self._ssid = initial_ap.ssid
        self._display_name = network.ssid_to_display_name(self._ssid)
        self._mode = initial_ap.mode
        self._strength = initial_ap.strength
        self._flags = initial_ap.flags
        self._wpa_flags = initial_ap.wpa_flags
        self._rsn_flags = initial_ap.rsn_flags
        self._device_caps = 0
        self._device_state = None
        self._color = None

        if self._mode == network.NM_802_11_MODE_ADHOC and \
                network.is_sugar_adhoc_network(self._ssid):
            self._color = profile.get_color()
        else:
            sha_hash = hashlib.sha1()
            data = self._ssid + hex(self._flags)
            sha_hash.update(data)
            digest = hash(sha_hash.digest())
            index = digest % len(xocolor.colors)

            self._color = xocolor.XoColor(
                '%s,%s' % (xocolor.colors[index][0], xocolor.colors[index][1]))

        pulse_color = XoColor('%s,%s' % (style.COLOR_BUTTON_GREY.get_svg(),
                                         style.COLOR_TRANSPARENT.get_svg()))
        self.props.pulse_color = pulse_color

        self.props.palette_invoker.props.toggle_palette = True
        self._palette = self._create_palette()
        self.set_palette(self._palette)
        self._palette_icon.props.xo_color = self._color
        self._update_badge()

        interface_props = dbus.Interface(self._device, dbus.PROPERTIES_IFACE)
        interface_props.Get(network.NM_WIRELESS_IFACE,
                            'WirelessCapabilities',
                            reply_handler=self.__get_device_caps_reply_cb,
                            error_handler=self.__get_device_caps_error_cb)
        interface_props.Get(network.NM_WIRELESS_IFACE,
                            'ActiveAccessPoint',
                            reply_handler=self.__get_active_ap_reply_cb,
                            error_handler=self.__get_active_ap_error_cb)

        self._bus.add_signal_receiver(self.__device_state_changed_cb,
                                      signal_name='StateChanged',
                                      path=self._device.object_path,
                                      dbus_interface=network.NM_DEVICE_IFACE)
        self._bus.add_signal_receiver(self.__wireless_properties_changed_cb,
                                      signal_name='PropertiesChanged',
                                      path=self._device.object_path,
                                      dbus_interface=network.NM_WIRELESS_IFACE)

    def _create_palette(self):
        icon_name = get_icon_state(_AP_ICON_NAME, self._strength)
        self._palette_icon = Icon(icon_name=icon_name,
                                  icon_size=style.STANDARD_ICON_SIZE,
                                  badge_name=self.props.badge_name)

        p = palette.Palette(primary_text=self._display_name,
                            icon=self._palette_icon)

        self.menu_box = Gtk.VBox()

        self._connect_item = PaletteMenuItem(_('Connect'))
        icon = Icon(pixel_size=style.SMALL_ICON_SIZE, icon_name='dialog-ok')
        self._connect_item.set_image(icon)
        self._connect_item.connect('activate', self.__connect_activate_cb)
        self.menu_box.add(self._connect_item)

        self._disconnect_item = PaletteMenuItem(_('Disconnect'))
        icon = Icon(pixel_size=style.SMALL_ICON_SIZE, icon_name='media-eject')
        self._disconnect_item.set_image(icon)
        self._disconnect_item.connect('activate',
                                      self.__disconnect_activate_cb)
        self.menu_box.add(self._disconnect_item)

        p.set_content(self.menu_box)
        self.menu_box.show_all()

        self.connect_to_palette_pop_events(p)

        return p

    def __device_state_changed_cb(self, new_state, old_state, reason):
        self._device_state = new_state
        self._update_state()
        self._update_icon()
        self._update_badge()
        self._update_color()

    def __update_active_ap(self, ap_path):
        if ap_path in self._access_points:
            # save reference to active AP, so that we always display the
            # strength of that one
            self._active_ap = self._access_points[ap_path]
            self.update_strength()
        elif self._active_ap is not None:
            # revert to showing state of strongest AP again
            self._active_ap = None
            self.update_strength()

    def __wireless_properties_changed_cb(self, properties):
        if 'ActiveAccessPoint' in properties:
            self.__update_active_ap(properties['ActiveAccessPoint'])

    def __get_active_ap_reply_cb(self, ap_path):
        self.__update_active_ap(ap_path)
        interface_props = dbus.Interface(self._device, dbus.PROPERTIES_IFACE)
        interface_props.Get(network.NM_DEVICE_IFACE,
                            'State',
                            reply_handler=self.__get_device_state_reply_cb,
                            error_handler=self.__get_device_state_error_cb)

    def __get_active_ap_error_cb(self, err):
        logging.error('Error getting the active access point: %s', err)

    def __get_device_caps_reply_cb(self, caps):
        self._device_caps = caps

    def __get_device_caps_error_cb(self, err):
        logging.error('Error getting the wireless device properties: %s', err)

    def __get_device_state_reply_cb(self, state):
        self._device_state = state
        self._update_state()
        self._update_color()
        self._update_icon()
        self._update_badge()

    def __get_device_state_error_cb(self, err):
        logging.error('Error getting the device state: %s', err)

    def _update_icon(self):
        if self._mode == network.NM_802_11_MODE_ADHOC and \
                network.is_sugar_adhoc_network(self._ssid):
            channel = max([1] +
                          [ap.channel for ap in self._access_points.values()])
            if self._device_state == network.NM_DEVICE_STATE_ACTIVATED and \
                    self._active_ap is not None:
                icon_name = 'network-adhoc-%s-connected' % channel
            else:
                icon_name = 'network-adhoc-%s' % channel
            self.props.icon_name = icon_name
            icon = self._palette.props.icon
            icon.props.icon_name = icon_name
        else:
            if self._device_state == network.NM_DEVICE_STATE_ACTIVATED and \
                    self._active_ap is not None:
                icon_name = '%s-connected' % _AP_ICON_NAME
            else:
                icon_name = _AP_ICON_NAME

            icon_name = get_icon_state(icon_name, self._strength)
            if icon_name:
                self.props.icon_name = icon_name
                icon = self._palette.props.icon
                icon.props.icon_name = icon_name

    def _update_badge(self):
        if self._mode != network.NM_802_11_MODE_ADHOC:
            if network.find_connection_by_ssid(self._ssid) is not None:
                self.props.badge_name = 'emblem-favorite'
                self._palette_icon.props.badge_name = 'emblem-favorite'
            elif self._flags == network.NM_802_11_AP_FLAGS_PRIVACY:
                self.props.badge_name = 'emblem-locked'
                self._palette_icon.props.badge_name = 'emblem-locked'
            else:
                self.props.badge_name = None
                self._palette_icon.props.badge_name = None
        else:
            self.props.badge_name = None
            self._palette_icon.props.badge_name = None

    def _update_state(self):
        if self._active_ap is not None:
            state = self._device_state
        else:
            state = network.NM_DEVICE_STATE_UNKNOWN

        if state == network.NM_DEVICE_STATE_PREPARE or \
           state == network.NM_DEVICE_STATE_CONFIG or \
           state == network.NM_DEVICE_STATE_NEED_AUTH or \
           state == network.NM_DEVICE_STATE_IP_CONFIG:
            if self._disconnect_item:
                self._disconnect_item.show()
            self._connect_item.hide()
            self._palette.props.secondary_text = _('Connecting...')
            self.props.pulsing = True
        elif state == network.NM_DEVICE_STATE_ACTIVATED:
            network.set_connected()
            if self._disconnect_item:
                self._disconnect_item.show()
            self._connect_item.hide()
            self._palette.props.secondary_text = _('Connected')
            self.props.pulsing = False
        else:
            if self._disconnect_item:
                self._disconnect_item.hide()
            self._connect_item.show()
            self._palette.props.secondary_text = None
            self.props.pulsing = False

    def _update_color(self):
        self.props.base_color = self._color
        if self._filtered:
            self.props.pulsing = False
            self.props.alpha = _FILTERED_ALPHA
        else:
            self.props.alpha = 1.0

    def __disconnect_activate_cb(self, item):
        ap_paths = self._access_points.keys()
        network.disconnect_access_points(ap_paths)

    def _add_ciphers_from_flags(self, flags, pairwise):
        ciphers = []
        if pairwise:
            if flags & network.NM_802_11_AP_SEC_PAIR_TKIP:
                ciphers.append('tkip')
            if flags & network.NM_802_11_AP_SEC_PAIR_CCMP:
                ciphers.append('ccmp')
        else:
            if flags & network.NM_802_11_AP_SEC_GROUP_WEP40:
                ciphers.append('wep40')
            if flags & network.NM_802_11_AP_SEC_GROUP_WEP104:
                ciphers.append('wep104')
            if flags & network.NM_802_11_AP_SEC_GROUP_TKIP:
                ciphers.append('tkip')
            if flags & network.NM_802_11_AP_SEC_GROUP_CCMP:
                ciphers.append('ccmp')
        return ciphers

    def _get_security(self):
        if not (self._flags & network.NM_802_11_AP_FLAGS_PRIVACY) and \
                (self._wpa_flags == network.NM_802_11_AP_SEC_NONE) and \
                (self._rsn_flags == network.NM_802_11_AP_SEC_NONE):
            # No security
            return None

        if (self._flags & network.NM_802_11_AP_FLAGS_PRIVACY) and \
                (self._wpa_flags == network.NM_802_11_AP_SEC_NONE) and \
                (self._rsn_flags == network.NM_802_11_AP_SEC_NONE):
            # Static WEP, Dynamic WEP, or LEAP
            wireless_security = WirelessSecurity()
            wireless_security.key_mgmt = 'none'
            return wireless_security

        if (self._mode != network.NM_802_11_MODE_INFRA):
            # Stuff after this point requires infrastructure
            logging.error('The infrastructure mode is not supoorted'
                          ' by your wireless device.')
            return None

        if (self._rsn_flags & network.NM_802_11_AP_SEC_KEY_MGMT_PSK) and \
                (self._device_caps & network.NM_WIFI_DEVICE_CAP_RSN):
            # WPA2 PSK first
            pairwise = self._add_ciphers_from_flags(self._rsn_flags, True)
            group = self._add_ciphers_from_flags(self._rsn_flags, False)
            wireless_security = WirelessSecurity()
            wireless_security.key_mgmt = 'wpa-psk'
            wireless_security.proto = 'rsn'
            wireless_security.pairwise = pairwise
            wireless_security.group = group
            return wireless_security

        if (self._wpa_flags & network.NM_802_11_AP_SEC_KEY_MGMT_PSK) and \
                (self._device_caps & network.NM_WIFI_DEVICE_CAP_WPA):
            # WPA PSK
            pairwise = self._add_ciphers_from_flags(self._wpa_flags, True)
            group = self._add_ciphers_from_flags(self._wpa_flags, False)
            wireless_security = WirelessSecurity()
            wireless_security.key_mgmt = 'wpa-psk'
            wireless_security.proto = 'wpa'
            wireless_security.pairwise = pairwise
            wireless_security.group = group
            return wireless_security

    def __connect_activate_cb(self, icon):
        self._connect()

    def _connect(self):
        # Activate existing connection, if there is one
        connection = network.find_connection_by_ssid(self._ssid)
        if connection:
            logging.debug('Activating existing connection for SSID %r',
                          self._ssid)
            connection.activate(self._device)
            return

        # Otherwise, create new connection and activate it
        logging.debug('Creating new connection for SSID %r', self._ssid)
        settings = Settings()
        settings.connection.id = self._display_name
        settings.connection.uuid = str(uuid.uuid4())
        settings.connection.type = '802-11-wireless'
        settings.wireless.ssid = self._ssid

        if self._mode == network.NM_802_11_MODE_INFRA:
            settings.wireless.mode = 'infrastructure'
            settings.connection.autoconnect = True
        elif self._mode == network.NM_802_11_MODE_ADHOC:
            settings.wireless.mode = 'adhoc'
            settings.wireless.band = 'bg'
            settings.ip4_config = IP4Config()
            settings.ip4_config.method = 'link-local'

        wireless_security = self._get_security()
        settings.wireless_security = wireless_security

        if wireless_security is not None:
            settings.wireless.security = '802-11-wireless-security'

        network.add_and_activate_connection(self._device, settings,
                                            self.get_first_ap().model)

    def set_filter(self, query):
        normalized_name = normalize_string(self._display_name.decode('utf-8'))
        self._filtered = normalized_name.find(query) == -1
        self._update_icon()
        self._update_color()

    def create_keydialog(self, response):
        keydialog.create(self._ssid, self._flags, self._wpa_flags,
                         self._rsn_flags, self._device_caps, response)

    def update_strength(self):
        if self._active_ap is not None:
            # display strength of AP that we are connected to
            new_strength = self._active_ap.strength
        else:
            # display the strength of the strongest AP that makes up this
            # network, also considering that there may be no APs
            new_strength = max(
                [0] + [ap.strength for ap in self._access_points.values()])

        if new_strength != self._strength:
            self._strength = new_strength
            self._update_icon()

    def add_ap(self, ap):
        self._access_points[ap.model.object_path] = ap
        self.update_strength()

    def remove_ap(self, ap):
        path = ap.model.object_path
        if path not in self._access_points:
            return
        del self._access_points[path]
        if self._active_ap == ap:
            self._active_ap = None
        self.update_strength()

    def num_aps(self):
        return len(self._access_points)

    def find_ap(self, ap_path):
        if ap_path not in self._access_points:
            return None
        return self._access_points[ap_path]

    def get_first_ap(self):
        return self._access_points.values()[0]

    def is_olpc_mesh(self):
        return self._mode == network.NM_802_11_MODE_ADHOC \
            and self._ssid == 'olpc-mesh'

    def remove_all_aps(self):
        for ap in self._access_points.values():
            ap.disconnect()
        self._access_points = {}
        self._active_ap = None
        self.update_strength()

    def disconnect(self):
        self._bus.remove_signal_receiver(
            self.__device_state_changed_cb,
            signal_name='StateChanged',
            path=self._device.object_path,
            dbus_interface=network.NM_DEVICE_IFACE)
        self._bus.remove_signal_receiver(
            self.__wireless_properties_changed_cb,
            signal_name='PropertiesChanged',
            path=self._device.object_path,
            dbus_interface=network.NM_WIRELESS_IFACE)
Esempio n. 51
0
    def __init__(self, tabbed_view, act):
        ToolbarBase.__init__(self)

        self._url_toolbar = UrlToolbar()

        self._activity = act

        self._tabbed_view = self._canvas = tabbed_view

        self._loading = False

        toolbar = self.toolbar
        activity_button = ActivityToolbarButton(self._activity)
        toolbar.insert(activity_button, 0)

        separator = Gtk.SeparatorToolItem()

        save_as_pdf = ToolButton('save-as-pdf')
        save_as_pdf.set_tooltip(_('Save page as pdf'))
        save_as_pdf.connect('clicked', self.save_as_pdf)

        activity_button.props.page.insert(separator, -1)
        activity_button.props.page.insert(save_as_pdf, -1)
        separator.show()
        save_as_pdf.show()

        self._go_home = ToolButton('go-home')
        self._go_home.set_tooltip(_('Home page'))
        self._go_home.connect('clicked', self._go_home_cb)
        # add a menu to save the home page
        menu_box = PaletteMenuBox()
        self._go_home.props.palette.set_content(menu_box)

        self._reset_home_menu = PaletteMenuItem()
        self._reset_home_menu.set_label(_('Reset initial page'))
        self._reset_home_menu.connect('activate', self._reset_home_cb)
        menu_box.append_item(self._reset_home_menu)

        if os.path.isfile(LIBRARY_PATH):
            library_menu = PaletteMenuItem()
            library_menu.set_label(_('Library'))
            library_menu.connect('activate', self._go_library_cb)
            menu_box.append_item(library_menu)

        menu_box.show_all()

        # verify if the home page is configured
        self._reset_home_menu.set_visible(False)

        toolbar.insert(self._go_home, -1)
        self._go_home.show()

        self.entry = WebEntry()
        self.entry.set_icon_from_name(iconentry.ICON_ENTRY_SECONDARY,
                                      'entry-stop')
        self.entry.connect('icon-press', self._stop_and_reload_cb)
        self.entry.connect('activate', self._entry_activate_cb)
        self.entry.connect('focus-in-event', self.__focus_in_event_cb)
        self.entry.connect('focus-out-event', self.__focus_out_event_cb)
        self.entry.connect('key-press-event', self.__key_press_event_cb)
        self.entry.connect('changed', self.__changed_cb)

        self._entry_item = Gtk.ToolItem()
        self._entry_item.set_expand(True)
        self._entry_item.add(self.entry)
        self.entry.show()

        toolbar.insert(self._entry_item, -1)

        self._entry_item.show()

        self._back = ToolButton('go-previous-paired')
        self._back.set_tooltip(_('Back'))
        self._back.props.sensitive = False
        self._back.connect('clicked', self._go_back_cb)
        toolbar.insert(self._back, -1)
        self._back.show()

        palette = self._back.get_palette()
        self._back_box_menu = Gtk.VBox()
        self._back_box_menu.show()
        palette.set_content(self._back_box_menu)
        # FIXME, this is a hack, should be done in the theme:
        palette._content.set_border_width(1)

        self._forward = ToolButton('go-next-paired')
        self._forward.set_tooltip(_('Forward'))
        self._forward.props.sensitive = False
        self._forward.connect('clicked', self._go_forward_cb)
        toolbar.insert(self._forward, -1)
        self._forward.show()

        palette = self._forward.get_palette()
        self._forward_box_menu = Gtk.VBox()
        self._forward_box_menu.show()
        palette.set_content(self._forward_box_menu)
        # FIXME, this is a hack, should be done in the theme:
        palette._content.set_border_width(1)

        self._link_add = ToolButton('emblem-favorite')
        self._link_add.set_tooltip(_('Bookmark'))
        self._link_add.connect('clicked', self._link_add_clicked_cb)
        toolbar.insert(self._link_add, -1)
        self._link_add.show()

        self._toolbar_separator = Gtk.SeparatorToolItem()
        self._toolbar_separator.props.draw = False
        self._toolbar_separator.set_expand(True)

        stop_button = StopButton(self._activity)
        toolbar.insert(stop_button, -1)

        self._progress_listener = None
        self._browser = None

        self._loading_changed_hid = None
        self._progress_changed_hid = None
        self._session_history_changed_hid = None
        self._uri_changed_hid = None
        self._security_status_changed_hid = None

        if tabbed_view.get_n_pages():
            self._connect_to_browser(tabbed_view.props.current_browser)

        tabbed_view.connect_after('switch-page', self.__switch_page_cb)
        tabbed_view.connect_after('page-added', self.__page_added_cb)

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

        self._configure_toolbar()
Esempio n. 52
0
class RecdButton(TrayButton):
    __gsignals__ = {
        'remove-requested': (GObject.SignalFlags.RUN_LAST, None, ()),
        'copy-clipboard-requested': (GObject.SignalFlags.RUN_LAST, None, ()),
    }

    def __init__(self, recd):
        TrayButton.__init__(self)
        self._recd = recd

        self.set_icon_widget(self.get_image())
        self._copy_menu_item_handler = None

        palette = Palette(recd.title)
        self.set_palette(palette)

        self._box = PaletteMenuBox()
        palette.set_content(self._box)
        self._box.show()

        self._rem_menu_item = PaletteMenuItem(_('Erase'),
                                              icon_name='edit-delete')
        self._rem_menu_item_handler = self._rem_menu_item.connect(
            'activate', self._remove_clicked)
        self._box.append_item(self._rem_menu_item)
        self._rem_menu_item.show()

        self._add_copy_menu_item()

    def _add_copy_menu_item(self):
        if self._recd.buddy and not self._recd.downloadedFromBuddy:
            return

        self._copy_menu_item = PaletteMenuItem(_('Copy to clipboard'),
                                               icon_name='edit-copy')
        self._copy_menu_item_handler = self._copy_menu_item.connect(
            'activate', self._copy_clipboard_clicked)
        self._box.append_item(self._copy_menu_item)
        self._copy_menu_item.show()

    def get_recd(self):
        return self._recd

    def get_image(self):
        ipb = self._recd.getThumbPixbuf()

        if ipb:
            w = ipb.get_width()
            h = ipb.get_height()
            a = float(w) / float(h)
        else:
            a = 16. / 9

        if a < 1.4:
            paths = {
                constants.TYPE_PHOTO: 'object-photo.svg',
                constants.TYPE_VIDEO: 'object-video.svg',
                constants.TYPE_AUDIO: 'object-audio.svg'
            }
            x = 8
            y = 8
        else:
            paths = {
                constants.TYPE_PHOTO: 'object-photo-16to9.svg',
                constants.TYPE_VIDEO: 'object-video-16to9.svg',
                constants.TYPE_AUDIO: 'object-audio-16to9.svg'
            }
            x = 9
            y = 18

        path = paths[self._recd.type]

        pixbuf = utils.load_colored_svg(path, self._recd.colorStroke,
                                        self._recd.colorFill)
        if ipb:
            ipb.composite(pixbuf, x, y, w, h, x, y, 1, 1,
                          GdkPixbuf.InterpType.BILINEAR, 255)
        img = Gtk.Image()
        img.set_from_pixbuf(pixbuf)
        img.show()
        return img

    def cleanup(self):
        self._rem_menu_item.disconnect(self._rem_menu_item_handler)
        if self._copy_menu_item_handler is not None:
            self._copy_menu_item.disconnect(self._copy_menu_item_handler)

    def _remove_clicked(self, widget):
        self.emit('remove-requested')

    def _copy_clipboard_clicked(self, widget):
        self.emit('copy-clipboard-requested')