def get_layout(self, widget): '''Gets the Pango layout used in the cell in a TreeView widget.''' layout = SmileyLayout(widget.create_pango_context(), self.function(unicode(self.markup, 'utf-8'))) if self.markup: try: decorated_markup = self.function(unicode(self.markup, 'utf-8')) except Exception, error: print "this nick: '%s' made the parser go crazy, striping" % \ (self.markup,) print error decorated_markup = Plus.msnplus_strip(self.markup) try: pango.parse_markup(self.function(unicode(self.markup, 'utf-8'), False)) except gobject.GError: print "invalid pango markup:", decorated_markup decorated_markup = Plus.msnplus_strip(self.markup) layout.set_text(decorated_markup)
def handle_markup (self, txt): """Handle markup inside of txt.""" if txt == None: print 'Warning, handle_markup handed None' return '' import pango outtxt = "" try: al,txt,sep = pango.parse_markup(txt,u'\x00') except: al,txt,sep = pango.parse_markup(xml.sax.saxutils.escape(txt),u'\x00') ai = al.get_iterator() more = True while more: fd,lang,atts=ai.get_font() chunk = xml.sax.saxutils.escape(txt.__getslice__(*ai.range())) trailing_newline = '' fields=fd.get_set_fields() if fields != 0: #if there are fields # Sometimes we get trailing newlines, which is ugly # because we end up with e.g. <b>Foo\n</b> # # So we define trailing_newline as a variable if chunk and chunk[-1]=='\n': trailing_newline = '\n'; chunk = chunk[:-1] if 'style' in fields.value_nicks and fd.get_style()==pango.STYLE_ITALIC: chunk=self.handle_italic(chunk) if 'weight' in fields.value_nicks and fd.get_weight()==pango.WEIGHT_BOLD: chunk=self.handle_bold(chunk) for att in atts: if att.type==pango.ATTR_UNDERLINE and att.value==pango.UNDERLINE_SINGLE: chunk=self.handle_underline(chunk) outtxt += chunk + trailing_newline more=ai.next() return outtxt
def get_layout(self, widget): '''Gets the Pango layout used in the cell in a TreeView widget.''' '''buf = RichBuffer.RichBuffer() plused_markup = Plus.msnplus(self.markup) view = gtk.TextView() view.set_buffer(buf) buf._put_formatted(plused_markup) return view''' layout = pango.Layout(widget.get_pango_context()) layout.set_width(-1) # Do not wrap text. if self.markup: try: decorated_markup = self.function(unicode(self.markup, 'utf-8')).encode('utf-8') except Exception, error: print "this nick: '%s' made the parser go crazy, striping" % (self.markup,) print error decorated_markup = Plus.msnplus_strip(self.markup) try: pango.parse_markup(decorated_markup) except gobject.GError: print "invalid pango markup:", decorated_markup log_strange_nick(decorated_markup, 'pango parser') decorated_markup = Plus.msnplus_strip(self.markup) layout.set_markup(decorated_markup)
def __check_markup(self, apply): try: f = AudioFile({"~filename":"dummy"}) pango.parse_markup(XMLFromPattern(self.text) % f, u"\u0000") except (ValueError, gobject.GError), e: qltk.ErrorMessage( self, _("Invalid pattern"), _("The pattern you entered was invalid. Make sure you enter " "< and > as \\< and \\> and that your tags are " "balanced.\n\n%s") % util.escape(str(e))).run() apply.stop_emission('clicked')
def set_text (self, txt): gtk.TextBuffer.set_text(self,"") try: self.parsed,self.txt,self.separator = pango.parse_markup(txt,u'\x00') except: # debug('Escaping text, we seem to have a problem here!') txt=xml.sax.saxutils.escape(txt) self.parsed,self.txt,self.separator = pango.parse_markup(txt,u'\x00') self.attrIter = self.parsed.get_iterator() self.add_iter_to_buffer() while self.attrIter.next(): self.add_iter_to_buffer()
def set_text (self, txt): gtk.TextBuffer.set_text(self,"") try: self.parsed,self.txt,self.separator = pango.parse_markup(txt,u'\x00') except: debug.deprint('Escaping text, we seem to have a problem here!', 2) txt=xml.sax.saxutils.escape(txt) self.parsed,self.txt,self.separator = pango.parse_markup(txt,u'\x00') self.attrIter = self.parsed.get_iterator() self.add_iter_to_buffer() while self.attrIter.next(): self.add_iter_to_buffer()
def set_text (self, txt): gtk.TextBuffer.set_text(self,"") try: self.parsed,self.txt,self.separator = pango.parse_markup(txt,u'\x00') except: print 'Problem encountered escaping text: "%s"'%txt import traceback; traceback.print_exc() txt=xml.sax.saxutils.escape(txt) self.parsed,self.txt,self.separator = pango.parse_markup(txt,u'\x00') self.attrIter = self.parsed.get_iterator() self.add_iter_to_buffer() while self.attrIter.next(): self.add_iter_to_buffer()
def run_scrolled_dialog(text, title=None): """Run a dialog intended for the display of a large amount of text.""" parent_window = get_dialog_parent() window = gtk.Window() window.set_transient_for(parent_window) window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG) window.set_border_width(DIALOG_SUB_PADDING) window.set_default_size(*DIALOG_SIZE_SCROLLED_MIN) if title is not None: window.set_title(title) scrolled = gtk.ScrolledWindow() scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) scrolled.show() label = gtk.Label() try: pango.parse_markup(text) except glib.GError: label.set_text(text) else: label.set_markup(text) label.show() filler_eb = gtk.EventBox() filler_eb.show() label_box = gtk.VBox() label_box.pack_start(label, expand=False, fill=False) label_box.pack_start(filler_eb, expand=True, fill=True) label_box.show() width, height = label.size_request() max_width, max_height = DIALOG_SIZE_SCROLLED_MAX width = min([max_width, width]) + 2 * DIALOG_PADDING height = min([max_height, height]) + 2 * DIALOG_PADDING scrolled.add_with_viewport(label_box) scrolled.get_child().set_shadow_type(gtk.SHADOW_NONE) scrolled.set_size_request(width, height) button = gtk.Button(stock=gtk.STOCK_OK) button.connect("clicked", lambda b: window.destroy()) button.show() button.grab_focus() button_box = gtk.HBox() button_box.pack_end(button, expand=False, fill=False) button_box.show() main_vbox = gtk.VBox(spacing=DIALOG_SUB_PADDING) main_vbox.pack_start(scrolled, expand=True, fill=True) main_vbox.pack_end(button_box, expand=False, fill=False) main_vbox.show() window.add(main_vbox) window.show() label.set_selectable(True) return False
def cairo_text_bbox(text, font_params, spacing=0, scale=1.0): surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8) ctx = cairo.Context(surf) # The scaling must match the final context. # If not there can be a mismatch between the computed extents here # and those generated for the final render. ctx.scale(scale, scale) font = cairo_font(font_params) if use_pygobject: status, attrs, plain_text, _ = pango.parse_markup(text, len(text), '\0') layout = pangocairo.create_layout(ctx) pctx = layout.get_context() fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL) pangocairo.context_set_font_options(pctx, fo) layout.set_font_description(font) layout.set_spacing(spacing * pango.SCALE) layout.set_text(plain_text, len(plain_text)) layout.set_attributes(attrs) li = layout.get_iter() # Get first line of text baseline = li.get_baseline() / pango.SCALE re = layout.get_pixel_extents()[1] # Get logical extents extents = (re.x, re.y, re.x + re.width, re.y + re.height) else: # pyGtk attrs, plain_text, _ = pango.parse_markup(text) pctx = pangocairo.CairoContext(ctx) pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pctx.create_layout() layout.set_font_description(font) layout.set_spacing(spacing * pango.SCALE) layout.set_text(plain_text) layout.set_attributes(attrs) li = layout.get_iter() # Get first line of text baseline = li.get_baseline() / pango.SCALE #print('@@ EXTENTS:', layout.get_pixel_extents()[1], spacing) extents = layout.get_pixel_extents()[1] # Get logical extents return [extents[0], extents[1], extents[2], extents[3], baseline]
def set_text (self, txt): buf = self.tv.get_buffer() # txt = re.sub('<p align[^>]*>', '<p>', txt) try: txt = txt.replace('strike','s') alignres = txt.find("LEFT") if alignres != -1: self.tv.set_justification(gtk.JUSTIFY_LEFT) txt = txt.replace('<pre><p align="LEFT" leading="21">','') alignres = txt.find("RIGHT") if alignres != -1: self.tv.set_justification(gtk.JUSTIFY_RIGHT) txt = txt.replace('<pre><p align="RIGHT" leading="21">','') alignres = txt.find("CENTER") if alignres != -1: self.tv.set_justification(gtk.JUSTIFY_CENTER) txt = txt.replace('<pre><p align="CENTER" leading="21">','') alignres = txt.find("JUSTIFY") if alignres != -1: self.tv.set_justification(gtk.JUSTIFY_FILL) txt = txt.replace('<pre><p align="JUSTIFY" leading="21">','') alignres = txt.find("LEFT") txt = txt.replace('</p></pre>','') parsed, txt, separator = pango.parse_markup(txt) except Exception ,e: pass
def convertMarkup(string): ''' Parses the string and returns a MarkupProps instance ''' attr_values = ('value', 'ink_rect', 'logical_rect', 'desc', 'color') attr_list, text, accel = pango.parse_markup( string ) attr_iter = attr_list.get_iterator() props = MarkupProps() props.text = text val = True while val: attrs = attr_iter.get_attrs() for attr in attrs: name = attr.type start = attr.start_index end = attr.end_index name = pango.AttrType(name).value_nick value = None for attr_value in attr_values: if hasattr( attr, attr_value ): value = getattr( attr, attr_value ) break if name == 'font_desc': name = 'font' props.add( name, value, start, end ) val = attr_iter.next() return props
def setup_widget_from_pango (self, widg, markupstring): """setup widget from a pango markup string""" #font = pango.FontDescription(fontstring) a,t,s = pango.parse_markup(markupstring,u'\x00') ai=a.get_iterator() font,lang,attrs=ai.get_font() return self.setup_widget(widg,font,attrs)
def write_text(self, ctx, text, box_width=None, size=10, fill_color=(0.0, 0.0, 0.0), alignment=None): if HAS_PANGOCAIRO_MODULE: (attr, t, accel) = pango.parse_markup(text) pctx = pangocairo.CairoContext(ctx) l = pctx.create_layout() l.set_attributes(attr) fd = pango.FontDescription("%s %d" % (self.font_name, size)) l.set_font_description(fd) if box_width: l.set_width(int(box_width * pango.SCALE)) if alignment: l.set_alignment(alignment) pctx.update_layout(l) l.set_text(t) pctx.set_source_rgb(*fill_color) pctx.show_layout(l) return l.get_pixel_extents()[0] else: ctx.rel_move_to(0, size) ctx.select_font_face(self.font_name, cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) ctx.set_font_size(size) ctx.show_text(text) ctx.rel_move_to(0, size) return (0, 0, len(text) * size, size)
def set_text(self, txt): gtk.TextBuffer.set_text(self, "") try: self.parsed, self.txt, self.separator = pango.parse_markup( txt, u'\x00') except: print 'Problem encountered escaping text: "%s"' % txt import traceback traceback.print_exc() txt = xml.sax.saxutils.escape(txt) self.parsed, self.txt, self.separator = pango.parse_markup( txt, u'\x00') self.attrIter = self.parsed.get_iterator() self.add_iter_to_buffer() while self.attrIter.next(): self.add_iter_to_buffer()
def setup_widget_from_pango(self, widg, markupstring): """setup widget from a pango markup string""" # font = pango.FontDescription(fontstring) a, t, s = pango.parse_markup(markupstring, u"\x00") ai = a.get_iterator() font, lang, attrs = ai.get_font() return self.setup_widget(widg, font, attrs)
def regenerate_menu(self): """ Builds the menu, with submenu if appropriate """ for marker in self._markers: label = self._parent.get_label(marker) if label is None: continue markup_data = pango.parse_markup(label) label_item = gtk.MenuItem(markup_data[1]) self.append(label_item) if len(self._markers) > 1: item_menu = gtk.Menu() label_item.set_submenu(item_menu) else: item_menu = self label_item.set_sensitive(False) self.append(gtk.SeparatorMenuItem()) context = { 'current-marker': marker, 'selected-markers': self._markers, 'current-position': self._position } for item in self._items: i = item.factory(self, self._parent, context) item_menu.append(i) self.show_all()
def setTitle(self, newtitle): """Replace characters that cannot be used for the filename \ in a FAT32 filesystem. Incomplete""" if not isinstance(newtitle, str): raise TypeError("Argument must be a string") has_pango = False try: import pango, gobject has_pango = True except ImportError: has_pango = False if has_pango: # parse_markup fails on unescaped markup. Common scenario would be unescaped ampersand. # It is bad practices but ignore an exception if raised. try: newtitle = pango.parse_markup(newtitle)[1] except gobject.GError: pass newtitle = newtitle.replace('"', '') newtitle = newtitle.replace('/', ' ') newtitle = newtitle.replace('\\', ' ') newtitle = newtitle.replace('|', '') newtitle = newtitle.replace('?', '') newtitle = newtitle.replace(':', '') self.title = newtitle
def setTitle (self, newtitle): """Replace characters that cannot be used for the filename \ in a FAT32 filesystem. Incomplete""" if not isinstance (newtitle, str): raise TypeError ("Argument must be a string") has_pango = False try: import pango, gobject has_pango = True except ImportError: has_pango = False if has_pango: # parse_markup fails on unescaped markup. Common scenario would be unescaped ampersand. # It is bad practices but ignore an exception if raised. try: newtitle = pango.parse_markup (newtitle)[1] except gobject.GError: pass newtitle = newtitle.replace ('"', '') newtitle = newtitle.replace ('/', ' ') newtitle = newtitle.replace ('\\', ' ') newtitle = newtitle.replace ('|', '') newtitle = newtitle.replace ('?', '') newtitle = newtitle.replace (':', '') self.title = newtitle
def onCopyActivate(self, treeview, path): it = treeview.get_model().get_iter(path) markupText = treeview.get_model().get_value(it, 0) plainText = pango.parse_markup(markupText, u'\x00')[1] clipboard = gtk.clipboard_get() clipboard.set_text(plainText) clipboard.store()
def run_choices_dialog(text, choices, title=None): """Run a dialog for choosing between a set of options.""" parent_window = get_dialog_parent() dialog = gtk.Dialog(title, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT), parent=parent_window) dialog.set_border_width(DIALOG_SUB_PADDING) label = gtk.Label() try: pango.parse_markup(text) except glib.GError: label.set_text(text) else: label.set_markup(text) dialog.vbox.set_spacing(DIALOG_SUB_PADDING) dialog.vbox.pack_start(label, expand=False, fill=False) if len(choices) < 5: for i, choice in enumerate(choices): group = None if i > 0: group = radio_button if i == 1: radio_button.set_active(True) radio_button = gtk.RadioButton(group, label=choice, use_underline=False) dialog.vbox.pack_start(radio_button, expand=False, fill=False) getter = (lambda: [ b.get_label() for b in radio_button.get_group() if b.get_active() ].pop()) else: combo_box = gtk.combo_box_new_text() for choice in choices: combo_box.append_text(choice) combo_box.set_active(0) dialog.vbox.pack_start(combo_box, expand=False, fill=False) getter = lambda: choices[combo_box.get_active()] dialog.show_all() response = dialog.run() if response == gtk.RESPONSE_ACCEPT: choice = getter() dialog.destroy() return choice dialog.destroy() return None
def onPopupMenuItemActivate (self, treeview, path): it = treeview.get_model().get_iter(path) markupText = treeview.get_model().get_value(it, 0) plainText = pango.parse_markup(markupText, u'\x00')[1] clipboard = gtk.clipboard_get() clipboard.set_text(plainText) clipboard.store()
def run_choices_dialog(text, choices, title=None): """Run a dialog for choosing between a set of options.""" parent_window = get_dialog_parent() dialog = gtk.Dialog(title, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT), parent=parent_window) dialog.set_border_width(DIALOG_SUB_PADDING) label = gtk.Label() try: pango.parse_markup(text) except glib.GError: label.set_text(text) else: label.set_markup(text) dialog.vbox.set_spacing(DIALOG_SUB_PADDING) dialog.vbox.pack_start(label, expand=False, fill=False) if len(choices) < 5: for i, choice in enumerate(choices): group = None if i > 0: group = radio_button if i == 1: radio_button.set_active(True) radio_button = gtk.RadioButton(group, label=choice, use_underline=False) dialog.vbox.pack_start(radio_button, expand=False, fill=False) getter = (lambda: [b.get_label() for b in radio_button.get_group() if b.get_active()].pop()) else: combo_box = gtk.combo_box_new_text() for choice in choices: combo_box.append_text(choice) combo_box.set_active(0) dialog.vbox.pack_start(combo_box, expand=False, fill=False) getter = lambda: choices[combo_box.get_active()] dialog.show_all() response = dialog.run() if response == gtk.RESPONSE_ACCEPT: choice = getter() dialog.destroy() return choice dialog.destroy() return None
def draw_label(self): """ Draw the label based on its attributes """ if self._sprites is None: return my_width = self.rect.width - self._margins[0] - self._margins[2] if my_width < 0: my_width = 0 my_height = self.rect.height - self._margins[1] - self._margins[3] for k in range(len(self.labels)): label_segments = self.labels[k].split('\n') for i in range(len(label_segments)): pl = self._sprites.canvas.create_pango_layout.set_markup_with_accel( pango.parse_markup('<b><i>' + str(label_segments[i]) + '</i></b>', accel_marker=u'\x00')) self._fd.set_size(int(self._scale[k] * pango.SCALE)) pl.set_font_description(self._fd) w = pl.get_size()[0] / pango.SCALE if w > my_width: if self._rescale[k]: self._fd.set_size( int(self._scale[k] * pango.SCALE * my_width / w)) pl.set_font_description(self._fd) w = pl.get_size()[0] / pango.SCALE else: j = len(self.labels[k]) - 1 while (w > my_width and j > 0): pl = self._sprites.canvas.create_pango_layout( "…" + self.labels[k][len(self.labels[k]) - j:]) self._fd.set_size(int(self._scale[i] * pango.SCALE)) pl.set_font_description(self._fd) w = pl.get_size()[0] / pango.SCALE j -= 1 if self._horiz_align[k] == "center": x = int(self.rect.x + self._margins[0] + (my_width - w) / 2) elif self._horiz_align[k] == 'left': x = int(self.rect.x + self._margins[0]) else: # right x = int(self.rect.x + self.rect.width - \ w - self._margins[2]) h = pl.get_size()[1] / pango.SCALE if self._vert_align[k] == "middle": # yoff = int(len(label_segments) * h / 2.) yoff = 0 y = int(self.rect.y + self._margins[1] + \ (my_height - h) / 2 - yoff + i * h) elif self._vert_align[k] == "top": y = int(self.rect.y + self._margins[1] + i * h) else: # bottom yoff = int(len(label_segments) * h) y = int(self.rect.y + self.rect.height - \ h - self._margins[3] - yoff + i * h) self._sprites.gc.set_foreground(self._color) self._sprites.area.draw_layout(self._sprites.gc, x, y, pl)
def layer_name_datafunc(self, column, renderer, model, tree_iter, *data_etc): layer = model.get_value(tree_iter, 0) path = model.get_path(tree_iter) name = layer.name attrs = pango.AttrList() if not name: layer_num = self.app.doc.get_number_for_nameless_layer(layer) name = _(u"Untitled layer #%d") % layer_num markup = "<small><i>%s</i></small> " % (escape(name),) if pygtkcompat.USE_GTK3: parse_result = pango.parse_markup(markup, -1, '\000') parse_ok, attrs, name, accel_char = parse_result assert parse_ok else: parse_result = pango.parse_markup(markup) attrs, name, accel_char = parse_result renderer.set_property("attributes", attrs) renderer.set_property("text", name)
def layer_name_datafunc(self, column, renderer, model, tree_iter, *data_etc): layer = model.get_value(tree_iter, 0) path = model.get_path(tree_iter) name = layer.name attrs = pango.AttrList() if not name: layer_num = self.app.doc.get_number_for_nameless_layer(layer) name = _(u"Untitled layer #%d") % layer_num markup = "<small><i>%s</i></small> " % (escape(name), ) if gtk2compat.USE_GTK3: parse_result = pango.parse_markup(markup, -1, '\000') parse_ok, attrs, name, accel_char = parse_result assert parse_ok else: parse_result = pango.parse_markup(markup) attrs, name, accel_char = parse_result renderer.set_property("attributes", attrs) renderer.set_property("text", name)
def show_notification(self, msg, title=_("<span size=\"medium\">" "<b>Information</b></span>"), stock=gtk.STOCK_DIALOG_INFO, fname=None, \ timeout=5000): """ Show a notification message by using libnotify or HIGTooltip class @param msg The text message of the notification @param title The title of the notification @param stock The stock image to use @param fname The image filename with full path to be used as image instead the stock image @param timeout Time to live of the notification expressed in msecs. (pass None for persistent notification) """ if self.type == TrayPlugin.TYPE_WINDOWS: if self.icon.notify_icon: title = pango.parse_markup(title)[1] msg = pango.parse_markup(msg)[1] self.icon.notify_icon.show_balloon(title, msg, (timeout is None) and (0) or (timeout), stock) elif self.type == TrayPlugin.TYPE_HIGTOOLTIP: rect = self.icon.get_geometry() if rect is not None: rect = rect[1] else: return data = HIGTooltipData(msg, title, stock, fname) self.notifier.show_at(self.icon, data, rect.x, rect.y, timeout) else: title = pango.parse_markup(title)[1] notify = self.notifier(title, msg, \ (fname is None) and (stock) or (None)) if fname: pixbuf = gtk.gdk.pixbuf_new_from_file(fname) notify.set_icon_from_pixbuf(pixbuf) if timeout: notify.set_timeout(timeout) notify.show()
def _update_base(self, elements_list=None): if elements_list is None: elements_list = [''] self._smilies = {} self._base_attrlist = pango.AttrList() text = '' if isinstance(elements_list, basestring): elements_list = [elements_list] for element in elements_list: if isinstance(element, basestring): try: attrl, ptxt, unused = pango.parse_markup(element, u'\x00') except: attrl, ptxt = pango.AttrList(), element #append attribute list shift = len(text) itter = attrl.get_iterator() while True: attrs = itter.get_attrs() for attr in attrs: attr.end_index += shift attr.start_index += shift self._base_attrlist.insert(attr) if not itter.next(): break text += ptxt elif isinstance(element, gtk.gdk.Pixbuf): self._smilies[len(text)] = element text += '_' pango.Layout.set_text(self, text) if hasattr(pango, 'find_base_dir'): for line in text.splitlines(): if (pango.find_base_dir(line, -1) == pango.DIRECTION_RTL): self._is_rtl = True break else: self._is_rtl = False logical = self.get_line(0).get_pixel_extents()[1] ascent = pango.ASCENT(logical) decent = pango.DESCENT(logical) self._text_height = ascent + decent self._base_to_center = (self._text_height // 2) - decent self._update_smilies()
def _update_base(self, elements_list=None): if elements_list is None: elements_list = [''] self._smilies = {} self._base_attrlist = pango.AttrList() text = '' if type(elements_list) in (str, unicode): elements_list = [elements_list] for element in elements_list: if type(element) in (str, unicode): try: attrl, ptxt, unused = pango.parse_markup(element, u'\x00') except: attrl, ptxt = pango.AttrList(), element #append attribute list shift = len(text) itter = attrl.get_iterator() while True: attrs = itter.get_attrs() for attr in attrs: attr.end_index += shift attr.start_index += shift self._base_attrlist.insert(attr) if not itter.next(): break text += ptxt elif type(element) == gtk.gdk.Pixbuf: self._smilies[len(text)] = element text += '_' pango.Layout.set_text(self, text) if hasattr(pango, 'find_base_dir'): for line in text.splitlines(): if (pango.find_base_dir(line, -1) == pango.DIRECTION_RTL): self._is_rtl = True break else: self._is_rtl = False logical = self.get_line(0).get_pixel_extents()[1] ascent = pango.ASCENT(logical) decent = pango.DESCENT(logical) self._text_height = ascent + decent self._base_to_center = (self._text_height // 2) - decent self._update_smilies()
def parse(self): attr_list, text, accel = pango.parse_markup(self.markup) minIndex = 0 maxIndex = 0 out = "<flowRoot " out += ' xml:space="preserve"' out += ' style="' out += 'letter-spacing:' + str(self.container_letter_spacing) + ";" out += "font-style:" + str( self.pango_style[self.container_font.get_style()]) + ";" out += "font-weight:" + str( self.pango_weight[self.container_font.get_weight()]) + ";" out += "font-variant:" + str( self.pango_variant[self.container_font.get_variant()]) + ";" out += "font-family:'" + self.container_font.get_family() + "';" out += "font-stretch:" + str( self.pango_stretch[self.container_font.get_stretch()]) + ";" out += "-inkscape-font-specification:'" + str( self.container_font) + "';" out += "font-size:" + str(math.ceil(self.container_font_size)) + "px;" out += "fill:rgb(" + str(self.container_color[0]) + "," + str( self.container_color[1]) + "," + str( self.container_color[2]) + ");" out += "fill-opacity:" + str(self.container_color[3] / 255.0) + ";" out += '"' out += ' direction="' + self.container_direction + '"' out += ' x="' + str(self.container_offset_X) + '"' out += ' y="' + str(self.container_offset_Y) + '"' out += '>' out += '<flowRegion>' out += '<rect' out += ' width="' + str(self.container_width - self.container_indent) + '"' out += ' height="' + str(self.container_height + self.getTopExents(attr_list, text)) + '"' out += ' x="' + str(self.container_offset_X + self.container_indent) + '"' out += ' y="' + str(self.container_offset_Y) + '"' out += ' />' out += '</flowRegion>' outText = text data = self.toSvg(attr_list, text) data.sort(key=lambda x: x[0]) gap = 0 for el in data: if el[1] != "</flowPara>" and el[1] != "</flowSpan>": el[1] = el[1].replace( "flowPara", 'flowPara id="' + str(self.counter) + '"') outText = outText[:el[0] + gap] + el[1] + outText[el[0] + gap:] gap += len(el[1]) self.counter += 1 return out + outText.replace('style=""', '').replace( "\n", "") + "</flowRoot>"
def __preview_pattern(self, edit, label): people = "\n".join( [util.tag("artist"), util.tag("performer"), util.tag("arranger")]) album = FakeAlbum({"date": "2004-10-31", "~length": util.format_time(6319), "~long-length": util.format_time_long(6319), "~tracks": ngettext("%d track", "%d tracks", 5) % 5, "~discs": ngettext("%d disc", "%d discs", 2) % 2, "~people": people}) try: text = XMLFromPattern(edit.text) % album except: text = _("Invalid pattern") edit.apply.set_sensitive(False) try: pango.parse_markup(text, u"\u0000") except gobject.GError: text = _("Invalid pattern") edit.apply.set_sensitive(False) else: edit.apply.set_sensitive(True) label.set_markup(text)
def get_hyperlink_label(text, search_func=lambda i: False): """Return a label with clickable hyperlinks.""" label = gtk.Label() label.show() try: pango.parse_markup(text) except glib.GError: label.set_text(text) else: try: label.connect("activate-link", lambda l, u: handle_link(u, search_func)) except TypeError: # No such signal before PyGTK 2.18 label.connect("button-release-event", lambda l, e: extract_link(l, search_func)) text = REC_HYPERLINK_ID_OR_URL.sub(MARKUP_URL_UNDERLINE, text) label.set_markup(text) else: text = REC_HYPERLINK_ID_OR_URL.sub(MARKUP_URL_HTML, text) label.set_markup(text) return label
def _set_slide_row_text(self, column, cell, model, titer): "Returns the title of the current presentation." rend = model.get_value(titer, 0) if isinstance(rend, theme.Text): text = pango.parse_markup(rend.markup)[1] cell.set_property('text', "Text: %s" % re.sub('\s+',' ',text)) elif isinstance(rend, theme.Image): if rend.src: text = os.path.split(rend.src)[1] else: text = "(No File Set)" cell.set_property('text', "Image: %s" % text)
def on_draw(self, ctx, width, height, timestamp, deltaT): if not self.IsVisible: return msg = self.Message.Text #update text string with current time if time markup found #for example "%{%a, %d %b %Y %H:%M:%S}%" def ReplaceMarkupTagWithDate(match): datestring = match.group(1).strip() #print 'datestring ' + datestring return strftime(datestring, gmtime()) #regex_with_arg = re.compile(r"\%{(.*?)\}%") msg = re.sub(r"\%{(.*?)\}%", ReplaceMarkupTagWithDate, msg) #distance = speed * time = pixels/second * dt delta_x = self.Movement*deltaT current_x = width-self.Message.DistanceMoved if not self.ScrollLeft: current_x = self.Message.DistanceMoved-msg_width pangoCtx = pangocairo.CairoContext(ctx) msglayout = pangoCtx.create_layout() msglayout.set_alignment(pango.ALIGN_RIGHT) msglayout.set_wrap(pango.WRAP_WORD_CHAR) msglayout.set_font_description(pango.FontDescription("Arial 24")) msgattrs, msgtext, msgaccel = pango.parse_markup(msg) msglayout.set_attributes(msgattrs) msglayout.set_text(msgtext) pangoCtx.update_layout(msglayout) [ink_rect, logical_rect] = msglayout.get_pixel_extents() msg_width = logical_rect[2] msg_height = logical_rect[3] self.Message.DistanceMoved += delta_x if self.Message.DistanceMoved>msg_width+width: self.Message.DistanceMoved=0 #draw a shaded background for messages to traverse (if there are any messages ) if self.Shading.IsVisible: self.Shading.X=0 self.Shading.Y=self.Y #+ybearing self.Shading.W=width self.Shading.H=msg_height self.Shading.Draw(ctx, width, height, timestamp, deltaT) #ctx.move_to( nick_ul_x+1,nick_ul_y+2 ) #ctx.set_source_rgb(0,0,0) #pangoCtx.show_layout(nicklayout) ctx.move_to( current_x, self.Y) ctx.set_source_rgb(1,1,1) pangoCtx.show_layout(msglayout)
def get_layout(self, widget): '''Gets the Pango layout used in the cell in a TreeView widget.''' layout = SmileyLayout(widget.create_pango_context(), self.function(unicode(self.markup, 'utf-8'))) if self.markup: try: decorated_markup = self.function(unicode(self.markup, 'utf-8')) except Exception, error: print "this nick: '%s' made the parser go crazy, striping" % \ (self.markup,) print error decorated_markup = Plus.msnplus_strip(self.markup) try: pango.parse_markup( self.function(unicode(self.markup, 'utf-8'), False)) except gobject.GError: print "invalid pango markup:", decorated_markup decorated_markup = Plus.msnplus_strip(self.markup) layout.set_text(decorated_markup)
def run_dialog(dialog_type, text, title=None, modal=True): """Run a simple dialog with an 'OK' button and some text.""" parent_window = get_dialog_parent() dialog = gtk.MessageDialog(type=dialog_type, buttons=gtk.BUTTONS_OK, parent=parent_window) try: pango.parse_markup(text) except glib.GError: try: dialog.set_markup(safe_str(text)) except: dialog.format_secondary_text(text) else: dialog.set_markup(text) if "\n" in text: dialog.label.set_line_wrap(False) dialog.set_resizable(True) dialog.set_modal(modal) if title is not None: dialog.set_title(title) dialog.run() dialog.destroy()
def draw_text(x, y, text, font, text_color, spacing, c): c.save() c.set_source_rgba(*rgb_to_cairo(text_color)) font = cairo_font(font) c.translate(x, y) if use_pygobject: status, attrs, plain_text, _ = pango.parse_markup( text, len(text), '\0') layout = pangocairo.create_layout(c) pctx = layout.get_context() fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL) pangocairo.context_set_font_options(pctx, fo) layout.set_font_description(font) layout.set_spacing(spacing * pango.SCALE) layout.set_text(plain_text, len(plain_text)) layout.set_attributes(attrs) pangocairo.update_layout(c, layout) pangocairo.show_layout(c, layout) else: # pyGtk attrs, plain_text, _ = pango.parse_markup(text) pctx = pangocairo.CairoContext(c) pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pctx.create_layout() layout.set_font_description(font) layout.set_spacing(spacing * pango.SCALE) layout.set_text(plain_text) layout.set_attributes(attrs) pctx.update_layout(layout) pctx.show_layout(layout) c.restore()
def write_text(self, label, text): if not text: return self.add_paragraph(label, style=self.ss.ParagraphStyles.Heading2) pars = text.split("\n") # since we may have to deal with markup, we're going to handle this # on our own... for par in pars: p = PyRTF.Paragraph(self.ss.ParagraphStyles.Normal) # this code is partly copied from handle_markup in # exporter.py (a bit dumb, I know...) import pango, xml.sax.saxutils try: al, txt, sep = pango.parse_markup(par, u'\x00') except: al, txt, sep = pango.parse_markup(xml.sax.saxutils.escape(par), u'\x00') ai = al.get_iterator() more = True while more: fd, lang, atts = ai.get_font() chunk = xml.sax.saxutils.escape(txt.__getslice__(*ai.range())) fields = fd.get_set_fields() style_args = {'font': self.ss.Fonts.TimesNewRoman} if fields != 0: if 'style' in fields.value_nicks and fd.get_style( ) == pango.STYLE_ITALIC: style_args['italic'] = True if 'weight' in fields.value_nicks and fd.get_weight( ) == pango.WEIGHT_BOLD: style_args['bold'] = True if filter( lambda att: att.type == pango.ATTR_UNDERLINE and att. value == pango.UNDERLINE_SINGLE, atts): style_args['underline'] = True p.append(PyRTF.Elements.TEXT(encode_text(chunk), **style_args)) more = ai.next() self.recsection.append(p)
def no_definition(suggestion, word): ''' returns a widget containing spelling suggestions ''' scroll = gtk.ScrolledWindow() scroll.set_size_request(500, 400) scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) string = '<span font_desc="Times New Roman Bold 24" foreground="#ff0000" f\ ont_family="Times New Roman"><span foreground="#000000">%s\n</span><i> No Defi\ nition Found</i></span><span font_desc="Times New Roman 16" font_family="Times\ New Roman">\n\nMay be you\'re searching for\n</span>' % (word) (attr, text, unused) = pango.parse_markup(string, accel_marker = u'\x00') label = gtk.Label() label.set_attributes(attr) label.set_text(text) label.set_justify(gtk.JUSTIFY_CENTER) v_box = gtk.VBox() v_box.pack_start(label) link = gtk.LinkButton('') link.set_label(suggestion[0].lower()) link.connect('clicked', linked, link.get_label().lower()) link.set_tooltip_text('click to search') del suggestion[0] alignment = gtk.Alignment(0.5, 0.5, 0, 0) alignment.add(link) v_box.pack_start(alignment) label = gtk.Label() label.set_text('\n') v_box.pack_start(label) while suggestion: end = len(suggestion) >= 5 and 5 or len(suggestion) h_box = gtk.HBox(8) for text in suggestion[:end]: link = gtk.LinkButton('') link.set_label(text.lower()) link.connect('clicked', linked, link.get_label().lower()) link.set_tooltip_text('click to search') alignment = gtk.Alignment(0.0, 0.5, 0, 0) alignment.add(link) h_box.pack_start(alignment) del suggestion[:end] alignment = gtk.Alignment(0.0, 0.0, 1, 0) alignment.add(h_box) v_box.pack_start(alignment) scroll.add_with_viewport(v_box) scroll.get_child().modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ffffff')) return scroll
def no_definition(suggestion, word): ''' returns a widget containing spelling suggestions ''' scroll = gtk.ScrolledWindow() scroll.set_size_request(500, 400) scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) string = '<span font_desc="Times New Roman Bold 24" foreground="#ff0000" f\ ont_family="Times New Roman"><span foreground="#000000">%s\n</span><i> No Defi\ nition Found</i></span><span font_desc="Times New Roman 16" font_family="Times\ New Roman">\n\nMay be you\'re searching for\n</span>' % (word) (attr, text, unused) = pango.parse_markup(string, accel_marker=u'\x00') label = gtk.Label() label.set_attributes(attr) label.set_text(text) label.set_justify(gtk.JUSTIFY_CENTER) v_box = gtk.VBox() v_box.pack_start(label) link = gtk.LinkButton('') link.set_label(suggestion[0].lower()) link.connect('clicked', linked, link.get_label().lower()) link.set_tooltip_text('click to search') del suggestion[0] alignment = gtk.Alignment(0.5, 0.5, 0, 0) alignment.add(link) v_box.pack_start(alignment) label = gtk.Label() label.set_text('\n') v_box.pack_start(label) while suggestion: end = len(suggestion) >= 5 and 5 or len(suggestion) h_box = gtk.HBox(8) for text in suggestion[:end]: link = gtk.LinkButton('') link.set_label(text.lower()) link.connect('clicked', linked, link.get_label().lower()) link.set_tooltip_text('click to search') alignment = gtk.Alignment(0.0, 0.5, 0, 0) alignment.add(link) h_box.pack_start(alignment) del suggestion[:end] alignment = gtk.Alignment(0.0, 0.0, 1, 0) alignment.add(h_box) v_box.pack_start(alignment) scroll.add_with_viewport(v_box) scroll.get_child().modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ffffff')) return scroll
def write_text (self, label, text): if not text: return self.add_paragraph(label, style=self.ss.ParagraphStyles.Heading2) pars=text.split("\n") # since we may have to deal with markup, we're going to handle this # on our own... for par in pars: p = PyRTF.Paragraph(self.ss.ParagraphStyles.Normal) # this code is partly copied from handle_markup in # exporter.py (a bit dumb, I know...) import pango, xml.sax.saxutils try: al,txt,sep = pango.parse_markup(par,u'\x00') except: al,txt,sep = pango.parse_markup(xml.sax.saxutils.escape(par),u'\x00') ai = al.get_iterator() more = True while more: fd,lang,atts=ai.get_font() chunk=xml.sax.saxutils.escape(txt.__getslice__(*ai.range())) fields=fd.get_set_fields() style_args = {'font':self.ss.Fonts.TimesNewRoman} if fields != 0: if 'style' in fields.value_nicks and fd.get_style()==pango.STYLE_ITALIC: style_args['italic']=True if 'weight' in fields.value_nicks and fd.get_weight()==pango.WEIGHT_BOLD: style_args['bold']=True if filter(lambda att: att.type==pango.ATTR_UNDERLINE and att.value==pango.UNDERLINE_SINGLE, atts): style_args['underline']=True p.append( PyRTF.Elements.TEXT(encode_text(chunk), **style_args) ) more = ai.next() self.recsection.append(p)
def add_lines(self, line, use_markup=False): buf = self._text.get_buffer() if not buf.get_start_iter().equal(buf.get_end_iter()): line = "\n" + line if not use_markup: buf.insert(buf.get_end_iter(), line) return try: ret = pango.parse_markup(line) except Exception, e: print 'Could not parse markup:', e buf.insert(buf.get_end_iter(), line) return
def __reminders_treeview_selection_changed(self, selection): (reminders_model, reminders_iter) = selection.get_selected() if reminders_iter: self.remove_reminder_button.set_sensitive(True) reminder = reminders_model.get_value(reminders_iter, 0) self.program_entry.set_text(reminder.program) channel = pango.parse_markup(reminder.channel, u"\x00")[1] self.channels_comboboxentry.child.set_text(channel) self.notify_spinbutton.set_value(reminder.notify_time) else: self.program_entry.set_text("") self.channels_comboboxentry.child.set_text("") self.notify_spinbutton.set_value(5) self.add_reminder_button.set_sensitive(False) self.update_reminder_button.set_sensitive(False) self.remove_reminder_button.set_sensitive(False)
def on_label_change(self, markup): attr, text, _ = pango.parse_markup(markup) self.override_font_attributes(attr, text) self.label.set_text(text) self.label.set_attributes(attr) if not self.get_property('visible'): self.show() if self.timer_hide: self.timer_hide.cancel() if self.options.timeout > 0: self.timer_hide = Timer(self.options.timeout, self.on_timeout_main) self.timer_hide.start() if self.timer_min: self.timer_min.cancel() self.timer_min = Timer(self.options.recent_thr * 2, self.on_timeout_min) self.timer_min.start()
def Push(self, message): """ Insert a new message into the messages stack. Parameters: message -- string containing the new message to be added to the StatusBar. Return: the value of the next valid message ID. """ if not self.label: pango_attr_list, text_without_markup, accel_char = pango.parse_markup(message) message = text_without_markup message_id = self.push(0, message) if self.label: self.label.set_use_markup(True) return message_id
def on_draw(self, ctx, width, height, timestamp, deltaT): ul_x = self.X ul_y = self.Y for msg in self.Messages: #update text string with current time if time markup found #for example "%{%a, %d %b %Y %H:%M:%S}%" def ReplaceMarkupTagWithDate(match): datestring = match.group(1).strip() #print 'datestring ' + datestring return strftime(datestring, gmtime()) #regex_with_arg = re.compile(r"\%{(.*?)\}%") msg = re.sub(r"\%{(.*?)\}%", ReplaceMarkupTagWithDate, msg) pangoCtx = pangocairo.CairoContext(ctx) msglayout = pangoCtx.create_layout() msglayout.set_width(pango.SCALE * self.W) msglayout.set_alignment(pango.ALIGN_LEFT) msglayout.set_wrap(pango.WRAP_WORD_CHAR) msglayout.set_font_description(pango.FontDescription("Arial 24")) msgattrs, msgtext, msgaccel = pango.parse_markup(msg) msglayout.set_attributes(msgattrs) msglayout.set_text(msgtext) pangoCtx.update_layout(msglayout) [ink_rect, logical_rect] = msglayout.get_pixel_extents() msg_width = logical_rect[2] msg_height = logical_rect[3] #draw a shaded background for messages to traverse (if there are any messages ) if self.Shading.IsVisible: self.Shading.X = ul_x self.Shading.Y = ul_y self.Shading.W = self.W self.Shading.H = msg_height self.Shading.Draw(ctx, width, height, timestamp, deltaT) #ctx.move_to( nick_ul_x+1,nick_ul_y+2 ) #ctx.set_source_rgb(0,0,0) #pangoCtx.show_layout(nicklayout) ctx.move_to(ul_x, ul_y) ctx.set_source_rgb(1, 1, 1) pangoCtx.show_layout(msglayout) ul_y += msg_height
def on_draw(self, ctx, width, height, timestamp, deltaT): ul_x = self.X ul_y = self.Y for msg in self.Messages: #update text string with current time if time markup found #for example "%{%a, %d %b %Y %H:%M:%S}%" def ReplaceMarkupTagWithDate(match): datestring = match.group(1).strip() #print 'datestring ' + datestring return strftime(datestring, gmtime()) #regex_with_arg = re.compile(r"\%{(.*?)\}%") msg = re.sub(r"\%{(.*?)\}%", ReplaceMarkupTagWithDate, msg) pangoCtx = pangocairo.CairoContext(ctx) msglayout = pangoCtx.create_layout() msglayout.set_width( pango.SCALE * self.W ) msglayout.set_alignment(pango.ALIGN_LEFT) msglayout.set_wrap(pango.WRAP_WORD_CHAR) msglayout.set_font_description(pango.FontDescription("Arial 24")) msgattrs, msgtext, msgaccel = pango.parse_markup(msg) msglayout.set_attributes(msgattrs) msglayout.set_text(msgtext) pangoCtx.update_layout(msglayout) [ink_rect, logical_rect] = msglayout.get_pixel_extents() msg_width = logical_rect[2] msg_height = logical_rect[3] #draw a shaded background for messages to traverse (if there are any messages ) if self.Shading.IsVisible: self.Shading.X=ul_x self.Shading.Y=ul_y self.Shading.W=self.W self.Shading.H=msg_height self.Shading.Draw(ctx, width, height, timestamp, deltaT) #ctx.move_to( nick_ul_x+1,nick_ul_y+2 ) #ctx.set_source_rgb(0,0,0) #pangoCtx.show_layout(nicklayout) ctx.move_to(ul_x, ul_y) ctx.set_source_rgb(1,1,1) pangoCtx.show_layout(msglayout) ul_y += msg_height
def resultSearchCb(model, column, key, it): """Callback function for searching in result list""" lineText = model.get_value(it, column) plainText = pango.parse_markup(lineText, u'\x00')[1] # remove Pango markup # for file names, add a leading slash before matching: parentIter = model.iter_parent(it) if parentIter == None and not (plainText.startswith("/")): plainText = "/" + plainText # if search text contains only lower-case characters, do case-insensitive matching: if key.islower(): plainText = plainText.lower() # if the line contains the search text, it matches: if plainText.find(key) >= 0: return False # line doesn't match: return True
def __init__(self, ctx, text, fmt): """ Parameters ---------- ctx : gtk.PrintContext fmt : TextFormat text : str text can be formatted with the Pango markup language, see https://developer.gnome.org/pango/stable/PangoMarkupFormat.html """ self.ctx = ctx self.fmt = fmt self.text = text font_descr = self.fmt.font_descr if not font_descr: font_descr = pango.FontDescription("{} {} {}".format( self.fmt.font, self.fmt.style, self.fmt.size)) self.layout = ctx.create_pango_layout() self.layout.set_font_description(font_descr) self.layout.set_alignment(self.fmt.align) self.layout.set_justify(self.fmt.justify) self.layout.set_spacing(self.fmt.line_spacing * pango.SCALE) self.layout.set_wrap(self.fmt.wrap) text = '<span foreground="{}">{}</span>'.format( self.fmt.color, self.text) if self.fmt.width: self.layout.set_width(int(self.fmt.width * pango.SCALE)) try: attrs, markup_text, accel = pango.parse_markup(text) self.layout.set_attributes(attrs) self.layout.set_text(markup_text) except Exception as e: raise RenderError("PANGO_MARKUP_PARSE_ERROR", e.args[0], gobject.markup_escape_text(self.text)) self.w = self.layout.get_pixel_size()[0] self.h = self.layout.get_pixel_size()[1] self.lines = self.layout.get_line_count()
def time_out(): ''' this function is called when network times out ''' scroll = gtk.ScrolledWindow() scroll.set_size_request(500, 400) scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) string = '<span font_desc="Times New Roman Bold 48" foreground="#ff0000" f\ ont_family="Times New Roman">Connection\nInterrupted</span>' (attr, text, unused) = pango.parse_markup(string, accel_marker=u'\x00') label = gtk.Label() label.set_attributes(attr) label.set_text(text) label.set_justify(gtk.JUSTIFY_CENTER) alignment = gtk.Alignment(0, 0, 1, 1) alignment.add(label) scroll.add_with_viewport(alignment) scroll.get_child().modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#ffffff')) return scroll
def __init__(self): super(PyApp, self).__init__() self.connect("destroy", gtk.main_quit) self.set_title("Pango Example") attributes, text, x = pango.parse_markup(quotes) label = gtk.Label(text) gtk.gdk.beep() fontdesc = pango.FontDescription("Serif bold 16") label.modify_font(fontdesc) gtk.Label.set_attributes(label, attributes) label.set_justify(gtk.JUSTIFY_CENTER) fix = gtk.Fixed() fix.put(label, 5, 5) self.add(fix) self.set_position(gtk.WIN_POS_CENTER) self.show_all()