def split_first_line(self): """Fit as much as possible in the available width for one line of text. Return ``(show_line, length, width, height, resume_at)``. ``show_line``: a closure that takes a cairo Context and draws the first line. ``length``: length in UTF-8 bytes of the first line ``width``: width in pixels of the first line ``height``: height in pixels of the first line ``baseline``: baseline in pixels of the first line ``resume_at``: The number of UTF-8 bytes to skip for the next line. May be ``None`` if the whole text fits in one line. This may be greater than ``length`` in case of preserved newline characters. """ lines = self.layout.get_lines_readonly() first_line = lines[0] length = first_line.length _ink_extents, logical_extents = first_line.get_extents() width = Pango.units_to_double(logical_extents.width) height = Pango.units_to_double(logical_extents.height) baseline = Pango.units_to_double(self.layout.get_baseline()) if len(lines) >= 2: resume_at = lines[1].start_index else: resume_at = None def show_line(context): """Draw the given ``line`` to the Cairo ``context``.""" PangoCairo.update_layout(context, self.layout) PangoCairo.show_layout_line(context, first_line) return show_line, length, width, height, baseline, resume_at
def __init__(self, text, style, context, width=None): self.layout = PangoCairo.create_layout(context) font = Pango.FontDescription() font.set_family(', '.join(style.font_family)) font.set_variant(PANGO_VARIANT[style.font_variant]) font.set_style(PANGO_STYLE[style.font_style]) font.set_absolute_size(Pango.units_from_double(style.font_size)) font.set_weight(style.font_weight) self.layout.set_font_description(font) self.layout.set_text(text, -1) self.layout.set_wrap(Pango.WrapMode.WORD) word_spacing = style.word_spacing letter_spacing = style.letter_spacing if letter_spacing == 'normal': letter_spacing = 0 if text and (word_spacing != 0 or letter_spacing != 0): word_spacing = Pango.units_from_double(word_spacing) letter_spacing = Pango.units_from_double(letter_spacing) markup = escape(text).replace( ' ', '<span letter_spacing="%i"> </span>' % ( word_spacing + letter_spacing,)) markup = '<span letter_spacing="%i">%s</span>' % ( letter_spacing , markup) attributes_list = Pango.parse_markup(markup, -1, '\x00')[1] self.layout.set_attributes(attributes_list) if width is not None: self.layout.set_width(Pango.units_from_double(width))
def sync_layout(self, size): """ Sync layout changes and calculate intrinsic size based on the parent's size. """ super(Text, self).sync_layout(size) width, height = self.size if self.__intrinsic_size_param == (width, height, self.text, self.font.name, self.font.size): self.intrinsic_size = self.__intrinsic_size_cache return self.__intrinsic_size_cache cr = create_cairo_context() layout = PangoCairo.create_layout(cr) layout.set_width(width * Pango.SCALE) layout.set_height(height * Pango.SCALE) layout.set_ellipsize(Pango.EllipsizeMode.END) layout.set_wrap(Pango.WrapMode.WORD_CHAR) layout.set_font_description(self.font.get_font_description()) layout.set_text(self.text, -1) PangoCairo.show_layout(cr, layout) self.__intrinsic_size_cache = \ int(min(width, Pango.units_to_double(layout.get_size()[0]))), \ int(min(height, Pango.units_to_double(layout.get_size()[1]))) self.__intrinsic_size_param = (width, height, self.text, self.font.name, self.font.size) self.intrinsic_size = self.__intrinsic_size_cache return self.__intrinsic_size_cache
def __check_markup(self, apply): try: f = AudioFile({"~filename": "dummy"}) Pango.parse_markup(XMLFromPattern(self.text) % f, -1, u"\u0000") except (ValueError, GLib.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, "") suc, self.parsed, self.txt, self.separator = Pango.parse_markup(txt, -1, u'\x00') if not suc: oldtxt = txt txt = saxutils.escape(txt) self.warn("Marked text is not correct. Escape %s to %s", oldtxt, txt) suc, self.parsed, self.txt, self.separator = Pango.parse_markup(txt, -1, u'\x00') self.attrIter = self.parsed.get_iterator() self.add_iter_to_buffer() while self.attrIter.next(): self.add_iter_to_buffer()
def canvas_draw(self, widget, cr): """ draw the word centered in the window. """ w, h = self.draw_size # center of the text cx, cy = w/2., h/2. # circle cr.set_line_width(9) cr.set_source_rgb(1.0, 1.0, 1.0) ctx = pangocairo.create_context(cr) layout = pango.Layout.new(ctx) prefixlayout = pango.Layout.new(ctx) desc = pango.font_description_from_string(self.font) for l in (layout, prefixlayout): l.set_font_description(desc) txt = self.current_word center = self.current_center if len(txt) > 0: markup = "%s<span foreground='red'>%s</span>%s" % tuple( t.replace("<", "<").replace(">", ">") for t in (txt[:center], txt[center], txt[center+1:])) prefix = txt[:center] else: markup = "" prefix = "" e, attr, txt, accel = pango.parse_markup(markup, -1, '\x00') layout.set_text(txt, -1) layout.set_attributes(attr) prefixlayout.set_text(prefix, -1) pangocairo.update_layout(cr, layout) pangocairo.update_layout(cr, prefixlayout) # text metrics _, txth = (x/1024. for x in layout.get_size()) prew, _ = (x/1024. for x in prefixlayout.get_size()) cr.move_to(cx - (prew), cy - txth/2) # render the text pangocairo.show_layout(cr, layout)
def __preview_pattern(self, edit, label): try: text = XMLFromMarkupPattern(edit.text) % self._EXAMPLE_ALBUM except: text = _("Invalid pattern") edit.apply.set_sensitive(False) try: Pango.parse_markup(text, -1, u"\u0000") except GLib.GError: text = _("Invalid pattern") edit.apply.set_sensitive(False) else: edit.apply.set_sensitive(True) label.set_markup(text)
def _pango_markup_parse(self, text, _err_mark='[TN82u8] '): success = True try: _, attr_list, text, _ = Pango.parse_markup(text, -1, '\0') except GLib.GError as err: if self.markup_warn: msg_start = '{}Pango formatting failed'.format(_err_mark) if msg_start not in text: # detect and avoid possible feedback loops log.warn('%s (%s) for text, stripping markup: %r', msg_start, err, text) else: text = xml_escape(text) # escape message so it'd render bugged part if self.markup_strip: text = strip_markup(text) try: _, attr_list, text, _ = Pango.parse_markup(text, -1, '\0') except GLib.GError: attr_list = None success = False return success, text, attr_list
def add_styles(self, styles): ''' Add styles nodes to the tree ''' assert self.tree is not None, "lxml.etree hasn't been set" root = self.tree.getroot() defn_iter = styles.iter_children(None) while defn_iter is not None: lang = GThemerRow(*[style for style in styles[defn_iter]]) print "Lang: {}".format(lang.get_row()) if lang['definition'] == 'Global gedit Settings': # Handle globals child_iter = styles.iter_children(defn_iter) while child_iter is not None: child = GThemerRow(*[style for style in styles[child_iter]]) print("Global child: {}".format(child.get_row())) if not all(item is None for item in child): element = etree.Element('style') for row, column in self.style_columns.iteritems(): attr = str(child[row]) if isinstance(child[row], bool) else child[row] if column == 'name': _, __, attr, ___ = Pango.parse_markup(child[row], len(child[row]), "\0") if attr is not None: element.set(column, attr) root.append(element) else: print("Oops, this row is empty for lang: {}. {}".format(lang['definition'], child.get_row() )) child_iter = styles.iter_next(child_iter) else: # Handle everything else. child_iter = styles.iter_children(defn_iter) while child_iter is not None: child = GThemerRow(*styles[child_iter]) print("Child: {}".format(child.get_row())) if not all(item is None for item in child): element = etree.Element('style') for row, column in self.style_columns.iteritems(): attr = str(child[row]) if isinstance(child[row], bool) else child[row] if column == 'name': _, __, attr, ___ = Pango.parse_markup(child[row], len(child[row]), "\0") if attr is not None: element.set(column, attr) root.append(element) else: print("Oops, this row is empty for lang: {}. {}".format(lang['definition'], child.get_row() )) child_iter = styles.iter_next(child_iter) defn_iter = styles.iter_next(defn_iter)
def _on_query_tooltip(self, widget, x, y, keyboard, tooltip): """ Show tooltip if needed @param widget as Gtk.Widget @param x as int @param y as int @param keyboard as bool @param tooltip as Gtk.Tooltip """ if keyboard: return True (exists, tx, ty, model, path, i) = self._view.get_tooltip_context( x, y, False) if exists: ctx = self._view.get_pango_context() layout = Pango.Layout.new(ctx) iterator = self._model.get_iter(path) if iterator is not None: text = self._model.get_value(iterator, 1) column = self._view.get_column(0) (position, width) = column.cell_get_position(self._renderer0) layout.set_ellipsize(Pango.EllipsizeMode.END) layout.set_width(Pango.units_from_double(width-8)) layout.set_text(text, -1) if layout.is_ellipsized(): tooltip.set_markup(escape(text)) return True return False
def layer_name_text_datafunc(column, cell, model, it, data): """Show the layer name, with italics for layer groups""" layer = model.get_layer(it=it) if layer is None or layer.name is None: if layer is None: # Can happen under some rare conditions, code has to be # robust. Pick something placeholdery, and hope it's # temporary. default_name = lib.layer.PlaceholderLayer.DEFAULT_NAME else: default_name = layer.DEFAULT_NAME path = model.get_path(it) markup = UNNAMED_LAYER_DISPLAY_NAME_TEMPLATE.format( default_name=default_name, path=str(path), ) else: markup = lib.xml.escape(layer.name) if isinstance(layer, lib.layer.LayerStack): markup = u"<i>%s</i>" % (markup,) attrs = Pango.AttrList() parse_result = Pango.parse_markup(markup, -1, '\000') parse_ok, attrs, text, accel_char = parse_result assert parse_ok cell.set_property("attributes", attrs) cell.set_property("text", text)
def create_files(self, name, save_format, lang, message, Thai=False): if not Thai and Pango.find_base_dir(self.wordlist[0][0], -1) == Pango.Direction.RTL: [i.reverse() for i in self.grid] RTL = True else: RTL = False img_files = '' if 'p' in save_format: self.export_pdf(name, '_grid.pdf', lang, RTL) self.export_pdf(name, '_key.pdf', lang, RTL) img_files += name + '_grid.pdf ' + name + '_key.pdf ' if 'l' in save_format: self.export_pdf(name, 'l_grid.pdf', lang, RTL, 612, 792) self.export_pdf(name, 'l_key.pdf', lang, RTL, 612, 792) img_files += name + 'l_grid.pdf ' + name + 'l_key.pdf ' if 'n' in save_format: self.create_img(name + '_grid.png', RTL) self.create_img(name + '_key.png', RTL) img_files += name + '_grid.png ' + name + '_key.png ' if 's' in save_format: self.create_img(name + '_grid.svg', RTL) self.create_img(name + '_key.svg', RTL) img_files += name + '_grid.svg ' + name + '_key.svg ' if 'n' in save_format or 's' in save_format: self.clues_txt(name + '_clues.txt', lang, Thai) img_files += name + '_clues.txt' if message: print(message + img_files)
def draw_string(self, label, x, y, offsets=None): '''Draw a string at the specified point. offsets is an optional tuple specifying where the string will be drawn relative to the coordinates passed in; for instance, if offsets are (-1, -1) the string will be drawn with the bottom right edge at the given x, y. ''' fontname = "Sans Italic 14" # fontname = "Sans Italic 14" layout = PangoCairo.create_layout(self.ctx) desc = Pango.font_description_from_string(fontname) layout.set_font_description( desc) layout.set_text(label, -1) if offsets: width, height = layout.get_pixel_size() # # pango draws text with the upper left corner at x, y. # # So that's an offset of (1, 1). Adjust if offsets are different. # # XXX Cairo may do things differently. # xbearing, ybearing, width, height, xadvance, yadvance = \ # self.ctx.text_extents(label) if offsets[0] == 0: x -= int(width/2) elif offsets[0] != 1: x += int(width * offsets[0]) if offsets[1] != 1: y += int(height * offsets[1] - height/2) self.ctx.move_to(x, y) PangoCairo.show_layout (self.ctx, layout)
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, -1, '0') label_item = Gtk.MenuItem.new_with_mnemonic(markup_data[2]) 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 on_start(self): """""" Sys.g.GUI_PRINT_STDOUT = False Sys.g.GUI = True init(conf.PRG_NAME, False, Sys.getpid(), True, Const.LOG_ALL) self.conf = ImpraConf(KiniFile('impra2.ini')) self.populate_profiles() self.populate_config() self.taskLabel = ImpraThread.TASK_LABEL self.taskStock = ImpraThread.TASK_STOCK self.progressbar = self.get('progressbar1') self.textview = self.get('textview1') try : self.textview.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 1.0)) self.textview.modify_font(Pango.font_description_from_string ('DejaVu Sans Mono Book 11' if Sys.isUnix() else 'Lucida Conosle 11')) except : pass self.textbuffer = self.textview.get_buffer() self.tags = self.buildTxtTags(self.textbuffer) self.initWidgetByThread('impra-1', self.textview, self.textbuffer, self.progressbar, self.tags) self.initWidgetByThread('MainThread', self.textview, self.textbuffer, self.progressbar, self.tags) self.tree = self.get('treeview1') self.tree.connect('row-activated', self.on_row_select) self.tree.get_selection().connect('changed', self.on_tree_selection_changed) self.launch_thread(self.on_ended) self.searchCatg = self.get('comboboxtext1') self.searchUser = self.get('comboboxtext4') self.searchAccount = self.get('comboboxtext5') self.filterIds = None self.index = None self.taskList = {} self.threads_work = [False, False]
def do_draw_cb(self, widget, cr): # The do_draw_cb is called when the widget is asked to draw itself # with the 'draw' as opposed to old function 'expose event' # Remember that this will be called a lot of times, so it's usually # a good idea to write this code as optimized as it can be, don't # Create any resources in here. cr.translate ( RADIUS, RADIUS) layout = PangoCairo.create_layout (cr) layout.set_text("శ్రీమదాంధ్రమహాభారతము", -1) desc = Pango.font_description_from_string (FONT) layout.set_font_description( desc) rangec = range(0, N_WORDS) for i in rangec: width, height = 0,0 angle = (360. * i) / N_WORDS; cr.save () red = (1 + math.cos ((angle - 60) * math.pi / 180.)) / 2 cr.set_source_rgb ( red, 0, 1.0 - red) cr.rotate ( angle * math.pi / 180.) #/* Inform Pango to re-layout the text with the new transformation */ PangoCairo.update_layout (cr, layout) width, height = layout.get_size() cr.move_to ( - (float(width) / 1024.) / 2, - RADIUS) PangoCairo.show_layout (cr, layout) cr.restore()
def init(): # import __main__ # TODO where to add __main__function core.fp3 = fp5 core.fp4 = fp6 Vi.PWD = PWD global PATH_GLOSS core.PATH_GLOSS = PATH_GLOSS = PWD + PATH_GLOSS global FONT_obj FONT_obj = Pango.font_description_from_string(def_FONT) browser.FONT_obj = FONT_obj browser.fp3 = fp4 # MAYBE do __main__ import here global BROWSER Vi.BROWSER = BROWSER global ignore_keys ignore_keys = [ v for k, v in utils.key_codes.items() if v != utils.key_codes["RETURN"]] for path in LIST_GLOSS: core.Glossary(path)
def do_draw(self, gpsmap, ctx): """ Draw all the messages """ ctx.save() font_size = "%s %d" % (self.font, self.size) font = Pango.FontDescription(font_size) descr = Pango.font_description_from_string(self.font) descr.set_size(self.size * Pango.SCALE) color = Gdk.color_parse(self.color) ctx.set_source_rgba(float(color.red / 65535.0), float(color.green / 65535.0), float(color.blue / 65535.0), 0.9) # transparency d_width = gpsmap.get_allocation().width d_width -= 100 ctx.restore() ctx.save() ctx.move_to(100, 5) layout = PangoCairo.create_layout(ctx) layout.set_font_description(descr) layout.set_indent(Pango.SCALE * 0) layout.set_alignment(Pango.Alignment.LEFT) layout.set_wrap(Pango.WrapMode.WORD_CHAR) layout.set_spacing(Pango.SCALE * 3) layout.set_width(d_width * Pango.SCALE) layout.set_text(self.message, -1) PangoCairo.show_layout(ctx, layout) ctx.restore() ctx.stroke()
def create_files(self, name, save_format, gtkmode=False, RTL=False): if Pango.find_base_dir(self.wordlist[0][0], -1) == Pango.Direction.RTL: [i.reverse() for i in self.grid] RTL = True img_files = '' if 'p' in save_format: self.export_pdf(name, '_grid.pdf', RTL) self.export_pdf(name, '_key.pdf', RTL) img_files += name + '_grid.pdf ' + name + '_key.pdf ' if 'l' in save_format: self.export_pdf(name, 'l_grid.pdf', RTL, 612, 792) self.export_pdf(name, 'l_key.pdf', RTL, 612, 792) img_files += name + 'l_grid.pdf ' + name + 'l_key.pdf ' if 'n' in save_format: self.create_img(name + '_grid.png', RTL) self.create_img(name + '_key.png', RTL) img_files += name + '_grid.png ' + name + '_key.png ' if 's' in save_format: self.create_img(name + '_grid.svg', RTL) self.create_img(name + '_key.svg', RTL) img_files += name + '_grid.svg ' + name + '_key.svg ' if 'n' in save_format or 's' in save_format: self.clues_txt(name + '_clues.txt') img_files += name + '_clues.txt' if not gtkmode: print('The following files have been saved to your current working directory:\n' + img_files)
def __init__(self): Gtk.Window.__init__(self, title="LEDParty ServerSIM") self.set_default_size(640, 480) self.connect("destroy", self.destroy) self.mode = MODO_TEXTO self.last_beat = 0 self.debug("LEDPartyServer iniciado") # Layout vertical self.vbox = Gtk.VBox(spacing=3) # Notebook para los tabs self.notebook = Gtk.Notebook() nb = self.notebook nb.set_tab_pos(Gtk.PositionType.TOP) nb.connect("switch-page", self.on_page_changed) # Tab del modo Texto hTexto = Gtk.HBox() hTexto.show() self.lblText = Gtk.Label(u"<vacío>") self.lblText.modify_font(Pango.font_description_from_string("sans 32")) self.lblText.show() hTexto.add(self.lblText) # Tab del modo Espectro hEspectro = Gtk.HBox() hEspectro.show() self.spectrumArea = Gtk.DrawingArea() self.spectrumArea.connect('draw', self.on_spectrum_draw) self.spectrumArea.show() hEspectro.add(self.spectrumArea) # Tab del modo Beatbox hBeatbox = Gtk.HBox() hBeatbox.show() self.beatboxArea = Gtk.DrawingArea() self.beatboxArea.connect('draw', self.on_beatbox_draw) self.beatboxArea.show() hBeatbox.add(self.beatboxArea) self.add_page("Texto", hTexto) self.add_page("Espectroscopio", hEspectro) self.add_page("BeatBox", hBeatbox) self.vbox.pack_start(nb, True, True, 0) # Status bar self.bar = Gtk.Statusbar() self.bar.push(0, 'Listo') self.tasks = 0 self.vbox.pack_start(self.bar, False, True, 0) self.beatbox_timer = GObject.timeout_add(10, self.on_update_beatbox) self.spectrum_timer = GObject.timeout_add(10, self.on_update_spectrum) print self.beatbox_timer # Añadir Layout self.add(self.vbox) self.show_all()
def create_font_from_description(desc): """ Creates Pango font from string description. :param desc: description """ return Pango.font_description_from_string(desc)
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, -1, '\x00') except Exception as e: print('Could not parse markup:', e) buf.insert(buf.get_end_iter(), line) return # TODO: fix this when pango supports get_iterator text = ret[2] buf.insert(buf.get_end_iter(), text) return piter = ret[1].get_iterator() while piter: attrs = piter.get_attrs() begin, end = piter.range() tags = self.attrs_to_tags(attrs) buf.insert_with_tags(buf.get_end_iter(), text[begin:end], *tags) if not piter.next(): break
def __export_pdf_cb(self, event): maxx, maxy = self._main_area.get_max_area() true_width = int(maxx) true_height = int(maxy) # Create the new journal entry fileObject = datastore.create() act_meta = self.metadata fileObject.metadata['title'] = act_meta['title'] + ' (PDF)' fileObject.metadata['title_set_by_user'] = \ act_meta['title_set_by_user'] fileObject.metadata['mime_type'] = 'application/pdf' # TODO: add text thoughts into fulltext metadata # fileObject.metadata['fulltext'] = ... fileObject.metadata['icon-color'] = act_meta['icon-color'] fileObject.file_path = os.path.join(self.get_activity_root(), 'instance', '%i' % time.time()) filename = fileObject.file_path surface = cairo.PDFSurface(filename, true_width, true_height) cairo_context = cairo.Context(surface) context = Pango.create_context(cairo_context) self._main_area.export(context, true_width, true_height, False) surface.finish() datastore.write(fileObject, transfer_ownership=True) fileObject.destroy() del fileObject
def draw_text_bubble(self, cr, pointx, pointy): """ Draw bubble with information text """ margin_top = 12.0 margin_bottom = 12.0 margin_start = 24.0 margin_end = 24.0 # Corner radius rounded = 9.0 if not self._bubble_text: return alloc = self.get_allocation() layout = PangoCairo.create_layout(cr) font_description = Pango.font_description_from_string(BUBBLE_TEXT_FONT) layout.set_font_description(font_description) layout.set_alignment(Pango.Alignment.CENTER) layout.set_spacing(3) layout.set_markup(self._bubble_text) (ink_rect, logical_rect) = layout.get_pixel_extents() # Calculate the bubble size based on the text layout size width = logical_rect.width + margin_start + margin_end height = logical_rect.height + margin_top + margin_bottom if pointx < alloc.width / 2: x = pointx + 20 else: x = pointx - width - 20 y = pointy - height / 2 # Make sure it fits in the visible area x = self.clamp(x, 0, alloc.width - width) y = self.clamp(y, 0, alloc.height - height) cr.save() cr.translate(x, y) # Draw the bubble cr.new_sub_path() cr.arc(width - rounded, rounded, rounded, -math.pi / 2, 0) cr.arc(width - rounded, height - rounded, rounded, 0, math.pi / 2) cr.arc(rounded, height - rounded, rounded, math.pi / 2, math.pi) cr.arc(rounded, rounded, rounded, math.pi, math.radians(270)) cr.close_path() cr.set_source_rgba(0.2, 0.2, 0.2, 0.7) cr.fill() # And finally draw the text cr.set_source_rgb(1, 1, 1) cr.move_to(margin_start, margin_top) PangoCairo.show_layout(cr, layout) cr.restore()
def setup_widget_from_pango(self, widg, markupstring): """setup widget from a pango markup string""" #font = Pango.FontDescription(fontstring) suc, a, t, s = Pango.parse_markup(markupstring, -1, u'\x00') ai = a.get_iterator() font, lang, attrs = ai.get_font() return self.setup_widget(widg, font, attrs)
def label_matches(row, label): row_label = self.rows[i][0] if isinstance(row_label, dict): row_label = row_label.get("text", pango.parse_markup(row_label.get("markup", ""), -1, "0")[2]) if fragment: return row_label.lower().startswith(label.lower()) else: return row_label.lower() == label.lower()
def set_content(self, line, word_infos, cursor): self.line = line self.word_infos = word_infos self.cursor = cursor self.invalidate_key() # determine text direction dir = Pango.find_base_dir(line, -1) self.ltr = dir != Pango.Direction.RTL
def font_changed(self, settings=None, key=None): if self.profile_settings.get_boolean("use-system-font"): font = self.system_settings.get_string("monospace-font-name") else: font = self.profile_settings.get_string("font") font_desc = Pango.font_description_from_string(font) self["view"].override_font(font_desc)
def _setElement(self, element): if self.element: text = self.element.get_text() _, _, t, _ = Pango.parse_markup(text, -1, u'\x00') #TODO trim text, first line etc self.name.props.text = t twidth, theight = text_size(self.name) self.namewidth = twidth self.nameheight = theight self._update()
def __init__ (self, map_layout): self.map_layout = map_layout self.outline_thickness_pt = 0.5 self.color_rgb = (0, 0, 0) self.rule_width_mm = 2.0 self.tick_length_mm = 0.5 self.font_description_str = "Luxi Serif 6" self.font_description = Pango.font_description_from_string (self.font_description_str)
def font_changed(self, settings=None, key=None): font = self.get_document_font() font_desc = Pango.font_description_from_string(font) chartable = self.panel.get_chartable() chartable.set_font_desc(font_desc)
def generate(self, tracks, bg=(10, 10, 10), rows=3, columns=3, show_lables=True, font="Monospace 10", tile=False, cascade=False): # Main control variables border = 29 text_offset = -7 size = 170 spacing = 9 mode = 1 if cascade: mode = 2 if tile: border = 0 spacing = 0 size = 160 text_offset = 15 # Determine the final width and height of album grid h = round((border * 2) + (size * rows) + (spacing * (rows - 1))) w = round((border * 2) + (size * columns) + (spacing * (columns - 1))) if mode == 2: r1, r2, r3 = cascade[0] print(r1 * 2 + r2 * 2 + r3 * 2) sets = [] for q in range(100, 10000): a = q / r1 b = q / r2 c = q / r3 if a - int(a) == b - int(b) == c - int(c) == 0: sets.append((int(a), int(b), int(c))) if not sets: return False abc = None for s in sets: if s[(r1, r2, r3).index(min((r1, r2, r3)))] > 165: abc = s break else: return False d1, d2, d3 = cascade[1] w = round(border * 2) + (abc[0] * r1) h = round( border * 2) + (abc[0] * d1) + (abc[1] * d2) + (abc[2] * d3) ww = w i = -1 positions = [] # Grid mode if mode == 1: for r in range(rows): for c in range(columns): i += 1 # Break if we run out of albums if i > len(tracks) - 1: break # Determine coordinates for current album x = round(border + ((spacing + size) * c)) y = round(border + ((spacing + size) * r)) positions.append((tracks[i], x, y, size)) positions.append(False) # Cascade mode elif mode == 2: a, b, c = abc size = a spacing = 0 inv_space = 0 if not tile: inv_space = 8 x = border y = border for d in range(d1): for cl in range(r1): i += 1 x = border + (spacing + size) * cl if i > len(tracks) - 1: break positions.append((tracks[i], x + inv_space // 2, y + inv_space // 2, size - inv_space)) y += spacing + size size = b if not tile: inv_space = 6 positions.append(False) for d in range(d2): for cl in range(r2): i += 1 x = border + (spacing + size) * cl print(x) if i > len(tracks) - 1: break positions.append((tracks[i], x + inv_space // 2, y + inv_space // 2, size - inv_space)) y += spacing + size size = c if not tile: inv_space = 4 positions.append(False) for d in range(d3): for cl in range(r3): i += 1 x = border + (spacing + size) * cl if i > len(tracks) - 1: break positions.append((tracks[i], x + inv_space // 2, y + inv_space // 2, size - inv_space)) y += spacing + size # Parse font font_comp = font.split(" ") font_size = int(font_comp.pop()) col_w = 500 two_col = False font_comp = font.split(" ") font_size = int(font_comp.pop()) if len(positions) * (font_size + 4) > h - border * 2: two_col = True font_size += 1 col_w = 380 if show_lables: ww += col_w # Add extra area to final size for text if two_col: ww += col_w + 20 # Get lables text = "" b_text = "" f = False for item in positions: if item is False: if not f: text += " \n" # Insert extra line to form groups for each row else: b_text += " \n" if two_col: f ^= True continue track, x, y, size = item # Determine the text label line artist = track.artist if track.album_artist: artist = track.album_artist line = f"{artist} - {track.album}\n" if not f: text += line else: b_text += line # Prepare a blank Cairo surface surface = cairo.ImageSurface(cairo.FORMAT_RGB24, ww, h) context = cairo.Context(surface) bg = (bg[0] / 255, bg[1] / 255, bg[2] / 255 ) # Convert 8-bit rgb values to decimal context.set_source_rgb(bg[0], bg[1], bg[2]) context.paint() # Fill in the background colour for item in positions: if item is False: continue track, x, y, size = item # Export the album art to file object try: art_file = self.album_art_gen.save_thumb(track, (size, size), None, png=True, zoom=True) except: continue # Skip drawing this album if loading of artwork failed if not art_file: continue # Load image into Cairo and draw art = cairo.ImageSurface.create_from_png(art_file) context.set_source_surface(art, x, y) context.paint() if show_lables: # Setup font and prepare Pango layout options = context.get_font_options() options.set_antialias(cairo.ANTIALIAS_GRAY) context.set_font_options(options) layout = PangoCairo.create_layout(context) layout.set_ellipsize(Pango.EllipsizeMode.END) layout.set_width((col_w - text_offset - spacing) * 1000) # layout.set_height((h - spacing * 2) * 1000) #layout.set_spacing(3 * 1000) #layout.set_font_description(Pango.FontDescription(font)) # Here we make sure the font size is small enough to fit font = " ".join(font_comp) + " " + str(font_size) layout.set_font_description(Pango.FontDescription(font)) layout.set_text(text, -1) try: font_size = int(font_size) while font_size > 2: th = layout.get_pixel_size()[1] if th < h - border: break font_size -= 1 font = " ".join(font_comp) + " " + str(font_size) layout.set_font_description(Pango.FontDescription(font)) layout.set_text(text, -1) except: print("error adjusting font size") # All good to render now y_text_padding = 3 if tile: y_text_padding += 6 context.translate(w + text_offset, border + y_text_padding) context.set_source_rgb(0.9, 0.9, 0.9) PangoCairo.show_layout(context, layout) if b_text: # Setup font and prepare Pango layout options = context.get_font_options() options.set_antialias(cairo.ANTIALIAS_GRAY) context.set_font_options(options) layout = PangoCairo.create_layout(context) layout.set_ellipsize(Pango.EllipsizeMode.END) layout.set_width((col_w - text_offset - spacing) * 1000) layout.set_font_description(Pango.FontDescription(font)) layout.set_text(b_text, -1) # All good to render now y_text_padding = 3 if tile: y_text_padding += 6 context.translate(col_w + 10, 0) context.set_source_rgb(0.9, 0.9, 0.9) PangoCairo.show_layout(context, layout) # Finally export as PNG output_path = os.path.join(self.user_dir, "chart.png") surface.write_to_png(output_path) # Convert to JPEG for convenience output_path2 = os.path.join(self.user_dir, "chart.jpg") im = Image.open(output_path) im.save(output_path2, 'JPEG', quality=92) return output_path2
def get_column_fonts(self): return [ Pango.FontDescription('Source Sans Pro {}'.format(self.font_size * 1.5)), Pango.FontDescription('Source Sans Pro {}'.format(self.font_size)) ]
def __init__(self): Gtk.Window.__init__(self, title=TITLE, name="ClientWindow") self.set_default_size(600, 100) style_provider = Gtk.CssProvider() css = "#ClientWindow{background-color: #ccffcc;}" style_provider.load_from_data(bytes(css.encode())) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) # Modify the overall font name and size, for use with video projection. if PROJECTOR: pangoFont = Pango.FontDescription(PROJECTOR_FONT) self.modify_font(pangoFont) # call function to read the data to a list of lists. self.data = read_csv_file_to_list() #print(self.data) # Setup GUI Window grid_main = Gtk.Grid() self.add(grid_main) self.label_1 = Gtk.Label(margin=10) grid_main.attach( self.label_1, 0, 0, 1, 1, ) # Create Frame_1 frame_1 = Gtk.Frame(margin=10) frame_1.set_label(FRAME_1) grid_main.attach(frame_1, 0, 0, 1, 1) grid_sub_1 = Gtk.Grid() frame_1.add(grid_sub_1) # Radio Button Set for Frame 1 self.f1_radio_button_1 = Gtk.RadioButton.new_from_widget(None) self.f1_radio_button_1.set_label(F1_RADIOBUTTON_1) self.f1_radio_button_1.connect("toggled", self.f1_radio_button_set_1_cb, "1") self.f1_radio_button_1.set_margin_left(10) grid_sub_1.attach( self.f1_radio_button_1, 0, 1, 1, 1, ) self.f1_radio_button_2 = Gtk.RadioButton.new_from_widget( self.f1_radio_button_1) self.f1_radio_button_2.set_label(F1_RADIOBUTTON_2) self.f1_radio_button_2.connect("toggled", self.f1_radio_button_set_1_cb, "2") self.f1_radio_button_2.set_margin_left(10) grid_sub_1.attach( self.f1_radio_button_2, 0, 2, 1, 1, ) self.f1_radio_button_3 = Gtk.RadioButton.new_from_widget( self.f1_radio_button_1) self.f1_radio_button_3.set_label(F1_RADIOBUTTON_3) self.f1_radio_button_3.connect("toggled", self.f1_radio_button_set_1_cb, "3") self.f1_radio_button_3.set_margin_left(10) grid_sub_1.attach( self.f1_radio_button_3, 0, 3, 1, 1, ) self.f1_radio_button_4 = Gtk.RadioButton.new_from_widget( self.f1_radio_button_1) self.f1_radio_button_4.set_label(F1_RADIOBUTTON_4) self.f1_radio_button_4.connect("toggled", self.f1_radio_button_set_1_cb, "4") self.f1_radio_button_4.set_margin_left(10) grid_sub_1.attach( self.f1_radio_button_4, 0, 4, 1, 1, ) self.f1_radio_button_5 = Gtk.RadioButton.new_from_widget( self.f1_radio_button_1) self.f1_radio_button_5.set_label(F1_RADIOBUTTON_5) self.f1_radio_button_5.connect("toggled", self.f1_radio_button_set_1_cb, "5") self.f1_radio_button_5.set_margin_left(10) grid_sub_1.attach( self.f1_radio_button_5, 0, 5, 1, 1, ) """ # Create Frame_2 frame_2 = Gtk.Frame(margin=10) frame_2.set_label(FRAME_2) grid_main.attach(frame_2, 0 , 1, 1, 1) grid_sub_1 = Gtk.Grid() frame_2.add(grid_sub_1) # Radio Button Set for Frame 2 #self.radio_button_1 = Gtk.RadioButton.new_with_label_from_widget( # None, "Button 1") self.f2_radio_button_1 = Gtk.RadioButton.new_from_widget(None) self.f2_radio_button_1.set_label(F2_RADIOBUTTON_1) self.f2_radio_button_1.connect("toggled", self.f2_radio_button_set_1_cb, "1") self.f2_radio_button_1.set_margin_left(10) grid_sub_1.attach(self.f2_radio_button_1, 0, 1, 1, 1,) self.f2_radio_button_2 = Gtk.RadioButton.new_from_widget(self.f2_radio_button_1) self.f2_radio_button_2.set_label(F2_RADIOBUTTON_2) self.f2_radio_button_2.connect("toggled", self.f2_radio_button_set_1_cb, "2") self.f2_radio_button_2.set_margin_left(10) grid_sub_1.attach(self.f2_radio_button_2, 0, 2, 1, 1,) self.f2_radio_button_3 = Gtk.RadioButton.new_from_widget(self.f2_radio_button_1) self.f2_radio_button_3.set_label(F2_RADIOBUTTON_3) self.f2_radio_button_3.connect("toggled", self.f2_radio_button_set_1_cb, "3") self.f2_radio_button_3.set_margin_left(10) grid_sub_1.attach(self.f2_radio_button_3, 0, 3, 1, 1,) # kick start self.f2_radio_button_1.set_active(True) """ # Create Frame_3 frame_3 = Gtk.Frame(margin=10) frame_3.set_label(FRAME_3) grid_main.attach(frame_3, 0, 5, 1, 1) grid_sub_1 = Gtk.Grid() frame_3.add(grid_sub_1) # Add two labels to display the totals. self.label_1 = Gtk.Label(margin=10) self.label_1.set_text("Total") grid_sub_1.attach( self.label_1, 0, 0, 1, 1, ) self.label_2 = Gtk.Label(margin=10) grid_sub_1.attach( self.label_2, 1, 0, 1, 1, ) self.label_2.set_text("") # Scrolled window to disploay the countries. self.scrolledwindow = Gtk.ScrolledWindow(margin=10) self.scrolledwindow.set_hexpand(True) self.scrolledwindow.set_vexpand(True) grid_sub_1.attach(self.scrolledwindow, 0, 2, 2, 1) self.textview = Gtk.TextView() # dir(Gtk.WrapMode) ['CHAR', 'NONE', 'WORD', 'WORD_CHAR' self.textview.set_wrap_mode(Gtk.WrapMode.WORD) # set_wrap_mode self.scrolledwindow.set_size_request(200, 300) # OK self.textbuffer = self.textview.get_buffer() self.textbuffer.set_text("") self.scrolledwindow.add(self.textview) self.tag_bold = self.textbuffer.create_tag("bold", weight=Pango.Weight.BOLD) self.tag_italic = self.textbuffer.create_tag("italic", style=Pango.Style.ITALIC) self.tag_underline = self.textbuffer.create_tag( "underline", underline=Pango.Underline.SINGLE) self.tag_found = self.textbuffer.create_tag("found", background="yellow") # kick start self.f1_radio_button_2.set_active(True) self.f1_radio_button_1.set_active(True)
def on_option_set(self, event, settings, option): if option == 'plugin/lyricsviewer/lyrics_font': self.lyrics_text.modify_font( Pango.FontDescription(settings.get_option(option)))
@override(ui.Label) def do_render(self): """the label is looking for an background_image attribute and if it is found it paints it""" if getattr(self, "background_image", None): self.background_image.render(self.graphics, self.width, self.height) ui.Button.images = { "normal": get_image("themes/assets/button_normal.png", 3, 3, 3, 3), "highlight": get_image("themes/assets/button_highlight.png", 3, 3, 3, 3), "pressed": get_image("themes/assets/button_pressed.png", 3, 3, 3, 3), "disabled": get_image("themes/assets/button_disabled.png", 3, 3, 3, 3), } ui.Button.font_desc = pango.FontDescription('Serif 10') @override(ui.Button) def do_render(self, state=None): """ Properties that affect rendering: state: normal / highlight / pressed focused: True / False enabled: True / False """ state = state or self.state if self.enabled: self.display_label.color = "#000" self.display_label.background_image = None image = self.images.get(state)
def get_column_fonts(self): return [ Pango.FontDescription(f"{WIDGET_FONT} {42}"), Pango.FontDescription(f"{WIDGET_FONT} {18}"), ]
def _calculate_char_width(self, char_count): widget = Gtk.Label(label='') context = widget.get_pango_context() pango_font = context.load_font(_SOURCE_FONT) metrics = pango_font.get_metrics() return Pango.PIXELS(metrics.get_approximate_char_width()) * char_count
def draw(self, context): style_ctxt = self.get_style_context() self.light = style_ctxt.lookup_color("p_light_color")[1] self.dark = style_ctxt.lookup_color("p_dark_color")[1] if not self.model: return # Draw graphical Clock. Should this be moved to preferences? drawClock = True rect = Gdk.Rectangle() clip_ext = context.clip_extents() rect.x, rect.y, rect.width, rect.height = clip_ext[0], clip_ext[1], \ clip_ext[2] - clip_ext[0], clip_ext[3] - clip_ext[1] context.rectangle(rect.width / 2. * self.model.movingColor, 0, rect.width / 2., rect.height) context.set_source_rgba(self.dark.red, self.dark.green, self.dark.blue, self.dark.alpha) context.fill_preserve() context.new_path() time0 = self.names[0], self.formatedCache[WHITE] layout0 = self.create_pango_layout(" %s: %s " % (time0)) layout0.set_font_description(Pango.FontDescription("Sans Serif 17")) time1 = self.names[1], self.formatedCache[BLACK] layout1 = self.create_pango_layout(" %s: %s " % (time1)) layout1.set_font_description(Pango.FontDescription("Sans Serif 17")) dbl_max = max(layout1.get_pixel_size()[0], layout0.get_pixel_size()[0]) * 2 self.set_size_request(dbl_max + rect.height + 7, -1) pangoScale = float(Pango.SCALE) # Analog clock code. def paintClock(player): clock_y = rect.height / 2. clock_x = clock_y + rect.width / 2. * player + 1 rec = rect.height / 2. - 3.5 context.arc(clock_x, clock_y, rec - 1, 0, 2 * pi) linear = cairo.LinearGradient(clock_x - rec * 2, clock_y - rec * 2, \ clock_x + rec * 2, clock_y + rec * 2) linear.add_color_stop_rgba(0, 1, 1, 1, 0.3) linear.add_color_stop_rgba(1, 0, 0, 0, 0.3) #context.set_source_rgba( 0, 0, 0, .3) context.set_source(linear) context.fill() linear = cairo.LinearGradient(clock_x - rec, clock_y - rec, \ clock_x + rec, clock_y + rec) linear.add_color_stop_rgba(0, 0, 0, 0, 0.5) linear.add_color_stop_rgba(1, 1, 1, 1, 0.5) context.arc(clock_x, clock_y, rec, 0, 2 * pi) context.set_source(linear) context.set_line_width(2.5) context.stroke() starttime = float(self.model.getInitialTime()) or 1 used = self.model.getPlayerTime(player) / starttime if used > 0: if used > 0: context.arc(clock_x, clock_y, rec - .8, -(used + 0.25) * 2 * pi, -0.5 * pi) context.line_to(clock_x, clock_y) context.close_path() elif used == 0: context.arc(clock_x, clock_y, rec - .8, -0.5 * pi, 1.5 * pi) context.line_to(clock_x, clock_y) radial = cairo.RadialGradient(clock_x, clock_y, 3, clock_x, clock_y, rec) if player == 0: #radial.add_color_stop_rgb(0, .73, .74, .71) radial.add_color_stop_rgb(0, .93, .93, .92) radial.add_color_stop_rgb(1, 1, 1, 1) else: #radial.add_color_stop_rgb(0, .53, .54, .52) radial.add_color_stop_rgb(0, .18, .20, .21) radial.add_color_stop_rgb(1, 0, 0, 0) context.set_source(radial) context.fill() x_loc = clock_x - cos((used - 0.25) * 2 * pi) * (rec - 1) y_loc = clock_y + sin((used - 0.25) * 2 * pi) * (rec - 1) context.move_to(clock_x, clock_y - rec + 1) context.line_to(clock_x, clock_y) context.line_to(x_loc, y_loc) context.set_line_width(0.2) if player == 0: context.set_source_rgb(0, 0, 0) else: context.set_source_rgb(1, 1, 1) context.stroke() if drawClock: paintClock(WHITE) if (self.model.movingColor or WHITE) == WHITE: context.set_source_rgba(self.light.red, self.light.green, self.light.blue, self.light.alpha) else: context.set_source_rgba(self.dark.red, self.dark.green, self.dark.blue, self.dark.alpha) y_loc = rect.height/2. - layout0.get_extents()[0].height/pangoScale/2 \ - layout0.get_extents()[0].y/pangoScale context.move_to(rect.height - 7, y_loc) PangoCairo.show_layout(context, layout0) if drawClock: paintClock(BLACK) if self.model.movingColor == BLACK: context.set_source_rgba(self.light.red, self.light.green, self.light.blue, self.light.alpha) else: context.set_source_rgba(self.dark.red, self.dark.green, self.dark.blue, self.dark.alpha) y_loc = rect.height/2. - layout0.get_extents()[0].height/pangoScale/2 \ - layout0.get_extents()[0].y/pangoScale context.move_to(rect.width / 2. + rect.height - 7, y_loc) PangoCairo.show_layout(context, layout1)
def _setup_widget(self): Gtk.HBox.__init__(self) GObject.signal_new('statusbar-updated', Statusbar, GObject.SignalFlags.RUN_LAST, GObject.TYPE_PYOBJECT, (GObject.TYPE_PYOBJECT,) ) self.set_property('margin-top', 3) self.set_property('margin-bottom', 3) vbox = Gtk.VBox() viewport = Gtk.Viewport() viewport.set_shadow_type(Gtk.ShadowType.NONE) hbox = Gtk.HBox() viewport.add(hbox) separator = Gtk.Separator() # PRIORITY label_priority = self.srvgui.add_widget('statusbar_label_priority', Gtk.Label()) label_priority.set_property('ellipsize', Pango.EllipsizeMode.MIDDLE) label_priority.set_property('selectable', True) label_priority.set_property('margin-left', 6) label_priority.set_property('margin-right', 6) label_priority.set_property('margin-top', 0) label_priority.set_property('margin-bottom', 3) label_priority.set_width_chars(8) label_priority.set_xalign(0.0) label_priority.modify_font(Pango.FontDescription('Monospace 10')) container = Gtk.Viewport() container.set_shadow_type(Gtk.ShadowType.OUT) container.add(label_priority) hbox.pack_start(container, False, False, 3) # MESSAGE label_message = self.srvgui.add_widget('statusbar_label_message', Gtk.Label()) label_message.set_property('ellipsize', Pango.EllipsizeMode.MIDDLE) label_message.set_property('selectable', True) label_message.set_property('margin-left', 6) label_message.set_property('margin-right', 6) label_message.set_property('margin-top', 0) label_message.set_xalign(0.0) label_message.modify_font(Pango.FontDescription('Monospace 10')) container = Gtk.Viewport() container.set_shadow_type(Gtk.ShadowType.OUT) container.add(label_message) hbox.pack_start(container, True, True, 3) # CANCEL BUTTON button = Gtk.Button() icon = self.srvicm.get_pixbuf_icon('basico-check-cancel', 18, 18) image = Gtk.Image() image.set_from_pixbuf(icon) button.set_image(image) button.set_relief(Gtk.ReliefStyle.NONE) self.srvgui.add_widget('statusbar_button_cancel', button) self.srvgui.add_signal('statusbar_button_cancel', 'clicked', 'self.srvweb.cancel_by_user') hbox.pack_end(button, False, False, 0) button.set_property('margin-right', 6) # ~ button.set_property('margin-bottom', 3) # SPINNER spinner = self.srvgui.add_widget('statusbar_spinner', Gtk.Spinner()) spinner.show_all() hbox.pack_start(spinner, False, False, 3) # ~ vbox.pack_start(separator, True, False, 0) vbox.pack_start(viewport, True, False, 0) self.add(vbox)
from sugar3.graphics.xocolor import XoColor from sugar3.graphics.menuitem import MenuItem from sugar3.graphics.toolbutton import ToolButton from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.bundle.activitybundle import ActivityBundle from sugar3.datastore import datastore from sugar3.env import get_user_activities_path from sugar3 import mime from jarabe.view import customizebundle _EXCLUDE_EXTENSIONS = ('.pyc', '.pyo', '.so', '.o', '.a', '.la', '.mo', '~', '.xo', '.tar', '.bz2', '.zip', '.gz') _EXCLUDE_NAMES = ['.deps', '.libs'] _SOURCE_FONT = Pango.FontDescription('Monospace %d' % style.FONT_SIZE) _logger = logging.getLogger('ViewSource') map_activity_to_window = {} def _is_web_activity(bundle_path): activity_bundle = ActivityBundle(bundle_path) return activity_bundle.get_command() == 'sugar-activity-web' def _is_gtk3_activity(bundle_path): # FIXME, find a way to check if the activity is GTK3 or GTK2. return True
def redraw_rect(self, widget, cairo_ctx): style_ctx = widget.get_style_context() (w, h) = (widget.get_allocated_width(), widget.get_allocated_height()) Gtk.render_background(style_ctx, cairo_ctx, 0, 0, w - 1, h - 1) xc = w // 2 yc = h // 2 # Consider using gtk_render_arrow def triangle(points): cairo_ctx.move_to(*points[0]) cairo_ctx.line_to(*points[1]) cairo_ctx.line_to(*points[2]) cairo_ctx.line_to(*points[0]) cairo_ctx.fill() cairo_ctx.stroke() th = 8 tw = 6 # Triangle pointing left points = [ (1, yc), (1 + th, yc - tw), (1 + th, yc + tw)] triangle(points) # pointing right points = [ (w - 2, yc), (w - 2 - th, yc - tw), (w - 2 - th, yc + tw)] triangle(points) # pointing up points = [ (xc, 1), (xc - tw, th), (xc + tw, th)] triangle(points) # pointing down points = [ (xc, h - 2), (xc - tw, h - 2 - th), (xc + tw, h - 2 - th)] triangle(points) pango_ctx = widget.get_pango_context() layout = Pango.Layout(pango_ctx) try: drawtext = self.text except AttributeError: print("fourway has no text") return while True: layout.set_text(drawtext, len(drawtext)) (text_width, text_height) = layout.get_pixel_size() # truncate text if it's too long if text_width < (w - th * 2) or len(drawtext) < 3: break drawtext = drawtext[:-1] Gtk.render_layout( style_ctx, cairo_ctx, xc - text_width // 2, yc - text_height // 2, layout)
def test_font_description(self): desc = Pango.FontDescription('monospace') self.assertEqual(desc.get_family(), 'monospace') self.assertEqual(desc.get_variant(), Pango.Variant.NORMAL)
def test_default_font_description(self): desc = Pango.FontDescription() self.assertEqual(desc.get_variant(), Pango.Variant.NORMAL)
def _test_markup(self, text): from gi.repository import Pango Pango.parse_markup(text, -1, "\x00")
def get_column_fonts(self): return [ Pango.FontDescription(f"{WIDGET_FONT} {self.font_size * 1.5}"), Pango.FontDescription(f"{WIDGET_FONT} {self.font_size}"), ]
def get_gudgitters_image(rankings): """return PIL image for rankings""" SMOKE_WHITE = (250, 250, 250) BLACK = (0, 0, 0) DISCORD_GRAY = (0.212, 0.244, 0.247) ROW_COLORS = ((0.95, 0.95, 0.95), (0.9, 0.9, 0.9)) WIDTH = 900 HEIGHT = 450 BORDER_MARGIN = 20 COLUMN_MARGIN = 10 HEADER_SPACING = 1.25 WIDTH_RANK = 0.08 * WIDTH WIDTH_NAME = 0.38 * WIDTH LINE_HEIGHT = (HEIGHT - 2 * BORDER_MARGIN) / (10 + HEADER_SPACING) # Cairo+Pango setup surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) context = cairo.Context(surface) context.set_line_width(1) context.set_source_rgb(*DISCORD_GRAY) context.rectangle(0, 0, WIDTH, HEIGHT) context.fill() layout = PangoCairo.create_layout(context) layout.set_font_description( Pango.font_description_from_string(",".join(FONTS) + " 20")) layout.set_ellipsize(Pango.EllipsizeMode.END) def draw_bg(y, color_index): nxty = y + LINE_HEIGHT # Simple context.move_to(BORDER_MARGIN, y) context.line_to(WIDTH, y) context.line_to(WIDTH, nxty) context.line_to(0, nxty) context.set_source_rgb(*ROW_COLORS[color_index]) context.fill() def draw_row(pos, username, handle, rating, color, y, bold=False): context.set_source_rgb(*[x / 255.0 for x in color]) context.move_to(BORDER_MARGIN, y) def draw(text, width=-1): text = html.escape(text) if bold: text = f"<b>{text}</b>" # pixel = 1000 pango units layout.set_width((width - COLUMN_MARGIN) * 1000) layout.set_markup(text, -1) PangoCairo.show_layout(context, layout) context.rel_move_to(width, 0) draw(pos, WIDTH_RANK) draw(username, WIDTH_NAME) draw(handle, WIDTH_NAME) draw(rating) # y = BORDER_MARGIN # draw header draw_row("#", "Name", "Handle", "Rating", SMOKE_WHITE, y, bold=True) y += LINE_HEIGHT * HEADER_SPACING for i, (pos, name, handle, rating) in enumerate(rankings): color = rating_to_color(rating) draw_bg(y, i % 2) draw_row(str(pos), name, handle, str(rating), color, y) if rating != "N/A" and rating >= 3000: # nutella draw_row("", name[0], handle[0], "", BLACK, y) y += LINE_HEIGHT image_data = io.BytesIO() surface.write_to_png(image_data) image_data.seek(0) discord_file = discord.File(image_data, filename="gudgitters.png") return discord_file
def get_markup_error(markup): try: Pango.parse_markup(markup, -1, '\0') except GLib.Error as e: return e.message return None
def __init__(self, parent, notebook, options): PluginBase.__init__(self, parent, notebook, options) # finalize title bar construction self._title_bar.create_title() # make options available in local namespace options = self._parent.options section = options.section('terminal') self._menu = None # change list icon self._title_bar.set_icon_from_name('utilities-terminal') # create main object self._terminal_type = section.get('type') if self._terminal_type == TerminalType.VTE: self._terminal = Vte.Terminal.new() self._terminal.connect('window-title-changed', self._update_title) # unset drag source self._terminal.drag_source_unset() # configure terminal widget shape = section.get('cursor_shape') shape_type = { CursorShape.BLOCK: Vte.CursorShape.BLOCK, CursorShape.IBEAM: Vte.CursorShape.IBEAM, CursorShape.UNDERLINE: Vte.CursorShape.UNDERLINE } self._terminal.set_cursor_shape(shape_type[shape]) self._terminal.set_allow_bold(section.get('allow_bold')) self._terminal.set_mouse_autohide(section.get('mouse_autohide')) if section.get('use_system_font'): self.__set_system_font() else: font = Pango.FontDescription(section.get('font')) self._terminal.set_font(font) elif self._terminal_type == TerminalType.EXTERNAL: self._terminal = Gtk.Socket() else: # failsafe when VTE module is not present # NOTE: Cursor needs to be visible for 'close tab' accelerator. self._terminal = Gtk.TextView() text = _('\n\nPython VTE module is not installed on this system!') self._terminal.get_buffer().set_text(text) self._terminal.set_editable(False) self._terminal.set_justification(Gtk.Justification.CENTER) self._terminal.set_wrap_mode(Gtk.WrapMode.WORD) # terminal container if self._terminal_type == TerminalType.VTE: self._container = Gtk.ScrolledWindow() self._container.set_shadow_type(Gtk.ShadowType.NONE) # apply scrollbar visibility show_scrollbars = section.get('show_scrollbars') scrollbar_vertical = self._container.get_vscrollbar() scrollbar_horizontal = self._container.get_hscrollbar() scrollbar_vertical.set_child_visible(show_scrollbars) scrollbar_horizontal.set_child_visible(False) elif self._terminal_type == TerminalType.EXTERNAL: self._container = Gtk.Viewport() self._container.set_shadow_type(Gtk.ShadowType.IN) # pack terminal self._container.add(self._terminal) self.pack_start(self._container, True, True, 0) # connect events to main object self._connect_main_object(self._terminal) # create menu self._create_menu()
def _draw_title(self, ctx, w_dots, h_dots, font_face): """ Draw the title at the current position inside a w_dots*h_dots rectangle. Args: ctx (cairo.Context): The Cairo context to use to draw. w_dots,h_dots (number): Rectangle dimension (ciaro units) font_face (str): Pango font specification. """ # Title background ctx.save() ctx.set_source_rgb(0.8, 0.9, 0.96) # TODO: make title bar color configurable? ctx.rectangle(0, 0, w_dots, h_dots) ctx.fill() ctx.restore() # Retrieve and paint the OSM logo ctx.save() grp, logo_width = self._get_osm_logo(ctx, 0.8*h_dots) if grp: ctx.translate(w_dots - logo_width - 0.1*h_dots, 0.1*h_dots) ctx.set_source(grp) ctx.paint_with_alpha(0.5) else: LOG.warning("OSM Logo not available.") logo_width = 0 ctx.restore() # Retrieve and paint the extra logo # TODO: logo_width2 = 0 if self.rc.poi_file: ctx.save() grp, logo_width2 = self._get_extra_logo(ctx, 0.8*h_dots) if grp: ctx.translate(0.4*h_dots, 0.1*h_dots) ctx.set_source(grp) ctx.paint_with_alpha(0.5) logo_width2 += 0.4*h_dots else: LOG.warning("Extra Logo not available.") logo_width2 = 0 ctx.restore() # Prepare the title pc = PangoCairo.create_context(ctx) layout = PangoCairo.create_layout(ctx) layout.set_width(int((w_dots - 0.1*w_dots - logo_width - logo_width2) * Pango.SCALE)) if not self.rc.i18n.isrtl(): layout.set_alignment(Pango.Alignment.LEFT) else: layout.set_alignment(Pango.Alignment.RIGHT) fd = Pango.FontDescription(font_face) fd.set_size(Pango.SCALE) layout.set_font_description(fd) layout.set_text(self.rc.title, -1) draw_utils.adjust_font_size(layout, fd, layout.get_width(), 0.8*h_dots) # Draw the title ctx.save() ctx.set_line_width(1) ctx.rectangle(0, 0, w_dots, h_dots) ctx.stroke() ctx.translate(0.4*h_dots + logo_width2, (h_dots - (layout.get_size()[1] / Pango.SCALE)) / 2.0) PangoCairo.update_layout(ctx, layout) PangoCairo.show_layout(ctx, layout) ctx.restore()
def set_font(self, font): ''' Set the font for a label ''' self._fd = Pango.FontDescription(font)
def get_column_fonts(self): return [ Pango.FontDescription('Source Sans Pro {}'.format(42)), Pango.FontDescription('Source Sans Pro {}'.format(18)) ]
def set_font_size(self, font_size): self.modify_font( Pango.FontDescription('Monospace {}'.format(font_size)))
def _draw(self, cr, highlight, bounding, color=None): try: layout = self.layout except AttributeError: layout = PangoCairo.create_layout(cr) # set font options # see http://lists.freedesktop.org/archives/cairo/2007-February/009688.html context = layout.get_context() fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_DEFAULT) fo.set_hint_style(cairo.HINT_STYLE_NONE) fo.set_hint_metrics(cairo.HINT_METRICS_OFF) try: PangoCairo.context_set_font_options(context, fo) except TypeError: # XXX: Some broken pangocairo bindings show the error # 'TypeError: font_options must be a cairo.FontOptions or None' pass except KeyError: # cairo.FontOptions is not registered as a foreign # struct in older PyGObject versions. # https://git.gnome.org/browse/pygobject/commit/?id=b21f66d2a399b8c9a36a1758107b7bdff0ec8eaa pass # set font font = Pango.FontDescription() # https://developer.gnome.org/pango/stable/PangoMarkupFormat.html markup = GObject.markup_escape_text(self.text) if self.pen.bold: markup = '<b>' + markup + '</b>' if self.pen.italic: markup = '<i>' + markup + '</i>' if self.pen.underline: markup = '<span underline="single">' + markup + '</span>' if self.pen.strikethrough: markup = '<s>' + markup + '</s>' if self.pen.superscript: markup = '<sup><small>' + markup + '</small></sup>' if self.pen.subscript: markup = '<sub><small>' + markup + '</small></sub>' success, attrs, text, _ = Pango.parse_markup(markup, -1, '\x00') assert success layout.set_attributes(attrs) font.set_family(self.pen.fontname) font.set_absolute_size(self.pen.fontsize*Pango.SCALE) layout.set_font_description(font) # set text layout.set_text(text, -1) # cache it self.layout = layout else: PangoCairo.update_layout(cr, layout) descent = 2 # XXX get descender from font metrics width, height = layout.get_size() width = float(width)/Pango.SCALE height = float(height)/Pango.SCALE # we know the width that dot thinks this text should have # we do not necessarily have a font with the same metrics # scale it so that the text fits inside its box if width > self.w: f = self.w / width width = self.w # equivalent to width *= f height *= f descent *= f else: f = 1.0 y = self.y - height + descent if bounding is None or (y <= bounding[3] and bounding[1] <= y + height): x = self.x - 0.5 * (1 + self.j) * width cr.move_to(x, y) cr.save() cr.scale(f, f) if color is None: cr.set_source_rgba(*self.select_pen(highlight).color) else: cr.set_source_rgba(*color) PangoCairo.show_layout(cr, layout) cr.restore() if 0: # DEBUG # show where dot thinks the text should appear cr.set_source_rgba(1, 0, 0, .9) x = self.x - 0.5 * (1 + self.j) * width cr.move_to(x, self.y) cr.line_to(x+self.w, self.y) cr.stroke()
def _draw_copyright_notice(self, ctx, w_dots, h_dots, notice=None, osm_date=None): """ Draw a copyright notice at current location and within the given w_dots*h_dots rectangle. Args: ctx (cairo.Context): The Cairo context to use to draw. w_dots,h_dots (number): Rectangle dimension (ciaro units). font_face (str): Pango font specification. notice (str): Optional notice to replace the default. """ today = datetime.date.today() if notice is None: notice = _(u'Copyright © %(year)d MapOSMatic/OCitySMap developers.') notice+= ' ' notice+= _(u'Map data © %(year)d OpenStreetMap contributors (see http://osm.org/copyright)') notice+= '\n' annotations = [] if self.rc.stylesheet.annotation != '': annotations.append(self.rc.stylesheet.annotation) for overlay in self._overlays: if overlay.annotation != '': annotations.append(overlay.annotation) if len(annotations) > 0: notice+= _(u'Map styles:') notice+= ' ' + '; '.join(annotations) + '\n' datasources = set() if self.rc.stylesheet.datasource != '': datasources.add(self.rc.stylesheet.datasource) for overlay in self._overlays: if overlay.datasource != '': datasources.add(overlay.datasource) if len(datasources) > 0: notice+= _(u'Additional data sources:') notice+= ' ' + '; '.join(list(datasources)) + '\n' notice+= _(u'Map rendered on: %(date)s. OSM data updated on: %(osmdate)s.') notice+= ' ' notice+= _(u'The map may be incomplete or inaccurate.') # We need the correct locale to be set for strftime(). prev_locale = locale.getlocale(locale.LC_TIME) try: locale.setlocale(locale.LC_TIME, self.rc.i18n.language_code()) except Exception: LOG.warning('error while setting LC_COLLATE to "%s"' % self.rc.i18n.language_code()) try: if osm_date is None: osm_date_str = _(u'unknown') else: osm_date_str = osm_date.strftime("%d %B %Y %H:%M") notice = notice % {'year': today.year, 'date': today.strftime("%d %B %Y"), 'osmdate': osm_date_str} finally: locale.setlocale(locale.LC_TIME, prev_locale) ctx.save() pc = PangoCairo.create_context(ctx) fd = Pango.FontDescription('DejaVu') fd.set_size(Pango.SCALE) layout = PangoCairo.create_layout(ctx) layout.set_font_description(fd) layout.set_text(notice, -1) draw_utils.adjust_font_size(layout, fd, w_dots, h_dots) PangoCairo.update_layout(ctx, layout) PangoCairo.show_layout(ctx, layout) ctx.restore()
def update(self, other=None): """Update our contents""" default_bg = False if self.config['title_hide_sizetext']: self.label.set_text("%s" % self.termtext) else: self.label.set_text("%s %s" % (self.termtext, self.sizetext)) if (not self.config['title_use_system_font'] ) and self.config['title_font']: title_font = Pango.FontDescription(self.config['title_font']) else: title_font = Pango.FontDescription( self.config.get_system_prop_font()) self.label.modify_font(title_font) self.grouplabel.modify_font(title_font) if other: term = self.terminal terminator = self.terminator if other == 'window-focus-out': title_fg = self.config['title_inactive_fg_color'] title_bg = self.config['title_inactive_bg_color'] icon = '_receive_off' default_bg = True group_fg = self.config['title_inactive_fg_color'] group_bg = self.config['title_inactive_bg_color'] elif term != other and term.group and term.group == other.group: if terminator.groupsend == terminator.groupsend_type['off']: title_fg = self.config['title_inactive_fg_color'] title_bg = self.config['title_inactive_bg_color'] icon = '_receive_off' default_bg = True else: title_fg = self.config['title_receive_fg_color'] title_bg = self.config['title_receive_bg_color'] icon = '_receive_on' group_fg = self.config['title_receive_fg_color'] group_bg = self.config['title_receive_bg_color'] elif term != other and not term.group or term.group != other.group: if terminator.groupsend == terminator.groupsend_type['all']: title_fg = self.config['title_receive_fg_color'] title_bg = self.config['title_receive_bg_color'] icon = '_receive_on' else: title_fg = self.config['title_inactive_fg_color'] title_bg = self.config['title_inactive_bg_color'] icon = '_receive_off' default_bg = True group_fg = self.config['title_inactive_fg_color'] group_bg = self.config['title_inactive_bg_color'] else: # We're the active terminal title_fg = self.config['title_transmit_fg_color'] title_bg = self.config['title_transmit_bg_color'] if terminator.groupsend == terminator.groupsend_type['all']: icon = '_active_broadcast_all' elif terminator.groupsend == terminator.groupsend_type[ 'group']: icon = '_active_broadcast_group' else: icon = '_active_broadcast_off' group_fg = self.config['title_transmit_fg_color'] group_bg = self.config['title_transmit_bg_color'] self.label.modify_fg(Gtk.StateType.NORMAL, Gdk.color_parse(title_fg)) self.grouplabel.modify_fg(Gtk.StateType.NORMAL, Gdk.color_parse(group_fg)) self.modify_bg(Gtk.StateType.NORMAL, Gdk.color_parse(title_bg)) if not self.get_desired_visibility(): if default_bg == True: color = term.get_style_context().get_background_color( Gtk.StateType.NORMAL) # VERIFY FOR GTK3 else: color = Gdk.color_parse(title_bg) self.update_visibility() self.ebox.modify_bg(Gtk.StateType.NORMAL, Gdk.color_parse(group_bg)) self.set_from_icon_name(icon, Gtk.IconSize.MENU)
def _current_font_from_gsetting(self, *args): if settings.get_boolean('use-system-font'): font_string = interface_settings.get_string('monospace-font-name') else: font_string = settings.get_string('custom-font') return Pango.FontDescription(font_string)
def font_changed(self, settings=None, key=None): font = self.get_font() font_desc = Pango.font_description_from_string(font) self.set_font(font_desc)
def __init__(self, handle): """Set up the Words activity.""" activity.Activity.__init__(self, handle) self._dictd_data_dir = './dictd/' self._dictionaries = dictdmodel.Dictionaries(self._dictd_data_dir) self._origin_languages = self._dictionaries.get_all_languages_origin() self._origin_lang_options = {} for lang in self._origin_languages: self._origin_lang_options[lang] = dictdmodel.lang_codes[lang] self.max_participants = 1 toolbar_box = ToolbarBox() activity_button = ActivityToolbarButton(self) toolbar_box.toolbar.insert(activity_button, 0) toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ) activity_button.show() toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1) from_toolitem = Gtk.ToolItem() from_toolitem.add(Gtk.Label(_('From:'))) from_toolitem.show_all() toolbar_box.toolbar.insert(from_toolitem, -1) if 'origin' in self.metadata: origin = self.metadata['origin'] else: origin = 'eng' if 'destination' in self.metadata: destination = self.metadata['destination'] else: destination = 'spa' if 'searches' in self.metadata: self._searches = json.loads(self.metadata['searches']) else: self._searches = {} # Initial values | Valores iniciales self.origin_lang = origin self.destination_lang = destination self._dictionary = dictdmodel.Dictionary(self._dictd_data_dir, self.origin_lang, self.destination_lang) self._autosearch_timer = None self._english_dictionary = None self._alert = ErrorAlert() self._alert.props.title = _('Wait...') self._alert.props.msg = _('Loading dictionary data') self.add_alert(self._alert) self._alert.connect('response', self._alert_cancel_cb) self._alert.show() GObject.idle_add(self._init_english_dictionary) self._last_word_translated = None self._from_button = FilterToolItem('go-down', origin, self._origin_lang_options) self._from_button.connect("changed", self.__from_language_changed_cb) toolbar_box.toolbar.insert(self._from_button, -1) to_toolitem = Gtk.ToolItem() to_toolitem.add(Gtk.Label(' ' + _('To:'))) to_toolitem.show_all() toolbar_box.toolbar.insert(to_toolitem, -1) self._init_destination_language() self._to_button = FilterToolItem('go-down', self.destination_lang, self._destination_lang_options) self._to_button.connect("changed", self.__to_language_changed_cb) toolbar_box.toolbar.insert(self._to_button, -1) separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) toolbar_box.toolbar.insert(separator, -1) separator.show() stop_button = StopButton(self) toolbar_box.toolbar.insert(stop_button, -1) stop_button.show() self.set_toolbar_box(toolbar_box) toolbar_box.show() font_size = int(style.FONT_SIZE * 1.5) font = Pango.FontDescription("Sans %d" % font_size) # This box will change the orientaion when the screen rotates self._big_box = Gtk.Box(Gtk.Orientation.HORIZONTAL) self._big_box.set_homogeneous(True) self._big_box.set_margin_top(style.DEFAULT_SPACING) self._big_box.set_margin_bottom(style.DEFAULT_SPACING) lang1_container = Gtk.Grid() lang1_container.set_row_spacing(style.DEFAULT_SPACING) lang1_container.set_border_width(style.DEFAULT_SPACING) lang1_round_box = RoundBox() lang1_round_box.background_color = style.COLOR_BUTTON_GREY lang1_round_box.border_color = style.COLOR_BUTTON_GREY lang1_round_box.pack_start(lang1_container, True, True, style.DEFAULT_SPACING) self._big_box.pack_start(lang1_round_box, True, True, 0) # Labels label1 = Gtk.Label() label1.set_markup('<span font="%d" color="white">%s</span>' % (font_size, _("Word"))) label1.set_halign(Gtk.Align.START) lang1_container.attach(label1, 0, 0, 1, 1) speak1 = Gtk.ToolButton() speak1.set_icon_widget(Icon(icon_name='microphone')) speak1.set_halign(Gtk.Align.END) speak1.connect("clicked", self.__speak_word_cb) lang1_container.attach(speak1, 1, 0, 1, 1) # Text entry box to enter word to be translated self.totranslate = iconentry.IconEntry() self.totranslate.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY, 'entry-search') # self.search_entry.set_placeholder_text(text) self.totranslate.add_clear_button() self.totranslate.connect('activate', self.__totranslate_activated_cb) self._totranslate_changed_id = self.totranslate.connect( "changed", self.__totranslate_changed_cb) self.totranslate.modify_font(font) self.totranslate.set_hexpand(True) lang1_container.attach(self.totranslate, 0, 1, 2, 1) label1 = Gtk.Label() label1.set_markup('<span font="%d" color="white">%s</span>' % (font_size, _("Suggestions"))) label1.set_halign(Gtk.Align.START) lang1_container.attach(label1, 0, 2, 2, 1) # The "lang1" treeview box self._suggestions_model = Gtk.ListStore(str) suggest_treeview = Gtk.TreeView(self._suggestions_model) suggest_treeview.modify_font(font) suggest_treeview.set_enable_search(False) suggest_treeview.set_headers_visible(False) lang1cell = Gtk.CellRendererText() lang1cell.props.ellipsize_set = True lang1cell.props.ellipsize = Pango.EllipsizeMode.END lang1treecol = Gtk.TreeViewColumn("", lang1cell, text=0) self._suggestion_changed_cb_id = suggest_treeview.connect( 'cursor-changed', self.__suggestion_selected_cb) suggest_treeview.append_column(lang1treecol) scroll = Gtk.ScrolledWindow(hadjustment=None, vadjustment=None) scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) scroll.add(suggest_treeview) scroll.set_vexpand(True) lang1_container.attach(scroll, 0, 3, 2, 1) # This container have the result data result_container = Gtk.Grid() result_container.set_row_spacing(style.DEFAULT_SPACING) result_container.set_border_width(style.DEFAULT_SPACING) lang2_round_box = RoundBox() lang2_round_box.background_color = style.COLOR_BUTTON_GREY lang2_round_box.border_color = style.COLOR_BUTTON_GREY lang2_round_box.pack_start(result_container, True, True, style.DEFAULT_SPACING) self._big_box.pack_start(lang2_round_box, True, True, 0) # Text entry box to receive word translated label = Gtk.Label() label.set_markup('<span font="%d" color="white">%s</span>' % (font_size, _("Translation"))) label.set_halign(Gtk.Align.START) result_container.attach(label, 0, 0, 1, 1) speak2 = Gtk.ToolButton() speak2.set_icon_widget(Icon(icon_name='microphone')) speak2.set_halign(Gtk.Align.END) speak2.connect("clicked", self.__speak_translation_cb) result_container.attach(speak2, 1, 0, 1, 1) self.translated = Gtk.TextView() self.translated.modify_font(font) self.translated.set_buffer(Gtk.TextBuffer()) self.translated.set_left_margin(style.DEFAULT_PADDING) self.translated.set_wrap_mode(Gtk.WrapMode.WORD_CHAR) self.translated.set_editable(False) self.translated.modify_bg(Gtk.StateType.NORMAL, style.COLOR_TEXT_FIELD_GREY.get_gdk_color()) self.translated.modify_bg(Gtk.StateType.SELECTED, style.COLOR_SELECTION_GREY.get_gdk_color()) scrolled = Gtk.ScrolledWindow() scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) scrolled.add(self.translated) scrolled.set_hexpand(True) scrolled.set_size_request(-1, style.GRID_CELL_SIZE * 2) result_container.attach(scrolled, 0, 1, 2, 1) label = Gtk.Label() label.set_markup('<span font="%d" color="white">%s</span>' % (font_size, _("Dictionary"))) label.set_halign(Gtk.Align.START) result_container.attach(label, 0, 2, 1, 1) speak2 = Gtk.ToolButton() speak2.set_icon_widget(Icon(icon_name='microphone')) speak2.set_halign(Gtk.Align.END) speak2.connect("clicked", self.__speak_dictionary_cb) result_container.attach(speak2, 1, 2, 1, 1) self.dictionary = WebKit.WebView() self.dictionary.load_html_string(EMPTY_HTML, 'file:///') self.dictionary.set_zoom_level(0.75) settings = self.dictionary.get_settings() settings.set_property('enable-default-context-menu', False) self.dictionary.set_settings(settings) scrolled = Gtk.ScrolledWindow() scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) scrolled.add(self.dictionary) scrolled.set_hexpand(True) scrolled.set_vexpand(True) result_container.attach(scrolled, 0, 3, 2, 1) self._big_box.show_all() self.set_canvas(self._big_box) self.totranslate.grab_focus() self.show_all()
def make_window(): window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL) window.set_title("Window Focus") window.set_size_request(640, 200) window.set_position(Gtk.WindowPosition.CENTER) window.connect("delete_event", Gtk.main_quit) icon = get_icon_pixbuf("windows.png") if icon: window.set_icon(icon) vbox = Gtk.VBox() hbox = Gtk.HBox() def add_btn(label, cb): b = Gtk.Button(label=label) def bcb(*_args): cb() b.connect('clicked', bcb) hbox.add(b) def restack_above(): window.get_window().restack(None, True) add_btn("Restack Above", restack_above) def restack_below(): window.get_window().restack(None, False) add_btn("Restack Below", restack_below) def _raise(): window.get_window().raise_() add_btn("Raise", _raise) def _lower(): window.get_window().lower() add_btn("Lower", _lower) vbox.add(hbox) N = 8 labels = [] font = Pango.FontDescription("sans 12") for _ in range(N): l = Gtk.Label() l.modify_font(font) labels.append(l) for l in labels: al = Gtk.Alignment(xalign=0, yalign=0.5, xscale=0.0, yscale=0) al.add(l) vbox.add(al) window.add(vbox) window.show_all() text = deque(maxlen=N) def update(s): text.append("%s: %s" % (datetime.now(), s)) for i, t in enumerate(text): labels[i].set_text(t) #self.selectX11FocusChange(self) def focus_in(_window, event): update("focus-in-event") def focus_out(_window, event): update("focus-out-event") def has_toplevel_focus(window, _event): update("has-toplevel-focus: %s" % window.has_toplevel_focus()) window.connect("focus-in-event", focus_in) window.connect("focus-out-event", focus_out) window.connect("notify::has-toplevel-focus", has_toplevel_focus) if POSIX and not OSX: from xpra.gtk_common.error import xlog from xpra.x11.gtk_x11.gdk_display_source import init_gdk_display_source from xpra.x11.gtk_x11.gdk_bindings import init_x11_filter from xpra.x11.bindings.window_bindings import X11WindowBindings #pylint: disable=no-name-in-module from xpra.os_util import is_Wayland if not is_Wayland(): #x11 focus events: gdk_win = window.get_window() xid = gdk_win.get_xid() init_gdk_display_source() os.environ["XPRA_X11_DEBUG_EVENTS"] = "FocusIn,FocusOut" init_x11_filter() with xlog: X11WindowBindings().selectFocusChange(xid) return window