@@ -74,11 +74,13 @@ def _arg_raw(dvi, delta):
7474 """Return *delta* without reading anything more from the dvi file"""
7575 return delta
7676
77+
7778def _arg (bytes , signed , dvi , _ ):
7879 """Read *bytes* bytes, returning the bytes interpreted as a
7980 signed integer if *signed* is true, unsigned otherwise."""
8081 return dvi ._arg (bytes , signed )
8182
83+
8284def _arg_slen (dvi , delta ):
8385 """Signed, length *delta*
8486
@@ -88,24 +90,28 @@ def _arg_slen(dvi, delta):
8890 return None
8991 return dvi ._arg (delta , True )
9092
93+
9194def _arg_slen1 (dvi , delta ):
9295 """Signed, length *delta*+1
9396
9497 Read *delta*+1 bytes, returning the bytes interpreted as signed."""
9598 return dvi ._arg (delta + 1 , True )
9699
100+
97101def _arg_ulen1 (dvi , delta ):
98102 """Unsigned length *delta*+1
99103
100104 Read *delta*+1 bytes, returning the bytes interpreted as unsigned."""
101105 return dvi ._arg (delta + 1 , False )
102106
107+
103108def _arg_olen1 (dvi , delta ):
104109 """Optionally signed, length *delta*+1
105110
106111 Read *delta*+1 bytes, returning the bytes interpreted as
107112 unsigned integer for 0<=*delta*<3 and signed if *delta*==3."""
108- return dvi ._arg (delta + 1 , delta == 3 )
113+ return dvi ._arg (delta + 1 , delta == 3 )
114+
109115
110116_arg_mapping = dict (raw = _arg_raw ,
111117 u1 = partial (_arg , 1 , False ),
@@ -116,6 +122,7 @@ def _arg_olen1(dvi, delta):
116122 slen1 = _arg_slen1 ,
117123 ulen1 = _arg_ulen1 )
118124
125+
119126def _dispatch (table , min , max = None , state = None , args = ('raw' ,)):
120127 """Decorator for dispatch by opcode. Sets the values in *table*
121128 from *min* to *max* to this method, adds a check that the Dvi state
@@ -149,6 +156,7 @@ def _dispatch(table, min, max=None, state=None, args=('raw',)):
149156 """
150157 def decorate (method ):
151158 get_args = [_arg_mapping [x ] for x in args ]
159+
152160 @wraps (method )
153161 def wrapper (self , byte ):
154162 if state is not None and self .state != state :
@@ -163,6 +171,7 @@ def wrapper(self, byte):
163171 return wrapper
164172 return decorate
165173
174+
166175class Dvi (object ):
167176 """
168177 A dvi ("device-independent") file, as produced by TeX.
@@ -240,11 +249,11 @@ def _output(self):
240249 maxy_pure = - np .inf
241250 for elt in self .text + self .boxes :
242251 if isinstance (elt , Box ):
243- x ,y , h , w = elt
252+ x , y , h , w = elt
244253 e = 0 # zero depth
245254 else : # glyph
246- x ,y , font ,g , w = elt
247- h ,e = font ._height_depth_of (g )
255+ x , y , font , g , w = elt
256+ h , e = font ._height_depth_of (g )
248257 minx = min (minx , x )
249258 miny = min (miny , y - h )
250259 maxx = max (maxx , x + w )
@@ -257,16 +266,17 @@ def _output(self):
257266 width = maxx - minx , height = maxy_pure - miny ,
258267 descent = maxy - maxy_pure )
259268
260- d = self .dpi / (72.27 * 2 ** 16 ) # from TeX's "scaled points" to dpi units
269+ # convert from TeX's "scaled points" to dpi units
270+ d = self .dpi / (72.27 * 2 ** 16 )
261271 if self .baseline is None :
262272 descent = (maxy - maxy_pure ) * d
263273 else :
264274 descent = self .baseline
265275
266- text = [ Text ((x - minx )* d , (maxy - y )* d - descent , f , g , w * d )
267- for (x ,y , f , g , w ) in self .text ]
268- boxes = [ Box ((x - minx )* d , (maxy - y )* d - descent , h * d , w * d )
269- for (x ,y , h , w ) in self .boxes ]
276+ text = [ Text ((x - minx )* d , (maxy - y )* d - descent , f , g , w * d )
277+ for (x , y , f , g , w ) in self .text ]
278+ boxes = [Box ((x - minx )* d , (maxy - y )* d - descent , h * d , w * d )
279+ for (x , y , h , w ) in self .boxes ]
270280
271281 return Page (text = text , boxes = boxes , width = (maxx - minx )* d ,
272282 height = (maxy_pure - miny )* d , descent = descent )
@@ -279,9 +289,9 @@ def _read(self):
279289 while True :
280290 byte = ord (self .file .read (1 )[0 ])
281291 self .dtable [byte ](self , byte )
282- if byte == 140 : # end of page
292+ if byte == 140 : # end of page
283293 return True
284- if self .state == _dvistate .post_post : # end of file
294+ if self .state == _dvistate .post_post : # end of file
285295 self .close ()
286296 return False
287297
@@ -434,7 +444,7 @@ def _fnt_def_real(self, k, c, s, d, a, l):
434444 if tfm is None :
435445 raise FileNotFoundError ("missing font metrics file: %s" % fontname )
436446 if c != 0 and tfm .checksum != 0 and c != tfm .checksum :
437- raise ValueError ('tfm checksum mismatch: %s' % n )
447+ raise ValueError ('tfm checksum mismatch: %s' % n )
438448
439449 vf = _vffile (fontname )
440450
@@ -444,7 +454,7 @@ def _fnt_def_real(self, k, c, s, d, a, l):
444454 def _pre (self , i , num , den , mag , k ):
445455 comment = self .file .read (k )
446456 if i != 2 :
447- raise ValueError ("Unknown dvi format %d" % i )
457+ raise ValueError ("Unknown dvi format %d" % i )
448458 if num != 25400000 or den != 7227 * 2 ** 16 :
449459 raise ValueError ("nonstandard units in dvi file" )
450460 # meaning: TeX always uses those exact values, so it
@@ -472,6 +482,7 @@ def _post_post(self, _):
472482 def _malformed (self , offset ):
473483 raise ValueError ("unknown command: byte %d" , 250 + offset )
474484
485+
475486class DviFont (object ):
476487 """
477488 Object that holds a font's texname and size, supports comparison,
@@ -511,8 +522,8 @@ def __init__(self, scale, tfm, texname, vf):
511522 nchars = max (six .iterkeys (tfm .width )) + 1
512523 except ValueError :
513524 nchars = 0
514- self .widths = [ (1000 * tfm .width .get (char , 0 )) >> 20
515- for char in xrange (nchars ) ]
525+ self .widths = [(1000 * tfm .width .get (char , 0 )) >> 20
526+ for char in xrange (nchars )]
516527
517528 def __eq__ (self , other ):
518529 return self .__class__ == other .__class__ and \
@@ -541,12 +552,13 @@ def _height_depth_of(self, char):
541552 """
542553
543554 result = []
544- for metric ,name in ((self ._tfm .height , "height" ),
545- (self ._tfm .depth , "depth" )):
555+ for metric , name in ((self ._tfm .height , "height" ),
556+ (self ._tfm .depth , "depth" )):
546557 value = metric .get (char , None )
547558 if value is None :
548559 matplotlib .verbose .report (
549- 'No %s for char %d in font %s' % (name , char , self .texname ),
560+ 'No %s for char %d in font %s' % (
561+ name , char , self .texname ),
550562 'debug' )
551563 result .append (0 )
552564 else :
@@ -615,11 +627,11 @@ def _read(self):
615627 self .state = _dvistate .inpage
616628 elif byte == 242 : # a long packet
617629 packet_len , packet_char , packet_width = \
618- [ self ._arg (x ) for x in (4 , 4 , 4 ) ]
630+ [self ._arg (x ) for x in (4 , 4 , 4 )]
619631 self ._init_packet (packet_len )
620632 elif 243 <= byte <= 246 :
621633 k = self ._arg (byte - 242 , byte == 246 )
622- c , s , d , a , l = [ self ._arg (x ) for x in (4 , 4 , 4 , 1 , 1 ) ]
634+ c , s , d , a , l = [self ._arg (x ) for x in (4 , 4 , 4 , 1 , 1 )]
623635 self ._fnt_def_real (k , c , s , d , a , l )
624636 if self ._first_font is None :
625637 self ._first_font = k
@@ -668,13 +680,15 @@ def _fix2comp(num):
668680 else :
669681 return num
670682
683+
671684def _mul2012 (num1 , num2 ):
672685 """
673686 Multiply two numbers in 20.12 fixed point format.
674687 """
675688 # Separated into a function because >> has surprising precedence
676689 return (num1 * num2 ) >> 20
677690
691+
678692class Tfm (object ):
679693 """
680694 A TeX Font Metric file. This implementation covers only the bare
@@ -724,12 +738,14 @@ def __init__(self, filename):
724738
725739 self .width , self .height , self .depth = {}, {}, {}
726740 widths , heights , depths = \
727- [ struct .unpack (str ('!%dI' ) % (len (x )/ 4 ), x )
728- for x in (widths , heights , depths ) ]
741+ [struct .unpack (str ('!%dI' ) % (len (x )/ 4 ), x )
742+ for x in (widths , heights , depths )]
729743 for idx , char in enumerate (xrange (bc , ec + 1 )):
730- self .width [char ] = _fix2comp (widths [ord (char_info [4 * idx ])])
731- self .height [char ] = _fix2comp (heights [ord (char_info [4 * idx + 1 ]) >> 4 ])
732- self .depth [char ] = _fix2comp (depths [ord (char_info [4 * idx + 1 ]) & 0xf ])
744+ byte0 = ord (char_info [4 * idx ])
745+ byte1 = ord (char_info [4 * idx + 1 ])
746+ self .width [char ] = _fix2comp (widths [byte0 ])
747+ self .height [char ] = _fix2comp (heights [byte1 >> 4 ])
748+ self .depth [char ] = _fix2comp (depths [byte1 & 0xf ])
733749
734750
735751PsFont = namedtuple ('Font' , 'texname psname effects encoding filename' )
@@ -797,14 +813,15 @@ def _parse(self, file):
797813 continue
798814 words , pos = [], 0
799815 while pos < len (line ):
800- if line [pos ] == '"' : # double quoted word
816+ if line [pos ] == '"' : # double quoted word
801817 pos += 1
802818 end = line .index ('"' , pos )
803819 words .append (line [pos :end ])
804820 pos = end + 1
805- else : # ordinary word
821+ else : # ordinary word
806822 end = line .find (' ' , pos + 1 )
807- if end == - 1 : end = len (line )
823+ if end == - 1 :
824+ end = len (line )
808825 words .append (line [pos :end ])
809826 pos = end
810827 while pos < len (line ) and line [pos ] == ' ' :
@@ -866,6 +883,7 @@ def _register(self, words):
866883 texname = texname , psname = psname , effects = effects ,
867884 encoding = encoding , filename = filename )
868885
886+
869887class Encoding (object ):
870888 """
871889 Parses a \*.enc file referenced from a psfonts.map style file.
@@ -881,9 +899,11 @@ class Encoding(object):
881899
882900 def __init__ (self , filename ):
883901 with open (filename , 'rt' ) as file :
884- matplotlib .verbose .report ('Parsing TeX encoding ' + filename , 'debug-annoying' )
902+ matplotlib .verbose .report ('Parsing TeX encoding ' + filename ,
903+ 'debug-annoying' )
885904 self .encoding = self ._parse (file )
886- matplotlib .verbose .report ('Result: ' + repr (self .encoding ), 'debug-annoying' )
905+ matplotlib .verbose .report ('Result: ' + repr (self .encoding ),
906+ 'debug-annoying' )
887907
888908 def __iter__ (self ):
889909 for name in self .encoding :
@@ -906,7 +926,7 @@ def _parse(self, file):
906926 line = line [line .index ('[' )+ 1 :].strip ()
907927
908928 if state == 1 :
909- if ']' in line : # ] def
929+ if ']' in line : # ] def
910930 line = line [:line .index (']' )]
911931 state = 2
912932 words = line .split ()
@@ -920,6 +940,7 @@ def _parse(self, file):
920940
921941 return result
922942
943+
923944def find_tex_file (filename , format = None ):
924945 """
925946 Call :program:`kpsewhich` to find a file in the texmf tree. If
@@ -941,8 +962,8 @@ def find_tex_file(filename, format=None):
941962 cmd += ['--format=' + format ]
942963 cmd += [filename ]
943964
944- matplotlib .verbose .report ('find_tex_file(%s): %s' \
945- % (filename ,cmd ), 'debug' )
965+ matplotlib .verbose .report ('find_tex_file(%s): %s'
966+ % (filename , cmd ), 'debug' )
946967 # stderr is unused, but reading it avoids a subprocess optimization
947968 # that breaks EINTR handling in some Python versions:
948969 # http://bugs.python.org/issue12493
@@ -961,6 +982,7 @@ def find_tex_file(filename, format=None):
961982_tfmcache = {}
962983_vfcache = {}
963984
985+
964986def _fontfile (texname , class_ , suffix , cache ):
965987 try :
966988 return cache [texname ]
@@ -976,29 +998,32 @@ def _fontfile(texname, class_, suffix, cache):
976998 cache [texname ] = result
977999 return result
9781000
1001+
9791002def _tfmfile (texname ):
9801003 return _fontfile (texname , Tfm , '.tfm' , _tfmcache )
9811004
1005+
9821006def _vffile (texname ):
9831007 return _fontfile (texname , Vf , '.vf' , _vfcache )
9841008
9851009
986-
9871010if __name__ == '__main__' :
9881011 import sys
9891012 matplotlib .verbose .set_level ('debug-annoying' )
9901013 fname = sys .argv [1 ]
991- try : dpi = float (sys .argv [2 ])
992- except IndexError : dpi = None
1014+ try :
1015+ dpi = float (sys .argv [2 ])
1016+ except IndexError :
1017+ dpi = None
9931018 with Dvi (fname , dpi ) as dvi :
9941019 fontmap = PsfontsMap (find_tex_file ('pdftex.map' ))
9951020 for page in dvi :
9961021 print ('=== new page ===' )
9971022 fPrev = None
998- for x ,y , f , c , w in page .text :
1023+ for x , y , f , c , w in page .text :
9991024 if f != fPrev :
1000- print ('font' , f .texname , 'scaled' , f ._scale / pow (2.0 ,20 ))
1025+ print ('font' , f .texname , 'scaled' , f ._scale / pow (2.0 , 20 ))
10011026 fPrev = f
1002- print (x ,y , c , 32 <= c < 128 and chr (c ) or '.' , w )
1003- for x ,y , w , h in page .boxes :
1004- print (x ,y , 'BOX' ,w , h )
1027+ print (x , y , c , 32 <= c < 128 and chr (c ) or '.' , w )
1028+ for x , y , w , h in page .boxes :
1029+ print (x , y , 'BOX' , w , h )
0 commit comments