-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwmf_parser.py
More file actions
774 lines (640 loc) · 30.2 KB
/
wmf_parser.py
File metadata and controls
774 lines (640 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
"""
WMF (Windows Metafile) Parser and Renderer
Handles parsing and rendering of WMF vector graphics files
"""
import struct
from PIL import Image, ImageDraw, ImageFont
class WMFRenderer:
"""Simple WMF renderer using PIL for basic graphics"""
def __init__(self, width=800, height=600):
self.width = width
self.height = height
self.image = Image.new('RGB', (width, height), 'white')
self.draw = ImageDraw.Draw(self.image)
# Current graphics state
self.current_pos = (0, 0)
self.pen_color = (0, 0, 0) # Black pen
self.pen_width = 1
self.pen_style = 0 # 0=solid
self.brush_color = (255, 255, 255) # WHITE_BRUSH default
self.brush_style = 0 # BS_SOLID - Windows GDI defaults to WHITE_BRUSH (solid white)
self.text_color = (0, 0, 0)
self.bg_color = (255, 255, 255)
# Coordinate transformation
self.window_org = (0, 0)
self.window_ext = (1000, 1000) # Default logical coordinate space
self.viewport_org = (0, 0)
self.viewport_ext = (width, height)
self.mapping_mode = 1 # MM_TEXT (default)
# Bounding box from placeable header
self.bbox = None
self.units_per_inch = 1440 # Default: twips
self.use_window_transform = False # Flag to use window/viewport instead of bbox
# Object table for GDI objects (supports negative indices for stock objects)
self.objects = {}
self.selected_pen = None
self.selected_brush = None
self.selected_font = None
# State stack for SAVEDC/RESTOREDC
self.state_stack = []
# Track coordinate bounds for auto-scaling
self.coord_min_x = None
self.coord_max_x = None
self.coord_min_y = None
self.coord_max_y = None
# Initialize stock objects (negative indices)
self._init_stock_objects()
def _init_stock_objects(self):
"""Initialize Windows stock objects (negative indices)"""
# Stock pens
self.objects[-1] = {'type': 'pen', 'style': 0, 'width': 1, 'color': (255, 255, 255)} # WHITE_PEN
self.objects[-2] = {'type': 'pen', 'style': 0, 'width': 1, 'color': (0, 0, 0)} # BLACK_PEN
self.objects[-3] = {'type': 'pen', 'style': 5, 'width': 0, 'color': (0, 0, 0)} # NULL_PEN
# Stock brushes
self.objects[-4] = {'type': 'brush', 'style': 0, 'color': (255, 255, 255), 'hatch': 0} # WHITE_BRUSH
self.objects[-5] = {'type': 'brush', 'style': 0, 'color': (192, 192, 192), 'hatch': 0} # LTGRAY_BRUSH
self.objects[-6] = {'type': 'brush', 'style': 0, 'color': (128, 128, 128), 'hatch': 0} # GRAY_BRUSH
self.objects[-7] = {'type': 'brush', 'style': 0, 'color': (64, 64, 64), 'hatch': 0} # DKGRAY_BRUSH
self.objects[-8] = {'type': 'brush', 'style': 0, 'color': (0, 0, 0), 'hatch': 0} # BLACK_BRUSH
self.objects[-9] = {'type': 'brush', 'style': 1, 'color': (0, 0, 0), 'hatch': 0} # NULL_BRUSH (hollow)
def set_bbox(self, left, top, right, bottom, units_per_inch):
"""Set bounding box from placeable header"""
self.bbox = (left, top, right, bottom)
self.units_per_inch = units_per_inch
# Set default window extent to bbox size
bbox_width = right - left
bbox_height = bottom - top
self.window_ext = (bbox_width, bbox_height)
self.window_org = (left, top)
def _track_coords(self, x, y):
"""Track coordinate ranges for auto-scaling"""
if self.coord_min_x is None or x < self.coord_min_x:
self.coord_min_x = x
if self.coord_max_x is None or x > self.coord_max_x:
self.coord_max_x = x
if self.coord_min_y is None or y < self.coord_min_y:
self.coord_min_y = y
if self.coord_max_y is None or y > self.coord_max_y:
self.coord_max_y = y
def transform_coords(self, x, y):
"""Transform logical coordinates to device (screen) coordinates"""
# Track coordinates for bounds
self._track_coords(x, y)
# If window extent was explicitly set, use window/viewport transform
if self.use_window_transform or not self.bbox:
# Use window/viewport transformation
win_org_x, win_org_y = self.window_org
win_ext_x, win_ext_y = self.window_ext
vp_org_x, vp_org_y = self.viewport_org
vp_ext_x, vp_ext_y = self.viewport_ext
if win_ext_x == 0 or win_ext_y == 0:
return (0, 0)
# Transform using window/viewport mapping
img_x = int(((x - win_org_x) * vp_ext_x) / win_ext_x + vp_org_x)
img_y = int(((y - win_org_y) * vp_ext_y) / win_ext_y + vp_org_y)
else:
# Use placeable header bounding box
left, top, right, bottom = self.bbox
bbox_width = right - left
bbox_height = bottom - top
if bbox_width == 0 or bbox_height == 0:
return (0, 0)
# Normalize to 0-1 based on bounding box
norm_x = (x - left) / bbox_width
norm_y = (y - top) / bbox_height
# Scale to image size
img_x = int(norm_x * self.width)
img_y = int(norm_y * self.height)
# Don't clamp - let PIL handle out of bounds coordinates
# This prevents cutting off shapes that extend beyond initial bounds
return (img_x, img_y)
def move_to(self, x, y):
"""Move current position without drawing"""
self.current_pos = (x, y)
def line_to(self, x, y):
"""Draw line from current position to (x, y)"""
start = self.transform_coords(*self.current_pos)
end = self.transform_coords(x, y)
if self.pen_style == 0: # Solid
self.draw.line([start, end], fill=self.pen_color, width=self.pen_width)
self.current_pos = (x, y)
def draw_polyline(self, points):
"""Draw a polyline"""
if len(points) < 2:
return
transformed = [self.transform_coords(x, y) for x, y in points]
if self.pen_style == 0: # Solid
self.draw.line(transformed, fill=self.pen_color, width=self.pen_width)
def draw_polygon(self, points):
"""Draw a filled polygon"""
if len(points) < 3:
return
transformed = [self.transform_coords(x, y) for x, y in points]
# Draw fill - handle different brush styles
# BS_SOLID=0, BS_NULL=1, BS_HATCHED=2, BS_PATTERN=3
if self.brush_style != 1: # Not NULL/HOLLOW brush
# For now, treat all non-null brushes as solid
# BS_SOLID (0), BS_HATCHED (2), BS_PATTERN (3) all fill
# Drawing polygon with fill
self.draw.polygon(transformed, fill=self.brush_color, outline=None)
else:
pass # Skipping fill for BS_NULL brush
# Draw outline (if pen is not NULL_PEN)
if self.pen_style != 5 and self.pen_width > 0: # style 5 = NULL_PEN
outline_points = transformed + [transformed[0]]
self.draw.line(outline_points, fill=self.pen_color, width=self.pen_width)
def draw_rectangle(self, left, top, right, bottom):
"""Draw a filled rectangle"""
p1 = self.transform_coords(left, top)
p2 = self.transform_coords(right, bottom)
# Ensure correct ordering
x1, y1 = min(p1[0], p2[0]), min(p1[1], p2[1])
x2, y2 = max(p1[0], p2[0]), max(p1[1], p2[1])
# Draw fill - handle different brush styles
if self.brush_style != 1: # Not NULL/HOLLOW brush
self.draw.rectangle([x1, y1, x2, y2], fill=self.brush_color, outline=None)
# Draw outline (if pen is not NULL_PEN)
if self.pen_style != 5 and self.pen_width > 0: # style 5 = NULL_PEN
self.draw.rectangle([x1, y1, x2, y2], outline=self.pen_color, width=self.pen_width)
def draw_ellipse(self, left, top, right, bottom):
"""Draw a filled ellipse"""
p1 = self.transform_coords(left, top)
p2 = self.transform_coords(right, bottom)
# Ensure correct ordering
x1, y1 = min(p1[0], p2[0]), min(p1[1], p2[1])
x2, y2 = max(p1[0], p2[0]), max(p1[1], p2[1])
# Draw fill - handle different brush styles
if self.brush_style != 1: # Not NULL/HOLLOW brush
self.draw.ellipse([x1, y1, x2, y2], fill=self.brush_color, outline=None)
# Draw outline (if pen is not NULL_PEN)
if self.pen_style != 5 and self.pen_width > 0: # style 5 = NULL_PEN
self.draw.ellipse([x1, y1, x2, y2], outline=self.pen_color, width=self.pen_width)
def draw_text(self, x, y, text):
"""Draw text at position"""
pos = self.transform_coords(x, y)
try:
font = ImageFont.truetype("DejaVuSans.ttf", 12)
except:
font = ImageFont.load_default()
self.draw.text(pos, text, fill=self.text_color, font=font)
def set_pen(self, style, width, color):
"""Set pen attributes"""
self.pen_style = style
self.pen_width = max(1, width) if width > 0 else 1
self.pen_color = color
def set_brush(self, style, color):
"""Set brush attributes"""
self.brush_style = style
self.brush_color = color
def set_text_color(self, color):
"""Set text color"""
self.text_color = color
def set_bg_color(self, color):
"""Set background color"""
self.bg_color = color
def set_window_org(self, x, y):
"""Set window origin"""
self.window_org = (x, y)
def set_window_ext(self, x, y):
"""Set window extent"""
self.window_ext = (x, y)
self.use_window_transform = True # Switch to window/viewport mode
def set_viewport_org(self, x, y):
"""Set viewport origin"""
self.viewport_org = (x, y)
def set_viewport_ext(self, x, y):
"""Set viewport extent"""
self.viewport_ext = (x, y)
def set_mapping_mode(self, mode):
"""Set coordinate mapping mode"""
self.mapping_mode = mode
def create_pen(self, index, style, width_x, width_y, color):
"""Create a pen object"""
self.objects[index] = {
'type': 'pen',
'style': style,
'width': width_x,
'color': color
}
# print(f"DEBUG: Created pen[{index}]: style={style}, width={width_x}, color={color}")
def create_brush(self, index, style, color, hatch):
"""Create a brush object"""
self.objects[index] = {
'type': 'brush',
'style': style,
'color': color,
'hatch': hatch
}
# print(f"DEBUG: Created brush[{index}]: style={style}, color={color}")
def create_font(self, index):
"""Create a font object"""
self.objects[index] = {
'type': 'font'
}
# print(f"DEBUG: Created font[{index}]")
def select_object(self, index):
"""Select an object from the object table"""
if index in self.objects:
obj = self.objects[index]
if obj['type'] == 'pen':
self.set_pen(obj['style'], obj['width'], obj['color'])
self.selected_pen = index
# print(f"DEBUG: Selected pen[{index}]: color={obj['color']}")
elif obj['type'] == 'brush':
self.set_brush(obj['style'], obj['color'])
self.selected_brush = index
# print(f"DEBUG: Selected brush[{index}]: style={obj['style']}, color={obj['color']}")
elif obj['type'] == 'font':
self.selected_font = index
# print(f"DEBUG: Selected font[{index}]")
else:
pass # Object not in table - may have been deleted
def delete_object(self, index):
"""Delete an object from the object table"""
if index in self.objects and index >= 0: # Don't delete stock objects
del self.objects[index]
def save_dc(self):
"""Save current graphics state (SAVEDC)"""
state = {
'pen_color': self.pen_color,
'pen_width': self.pen_width,
'pen_style': self.pen_style,
'brush_color': self.brush_color,
'brush_style': self.brush_style,
'text_color': self.text_color,
'bg_color': self.bg_color,
'current_pos': self.current_pos,
'window_org': self.window_org,
'window_ext': self.window_ext,
'viewport_org': self.viewport_org,
'viewport_ext': self.viewport_ext,
}
self.state_stack.append(state)
def restore_dc(self):
"""Restore saved graphics state (RESTOREDC)"""
if self.state_stack:
state = self.state_stack.pop()
self.pen_color = state['pen_color']
self.pen_width = state['pen_width']
self.pen_style = state['pen_style']
self.brush_color = state['brush_color']
self.brush_style = state['brush_style']
self.text_color = state['text_color']
self.bg_color = state['bg_color']
self.current_pos = state['current_pos']
self.window_org = state['window_org']
self.window_ext = state['window_ext']
self.viewport_org = state['viewport_org']
self.viewport_ext = state['viewport_ext']
def auto_scale_viewport(self):
"""Auto-scale viewport based on actual coordinate ranges"""
if self.coord_min_x is not None and self.coord_max_x is not None:
coord_width = self.coord_max_x - self.coord_min_x
coord_height = self.coord_max_y - self.coord_min_y
if coord_width > 0 and coord_height > 0:
# Add 5% padding
padding_x = coord_width * 0.05
padding_y = coord_height * 0.05
self.window_org = (
int(self.coord_min_x - padding_x),
int(self.coord_min_y - padding_y)
)
self.window_ext = (
int(coord_width + 2 * padding_x),
int(coord_height + 2 * padding_y)
)
self.use_window_transform = True
def get_image(self):
"""Get the rendered image"""
return self.image
def parse_colorref(color_ref):
"""Parse COLORREF value (0x00BBGGRR) to RGB tuple"""
r = color_ref & 0xFF
g = (color_ref >> 8) & 0xFF
b = (color_ref >> 16) & 0xFF
return (r, g, b)
def parse_wmf(data, max_dimension=1200):
"""
Parse WMF binary data and return rendered image
Args:
data: Binary WMF file data
max_dimension: Maximum width or height (maintains aspect ratio)
Returns:
PIL Image object
"""
if len(data) < 18:
raise ValueError(f"Invalid WMF file: too short ({len(data)} bytes, need at least 18)")
# Pre-scan to get dimensions for proper aspect ratio
pos = 0
has_placeable = False
bbox_width = 1000
bbox_height = 1000
# Check for placeable header to get bounding box
if len(data) >= 22:
magic = struct.unpack('<I', data[0:4])[0]
if magic == 0x9AC6CDD7:
has_placeable = True
left, top, right, bottom = struct.unpack('<hhhh', data[6:14])
bbox_width = abs(right - left)
bbox_height = abs(bottom - top)
pos = 22 # Skip placeable header
# Calculate output dimensions maintaining aspect ratio
if bbox_width > 0 and bbox_height > 0:
aspect_ratio = bbox_width / bbox_height
if aspect_ratio > 1:
# Wider than tall
width = min(max_dimension, bbox_width)
height = int(width / aspect_ratio)
else:
# Taller than wide
height = min(max_dimension, bbox_height)
width = int(height * aspect_ratio)
else:
# Fallback if no valid dimensions
width = 800
height = 600
# Create renderer with proper dimensions
renderer = WMFRenderer(width, height)
pos = 0
# Check for placeable header (reparse to set bbox)
if len(data) >= 22:
magic = struct.unpack('<I', data[0:4])[0]
if magic == 0x9AC6CDD7:
has_placeable = True
# Parse placeable header
left, top, right, bottom = struct.unpack('<hhhh', data[6:14])
units_per_inch = struct.unpack('<H', data[14:16])[0]
renderer.set_bbox(left, top, right, bottom, units_per_inch)
pos = 22 # Skip placeable header
# Read standard header (18 bytes)
if pos + 18 > len(data):
raise ValueError(f"Invalid WMF file: too short for header at position {pos} (file size: {len(data)})")
header = data[pos:pos+18]
file_type, header_size, version, file_size, num_objects, max_record, num_params = \
struct.unpack('<HHHIHIH', header)
pos += 18
# Track object indices - use a free list for reusing deleted slots
next_object_index = 0
free_object_indices = [] # Stack of freed indices that can be reused
# First pass: scan for coordinate bounds if no bbox or window extent set
if not has_placeable:
coord_min_x, coord_min_y = None, None
coord_max_x, coord_max_y = None, None
scan_pos = pos
while scan_pos < len(data):
if scan_pos + 6 > len(data):
break
rec_size, rec_func = struct.unpack('<IH', data[scan_pos:scan_pos+6])
par_size = (rec_size - 3) * 2
if scan_pos + 6 + par_size > len(data):
break
pars = data[scan_pos+6:scan_pos+6+par_size]
# Extract coordinates from drawing records
try:
if rec_func in [0x0213, 0x0214] and len(pars) >= 4: # LINETO, MOVETO
y, x = struct.unpack('<hh', pars[0:4])
if coord_min_x is None or x < coord_min_x: coord_min_x = x
if coord_max_x is None or x > coord_max_x: coord_max_x = x
if coord_min_y is None or y < coord_min_y: coord_min_y = y
if coord_max_y is None or y > coord_max_y: coord_max_y = y
elif rec_func in [0x0324, 0x0325] and len(pars) >= 2: # POLYGON, POLYLINE
num_pts = struct.unpack('<H', pars[0:2])[0]
for i in range(num_pts):
off = 2 + i * 4
if off + 4 <= len(pars):
x, y = struct.unpack('<hh', pars[off:off+4])
if coord_min_x is None or x < coord_min_x: coord_min_x = x
if coord_max_x is None or x > coord_max_x: coord_max_x = x
if coord_min_y is None or y < coord_min_y: coord_min_y = y
if coord_max_y is None or y > coord_max_y: coord_max_y = y
elif rec_func in [0x0418, 0x041B] and len(pars) >= 8: # ELLIPSE, RECTANGLE
bottom, right, top, left = struct.unpack('<hhhh', pars[0:8])
for coord in [left, right]:
if coord_min_x is None or coord < coord_min_x: coord_min_x = coord
if coord_max_x is None or coord > coord_max_x: coord_max_x = coord
for coord in [top, bottom]:
if coord_min_y is None or coord < coord_min_y: coord_min_y = coord
if coord_max_y is None or coord > coord_max_y: coord_max_y = coord
elif rec_func == 0x020C and len(pars) >= 4: # SETWINDOWEXT - use it directly
y, x = struct.unpack('<hh', pars[0:4])
renderer.set_window_ext(x, y)
break # Stop scanning if window extent is set
except:
pass
scan_pos += rec_size * 2
# Set window extent based on scanned bounds if we found any
if coord_min_x is not None and coord_max_x is not None and not renderer.use_window_transform:
coord_width = coord_max_x - coord_min_x
coord_height = coord_max_y - coord_min_y
if coord_width > 0 and coord_height > 0:
padding_x = coord_width * 0.1
padding_y = coord_height * 0.1
renderer.window_org = (int(coord_min_x - padding_x), int(coord_min_y - padding_y))
renderer.window_ext = (int(coord_width + 2 * padding_x), int(coord_height + 2 * padding_y))
# Parse records (actual rendering)
while pos < len(data):
# Read record header
if pos + 6 > len(data):
break
record_size, record_func = struct.unpack('<IH', data[pos:pos+6])
# record_size is in WORDs (2 bytes each), includes 3-WORD header
param_size = (record_size - 3) * 2
if pos + 6 + param_size > len(data):
break
params = data[pos+6:pos+6+param_size]
try:
# Process record based on function code
# META_EOF (0x0000)
if record_func == 0x0000:
break
# META_SAVEDC (0x001E)
elif record_func == 0x001E:
renderer.save_dc()
# META_RESTOREDC (0x0127)
elif record_func == 0x0127:
renderer.restore_dc()
# META_SETBKCOLOR (0x0201)
elif record_func == 0x0201 and len(params) >= 4:
color_ref = struct.unpack('<I', params[0:4])[0]
renderer.set_bg_color(parse_colorref(color_ref))
# META_SETBKMODE (0x0102)
elif record_func == 0x0102:
pass # Background mode
# META_SETMAPMODE (0x0103)
elif record_func == 0x0103 and len(params) >= 2:
mode = struct.unpack('<H', params[0:2])[0]
renderer.set_mapping_mode(mode)
# META_SETROP2 (0x0104)
elif record_func == 0x0104:
pass # Binary raster operation
# META_SETPOLYFILLMODE (0x0106)
elif record_func == 0x0106:
pass # Polygon fill mode
# META_SETTEXTCOLOR (0x0209)
elif record_func == 0x0209 and len(params) >= 4:
color_ref = struct.unpack('<I', params[0:4])[0]
renderer.set_text_color(parse_colorref(color_ref))
# META_SETWINDOWORG (0x020B)
elif record_func == 0x020B and len(params) >= 4:
y, x = struct.unpack('<hh', params[0:4])
renderer.set_window_org(x, y)
# META_SETWINDOWEXT (0x020C)
elif record_func == 0x020C and len(params) >= 4:
y, x = struct.unpack('<hh', params[0:4])
renderer.set_window_ext(x, y)
# META_SETVIEWPORTORG (0x020D)
elif record_func == 0x020D and len(params) >= 4:
y, x = struct.unpack('<hh', params[0:4])
renderer.set_viewport_org(x, y)
# META_SETVIEWPORTEXT (0x020E)
elif record_func == 0x020E and len(params) >= 4:
y, x = struct.unpack('<hh', params[0:4])
renderer.set_viewport_ext(x, y)
# META_LINETO (0x0213)
elif record_func == 0x0213 and len(params) >= 4:
y, x = struct.unpack('<hh', params[0:4])
renderer.line_to(x, y)
# META_MOVETO (0x0214)
elif record_func == 0x0214 and len(params) >= 4:
y, x = struct.unpack('<hh', params[0:4])
renderer.move_to(x, y)
# META_POLYGON (0x0324)
elif record_func == 0x0324 and len(params) >= 2:
num_points = struct.unpack('<H', params[0:2])[0]
points = []
for i in range(num_points):
offset = 2 + i * 4
if offset + 4 <= len(params):
x, y = struct.unpack('<hh', params[offset:offset+4])
points.append((x, y))
if points:
renderer.draw_polygon(points)
# META_POLYLINE (0x0325)
elif record_func == 0x0325 and len(params) >= 2:
num_points = struct.unpack('<H', params[0:2])[0]
points = []
for i in range(num_points):
offset = 2 + i * 4
if offset + 4 <= len(params):
x, y = struct.unpack('<hh', params[offset:offset+4])
points.append((x, y))
if points:
renderer.draw_polyline(points)
# META_POLYPOLYGON (0x0538)
elif record_func == 0x0538 and len(params) >= 2:
num_polys = struct.unpack('<H', params[0:2])[0]
# Read point counts for each polygon
point_counts = []
offset = 2
for i in range(num_polys):
if offset + 2 <= len(params):
count = struct.unpack('<H', params[offset:offset+2])[0]
point_counts.append(count)
offset += 2
# Read and draw each polygon
for count in point_counts:
points = []
for i in range(count):
if offset + 4 <= len(params):
x, y = struct.unpack('<hh', params[offset:offset+4])
points.append((x, y))
offset += 4
if points:
renderer.draw_polygon(points)
# META_ELLIPSE (0x0418)
elif record_func == 0x0418 and len(params) >= 8:
bottom, right, top, left = struct.unpack('<hhhh', params[0:8])
renderer.draw_ellipse(left, top, right, bottom)
# META_RECTANGLE (0x041B)
elif record_func == 0x041B and len(params) >= 8:
bottom, right, top, left = struct.unpack('<hhhh', params[0:8])
renderer.draw_rectangle(left, top, right, bottom)
# META_ROUNDRECT (0x061C)
elif record_func == 0x061C and len(params) >= 12:
# Simplified: draw as regular rectangle
height, width, bottom, right, top, left = struct.unpack('<hhhhhh', params[0:12])
renderer.draw_rectangle(left, top, right, bottom)
# META_TEXTOUT (0x0521)
elif record_func == 0x0521 and len(params) >= 6:
# Simple text output
count = struct.unpack('<H', params[0:2])[0]
if len(params) >= 2 + count + 4:
text = params[2:2+count].decode('ascii', errors='ignore')
# Align to word boundary
text_bytes = count if count % 2 == 0 else count + 1
offset = 2 + text_bytes
y, x = struct.unpack('<hh', params[offset:offset+4])
renderer.draw_text(x, y, text)
# META_CREATEPENINDIRECT (0x02FA)
elif record_func == 0x02FA and len(params) >= 10:
# Reuse freed index or allocate new one
if free_object_indices:
obj_index = free_object_indices.pop()
else:
obj_index = next_object_index
next_object_index += 1
style = struct.unpack('<H', params[0:2])[0]
width_x, width_y = struct.unpack('<hh', params[2:6])
color_ref = struct.unpack('<I', params[6:10])[0]
color = parse_colorref(color_ref)
renderer.create_pen(obj_index, style, width_x, width_y, color)
# META_CREATEBRUSHINDIRECT (0x02FB)
elif record_func == 0x02FB and len(params) >= 8:
# Reuse freed index or allocate new one
if free_object_indices:
obj_index = free_object_indices.pop()
else:
obj_index = next_object_index
next_object_index += 1
style = struct.unpack('<H', params[0:2])[0]
color_ref = struct.unpack('<I', params[2:6])[0]
hatch = struct.unpack('<H', params[6:8])[0]
color = parse_colorref(color_ref)
renderer.create_brush(obj_index, style, color, hatch)
# META_CREATEFONTINDIRECT (0x02FC)
elif record_func == 0x02FC:
# Reuse freed index or allocate new one
if free_object_indices:
obj_index = free_object_indices.pop()
else:
obj_index = next_object_index
next_object_index += 1
# WORKAROUND: Some WMF files incorrectly use 0x02FC for brush creation
# Standard LOGFONT structure is 18+ bytes, but if we get exactly 8 bytes,
# it's actually a CREATEBRUSHINDIRECT structure (style + color + hatch)
if len(params) == 8:
# Treat as CREATEBRUSHINDIRECT
style = struct.unpack('<H', params[0:2])[0]
color_ref = struct.unpack('<I', params[2:6])[0]
hatch = struct.unpack('<H', params[6:8])[0]
color = parse_colorref(color_ref)
renderer.create_brush(obj_index, style, color, hatch)
else:
# Actual font - just track the index
renderer.create_font(obj_index)
# META_SELECTOBJECT (0x012D)
elif record_func == 0x012D and len(params) >= 2:
index = struct.unpack('<H', params[0:2])[0]
renderer.select_object(index)
# META_DELETEOBJECT (0x01F0)
elif record_func == 0x01F0 and len(params) >= 2:
index = struct.unpack('<H', params[0:2])[0]
renderer.delete_object(index)
# Add freed index to free list for reuse
if index >= 0: # Don't free stock objects (negative indices)
free_object_indices.append(index)
except Exception as e:
# Continue parsing even if individual record fails
pass
# Move to next record (record_size is in WORDs)
pos += record_size * 2
return renderer.get_image()
if __name__ == "__main__":
# Test parser
import sys
if len(sys.argv) > 1:
with open(sys.argv[1], 'rb') as f:
data = f.read()
image = parse_wmf(data)
image.show()
print(f"Parsed {sys.argv[1]}")