Debian Codegraph @

texk/texlive/linked_scripts/dviasm/dviasm.py

raw
1 #! /usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # This is DVIasm, a DVI utility for editing DVI files directly.
5 #
6 # Copyright (C) 2007-2008 by Jin-Hwan Cho <[email protected]>
7 # Copyright (C) 2011-2017 by Khaled Hosny <[email protected]>
8 # Copyright (C) 2019 by Arthur Reutenauer <[email protected]>
9 # Copyright (C) 2019-2024 by Hironobu Yamashita <[email protected]>
10 #
11 # This program is free software: you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation, either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this program. If not, see <https://www.gnu.org/licenses/>.
23
24 import sys, os.path
25 from optparse import OptionParser
26
27 # Global variables
28 is_ptex = False
29 is_subfont = False
30 cur_font = None
31 cur_dsize = 0
32 cur_ssize = 0
33 subfont_idx = 0
34 subfont_list = ['cyberb', 'outbtm', 'outbtb', 'outgtm', 'outgtb']
35
36 # DVI opcodes
37 SET_CHAR_0 = 0; SET_CHAR_127 = 127;
38 SET1 = 128; SET2 = 129; SET3 = 130; SET4 = 131;
39 SET_RULE = 132;
40 PUT1 = 133; PUT2 = 134; PUT3 = 135; PUT4 = 136;
41 PUT_RULE = 137;
42 NOP = 138;
43 BOP = 139; EOP = 140;
44 PUSH = 141; POP = 142;
45 RIGHT1 = 143; RIGHT2 = 144; RIGHT3 = 145; RIGHT4 = 146;
46 W0 = 147; W1 = 148; W2 = 149; W3 = 150; W4 = 151;
47 X0 = 152; X1 = 153; X2 = 154; X3 = 155; X4 = 156;
48 DOWN1 = 157; DOWN2 = 158; DOWN3 = 159; DOWN4 = 160;
49 Y0 = 161; Y1 = 162; Y2 = 163; Y3 = 164; Y4 = 165;
50 Z0 = 166; Z1 = 167; Z2 = 168; Z3 = 169; Z4 = 170;
51 FNT_NUM_0 = 171; FNT_NUM_63 = 234;
52 FNT1 = 235; FNT2 = 236; FNT3 = 237; FNT4 = 238;
53 XXX1 = 239; XXX2 = 240; XXX3 = 241; XXX4 = 242;
54 FNT_DEF1 = 243; FNT_DEF2 = 244; FNT_DEF3 = 245; FNT_DEF4 = 246;
55 PRE = 247; POST = 248; POST_POST = 249;
56 # DVIV opcodes
57 DIR = 255;
58 # DVI-IVD opcodes
59 BEGIN_REFLECT = 250; END_REFLECT = 251;
60 # XDV opcodes
61 NATIVE_FONT_DEF = 252;
62 GLYPHS = 253;
63 TEXT_GLYPHS = 254;
64 # XDV flags
65 XDV_FLAG_VERTICAL = 0x0100;
66 XDV_FLAG_COLORED = 0x0200;
67 XDV_FLAG_EXTEND = 0x1000;
68 XDV_FLAG_SLANT = 0x2000;
69 XDV_FLAG_EMBOLDEN = 0x4000;
70 # DVI identifications
71 DVI_ID = 2; DVIV_ID = 3; XDVI_ID = 6; XDV_ID = 7;
72 DVI_IDS = (DVI_ID, DVIV_ID, XDVI_ID, XDV_ID)
73
74 def warning(msg):
75 sys.stderr.write('warning: %s\n' % msg)
76
77 def ValidID(dvi_id):
78 if dvi_id not in DVI_IDS:
79 return False
80 return True
81
82 def BadDVI(msg):
83 raise AttributeError('Bad DVI file: %s!' % msg)
84
85 def GetByte(fp): # { returns the next byte, unsigned }
86 try: return ord(fp.read(1))
87 except: return -1
88
89 def SignedByte(fp): # { returns the next byte, signed }
90 try: b = ord(fp.read(1))
91 except: return -1
92 if b < 128: return b
93 else: return b - 256
94
95 def Get2Bytes(fp): # { returns the next two bytes, unsigned }
96 try: a, b = fp.read(2)
97 except: BadDVI('Failed to Get2Bytes()')
98 return (a << 8) + b
99
100 def SignedPair(fp): # {returns the next two bytes, signed }
101 try: a, b = fp.read(2)
102 except: BadDVI('Failed to SignedPair()')
103 if a < 128: return (a << 8) + b
104 else: return ((a - 256) << 8) + b
105
106 def Get3Bytes(fp): # { returns the next three bytes, unsigned }
107 try: a, b, c = fp.read(3)
108 except: BadDVI('Failed to Get3Bytes()')
109 return (((a << 8) + b) << 8) + c
110
111 def SignedTrio(fp): # { returns the next three bytes, signed }
112 try: a, b, c = fp.read(3)
113 except: BadDVI('Failed to SignedTrio()')
114 if a < 128: return (((a << 8) + b) << 8) + c
115 else: return ((((a - 256) << 8) + b) << 8) + c
116
117 def Get4Bytes(fp): # { returns the next four bytes, unsigned }
118 try: a, b, c, d = fp.read(4)
119 except: BadDVI('Failed to Get4Bytes()')
120 return (((((a << 8) + b) << 8) + c) << 8) + d
121
122 def SignedQuad(fp): # { returns the next four bytes, signed }
123 try: a, b, c, d = fp.read(4)
124 except: BadDVI('Failed to get SignedQuad()')
125 if a < 128: return (((((a << 8) + b) << 8) + c) << 8) + d
126 else: return ((((((a - 256) << 8) + b) << 8) + c) << 8) + d
127
128 def PutByte(q):
129 return bytes.fromhex('%02x' % (q & 0xff))
130
131 def Put2Bytes(q):
132 return PutByte(q>>8) + PutByte(q)
133
134 def Put3Bytes(q):
135 return PutByte(q>>16) + PutByte(q>>8) + PutByte(q)
136
137 def PutSignedQuad(q):
138 if q < 0: q += 0x100000000
139 return PutByte(q>>24) + PutByte(q>>16) + PutByte(q>>8) + PutByte(q)
140
141 def PutUnsigned(q):
142 if q >= 0x1000000: return (3, PutSignedQuad(q))
143 if q >= 0x10000: return (2, Put3Bytes(q))
144 if q >= 0x100: return (1, Put2Bytes(q))
145 return (0, PutByte(q))
146
147 def PutSigned(q):
148 if q < -0x800000 or q >= 0x800000: return (3, PutSignedQuad(q))
149 if q >= 0x8000: return (2, Put3Bytes(q))
150 if q < -0x8000: q += 0x1000000; return (2, Put3Bytes(q))
151 if q >= 0x80: return (1, Put2Bytes(q))
152 if q < -0x80: q += 0x10000; return (1, Put2Bytes(q))
153 return (0, PutByte(q))
154
155 def PutGlyphs(width, glyphs):
156 s = []
157 length = len(glyphs)
158 s.append(PutSignedQuad(width))
159 s.append(Put2Bytes(length))
160 for glyph in glyphs:
161 s.append(PutSignedQuad(glyph["x"]))
162 s.append(PutSignedQuad(glyph["y"]))
163 for glyph in glyphs:
164 s.append(Put2Bytes(glyph["id"]))
165
166 return b''.join(s)
167
168 def PutTextGlyphs(text, width, glyphs):
169 s = []
170 length = len(text)
171 s.append(Put2Bytes(length))
172 for ch in text:
173 s.append(Put2Bytes(ch))
174 s.append(PutGlyphs(width, glyphs))
175
176 return b''.join(s)
177
178 def GetInt(s):
179 try: return int(s)
180 except: return -1
181
182 def GetStrASCII(s): # used in Parse()
183 if len(s) > 1 and ((s[0] == "'" and s[-1] == "'") or (s[0] == '"' and s[-1] == '"')):
184 return [ord(c) for c in s[1:-1].decode('unicode_escape')]
185 else: return ''
186
187 def UCS2toJIS(c):
188 try:
189 s = c.encode('iso2022-jp')
190 except UnicodeEncodeError:
191 s = c.encode('raw_unicode_escape')
192 if len(s) == 1: return ord(s)
193 else: return (s[3] << 8) + s[4]
194
195 def XUnicodeDecode(s): # dirty hack to handle >= 0x110000
196 t = []
197 i = 1
198 while i < len(s)-1:
199 c = -1
200 if s[i] == '\\':
201 if s[i+1] == 'x':
202 try:
203 c = int(s[i+2:i+4],16)
204 i += 4
205 except ValueError:
206 warning('Invalid escape sequence \\x ignored!')
207 i += 2
208 elif s[i+1] == 'u':
209 try:
210 c = int(s[i+2:i+6],16)
211 i += 6
212 except ValueError:
213 warning('Invalid escape sequence \\u ignored!')
214 i += 2
215 elif s[i+1] == 'U':
216 try:
217 c = int(s[i+2:i+10],16)
218 i += 10
219 except ValueError:
220 warning('Invalid escape sequence \\U ignored!')
221 i += 2
222 else:
223 if i+1 < len(s)-1:
224 c = ord(s[i+1])
225 i += 2
226 else:
227 warning('Invalid escape character \\ ignored!')
228 i += 1
229 else:
230 c = ord(s[i])
231 i += 1
232 if is_ptex: c = UCS2toJIS(chr(c))
233 if c >= 0: t.append(c)
234 return t
235
236 def GetStrUTF8(s): # used in Parse()
237 if len(s) > 1 and ((s[0] == "'" and s[-1] == "'") or (s[0] == '"' and s[-1] == '"')):
238 try: # This should work for valid Unicode
239 t = s[1:-1].encode('raw_unicode_escape').decode('unicode_escape')
240 if is_ptex: return [UCS2toJIS(c) for c in t]
241 else: return [ord(c) for c in t]
242 except UnicodeDecodeError: # e.g. for upTeX >= 0x110000
243 return XUnicodeDecode(s)
244 else: return ''
245
246 def PutStrASCII(t): # used in Dump()
247 s = ''
248 for o in t:
249 if o == 92: s += '\\\\'
250 elif 32 <= o < 127: s += chr(o)
251 elif o < 256: s += ('\\x%02x' % o)
252 elif o < 65536: s += ('\\u%04x' % o)
253 else: s += ('\\U%08x' % o)
254 return "'%s'" % s
255
256 def PutStrLatin1(t): # used in Dump()
257 s = ''
258 for o in t:
259 if o == 92: s += '\\\\'
260 elif 32 <= o < 127 or 161 <= o < 256: s += chr(o)
261 elif o < 256: s += ('\\x%02x' % o)
262 elif o < 65536: s += ('\\u%04x' % o)
263 else: s += ('\\U%08x' % o)
264 return "'%s'" % s
265
266 def DecodeISO2022JP(c):
267 try:
268 s = bytes.fromhex("1b 24 42 %02x %02x" % (c//256, c%256)).decode('iso2022-jp')
269 except UnicodeDecodeError:
270 s = chr(c)
271 return s
272
273 def PutStrUTF8(t): # used in Dump()
274 s = ''
275 if is_subfont:
276 for o in t:
277 s += chr((subfont_idx << 8) + o)
278 else: # not the case of subfont
279 for o in t:
280 if o == 92: s += '\\\\'
281 elif 32 <= o < 127: s += chr(o)
282 elif o < 128: s += ('\\x%02x' % o)
283 elif is_ptex:
284 s += DecodeISO2022JP(o)
285 else:
286 try: s += chr(o)
287 except ValueError: # upTeX may have >= 0x110000
288 if o < 256: s += '\\x%02x' % o
289 elif o < 65536: s += '\\u%04x' % o
290 else: s += '\\U%08x' % o
291 return "'%s'" % s
292
293 def IsFontChanged(f, z):
294 global cur_font, cur_ssize, subfont_idx, is_subfont
295 for n in subfont_list:
296 if n == f[:-2]:
297 is_subfont = True
298 subfont_idx = int(f[-2:], 16)
299 if cur_font == n and cur_ssize == z:
300 return False
301 else:
302 cur_font = n; cur_ssize = z
303 return True
304 else:
305 is_subfont = False
306 cur_font = f; cur_ssize = z
307 return True
308
309 ############################################################
310 # DVI class
311 ############################################################
312 class DVI(object):
313 def __init__(self, unit='pt'):
314 if unit == 'sp': self.byconv = self.by_sp_conv
315 elif unit == 'bp': self.byconv = self.by_bp_conv
316 elif unit == 'mm': self.byconv = self.by_mm_conv
317 elif unit == 'cm': self.byconv = self.by_cm_conv
318 elif unit == 'in': self.byconv = self.by_in_conv
319 else: self.byconv = self.by_pt_conv
320 self.Initialize()
321
322 ##########################################################
323 # Initialize: Required by __init__(), Load(), and Parse()
324 ##########################################################
325 def Initialize(self):
326 self.id = DVI_ID
327 self.numerator = 25400000
328 self.denominator = 473628672
329 self.mag = 1000
330 self.ComputeConversionFactors()
331 self.comment = ''
332 self.font_def = {}
333 self.max_v = self.max_h = self.max_s = self.total_pages = 0
334 self.pages = []
335
336 ##########################################################
337 # Load: DVI -> Internal Format
338 ##########################################################
339 def Load(self, fn):
340 fp = open(fn, 'rb')
341 self.LoadFromFile(fp)
342 fp.close()
343
344 def LoadFromFile(self, fp):
345 self.Initialize()
346 fp.seek(0, 2)
347 if fp.tell() < 53: BadDVI('less than 53 bytes long')
348 self.ProcessPreamble(fp)
349 self.ProcessPostamble(fp)
350 loc = self.first_backpointer
351 while loc >= 0:
352 fp.seek(loc)
353 if GetByte(fp) != BOP: BadDVI('byte %d is not bop' % fp.tell())
354 cnt = [SignedQuad(fp) for i in range(10)]
355 loc = SignedQuad(fp)
356 page = self.ProcessPage(fp)
357 self.pages.insert(0, {'count':cnt, 'content':page})
358
359 def ProcessPreamble(self, fp):
360 fp.seek(0)
361 if GetByte(fp) != PRE: BadDVI("First byte isn't start of preamble")
362 id = GetByte(fp)
363 if not ValidID(id):
364 warning("ID byte is %d; use the default %d!" % (id, DVI_ID))
365 self.id = id
366 numerator = SignedQuad(fp)
367 if numerator <= 0:
368 warning('numerator is %d; use the default 25400000!' % numerator)
369 else:
370 self.numerator = numerator
371 denominator = SignedQuad(fp)
372 if denominator <= 0:
373 warning('denominator is %d; use the default 473628672!' % denominator)
374 else:
375 self.denominator = denominator
376 mag = SignedQuad(fp)
377 if mag <= 0:
378 warning('magnification is %d; use the default 1000!' % mag)
379 else:
380 self.mag = mag
381 self.comment = fp.read(GetByte(fp)).decode('utf8')
382 self.ComputeConversionFactors()
383
384 def ProcessPostamble(self, fp):
385 fp.seek(-5, 2) # at least four 223's
386 while True:
387 k = GetByte(fp)
388 if k < 0: BadDVI('all 223s; is it a DVI file?') # found EOF
389 elif k != 223: break
390 fp.seek(-2, 1)
391 if not ValidID(k):
392 warning('ID byte is %d' % k)
393 fp.seek(-5, 1)
394 q = SignedQuad(fp)
395 m = fp.tell() # id_byte
396 if q < 0 or q > m - 33: BadDVI('post pointer %d at byte %d' % (q, m - 4))
397 fp.seek(q) # move to post
398 k = GetByte(fp)
399 if k != POST: BadDVI('byte %d is not post' % k)
400 self.post_loc = q
401 self.first_backpointer = SignedQuad(fp)
402
403 if SignedQuad(fp) != self.numerator:
404 warning("numerator doesn't match the preamble!")
405 if SignedQuad(fp) != self.denominator:
406 warning("denominator doesn't match the preamble!")
407 if SignedQuad(fp) != self.mag:
408 warning("magnification doesn't match the preamble!")
409 self.max_v = SignedQuad(fp)
410 self.max_h = SignedQuad(fp)
411 self.max_s = Get2Bytes(fp)
412 self.total_pages = Get2Bytes(fp)
413 while True:
414 k = GetByte(fp)
415 if k == FNT_DEF1: p = GetByte(fp)
416 elif k == FNT_DEF2: p = Get2Bytes(fp)
417 elif k == FNT_DEF3: p = Get3Bytes(fp)
418 elif k == FNT_DEF4: p = SignedQuad(fp)
419 elif k == NATIVE_FONT_DEF: p = SignedQuad(fp)
420 elif k != NOP: break
421 if k == NATIVE_FONT_DEF: self.DefineNativeFont(p, fp)
422 else: self.DefineFont(p, fp)
423 if k != POST_POST:
424 warning('byte %d is not postpost!' % (fp.tell() - 1))
425 if SignedQuad(fp) != self.post_loc:
426 warning('bad postamble pointer in byte %d!' % (fp.tell() - 4))
427 m = GetByte(fp)
428 if not ValidID(m):
429 warning('identification in byte %d should be one of: %s!' % (fp.tell() - 1, DVI_IDS))
430 if not self.id == m:
431 if not (self.id == 2 and m == 3): # pTeX/upTeX with dir allowed
432 warning('ID byte mismatch: preamble %d vs postamble %d!' % (self.id, m))
433
434 def DefineFont(self, e, fp):
435 c = SignedQuad(fp) # font_check_sum
436 q = SignedQuad(fp) # font_scaled_size
437 d = SignedQuad(fp) # font_design_size
438 n = fp.read(GetByte(fp) + GetByte(fp)).decode('utf8')
439 try:
440 f = self.font_def[e]
441 except KeyError:
442 self.font_def[e] = {'name':n, 'checksum':c, 'scaled_size':q, 'design_size':d}
443 if q <= 0 or q >= 0o1000000000:
444 warning("%s---not loaded, bad scale (%d)!" % (n, q))
445 elif d <= 0 or d >= 0o1000000000:
446 warning("%s---not loaded, bad design size (%d)!" % (n, d))
447 else:
448 if f['checksum'] != c:
449 warning("\t---check sum doesn't match previous definition!")
450 if f['scaled_size'] != q:
451 warning("\t---scaled size doesn't match previous definition!")
452 if f['design_size'] != d:
453 warning("\t---design size doesn't match previous definition!")
454 if f['name'] != n:
455 warning("\t---font name doesn't match previous definition!")
456
457 def DefineNativeFont(self, e, fp):
458 size = Get4Bytes(fp) # scaled size
459 flags = Get2Bytes(fp)
460 l = GetByte(fp) # name length
461 fnt_name = fp.read(l).decode('utf8')
462 index = Get4Bytes(fp) # face index
463 ext = []
464 embolden = 0
465 if flags & XDV_FLAG_VERTICAL: ext.append("vertical")
466 if flags & XDV_FLAG_COLORED: ext.append("color=%08X" % Get4Bytes(fp))
467 if flags & XDV_FLAG_EXTEND: ext.append("extend=%d" % SignedQuad(fp))
468 if flags & XDV_FLAG_SLANT: ext.append("slant=%d" % SignedQuad(fp))
469 if flags & XDV_FLAG_EMBOLDEN: ext.append("embolden=%d" % SignedQuad(fp))
470 try:
471 f = self.font_def[e]
472 except KeyError:
473 if index > 0:
474 fnt_name += "[%d]" % index
475 name = '"%s"' % fnt_name
476 if ext:
477 name = '"%s:%s"' % (fnt_name, ";".join(ext))
478
479 self.font_def[e] = {
480 'name': name,
481 'checksum': 0,
482 'scaled_size': size,
483 'design_size': 655360, # hardcoded
484 }
485
486 def ProcessPage(self, fp):
487 s = []
488 while True:
489 o = GetByte(fp)
490 p = self.Get1Arg(o, fp)
491 if o < SET_CHAR_0 + 128 or o in (SET1, SET2, SET3, SET4):
492 q = [p]
493 while True:
494 o = GetByte(fp)
495 p = self.Get1Arg(o, fp)
496 if o < SET_CHAR_0 + 128 or o in (SET1, SET2, SET3, SET4):
497 q.append(p)
498 else:
499 break
500 s.append([SET1, q])
501 if o == SET_RULE:
502 s.append([SET_RULE, [p, SignedQuad(fp)]])
503 elif o in (PUT1, PUT2, PUT3, PUT4):
504 s.append([PUT1, [p]])
505 elif o == PUT_RULE:
506 s.append([PUT_RULE, [p, SignedQuad(fp)]])
507 elif o == NOP:
508 continue
509 elif o == BOP:
510 warning('bop occurred before eop!')
511 break
512 elif o == EOP:
513 break
514 elif o == PUSH:
515 s.append([PUSH])
516 elif o == POP:
517 s.append([POP])
518 elif o in (RIGHT1, RIGHT2, RIGHT3, RIGHT4):
519 s.append([RIGHT1, p])
520 elif o == W0:
521 s.append([W0])
522 elif o in (W1, W2, W3, W4):
523 s.append([W1, p])
524 elif o == X0:
525 s.append([X0])
526 elif o in (X1, X2, X3, X4):
527 s.append([X1, p])
528 elif o in (DOWN1, DOWN2, DOWN3, DOWN4):
529 s.append([DOWN1, p])
530 elif o == Y0:
531 s.append([Y0])
532 elif o in (Y1, Y2, Y3, Y4):
533 s.append([Y1, p])
534 elif o == Z0:
535 s.append([Z0])
536 elif o in (Z1, Z2, Z3, Z4):
537 s.append([Z1, p])
538 elif o < FNT_NUM_0 + 64 or o in (FNT1, FNT2, FNT3, FNT4):
539 s.append([FNT1, p])
540 elif o in (XXX1, XXX2, XXX3, XXX4):
541 q = fp.read(p)
542 s.append([XXX1, q])
543 elif o in (FNT_DEF1, FNT_DEF2, FNT_DEF3, FNT_DEF4):
544 self.DefineFont(p, fp)
545 elif o == NATIVE_FONT_DEF:
546 self.DefineNativeFont(p, fp)
547 elif o == GLYPHS:
548 s.append([GLYPHS, self.GetGlyphs(fp)])
549 elif o == TEXT_GLYPHS:
550 s.append([TEXT_GLYPHS, self.GetTextGlyphs(fp)])
551 elif o == DIR:
552 s.append([DIR, p])
553 elif o == BEGIN_REFLECT:
554 s.append([BEGIN_REFLECT])
555 elif o == END_REFLECT:
556 s.append([END_REFLECT])
557 elif o == PRE:
558 warning('preamble command within a page!')
559 break
560 elif o in (POST, POST_POST):
561 warning('postamble command %d!' % o)
562 break
563 else:
564 warning('undefined command %d!' % o)
565 break
566 return s
567
568 def Get1Arg(self, o, fp):
569 if o < SET_CHAR_0 + 128:
570 return o - SET_CHAR_0
571 if o in (SET1, PUT1, FNT1, XXX1, FNT_DEF1, DIR):
572 return GetByte(fp)
573 if o in (SET2, PUT2, FNT2, XXX2, FNT_DEF2):
574 return Get2Bytes(fp)
575 if o in (SET3, PUT3, FNT3, XXX3, FNT_DEF3):
576 return Get3Bytes(fp)
577 if o in (RIGHT1, W1, X1, DOWN1, Y1, Z1):
578 return SignedByte(fp)
579 if o in (RIGHT2, W2, X2, DOWN2, Y2, Z2):
580 return SignedPair(fp)
581 if o in (RIGHT3, W3, X3, DOWN3, Y3, Z3):
582 return SignedTrio(fp)
583 if o in (SET4, SET_RULE, PUT4, PUT_RULE, RIGHT4, W4, X4, DOWN4, Y4, Z4, FNT4, XXX4, FNT_DEF4, NATIVE_FONT_DEF):
584 return SignedQuad(fp)
585 if o in (NOP, BOP, EOP, PUSH, POP, PRE, POST, POST_POST) or o > POST_POST:
586 return 0
587 if o in (W0, X0, Y0, Z0, BEGIN_REFLECT, END_REFLECT):
588 return 0
589 if o < FNT_NUM_0 + 64:
590 return o - FNT_NUM_0
591
592 def GetGlyphs(self, fp):
593 width = SignedQuad(fp)
594 length = Get2Bytes(fp)
595 glyphs = {}
596 for i in range(length):
597 glyphs[i] = {}
598 glyphs[i]["x"] = SignedQuad(fp)
599 glyphs[i]["y"] = SignedQuad(fp)
600
601 for i in range(length):
602 glyphs[i]["id"] = Get2Bytes(fp)
603
604 return (width, glyphs)
605
606 def GetTextGlyphs(self, fp):
607 length = Get2Bytes(fp)
608 chars = []
609 for i in range(length):
610 chars.append(Get2Bytes(fp))
611 width, glyphs = self.GetGlyphs(fp)
612
613 return (chars, width, glyphs)
614
615 def ReadGlyphs(self, val):
616 import re
617 glyphs = []
618 w, g = val.split(" ", 1)
619 for m in re.finditer(r"gid(?P<id>\d+?)\((?P<pos>.*?.)\)", g):
620 gid = m.group("id")
621 pos = m.group("pos")
622
623 if "," in pos:
624 x, y = pos.split(",")
625 else:
626 x, y = pos, "0sp"
627
628 glyphs.append({"id": int(gid), 'x': self.ConvLen(x), 'y': self.ConvLen(y)})
629
630 return (self.ConvLen(w), glyphs)
631
632 def ReadTextGlyphs(self, val):
633 _, text, glyphs = val.split(val[0])
634 text = "'%s'" % text
635 glyphs = glyphs.lstrip()
636 chars = GetStr(text)
637 w, glyphs = self.ReadGlyphs(glyphs)
638
639 return (chars, w, glyphs)
640
641 ##########################################################
642 # Save: Internal Format -> DVI
643 ##########################################################
644 def Save(self, fn):
645 fp = open(fn, 'wb')
646 self.SaveToFile(fp)
647 fp.close()
648
649 def SaveToFile(self, fp):
650 # WritePreamble
651 fp.write(b''.join([bytes.fromhex('%02x' % PRE), PutByte(self.id), PutSignedQuad(self.numerator), PutSignedQuad(self.denominator), PutSignedQuad(self.mag), PutByte(len(self.comment)), self.comment.encode('utf8')]))
652 # WriteFontDefinitions
653 self.WriteFontDefinitions(fp)
654 # WritePages
655 if not self.pages:
656 # dvistd0.pdf, Section A.1:
657 # > A DVI file consists of a ``preamble,'' followed by a sequence of
658 # > one or more "pages," followed by a ``postamble.''
659 warning('one or more pages required!')
660 self.pages.append({'count':[1,0,0,0,0,0,0,0,0,0], 'content':[]})
661 stackdepth = 0; loc = -1
662 for page in self.pages:
663 w = x = y = z = 0; stack = []
664 s = [bytes.fromhex('%02x' % BOP)]
665 s.extend([PutSignedQuad(c) for c in page['count']])
666 s.append(PutSignedQuad(loc))
667 for cmd in page['content']:
668 if cmd[0] == SET1:
669 for o in cmd[1]:
670 if o < 128: s.append(bytes.fromhex('%02x' % (SET_CHAR_0 + o)))
671 else: s.append(self.CmdPairU([SET1, o]))
672 elif cmd[0] in (SET_RULE, PUT_RULE):
673 s.append(bytes.fromhex('%02x' % cmd[0]) + PutSignedQuad(cmd[1][0]) + PutSignedQuad(cmd[1][1]))
674 elif cmd[0] == PUT1:
675 s.append(self.CmdPairU([PUT1, cmd[1][0]]))
676 elif cmd[0] in (RIGHT1, DOWN1):
677 s.append(self.CmdPair(cmd))
678 elif cmd[0] in (W0, X0, Y0, Z0):
679 s.append(bytes.fromhex('%02x' % cmd[0]))
680 elif cmd[0] == PUSH:
681 s.append(bytes.fromhex('%02x' % PUSH))
682 stack.append((w, x, y, z))
683 if len(stack) > stackdepth: stackdepth = len(stack)
684 elif cmd[0] == POP:
685 s.append(bytes.fromhex('%02x' % POP))
686 w, x, y, z = stack.pop()
687 elif cmd[0] == W1:
688 w = cmd[1]; s.append(self.CmdPair(cmd))
689 elif cmd[0] == X1:
690 x = cmd[1]; s.append(self.CmdPair(cmd))
691 elif cmd[0] == Y1:
692 y = cmd[1]; s.append(self.CmdPair(cmd))
693 elif cmd[0] == Z1:
694 z = cmd[1]; s.append(self.CmdPair(cmd))
695 elif cmd[0] == FNT1:
696 if cmd[1] < 64: s.append(bytes.fromhex('%02x' % (FNT_NUM_0 + cmd[1])))
697 else: s.append(self.CmdPairU(cmd))
698 elif cmd[0] == XXX1:
699 if options.xxx_encoding == "none":
700 l = len(cmd[1]) # leave encoding untouched
701 else:
702 cmd1 = cmd[1].encode(options.xxx_encoding)
703 l = len(cmd1)
704 if l < 256:
705 s.append(bytes.fromhex('%02x' % XXX1) + bytes.fromhex('%02x' % l))
706 else:
707 s.append(bytes.fromhex('%02x' % XXX4) + PutSignedQuad(l))
708 if options.xxx_encoding == "none":
709 for o in cmd[1]:
710 s.append(bytes.fromhex('%02x' % ord(o)))
711 else:
712 s.append(cmd1)
713 elif cmd[0] == DIR:
714 s.append(bytes.fromhex('%02x' % DIR) + bytes.fromhex('%02x' % cmd[1]))
715 elif cmd[0] == BEGIN_REFLECT:
716 s.append(bytes.fromhex('%02x' % BEGIN_REFLECT))
717 elif cmd[0] == END_REFLECT:
718 s.append(bytes.fromhex('%02x' % END_REFLECT))
719 elif cmd[0] == GLYPHS:
720 s.append(PutByte(GLYPHS))
721 s.append(PutGlyphs(cmd[1], cmd[2]))
722 elif cmd[0] == TEXT_GLYPHS:
723 s.append(PutByte(TEXT_GLYPHS))
724 s.append(PutTextGlyphs(cmd[1], cmd[2], cmd[3]))
725 else:
726 warning('invalid command %s!' % cmd[0])
727 s.append(bytes.fromhex('%02x' % EOP))
728 loc = fp.tell()
729 fp.write(b''.join(s))
730 # WritePostamble
731 post_loc = fp.tell()
732 fp.write(b''.join([bytes.fromhex('%02x' % POST), PutSignedQuad(loc), PutSignedQuad(self.numerator), PutSignedQuad(self.denominator), PutSignedQuad(self.mag), PutSignedQuad(self.max_v), PutSignedQuad(self.max_h), Put2Bytes(stackdepth), Put2Bytes(len(self.pages))]))
733 # WriteFontDefinitions
734 self.WriteFontDefinitions(fp)
735 # WritePostPostamble
736 fp.write(b''.join([bytes.fromhex('%02x' % POST_POST), PutSignedQuad(post_loc), PutByte(self.id_post), b'\xdf\xdf\xdf\xdf']))
737 loc = fp.tell()
738 while (loc % 4) != 0:
739 fp.write(b'\xdf'); loc += 1
740
741 def WriteFontDefinitions(self, fp):
742 s = []
743 for e in sorted(self.font_def.keys()):
744 try:
745 self.font_def[e]['native']
746 flags = self.font_def[e]['flags']
747 s.append(PutByte(NATIVE_FONT_DEF))
748 s.append(PutSignedQuad(e))
749 s.append(PutSignedQuad(self.font_def[e]['scaled_size']))
750 s.append(Put2Bytes(flags))
751 s.append(PutByte(len(self.font_def[e]['name'])))
752 s.append(self.font_def[e]['name'].encode('utf8'))
753 s.append(PutSignedQuad(self.font_def[e]['index']))
754 if flags & XDV_FLAG_COLORED: s.append(PutSignedQuad(self.font_def[e]['color']))
755 if flags & XDV_FLAG_EXTEND: s.append(PutSignedQuad(self.font_def[e]['extend']))
756 if flags & XDV_FLAG_SLANT: s.append(PutSignedQuad(self.font_def[e]['slant']))
757 if flags & XDV_FLAG_EMBOLDEN: s.append(PutSignedQuad(self.font_def[e]['embolden']))
758 except KeyError:
759 l, q = PutUnsigned(e)
760 s.append(PutByte(FNT_DEF1 + l))
761 s.append(q)
762 s.append(PutSignedQuad(self.font_def[e]['checksum']))
763 s.append(PutSignedQuad(self.font_def[e]['scaled_size']))
764 s.append(PutSignedQuad(self.font_def[e]['design_size']))
765 s.append(b'\x00')
766 s.append(PutByte(len(self.font_def[e]['name'])))
767 s.append(self.font_def[e]['name'].encode('utf8'))
768 fp.write(b''.join(s))
769
770 def CmdPairU(self, cmd):
771 l, q = PutUnsigned(cmd[1])
772 return bytes.fromhex('%02x' % (cmd[0] + l)) + q
773
774 def CmdPair(self, cmd):
775 l, q = PutSigned(cmd[1])
776 return bytes.fromhex('%02x' % (cmd[0] + l)) + q
777
778 ##########################################################
779 # Parse: Text -> Internal Format
780 ##########################################################
781 def Parse(self, fn, encoding=''):
782 fp = open(fn, 'r', encoding=encoding)
783 s = fp.read()
784 fp.close()
785 self.ParseFromString(s, encoding=encoding)
786
787 def ParseFromString(self, s, encoding=''):
788 global GetStr, cur_font, cur_dsize, cur_ssize, subfont_idx
789 if encoding == 'ascii': GetStr = GetStrASCII
790 else: GetStr = GetStrUTF8
791 self.Initialize()
792 self.fnt_num = 0
793 dir_used = 0
794 for l in s.split('\n'):
795 l = l.strip()
796 if not l or l[0] == '%': continue
797 try:
798 key, val = l.split(':', 1)
799 key = key.strip(); val = val.strip()
800 except:
801 if l[-1] == ']': v = l[:-1].split(' ')
802 else: v = l.split(' ')
803 if v[0] == "[page":
804 self.cur_page = []
805 count = [GetInt(c) for c in v[1:]]
806 if len(count) < 10: count += ([0] * (10-len(count)))
807 self.pages.append({'count':count, 'content':self.cur_page})
808 continue
809 # ParsePreamble
810 if key == "id":
811 self.id = GetInt(val)
812 if not ValidID(self.id):
813 warning('identification byte %d should be one of: %s!' % (self.id, DVI_IDS))
814 elif key == "numerator":
815 d = GetInt(val)
816 if d <= 0:
817 warning('non-positive numerator %d!' % d)
818 else:
819 self.numerator = d
820 self.ComputeConversionFactors()
821 elif key == "denominator":
822 d = GetInt(val)
823 if d <= 0:
824 warning('non-positive denominator %d!' % d)
825 else:
826 self.denominator = d
827 self.ComputeConversionFactors()
828 elif key == "magnification":
829 d = GetInt(val)
830 if d <= 0:
831 warning('non-positive magnification %d!' % d)
832 else:
833 self.mag = d
834 elif key == "comment":
835 self.comment = val[1:-1]
836 # Parse Postamble
837 elif key == "maxv":
838 self.max_v = self.ConvLen(val)
839 elif key == "maxh":
840 self.max_h = self.ConvLen(val)
841 elif key == "maxs":
842 self.max_s = GetInt(val)
843 elif key == "pages":
844 self.total_pages = GetInt(val)
845 # Parse Font Definitions
846 elif key == "fntdef":
847 self.font_def[self.fnt_num] = self.GetFntDef(val)
848 self.fnt_num += 1
849 # Parse Pages
850 elif key == 'xxx':
851 self.cur_page.append([XXX1, eval(val)])
852 elif key == 'set':
853 ol = GetStr(val)
854 if is_subfont:
855 subfont_idx = (ol[0] >> 8)
856 self.AppendFNT1()
857 nl = [ol[0] & 0xff]
858 for o in ol[1:]:
859 idx = (o >> 8)
860 if idx != subfont_idx:
861 self.cur_page.append([SET1, nl])
862 subfont_idx = idx
863 self.AppendFNT1()
864 nl = [o & 0xff]
865 else:
866 nl.append(o & 0xff)
867 self.cur_page.append([SET1, nl])
868 else:
869 self.cur_page.append([SET1, ol])
870 elif key == 'put':
871 ol = GetStr(val)
872 if len(ol) != 1:
873 warning('only one character is allowed for put!')
874 self.cur_page.append([PUT1, ol])
875 elif key == 'setrule':
876 v = val.split(' ')
877 if len(v) != 2:
878 warning('two values are required for setrule!')
879 continue
880 self.cur_page.append([SET_RULE, [self.ConvLen(c) for c in v]])
881 elif key == 'putrule':
882 v = val.split(' ')
883 if len(v) != 2:
884 warning('two values are required for putrule!')
885 continue
886 self.cur_page.append([PUT_RULE, [self.ConvLen(c) for c in v]])
887 elif key == 'fnt':
888 f = self.GetFntDef(val)
889 n = f['name']
890 d = f['design_size']
891 q = f['scaled_size']
892 if n in subfont_list:
893 is_subfont = True
894 cur_font = n; cur_dsize = d; cur_ssize = q
895 else:
896 is_subfont = False
897 try:
898 e = list(self.font_def.keys())[list(self.font_def.values()).index(f)]
899 except:
900 e = self.fnt_num
901 self.font_def[self.fnt_num] = f
902 self.fnt_num += 1
903 self.cur_page.append([FNT1, e])
904 elif key == 'right':
905 self.cur_page.append([RIGHT1, self.ConvLen(val)])
906 elif key == 'down':
907 self.cur_page.append([DOWN1, self.ConvLen(val)])
908 elif key == 'w':
909 self.cur_page.append([W1, self.ConvLen(val)])
910 elif key == 'x':
911 self.cur_page.append([X1, self.ConvLen(val)])
912 elif key == 'y':
913 self.cur_page.append([Y1, self.ConvLen(val)])
914 elif key == 'z':
915 self.cur_page.append([Z1, self.ConvLen(val)])
916 elif key == 'push':
917 self.cur_page.append([PUSH])
918 elif key == 'pop':
919 self.cur_page.append([POP])
920 elif key == 'w0':
921 self.cur_page.append([W0])
922 elif key == 'x0':
923 self.cur_page.append([X0])
924 elif key == 'y0':
925 self.cur_page.append([Y0])
926 elif key == 'z0':
927 self.cur_page.append([Z0])
928 elif key == 'dir':
929 self.cur_page.append([DIR, GetInt(val)])
930 dir_used = 1
931 elif key == 'begin_reflect':
932 self.cur_page.append([BEGIN_REFLECT])
933 elif key == 'end_reflect':
934 self.cur_page.append([END_REFLECT])
935 elif key == 'setglyphs':
936 w, glyphs = self.ReadGlyphs(val)
937 self.cur_page.append([GLYPHS, w, glyphs])
938 elif key == 'settextglyphs':
939 text, w, glyphs = self.ReadTextGlyphs(val)
940 self.cur_page.append([TEXT_GLYPHS, text, w, glyphs])
941 else:
942 warning('invalid command %s!' % key)
943 if self.id == 2 and dir_used == 1: # standard DVI with dir -> force pTeX/upTeX spec
944 self.id_post = 3
945 else:
946 self.id_post = self.id
947
948 def AppendFNT1(self):
949 f = {'name':cur_font+"%02x"%subfont_idx, 'design_size':cur_dsize, 'scaled_size':cur_ssize, 'checksum':0}
950 try:
951 e = list(self.font_def.keys())[list(self.font_def.values()).index(f)]
952 except:
953 e = self.fnt_num
954 self.font_def[e] = f
955 self.fnt_num += 1
956 self.cur_page.append([FNT1, e])
957
958 ##########################################################
959 # Dump: Internal Format -> Text
960 ##########################################################
961 def Dump(self, fn, tabsize=2, encoding=''):
962 fp = open(fn, 'w', encoding=encoding)
963 self.DumpToFile(fp, tabsize=tabsize, encoding=encoding)
964 fp.close()
965
966 def DumpToFile(self, fp, tabsize=2, encoding=''):
967 global PutStr
968 if encoding == 'ascii': PutStr = PutStrASCII
969 elif encoding == 'latin1': PutStr = PutStrLatin1
970 else: PutStr = PutStrUTF8
971 # DumpPreamble
972 fp.write("[preamble]\n")
973 fp.write("id: %d\n" % self.id)
974 fp.write("numerator: %d\n" % self.numerator)
975 fp.write("denominator: %d\n" % self.denominator)
976 fp.write("magnification: %d\n" % self.mag)
977 fp.write("comment: %s\n" % repr(self.comment))
978 # DumpPostamble
979 fp.write("\n[postamble]\n")
980 fp.write("maxv: %s\n" % self.byconv(self.max_v))
981 fp.write("maxh: %s\n" % self.byconv(self.max_h))
982 fp.write("maxs: %d\n" % self.max_s)
983 fp.write("pages: %d\n" % self.total_pages)
984 # DumpFontDefinitions
985 fp.write("\n[font definitions]\n")
986 for e in sorted(self.font_def.keys()):
987 fp.write("fntdef: %s " % self.font_def[e]['name'])
988 if self.font_def[e]['design_size'] != self.font_def[e]['scaled_size']:
989 fp.write("(%s) " % self.byconv(self.font_def[e]['design_size']))
990 fp.write("at %s\n" % self.byconv(self.font_def[e]['scaled_size']))
991 # DumpPages
992 if not self.pages:
993 # dvistd0.pdf, Section A.1:
994 # > A DVI file consists of a ``preamble,'' followed by a sequence of
995 # > one or more "pages," followed by a ``postamble.''
996 warning('one or more pages required!')
997 self.pages.append({'count':[1,0,0,0,0,0,0,0,0,0], 'content':[]})
998 for page in self.pages:
999 fp.write("\n[page" + (" %d"*10 % tuple(page['count'])) + "]\n")
1000 indent = 0
1001 for cmd in page['content']:
1002 if cmd[0] == POP:
1003 indent -= tabsize
1004 fp.write("%spop:\n" % (' ' * indent))
1005 continue
1006 fp.write("%s" % (' ' * indent))
1007 if cmd[0] == PUSH:
1008 fp.write("push:\n")
1009 indent += tabsize
1010 elif cmd[0] == XXX1:
1011 if options.xxx_encoding == "none":
1012 fp.write("xxx: %s\n" % PutStrASCII(cmd[1])) # leave encoding untouched
1013 else:
1014 fp.write("xxx: '%s'\n" % cmd[1].decode(options.xxx_encoding))
1015 elif cmd[0] == DIR:
1016 fp.write("dir: %d\n" % cmd[1])
1017 elif cmd[0] == BEGIN_REFLECT:
1018 fp.write("begin_reflect:\n")
1019 elif cmd[0] == END_REFLECT:
1020 fp.write("end_reflect:\n")
1021 elif cmd[0] == SET_RULE:
1022 fp.write("setrule: %s %s\n" % (self.byconv(cmd[1][0]), self.byconv(cmd[1][1])))
1023 elif cmd[0] == PUT_RULE:
1024 fp.write("putrule: %s %s\n" % (self.byconv(cmd[1][0]), self.byconv(cmd[1][1])))
1025 elif cmd[0] == SET1:
1026 fp.write("set: %s\n" % PutStr(cmd[1]))
1027 elif cmd[0] == PUT1:
1028 fp.write("put: %s\n" % PutStr(cmd[1]))
1029 elif cmd[0] == FNT1:
1030 f = self.font_def[cmd[1]]['name']
1031 z = self.font_def[cmd[1]]['scaled_size']
1032 if IsFontChanged(f, z):
1033 fp.write("fnt: %s " % cur_font)
1034 if self.font_def[cmd[1]]['design_size'] != self.font_def[cmd[1]]['scaled_size']:
1035 fp.write("(%s) " % self.byconv(self.font_def[cmd[1]]['design_size']))
1036 fp.write("at %s\n" % self.byconv(cur_ssize))
1037 elif cmd[0] == GLYPHS:
1038 fp.write("setglyphs: %s\n" % self.DumpGlyphs(cmd[1][0], cmd[1][1]))
1039 elif cmd[0] == TEXT_GLYPHS:
1040 fp.write("settextglyphs: %s\n" % self.DumpTextGlyphs(cmd[1][0], cmd[1][1], cmd[1][2]))
1041 elif cmd[0] == RIGHT1:
1042 fp.write("right: %s\n" % self.byconv(cmd[1]))
1043 elif cmd[0] == DOWN1:
1044 fp.write("down: %s\n" % self.byconv(cmd[1]))
1045 elif cmd[0] == W1:
1046 fp.write("w: %s\n" % self.byconv(cmd[1]))
1047 elif cmd[0] == X1:
1048 fp.write("x: %s\n" % self.byconv(cmd[1]))
1049 elif cmd[0] == Y1:
1050 fp.write("y: %s\n" % self.byconv(cmd[1]))
1051 elif cmd[0] == Z1:
1052 fp.write("z: %s\n" % self.byconv(cmd[1]))
1053 elif cmd[0] == W0:
1054 fp.write("w0:\n")
1055 elif cmd[0] == X0:
1056 fp.write("x0:\n")
1057 elif cmd[0] == Y0:
1058 fp.write("y0:\n")
1059 elif cmd[0] == Z0:
1060 fp.write("z0:\n")
1061
1062 def DumpGlyphs(self, w, g):
1063 yPresent = False
1064 for i in g:
1065 if g[i]["y"] != 0:
1066 yPresent = True
1067
1068 glyphs = []
1069 for i in g:
1070 gid = "gid%s" % g[i]["id"]
1071 x = self.byconv(g[i]["x"])
1072 y = self.byconv(g[i]["y"])
1073 if yPresent:
1074 glyphs.append("%s(%s, %s)" % (gid, x, y))
1075 else:
1076 glyphs.append("%s(%s)" % (gid, x))
1077
1078 return "%s %s" % (self.byconv(w), " ".join(glyphs))
1079
1080 def DumpTextGlyphs(self, t, w, g):
1081 return "%s %s" % (PutStrUTF8(t), self.DumpGlyphs(w, g))
1082
1083 ##########################################################
1084 # Misc Functions
1085 ##########################################################
1086 def ComputeConversionFactors(self):
1087 self.sp_conv = (self.numerator / 25400000.) * (473628672. / self.denominator)
1088 self.pt_conv = (self.numerator / 25400000.) * (7227. / self.denominator)
1089 self.bp_conv = (self.numerator / 254000.) * (72. / self.denominator)
1090 self.mm_conv = (self.numerator / 10000.) / self.denominator
1091 self.cm_conv = (self.numerator / 100000.) / self.denominator
1092 self.in_conv = (self.numerator / 254000.) * (1. / self.denominator)
1093
1094 def ConvLen(self, s):
1095 try: return int(s)
1096 except: pass
1097 try: f = float(s[:-2])
1098 except: return 0
1099 m = s[-2:]
1100 if m == "pt": return int(round(f / self.pt_conv))
1101 elif m == "in": return int(round(f / self.in_conv))
1102 elif m == "mm": return int(round(f / self.mm_conv))
1103 elif m == "cm": return int(round(f / self.cm_conv))
1104 elif m == "bp": return int(round(f / self.bp_conv))
1105 elif m == "sp": return int(round(f / self.sp_conv))
1106 else:
1107 try: return int(round(f / self.pt_conv))
1108 except: return 0
1109
1110 def GetFntDef(self, s):
1111 f = {}
1112 try:
1113 n, size = s.split('(', 1)
1114 d, q = size.split(')', 1)
1115 except:
1116 n, q = s.split(' ', 1)
1117 n = n.strip(); q = q.strip()
1118 if n.startswith('"') and n.endswith('"'):
1119 f['native'] = True
1120 n = n.strip('"')
1121 flags = 0
1122 color = 0
1123 extend = 0
1124 slant = 0
1125 embolden = 0
1126 try:
1127 name, ext = n.split(':')
1128 except:
1129 name, ext = n, ""
1130
1131 try:
1132 name, index = name.split('[')
1133 index = index.split(']')[0]
1134 except:
1135 index = 0
1136
1137 if ext:
1138 ext = ext.split(';')
1139 for opt in ext:
1140 try:
1141 key, value = opt.split('=')
1142 except:
1143 key, value = opt, ""
1144 if key == "color":
1145 flags |= XDV_FLAG_COLORED
1146 color = int(value, 16)
1147 if key == "vertical":
1148 flags |= XDV_FLAG_VERTICAL
1149 if key == "extend":
1150 flags |= XDV_FLAG_EXTEND
1151 extend = int(value)
1152 if key == "slant":
1153 flags |= XDV_FLAG_SLANT
1154 slant = int(value)
1155 if key == "embolden":
1156 flags |= XDV_FLAG_EMBOLDEN
1157 embolden = int(value)
1158
1159 f['name'] = name
1160 f['index'] = int(index)
1161 f['flags'] = flags
1162 f['color'] = color
1163 f['extend'] = extend
1164 f['slant'] = slant
1165 f['embolden'] = embolden
1166 else:
1167 f['name'] = n
1168
1169 if q[:2] == "at": q = q[2:]
1170 q = self.ConvLen(q.strip())
1171 try: d = self.ConvLen(d.strip())
1172 except: d = q
1173
1174 f['design_size'] = d
1175 f['scaled_size'] = q
1176 f['checksum'] = 0
1177
1178 return f
1179
1180 def by_sp_conv(self, a):
1181 v = self.sp_conv * a
1182 return "%dsp" % int(v)
1183
1184 def by_pt_conv(self, a):
1185 v = self.pt_conv * a
1186 if v == int(v): return "%dpt" % int(v)
1187 else: return "%fpt" % v
1188
1189 def by_bp_conv(self, a):
1190 v = self.bp_conv * a
1191 if v == int(v): return "%dbp" % int(v)
1192 else: return "%fbp" % v
1193
1194 def by_mm_conv(self, a):
1195 v = self.mm_conv * a
1196 if v == int(v): return "%dmm" % int(v)
1197 else: return "%fmm" % v
1198
1199 def by_cm_conv(self, a):
1200 v = self.cm_conv * a
1201 if v == int(v): return "%dcm" % int(v)
1202 else: return "%fcm" % v
1203
1204 def by_in_conv(self, a):
1205 v = self.in_conv * a
1206 if v == int(v): return "%din" % int(v)
1207 else: return "%fin" % v
1208
1209 ############################################################
1210 # Misc Functions for Main Routine
1211 ############################################################
1212 def ProcessOptions():
1213 usage = """%prog [options] dvi_file|dvi_dump_file
1214
1215 DVIasm is a Python script to support changing or creating DVI files
1216 via disassembling into text, editing, and then reassembling into
1217 binary format. It is fully documented at
1218 https://tug.org/TUGboat/Articles/tb28-2/tb89cho.pdf
1219 http://ajt.ktug.kr/assets/2008/5/1/0201cho.pdf
1220
1221 Please report bugs to
1222 https://github.com/aminophen/dviasm"""
1223
1224 version = """This is %prog-20240725
1225
1226 Copyright (C) 2007-2008 by Jin-Hwan Cho <[email protected]>
1227 Copyright (C) 2011-2017 by Khaled Hosny <[email protected]>
1228 Copyright (C) 2019 by Arthur Reutenauer <[email protected]>
1229 Copyright (C) 2019-2024 by Hironobu Yamashita <[email protected]>
1230
1231 This is free software; you can redistribute it and/or modify
1232 it under the terms of the GNU General Public License as published by
1233 the Free Software Foundation, either version 3 of the License, or
1234 (at your option) any later version."""
1235
1236 parser = OptionParser(usage=usage, version=version)
1237 parser.add_option("-u", "--unit",
1238 action="store", type="string", dest="unit",
1239 metavar="STR",
1240 help="unit (sp, pt, bp, mm, cm, in) [default=%default]")
1241 parser.add_option("-o", "--output",
1242 action="store", type="string", dest="output",
1243 metavar="FILE",
1244 help="filename for output instead of stdout")
1245 parser.add_option("-e", "--encoding",
1246 action="store", type="string", dest="encoding",
1247 metavar="STR",
1248 help="encoding for input/output [default=%default]")
1249 parser.add_option("-x", "--xxx-encoding",
1250 action="store", type="string", dest="xxx_encoding",
1251 metavar="STR",
1252 help="encoding for interpreting xxx strings [default=%default]")
1253 parser.add_option("-t", "--tabsize",
1254 action="store", type="int", dest="tabsize",
1255 metavar="INT",
1256 help="tab size for push/pop [default=%default]")
1257 parser.add_option("-p", "--ptex",
1258 action="store_true", dest="ptex", default=False,
1259 help="ISO-2022-JP-encoded DVI for Japanese pTeX")
1260 parser.add_option("-s", "--subfont",
1261 action="append", type="string", dest="subfont",
1262 metavar="STR",
1263 help="the list of fonts with UCS2 subfont scheme (comma separated); disable internal subfont list if STR is empty")
1264 parser.set_defaults(unit='pt', encoding='utf8', xxx_encoding='none', tabsize=2)
1265 (options, args) = parser.parse_args()
1266 if not options.unit in ['sp', 'pt', 'bp', 'mm', 'cm', 'in']:
1267 parser.error("invalid unit name '%s'!" % options.unit)
1268 if options.tabsize < 0:
1269 parser.error("negative tabsize!")
1270 if not options.xxx_encoding in ['none', 'utf8', 'sjis', 'eucjp']:
1271 parser.error("invalid xxx-encoding '%s'!" % options.xxx_encoding)
1272 if not options.encoding in ['ascii', 'latin1', 'utf8', 'sjis', 'eucjp']:
1273 parser.error("invalid encoding '%s'!" % options.encoding)
1274 if options.ptex:
1275 global is_ptex
1276 is_ptex = True
1277 if not options.encoding in ['utf8', 'sjis', 'eucjp']:
1278 parser.error("invalid encoding '%s' for Japanese pTeX!" % options.encoding)
1279 if options.subfont:
1280 global subfont_list
1281 if not options.subfont[0]: # disable subfont
1282 subfont_list = []
1283 for l in options.subfont:
1284 subfont_list.extend([f.strip() for f in l.split(',')])
1285 if len(args) != 1:
1286 parser.error("try with the option --help!")
1287 return (options, args)
1288
1289 def IsDVI(fname):
1290 from os.path import splitext
1291 if splitext(fname)[1] not in ('.dvi', '.xdv'): return False
1292 try:
1293 fp = open(fname, 'rb')
1294 fp.seek(0)
1295 if GetByte(fp) != PRE: return False
1296 fp.seek(-4, 2)
1297 if GetByte(fp) != 223: return False
1298 fp.close()
1299 except:
1300 sys.stderr.write('Failed to read %s\n' % fname)
1301 return False
1302 return True
1303
1304 ############################################################
1305 # Main Routine
1306 ############################################################
1307 if __name__ == '__main__':
1308 (options, args) = ProcessOptions()
1309 aDVI = DVI(unit=options.unit)
1310 if os.path.isfile(args[0]): fname = args[0]
1311 elif os.path.isfile(args[0] + '.xdv'): fname = args[0] + '.xdv'
1312 elif os.path.isfile(args[0] + '.dvi'): fname = args[0] + '.dvi'
1313 else:
1314 sys.stderr.write('File %s not found\n' % args[0])
1315 sys.exit(1)
1316 if IsDVI(fname): # dvi -> dump
1317 aDVI.Load(fname)
1318 if options.output: aDVI.Dump(options.output, tabsize=options.tabsize, encoding=options.encoding)
1319 else: aDVI.DumpToFile(sys.stdout, tabsize=options.tabsize, encoding=options.encoding)
1320 else: # dump -> dvi
1321 aDVI.Parse(fname, encoding=options.encoding)
1322 if options.output: aDVI.Save(options.output)
1323 else: aDVI.SaveToFile(sys.stdout.buffer)