def draw_label(self, context, lod): layout, rect, cursor_rect, layout_pos = self._calc_layout_params() cursor_width = cursor_rect.h * 0.075 cursor_width = max(cursor_width, 1.0) label_rgba = self.get_label_color() context.save() context.rectangle(*rect) context.clip() # draw text context.set_source_rgba(*label_rgba) context.move_to(*layout_pos) PangoCairo.show_layout(context, layout) context.restore() # don't clip the caret # draw caret context.move_to(cursor_rect.x, cursor_rect.y) context.rel_line_to(0, cursor_rect.h) context.set_source_rgba(*label_rgba) context.set_line_width(cursor_width) context.stroke() # reset attributes; layout is reused by all keys due to memory leak layout.set_attributes(Pango.AttrList())
def create_fancy_attr_list_for_layout(self, layout): pango_ctx = layout.get_context() metrics = pango_ctx.get_metrics(layout.get_font_description(), None) ascent = metrics.get_ascent() logical_rect = Pango.Rectangle() logical_rect.x = 0 logical_rect.width = ascent logical_rect.y = -ascent logical_rect.height = ascent # Set fancy shape attributes for all hearts attrs = Pango.AttrList() # FIXME: attr_shape_new_with_data isn't introspectable ''' ink_rect = logical_rect p = BYTES_TEXT.find(BYTES_HEART) while (p != -1): attr = Pango.attr_shape_new_with_data(ink_rect, logical_rect, ord(HEART), None) attr.start_index = p attr.end_index = p + len(BYTES_HEART) p = UTF8_TEXT.find(HEART, attr.end_index) attrs.insert(attr) ''' return attrs
def append_info(self, selection=None): """Completes the profile auxiliar data on the right side of the box""" model, iterator = selection.get_selected() if not iterator: return None table = self.sidetable for child in table.get_children(): table.remove(child) profile = model.get_value(iterator, 0) row = 0 for track in profile.tracks: label = Gtk.Label(label=track.flavor + ": ") label.set_alignment(1, 0) label.set_width_chars(int(self.hprop * 15)) widget = Gtk.Label(label=track.name) widget.set_alignment(0, 0) widget.set_ellipsize(Pango.EllipsizeMode.END) alist = Pango.AttrList() #font = Pango.FontDescription(str(int(self.hprop*13))) #attr=Pango.AttrFontDesc(font,0,-1) #alist.insert(attr) label.set_attributes(alist) widget.set_attributes(alist) label.show() widget.show() table.attach(label, 0, 1, row, row + 1, Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, False, 0, 0) table.attach(widget, 1, 2, row, row + 1, Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, False, 0, 0) row += 1
def create_tab_label(self, title, tab_child): box = Gtk.HBox(False, 1) # Tab text label #label = Gtk.Label(label='Terminal') label = Gtk.Label(label=title) small = Pango.AttrScale(Pango.SCALE_SMALL, 0, -1) label_attributes = Pango.AttrList() label_attributes.insert(small) label.set_attributes(label_attributes) label.set_ellipsize(Pango.EllipsizeMode.START) label.set_width_chars(9) # Tab terminal icon icon = Gtk.Image() icon.set_from_file( os.path.join('lib', 'ui', 'data', 'icons', 'terminal.png')) # Tab pseudo-close button eb = Gtk.EventBox() cross = Gtk.Image() cross.set_from_file( os.path.join('lib', 'ui', 'data', 'icons', 'cross.png')) cross.connect("realize", self._realize_cb) eb.add(cross) eb.connect('button_press_event', self.close_tab) # Pack en return the box box.pack_start(icon, False, False) box.pack_start(label, True, True) box.pack_start(eb, True, True) return box
def setStep(self, step): super(DistUpgradeViewGtk3, self).setStep(step) if self.icontheme.rescan_if_needed(): logging.debug("icon theme changed, re-reading") # first update the "previous" step as completed size = Gtk.IconSize.MENU attrlist = Pango.AttrList() if self.prev_step: image = getattr(self, "image_step%i" % self.prev_step.value) label = getattr(self, "label_step%i" % self.prev_step.value) arrow = getattr(self, "arrow_step%i" % self.prev_step.value) label.set_property("attributes", attrlist) image.set_from_stock(Gtk.STOCK_APPLY, size) image.show() arrow.hide() self.prev_step = step # show the an arrow for the current step and make the label bold image = getattr(self, "image_step%i" % step.value) label = getattr(self, "label_step%i" % step.value) arrow = getattr(self, "arrow_step%i" % step.value) # check if that step was not hidden with hideStep() if not label.get_property("visible"): return arrow.show() image.hide()
def _format_set(self, record, field): attrlist = Pango.AttrList() functions = { 'color': self._set_foreground, 'fg': self._set_foreground, 'bg': self._set_background, 'font': self._set_font } attrs = record.expr_eval( field.get_state_attrs(record).get('states', {})) states = record.expr_eval(self.attrs.get('states', {})).copy() states.update(attrs) for attr in list(states.keys()): if not states[attr]: continue key = attr.split('_') if key[0] == 'field': continue if key[0] == 'label': key = key[1:] if isinstance(states[attr], str): key.append(states[attr]) if key[0] in functions: if len(key) != 2: raise ValueError(common.FORMAT_ERROR + attr) functions[key[0]](key[1], attrlist) self.set_attributes(attrlist)
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 _set_column_widget(self, column, attributes, arrow=True, align=0.5): hbox = Gtk.HBox(homogeneous=False, spacing=2) label = Gtk.Label(label=attributes['string']) field = self.field_attrs.get(attributes['name'], {}) if field and self.view.editable: required = field.get('required') readonly = field.get('readonly') common.apply_label_attributes(label, readonly, required) attrlist = Pango.AttrList() self._format_set(attributes, attrlist) label.set_attributes(attrlist) label.show() help = attributes.get('help') if help: tooltips = Tooltips() tooltips.set_tip(label, help) tooltips.enable() if arrow: arrow_widget = Gtk.Image() arrow_widget.show() column.arrow = arrow_widget hbox.pack_start(label, expand=True, fill=True, padding=0) if arrow: hbox.pack_start(arrow_widget, expand=False, fill=False, padding=0) column.set_clickable(True) hbox.show() column.set_widget(hbox) column.set_alignment(align)
def undo_text_action(self, action, mode): self.undo.block() if action.undo_type == UndoManager.DELETE_LETTER or action.undo_type == UndoManager.DELETE_WORD: real_mode = not mode attrslist = [action.args[5], action.args[4]] else: real_mode = mode attrslist = [action.args[3], action.args[4]] self.bindex = action.args[0] self.index = self.index_from_bindex(self.bindex) self.end_index = self.index if real_mode == UndoManager.UNDO: attrs = attrslist[0] self.end_index = self.index + action.args[2] self.delete_char() else: attrs = attrslist[1] self.add_text(action.text) self.rebuild_byte_table() self.bindex = self.b_f_i(self.index) del self.attributes self.attributes = Pango.AttrList() for a in attrs: self.attributes.change(a) self.recalc_edges() self.emit("begin_editing") self.emit("title_changed", self.text) self.emit("update_view") self.emit("grab_focus", False) self.undo.unblock()
def _draw_typed(self, ctx, layout, hurigana): attr_list_preedit = Pango.AttrList().new() typed = get_prefix(self.engine.get_plain(), self.engine.get_typed()) correct_length = len(typed) typed = hurigana.adjust_typed(typed) formatted = '<span foreground="#0066CC">' + typed + '</span>' if correct_length < len(self.engine.get_typed()): formatted += '<span foreground="#FF0000" background="#FFCCFF">' + \ self.engine.get_typed()[correct_length:] + \ '</span>' typed += self.engine.get_typed()[correct_length:] preedit = self.engine.get_preedit() if preedit[0] and 0 < preedit[2]: attr_list_preedit.splice(preedit[1], len(typed.encode()), len(preedit[0][:preedit[2]].encode())) formatted += '<span foreground="#0066FF">' + preedit[ 0][:preedit[2]] + '</span>' typed += preedit[0][:preedit[2]] layout.set_markup(formatted, -1) if preedit[0] and 0 < preedit[2]: attr_list = layout.get_attributes() attr_list.splice(attr_list_preedit, 0, 0) layout.set_attributes(attr_list) PangoCairo.update_layout(ctx, layout) PangoCairo.show_layout(ctx, layout) return layout, typed
def _draw_typed(self, ctx, layout, hurigana): typed = get_prefix(self.engine.get_plain(), self.engine.get_typed()) correct_length = len(typed) typed = hurigana.adjust_typed(typed) attr_list = Pango.AttrList().new() formatted = typed so = 0 eo = len(formatted.encode()) attr = Pango.attr_foreground_new(0x0000, 0x6600, 0xcc00) attr.start_index = so attr.end_index = eo attr_list.insert(attr) if correct_length < len(self.engine.get_typed()): typed += self.engine.get_typed()[correct_length:] formatted += self.engine.get_typed()[correct_length:] so = eo eo = so + len( self.engine.get_typed()[correct_length:].encode()) attr = Pango.attr_background_new(0xff00, 0xcc00, 0xff00) attr.start_index = so attr.end_index = eo attr_list.insert(attr) attr = Pango.attr_foreground_new(0xff00, 0x0000, 0x0000) attr.start_index = so attr.end_index = eo attr_list.insert(attr) preedit = self.engine.get_preedit() if preedit[0] and 0 < preedit[2]: typed += preedit[0][:preedit[2]] formatted += preedit[0][:preedit[2]] so = eo eo = so + len(preedit[0][:preedit[2]].encode()) attr = Pango.attr_foreground_new(0x0000, 0x6600, 0xff00) attr.start_index = so attr.end_index = eo attr_list.insert(attr) # Note with Pango 1.48, the following splice() does not work # as expected. It works with Pango 1.44, though. So we will # manually marge preedit attributes into attr_list: # attr_list.splice(preedit[1], so, 0) attributes = preedit[1].get_attributes() for i in attributes: i.start_index += so i.end_index += so attr_list.change(i) layout.set_text(formatted, -1) layout.set_attributes(attr_list) PangoCairo.update_layout(ctx, layout) PangoCairo.show_layout(ctx, layout) return layout, typed
def __init__(self, lbl, is_active=False): gtk.ImageMenuItem.__init__(self) self.label = gtk.Label(lbl) if is_active: atrlist = Pango.AttrList() atrlist.insert(Pango.AttrWeight(Pango.WEIGHT_BOLD, 0, 50)) self.label.set_attributes(atrlist) self.label.set_alignment(0, 0) self.add(self.label) self.label.show()
def _set_list_renderers(self): self._now_playing_column.set_cell_data_func( self._now_playing_cell, self._on_list_widget_icon_render, None) self._star_handler = StarHandlerWidget(self, 6) self._star_handler.add_star_renderers(self._star_column) attrs = Pango.AttrList() attrs.insert(Pango.AttrFontFeatures.new("tnum=1")) self._duration_renderer.props.attributes = attrs
def __init__(self, lbl, is_active=False): Gtk.ImageMenuItem.__init__(self) self.label = Gtk.Label(lbl) if is_active: atrlist = Pango.AttrList() #atrlist.insert(Pango.Weight(Pango.Weight.BOLD, 0, 50)) self.label.set_attributes(atrlist) self.label.set_justify(Gtk.Justification.LEFT) self.label.set_alignment(0, 0) self.add(self.label) self.label.show()
def _layer_name_text_datafunc(self, column, cell, model, it, data): """Show the layer name, with italics for layer groups""" layer = model.get_layer(it=it) markup = self._layer_description_markup(layer) 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 _createLayout(self, text): """Produces a Pango layout describing this text in this __font""" # create layout layout = Pango.Layout(Gdk.pango_context_get()) layout.set_font_description(self.fd) if self.underline: attrs = layout.get_attributes() if not attrs: attrs = Pango.AttrList() attrs.insert(Pango.AttrUnderline(Pango.Underline.SINGLE, 0, 32767)) layout.set_attributes(attrs) layout.set_text(text) return layout
def getLabel(self, text, font, color, align): lbl = Gtk.Label() lbl.set_markup(text) fd = Pango.FontDescription(font) attrlist = Pango.AttrList() attrlist.insert(Pango.attr_family_new(fd.get_family())) attrlist.insert(Pango.attr_style_new(fd.get_style())) attrlist.insert(Pango.attr_size_new(fd.get_size())) fgColor = Gdk.color_parse(color) attrlist.insert( Pango.attr_foreground_new(fgColor.red, fgColor.green, fgColor.blue)) lbl.set_attributes(attrlist) lbl.set_halign(align) return lbl
def _layout_text(self, cr, buffer): attr_list = Pango.AttrList().new() text = self.text current = self.current if self._has_preedit(): text = text[:current] + self.preedit[0] + text[current:] attr_list.splice(self.preedit[1], len(text[:current].encode()), len(self.preedit[0].encode())) current += self.preedit[2] layout = PangoCairo.create_layout(cr) desc = Pango.font_description_from_string(self.font) layout.set_font_description(desc) layout.set_text(text, -1) layout.set_attributes(attr_list) PangoCairo.update_layout(cr, layout) return layout, text, current
def __init__(self, dial_group=None, window_group=None, window_title="", additional_text=None, actionok=None, actioncancel=None): Gtk.Dialog.__init__(self, window_title, None, Gtk.DialogFlags.DESTROY_WITH_PARENT, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) if window_group is not None: window_group.add_window(self) self.set_resizable(False) self.connect("close", self.respond, actionok, actioncancel) self.connect("response", self.respond, actionok, actioncancel) self.connect("window-state-event", self.window_attn) self.set_default_response(Gtk.ResponseType.OK) hbox = Gtk.HBox(False, 20) hbox.set_border_width(20) self.vbox.pack_start(hbox, True, True, 0) hbox.show() image = Gtk.Image() image.set_from_stock(Gtk.STOCK_DIALOG_WARNING, Gtk.IconSize.DIALOG) hbox.pack_start(image, True, True, 0) image.show() vbox = Gtk.VBox() vbox.set_spacing(8) hbox.pack_start(vbox, True, True, 0) vbox.show() if additional_text is not None: if type(additional_text) is str: additional_text = additional_text.splitlines() for each in additional_text: label = Gtk.Label() attrlist = Pango.AttrList() attrlist.insert(Pango.AttrSize(12500, 0, len(each))) label.set_attributes(attrlist) label.set_text(each) vbox.add(label) label.show() if dial_group is not None: dial_group.add(self) self.dial_group = dial_group
def __init__(self, parent=None, size=(1920, 1080)): self.superior = parent wprop = size[0] / 1920.0 hprop = size[1] / 1080.0 self.wprop = wprop self.hprop = hprop #GObject.__init__(self, False, int(wprop*5)) GObject.GObject.__init__(self) self.set_border_width(int(wprop * 20)) self.vbox = Gtk.VBox(False, 0) self.buttons = Gtk.VButtonBox() self.buttons.set_layout(Gtk.ButtonBoxStyle.START) self.buttons.set_spacing(int(wprop * 5)) scrolled = Gtk.ScrolledWindow() scrolled.set_shadow_type(Gtk.ShadowType.ETCHED_IN) self.list, self.view = self.prepare_view() self.view.get_selection().connect("changed", self.append_info) scrolled.add(self.view) sidebox = Gtk.VBox(False, 0) frame = Gtk.Frame() label = Gtk.Label(label=_("Profile Tracks")) alist = Pango.AttrList() #font = Pango.FontDescription("bold "+str(int(self.hprop*15))) #attr=Pango.AttrFontDesc(font,0,-1) #alist.insert(attr) label.set_attributes(alist) frame.set_label_widget(label) frame.set_label_align(0.5, 0.5) frame.set_shadow_type(Gtk.ShadowType.ETCHED_IN) align = Gtk.Alignment.new(1, 0.5, 0.95, 0.9) self.sidetable = Gtk.Table(homogeneous=True) self.sidetable.set_size_request(int(wprop * 300), -1) align.add(self.sidetable) frame.add(align) self.vbox.pack_end(scrolled, True, True, 0) self.pack_start(self.vbox, True, True, 0) sidebox.pack_start(self.buttons, False, False, int(hprop * 10)) sidebox.pack_start(frame, False, False, int(hprop * 15)) self.pack_start(sidebox, False, False, int(wprop * 15))
def resize(self): """Adapts GUI elements to the screen size""" buttonlist = [ "playbutton", "editbutton", "ingestbutton", "deletebutton" ] size = context.get_mainwindow().get_size() wprop = size[0] / 1920.0 hprop = size[1] / 1080.0 vbar = self.scroll.get_vscrollbar() vbar.set_size_request(int(wprop * 6), -1) self.renders[0].set_property('height', int(hprop * 40)) self.renders[0].set_property('width-chars', int(wprop * 56)) #name self.renders[1].set_property('width-chars', int(wprop * 14)) #size self.renders[2].set_property('width-chars', int(wprop * 10)) #duration self.renders[3].set_property('width-chars', int(wprop * 23)) #date self.renders[5].set_property('width-chars', int(wprop * 27)) #presenter self.renders[6].set_property('width-chars', int(wprop * 33.5)) #series #self.renders[7].set_property('width-chars',int(wprop*12.5))#statusess self.renders[8].set_property('width-chars', int(wprop * 14)) #operations less fsize = 12 * hprop for cell in self.renders: font = Pango.FontDescription(str(fsize)) cell.set_property('font-desc', font) for column in self.vista.get_columns(): first = column.get_widget() if not first: label = Gtk.Label(label=" " + column.get_title()) else: label = column.get_widget() attr = Pango.AttrList() # attr.insert(Pango.AttrFontDesc(font,0,-1)) label.set_attributes(attr) if not first: label.show() column.set_widget(label) column.queue_resize() self.do_resize(buttonlist) return True
def addLabel( self, text, styles = None ): label = Gtk.Label() if "<b>" in text or "<span" in text: label.set_markup(text.replace('&', '&')) # don't remove our pango else: label.set_text(text) if styles: labelStyle = Pango.AttrList() for attr in styles: labelStyle.insert( attr ) label.set_attributes( labelStyle ) label.set_ellipsize( Pango.EllipsizeMode.END ) label.set_alignment( 0.0, 1.0 ) label.set_max_width_chars(0) label.show() self.labelBox.pack_start( label , True, True, 0)
def print_text(context, text="", rect={'x': 0, 'y': 0, 'w': 1, 'h': 1}, font="", font_name="", font_style="", font_size=None, align=TOP_LEFT, border=4, letter_spacing=[(0,0)],scale=0): """ print_text(context, text, rect,font,font_name,font_style, font_size,align, border, letter_spacing) context is cairo.Context text is any types rect is dict type {'x': int, 'y': int, 'w': int, 'h': int} font is string font description, example:'Ubuntu Normal 10' -- Ubuntu - font name, Normal - style, 10-size if font != "" then font_name,font_style,font_size do not used! font_name is string font_style is string font_size is int align is int see align types border is int border size letter_spacing is list of tuple letter_spacing size,example: letter_spacing=[(2,3)(5,5)(10,0)] after the 2nd character letter spacing is 5 after the 5th character letter spacing is 5 after the 10th character letter spacing reset to 0 """ context.save() font = font or " ".join([font_name, font_style, str(font_size)]) or Gtk.Style().font_desc.to_string() layout = pangocairo.CairoContext.create_layout(context) desc = Pango.FontDescription(font) layout.set_font_description(desc) attr_list=Pango.AttrList() if len(letter_spacing): for i in letter_spacing: attr = Pango.AttrLetterSpacing(int(i[1]*Pango.SCALE),i[0],len(text)) attr_list.insert(attr) layout.set_attributes(attr_list) layout.set_markup(str(text)) pangocairo.CairoContext.update_layout(context, layout) lw, lh = layout.get_size() lw /= Pango.SCALE lh /= Pango.SCALE context_align(context,rect,align,lw,lh,border) pangocairo.CairoContext.show_layout(context, layout) context.restore()
def do_draw(self, context): self.context = context context.set_antialias(self.compositing) (w, h) = self.get_size() # Make background transparent context.set_source_rgba(0.0, 0.0, 0.0, 0.4) # Don't layer drawing over each other, always replace self.col(self.bg_col) context.paint() context.set_operator(cairo.OPERATOR_OVER) self.col(self.fg_col) if not self.connected: return long_string = "" for line in self.content: col = "#fff" if 'nick_col' in line and line['nick_col']: col = line['nick_col'] long_string = "%s\n<span foreground='%s'>%s</span>: %s" % ( long_string, self.santize_string(col), self.santize_string( line["nick"]), self.santize_string(line["content"])) layout = self.create_pango_layout(long_string) layout.set_markup(long_string, -1) attr = Pango.AttrList() layout.set_width(Pango.SCALE * w) layout.set_spacing(Pango.SCALE * 3) if (self.text_font): font = Pango.FontDescription("%s %s" % (self.text_font, self.text_size)) layout.set_font_description(font) tw, th = layout.get_pixel_size() context.move_to(0, -th + h) PangoCairo.show_layout(context, layout)
def __init__(self, coords, Pango_context, thought_number, save, undo, loading, name="thought"): super(TextThought, self).__init__(save, name, undo) self.index = 0 self.end_index = 0 self.bytes = "" self.bindex = 0 self.text_location = coords self.text_element = save.createTextNode("GOOBAH") self.element.appendChild(self.text_element) self.layout = None self.identity = thought_number self.Pango_context = Pango_context self.moving = False self.preedit = None self.attrlist = None self.attributes = Pango.AttrList() self.current_attrs = [] if prefs.get_direction() == Gtk.TextDirection.LTR: self.Pango_context.set_base_dir(Pango.Direction.LTR) else: self.Pango_context.set_base_dir(Pango.Direction.RTL) self.b_f_i = self.bindex_from_index margin = utils.margin_required(utils.STYLE_NORMAL) if coords: self.ul = (coords[0] - margin[0], coords[1] - margin[1]) else: self.ul = None self.all_okay = True
def main(args) -> int: # open output archive with tarfile.open(args.out, "w:xz") as tar: for lang in languages(args.podir): # these are the 1.6:1 of some common(ish) screen widths if lang == "en": label_translated: str = args.label else: potfile = PotFile( os.path.join(args.podir, "{}.po".format(lang))) try: label_translated = potfile.msgs[args.label] except KeyError as _: continue if label_translated == args.label: continue for width, height in ( (640, 480), (800, 600), (1024, 768), (1280, 720), (1280, 800), (1366, 768), (1536, 864), (1600, 900), (1920, 1080), (1920, 1200), (2160, 1350), (2560, 1440), (3840, 2160), (5120, 2880), (5688, 3200), (7680, 4320), ): # generate PangoLanguage font_desc = "Sans %.2fpx" % (height / 32, ) fd = Pango.FontDescription(font_desc) font_option = cairo.FontOptions() font_option.set_antialias(cairo.ANTIALIAS_SUBPIXEL) l = Pango.Language.from_string(lang) # create surface img = cairo.ImageSurface(cairo.FORMAT_RGB24, 1, 1) cctx = cairo.Context(img) layout = PangoCairo.create_layout(cctx) pctx = layout.get_context() pctx.set_font_description(fd) pctx.set_language(l) fs = pctx.load_fontset(fd, l) PangoCairo.context_set_font_options(pctx, font_option) attrs = Pango.AttrList() length = len(bytes(label_translated, "utf8")) items = Pango.itemize(pctx, label_translated, 0, length, attrs, None) gs = Pango.GlyphString() Pango.shape(label_translated, length, items[0].analysis, gs) del img, cctx, pctx, layout def find_size(fs, f, data): """ find our size, I hope... """ (ink, log) = gs.extents(f) if ink.height == 0 or ink.width == 0: return False data.update({"log": log, "ink": ink}) return True data: Dict[str, Any] = {} fs.foreach(find_size, data) if len(data) == 0: print("Missing sans fonts") return 2 log = data["log"] ink = data["ink"] surface_height = math.ceil( max(ink.height, log.height) / Pango.SCALE) surface_width = math.ceil( max(ink.width, log.width) / Pango.SCALE) x = -math.ceil(log.x / Pango.SCALE) y = -math.ceil(log.y / Pango.SCALE) img = cairo.ImageSurface(cairo.FORMAT_RGB24, surface_width, surface_height) cctx = cairo.Context(img) layout = PangoCairo.create_layout(cctx) pctx = layout.get_context() PangoCairo.context_set_font_options(pctx, font_option) cctx.set_source_rgb(1, 1, 1) cctx.move_to(x, y) def do_write(fs, f, data): """ write out glyphs """ ink = gs.extents(f)[0] if ink.height == 0 or ink.width == 0: return False PangoCairo.show_glyph_string(cctx, f, gs) return True fs.foreach(do_write, None) img.flush() # convert to BMP and add to archive with io.BytesIO() as io_bmp: io_bmp.write(_cairo_surface_write_to_bmp(img)) filename = "fwupd-{}-{}-{}.bmp".format(lang, width, height) tarinfo = tarfile.TarInfo(filename) tarinfo.size = io_bmp.tell() io_bmp.seek(0) tar.addfile(tarinfo, fileobj=io_bmp) # success return 0
def __init__(self, parent, tracks, current_position=0, with_extras=False): """ :param parent: the parent window for modal operation :type parent: :class:`Gtk.Window` :param tracks: the tracks to process :type tracks: list of :class:`xl.trax.Track` objects :param current_position: the position of the currently selected track in the list :type current_position: int :param with_extras: whether there are extra, non-selected tracks in `tracks` (currently happens when only 1 track is selected) :type with_extras: bool """ GObject.GObject.__init__(self) self.builder = Gtk.Builder() self.builder.add_from_file( xdg.get_data_path('ui', 'trackproperties_dialog.ui')) self.builder.connect_signals(self) self.dialog = self.builder.get_object('TrackPropertiesDialog') self.dialog.set_transient_for(parent) self.__default_attributes = Pango.AttrList() self.__changed_attributes = Pango.AttrList() self.message = dialogs.MessageBar( parent=self.builder.get_object('main_content'), buttons=Gtk.ButtonsType.CLOSE, ) self.remove_tag_button = self.builder.get_object('remove_tag_button') self.cur_track_label = self.builder.get_object('current_track_label') self.apply_button = self.builder.get_object('apply_button') self.prev_button = self.builder.get_object('prev_track_button') self.next_button = self.builder.get_object('next_track_button') self.tags_grid = self.builder.get_object('tags_grid') self.properties_grid = self.builder.get_object('properties_grid') self.rows = [] self.new_tag_combo = self.builder.get_object('new_tag_combo') self.new_tag_combo_list = Gtk.ListStore(str, str) for tag, tag_info in tag_data.items(): if tag_info is not None and tag_info.editable: self.new_tag_combo_list.append((tag, tag_info.translated_name)) self.new_tag_combo_list.set_sort_column_id(1, Gtk.SortType.ASCENDING) self.new_tag_combo.set_model(self.new_tag_combo_list) self.add_tag_button = self.builder.get_object('add_tag_button') self.add_tag_button.set_sensitive(False) # Show these tags for all tracks, no matter what def_tags = [ 'tracknumber', 'title', 'artist', 'albumartist', 'album', 'discnumber', 'date', 'genre', 'cover', 'comment', '__startoffset', '__stopoffset', 'lyrics', ] self.def_tags = OrderedDict([(tag, tag_data[tag]) for tag in def_tags]) # Store the tracks and a working copy self.tracks = tracks self.trackdata = self._tags_copy(tracks) self.trackdata_original = self._tags_copy(tracks) self.current_position = current_position self._build_from_track(self.current_position) self._setup_position() self.dialog.show() self.rows[0].field.grab_focus()
class KLTContainerLabel(object): width = 210_000 height = 74_000 def __init__(self, label_font=None, data_font=None, long_data_font=None, large_data_font=None, large_long_data_font=None, description_fonts=None): if description_fonts is None: basic_font = Pango.font_description_from_string("Fira Sans") description_fonts = [] for font_size in (16_000, 14_000, 12_000, 10_000, 8_000): font = basic_font.copy() font.set_absolute_size(font_size * Pango.SCALE) description_fonts.append(font) del font del basic_font if label_font is None: label_font = Pango.font_description_from_string("Fira Sans Condensed") label_font.set_absolute_size(2_500 * Pango.SCALE) if data_font is None: data_font = Pango.font_description_from_string("Fira Sans") data_font.set_absolute_size(5_000 * Pango.SCALE) if long_data_font is None: long_data_font = Pango.font_description_from_string("Fira Sans Compressed") long_data_font.set_absolute_size(4_500 * Pango.SCALE) if large_data_font is None: large_data_font = Pango.font_description_from_string("Fira Sans") large_data_font.set_absolute_size(8_000 * Pango.SCALE) if large_long_data_font is None: large_long_data_font = Pango.font_description_from_string("Fira Sans Compressed") large_long_data_font.set_absolute_size(8_000 * Pango.SCALE) tnum_attrs = Pango.AttrList() tnum_attrs.insert(Pango.attr_font_features_new("tnum")) font_settings = { "label_font": label_font, "data_font": data_font, "long_data_font": long_data_font } large_font_settings = { "label_font": label_font, "data_font": large_data_font, "long_data_font": large_long_data_font } self._position_field = SplitField(35_000, 2_000, 130_000, 10_000, sub_fields=( TextField(0, 0, 17_000, 10_000, '(1a) Site', show_borders=False, alignment=Alignment.CENTER, only_uppercase=True, **large_font_settings), TextField(17_000, 0, 17_000, 10_000, '(1b) Rack', show_borders=False, alignment=Alignment.CENTER, only_uppercase=True, **large_font_settings), TextField(34_000, 0, 17_000, 10_000, '(1c) Slot', show_borders=False, alignment=Alignment.CENTER, only_uppercase=True, **large_font_settings), )) self._policy_field = SplitField(35_000, 59_000, 130_000, 10_000, sub_fields=( TextField(0, 0, 25_000, 10_000, '(5) Richtlinie', show_borders=False, alignment=Alignment.CENTER, **font_settings), TextField(30_000, 0, 50_000, 10_000, '(6) Verantwortung', show_borders=False, alignment=Alignment.LEFT, **font_settings))) self._id_field = TextField(165_000, 2_000, 40_000, 10_000, '(2) Behälter-Nr.', alignment=Alignment.CENTER, only_uppercase=True, text_attributes=tnum_attrs, **large_font_settings) self._id_barcode_field = BarcodeField(165_000, 59_000, 40_000, 10_000, '(2) Behälter-Nr.', label_font=label_font) self._url_field = QRCodeField(5_000, 39_000, 30_000, 30_000, label_font=label_font) self._description_field = TextField(35_000, 12_000, 170_000, 47_000, '(4) Bezeichnung Inhalt', allow_markup=True, alignment=Alignment.CENTER, vertical_alignment=Alignment.CENTER, data_fonts=description_fonts, label_font=label_font) self._org_field = TextField(5_000, 32_000, 30_000, 7_000, '(3) Organisation', padding=(250, 250, 0, 250), only_uppercase=True, **font_settings) self._logo_field = ImageField(5_000, 2_000, 30_000, 30_000, label_font=label_font)
def backspace_char(self): if self.index == self.end_index == 0: return if self.index > self.end_index: self.index, self.end_index = self.end_index, self.index if self.index != self.end_index: left = self.text[:self.index] right = self.text[self.end_index:] bleft = self.bytes[:self.b_f_i(self.index)] bright = self.bytes[self.b_f_i(self.end_index):] local_text = self.text[self.index:self.end_index] local_bytes = self.bytes[self.b_f_i(self.index):self. b_f_i(self.end_index)] change = -len(local_text) else: left = self.text[:self.index - int(self.bytes[self.bindex - 1])] right = self.text[self.index:] bleft = self.bytes[:self.b_f_i(self.index) - 1] bright = self.bytes[self.b_f_i(self.index):] local_text = self.text[self.index - int(self.bytes[self.bindex - 1]):self.index] local_bytes = self.bytes[self.b_f_i(self.index) - 1] self.index -= int(self.bytes[self.bindex - 1]) change = -len(local_text) old_attrs = [] changes = [] accounted = -change for l, (start, end) in wrap_attriterator(self.attributes.get_iterator()): if end <= self.index: for x in l: old_attrs.append(x.copy()) changes.append(x) elif start < self.index and end <= self.end_index: # partial ending for x in l: old_attrs.append(x.copy()) accounted -= (x.end_index - self.index) x.end_index -= (x.end_index - self.index) changes.append(x) elif start <= self.index and end >= self.end_index: # Swallow whole accounted -= (end - start) for x in l: old_attrs.append(x.copy()) x.end_index += change changes.append(x) elif start < self.end_index and end > self.end_index: # partial beginning for x in l: old_attrs.append(x.copy()) accounted -= (x.start_index - self.index) x.start_index = self.index x.end_index = x.start_index + (end - start) - accounted changes.append(x) else: # Past for x in l: old_attrs.append(x.copy()) x.start_index += change x.end_index += change changes.append(x) del self.attributes self.attributes = Pango.AttrList() for a in changes: self.attributes.change(a) self.text = left + right self.bytes = bleft + bright self.end_index = self.index self.undo.add_undo( UndoManager.UndoAction(self, UndoManager.DELETE_LETTER, self.undo_text_action, self.b_f_i(self.index), local_text, len(local_text), local_bytes, old_attrs, changes)) if self.index < 0: self.index = 0
def add_text(self, string): if self.index > self.end_index: self.index, self.end_index = self.end_index, self.index left = self.text[:self.index] right = self.text[self.end_index:] bleft = self.bytes[:self.b_f_i(self.index)] bright = self.bytes[self.b_f_i(self.end_index):] change = self.index - self.end_index + len(string) # Rather a hack: font descriptions override bold/italic attributes, so # we pull them out and set them before other changes. changes = [] fontdesc_changes = [] def cache_change(x): if x.type == Pango.ATTR_FONT_DESC: fontdesc_changes.append(x) else: changes.append(x) for x in self.current_attrs: x.start_index = self.index x.end_index = self.index + len(string) cache_change(x) old_attrs = [] it = wrap_attriterator(self.attributes.get_iterator()) for attrs, (start, end) in it: if start <= self.index: if end > self.end_index: # Inside range for x in attrs: old_attrs.append(x.copy()) x.end_index += change cache_change(x) else: for x in attrs: old_attrs.append(x.copy()) cache_change(x) else: if end > self.end_index: for x in attrs: old_attrs.append(x.copy()) x.end_index += change x.start_index += change cache_change(x) else: for x in attrs: old_attrs.append(x.copy()) cache_change(x) del self.attributes self.attributes = Pango.AttrList() for x in fontdesc_changes + changes: self.attributes.change(x) self.text = left + string + right self.undo.add_undo( UndoManager.UndoAction(self, UndoManager.INSERT_LETTER, self.undo_text_action, self.bindex, string, len(string), old_attrs, changes)) self.index += len(string) self.bytes = bleft + str(len(string)) + bright self.bindex = self.b_f_i(self.index) self.end_index = self.index