File: image.py

package info (click to toggle)
pythoncad 0.1.23-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,044 kB
  • ctags: 3,568
  • sloc: python: 54,867; sh: 100; makefile: 39
file content (2194 lines) | stat: -rw-r--r-- 82,270 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
#
# Copyright (c) 2002, 2003, 2004, 2005 Art Haas
#
# This file is part of PythonCAD.
#
# PythonCAD is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PythonCAD is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PythonCAD; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#
# The class for a drawing
#

import sys
import math

from PythonCAD.Generic import globals
from PythonCAD.Generic import layer
from PythonCAD.Generic import graphicobject
from PythonCAD.Generic import point
from PythonCAD.Generic import style
from PythonCAD.Generic import linetype
from PythonCAD.Generic import tolerance
from PythonCAD.Generic import intersections
from PythonCAD.Generic import dimension
from PythonCAD.Generic import color
from PythonCAD.Generic import text
from PythonCAD.Generic import units
from PythonCAD.Generic import options
from PythonCAD.Generic import baseobject
from PythonCAD.Generic import entity
from PythonCAD.Generic import logger
from PythonCAD.Generic import util

class Image(entity.Entity):
    """The class representing a CAD drawing.

This class contains all the interface-neutral parts of
a drawing. An image is essentially a collection of Layer
objects, plus the bits needed to store the colors, linetypes,
and styles used in a drawing.

Each instance has several attributes:

active_layer: The currently active Layer
top_layer: The initial Layer in the Image
scale: The scale factor of the Image

The following methods are available for each instance:

{get/set}Scale(): Get/Set the current scale factor.
hasColor(): See if a color is already in use in the drawing.
addColor(): Add a Color to the set available for objects in the drawing.
hasLinetype(): See if a Linetype is found in the drawing.
addLinetype(): Add a Linetype to the set available for objects in the drawing.
hasStyle(): See if a Style is in the drawing.
addStyle(): Add a Style to the set available for objects in the drawing.
{get/set}ActiveLayer(): Get/Set the currently active Layer.
addChildLayer(): Make one Layer object a child of another.
addLayer(): Make one Layer object a child of the active Layer's parent.
delLayer(): Remove a Layer from the image.
hasPoint(): Find a Point object in the drawing.
findPoint(): Find a Point object in the drawing.
mapPoint(): Find objects in the drawing where at some location.
addObject(): Add an object to the drawing.
delObject(): Delete an object from the drawing.
getObject(): Return an object with a specific entity ID
selectObject(): Store a references to an object in the drawing.
deselectObject(): Release a reference to a stored object.
getSelectedObjects(): Retrieve all the selected objects.
clearSelectedObjets(): Release all references to selected objects.
hasSelection(): Return whether the image has an active selection.
getExtents(): Find the size of the drawing.
{get/set}Option(): Retrieve/Store an option used in the drawing.
{get/set}Filename(): Get/Set the filename for this image.
getImageEntities(): Get all the instances of certain image-wide object.
{get/set}Units(): Get/Set the basic length unit in the image.
scaleLength(): Return a linear distance in millimeters.
    """

    messages = {
    'scale_changed' : True,
    'units_changed' : True,
    'added_object' : True,
    'deleted_object' : True,
    'added_layer' : True,
    'deleted_layer' : True
    }
    def __init__(self, **kw):
        """Instatiate a Image object.

Image()

There are no parameters used to create the object.
        """
        super(Image, self).__init__(**kw)
        _top = layer.Layer(u'TopLayer')
        _top.setParent(self)
        self.__top_layer = _top
        self.__active_layer = _top
        _top.connect('modified', self._objectModified)
        _top.connect('added_child', self._layerAddedChild)
        _top.connect('removed_child', self._layerRemovedChild)
        _top.connect('name_changed', self._layerNameChanged)
        _log = layer.LayerLog(_top)
        _top.setLog(_log)
        self.__scale = 1.0
        self.__styles = []
        self.__dimstyles = []
        self.__textstyles = []
        self.__linetypes = []
        self.__colors = baseobject.TypedDict(keytype=color.Color)
        self.__units = units.Unit(units.MILLIMETERS)
        self.__options = baseobject.TypedDict(keytype=str) # miscellaneous options
        self.__fonts = baseobject.TypedDict(keytype=str) # font names
        self.__selected = {}
        self.__filename = None
        self.__vars = {}
        self.__busy = False
        self.__undo = []
        self.__redo = []
        self.__delhist = {}
        self.__logs = {}
        self.__action = 0L
        add_defaults(self)
        self.connect('modified', self._objectModified)
        self.__vars['image'] = self

    def __contains__(self, obj):
        """Define if an object is in the Drawing.

Defining this method allows the use of 'in' type test.
        """
        _res = False
        if isinstance(obj, style.Style):
            _res = obj in self.__styles
        elif isinstance(obj, linetype.Linetype):
            _res = obj in self.__linetypes
        elif isinstance(obj, color.Color):
            _res = obj in self.__colors
        elif isinstance(obj, dimension.DimStyle):
            _res = obj in self.__dimstyles
        elif isinstance(obj, text.TextStyle):
            _res = obj in self.__textstyles
        else:
            _layers = [self.__top_layer]
            while (len(_layers)):
                _layer = _layers.pop()
                _res = obj in _layer
                if _res:
                    break
                _layers.extend(_layer.getSublayers())
        return _res

    def close(self):
        """Release all the entities stored in the drawing

close()
        """
        print "in image::close()"
        self.__vars.clear()
        del self.__styles[:]
        self.__colors.clear()
        del self.__linetypes[:]
        del self.__dimstyles[:]
        del self.__textstyles[:]
        self.__options.clear()
        self.__fonts.clear()
        _layers = []
        _sublayers = [self.__top_layer]
        while len(_sublayers):
            _layer = _sublayers.pop()
            _layers.append(_layer)
            _sublayers.extend(_layer.getSublayers())
        _layers.reverse()
        for _layer in _layers:
            print "closing layer " + _layer.getName()
            _layer.clear()
            _layer.setParent(None)
            _layer.setParentLayer(None)

    def addChildLayer(self, l, p=None):
        """Add a child Layer of the active Layer.

addChildLayer(l [, p])

There is a one required argument:

l: The child Layer

There is one optional argument:

p: The new parent Layer of the child

The default parent is the currently active layer.

The child layer cannot be a layer found when moving
up from the new parent layer to the topmost layer.
        """
        _child = l
        if not isinstance(_child, layer.Layer):
            raise TypeError, "Unexpected type for layer: " + `type(_child)`
        _pl = p
        if _pl is None:
            _pl = self.__active_layer
        if not isinstance(_pl, layer.Layer):
            raise TypeError, "Unexpected type for parent layer: " + `type(_pl)`
        if _pl.getParent() is not self:
            raise ValueError, "Parent layer not in Image."
        if _child is _pl:
            raise ValueError, "Child and parent layers identical."
        _layer = _pl
        _tpl = _pl.getParentLayer()
        while _tpl is not None:
            _layer = _tpl
            if _tpl is _child:
                raise ValueError, "Child layer found in parent chain"
            _tpl = _tpl.getParentLayer()
        if _layer is not self.__top_layer:
            raise ValueError, "Parent layer not found in drawing"
        if not self.inUndo():
            self.ignore('modified')
        try:
            _child.setParentLayer(_pl)
        finally:
            if not self.inUndo():
                self.receive('modified')
        _parent = _child.getParent()
        if _parent is not self:
            _child.setParent(self)
        #
        # restore the Layer log if possible
        #
        _cid = _child.getID()
        _log = _child.getLog()
        if _log is None:
            _log = layer.LayerLog(_child)
            _child.setLog(_log)
        _oldlog = self.__logs.get(_cid)
        if _oldlog is not None: # re-attach old log
            _log.transferData(_oldlog)
            del self.__logs[_cid]
        #
        # re-add deleted entity history
        #
        _data = self.__delhist.get(_cid)
        if _data is not None:
            _child.setDeletedEntityData(_data)
            del self.__delhist[_cid]
        _child.connect('modified', self._objectModified)
        _child.connect('added_child', self._layerAddedChild)
        _child.connect('removed_child', self._layerRemovedChild)
        _child.connect('name_changed', self._layerNameChanged)
        self.__active_layer = _child
        self.sendMessage('added_layer', _layer, _pl)

    def addLayer(self, l):
        """Add a new Layer as a child of the active Layer's parent.

addLayer(l)

If the active layer is the topmost Layer in the drawing, the Layer
is added as a child Layer to that Layer. Otherwise, the new layer
is added and is a sibling to the active Layer.
        """
        _layer = l
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer type: " + `type(_layer)`
        _pl = self.__active_layer.getParentLayer()
        if _pl is None:
            _pl = self.__top_layer
        self.addChildLayer(l, _pl)

    def old_addLayer(self, l):
        """Add a new Layer as a child of the active Layer's parent.

addLayer(l)

If the active layer is the topmost Layer in the drawing, the Layer
is added as a child Layer to that Layer. Otherwise, the new layer
is added and is a sibling to the active Layer.
        """
        _layer = l
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer type: " + `type(_layer)`
        _pl = self.__active_layer.getParentLayer()
        if _pl is None:
            _pl = self.__top_layer
        if _layer is _pl:
            raise ValueError, "Child and parent layers identical."
        _lp = _layer.getParentLayer()
        if _lp is not None: # see if layer already in drawing ...
            _l = _pl
            _pl = _l.getParentLayer()
            while _pl is not None:
                if _layer is _pl:
                    raise ValueError, "Layer found in parent chain."
                _l = _pl
        self.ignore('modified')
        try:
            _layer.setParentLayer(_pl)
        finally:
            self.receive('modified')
        _parent = _layer.getParent()
        if _parent is not self:
            _layer.setParent(self)
        self.__active_layer = _layer
        _log = _layer.getLog()
        if _log is None:
            _log = layer.LayerLog(_layer)
            _layer.setLog(_log)
        _layer.connect('modified', self._objectModified)
        _layer.connect('added_child', self._layerAddedChild)
        _layer.connect('removed_child', self._layerRemovedChild)
        _layer.connect('name_changed', self._layerNameChanged)
        self.sendMessage('added_layer', _layer, _pl)

    def delLayer(self, l):
        """Remove a Layer from the drawing.

delLayer(l)

A Layer object cannot be removed until its children are
either deleted or moved to another Layer.

The topmost Layer in a drawing cannot be deleted.
        """
        _layer = l
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer type: " + `type(_layer)`
        _l = _layer
        _pl = _l.getParentLayer()
        while _pl is not None:
            _l = _pl
            _pl = _pl.getParentLayer()
        if _l is not self.__top_layer:
            raise ValueError, "Layer not found in drawing: " + `_layer`
        if _layer.getParent() is not self:
            raise ValueError, "Image/Layer parent inconsistency"
        _pl = _layer.getParentLayer()
        if _pl is not None:
            # print "ParentLayer is not None"
            if not _pl.hasSublayers():
                raise ValueError, "Layer not in parent sublayer: " + `_layer`
            if _layer not in _pl.getSublayers():
                raise ValueError, "Layer not in parent sublayers: " + `_layer`
            if not _layer.hasSublayers():
                # print "deleting layer ..."
                _lid = _layer.getID()
                _data = _layer.getDeletedEntityData()
                #
                # save the layer info so it can be reattched if
                # the layer deletion is undone
                #
                if len(_data):
                    # print "has DeletedEntityData()"
                    self.__delhist[_lid] = _data
                _log = _layer.getLog()
                if _log is not None:
                    # print "Saving log file ..."
                    _log.detatch()
                    self.__logs[_lid] = _log
                    _layer.setLog(None)
                #
                # print "Setting ParentLayer and Parent to None"
                _layer.disconnect(self)
                #
                # call setParent() before setParentLayer() so
                # the Layer's getValues() calls will have
                # the parent layer information
                #
                _layer.setParent(None)
                if not self.inUndo():
                    self.ignore('modified')
                try:
                    _layer.setParentLayer(None)
                finally:
                    if not self.inUndo():
                        self.receive('modified')
                self.sendMessage('deleted_layer', _layer, _pl)

    def hasLayer(self, l):
        """Return whether or not a layer is in a drawing.

hasLayer(l)
        """
        _layer = l
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer type : " + `type(_layer)`
        _flag = False
        _l = _layer
        _p = _l.getParentLayer()
        while _p is not None:
            _l = _p
            _p = _p.getParentLayer()
        if _l is self.__top_layer:
            _flag = True
        _image = _layer.getParent()
        if ((_image is self and _flag is False) or
            (_image is not self and _flag is True)):
            raise ValueError, "Image/Layer parent inconsistency"
        return _flag

    def getActiveLayer(self):
        """Return the active Layer in the drawing.

getActiveLayer()

The active Layer is the Layer to which any new objects will
be stored.
        """
        return self.__active_layer

    def setActiveLayer(self, l=None):
        """Set the active Layer in the Image.

setActiveLayer(l)

The the Layer 'l' to be the active Layer in the drawing. If
the function is called without arguments, the topmost Layer
in the drawing is set to the active layer.
        """
        _layer = l
        if _layer is None:
            _layer = self.__top_layer
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer type: " + `type(_layer)`
        if _layer is not self.__top_layer:
            _l = _layer
            _p = _l.getParentLayer()
            while _p is not None:
                _l = _p
                _p = _p.getParentLayer()
            if _l is not self.__top_layer:
                raise ValueError, "Layer not found in image: " + `_layer`
            _parent = _layer.getParentLayer()
            if not _parent.hasSublayers():
                raise ValueError, "Layer not in parent sublayer: " + `_layer`
            if _layer not in _parent.getSublayers():
                raise ValueError, "Layer not in parent sublayers: " + `_layer`
            if _layer.getParent() is not self:
                raise ValueError, "Image/Layer parent inconsistency"
        self.__active_layer = _layer

    active_layer = property(getActiveLayer, setActiveLayer,
                            None, "Image active Layer object.")

    def getTopLayer(self):
        """Return the top Layer of the image

getTopLayer()
        """
        return self.__top_layer

    top_layer = property(getTopLayer, None, None, "Image top Layer.")

    def getScale(self):
        """Return the image's scale factor.

getScale()
        """
        return self.__scale

    def setScale(self, scale):
        """Set the image's scale factor.

setScale(scale)

The scale must be a float greater than 0.
        """
        _s = util.get_float(scale)
        if _s < 1e-10:
            raise ValueError, "Invalid scale factor: %g" % _s
        _os = self.__scale
        if abs(_os - _s) > 1e-10:
            self.__scale = _s
            self.sendMessage('scale_changed', _os)
            self.modified()

    scale = property(getScale, setScale, None, "Image scale factor.")

    def canParent(self, obj):
        """Test if an Entity can be the parent of another Entity.

canParent(obj)

This method overrides the Entity::canParent() method. An Image can
be the parent of Layer entities only.
        """
        return isinstance(obj, layer.Layer)

    def getImageEntities(self, entity):
        """Return all the entities of a particular type

getImageEntities(entity)

The argument 'entity' should be one of the following:
color, linetype, style, font, dimstyle, or textstyle
        """
        if entity == "color":
            _objs = self.__colors.keys()
        elif entity == "linetype":
            _objs = self.__linetypes[:]
        elif entity == "style":
            _objs = self.__styles[:]
        elif entity == "font":
            _objs = self.__fonts.keys()
        elif entity == "dimstyle":
            _objs = self.__dimstyles[:]
        elif entity == "textstyle":
            _objs = self.__textstyles[:]
        else:
            raise ValueError, "Invalid image entity: " + `entity`
        return _objs

    def addColor(self, c):
        """Add a Color object to the drawing.

addColor(c)
        """
        if not isinstance(c, color.Color):
            raise TypeError, "Invalid Color type: " + `type(c)`
        if c not in self.__colors:
            self.__colors[c] = True # maybe count entities ?

    def hasColor(self, c):
        """Check if a Color already exists in the drawing.

hasColor(c)
        """
        _c = c
        if not isinstance(_c, color.Color):
            _c = color.Color(c)
        return _c in self.__colors

    def getColor(self, c):
        """Return an instance of a Color.

getColor(c)
        """
        _c = c
        if not isinstance(_c, color.Color):
            _c = color.Color(c)
        return globals.colors.setdefault(_c, _c)

    def addLinetype(self, lt):
        """Add a Linetype to the drawing.

addLinetype(lt)
        """
        if not isinstance(lt, linetype.Linetype):
            raise TypeError, "Invalid Linetype type: " + `type(lt)`
        if lt not in self.__linetypes:
            self.__linetypes.append(lt)

    def hasLinetype(self, lt):
        """Check if a Linetype already exists in the drawing.

hasLinetype(lt)
        """
        if not isinstance(lt, linetype.Linetype):
            raise TypeError, "Invalid Linetype type: " + `type(lt)`
        return lt in self.__linetypes

    def getLinetype(self, lt):
        """Return an instance of a Linetype.

getLinetype(lt)
        """
        if not isinstance(lt, linetype.Linetype):
            raise TypeError, "Invalid Linetype type: " + `type(lt)`
        return globals.linetypes.setdefault(lt, lt)

    def addStyle(self, s):
        """Add a Style to the drawing.

addStyle(s)
        """
        if not isinstance(s, style.Style):
            raise TypeError, "Invalid Style type: " + `type(s)`
        if s not in self.__styles:
            _col = s.getColor()
            if _col not in self.__colors:
                self.__colors[_col] = True
            _lt = s.getLinetype()
            if _lt not in self.__linetypes:
                self.__linetypes.append(_lt)
            self.__styles.append(s)

    def hasStyle(self, s):
        """Check if a Style already exists within the drawing.

hasStyle(s)
        """
        _s = s
        if not isinstance(_s, style.Style):
            _s = style.Style(s)
        return _s in self.__styles

    def addDimStyle(self, ds):
        """Add a DimStyle to the drawing

addDimStyle(ds)
        """
        if not isinstance(ds, dimension.DimStyle):
            raise TypeError, "Invalid DimStyle type: " + `type(ds)`
        if ds not in self.__dimstyles:
            _col = ds.getValue('DIM_COLOR')
            if _col is not None and _col not in self.__colors:
                self.__colors[_col] = True
            _col = ds.getValue('DIM_PRIMARY_FONT_COLOR')
            if _col is not None and _col not in self.__colors:
                self.__colors[_col] = True
            _col = ds.getValue('DIM_SECONDARY_FONT_COLOR')
            if _col is not None and _col not in self.__colors:
                self.__colors[_col] = True
            _family = ds.getValue('DIM_PRIMARY_FONT_FAMILY')
            if _family is not None and _family not in self.__fonts:
                self.__fonts[_family] = 1
            _family = ds.getValue('DIM_SECONDARY_FONT_FAMILY')
            if _family is not None and _family not in self.__fonts:
                self.__fonts[_family] = 1
            self.__dimstyles.append(ds)

    def hasDimStyle(self, ds):
        """Check if a DimStyle already exists within the drawing.

hasDimStyle(ds)
        """
        if not isinstance(ds, dimension.DimStyle):
            raise TypeError, "Invalid DimStyle type: " + `type(ds)`
        return ds in self.__dimstyles

    def getDimStyle(self, name=None, dsdict=None):
        if name is not None:
            for _ds in globals.dimstyles:
                if _ds.getName() == name:
                    return _ds
        elif dsdict is None:
            pass
        return None

    def addTextStyle(self, ts):
        """Add a TextStyle to the drawing.

addTextStyle(ts)
        """
        # print "Image::addTextStyle() ..."
        if not isinstance(ts, text.TextStyle):
            raise TypeError, "Invalid TextStyle type: " + `type(ts)`
        if ts not in self.__textstyles:
            # print "adding TextStyle: %s" % ts.getName()
            _color = ts.getColor()
            if _color not in self.__colors:
                self.__colors[_color] = True
            _family = ts.getFamily()
            if _family in self.__fonts:
                self.__fonts[_family] = 1
            self.__textstyles.append(ts)

    def hasTextStyle(self, ts):
        """Return whether or not a TextStyle is already in an image.

hasTextStyle(ts)
        """
        if not isinstance(ts, text.TextStyle):
            raise TypeError, "Invalid TextStyle: " + str(ts)
        return ts in self.__textstyles

    def addFont(self, family):
        """Store the usage of a font in the image.

addFont(family)

Invoking this method does not set the current text font to
the value used in this function. That must be done with setOption().
        """
        if not isinstance(family, str):
            raise TypeError, "Invalid font family name: " + `family`
        self.__fonts[family] = 1

    def getUnits(self):
        """Return the currently selected unit.

getUnits()
        """
        return self.__units.getUnit()

    def setUnits(self, unit):
        """Set the basic unit for the image.

setUnits(unit)

The available choices for the units are defined in the units.py file.
        """
        _ou = self.__units.getUnit()
        self.__units.setUnit(unit)
        if unit != _ou:
            self.sendMessage('units_changed', _ou)
            self.modified()

    units = property(getUnits, setUnits, None,
                     "Linear dimensional units for the image.")

    def scaleLength(self, l):
        """Convert some distance to a value in millimeters.

scaleLength(l)

The argument 'l' should be a float equal or greater than 0.0.
        """
        _l = util.get_float(l)
        if _l < 0.0:
            raise ValueError, "Invalid scaling length: %g" % _l
        return self.__units.toMillimeters(_l)

    def findPoint(self, x, y, tol=tolerance.TOL):
        """Return a Point object found at the x-y coordinates.

findPoint(self, x, y [,tol])

The function has two required arguments

x: A float representing the x-coordinate
y: A float representing the y-coordinate

The optional argument 'tol' gives a distance between the
existing objects and the 'x' and 'y' arguments. The default
value is 1e-10.

This method returns a tuple of two objects, the first
object is a Point object, and the second object is a
boolean True/False value indicating if the point is an
exisiting point in the active layer or a newly created
point.

If there were no Point objects found within the tolerance
supplied, the Point object in the tuple is None.
        """
        _x = util.get_float(x)
        _y = util.get_float(y)
        _t = tolerance.toltest(tol)
        _test_point = point.Point(_x, _y)
        _new_pt = False
        _active_layer = self.__active_layer
        _pt = _active_layer.find('point', _x, _y, _t)
        if _pt is None:
            _objs = []
            _ptmap = {}
            _layers = [self.__top_layer]
            while len(_layers):
                _layer = _layers.pop()
                if _layer is not _active_layer:
                    _lp = _layer.find('point', _x, _y, _t)
                    if _lp is not None:
                        _pt = _lp.clone()
                        _new_pt = True
                        break
                _stop = False
                for _obj, _map_pt in _layer.mapPoint(_test_point, _t, None):
                    if isinstance(_obj, dimension.Dimension):
                        continue
                    if len(_objs):
                        for _tobj in _objs:
                            _ints = intersections.find_intersections(_tobj, _obj)
                            _count = len(_ints)
                            if _count == 1:
                                _stop = True
                                _x, _y = _ints[0]
                                _pt = point.Point(_x, _y)
                                _new_pt = True
                                break
                            elif _count == 2:
                                _stop = True
                                _tx, _ty = _test_point.getCoords()
                                _x1, _y1 = _ints[0]
                                _d1 = math.hypot((_tx - _x1), (_ty - _y1))
                                _x2, _y2 = _ints[1]
                                _d2 = math.hypot((_tx - _x2), (_ty - _y2))
                                if _d1 < _d2:
                                    _pt = point.Point(_x1, _y1)
                                else:
                                    _pt = point.Point(_x2, _y2)
                                _new_pt = True
                                break
                            else:
                                pass # this should handle _count > 2
                    _ptmap[_obj] = _map_pt
                    _objs.append(_obj)
                if _stop:
                    break
                _layers.extend(_layer.getSublayers())
            if _pt is None: # need to use one of the mapped points ...
                _min_sep = None
                _map_obj = None
                for _obj in _ptmap:
                    _sep = _ptmap[_obj] - _test_point
                    if _min_sep is None or _sep < _min_sep:
                        _map_obj = _obj
                if _map_obj is not None:
                    _pt = _ptmap[_map_obj]
                    _new_pt = True
        return _pt, _new_pt

    def hasPoint(self, x, y, tol=tolerance.TOL, map=True):
        """Return a Point object found at the x-y coordinates.

hasPoint(self, x, y [,tol, map])

The function has two required arguments

x: A float representing the x-coordinate
y: A float representing the y-coordinate

The optional argument 'tol' gives a distance between the
existing objects and the 'x' and 'y' arguments. The default
value is 1e-10.

The map argument is by default True. Passing the
argument as False will skip the attempt to place
an xy coordinate on objects.

The function returns a Point object - either an existing
Point in the currently active Layer, or a new Point based
on the location of a Point object in another layer. The
returned point can be stored in the active Layer.

If there were no Point objects found within the tolerance
supplied, the function returns None.
        """
        _x = util.get_float(x)
        _y = util.get_float(y)
        _t = tolerance.toltest(tol)
        _test_point = point.Point(_x,_y)
        util.test_booean(map)
        _active_layer = self.__active_layer
        _sp = _active_layer.find('point', _x, _y, _t)
        if _sp is None:
            _layers = [self.__top_layer]
            while (len(_layers)):
                _layer = _layers.pop()
                if _layer is not _active_layer:
                    _lp = _layer.find('point', _x, _y, _t)
                    if _lp is not None:
                        _sp = _lp.clone()
                        break
                _layers.extend(_layer.getSublayers())
        if _sp is None and map:
            _objdict = self.mapPoint(_x, _y, _t)
            _tuplist = []
            if len(_objdict):
                _count = len(_objdict)
                for _layer in _objdict:
                    _tuplist = _tuplist + _objdict[_layer]
                if len(_tuplist) == 1:
                    _sp = _tuplist[0][1]
                else:
                    _obj1 = _tuplist[0][0]
                    _obj2 = _tuplist[1][0]
                    _ints = intersections.find_intersections(_obj1, _obj2)
                    _count = len(_ints)
                    if _count == 0:
                        _sp = _tuplist[0][1] # arbitrary choice ...
                    elif _count == 1:
                        _x, _y = _ints[0]
                        _sp = point.Point(_x, _y)
                    elif _count == 2:
                        _tx, _ty = _test_point.getCoords()
                        _x1, _y1 = _ints[0]
                        _d1 = math.hypot((_tx - _x1), (_ty - _y1))
                        _x2, _y2 = _ints[1]
                        _d2 = math.hypot((_tx - _x2), (_ty - _y2))
                        if _d1 < _d2:
                            _sp = point.Point(_x1, _y1)
                        else:
                            _sp = point.Point(_x2, _y2)
                    else: # need to handle 3 or more intersection points
                        pass
        return _sp

    def mapPoint(self, x, y, tol, count=2):
        """Return a set of Layers with objects found at the (x,y) location

mapPoint(self, x, y, tol[, count])

This method has three required arguments:

x: A float representing the x-coordinate
y: A float representing the y-coordinate
tol: A positive float giving the maximum distance between the
     x and y coordinates and the projected points of the objects

There is a single optional argument:

count: The maximum number of objects to retrieve in any layer. The
       default value of objects is 2.

Setting 'count' to either None or a negative value will result
in the maximum number of objects as unlimited.

The function returns a dict object, with each key being
a Layer object where some objects were found, and the
value being a list of some tuples. Read the doc-string
info for the layer::mapPoint() method for details regarding
the tuple(s) in the list.

If any objects in the currently active layer are identified, no
other layers in the drawing will be examined.

If there were no objects found within the tolerance
supplied, the function returns an empty dict.
        """
        _x = util.get_float(x)
        _y = util.get_float(y)
        _t = tolerance.toltest(tol)
        _count = count
        if _count is None:
            _count = sys.maxint
        else:
            if not isinstance(_count, int):
                _count = int(count)
            if _count < 0: # What if _count == 0 ???
                _count = sys.maxint
        _tp = point.Point(_x, _y)
        _active_layer = self.__active_layer
        _objdict = {}
        _hits = _active_layer.mapPoint(_tp, _t, _count)
        if len(_hits):
            _objdict[_active_layer] = _hits
        else:
            _layers = [self.__top_layer]
            while len(_layers):
                _layer = _layers.pop()
                if _layer is not _active_layer:
                    _hits = _layer.mapPoint(_tp, _t, _count)
                    if len(_hits):
                        _objdict[_layer] = _hits
                _layers.extend(_layer.getSublayers())
        return _objdict

    def _objectModified(self, obj, *args):
        # print "Image::objectModified()"
        # print "obj: " + `obj`
        if obj.inUndo():
            raise RuntimeError, "Recieved 'modified' during undo: " + `obj`
        _oid = obj.getID()
        _pid = None
        _parent = obj.getParent()
        if _parent is None:
            if obj is not self:
                raise ValueError, "Invalid object without parent: " + `obj`
        else:
            _pid = _parent.getID()
            if _parent is self:
                if not isinstance(obj, layer.Layer):
                    raise ValueError, "Non-layer with Image as parent: " + `obj`
            else:
                _layer = None
                for _child in self.getChildren():
                    _cid = _child.getID()
                    if _cid == _pid:
                        _layer = _child
                        break
                if _layer is None:
                    raise ValueError, "Parent %d not in Image children: %s" % (_pid,  `_parent`)
                _lobj = _layer.getObject(_oid)
                if _lobj is not obj:
                    raise ValueError, "Object %d not found in Layer: %s" % (_oid, `obj`)
        _i = self.__action
        # print "i: %d" % _i
        _undo = self.__undo
        # print "len(self.__undo): %d" % len(_undo)
        if len(_undo) == _i:
            _undo.insert(_i, [(_pid, _oid)])
        else:
            _undo[_i].append((_pid, _oid))
        if not self.__busy:
            self.__action = _i + 1

    def _layerAddedChild(self, l, *args):
        # print "Image::layerAddedChild() ..."
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _obj = args[0]
        # print "obj: " + `_obj`
        _obj.connect('modified', self._objectModified)
        if isinstance(_obj, graphicobject.GraphicObject):
            self.addStyle(_obj.getStyle())
            self.addLinetype(_obj.getLinetype())
            self.addColor(_obj.getColor())
            _obj.connect('style_changed', self._styleChanged)
            _obj.connect('color_changed', self._colorChanged)
            _obj.connect('linetype_changed', self._linetypeChanged)
        if isinstance(_obj, text.TextBlock):
            self.addColor(_obj.getColor())
            self.addTextStyle(_obj.getTextStyle())
            _obj.connect('font_color_changed', self._colorChanged)
            _obj.connect('textstyle_changed', self._textstyleChanged)
        if isinstance(_obj, dimension.Dimension):
            self.addDimStyle(_obj.getDimStyle())
            self.addColor(_obj.getColor())
            _obj.connect('dimstyle_changed', self._dimstyleChanged)
            _obj.connect('color_changed', self._colorChanged)
            _ds1, _ds2 = _obj.getDimstrings()
            self.addColor(_ds1.getColor())
            self.addTextStyle(_ds1.getTextStyle())
            _ds1.connect('font_color_changed', self._colorChanged)
            _ds1.connect('textstyle_changed', self._textstyleChanged)
            self.addColor(_ds2.getColor())
            self.addTextStyle(_ds2.getTextStyle())
            _ds2.connect('font_color_changed', self._colorChanged)
            _ds2.connect('textstyle_changed', self._textstyleChanged)
        self.sendMessage('added_object', l, _obj)

    def _layerRemovedChild(self, l, *args):
        # print "Image::layerRemovedChild() ..."
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _obj = args[0]
        _obj.disconnect(self)
        if isinstance(_obj, dimension.Dimension):
            _ds1, _ds2 = _obj.getDimstrings()
            _ds1.disconnect(self)
            _ds2.disconnect(self)
        self.sendMessage('deleted_object', l, _obj)

    def _layerNameChanged(self, l, *args):
        #
        # fixme - this method is a hackish way to have the
        # layer name updated in the GTK layer model - it
        # will go away when the interface learns about messages
        #
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        if l.getParent() is not self:
            raise ValueError, "Image/Layer parent inconsistency"
        self.renameLayer(l) # defined in gtkimage.py

    def renameLayer(self, l):
        pass

    def _styleChanged(self, obj, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        self.addStyle(obj.getStyle())

    def _colorChanged(self, obj, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        self.addColor(obj.getColor())

    def _linetypeChanged(self, obj, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        self.addLinetype(obj.getLinetype())

    def _textstyleChanged(self, obj, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        self.addTextStyle(obj.getTextstyle())

    def _dimstyleChanged(self, obj, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        self.addDimStyle(obj.getDimStyle())

    def printStack(self, undo):
        if undo:
            print "Image undo list:"
            _stack = self.__undo
        else:
            print "Image redo list:"
            _stack = self.__redo
        print "length: %d" % len(_stack)
        for _data in _stack:
            print _data

    def canUndo(self):
        return len(self.__undo) > 0

    def canRedo(self):
        return len(self.__redo) > 0

    def doUndo(self):
        # print "Image::doUndo() ..."
        if len(self.__undo):
            _act = self.__undo.pop()
            # print "Actions: " + str(_act)
            # print "undo length: %d" % len(self.__undo)
            self.__redo.append(_act[:])
            self.__action = len(self.__undo)
            _act.reverse()
            self.ignore('modified')
            try:
                _sid = self.getID()
                _layers = {}
                for _pid, _oid in _act:
                    # print "pid: " + str(_pid)
                    # print "oid: %d" % _oid
                    _obj = None
                    if _pid is None:
                        if _oid != _sid:
                            raise ValueError, "Invalid orphan: %d" % _oid
                        _obj = self
                    if _obj is None and _pid == _sid:
                        _obj = _layers.get(_oid)
                        if _obj is None:
                            for _layer in self.getChildren():
                                _lid = _layer.getID()
                                _layers[_lid] = _layer
                                if _lid == _oid:
                                    _obj = _layer
                                    break
                        if _obj is None:
                            raise ValueError, "Layer %d not found in Image" % _oid
                    if _obj is None:
                        _par = _layers.get(_pid)
                        if _par is None:
                            for _layer in self.getChildren():
                                _lid = _layer.getID()
                                _layers[_lid] = _layer
                                if _lid == _pid:
                                    _par = _layer
                                    break
                        if _par is None:
                            raise ValueError, "Parent layer not found: %d" % _pid
                        _obj = _par.getObject(_oid)
                        if _obj is None:
                            raise ValueError, "Object %d not found in parent %d" % (_oid, _pid)
                    # print "executing undo on obj: " + `_obj`
                    _obj.undo()
            finally:
                self.receive('modified')

    def doRedo(self):
        # print "Image::doRedo() ..."
        if len(self.__redo):
            _act = self.__redo.pop()
            self.__action = len(self.__undo)
            #
            # wrap all the redo() actions within a
            # startAction()/endAction block - this will
            # ensure that all the 'modified' messages the
            # redo operations generate will be stored in
            # in the undo list as a single set of operations
            #
            self.startAction()
            try:
                _sid = self.getID()
                _layers = {}
                for _pid, _oid in _act:
                    _obj = None
                    if _pid is None:
                        if _oid != _sid:
                            raise ValueError, "Invalid orphan: %d" % _oid
                        _obj = self
                    if _obj is None and _pid == _sid:
                        _obj = _layers.get(_oid)
                        if _obj is None:
                            for _layer in self.getChildren():
                                _lid = _layer.getID()
                                _layers[_lid] = _layer
                                if _lid == _oid:
                                    _obj = _layer
                                    break
                        if _obj is None:
                            raise ValueError, "Layer %d not found in Image" % _oid
                    if _obj is None:
                        _par = _layers.get(_pid)
                        if _par is None:
                            for _layer in self.getChildren():
                                _lid = _layer.getID()
                                _layers[_lid] = _layer
                                if _lid == _pid:
                                    _par = _layer
                                    break
                        if _par is None:
                            raise ValueError, "Parent layer not found: %d" % _pid
                        _obj = _par.getObject(_oid)
                        if _obj is None:
                            raise ValueError, "Object %d not found in parent %d" % (_oid, _pid)
                    # print "executing redo on obj: " + `_obj`
                    _obj.redo()
            finally:
                self.endAction()

    def addObject(self, obj, l=None):
        """Add an object to the Drawing.

addObject(obj [, l])

There is one required argument:

obj: The thing to be added

There is one optional argument:

l: The layer that will hold the object

By default, the currently active layer holds the object.
        """
        _layer = l
        if _layer is None:
            _layer = self.__active_layer
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer argument: " + `_layer`
        if _layer is not self.__active_layer:
            _l = _layer
            _p = _l.getParentLayer()
            while _p is not None:
                _l = _p
                _p = _p.getParentLayer()
            if _l is not self.__top_layer:
                raise ValueError, "Layer not found in drawing: " + `_layer`
            _parent = _layer.getParentLayer()
            if _parent is not None:
                if not _parent.hasSublayers():
                    raise ValueError, "Layer not a sublayer of parent: " + `_layer`
                if _layer not in _parent.getSublayers():
                    raise ValueError, "Layer not a sublayer of parent: " + `_layer`
            if _layer.getParent() is not self:
                raise ValueError, "Image/Layer parent inconsistency"
        _layer.addObject(obj)

    def delObject(self, obj, l=None):
        """Remove an object from the Drawing.

delObject(obj [, l])

There is one required argument:

obj: The thing to be added

There is one optional argument:

l: The layer holding the object.

By default, the currently active layer holds the object.
        """
        _layer = l
        if _layer is None:
            _layer = self.__active_layer
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer argument: " + `_layer`
        if _layer is not self.__active_layer:
            _l = _layer
            _p = _l.getParentLayer()
            while _p is not None:
                _l = _p
                _p = _p.getParentLayer()
            if _l is not self.__top_layer:
                raise ValueError, "Layer not found in drawing: " + `_layer`
            _parent = _layer.getParentLayer()
            if _parent is not None:
                if not _parent.hasSublayers():
                    raise ValueError, "Layer not in parent layer sublayers: " + `_layer`
                if _layer not in _parent.getSublayers():
                    raise ValueError, "Layer not in parent layer sublayers: " + `_layer`
            if _layer.getParent() is not self:
                raise ValueError, "Image/Layer parent inconsistency"
        _layer.delObject(obj)

    def getObject(self, eid):
        """Retrieve an object with a specified ID.

getObject(eid)

Argument eid is an entity ID. If an object with an ID of
that specified is found, the object is returned. Otherwise
this method returns None.
        """
        _layers = [self.__top_layer]
        while len(_layers):
            _layer = _layers.pop()
            if _layer.getID() == eid:
                return _layer
            _obj = _layer.getObject(eid)
            if _obj is not None:
                return _obj
            _layers.extend(_layer.getSublayers())
        return None

    def findLayerWithObj(self, oid):
        """Retrieve the layer containing an object

findLayerWithObj(oid)

Argument oid is the entityID. If no layer is found with
the entity ID this method returns None
        """
        _layers = [self.__top_layer]
        while len(_layers):
            _layer = _layers.pop()
            if _layer.hasObject(oid):
                return _layer
            _layers.extend(_layer.getSublayers())
        return None

    def startAction(self):
        if self.__busy:
            raise ValueError, "Image already in busy state"
        self.__busy = True

    def endAction(self):
        if not self.__busy:
            raise ValueError, "Image not in busy state"
        self.__busy = False
        self.__action = self.__action + 1

    def inAction(self):
        return self.__busy

    def getAction(self):
        return self.__action

    action = property(getAction, None, None, "Action value.")

    def findLayerWithObject(self, obj):
        """Find which layer holds a particular entity.

findLayerWithObject(obj)

This method returns the layer that the object is store in.
If the object is not found in any layer this method returns
None.
        """
        _layers = [self.__top_layer]
        while len(_layers):
            _layer = _layers.pop(0)
            if obj in _layer:
                return _layer
            _layers.extend(_layer.getSublayers())
        return None

    def selectObject(self, lyr, obj):
        """Store a reference to an object found in a layer.

selectObject(lyr, obj)

The argument 'obj' is one of the objects stored in the layer 'lyr'.
Storing an object with selectObject() is the means by which objects
can be copied or modified.
        """
        if not isinstance(lyr, layer.Layer):
            raise TypeError, "Invalid layer: " + `lyr`
        if obj not in lyr:
            raise ValueError, "Object not found in layer: " + `obj`
        _objlist = self.__selected.setdefault(lyr, [])
        _flag = True
        for _i in range(len(_objlist)):
            if obj is _objlist[_i]:
                _flag = False
                break
        if _flag:
            _objlist.append(obj)

    def deselectObject(self, lyr, obj):
        """Remove any occurance of an object found in a layer.

unselectObject(lyr, obj)

If the object isn't found as already selected a ValueError is returned.
        """
        if not isinstance(lyr, layer.Layer):
            raise TypeError, "Invalid layer: " + `lyr`
        if not self.__selected.has_key(lyr):
            raise ValueError, "No objects stored from layer: " + `lyr`
        _idx = None
        _objlist = self.__selected[lyr]
        for _i in range(len(_objlist)):
            _sobj = _objlist[_i]
            if _sobj is obj:
                _idx = _i
                break
        if _idx is None:
            raise ValueError, "Invalid object for deselection: " + `obj`
        del _objlist[_idx]
        if len(_objlist) == 0:
            del self.__selected[lyr]

    def getSelectedObjects(self):
        """Return all the currently selected objects.

getSelectedObjects()

Invoking this method releases the objects from being selected.
        """
        _objs = []
        for _layer in self.__selected:
            _objlist = self.__selected[_layer]
            for _obj in _objlist:
                _objs.append((_layer, _obj))
        self.__selected.clear()
        return _objs

    def clearSelectedObjects(self):
        """Empty the list list of selected objects.

clearSelectedObjects()
        """
        self.__selected.clear()

    def hasSelection(self):
        """Return whether or not there are selected objects in the drawing.

hasSelection()
        """
        return len(self.__selected) > 0

    def getImageVariables(self):
        """Get the dictionary storing the variables local to the image.

getImageVariables()
        """
        return self.__vars
    
    def getExtents(self):
        """Return the coordinates of a window holding the whole drawing

getExtents()

The function will return a tuple of the format:

(xmin, ymin, xmax, ymax)

Each value will be a float.
        """
        _xmin = None
        _ymin = None
        _xmax = None
        _ymax = None
        _set = False
        _layers = [self.__top_layer]
        while (len(_layers)):
            _layer = _layers.pop()
            if _layer.isVisible():
                _set = True
                _xmn, _ymn, _xmx, _ymx = _layer.getBoundary()
                if _xmin is None or _xmn < _xmin:
                    _xmin = _xmn
                if _ymin is None or _ymn < _ymin:
                    _ymin = _ymn
                if _xmax is None or _xmx > _xmax:
                    _xmax = _xmx
                if _ymax is None or _ymx > _ymax:
                    _ymax = _ymx
            _layers.extend(_layer.getSublayers())
        if _set: # make sure the values are different
            if abs(_xmax - _xmin) < 1e-10:
                _xmin = _xmin - 1.0
                _xmax = _xmax + 1.0
            if abs(_ymax - _ymin) < 1e-10:
                _ymin = _ymin - 1.0
                _ymax = _ymax + 1.0
        else:
            _xmin = -1.0
            _ymin = -1.0
            _xmax = 1.0
            _ymax = 1.0
        return (_xmin, _ymin, _xmax, _ymax)

    def getOption(self, key):
        """Return the value of an option set in the drawing.

getOption(key)

Return the value of the option associated with the string 'key'.
If there is no option found for that key, return None.
        """
        if not isinstance(key, str):
            raise TypeError, "Invalid key: " + `key`
        if key in self.__options:
            _val = self.__options[key]
        elif key in globals.prefs:
            _val = globals.prefs[key]
        else:
            _val = None
        return _val

    def setOption(self, key, value):
        """Set an option in the drawing.

setOption(key, value)

Argument 'key' must be a string, and argument 'value' can
any type of object. Using the same key twice will result on
the second value overwriting the first.
        """
        #
        # test_option will raise an exception for invalid values ...
        #
        _valid = options.test_option(key, value)
        _gval = None
        _set = False
        _gkey = True
        if key in globals.prefs:
            _gval = globals.prefs[key]
        #
        # check that the new value is different from that stored
        # in the global preferences
        #
        if key == 'UNITS':
            self.setUnits(value)
        elif key == 'DIM_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_FONT_FAMILY':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_FONT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_PRIMARY_FONT_WEIGHT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_FONT_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_FONT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_PRECISION':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_UNITS':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_LEADING_ZERO':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_TRAILING_DECIMAL':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_TEXT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_PRIMARY_TEXT_ANGLE':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_PRIMARY_TEXT_ALIGNMENT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval : _set = True
        elif key == 'DIM_SECONDARY_FONT_FAMILY':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_FONT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_FONT_WEIGHT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_FONT_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_FONT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_PRECISION':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_UNITS':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_LEADING_ZERO':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_TRAILING_DECIMAL':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_TEXT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_SECONDARY_TEXT_ANGLE':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_SECONDARY_TEXT_ALIGNMENT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval : _set = True
        elif key == 'DIM_OFFSET':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_EXTENSION':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_POSITION':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_POSITION_OFFSET':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_ENDPOINT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_ENDPOINT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_THICKNESS':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_DUAL_MODE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_DUAL_MODE_OFFSET':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'RADIAL_DIM_PRIMARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'RADIAL_DIM_PRIMARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'RADIAL_DIM_SECONDARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'RADIAL_DIM_SECONDARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'RADIAL_DIM_DIA_MODE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'ANGULAR_DIM_PRIMARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'ANGULAR_DIM_PRIMARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'ANGULAR_DIM_SECONDARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'ANGULAR_DIM_SECONDARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'TEXT_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_FAMILY':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_WEIGHT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'TEXT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'TEXT_ANGLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'TEXT_ALIGNMENT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'CHAMFER_LENGTH':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'FILLET_RADIUS':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'LINE_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'LINE_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'LINE_TYPE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'LINE_THICKNESS':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'HIGHLIGHT_POINTS':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'INACTIVE_LAYER_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'BACKGROUND_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'SINGLE_POINT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'MULTI_POINT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'AUTOSPLIT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'LEADER_ARROW_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        else: # other or possibly untested option
            _gkey = False
            print "non-global key: %s" % key
            if _valid: _set = True
        #
        # if the new value will be stored in the options dictionary
        # we do more tests on the values of certain keys
        #
        if _set:
            if (key == 'LINE_COLOR' or
                key == 'FONT_COLOR' or
                key == 'BACKGROUND_COLOR' or
                key == 'INACTIVE_LAYER_COLOR' or
                key == 'SINGLE_POINT_COLOR' or
                key == 'MULTI_POINT_COLOR' or
                key == 'DIM_COLOR' or
                key == 'DIM_PRIMARY_FONT_COLOR' or
                key == 'DIM_SECONDARY_FONT_COLOR'):
                if value in globals.colors:
                    _color = globals.colors[value]
                    if _color is not value:
                        print "%s: color duplicated: %s" % (key,  str(_color))
                        self.setOption(key, _color)
                        return
                else:
                    globals.colors[value] = value
                if value not in self.__colors:
                    self.__colors[value] = True
            elif key == 'LINE_STYLE':
                self.setOption('LINE_COLOR', value.getColor())
                self.setOption('LINE_TYPE', value.getLinetype())
                self.setOption('LINE_THICKNESS', value.getThickness())
                if value not in self.__styles:
                    self.__styles.append(value)
            elif key == 'LINE_TYPE':
                if value not in self.__linetypes:
                    self.__linetypes.append(value)
            elif key == 'DIM_STYLE':
                for _opt in value.getOptions():
                    _optval = value.getValue(_opt)
                    self.setOption(_opt, _optval)
                if value not in self.__dimstyles:
                    self.__dimstyles.append(value)
            elif key == 'TEXT_STYLE':
                self.setOption('FONT_COLOR', value.getColor())
                self.setOption('FONT_WEIGHT', value.getWeight())
                self.setOption('FONT_STYLE', value.getStyle())
                self.setOption('FONT_FAMILY',  value.getFamily())
                self.setOption('TEXT_SIZE', value.getSize())
                self.setOption('TEXT_ANGLE', value.getAngle())
                self.setOption('TEXT_ALIGNMENT', value.getAngle())
            elif (key == 'FONT_FAMILY' or
                  key == 'DIM_PRIMARY_FONT_FAMILY' or
                  key == 'DIM_SECONDARY_FONT_FAMILY'):
                if value not in self.__fonts:
                    self.__fonts[value] = 1
            else: # other or possibly untested option
                pass
            self.__options[key] = value
        else:
            if _gkey and key in self.__options: # use the global value
                del self.__options[key]

    def setFilename(self, fname):
        """Set the filename for this image.

setFilename(fname)

The filename will be where the system will save
the data in this file.
        """
        self.__filename = fname

    def getFilename(self):
        """Return the filename for this image.

getFilename()
        """
        return self.__filename

    filename = property(getFilename, setFilename, None, "Image filename.")

    def sendsMessage(self, m):
        if m in Image.messages:
            return True
        return super(Image, self).sendsMessage(m)

#
# provide some default colors, linetypes, and styles
# for an image
#

def add_defaults(image):
    # red = color.Color(255,0,0)
    # image.addColor(red)
    # green = color.Color(0,255,0)
    # image.addColor(green)
    # blue = color.Color(0,0,255)
    # image.addColor(blue)
    # violet = color.Color(255,0,255)
    # image.addColor(violet)
    # yellow = color.Color(255,255,0)
    # image.addColor(yellow)
    # cyan = color.Color(0,255,255)
    # image.addColor(cyan)
    # white = color.Color(255,255,255)
    # image.addColor(white)
    # black = color.Color(0,0,0)
    # image.addColor(black)
    _sstyle = globals.prefs['STANDARD_STYLE']
    _dstyle = globals.prefs['DEFAULT_STYLE']
    _styles = globals.prefs['STYLES']
    _set_style = False
    for _style in _styles:
        _istyle = _style.clone()
        image.addStyle(_istyle)
        _name = _style.getName()
        if _name == _dstyle:
            image.setOption('LINE_STYLE', _istyle)
            _set_style = True
    if not _set_style:
        image.setOption('LINE_STYLE', _sstyle)

    #
    # standard colors
    #
    # _colors = globals.prefs['COLORS']
    # for _color in _colors:
        # image.addColor(_color.clone())
    #
    # standard linetypes
    #
    _linetypes = globals.prefs['LINETYPES']
    for _linetype in _linetypes:
        image.addLinetype(_linetype.clone())

    #
    # standards styles
    #
    # solid = linetype.Linetype('Solid')
    # dash1 = linetype.Linetype('Dash1', [4,1])
    # dash2 = linetype.Linetype('Dash2', [8,2])
    # dash3 = linetype.Linetype('Dash3', [12,2])
    # dash4 = linetype.Linetype('Dash4', [10,2,2,2])
    # dash5 = linetype.Linetype('Dash5', [15,5,5,5])
    # st = style.Style('Solid White Line', solid, white, 1)
    # image.addStyle(st)
    # image.setOption('LINE_STYLE', st)
    # st = style.Style('Solid Black Line', solid, black, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Red Line', dash1, red, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Green Line', dash1, green, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Blue Line', dash1, blue, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Yellow Line', dash2, yellow, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Violet Line', dash2, violet, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Cyan Line', dash2, cyan, 1)
    # image.addStyle(st)

    _dsopts = {}
    for _opt in dimension.dimstyle_defaults:
        _val = dimension.dimstyle_defaults[_opt]
        if (_opt == 'DIM_COLOR' or
            _opt == 'DIM_PRIMARY_FONT_COLOR' or
            _opt == 'DIM_SECONDARY_FONT_COLOR'):
            _val = _val.clone()
        _dsopts[_opt] = _val
    _ds = dimension.DimStyle('Default DimStyle', _dsopts)
    image.addDimStyle(_ds)

    _dstyle = globals.prefs['DEFAULT_DIMSTYLE']
    _dname = None
    if _dstyle is not None:
        _dname = _dstyle.getName()
    _dimstyles = globals.prefs['DIMSTYLES']
    _set_style = False
    for _dimstyle in _dimstyles:
        image.addDimStyle(_dimstyle)
        _name = _dimstyle.getName()
        if _dname is not None and _name == _dname:
            image.setOption('DIM_STYLE', _dimstyle)
            _set_style = True
    if not _set_style:
        # print "setting DIM_STYLE to default _ds ..."
        image.setOption('DIM_STYLE', _ds)
        for _opt in _ds.getOptions():
            _val = str(_ds.getValue(_opt))
            # print "opt: %s; value: %s" % (_opt, _val)
    #
    # FIXME: re-examine this once new text stuff is in place
    #
    _ts = text.TextStyle('default')
    image.addTextStyle(_ts)
    _tstyle = globals.prefs['DEFAULT_TEXTSTYLE']
    _tname = None
    if _tstyle is not None:
        _tname = _tstyle.getName()
    _textstyles = globals.prefs['TEXTSTYLES']
    _set_style = False
    for _textstyle in _textstyles:
        image.addTextStyle(_textstyle)
        _name = _textstyle.getName()
        if _tname is not None and _name == _tname:
            image.setOption('TEXT_STYLE', _textstyle)
            _set_style = True
    if not _set_style and False:
        image.setOption('TEXT_STYLE', _ts)
    #
    # these will override what the style has set
    #
    # image.setOption('FONT_FAMILY', globals.prefs['FONT_FAMILY'])
    # image.setOption('FONT_SIZE', globals.prefs['FONT_SIZE'])
    # image.setOption('FONT_STYLE', globals.prefs['FONT_STYLE'])
    # image.setOption('FONT_WEIGHT', globals.prefs['FONT_WEIGHT'])
    # _font_color = globals.prefs['FONT_COLOR'].clone()
    # image.setOption('FONT_COLOR', _font_color)
    # image.setOption('CHAMFER_LENGTH', globals.prefs['CHAMFER_LENGTH'])
    # image.setOption('FILLET_RADIUS', globals.prefs['FILLET_RADIUS'])

    image.setUnits(globals.prefs['UNITS'])
    # image.setOption('HIGHLIGHT_POINTS', globals.prefs['HIGHLIGHT_POINTS'])

    # image.setOption('INACTIVE_LAYER_COLOR', globals.prefs['INACTIVE_LAYER_COLOR'])
    # image.setOption('AUTOSPLIT', globals.prefs['AUTOSPLIT'])
    # image.setOption('LEADER_ARROW_SIZE', globals.prefs['LEADER_ARROW_SIZE'])

#
# Image history class
#

class ImageLog(entity.EntityLog):
    def __init__(self, image):
        if not isinstance(image, Image):
            raise TypeError, "Invalid Image: " + `image`
        super(ImageLog, self).__init__(image)
        image.connect('scale_changed', self._scaleChanged)
        image.connect('units_changed', self._unitsChanged)
        image.connect('added_child', self._addedChild)
        image.connect('removed_child', self._removedChild)

    def _scaleChanged(self, image, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _scale = args[0]
        if not isinstance(_scale, float):
            raise TypeError, "Unexpected type for scale: " + `type(_scale)`
        if _scale < 1e-10:
            raise ValueError, "Invalid scale: %g" % _scale
        self.saveUndoData('scale_changed', _scale)

    def _unitsChanged(self, image, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _units = args[0]
        # fixme - maybe add error checking  ...
        self.saveUndoData('scale_changed', _units)

    def _addedChild(self, image, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _obj = args[0]
        _vals = _obj.getValues()
        if not isinstance(_vals, entity.EntityData):
            raise TypeError, "non EntityData for obj: " + `_obj`
        _vals.lock()
        self.saveUndoData('added_child', _vals)

    def _removedChild(self, image, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _obj = args[0]
        _vals = _obj.getValues()
        if not isinstance(_vals, entity.EntityData):
            raise TypeError, "non EntityData for obj: " + `_obj`
        _vals.lock()
        self.saveUndoData('removed_child', _vals)

    def execute(self, undo, *args):
        # print "ImageLog::execute() ..."
        # print args
        util.test_boolean(undo)
        _alen = len(args)
        if len(args) == 0:
            raise ValueError, "No arguments to execute()"
        _img = self.getObject()
        _op = args[0]
        if _op == 'units_changed':
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _sdata = _img.getUnits()
            self.ignore(_op)
            try:
                _unit = args[1]
                if undo:
                    _img.startUndo()
                    try:
                        _img.setUnits(_unit)
                    finally:
                        _img.endUndo()
                else:
                    _img.startRedo()
                    try:
                        _img.setUnits(_unit)
                    finally:
                        _img.endRedo()
            finally:
                self.receive(_op)
            self.saveData(undo, _op, _sdata)
        elif _op == 'scale_changed':
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _sdata = _img.getScale()
            self.ignore(_op)
            try:
                _scale = args[1]
                if undo:
                    _img.startUndo()
                    try:
                        _img.setScale(_scale)
                    finally:
                        _img.endUndo()
                else:
                    _img.startRedo()
                    try:
                        _img.setScale(_scale)
                    finally:
                        _img.endRedo()
            finally:
                self.receive(_op)
            self.saveData(undo, _op, _sdata)
        elif _op == 'added_child':
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _vals = args[1]
            if not isinstance(_vals, entity.EntityData):
                raise TypeError, "Invalid EntityData: " + `_vals`
            self.ignore('modified')
            try:
                if undo:
                    _lid = _vals.get('id')
                    _layer = None
                    for _child in _img.getChildren():
                        if _child.getID() == _lid:
                            _layer = _child
                            break
                    if _layer is None:
                        raise ValueError, "Layer not found in Image"
                    _sdata = _vals
                    self.ignore('removed_child')
                    try:
                        _img.startUndo()
                        try:
                            _img.delLayer(_layer)
                        finally:
                            _img.endUndo()
                    finally:
                        self.receive('removed_child')
                else:
                    _pid = _vals.get('parent_layer')
                    _parent_layer = None
                    for _child in _img.getChildren():
                        if _child.getID() == _pid:
                            _parent_layer = _child
                            break
                    if _parent_layer is None:
                        raise ValueError, "Parent layer not found in Image"
                    _layer = self._makeLayer(_vals)
                    self.ignore(_op)
                    try:
                        _img.startRedo()
                        try:
                            _img.addChildLayer(_layer, _parent_layer)
                        finally:
                            _img.endRedo()
                        _sdata = _layer.getValues()
                        _sdata.lock()
                    finally:
                        self.receive(_op)
            finally:
                self.receive('modified')
            self.saveData(undo, _op, _sdata)
        elif _op == 'removed_child':
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _vals = args[1]
            if not isinstance(_vals, entity.EntityData):
                raise TypeError, "Invalid EntityData: " + `_vals`
            self.ignore('modified')
            try:
                if undo:
                    _pid = _vals.get('parent_layer')
                    _parent_layer = None
                    for _child in _img.getChildren():
                        if _child.getID() == _pid:
                            _parent_layer = _child
                            break
                    if _parent_layer is None:
                        raise ValueError, "Parent layer not found in Image"
                    _layer = self._makeLayer(_vals)
                    self.ignore('added_child')
                    try:
                        _img.startUndo()
                        try:
                            _img.addChildLayer(_layer, _parent_layer)
                        finally:
                            _img.endUndo()
                        _sdata = _layer.getValues()
                        _sdata.lock()
                    finally:
                        self.receive('added_child')
                else:
                    _lid = _vals.get('id')
                    _layer = None
                    for _child in _img.getChildren():
                        if _child.getID() == _lid:
                            _layer = _child
                            break
                    if _layer is None:
                        raise ValueError, "Layer not found in Image"
                    _sdata = _vals
                    self.ignore(_op)
                    try:
                        _img.startRedo()
                        try:
                            _img.delLayer(_layer)
                        finally:
                            _img.endRedo()
                    finally:
                        self.receive(_op)
            finally:
                self.receive('modified')
            self.saveData(undo, _op, _sdata)                
        else:
            super(ImageLog, self).execute(undo, *args)

    def _makeLayer(self, values):
        _type = values.get('type')
        if _type != 'layer':
            _keys = values.keys()
            _keys.sort()
            for _key in _keys:
                print "key: %s: value: %s" % (_key, str(values.get(_key)))
            raise RuntimeError, "Invalid layer values"
        _id = values.get('id')
        if _id is None:
            raise ValueError, "Lost 'id' for recreating Layer"
        _name = values.get('name')
        if _name is None:
            raise ValueError, "Lost 'name' value for Layer"
        _scale = values.get('scale')
        if _scale is None:
            raise ValueError, "Lost 'scale' value for Layer"
        _layer = layer.Layer(_name, id=_id)
        _layer.setScale(_scale)
        return _layer