def getTopExents(self, attr_list, text): c = pango.FontMap.create_context(pangocairo.cairo_font_map_get_default()) l = pango.Layout(c) l.set_attributes(attr_list) l.set_text(text) line = l.get_line(0) return (line.get_pixel_extents()[1][3]-line.get_pixel_extents()[0][3]) * (self.input_resolution/self.output_resolution)
def draw_image(self, temp_data): """ Draw image file from text file """ surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1220, 620) context = cairo.Context(surf) context.rectangle(0, 0, 1220, 620) # draw a background rectangle: context.set_source_rgb(1, 1, 1) context.fill() font_map = pangocairo.cairo_font_map_get_default() families = font_map.list_families() context.translate(150, 55) pangocairo_context = pangocairo.CairoContext(context) pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pangocairo_context.create_layout() fontname = sys.argv[1] if len(sys.argv) >= 2 else "Sans" font = pango.FontDescription(fontname + " 25") layout.set_font_description(font) layout.set_text(temp_data) context.set_source_rgb(0, 0, 0) pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout) with open("wallnote.png", "wb") as image_file: surf.write_to_png(image_file) path = os.path.join(os.getcwd(), "wallnote.png") fd = os.popen( "gsettings set org.gnome.desktop.background picture-uri file:///{}".format(path)) fd.close()
def generate_images(opts,args): # Set up variables for drawing space width = 2550 # Will resize to match text; default 8.5"x11" @ 300dpi height = 3300 MARGIN_X = 300 MARGIN_Y = 300 LINE_SPACE = 35 #TODO: Command-line opts LANG = "ka" TESS_LANG = "kat" # Set up decent spacing for box files attrs = pango.AttrList() #TODO: Command line opts or config attrs.insert(pango.AttrLanguage(LANG,0,-1)) attrs.insert(pango.AttrLetterSpacing(10000,0,-1)) attrs.insert(pango.AttrSize(48000,0,-1)) attrs.insert(pango.AttrFallback(False,0,-1)) attrs.insert(pango.AttrStyle(pango.STYLE_NORMAL,0,-1)) attrs.insert(pango.AttrWeight(pango.WEIGHT_NORMAL,0,-1)) attrs.insert(pango.AttrUnderline(pango.UNDERLINE_NONE,0,-1)) # Instantiate Cairo surface and context surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = pangocairo.CairoContext(cairo.Context(surf)) # Instantiate PangoCairo context context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) #get font families: font_map = pangocairo.cairo_font_map_get_default() # to see family names: if opts.list_fonts: print [f.get_name() for f in font_map.list_families()]
def __initialize_font_list(self): """ Construct font list """ def compare_data(model, iter1, iter2): """ Sorting function for the fonts list store """ data1 = model.get_value(iter1,0) data2 = model.get_value(iter2,0) return cmp(data1, data2) self.__fontlist=TreeViewFactory('list', ['str','markup'], [],treeview=self.__tview) # Get all system fonts self.__font_families=pangocairo.cairo_font_map_get_default().list_families() for family in self.__font_families: escaped=gobject.markup_escape_text(family.get_name()) markedup='<span face="%s">%s</span>' % (escaped,escaped) self.__fontlist.append([family.get_name(),markedup]) self.__tview.set_headers_visible(False) self.__tview.get_column(0).set_property('visible',False) self.__scroller.set_policy(gtk.POLICY_NEVER,gtk.POLICY_AUTOMATIC) self.__fontlist.storagemodel.set_sort_func(0,compare_data) self.__fontlist.storagemodel.set_sort_column_id(0,gtk.SORT_ASCENDING)
def use_pango_font(font, start, count, will_call_prepost=False): import pango, cairo, pangocairo fontDesc = pango.FontDescription(font) a = array.array('b', itertools.repeat(0, 256*256)) surface = cairo.ImageSurface.create_for_data(a, cairo.FORMAT_A8, 256, 256) context = pangocairo.CairoContext(cairo.Context(surface)) layout = context.create_layout() fontmap = pangocairo.cairo_font_map_get_default() font = fontmap.load_font(fontmap.create_context(), fontDesc) layout.set_font_description(fontDesc) metrics = font.get_metrics() descent = metrics.get_descent() d = pango.PIXELS(descent) linespace = metrics.get_ascent() + metrics.get_descent() width = metrics.get_approximate_char_width() glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT) glPixelStorei(GL_UNPACK_SWAP_BYTES, 0) glPixelStorei(GL_UNPACK_LSB_FIRST, 1) glPixelStorei(GL_UNPACK_ROW_LENGTH, 256) glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 256) glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0) glPixelStorei(GL_UNPACK_SKIP_ROWS, 0) glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glPixelZoom(1, -1) base = glGenLists(count) for i in range(count): ch = unichr(start+i) layout.set_text(ch) w, h = layout.get_size() context.save() context.new_path() context.rectangle(0, 0, 256, 256) context.set_source_rgba(0., 0., 0., 0.) context.set_operator (cairo.OPERATOR_SOURCE); context.paint() context.restore() context.save() context.set_source_rgba(1., 1., 1., 1.) context.set_operator (cairo.OPERATOR_SOURCE); context.move_to(0, 0) context.update_layout(layout) context.show_layout(layout) context.restore() w, h = pango.PIXELS(w), pango.PIXELS(h) glNewList(base+i, GL_COMPILE) glBitmap(0, 0, 0, 0, 0, h-d, ''); if not will_call_prepost: pango_font_pre() if w and h: glDrawPixels(w, h, GL_LUMINANCE, GL_UNSIGNED_BYTE, a) glBitmap(0, 0, 0, 0, w, -h+d, ''); if not will_call_prepost: pango_font_post() glEndList() glPopClientAttrib() return base, pango.PIXELS(width), pango.PIXELS(linespace)
def use_pango_font(font, start, count, will_call_prepost=False): import pango, cairo, pangocairo fontDesc = pango.FontDescription(font) a = array.array('b', itertools.repeat(0, 256 * 256)) surface = cairo.ImageSurface.create_for_data(a, cairo.FORMAT_A8, 256, 256) context = pangocairo.CairoContext(cairo.Context(surface)) layout = context.create_layout() fontmap = pangocairo.cairo_font_map_get_default() font = fontmap.load_font(fontmap.create_context(), fontDesc) layout.set_font_description(fontDesc) metrics = font.get_metrics() descent = metrics.get_descent() d = pango.PIXELS(descent) linespace = metrics.get_ascent() + metrics.get_descent() width = metrics.get_approximate_char_width() glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT) glPixelStorei(GL_UNPACK_SWAP_BYTES, 0) glPixelStorei(GL_UNPACK_LSB_FIRST, 1) glPixelStorei(GL_UNPACK_ROW_LENGTH, 256) glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 256) glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0) glPixelStorei(GL_UNPACK_SKIP_ROWS, 0) glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glPixelZoom(1, -1) base = glGenLists(count) for i in range(count): ch = unichr(start + i) layout.set_text(ch) w, h = layout.get_size() context.save() context.new_path() context.rectangle(0, 0, 256, 256) context.set_source_rgba(0., 0., 0., 0.) context.set_operator(cairo.OPERATOR_SOURCE) context.paint() context.restore() context.save() context.set_source_rgba(1., 1., 1., 1.) context.set_operator(cairo.OPERATOR_SOURCE) context.move_to(0, 0) context.update_layout(layout) context.show_layout(layout) context.restore() w, h = pango.PIXELS(w), pango.PIXELS(h) glNewList(base + i, GL_COMPILE) glBitmap(0, 0, 0, 0, 0, h - d, '') if not will_call_prepost: pango_font_pre() if w and h: glDrawPixels(w, h, GL_LUMINANCE, GL_UNSIGNED_BYTE, a) glBitmap(0, 0, 0, 0, w, -h + d, '') if not will_call_prepost: pango_font_post() glEndList() glPopClientAttrib() return base, pango.PIXELS(width), pango.PIXELS(linespace)
def get_font_families(): ''' Get all font families in system. @return: Return font families list in current system. ''' fontmap = pangocairo.cairo_font_map_get_default() return map(lambda f: f.get_name(), fontmap.list_families())
def get_font_list(): """Returns a sorted list of all system font names""" font_map = pangocairo.cairo_font_map_get_default() font_list = [f.get_name() for f in font_map.list_families()] font_list.sort() return font_list
def get_font_families(): ''' Get all font families in system. @return: Return font families list in current system. ''' fontmap = pangocairo.cairo_font_map_get_default() return map (lambda f: f.get_name(), fontmap.list_families())
def getTopExents(self, attr_list, text): c = pango.FontMap.create_context( pangocairo.cairo_font_map_get_default()) l = pango.Layout(c) l.set_attributes(attr_list) l.set_text(text) line = l.get_line(0) return (line.get_pixel_extents()[1][3] - line.get_pixel_extents()[0][3] ) * (self.input_resolution / self.output_resolution)
def get_system_fonts(): # Currently this only works with the cairo backend if settings.IMPOSITIONS_BACKEND != 'cairo': raise NotImplementedError("Font listing does not work with the selected impositions backend.") import pangocairo font_map = pangocairo.cairo_font_map_get_default() font_list = [f.get_name() for f in font_map.list_families()] font_list.sort() return font_list
def __init__(self, image_scale = 1.0, image_width = None, image_height = None): super(CairoBackend, self).__init__(image_scale, image_width, image_height) self.set_margin(*(CairoBackend.DEFAULT_MARGIN)) self.set_image_size(0, 0) self.__surfaces = [] self.__ctx = None self.__drawn_graph = None self.__font_map = pangocairo.cairo_font_map_get_default() self.__available_font_names = [f.get_name() for f in self.__font_map.list_families()] return
def get_font_families(filter_terminal_font=False): '''Get all font families in system.''' fontmap = pangocairo.cairo_font_map_get_default() font_families = fontmap.list_families() if filter_terminal_font: font_families = filter( lambda f: f.is_monospace() or f.get_name() == "文泉驿ç‰å®½å¾®ç±³é»‘", filter( lambda f: not f.get_name() in ["Droid Sans Japanese", "MT Extra", "Monospace"], font_families)) return sorted(map(lambda f: f.get_name(), font_families))
def get_system_fonts(only_home=True): if only_home: # TODO (anguelos) FIX THIS font_list = [f.split("/")[-1].split(".")[0] for f in go('echo "$HOME/.fonts/"*.ttf').split()] font_list = [f.get_name() for f in pangocairo.cairo_font_map_get_default().list_families()] return font_list else: raise NotImplementedError()
def _find_font_desc(self, font_name): font_map = pangocairo.cairo_font_map_get_default() families = font_map.list_families() for family in families: for face in family.list_faces(): _font_name = '{} {}'.format(family.get_name() , face.get_face_name()) if font_name == _font_name or font_name == family.get_name(): return face.describe() return None
def create_layout(self, cr): pcctx = pangocairo.CairoContext(cr) font_map = pangocairo.cairo_font_map_get_default() pcr = font_map.create_context() p_layout = pango.Layout(pcr) p_layout.set_wrap(pango.WRAP_WORD) p_layout.set_width(int(self.width*pango.SCALE)) font = pango.FontDescription(self.font_description) p_layout.set_font_description(font) p_layout.set_alignment(self.align) p_layout.set_text(self.string) return p_layout
def _find_font_desc(self, font_name): font_map = pangocairo.cairo_font_map_get_default() families = font_map.list_families() for family in families: for face in family.list_faces(): _font_name = '{} {}'.format(family.get_name(), face.get_face_name()) if font_name == _font_name or font_name == family.get_name(): return face.describe() return None
def create_layout(self, cr): pcctx = pangocairo.CairoContext(cr) font_map = pangocairo.cairo_font_map_get_default() pcr = font_map.create_context() p_layout = pango.Layout(pcr) p_layout.set_wrap(pango.WRAP_WORD) p_layout.set_width(int(self.width * pango.SCALE)) font = pango.FontDescription(self.font_description) p_layout.set_font_description(font) p_layout.set_alignment(self.align) p_layout.set_text(self.string) return p_layout
def _get_fonts(families_list, families_dict): fm = pangocairo.cairo_font_map_get_default() context = fm.create_context() families = context.list_families() for item in families: fcs = {} scalable = True for face in item.list_faces(): if not face.list_sizes() is None: scalable = False fcs[face.get_face_name()] = face if scalable: families_dict[item.get_name()] = fcs families_list.append(item.get_name()) families_list.sort()
def _get_font(self): font_map = pangocairo.cairo_font_map_get_default() font_name = self.font_name if not font_name: stop_alert("render cairoe unable to find a valid font name, please use --font_name or pymterm.json to set font name") sys.exit(1) font = self._find_font_desc(font_name) if not font: font = pango.FontDescription(' '.join([font_name, str(self.font_size)])) else: font.set_size(int(float(self.font_size) * pango.SCALE * 72 / font_map.get_resolution()) + 1) return font
def transformText(text, file_path, fontname="Sans"): # fontname = sys.argv[2] if len(sys.argv) >= 3 else "Sans" # text = sys.argv[1] if len(sys.argv) >= 2 else u"Some text" surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 320, 120) context = cairo.Context(surf) #draw a background rectangle: context.rectangle(0,0,320,120) context.set_source_rgb(1, 1, 1) context.fill() #get font families: font_map = pangocairo.cairo_font_map_get_default() families = font_map.list_families() # to see family names: print [f.get_name() for f in font_map.list_families()]
def _get_font(self): font_map = pangocairo.cairo_font_map_get_default() font_name = self.font_name if not font_name: stop_alert( "render cairoe unable to find a valid font name, please use --font_name or pymterm.json to set font name" ) sys.exit(1) font = self._find_font_desc(font_name) if not font: font = pango.FontDescription(' '.join( [font_name, str(self.font_size)])) else: font.set_size( int( float(self.font_size) * pango.SCALE * 72 / font_map.get_resolution()) + 1) return font
def get_font_families(): '''Get all font families in system.''' fontmap = pangocairo.cairo_font_map_get_default() return sorted(map(lambda f: f.get_name(), fontmap.list_families()))
def generate_images(opts,args): # Set up variables for drawing space width = 2550 # Will resize to match text; default 8.5"x11" @ 300dpi height = 3300 MARGIN_X = 300 MARGIN_Y = 300 LINE_SPACE = 35 #TODO: Command-line opts LANG = "ka" TESS_LANG = "kat" # Set up decent spacing for box files attrs = pango.AttrList() #TODO: Command line opts or config attrs.insert(pango.AttrLanguage(LANG,0,-1)) attrs.insert(pango.AttrLetterSpacing(10000,0,-1)) attrs.insert(pango.AttrSize(48000,0,-1)) attrs.insert(pango.AttrFallback(False,0,-1)) attrs.insert(pango.AttrStyle(pango.STYLE_NORMAL,0,-1)) attrs.insert(pango.AttrWeight(pango.WEIGHT_NORMAL,0,-1)) attrs.insert(pango.AttrUnderline(pango.UNDERLINE_NONE,0,-1)) # Instantiate Cairo surface and context surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = pangocairo.CairoContext(cairo.Context(surf)) # Instantiate PangoCairo context context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) #get font families: font_map = pangocairo.cairo_font_map_get_default() # to see family names: if opts.list_fonts: print [f.get_name() for f in font_map.list_families()] return # Set up pango layout layout = context.create_layout() layout.set_attributes(attrs) layout.set_width((width+MARGIN_X)*pango.SCALE) layout.set_spacing(LINE_SPACE*pango.SCALE) #print layout.get_width() # Read text from file TODO: Command line argument # TODO: Multiple files print to multiple image documents text = '' with codecs.open(opts.input_file) as text_file: for line in text_file: text += line + '\n' font_names = args # (variant, reset,"desc") #Font variants is an array of tuples consisting of: (AttrStyle, InverseAttrStyle, Name) font_variants = [ (pango.AttrStyle(pango.STYLE_NORMAL,0,-1),pango.AttrStyle(pango.STYLE_NORMAL,0,-1),"")] #Add other stylings based on command-line options if opts.italic: font_variants.append((pango.AttrStyle(pango.STYLE_ITALIC,0,-1),pango.AttrStyle(pango.STYLE_NORMAL,0,-1),"italic")) if opts.bold: font_variants.append((pango.AttrWeight(pango.WEIGHT_HEAVY,0,-1),pango.AttrWeight(pango.WEIGHT_NORMAL,0,-1),"bold")) if opts.underline: font_variants.append((pango.AttrUnderline(pango.UNDERLINE_SINGLE,0,-1),pango.AttrUnderline(pango.UNDERLINE_NONE,0,-1),"underline")) #Generate pages for each font name and variation. for fn in font_names: for fvar in font_variants: # Change to a new variant attrs.change(fvar[0]) layout.set_attributes(attrs) # Change to a new font fontname = fn font = pango.FontDescription(fontname + " 25") layout.set_font_description(font) layout.set_text(text) (ink, logical) = layout.get_pixel_extents() # If layout exceeds size of surface, change surface size if logical[2] > (width-MARGIN_X) or logical[3] > (height-MARGIN_Y): width = logical[2]+MARGIN_X height = logical[3]+MARGIN_Y surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = pangocairo.CairoContext(cairo.Context(surf)) context.update_layout(layout) #draw a background rectangle: context.rectangle(0,0,width,height) context.set_source_rgb(1, 1, 1) context.fill() # Translate context so that desired text upperleft corner is at 0,0 context.translate(50,25) context.set_source_rgb(0, 0, 0) context.update_layout(layout) context.show_layout(layout) # Write to image # TODO: Specify outfile on command line #print fontname #print fvar[2] with open(TESS_LANG+"."+fontname+fvar[2]+".exp0.png", "wb") as image_file: surf.write_to_png(image_file) attrs.change(fvar[1]) layout.set_attributes(attrs)
"weight=\"bold\" style=\"", text) text = re.sub("style=\"font-style: italic(?:; )?", "style=\"italic\" style=\"", text) text = re.sub("style=\"background-color: (#[0-9A-Fa-f]{6})(?:; )?", "background=\"\\1\" style=\"", text) text = re.sub("style=\"\"", "", text) text = text.strip() # First pass, find image size to hold the text. mode = { "grey": -1, "bilevel": cairo.ANTIALIAS_NONE, "subpixel": cairo.ANTIALIAS_SUBPIXEL }[args.mode] pangocairo.cairo_font_map_get_default().set_resolution(72) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0) context = pangocairo.CairoContext(cairo.Context(surface)) layout = context.create_layout() options = cairo.FontOptions() options.set_antialias(mode) pangocairo.context_set_font_options(layout.get_context(), options) layout.set_font_description(pango.FontDescription(args.font)) layout.set_markup(text) width = max(layout.get_pixel_size()[0] + args.pad * 2, args.width) height = max(layout.get_pixel_size()[1] + args.pad * 2, args.height) # Second pass, render actual image and save it. surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = pangocairo.CairoContext(cairo.Context(surface))
def get_all_font_info(): font_map = pangocairo.cairo_font_map_get_default() families = font_map.list_families() return sorted([f.get_name() for f in families])
def print_fonts(): font_map = pangocairo.cairo_font_map_get_default() print repr([f.get_name() for f in font_map.list_families()])
def render(text,seed,align,fillbackground,linespacing, rotation,backgroundcolors): # Texte ausmessen, um Bildbreite zu bestimmen presurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1) precontext = cairo.Context(presurf) prepangocairo_context = pangocairo.CairoContext(precontext) prelayout = prepangocairo_context.create_layout() lines=text.split("\n") i=0 maxw=0 dxtick=10 font="Politics Head " fontsizes=[15,20,25,30,35] linesattributes=[] RE_CONTROL=re.compile("^.*|") RE_FONTSIZE=re.compile("[1-5]") RE_BGCOL=re.compile("[a-e]") bgcolmap={} bgcolmap['a']=0 bgcolmap['b']=1 bgcolmap['c']=2 bgcolmap['d']=3 bgcolmap['e']=4 linedefaults={} linedefaults['fontsize']=fontsizes[3] linedefaults['dx']=0 linedefaults['backgroundcolor']='000000'; backgroundcolors.insert(0,'000000') # schwarz als erste hintergrundfarbe # Erster Durchlauf durch alle Zeilen: Dimensionen bestimmen, # Steuerzeichen auswerten for line in lines: if len(line)==0: i=i+1 continue line=line.strip(' \t\n\r') lineattributes=copy(linedefaults) control=RE_CONTROL.search(line).group(0) if (control): fontsize=RE_FONTSIZE.search(control) if (fontsize): lineattributes['fontsize']=fontsizes[int(fontsize.group(0))] backgroundcolor=RE_BGCOL.search(control) if (backgroundcolor): # print backgroundcolors # print backgroundcolor.group(0) # print bgcolmap[backgroundcolor.group(0)] lineattributes['backgroundcolor']=backgroundcolors[bgcolmap[backgroundcolor.group(0)]] else: if (i % 2 == 0): lineattributes['backgroundcolor']=backgroundcolors[0] else: lineattributes['backgroundcolor']=backgroundcolors[1] lineattributes['dx']=(control.count('>')-control.count('<'))*dxtick linesattributes.append(lineattributes) # Text abmessen prelayout.set_text(line) font = pango.FontDescription("Politics Head "+str(lineattributes['fontsize'])) prelayout.set_font_description(font) prepangocairo_context.update_layout(prelayout) w,h = prelayout.get_size() if (w>maxw): maxw=w # maxw enthält jetzt größte gemessene Breite fontsize=25 # Format des Bilds bestimmen HEIGHT=int(linespacing*(len(lines))+60) WIDTH=maxw/pango.SCALE+150 # Bild vorbereiten surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) context = cairo.Context(surf) pangocairo_context = pangocairo.CairoContext(context) pangocairo_context.set_antialias(cairo.ANTIALIAS_GRAY) if (fillbackground): context.rectangle(0,0,WIDTH,HEIGHT) context.set_source_rgb(0, 0, 0) context.fill() font_map = pangocairo.cairo_font_map_get_default() families = font_map.list_families() context.set_antialias(cairo.ANTIALIAS_GRAY) layout = pangocairo_context.create_layout() # noch ein paar Variablen für Abstände i=0 dx=5 dyu=0 dyl=4 dd=1 dd1=1 # Zufallszahlengenerator setzen numpy.random.seed(int(seed)) # Zweiter Durchlauf durch alle Zeilen: Text setzen for line in lines: # zeile vorbereiten, leere Zeilen überspringen line=line.strip(' \t\n\r') line=re.sub(r'^([^\|]*\|)?(.*)','\\2',line) # print i # print linespacing if len(line)==0: i=i+1 continue font = pango.FontDescription("Politics Head "+str(linesattributes[i]['fontsize'])) layout.set_font_description(font) # text laden layout.set_text(line) pangocairo_context.update_layout(layout) w,h = layout.get_size() context.save() # Position bestimmen shiftx=linesattributes[i]['dx'] # print "Align: "+align if align=="left": context.translate(50+shiftx,25+i*linespacing) elif align=="center": context.translate(WIDTH/2-w/(pango.SCALE*2)+shiftx,25+i*linespacing) elif align=="right": context.translate(WIDTH-50-w/pango.SCALE+shiftx,25+i*linespacing) # Rotation linerot=numpy.random.random()*2*rotation-rotation context.rotate(linerot) # Weißer Hintergrund context.set_source_rgb(1, 1, 1) context.rectangle(-dx-dd*numpy.random.random()-dd1, dyu-dd*numpy.random.random()-dd1, w/pango.SCALE+dx*2+2*dd*numpy.random.random()+dd1*2, h/pango.SCALE+dyl-dyu+2*dd*numpy.random.random()+dd1*2) context.fill() # Farbiger Hintergrund webcolortosource(context,linesattributes[i]['backgroundcolor']) context.rectangle(-dx,dyu,w/pango.SCALE+dx*2, h/pango.SCALE+dyl-dyu) context.fill() # Text in Weiß context.set_source_rgb(255, 255, 255) pangocairo_context.show_layout(layout) context.restore() i=i+1 # Bild als String zurückgeben image_string=io.BytesIO() surf.write_to_png(image_string) val=image_string.getvalue() image_string.close() return val
def __init__(self, page_setup, cr): self.page_setup = page_setup self.paper_size = page_setup.get_paper_size() self.pango_fontmap = pangocairo.cairo_font_map_get_default() self.cr = cr
import pango #------------------------------------------------------------------------ # # Gramps modules # #------------------------------------------------------------------------ from gen.plug.docgen import (BaseDoc, TextDoc, FONT_SERIF, PARA_ALIGN_RIGHT, FONT_SANS_SERIF, FONT_MONOSPACE, PARA_ALIGN_CENTER, PARA_ALIGN_LEFT) import ManagedWindow try: import pangocairo RESOLUTION = pangocairo.cairo_font_map_get_default().get_resolution() except: RESOLUTION = 96 def pixels(cm): return int (RESOLUTION/2.54 * cm) #------------------------------------------------------------------------ # # Constants # #------------------------------------------------------------------------ LEFT,RIGHT,CENTER = 'LEFT','RIGHT','CENTER' _WIDTH_IN_CHARS = 72 class DisplayBuf(ManagedWindow.ManagedWindow):
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import pango import pangocairo import cairo import gobject import logging logger = logging.getLogger(__name__) # Shared pango context pango_context = pangocairo.cairo_font_map_get_default().create_context() """ Handles drawing and measuring of text on a screen. """ def new_text(screen = None): """ Create a new text handler. This should be used rather than directly constructing the G15PangoText """ if screen: return G15PangoText(screen.driver.get_antialias()) else: return G15PangoText(True)
def __init__(self): Overlay.__init__(self) self.pango_context = pangocairo.cairo_font_map_get_default().create_context()
def _create_frame_textbox(width , height , texts): global text_i image_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(round(width * cm)), int(round(height * cm)) ) cairo_context = cairo.Context(image_surface) cairo_context.set_miter_limit(cairo.LINE_JOIN_ROUND) cairo_context.set_line_cap(cairo.LINE_CAP_ROUND) cairo_fontmap = pangocairo.cairo_font_map_get_default() cairo_fontmap.set_resolution(dpi) cairo_context.move_to(0,0) cairo_context.set_line_width(1.0) pangocairo_context = pangocairo.CairoContext(cairo_context) pango_layout = pangocairo_context.create_layout() pango_layout.set_spacing(0) pango_layout.set_wrap(pango.WRAP_WORD) bullet_layout = None bullet = None y_pos = 0.0 for i in range(len(texts)): first_line = True font_outline = False text = "" p = texts[i] margin = {'left':0 , 'right':0 , 'top':0 , 'bottom':0} para_style = p['paragraph-style'] if para_style.has_key('fo:margin-left'): margin['left'] = float(para_style['fo:margin-left'].rstrip('cm')) * cm if para_style.has_key('fo:margin-right'): margin['right'] = float(para_style['fo:margin-right'].rstrip('cm')) * cm if para_style.has_key('fo:margin-top'): margin['top'] = float(para_style['fo:margin-top'].rstrip('cm')) * cm if para_style.has_key('fo:margin-bottom'): margin['bottom'] = float(para_style['fo:margin-bottom'].rstrip('cm'))*cm if p['paragraph-style'].has_key('fo:text-align'): text_align = p['paragraph-style']['fo:text-align'] else : text_align = 'start' if text_align == 'start' : pango_layout.set_alignment(pango.ALIGN_LEFT) elif text_align == 'center': pango_layout.set_alignment(pango.ALIGN_CENTER) elif text_align == 'end': pango_layout.set_alignment(pango.ALIGN_RIGHT) if len(p['texts'])>0: for t in p['texts']: #pprint(t,depth=1) if type(t) is dict: if t.has_key('text-style'): if t['text-style']['style:text-outline'] == 'true' : font_outline = True text += _get_pango_span(t['text-style']) + t['text-content'] + "</span>" else: text += _get_pango_span(p['text-style']) + t['text-content'] + "</span>" elif type(t) is unicode: text += _get_pango_span(p['text-style']) + t + "</span>" else: text = _get_pango_span(p['text-style']) + ' ' + "</span>" #pprint(text) if p.has_key('bullet'): bullet_layout = pangocairo_context.create_layout() bullet_layout.set_width(int(round(width * cm)) * pango.SCALE) bullet = p['bullet'] bullet_span = _get_pango_span(bullet['text-style']) + bullet['text-content'] + '</span>' bullet_layout.set_markup(bullet_span) if bullet['list-style'].has_key('text:space-before'): space_before = float(bullet['list-style']['text:space-before'].rstrip('cm') ) bullet['_space-before'] = space_before * cm else: bullet['_space-before'] = 0 if bullet['list-style'].has_key('text:min-label-width'): label_width = float(bullet['list-style']['text:min-label-width'].rstrip('cm') ) bullet['_label-width'] = label_width * cm else: bullet['_label-width'] = 0 ink,logical = bullet_layout.get_pixel_extents() bullet['_width'] = logical[2] xstart = bullet['_label-width'] + bullet['_space-before'] pango_layout.set_width(int(math.floor( (width * cm - xstart) * pango.SCALE) ) ) else: pango_layout.set_width(int(math.floor( (width * cm) * pango.SCALE) ) ) xstart = 0.0 pango_layout.set_markup(text) iter = pango_layout.get_iter() lines_remains = True tmp_ypos = 0 while lines_remains: ink_t , logical_t = iter.get_line_extents() ink = map(lambda x:x/pango.SCALE, ink_t) logical = map(lambda x:x/pango.SCALE, logical_t) line = iter.get_line() baseline = iter.get_baseline() # cairo_context.move_to( xstart + ink[0] - (ink[0] - logical[0])/2.0 , y_pos + ink[1]) # _draw_rectangle(ink,(0,1,0),cairo_context) # cairo_context.move_to( xstart + logical[0] , y_pos + logical[1]) # _draw_rectangle(logical,(1,0,0),cairo_context) text_xpos = xstart + logical[0] + (logical[0] - ink[0])/2.0 text_ypos = y_pos + baseline/pango.SCALE if bullet is not None and first_line: if text_align == 'start': bullet_ink,bullet_logic = bullet_layout.get_pixel_extents() bullet_xpos = bullet['_space-before'] bullet_ypos = y_pos + (logical[3] - bullet_logic[3])/2.0 elif text_align == 'center': bullet_ink,bullet_logic = bullet_layout.get_pixel_extents() bullet_xpos = text_xpos - bullet['_label-width'] bullet_ypos = y_pos + (logical[3] - bullet_logic[3])/2.0 elif text_align == 'end': bullet_ink,bullet_logic = bullet_layout.get_pixel_extents() bullet_xpos = text_xpos - bullet['_label-width'] bullet_ypos = y_pos + (logical[3] - bullet_logic[3])/2.0 cairo_context.move_to( bullet_xpos, bullet_ypos ) cairo_context.set_source_rgb(0.0,0.0,0.0) pangocairo_context.show_layout(bullet_layout) cairo_context.move_to( text_xpos, text_ypos ) if font_outline : pangocairo_context.layout_line_path(line) cairo_context.set_line_width(2.0) cairo_context.set_source_rgb(0.0,0.0,0.0) cairo_context.stroke_preserve() cairo_context.set_source_rgba(1.0,1.0,1.0,1.0) cairo_context.fill() else : pangocairo_context.layout_line_path(line) cairo_context.set_source_rgb(0.0,0.0,0.0) cairo_context.fill() first_line = False lines_remains = iter.next_line() tmp_ypos += logical[3] y_pos += tmp_ypos + margin['bottom'] image_buffer = StringIO.StringIO() # image_surface.write_to_png("./tests/test_cairo/TEST_%s.png" % ("%04d" % text_i)) image_surface.write_to_png(image_buffer) image_buffer.seek(0) result = {'name' : "FRAME_%04d" % text_i , 'buffer' : image_buffer} text_i += 1 return result
def __init__(self): gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) self.set_title(_("Titler")) self.connect("delete-event", lambda w, e:close_titler()) if editorstate.SCREEN_HEIGHT < 800: global TEXT_LAYER_LIST_HEIGHT, TEXT_VIEW_HEIGHT, VIEW_EDITOR_HEIGHT TEXT_LAYER_LIST_HEIGHT = 200 TEXT_VIEW_HEIGHT = 225 VIEW_EDITOR_HEIGHT = 550 self.block_updates = False self.view_editor = vieweditor.ViewEditor(PLAYER().profile, VIEW_EDITOR_WIDTH, VIEW_EDITOR_HEIGHT) self.view_editor.active_layer_changed_listener = self.active_layer_changed self.guides_toggle = vieweditor.GuidesViewToggle(self.view_editor) add_b = gtk.Button(_("Add")) del_b = gtk.Button(_("Delete")) add_b.connect("clicked", lambda w:self._add_layer_pressed()) del_b.connect("clicked", lambda w:self._del_layer_pressed()) add_del_box = gtk.HBox() add_del_box = gtk.HBox(True,1) add_del_box.pack_start(add_b) add_del_box.pack_start(del_b) center_h_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "center_horizontal.png") center_v_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "center_vertical.png") center_h = gtk.Button() center_h.set_image(center_h_icon) center_h.connect("clicked", lambda w:self._center_h_pressed()) center_v = gtk.Button() center_v.set_image(center_v_icon) center_v.connect("clicked", lambda w:self._center_v_pressed()) self.layer_list = TextLayerListView(self._layer_selection_changed, self._layer_visibility_toggled) self.layer_list.set_size_request(TEXT_LAYER_LIST_WIDTH, TEXT_LAYER_LIST_HEIGHT) self.text_view = gtk.TextView() self.text_view.set_pixels_above_lines(2) self.text_view.set_left_margin(2) self.text_view.get_buffer().connect("changed", self._text_changed) self.sw = gtk.ScrolledWindow() self.sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) self.sw.add(self.text_view) self.sw.set_size_request(TEXT_VIEW_WIDTH, TEXT_VIEW_HEIGHT) scroll_frame = gtk.Frame() scroll_frame.add(self.sw) self.tc_display = guicomponents.MonitorTCDisplay() self.tc_display.use_internal_frame = True self.pos_bar = positionbar.PositionBar() self.pos_bar.set_listener(self.position_listener) self.pos_bar.update_display_from_producer(PLAYER().producer) self.pos_bar.mouse_release_listener = self.pos_bar_mouse_released pos_bar_frame = gtk.Frame() pos_bar_frame.add(self.pos_bar.widget) pos_bar_frame.set_shadow_type(gtk.SHADOW_ETCHED_IN) font_map = pangocairo.cairo_font_map_get_default() unsorted_families = font_map.list_families() if len(unsorted_families) == 0: print "No font families found in system! Titler will not work." self.font_families = sorted(unsorted_families, key=lambda family: family.get_name()) self.font_family_indexes_for_name = {} combo = gtk.combo_box_new_text() indx = 0 for family in self.font_families: combo.append_text(family.get_name()) self.font_family_indexes_for_name[family.get_name()] = indx indx += 1 combo.set_active(0) self.font_select = combo self.font_select.connect("changed", self._edit_value_changed) adj = gtk.Adjustment(float(DEFAULT_FONT_SIZE), float(1), float(300), float(1)) self.size_spin = gtk.SpinButton(adj) self.size_spin.connect("changed", self._edit_value_changed) self.size_spin.connect("key-press-event", self._key_pressed_on_widget) font_main_row = gtk.HBox() font_main_row.pack_start(self.font_select, True, True, 0) font_main_row.pack_start(guiutils.pad_label(5, 5), False, False, 0) font_main_row.pack_start(self.size_spin, False, False, 0) self.bold_font = gtk.ToggleButton() self.italic_font = gtk.ToggleButton() bold_icon = gtk.image_new_from_stock(gtk.STOCK_BOLD, gtk.ICON_SIZE_BUTTON) italic_icon = gtk.image_new_from_stock(gtk.STOCK_ITALIC, gtk.ICON_SIZE_BUTTON) self.bold_font.set_image(bold_icon) self.italic_font.set_image(italic_icon) self.bold_font.connect("clicked", self._edit_value_changed) self.italic_font.connect("clicked", self._edit_value_changed) self.left_align = gtk.RadioButton() self.center_align = gtk.RadioButton(self.left_align) self.right_align = gtk.RadioButton(self.left_align) left_icon = gtk.image_new_from_stock(gtk.STOCK_JUSTIFY_LEFT, gtk.ICON_SIZE_BUTTON) center_icon = gtk.image_new_from_stock(gtk.STOCK_JUSTIFY_CENTER, gtk.ICON_SIZE_BUTTON) right_icon = gtk.image_new_from_stock(gtk.STOCK_JUSTIFY_RIGHT, gtk.ICON_SIZE_BUTTON) self.left_align.set_image(left_icon) self.center_align.set_image(center_icon) self.right_align.set_image(right_icon) self.left_align.set_mode(False) self.center_align.set_mode(False) self.right_align.set_mode(False) self.left_align.connect("clicked", self._edit_value_changed) self.center_align.connect("clicked", self._edit_value_changed) self.right_align.connect("clicked", self._edit_value_changed) self.color_button = gtk.ColorButton() self.color_button.connect("color-set", self._edit_value_changed) buttons_box = gtk.HBox() buttons_box.pack_start(gtk.Label(), True, True, 0) buttons_box.pack_start(self.bold_font, False, False, 0) buttons_box.pack_start(self.italic_font, False, False, 0) buttons_box.pack_start(guiutils.pad_label(5, 5), False, False, 0) buttons_box.pack_start(self.left_align, False, False, 0) buttons_box.pack_start(self.center_align, False, False, 0) buttons_box.pack_start(self.right_align, False, False, 0) buttons_box.pack_start(guiutils.pad_label(5, 5), False, False, 0) buttons_box.pack_start(self.color_button, False, False, 0) buttons_box.pack_start(gtk.Label(), True, True, 0) load_layers = gtk.Button(_("Load Layers")) load_layers.connect("clicked", lambda w:self._load_layers_pressed()) save_layers = gtk.Button(_("Save Layers")) save_layers.connect("clicked", lambda w:self._save_layers_pressed()) clear_layers = gtk.Button(_("Clear All")) clear_layers.connect("clicked", lambda w:self._clear_layers_pressed()) layers_save_buttons_row = gtk.HBox() layers_save_buttons_row.pack_start(save_layers, False, False, 0) layers_save_buttons_row.pack_start(load_layers, False, False, 0) layers_save_buttons_row.pack_start(gtk.Label(), True, True, 0) #layers_save_buttons_row.pack_start(clear_layers, False, False, 0) adj = gtk.Adjustment(float(0), float(0), float(3000), float(1)) self.x_pos_spin = gtk.SpinButton(adj) self.x_pos_spin.connect("changed", self._position_value_changed) self.x_pos_spin.connect("key-press-event", self._key_pressed_on_widget) adj = gtk.Adjustment(float(0), float(0), float(3000), float(1)) self.y_pos_spin = gtk.SpinButton(adj) self.y_pos_spin.connect("changed", self._position_value_changed) self.y_pos_spin.connect("key-press-event", self._key_pressed_on_widget) adj = gtk.Adjustment(float(0), float(0), float(3000), float(1)) self.rotation_spin = gtk.SpinButton(adj) self.rotation_spin.connect("changed", self._position_value_changed) self.rotation_spin.connect("key-press-event", self._key_pressed_on_widget) undo_pos = gtk.Button() undo_icon = gtk.image_new_from_stock(gtk.STOCK_UNDO, gtk.ICON_SIZE_BUTTON) undo_pos.set_image(undo_icon) next_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "next_frame_s.png") prev_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "prev_frame_s.png") prev_frame = gtk.Button() prev_frame.set_image(prev_icon) prev_frame.connect("clicked", lambda w:self._prev_frame_pressed()) next_frame = gtk.Button() next_frame.set_image(next_icon) next_frame.connect("clicked", lambda w:self._next_frame_pressed()) self.scale_selector = vieweditor.ScaleSelector(self) timeline_box = gtk.HBox() timeline_box.pack_start(guiutils.get_in_centering_alignment(self.tc_display.widget), False, False, 0) timeline_box.pack_start(guiutils.get_in_centering_alignment(pos_bar_frame, 1.0), True, True, 0) timeline_box.pack_start(prev_frame, False, False, 0) timeline_box.pack_start(next_frame, False, False, 0) timeline_box.pack_start(self.guides_toggle, False, False, 0) timeline_box.pack_start(self.scale_selector, False, False, 0) positions_box = gtk.HBox() positions_box.pack_start(gtk.Label(), True, True, 0) positions_box.pack_start(gtk.Label("X:"), False, False, 0) positions_box.pack_start(self.x_pos_spin, False, False, 0) positions_box.pack_start(guiutils.pad_label(10, 5), False, False, 0) positions_box.pack_start(gtk.Label("Y:"), False, False, 0) positions_box.pack_start(self.y_pos_spin, False, False, 0) positions_box.pack_start(guiutils.pad_label(10, 5), False, False, 0) #positions_box.pack_start(gtk.Label(_("Angle")), False, False, 0) #positions_box.pack_start(self.rotation_spin, False, False, 0) positions_box.pack_start(guiutils.pad_label(10, 5), False, False, 0) positions_box.pack_start(center_h, False, False, 0) positions_box.pack_start(center_v, False, False, 0) positions_box.pack_start(gtk.Label(), True, True, 0) controls_panel_1 = gtk.VBox() controls_panel_1.pack_start(add_del_box, False, False, 0) controls_panel_1.pack_start(self.layer_list, False, False, 0) controls_panel_1.pack_start(layers_save_buttons_row, False, False, 0) controls_panel_2 = gtk.VBox() controls_panel_2.pack_start(scroll_frame, True, True, 0) controls_panel_2.pack_start(font_main_row, False, False, 0) controls_panel_2.pack_start(buttons_box, False, False, 0) controls_panel = gtk.VBox() controls_panel.pack_start(guiutils.get_named_frame(_("Active Layer"),controls_panel_2), True, True, 0) controls_panel.pack_start(guiutils.get_named_frame(_("Layers"),controls_panel_1), False, False, 0) view_editor_editor_buttons_row = gtk.HBox() view_editor_editor_buttons_row.pack_start(positions_box, False, False, 0) view_editor_editor_buttons_row.pack_start(gtk.Label(), True, True, 0) keep_label = gtk.Label(_("Keep Layers When Closed")) self.keep_layers_check = gtk.CheckButton() self.keep_layers_check.set_active(_keep_titler_data) self.keep_layers_check.connect("toggled", self._keep_layers_toggled) open_label = gtk.Label(_("Open Saved Title In Bin")) self.open_in_current_check = gtk.CheckButton() self.open_in_current_check.set_active(_open_saved_in_bin) self.open_in_current_check.connect("toggled", self._open_saved_in_bin) exit_b = guiutils.get_sized_button(_("Close"), 150, 32) exit_b.connect("clicked", lambda w:close_titler()) save_titles_b = guiutils.get_sized_button(_("Save Title Graphic"), 150, 32) save_titles_b.connect("clicked", lambda w:self._save_title_pressed()) editor_buttons_row = gtk.HBox() editor_buttons_row.pack_start(gtk.Label(), True, True, 0) editor_buttons_row.pack_start(keep_label, False, False, 0) editor_buttons_row.pack_start(self.keep_layers_check, False, False, 0) editor_buttons_row.pack_start(guiutils.pad_label(24, 2), False, False, 0) editor_buttons_row.pack_start(open_label, False, False, 0) editor_buttons_row.pack_start(self.open_in_current_check, False, False, 0) editor_buttons_row.pack_start(guiutils.pad_label(24, 2), False, False, 0) editor_buttons_row.pack_start(exit_b, False, False, 0) editor_buttons_row.pack_start(save_titles_b, False, False, 0) editor_panel = gtk.VBox() editor_panel.pack_start(self.view_editor, True, True, 0) editor_panel.pack_start(timeline_box, False, False, 0) editor_panel.pack_start(guiutils.get_in_centering_alignment(view_editor_editor_buttons_row), False, False, 0) editor_panel.pack_start(guiutils.pad_label(2, 24), False, False, 0) editor_panel.pack_start(editor_buttons_row, False, False, 0) editor_row = gtk.HBox() editor_row.pack_start(controls_panel, False, False, 0) editor_row.pack_start(editor_panel, True, True, 0) alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0) alignment.set_padding(8,8,8,8) alignment.add(editor_row) self.add(alignment) self.layer_list.fill_data_model() self._update_gui_with_active_layer_data() self.show_all() self.connect("size-allocate", lambda w, e:self.window_resized()) self.connect("window-state-event", lambda w, e:self.window_resized())
else: text = re.sub( "style=\"font-weight: bold(?:; )?", "weight=\"bold\" style=\"", text ) text = re.sub( "style=\"font-style: italic(?:; )?", "style=\"italic\" style=\"", text ) text = re.sub( "style=\"background-color: (#[0-9A-Fa-f]{6})(?:; )?", "background=\"\\1\" style=\"", text ) text = re.sub( "style=\"\"", "", text ) text = text.strip() # First pass, find image size to hold the text. mode = { "grey" : -1, "bilevel" : cairo.ANTIALIAS_NONE, "subpixel" : cairo.ANTIALIAS_SUBPIXEL }[ args.mode ] pangocairo.cairo_font_map_get_default().set_resolution( RESOLUTION ) surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, 0, 0 ) context = pangocairo.CairoContext( cairo.Context( surface ) ) layout = context.create_layout() options = cairo.FontOptions() options.set_antialias( mode ) pangocairo.context_set_font_options( layout.get_context(), options ) layout.set_font_description( pango.FontDescription( args.font ) ) layout.set_markup( text ) width = max( layout.get_pixel_size()[ 0 ] + args.pad * 2, args.width ) height = max( layout.get_pixel_size()[ 1 ] + args.pad * 2, args.height ) # Second pass, render actual image and save it. surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, width, height ) context = pangocairo.CairoContext( cairo.Context( surface ) ) layout = context.create_layout()
text = re.sub( "style=\"font-weight: bold(?:; )?", "weight=\"bold\" style=\"", text ) text = re.sub( "style=\"font-style: italic(?:; )?", "style=\"italic\" style=\"", text ) text = re.sub( "style=\"background-color: (#[0-9A-Fa-f]{6})(?:; )?", "background=\"\\1\" style=\"", text ) text = re.sub( "style=\"\"", "", text ) text = text.strip() # First pass, find image size to hold the text. mode = { "grey" : -1, "bilevel" : cairo.ANTIALIAS_NONE, "subpixel" : cairo.ANTIALIAS_SUBPIXEL }[ args.mode ] pangocairo.cairo_font_map_get_default().set_resolution( 72 ) surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, 0, 0 ) context = pangocairo.CairoContext( cairo.Context( surface ) ) layout = context.create_layout() options = cairo.FontOptions() options.set_antialias( mode ) pangocairo.context_set_font_options( layout.get_context(), options ) layout.set_font_description( pango.FontDescription( args.font ) ) layout.set_markup( text ) width = max( layout.get_pixel_size()[ 0 ] + args.pad * 2, args.width ) height = max( layout.get_pixel_size()[ 1 ] + args.pad * 2, args.height ) # Second pass, render actual image and save it. surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, width, height ) context = pangocairo.CairoContext( cairo.Context( surface ) )
def draw_fonts(args): label = args[0] char = args[1] output = [] for cycle in range(1): for fontname in fontnames: surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 600, 600) context = cairo.Context(surf) #draw a background rectangle: context.rectangle(0, 0, 600, 600) context.set_source_rgb(1, 1, 1) context.fill() #get font families: font_map = pangocairo.cairo_font_map_get_default() # context.translate(0,0) pangocairo_context = pangocairo.CairoContext(context) pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pangocairo_context.create_layout() #fontname = sys.argv[1] if len(sys.argv) >= 2 else "Sans" # font = pango.FontDescription(fontname + " 200") if cycle == 0: font = pango.FontDescription(fontname + " 200") else: font = pango.FontDescription(fontname + " bold 200") layout.set_font_description(font) layout.set_text(char) context.set_source_rgb(0, 0, 0) pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout) fname = "/tmp/%s%d.png" % (fontname, randint(0, 20000000)) with open(fname, "wb") as image_file: surf.write_to_png(image_file) im = Image.open(fname) os.remove(fname) im = im.convert('L') a = np.asarray(im) a = trim(a) a = add_padding(a, padding=2) #####experimental normalization h, w = a.shape h = float(h) w = float(w) L = 32 sm = np.argmin([h, w]) bg = np.argmax([h, w]) R1 = [h, w][sm] / [h, w][bg] # R2 = np.sqrt(np.sin((np.pi/2.0)*R1)) # R2 = pow(R1, (1/3)) R2 = np.sqrt(R1) # R2 = R1 # if R1 < .5: # R2 = 1.5*R1 + .25 # else: # R2 = 1 if sm == 0: H2 = L * R2 W2 = L else: H2 = L W2 = L * R2 alpha = W2 / w beta = H2 / h a = resize(a, (0, 0), fy=beta, fx=alpha, interpolation=INTER_AREA) smn = a.shape[sm] offset = int(np.floor((L - smn) / 2.)) c = np.ones((L, L), dtype=np.uint8) * 255 # print a # print a.shape if (L - smn) % 2 == 1: start = offset + 1 end = offset else: start = end = offset if sm == 0: # print c[start:L-end, :].shape, a.shape c[start:L - end, :] = a else: # print c[:,start:L-end].shape, a.shape c[:, start:L - end] = a #########classic approach # im = Image.fromarray(a) # im.thumbnail((16,32), Image.ANTIALIAS) # im = np.asarray(im) # a = np.ones((32,16), dtype=np.uint8)*255 # a[0:im.shape[0],0:im.shape[1]] = im ########### #### USE FOLLOWING IF WANT TO SAVE NEW TRAINING DATA ################## a = c a[np.where(a < 120)] = 0 a[np.where(a >= 120)] = 1 # a = degrade(a) output.append( str(label) + ',' + ','.join(str(i) for i in a.flatten())) # # return output
'SuraVara_Samhita': [48, 'K', 'BB', 0, 1, 'Samhita', 1], 'SURAVARA_Swarna': [48, 'K', 'BB', 0, 1, 'Swarna', 1], 'Suravaram': [48, 'K', 'BR', 1, 1, 'Suravaram', 1], 'TenaliRamakrishna': [48, 'K', 'BB', 0, 1, 'Tenali', 1], 'Timmana': [48, 'K', 'BB', 0, 1, 'Timmana', 0], 'Vajram': [48, 'K', 'BB', 0, 1, 'Vajram', 1], 'Vani': [48, 'K', 'BR', 0, 1, 'Vani', 1], 'Vemana2000': [48, 'K', 'BR', 1, 1, 'Vemana', 1] # Non-Unicode #'AV-Web-Tel1': [48, 'K', 'BB', 0, 1, 'AVWeb', 1], #'TLW-TTHemalatha': [48, 'K', 'BB', 0, 1, 'Hemalatha', 1], #'DKM Telugu': [48, 'K', 'BB', 0, 1, 'DKM', 1], } ABBR_DICT = {} for font, properties in FP_DICT.items(): properties = properties[:] abbr = properties[ABBR] properties[ABBR] = font ABBR_DICT[abbr] = properties if __name__ == '__main__': import pangocairo #get font families: font_map = pangocairo.cairo_font_map_get_default() families = font_map.list_families() font_names = [f.get_name() for f in families] for f in sorted(font_names): print(f)
def flattern(self, attr_array, text): data = [] attr_values = ('value', 'desc', 'color') style = { pango.STYLE_NORMAL : 'normal', pango.STYLE_ITALIC : 'italic', pango.STYLE_OBLIQUE : 'oblique'} previous_start = 0 previous_end = 0 acumulated_line_height = 0; c = pango.FontMap.create_context(pangocairo.cairo_font_map_get_default()) l = pango.Layout(c) last_font = str(self.container_font) line_index = 0 for attr in attr_array: name = attr.type start = attr.start_index end = attr.end_index if start == end: continue name = pango.AttrType(name).value_nick value = False for attr_value in attr_values: if hasattr( attr, attr_value ): value = getattr( attr, attr_value ) break fill = "" if name == "foreground": fill = "fill:rgb(" + str((value.red*255)/65535) + "," + str((value.green*255)/65535) + "," + str((value.blue*255)/65535) + ");" underline = "" if name == "underline": underline = "text-decoration:underline;" strike = "" if name == "strikethrough": strike = "text-decoration:line-through;" font_style = "" font_weight = "" font_variant = "" font_family = "" font_stretch = "" inkscape_font_specification = "" if name == "font-desc": font_attrb = value.get_set_fields(); last_font = str(value) if(font_attrb & pango.FONT_MASK_STYLE): font_style = "font-style:"+ str(self.pango_style[value.get_style()]) +";" if(font_attrb & pango.FONT_MASK_WEIGHT): font_weight = "font-weight:"+ str(self.pango_weight[value.get_weight()]) +";" if(font_attrb & pango.FONT_MASK_VARIANT): font_variant = "font-variant:"+ str(self.pango_variant[value.get_variant()]) +";" if(font_attrb & pango.FONT_MASK_FAMILY): font_family = "font-family:'"+ value.get_family() + "';" inkscape_font_specification = "-inkscape-font-specification:'" + str(value) + "';" if(font_attrb & pango.FONT_MASK_STRETCH): font_stretch = "font-stretch:"+ str(self.pango_stretch[value.get_stretch()]) + ";" letter_spacing = "" if name == "letter-spacing": letter_spacing = "letter-spacing:" + str((((value/1024.0) / (self.input_resolution/self.output_resolution))/10)) + "px;" size = "" if name == "size": size = "font-size:" + str(math.ceil((value/1024.0) * (72.0/72.27))) + "px;" sub_super = "" if name == "scale": if value < 1: sub_super = "font-size:" + str(value * 100) + "%;baseline-shift:sub;" elif value > 1: sub_super = "font-size:" + str(value * 100) + "%;baseline-shift:super;" rise = "" if name == "rise" and value != 1024: rise = "baseline-shift:" + str((value/1024.0)) + ";" line_height = "" flowPara = False if name == "background" and value.red == 54321 and value.green == 12345 and value.blue == 6553: flowPara = True attr_list_full = self.arrToAttrList(attr_array) l.set_attributes(attr_list_full) l.set_text(text) line = l.get_line(line_index) line_index += 1 if line_index == 1: line_height = "line-height:" + str(math.floor(line.get_pixel_extents()[1][3] + (line.get_pixel_extents()[1][3]-line.get_pixel_extents()[0][3])) * (self.input_resolution/self.output_resolution)) + "px;" else: line_height = "line-height:" + str(math.floor(line.get_pixel_extents()[1][3]) * (self.input_resolution/self.output_resolution)) + "px;" if previous_start == start and previous_end == end: start_tag = data[len(data)-2] if ';fill:' not in start_tag[1] and '"fill:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + fill) if ';text-decoration:' not in start_tag[1] and '"text-decoration:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + underline + strike) if ';font-style:' not in start_tag[1] and '"font-style:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + font_style) if ';font-weight:' not in start_tag[1] and '"font-weight:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + font_weight) if ';font-stretch:' not in start_tag[1] and '"font-stretch:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + font_stretch) if ';font-variant:' not in start_tag[1] and '"font-variant:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + font_variant) if ';font-family:' not in start_tag[1] and '"font-family:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + font_family) if ';-inkscape-font-specification:' not in start_tag[1] and '"-inkscape-font-specification:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + inkscape_font_specification) if ';letter-spacing:' not in start_tag[1] and '"letter-spacing:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + letter_spacing) if ';font-size:' not in start_tag[1] and '"font-size:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + size) if ';baseline-shift:' not in start_tag[1] and '"baseline-shift:' not in start_tag[1]: start_tag[1] = start_tag[1].replace('style="','style="' + rise) else: if flowPara: element = "flowPara" else: element = "flowSpan" data.append([start,'<' + element + ' style="' + rise + fill + underline + font_stretch + font_weight + font_variant + font_style + font_family + inkscape_font_specification + letter_spacing + size + sub_super + line_height + '">']) data.append([end, '</'+ element +'>']) previous_start = attr.start_index previous_end = attr.end_index return data
def flattern(self, attr_array, text): data = [] attr_values = ('value', 'desc', 'color') style = { pango.STYLE_NORMAL: 'normal', pango.STYLE_ITALIC: 'italic', pango.STYLE_OBLIQUE: 'oblique' } previous_start = 0 previous_end = 0 acumulated_line_height = 0 c = pango.FontMap.create_context( pangocairo.cairo_font_map_get_default()) l = pango.Layout(c) last_font = str(self.container_font) line_index = 0 for attr in attr_array: name = attr.type start = attr.start_index end = attr.end_index if start == end: continue name = pango.AttrType(name).value_nick value = False for attr_value in attr_values: if hasattr(attr, attr_value): value = getattr(attr, attr_value) break fill = "" if name == "foreground": fill = "fill:rgb(" + str( (value.red * 255) / 65535) + "," + str( (value.green * 255) / 65535) + "," + str( (value.blue * 255) / 65535) + ");" underline = "" if name == "underline": underline = "text-decoration:underline;" strike = "" if name == "strikethrough": strike = "text-decoration:line-through;" font_style = "" font_weight = "" font_variant = "" font_family = "" font_stretch = "" inkscape_font_specification = "" if name == "font-desc": font_attrb = value.get_set_fields() last_font = str(value) if (font_attrb & pango.FONT_MASK_STYLE): font_style = "font-style:" + str( self.pango_style[value.get_style()]) + ";" if (font_attrb & pango.FONT_MASK_WEIGHT): font_weight = "font-weight:" + str( self.pango_weight[value.get_weight()]) + ";" if (font_attrb & pango.FONT_MASK_VARIANT): font_variant = "font-variant:" + str( self.pango_variant[value.get_variant()]) + ";" if (font_attrb & pango.FONT_MASK_FAMILY): font_family = "font-family:'" + value.get_family() + "';" inkscape_font_specification = "-inkscape-font-specification:'" + str( value) + "';" if (font_attrb & pango.FONT_MASK_STRETCH): font_stretch = "font-stretch:" + str( self.pango_stretch[value.get_stretch()]) + ";" letter_spacing = "" if name == "letter-spacing": letter_spacing = "letter-spacing:" + str( (((value / 1024.0) / (self.input_resolution / self.output_resolution)) / 10)) + "px;" size = "" if name == "size": size = "font-size:" + str( math.ceil((value / 1024.0) * (72.0 / 72.27))) + "px;" sub_super = "" if name == "scale": if value < 1: sub_super = "font-size:" + str( value * 100) + "%;baseline-shift:sub;" elif value > 1: sub_super = "font-size:" + str( value * 100) + "%;baseline-shift:super;" rise = "" if name == "rise" and value != 1024: rise = "baseline-shift:" + str((value / 1024.0)) + ";" line_height = "" flowPara = False if name == "background" and value.red == 54321 and value.green == 12345 and value.blue == 6553: flowPara = True attr_list_full = self.arrToAttrList(attr_array) l.set_attributes(attr_list_full) l.set_text(text) line = l.get_line(line_index) line_index += 1 if line_index == 1: line_height = "line-height:" + str( math.floor(line.get_pixel_extents()[1][3] + (line.get_pixel_extents()[1][3] - line.get_pixel_extents()[0][3])) * (self.input_resolution / self.output_resolution)) + "px;" else: line_height = "line-height:" + str( math.floor(line.get_pixel_extents()[1][3]) * (self.input_resolution / self.output_resolution)) + "px;" if previous_start == start and previous_end == end: start_tag = data[len(data) - 2] if ';fill:' not in start_tag[1] and '"fill:' not in start_tag[ 1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + fill) if ';text-decoration:' not in start_tag[ 1] and '"text-decoration:' not in start_tag[1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + underline + strike) if ';font-style:' not in start_tag[ 1] and '"font-style:' not in start_tag[1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + font_style) if ';font-weight:' not in start_tag[ 1] and '"font-weight:' not in start_tag[1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + font_weight) if ';font-stretch:' not in start_tag[ 1] and '"font-stretch:' not in start_tag[1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + font_stretch) if ';font-variant:' not in start_tag[ 1] and '"font-variant:' not in start_tag[1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + font_variant) if ';font-family:' not in start_tag[ 1] and '"font-family:' not in start_tag[1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + font_family) if ';-inkscape-font-specification:' not in start_tag[ 1] and '"-inkscape-font-specification:' not in start_tag[ 1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + inkscape_font_specification) if ';letter-spacing:' not in start_tag[ 1] and '"letter-spacing:' not in start_tag[1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + letter_spacing) if ';font-size:' not in start_tag[ 1] and '"font-size:' not in start_tag[1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + size) if ';baseline-shift:' not in start_tag[ 1] and '"baseline-shift:' not in start_tag[1]: start_tag[1] = start_tag[1].replace( 'style="', 'style="' + rise) else: if flowPara: element = "flowPara" else: element = "flowSpan" data.append([ start, '<' + element + ' style="' + rise + fill + underline + font_stretch + font_weight + font_variant + font_style + font_family + inkscape_font_specification + letter_spacing + size + sub_super + line_height + '">' ]) data.append([end, '</' + element + '>']) previous_start = attr.start_index previous_end = attr.end_index return data
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import pango import pangocairo import cairo import gobject import logging logger = logging.getLogger(__name__) # Shared pango context pango_context = pangocairo.cairo_font_map_get_default().create_context() """ Handles drawing and measuring of text on a screen. """ def new_text(screen=None): """ Create a new text handler. This should be used rather than directly constructing the G15PangoText """ if screen: return G15PangoText(screen.driver.get_antialias()) else: return G15PangoText(True)
dc = win32ui.CreateDC() dc.CreatePrinterDC() dc.StartDoc("foo") dc.StartPage() surf = cairo.Win32PrintingSurface(dc.GetHandleAttrib()) context = cairo.Context(surf) #draw a background rectangle: context.rectangle(0,0,50,50) context.set_source_rgb(0, 0, 0) context.fill() #get font families: font_map = pangocairo.cairo_font_map_get_default() families = font_map.list_families() # to see family names: #print [f.get_name() for f in font_map.list_families()] #context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) # Translates context so that desired text upperleft corner is at 0,0 context.translate(0,0) pangocairo_context = pangocairo.CairoContext(context) pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pangocairo_context.create_layout() fontname = "FuturaBook BT"
class Window(): def set_default_font(self): self._pango_ctx = gtk.Window().get_pango_context() df = self._pango_ctx.get_font_description() fam = df.get_family() monospace = filter(lambda f: f.is_monospace(), self._pango_ctx.list_families()) if len(monospace) == 0: raise AppException, \ ('Monospace font is not available on this system.', None) match = filter(lambda f: f.get_name() == fam, monospace) if not match: fam = monospace[0].get_name() default_font_size = 16 self._default_text_font_size = default_font_size self._default_header_font_size = default_font_size - 2 self._default_text_font = ('%s %d' % (fam, self._default_text_font_size)) self._default_header_font = ('%s %d' % (fam, self._default_header_font_size)) self._default['text_font']['default'] = self._default_text_font self._default['header_font']['default'] = self._default_header_font self.text_font_family = fam self.text_font_size = default_font_size self.text_font_weight = cairo.FONT_WEIGHT_NORMAL self.text_font_style = cairo.FONT_SLANT_NORMAL ## _screen = gtk.gdk.Screen() (_root_width, _root_height) = (_screen.get_width(), _screen.get_height()) _default_horizontal_margin = int(_root_width * 0.01) _default_vertical_margin = int(_root_height * 0.01) _max_horizontal_margin = int(_root_width * 0.05) _max_vertical_margin = int(_root_height * 0.05) _max_window_positon_x = int(_root_width * 0.9) _max_window_positon_y = int(_root_height * 0.9) _fontmap_resolution = int( pangocairo.cairo_font_map_get_default().get_resolution()) gtk.settings_get_default().set_long_property( 'gtk-xft-dpi', 1024 * _fontmap_resolution, '') _min_font_size = int(_fontmap_resolution / 12) _max_font_size = int(_fontmap_resolution * 0.5) _default = { 'text_font': { 'default': None, 'check_func': 'check_font' }, 'text_color': { 'default': '#000000', 'type': gtk.gdk.Color, 'check_func': 'check_color' }, 'background_color': { 'default': '#FFFFFF', 'type': gtk.gdk.Color, 'check_func': 'check_color' }, 'header_font': { 'default': None, 'check_func': 'check_font' }, 'header_fg_color': { 'default': '#000000', 'type': gtk.gdk.Color, 'check_func': 'check_color' }, 'header_bg_color': { 'default': '#FFFFFF', 'type': gtk.gdk.Color, 'check_func': 'check_color' }, 'header_format': { 'default': u'%f %p/%P' }, 'lpp': { 'default': 1, 'type': int, 'check_func': 'check_range', 'func_args': (1, None) }, 'cpl': { 'default': 1, 'type': int, 'check_func': 'check_range', 'func_args': (1, None) }, 'saved_position': { 'default': 0, 'type': int }, 'line_gap': { 'default': 2, 'type': int, 'check_func': 'check_range', 'func_args': (1, None) }, 'char_gap': { 'default': 2, 'type': int, 'check_func': 'check_range', 'func_args': (1, None) }, 'top_margin': { 'default': _default_vertical_margin, 'type': int, 'check_func': 'check_range', 'func_args': (0, _max_vertical_margin) }, 'bottom_margin': { 'default': _default_vertical_margin, 'type': int, 'check_func': 'check_range', 'func_args': (0, _max_vertical_margin) }, 'left_margin': { 'default': _default_horizontal_margin, 'type': int, 'check_func': 'check_range', 'func_args': (0, _max_horizontal_margin) }, 'right_margin': { 'default': _default_horizontal_margin, 'type': int, 'check_func': 'check_range', 'func_args': (0, _max_horizontal_margin) }, 'win_x': { 'default': 0, 'type': int, 'check_func': 'check_range', 'func_args': (-(_max_window_positon_x), _max_window_positon_x) }, 'win_y': { 'default': 0, 'type': int, 'check_func': 'check_range', 'func_args': (-(_max_window_positon_y), _max_window_positon_y) }, } def __init__(self): self.set_default_font()