rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def autotrace_font (fontname, metric, glyphs, encoding, magnification): global gf_fontname if not gf_fontname: base = gen_pixel_font (fontname, metric, magnification) gf_fontname = base + 'gf'
def autotrace_font (fontname, gf_file, metric, glyphs, encoding, magnification):
def autotrace_font (fontname, metric, glyphs, encoding, magnification): global gf_fontname if not gf_fontname: base = gen_pixel_font (fontname, metric, magnification) gf_fontname = base + 'gf' t1os = [] font_bbox = (10000,10000,-10000,-10000) progress (_ ("Tracing bitmaps... ")) eps_lines = [] # for single glyph testing. # glyphs = [] for a in glyphs: valid = metric.has_char (a) if not valid: continue valid = make_pbm (gf_fontname, 'char.pbm', a) if not valid: continue (w,h, xo, yo) = read_gf_dims (gf_fontname, a) if not verbose_p: sys.stderr.write('[%d' % a) sys.stderr.flush() success = do_autotrace_one ("char.pbm", '%s-%d' % (fontname, a)) if not success : sys.stderr.write ("(skipping character)]") sys.stderr.flush () continue if not verbose_p: sys.stderr.write(']') sys.stderr.flush() tw = int (round (metric.get_char (a).width / metric.design_size * 1000)) (bbox, t1o) = autotrace_path_to_type1_ops ("char.eps", (h, w, xo, yo), tw) if t1o == '' : continue font_bbox = update_bbox_with_bbox (font_bbox, bbox) t1os.append ('/%s %s ' % (encoding[a] , t1o )) progress ('\n') if pfa_p or ttf_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 1) if ttf_p: shutil.copy2 (fontname + '.pfa', fontname + '.pfx') if pfb_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 0)
valid = make_pbm (gf_fontname, 'char.pbm', a)
valid = make_pbm (gf_file, 'char.pbm', a)
def autotrace_font (fontname, metric, glyphs, encoding, magnification): global gf_fontname if not gf_fontname: base = gen_pixel_font (fontname, metric, magnification) gf_fontname = base + 'gf' t1os = [] font_bbox = (10000,10000,-10000,-10000) progress (_ ("Tracing bitmaps... ")) eps_lines = [] # for single glyph testing. # glyphs = [] for a in glyphs: valid = metric.has_char (a) if not valid: continue valid = make_pbm (gf_fontname, 'char.pbm', a) if not valid: continue (w,h, xo, yo) = read_gf_dims (gf_fontname, a) if not verbose_p: sys.stderr.write('[%d' % a) sys.stderr.flush() success = do_autotrace_one ("char.pbm", '%s-%d' % (fontname, a)) if not success : sys.stderr.write ("(skipping character)]") sys.stderr.flush () continue if not verbose_p: sys.stderr.write(']') sys.stderr.flush() tw = int (round (metric.get_char (a).width / metric.design_size * 1000)) (bbox, t1o) = autotrace_path_to_type1_ops ("char.eps", (h, w, xo, yo), tw) if t1o == '' : continue font_bbox = update_bbox_with_bbox (font_bbox, bbox) t1os.append ('/%s %s ' % (encoding[a] , t1o )) progress ('\n') if pfa_p or ttf_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 1) if ttf_p: shutil.copy2 (fontname + '.pfa', fontname + '.pfx') if pfb_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 0)
(w,h, xo, yo) = read_gf_dims (gf_fontname, a)
(w,h, xo, yo) = read_gf_dims (gf_file, a)
def autotrace_font (fontname, metric, glyphs, encoding, magnification): global gf_fontname if not gf_fontname: base = gen_pixel_font (fontname, metric, magnification) gf_fontname = base + 'gf' t1os = [] font_bbox = (10000,10000,-10000,-10000) progress (_ ("Tracing bitmaps... ")) eps_lines = [] # for single glyph testing. # glyphs = [] for a in glyphs: valid = metric.has_char (a) if not valid: continue valid = make_pbm (gf_fontname, 'char.pbm', a) if not valid: continue (w,h, xo, yo) = read_gf_dims (gf_fontname, a) if not verbose_p: sys.stderr.write('[%d' % a) sys.stderr.flush() success = do_autotrace_one ("char.pbm", '%s-%d' % (fontname, a)) if not success : sys.stderr.write ("(skipping character)]") sys.stderr.flush () continue if not verbose_p: sys.stderr.write(']') sys.stderr.flush() tw = int (round (metric.get_char (a).width / metric.design_size * 1000)) (bbox, t1o) = autotrace_path_to_type1_ops ("char.eps", (h, w, xo, yo), tw) if t1o == '' : continue font_bbox = update_bbox_with_bbox (font_bbox, bbox) t1os.append ('/%s %s ' % (encoding[a] , t1o )) progress ('\n') if pfa_p or ttf_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 1) if ttf_p: shutil.copy2 (fontname + '.pfa', fontname + '.pfx') if pfb_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 0)
success = do_autotrace_one ("char.pbm", '%s-%d' % (fontname, a))
success = do_autotrace_one ("char.pbm", '%s-%d' % (gf_fontname, a))
def autotrace_font (fontname, metric, glyphs, encoding, magnification): global gf_fontname if not gf_fontname: base = gen_pixel_font (fontname, metric, magnification) gf_fontname = base + 'gf' t1os = [] font_bbox = (10000,10000,-10000,-10000) progress (_ ("Tracing bitmaps... ")) eps_lines = [] # for single glyph testing. # glyphs = [] for a in glyphs: valid = metric.has_char (a) if not valid: continue valid = make_pbm (gf_fontname, 'char.pbm', a) if not valid: continue (w,h, xo, yo) = read_gf_dims (gf_fontname, a) if not verbose_p: sys.stderr.write('[%d' % a) sys.stderr.flush() success = do_autotrace_one ("char.pbm", '%s-%d' % (fontname, a)) if not success : sys.stderr.write ("(skipping character)]") sys.stderr.flush () continue if not verbose_p: sys.stderr.write(']') sys.stderr.flush() tw = int (round (metric.get_char (a).width / metric.design_size * 1000)) (bbox, t1o) = autotrace_path_to_type1_ops ("char.eps", (h, w, xo, yo), tw) if t1o == '' : continue font_bbox = update_bbox_with_bbox (font_bbox, bbox) t1os.append ('/%s %s ' % (encoding[a] , t1o )) progress ('\n') if pfa_p or ttf_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 1) if ttf_p: shutil.copy2 (fontname + '.pfa', fontname + '.pfx') if pfb_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 0)
tw = int (round (metric.get_char (a).width / metric.design_size * 1000))
metric_width = metric.get_char (a).width tw = int (round (metric_width / metric.design_size * 1000))
def autotrace_font (fontname, metric, glyphs, encoding, magnification): global gf_fontname if not gf_fontname: base = gen_pixel_font (fontname, metric, magnification) gf_fontname = base + 'gf' t1os = [] font_bbox = (10000,10000,-10000,-10000) progress (_ ("Tracing bitmaps... ")) eps_lines = [] # for single glyph testing. # glyphs = [] for a in glyphs: valid = metric.has_char (a) if not valid: continue valid = make_pbm (gf_fontname, 'char.pbm', a) if not valid: continue (w,h, xo, yo) = read_gf_dims (gf_fontname, a) if not verbose_p: sys.stderr.write('[%d' % a) sys.stderr.flush() success = do_autotrace_one ("char.pbm", '%s-%d' % (fontname, a)) if not success : sys.stderr.write ("(skipping character)]") sys.stderr.flush () continue if not verbose_p: sys.stderr.write(']') sys.stderr.flush() tw = int (round (metric.get_char (a).width / metric.design_size * 1000)) (bbox, t1o) = autotrace_path_to_type1_ops ("char.eps", (h, w, xo, yo), tw) if t1o == '' : continue font_bbox = update_bbox_with_bbox (font_bbox, bbox) t1os.append ('/%s %s ' % (encoding[a] , t1o )) progress ('\n') if pfa_p or ttf_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 1) if ttf_p: shutil.copy2 (fontname + '.pfa', fontname + '.pfx') if pfb_p: to_type1 (t1os, font_bbox, fontname, encoding, magnification, 0)
autotrace_font (basename, metric, glyph_range, encoding, magnification)
if not gf_fontname: base = gen_pixel_font (basename, metric, magnification) gf_fontname = base + 'gf' autotrace_font (basename, gf_fontname, metric, glyph_range, encoding, magnification)
def __getitem__ (self, key): return self.__dict__[key]
'TeX text': 'tex256.enc',
def interpolate (str): str = string.replace (str, '{', '(') str = string.replace (str, '}', ')s') str = string.replace (str, '$', '%') return str
stat = system ("fontforge -usage > pfv 2>&1", ignore_error = 1) fontforge_cmd = 'fontforge'
global fontforge_cmd stat = system ("fontforge -usage > pfv 2>&1 > /dev/null", ignore_error = 1)
def check_pfaedit_scripting (): stat = system ("fontforge -usage > pfv 2>&1", ignore_error = 1) fontforge_cmd = 'fontforge' if stat <> 0: stat = system ("pfaedit -usage > pfv 2>&1", ignore_error = 1) if stat == 0: fontforge_cmd = 'pfaedit' if stat <> 0: warning ("Command `fontforge -usage' failed. Cannot simplify or convert to TTF.") return 0 if fontforge_cmd == 'pfaedit' and \ re.search ("-script", open ('pfv').read()) == None: warning ("pfaedit does not support -script. Install 020215 or later.\nCannot simplify or convert to TTF.\n") return 0 return 1
prefixes = [("cmtt", "CMTypewriter"), ("cmvtt", "CMVariableWidthTypewriter"), ("cmss", "CMSans"), ("cm", "CM")]
prefixes = [("cmtt", "CModernTypewriter"), ("cmvtt", "CModernVariableWidthTypewriter"), ("cmss", "CModernSans"), ("cm", "CModern")]
def cm_guess_font_info (filename, fontinfo): # urg. filename = re.sub ("cm(.*)tt", r"cmtt\1", filename) m = re.search ("([0-9]+)$", filename) design_size = '' if m: design_size = string.atoi (m.group (1)) fontinfo['DesignSize'] = design_size prefixes = [("cmtt", "CMTypewriter"), ("cmvtt", "CMVariableWidthTypewriter"), ("cmss", "CMSans"), ("cm", "CM")] family = '' for (k, v) in prefixes: if re.search (k, filename): family = v if k == 'cmtt': fontinfo['isFixedPitch'] = 'true' filename = re.sub (k, '', filename) break # shapes prefixes = [("r", "Roman"), ("mi", "Math italic"), ("u", "Unslanted italic"), ("sl", "Oblique"), ("csc", "Small Caps"), ("ex", "Math extension"), ("ti", "Text italic"), ("i", "Italic")] shape = '' for (k, v) in prefixes: if re.search (k, filename): shape = v filename = re.sub (k, '', filename) prefixes = [("b", "Bold"), ("d", "Demi bold")] weight = 'Regular' for (k, v) in prefixes: if re.search (k, filename): weight = v filename = re.sub (k, '', filename) prefixes = [("c", "Condensed"), ("x", "Extended")] stretch = '' for (k, v) in prefixes: if re.search (k, filename): stretch = v filename = re.sub (k, '', filename) fontinfo['ItalicAngle'] = 0 if re.search ('[Ii]talic', shape) or re.search ('[Oo]blique', shape): a = -14 if re.search ("Sans", family): a = -12 fontinfo ["ItalicAngle"] = a fontinfo['Weight'] = weight fontinfo['FamilyName'] = family full = '%s %s %s %s %dpt' \ % (family, shape, weight, stretch, design_size) full = re.sub (" +", ' ', full) fontinfo['FullName'] = full fontinfo['FontName'] = derive_font_name (family, full) return fontinfo
prefixes = [("ecss", "EuropeanCMSans"), ("ectt", "EuropeanCMTypewriter"), ("ec", "EuropeanCM")]
prefixes = [("ecss", "ECModernSans"), ("ectt", "ECModernTypewriter"), ("ec", "ECModern")]
def ec_guess_font_info (filename, fontinfo): design_size = 12 m = re.search ("([0-9]+)$", filename) if m: design_size = string.atoi (m.group (1)) fontinfo['DesignSize'] = design_size prefixes = [("ecss", "EuropeanCMSans"), ("ectt", "EuropeanCMTypewriter"), ("ec", "EuropeanCM")] family = '' for (k, v) in prefixes: if re.search (k, filename): if k == 'ectt': fontinfo['isFixedPitch'] = 'true' family = v filename = re.sub (k, '', filename) break # shapes prefixes = [("r", "Roman"), ("mi", "Math italic"), ("u", "Unslanted italic"), ("sl", "Oblique"), ("cc", "Small caps"), ("ex", "Math extension"), ("ti", "Italic"), ("i", "Italic")] shape = '' for (k, v) in prefixes: if re.search (k, filename): shape = v filename = re.sub (k, '', filename) prefixes = [("b", "Bold"), ("d", "Demi bold")] weight = 'Regular' for (k, v) in prefixes: if re.search (k, filename): weight = v filename = re.sub (k, '', filename) prefixes = [("c", "Condensed"), ("x", "Extended")] stretch = '' for (k, v) in prefixes: if re.search (k, filename): stretch = v filename = re.sub (k, '', filename) fontinfo['ItalicAngle'] = 0 if re.search ('[Ii]talic', shape) or re.search ('[Oo]blique', shape): a = -14 if re.search ("Sans", family): a = -12 fontinfo ["ItalicAngle"] = a fontinfo['Weight'] = weight fontinfo['FamilyName'] = family full = '%s %s %s %s %dpt' \ % (family, shape, weight, stretch, design_size) full = re.sub (" +", ' ', full) fontinfo['FontName'] = derive_font_name (family, full) fontinfo['FullName'] = full return fontinfo
str = string.replace (str, '}', ')s') str = string.replace (str, '$', '%') return str if prefix <> '@' + 'prefix@': exec_prefix = interpolate (exec_prefix) % vars() datadir = os.path.join (interpolate (datadir) % vars() , 'mftrace') libdir = interpolate (libdir) % vars()
str = string.replace (str, '}', ')s') str = string.replace (str, '$', '%') return str if prefix != '@' + 'prefix@': exec_prefix = interpolate (exec_prefix) % vars () datadir = os.path.join (interpolate (datadir) % vars (), 'mftrace') libdir = interpolate (libdir) % vars ()
def interpolate (str): str = string.replace (str, '{', '(') str = string.replace (str, '}', ')s') str = string.replace (str, '$', '%') return str
sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001--2002'))
sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001--2004'))
def warranty (): identify (sys.stdout) sys.stdout.write ('\n') sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001--2002')) sys.stdout.write ('\n') sys.stdout.write (' Han-Wen Nienhuys') sys.stdout.write (' Jan Nieuwenhuizen') sys.stdout.write ('\n') sys.stdout.write (_ (r'''
l = o[2]
lst = o[2]
def getopt_args (opts): '''Construct arguments (LONG, SHORT) for getopt from list of options.''' short = '' long = [] for o in opts: if o[1]: short = short + o[1] if o[0]: short = short + ':' if o[2]: l = o[2] if o[0]: l = l + '=' long.append (l) return (short, long)
l = l + '=' long.append (l)
lst = lst + '=' long.append (lst)
def getopt_args (opts): '''Construct arguments (LONG, SHORT) for getopt from list of options.''' short = '' long = [] for o in opts: if o[1]: short = short + o[1] if o[0]: short = short + ':' if o[2]: l = o[2] if o[0]: l = l + '=' long.append (l) return (short, long)
('', '', 'simplify', _("Simplify using fontforge")), ('FILE', '', 'gffile', _("Use gf FILE instead of running Metafont")), ('DIR', 'I', 'include', _("Add to path for searching files")), ('LIST','', 'glyphs', _('Process only these glyphs. LIST is comma separated')), ('FILE', '', 'tfmfile' , _("Use FILE for the TFM file")), ('FILE', 'o', 'output-base', _("Set output file name")), ('ENC', 'e', 'encoding', _("Use encoding file ENC")), ('', 't', 'truetype', _("Generate TrueType file (requires fontforge).")), ('', '', 'keep-trying', _("Don't stop if tracing fails")),
('', '', 'simplify', _ ("Simplify using fontforge")), ('FILE', '', 'gffile', _ ("Use gf FILE instead of running Metafont")), ('DIR', 'I', 'include', _ ("Add to path for searching files")), ('LIST', '', 'glyphs', _ ('Process only these glyphs. LIST is comma separated')), ('FILE', '', 'tfmfile', _ ("Use FILE for the TFM file")), ('ENC', 'e', 'encoding', _ ("Use encoding file ENC")), ('', 't', 'truetype', _ ("Generate TrueType file (requires fontforge).")), ('', '', 'keep-trying', _ ("Don't stop if tracing fails")),
def strip_extension (f, ext): (p, e) = os.path.splitext (f) if e == ext: e = '' return p + e
('', '', 'noround', _ ("Don't round coordinates of control points to integer values (use with --grid)")),
('', '', 'noround', _ ("Do not round coordinates of control points \n to integer values (use with --grid)")),
def strip_extension (f, ext): (p, e) = os.path.splitext (f) if e == ext: e = '' return p + e
return trace_binary + opts + backend_options + " --output-file=char.eps %s " % fn
return trace_binary + opts + backend_options \ + " --output-file=char.eps %s " % fn
def autotrace_command (fn, opts): opts = " " + opts + " --background-color=FFFFFF --output-format=eps --input-format=pbm " return trace_binary + opts + backend_options + " --output-file=char.eps %s " % fn
+ ' -u %d ' % potrace_scale \ + backend_options + " -q -c --eps --output=char.eps %s " % (fn)
+ ' -u %d ' % potrace_scale \ + backend_options \ + " -q -c --eps --output=char.eps %s " % (fn)
def potrace_command (fn, opts): return trace_binary + opts \ + ' -u %d ' % potrace_scale \ + backend_options + " -q -c --eps --output=char.eps %s " % (fn)
if status <> 0:
if status != 0:
def trace_one (pbmfile, id): """ Run tracer, do error handling """ status = system (trace_command (pbmfile, ''), 1) if status == 2: sys.stderr.write ("\nUser interrupt. Exiting\n") sys.exit(2) if status == 0 and keep_temp_dir_p: shutil.copy2 (pbmfile, '%s.pbm' % id) shutil.copy2 ('char.eps', '%s.eps' % id) if status <> 0: error_file = os.path.join (origdir, 'trace-bug-%s.pbm' % id) shutil.copy2 (pbmfile, error_file) msg = """Trace failed on bitmap. Bitmap left in `%s\'
Please submit a bugreport to %s development.""" % (error_file, trace_command (error_file, ''), trace_binary)
Please submit a bugreport to %s development.""" \ % (error_file, trace_command (error_file, ''), trace_binary)
def trace_one (pbmfile, id): """ Run tracer, do error handling """ status = system (trace_command (pbmfile, ''), 1) if status == 2: sys.stderr.write ("\nUser interrupt. Exiting\n") sys.exit(2) if status == 0 and keep_temp_dir_p: shutil.copy2 (pbmfile, '%s.pbm' % id) shutil.copy2 ('char.eps', '%s.eps' % id) if status <> 0: error_file = os.path.join (origdir, 'trace-bug-%s.pbm' % id) shutil.copy2 (pbmfile, error_file) msg = """Trace failed on bitmap. Bitmap left in `%s\'
l = []
lst = []
def unzip_pairs (tups): l = [] while tups: l = l + list (tups[0]) tups = tups[1:] return l
l = l + list (tups[0])
lst = lst + list (tups[0])
def unzip_pairs (tups): l = [] while tups: l = l + list (tups[0]) tups = tups[1:] return l
return l
return lst
def unzip_pairs (tups): l = [] while tups: l = l + list (tups[0]) tups = tups[1:] return l
bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '*u\n':
bbox = (10000, 10000, -10000, -10000) while ls and ls[0] != '*u\n':
def autotrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid): inv_scale = 1000.0/magnification (size_y, size_x, off_x,off_y)= map(lambda m, s=inv_scale : m * s, bitmap_metrics) ls = open (at_file).readlines () bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '*u\n': ls = ls[1:] if ls == []: return (bbox, '') ls = ls[1:] commands = [] while ls[0] <> '*U\n': l = ls[0] ls = ls[1:] toks = string.split (l) if len(toks) < 1: continue cmd= toks[-1] args = map (lambda m, s=inv_scale : s * string.atof(m), toks[:-1]) if round_to_int: args = zip_to_pairs (map (round, args)) else : args = zip_to_pairs (args) commands.append ((cmd,args)) expand = { 'l': 'rlineto', 'm': 'rmoveto', 'c': 'rrcurveto', 'f': 'closepath' , } cx = 0 cy = size_y - off_y -1 # t1asm seems to fuck up when using sbw. Oh well. t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid) bbox = (10000,10000,-10000,-10000) for (c,args) in commands: na = [] for a in args: (nx, ny) = a if c == 'l' or c == 'c': bbox = update_bbox_with_point (bbox, a) na.append( (nx -cx, ny -cy) ) (cx, cy) = (nx, ny) a = na c = expand[c] if round_to_int: a = map (lambda x: '%d' % int (round (x)), unzip_pairs (a)) else : a = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (a)) t1_outline = t1_outline + ' %s %s\n' % (string.join (a),c) t1_outline = t1_outline + ' endchar ' t1_outline = '{\n %s } |- \n' % t1_outline return (bbox, t1_outline)
while ls[0] <> '*U\n': l = ls[0]
while ls[0] != '*U\n': ell = ls[0]
def autotrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid): inv_scale = 1000.0/magnification (size_y, size_x, off_x,off_y)= map(lambda m, s=inv_scale : m * s, bitmap_metrics) ls = open (at_file).readlines () bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '*u\n': ls = ls[1:] if ls == []: return (bbox, '') ls = ls[1:] commands = [] while ls[0] <> '*U\n': l = ls[0] ls = ls[1:] toks = string.split (l) if len(toks) < 1: continue cmd= toks[-1] args = map (lambda m, s=inv_scale : s * string.atof(m), toks[:-1]) if round_to_int: args = zip_to_pairs (map (round, args)) else : args = zip_to_pairs (args) commands.append ((cmd,args)) expand = { 'l': 'rlineto', 'm': 'rmoveto', 'c': 'rrcurveto', 'f': 'closepath' , } cx = 0 cy = size_y - off_y -1 # t1asm seems to fuck up when using sbw. Oh well. t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid) bbox = (10000,10000,-10000,-10000) for (c,args) in commands: na = [] for a in args: (nx, ny) = a if c == 'l' or c == 'c': bbox = update_bbox_with_point (bbox, a) na.append( (nx -cx, ny -cy) ) (cx, cy) = (nx, ny) a = na c = expand[c] if round_to_int: a = map (lambda x: '%d' % int (round (x)), unzip_pairs (a)) else : a = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (a)) t1_outline = t1_outline + ' %s %s\n' % (string.join (a),c) t1_outline = t1_outline + ' endchar ' t1_outline = '{\n %s } |- \n' % t1_outline return (bbox, t1_outline)
toks = string.split (l) if len(toks) < 1:
toks = string.split (ell) if len (toks) < 1:
def autotrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid): inv_scale = 1000.0/magnification (size_y, size_x, off_x,off_y)= map(lambda m, s=inv_scale : m * s, bitmap_metrics) ls = open (at_file).readlines () bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '*u\n': ls = ls[1:] if ls == []: return (bbox, '') ls = ls[1:] commands = [] while ls[0] <> '*U\n': l = ls[0] ls = ls[1:] toks = string.split (l) if len(toks) < 1: continue cmd= toks[-1] args = map (lambda m, s=inv_scale : s * string.atof(m), toks[:-1]) if round_to_int: args = zip_to_pairs (map (round, args)) else : args = zip_to_pairs (args) commands.append ((cmd,args)) expand = { 'l': 'rlineto', 'm': 'rmoveto', 'c': 'rrcurveto', 'f': 'closepath' , } cx = 0 cy = size_y - off_y -1 # t1asm seems to fuck up when using sbw. Oh well. t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid) bbox = (10000,10000,-10000,-10000) for (c,args) in commands: na = [] for a in args: (nx, ny) = a if c == 'l' or c == 'c': bbox = update_bbox_with_point (bbox, a) na.append( (nx -cx, ny -cy) ) (cx, cy) = (nx, ny) a = na c = expand[c] if round_to_int: a = map (lambda x: '%d' % int (round (x)), unzip_pairs (a)) else : a = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (a)) t1_outline = t1_outline + ' %s %s\n' % (string.join (a),c) t1_outline = t1_outline + ' endchar ' t1_outline = '{\n %s } |- \n' % t1_outline return (bbox, t1_outline)
a = map (lambda x: '%d' % int (round (x)), unzip_pairs (a)) else : a = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (a)) t1_outline = t1_outline + ' %s %s\n' % (string.join (a),c)
a = map (lambda x: '%d' % int (round (x)), unzip_pairs (a)) else: a = map (lambda x: '%d %d div' \ % (int (round (x * potrace_scale/inv_scale)), int (round (potrace_scale/inv_scale))), unzip_pairs (a)) t1_outline = t1_outline + ' %s %s\n' % (string.join (a), c)
def autotrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid): inv_scale = 1000.0/magnification (size_y, size_x, off_x,off_y)= map(lambda m, s=inv_scale : m * s, bitmap_metrics) ls = open (at_file).readlines () bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '*u\n': ls = ls[1:] if ls == []: return (bbox, '') ls = ls[1:] commands = [] while ls[0] <> '*U\n': l = ls[0] ls = ls[1:] toks = string.split (l) if len(toks) < 1: continue cmd= toks[-1] args = map (lambda m, s=inv_scale : s * string.atof(m), toks[:-1]) if round_to_int: args = zip_to_pairs (map (round, args)) else : args = zip_to_pairs (args) commands.append ((cmd,args)) expand = { 'l': 'rlineto', 'm': 'rmoveto', 'c': 'rrcurveto', 'f': 'closepath' , } cx = 0 cy = size_y - off_y -1 # t1asm seems to fuck up when using sbw. Oh well. t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid) bbox = (10000,10000,-10000,-10000) for (c,args) in commands: na = [] for a in args: (nx, ny) = a if c == 'l' or c == 'c': bbox = update_bbox_with_point (bbox, a) na.append( (nx -cx, ny -cy) ) (cx, cy) = (nx, ny) a = na c = expand[c] if round_to_int: a = map (lambda x: '%d' % int (round (x)), unzip_pairs (a)) else : a = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (a)) t1_outline = t1_outline + ' %s %s\n' % (string.join (a),c) t1_outline = t1_outline + ' endchar ' t1_outline = '{\n %s } |- \n' % t1_outline return (bbox, t1_outline)
bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '0 setgray\n':
bbox = (10000, 10000, -10000, -10000) while ls and ls[0] != '0 setgray\n':
def potrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid): inv_scale = 1000.0/magnification (size_y, size_x, off_x, off_y)= map(lambda m, s=inv_scale : m * s, bitmap_metrics) ls = open (at_file).readlines () bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '0 setgray\n': ls = ls[1:] if ls == []: return (bbox, '') ls = ls[1:] commands = [] while ls and ls[0] <> 'grestore\n': l = ls[0] ls = ls[1:] if l == 'fill\n': continue toks = string.split (l) if len(toks) < 1: continue cmd= toks[-1] args = map (lambda m, s=inv_scale : s * string.atof (m), toks[:-1]) args = zip_to_pairs (args) commands.append ((cmd,args)) # t1asm seems to fuck up when using sbw. Oh well. t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid) bbox = (10000,10000,-10000,-10000) # Type1 fonts have relative coordinates (doubly relative for # rrcurveto), so must convert moveto and rcurveto. z = (0.0, size_y - off_y - 1.0) nc = [] for (c, args) in commands: args = map (lambda x: (x[0] * (1.0 / potrace_scale), x[1] * (1.0/potrace_scale)), args) if c == 'moveto': args = [(args[0][0]-z[0], args[0][1] - z[1])] zs = [] for a in args: lz= (z[0] + a[0], z[1] + a[1]) bbox = update_bbox_with_point (bbox, lz) zs.append (lz) if round_to_int: last_discr_z = (int (round (z[0])), int (round (z[1]))) else : last_discr_z = (z[0], z[1]) args = [] for a in zs: if round_to_int: a = (int (round (a[0])), int (round (a[1]))) else : a = (a[0], a[1]) args.append ( (a[0] - last_discr_z[0], a[1] - last_discr_z[1])) last_discr_z = a if zs: z = zs[-1] c = { 'rcurveto': 'rrcurveto', 'moveto': 'rmoveto', 'closepath': 'closepath', 'rlineto' : 'rlineto'}[c] if c == 'rmoveto': t1_outline += ' closepath ' if round_to_int: args = map (lambda x: '%d' % int (round (x)), unzip_pairs (args)) else : args = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (args)) t1_outline = t1_outline + ' %s %s\n' % (string.join (args),c) t1_outline = t1_outline + ' endchar ' t1_outline = '{\n %s } |- \n' % t1_outline return (bbox, t1_outline)
while ls and ls[0] <> 'grestore\n': l = ls[0]
while ls and ls[0] != 'grestore\n': ell = ls[0]
def potrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid): inv_scale = 1000.0/magnification (size_y, size_x, off_x, off_y)= map(lambda m, s=inv_scale : m * s, bitmap_metrics) ls = open (at_file).readlines () bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '0 setgray\n': ls = ls[1:] if ls == []: return (bbox, '') ls = ls[1:] commands = [] while ls and ls[0] <> 'grestore\n': l = ls[0] ls = ls[1:] if l == 'fill\n': continue toks = string.split (l) if len(toks) < 1: continue cmd= toks[-1] args = map (lambda m, s=inv_scale : s * string.atof (m), toks[:-1]) args = zip_to_pairs (args) commands.append ((cmd,args)) # t1asm seems to fuck up when using sbw. Oh well. t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid) bbox = (10000,10000,-10000,-10000) # Type1 fonts have relative coordinates (doubly relative for # rrcurveto), so must convert moveto and rcurveto. z = (0.0, size_y - off_y - 1.0) nc = [] for (c, args) in commands: args = map (lambda x: (x[0] * (1.0 / potrace_scale), x[1] * (1.0/potrace_scale)), args) if c == 'moveto': args = [(args[0][0]-z[0], args[0][1] - z[1])] zs = [] for a in args: lz= (z[0] + a[0], z[1] + a[1]) bbox = update_bbox_with_point (bbox, lz) zs.append (lz) if round_to_int: last_discr_z = (int (round (z[0])), int (round (z[1]))) else : last_discr_z = (z[0], z[1]) args = [] for a in zs: if round_to_int: a = (int (round (a[0])), int (round (a[1]))) else : a = (a[0], a[1]) args.append ( (a[0] - last_discr_z[0], a[1] - last_discr_z[1])) last_discr_z = a if zs: z = zs[-1] c = { 'rcurveto': 'rrcurveto', 'moveto': 'rmoveto', 'closepath': 'closepath', 'rlineto' : 'rlineto'}[c] if c == 'rmoveto': t1_outline += ' closepath ' if round_to_int: args = map (lambda x: '%d' % int (round (x)), unzip_pairs (args)) else : args = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (args)) t1_outline = t1_outline + ' %s %s\n' % (string.join (args),c) t1_outline = t1_outline + ' endchar ' t1_outline = '{\n %s } |- \n' % t1_outline return (bbox, t1_outline)
if l == 'fill\n':
if ell == 'fill\n':
def potrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid): inv_scale = 1000.0/magnification (size_y, size_x, off_x, off_y)= map(lambda m, s=inv_scale : m * s, bitmap_metrics) ls = open (at_file).readlines () bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '0 setgray\n': ls = ls[1:] if ls == []: return (bbox, '') ls = ls[1:] commands = [] while ls and ls[0] <> 'grestore\n': l = ls[0] ls = ls[1:] if l == 'fill\n': continue toks = string.split (l) if len(toks) < 1: continue cmd= toks[-1] args = map (lambda m, s=inv_scale : s * string.atof (m), toks[:-1]) args = zip_to_pairs (args) commands.append ((cmd,args)) # t1asm seems to fuck up when using sbw. Oh well. t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid) bbox = (10000,10000,-10000,-10000) # Type1 fonts have relative coordinates (doubly relative for # rrcurveto), so must convert moveto and rcurveto. z = (0.0, size_y - off_y - 1.0) nc = [] for (c, args) in commands: args = map (lambda x: (x[0] * (1.0 / potrace_scale), x[1] * (1.0/potrace_scale)), args) if c == 'moveto': args = [(args[0][0]-z[0], args[0][1] - z[1])] zs = [] for a in args: lz= (z[0] + a[0], z[1] + a[1]) bbox = update_bbox_with_point (bbox, lz) zs.append (lz) if round_to_int: last_discr_z = (int (round (z[0])), int (round (z[1]))) else : last_discr_z = (z[0], z[1]) args = [] for a in zs: if round_to_int: a = (int (round (a[0])), int (round (a[1]))) else : a = (a[0], a[1]) args.append ( (a[0] - last_discr_z[0], a[1] - last_discr_z[1])) last_discr_z = a if zs: z = zs[-1] c = { 'rcurveto': 'rrcurveto', 'moveto': 'rmoveto', 'closepath': 'closepath', 'rlineto' : 'rlineto'}[c] if c == 'rmoveto': t1_outline += ' closepath ' if round_to_int: args = map (lambda x: '%d' % int (round (x)), unzip_pairs (args)) else : args = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (args)) t1_outline = t1_outline + ' %s %s\n' % (string.join (args),c) t1_outline = t1_outline + ' endchar ' t1_outline = '{\n %s } |- \n' % t1_outline return (bbox, t1_outline)
toks = string.split (l) if len(toks) < 1:
toks = string.split (ell) if len (toks) < 1:
def potrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid): inv_scale = 1000.0/magnification (size_y, size_x, off_x, off_y)= map(lambda m, s=inv_scale : m * s, bitmap_metrics) ls = open (at_file).readlines () bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '0 setgray\n': ls = ls[1:] if ls == []: return (bbox, '') ls = ls[1:] commands = [] while ls and ls[0] <> 'grestore\n': l = ls[0] ls = ls[1:] if l == 'fill\n': continue toks = string.split (l) if len(toks) < 1: continue cmd= toks[-1] args = map (lambda m, s=inv_scale : s * string.atof (m), toks[:-1]) args = zip_to_pairs (args) commands.append ((cmd,args)) # t1asm seems to fuck up when using sbw. Oh well. t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid) bbox = (10000,10000,-10000,-10000) # Type1 fonts have relative coordinates (doubly relative for # rrcurveto), so must convert moveto and rcurveto. z = (0.0, size_y - off_y - 1.0) nc = [] for (c, args) in commands: args = map (lambda x: (x[0] * (1.0 / potrace_scale), x[1] * (1.0/potrace_scale)), args) if c == 'moveto': args = [(args[0][0]-z[0], args[0][1] - z[1])] zs = [] for a in args: lz= (z[0] + a[0], z[1] + a[1]) bbox = update_bbox_with_point (bbox, lz) zs.append (lz) if round_to_int: last_discr_z = (int (round (z[0])), int (round (z[1]))) else : last_discr_z = (z[0], z[1]) args = [] for a in zs: if round_to_int: a = (int (round (a[0])), int (round (a[1]))) else : a = (a[0], a[1]) args.append ( (a[0] - last_discr_z[0], a[1] - last_discr_z[1])) last_discr_z = a if zs: z = zs[-1] c = { 'rcurveto': 'rrcurveto', 'moveto': 'rmoveto', 'closepath': 'closepath', 'rlineto' : 'rlineto'}[c] if c == 'rmoveto': t1_outline += ' closepath ' if round_to_int: args = map (lambda x: '%d' % int (round (x)), unzip_pairs (args)) else : args = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (args)) t1_outline = t1_outline + ' %s %s\n' % (string.join (args),c) t1_outline = t1_outline + ' endchar ' t1_outline = '{\n %s } |- \n' % t1_outline return (bbox, t1_outline)
args = map (lambda x: '%d' % int (round (x)), unzip_pairs (args)) else : args = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (args)) t1_outline = t1_outline + ' %s %s\n' % (string.join (args),c)
args = map (lambda x: '%d' % int (round (x)), unzip_pairs (args)) else: args = map (lambda x: '%d %d div' \ % (int (round (x*potrace_scale/inv_scale)), int (round (potrace_scale/inv_scale))), unzip_pairs (args)) t1_outline = t1_outline + ' %s %s\n' % (string.join (args), c)
def potrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid): inv_scale = 1000.0/magnification (size_y, size_x, off_x, off_y)= map(lambda m, s=inv_scale : m * s, bitmap_metrics) ls = open (at_file).readlines () bbox = (10000,10000,-10000,-10000) while ls and ls[0] <> '0 setgray\n': ls = ls[1:] if ls == []: return (bbox, '') ls = ls[1:] commands = [] while ls and ls[0] <> 'grestore\n': l = ls[0] ls = ls[1:] if l == 'fill\n': continue toks = string.split (l) if len(toks) < 1: continue cmd= toks[-1] args = map (lambda m, s=inv_scale : s * string.atof (m), toks[:-1]) args = zip_to_pairs (args) commands.append ((cmd,args)) # t1asm seems to fuck up when using sbw. Oh well. t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid) bbox = (10000,10000,-10000,-10000) # Type1 fonts have relative coordinates (doubly relative for # rrcurveto), so must convert moveto and rcurveto. z = (0.0, size_y - off_y - 1.0) nc = [] for (c, args) in commands: args = map (lambda x: (x[0] * (1.0 / potrace_scale), x[1] * (1.0/potrace_scale)), args) if c == 'moveto': args = [(args[0][0]-z[0], args[0][1] - z[1])] zs = [] for a in args: lz= (z[0] + a[0], z[1] + a[1]) bbox = update_bbox_with_point (bbox, lz) zs.append (lz) if round_to_int: last_discr_z = (int (round (z[0])), int (round (z[1]))) else : last_discr_z = (z[0], z[1]) args = [] for a in zs: if round_to_int: a = (int (round (a[0])), int (round (a[1]))) else : a = (a[0], a[1]) args.append ( (a[0] - last_discr_z[0], a[1] - last_discr_z[1])) last_discr_z = a if zs: z = zs[-1] c = { 'rcurveto': 'rrcurveto', 'moveto': 'rmoveto', 'closepath': 'closepath', 'rlineto' : 'rlineto'}[c] if c == 'rmoveto': t1_outline += ' closepath ' if round_to_int: args = map (lambda x: '%d' % int (round (x)), unzip_pairs (args)) else : args = map (lambda x: '%d %d div' % (int (round (x * potrace_scale/inv_scale)), int( round (potrace_scale/inv_scale))), unzip_pairs (args)) t1_outline = t1_outline + ' %s %s\n' % (string.join (args),c) t1_outline = t1_outline + ' endchar ' t1_outline = '{\n %s } |- \n' % t1_outline return (bbox, t1_outline)
str = ' %d array\n0 1 %d {1 index exch /.notdef put} for\n' % (len (encoding), len(encoding)-1)
str = ' %d array\n0 1 %d {1 index exch /.notdef put} for\n' \ % (len (encoding), len (encoding)-1)
str = ' %d array\n0 1 %d {1 index exch /.notdef put} for\n' % (len (encoding), len(encoding)-1)
'CharBBox': '0 0 0 0'
'CharBBox': '0 0 0 0',
/.notdef { 0 0 hsbw endchar } |-
stat = system ("fontforge -usage > pfv 2>&1 > /dev/null", ignore_error = 1) if stat <> 0:
stat = system ("fontforge -usage > pfv 2>&1 > /dev/null", ignore_error = 1) if stat != 0:
def check_pfaedit_scripting (): global fontforge_cmd stat = system ("fontforge -usage > pfv 2>&1 > /dev/null", ignore_error = 1) if stat <> 0: stat = system ("pfaedit -usage > pfv 2>&1", ignore_error = 1) if stat == 0: fontforge_cmd = 'pfaedit' else: fontforge_cmd = 'fontforge' if stat <> 0: warning ("Command `fontforge -usage' failed. Cannot simplify or convert to TTF.") return 0 if fontforge_cmd == 'pfaedit' and \ re.search ("-script", open ('pfv').read()) == None: warning ("pfaedit does not support -script. Install 020215 or later.\nCannot simplify or convert to TTF.\n") return 0 return 1
if stat <> 0: warning ("Command `fontforge -usage' failed. Cannot simplify or convert to TTF.")
if stat != 0: warning ("Command `fontforge -usage' failed. Cannot simplify or convert to TTF.")
def check_pfaedit_scripting (): global fontforge_cmd stat = system ("fontforge -usage > pfv 2>&1 > /dev/null", ignore_error = 1) if stat <> 0: stat = system ("pfaedit -usage > pfv 2>&1", ignore_error = 1) if stat == 0: fontforge_cmd = 'pfaedit' else: fontforge_cmd = 'fontforge' if stat <> 0: warning ("Command `fontforge -usage' failed. Cannot simplify or convert to TTF.") return 0 if fontforge_cmd == 'pfaedit' and \ re.search ("-script", open ('pfv').read()) == None: warning ("pfaedit does not support -script. Install 020215 or later.\nCannot simplify or convert to TTF.\n") return 0 return 1
if fontforge_cmd == 'pfaedit' and \ re.search ("-script", open ('pfv').read()) == None: warning ("pfaedit does not support -script. Install 020215 or later.\nCannot simplify or convert to TTF.\n")
if fontforge_cmd == 'pfaedit' \ and re.search ("-script", open ('pfv').read ()) == None: warning ("pfaedit does not support -script. Install 020215 or later.\nCannot simplify or convert to TTF.\n")
def check_pfaedit_scripting (): global fontforge_cmd stat = system ("fontforge -usage > pfv 2>&1 > /dev/null", ignore_error = 1) if stat <> 0: stat = system ("pfaedit -usage > pfv 2>&1", ignore_error = 1) if stat == 0: fontforge_cmd = 'pfaedit' else: fontforge_cmd = 'fontforge' if stat <> 0: warning ("Command `fontforge -usage' failed. Cannot simplify or convert to TTF.") return 0 if fontforge_cmd == 'pfaedit' and \ re.search ("-script", open ('pfv').read()) == None: warning ("pfaedit does not support -script. Install 020215 or later.\nCannot simplify or convert to TTF.\n") return 0 return 1
fontinfo["FamilyName"] = family fontinfo['FullName'] = '%s %s %s designed at %spt' % (family, shape, weight, design_size)
fontinfo['FamilyName'] = family fontinfo['FullName'] = '%s %s %s designed at %spt' \ % (family, shape, weight, design_size)
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
fi = { 'FontName' : filename, 'FamilyName' : filename, "Weight" : 'regular', "ItalicAngle" : 0, 'FullName' : filename}
fi = { 'FontName': filename, 'FamilyName': filename, 'Weight': 'regular', 'ItalicAngle': 0, 'FullName': filename, }
def guess_fontinfo (filename): fi = { 'FontName' : filename, 'FamilyName' : filename, "Weight" : 'regular', "ItalicAngle" : 0, 'FullName' : filename} if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi global afmfile if not afmfile: afmfile = find_file (filename + '.afm') if afmfile: afmfile = os.path.abspath (afmfile) afm_struct = afm.read_afm_file (afmfile) fi.update (afm_struct.__dict__) return fi
outname = ''
output_name = ''
def guess_fontinfo (filename): fi = { 'FontName' : filename, 'FamilyName' : filename, "Weight" : 'regular', "ItalicAngle" : 0, 'FullName' : filename} if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi global afmfile if not afmfile: afmfile = find_file (filename + '.afm') if afmfile: afmfile = os.path.abspath (afmfile) afm_struct = afm.read_afm_file (afmfile) fi.update (afm_struct.__dict__) return fi
glyph_range = map (string.atoi, string.split(a, ',')) elif o == '--output-base' or o == '-o': outname = a elif o == '--tfmfile' :
glyph_range = map (string.atoi, string.split (a, ',')) elif o == '--tfmfile':
def guess_fontinfo (filename): fi = { 'FontName' : filename, 'FamilyName' : filename, "Weight" : 'regular', "ItalicAngle" : 0, 'FullName' : filename} if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi global afmfile if not afmfile: afmfile = find_file (filename + '.afm') if afmfile: afmfile = os.path.abspath (afmfile) afm_struct = afm.read_afm_file (afmfile) fi.update (afm_struct.__dict__) return fi
raise 'Ugh -- forgot to implement option %s. :)' % o backend_options = getenv('MFTRACE_BACKEND_OPTIONS','') stat = os.system ('potrace --version > /dev/null') if trace_binary <> 'autotrace' and stat == 0:
raise 'Ugh -- forgot to implement option: %s.)' % o backend_options = getenv ('MFTRACE_BACKEND_OPTIONS', '') stat = os.system ('potrace --version > /dev/null') if trace_binary != 'autotrace' and stat == 0:
def guess_fontinfo (filename): fi = { 'FontName' : filename, 'FamilyName' : filename, "Weight" : 'regular', "ItalicAngle" : 0, 'FullName' : filename} if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi global afmfile if not afmfile: afmfile = find_file (filename + '.afm') if afmfile: afmfile = os.path.abspath (afmfile) afm_struct = afm.read_afm_file (afmfile) fi.update (afm_struct.__dict__) return fi
stat = os.system ('autotrace --version > /dev/null') if trace_binary <> 'potrace' and stat == 0:
stat = os.system ('autotrace --version > /dev/null') if trace_binary != 'potrace' and stat == 0:
def guess_fontinfo (filename): fi = { 'FontName' : filename, 'FamilyName' : filename, "Weight" : 'regular', "ItalicAngle" : 0, 'FullName' : filename} if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi global afmfile if not afmfile: afmfile = find_file (filename + '.afm') if afmfile: afmfile = os.path.abspath (afmfile) afm_struct = afm.read_afm_file (afmfile) fi.update (afm_struct.__dict__) return fi
TestCmd.fail_test(self, condition, *args)
TestCmd.TestCmd.fail_test(self, condition, *args)
def fail_test(self, condition, *args):
return open(self.native_file_name(name), "r").read()
return open(self.native_file_name(name), "rb").read()
def read(self, name): return open(self.native_file_name(name), "r").read()
lines = open(self.native_file_name(name), "r").readlines()
lines = open(self.native_file_name(name), "rb").readlines()
def read_and_strip(self, name): lines = open(self.native_file_name(name), "r").readlines() result = string.join(map(string.rstrip, lines), "\n") if lines and lines[-1][-1] == '\n': return result + '\n' else: return result
if os.uname()[0] == 'Darwin':
if os.__dict__.has_key('uname') and os.uname()[0] == 'Darwin':
def prepare_suffix_map(toolset): global windows, suffixes suffixes = {'.exe': '', '.dll': '.so', '.lib': '.a', '.obj': '.o'} if os.environ.get('OS','').lower().startswith('windows'): windows = 1 suffixes = {} if toolset in ["gcc"]: suffixes['.lib'] = '.a' # static libs have '.a' suffix with mingw... suffixes['.obj'] = '.o' if os.uname()[0] == 'Darwin': suffixes['.dll'] = '.dylib'
elif os.name == 'posix':
elif os.name == 'posix' and os.__dict__.has_key('uname'):
def __init__(self, arguments="", executable = 'bjam', match = TestCmd.match_exact, boost_build_path = None, translate_suffixes = 1, pass_toolset = 1, **keywords):
exit(1)
os.exit(1)
def __init__(self, arguments="", executable = 'bjam', match = TestCmd.match_exact, boost_build_path = None, translate_suffixes = 1, pass_toolset = 1, **keywords):
if not stderr is None and not match(self.stderr(), stderr):
intel_workaround = re.compile("^xi(link|lib): executing.*\n", re.M) actual_stderr = re.sub(intel_workaround, "", self.stderr()) if not stderr is None and not match(actual_stderr, stderr):
def run_build_system( self, extra_args='', subdir='', stdout = None, stderr = '', status = 0, match = None, pass_toolset = None, **kw):
print self.stderr() self.maybe_do_diff(self.stderr(), stderr)
print actual_stderr self.maybe_do_diff(actual_stderr, stderr)
def run_build_system( self, extra_args='', subdir='', stdout = None, stderr = '', status = 0, match = None, pass_toolset = None, **kw):
if windows: filesets = [d.modified_files, d.touched_files] else: filesets = [d.touched_files]
filesets = [d.modified_files, d.touched_files]
def expect_touch(self, names): d = self.unexpected_difference for name in self.adjust_names(names):
"order_sensitive",
"ordered_properties",
def reorder_tests(tests, first_test): try: n = tests.index(first_test) return [first_test] + tests[:n] + tests[n+1:] except ValueError: return tests
"library_order",
def reorder_tests(tests, first_test): try: n = tests.index(first_test) return [first_test] + tests[:n] + tests[n+1:] except ValueError: return tests
self.last_build_time = time.time
self.last_build_time = time.time()
def run_build_system( self, extra_args='', subdir='', stdout = None, stderr = '', status = 0, match = None, **kw):
while int(time.time()) == self.last_build_time: os.sleep(0.1)
while int(time.time()) == int(self.last_build_time): time.sleep(0.1)
def wait_for_time_change(self): while int(time.time()) == self.last_build_time: os.sleep(0.1)
global windows, suffixes
def prepare_suffix_map(toolset): suffixes = {'.exe': '', '.dll': '.so', '.lib': '.a', '.obj': '.o'} if os.environ.get('OS','').lower().startswith('windows'): global windows, suffixes windows = 1 suffixes = {} if toolset in ["gcc"]: suffixes['.lib'] = '.a' # static libs have '.a' suffix with mingw... suffixes['.obj'] = '.o'
prepare_suffix_map(pass_toolset and 'gcc' or self.toolset)
prepare_suffix_map(pass_toolset and self.toolset or 'gcc')
def __init__(self, arguments="", executable = 'bjam', match = TestCmd.match_exact, boost_build_path = None, translate_suffixes = 1, pass_toolset = 1, **keywords):
jam_build_dir = "bin.linuxx86"
cpu = os.uname()[4] if re.match("i.86", cpu): jam_build_dir = "bin.linuxx86"; else: jam_build_dir = "bin.linux" + os.uname()[4]
def __init__(self, arguments="", executable = 'bjam', match = TestCmd.match_exact, boost_build_path = None, translate_suffixes = 1, pass_toolset = 1, **keywords):
lib a : a.cpp l ;
static-lib a : a.cpp l ;
#ifdef _WIN32
actual_ = map(lambda x: sorted(x.split()),actual.splitlines()) content_ = map(lambda x: sorted(x.split()),content.splitlines())
def expect_content(self, name, content, exact=0): name = self.adjust_names(name)[0] try: if exact: actual = self.read(name) else: actual = string.replace(self.read_and_strip(name), "\\", "/") except IOError: print "Note: could not open file", name self.fail_test(1)
"unused",
def reorder_tests(tests, first_test): try: n = tests.index(first_test) return [first_test] + tests[:n] + tests[n+1:] except ValueError: return tests
if os.name == 'nt' or ( os.uname()[0].lower().startswith('cygwin') and get_toolset() != 'gcc') :
if (os.name == 'nt' or os.uname()[0].lower().startswith('cygwin')) and get_toolset() != 'gcc':
#ifdef _WIN32
if os.name == 'nt':
if os.name == 'nt' or ( os.uname()[0].lower().startswith('cygwin') and get_toolset() != 'gcc') :
#ifdef _WIN32
int main() { return 0; }
void foo(); int main() { foo(); return 0; }
#ifdef _WIN32
self.difference.pprint()
if hasattr(self, 'difference'): self.difference.pprint()
def fail_test(self, *args, **kw): self.difference.pprint() TestCmd.fail_test(self, *args, **kw)
if _failed(self, status):
if status != None and _failed(self, status):
def run_build_system(self, extra_args='', subdir='', stdout = None, stderr = '', status = 0, **kw): self.previous_tree = build_tree(self.workdir)
os.mkdir(self.workdir)
if not os.path.exists(self.workdir): os.mkdir(self.workdir)
def rm(self, names): self.wait_for_time_change() if not type(names) == types.ListType: names = [names]
jam_build_dir = "bin.linuxx86" else: raise "Don't know directory where jam is build for this system"
raise "Don't know directory where jam is build for this system: " + os.name + "/" + os.uname()[0] else: raise "Don't know directory where jam is build for this system: " + os.name
def __init__(self, arguments="", executable = 'bjam', match = TestCmd.match_exact, boost_build_path = None, translate_suffixes = 1, pass_toolset = 1, **keywords):
TestCmd.TestCmd.__init__(self, program=os.path.join('..', 'jam_src', jam_build_dir, 'bjam') + ' -d0', match=TestCmd.match_exact, workdir='')
TestCmd.TestCmd.__init__( self , program=os.path.join( '..', 'jam_src', jam_build_dir, 'bjam') + ' -d0 --debug --quiet' , match=TestCmd.match_exact , workdir='')
def __init__(self):
print "STDOUT ============" print self.stdout() print "STDERR ============" print self.stderr()
self.dump_stdio()
def run_build_system( self, extra_args='', subdir='', stdout = None, stderr = '', status = 0, match = None, pass_toolset = None, **kw):
print "STDOUT ============" print self.stdout() print "STDERR ============" print self.stderr()
def run_build_system( self, extra_args='', subdir='', stdout = None, stderr = '', status = 0, match = None, pass_toolset = None, **kw):
self.fail_test(1)
self.fail_test(1, dump_stdio = 0)
def run_build_system( self, extra_args='', subdir='', stdout = None, stderr = '', status = 0, match = None, pass_toolset = None, **kw):
def fail_test(self, condition, *args): if condition and hasattr(self, 'difference'):
def fail_test(self, condition, dump_stdio = 1, *args): if condition and hasattr(self, 'difference'):
def fail_test(self, condition, *args):
self.difference.pprint()
def run_build_system( self, extra_args='', subdir='', stdout = None, stderr = '', status = 0, match = None, **kw):
def fail_test(self, *args, **kw): self.difference.pprint() TestCmd.fail_test(self, *args, **kw)
def read_and_strip(self, name): lines = open(self.native_file_name(name), "r").readlines() result = string.join(map(string.rstrip, lines), "\n") if lines and lines[-1][-1] == '\n': return result + '\n' else: return result
and _sort_tuple(g.atoms()) != _sort_tuple(v.group.atoms()):
and _sort_tuple(g.atoms()) == _sort_tuple(v.group.atoms()):
def _examine_edge(states, queue, g): """Handle a possible new state in the search. """ g_state = State(g) v = states.setdefault(g_state, g_state) if v.group is g: queue.append(g_state) return False if v.group.cost > g.cost: if debug: print 'reducing cost of state(%s) via %s' % (v.group,g) v.group.ambiguous = None v.group = g elif v.group.cost < g.cost: if debug: print 'discarding %s due to lower cost state(%s)' % (g, v.group) elif not (g.generator or v.group.generator) \ and _sort_tuple(g.atoms()) != _sort_tuple(v.group.atoms()): # These are two different ways of combining the same groups of # a given type to produce a larger group, without using a generator if debug: print 'discarding %s as a redundant formulation of %s' % (g,v.group) else: if debug: print '%s is an ambiguous path due to %s' % (v.group, g) # Remember the group which caused the ambiguity v.group.ambiguous = g return True
s = string.replace(s, "\ ", '\001') self.l = [] for e in string.split(s):
elements = [] if isinstance(s, type("")): s = string.replace(s, "\ ", '\001') elements = string.split(s) else: elements = s; self.l = [] for e in elements:
def __init__(self, s=""): # Have to handle espaced spaces correctly s = string.replace(s, "\ ", '\001') self.l = [] for e in string.split(s): self.l.append(string.replace(e, '\001', ' '))
def __coerce__(self, other): if isinstance(other, type("")): return (self,List(other)) else: return None
def __delitem__(self, key): del self.l[key]
exe main : main.cpp test_lib ;
exe main : main.cpp helper ; lib helper : helper.cpp test_lib ;
#ifdef _WIN32
int main() { foo(); return 0; }
void __declspec(dllexport) helper() { foo(); }
#ifdef _WIN32
t.run_build_system()
t.run_build_system(stderr=None)
#ifdef _WIN32
self.cost = reduce(lambda x,y:x + y.cost, parents, 1)
def __init__( self , target_type , size # how many of that type are in the group. , parents = () , generator = None): """ >>> g1 = TargetTypeGroup('x', 1) >>> assert not g1.extra_targets >>> assert g1.consumed_sources == { g1:1 } >>> g2 = TargetTypeGroup('x', 1) >>> g3 = TargetTypeGroup('x', 1, [g1,g2]) >>> assert g1 in g3.consumed_sources >>> assert g2 in g3.consumed_sources >>> assert not g3 in g3.consumed_sources """ self.target_type = target_type self.size = size self.parents = parents self.generator = generator self.cost = reduce(lambda x,y:x + y.cost, parents, 1) self.siblings = None self.id = TargetTypeGroup.instances self.ambiguous = reduce(lambda x,y: x or y.ambiguous and 1, parents, None) self.generators = { generator : 1 } # it doesn't hurt to store None here ignored = [ self.generators.update(p.generators) for p in parents ] self.__constituents = None self.__extra_targets = None TargetTypeGroup.instances += 1
elif len(parents) == 1: self.consumed_sources = parents[0].consumed_sources
def __init__( self , target_type , size # how many of that type are in the group. , parents = () , generator = None): """ >>> g1 = TargetTypeGroup('x', 1) >>> assert not g1.extra_targets >>> assert g1.consumed_sources == { g1:1 } >>> g2 = TargetTypeGroup('x', 1) >>> g3 = TargetTypeGroup('x', 1, [g1,g2]) >>> assert g1 in g3.consumed_sources >>> assert g2 in g3.consumed_sources >>> assert not g3 in g3.consumed_sources """ self.target_type = target_type self.size = size self.parents = parents self.generator = generator self.cost = reduce(lambda x,y:x + y.cost, parents, 1) self.siblings = None self.id = TargetTypeGroup.instances self.ambiguous = reduce(lambda x,y: x or y.ambiguous and 1, parents, None) self.generators = { generator : 1 } # it doesn't hurt to store None here ignored = [ self.generators.update(p.generators) for p in parents ] self.__constituents = None self.__extra_targets = None TargetTypeGroup.instances += 1
self.consumed_sources = {} for c in parents: self.consumed_sources.update(c.consumed_sources)
ignored = [ self.moves.update(p.moves) for p in parents ] if len(parents) == 1: self.consumed_sources = parents[0].consumed_sources else: self.consumed_sources = {} for c in parents: self.consumed_sources.update(c.consumed_sources)
def __init__( self , target_type , size # how many of that type are in the group. , parents = () , generator = None): """ >>> g1 = TargetTypeGroup('x', 1) >>> assert not g1.extra_targets >>> assert g1.consumed_sources == { g1:1 } >>> g2 = TargetTypeGroup('x', 1) >>> g3 = TargetTypeGroup('x', 1, [g1,g2]) >>> assert g1 in g3.consumed_sources >>> assert g2 in g3.consumed_sources >>> assert not g3 in g3.consumed_sources """ self.target_type = target_type self.size = size self.parents = parents self.generator = generator self.cost = reduce(lambda x,y:x + y.cost, parents, 1) self.siblings = None self.id = TargetTypeGroup.instances self.ambiguous = reduce(lambda x,y: x or y.ambiguous and 1, parents, None) self.generators = { generator : 1 } # it doesn't hurt to store None here ignored = [ self.generators.update(p.generators) for p in parents ] self.__constituents = None self.__extra_targets = None TargetTypeGroup.instances += 1
cost = property(lambda self: len(self.moves))
def __get_constituents(self): if self.__constituents is None: self.__constituents = {self:1} for c in self.parents: self.__constituents.update(c.constituents) return self.__constituents
if name.endswith('.exe'):
if windows:
def expect_touch(self, names): d = self.unexpected_difference for name in self.adjust_names(names):
f = open(os.path.join(invocation_dir, 'test_results.txt'), 'w') f.write(i) f.close() raise
if failures_count == 0: f = open(os.path.join(invocation_dir, 'test_results.txt'), 'w') f.write(i) f.close() failures_count = failures_count + 1 os.chdir(invocation_dir) continue
def run_tests(critical_tests, other_tests): """Runs first critical tests and then other_tests. Stops on first error, and write the name of failed test to test_results.txt. Critical tests are run in the specified order, other tests are run starting with the one that failed the last time. """ last_failed = last_failed_test() other_tests = reorder_tests(other_tests, last_failed) all_tests = critical_tests + other_tests invocation_dir = os.getcwd() for i in all_tests: print ("%-25s : " %(i)), try: __import__(i) except: print "FAILED" f = open(os.path.join(invocation_dir, 'test_results.txt'), 'w') f.write(i) f.close() raise print "PASSED" sys.stdout.flush() # makes testing under emacs more entertaining. # Erase the file on success open('test_results.txt', 'w')
open('test_results.txt', 'w')
if failures_count == 0: open('test_results.txt', 'w')
def run_tests(critical_tests, other_tests): """Runs first critical tests and then other_tests. Stops on first error, and write the name of failed test to test_results.txt. Critical tests are run in the specified order, other tests are run starting with the one that failed the last time. """ last_failed = last_failed_test() other_tests = reorder_tests(other_tests, last_failed) all_tests = critical_tests + other_tests invocation_dir = os.getcwd() for i in all_tests: print ("%-25s : " %(i)), try: __import__(i) except: print "FAILED" f = open(os.path.join(invocation_dir, 'test_results.txt'), 'w') f.write(i) f.close() raise print "PASSED" sys.stdout.flush() # makes testing under emacs more entertaining. # Erase the file on success open('test_results.txt', 'w')
int __declspec(dllexport) must_export_something();
int __declspec(dllexport) must_export_something;
#ifdef _WIN32
t.write("lib1/c.cpp", "")
t.write("lib1/c.cpp", """ int __declspec(dllexport) must_export_something; """)
#ifdef _WIN32
if not type(names) == types.ListType: names = [names] for name in names:
for name in self.adjust_names(names):
def touch(self, names): self.wait_for_time_change() if not type(names) == types.ListType: names = [names] for name in names: os.utime(self.native_file_name(name), None)
boost_build_path += ":" + self.original_workdir
if windows: boost_build_path += ";" + self.original_workdir else: boost_build_path += ":" + self.original_workdir
def __init__(self, arguments="", executable = 'bjam', match = TestCmd.match_exact, boost_build_path = None, translate_suffixes = 1, pass_toolset = 1, **keywords):
kw['program'] = self.program + ' ' + self.toolset + ' ' + extra_args
kw['program'] = self.program + ' ' + extra_args + ' ' + self.toolset
def run_build_system( self, extra_args='', subdir='', stdout = None, stderr = '', status = 0, match = None, pass_toolset = None, **kw):
if os.name == 'posix' and not os.uname()[0].startswith('CYGWIN'):
if os.name == 'posix':
def reorder_tests(tests, first_test): try: n = tests.index(first_test) return [first_test] + tests[:n] + tests[n+1:] except ValueError: return tests
tests.append("railsys")
if not os.uname()[0].startswith('CYGWIN'): tests.append("railsys")
def reorder_tests(tests, first_test): try: n = tests.index(first_test) return [first_test] + tests[:n] + tests[n+1:] except ValueError: return tests
ignore_elements(self.unexpected_difference.added_files, wildcard)
self.ignore_elements(self.unexpected_difference.added_files, wildcard)
def ignore_addition(self, wildcard): ignore_elements(self.unexpected_difference.added_files, wildcard)
ignore_elements(self.unexpected_difference.removed_files, wildcard)
self.ignore_elements(self.unexpected_difference.removed_files, wildcard)
def ignore_removal(self, wildcard): ignore_elements(self.unexpected_difference.removed_files, wildcard)
ignore_elements(self.unexpected_difference.modified_files, wildcard)
self.ignore_elements(self.unexpected_difference.modified_files, wildcard)
def ignore_modification(self, wildcard): ignore_elements(self.unexpected_difference.modified_files, wildcard)
ignore_elements(self.unexpected_difference.touched_files, wildcard)
self.ignore_elements(self.unexpected_difference.touched_files, wildcard)
def ignore_touch(self, wildcard): ignore_elements(self.unexpected_difference.touched_files, wildcard)