Exemple #1
0
    def setup_palette(self):
        activity_name = self._home_activity.get_activity_name()
        if activity_name:
            self.props.primary_text = glib.markup_escape_text(activity_name)

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

        menu_item = MenuItem(_('Resume'), 'activity-start')
        menu_item.connect('activate', self.__resume_activate_cb)
        self.menu.append(menu_item)
        menu_item.show()

        # TODO: share-with, keep

        menu_item = MenuItem(_('View Source'), 'view-source')
        # TODO Make this accelerator translatable
        menu_item.props.accelerator = '<Alt><Shift>v'
        menu_item.connect('activate', self.__view_source__cb)
        self.menu.append(menu_item)
        menu_item.show()

        separator = gtk.SeparatorMenuItem()
        self.menu.append(separator)
        separator.show()

        menu_item = MenuItem(_('Stop'), 'activity-stop')
        menu_item.connect('activate', self.__stop_activate_cb)
        self.menu.append(menu_item)
        menu_item.show()
Exemple #2
0
    def __init__(self):
        label = glib.markup_escape_text(_('Wired Network'))
        Palette.__init__(self, primary_text=label)

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

        self._ip_address_label = Gtk.Label()

        self._info = Gtk.VBox()

        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._speed_label), True, True, 0)
        self._info.pack_start(_padded(self._ip_address_label), True, True, 0)
        self._info.show_all()

        self.set_content(self._info)
        self.props.secondary_text = glib.markup_escape_text(_('Connected'))
Exemple #3
0
    def __init__(self):
        label = glib.markup_escape_text(_('Wired Network'))
        Palette.__init__(self, primary_text=label)

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

        self._ip_address_label = Gtk.Label()

        self._info = Gtk.VBox()

        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._speed_label), True, True, 0)
        self._info.pack_start(_padded(self._ip_address_label), True, True, 0)
        self._info.show_all()

        self.set_content(self._info)
        self.props.secondary_text = glib.markup_escape_text(_('Connected'))
Exemple #4
0
def notify():
    from glib import markup_escape_text
    import pynotify
    pynotify.init('vk-notify')

    try:
        token, _ = get_settings()
        user_messages = get_new_messages(token)

        tm = 5000
        for (user, title), g in groupby(user_messages, lambda (u, t, _):(u, t)):
            messages = map(markup_escape_text, (r['body'] for _, _, r in g))
            ntitle = markup_escape_text(user)
            if title:
                ntitle = u'{} (<small>{}</small>)'.format(ntitle, markup_escape_text(title))
            n = pynotify.Notification(ntitle, u'\n'.join(messages))
            n.set_timeout(tm)
            n.show()
            tm += 2000

    except Exception as e:
        n = pynotify.Notification('VK', markup_escape_text(str(e)))
        n.set_timeout(5000)
        n.show()
        raise
Exemple #5
0
        def message_data_func(column, cell, model, tree_iter, user_data):

            msg = model.get_value(tree_iter, id_)

            if not highlighters:
                cell.props.text = msg
                return

            if len(highlighters) > 1:
                raise NotImplementedError("FIXME: Support more than one...")

            highlighter = highlighters.values()[0]
            row = model[tree_iter]
            ranges = highlighter(row)
            if not ranges:
                cell.props.text = msg
            else:
                tags = []
                prev_end = 0
                end = None
                for start, end in ranges:
                    if prev_end < start:
                        tags.append(
                            glib.markup_escape_text(msg[prev_end:start]))
                    msg_escape = glib.markup_escape_text(msg[start:end])
                    tags.append("<span foreground=\'#FFFFFF\'"
                                " background=\'#0000FF\'>%s</span>" %
                                (msg_escape, ))
                    prev_end = end
                if end is not None:
                    tags.append(glib.markup_escape_text(msg[end:]))
                cell.props.markup = "".join(tags)
Exemple #6
0
    def setup_palette(self):
        activity_name = self._home_activity.get_activity_name()
        if activity_name:
            self.props.primary_text = glib.markup_escape_text(activity_name)

        title = self._home_activity.get_title()
        if title and title != activity_name:
            self.props.secondary_text = glib.markup_escape_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)

        # TODO: share-with, keep

        menu_item = PaletteMenuItem(_('View Source'), 'view-source')
        menu_item.connect('activate', self.__view_source__cb)
        self.menu_box.append_item(menu_item)

        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)

        self.set_content(self.menu_box)
        self.menu_box.show_all()
    def _show_message(self, msgtype, message_str, boxtitle = "",
                            headline_str = "", secmsg_str = ""):
        """Shows message box using markup.
        
        @attention: gtk.MessageDialog is not fully thread-safe so it is
                    put in a critical section, here!
        """
        gtk.gdk.threads_enter()
        dialog = gtk.MessageDialog(
                    flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                    type = msgtype,
                    buttons = gtk.BUTTONS_CLOSE)
        if boxtitle.strip() != "":
            dialog.set_title(boxtitle)

        _hdl = headline_str.strip(" \n\t")
        if _hdl != "":
            _hdl = "<b>%s</b>\n\n" % (glib.markup_escape_text(_hdl))
        _msg = "%s%s" % (_hdl, glib.markup_escape_text(message_str))
        dialog.set_markup(_msg)

        # an optional secondary message is added
        _sec = secmsg_str.strip(" \n\t")
        if _sec != "":
            _sec = "<small>%s</small>" % (glib.markup_escape_text(_sec))
            dialog.format_secondary_markup(_sec)

        # show the message box and destroy it afterwards
        dialog.run()
        dialog.destroy()
        gtk.gdk.threads_leave()
Exemple #8
0
        def message_data_func (column, cell, model, tree_iter, user_data):

            msg = model.get_value (tree_iter, id_)

            if not highlighters:
                cell.props.text = msg
                return

            if len (highlighters) > 1:
                raise NotImplementedError ("FIXME: Support more than one...")

            highlighter = highlighters.values ()[0]
            row = model[tree_iter]
            ranges = highlighter (row)
            if not ranges:
                cell.props.text = msg
            else:
                tags = []
                prev_end = 0
                end = None
                for start, end in ranges:
                    if prev_end < start:
                        tags.append (glib.markup_escape_text (msg[prev_end:start]))
                    msg_escape = glib.markup_escape_text (msg[start:end])
                    tags.append ("<span foreground=\'#FFFFFF\'"
                                 " background=\'#0000FF\'>%s</span>" % (msg_escape,))
                    prev_end = end
                if end is not None:
                    tags.append (glib.markup_escape_text (msg[end:]))
                cell.props.markup = "".join (tags)
 def __set_mpris_meta_info(self, pid):
     if 'mpris:artUrl' in self.mpris2.mpris_process[pid]['property']['Metadata']:
         arturl = urlparse(self.mpris2.mpris_process[pid]['property']['Metadata']['mpris:artUrl'])
         if arturl.scheme == 'file' and os.path.exists(arturl.path):
             art_pixbuf = gtk.gdk.pixbuf_new_from_file(arturl.path).scale_simple(32, 32, gtk.gdk.INTERP_TILES)
             #self.mpris_list[pid]['meta_img'].set_from_pixbuf(art_pixbuf)
             self.mpris_list[pid]['meta_img'].pixbuf = art_pixbuf
     else:
         self.mpris_list[pid]['meta_img'].pixbuf = self.mpris_list[pid]['logo']
     self.mpris_list[pid]['meta_img'].queue_draw()
     if 'xesam:title' in self.mpris2.mpris_process[pid]['property']['Metadata']:
         self.mpris_list[pid]['meta_title'].set_text(
             markup_escape_text(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:title']))
     else:
         self.mpris_list[pid]['meta_title'].set_text("-")
     if 'xesam:artist' in self.mpris2.mpris_process[pid]['property']['Metadata']:
         self.mpris_list[pid]['meta_artist'].set_text(
             markup_escape_text('&'.join(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:artist'])))
     else:
         self.mpris_list[pid]['meta_artist'].set_text("-")
     if 'xesam:album' in self.mpris2.mpris_process[pid]['property']['Metadata']:
         self.mpris_list[pid]['meta_album'].set_text(
             markup_escape_text(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:album']))
     else:
         self.mpris_list[pid]['meta_album'].set_text("-")
Exemple #10
0
def notify():
    from glib import markup_escape_text
    import pynotify
    pynotify.init('vk-notify')

    try:
        token, _ = get_settings()
        user_messages = get_new_messages(token)

        tm = 5000
        for (user, title), g in groupby(user_messages, lambda (u, t, _):
                                        (u, t)):
            messages = map(markup_escape_text, (r['body'] for _, _, r in g))
            ntitle = markup_escape_text(user)
            if title:
                ntitle = u'{} (<small>{}</small>)'.format(
                    ntitle, markup_escape_text(title))
            n = pynotify.Notification(ntitle, u'\n'.join(messages))
            n.set_timeout(tm)
            n.show()
            tm += 2000

    except Exception as e:
        n = pynotify.Notification('VK', markup_escape_text(str(e)))
        n.set_timeout(5000)
        n.show()
        raise
Exemple #11
0
    def setup_palette(self):
        activity_name = self._home_activity.get_activity_name()
        if activity_name:
            self.props.primary_text = glib.markup_escape_text(activity_name)

        title = self._home_activity.get_title()
        if title and title != activity_name:
            self.props.secondary_text = glib.markup_escape_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)

        # TODO: share-with, keep

        menu_item = PaletteMenuItem(_('View Source'), 'view-source')
        menu_item.connect('activate', self.__view_source__cb)
        self.menu_box.append_item(menu_item)

        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)

        self.set_content(self.menu_box)
        self.menu_box.show_all()
Exemple #12
0
    def setup_palette(self):
        activity_name = self._home_activity.get_activity_name()
        if activity_name:
            self.props.primary_text = glib.markup_escape_text(activity_name)

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

        menu_item = MenuItem(_('Resume'), 'activity-start')
        menu_item.connect('activate', self.__resume_activate_cb)
        self.menu.append(menu_item)
        menu_item.show()

        # TODO: share-with, keep

        menu_item = MenuItem(_('View Source'), 'view-source')
        # TODO Make this accelerator translatable
        menu_item.props.accelerator = '<Alt><Shift>v'
        menu_item.connect('activate', self.__view_source__cb)
        self.menu.append(menu_item)
        menu_item.show()

        separator = gtk.SeparatorMenuItem()
        self.menu.append(separator)
        separator.show()

        menu_item = MenuItem(_('Stop'), 'activity-stop')
        menu_item.connect('activate', self.__stop_activate_cb)
        self.menu.append(menu_item)
        menu_item.show()
 def __set_mpris_meta_info(self, pid):
     if 'mpris:artUrl' in self.mpris2.mpris_process[pid]['property']['Metadata']:
         arturl = urlparse(self.mpris2.mpris_process[pid]['property']['Metadata']['mpris:artUrl'])
         if arturl.scheme == 'file' and os.path.exists(arturl.path):
             art_pixbuf = gtk.gdk.pixbuf_new_from_file(arturl.path).scale_simple(32, 32, gtk.gdk.INTERP_TILES)
             #self.mpris_list[pid]['meta_img'].set_from_pixbuf(art_pixbuf)
             self.mpris_list[pid]['meta_img'].pixbuf = art_pixbuf
     else:
         self.mpris_list[pid]['meta_img'].pixbuf = None
     self.mpris_list[pid]['meta_img'].queue_draw()
     if 'xesam:title' in self.mpris2.mpris_process[pid]['property']['Metadata']:
         self.mpris_list[pid]['meta_title'].set_text(
             markup_escape_text(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:title']))
     else:
         self.mpris_list[pid]['meta_title'].set_text("-")
     if 'xesam:artist' in self.mpris2.mpris_process[pid]['property']['Metadata']:
         self.mpris_list[pid]['meta_artist'].set_text(
             markup_escape_text('&'.join(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:artist'])))
     else:
         self.mpris_list[pid]['meta_artist'].set_text("-")
     if 'xesam:album' in self.mpris2.mpris_process[pid]['property']['Metadata']:
         self.mpris_list[pid]['meta_album'].set_text(
             markup_escape_text(self.mpris2.mpris_process[pid]['property']['Metadata']['xesam:album']))
     else:
         self.mpris_list[pid]['meta_album'].set_text("-")
Exemple #14
0
        def stream_tags_changed_cb(client):
            self.__current_title = client.stream_tags.get(
                'title').strip() or None
            org = client.stream_tags.get('organization').strip() or None
            markup = []

            if self.__current_title:
                markup.append('<b>%s</b>' %
                              glib.markup_escape_text(self.__current_title))
            if org:
                markup.append('<small>%s</small>' %
                              glib.markup_escape_text(org))

            if markup:
                self.__stream_info.set_markup(' - '.join(markup))
                self.__stream_info.set_tooltip_markup('\n'.join(markup))
                self.__stream_info.show()

            else:
                self.__stream_info.set_markup('')
                self.__stream_info.hide()

            self.__favorite_button.set_sensitive(bool(self.__current_title))
            self.__favorite_button.set_active(
                self.__current_title in self.__wishlist)
Exemple #15
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())
        p_icon = Icon(file=self._model.bundle.get_icon(),
                      xo_color=self._model.get_color())
        p_icon.props.icon_size = gtk.ICON_SIZE_LARGE_TOOLBAR
        p = palette.Palette(None,
                            primary_text=primary_text,
                            secondary_text=secondary_text,
                            icon=p_icon)

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

        if joined:
            item = MenuItem(_('Resume'), 'activity-start')
            item.connect('activate', self._clicked_cb)
            item.show()
            p.menu.append(item)
        elif not private:
            item = MenuItem(_('Join'), 'activity-start')
            item.connect('activate', self._clicked_cb)
            item.show()
            p.menu.append(item)

        return p
Exemple #16
0
def markup(text, isheading):
	"""
	Gives markup for name - for liststore.
	"""
	if isheading:
		return "<u><i>%s</i></u>" % (glib.markup_escape_text(text))
	else:
		return glib.markup_escape_text(text)
Exemple #17
0
def markup(text, isheading):
    """
    Gives markup for name - for liststore.
    """
    if isheading:
        return "<u><i>%s</i></u>" % (glib.markup_escape_text(text))
    else:
        return glib.markup_escape_text(text)
 def _update(self):
     name = self._cb_object.get_name()
     self.props.primary_text = glib.markup_escape_text(name)
     preview = self._cb_object.get_preview()
     if preview:
         self.props.secondary_text = glib.markup_escape_text(preview)
     self._update_progress_bar()
     self._update_items_visibility()
     self._update_open_submenu()
Exemple #19
0
 def _update(self):
     name = self._cb_object.get_name()
     self.props.primary_text = glib.markup_escape_text(name)
     preview = self._cb_object.get_preview()
     if preview:
         self.props.secondary_text = glib.markup_escape_text(preview)
     self._update_progress_bar()
     self._update_items_visibility()
     self._update_open_submenu()
Exemple #20
0
    def _format(self, show_err):
        buffer = self._window.get_active_document()
        text = buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter())

        try:
            p = subprocess.Popen([self._plugin.model.gobin_path + '/gofmt'],
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)

            stdoutdata, stderrdata = p.communicate(text)
        except OSError as e:
            if show_err:
                dialog = gtk.MessageDialog(flags=gtk.DIALOG_DESTROY_WITH_PARENT,
                                           type=gtk.MESSAGE_ERROR,
                                           buttons=gtk.BUTTONS_OK)
                dialog.set_markup(_("An error occurred when <i>gofmt</i> was attempted to run:"))
                dialog.format_secondary_markup('<span font_family="monospace">' +
                                               glib.markup_escape_text(str(e)) +
                                               '</span>')
                dialog.run()
                dialog.destroy()

        if len(stderrdata) != 0:
            if show_err:
                dialog = gtk.MessageDialog(flags=gtk.DIALOG_DESTROY_WITH_PARENT,
                                           type=gtk.MESSAGE_ERROR,
                                           buttons=gtk.BUTTONS_OK)
                dialog.set_markup(_("An error occurred while running <i>gofmt</i>:"))
                if len(stderrdata) > utils.MAX_ERR_MSG_LEN: # cut down too long error messages
                    stderrdata = stderrdata[:utils.MAX_ERR_MSG_LEN] + "..."
                dialog.format_secondary_markup('<span font_family="monospace">' +
                                               glib.markup_escape_text(stderrdata) +
                                               '</span>')
                dialog.run()
                dialog.destroy()
            return

        # save the cursor position before modifying the document
        cursor_iter = utils.get_iter_cursor(buffer)
        offset = cursor_iter.get_offset()
        old_buf_len = buffer.get_char_count()

        buffer.begin_user_action()

        buffer.set_text(stdoutdata)

        # attempt to return the cursor back to where it was
        new_buf_len = buffer.get_char_count()
        # adjust offset to account for indentation changes
        new_offset = offset + (new_buf_len - old_buf_len)
        buffer.place_cursor(buffer.get_iter_at_offset(new_offset))
        view = self._window.get_active_view()
        utils.scroll_to_insert(buffer, view)

        buffer.end_user_action()
Exemple #21
0
 def _finish_single_copy(self, source, async_result):
     
     try:
         if source.copy_finish(async_result):
             self._step()
             self._start_next_copy()
     except gio.Error,e:
         self._on_error( _("Error occurred while copying %s: %s") % (
             glib.markup_escape_text( self.source.get_uri() ),
             glib.markup_escape_text( str(e) ) ) )
Exemple #22
0
 def get_repl_markup(self, repl):
     if type(repl) != list:
         repl = [repl]
     for c in repl:
         if type(c) != ReplData:
             return unicode(glib.markup_escape_text(c))
         if c.font is None:
             return unicode(glib.markup_escape_text(c.value))
         elif c.font in self.font_families:
             return '<span font_family="' + c.font + '">' + \
                 unicode(glib.markup_escape_text(c.value)) + '</span>'
Exemple #23
0
 def get_repl_markup(self, repl):
     if type(repl) != list:
         repl = [repl]
     for c in repl:
         if type(c) != ReplData:
             return unicode(glib.markup_escape_text(c))
         if c.font is None:
             return unicode(glib.markup_escape_text(c.value))
         elif c.font in self.font_families:
             return '<span font_family="' + c.font + '">' + \
                 unicode(glib.markup_escape_text(c.value)) + '</span>'
Exemple #24
0
 def populate_tree_view(self, content_pages):
     """Populate the tree view with tasks from `content_pages`."""
     self._tree_view.get_model().clear()
     store = self._tree_view.get_model()
     pages = gaupol.conf.text_assistant.pages
     for page in content_pages:
         title = glib.markup_escape_text(page.title)
         description = glib.markup_escape_text(page.description)
         markup = "<b>%s</b>\n%s" % (title, description)
         page.props.visible = (page.handle in pages)
         store.append((page, page.handle in pages, markup))
     self._tree_view.get_selection().unselect_all()
Exemple #25
0
    def update(self, value, label, text):
        """ Update dialog information.

		@value: value to set for progress bar
		@label: current action (displayed in emphasized style)
		@text: current information (normal style)
		"""
        self.progressbar.set_fraction(min(value / self.max_value, 1.0))
        self.label_info.set_markup(u"<b>%s</b> %s" % (
            glib.markup_escape_text(label),
            glib.markup_escape_text(text),
        ))
        return self.aborted
Exemple #26
0
    def update(self, value, label, text):
        """ Update dialog information.

        @value: value to set for progress bar
        @label: current action (displayed in emphasized style)
        @text: current information (normal style)
        """
        self.progressbar.set_fraction(min(value / self.max_value, 1.0))
        self.label_info.set_markup(u"<b>%s</b> %s" %
            (
                glib.markup_escape_text(label),
                glib.markup_escape_text(text),
            ))
        return self.aborted
Exemple #27
0
    def do_get_size(self, widget, cell_area):
        if self._details_callback:
            details = self._details_callback(self.data)
            mark_up = '%s\n<span foreground="%s">%s</span>'
            color = gdk_color_to_string(widget.style.fg[gtk.STATE_NORMAL])
            text = mark_up % (self.label, color,
                              glib.markup_escape_text(details))
        else:
            text = glib.markup_escape_text(self.label)

        self._label_layout.set_markup(text)
        width, height = self._label_layout.get_pixel_size()

        return 0, 0, width, height + 2
Exemple #28
0
def pangonify_rst(text):
    result = ""

    lines = text.strip().expandtabs().splitlines()

    if len(lines) > 1 and lines[1].strip():
        lines = [lines[0]] + [""] + lines[1:]

    indent = 1000
    for l in lines[1:]:
        stripped = l.lstrip()
        if stripped:
            indent = min(indent, len(l) - len(stripped))

    trimmed = [lines[0].strip()]
    if indent < 1000:
        for line in lines[1:]:
            trimmed.append(line[indent:].rstrip())

    wrapper = textwrap.TextWrapper(width=60)
    paragraph = ""
    break_paragraph = False

    def add_paragraph():
        r = result
        if paragraph:
            if break_paragraph:
                r += "\n"

            r += wrapper.fill(paragraph) + "\n\n"
            return r, "", False

        return r, "", break_paragraph

    for l in trimmed:
        if not l.strip():
            result, paragraph, break_paragraph = add_paragraph()
        else:
            if l.startswith("  "):
                result, paragraph, break_paragraph = add_paragraph()
                break_paragraph = True
                result += "<tt>%s</tt>" % markup_escape_text(l)
                result += "\n"
            else:
                paragraph += markup_escape_text(l) + " "

    if paragraph:
        result, _, _ = add_paragraph()

    return result
Exemple #29
0
    def _get_odata(self, buffer, cursor_iter):
        """
        Return gocode object data.
        """ 
        cursor_offset = cursor_iter.get_offset()
        text = buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter())
        byte_offset = len(buffer.get_text(buffer.get_start_iter(), buffer.get_iter_at_offset(cursor_offset)))
        try:
            p = subprocess.Popen([self._plugin.model.gobin_path + '/gocode',
                                '-f=json',
                                'autocomplete',
                                buffer.get_uri_for_display(),
                                str(byte_offset)],
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        except OSError as e:
            dialog = gtk.MessageDialog(flags=gtk.DIALOG_DESTROY_WITH_PARENT,
                                       type=gtk.MESSAGE_ERROR,
                                       buttons=gtk.BUTTONS_OK)
            dialog.set_markup(_("An error occurred when <i>gocode</i> was attempted to run:"))
            dialog.format_secondary_markup('<span font_family="monospace">' +
                                           glib.markup_escape_text(str(e)) +
                                           '</span>')
            dialog.run()
            dialog.destroy()
            return []

        stdoutdata, stderrdata = p.communicate(text)

        if len(stderrdata) != 0:
            dialog = gtk.MessageDialog(flags=gtk.DIALOG_DESTROY_WITH_PARENT,
                                       type=gtk.MESSAGE_ERROR,
                                       buttons=gtk.BUTTONS_OK)
            dialog.set_markup(_("An error occurred while running <i>gocode</i>:"))
            if len(stderrdata) > utils.MAX_ERR_MSG_LEN: # cut down too long error messages
                stderrdata = stderrdata[:utils.MAX_ERR_MSG_LEN] + "..."
            dialog.format_secondary_markup('<span font_family="monospace">' +
                                           glib.markup_escape_text(stderrdata) +
                                           '</span>')
            dialog.run()
            dialog.destroy()
            return []

        try:
            return json.loads(stdoutdata)
        except ValueError:
            print "ERROR: gocode input was invalid."
            return []
Exemple #30
0
    def show_error (self, message1, message2):

        bar = Gtk.InfoBar ()
        bar.props.message_type = Gtk.MessageType.ERROR
        box = bar.get_content_area ()

        markup = "<b>%s</b> %s" % (glib.markup_escape_text (message1),
                                   glib.markup_escape_text (message2),)
        label = Gtk.Label ()
        label.props.use_markup = True
        label.props.label = markup
        label.props.selectable = True
        box.pack_start (label, False, False, 0)

        self.show_info (bar)
def info_name(info):
    """Return a human-readable filename (without the path and quoting)."""
    if  isinstance(info, GES.Asset):
        filename = unquote(os.path.basename(info.get_id()))
    else:
        filename = unquote(os.path.basename(info.get_uri()))
    return glib.markup_escape_text(filename)
Exemple #32
0
 def create_palette(self):
     """ Create a palette for this icon; called by the Sugar framework
     when a palette needs to be displayed. """
     label = glib.markup_escape_text(_('My touchpad'))
     self.palette = ResourcePalette(label, self.icon)
     self.palette.set_group_id('frame')
     return self.palette
Exemple #33
0
    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_
Exemple #34
0
 def escape(self, string):
     """Escapes the text and makes it suitable for use with a
     PangoMarkup, usually via Label.set_markup()"""
     import glib
     if string is None:
         string = ''
     return unicode(glib.markup_escape_text(string))
Exemple #35
0
    def setup_palette(self):
        title = self._home_activity.get_title()
        self.set_primary_text(glib.markup_escape_text(title))

        vbox = gtk.VBox()
        self.set_content(vbox)
        vbox.show()

        self._progress_bar = gtk.ProgressBar()
        vbox.add(self._progress_bar)
        self._progress_bar.show()

        self._free_space_label = gtk.Label()
        self._free_space_label.set_alignment(0.5, 0.5)
        vbox.add(self._free_space_label)
        self._free_space_label.show()

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

        menu_item = MenuItem(_('Show contents'))

        icon = Icon(file=self._home_activity.get_icon_path(),
                    icon_size=gtk.ICON_SIZE_MENU,
                    xo_color=self._home_activity.get_icon_color())
        menu_item.set_image(icon)
        icon.show()

        menu_item.connect('activate', self.__open_activate_cb)
        self.menu.append(menu_item)
        menu_item.show()
Exemple #36
0
    def __init__(self, mount):
        Palette.__init__(self, label=mount.get_name())
        self._mount = mount

        path = mount.get_root().get_path()
        self.props.secondary_text = glib.markup_escape_text(path)

        vbox = gtk.VBox()
        self.set_content(vbox)
        vbox.show()

        self._progress_bar = gtk.ProgressBar()
        vbox.add(self._progress_bar)
        self._progress_bar.show()

        self._free_space_label = gtk.Label()
        self._free_space_label.set_alignment(0.5, 0.5)
        vbox.add(self._free_space_label)
        self._free_space_label.show()

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

        menu_item = MenuItem(pgettext('Volume', 'Remove'))

        icon = Icon(icon_name='media-eject', icon_size=gtk.ICON_SIZE_MENU)
        menu_item.set_image(icon)
        icon.show()

        menu_item.connect('activate', self.__unmount_activate_cb)
        self.menu.append(menu_item)
        menu_item.show()
Exemple #37
0
 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'
     text = _('Connected for %s') % (formatted_time, )
     self.props.secondary_text = glib.markup_escape_text(text)
Exemple #38
0
 def create_palette(self):
     """ Create a palette for this icon; called by the Sugar framework
     when a palette needs to be displayed. """
     label = glib.markup_escape_text(_('My touchpad'))
     self.palette = ResourcePalette(label, self.icon)
     self.palette.set_group_id('frame')
     return self.palette
Exemple #39
0
    def __init__(self, activity_info):
        self._activity_info = activity_info

        client = GConf.Client.get_default()
        color = XoColor(client.get_string('/desktop/sugar/user/color'))
        activity_icon = Icon(file=activity_info.get_icon(),
                             xo_color=color,
                             icon_size=Gtk.IconSize.LARGE_TOOLBAR)

        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()
Exemple #40
0
    def key_raw_mode(self, event):
        # modifiers
        mod = ''
        for cap in REPLACE_MODS.keys():
            if event.modifiers[cap]:
                mod = mod + REPLACE_MODS[cap][self.mods_index]

        # keycaps
        key_repl = self.replace_syms.get(event.symbol)
        if key_repl is None:
            if keysym_to_mod(event.symbol):
                return False
            else:
                repl = event.string.upper() if event.string else event.symbol
                markup = unicode(glib.markup_escape_text(repl))
                key_repl = KeyRepl(False, False, len(repl) > 1, markup)

        if mod == '':
            repl = key_repl.repl

            # switches
            if event.symbol in ['Caps_Lock', 'Num_Lock']:
                state = event.modifiers[event.symbol.lower()]
                repl += '(%s)' % (_('off') if state else _('on'))

            self.data.append(KeyData(datetime.now(), False, key_repl.bk_stop,
                                     key_repl.silent, key_repl.spaced, repl))
        else:
            if self.mods_mode == 'emacs' or key_repl.repl[0] != mod[-1]:
                repl = mod + key_repl.repl
            else:
                repl = mod + '‟' + key_repl.repl + '”'
            self.data.append(KeyData(datetime.now(), True, key_repl.bk_stop,
                                     key_repl.silent, key_repl.spaced, repl))
        return True
Exemple #41
0
def info_name(info):
    """Return a human-readable filename (without the path and quoting)."""
    if isinstance(info, GES.Asset):
        filename = unquote(os.path.basename(info.get_id()))
    else:
        filename = unquote(os.path.basename(info.get_uri()))
    return glib.markup_escape_text(filename)
Exemple #42
0
    def _update_secondary(self):
        secondary_text = ''
        status_text = '%s%%' % (self._level, )

        progress_widget = self._progress_widget
        if self._status == _STATUS_NOT_PRESENT:
            secondary_text = _('Removed')
            progress_widget = None
        elif self._status == _STATUS_CHARGING:
            secondary_text = _('Charging')
        elif self._status == _STATUS_DISCHARGING:
            if self._level <= _WARN_MIN_PERCENTAGE:
                secondary_text = _('Very little power remaining')
            else:
                minutes_remaining = self._time // 60
                remaining_hourpart = minutes_remaining // 60
                remaining_minpart = minutes_remaining % 60
                # TRANS: do not translate %(hour)d:%(min).2d  it is a variable,
                # only translate the word "remaining"
                secondary_text = _('%(hour)d:%(min).2d remaining') % \
                        {'hour': remaining_hourpart, 'min': remaining_minpart}
        else:
            secondary_text = _('Charged')

        self.set_content(progress_widget)

        self.props.secondary_text = glib.markup_escape_text(secondary_text)
        self._status_label.set_text(status_text)
Exemple #43
0
    def _play_video(self, idx):
        video = self._videos[idx]
        self._menu.hide()
        self._video.show()
        self._video.stop()

        self._video_title.set_markup('<span size="x-large" weight="bold">' +
                                     glib.markup_escape_text(video[1]) +
                                     '</span>')
        self._video_title.show()

        if len(video) > 2:
            self._video_description.set_text(video[2].strip())
        else:
            self._video_description.set_text('')
        self._video_description.show()

        if len(video) > 3:
            music_name = video[3]
        else:
            music_name = None

        self._video.play(video[0], music_name)
        self._current_video_idx = idx
        self._dance_button.set_sensitive(True)
        self._exercise_button.set_sensitive(True)

        self._prev_button.set_sensitive(idx != 0)
        self._next_button.set_sensitive(idx != (len(self._videos) - 1))
Exemple #44
0
    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()
Exemple #45
0
    def _check_client_birthdays(self):
        if not api.sysparam.get_bool('BIRTHDAY_NOTIFICATION'):
            return

        # Display the info bar once per day
        date = api.user_settings.get('last-birthday-check')
        last_check = date and datetime.datetime.strptime(date, '%Y-%m-%d').date()
        if last_check and last_check >= datetime.date.today():
            return

        # Only display the infobar if the user has access to calendar (because
        # clicking on the button will open it) and to sales (because it
        # requires that permission to be able to check client details)
        user = api.get_current_user(self.store)
        if not all([user.profile.check_app_permission(u'calendar'),
                    user.profile.check_app_permission(u'sales')]):
            return

        branch = api.get_current_branch(self.store)
        clients_count = ClientWithSalesView.find_by_birth_date(
            self.store, datetime.datetime.today(), branch=branch).count()

        if clients_count:
            msg = stoqlib_ngettext(
                _("There is %s client doing birthday today!"),
                _("There are %s clients doing birthday today!"),
                clients_count) % (clients_count, )
            button = gtk.Button(_("Check the calendar"))
            button.connect('clicked', self._on_check_calendar__clicked)

            self._birthdays_bar = self.add_info_bar(
                gtk.MESSAGE_INFO,
                "<b>%s</b>" % (glib.markup_escape_text(msg), ),
                action_widget=button)
Exemple #46
0
    def format(self, track, markup_escape=False):
        """
            Returns a string for places where
            track data is presented to the user

            :param track: a single track to take data from
            :type track: :class:`xl.trax.Track`
            :param markup_escape: whether to escape markup-like
                characters in tag values
            :type markup_escape: bool
            :returns: the formatted text
            :rtype: string
        """
        if not isinstance(track, trax.Track):
            raise TypeError('First argument to format() needs '
                            'to be of type xl.trax.Track')

        extractions = self.extract()
        self._substitutions = {}

        for identifier, (tag, parameters) in extractions.iteritems():
            provider = providers.get_provider('tag-formatting', tag)

            if provider is None:
                substitute = track.get_tag_display(tag)
            else:
                substitute = provider.format(track, parameters)

            if markup_escape:
                substitute = glib.markup_escape_text(substitute)

            self._substitutions[identifier] = substitute

        return Formatter.format(self)
Exemple #47
0
    def key_raw_mode(self, event):
        # modifiers
        mod = ''
        for cap in REPLACE_MODS.keys():
            if event.modifiers[cap]:
                mod = mod + REPLACE_MODS[cap][self.mods_index]

        # keycaps
        key_repl = self.replace_syms.get(event.symbol)
        if key_repl is None:
            if keysym_to_mod(event.symbol):
                return False
            else:
                repl = event.string.upper() if event.string else event.symbol
                markup = unicode(glib.markup_escape_text(repl))
                key_repl = KeyRepl(False, False, len(repl) > 1, markup)

        if mod == '':
            repl = key_repl.repl

            # switches
            if event.symbol in ['Caps_Lock', 'Num_Lock']:
                state = event.modifiers[event.symbol.lower()]
                repl += '(%s)' % (_('off') if state else _('on'))

            self.data.append(KeyData(datetime.now(), False, key_repl.bk_stop,
                                     key_repl.silent, key_repl.spaced, repl))
        else:
            if self.mods_mode == 'emacs' or key_repl.repl[0] != mod[-1]:
                repl = mod + key_repl.repl
            else:
                repl = mod + '‟' + key_repl.repl + '”'
            self.data.append(KeyData(datetime.now(), True, key_repl.bk_stop,
                                     key_repl.silent, key_repl.spaced, repl))
        return True
Exemple #48
0
    def _update_secondary(self):
        secondary_text = ''
        status_text = '%s%%' % (self._level, )

        progress_widget = self._progress_widget
        if self._status == _STATUS_NOT_PRESENT:
            secondary_text = _('Removed')
            progress_widget = None
        elif self._status == _STATUS_CHARGING:
            secondary_text = _('Charging')
        elif self._status == _STATUS_DISCHARGING:
            if self._level <= _WARN_MIN_PERCENTAGE:
                secondary_text = _('Very little power remaining')
            else:
                minutes_remaining = self._time // 60
                remaining_hourpart = minutes_remaining // 60
                remaining_minpart = minutes_remaining % 60
                # TRANS: do not translate %(hour)d:%(min).2d  it is a variable,
                # only translate the word "remaining"
                secondary_text = _('%(hour)d:%(min).2d remaining') % \
                        {'hour': remaining_hourpart, 'min': remaining_minpart}
        else:
            secondary_text = _('Charged')

        self.set_content(progress_widget)

        self.props.secondary_text = glib.markup_escape_text(secondary_text)
        self._status_label.set_text(status_text)
Exemple #49
0
 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'
     text = _('Connected for %s') % (formatted_time, )
     self.props.secondary_text = glib.markup_escape_text(text)
 def update_text(self):
     markup = ""
     recent = False
     for i, key in enumerate(self.data):
         if i != 0:
             # character block spacing
             last = self.data[i - 1]
             if last.repl[-1] == '\n':
                 pass
             elif len(key.repl.rstrip('\n')) > 1 or len(last.repl) > 1:
                 markup += ' '
             elif key.bk_stop or last.bk_stop:
                 markup += '<span font_family="sans">\u2009</span>'
         if not recent and (datetime.now() - key.stamp).total_seconds() < self.recent_thr:
             recent = True
             markup += '<u>'
         if len(key.repl) == 1 and 0x0300 <= ord(key.repl) <= 0x036F:
             # workaround for pango not handling ZWNJ correctly for combining marks
             markup += '\u180e' + key.repl + '\u200a'
         else:
             markup += '\u200c' + glib.markup_escape_text(key.repl)
     markup = markup.rstrip('\n')
     if recent:
         markup += '</u>'
     self.logger.debug("Label updated: %s." % repr(markup))
     self.listener(markup)
Exemple #51
0
    def __init__(self, invite):
        Palette.__init__(self, '')

        self._invite = invite

        menu_item = MenuItem(_('Join'), icon_name='dialog-ok')
        menu_item.connect('activate', self.__join_activate_cb)
        self.menu.append(menu_item)
        menu_item.show()

        menu_item = MenuItem(_('Decline'), icon_name='dialog-cancel')
        menu_item.connect('activate', self.__decline_activate_cb)
        self.menu.append(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(glib.markup_escape_text(name))
Exemple #52
0
 def set_title(self, title):
     '''Sets the title for this widget. Hides title if title is None'''
     if title is None:
         self.title.hide()
     else:
         self.title.set_markup('<big><b>' + glib.markup_escape_text(title) + '</b></big>')
         self.title.show()
Exemple #53
0
    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)

        label = glib.markup_escape_text(self._display_name)
        p = palette.Palette(primary_text=label, 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)

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

        self.connect_to_palette_pop_events(p)

        return p
Exemple #54
0
 def update_text(self):
     markup = ""
     recent = False
     for i, key in enumerate(self.data):
         if i != 0:
             last = self.data[i - 1]
             if len(key.repl) > 1 or len(last.repl) > 1:
                 markup += ' '
             elif key.bk_stop or last.bk_stop:
                 markup += '<span font_family="sans">\u2009</span>'
         if not recent and (datetime.now() - key.stamp).total_seconds() < self.recent_thr:
             recent = True
             markup += '<u>'
         escaped_key_repl = glib.markup_escape_text(key.repl)
         self.logger.debug("escaped_key_repl is: " + key.repl)
         codepoints = map(ord, key.repl)
         self.logger.debug("codepoints are: " + str(codepoints))
         # for some reason, in my system it screws formatting when running
         # this, so yeah, quick dirty hack to make it work
         if codepoints == [65107]:
             escaped_key_repl = '~'
         elif codepoints == [65106]:
             escaped_key_repl = '^'
         markup += '\u200c' + escaped_key_repl
     if recent:
         markup += '</u>'
     self.logger.debug("Label updated: %s." % markup)
     glib.idle_add(lambda: self.listener(markup))
Exemple #55
0
    def format(self, track, markup_escape=False):
        """
            Returns a string for places where
            track data is presented to the user

            :param track: a single track to take data from
            :type track: :class:`xl.trax.Track`
            :param markup_escape: whether to escape markup-like
                characters in tag values
            :type markup_escape: bool
            :returns: the formatted text
            :rtype: string
        """
        if not isinstance(track, trax.Track):
            raise TypeError('First argument to format() needs '
                            'to be of type xl.trax.Track')

        extractions = self.extract()
        self._substitutions = {}

        for identifier, (tag, parameters) in extractions.iteritems():
            provider = providers.get_provider('tag-formatting', tag)

            if provider is None:
                substitute = track.get_tag_display(tag)
            else:
                substitute = provider.format(track, parameters)

            if markup_escape:
                substitute = glib.markup_escape_text(substitute)

            self._substitutions[identifier] = substitute

        return Formatter.format(self)
Exemple #56
0
    def _check_client_birthdays(self):
        if not api.sysparam.get_bool('BIRTHDAY_NOTIFICATION'):
            return

        # Display the info bar once per day
        date = api.user_settings.get('last-birthday-check')
        last_check = date and datetime.datetime.strptime(date, '%Y-%m-%d').date()
        if last_check and last_check >= datetime.date.today():
            return

        # Only display the infobar if the user has access to calendar (because
        # clicking on the button will open it) and to sales (because it
        # requires that permission to be able to check client details)
        user = api.get_current_user(self.store)
        if not all([user.profile.check_app_permission(u'calendar'),
                    user.profile.check_app_permission(u'sales')]):
            return

        branch = api.get_current_branch(self.store)
        clients_count = ClientWithSalesView.find_by_birth_date(
            self.store, datetime.datetime.today(), branch=branch).count()

        if clients_count:
            msg = stoqlib_ngettext(
                _("There is %s client doing birthday today!"),
                _("There are %s clients doing birthday today!"),
                clients_count) % (clients_count, )
            button = gtk.Button(_("Check the calendar"))
            button.connect('clicked', self._on_check_calendar__clicked)

            self._birthdays_bar = self.add_info_bar(
                gtk.MESSAGE_INFO,
                "<b>%s</b>" % (glib.markup_escape_text(msg), ),
                action_widget=button)