Repository navigation
Expand file tree
/
Copy pathpyemf.py
More file actions
executable file
·3878 lines (3150 loc) · 117 KB
/
Copy pathpyemf.py
File metadata and controls
executable file
·3878 lines (3150 loc) · 117 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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
pyemf is a pure python module that provides a cross-platform ability
to generate enhanced metafiles (.emf files), a vector graphics format
defined by the ECMA-234 standard. Enhanced metafiles are a natively
supported image and scalable clip-art format in the OpenOffice suite
of tools and in Windows applications.
U{ECMA-234<http://www.ecma-international.org/publications/standards/Ecma-234.htm>}
is the published interface for enhanced metafiles, which is also a
file-based representation of the Windows graphics device interface.
This API follows most of the naming conventions of ECMA-234, and most
of the parameter lists of methods are the same as their ECMA-234
equivalents. The primary difference is that pyemf has extended the
API to be object-oriented based on the class L{EMF}. So, while in
ECMA-234 the first argument is generally the device context, here in
pyemf it is implicit in the class instance.
ECMA-234 defines a lot of constants (mostly integers that are used as
flags to various functions) that pyemf defines as module level
variables. So, rather than pollute your global namespace, it is
recommended that you use C{import pyemf} rather than C{from pyemf
import *}.
Introduction
============
To use pyemf in your programs, you L{instantiate<EMF.__init__>} an
L{EMF} object, draw some stuff using its methods, and save the file.
An example::
#!/usr/bin/env python
import pyemf
width=8.0
height=6.0
dpi=300
emf=pyemf.EMF(width,height,dpi)
thin=emf.CreatePen(pyemf.PS_SOLID,1,(0x01,0x02,0x03))
emf.SelectObject(thin)
emf.Polyline([(0,0),(width*dpi,height*dpi)])
emf.Polyline([(0,height*dpi),(width*dpi,0)])
emf.save("test-1.emf")
This small program creates a 8in x 6in EMF at 300 dots per inch, and
draws two lines connecting the opposite corners. This simple test is
available as C{test-1.py} in the C{examples} directory of the pyemf
distribution. There are many other small test programs to demonstrate
other features of the EMF class.
Naming Conventions in pyemf
===========================
Methods that belong to ECMA-234 are C{CamelCased} starting with a
capital letter. Methods that apply to the operation of the L{EMF}
class itself (i.e. L{load<EMF.load>} and L{save<EMF.save>}) are
C{lower} cased. Constants described in L{pyemf} that are used as
parameters are C{ALL_UPPER_CASE}.
Coordinate System
=================
Coordinates are addressed a coordinate system called B{page space} by
integer pixels in a horizontal range (increasing to the right) from C{0}
to C{width*density}, and vertically (from the top down) C{0} to
C{height*density}. Density is either dots per inch if working in
english units, or dots per millimeter if working in metric.
World and Page Space
--------------------
Note that there are four coordinate spaces used by GDI: world, page,
device, and physical device. World and page are the same, unless a
world transform (L{SetWorldTransform<EMF.SetWorldTransform>},
L{ModifyWorldTransform<EMF.ModifyWorldTransform>}) is used. In that
case, you operate in world space (that is transformed into page space
by multiplying by the transformation matrix), and it could be scaled
differently.
Experimental Coordinate System
------------------------------
Experimental support for device coordinates is available through
L{SetMapMode<EMF.SetMapMode>} and the various Window and Viewport
methods. Device coordinates are referenced by physical dimensions
corresponding to the mapping mode currently used. [The methods work
correctly (in the sense that they generate the correct records in the
metafile) and the API won't change, but it's not clear to me what the
parameters should do.]
Drawing Characteristics
=======================
GDI has a concept of the B{current object} for the each of the three
drawing characteristics: line style, fill style, and font. Once a
characteristic is made current using
L{SelectObject<EMF.SelectObject>}, it remains current until it is
replaced by another call to SelectObject. Note that a call to
SelectObject only affects that characteristic, and not the other two,
so changing the line style doesn't effect the fill style or the font.
Additionally, there is a set of B{stock objects} retrievable with
L{GetStockObject<EMF.GetStockObject>} that should be available on any
system capable of rendering an EMF.
Colors
------
A quick note about color. Colors in pyemf are specified one of three
ways:
- (r,g,b) tuple, where each component is a integer between 0 and 255 inclusive.
- (r,g,b) tuple, where each component is a float between 0.0 and 1.0 inclusive.
- packed integer created by a call to L{RGB}
Line Styles
-----------
Line styles are created by L{CreatePen<EMF.CreatePen>} and specify the
style, width, and color.
Note that there is a NULL_PEN stock object if you don't actually want
to draw a line with a drawing primitive.
Fill Styles
-----------
Polygon fill styles are created by
L{CreateSolidBrush<EMF.CreateSolidBrush>} and theoretically
L{CreateHatchBrush<EMF.CreateHatchBrush>}, although the latter doesn't
seem to be supported currently in OpenOffice. So, reliably we can only
use CreateSolidBrush and thus can only specify a fill color and not a
fill pattern.
Note that there is a stock object NULL_BRUSH that doesn't fill, useful
if you want to only draw an outline of a primitive that is normally
filled.
An interesting side-note is that there is no direct support for
gradients in EMF. Examining some .emfs that do have gradients shows
that Windows produces them using clipping regions and subdividing the
object into areas of a single color an drawing slices of the
individual color. Better support for clipping regions is the subject
of a future release of pyemf, but they also don't seem to work well in
OpenOffice, so it hasn't been a high priority.
Fonts
-----
L{CreateFont<EMF.CreateFont>} requires a large number of parameters,
the most important being the height, the rotation, and the name. Note
that the height can either be specified as a positive or negative
integer, where negative means use that value as the average I{glyph}
height and positive means use the value as the average I{cell} height.
Since a glyph is contained within a cell, the negative value will
yield a slightly larger font when rendered on screen.
Note that the two rotation values must specify the same angle.
Also note that font color is not part of a
L{SelectObject<EMF.SelectObject>} characteristic. It is specified
using the separate method L{SetTextColor<EMF.SetTextColor>}.
L{SetBkMode<EMF.SetBkMode>} and L{SetBkColor<EMF.SetBkColor>} are
supposed to work with text, but in my testing with OpenOffice it hasn't been
consistent. I tend to just C{SetBkMode(pyemf.TRANSPARENT)} and leave
it at that.
Drawing
=======
The methods listed under B{Drawing Primitives} below use either the
current line style or the current fill style (or both). Any primitive
that creates a closed figure (L{Polygon<EMF.Polygon>},
L{PolyPolygon<EMF.PolyPolygon>}, L{Rectangle<EMF.Rectangle>},
L{RoundRect<EMF.RoundRect>}, L{Ellipse<EMF.Ellipse>},
L{Chord<EMF.Chord>}, and L{Pie<EMF.Pie>}) will use both the line and
fill style. Others (L{Polyline<EMF.Polyline>},
L{PolyPolyline<EMF.PolyPolyline>} and L{Arc<EMF.Arc>}) will only use
the line style, excepting L{SetPixel<EMF.SetPixel>} which doesn't use either.
Paths
=====
To create more complicated shapes, the B{Path Primitives} are used. A
path is started with a call to L{BeginPath<EMF.BeginPath>} and the
initial point should be set with L{MoveTo<EMF.MoveTo>}. Calls to
L{LineTo<EMF.LineTo>}, L{PolylineTo<EMF.PolylineTo>},
L{ArcTo<EMF.ArcTo>}, and L{PolyBezierTo<EMF.PolyBezierTo>} extend the
path. L{CloseFigure<EMF.CloseFigure>} should be used to connect the
final point to the starting point, otherwise the path may be filled
incorrectly. L{EndPath<EMF.EndPath>} then completes the path, and it
may be outlined with L{StrokePath<EMF.StrokePath>}, filled with
L{FillPath<EMF.FillPath>} or both with
L{StrokeAndFillPath<EMF.StrokeAndFillPath>}.
Note that OpenOffice ignores L{ArcTo<EMF.ArcTo>} in terms of path
continuity -- the arc is drawn, but it is not connected to the path.
Note that L{SelectClipPath<EMF.SelectClipPath>} is broken in OpenOffice.
Coordinate System Transformation
================================
You might have noticed that methods like L{Ellipse<EMF.Ellipse>} and
L{Rectangle<EMF.Rectangle>} can only create objects that are aligned
with the X-Y axis. This would be a real limitation without some way
to rotate the figures. L{SetWorldTransform<EMF.SetWorldTransform>}
and L{ModifyWorldTransform<EMF.ModifyWorldTransform>} provide this.
These methods provide a generalized linear transformation that can
translate, rotate, scale and shear subsequent graphics operations.
These methods aren't required by the ECMA-234 spec, which may explain
why their support in OpenOffice is mixed. Drawing primitives and
paths seem to be supported and are transformed, but text is not
(though it should be).
@author: $author
@version: $version
"""
from __future__ import print_function, division
__extra_epydoc_fields__ = [
('gdi', 'GDI Command', 'GDI Commands'),
('oo', 'OpenOffice Support'),
]
import os
import sys
import re
import struct
import copy
import inspect
# python 2/3 compatibility helpers
is_py3 = sys.version_info[0] == 3
if is_py3:
from io import BytesIO, StringIO
cunicode = str
else:
from cStringIO import StringIO
BytesIO = StringIO
cunicode = unicode
# setup.py requires that these be defined, and the OnceAndOnlyOnce
# principle is used here. This is the only place where these values
# are defined in the source distribution, and everything else that
# needs this should grab it from here.
__version__ = "2.0.0"
__author__ = "Rob McMullen"
__author_email__ = "robm@users.sourceforge.net"
__url__ = "http://pyemf.sourceforge.net"
__download_url__ = "http://sourceforge.net/project/showfiles.php?group_id=148144"
__description__ = "Pure Python Enhanced Metafile Library"
__keywords__ = "graphics, scalable, vector, image, clipart, emf"
__license__ = "LGPL"
# Reference: libemf.h
# and also wine: http://cvs.winehq.org/cvsweb/wine/include/wingdi.h
# Brush styles
BS_SOLID = 0
BS_NULL = 1
BS_HOLLOW = 1
BS_HATCHED = 2
BS_PATTERN = 3
BS_INDEXED = 4
BS_DIBPATTERN = 5
BS_DIBPATTERNPT = 6
BS_PATTERN8X8 = 7
BS_DIBPATTERN8X8 = 8
BS_MONOPATTERN = 9
# Hatch styles
HS_HORIZONTAL = 0
HS_VERTICAL = 1
HS_FDIAGONAL = 2
HS_BDIAGONAL = 3
HS_CROSS = 4
HS_DIAGCROSS = 5
# mapping modes
MM_TEXT = 1
MM_LOMETRIC = 2
MM_HIMETRIC = 3
MM_LOENGLISH = 4
MM_HIENGLISH = 5
MM_TWIPS = 6
MM_ISOTROPIC = 7
MM_ANISOTROPIC = 8
MM_MAX = MM_ANISOTROPIC
# background modes
TRANSPARENT = 1
OPAQUE = 2
BKMODE_LAST = 2
# polyfill modes
ALTERNATE = 1
WINDING = 2
POLYFILL_LAST = 2
# line styles and options
PS_SOLID = 0x00000000
PS_DASH = 0x00000001
PS_DOT = 0x00000002
PS_DASHDOT = 0x00000003
PS_DASHDOTDOT = 0x00000004
PS_NULL = 0x00000005
PS_INSIDEFRAME = 0x00000006
PS_USERSTYLE = 0x00000007
PS_ALTERNATE = 0x00000008
PS_STYLE_MASK = 0x0000000f
PS_ENDCAP_ROUND = 0x00000000
PS_ENDCAP_SQUARE = 0x00000100
PS_ENDCAP_FLAT = 0x00000200
PS_ENDCAP_MASK = 0x00000f00
PS_JOIN_ROUND = 0x00000000
PS_JOIN_BEVEL = 0x00001000
PS_JOIN_MITER = 0x00002000
PS_JOIN_MASK = 0x0000f000
PS_COSMETIC = 0x00000000
PS_GEOMETRIC = 0x00010000
PS_TYPE_MASK = 0x000f0000
# Stock GDI objects for GetStockObject()
WHITE_BRUSH = 0
LTGRAY_BRUSH = 1
GRAY_BRUSH = 2
DKGRAY_BRUSH = 3
BLACK_BRUSH = 4
NULL_BRUSH = 5
HOLLOW_BRUSH = 5
WHITE_PEN = 6
BLACK_PEN = 7
NULL_PEN = 8
OEM_FIXED_FONT = 10
ANSI_FIXED_FONT = 11
ANSI_VAR_FONT = 12
SYSTEM_FONT = 13
DEVICE_DEFAULT_FONT = 14
DEFAULT_PALETTE = 15
SYSTEM_FIXED_FONT = 16
DEFAULT_GUI_FONT = 17
STOCK_LAST = 17
# Text alignment
TA_NOUPDATECP = 0x00
TA_UPDATECP = 0x01
TA_LEFT = 0x00
TA_RIGHT = 0x02
TA_CENTER = 0x06
TA_TOP = 0x00
TA_BOTTOM = 0x08
TA_BASELINE = 0x18
TA_RTLREADING = 0x100
TA_MASK = TA_BASELINE+TA_CENTER+TA_UPDATECP+TA_RTLREADING
# lfWeight values
FW_DONTCARE = 0
FW_THIN = 100
FW_EXTRALIGHT = 200
FW_ULTRALIGHT = 200
FW_LIGHT = 300
FW_NORMAL = 400
FW_REGULAR = 400
FW_MEDIUM = 500
FW_SEMIBOLD = 600
FW_DEMIBOLD = 600
FW_BOLD = 700
FW_EXTRABOLD = 800
FW_ULTRABOLD = 800
FW_HEAVY = 900
FW_BLACK = 900
# lfCharSet values
ANSI_CHARSET = 0 # CP1252, ansi-0, iso8859-{1,15}
DEFAULT_CHARSET = 1
SYMBOL_CHARSET = 2
SHIFTJIS_CHARSET = 128 # CP932
HANGEUL_CHARSET = 129 # CP949, ksc5601.1987-0
HANGUL_CHARSET = HANGEUL_CHARSET
GB2312_CHARSET = 134 # CP936, gb2312.1980-0
CHINESEBIG5_CHARSET = 136 # CP950, big5.et-0
GREEK_CHARSET = 161 # CP1253
TURKISH_CHARSET = 162 # CP1254, -iso8859-9
HEBREW_CHARSET = 177 # CP1255, -iso8859-8
ARABIC_CHARSET = 178 # CP1256, -iso8859-6
BALTIC_CHARSET = 186 # CP1257, -iso8859-13
RUSSIAN_CHARSET = 204 # CP1251, -iso8859-5
EE_CHARSET = 238 # CP1250, -iso8859-2
EASTEUROPE_CHARSET = EE_CHARSET
THAI_CHARSET = 222 # CP874, iso8859-11, tis620
JOHAB_CHARSET = 130 # korean (johab) CP1361
MAC_CHARSET = 77
OEM_CHARSET = 255
VISCII_CHARSET = 240 # viscii1.1-1
TCVN_CHARSET = 241 # tcvn-0
KOI8_CHARSET = 242 # koi8-{r,u,ru}
ISO3_CHARSET = 243 # iso8859-3
ISO4_CHARSET = 244 # iso8859-4
ISO10_CHARSET = 245 # iso8859-10
CELTIC_CHARSET = 246 # iso8859-14
FS_LATIN1 = 0x00000001
FS_LATIN2 = 0x00000002
FS_CYRILLIC = 0x00000004
FS_GREEK = 0x00000008
FS_TURKISH = 0x00000010
FS_HEBREW = 0x00000020
FS_ARABIC = 0x00000040
FS_BALTIC = 0x00000080
FS_VIETNAMESE = 0x00000100
FS_THAI = 0x00010000
FS_JISJAPAN = 0x00020000
FS_CHINESESIMP = 0x00040000
FS_WANSUNG = 0x00080000
FS_CHINESETRAD = 0x00100000
FS_JOHAB = 0x00200000
FS_SYMBOL = 0x80000000
# lfOutPrecision values
OUT_DEFAULT_PRECIS = 0
OUT_STRING_PRECIS = 1
OUT_CHARACTER_PRECIS = 2
OUT_STROKE_PRECIS = 3
OUT_TT_PRECIS = 4
OUT_DEVICE_PRECIS = 5
OUT_RASTER_PRECIS = 6
OUT_TT_ONLY_PRECIS = 7
OUT_OUTLINE_PRECIS = 8
# lfClipPrecision values
CLIP_DEFAULT_PRECIS = 0x00
CLIP_CHARACTER_PRECIS = 0x01
CLIP_STROKE_PRECIS = 0x02
CLIP_MASK = 0x0F
CLIP_LH_ANGLES = 0x10
CLIP_TT_ALWAYS = 0x20
CLIP_EMBEDDED = 0x80
# lfQuality values
DEFAULT_QUALITY = 0
DRAFT_QUALITY = 1
PROOF_QUALITY = 2
NONANTIALIASED_QUALITY = 3
ANTIALIASED_QUALITY = 4
# lfPitchAndFamily pitch values
DEFAULT_PITCH = 0x00
FIXED_PITCH = 0x01
VARIABLE_PITCH = 0x02
MONO_FONT = 0x08
FF_DONTCARE = 0x00
FF_ROMAN = 0x10
FF_SWISS = 0x20
FF_MODERN = 0x30
FF_SCRIPT = 0x40
FF_DECORATIVE = 0x50
# Graphics Modes
GM_COMPATIBLE = 1
GM_ADVANCED = 2
GM_LAST = 2
# Arc direction modes
AD_COUNTERCLOCKWISE = 1
AD_CLOCKWISE = 2
# Clipping paths
RGN_ERROR = 0
RGN_AND = 1
RGN_OR = 2
RGN_XOR = 3
RGN_DIFF = 4
RGN_COPY = 5
RGN_MIN = RGN_AND
RGN_MAX = RGN_COPY
# Color management
ICM_OFF = 1
ICM_ON = 2
ICM_QUERY = 3
ICM_MIN = 1
ICM_MAX = 3
# World coordinate system transformation
MWT_IDENTITY = 1
MWT_LEFTMULTIPLY = 2
MWT_RIGHTMULTIPLY = 3
def _round4(num):
"""Round to the nearest multiple of 4 greater than or equal to the
given number. EMF records are required to be aligned to 4 byte
boundaries."""
return ((num+3)//4)*4
def RGB(r,g,b):
"""
Pack integer color values into a 32-bit integer format.
@param r: 0 - 255 or 0.0 - 1.0 specifying red
@param g: 0 - 255 or 0.0 - 1.0 specifying green
@param b: 0 - 255 or 0.0 - 1.0 specifying blue
@return: single integer that should be used when any function needs a color value
@rtype: int
@type r: int or float
@type g: int or float
@type b: int or float
"""
if isinstance(r,float):
r=int(255*r)
if r>255: r=255
elif r<0: r=0
if isinstance(g,float):
g=int(255*g)
if g>255: g=255
elif g<0: g=0
if isinstance(b,float):
b=int(255*b)
if b>255: b=255
elif b<0: b=0
return ((b<<16)|(g<<8)|r)
def _normalizeColor(c):
"""
Normalize the input into a packed integer. If the input is a tuple,
pass it through L{RGB} to generate the color value.
@param c: color
@type c: int or (r,g,b) tuple
@return: packed integer color from L{RGB}
@rtype: int
"""
if isinstance(c,int):
return c
if isinstance(c,tuple) or isinstance(c,list):
return RGB(*c)
raise TypeError("Color must be specified as packed integer or 3-tuple (r,g,b)")
# FIXME: do I need DPtoLP and LPtoDP?
class _DC:
"""Device Context state machine. This is used to simulate the
state of the GDI buffer so that some user commands can return
information. In a real GDI implementation, there'd be lots of
error checking done, but here we can't do a whole bunch because
we're outputting to a metafile. So, in general, we assume
success.
Here's Microsoft's explanation of units: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/cordspac_3qsz.asp
Window <=> Logical units <=> page space or user addressable
integer pixel units.
Viewport <=> Physical units <=> device units and are measured in actual
dimensions, like .01 mm units.
There are four coordinate spaces used by GDI: world, page, device,
and physical device. World and page are the same, unless a world
transform is used. These are addressed by integer pixels. Device
coordinates are referenced by physical dimensions corresponding to
the mapping mode currently used.
"""
def __init__(self,width='6.0',height='4.0',density='72',units='in'):
self.x=0
self.y=0
# list of objects that can be referenced by their index
# number, called "handle"
self.objects=[]
self.objects.append(None) # handle 0 is reserved
# Maintain a stack that contains list of empty slots in object
# list resulting from deletes
self.objectholes=[]
# Reference device size in logical units (pixels)
self.ref_pixelwidth=1024
self.ref_pixelheight=768
# Reference device size in mm
self.ref_width=320
self.ref_height=240
# physical dimensions are in .01 mm units
self.width=0
self.height=0
if units=='mm':
self.setPhysicalSize([[0,0],[int(width*100),int(height*100)]])
else:
self.setPhysicalSize([[0,0],[int(width*2540),int(height*2540)]])
# addressable pixel sizes
self.pixelwidth=0
self.pixelheight=0
self.setPixelSize([[0,0],[int(width*density),int(height*density)]])
#self.text_alignment = TA_BASELINE;
self.text_color = RGB(0,0,0);
#self.bk_mode = OPAQUE;
#self.polyfill_mode = ALTERNATE;
#self.map_mode = MM_TEXT;
# Viewport origin. A pixel drawn at (x,y) after the viewport
# origin has been set to (xv,yv) will be displayed at
# (x+xv,y+yv).
self.viewport_x=0
self.viewport_y=0
# Viewport extents. Should density be replaced by
# self.ref_pixelwidth/self.ref_width?
self.viewport_ext_x=self.width/100*density
self.viewport_ext_y=self.height/100*density
# Window origin. A pixel drawn at (x,y) after the window
# origin has been set to (xw,yw) will be displayed at
# (x-xw,y-yw).
# If both window and viewport origins are set, a pixel drawn
# at (x,y) will be displayed at (x-xw+xv,y-yw+yv)
self.window_x=0
self.window_y=0
# Window extents
self.window_ext_x=self.pixelwidth
self.window_ext_y=self.pixelheight
def getBounds(self,header):
"""Extract the dimensions from an _EMR._HEADER record."""
self.setPhysicalSize(header.rclFrame)
if header.szlMicrometers[0]>0:
self.ref_width=header.szlMicrometers[0]/10
self.ref_height=header.szlMicrometers[1]/10
else:
self.ref_width=header.szlMillimeters[0]*100
self.ref_height=header.szlMillimeters[1]*100
self.setPixelSize(header.rclBounds)
self.ref_pixelwidth=header.szlDevice[0]
self.ref_pixelheight=header.szlDevice[1]
def setPhysicalSize(self,points):
"""Set the physical (i.e. stuff you could measure with a
meterstick) dimensions."""
left=points[0][0]
top=points[0][1]
right=points[1][0]
bottom=points[1][1]
self.width=right-left
self.height=bottom-top
self.frame_left=left
self.frame_top=top
self.frame_right=right
self.frame_bottom=bottom
def setPixelSize(self,points):
"""Set the pixel-addressable dimensions."""
left=points[0][0]
top=points[0][1]
right=points[1][0]
bottom=points[1][1]
self.pixelwidth=right-left
self.pixelheight=bottom-top
self.bounds_left=left
self.bounds_top=top
self.bounds_right=right
self.bounds_bottom=bottom
def addObject(self,emr,handle=-1):
"""Add an object to the handle list, so it can be retrieved
later or deleted."""
count=len(self.objects)
if handle>0:
# print "Adding handle %s (%s)" % (handle,emr.__class__.__name__.lstrip('_'))
if handle>=count:
self.objects+=[None]*(handle-count+1)
self.objects[handle]=emr
elif self.objectholes:
handle=self.objectholes.pop()
self.objects[handle]=emr
else:
handle=count
self.objects.append(emr)
return handle
def removeObject(self,handle):
"""Remove an object by its handle. Handles can be reused, and
are reused from lowest available handle number."""
if handle<1 or handle>=len(self.objects):
raise IndexError("Invalid handle")
# print "removing handle %d (%s)" % (handle,self.objects[handle].__class__.__name__.lstrip('_'))
self.objects[handle]=None
found=False
# insert handle in objectholes list, but keep object holes
# list in sorted order
i=0
while i<len(self.objectholes):
if handle<self.objectholes[i]:
self.objectholes.insert(i,handle)
break
i+=1
else:
self.objectholes.append(handle)
# print self.objectholes
def popObject(self):
"""Remove last object. Used mainly in case of error."""
self.objects.pop()
##### - Field, Record, and related classes: a way to represent data
##### more advanced than using just import struct
# A structrecord class for EMF strings
class Field(object):
def __init__(self,fmt,size=1,num=1,offset=None):
# Format string, if applicable
self.fmt=fmt
# Size of record, in bytes
self.size=size
# Number of records. Could be an integer OR a text string
# that will be interpreted as a key in the object. That key
# will be referenced at unpack time to determine the number of
# records
self.num=num
# Relative offset to start of record, if supplied
self.offset=offset
self.debug=False
def getNumBytes(self,obj=None):
size=self.size*self.getNum(obj)
#if debug: print "size=%d" % size
return size
def calcNumBytes(self,obj,name):
if isinstance(obj.values[name],list) or isinstance(obj.values[name],tuple):
size=self.size*len(obj.values[name])
if self.debug: print(" calcNumBytes: size=%d len(obj.values[%s])=%d total=%d" % (self.size,name,len(obj.values[name]),size))
# also update the linked number, if applicable
else:
size=self.size*self.getNum(obj)
return size
# Get number of elements of this object (i.e. number of chars in a
# string, number of items in a list, etc.)
def getNum(self,obj=None):
num=0
if isinstance(self.num,int):
num=self.num
elif obj:
num=getattr(obj,self.num) # find obj."num"
#if debug: print "getting number for obj=%s, self.num=%s => num=%d" % (obj.__class__.__name__,self.num,num)
return num
def hasNumReference(self):
# If this format uses a reference to get the number, return
# that reference name
if isinstance(self.num,str):
return self.num
return False
def calcNum(self,obj,name):
if isinstance(obj.values[name],list) or isinstance(obj.values[name],tuple):
num=len(obj.values[name])
##if debug: print "calcNumBytes: size=%d num=%d" % (size,len(obj.values[name]))
# also update the linked number, if applicable
else:
num=self.getNum(obj)
return num
def getOffset(self,obj):
if self.offset==None: return None
offset=0
if isinstance(self.offset,int):
offset+=self.offset
elif obj:
offset+=getattr(obj,self.offset) # find obj."offset"
if self.debug: print("getting offset for obj=%s, self.offset=%s => offset=%d" % (obj.__class__.__name__,self.offset,offset))
return offset
def hasOffsetReference(self):
# If this format uses a reference to get the offset, return
# that reference name
if (self.offset,str):
return self.offset
return False
def unpack(self,obj,name,data,ptr):
raise NotImplementedError()
def pack(self,obj,name,value):
raise NotImplementedError()
def getDefault(self):
return None
def setDefault(self):
pass
def getString(self,name,val):
return val
class StructFormat(Field):
def __init__(self,fmt):
Field.__init__(self,fmt,struct.calcsize(fmt))
def unpack(self,obj,name,data,ptr):
value=struct.unpack(self.fmt,data[ptr:ptr+self.size])[0]
return (value,self.size)
def pack(self,obj,name,value):
return struct.pack(self.fmt,value)
def str_color(self,val):
return "red=0x%02x green=0x%02x blue=0x%02x" % ((val&0xff),((val&0xff00)>>8),((val&0xff0000)>>16))
def getString(self,name,val):
if name.endswith("olor"):
val=self.str_color(val)
elif self.fmt.endswith("s"):
val=val.decode('utf-16le')
return val
class String(Field):
def __init__(self,default=None,size=1,num=1,offset=None):
# Note the two bytes per unicode char
Field.__init__(self,None,size=size,num=num,offset=offset)
self.setDefault(default)
def calcNumBytes(self,obj,name):
if self.hasNumReference():
# If this is a dynamic string, calculate the size required
txt=obj.values[name]
if self.size==2:
# it's unicode, so get the number of actual bytes required
# to store it
txt=txt.encode('utf-16')
# EMF requires that strings be stored as multiples of 4 bytes
return len(txt)
else:
# this is a fixed length string, so we know the length already.
return Field.calcNumBytes(self,obj,name)
def calcNum(self,obj,name):
if self.hasNumReference():
return len(obj.values[name])
else:
return Field.calcNumBytes(self,obj,name)
def unpack(self,obj,name,data,ptr):
offset=self.getOffset(obj)
if offset==None:
pass
elif offset>0:
ptr=offset
else:
return ('',0)
size=self.getNumBytes(obj)
txt=data[ptr:ptr+size]
if self.size==2:
txt=txt.decode('utf-16') # Now is a unicode string
if self.debug:
try:
print("str: '%s'" % str(txt))
except UnicodeEncodeError:
print("<<<BAD UNICODE STRING>>>: '%s'" % repr(txt))
return (txt,size)
def pack(self,obj,name,value):
txt=value
if self.size==2:
txt=txt.encode('utf-16')
maxlen=self.getNumBytes(obj)
if len(txt)>maxlen:
txt=txt[0:maxlen]
else:
txt+='\0'*(maxlen-len(txt))
return txt
def getDefault(self):
# FIXME: need to take account of number
return self.default
def setDefault(self,default):
if default is None:
if self.size==2:
default=u''
else:
default=''
self.default=default
class CString(String):
def __init__(self,default=None,num=1,offset=None):
String.__init__(self,None,size=1,num=num,offset=offset)
def unpack(self,obj,name,data,ptr):
(txt,size)=String.unpack(self,obj,name,data,ptr)
i=0
while i<size:
if txt[i]=='\0': break
i+=1
return (txt[0:i],i)
class List(Field):
def __init__(self,default=None,num=1,fmt='i',offset=None):
Field.__init__(self,fmt,struct.calcsize(fmt),num,offset=offset)
self.setDefault(default)
def unpack(self,obj,name,data,ptr):
values=[]
offset=self.getOffset(obj)
if offset==None:
pass
elif offset>0:
ptr=offset
else:
return (values,0)
num=self.getNum(obj)
while num>0:
values.append(struct.unpack(self.fmt,data[ptr:ptr+self.size])[0])
ptr+=self.size
num-=1
return (values,self.getNumBytes(obj))
def pack(self,obj,name,value):
fh=BytesIO()
size=0
for val in value:
fh.write(struct.pack(self.fmt,val))
return fh.getvalue()
def getDefault(self):
return self.default
def setDefault(self,default):
if default is not None:
default=[0]*self.getNum()
self.default=default
class Tuples(Field):
def __init__(self,default=None,rank=2,num=1,fmt='i',offset=None):
if fmt[0] in "<>@!=":
fmt=fmt[0]+fmt[1]*rank
else:
fmt=fmt*rank
Field.__init__(self,fmt,struct.calcsize(fmt),num,offset=offset)
if self.debug: print("Tuples:%s self.size=%d" % (self.__class__.__name__,self.size))
self.rank=rank
self.setDefault(default)
# always create a list of lists